Page MenuHomePhorge

No OneTemporary

Size
971 KB
Referenced Files
None
Subscribers
None
This file is larger than 256 KB, so syntax highlighting was skipped.
This document is not UTF8. It was detected as ISO-8859-1 (Latin 1) and converted to UTF8 for display.
diff --git a/CAH_Version_2019.03.27/src/AbstractionModule.cpp b/CAH_Version_2019.03.27/src/AbstractionModule.cpp
new file mode 100644
index 0000000..b14e885
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/AbstractionModule.cpp
@@ -0,0 +1,198 @@
+#include "AbstractionModule.h"
+#include "abstraction_interface.h"
+
+#include <stdio.h>
+
+
+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_ix<MAX_NUM_OF_LOOKUPTABLES; lut_ix++) {
+ flag_lookuptable_exist[lut_ix] = false;
+ }
+
+ if(lut != NULL) {
+ list_lookuptables[num_of_lookuptables] = lut;
+ flag_lookuptable_exist[num_of_lookuptables] = true;
+ lookuptable_to_use = num_of_lookuptables;
+ num_of_lookuptables++;
+ }
+}
+
+AbstractionModule :: AbstractionModule(Lookuptable* lut, unsigned int abstraction_method) {
+ set_name(NO_NAME);
+ initialize_abstraction(lut, abstraction_method);
+}
+
+AbstractionModule :: AbstractionModule(char* name, Lookuptable* lut, unsigned int abstraction_method) {
+ set_name(name);
+ initialize_abstraction(lut, abstraction_method);
+}
+
+bool AbstractionModule :: set_abstraction_method(unsigned int abstraction_strategy) {
+ if(abstraction_strategy < NUM_OF_ABSTRACTIONS) {
+ this->abstraction_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<MAX_NUM_OF_INPUT_VALUES; pos++) {
+
+
+
+
+ }
+
+
+
+ }
+
+ return false;
+}
+*/
+
+
+
+
+
+
+
+
+bool AbstractionModule :: abstract_via_lookuptables_and_condition_variable() {
+
+
+ return true;
+}
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/AbstractionModule.h b/CAH_Version_2019.03.27/src/AbstractionModule.h
new file mode 100644
index 0000000..95b4e34
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/AbstractionModule.h
@@ -0,0 +1,91 @@
+#ifndef ABSTRACTION_HEADERFILE
+#define ABSTRACTION_HEADERFILE
+
+#include "Lookuptable.h"
+
+
+
+#define MAX_NUM_OF_INPUT_VALUES 10
+#define MAX_NUM_OF_SCORES 10
+
+
+//abstraction methods
+#define NUM_OF_ABSTRACTIONS 2
+#define ABSTRACTION_METHOD_NOT_SPECIFIED 0
+#define ABSTRACTION_LOOKUPTABLE 1
+
+
+#define MAX_NUM_OF_LOOKUPTABLES 5
+
+class AbstractionModule : public Module {
+
+ private:
+ unsigned int abstraction_method;
+
+ unsigned int num_of_lookuptables;
+ Lookuptable* list_lookuptables[MAX_NUM_OF_LOOKUPTABLES];
+ bool flag_lookuptable_exist[MAX_NUM_OF_LOOKUPTABLES];
+
+ unsigned int lookuptable_to_use;
+
+
+
+
+ //TODO: lut factor
+
+ //private functions
+ void initialize_abstraction(Lookuptable* lut, unsigned int abstraction_method);
+
+ bool abstract_via_lookuptable(float input, int* output);
+ bool abstract_via_factorized_lookuptable_and_condition_variable();
+ bool abstract_via_lookuptables_and_condition_variable();
+
+
+
+
+ //unsigned int num_of_slaveagents;
+ //unsigned int num_of_sensors;
+
+ /*
+ int abstracted_data;
+ bool flag_input_data_float_is_in_use[MAX_NUM_OF_INPUT_VALUES];
+ float input_data_float[MAX_NUM_OF_INPUT_VALUES];
+ */
+
+ /*
+ bool flag_input_data_int_is_in_use[MAX_NUM_OF_INPUT_VALUES];
+ int input_data_int[MAX_NUM_OF_INPUT_VALUES];
+ */
+
+ public:
+ AbstractionModule(Lookuptable* lut, unsigned int abstraction_method);
+ AbstractionModule(char* name, Lookuptable* lut, unsigned int abstraction_method);
+
+ bool set_abstraction_method(unsigned int abstraction_method);
+ unsigned int get_abstraction_method();
+
+ //TODO irgendwie muss man wissen an welcher position das is .. geht also im moment nur mit einer lookupttable
+ bool add_lookuptable(Lookuptable* lut);
+ bool get_flag_lookuptable_exist(unsigned int position);
+ Lookuptable* get_lookuptable(unsigned int position);
+
+ /*
+ void set_num_of_slaveagents(unsigned int num_of_slaveagents);
+ unsigned int get_num_of_slaveagents();
+
+ void set_num_of_sensors(unsigned int num_of_sensors);
+ unsigned int get_num_of_sensors();
+ */
+ /*
+ bool set_input_parameter(unsigned int position, int input_parameter);
+ bool set_input_parameter(unsigned int position, float input_parameter);
+ bool get_input_parameter(unsigned int position, int* input_parameter);
+ bool get_input_parameter(unsigned int position, float* input_parameter);
+ */
+
+ bool abstract(float input, int* output);
+
+ //bool 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);
+};
+
+#endif
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/Agent.cpp b/CAH_Version_2019.03.27/src/Agent.cpp
new file mode 100644
index 0000000..46b909c
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/Agent.cpp
@@ -0,0 +1,1079 @@
+#include "Agent.h"
+#include "printError.h"
+#include <stdio.h>
+
+//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;
+}
+
+
+
+
+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();
+
+
+ slaveAgentHandlerOfAgent->read_allSlaveAgentValues();
+ }
+
+
+ if(stateHandler != NULL) {
+ stateHandler->trigger(cycle);
+
+
+ }
+
+
+ //Job: Just pass the Sensory Data (without abstraction) to master
+ if(masterAgentHandlerOfAgent != NULL) {
+ if(sensorHandlerOfAgent != NULL) {
+ vector<SensorSlotOfAgent*>* 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();
+ }
+ }
+
+
+
+ /*
+ 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_ix<num_of_mounted_slaveagents; sa_ix++) {
+
+ if(flag_ccv_module_exist[sa_ix]) {
+ //flag_slaveagent_value_confident[sa_ix] = list_of_ccv_modules[sa_ix]->cross_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_ix<num_of_mounted_sensors; s_ix++) {
+ if(flag_sensor_value_set[s_ix]) {
+ if(flag_abstraction_exist[s_ix]) {
+ if(list_of_abstractions[s_ix]->abstract(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_ix<num_of_mounted_sensors; s_ix++) {
+
+ if(flag_abstracted_sensor_score_exist[s_ix]) {
+
+
+ if(flag_confidence_validator_exist[s_ix]) {
+ if(flag_sensor_value_confident[s_ix]) {
+ mounted_masteragent_outputport->set_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_ix<MAX_NUM_OF_MOUNTED_SLAVEAGENTS; sa_ix++) {
+ flag_slaveagent_is_mounted[sa_ix] = UNMOUNTED;
+ flag_slaveagent_has_dedicated_position[sa_ix] = NO;
+ flag_slaveagent_inputport_is_active[sa_ix] = INACTIVE;
+ flag_slaveagent_outputport_is_active[sa_ix] = INACTIVE;
+
+ //Slaveagent value
+ flag_slaveagent_value_set[sa_ix] = false;
+ flag_slaveagent_value_changed[sa_ix] = false;
+
+ flag_slaveagent_value_confident[sa_ix] = false;
+
+ flag_ccv_module_exist[sa_ix] = false;
+ }
+}
+
+void Agent :: initialize_sensor_slots() {
+ num_of_mounted_sensors = 0;
+ //number_of_active_mounted_sensors = 0;
+ for(unsigned int s_ix=0; s_ix<MAX_NUM_OF_MOUNTED_SENSORS; s_ix++) {
+ //sensors
+ flag_sensor_is_mounted[s_ix] = UNMOUNTED;
+ flag_sensor_has_dedicated_position[s_ix] = NO;
+ mounted_sensor_inputport[s_ix] = INACTIVE;
+ flag_sensor_inputport_is_active[s_ix] = INACTIVE;
+
+ //Sensor value
+ flag_sensor_value_set[s_ix] = false;
+ flag_sensor_value_changed[s_ix] = false;
+
+ //Sensor History
+ flag_sensor_history_exist[s_ix] = false;
+
+ //confedence
+ flag_confidence_validator_exist[s_ix] = false;
+ flag_sensor_value_confident[s_ix] = false;
+
+ //abstraction
+ flag_abstraction_exist[s_ix] = false;
+ flag_abstracted_sensor_score_exist[s_ix] = false;
+ }
+}
+
+void Agent :: initialize_bunch_module() {
+ flag_bunch_module_exist = false;
+ flag_bunched_score_exist = false;
+ bunch_score_confidency = 0;
+}
+
+void Agent :: initialize_working_frequency(int* success_indicator) {
+ if(set_working_frequency(working_frequency)) {
+ *success_indicator = 0;
+ }
+ else {
+ *success_indicator = 1;
+ }
+}
+
+// ----- Standard Attributes -----
+Agent :: Agent() {
+ set_name(NO_NAME);
+ initialize_master_slot();
+ initialize_slaveagent_slots();
+ initialize_sensor_slots();
+ initialize_bunch_module();
+}
+
+Agent :: Agent(char* name) {
+ set_name(name);
+ initialize_master_slot();
+ initialize_slaveagent_slots();
+ initialize_sensor_slots();
+ initialize_bunch_module();
+}
+
+Agent :: Agent(unsigned int working_frequency, int* success_indicator) {
+ set_name(NO_NAME);
+ initialize_master_slot();
+ initialize_slaveagent_slots();
+ initialize_sensor_slots();
+ initialize_bunch_module();
+ initialize_working_frequency(success_indicator);
+}
+
+Agent :: Agent(char* name, unsigned int working_frequency, int* success_indicator) {
+ set_name(name);
+ initialize_master_slot();
+ initialize_slaveagent_slots();
+ initialize_sensor_slots();
+ initialize_bunch_module();
+ initialize_working_frequency(success_indicator);
+}
+
+bool Agent :: set_working_frequency(unsigned int working_frequency) {
+ if(working_frequency <= MAX_WORK_FREQU) {
+ this->working_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_ix<num_of_mounted_sensors; s_ix++) {
+ read_mountedSensor(s_ix);
+ printf("Agent %s got value: %f\n", name, sensor_value[s_ix]);
+ }
+}
+
+bool Agent :: save_mountedSensor_history(unsigned int s_ix) {
+
+ bool flag_data_saved = false;
+
+ if(flag_sensor_value_set[s_ix] && flag_sensor_history_exist[s_ix]) {
+ flag_data_saved = sensor_history[s_ix]->drop_data(sensor_value[s_ix]);
+ }
+
+ return flag_data_saved;
+}
+
+void Agent :: save_all_mountedSensor_histories() {
+
+ for(unsigned int s_ix = 0; s_ix<num_of_mounted_sensors; s_ix++) {
+ save_mountedSensor_history(s_ix);
+
+ //Next lines are only for print
+ float temp_value;
+ if(flag_sensor_history_exist[s_ix]) {
+ if(sensor_history[s_ix]->get_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_ix<num_of_mounted_sensors; s_ix++) {
+ validate_confidence_of_mountedSensor(s_ix);
+ }
+}
+
+//TODO: test / modify!
+bool Agent :: read_slaveAgent(unsigned int sa_ix) {
+ //TODO: instructions in own line (unsigned int) ?!
+ //TODO: Class/Object Control Unit (with included instruction set)
+ int instruction = ISA_NO_INSTRUCTION;
+ int data = 0; //TODO: better value
+
+ while(mounted_slaveagent_inputport[sa_ix]->is_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_ix<num_of_mounted_slaveagents; sa_ix++) {
+ read_slaveAgent(sa_ix);
+ }
+}
+
+
+
+// ----- Runtime Functions -----
+void Agent :: trigger() {
+
+ //NOTE: I made readig, confidence, etc. in own loops/functions... because it may happen that confidence range changes and the sensor value is still the same but then valid or not
+
+ 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_ix<num_of_mounted_slaveagents; sa_ix++) {
+
+ if(flag_ccv_module_exist[sa_ix]) {
+ //flag_slaveagent_value_confident[sa_ix] = list_of_ccv_modules[sa_ix]->cross_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_ix<num_of_mounted_sensors; s_ix++) {
+ if(flag_sensor_value_set[s_ix]) {
+ if(flag_abstraction_exist[s_ix]) {
+ if(list_of_abstractions[s_ix]->abstract(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_ix<num_of_mounted_sensors; s_ix++) {
+
+ if(flag_abstracted_sensor_score_exist[s_ix]) {
+
+
+ if(flag_confidence_validator_exist[s_ix]) {
+ if(flag_sensor_value_confident[s_ix]) {
+ mounted_masteragent_outputport->set_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_ix<MAX_NUM_OF_MOUNTED_SLAVEAGENTS; sa_ix++) {
+ if(flag_slaveagent_is_mounted[sa_ix] == UNMOUNTED) {
+ flag_slaveagent_is_mounted[sa_ix] = MOUNTED;
+ flag_slaveagent_has_dedicated_position[sa_ix] = NO;
+ if(inputport != NULL) {
+ mounted_slaveagent_inputport[sa_ix] = inputport;
+ flag_slaveagent_inputport_is_active[sa_ix] = ACTIVE;
+ }
+ else {
+ flag_slaveagent_inputport_is_active[sa_ix] = INACTIVE;
+ }
+ if(outputport != NULL) {
+ mounted_slaveagent_outputport[sa_ix] = outputport;
+ flag_slaveagent_outputport_is_active[sa_ix] = ACTIVE;
+ }
+ else {
+ flag_slaveagent_outputport_is_active[sa_ix] = INACTIVE;
+ }
+ num_of_mounted_slaveagents++;
+ //abstraction.set_num_of_slaveagents(num_of_mounted_slaveagents);
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+
+//TODO: prevent possibility to mount yourself as subagent!
+//TODO: prevent possibility to mount sensor as subagent!
+bool Agent :: mount_slaveagent(Channel* inputport, Channel* outputport, unsigned int position) {
+ if(position < MAX_NUM_OF_MOUNTED_SLAVEAGENTS) {
+ if(flag_slaveagent_has_dedicated_position[position] == NO && (inputport != NULL || outputport != NULL)) {
+ if(flag_slaveagent_is_mounted[position] == MOUNTED) {
+ if(num_of_mounted_slaveagents < MAX_NUM_OF_MOUNTED_SLAVEAGENTS) {
+ for(unsigned int sa_ix=0; sa_ix<MAX_NUM_OF_MOUNTED_SLAVEAGENTS; sa_ix++) {
+ if(flag_slaveagent_is_mounted[sa_ix] == UNMOUNTED) {
+ flag_slaveagent_is_mounted[sa_ix] = flag_slaveagent_is_mounted[position];
+ flag_slaveagent_has_dedicated_position[sa_ix] = flag_slaveagent_has_dedicated_position[position];
+ flag_slaveagent_inputport_is_active[sa_ix] = flag_slaveagent_inputport_is_active[position];
+ if(flag_slaveagent_inputport_is_active[position])
+ mounted_slaveagent_inputport[sa_ix] = mounted_slaveagent_inputport[position];
+ flag_slaveagent_outputport_is_active[sa_ix] = flag_slaveagent_outputport_is_active[position];
+ if(flag_slaveagent_outputport_is_active[position])
+ mounted_slaveagent_outputport[sa_ix] = mounted_slaveagent_outputport[position];
+ break;
+ }
+ }
+ }
+ else {
+ return false;
+ }
+ }
+
+ flag_slaveagent_is_mounted[position] = MOUNTED;
+ flag_slaveagent_has_dedicated_position[position] = YES;
+
+ if(inputport != NULL) {
+ mounted_slaveagent_inputport[position] = inputport;
+ flag_slaveagent_inputport_is_active[position] = ACTIVE;
+ }
+ else {
+ flag_slaveagent_inputport_is_active[position] = INACTIVE;
+ }
+ if(outputport != NULL) {
+ mounted_slaveagent_outputport[position] = outputport;
+ flag_slaveagent_outputport_is_active[position] = ACTIVE;
+ }
+ else {
+ flag_slaveagent_outputport_is_active[position] = INACTIVE;
+ }
+ num_of_mounted_slaveagents++;
+ //abstraction.set_num_of_slaveagents(num_of_mounted_slaveagents);
+ return true;
+ }
+ }
+ return false;
+}
+
+//TODO: soetwas wie ccv != NULL auch bei anderen mounting sachen amchen.. mit Confidence, Abstraction usw
+bool Agent :: mount_slaveagent(Channel* inputport, Channel* outputport, Cross_Confidence_Validator* ccv) {
+ if(num_of_mounted_slaveagents < MAX_NUM_OF_MOUNTED_SLAVEAGENTS && (inputport != NULL || outputport != NULL) && ccv != NULL) {
+ for(unsigned int sa_ix=0; sa_ix<MAX_NUM_OF_MOUNTED_SLAVEAGENTS; sa_ix++) {
+ if(flag_slaveagent_is_mounted[sa_ix] == UNMOUNTED) {
+ flag_slaveagent_is_mounted[sa_ix] = MOUNTED;
+ flag_slaveagent_has_dedicated_position[sa_ix] = NO;
+ if(inputport != NULL) {
+ mounted_slaveagent_inputport[sa_ix] = inputport;
+ flag_slaveagent_inputport_is_active[sa_ix] = ACTIVE;
+ }
+ else {
+ flag_slaveagent_inputport_is_active[sa_ix] = INACTIVE;
+ }
+ if(outputport != NULL) {
+ mounted_slaveagent_outputport[sa_ix] = outputport;
+ flag_slaveagent_outputport_is_active[sa_ix] = ACTIVE;
+ }
+ else {
+ flag_slaveagent_outputport_is_active[sa_ix] = INACTIVE;
+ }
+
+ list_of_ccv_modules[sa_ix] = ccv;
+ flag_ccv_module_exist[sa_ix] = true;
+ //TODO: Fehlerbehandlung
+ list_of_ccv_modules[sa_ix]->set_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_ix<MAX_NUM_OF_MOUNTED_SENSORS; s_ix++) {
+ if(flag_sensor_is_mounted[s_ix] == UNMOUNTED) {
+ flag_sensor_is_mounted[s_ix] = flag_sensor_is_mounted[position];
+ flag_sensor_has_dedicated_position[s_ix] = flag_sensor_has_dedicated_position[position];
+ mounted_sensor_inputport[s_ix] = mounted_sensor_inputport[position];
+ flag_sensor_inputport_is_active[s_ix] = flag_sensor_inputport_is_active[position];
+ }
+ }
+ }
+ else {
+ return false;
+ }
+ }
+ flag_sensor_is_mounted[position] = MOUNTED;
+ flag_sensor_has_dedicated_position[position] = YES;
+ mounted_sensor_inputport[position] = inputport;
+ flag_sensor_inputport_is_active[position] = ACTIVE;
+ num_of_mounted_sensors++;
+ //abstraction.set_num_of_sensors(num_of_mounted_sensors);
+ return true;
+ }
+ }
+ return false;
+}
+
+
+//TODO: prevent possibility to mount yourself as subagent!
+//TODO: prevent possibility to mount subagent as sensor!
+bool Agent :: mount_sensor(Channel* inputport) {
+ if(num_of_mounted_sensors < MAX_NUM_OF_MOUNTED_SENSORS && inputport != NULL) {
+ for(unsigned int s_ix=0; s_ix<MAX_NUM_OF_MOUNTED_SENSORS; s_ix++) {
+ if(flag_sensor_is_mounted[s_ix] == UNMOUNTED) {
+ flag_sensor_is_mounted[s_ix] = MOUNTED;
+ flag_sensor_has_dedicated_position[s_ix] = NO;
+ mounted_sensor_inputport[s_ix] = inputport;
+ flag_sensor_inputport_is_active[s_ix] = ACTIVE;
+ num_of_mounted_sensors++;
+ //abstraction.set_num_of_sensors(num_of_mounted_sensors);
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+bool Agent :: mount_sensor(Channel* inputport, Abstraction* abstraction) {
+ if(num_of_mounted_sensors < MAX_NUM_OF_MOUNTED_SENSORS && inputport != NULL) {
+ for(unsigned int s_ix=0; s_ix<MAX_NUM_OF_MOUNTED_SENSORS; s_ix++) {
+ if(flag_sensor_is_mounted[s_ix] == UNMOUNTED) {
+ flag_sensor_is_mounted[s_ix] = MOUNTED;
+ flag_sensor_has_dedicated_position[s_ix] = NO;
+ mounted_sensor_inputport[s_ix] = inputport;
+ flag_sensor_inputport_is_active[s_ix] = ACTIVE;
+
+ if(abstraction != NULL) {
+ flag_abstraction_exist[s_ix] = true;
+ list_of_abstractions[s_ix] = abstraction;
+ }
+
+ num_of_mounted_sensors++;
+
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+bool Agent :: mount_sensor(Channel* inputport, Confidence_Validator* confidence_validator) {
+ if(num_of_mounted_sensors < MAX_NUM_OF_MOUNTED_SENSORS && inputport != NULL) {
+ for(unsigned int s_ix=0; s_ix<MAX_NUM_OF_MOUNTED_SENSORS; s_ix++) {
+ if(flag_sensor_is_mounted[s_ix] == UNMOUNTED) {
+ flag_sensor_is_mounted[s_ix] = MOUNTED;
+ flag_sensor_has_dedicated_position[s_ix] = NO;
+ mounted_sensor_inputport[s_ix] = inputport;
+ flag_sensor_inputport_is_active[s_ix] = ACTIVE;
+
+ if(confidence_validator != NULL) {
+ flag_confidence_validator_exist[s_ix] = true;
+ list_of_confidence_validators[s_ix] = confidence_validator;
+ }
+
+ num_of_mounted_sensors++;
+
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+
+bool Agent :: mount_sensor(Channel* inputport, HistoryModule* historyModule) {
+
+ /*
+ sensor_history[MAX_NUM_OF_MOUNTED_SENSORS];
+ flag_sensor_history_exist[MAX_NUM_OF_MOUNTED_SENSORS];
+ */
+
+/* if(num_of_mounted_sensors < MAX_NUM_OF_MOUNTED_SENSORS && inputport != NULL && historyModule != NULL) {
+
+ for(unsigned int s_ix=0; s_ix<MAX_NUM_OF_MOUNTED_SENSORS; s_ix++) {
+
+ if(flag_sensor_is_mounted[s_ix] == UNMOUNTED) {
+
+ flag_sensor_is_mounted[s_ix] = MOUNTED;
+ flag_sensor_has_dedicated_position[s_ix] = NO;
+ mounted_sensor_inputport[s_ix] = inputport;
+ flag_sensor_inputport_is_active[s_ix] = ACTIVE;
+
+ flag_sensor_history_exist[s_ix] = true;
+ sensor_history[s_ix] = historyModule;
+
+ num_of_mounted_sensors++;
+
+ return true;
+ }
+ }
+ }
+
+ return false;
+}
+
+
+bool Agent :: mount_sensor(Channel* inputport, Confidence_Validator* confidence_validator, Abstraction* abstraction) {
+ if(num_of_mounted_sensors < MAX_NUM_OF_MOUNTED_SENSORS && inputport != NULL) {
+ for(unsigned int s_ix=0; s_ix<MAX_NUM_OF_MOUNTED_SENSORS; s_ix++) {
+ if(flag_sensor_is_mounted[s_ix] == UNMOUNTED) {
+ flag_sensor_is_mounted[s_ix] = MOUNTED;
+ flag_sensor_has_dedicated_position[s_ix] = NO;
+ mounted_sensor_inputport[s_ix] = inputport;
+ flag_sensor_inputport_is_active[s_ix] = ACTIVE;
+
+ if(confidence_validator != NULL) {
+ flag_confidence_validator_exist[s_ix] = true;
+ list_of_confidence_validators[s_ix] = confidence_validator;
+ }
+
+ if(abstraction != NULL) {
+ flag_abstraction_exist[s_ix] = true;
+ list_of_abstractions[s_ix] = abstraction;
+ }
+
+ num_of_mounted_sensors++;
+
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+// ----- Bunch Module -----
+bool Agent :: mount_bunch_module(Bunch_Module* bunch_module){
+ if(bunch_module != NULL) {
+ this->bunch_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; i<MAX_NUM_OF_MOUNTED_SLAVEAGENTS; i++) {
+ if(flag_slaveagent_is_mounted[i]) {
+ if(flag_slaveagent_inputport_is_active[i]) {
+ printf("%s has mounted %s on position %i\n", this->name, 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; i<MAX_NUM_OF_MOUNTED_SENSORS; i++) {
+ if(flag_sensor_is_mounted[i]) {
+ if(flag_sensor_inputport_is_active[i]) {
+ printf("%s has mounted %s on position %i\n", this->name, mounted_sensor_inputport[i]->get_name(), i);
+ }
+ }
+ else {
+ printf("%s has nothing mounted on position %i\n", this->name, i);
+ }
+ }
+ getchar();
+}
+*/
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/Agent.h b/CAH_Version_2019.03.27/src/Agent.h
new file mode 100644
index 0000000..ead2ee5
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/Agent.h
@@ -0,0 +1,202 @@
+#ifndef AGENT_HEADERFILE
+#define AGENT_HEADERFILE
+
+#include "MasterAgentHandlerOfAgent.h"
+#include "Node.h"
+#include "SensorHandlerOfAgent.h"
+#include "SlaveAgentHandlerOfAgent.h"
+#include "StateHandler.h"
+
+
+class Agent : public Node {
+
+ private :
+ SensorHandlerOfAgent* sensorHandlerOfAgent;
+ SlaveAgentHandlerOfAgent* slaveAgentHandlerOfAgent;
+ MasterAgentHandlerOfAgent* masterAgentHandlerOfAgent;
+
+ 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);
+
+
+ /*
+ 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
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/AgentSlotOfTestbench.cpp b/CAH_Version_2019.03.27/src/AgentSlotOfTestbench.cpp
new file mode 100644
index 0000000..ff586fd
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/AgentSlotOfTestbench.cpp
@@ -0,0 +1,31 @@
+#include "AgentSlotOfTestbench.h"
+
+#include <stdio.h>
+
+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;
+}
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/AgentSlotOfTestbench.h b/CAH_Version_2019.03.27/src/AgentSlotOfTestbench.h
new file mode 100644
index 0000000..f7d097b
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/AgentSlotOfTestbench.h
@@ -0,0 +1,21 @@
+#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();
+};
+
+#endif
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/AverageValue.cpp b/CAH_Version_2019.03.27/src/AverageValue.cpp
new file mode 100644
index 0000000..6b0c0dd
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/AverageValue.cpp
@@ -0,0 +1,39 @@
+#include "AverageValue.h"
+
+#include <stdio.h>
+
+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/CAH_Version_2019.03.27/src/AverageValue.h b/CAH_Version_2019.03.27/src/AverageValue.h
new file mode 100644
index 0000000..a889eee
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/Bunch_Module.cpp b/CAH_Version_2019.03.27/src/Bunch_Module.cpp
new file mode 100644
index 0000000..0bfb98a
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/Bunch_Module.cpp
@@ -0,0 +1,66 @@
+#include "Bunch_Module.h"
+
+#include <stdio.h>
+
+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_ix<num_of_input; in_ix++) {
+ if(input_is_valid[in_ix]) {
+ result = result + *(input+in_ix);
+ data_confidence_counter++;
+ //printf("%u - valid\n", in_ix);
+ }
+
+ }
+
+ *output = result;
+
+ return data_confidence_counter;
+}
+
+void Bunch_Module :: set_bunch_method(unsigned int bunch_method) {
+ this->bunch_method = bunch_method;
+}
+
+unsigned int Bunch_Module :: get_bunch_method() {
+ return bunch_method;
+}
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/Bunch_Module.h b/CAH_Version_2019.03.27/src/Bunch_Module.h
new file mode 100644
index 0000000..45ef099
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/Bunch_Module.h
@@ -0,0 +1,33 @@
+#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 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/CAH_Version_2019.03.27/src/CSV_Writer.cpp b/CAH_Version_2019.03.27/src/CSV_Writer.cpp
new file mode 100644
index 0000000..a359c2e
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/CSV_Writer.cpp
@@ -0,0 +1,82 @@
+#include "CSV_Writer.h"
+//#include <string>
+//#include <iostream>
+
+#define STRINGLENGTH 5000
+
+void CSV_Writer :: initialize_csv_writer(char* filepath_write) {
+ //fpointer_write = fopen(filepath_write, "w");
+ fopen_s(&fpointer_write, filepath_write, "w");
+}
+
+CSV_Writer :: CSV_Writer(char* filepath_write) {
+ set_name(NO_NAME);
+ initialize_csv_writer(filepath_write);
+}
+
+CSV_Writer :: CSV_Writer(char* name, char* filepath_write) {
+ 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_ix<num_of_datasets; d_ix++) {
+ fprintf(fpointer_write, "%f", datasets[d_ix]);
+ if(d_ix < num_of_datasets-1)
+ fprintf(fpointer_write, ",");
+ }
+ fprintf(fpointer_write, "\n");
+ return true;
+ }
+ return false;
+}
+
+void CSV_Writer :: close_file() {
+ if(fpointer_write)
+ fclose(fpointer_write);
+}
diff --git a/CAH_Version_2019.03.27/src/CSV_Writer.h b/CAH_Version_2019.03.27/src/CSV_Writer.h
new file mode 100644
index 0000000..acab2d7
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/CSV_Writer.h
@@ -0,0 +1,35 @@
+#ifndef CSV_WRITER_HEADERFILE
+#define CSV_WRITER_HEADERFILE
+
+#include "Module.h"
+#include <fstream>
+
+#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];
+
+ //private fuctions
+ void initialize_csv_writer(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 close_file();
+};
+
+#endif
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/CSVreaderModule.cpp b/CAH_Version_2019.03.27/src/CSVreaderModule.cpp
new file mode 100644
index 0000000..f2d574c
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/CSVreaderModule.cpp
@@ -0,0 +1,190 @@
+#include "CSVreaderModule.h"
+#include <string>
+#include <iostream>
+
+#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_ix<num_of_datasets; d_ix++) {
+ this->list_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(;row<start_row; row++) {
+
+ if(!fgets(readrow, STRINGLENGTH, fpointer))
+ return false;
+ }
+
+ if(fgets (readrow, STRINGLENGTH, fpointer))
+ {
+ char *ptr, *next_ptr;
+ //TODO: make delimiter configurable!
+ ptr = strtok_s(readrow, ",;", &next_ptr);
+ //OLD: unsigned int dataset_counter = 0;
+ dataset_counter = 0;
+
+ if(list_of_datasets[dataset_counter] == 1) {
+ data_read[dataset_counter] = std::stof(ptr, NULL);
+ dataset_counter++;
+ }
+ else {
+ ptr = strtok_s(NULL, ",;", &next_ptr);
+ }
+
+ for(;dataset_counter<num_of_datasets;dataset_counter++) {
+ for(unsigned int c_ix=list_of_datasets[dataset_counter-1]; c_ix<list_of_datasets[dataset_counter]; c_ix++)
+ {
+ ptr = strtok_s(NULL, ",;", &next_ptr);
+ }
+ data_read[dataset_counter] = std::stof(ptr, NULL);
+ }
+ return true;
+ }
+ }
+ return false;
+}
+
+float CSVreaderModule :: get_value_of_field(unsigned int field) {
+ //TODO: Bessere Fehlerbehandlung.. also nciht einfach 0 returnen, wenn kein richtiges FEld!!!
+ if(field < num_of_datasets) {
+ return data_read[field];
+ }
+
+ return 0.0;
+}
+
+
+
+//TODO: überarbeiten nach folgendem Beispiel https://msdn.microsoft.com/en-us/library/ftsafwz3.aspx
+bool CSVreaderModule :: read_field() {
+ if(fpointer)
+ {
+ char readrow[STRINGLENGTH] = "", electedfield[STRINGLENGTH] = "";
+
+ //TODO: move following for-loop to "initialize_csvreader(...)
+ for(;row<start_row; row++) {
+
+ if(!fgets(readrow, STRINGLENGTH, fpointer))
+ return false;
+ }
+
+ if(fgets (readrow, STRINGLENGTH, fpointer))
+ {
+ char *ptr, *next_ptr;
+ //TODO: make delimiter configurable!
+ ptr = strtok_s(readrow, ",;", &next_ptr);
+
+ for(unsigned int d_ix=1; d_ix<column; d_ix++) {
+ ptr = strtok_s(NULL, ",;", &next_ptr);
+ }
+
+ input_data = std::stof(ptr, NULL);
+ return true;
+ }
+ }
+ return false;
+}
+
+
+bool CSVreaderModule :: get_next_value(float* value) {
+
+ if(flag_csv_reader_configured) {
+ if(read_field()) {
+ *value = input_data;
+ return true;
+ }
+ }
+
+ return false;
+}
+
+//TODO: flag_csv_reader_configured abfragen
+void CSVreaderModule :: close_file() {
+ fclose(fpointer);
+}
diff --git a/CAH_Version_2019.03.27/src/CSVreaderModule.h b/CAH_Version_2019.03.27/src/CSVreaderModule.h
new file mode 100644
index 0000000..919b5b1
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/CSVreaderModule.h
@@ -0,0 +1,47 @@
+#ifndef CSV_READER_HEADERFILE
+#define CSV_READER_HEADERFILE
+
+#include "Module.h"
+#include <fstream>
+
+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 close_file();
+};
+
+#endif
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/Channel.cpp b/CAH_Version_2019.03.27/src/Channel.cpp
new file mode 100644
index 0000000..5c1b66b
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/Channel.cpp
@@ -0,0 +1,286 @@
+#include "Channel.h"
+#include <stdio.h>
+
+#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<Message*>* buffer, Message* message) {
+ try {
+ buffer->push_front(message);
+ }
+ catch(bad_alloc& error) {
+ delete message;
+ return false;
+ }
+ return true;
+}
+
+bool Channel :: del_msgAtBegin (list<Message*>* buffer) {
+ try {
+ /*
+ printf("a\n");
+ getchar();
+ delete buffer->back();
+ printf("b\n");
+ getchar();
+ */
+ buffer->pop_front();
+ /*
+ printf("c\n");
+ getchar();
+ */
+ }
+ catch(bad_alloc& error) {
+ return false;
+ }
+ return true;
+}
+
+bool Channel :: add_msgAtEnd (list<Message*>* buffer, Message* message) {
+ try {
+ buffer->push_back(message);
+ }
+ catch(bad_alloc& error) {
+ delete message;
+ return false;
+ }
+ return true;
+}
+
+bool del_msgAtEnd (list<Message*>* buffer) {
+ try {
+ 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<Message*>* dest_buffer, list<Message*>* 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; i<NumOfMsgsToMove; i++) {
+ if(add_msgAtEnd(dest_buffer, src_buffer->front())) {
+ 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;
+
+}
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/Channel.h b/CAH_Version_2019.03.27/src/Channel.h
new file mode 100644
index 0000000..950dcfc
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/Channel.h
@@ -0,0 +1,72 @@
+#ifndef CHANNEL_HEADERFILE
+#define CHANNEL_HEADERFILE
+
+#include <list>
+#include "Message.h"
+#include "Module.h"
+
+
+#define MAX_BUFFER_LENGTH 100
+#define OPEN NULL
+
+using namespace std;
+
+class Channel : public Module {
+
+ private:
+
+ list<Message*> lInputMsgBufferUp;
+ list<Message*> lOutputMsgBufferUp;
+
+ list<Message*> lInputMsgBufferDown;
+ list<Message*> lOutputMsgBufferDown;
+
+ unsigned int maxBufferLength;
+ unsigned int transferRate;
+
+ void init_channel();
+
+ bool add_msgAtBegin (list<Message*>* buffer, Message* message);
+ bool del_msgAtBegin (list<Message*>* buffer);
+
+ bool add_msgAtEnd (list<Message*>* buffer, Message* message);
+ bool del_msgAtEnd (list<Message*>* buffer);
+
+ 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<Message*>* dest_buffer, list<Message*>* src_buffer);
+
+};
+
+
+#endif
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/ChannelSlotOfTestbench.cpp b/CAH_Version_2019.03.27/src/ChannelSlotOfTestbench.cpp
new file mode 100644
index 0000000..480ce9c
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/ChannelSlotOfTestbench.cpp
@@ -0,0 +1,31 @@
+#include "ChannelSlotOfTestbench.h"
+
+#include <stdio.h>
+
+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;
+}
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/ChannelSlotOfTestbench.h b/CAH_Version_2019.03.27/src/ChannelSlotOfTestbench.h
new file mode 100644
index 0000000..9adc1b9
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/ChannelSlotOfTestbench.h
@@ -0,0 +1,21 @@
+#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();
+};
+
+#endif
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/ConfidenceModule.cpp b/CAH_Version_2019.03.27/src/ConfidenceModule.cpp
new file mode 100644
index 0000000..1ea4d92
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/ConfidenceModule.cpp
@@ -0,0 +1,167 @@
+#include "ConfidenceModule.h"
+#include "HistoryModule.h"
+
+#include <stdio.h>
+
+//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/CAH_Version_2019.03.27/src/ConfidenceModule.h b/CAH_Version_2019.03.27/src/ConfidenceModule.h
new file mode 100644
index 0000000..b174292
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/Continuous_Average.cpp b/CAH_Version_2019.03.27/src/Continuous_Average.cpp
new file mode 100644
index 0000000..f48237f
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/Continuous_Average.h b/CAH_Version_2019.03.27/src/Continuous_Average.h
new file mode 100644
index 0000000..c228de7
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/Cross_Confidence_Validator.cpp b/CAH_Version_2019.03.27/src/Cross_Confidence_Validator.cpp
new file mode 100644
index 0000000..329aabf
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/Cross_Confidence_Validator.cpp
@@ -0,0 +1,80 @@
+#include "Cross_Confidence_Validator.h"
+
+#include <stdio.h>
+
+//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<num_of_input; in_ix++) {
+
+ //printf("input_is_valid[%i] = %i\n", in_ix, input_is_valid[in_ix]);
+
+ if(input_is_valid[in_ix]) {
+ num_of_valid++;
+
+ if(in_ix != proband) {
+ //TODO: kein hardcoded 0 ... könnte ja auch einen schlechten score bedeuten
+ if(input[in_ix] != 0) {
+ num_of_not_perfect++;
+ }
+ }
+ }
+ }
+
+ //printf("num_of_valid = %u, num_of_not_perfect = %u, divided = %f, \% = %f\n", num_of_valid, num_of_not_perfect, (float)num_of_not_perfect/(float)num_of_valid, percentage_of_inputs_must_be_bad);
+
+ //TO CHECK: passt das?
+ if(num_of_valid == 0) {
+ return false;
+ }
+
+ if((float)num_of_not_perfect/(float)num_of_valid >= 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/CAH_Version_2019.03.27/src/Cross_Confidence_Validator.h b/CAH_Version_2019.03.27/src/Cross_Confidence_Validator.h
new file mode 100644
index 0000000..1a59182
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/Discrete_Average.cpp b/CAH_Version_2019.03.27/src/Discrete_Average.cpp
new file mode 100644
index 0000000..e69de29
diff --git a/CAH_Version_2019.03.27/src/Discrete_Average.h b/CAH_Version_2019.03.27/src/Discrete_Average.h
new file mode 100644
index 0000000..9ff7a4d
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/Evaluation.cpp b/CAH_Version_2019.03.27/src/Evaluation.cpp
new file mode 100644
index 0000000..8dff754
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/Evaluation.cpp
@@ -0,0 +1,163 @@
+#include "Evaluation.h"
+#include <stdio.h>
+#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_ix<agent.get_number_of_mounted_sensors(); s_ix++) {
+ if(agent.get_flag_mounted_sensor_is_active(s_ix)) {
+ Sensor* sensor = agent.get_mounted_sensor(s_ix);
+ unsigned int number_of_scores = sensor->get_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; score<number_of_scores; score++) {
+ if(!is_it_lower_than_boundary(sensor, score, LOWER_BOUNDARY)) {
+ sensor->set_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; score<number_of_scores; score++) {
+ if(!is_it_higher_than_boundary(sensor, score, UPPER_BOUNDARY)) {
+ sensor->set_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; score<number_of_scores; score++) {
+ if(!is_it_lower_than_hardcoded_boundary(sensor, 0, LOWER_BOUNDARY)) {
+ sensor->set_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; score<number_of_scores; score++) {
+ if(!is_it_higher_than_hardcoded_boundary(sensor, 0, LOWER_BOUNDARY)) {
+ sensor->set_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_ix<agent.get_number_of_mounted_sensors(); s_ix++) {
+ if(agent.get_flag_mounted_sensor_is_active(s_ix)) {
+ score += agent.get_mounted_sensor(s_ix)->get_score();
+ }
+ }
+ for(unsigned int sa_ix=0; sa_ix<agent.get_num_of_mounted_slaveagents(); sa_ix++) {
+ if(agent.get_flag_mounted_subagent_is_active(sa_ix)) {
+ printf("aktiv - subscore: %i\n", agent.get_mounted_subagent(sa_ix)->get_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; sensor<MAX_NUM_OF_SENSORS; sensor++) {
+ if(agent->get_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; sensor<MAX_NUM_OF_SENSORS; sensor++) {
+ if(agent->get_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; sensor<MAX_NUM_OF_SENSORS; sensor++) {
+ if(agent->get_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/CAH_Version_2019.03.27/src/Evaluation.h b/CAH_Version_2019.03.27/src/Evaluation.h
new file mode 100644
index 0000000..688e015
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/ExtremeValue.cpp b/CAH_Version_2019.03.27/src/ExtremeValue.cpp
new file mode 100644
index 0000000..f11f05b
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/ExtremeValue.h b/CAH_Version_2019.03.27/src/ExtremeValue.h
new file mode 100644
index 0000000..46756b7
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/HandlerOfAgent.cpp b/CAH_Version_2019.03.27/src/HandlerOfAgent.cpp
new file mode 100644
index 0000000..e69de29
diff --git a/CAH_Version_2019.03.27/src/HandlerOfAgent.h b/CAH_Version_2019.03.27/src/HandlerOfAgent.h
new file mode 100644
index 0000000..a05a9e2
--- /dev/null
+++ b/CAH_Version_2019.03.27/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<SlaveAgentSlotOfAgent*> 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/CAH_Version_2019.03.27/src/Header.h b/CAH_Version_2019.03.27/src/Header.h
new file mode 100644
index 0000000..6f70f09
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/Header.h
@@ -0,0 +1 @@
+#pragma once
diff --git a/CAH_Version_2019.03.27/src/HistoryEntry.cpp b/CAH_Version_2019.03.27/src/HistoryEntry.cpp
new file mode 100644
index 0000000..775ab46
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/HistoryEntry.h b/CAH_Version_2019.03.27/src/HistoryEntry.h
new file mode 100644
index 0000000..02b1e71
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/HistoryModule.cpp b/CAH_Version_2019.03.27/src/HistoryModule.cpp
new file mode 100644
index 0000000..62562af
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/HistoryModule.cpp
@@ -0,0 +1,442 @@
+#include "HistoryModule.h"
+#include "printError.h"
+#include <stdio.h>
+
+#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<history_max_length) {
+ if(next_history_pointer < history_max_length) {
+ history[next_history_pointer] = value;
+ next_history_pointer++;
+ }
+ else {
+ //if(flag_ring_memory) //TODO: Option(en) einbauen
+ history[0] = value;
+ next_history_pointer = 1;
+ }
+ }
+ else {
+ printf("Field %i of history array is out of range!\n", point);
+ }
+}
+unsigned int History :: get_history(unsigned int point) {
+ if(point<history_max_length) {
+ return history[point];
+ }
+ else {
+ printf("Field %i of history array is out of range!\n", point);
+ return NULL;
+ }
+}
+
+void History :: set_history_max_length(unsigned int max_length) {
+ history_max_length = max_length;
+}
+unsigned int History :: get_history_max_length() {
+ return history_max_length;
+}
+*/
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/HistoryModule.h b/CAH_Version_2019.03.27/src/HistoryModule.h
new file mode 100644
index 0000000..d67ea6c
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/HistoryModule.h
@@ -0,0 +1,90 @@
+#ifndef HISTORYMODULE_HEADERFILE
+#define HISTORYMODULE_HEADERFILE
+
+#include "HistoryEntry.h"
+#include "Module.h"
+#include <vector>
+
+/*
+#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<HistoryEntry*> 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/CAH_Version_2019.03.27/src/Lookuptable.cpp b/CAH_Version_2019.03.27/src/Lookuptable.cpp
new file mode 100644
index 0000000..4f5b55b
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/Lookuptable.cpp
@@ -0,0 +1,82 @@
+#include "Lookuptable.h"
+#include <stdio.h>
+
+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<num_of_ranges; r_ix++) {
+
+ //printf("list_of_ranges[r_ix].get_lower_boundary() = %f\nlist_of_ranges[num_of_ranges].get_upper_boundary() = %f\n\n", list_of_ranges[r_ix].get_lower_boundary(), list_of_ranges[num_of_ranges].get_upper_boundary());
+ if(list_of_ranges[r_ix].get_lower_boundary() == list_of_ranges[num_of_ranges].get_upper_boundary()) {
+ //printf("drinnen1\n");
+
+ list_of_ranges[r_ix].set_range_below(&list_of_ranges[num_of_ranges]);
+ list_of_ranges[num_of_ranges].set_range_upon(&list_of_ranges[r_ix]);
+
+ }
+
+ //printf("list_of_ranges[r_ix].get_upper_boundary() = %f\nlist_of_ranges[num_of_ranges].get_lower_boundary() = %f\n\n", list_of_ranges[r_ix].get_upper_boundary(), list_of_ranges[num_of_ranges].get_lower_boundary());
+ if(list_of_ranges[r_ix].get_upper_boundary() == list_of_ranges[num_of_ranges].get_lower_boundary()) {
+ //printf("drinnen2\n");
+
+ list_of_ranges[r_ix].set_range_upon(&list_of_ranges[num_of_ranges]);
+ list_of_ranges[num_of_ranges].set_range_below(&list_of_ranges[r_ix]);
+
+ }
+ }
+
+ num_of_ranges++;
+
+ return true;
+ }
+ return false;
+}
+
+bool Lookuptable :: check_sort_and_activate() {
+ if(num_of_ranges > 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<num_of_ranges; i++) {
+ if(list_of_ranges[i].get_range_below() != nullptr)
+ printf("%i ist unten verbunden\n", i);
+ else
+ printf("%i ist unten NICHT verbunden\n", i);
+
+ if(list_of_ranges[i].get_range_upon() != nullptr)
+ printf("%i ist oben verbunden\n", i);
+ else
+ printf("%i ist oben NICHT verbunden\n", i);
+ }
+ printf("blub\n");
+ getchar();
+}
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/Lookuptable.h b/CAH_Version_2019.03.27/src/Lookuptable.h
new file mode 100644
index 0000000..e78a694
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/Lookuptable.h
@@ -0,0 +1,38 @@
+#ifndef LOOKUPTABLE_HEADERFILE
+#define LOOKUPTABLE_HEADERFILE
+
+#include "Module.h"
+#include "Range.h"
+
+#define MAX_NUM_OF_RANGES 10
+
+#define INCLUDED true
+#define EXCLUDED false
+
+class Lookuptable : public Module {
+
+ private:
+ bool lookuptable_is_correct_and_active;
+ unsigned int num_of_ranges;
+
+ Range list_of_ranges[MAX_NUM_OF_RANGES];
+
+ public:
+ Lookuptable();
+ Lookuptable(char* name);
+
+ bool add_range_to_lookuptable(int score, float lower_boundary, bool flag_lower_boundary_included, float upper_boundary, bool flag_upper_boundary_included);
+
+ bool check_sort_and_activate();
+
+ bool get_lookuptable_is_correct_and_active();
+
+ int get_score(float input);
+
+
+
+ //testing/debugging functions
+ void printf_ranges();
+};
+
+#endif
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/MasterAgentHandlerOfAgent.cpp b/CAH_Version_2019.03.27/src/MasterAgentHandlerOfAgent.cpp
new file mode 100644
index 0000000..f9ae8f6
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/MasterAgentHandlerOfAgent.cpp
@@ -0,0 +1,88 @@
+#include "MasterAgentHandlerOfAgent.h"
+
+#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<get_occSendBuffer(); i++)
+ while(get_occSendBuffer() > 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;
+}
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/MasterAgentHandlerOfAgent.h b/CAH_Version_2019.03.27/src/MasterAgentHandlerOfAgent.h
new file mode 100644
index 0000000..53df2f3
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/MasterAgentHandlerOfAgent.h
@@ -0,0 +1,34 @@
+#ifndef MASTERAGENTHANDLEROFAGENT_HEADERFILE
+#define MASTERAGENTHANDLEROFAGENT_HEADERFILE
+
+#include "MasterAgentSlotOfAgent.h"
+#include "Unit.h"
+
+class MasterAgentHandlerOfAgent : public Unit {
+
+ private:
+ MasterAgentSlotOfAgent* masterAgentSlotOfAgent;
+
+ list<Message*> 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();
+
+};
+
+
+#endif
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/MasterAgentSlotOfAgent.cpp b/CAH_Version_2019.03.27/src/MasterAgentSlotOfAgent.cpp
new file mode 100644
index 0000000..6702201
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/MasterAgentSlotOfAgent.cpp
@@ -0,0 +1,5 @@
+#include "MasterAgentSlotOfAgent.h"
+
+MasterAgentSlotOfAgent :: MasterAgentSlotOfAgent() {
+
+}
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/MasterAgentSlotOfAgent.h b/CAH_Version_2019.03.27/src/MasterAgentSlotOfAgent.h
new file mode 100644
index 0000000..1d40ee5
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/MaximumValue.cpp b/CAH_Version_2019.03.27/src/MaximumValue.cpp
new file mode 100644
index 0000000..a709f21
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/MaximumValue.h b/CAH_Version_2019.03.27/src/MaximumValue.h
new file mode 100644
index 0000000..520ea3b
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/Message.cpp b/CAH_Version_2019.03.27/src/Message.cpp
new file mode 100644
index 0000000..469c6eb
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/Message.cpp
@@ -0,0 +1,58 @@
+#include "Message.h"
+
+#include <stdio.h>
+
+#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/CAH_Version_2019.03.27/src/Message.h b/CAH_Version_2019.03.27/src/Message.h
new file mode 100644
index 0000000..6e14395
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/MinumumValue.cpp b/CAH_Version_2019.03.27/src/MinumumValue.cpp
new file mode 100644
index 0000000..5739c73
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/MinumumValue.h b/CAH_Version_2019.03.27/src/MinumumValue.h
new file mode 100644
index 0000000..7228e91
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/Module.cpp b/CAH_Version_2019.03.27/src/Module.cpp
new file mode 100644
index 0000000..b33beea
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/Module.cpp
@@ -0,0 +1,19 @@
+#include "Module.h"
+#include <string.h>
+
+Module :: Module() {
+ set_name(NO_NAME);
+}
+
+Module :: Module(char* name) {
+ set_name(name);
+}
+
+
+void Module :: set_name(char* name) {
+ strncpy_s (this->name, name, MAX_LENGTH_NAME);
+}
+
+char* Module :: get_name() {
+ return this->name;
+}
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/Module.h b/CAH_Version_2019.03.27/src/Module.h
new file mode 100644
index 0000000..49122b7
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/Module.h
@@ -0,0 +1,20 @@
+#ifndef MODULE_HEADERFILE
+#define MODULE_HEADERFILE
+
+#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
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/Node.cpp b/CAH_Version_2019.03.27/src/Node.cpp
new file mode 100644
index 0000000..5495c37
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/Node.h b/CAH_Version_2019.03.27/src/Node.h
new file mode 100644
index 0000000..50a4f06
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/Range.cpp b/CAH_Version_2019.03.27/src/Range.cpp
new file mode 100644
index 0000000..5977fd2
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/Range.cpp
@@ -0,0 +1,224 @@
+#include "Range.h"
+#include <stdio.h>
+
+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/CAH_Version_2019.03.27/src/Range.h b/CAH_Version_2019.03.27/src/Range.h
new file mode 100644
index 0000000..1c38cb8
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/Sensor.cpp b/CAH_Version_2019.03.27/src/Sensor.cpp
new file mode 100644
index 0000000..92c4bb2
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/Sensor.cpp
@@ -0,0 +1,166 @@
+#include "Sensor.h"
+#include <stdio.h>
+
+//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/CAH_Version_2019.03.27/src/Sensor.h b/CAH_Version_2019.03.27/src/Sensor.h
new file mode 100644
index 0000000..824a26e
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/SensorHandlerOfAgent.cpp b/CAH_Version_2019.03.27/src/SensorHandlerOfAgent.cpp
new file mode 100644
index 0000000..b80a08a
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/SensorHandlerOfAgent.cpp
@@ -0,0 +1,190 @@
+#include "SensorHandlerOfAgent.h"
+#include <stdio.h>
+#include "printError.h"
+
+#include <algorithm>
+
+#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<SensorSlotOfAgent*>* SensorHandlerOfAgent :: get_vMountedSensors() {
+ return &vMountedSensors;
+}
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/SensorHandlerOfAgent.h b/CAH_Version_2019.03.27/src/SensorHandlerOfAgent.h
new file mode 100644
index 0000000..1b11494
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/SensorHandlerOfAgent.h
@@ -0,0 +1,52 @@
+#ifndef SENSORHANDLEROFAGENT_HEADERFILE
+#define SENSORHANDLEROFAGENT_HEADERFILE
+
+#include <vector>
+#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<SensorSlotOfAgent*> vMountedSensors;
+ unsigned int maxNumOf_mountedSensors;
+
+ void init_sensorHandler();
+
+ 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<SensorSlotOfAgent*>* get_vMountedSensors();
+
+};
+
+
+#endif
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/SensorSlotOfAgent.cpp b/CAH_Version_2019.03.27/src/SensorSlotOfAgent.cpp
new file mode 100644
index 0000000..b1fe99b
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/SensorSlotOfAgent.cpp
@@ -0,0 +1,45 @@
+#include <stdio.h>
+#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/CAH_Version_2019.03.27/src/SensorSlotOfAgent.h b/CAH_Version_2019.03.27/src/SensorSlotOfAgent.h
new file mode 100644
index 0000000..ccbdfbb
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/SensorSlotOfTestbench.cpp b/CAH_Version_2019.03.27/src/SensorSlotOfTestbench.cpp
new file mode 100644
index 0000000..1c7757a
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/SensorSlotOfTestbench.cpp
@@ -0,0 +1,51 @@
+#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;
+}
+
diff --git a/CAH_Version_2019.03.27/src/SensorSlotOfTestbench.h b/CAH_Version_2019.03.27/src/SensorSlotOfTestbench.h
new file mode 100644
index 0000000..46865d3
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/SensorSlotOfTestbench.h
@@ -0,0 +1,27 @@
+#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();
+};
+
+#endif
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/SlaveAgentHandlerOfAgent.cpp b/CAH_Version_2019.03.27/src/SlaveAgentHandlerOfAgent.cpp
new file mode 100644
index 0000000..0aa9e99
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/SlaveAgentHandlerOfAgent.cpp
@@ -0,0 +1,222 @@
+#include "SlaveAgentHandlerOfAgent.h"
+
+#include "instruction_set_architecture.h"
+#include <stdio.h>
+#include "printError.h"
+
+
+#include <algorithm>
+
+#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<SlaveAgentSlotOfAgent*>* SlaveAgentHandlerOfAgent :: get_vMountedSlaveAgents() {
+ return &vMountedSlaveAgents;
+}
+
+bool SlaveAgentHandlerOfAgent::saveValueInHistory(SlaveAgentSlotOfAgent* slaveAgentSlotOfAgent) {
+ if (slaveAgentSlotOfAgent != NULL) {
+ //TODO: change this hardcoded value
+ while (slaveAgentSlotOfAgent->getHistoryLength() >= histLength) { //10) {
+ slaveAgentSlotOfAgent->deleteOldestHistoryEntry();
+ }
+ 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/CAH_Version_2019.03.27/src/SlaveAgentHandlerOfAgent.h b/CAH_Version_2019.03.27/src/SlaveAgentHandlerOfAgent.h
new file mode 100644
index 0000000..d627671
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/SlaveAgentHandlerOfAgent.h
@@ -0,0 +1,56 @@
+#ifndef SLAVEAGENTHANDLEROFAGENT_HEADERFILE
+#define SLAVEAGENTHANDLEROFAGENT_HEADERFILE
+
+#include "SlaveAgentSlotOfAgent.h"
+#include "Unit.h"
+#include <vector>
+
+using namespace std;
+
+class SlaveAgentHandlerOfAgent : public Unit {
+
+ private:
+
+ //TODO: set- and get function for maxNumOf_mountedSlaveAgents;
+ vector<SlaveAgentSlotOfAgent*> 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<SlaveAgentSlotOfAgent*>* get_vMountedSlaveAgents();
+
+ bool saveValueInHistory(SlaveAgentSlotOfAgent* slaveAgentSlotOfAgent);
+ bool saveAllValuesInHistory();
+
+ //schirch
+ unsigned int histLength;
+
+};
+
+
+#endif
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/SlaveAgentSlotOfAgent.cpp b/CAH_Version_2019.03.27/src/SlaveAgentSlotOfAgent.cpp
new file mode 100644
index 0000000..fd47597
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/SlaveAgentSlotOfAgent.cpp
@@ -0,0 +1,218 @@
+#include "SlaveAgentSlotOfAgent.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)) {
+ //if (valueIsRelatedToReferenceValueCanberra(slaveAgentValue, entry, threshold)) {
+ numberOfRelativesToActualValue++;
+ }
+ }
+ return numberOfRelativesToActualValue;
+}
+
+
+
+
+
+void SlaveAgentSlotOfAgent::printHistory() {
+ printf("History: ");
+ for (auto &entry : lSlaveAgentHistory) {
+ printf("%f, ", entry);
+ }
+ printf("\n");
+}
+
+
+/*
+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<State*>* 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<State*>::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();
+}
+*/
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/SlaveAgentSlotOfAgent.h b/CAH_Version_2019.03.27/src/SlaveAgentSlotOfAgent.h
new file mode 100644
index 0000000..9d3f2a4
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/SlaveAgentSlotOfAgent.h
@@ -0,0 +1,77 @@
+#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<float> lSlaveAgentHistory;
+
+ bool flagSlaveAgentValueIsSet;
+ /*
+ //XXX - next 3 variables needed?
+ bool flagSlaveAgentValueHasChanged;
+ bool flagSlaveAgentValueChangeIsSet;
+ float slaveAgentValueChange;
+ */
+
+
+
+ /*
+ vector<State*> vStates;
+ State* activeState;
+ State* backupState;
+
+ bool addStateToStatesVector(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);
+
+
+
+ void printHistory();
+
+
+ /*
+ bool get_flagSlaveAgentValueHasChanged();
+
+ bool get_slaveAgentValueChangingRate(float* slaveAgentValueChangingRate);
+
+ /*
+ vector<State*>* 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<State*>* getStatesVector();
+ State* getActiveState();
+ */
+};
+
+
+#endif
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/Slot.cpp b/CAH_Version_2019.03.27/src/Slot.cpp
new file mode 100644
index 0000000..ea1be21
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/Slot.cpp
@@ -0,0 +1,20 @@
+#include "Slot.h"
+
+#include <stdio.h>
+
+
+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/CAH_Version_2019.03.27/src/Slot.h b/CAH_Version_2019.03.27/src/Slot.h
new file mode 100644
index 0000000..9fe673d
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/SlotOfAgent.cpp b/CAH_Version_2019.03.27/src/SlotOfAgent.cpp
new file mode 100644
index 0000000..68eb7e0
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/SlotOfAgent.cpp
@@ -0,0 +1,47 @@
+#include "SlotOfAgent.h"
+
+#include <stdio.h>
+
+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/CAH_Version_2019.03.27/src/SlotOfAgent.h b/CAH_Version_2019.03.27/src/SlotOfAgent.h
new file mode 100644
index 0000000..92d30fb
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/State.cpp b/CAH_Version_2019.03.27/src/State.cpp
new file mode 100644
index 0000000..6e3d970
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/State.cpp
@@ -0,0 +1,254 @@
+#include "State.h"
+
+#include "printError.h"
+#include "relationChecker.h"
+
+#define INJECTIONPARTITIONING 10
+
+State::State() {
+ //discreteAveragePartitionSize = INJECTIONPARTITIONING;
+ discreteAveragePartitionCounter = 0;
+}
+/*
+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<SubState*>* 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<SubState*>* 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<SubState*>* 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 (!valueIsRelatedToReferenceValueCanberra(subState->getDiscreteAverageOfFirstBlock(discreteAveragePartitionSize), subState->getDiscreteAverageOfLastBlock(discreteAveragePartitionSize), thresholdNotDrift)) {
+ 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);
+}
+
+
+
+/*
+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);
+}
+
+*/
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/State.h b/CAH_Version_2019.03.27/src/State.h
new file mode 100644
index 0000000..c19d754
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/State.h
@@ -0,0 +1,73 @@
+#ifndef STATE_HEADERFILE
+#define STATE_HEADERFILE
+
+#include "SlaveAgentSlotOfAgent.h"
+#include "SubState.h"
+#include <vector>
+
+class State {
+
+ private:
+
+ vector<SubState*> vInputSubStates;
+ vector<SubState*> vOutputSubStates;
+
+ //unsigned int discreteAveragePartitionSize;
+ unsigned int discreteAveragePartitionCounter;
+
+ /*
+ StatisticValue continuousStatisticValue;
+ vector<AverageValue*> vDiscreteAveragePartition;
+
+ bool addDiscreteAveragePartition();
+ */
+
+ bool addSubState(vector<SubState*>* vSubStates, SlaveAgentSlotOfAgent* slot);
+
+ bool variablesAreRelated(vector<SubState*>* vSubStates, float thresholdToBeRelated);
+
+ bool checkSubStatesForNotDrifting(vector<SubState*>* vSubStates, unsigned int discreteAveragePartitionSize, unsigned int compareDistanceDiscreteAveragePartition, float thresholdNotDrift);
+
+ 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);
+
+
+
+ /*
+
+
+ bool injectValue(float value);
+ bool valueIsRelated(float value, float thresholdToAverage);
+
+ bool isNew();
+
+ unsigned int getNumberOfInjections();
+
+ void deleteState();
+ */
+
+
+};
+
+#endif
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/StateHandler.cpp b/CAH_Version_2019.03.27/src/StateHandler.cpp
new file mode 100644
index 0000000..5ffd9a1
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/StateHandler.cpp
@@ -0,0 +1,713 @@
+#include "StateHandler.h"
+
+#include <algorithm>
+#include "printError.h"
+#include "rlutil.h"
+
+
+//#define PRINT
+//#define STOP_WHEN_BROKEN
+//#define STOP_WHEN_DRIFT
+//#define STOP_WHEN_NEW_STATE
+//#define STOP_EVERY_CYCLE
+
+
+
+//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
+
+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;
+
+}
+
+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<SlaveAgentSlotOfAgent*>* 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::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<SlaveAgentSlotOfAgent*>* 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 {
+
+ //printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
+
+ return false;
+ }
+ }
+
+ return flagAllVariablesAreStable;
+}
+
+
+State* StateHandler::makeNewState() {
+#ifdef PRINT
+ printf(" >> New State\n");
+#endif // PRINT
+ 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() {
+#ifdef PRINT
+ printf(" >> Save Active State\n");
+#endif // PRINT
+ if (activeState != NULL) {
+ for (auto &state : vStates) {
+ if (state == activeState)
+ return true;
+ }
+
+
+ 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;
+}
+
+int StateHandler::findRelatedStateAndMakeItActive() {
+ /*State* state = findRelatedState();
+ if (state != NULL) {
+ activeState = state;
+ return true;
+ }
+ return false;
+ */
+
+
+
+ for (auto &state : vStates) {
+ if (state->inputVariablesAreRelated(thresholdToBeRelated) && state->outputVariablesAreRelated(thresholdToBeRelated)) {
+ activeState = state;
+ return 1;
+ }
+ else if ((state->inputVariablesAreRelated(thresholdToBeRelated) && !(state->outputVariablesAreRelated(thresholdToBeRelated))) || (!(state->inputVariablesAreRelated(thresholdToBeRelated)) && state->outputVariablesAreRelated(thresholdToBeRelated))) {
+ activeState = state;
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
+void StateHandler::eraseStatesWithLessInjections() {
+ if (activeState != NULL) {
+ if (activeState->getNumOfInjections() < minNumToBeValidState) {
+ activeState = NULL;
+ }
+ }
+
+ for (vector<State*>::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--;
+ }
+ }
+
+}
+
+
+
+
+//XXX - only for now
+bool test = true;
+unsigned int brokenCounter = 0, driftCounter = 0;
+
+void printDrift() {
+ driftCounter++;
+#ifdef PRINT
+ setColor(TXTCOLOR_YELLOW);
+ printf(" >> DRIFT\n");
+ setColor(TXTCOLOR_GREY);
+#endif // PRINT
+
+#ifdef STOP_WHEN_DRIFT
+ getchar();
+#endif // STOP_WHEN_DRIFT
+
+
+ test = true;
+}
+
+void printBroken() {
+ brokenCounter++;
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTRED);
+ printf(" >> BROKEN\n");
+ setColor(TXTCOLOR_GREY);
+#endif // PRINT
+
+
+#ifdef STOP_WHEN_BROKEN
+ getchar();
+#endif // STOP_WHEN_BROKEN
+
+ test = true;
+}
+
+//XXX - only for now
+//unsigned int old_cycle = 1;
+
+void StateHandler::trigger(unsigned int cycle) {
+#ifdef PRINT
+ printf("cycle: %u\n", cycle);
+#endif // PRINT
+
+ /*
+ //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;
+ */
+
+
+ //New for Journal Submission
+ if (cycle == 1) {
+ csv_writer->write_field("Unstable(0)/Stable(1)");
+ csv_writer->make_new_field();
+
+ csv_writer->write_field("NoState(0)/NewState(1)/oldState(2)/sameState(3)");
+ csv_writer->make_new_field();
+
+ csv_writer->write_field("unknown(0)/broken(1)/drift(2)/ok(3)");
+ csv_writer->make_new_field();
+
+ csv_writer->write_field("numOfInjections");
+ csv_writer->make_new_field();
+
+ csv_writer->write_field("numOfStates");
+ csv_writer->make_new_field();
+
+ csv_writer->write_field("actualState");
+ csv_writer->make_new_line();
+ }
+
+
+
+
+ if (variablesAreStable(&vInputVariables) && variablesAreStable(&vOutputVariables)) {
+#ifdef PRINT
+ printf(" > stable\n");
+#endif // PRINT
+ //XXX - only for now
+ csv_writer->write_field(1); //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->write_field(3); //ok
+ 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->write_field(3); //still same active state
+ csv_writer->make_new_field();
+ csv_writer->write_field(2); //drift
+ csv_writer->make_new_field();
+ }
+ //XXX - only for now
+ else {
+ csv_writer->write_field(3); //still same active state
+ csv_writer->make_new_field();
+ csv_writer->write_field(3); //ok
+ csv_writer->make_new_field();
+ }
+ }
+ else {
+ if (activeState->getNumOfInjections() >= minNumToBeValidState) {
+ if ((!flagInputUnchanged && flagOutputUnchanged) || (flagInputUnchanged && !flagOutputUnchanged)) {
+ printBroken();
+ //getchar();
+
+ //XXX - only for now
+ csv_writer->write_field(0); //no state
+ csv_writer->make_new_field();
+ csv_writer->write_field(1); //broken
+ csv_writer->make_new_field();
+ }
+ else {
+ addActiveStateToStateVector();
+
+ if (findRelatedStateAndMakeItActive() == 0) {
+ makeNewActiveState();
+ activeState->injectValues(discreteAveragePartitionSize);
+
+ //XXX - only for now
+ csv_writer->write_field(1); //new active state
+ csv_writer->make_new_field();
+ csv_writer->write_field(3); //ok
+ csv_writer->make_new_field();
+ }
+ else if (findRelatedStateAndMakeItActive() == 1) {
+ //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(2); //drift
+ csv_writer->make_new_field();
+ }
+ //XXX - only for now
+ else {
+ csv_writer->write_field(3); //ok
+ 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();
+
+ //XXX - only for now
+ csv_writer->write_field(1); //broken
+ csv_writer->make_new_field();
+ }
+ }
+ }
+ else {
+ delete activeState;
+ if (findRelatedStateAndMakeItActive() == 0) {
+ makeNewActiveState();
+ activeState->injectValues(discreteAveragePartitionSize);
+
+ //XXX - only for now
+ csv_writer->write_field(1); //new active state
+ csv_writer->make_new_field();
+ csv_writer->write_field(3); //ok
+ csv_writer->make_new_field();
+ }
+ else if(findRelatedStateAndMakeItActive() == 1) {
+ //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(2); //drift
+ csv_writer->make_new_field();
+ }
+ //XXX - only for now
+ else {
+ csv_writer->write_field(3); //ok
+ 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();
+
+ //XXX - only for now
+ csv_writer->write_field(1); //broken
+ csv_writer->make_new_field();
+ }
+ }
+ }
+ }
+ else {
+ if (findRelatedStateAndMakeItActive() == 0) {
+ makeNewActiveState();
+ activeState->injectValues(discreteAveragePartitionSize);
+
+ //XXX - only for now
+ csv_writer->write_field(1); //new active state
+ csv_writer->make_new_field();
+ csv_writer->write_field(3); //ok
+ csv_writer->make_new_field();
+ }
+ else if (findRelatedStateAndMakeItActive() == 1){
+ //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(2); //drift
+ csv_writer->make_new_field();
+ }
+ //XXX - only for now
+ else {
+ csv_writer->write_field(3); //ok
+ 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();
+
+ //XXX - only for now
+ csv_writer->write_field(1); //broken
+ csv_writer->make_new_field();
+ }
+ }
+ }
+
+
+
+
+
+ if (activeState != NULL) {
+#ifdef PRINT
+ printf(" -- an activeState exist: \n");
+ printf(" --- injections: %u\n", activeState->getNumOfInjections());
+#endif // PRINT
+ //XXX - only for now
+ csv_writer->write_field((int)activeState->getNumOfInjections()); //number of injections
+ csv_writer->make_new_field();
+
+
+ bool activeStateIsAlreadySaved = false;
+ int stateNr = 1;
+ for (auto &s : vStates) {
+ if (s == activeState) {
+ activeStateIsAlreadySaved = true;
+ break;
+ }
+ stateNr++;
+ }
+
+ if (activeStateIsAlreadySaved) {
+ csv_writer->write_field((int)vStates.size()); //numOfStates
+ csv_writer->make_new_field();
+ csv_writer->write_field(stateNr); //ActualState
+ }
+ else {
+ csv_writer->write_field((int)vStates.size() + 1); //numOfStates
+ csv_writer->make_new_field();
+ csv_writer->write_field((int)vStates.size() + 1); //ActualState
+ }
+
+ csv_writer->make_new_line();
+
+ }
+ //XXX - only for now
+ else {
+ csv_writer->write_field(0); //number of injections
+ csv_writer->make_new_field();
+ csv_writer->write_field((int)vStates.size() + 1); //numOfStates
+ csv_writer->make_new_field();
+ csv_writer->write_field(0); //ActualState
+ csv_writer->make_new_line();
+ }
+
+#ifdef PRINT
+ bool activeStateIsAlreadySaved = false;
+ int stateNr = 1;
+ for (auto &s : vStates) {
+ if (s == activeState) {
+ activeStateIsAlreadySaved = true;
+ break;
+ }
+ stateNr++;
+ }
+
+ if (activeStateIsAlreadySaved) {
+ printf(" ----------- Number of States: %u\n", vStates.size());
+ printf(" ----------- Actual State: %u\n", stateNr);
+ }
+ else {
+ printf(" ----------- Number of States: %u\n", vStates.size() + 1);
+ printf(" ----------- Actual State: %u\n", vStates.size() + 1);
+ }
+
+
+ /*
+ 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);
+#endif // PRINT
+
+
+ if (test) {
+ test = false;
+ //getchar();
+ }
+
+ flagVariablesWereStable = true;
+ }
+
+ else {
+#ifdef PRINT
+ printf(" > unstable\n");
+#endif // PRINT
+
+ //XXX - only for now
+ csv_writer->write_field(0); //unstable
+ csv_writer->make_new_field();
+ csv_writer->write_field(0); //no state
+ csv_writer->make_new_field();
+ csv_writer->write_field(0); //don't know if drift, broken, ok
+ csv_writer->make_new_field();
+ csv_writer->write_field(0); //num of injections
+ csv_writer->make_new_field();
+ csv_writer->write_field((int)vStates.size()); //numOfStates
+ csv_writer->make_new_field();
+ csv_writer->write_field(0); //ActualState
+ 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;
+ }
+ //activeState = NULL;
+ }
+ }
+
+ flagVariablesWereStable = false;
+ }
+
+#ifdef STOP_EVERY_CYCLE
+ getchar();
+#endif // STOP_EVERY_CYCLE
+
+
+ //xxx - only for now
+ //csv_writer->make_new_line();
+}
+
+
+void StateHandler::closeCsvFile() {
+ if(csv_writer != NULL)
+ csv_writer->close_file();
+}
+
+void StateHandler::setCSVwriter(char* output_file_name) {
+ csv_writer = new CSV_Writer("CSV Writer", output_file_name);
+}
+
+
diff --git a/CAH_Version_2019.03.27/src/StateHandler.h b/CAH_Version_2019.03.27/src/StateHandler.h
new file mode 100644
index 0000000..ea86cb5
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/StateHandler.h
@@ -0,0 +1,121 @@
+#ifndef STATEHANDLER_HEADERFILE
+#define STATEHANDLER_HEADERFILE
+
+#include "Module.h"
+#include "SlaveAgentSlotOfAgent.h"
+#include "State.h"
+
+#include "StateVariable.h"
+#include <vector>
+
+//XXX - only for now
+#include "CSV_Writer.h"
+
+
+using namespace std;
+
+class StateHandler : public Module {
+ private:
+ //XXX - Maybe Object "StateVariable" between StateHandler and Slot?!
+ vector<SlaveAgentSlotOfAgent*> vInputVariables;
+ vector<SlaveAgentSlotOfAgent*> vOutputVariables;
+
+ vector<State*> vStates;
+ State* activeState;
+
+
+ bool flagVariablesWereStable;
+
+
+ unsigned int discreteAveragePartitionSize;
+ unsigned int compareDistanceDiscreteAveragePartition;
+
+
+
+
+ void initStateHandler();
+
+ bool addVariable(vector<SlaveAgentSlotOfAgent*>* vVariables, SlaveAgentSlotOfAgent* slot);
+ bool variablesAreStable(vector<SlaveAgentSlotOfAgent*>* vVariables);
+
+ State* makeNewState();
+
+ bool addActiveStateToStateVector();
+ //bool addStateAndMakeItActive();
+
+ bool makeNewActiveState();
+
+ State* findRelatedState();
+ int findRelatedStateAndMakeItActive();
+
+ void eraseStatesWithLessInjections();
+
+ //schirch
+ 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();
+
+
+
+
+ //schirch
+ unsigned int slidingWindowBufferSize;
+ unsigned int minNumOfRelatedValuesToBeStable;
+ float thresholdToBeStable;
+ unsigned int minNumToBeValidState;
+ float thresholdToBeRelated;
+ float thresholdNotDrift;
+ unsigned int allowedDisparityTime;
+
+
+ void StateHandler::setCSVwriter(char* output_file_name);
+
+ /*
+ private:
+ vector<SlaveAgentSlotOfAgent*> 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
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/StateModule.cpp b/CAH_Version_2019.03.27/src/StateModule.cpp
new file mode 100644
index 0000000..b59ed52
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/StateModule.h b/CAH_Version_2019.03.27/src/StateModule.h
new file mode 100644
index 0000000..56496d7
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/StateModule.h
@@ -0,0 +1,34 @@
+#ifndef STATEMODULE_HEADERFILE
+#define STATEMODULE_HEADERFILE
+/*
+#include "State.h"
+#include "Module.h"
+#include <vector>
+
+using namespace std;
+
+class StateModule : public Module {
+
+ private:
+ vector<State*> 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/CAH_Version_2019.03.27/src/StateVariable.cpp b/CAH_Version_2019.03.27/src/StateVariable.cpp
new file mode 100644
index 0000000..e785824
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/StateVariable.cpp
@@ -0,0 +1,5 @@
+#include "StateVariable.h"
+
+StateVariable::StateVariable() {
+
+}
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/StateVariable.h b/CAH_Version_2019.03.27/src/StateVariable.h
new file mode 100644
index 0000000..814ef8a
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/StatisticValue.cpp b/CAH_Version_2019.03.27/src/StatisticValue.cpp
new file mode 100644
index 0000000..2c232df
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/StatisticValue.h b/CAH_Version_2019.03.27/src/StatisticValue.h
new file mode 100644
index 0000000..966b8be
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/SubState.cpp b/CAH_Version_2019.03.27/src/SubState.cpp
new file mode 100644
index 0000000..2980d26
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/SubState.cpp
@@ -0,0 +1,140 @@
+#include "SubState.h"
+
+#include "printError.h"
+#include "relationChecker.h"
+
+
+SubState::SubState() {
+
+
+}
+
+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 valueIsRelatedToReferenceValue(statisticValue.getAverageValue(), value, thresholdToBeRelated);
+ return valueIsRelatedToReferenceValueOrBetweenMinAndMax(statisticValue.getAverageValue(), statisticValue.getMinimumValue(), statisticValue.getMaximumValue(), value, thresholdToBeRelated);
+ //return valueIsRelatedToReferenceValueCanberra(statisticValue.getAverageValue(), 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();
+ }
+ }
+}
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/SubState.h b/CAH_Version_2019.03.27/src/SubState.h
new file mode 100644
index 0000000..ac1297e
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/SubState.h
@@ -0,0 +1,40 @@
+#ifndef SUBSTATE_HEADERFILE
+#define SUBSTATE_HEADERFILE
+
+#include "SlaveAgentSlotOfAgent.h"
+#include "StatisticValue.h"
+
+class SubState {
+
+ private:
+ SlaveAgentSlotOfAgent* slot;
+ StatisticValue statisticValue;
+ vector<AverageValue*> vDiscreteAverage;
+
+ bool lastDiscreteAverageBlockIsCompleted(unsigned int discreteAveragePartitionSize);
+
+ 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);
+};
+
+#endif
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/Testbench.cpp b/CAH_Version_2019.03.27/src/Testbench.cpp
new file mode 100644
index 0000000..c277680
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/Testbench.cpp
@@ -0,0 +1,553 @@
+#include "Testbench.h"
+
+#include "printError.h"
+#include <stdio.h>
+
+#define MAXNUMOF_REGISTEREDCAGENTS 1000
+#define MAXNUMOF_REGISTEREDCHANNELS 1000
+#define MAXNUMOF_REGISTEREDSENSORS 1000
+
+using namespace std;
+
+void Testbench :: init_testbench() {
+ maxNumOf_registeredAgents = MAXNUMOF_REGISTEREDCAGENTS;
+ maxNumOf_registeredChannels = MAXNUMOF_REGISTEREDCHANNELS;
+ maxNumOf_registeredSensors = MAXNUMOF_REGISTEREDSENSORS;
+}
+
+Testbench :: Testbench() {
+ set_name(NO_NAME);
+ init_testbench();
+}
+
+Testbench :: Testbench(char* name) {
+ set_name(name);
+ init_testbench();
+}
+
+bool Testbench :: register_agent(Agent* agent) {
+ AgentSlotOfTestbench* agentSlot = new AgentSlotOfTestbench();
+ if(agentSlot != NULL) {
+ if(agentSlot->set_agent(agent)) {
+ try {
+ if(vector_registeredAgents.size() < maxNumOf_registeredAgents) {
+ 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() < maxNumOf_registeredSensors) {
+ 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() < maxNumOf_registeredChannels) {
+ 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;
+ }
+}
+
+void Testbench :: simulate(unsigned int rounds) {
+ for(unsigned int cycle =1; cycle <=rounds; cycle++) {
+
+ //printf("cycle %u\n", sec);
+
+ //update sensor values
+ for(auto &sensorSlot : vector_registeredSensors) {
+ Sensor *sensor = sensorSlot->get_sensor();
+ 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();
+ }
+ }
+ }
+
+}
+
+
+
+
+
+/*
+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_ix<num_of_registered_sensors; s_ix++) {
+ csv_writer->write_field(registered_sensors[s_ix]->get_name());
+ csv_writer->make_new_field();
+ }
+
+ for(unsigned int a_ix=0; a_ix<num_of_registered_agents; a_ix++) {
+
+ csv_writer->write_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_ix<num_of_registered_agents-1; a_ix++) {
+ registered_agents[a_ix] = registered_agents[a_ix+1];
+ }
+ num_of_registered_agents--;
+
+ return true;
+ }
+ return false;
+}
+
+bool Testbench :: get_ix_of_agent(Agent *agent, unsigned int *agent_ix) {
+ for(unsigned int a_ix=0; a_ix<num_of_registered_agents; a_ix++) {
+ if(registered_agents[a_ix] == agent) {
+ *agent_ix = a_ix;
+ return true;
+ }
+ }
+ return false;
+}
+
+
+//for sensors:
+unsigned int Testbench :: get_num_of_registered_sensors() {
+ return num_of_registered_sensors;
+}
+
+bool Testbench :: register_sensor(Sensor* sensor) {
+ if(num_of_registered_sensors < MAX_NUM_OF_SENSORS) {
+ registered_sensors[num_of_registered_sensors] = sensor;
+ num_of_registered_sensors++;
+ return true;
+ }
+ return false;
+}
+
+bool Testbench :: register_sensor(Sensor* sensor, CSV_Reader *csvr) {
+ if(num_of_registered_sensors < MAX_NUM_OF_SENSORS) {
+ registered_sensors[num_of_registered_sensors] = sensor;
+ registered_sensors_csvr[num_of_registered_sensors] = csvr;
+ flag_sensor_has_csvr[num_of_registered_sensors] = true;
+
+ num_of_registered_sensors++;
+ return true;
+ }
+
+ return false;
+}
+
+bool Testbench :: deregister_sensor(Sensor* sensor) {
+ unsigned int sensor_ix;
+
+ if(get_ix_of_sensor(sensor, &sensor_ix)) {
+ return deregister_sensor(sensor_ix);
+ }
+
+ return false;
+}
+
+bool Testbench :: deregister_sensor(unsigned int sensor_ix) {
+ if(sensor_ix < num_of_registered_sensors) {
+ for(unsigned int s_ix=sensor_ix; s_ix<num_of_registered_sensors-1; s_ix++) {
+ registered_sensors[s_ix] = registered_sensors[s_ix+1];
+ //todo: next 2 lines are untested - test then
+ registered_sensors_csvr[s_ix] = registered_sensors_csvr[s_ix+1];
+ flag_sensor_has_csvr[s_ix] = flag_sensor_has_csvr[s_ix+1];
+ }
+ num_of_registered_sensors--;
+
+ return true;
+ }
+ return false;
+}
+
+bool Testbench :: get_ix_of_sensor(Sensor* sensor, unsigned int *sensor_ix) {
+ for(unsigned int s_ix=0; s_ix<num_of_registered_sensors; s_ix++) {
+ if(registered_sensors[s_ix] == sensor) {
+ *sensor_ix = s_ix;
+ return true;
+ }
+ }
+ return false;
+}
+
+bool Testbench :: get_flag_sensor_has_csvr(unsigned int sensor_ix) {
+ return flag_sensor_has_csvr[sensor_ix];
+}
+
+CSV_Reader* Testbench :: get_registered_sensors_csvr(unsigned int sensor_ix) {
+ if(flag_sensor_has_csvr[sensor_ix]) {
+ return registered_sensors_csvr[sensor_ix];
+ }
+ return NULL;
+}
+
+//TODO: test following function! ...until now it is untested
+CSV_Reader* Testbench :: get_registered_sensors_csvr(Sensor* sensor) {
+ unsigned int sensor_ix;
+
+ if(get_ix_of_sensor(sensor, &sensor_ix)) {
+ if(flag_sensor_has_csvr[sensor_ix]) {
+ return registered_sensors_csvr[sensor_ix];
+ }
+ }
+
+ return NULL;
+}
+
+
+
+
+
+
+//for channels:
+unsigned int Testbench :: get_num_of_registered_channels() {
+ return num_of_registered_channels;
+}
+
+bool Testbench :: register_channel(Channel* channel) {
+ if(num_of_registered_channels < MAX_NUM_OF_CHANNELS) {
+ registered_channels[num_of_registered_channels] = channel;
+ num_of_registered_channels++;
+ return true;
+ }
+ return false;
+}
+
+bool Testbench :: deregister_channel(Channel* channel) {
+ unsigned int channel_ix;
+
+ if(get_ix_of_channel(channel, &channel_ix)) {
+ return deregister_channel(channel_ix);
+ }
+
+ return false;
+}
+
+bool Testbench :: deregister_channel(unsigned int channel_ix) {
+ if(channel_ix < num_of_registered_channels) {
+ for(unsigned int c_ix=channel_ix; c_ix<num_of_registered_channels-1; c_ix++) {
+ registered_channels[channel_ix] = registered_channels[channel_ix+1];
+ }
+ num_of_registered_channels--;
+
+ return true;
+ }
+ return false;
+}
+
+bool Testbench :: get_ix_of_channel(Channel* channel, unsigned int *channel_ix) {
+ for(unsigned int c_ix=0; c_ix<num_of_registered_channels; c_ix++) {
+ if(registered_channels[c_ix] == channel) {
+ *channel_ix = c_ix;
+ return true;
+ }
+ }
+ return false;
+}
+
+bool Testbench :: register_csv_reader(CSV_Reader* csv_reader) {
+ if(csv_reader != NULL) {
+ this->csv_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;
+}
+*/
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/Testbench.h b/CAH_Version_2019.03.27/src/Testbench.h
new file mode 100644
index 0000000..b68f721
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/Testbench.h
@@ -0,0 +1,118 @@
+#ifndef TESTBENCH_HEADERFILE
+#define TESTBENCH_HEADERFILE
+
+#include "AgentSlotOfTestbench.h"
+#include "ChannelSlotOfTestbench.h"
+#include "CSVreaderModule.h"
+#include "SensorSlotOfTestbench.h"
+#include "Unit.h"
+#include <vector>
+
+/*
+#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;
+
+class Testbench : public Module {
+
+ private:
+ //TODO: set- and get function for maxNumOf_registeredAgents;
+ vector<AgentSlotOfTestbench*> vector_registeredAgents;
+ unsigned int maxNumOf_registeredAgents;
+
+ //TODO: set- and get function for maxNumOf_registeredChannels;
+ vector<ChannelSlotOfTestbench*> vector_registeredChannels;
+ unsigned int maxNumOf_registeredChannels;
+
+ //TODO: set- and get function for maxNumOf_registeredSensors;
+ vector<SensorSlotOfTestbench*> vector_registeredSensors;
+ unsigned int maxNumOf_registeredSensors;
+
+ void init_testbench();
+
+ public:
+ Testbench();
+ Testbench(char* name);
+
+ bool register_agent(Agent* agent);
+
+ bool register_sensor(Sensor* sensor);
+ SensorSlotOfTestbench* get_sensorSlotAddressOfTestbench(Sensor* sensor);
+
+ bool register_channel(Channel* channel);
+
+ void simulate(unsigned int rounds);
+
+
+
+
+ /*
+ 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
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/Unit.cpp b/CAH_Version_2019.03.27/src/Unit.cpp
new file mode 100644
index 0000000..71c4d95
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/Unit.h b/CAH_Version_2019.03.27/src/Unit.h
new file mode 100644
index 0000000..ec557f5
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/abstraction_functions.cpp b/CAH_Version_2019.03.27/src/abstraction_functions.cpp
new file mode 100644
index 0000000..e69de29
diff --git a/CAH_Version_2019.03.27/src/abstraction_functions.h b/CAH_Version_2019.03.27/src/abstraction_functions.h
new file mode 100644
index 0000000..0b2db65
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/abstraction_interface.cpp b/CAH_Version_2019.03.27/src/abstraction_interface.cpp
new file mode 100644
index 0000000..59ae617
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/abstraction_interface.h b/CAH_Version_2019.03.27/src/abstraction_interface.h
new file mode 100644
index 0000000..0b0a7b6
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/attach_modules.cpp b/CAH_Version_2019.03.27/src/attach_modules.cpp
new file mode 100644
index 0000000..bf5d216
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/attach_modules.cpp
@@ -0,0 +1,58 @@
+#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) {
+#ifdef PRINT
+ printf(" > HistoryModule ");
+ setColor(TXTCOLOR_LIGHTCYAN);
+ printf("%s ", historyModule->get_name());
+ setColor(TXTCOLOR_GREY);
+ printf("(id: %03u) ", historyModule->get_id());
+#endif // PRINT
+ if(sensorSlotOfAgent->set_historyModule(historyModule)) {
+#ifdef PRINT
+ 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());
+#endif // PRINT
+ return true;
+ }
+ else {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTRED);
+ printf("Couldn't attach the HistoryModule!\n");
+ setColor(TXTCOLOR_GREY);
+#endif // PRINT
+ }
+ }
+ else {
+#ifdef PRINT
+ 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);
+#endif // PRINT
+ }
+ }
+ else {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTRED);
+ printf(" > Couldn't attach the HistoryModule because Agent, Channel, or HistoryModule is not valid!\n");
+ setColor(TXTCOLOR_GREY);
+#endif // PRINT
+ }
+ return false;
+}
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/attach_modules.h b/CAH_Version_2019.03.27/src/attach_modules.h
new file mode 100644
index 0000000..1dc98a2
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/attach_modulesToTestbench.cpp b/CAH_Version_2019.03.27/src/attach_modulesToTestbench.cpp
new file mode 100644
index 0000000..f296fd4
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/attach_modulesToTestbench.cpp
@@ -0,0 +1,60 @@
+#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) {
+#ifdef PRINT
+ printf(" > CSV-Reader ");
+ setColor(TXTCOLOR_LIGHTCYAN);
+ printf("%s ", csvReaderModule->get_name());
+ setColor(TXTCOLOR_GREY);
+ printf("(id: %03u) ", csvReaderModule->get_id());
+#endif // PRINT
+ if(sensorSlot->set_csvReaderModule(csvReaderModule)) {
+#ifdef PRINT
+ 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());
+#endif // PRINT
+ return true;
+ }
+ else {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTRED);
+ printf("Couldn't attach the CSVreaderModule!\n");
+ setColor(TXTCOLOR_GREY);
+#endif // PRINT
+ }
+ }
+ else {
+#ifdef PRINT
+ 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);
+#endif // PRINT
+ }
+ }
+ else {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTRED);
+ printf(" > Couldn't attach the CSVreaderModule because Testbench, Sensorm or CSVreaderModule is not valid!\n");
+ setColor(TXTCOLOR_GREY);
+#endif // PRINT
+ }
+ return false;
+}
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/attach_modulesToTestbench.h b/CAH_Version_2019.03.27/src/attach_modulesToTestbench.h
new file mode 100644
index 0000000..f4716f1
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/boundary_check.cpp b/CAH_Version_2019.03.27/src/boundary_check.cpp
new file mode 100644
index 0000000..e994273
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/boundary_check.h b/CAH_Version_2019.03.27/src/boundary_check.h
new file mode 100644
index 0000000..5b5fc88
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/clock.cpp b/CAH_Version_2019.03.27/src/clock.cpp
new file mode 100644
index 0000000..43a8c5b
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/clock.cpp
@@ -0,0 +1,21 @@
+#include "clock.h"
+#include <Windows.h>
+#include <stdio.h>
+
+/*
+typedef struct timeval {
+ long tv_sec;
+ long tv_usec;
+} timeval;
+*/
+
+Clock :: Clock() {
+
+}
+
+void Clock :: initiate_clock() {
+ SYSTEMTIME st;
+ GetSystemTime(&st);
+
+ //printf("hour %i\n", st.wHour);
+}
diff --git a/CAH_Version_2019.03.27/src/clock.h b/CAH_Version_2019.03.27/src/clock.h
new file mode 100644
index 0000000..6cf7365
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/create_unit.cpp b/CAH_Version_2019.03.27/src/create_unit.cpp
new file mode 100644
index 0000000..dcbdae7
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/create_unit.cpp
@@ -0,0 +1,427 @@
+#include "create_unit.h"
+#include <stdio.h>
+#include "rlutil.h"
+
+//#define PRINT
+
+using namespace rlutil;
+
+void print_agent(Agent agent) {
+
+}
+
+Agent create_agent() {
+ return create_agent(NO_NAME);
+}
+
+Agent create_agent(char* name) {
+ Agent agent(name);
+#ifdef PRINT
+ 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);
+#endif // PRINT
+ return agent;
+}
+
+
+Sensor create_sensor() {
+ return create_sensor(NO_NAME);
+}
+
+Sensor create_sensor(char* name) {
+ Sensor sensor(name);
+#ifdef PRINT
+ 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);
+#endif
+ 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);
+#ifdef PRINT
+ 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);
+#endif
+ if(historyModule.set_maxHistoryLength(history_length)) {
+#ifdef PRINT
+ printf(" > History length ");
+ setColor(TXTCOLOR_LIGHTGREEN);
+ printf("set ");
+ setColor(TXTCOLOR_GREY);
+ printf("to %u\n", history_length);
+#endif
+ }
+ else {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTRED);
+ printf(" > historyLength could not set (out of allowed range).");
+ setColor(TXTCOLOR_GREY);
+#endif
+ }
+ if(historyModule.set_delimitationMode(delimitation_mode)) {
+#ifdef PRINT
+ printf(" > Delimitation Mode ");
+ setColor(TXTCOLOR_LIGHTGREEN);
+ printf("set ");
+ setColor(TXTCOLOR_GREY);
+ printf("to %u\n", delimitation_mode);
+#endif
+ }
+ else {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTRED);
+ printf(" > Delimitation Mode could not set (out of allowed range).");
+ setColor(TXTCOLOR_GREY);
+#endif
+ }
+
+ 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(name);
+#ifdef PRINT
+ 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);
+#endif
+ if(channel.set_transferRate(transfer_rate)) {
+ if(transfer_rate != 0) {
+#ifdef PRINT
+ printf(" > transfer rate ");
+ setColor(TXTCOLOR_LIGHTGREEN);
+ printf("set ");
+ setColor(TXTCOLOR_GREY);
+ printf("to %i\n", transfer_rate);
+#endif
+ }
+ else {
+#ifdef PRINT
+ printf(" > transfer ");
+ setColor(TXTCOLOR_LIGHTGREEN);
+ printf("set ");
+ setColor(TXTCOLOR_GREY);
+ printf("to immediately transportation\n");
+#endif
+ }
+ }
+ else {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTRED);
+ printf(" > Transfer Rate out of allowed bounds!\n");
+ setColor(TXTCOLOR_GREY);
+#endif
+ }
+ return channel;
+}
+
+
+
+
+Testbench create_testbench() {
+ Testbench testbench;
+#ifdef PRINT
+ printf(" > ");
+ 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);
+#endif
+ return testbench;
+}
+
+Testbench create_testbench(char* name) {
+ Testbench testbench(name);
+#ifdef PRINT
+ 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);
+#endif
+ 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(char* filepath, int mode) {
+
+ FILE* fpointer;
+ bool file_opened;
+
+ if(mode == CSV_MODE_READ) {
+ file_opened = fopen_s(&fpointer, filepath, "r");
+ }
+ else if(mode == CSV_MODE_WRITE) {
+ file_opened = fopen_s(&fpointer, filepath, "w");
+ }
+ else {
+#ifdef PRINT
+ printf("File pointer mode for \"%s\" ", filepath);
+ rlutil::setColor(TXTCOLOR_LIGHTRED);
+ printf("is not supported!\n");
+ rlutil::setColor(TXTCOLOR_GREY);
+#endif
+ return NULL;
+ }
+
+ if(file_opened == 0) {
+ return fpointer;
+ }
+#ifdef PRINT
+ printf("File pointer \"%s\" ", filepath);
+ rlutil::setColor(TXTCOLOR_LIGHTRED);
+ printf("could not created!\n");
+ rlutil::setColor(TXTCOLOR_GREY);
+#endif
+ return NULL;
+}
+
+void print_csv_reader(CSVreaderModule csvReaderModule, char* filepath) {
+#ifdef PRINT
+ 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);
+#endif
+}
+
+CSVreaderModule create_CSVreaderModule(char* filepath, unsigned int column, unsigned int start_row) {
+
+ FILE* fpointer = make_file_pointer(filepath, CSV_MODE_READ);
+
+ if(fpointer) {
+ CSVreaderModule csvr(fpointer, column, start_row);
+ print_csv_reader(csvr, filepath);
+
+ return csvr;
+ }
+ else {
+ CSVreaderModule csvr;
+
+ return csvr;
+ }
+}
+
+CSVreaderModule create_CSVreaderModule(char* name, char* filepath, unsigned int column, unsigned int start_row) {
+
+ FILE* fpointer = make_file_pointer(filepath, CSV_MODE_READ);
+
+ if(fpointer) {
+ CSVreaderModule csvr(name, fpointer, column, start_row);
+ print_csv_reader(csvr, filepath);
+
+ return csvr;
+ }
+ else {
+ CSVreaderModule csvr;
+
+ return csvr;
+ }
+}
+
+
+StateHandler create_stateHandler() {
+ return create_stateHandler(NO_NAME);
+}
+
+StateHandler create_stateHandler(char* name) {
+ StateHandler stateHandler(name);
+ return stateHandler;
+}
diff --git a/CAH_Version_2019.03.27/src/create_unit.h b/CAH_Version_2019.03.27/src/create_unit.h
new file mode 100644
index 0000000..5f4a72f
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/create_unit.h
@@ -0,0 +1,61 @@
+#ifndef CREATE_UNIT_HEADERFILE
+#define CREATE_UNIT_HEADERFILE
+
+#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(char* filepath, unsigned int column, unsigned int start_row);
+CSVreaderModule create_CSVreaderModule(char* name, char* filepath, unsigned int column, unsigned int start_row);
+
+StateHandler create_stateHandler();
+StateHandler create_stateHandler(char* name);
+
+
+#endif
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/csvparser.c b/CAH_Version_2019.03.27/src/csvparser.c
new file mode 100644
index 0000000..6f26bbe
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/csvparser.c
@@ -0,0 +1,239 @@
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <errno.h>
+
+#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/CAH_Version_2019.03.27/src/csvparser.h b/CAH_Version_2019.03.27/src/csvparser.h
new file mode 100644
index 0000000..38ce8b7
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/csvparser.h
@@ -0,0 +1,52 @@
+#ifndef CSVPARSER_H
+#define CSVPARSER_H
+
+#include <stdio.h>
+
+#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/CAH_Version_2019.03.27/src/extremaValues.cpp b/CAH_Version_2019.03.27/src/extremaValues.cpp
new file mode 100644
index 0000000..e69de29
diff --git a/CAH_Version_2019.03.27/src/extremaValues.h b/CAH_Version_2019.03.27/src/extremaValues.h
new file mode 100644
index 0000000..f496826
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/fluidConfig.cpp b/CAH_Version_2019.03.27/src/fluidConfig.cpp
new file mode 100644
index 0000000..daac7b4
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/fluidConfig.cpp
@@ -0,0 +1,208 @@
+#include "fluidConfig.h"
+#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 <stdio.h>
+#include "Testbench.h"
+
+
+
+//#define PRINT
+
+void configAndStartFluid(char* rootPath, char* datasetName, unsigned int datasetLength, int slidingWindowBufferSize, int minNumOfRelatedValuesToBeStable, float thresholdToBeStable, int minNumToBeValidState, float thresholdToBeRelated, unsigned int allowedDisparityTime, float thresholdNotDrift, int sampleRate, char* destPath)
+{
+ char datasetPath[500];
+ //sprintf_s(datasetPath, "%s\\Datasets\\%s.csv", rootPath, datasetName);
+ sprintf_s(datasetPath, "%s\\Datasets\\%s.csv", rootPath, datasetName);
+ unsigned int workingCycle = sampleRate;
+
+
+
+ //printf("anamoly case\n");
+
+ // --- Bearing Defect ---
+ //create agents
+ //printf("Create Agents\n");
+ Agent a_voltage = create_agent("A:Voltage");
+ setWorkingCycleOfAgent(&a_voltage, workingCycle);
+ Agent a_temp1 = create_agent("A:Temp1");
+ setWorkingCycleOfAgent(&a_temp1, workingCycle);
+ Agent a_temp2 = create_agent("A:Temp2");
+ setWorkingCycleOfAgent(&a_temp2, workingCycle);
+ Agent a_sharkyS = create_agent("A:SharkyS");
+ setWorkingCycleOfAgent(&a_sharkyS, workingCycle);
+ Agent a_sharkyB = create_agent("A:SharkyS");
+ setWorkingCycleOfAgent(&a_sharkyB, workingCycle);
+ Agent a_dyna = create_agent("A:Dyna");
+ setWorkingCycleOfAgent(&a_dyna, workingCycle);
+ Agent a_riels = create_agent("A:Riels");
+ setWorkingCycleOfAgent(&a_riels, workingCycle);
+ Agent a_viabilityMonitor = create_agent("ViabilityMonitor");
+ setWorkingCycleOfAgent(&a_viabilityMonitor, workingCycle);
+
+ //create sensors
+ //printf("\nCreate Sensors\n");
+ Sensor s_voltage = create_sensor("S:Voltage");
+ setWorkingCycleOfSensor(&s_voltage, workingCycle);
+ Sensor s_temp1 = create_sensor("S:Temp1");
+ setWorkingCycleOfSensor(&s_temp1, workingCycle);
+ Sensor s_temp2 = create_sensor("S:Temp2");
+ setWorkingCycleOfSensor(&s_temp2, workingCycle);
+ Sensor s_sharkyS = create_sensor("S:SharkyS");
+ setWorkingCycleOfSensor(&s_sharkyS, workingCycle);
+ Sensor s_sharkyB = create_sensor("S:SharkyB");
+ setWorkingCycleOfSensor(&s_sharkyB, workingCycle);
+ Sensor s_dyna = create_sensor("S:Dyna");
+ setWorkingCycleOfSensor(&s_dyna, workingCycle);
+ Sensor s_riels = create_sensor("S:Riels");
+ setWorkingCycleOfSensor(&s_riels, workingCycle);
+
+
+ //create channels for sensors
+ //printf("\nCreate Channels for Sensors\n");
+ Channel c_sa_voltage = create_channel("C:SA:Voltage", 0);
+ Channel c_sa_temp1 = create_channel("C:SA:Temp1", 0);
+ Channel c_sa_temp2 = create_channel("C:SA:Temp2", 0);
+ Channel c_sa_sharkyS = create_channel("C:SA:SharkyS", 0);
+ Channel c_sa_sharkyB = create_channel("C:SA:SharkyB", 0);
+ Channel c_sa_dyna = create_channel("C:SA:Dyna", 0);
+ Channel c_sa_riels = create_channel("C:SA:Riels", 0);
+
+ //create channels for sensors
+ //printf("\nCreate Channels for Agents\n");
+ Channel c_aa_voltage = create_channel("C:AA:Voltage", MAX_BUFFER_LENGTH);
+ Channel c_aa_temp1 = create_channel("C:AA:Temp1", MAX_BUFFER_LENGTH);
+ Channel c_aa_temp2 = create_channel("C:AA:Temp2", MAX_BUFFER_LENGTH);
+ Channel c_aa_sharkyS = create_channel("C:AA:SharkyS", MAX_BUFFER_LENGTH);
+ Channel c_aa_sharkyB = create_channel("C:AA:SharkyB", MAX_BUFFER_LENGTH);
+ Channel c_aa_dyna = create_channel("C:AA:Dyna", MAX_BUFFER_LENGTH);
+ Channel c_aa_riels = create_channel("C:AA:Riels", MAX_BUFFER_LENGTH);
+
+ //mount sensors in agents
+ //printf("\nMount Sensors in Agents\n");
+ mount_sensorInAgent(&a_voltage, &s_voltage, &c_sa_voltage);
+ mount_sensorInAgent(&a_temp1, &s_temp1, &c_sa_temp1);
+ mount_sensorInAgent(&a_temp2, &s_temp2, &c_sa_temp2);
+ mount_sensorInAgent(&a_sharkyS, &s_sharkyS, &c_sa_sharkyS);
+ mount_sensorInAgent(&a_sharkyB, &s_sharkyB, &c_sa_sharkyB);
+ mount_sensorInAgent(&a_dyna, &s_dyna, &c_sa_dyna);
+ mount_sensorInAgent(&a_riels, &s_riels, &c_sa_riels);
+
+ //mount agents in agent(s)
+ //printf("\nMount Agents in Agents\n");
+ mount_agentInAgent(&a_viabilityMonitor, &a_voltage, &c_aa_voltage);
+ mount_agentInAgent(&a_viabilityMonitor, &a_temp1, &c_aa_temp1);
+ mount_agentInAgent(&a_viabilityMonitor, &a_temp2, &c_aa_temp2);
+ mount_agentInAgent(&a_viabilityMonitor, &a_sharkyS, &c_aa_sharkyS);
+ mount_agentInAgent(&a_viabilityMonitor, &a_sharkyB, &c_aa_sharkyB);
+ mount_agentInAgent(&a_viabilityMonitor, &a_dyna, &c_aa_dyna);
+ mount_agentInAgent(&a_viabilityMonitor, &a_riels, &c_aa_riels);
+
+
+ //register agents in agents' stateHandler
+ //printf("\nRegister agents in agents' stateHandler\n");
+ registerSlaveAgentAsInputVariableInStateHandler(&a_viabilityMonitor, &c_aa_voltage);
+ registerSlaveAgentAsOutputVariableInStateHandler(&a_viabilityMonitor, &c_aa_temp1);
+ registerSlaveAgentAsOutputVariableInStateHandler(&a_viabilityMonitor, &c_aa_temp2);
+ registerSlaveAgentAsOutputVariableInStateHandler(&a_viabilityMonitor, &c_aa_sharkyS);
+ registerSlaveAgentAsOutputVariableInStateHandler(&a_viabilityMonitor, &c_aa_sharkyB);
+ registerSlaveAgentAsOutputVariableInStateHandler(&a_viabilityMonitor, &c_aa_dyna);
+ registerSlaveAgentAsOutputVariableInStateHandler(&a_viabilityMonitor, &c_aa_riels);
+
+
+
+
+
+
+ //schirch
+ a_viabilityMonitor.get_stateHandler()->slidingWindowBufferSize = slidingWindowBufferSize;
+ a_viabilityMonitor.get_stateHandler()->minNumOfRelatedValuesToBeStable = minNumOfRelatedValuesToBeStable;
+ a_viabilityMonitor.get_stateHandler()->thresholdToBeStable = thresholdToBeStable;
+ a_viabilityMonitor.get_stateHandler()->minNumToBeValidState = minNumToBeValidState;
+ a_viabilityMonitor.get_stateHandler()->thresholdToBeRelated = thresholdToBeRelated;
+ a_viabilityMonitor.get_stateHandler()->thresholdNotDrift = thresholdNotDrift;
+ a_viabilityMonitor.get_stateHandler()->setCSVwriter(destPath);
+ //sicher so?
+ a_viabilityMonitor.get_slaveAgentHandlerOfAgent()->histLength = slidingWindowBufferSize;
+
+ a_viabilityMonitor.get_stateHandler()->allowedDisparityTime = allowedDisparityTime;
+
+
+
+
+
+ //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;
+
+ //printf("\nCreate CSV Reader Modules\n");
+
+ CSVreaderModule csvr_voltage = create_CSVreaderModule("CSVR:Voltage", datasetPath, 4, ROW);
+ CSVreaderModule csvr_Temp1 = create_CSVreaderModule("CSVR:Temp1", datasetPath, 5, ROW);
+ CSVreaderModule csvr_Temp2 = create_CSVreaderModule("CSVR:Temp2", datasetPath, 6, ROW);
+ CSVreaderModule csvr_sharkyS = create_CSVreaderModule("CSVR:SharkyS", datasetPath, 7, ROW);
+ CSVreaderModule csvr_sharkyB = create_CSVreaderModule("CSVR:SharkyB", datasetPath, 8, ROW);
+ CSVreaderModule csvr_dyna = create_CSVreaderModule("CSVR:Dyna", datasetPath, 9, ROW);
+ CSVreaderModule csvr_riels = create_CSVreaderModule("CSVR:Riels", datasetPath, 10, ROW);
+
+
+ //register agents
+ //printf("\nRegister Agents in Testbench\n");
+ //TODO: "Test Bench" not "Testbench"
+ register_agentInTestbench(&tb, &a_voltage);
+ register_agentInTestbench(&tb, &a_temp1);
+ register_agentInTestbench(&tb, &a_temp2);
+ register_agentInTestbench(&tb, &a_sharkyS);
+ register_agentInTestbench(&tb, &a_sharkyB);
+ register_agentInTestbench(&tb, &a_dyna);
+ register_agentInTestbench(&tb, &a_riels);
+ register_agentInTestbench(&tb, &a_viabilityMonitor);
+
+
+ //register sensors with their csv-readers
+ //printf("\nRegister Sensors in Testbench\n");
+ register_sensorInTestbench(&tb, &s_voltage, &csvr_voltage);
+ register_sensorInTestbench(&tb, &s_temp1, &csvr_Temp1);
+ register_sensorInTestbench(&tb, &s_temp2, &csvr_Temp2);
+ register_sensorInTestbench(&tb, &s_sharkyS, &csvr_sharkyS);
+ register_sensorInTestbench(&tb, &s_sharkyB, &csvr_sharkyB);
+ register_sensorInTestbench(&tb, &s_dyna, &csvr_dyna);
+ register_sensorInTestbench(&tb, &s_riels, &csvr_riels);
+
+ //register sensor channels
+ //printf("\nRegister Channels in Testbench\n");
+ register_channelInTestbench(&tb, &c_sa_voltage);
+ register_channelInTestbench(&tb, &c_sa_temp1);
+ register_channelInTestbench(&tb, &c_sa_temp2);
+ register_channelInTestbench(&tb, &c_sa_sharkyS);
+ register_channelInTestbench(&tb, &c_sa_sharkyB);
+ register_channelInTestbench(&tb, &c_sa_dyna);
+ register_channelInTestbench(&tb, &c_sa_riels);
+
+ register_channelInTestbench(&tb, &c_aa_voltage);
+ register_channelInTestbench(&tb, &c_aa_temp1);
+ register_channelInTestbench(&tb, &c_aa_temp2);
+ register_channelInTestbench(&tb, &c_aa_sharkyS);
+ register_channelInTestbench(&tb, &c_aa_sharkyB);
+ register_channelInTestbench(&tb, &c_aa_dyna);
+ register_channelInTestbench(&tb, &c_aa_riels);
+
+
+ //printf("starten?\n");
+ //getchar();
+
+ tb.simulate(datasetLength);
+
+}
+
+
diff --git a/CAH_Version_2019.03.27/src/fluidConfig.h b/CAH_Version_2019.03.27/src/fluidConfig.h
new file mode 100644
index 0000000..d285396
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/fluidConfig.h
@@ -0,0 +1,8 @@
+#ifndef FLUID_CONFIG
+#define FLUID_CONFIG
+
+
+
+void configAndStartFluid(char* rootPath, char* datasetName, unsigned int datasetLength, int slidingWindowBufferSize, int minNumOfRelatedValuesToBeStable, float thresholdToBeStable, int minNumToBeValidState, float thresholdToBeRelated, unsigned int allowedDisparityTime, float thresholdNotDrift, int sampleRate, char* destPath);
+
+#endif
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/gen_agent_test2.vcxproj b/CAH_Version_2019.03.27/src/gen_agent_test2.vcxproj
new file mode 100644
index 0000000..38460ca
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/gen_agent_test2.vcxproj
@@ -0,0 +1,274 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <ItemGroup Label="ProjectConfigurations">
+ <ProjectConfiguration Include="Debug|Win32">
+ <Configuration>Debug</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Debug|x64">
+ <Configuration>Debug</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release|Win32">
+ <Configuration>Release</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release|x64">
+ <Configuration>Release</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
+ </ItemGroup>
+ <PropertyGroup Label="Globals">
+ <ProjectGuid>{0C0999CA-0E04-4B84-BB4F-98008F98E2CA}</ProjectGuid>
+ <Keyword>Win32Proj</Keyword>
+ <RootNamespace>gen_agent_test2</RootNamespace>
+ <WindowsTargetPlatformVersion>10.0.15063.0</WindowsTargetPlatformVersion>
+ </PropertyGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+ <ConfigurationType>Application</ConfigurationType>
+ <UseDebugLibraries>true</UseDebugLibraries>
+ <PlatformToolset>v141</PlatformToolset>
+ <CharacterSet>Unicode</CharacterSet>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+ <ConfigurationType>Application</ConfigurationType>
+ <UseDebugLibraries>true</UseDebugLibraries>
+ <PlatformToolset>v141</PlatformToolset>
+ <CharacterSet>Unicode</CharacterSet>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+ <ConfigurationType>Application</ConfigurationType>
+ <UseDebugLibraries>false</UseDebugLibraries>
+ <PlatformToolset>v141</PlatformToolset>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ <CharacterSet>Unicode</CharacterSet>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+ <ConfigurationType>Application</ConfigurationType>
+ <UseDebugLibraries>false</UseDebugLibraries>
+ <PlatformToolset>v141</PlatformToolset>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ <CharacterSet>Unicode</CharacterSet>
+ </PropertyGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+ <ImportGroup Label="ExtensionSettings">
+ </ImportGroup>
+ <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <PropertyGroup Label="UserMacros" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+ <LinkIncremental>true</LinkIncremental>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+ <LinkIncremental>true</LinkIncremental>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+ <LinkIncremental>false</LinkIncremental>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+ <LinkIncremental>false</LinkIncremental>
+ </PropertyGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+ <ClCompile>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <WarningLevel>Level3</WarningLevel>
+ <Optimization>Disabled</Optimization>
+ <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ClCompile>
+ <Link>
+ <SubSystem>Console</SubSystem>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+ <ClCompile>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <WarningLevel>Level3</WarningLevel>
+ <Optimization>Disabled</Optimization>
+ <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ClCompile>
+ <Link>
+ <SubSystem>Console</SubSystem>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+ <ClCompile>
+ <WarningLevel>Level3</WarningLevel>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <Optimization>MaxSpeed</Optimization>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <IntrinsicFunctions>true</IntrinsicFunctions>
+ <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ClCompile>
+ <Link>
+ <SubSystem>Console</SubSystem>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <EnableCOMDATFolding>true</EnableCOMDATFolding>
+ <OptimizeReferences>true</OptimizeReferences>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+ <ClCompile>
+ <WarningLevel>Level3</WarningLevel>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <Optimization>MaxSpeed</Optimization>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <IntrinsicFunctions>true</IntrinsicFunctions>
+ <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ClCompile>
+ <Link>
+ <SubSystem>Console</SubSystem>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <EnableCOMDATFolding>true</EnableCOMDATFolding>
+ <OptimizeReferences>true</OptimizeReferences>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemGroup>
+ <ClCompile Include="abstraction_functions.cpp" />
+ <ClCompile Include="AbstractionModule.cpp" />
+ <ClCompile Include="abstraction_interface.cpp" />
+ <ClCompile Include="Agent.cpp" />
+ <ClCompile Include="AgentSlotOfTestbench.cpp" />
+ <ClCompile Include="attach_modules.cpp" />
+ <ClCompile Include="attach_modulesToTestbench.cpp" />
+ <ClCompile Include="AverageValue.cpp" />
+ <ClCompile Include="boundary_check.cpp" />
+ <ClCompile Include="Bunch_Module.cpp" />
+ <ClCompile Include="Channel.cpp" />
+ <ClCompile Include="ChannelSlotOfTestbench.cpp" />
+ <ClCompile Include="clock.cpp" />
+ <ClCompile Include="Continuous_Average.cpp" />
+ <ClCompile Include="create_unit.cpp" />
+ <ClCompile Include="Cross_Confidence_Validator.cpp" />
+ <ClCompile Include="CSVreaderModule.cpp" />
+ <ClCompile Include="CSV_Writer.cpp" />
+ <ClCompile Include="Discrete_Average.cpp" />
+ <ClCompile Include="Evaluation.cpp" />
+ <ClCompile Include="ExtremeValue.cpp" />
+ <ClCompile Include="fluidConfig.cpp" />
+ <ClCompile Include="HandlerOfAgent.cpp" />
+ <ClCompile Include="HistoryEntry.cpp" />
+ <ClCompile Include="HistoryModule.cpp" />
+ <ClCompile Include="inAgentsRegistrations.cpp" />
+ <ClCompile Include="Lookuptable.cpp" />
+ <ClCompile Include="main.cpp" />
+ <ClCompile Include="MasterAgentHandlerOfAgent.cpp" />
+ <ClCompile Include="MasterAgentSlotOfAgent.cpp" />
+ <ClCompile Include="MaximumValue.cpp" />
+ <ClCompile Include="Message.cpp" />
+ <ClCompile Include="MinumumValue.cpp" />
+ <ClCompile Include="Module.cpp" />
+ <ClCompile Include="mount_nodes.cpp" />
+ <ClCompile Include="newMotorConfig.cpp" />
+ <ClCompile Include="Node.cpp" />
+ <ClCompile Include="ConfidenceModule.cpp" />
+ <ClCompile Include="printError.cpp" />
+ <ClCompile Include="Range.cpp" />
+ <ClCompile Include="register_in_testbench.cpp" />
+ <ClCompile Include="relationChecker.cpp" />
+ <ClCompile Include="Sensor.cpp" />
+ <ClCompile Include="SensorHandlerOfAgent.cpp" />
+ <ClCompile Include="SensorSlotOfAgent.cpp" />
+ <ClCompile Include="setupNode.cpp" />
+ <ClCompile Include="setup_lookuptable.cpp" />
+ <ClCompile Include="SlaveAgentHandlerOfAgent.cpp" />
+ <ClCompile Include="SlaveAgentSlotOfAgent.cpp" />
+ <ClCompile Include="Slot.cpp" />
+ <ClCompile Include="SlotOfAgent.cpp" />
+ <ClCompile Include="State.cpp" />
+ <ClCompile Include="StateHandler.cpp" />
+ <ClCompile Include="StateModule.cpp" />
+ <ClCompile Include="StateVariable.cpp" />
+ <ClCompile Include="StatisticValue.cpp" />
+ <ClCompile Include="SubState.cpp" />
+ <ClCompile Include="Testbench.cpp" />
+ <ClCompile Include="SensorSlotOfTestbench.cpp" />
+ <ClCompile Include="Unit.cpp" />
+ <ClCompile Include="user_method_abstraction.cpp" />
+ </ItemGroup>
+ <ItemGroup>
+ <ClInclude Include="abstraction_functions.h" />
+ <ClInclude Include="AbstractionModule.h" />
+ <ClInclude Include="abstraction_interface.h" />
+ <ClInclude Include="Agent.h" />
+ <ClInclude Include="AgentSlotOfTestbench.h" />
+ <ClInclude Include="attach_modules.h" />
+ <ClInclude Include="attach_modulesToTestbench.h" />
+ <ClInclude Include="AverageValue.h" />
+ <ClInclude Include="boundary_check.h" />
+ <ClInclude Include="Bunch_Module.h" />
+ <ClInclude Include="Channel.h" />
+ <ClInclude Include="ChannelSlotOfTestbench.h" />
+ <ClInclude Include="clock.h" />
+ <ClInclude Include="Continuous_Average.h" />
+ <ClInclude Include="create_unit.h" />
+ <ClInclude Include="Cross_Confidence_Validator.h" />
+ <ClInclude Include="CSVreaderModule.h" />
+ <ClInclude Include="CSV_Writer.h" />
+ <ClInclude Include="Discrete_Average.h" />
+ <ClInclude Include="Evaluation.h" />
+ <ClInclude Include="ExtremeValue.h" />
+ <ClInclude Include="fluidConfig.h" />
+ <ClInclude Include="HandlerOfAgent.h" />
+ <ClInclude Include="HistoryEntry.h" />
+ <ClInclude Include="HistoryModule.h" />
+ <ClInclude Include="inAgentsRegistrations.h" />
+ <ClInclude Include="instruction_set_architecture.h" />
+ <ClInclude Include="Lookuptable.h" />
+ <ClInclude Include="MasterAgentHandlerOfAgent.h" />
+ <ClInclude Include="MasterAgentSlotOfAgent.h" />
+ <ClInclude Include="MaximumValue.h" />
+ <ClInclude Include="Message.h" />
+ <ClInclude Include="MinumumValue.h" />
+ <ClInclude Include="Module.h" />
+ <ClInclude Include="mount_nodes.h" />
+ <ClInclude Include="newMotorConfig.h" />
+ <ClInclude Include="Node.h" />
+ <ClInclude Include="ConfidenceModule.h" />
+ <ClInclude Include="printError.h" />
+ <ClInclude Include="project_settings.h" />
+ <ClInclude Include="Range.h" />
+ <ClInclude Include="register_in_testbench.h" />
+ <ClInclude Include="relationChecker.h" />
+ <ClInclude Include="rlutil.h" />
+ <ClInclude Include="Sensor.h" />
+ <ClInclude Include="SensorHandlerOfAgent.h" />
+ <ClInclude Include="SensorSlotOfAgent.h" />
+ <ClInclude Include="settings.h" />
+ <ClInclude Include="setupNode.h" />
+ <ClInclude Include="setup_lookuptable.h" />
+ <ClInclude Include="SlaveAgentHandlerOfAgent.h" />
+ <ClInclude Include="SlaveAgentSlotOfAgent.h" />
+ <ClInclude Include="Slot.h" />
+ <ClInclude Include="SlotOfAgent.h" />
+ <ClInclude Include="State.h" />
+ <ClInclude Include="StateHandler.h" />
+ <ClInclude Include="StateModule.h" />
+ <ClInclude Include="StateVariable.h" />
+ <ClInclude Include="StatisticValue.h" />
+ <ClInclude Include="SubState.h" />
+ <ClInclude Include="Testbench.h" />
+ <ClInclude Include="SensorSlotOfTestbench.h" />
+ <ClInclude Include="Unit.h" />
+ <ClInclude Include="user_method_abstraction.h" />
+ </ItemGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+ <ImportGroup Label="ExtensionTargets">
+ </ImportGroup>
+</Project>
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/gen_agent_test2.vcxproj.filters b/CAH_Version_2019.03.27/src/gen_agent_test2.vcxproj.filters
new file mode 100644
index 0000000..4fb279d
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/gen_agent_test2.vcxproj.filters
@@ -0,0 +1,396 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <ItemGroup>
+ <Filter Include="Source Files">
+ <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
+ <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+ </Filter>
+ <Filter Include="Header Files">
+ <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
+ <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+ </Filter>
+ <Filter Include="Resource Files">
+ <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
+ <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
+ </Filter>
+ </ItemGroup>
+ <ItemGroup>
+ <ClCompile Include="main.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Agent.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Sensor.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Node.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Evaluation.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="boundary_check.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="clock.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Channel.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Testbench.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Unit.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="register_in_testbench.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="create_unit.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="mount_nodes.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="user_method_abstraction.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="abstraction_interface.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="abstraction_functions.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Lookuptable.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Range.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="setup_lookuptable.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Bunch_Module.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="CSV_Writer.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Cross_Confidence_Validator.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Continuous_Average.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Discrete_Average.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Slot.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="printError.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="HistoryModule.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="ConfidenceModule.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="AbstractionModule.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="attach_modules.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="SensorSlotOfTestbench.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="ChannelSlotOfTestbench.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="AgentSlotOfTestbench.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="attach_modulesToTestbench.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="CSVreaderModule.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Module.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="HistoryEntry.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="StateModule.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="State.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="StateHandler.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="SlaveAgentSlotOfAgent.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="SlotOfAgent.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="SensorSlotOfAgent.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="SensorHandlerOfAgent.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="SlaveAgentHandlerOfAgent.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="HandlerOfAgent.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Message.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="MasterAgentHandlerOfAgent.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="MasterAgentSlotOfAgent.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="inAgentsRegistrations.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="AverageValue.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="MinumumValue.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="MaximumValue.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="ExtremeValue.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="StatisticValue.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="SubState.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="StateVariable.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="relationChecker.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="setupNode.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="fluidConfig.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="newMotorConfig.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ </ItemGroup>
+ <ItemGroup>
+ <ClInclude Include="Agent.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="Sensor.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="project_settings.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="Node.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="Evaluation.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="boundary_check.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="clock.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="Channel.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="Testbench.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="Unit.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="rlutil.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="register_in_testbench.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="create_unit.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="mount_nodes.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="user_method_abstraction.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="settings.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="abstraction_interface.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="abstraction_functions.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="Lookuptable.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="Range.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="setup_lookuptable.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="Bunch_Module.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="CSV_Writer.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="Cross_Confidence_Validator.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="instruction_set_architecture.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="Continuous_Average.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="Discrete_Average.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="printError.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="HistoryModule.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="Slot.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="ConfidenceModule.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="AbstractionModule.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="attach_modules.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="SensorSlotOfTestbench.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="ChannelSlotOfTestbench.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="AgentSlotOfTestbench.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="attach_modulesToTestbench.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="CSVreaderModule.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="Module.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="HistoryEntry.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="StateModule.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="State.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="StateHandler.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="SlaveAgentSlotOfAgent.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="SlotOfAgent.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="SensorSlotOfAgent.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="SensorHandlerOfAgent.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="SlaveAgentHandlerOfAgent.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="HandlerOfAgent.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="Message.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="MasterAgentHandlerOfAgent.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="MasterAgentSlotOfAgent.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="inAgentsRegistrations.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="AverageValue.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="MinumumValue.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="MaximumValue.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="ExtremeValue.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="StatisticValue.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="SubState.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="StateVariable.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="relationChecker.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="setupNode.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="fluidConfig.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="newMotorConfig.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ </ItemGroup>
+</Project>
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/gen_agent_test2.vcxproj.user b/CAH_Version_2019.03.27/src/gen_agent_test2.vcxproj.user
new file mode 100644
index 0000000..be25078
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/gen_agent_test2.vcxproj.user
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <PropertyGroup />
+</Project>
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/inAgentsRegistrations.cpp b/CAH_Version_2019.03.27/src/inAgentsRegistrations.cpp
new file mode 100644
index 0000000..db9c534
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/inAgentsRegistrations.cpp
@@ -0,0 +1,104 @@
+#include "inAgentsRegistrations.h"
+#include "rlutil.h"
+
+//#define PRINT
+
+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)){
+#ifdef PRINT
+ 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());
+#endif // PRINT
+ return true;
+ }
+ else {
+#ifdef PRINT
+ 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());
+#endif // PRINT
+ }
+ }
+ else {
+#ifdef PRINT
+ 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());
+#endif // PRINT
+ }
+ }
+ else {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTRED);
+ printf(" > Agent or Channel is not valid\n");
+#endif // PRINT
+ }
+ 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)) {
+#ifdef PRINT
+ 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());
+#endif // PRINT
+ return true;
+ }
+ else {
+#ifdef PRINT
+ 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());
+#endif // PRINT
+ }
+ }
+ else {
+#ifdef PRINT
+ 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());
+#endif // PRINT
+ }
+ }
+ else {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTRED);
+ printf(" > Agent or Channel is not valid\n");
+#endif // PRINT
+ }
+ return false;
+}
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/inAgentsRegistrations.h b/CAH_Version_2019.03.27/src/inAgentsRegistrations.h
new file mode 100644
index 0000000..7b181d3
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/instruction_set_architecture.h b/CAH_Version_2019.03.27/src/instruction_set_architecture.h
new file mode 100644
index 0000000..becbd61
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/main.cpp b/CAH_Version_2019.03.27/src/main.cpp
new file mode 100644
index 0000000..d32c190
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/main.cpp
@@ -0,0 +1,595 @@
+#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 <stdio.h>
+#include "Testbench.h"
+
+
+#include "fluidConfig.h"
+#include "newMotorConfig.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"
+
+int main(int argc, char* argv[])
+{
+ printf("ja?\n");
+
+ if (argc > 12) {
+
+ char rootPath[300];
+ char datasetName[100];
+ char datasetPath[500];
+ unsigned int datasetLength;
+
+ sprintf_s(rootPath, "%s", argv[1]);
+ sprintf_s(datasetName, "%s", argv[2]);
+ sprintf_s(datasetPath, "%s\\Datasets\\%s", rootPath, datasetName);
+ datasetLength = (unsigned int)atoi(argv[3]);
+ int slidingWindowBufferSize = atoi(argv[4]);
+ int minNumOfRelatedValuesToBeStable = atoi(argv[5]);
+ float thresholdToBeStable = atof(argv[6]);
+ int minNumToBeValidState = atoi(argv[7]);
+ float thresholdToBeRelated = atof(argv[8]);
+ unsigned int allowedDisparityTime = (unsigned int)atoi(argv[9]);
+ float thresholdNotDrift = atof(argv[10]);
+ int sampleRate = atoi(argv[11]);
+
+
+ char destPath[600];
+ sprintf_s(destPath, "%s\\output.csv", argv[12]);
+
+
+ bool fluid = false;
+ bool newMotor = false;
+
+ if (argc > 13) {
+ int input = atoi(argv[13]);
+ if (input == 1)
+ fluid = true;
+ else if (input == 2)
+ newMotor = true;
+ }
+
+
+
+
+ //unsigned int workingCycle = 50;
+ unsigned int workingCycle = sampleRate;
+
+
+
+ if (strcmp(datasetName, "Anomaly-bearing_defect-OR_0nm_2") == 0) {
+
+ // --- 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);
+
+
+ //schirch
+ a_viabilityMonitor.get_stateHandler()->slidingWindowBufferSize = slidingWindowBufferSize;
+ a_viabilityMonitor.get_stateHandler()->minNumOfRelatedValuesToBeStable = minNumOfRelatedValuesToBeStable;
+ a_viabilityMonitor.get_stateHandler()->thresholdToBeStable = thresholdToBeStable;
+ a_viabilityMonitor.get_stateHandler()->minNumToBeValidState = minNumToBeValidState;
+ a_viabilityMonitor.get_stateHandler()->thresholdToBeRelated = thresholdToBeRelated;
+ a_viabilityMonitor.get_stateHandler()->thresholdNotDrift = thresholdNotDrift;
+ a_viabilityMonitor.get_stateHandler()->setCSVwriter(destPath);
+ //sicher so?
+ a_viabilityMonitor.get_slaveAgentHandlerOfAgent()->histLength = slidingWindowBufferSize;
+
+
+
+ //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;
+
+
+ //printf("\nCreate CSV Reader Modules\n");
+ char csvPath[600];
+
+ sprintf_s(csvPath, "%s\\statorVoltage_abstracted.csv", datasetPath);
+ CSVreaderModule csvr_statorVoltage = create_CSVreaderModule("Stator Voltage CSV-Reader", csvPath, 2, ROW);
+ sprintf_s(csvPath, "%s\\statorCurrent_abs_fil.csv", datasetPath);
+ CSVreaderModule csvr_statorCurrent_1 = create_CSVreaderModule("Stator Current CSV-Reader", csvPath, 2, ROW);
+ CSVreaderModule csvr_statorCurrent_2 = create_CSVreaderModule("Stator Current CSV-Reader", csvPath, 3, ROW);
+ CSVreaderModule csvr_statorCurrent_3 = create_CSVreaderModule("Stator Current CSV-Reader", csvPath, 4, ROW);
+ sprintf_s(csvPath, "%s\\te_filtered.csv", datasetPath);
+ CSVreaderModule csvr_electromagneticTorque = create_CSVreaderModule("Electromagnetic Torque CSV-Reader", csvPath, 2, ROW);
+ sprintf_s(csvPath, "%s\\vib1_filtered.csv", datasetPath);
+ CSVreaderModule csvr_vibration_1 = create_CSVreaderModule("Mechanical Torque CSV-Reader", csvPath, 2, ROW);
+ sprintf_s(csvPath, "%s\\vib2_filtered.csv", datasetPath);
+ CSVreaderModule csvr_vibration_2 = create_CSVreaderModule("Mechanical Torque CSV-Reader", csvPath, 2, ROW);
+ sprintf_s(csvPath, "%s\\vib3_filtered.csv", datasetPath);
+ CSVreaderModule csvr_vibration_3 = create_CSVreaderModule("Mechanical Torque CSV-Reader", csvPath, 2, ROW);
+
+
+
+ //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);
+
+ //printf("starten...?\n");
+ //getchar();
+
+ tb.simulate(datasetLength);
+ }
+ else if (strcmp(datasetName, "Wear-out") == 0 || strcmp(datasetName, "Normal_operation-Tm0") == 0 || strcmp(datasetName, "Normal_operation-changing_load") == 0) {
+
+ // --- 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);
+
+
+ //schirch
+ a_viabilityMonitor.get_stateHandler()->slidingWindowBufferSize = slidingWindowBufferSize;
+ a_viabilityMonitor.get_stateHandler()->minNumOfRelatedValuesToBeStable = minNumOfRelatedValuesToBeStable;
+ a_viabilityMonitor.get_stateHandler()->thresholdToBeStable = thresholdToBeStable;
+ a_viabilityMonitor.get_stateHandler()->minNumToBeValidState = minNumToBeValidState;
+ a_viabilityMonitor.get_stateHandler()->thresholdToBeRelated = thresholdToBeRelated;
+ a_viabilityMonitor.get_stateHandler()->thresholdNotDrift = thresholdNotDrift;
+ a_viabilityMonitor.get_stateHandler()->setCSVwriter(destPath);
+ //sicher so?
+ a_viabilityMonitor.get_slaveAgentHandlerOfAgent()->histLength = slidingWindowBufferSize;
+
+
+
+
+ //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;
+
+
+ //printf("\nCreate CSV Reader Modules\n");
+ char csvPath[600];
+ sprintf_s(csvPath, "%s\\statorVoltage_abstracted.csv", datasetPath);
+ CSVreaderModule csvr_statorVoltage = create_CSVreaderModule("Stator Voltage CSV-Reader", csvPath, 2, ROW);
+ sprintf_s(csvPath, "%s\\statorCurrent_abs_fil.csv", datasetPath);
+ CSVreaderModule csvr_statorCurrent = create_CSVreaderModule("Stator Current CSV-Reader", csvPath, 2, ROW);
+ sprintf_s(csvPath, "%s\\speed_filtered.csv", datasetPath);
+ CSVreaderModule csvr_speed = create_CSVreaderModule("Speed CSV-Reader", csvPath, 2, ROW);
+ sprintf_s(csvPath, "%s\\te_filtered.csv", datasetPath);
+ CSVreaderModule csvr_electromagneticTorque = create_CSVreaderModule("Electromagnetic Torque CSV-Reader", csvPath, 2, ROW);
+ sprintf_s(csvPath, "%s\\mechanicalTorque.csv", datasetPath);
+ CSVreaderModule csvr_mechanicalTorque = create_CSVreaderModule("Mechanical Torque CSV-Reader", csvPath, 2, ROW);
+
+
+ //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);
+
+ //printf("starten...?\n");
+ //getchar();
+
+ tb.simulate(datasetLength); //bearingDefect
+
+ }
+ else if (strcmp(datasetName, "Change_of_speed") == 0) {
+
+ // --- 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);
+
+
+ //schirch
+ a_viabilityMonitor.get_stateHandler()->slidingWindowBufferSize = slidingWindowBufferSize;
+ a_viabilityMonitor.get_stateHandler()->minNumOfRelatedValuesToBeStable = minNumOfRelatedValuesToBeStable;
+ a_viabilityMonitor.get_stateHandler()->thresholdToBeStable = thresholdToBeStable;
+ a_viabilityMonitor.get_stateHandler()->minNumToBeValidState = minNumToBeValidState;
+ a_viabilityMonitor.get_stateHandler()->thresholdToBeRelated = thresholdToBeRelated;
+ a_viabilityMonitor.get_stateHandler()->thresholdNotDrift = thresholdNotDrift;
+ a_viabilityMonitor.get_stateHandler()->setCSVwriter(destPath);
+ //sicher so?
+ a_viabilityMonitor.get_slaveAgentHandlerOfAgent()->histLength = slidingWindowBufferSize;
+
+
+
+
+ //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;
+
+
+
+ //printf("\nCreate CSV Reader Modules\n");
+ char csvPath[600];
+ sprintf_s(csvPath, "%s\\statorVoltage_abs_fil.csv", datasetPath);
+ CSVreaderModule csvr_statorVoltage = create_CSVreaderModule("Stator Voltage CSV-Reader", csvPath, 2, ROW);
+ sprintf_s(csvPath, "%s\\statorCurrent_abs_fil.csv", datasetPath);
+ CSVreaderModule csvr_statorCurrent = create_CSVreaderModule("Stator Current CSV-Reader", csvPath, 2, ROW);
+ sprintf_s(csvPath, "%s\\speed_filtered.csv", datasetPath);
+ CSVreaderModule csvr_speed = create_CSVreaderModule("Speed CSV-Reader", csvPath, 2, ROW);
+ sprintf_s(csvPath, "%s\\te_filtered.csv", datasetPath);
+ CSVreaderModule csvr_electromagneticTorque = create_CSVreaderModule("Electromagnetic Torque CSV-Reader", csvPath, 2, ROW);
+ sprintf_s(csvPath, "%s\\mechanicalTorque.csv", datasetPath);
+ CSVreaderModule csvr_mechanicalTorque = create_CSVreaderModule("Mechanical Torque CSV-Reader", csvPath, 2, ROW);
+ sprintf_s(csvPath, "%s\\frequency.csv", datasetPath);
+ CSVreaderModule csvr_frequency = create_CSVreaderModule("Mechanical Torque CSV-Reader", csvPath, 2, ROW);
+
+
+
+
+
+
+
+ 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);
+
+ //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);
+
+ //printf("starten...?\n");
+ //getchar();
+
+ tb.simulate(datasetLength); //bearingDefect
+
+ }
+ else if (fluid == true) {
+ configAndStartFluid(rootPath, datasetName, datasetLength, slidingWindowBufferSize, minNumOfRelatedValuesToBeStable, thresholdToBeStable, minNumToBeValidState, thresholdToBeRelated, allowedDisparityTime, thresholdNotDrift, sampleRate, destPath);
+ }
+ else if (newMotor == true) {
+ configAndStartNewMotor(rootPath, datasetName, datasetLength, slidingWindowBufferSize, minNumOfRelatedValuesToBeStable, thresholdToBeStable, minNumToBeValidState, thresholdToBeRelated, allowedDisparityTime, thresholdNotDrift, sampleRate, destPath);
+ }
+ else {
+ printf("SOMETHING WENT WRONG (1)\n");
+ printf("datasetName: %s\n\n", datasetName);
+ }
+ }
+ else {
+ printf("Arguments wrong! ");
+
+ printf("Nr: %i\n", argc);
+ }
+}
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/mount_nodes.cpp b/CAH_Version_2019.03.27/src/mount_nodes.cpp
new file mode 100644
index 0000000..ccc8f74
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/mount_nodes.cpp
@@ -0,0 +1,408 @@
+#include "attach_modules.h"
+#include "mount_nodes.h"
+#include "rlutil.h"
+#include <stdio.h>
+
+//#define PRINT
+
+using namespace rlutil;
+
+bool mount_sensorInAgent(Agent* agent, Sensor* sensor, Channel* channel) {
+ if(agent != NULL && sensor != NULL && channel != NULL) {
+#ifdef PRINT
+ printf(" > Sensor ");
+ setColor(TXTCOLOR_LIGHTCYAN);
+ printf("%s ", sensor->get_name());
+ setColor(TXTCOLOR_GREY);
+ printf("(id: %03u) ", sensor->get_id());
+#endif // PRINT
+ if(agent->get_sensorHandlerOfAgent()->mount_sensorIntoSensorSlot(channel) && sensor->mount_agent(channel)) {
+#ifdef PRINT
+ 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());
+#endif // PRINT
+ return true;
+ }
+ else {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTRED);
+ printf("couldn't be mounted in %s (id: %03u)\n", agent->get_name(), agent->get_id());
+ setColor(TXTCOLOR_GREY);
+#endif // PRINT
+ }
+ }
+ else {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTRED);
+ printf(" > Agent, Sensor, or Channel is not valid\n");
+ setColor(TXTCOLOR_GREY);
+#endif
+ }
+ 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 {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTRED);
+ printf("Agent, Sensor, Channel, or HistoryModule is not valid\n");
+ setColor(TXTCOLOR_GREY);
+#endif
+ }
+ 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)) {
+#ifdef PRINT
+ 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());
+#endif
+ return true;
+ }
+ else {
+#ifdef PRINT
+ 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);
+#endif
+ masteragent->get_slaveAgentHandlerOfAgent()->demount_slaveAgentIntoSlaveAgentSlot(channel);
+ }
+ }
+ }
+ else {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTRED);
+ printf(" > One of the Agents or Channel not valid\n");
+ setColor(TXTCOLOR_GREY);
+#endif
+ }
+ 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/CAH_Version_2019.03.27/src/mount_nodes.h b/CAH_Version_2019.03.27/src/mount_nodes.h
new file mode 100644
index 0000000..80f93a5
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/newMotorConfig.cpp b/CAH_Version_2019.03.27/src/newMotorConfig.cpp
new file mode 100644
index 0000000..83291d6
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/newMotorConfig.cpp
@@ -0,0 +1,192 @@
+#include "fluidConfig.h"
+#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 <stdio.h>
+#include "Testbench.h"
+
+
+
+//#define PRINT
+
+void configAndStartNewMotor(char* rootPath, char* datasetName, unsigned int datasetLength, int slidingWindowBufferSize, int minNumOfRelatedValuesToBeStable, float thresholdToBeStable, int minNumToBeValidState, float thresholdToBeRelated, unsigned int allowedDisparityTime, float thresholdNotDrift, int sampleRate, char* destPath)
+{
+ char datasetPath[500];
+ //sprintf_s(datasetPath, "%s\\Datasets\\%s.csv", rootPath, datasetName);
+ sprintf_s(datasetPath, "%s\\Datasets\\%s.csv", rootPath, datasetName);
+ unsigned int workingCycle = sampleRate;
+
+
+ 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);
+
+
+ //schirch
+ a_viabilityMonitor.get_stateHandler()->slidingWindowBufferSize = slidingWindowBufferSize;
+ a_viabilityMonitor.get_stateHandler()->minNumOfRelatedValuesToBeStable = minNumOfRelatedValuesToBeStable;
+ a_viabilityMonitor.get_stateHandler()->thresholdToBeStable = thresholdToBeStable;
+ a_viabilityMonitor.get_stateHandler()->minNumToBeValidState = minNumToBeValidState;
+ a_viabilityMonitor.get_stateHandler()->thresholdToBeRelated = thresholdToBeRelated;
+ a_viabilityMonitor.get_stateHandler()->thresholdNotDrift = thresholdNotDrift;
+ a_viabilityMonitor.get_stateHandler()->setCSVwriter(destPath);
+ //sicher so?
+ a_viabilityMonitor.get_slaveAgentHandlerOfAgent()->histLength = slidingWindowBufferSize;
+
+
+
+
+ //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;
+
+
+
+ //printf("\nCreate CSV Reader Modules\n");
+ //char csvPath[600];
+ //sprintf_s(csvPath, "%s\\statorVoltage_abs_fil.csv", datasetPath);
+ CSVreaderModule csvr_statorVoltage = create_CSVreaderModule("Stator Voltage CSV-Reader", datasetPath, 3, ROW);
+ //sprintf_s(csvPath, "%s\\statorCurrent_abs_fil.csv", datasetPath);
+ CSVreaderModule csvr_statorCurrent = create_CSVreaderModule("Stator Current CSV-Reader", datasetPath, 8, ROW);
+ //sprintf_s(csvPath, "%s\\speed_filtered.csv", datasetPath);
+ CSVreaderModule csvr_speed = create_CSVreaderModule("Speed CSV-Reader", datasetPath, 12, ROW);
+ //sprintf_s(csvPath, "%s\\te_filtered.csv", datasetPath);
+ CSVreaderModule csvr_electromagneticTorque = create_CSVreaderModule("Electromagnetic Torque CSV-Reader", datasetPath, 11, ROW);
+ //sprintf_s(csvPath, "%s\\mechanicalTorque.csv", datasetPath);
+ CSVreaderModule csvr_mechanicalTorque = create_CSVreaderModule("Mechanical Torque CSV-Reader", datasetPath, 7, ROW);
+ //sprintf_s(csvPath, "%s\\frequency.csv", datasetPath);
+ CSVreaderModule csvr_frequency = create_CSVreaderModule("Frequency CSV-Reader", datasetPath, 6, ROW);
+
+
+
+
+
+
+
+ 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);
+
+ //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);
+
+ //printf("starten...?\n");
+ //getchar();
+
+ tb.simulate(datasetLength); //bearingDefect
+
+}
+
+
diff --git a/CAH_Version_2019.03.27/src/newMotorConfig.h b/CAH_Version_2019.03.27/src/newMotorConfig.h
new file mode 100644
index 0000000..2284b26
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/newMotorConfig.h
@@ -0,0 +1,8 @@
+#ifndef NEWMOTOR_CONFIG
+#define NEWMOTOR_CONFIG
+
+
+
+void configAndStartNewMotor(char* rootPath, char* datasetName, unsigned int datasetLength, int slidingWindowBufferSize, int minNumOfRelatedValuesToBeStable, float thresholdToBeStable, int minNumToBeValidState, float thresholdToBeRelated, unsigned int allowedDisparityTime, float thresholdNotDrift, int sampleRate, char* destPath);
+
+#endif
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/printError.cpp b/CAH_Version_2019.03.27/src/printError.cpp
new file mode 100644
index 0000000..85f8f2b
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/printError.cpp
@@ -0,0 +1,16 @@
+#include <stdio.h>
+#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/CAH_Version_2019.03.27/src/printError.h b/CAH_Version_2019.03.27/src/printError.h
new file mode 100644
index 0000000..03da966
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/project_settings.h b/CAH_Version_2019.03.27/src/project_settings.h
new file mode 100644
index 0000000..3a5d949
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/register_in_testbench.cpp b/CAH_Version_2019.03.27/src/register_in_testbench.cpp
new file mode 100644
index 0000000..40a7b85
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/register_in_testbench.cpp
@@ -0,0 +1,130 @@
+#include "register_in_testbench.h"
+
+#include "attach_modulesToTestbench.h"
+#include "rlutil.h"
+#include <stdio.h>
+
+//#define PRINT
+
+using namespace rlutil;
+
+bool register_agentInTestbench(Testbench *tb, Agent *agent) {
+ if(tb != NULL && agent != NULL) {
+#ifdef PRINT
+ printf(" > Agent ");
+ setColor(TXTCOLOR_LIGHTCYAN);
+ printf("%s ", agent->get_name());
+ setColor(TXTCOLOR_GREY);
+ printf("(id: %03u) ", agent->get_id());
+#endif // PRINT
+ if(tb->register_agent(agent)) {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTGREEN);
+ printf("registered ");
+ setColor(TXTCOLOR_GREY);
+ printf("in Testbench ");
+ setColor(TXTCOLOR_LIGHTCYAN);
+ printf("%s\n", tb->get_name());
+ setColor(TXTCOLOR_GREY);
+#endif // PRINT
+ return true;
+ }
+ else {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTRED);
+ printf("couldn't be registered in %s", tb->get_name());
+#endif // PRINT
+ }
+ }
+ else {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTRED);
+ printf(" > Testbench or Agent is not valid\n");
+#endif // PRINT
+ }
+ setColor(TXTCOLOR_GREY);
+ return false;
+}
+
+bool register_sensorInTestbench(Testbench *tb, Sensor *sensor) {
+ if(tb != NULL && sensor != NULL) {
+#ifdef PRINT
+ printf(" > Sensor ");
+ setColor(TXTCOLOR_LIGHTCYAN);
+ printf("%s ", sensor->get_name());
+ setColor(TXTCOLOR_GREY);
+ printf("(id: %03u) ", sensor->get_id());
+#endif // PRINT
+ if(tb->register_sensor(sensor)) {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTGREEN);
+ printf("registered ");
+ setColor(TXTCOLOR_GREY);
+ printf("in ");
+ setColor(TXTCOLOR_LIGHTCYAN);
+ printf("%s\n", tb->get_name());
+ setColor(TXTCOLOR_GREY);
+#endif // PRINT
+ return true;
+ }
+ else {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTRED);
+ printf("couldn't be registered in %s\n", tb->get_name());
+#endif // PRINT
+ }
+ }
+ else {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTRED);
+ printf(" > Testbench or sensor is not valid\n");
+#endif // PRINT
+ }
+ 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 {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTRED);
+ printf("Testbench or sensor is not valid\n");
+#endif // PRINT
+ }
+ setColor(TXTCOLOR_GREY);
+ return false;
+}
+
+bool register_channelInTestbench(Testbench *tb, Channel *channel) {
+#ifdef PRINT
+ printf(" > Channel ");
+ setColor(TXTCOLOR_LIGHTCYAN);
+ printf("%s ", channel->get_name());
+ setColor(TXTCOLOR_GREY);
+ printf("(id: %03u) ", channel->get_id());
+#endif // PRINT
+ if(tb->register_channel(channel)){
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTGREEN);
+ printf("registered ");
+ setColor(TXTCOLOR_GREY);
+ printf("in Testbench ");
+ setColor(TXTCOLOR_LIGHTCYAN);
+ printf("%s\n", tb->get_name());
+#endif // PRINT
+ }
+ else {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTRED);
+ printf("couldn't be registered in %s\n", tb->get_name());
+#endif // PRINT
+ }
+ setColor(TXTCOLOR_GREY);
+
+ return false;
+}
diff --git a/CAH_Version_2019.03.27/src/register_in_testbench.h b/CAH_Version_2019.03.27/src/register_in_testbench.h
new file mode 100644
index 0000000..b36f41e
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/relationChecker.cpp b/CAH_Version_2019.03.27/src/relationChecker.cpp
new file mode 100644
index 0000000..281d632
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/relationChecker.cpp
@@ -0,0 +1,63 @@
+#include "relationChecker.h"
+
+#include <stdio.h>
+
+
+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 valueIsRelatedToReferenceValueCanberra(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 (referenceValue < 0)
+ referenceValue = referenceValue * (-1);
+ if (value < 0)
+ value = value * (-1);
+
+ if (diff == 0 || ((diff / (referenceValue + value)) <= 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);
+}
diff --git a/CAH_Version_2019.03.27/src/relationChecker.h b/CAH_Version_2019.03.27/src/relationChecker.h
new file mode 100644
index 0000000..ada8fa4
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/relationChecker.h
@@ -0,0 +1,11 @@
+#ifndef RELATIONCHECKER_HEADERFILE
+#define RELATIONCHECKER_HEADERFILE
+
+bool valueIsRelatedToReferenceValue(float referenceValue, float value, float threshold);
+bool valueIsRelatedToReferenceValueOrBetweenMinAndMax(float referenceValue, float minimumValue, float maximumValue, float value, float threshold);
+
+//bool valueIsRelatedToReferenceValueCanberra(float referenceValue, float value, float threshold);
+
+
+
+#endif
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/rlutil.h b/CAH_Version_2019.03.27/src/rlutil.h
new file mode 100644
index 0000000..f19baf6
--- /dev/null
+++ b/CAH_Version_2019.03.27/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 <License>
+ */
+
+//#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 <iostream>
+ #include <string>
+ #include <cstdio> // 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 <stdio.h> // for getch() / printf()
+ #include <string.h> // for strlen()
+ RLUTIL_INLINE void locate(int x, int y); // Forward declare for C to avoid warnings
+#endif // __cplusplus
+
+#ifdef _WIN32
+ #include <windows.h> // for WinAPI and Sleep()
+ #define _NO_OLDNAMES // for MinGW compatibility
+ #include <conio.h> // for getch() and kbhit()
+ #define getch _getch
+ #define kbhit _kbhit
+#else
+ #include <termios.h> // for getch() and kbhit()
+ #include <unistd.h> // for getch(), kbhit() and (u)sleep()
+ #include <sys/ioctl.h> // for getkey()
+ #include <sys/types.h> // for kbhit()
+ #include <sys/time.h> // 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.locate>.
+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 <getch>, <kbhit> and <gotoxy> 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 <Key codes for keyhit()>
+///
+/// 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 <Color Codes>
+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 <Color Codes>
+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 <Color Codes>
+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 <Color Codes>
+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 <Color Codes>
+/// See <resetColor>
+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 <Color Codes>
+/// See <setColor>
+/// See <saveDefaultColor>
+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 <class T> 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 <rlutil.hidecursor>.
+/// 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/CAH_Version_2019.03.27/src/settings.h b/CAH_Version_2019.03.27/src/settings.h
new file mode 100644
index 0000000..e69de29
diff --git a/CAH_Version_2019.03.27/src/setupNode.cpp b/CAH_Version_2019.03.27/src/setupNode.cpp
new file mode 100644
index 0000000..508dc0b
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/setupNode.cpp
@@ -0,0 +1,53 @@
+#include "setupNode.h"
+
+#include "rlutil.h"
+
+//#define PRINT
+
+using namespace rlutil;
+
+void setWorkingCycleOfSensor(Sensor* sensor, unsigned int workingCycle) {
+ if (sensor->set_workingCycle(workingCycle)) {
+#ifdef PRINT
+ 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);
+#endif // PRINT
+ }
+ else {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTRED);
+ printf(" > Couldn't set WorkingCycle of Sensor %s (id: %03u)\n", sensor->get_name(), sensor->get_id());
+ setColor(TXTCOLOR_GREY);
+#endif // PRINT
+ }
+}
+
+void setWorkingCycleOfAgent(Agent* agent, unsigned int workingCycle) {
+ if (agent->set_workingCycle(workingCycle)) {
+#ifdef PRINT
+ 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);
+#endif // PRINT
+ }
+ else {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTRED);
+ printf(" > Couldn't set WorkingCycle of Sensor %s (id: %03u)\n", agent->get_name(), agent->get_id());
+ setColor(TXTCOLOR_GREY);
+#endif // PRINT
+ }
+}
\ No newline at end of file
diff --git a/CAH_Version_2019.03.27/src/setupNode.h b/CAH_Version_2019.03.27/src/setupNode.h
new file mode 100644
index 0000000..2df067d
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/setup_agent.cpp b/CAH_Version_2019.03.27/src/setup_agent.cpp
new file mode 100644
index 0000000..13f01f4
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/setup_agent.cpp
@@ -0,0 +1,13 @@
+#include "setup_agent.h"
+
+#include <stdio.h>
+
+//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/CAH_Version_2019.03.27/src/setup_agent.h b/CAH_Version_2019.03.27/src/setup_agent.h
new file mode 100644
index 0000000..3888cbb
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/setup_lookuptable.cpp b/CAH_Version_2019.03.27/src/setup_lookuptable.cpp
new file mode 100644
index 0000000..19c816a
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/setup_lookuptable.cpp
@@ -0,0 +1,52 @@
+#include "setup_lookuptable.h"
+#include <stdio.h>
+#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/CAH_Version_2019.03.27/src/setup_lookuptable.h b/CAH_Version_2019.03.27/src/setup_lookuptable.h
new file mode 100644
index 0000000..c457db1
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/user_method_abstraction.cpp b/CAH_Version_2019.03.27/src/user_method_abstraction.cpp
new file mode 100644
index 0000000..dcb30e5
--- /dev/null
+++ b/CAH_Version_2019.03.27/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/CAH_Version_2019.03.27/src/user_method_abstraction.h b/CAH_Version_2019.03.27/src/user_method_abstraction.h
new file mode 100644
index 0000000..6826a78
--- /dev/null
+++ b/CAH_Version_2019.03.27/src/user_method_abstraction.h
@@ -0,0 +1 @@
+void br_abstraction(float input, int* output);
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/AbstractionModule.cpp b/SA-EWS_Version_2019.03.27/src/AbstractionModule.cpp
new file mode 100644
index 0000000..14e2876
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/AbstractionModule.cpp
@@ -0,0 +1,198 @@
+#include "AbstractionModule.h"
+#include "abstraction_interface.h"
+
+#include <stdio.h>
+
+
+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_ix<MAX_NUM_OF_LOOKUPTABLES; lut_ix++) {
+ flag_lookuptable_exist[lut_ix] = false;
+ }
+
+ if(lut != NULL) {
+ list_lookuptables[num_of_lookuptables] = lut;
+ flag_lookuptable_exist[num_of_lookuptables] = true;
+ lookuptable_to_use = num_of_lookuptables;
+ num_of_lookuptables++;
+ }
+}
+
+AbstractionModule :: AbstractionModule(Lookuptable* lut, unsigned int abstraction_method) {
+ setName(NO_NAME);
+ initialize_abstraction(lut, abstraction_method);
+}
+
+AbstractionModule :: AbstractionModule(char* name, Lookuptable* lut, unsigned int abstraction_method) {
+ setName(name);
+ initialize_abstraction(lut, abstraction_method);
+}
+
+bool AbstractionModule :: set_abstraction_method(unsigned int abstraction_strategy) {
+ if(abstraction_strategy < NUM_OF_ABSTRACTIONS) {
+ this->abstraction_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<MAX_NUM_OF_INPUT_VALUES; pos++) {
+
+
+
+
+ }
+
+
+
+ }
+
+ return false;
+}
+*/
+
+
+
+
+
+
+
+
+bool AbstractionModule :: abstract_via_lookuptables_and_condition_variable() {
+
+
+ return true;
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/AbstractionModule.h b/SA-EWS_Version_2019.03.27/src/AbstractionModule.h
new file mode 100644
index 0000000..1112332
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/AbstractionModule.h
@@ -0,0 +1,92 @@
+#ifndef ABSTRACTION_HEADERFILE
+#define ABSTRACTION_HEADERFILE
+
+#include "Lookuptable.h"
+
+
+
+#define MAX_NUM_OF_INPUT_VALUES 10
+#define MAX_NUM_OF_SCORES 10
+
+
+//abstraction methods
+#define NUM_OF_ABSTRACTIONS 2
+#define ABSTRACTION_METHOD_NOT_SPECIFIED 0
+#define ABSTRACTION_LOOKUPTABLE 1
+
+
+#define MAX_NUM_OF_LOOKUPTABLES 5
+
+class AbstractionModule : public Unit {
+//class AbstractionModule : public Module {
+
+ private:
+ unsigned int abstraction_method;
+
+ unsigned int num_of_lookuptables;
+ Lookuptable* list_lookuptables[MAX_NUM_OF_LOOKUPTABLES];
+ bool flag_lookuptable_exist[MAX_NUM_OF_LOOKUPTABLES];
+
+ unsigned int lookuptable_to_use;
+
+
+
+
+ //TODO: lut factor
+
+ //private functions
+ void initialize_abstraction(Lookuptable* lut, unsigned int abstraction_method);
+
+ bool abstract_via_lookuptable(float input, int* output);
+ bool abstract_via_factorized_lookuptable_and_condition_variable();
+ bool abstract_via_lookuptables_and_condition_variable();
+
+
+
+
+ //unsigned int num_of_slaveagents;
+ //unsigned int num_of_sensors;
+
+ /*
+ int abstracted_data;
+ bool flag_input_data_float_is_in_use[MAX_NUM_OF_INPUT_VALUES];
+ float input_data_float[MAX_NUM_OF_INPUT_VALUES];
+ */
+
+ /*
+ bool flag_input_data_int_is_in_use[MAX_NUM_OF_INPUT_VALUES];
+ int input_data_int[MAX_NUM_OF_INPUT_VALUES];
+ */
+
+ public:
+ AbstractionModule(Lookuptable* lut, unsigned int abstraction_method);
+ AbstractionModule(char* name, Lookuptable* lut, unsigned int abstraction_method);
+
+ bool set_abstraction_method(unsigned int abstraction_method);
+ unsigned int get_abstraction_method();
+
+ //TODO irgendwie muss man wissen an welcher position das is .. geht also im moment nur mit einer lookupttable
+ bool add_lookuptable(Lookuptable* lut);
+ bool get_flag_lookuptable_exist(unsigned int position);
+ Lookuptable* get_lookuptable(unsigned int position);
+
+ /*
+ void set_num_of_slaveagents(unsigned int num_of_slaveagents);
+ unsigned int get_num_of_slaveagents();
+
+ void set_num_of_sensors(unsigned int num_of_sensors);
+ unsigned int get_num_of_sensors();
+ */
+ /*
+ bool set_input_parameter(unsigned int position, int input_parameter);
+ bool set_input_parameter(unsigned int position, float input_parameter);
+ bool get_input_parameter(unsigned int position, int* input_parameter);
+ bool get_input_parameter(unsigned int position, float* input_parameter);
+ */
+
+ bool abstract(float input, int* output);
+
+ //bool 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);
+};
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/Agent.cpp b/SA-EWS_Version_2019.03.27/src/Agent.cpp
new file mode 100644
index 0000000..a017d62
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/Agent.cpp
@@ -0,0 +1,1329 @@
+#include "Agent.h"
+#include "printError.h"
+#include <stdio.h>
+
+
+//TODO: Move this include to ControlModule
+#include "instruction_set_architecture.h"
+
+#include "ScoreAndConfidence.h"
+#include <iostream>
+#include <algorithm>
+
+/*
+#include "Evaluation.h"
+#include "instruction_set_architecture.h"
+*/
+
+//#define PRINT_READING
+
+//#define PRINT
+
+#define MORE_INFO_IN_CSV
+
+#define MULTIPLICATION 0
+#define CONJUNCTION 1
+#define AVERAGE 2
+#define MULTIPLICATION_THEORETICAL 3
+#define CONJUNCTION_THEORETICAL 4
+#define AVERAGE_THEORETICAL 5
+
+
+
+#define MAX_SIZE_POSSCOREHIST 20
+
+
+
+//SHORTCUT/WORKAUROUND -> TODO: make this better!
+#define HR (unsigned int)16
+#define RR (unsigned int)17
+#define BP (unsigned int)18
+#define SPO2 (unsigned int)19
+#define BTEMP (unsigned int)20
+
+#define AGENT1 slaveAgent->get_comPort()->getId()
+#define AGENT2 slaveAgent2->get_comPort()->getId()
+
+
+void Agent :: init_agent() {
+ sensorHandlerOfAgent = NULL;
+ slaveAgentHandlerOfAgent = NULL;
+ masterAgentHandlerOfAgent = NULL;
+
+ stateHandler = NULL;
+
+ historyController = NULL;
+ stabilityController = NULL;
+
+ workingCycleCounter = 0;
+
+
+ //SHORTCUT/WORKAUROUND -> TODO: make this better!
+ abstractionModule = NULL;
+ reliabilityModule = NULL;
+
+ lastScore = NULL;
+ timeSinceChange = 0;
+
+}
+
+Agent::Agent() {
+ setName(NO_NAME);
+ init_agent();
+}
+
+Agent :: Agent(string name) : Node(name) {
+ setName(name);
+ init_agent();
+
+ csvWriter = NULL;
+
+ /*
+ //5 -> HR
+ //6 -> RR
+ //7 -> BP
+ //8 -> SPO2
+ //9 -> BTemp
+ if (id >= 5 && id <= 9) {
+ switch (id) {
+ case 5: csvWriter = new CSV_Writer("C:\\csv-data\\output_HR.csv"); break;
+ case 6: csvWriter = new CSV_Writer("C:\\csv-data\\output_RR.csv"); break;
+ case 7: csvWriter = new CSV_Writer("C:\\csv-data\\output_BP.csv"); break;
+ case 8: csvWriter = new CSV_Writer("C:\\csv-data\\output_SPO2.csv"); break;
+ case 9: csvWriter = new CSV_Writer("C:\\csv-data\\output_BTemp.csv"); break;
+ default: printf("FEHLER\n");
+ getchar();
+ return;
+ }
+
+ csvWriter->write_field("Input Value");
+ csvWriter->make_new_field();
+ csvWriter->write_field("Reliability IN");
+ csvWriter->make_new_field();
+ csvWriter->write_field("Score");
+ csvWriter->make_new_field();
+ csvWriter->write_field("Confidence");
+ csvWriter->make_new_field();
+ csvWriter->write_field("Reliability OUT");
+ csvWriter->make_new_line();
+ }
+
+
+
+
+ if (id == 10) {
+ csvWriter = new CSV_Writer("C:\\csv-data\\output_EWS.csv");
+ csvWriter->write_field("ews1");
+ csvWriter->make_new_field();
+ csvWriter->write_field("reliability");
+ csvWriter->make_new_field();
+ csvWriter->write_field("ews2");
+ csvWriter->make_new_field();
+ csvWriter->write_field("reliability");
+ csvWriter->make_new_line();
+ }
+ */
+
+}
+
+Agent::~Agent(){
+ //TODO: deallocate memory
+}
+
+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;
+}
+
+
+
+bool Agent::setHistoryController() {
+ if (historyController == NULL) {
+ historyController = new HistoryController();
+ return true;
+ }
+ return false;
+}
+
+bool Agent::setHistoryController(HistoryController* historyController) {
+ if (this->historyController && !historyController) {
+ this->historyController = historyController;
+ return true;
+ }
+ return false;
+}
+
+bool Agent::delHistoryController() {
+ if (!historyController) {
+ delete historyController;
+ historyController = NULL;
+ return true;
+ }
+ return false;
+}
+
+HistoryController* Agent::getHistoryController() {
+ if (!historyController) {
+ setHistoryController();
+ }
+ return historyController;
+}
+
+
+
+bool Agent::setStabilityController() {
+ if (stabilityController == NULL) {
+ stabilityController = new StabilityController();
+ return true;
+ }
+ return false;
+}
+
+bool Agent::setStabilityController(StabilityController* stabilityController) {
+ if (this->stabilityController == NULL && stabilityController != NULL) {
+ this->stabilityController = stabilityController;
+ return true;
+ }
+ return false;
+}
+
+bool Agent::delStabilityController() {
+ if (stabilityController != NULL) {
+ delete stabilityController;
+ stabilityController = NULL;
+ return true;
+ }
+ return false;
+}
+
+StabilityController* Agent::getStabilityController() {
+ if (!stabilityController) {
+ setStabilityController();
+ }
+ return stabilityController;
+}
+
+
+//TODO: maybe inline function?
+float absoluteValue(float value1, float value2) {
+ if (value1 >= value2)
+ return value1 - value2;
+ else
+ return value2 - value1;
+}
+
+int absoluteValue(int value1, int value2) {
+ if (value1 >= value2)
+ return value1 - value2;
+ else
+ return value2 - value1;
+}
+
+float crossReliability(SlaveAgentSlotOfAgent* slaveAgent, vector<SlaveAgentSlotOfAgent*>* slaveAgents, SlaveAgentSlotOfAgent* excludeSlaveAgent) {
+
+
+ //getchar();
+
+ float crossReliabilityParameter = 1.5;
+ float minCrossReliability = 1;
+ float crossReliabiability;
+
+ float forRR = 0.6f;
+
+
+ printf("cro init = %f\n", crossReliabilityParameter);
+
+
+ //for (auto &slaveAgent1 : *slaveAgents) {
+ for (auto &slaveAgent2 : *slaveAgents) {
+
+ //this line is new
+ crossReliabilityParameter = 1.5;
+
+
+ if (slaveAgent != slaveAgent2 && slaveAgent2 != excludeSlaveAgent && slaveAgent->get_flagSlaveAgentValueIsSet() && slaveAgent2->get_flagSlaveAgentValueIsSet()) {
+
+ if (AGENT1 == HR && AGENT2 == RR) {
+ crossReliabilityParameter = forRR;
+ }
+ else if (AGENT1 == HR && AGENT2 == BP) {
+ printf("hr - bp\n");
+ crossReliabilityParameter = 2.5;
+ }
+ else if (AGENT1 == HR && AGENT2 == SPO2) {
+
+ }
+ else if (AGENT1 == HR && AGENT2 == BTEMP) {
+ printf("hr - btemp\n");
+ }
+ else if (AGENT1 == RR && AGENT2 == HR) {
+ crossReliabilityParameter = forRR;
+ }
+ else if (AGENT1 == RR && AGENT2 == BP) {
+ crossReliabilityParameter = forRR;
+ }
+ else if (AGENT1 == RR && AGENT2 == SPO2) {
+ crossReliabilityParameter = forRR;
+ }
+ else if (AGENT1 == RR && AGENT2 == BTEMP) {
+ crossReliabilityParameter = forRR;
+ }
+ else if (AGENT1 == BP && AGENT2 == HR) {
+ printf("bp - hr\n");
+ crossReliabilityParameter = 2.5;
+ }
+ else if (AGENT1 == BP && AGENT2 == RR) {
+ crossReliabilityParameter = forRR;
+ }
+ else if (AGENT1 == BP && AGENT2 == SPO2) {
+
+ }
+ else if (AGENT1 == BP && AGENT2 == BTEMP) {
+
+ }
+ else if (AGENT1 == SPO2 && AGENT2 == HR) {
+
+ }
+ else if (AGENT1 == SPO2 && AGENT2 == RR) {
+ crossReliabilityParameter = forRR;
+ }
+ else if (AGENT1 == SPO2 && AGENT2 == BP) {
+
+ }
+ else if (AGENT1 == SPO2 && AGENT2 == BTEMP) {
+
+ }
+ else if (AGENT1 == BTEMP && AGENT2 == HR) {
+ printf("btemp - hr\n");
+ }
+ else if (AGENT1 == BTEMP && AGENT2 == RR) {
+ crossReliabilityParameter = forRR;
+ }
+ else if (AGENT1 == BTEMP && AGENT2 == BP) {
+
+ }
+ else if (AGENT1 == BTEMP && AGENT2 == SPO2) {
+
+ }
+ else {
+ printf("HEY! %u, %u\n", AGENT1, AGENT2);
+ getchar();
+ }
+
+
+
+ if (slaveAgent->getScoreValue() == slaveAgent2->getScoreValue())
+ crossReliabiability = 1;
+ else
+ crossReliabiability = 1 / (crossReliabilityParameter * absoluteValue((float)slaveAgent->getScoreValue(), (float)slaveAgent2->getScoreValue()));
+
+ //printf("cro = %f ", crossReliabilityParameter);
+
+ //printf("%s -> %s cross-rel: %f\n", slaveAgent->get_comPort()->getName().c_str(), slaveAgent2->get_comPort()->getName().c_str(), crossReliabiability);
+
+ if (crossReliabiability < minCrossReliability)
+ minCrossReliability = crossReliabiability;
+ }
+ }
+ //}
+
+ return minCrossReliability;
+}
+
+float crossReliability(SlaveAgentSlotOfAgent* slaveAgent, vector<SlaveAgentSlotOfAgent*>* slaveAgents) {
+ return crossReliability(slaveAgent, slaveAgents, NULL);
+}
+
+
+float Agent::crossReliabilityNEW(SlaveAgentSlotOfAgent* slaveAgent, vector<SlaveAgentSlotOfAgent*>* slaveAgents, SlaveAgentSlotOfAgent* excludeSlaveAgent, int mode, int theoreticalScore) {
+
+ float finalCrossReliability = 1;
+ float crossReliabiability;
+ unsigned int numOfAgentsWereCompared = 0;
+
+ /*
+ float crossReliabilityParameter = 1; // 2.5; //1.5
+
+
+ //float forRR = 0.6; //mobiHealth2017 submission
+ //float forRR = 1.5;
+ float forRR = 0.5;
+ float forHRBP = 1; // 2.5;
+
+ //printf("cro init = %f\n", crossReliabilityParameter);
+ */
+
+ //for (auto &slaveAgent1 : *slaveAgents) {
+ for (auto &slaveAgent2 : *slaveAgents) {
+
+ //this line is new
+ //crossReliabilityParameter = 1; //1.5;
+
+ if (slaveAgent != slaveAgent2 && slaveAgent2 != excludeSlaveAgent && slaveAgent->get_flagSlaveAgentValueIsSet() && slaveAgent2->get_flagSlaveAgentValueIsSet()) {
+
+ /*
+ if (AGENT1 == HR && AGENT2 == RR) {
+ crossReliabilityParameter = forRR;
+ }
+ else if (AGENT1 == HR && AGENT2 == BP) {
+ //printf("hr - bp\n");
+ crossReliabilityParameter = forHRBP;
+ }
+ else if (AGENT1 == HR && AGENT2 == SPO2) {
+
+ }
+ else if (AGENT1 == HR && AGENT2 == BTEMP) {
+ //printf("hr - btemp\n");
+ }
+ else if (AGENT1 == RR && AGENT2 == HR) {
+ crossReliabilityParameter = forRR;
+ }
+ else if (AGENT1 == RR && AGENT2 == BP) {
+ crossReliabilityParameter = forRR;
+ }
+ else if (AGENT1 == RR && AGENT2 == SPO2) {
+ crossReliabilityParameter = forRR;
+ }
+ else if (AGENT1 == RR && AGENT2 == BTEMP) {
+ crossReliabilityParameter = forRR;
+ }
+ else if (AGENT1 == BP && AGENT2 == HR) {
+ //printf("bp - hr\n");
+ crossReliabilityParameter = forHRBP;
+ }
+ else if (AGENT1 == BP && AGENT2 == RR) {
+ crossReliabilityParameter = forRR;
+ }
+ else if (AGENT1 == BP && AGENT2 == SPO2) {
+
+ }
+ else if (AGENT1 == BP && AGENT2 == BTEMP) {
+
+ }
+ else if (AGENT1 == SPO2 && AGENT2 == HR) {
+
+ }
+ else if (AGENT1 == SPO2 && AGENT2 == RR) {
+ crossReliabilityParameter = forRR;
+ }
+ else if (AGENT1 == SPO2 && AGENT2 == BP) {
+
+ }
+ else if (AGENT1 == SPO2 && AGENT2 == BTEMP) {
+
+ }
+ else if (AGENT1 == BTEMP && AGENT2 == HR) {
+ //printf("btemp - hr\n");
+ }
+ else if (AGENT1 == BTEMP && AGENT2 == RR) {
+ crossReliabilityParameter = forRR;
+ }
+ else if (AGENT1 == BTEMP && AGENT2 == BP) {
+
+ }
+ else if (AGENT1 == BTEMP && AGENT2 == SPO2) {
+
+ }
+ else {
+ printf("HEY! %u, %u\n", AGENT1, AGENT2);
+ getchar();
+ }
+ */
+
+
+ int score1, score2;
+ float reliability;
+
+ if (mode == MULTIPLICATION || mode == CONJUNCTION || mode == AVERAGE) {
+ slaveAgent->getPossibleScore(slaveAgent->getPossibleScoreCount(), &score1, &reliability);
+ }
+ else if (mode == MULTIPLICATION_THEORETICAL || mode == CONJUNCTION_THEORETICAL || mode == AVERAGE_THEORETICAL) {
+ score1 = theoreticalScore;
+ }
+ else {
+ printf("FEHLER-1234\n");
+ getchar();
+ }
+
+ slaveAgent2->getPossibleScore(slaveAgent2->getPossibleScoreCount(), &score2, &reliability);
+
+ if (score1 == score2)
+ crossReliabiability = 1;
+ else
+ crossReliabiability = 1 / (crossReliabilityParameter * absoluteValue((float)score1, (float)score2));
+
+
+
+ //profile reliability
+ float crossReliabilityFromProfile = crossReliabilityProfileModule->getCrossReliabilityFromProfile(slaveAgent->get_comPort()->getName(), slaveAgent2->get_comPort()->getName(), absoluteValue(score1, score2));
+ crossReliabiability = std::max(crossReliabiability, crossReliabilityFromProfile);
+
+
+
+
+ //printf("pcro = %f ", crossReliabilityParameter);
+ //printf("%s -> %s cross-rel: %f\n", slaveAgent->get_comPort()->getName().c_str(), slaveAgent2->get_comPort()->getName().c_str(), crossReliabiability);
+
+ /*
+ if (crossReliabiability < minCrossReliability)
+ minCrossReliability = crossReliabiability;
+ */
+
+ if (mode == MULTIPLICATION || mode == MULTIPLICATION_THEORETICAL) {
+ finalCrossReliability *= crossReliabiability;
+ }
+ else if (mode == CONJUNCTION || mode == CONJUNCTION_THEORETICAL) {
+ finalCrossReliability = min(finalCrossReliability, crossReliabiability);
+ }
+ else if (mode == AVERAGE || mode == AVERAGE_THEORETICAL) {
+ //finalCrossReliability = min(finalCrossReliability, crossReliabiability);
+ if (numOfAgentsWereCompared == 0) {
+ finalCrossReliability = crossReliabiability;
+ }
+ else {
+ finalCrossReliability = (finalCrossReliability*(float)numOfAgentsWereCompared + crossReliabiability) / ((float)numOfAgentsWereCompared + 1);
+ }
+
+ numOfAgentsWereCompared = numOfAgentsWereCompared + 1;
+ }
+ else {
+ printf("FEHLER\n");
+ getchar();
+ }
+
+ }
+ }
+ //}
+
+
+
+ return finalCrossReliability;
+}
+
+
+float Agent::crossReliabilityNEW(SlaveAgentSlotOfAgent* slaveAgent, vector<SlaveAgentSlotOfAgent*>* slaveAgents, int mode, int theoreticalScore) {
+ return crossReliabilityNEW(slaveAgent, slaveAgents, NULL, mode, theoreticalScore);
+}
+
+
+bool compareByReliability(PossibleScore* a, PossibleScore* b)
+{
+ return a->confOrRel > b->confOrRel;
+}
+
+bool compareByConfRel(PossibleScore* a, PossibleScore* b)
+{
+ return a->confOrRel > b->confOrRel;
+}
+
+bool compareByScore(PossibleScore* a, PossibleScore* b)
+{
+ return a->score < b->score;
+}
+
+
+
+
+
+
+
+
+
+
+
+
+float Agent::getInputReliability(SensorSlotOfAgent* mountedAgent, float actualSensorValue) {
+ float inputReliability;
+ float previousSensorValue;
+
+ //calculate input reliability
+ #ifdef PRINT
+ printf("%s - ", name.c_str());
+ #endif // PRINT
+ if (mountedAgent->getPreviousSensorValue(&previousSensorValue)) {
+ inputReliability = reliabilityModule->getRelibility(actualSensorValue, previousSensorValue, mountedAgent->getValueSetCounter());
+ }
+ else {
+ inputReliability = reliabilityModule->getAbsoluteReliability(actualSensorValue);
+ }
+ #ifdef PRINT
+ printf("rel = %f\n", inputReliability);
+ #endif // PRINT
+
+ return inputReliability;
+}
+
+void Agent::combineConfidenceAndReliabilityOfActualPossibleScores(vector<PossibleScore*>* actualPossibleScores, float inputReliability) {
+ for (auto &pS : *actualPossibleScores) {
+ //combine input reliability with score confidence
+ //NOTE: multiplication, AND, or average would be alternatives (best to worst: AND = Multiplication >> Avg)
+ //pS->confOrRel = pS->confOrRel * inputReliability;
+ //pS->confOrRel = (pS->confOrRel + inputReliability) / 2;
+ pS->confOrRel = std::min(pS->confOrRel, inputReliability);
+ }
+}
+
+void Agent::saveActualPossibleScoresInHistory(vector<PossibleScore*>* actualPossibleScores) {
+
+ //check if the reliability of at least one possible score is high enough
+
+
+ bool atLeastOneRelIsHigh = false;
+ for (auto &pS : *actualPossibleScores) {
+ if (pS->confOrRel > 0.5) {
+ atLeastOneRelIsHigh = true;
+ }
+ }
+
+
+ //save possible scores if at least one possible score is high enough (or if the history is empty)
+ if (possibleScoreHistory.size() < 1 || atLeastOneRelIsHigh == true) {
+
+ possibleScoreHistory.push_front(actualPossibleScores);
+
+ //if history size is higher than allowed, savo oldest element
+ while (possibleScoreHistory.size() > maxHistSizePossScores) {
+ //delete possibleScoreHistory.back();
+ possibleScoreHistory.pop_back();
+ }
+ }
+}
+
+void Agent::getAllPossibleScoresBasedOnHistory(vector<PossibleScore*>* possibleScores) {
+ //vector<PossibleScore*> possibleScores;
+
+ //printf("a1\n");
+
+ //iterate through all history entries
+ float posInHistory = 0;
+ for (auto &pShE : possibleScoreHistory) {
+
+ //printf("a2\n");
+
+ //iterate through all possible scores of each history entry
+ for (auto &pSh : *pShE) {
+
+ //printf("a3\n");
+
+ int historyScore = pSh->score;
+ float historyConf = pSh->confOrRel;
+
+ //combine each history score with the confidence of time
+ //NOTE: multiplication, AND, or average would be alternatives (best to worst: multiplication = AND = average)
+ historyConf = historyConf * confTimeScoreHasBeen->getY(posInHistory);
+ //historyConf = (historyConf + confTimeScoreHasBeen->getY(posInHistory)) / 2;
+ //historyConf = std::min(historyConf, confTimeScoreHasBeen->getY(posInHistory));
+
+ //printf("a4\n");
+
+ bool foundScore = false;
+ for (auto &pS : *possibleScores) {
+
+ if (pS->score == historyScore) {
+
+ //calculate confidence for score
+ //NOTE: multiplication, AND, or average would be alternatives (best to worst: AND >> average = multiplication )
+ //pS->confOrRel = pS->confOrRel * historyConf;
+ //pS->confOrRel = (pS->confOrRel + historyConf) / 2;
+ pS->confOrRel = std::max(pS->confOrRel, historyConf);
+
+ foundScore = true;
+ }
+ }
+
+ if (foundScore == false) {
+
+ PossibleScore* possibleScore = new PossibleScore();
+ possibleScore->score = historyScore;
+ possibleScore->confOrRel = historyConf;
+
+ possibleScores->push_back(possibleScore);
+
+ }
+ }
+
+ //printf("a11\n");
+
+ posInHistory = posInHistory + 1;
+ }
+
+}
+
+
+
+
+void Agent::sendPossibleScoresToMaster(vector<PossibleScore*>* possibleScores) {
+ masterAgentHandlerOfAgent->pass_msgToSendBuffer(ISA_AbstractedSensoryDataAndReliability);
+ for (auto &pS : *possibleScores) {
+ masterAgentHandlerOfAgent->pass_msgToSendBuffer(pS->score);
+ masterAgentHandlerOfAgent->pass_msgToSendBuffer(pS->confOrRel);
+#ifdef PRINT
+ printf(" > Sends Up %i / %f\n", pS->score, pS->confOrRel);
+#endif // PRINT
+ }
+ masterAgentHandlerOfAgent->send_msgs();
+}
+
+void Agent::sendMostLikelyScoreToMaster(vector<PossibleScore*>* possibleScores) {
+ masterAgentHandlerOfAgent->pass_msgToSendBuffer(ISA_AbstractedSensoryDataAndReliability);
+ masterAgentHandlerOfAgent->pass_msgToSendBuffer(possibleScores->front()->score);
+ masterAgentHandlerOfAgent->pass_msgToSendBuffer(possibleScores->front()->confOrRel);
+#ifdef PRINT
+ printf(" > Sends Up %i / %f\n", possibleScores->front()->score, possibleScores->front()->confOrRel);
+#endif // PRINT
+ masterAgentHandlerOfAgent->send_msgs();
+}
+
+
+
+ void Agent::calculateAllPossibleScores(vector<PossibleScore*>* possibleEWSs) {
+
+ //vector<PossibleScore*> possibleEWSsBackup;
+
+ //get all mounted slave agents
+ vector<SlaveAgentSlotOfAgent*>* vMountedSlaveAgents = slaveAgentHandlerOfAgent->get_vMountedSlaveAgents();
+
+ //calculate number of all possible EWS options
+ unsigned int numOfPossibleScores = 1;
+ for (auto slaveAgentSlot : *vMountedSlaveAgents)
+ numOfPossibleScores *= slaveAgentSlot->getNumOfPossibleScores();
+
+ //iterate through all possibilities
+ bool changeToNextPossibility = false;
+ for (unsigned int i = 1; i <= numOfPossibleScores; i++) {
+
+
+ int actualPossibleEWS = 0;
+ float actualPossibleReliability = 1;
+
+ float actualCombinedInputReliability = 1;
+ float actualCombinedCrossReliability = 1;
+
+ for (auto slaveAgentSlot : *(slaveAgentHandlerOfAgent->get_vMountedSlaveAgents())) {
+
+ if (changeToNextPossibility) {
+ slaveAgentSlot->incPossibleScoreCount();
+ if (slaveAgentSlot->getPossibleScoreCount() == 0)
+ changeToNextPossibility = true;
+ else
+ changeToNextPossibility = false;
+ }
+
+
+ //get score and input reliability of one poissible score of the slave agent
+ int score;
+ float reliability;
+ slaveAgentSlot->getPossibleScore(slaveAgentSlot->getPossibleScoreCount(), &score, &reliability);
+
+ //update the actual EWS
+ actualPossibleEWS = actualPossibleEWS + score;
+
+ //udate actual combined input reliability
+ //NOTE: there would be also other options than min. e.g.: max, multiply
+ actualCombinedInputReliability = std::min(actualCombinedInputReliability, reliability);
+
+ //get cross confidence of this slave agent value to all the other slave agent values (all of the values belong to the same possible EWS)
+ //NOTE: alternative way would be multipilcation instead of Conjunction
+ float crossReliabilityOfSlaveAgent = crossReliabilityNEW(slaveAgentSlot, slaveAgentHandlerOfAgent->get_vMountedSlaveAgents(), CONJUNCTION, 0);
+
+ // udate actual combined cross reliability
+ //NOTE: there would be also other options than min. e.g.: max, multiply
+ actualCombinedCrossReliability = std::min(actualCombinedCrossReliability, crossReliabilityOfSlaveAgent);
+ }
+
+ // update actual possible reliability
+ //possibleReliability = possibleReliabilitySignals * possibleReliabilityCross;
+ actualPossibleReliability = std::min(actualCombinedInputReliability, actualCombinedCrossReliability);
+
+ //signaling that the next possibility shall be calculated
+ changeToNextPossibility = true;
+
+ PossibleScore* pS = new PossibleScore;
+ pS->score = actualPossibleEWS;
+ pS->confOrRel = actualPossibleReliability;
+ possibleEWSs->push_back(pS);
+ /*
+ if (actualPossibleReliability > 0.5) {
+ possibleEWSs->push_back(pS);
+ }
+ else {
+ possibleEWSsBackup.push_back(pS);
+ }
+ */
+ }
+
+ /*
+ if (possibleEWSs->size() < 1) {
+ printf("JA!\n");
+ getchar();
+ for (auto &pS : possibleEWSsBackup) {
+ possibleEWSs->push_back(pS);
+ }
+ }
+ */
+}
+
+void Agent::removeDuplicatesOfScores(vector<PossibleScore*>* possibleScores) {
+
+ //printf("bla1\n");
+
+ std::sort(possibleScores->begin(), possibleScores->end(), [](PossibleScore* a, PossibleScore* b) {
+ return (a->score > b->score || (a->score == b->score && a->confOrRel > b->confOrRel));
+ });
+
+ //printf("bla2\n");
+
+ auto last = std::unique(possibleScores->begin(), possibleScores->end(), [](PossibleScore* a, PossibleScore* b) {
+ return (a->score == b->score);
+ });
+
+ //printf("bla3\n");
+
+ possibleScores->erase(last, possibleScores->end());
+}
+
+
+
+
+
+void Agent::justSumScoresUp(int* EWS, float* reliability) {
+ int combinedSc = 0;
+ float combinedRel = 1;
+ for (auto &sA : *(slaveAgentHandlerOfAgent->get_vMountedSlaveAgents())) {
+ int sc;
+ float rel;
+
+ //get score with the highest reliability
+ sA->getPossibleScore(0, &sc, &rel);
+
+ combinedSc = combinedSc + sc;
+ combinedRel = std::min(combinedRel, rel);
+ }
+
+ *EWS = combinedSc;
+ *reliability = combinedRel;
+}
+
+
+void Agent::triggerLowLevelAgent() {
+
+
+
+
+ if (sensorHandlerOfAgent) {
+ sensorHandlerOfAgent->read_allSensorValues();
+
+ //NOTE: only one sensor is mounted! Thus, we read only the first one!
+ SensorSlotOfAgent* mountedAgent = sensorHandlerOfAgent->get_vMountedSensors()->front();
+
+ float actualSensorValue;
+ //float previousSensorValue;
+ float inputReliability;
+
+ if (mountedAgent->get_sensorValue(&actualSensorValue)) {
+
+#ifdef PRINT
+ printf("%s reads %f\n", name.c_str(), actualSensorValue);
+#endif // PRINT
+
+ //collect all possible scores with their confidences
+ vector<PossibleScore*>* actualPossibleScores = scoreConfidenceModule->getScoresWithConfidences(actualSensorValue);
+
+ //printf("#actualPossibleScores: %u\n", actualPossibleScores->size());
+
+ //calculate input reliability
+ inputReliability = getInputReliability(mountedAgent, actualSensorValue);
+
+ //only for test stuff
+ /*if (inputReliability < 1) {
+ printf("niedriger! - %f\n", inputReliability);
+ getchar();
+ }*/
+
+ //combine input reliability and confidence for all actual possible scores
+ combineConfidenceAndReliabilityOfActualPossibleScores(actualPossibleScores, inputReliability);
+
+ //printf("#actualPossibleScores (after combi): %u\n", actualPossibleScores->size());
+
+ //FROM HERE - MASTER INPUT
+ //clear suggested scores from last cycle
+ masterAgentHandlerOfAgent->clearSuggestedScores();
+ masterAgentHandlerOfAgent->read_masterAgentValues();
+
+ vector<PossibleScore*>* suggestedScores = masterAgentHandlerOfAgent->getSuggestedScores();
+
+ //if (id == 6)
+ //printf("++++++++\nsuggestedScores: %u\nactualPossibleScores: %u\n+++++++++\n", suggestedScores->size(), actualPossibleScores->size());
+
+ for (auto &sS : *suggestedScores) {
+ for (auto &aPs : *actualPossibleScores) {
+ if (aPs->score == sS->score) {
+ //combine suggested score with actual score
+ //NOTE: multiplication, AND, or average would be alternatives (best to worst: AND > multiplication >> average)
+ //aPs->confOrRel = std::min(aPs->confOrRel, sS->confOrRel);
+ aPs->confOrRel = (aPs->confOrRel + sS->confOrRel);
+ //aPs->confOrRel = aPs->confOrRel * sS->confOrRel;
+ }
+ }
+ }
+ //TO HERE - MASTER INPUT
+
+ //if (id == 6)
+ //printf("++++++++\nsuggestedScores: %u\nactualPossibleScores: %u\n+++++++++\n", suggestedScores->size(), actualPossibleScores->size());
+
+ //save actual possible scores in history
+ saveActualPossibleScoresInHistory(actualPossibleScores);
+
+ //evaluate all possible scores (based on the history)
+ vector<PossibleScore*> possibleScores;
+
+ //printf("SIZE BEFORE: %u\n", possibleScores.size());
+
+ getAllPossibleScoresBasedOnHistory(&possibleScores);
+
+ //printf("SIZE AFTER: %u\n", possibleScores.size());
+
+ //sort all possible scores so that outputRel_i >= outputRel_i+1
+ std::sort(possibleScores.begin(), possibleScores.end(), compareByConfRel);
+
+ //send possible scores to high level agent
+ //sendPossibleScoresToMaster(&possibleScores);
+
+ for (auto &pS : possibleScores) {
+#ifdef PRINT
+ printf(" > possible Score %i / %f\n", pS->score, pS->confOrRel);
+#endif // PRINT
+ }
+
+ //send most likely score to high level agent
+ sendMostLikelyScoreToMaster(&possibleScores);
+
+ }
+ }
+}
+
+
+
+void Agent::triggerHighLevelAgent() {
+
+
+
+ if (slaveAgentHandlerOfAgent) {
+
+ //get all mounted slave agents
+ vector<SlaveAgentSlotOfAgent*>* mountedSlaveAgents = slaveAgentHandlerOfAgent->get_vMountedSlaveAgents();
+
+ //clear possible scores from last cycle
+ for (auto &sA : *mountedSlaveAgents) {
+ sA->clearPossibleScores();
+ }
+
+ //read all slave agent values
+ bool readSlaveAgentsWorked = slaveAgentHandlerOfAgent->read_allSlaveAgentValues();
+
+ if (readSlaveAgentsWorked) {
+
+
+ int EWS = 0;
+ float combinedInputRel = 1;
+ float combinedCrossRel = 1;
+ float outputReliability;
+
+ unsigned int numOfSlaveAgentsWereChecked = 0;
+
+ for (auto &sA : *mountedSlaveAgents) {
+ int sc;
+ float rel;
+
+ //get score with the highest reliability
+ sA->getPossibleScore(0, &sc, &rel);
+
+ EWS = EWS + sc;
+ //calulate combined input reliability (possible AND, Average, Multiplication) - (best to worst: AND = Avg > Multiplication)
+ //combinedInputRel = combinedInputRel * rel;
+ /*
+ if (numOfSlaveAgentsWereChecked == 0) {
+ combinedInputRel = rel;
+ }
+ else {
+ combinedInputRel = (combinedInputRel * (float)numOfSlaveAgentsWereChecked + rel) / (numOfSlaveAgentsWereChecked + 1);
+ }
+ */
+ combinedInputRel = std::min(combinedInputRel, rel);
+
+
+ //calculate the cross reliability for this slave agent
+ float realCrossReliabilityOfSlaveAgent = crossReliabilityNEW(sA, mountedSlaveAgents, CONJUNCTION, 0); //AVERAGE, MULTIPLICATION, CONJUNCTION (best to worst: AVERAGE = CONJUNCTION > MULTIPLICATION >> )
+
+ //send all theoritcally possible scores to slave agent
+#ifdef PRINT
+ printf(" > Sends Down ");
+#endif // PRINT
+ sA->pass_msgToSendBuffer(ISA_SuggestedAbstractedSensoryDataAndReliability);
+ for (int theoreticalScore = 0; theoreticalScore <= 3; theoreticalScore++) {
+ //calculate the cross reliability for this slave agent
+ float theoreticalCrossReliabilityOfSlaveAgent = crossReliabilityNEW(sA, mountedSlaveAgents, CONJUNCTION_THEORETICAL, theoreticalScore); //AVERAGE_THEORETICAL, MULTIPLICATION_THEORETICAL, CONJUNCTION_THEORETICAL (best to worst: AVERAGE_THEORETICAL = CONJUNCTION_THEORETICAL > MULTIPLICATION_THEORETICAL >> )
+ sA->pass_msgToSendBuffer(theoreticalScore);
+ sA->pass_msgToSendBuffer(theoreticalCrossReliabilityOfSlaveAgent);
+#ifdef PRINT
+ printf("- %i / %f to %s", theoreticalScore, theoreticalCrossReliabilityOfSlaveAgent, sA->get_comPort()->getName().c_str());
+#endif // PRINT
+ }
+ sA->send_msgs();
+#ifdef PRINT
+ printf("\n");
+#endif // PRINT
+
+ //combine cross reliabilites of all slave agents
+ //NOTE: options would be multiply, average, AND (best to worst: average = AND > multiply)
+ //combinedCrossRel = combinedCrossRel * realCrossReliabilityOfSlaveAgent;
+ /*
+ if (numOfSlaveAgentsWereChecked == 0) {
+ combinedCrossRel = realCrossReliabilityOfSlaveAgent;
+ }
+ else {
+ combinedCrossRel = (combinedCrossRel * (float)numOfSlaveAgentsWereChecked + realCrossReliabilityOfSlaveAgent) / (numOfSlaveAgentsWereChecked + 1);
+ }
+ */
+ combinedCrossRel = std::min(combinedCrossRel, realCrossReliabilityOfSlaveAgent);
+
+#ifdef MORE_INFO_IN_CSV
+ csvWriter->write_field(sc);
+ csvWriter->make_new_field();
+
+ secondCsvWriter->write_field(sc);
+ secondCsvWriter->make_new_field();
+ secondCsvWriter->write_field(rel);
+ secondCsvWriter->make_new_field();
+#endif // MORE_INFO_IN_CSV
+
+ numOfSlaveAgentsWereChecked++;
+ }
+
+ //combine cross reliabilites and input reliabilites of all slave agents
+ //NOTE: options would be multiply, average, AND (best to worst: )
+ //outputReliability = combinedInputRel * combinedCrossRel;
+ //outputReliability = (combinedInputRel + combinedCrossRel) / 2;
+ outputReliability = std::min(combinedInputRel, combinedCrossRel);
+
+
+
+
+
+ csvWriter->write_field(EWS);
+ csvWriter->make_new_field();
+ csvWriter->write_field(outputReliability);
+ csvWriter->make_new_line();
+
+ secondCsvWriter->write_field(EWS);
+ secondCsvWriter->make_new_field();
+ secondCsvWriter->write_field(outputReliability);
+ secondCsvWriter->make_new_field();
+ for (auto &sA : *(slaveAgentHandlerOfAgent->get_vMountedSlaveAgents())) {
+
+ int score;
+ float inputRel;
+ unsigned int rank = 0;
+
+ while (sA->getPossibleScore(rank, &score, &inputRel)) {
+#ifdef PRINT
+ printf("%s got possible score = %i / %f from %s\n", name.c_str(), score, inputRel, sA->get_comPort()->getName().c_str());
+#endif // PRINT
+ secondCsvWriter->write_field(sA->get_comPort()->getName());
+ secondCsvWriter->make_new_field();
+ secondCsvWriter->write_field(score);
+ secondCsvWriter->make_new_field();
+ secondCsvWriter->write_field(inputRel);
+ secondCsvWriter->make_new_field();
+
+ rank++;
+ }
+ }
+ secondCsvWriter->make_new_line();
+
+
+ }
+ }
+}
+
+
+
+
+
+
+
+
+
+void Agent :: trigger(unsigned int cycle) {
+
+ if (workingCycleCounter < getWorkCycle())
+ workingCycleCounter++;
+ else
+ workingCycleCounter = 1;
+
+ if (workingCycleCounter == 1) {
+ //TODO: make control_module to set the method of operating for each agent individual
+
+ if (id >= 5 && id <= 9) {
+ triggerLowLevelAgent();
+ }
+ else if (id == 10) {
+ triggerHighLevelAgent();
+ }
+ else {
+ printf("something wrong with agent disambiguation!\n");
+ getchar();
+ }
+ }
+}
+
+
+
+
+//SHORTCUT/WORKAUROUND -> TODO: make this better!
+bool Agent::setAbstractionModule(AbstractionModule *abstractionModule) {
+ if (abstractionModule) {
+ this->abstractionModule = abstractionModule;
+ //printf(" > abstraction module mounted in %s\n", name.c_str());
+ return true;
+ }
+ return false;
+}
+
+
+bool Agent::setReliabilityModule(ReliabilityModule* reliabilityModule) {
+ if (reliabilityModule) {
+ this->reliabilityModule = reliabilityModule;
+ //printf(" > reliability module mounted in %s\n", name.c_str());
+ return true;
+ }
+ return false;
+}
+
+void Agent::closeCSV() {
+ if (csvWriter != NULL)
+ csvWriter->close_file();
+ /*if (secondCsvWriter != NULL) {
+ printf("hier?\n");
+ secondCsvWriter->close_file();
+ }*/
+}
+
+
+
+bool Agent::setScoreConfidenceModule(ScoreConfidenceModule* scoreConfidenceModule) {
+ if (scoreConfidenceModule) {
+ this->scoreConfidenceModule = scoreConfidenceModule;
+ return true;
+ }
+
+ return false;
+}
+
+void Agent::setConfidenceChange(LinearFunctionBlock* confChangeRightDiff, LinearFunctionBlock* confChangeWrongDiff, LinearFunctionBlock* confChangeRightTime, LinearFunctionBlock* confChangeWrongTime) {
+ this->confChangeRightDiff = confChangeRightDiff;
+ this->confChangeWrongDiff = confChangeWrongDiff;
+ this->confChangeRightTime = confChangeRightTime;
+ this->confChangeWrongTime = confChangeWrongTime;
+}
+
+void Agent::setScoreHistorLength(unsigned int scoreHistoryLength) {
+ this->scoreHistoryLength = scoreHistoryLength;
+}
+
+void Agent::saveInScoreHistoryLength(int score, float reliability) {
+ PossibleScore* pS = new PossibleScore;
+ pS->score = score;
+ pS->confOrRel = reliability;
+
+ while (scoreHistory.size() >= scoreHistoryLength)
+ scoreHistory.pop_back();
+
+ scoreHistory.push_front(pS);
+}
+
+
+
+
+
+
+/*
+void Agent::setConfidenceScoreChangeRight(LinearFunctionBlock* conf) {
+ confidenceScoreChangeRight = conf;
+}
+
+void Agent::setConfidenceScoreChangeWrong(LinearFunctionBlock* conf) {
+ confidenceScoreChangeWrong = conf;
+}
+*/
+
+
+void Agent::setCSVWRiter(char* filepath) {
+ csvWriter = new CSV_Writer(filepath);
+#ifdef MORE_INFO_IN_CSV
+ for (auto &sa : *(slaveAgentHandlerOfAgent->get_vMountedSlaveAgents())) {
+ csvWriter->write_field(sa->get_comPort()->getName());
+ csvWriter->make_new_field();
+ }
+#endif // MORE_INFO_IN_CSV
+ csvWriter->write_field("sa-ews");
+ csvWriter->make_new_field();
+ csvWriter->write_field("reliability");
+ csvWriter->make_new_line();
+}
+
+void Agent::setSecondCSVWRiter(char* filepath) {
+ secondCsvWriter = new CSV_Writer(filepath);
+ secondCsvWriter->write_field("sa-ews");
+ secondCsvWriter->make_new_field();
+ secondCsvWriter->write_field("reliability");
+ secondCsvWriter->make_new_line();
+}
+
+
+
+void Agent::resetAgent() {
+
+ //delete lastScore;
+ timeSinceChange = 0;
+
+ scoreHistoryLength = 0;
+ scoreHistory.clear();
+
+ lastEwsScore = 0;
+ lastReliability = 0;
+
+ agentScore = 0;
+
+ //vector<SlaveAgentSlot*> temp = slaveAgentHandlerOfAgent->get_vMountedSlaveAgents();
+
+ if (slaveAgentHandlerOfAgent)
+ slaveAgentHandlerOfAgent->resetHandler();
+
+ if (sensorHandlerOfAgent)
+ sensorHandlerOfAgent->resetHandler();
+}
+
+
+void Agent::setConfTimeScoreHasBeen(LinearFunctionBlock* confTimeScoreHasBeen) {
+ this->confTimeScoreHasBeen = confTimeScoreHasBeen;
+}
+
+void Agent::setMaxHistSizePossScores(unsigned int maxHistSizePossScores) {
+ this->maxHistSizePossScores = maxHistSizePossScores;
+}
+
+void Agent::setCrossReliabilityProfileModule(CrossReliabilityProfileModule* crossReliabilityProfileModule) {
+ this->crossReliabilityProfileModule = crossReliabilityProfileModule;
+}
+
+void Agent::setCrossReliabiabilityParameter(float crossReliabilityParameter) {
+ this->crossReliabilityParameter = crossReliabilityParameter;
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/Agent.h b/SA-EWS_Version_2019.03.27/src/Agent.h
new file mode 100644
index 0000000..48042bf
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/Agent.h
@@ -0,0 +1,185 @@
+#ifndef AGENT_HEADERFILE
+#define AGENT_HEADERFILE
+
+#include "HistoryController.h"
+#include "MasterAgentHandlerOfAgent.h"
+#include "Node.h"
+#include "SensorHandlerOfAgent.h"
+#include "SlaveAgentHandlerOfAgent.h"
+#include "StateHandler.h"
+#include "StabilityController.h"
+
+//SHORTCUT/WORKAUROUND -> TODO: make this better!
+#include "AbstractionModule.h"
+#include "ReliabilityModule.h"
+#include "ScoreConfidenceModule.h"
+#include "CrossReliabilityProfileModule.h"
+
+#include <list>
+
+
+class Agent : public Node {
+
+ private :
+
+ SensorHandlerOfAgent* sensorHandlerOfAgent;
+ SlaveAgentHandlerOfAgent* slaveAgentHandlerOfAgent;
+ MasterAgentHandlerOfAgent* masterAgentHandlerOfAgent;
+
+ //History Controller
+ HistoryController* historyController;
+
+ //State Controller
+ StateHandler* stateHandler;
+
+ //Stability Controller
+ StabilityController* stabilityController;
+
+ //StabilityModule* stabilityModule;
+
+
+ unsigned int workingCycleCounter;
+
+ void init_agent();
+
+
+ //SHORTCUT/WORKAUROUND -> TODO: make this better!
+ AbstractionModule *abstractionModule;
+ ReliabilityModule *reliabilityModule;
+ int agentScore;
+ CSV_Writer *csvWriter;
+ CSV_Writer *secondCsvWriter;
+
+ //New for Journal - SHORTCUT/WORKAUROUND -> TODO: make this better!
+ ScoreConfidenceModule* scoreConfidenceModule;
+ int lastEwsScore;
+ float lastReliability;
+
+
+ LinearFunctionBlock* confChangeRightDiff;
+ LinearFunctionBlock* confChangeWrongDiff;
+ LinearFunctionBlock* confChangeRightTime;
+ LinearFunctionBlock* confChangeWrongTime;
+
+
+ LinearFunctionBlock* confTimeScoreHasBeen;
+ unsigned int maxHistSizePossScores;
+
+
+ float crossReliabilityParameter;
+
+
+ PossibleScore* lastScore;
+ unsigned int timeSinceChange;
+
+ unsigned int scoreHistoryLength;
+ list<PossibleScore*> scoreHistory;
+
+
+ list<vector<PossibleScore*>*> possibleScoreHistory;
+
+ CrossReliabilityProfileModule* crossReliabilityProfileModule;
+
+
+ float crossReliabilityNEW(SlaveAgentSlotOfAgent* slaveAgent, vector<SlaveAgentSlotOfAgent*>* slaveAgents, SlaveAgentSlotOfAgent* excludeSlaveAgent, int mode, int theoreticalScore);
+ float crossReliabilityNEW(SlaveAgentSlotOfAgent* slaveAgent, vector<SlaveAgentSlotOfAgent*>* slaveAgents, int mode, int theoreticalScore);
+
+ /*
+ LinearFunctionBlock* confidenceScoreChangeRight;
+ LinearFunctionBlock* confidenceScoreChangeWrong;
+ */
+
+ float getInputReliability(SensorSlotOfAgent* mountedAgent, float actualSensorValue);
+ void combineConfidenceAndReliabilityOfActualPossibleScores(vector<PossibleScore*>* actualPossibleScores, float inputReliability);
+ void saveActualPossibleScoresInHistory(vector<PossibleScore*>* actualPossibleScores);
+ void getAllPossibleScoresBasedOnHistory(vector<PossibleScore*>* possibleScores);
+ void sendPossibleScoresToMaster(vector<PossibleScore*>* possibleScores);
+ void sendMostLikelyScoreToMaster(vector<PossibleScore*>* possibleScores);
+ void triggerLowLevelAgent();
+ void calculateAllPossibleScores(vector<PossibleScore*>* possibleEWSs);
+ void removeDuplicatesOfScores(vector<PossibleScore*>* possibleEWSs);
+ void justSumScoresUp(int* EWS, float* reliability);
+ void triggerHighLevelAgent();
+
+
+ public:
+ Agent();
+ Agent(string name);
+
+ //TODO: do this in all classes where memory was allocated
+ ~Agent();
+
+ 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();
+
+ bool setHistoryController();
+ bool setHistoryController(HistoryController* historyController);
+ bool delHistoryController();
+ HistoryController* getHistoryController();
+
+ bool setStabilityController();
+ bool setStabilityController(StabilityController* stabilityController);
+ bool delStabilityController();
+ StabilityController* getStabilityController();
+
+ /*
+ bool mountStabilityModule(StabilityModule* stabilityModule);
+ bool unmountStabilityModule();
+ StabilityModule* getStabilityModule();
+ */
+
+ void trigger(unsigned int cycle);
+
+
+
+
+ //SHORTCUT/WORKAUROUND -> TODO: make this better!
+ bool setAbstractionModule(AbstractionModule *abstractionModule);
+ bool setReliabilityModule(ReliabilityModule* reliabilityModule);
+ void closeCSV();
+
+ //New for Journal - SHORTCUT/WORKAUROUND -> TODO: make this better!
+ bool setScoreConfidenceModule(ScoreConfidenceModule* scoreConfidenceModule);
+
+ void setConfidenceChange(LinearFunctionBlock* confChangeRightDiff, LinearFunctionBlock* confChangeWrongDiff, LinearFunctionBlock* confChangeRightTime, LinearFunctionBlock* confChangeWrongTime);
+
+ void setScoreHistorLength(unsigned int scoreHistoryLength);
+
+ void saveInScoreHistoryLength(int score, float reliability);
+
+
+ /*
+ void setConfidenceScoreChangeRight(LinearFunctionBlock* conf);
+ void setConfidenceScoreChangeWrong(LinearFunctionBlock* conf);
+ */
+
+ void setCSVWRiter(char* filepath);
+ void setSecondCSVWRiter(char* filepath);
+
+ void resetAgent();
+
+
+ void setConfTimeScoreHasBeen(LinearFunctionBlock* confTimeScoreHasBeen);
+ void setMaxHistSizePossScores(unsigned int maxHistSizePossScores);
+
+ void setCrossReliabilityProfileModule(CrossReliabilityProfileModule* crossReliabilityProfileModule);
+
+ void setCrossReliabiabilityParameter(float crossReliabilityParameter);
+
+};
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/AgentSlotOfTestbench.cpp b/SA-EWS_Version_2019.03.27/src/AgentSlotOfTestbench.cpp
new file mode 100644
index 0000000..ff586fd
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/AgentSlotOfTestbench.cpp
@@ -0,0 +1,31 @@
+#include "AgentSlotOfTestbench.h"
+
+#include <stdio.h>
+
+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;
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/AgentSlotOfTestbench.h b/SA-EWS_Version_2019.03.27/src/AgentSlotOfTestbench.h
new file mode 100644
index 0000000..f7d097b
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/AgentSlotOfTestbench.h
@@ -0,0 +1,21 @@
+#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();
+};
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/AverageValue.cpp b/SA-EWS_Version_2019.03.27/src/AverageValue.cpp
new file mode 100644
index 0000000..6b0c0dd
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/AverageValue.cpp
@@ -0,0 +1,39 @@
+#include "AverageValue.h"
+
+#include <stdio.h>
+
+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/SA-EWS_Version_2019.03.27/src/AverageValue.h b/SA-EWS_Version_2019.03.27/src/AverageValue.h
new file mode 100644
index 0000000..a889eee
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/Bunch_Module.cpp b/SA-EWS_Version_2019.03.27/src/Bunch_Module.cpp
new file mode 100644
index 0000000..be42a43
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/Bunch_Module.cpp
@@ -0,0 +1,66 @@
+#include "Bunch_Module.h"
+
+#include <stdio.h>
+
+void Bunch_Module :: initialize_bunch_module(unsigned int bunch_method) {
+ this->bunch_method = bunch_method;
+}
+
+Bunch_Module :: Bunch_Module(unsigned int bunch_method) {
+ setName(NO_NAME);
+
+ initialize_bunch_module(bunch_method);
+}
+
+Bunch_Module :: Bunch_Module(char* name, unsigned int bunch_method) {
+ setName(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_ix<num_of_input; in_ix++) {
+ if(input_is_valid[in_ix]) {
+ result = result + *(input+in_ix);
+ data_confidence_counter++;
+ //printf("%u - valid\n", in_ix);
+ }
+
+ }
+
+ *output = result;
+
+ return data_confidence_counter;
+}
+
+void Bunch_Module :: set_bunch_method(unsigned int bunch_method) {
+ this->bunch_method = bunch_method;
+}
+
+unsigned int Bunch_Module :: get_bunch_method() {
+ return bunch_method;
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/Bunch_Module.h b/SA-EWS_Version_2019.03.27/src/Bunch_Module.h
new file mode 100644
index 0000000..213570a
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/Bunch_Module.h
@@ -0,0 +1,35 @@
+#ifndef BUNCH_HEADERFILE
+#define BUNCH_HEADERFILE
+
+//#include "Module.h"
+#include "Unit.h"
+
+#define BUNCH_METHOD_NOT_SPECIFIED 0
+#define BUNCH_SIMPLY_ADD 1
+
+class Bunch_Module : public Unit {
+//class Bunch_Module : public Module {
+
+ private:
+ unsigned int bunch_method;
+
+ //private functions
+ 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/SA-EWS_Version_2019.03.27/src/CSV_Writer.cpp b/SA-EWS_Version_2019.03.27/src/CSV_Writer.cpp
new file mode 100644
index 0000000..e5cca47
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/CSV_Writer.cpp
@@ -0,0 +1,96 @@
+#include "CSV_Writer.h"
+//#include <string>
+//#include <iostream>
+
+#define STRINGLENGTH 5000
+
+void CSV_Writer::initialize_csv_writer(char* filepath_write) {
+ //fpointer_write = fopen(filepath_write, "w");
+ fopen_s(&fpointer_write, filepath_write, "w");
+
+ //printf("pointer address: %p\n", fpointer_write);
+ //getchar();
+}
+
+CSV_Writer::CSV_Writer(char* filepath_write) {
+ //setName(NO_NAME);
+ initialize_csv_writer(filepath_write);
+}
+
+/*
+CSV_Writer :: CSV_Writer(char* name, char* filepath_write) {
+ setName(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::write_field(std::string dataset) {
+ if (fpointer_write) {
+ fprintf(fpointer_write, "%s", dataset.c_str());
+ 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_ix < num_of_datasets; d_ix++) {
+ fprintf(fpointer_write, "%f", datasets[d_ix]);
+ if (d_ix < num_of_datasets - 1)
+ fprintf(fpointer_write, ",");
+ }
+ fprintf(fpointer_write, "\n");
+ return true;
+ }
+ return false;
+}
+
+void CSV_Writer::close_file() {
+
+ if (fpointer_write != NULL)
+ fclose(fpointer_write);
+}
diff --git a/SA-EWS_Version_2019.03.27/src/CSV_Writer.h b/SA-EWS_Version_2019.03.27/src/CSV_Writer.h
new file mode 100644
index 0000000..c9529aa
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/CSV_Writer.h
@@ -0,0 +1,39 @@
+#ifndef CSV_WRITER_HEADERFILE
+#define CSV_WRITER_HEADERFILE
+
+//#include "Module.h"
+#include "Unit.h"
+#include <fstream>
+#include <string>
+
+#define MAX_LENGTH_OF_NAMES_TO_WRITE 50
+
+class CSV_Writer { //: public Unit {
+//class CSV_Writer : public Module {
+
+private:
+ FILE *fpointer_write;
+ unsigned int num_of_datasets;
+ float datasets[MAX_NUM_OF_DATA_SETS];
+
+ //private fuctions
+ void initialize_csv_writer(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 write_field(std::string dataset);
+ bool make_new_field();
+ bool make_new_line();
+
+ bool write_row_data(unsigned int num_of_datasets, float* datasets);
+
+ void close_file();
+};
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/CSVreaderModule.cpp b/SA-EWS_Version_2019.03.27/src/CSVreaderModule.cpp
new file mode 100644
index 0000000..77ed04e
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/CSVreaderModule.cpp
@@ -0,0 +1,209 @@
+#include "CSVreaderModule.h"
+#include <string>
+#include <iostream>
+
+#define STRINGLENGTH 1000
+
+/*
+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_ix<num_of_datasets; d_ix++) {
+ this->list_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) {
+ setName(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) {
+ setName(name);
+ initialize_csvreader(filepath_read, num_of_data_sets, list_of_datasets, start_row);
+}
+*/
+
+CSVreaderModule :: CSVreaderModule() {
+ setName(NO_NAME);
+ flag_csv_reader_configured = false;
+}
+
+CSVreaderModule :: CSVreaderModule(char* name) {
+ setName(name);
+ flag_csv_reader_configured = false;
+}
+
+CSVreaderModule :: CSVreaderModule(FILE* fpointer, unsigned int column, unsigned int start_row) {
+ setName(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) {
+ setName(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(;row<start_row; row++) {
+ if(!fgets(readrow, STRINGLENGTH, fpointer))
+ return false;
+ }
+
+ if(fgets (readrow, STRINGLENGTH, fpointer))
+ {
+ char *ptr, *next_ptr;
+ //TODO: make delimiter configurable!
+ ptr = strtok_s(readrow, ",;", &next_ptr);
+ //OLD: unsigned int dataset_counter = 0;
+ dataset_counter = 0;
+
+ if(list_of_datasets[dataset_counter] == 1) {
+ data_read[dataset_counter] = std::stof(ptr, NULL);
+ dataset_counter++;
+ }
+ else {
+ ptr = strtok_s(NULL, ",;", &next_ptr);
+ }
+
+ for(;dataset_counter<num_of_datasets;dataset_counter++) {
+ for(unsigned int c_ix=list_of_datasets[dataset_counter-1]; c_ix<list_of_datasets[dataset_counter]; c_ix++)
+ {
+ ptr = strtok_s(NULL, ",;", &next_ptr);
+ }
+ data_read[dataset_counter] = std::stof(ptr, NULL);
+ }
+ return true;
+ }
+ }
+ return false;
+}
+*/
+
+float CSVreaderModule :: get_value_of_field(unsigned int field) {
+ //TODO: Bessere Fehlerbehandlung.. also nciht einfach 0 returnen, wenn kein richtiges FEld!!!
+ if(field < num_of_datasets) {
+ return data_read[field];
+ }
+
+ return 0.0;
+}
+
+
+
+//TODO: überarbeiten nach folgendem Beispiel https://msdn.microsoft.com/en-us/library/ftsafwz3.aspx
+bool CSVreaderModule :: read_field() {
+ if(fpointer)
+ {
+ char readrow[STRINGLENGTH] = "", electedfield[STRINGLENGTH] = "";
+
+ //TODO: move following for-loop to "initialize_csvreader(...)
+ for(;row<start_row; row++) {
+ if(!fgets(readrow, STRINGLENGTH, fpointer))
+ return false;
+ /*
+ cout << "JUMP-row:" << endl;
+ printf("%s\n", readrow);
+ */
+ }
+
+ if(fgets (readrow, STRINGLENGTH, fpointer))
+ {
+ /*
+ cout << "row:" << endl;
+ cout << readrow << endl;
+ */
+ char *ptr, *next_ptr;
+ //TODO: make delimiter configurable!
+ ptr = strtok_s(readrow, ",;", &next_ptr);
+
+ for(unsigned int d_ix=1; d_ix<column; d_ix++) {
+ ptr = strtok_s(NULL, ",;", &next_ptr);
+ }
+ /*
+ cout << "field:" << endl;
+ cout << ptr << endl;
+ */
+
+ //WORKAROUND -TODO: empty fields are 'x'
+ if (strcmp(ptr, "x") == 0 || strcmp(ptr, "nan") == 0)
+ return false;
+
+
+
+
+ input_data = std::stof(ptr, NULL);
+ return true;
+ }
+ }
+ return false;
+}
+
+
+bool CSVreaderModule :: get_next_value(float* value) {
+ //printf("if\n");
+ if(flag_csv_reader_configured) {
+ //printf("yes\n");
+ if(read_field()) {
+ *value = input_data;
+ return true;
+ }
+ }
+ //printf("no\n");
+ return false;
+}
+
+//TODO: flag_csv_reader_configured abfragen
+void CSVreaderModule :: close_file() {
+ fclose(fpointer);
+}
diff --git a/SA-EWS_Version_2019.03.27/src/CSVreaderModule.h b/SA-EWS_Version_2019.03.27/src/CSVreaderModule.h
new file mode 100644
index 0000000..9f1b58c
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/CSVreaderModule.h
@@ -0,0 +1,49 @@
+#ifndef CSV_READER_HEADERFILE
+#define CSV_READER_HEADERFILE
+
+//#include "Module.h"
+#include "Unit.h"
+#include <fstream>
+
+class CSVreaderModule : public Unit {
+//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 close_file();
+};
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/Channel.cpp b/SA-EWS_Version_2019.03.27/src/Channel.cpp
new file mode 100644
index 0000000..b582cc2
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/Channel.cpp
@@ -0,0 +1,318 @@
+#include "Channel.h"
+#include <stdio.h>
+
+#define MAX_BUFFER_LENGTH 100
+
+//#define PRINT
+
+void Channel :: init_channel() {
+ maxBufferLength = MAX_BUFFER_LENGTH;
+ transferRate = MAX_BUFFER_LENGTH;
+}
+
+Channel :: Channel() {
+ init_channel();
+}
+
+Channel :: Channel(string name) : Unit(name) {
+ setName(name);
+ init_channel();
+}
+
+bool Channel::setMaxBufferLength(unsigned int maxBufferLength) {
+ if(maxBufferLength <= MAX_BUFFER_LENGTH) {
+ this->maxBufferLength = maxBufferLength;
+ return true;
+ }
+ return false;
+}
+
+unsigned int Channel::getMaxBufferLength() {
+ 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 :: setTransferRate(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<Message*>* buffer, Message* message) {
+ try {
+ buffer->push_front(message);
+ }
+ catch(bad_alloc& error) {
+ delete message;
+ return false;
+ }
+ return true;
+}
+
+bool Channel :: del_msgAtBegin (list<Message*>* buffer) {
+
+
+ try {
+ /*
+ printf("a\n");
+ getchar();
+ delete buffer->back();
+ printf("b\n");
+ getchar();
+ */
+
+
+ if (buffer) {
+ //Message* msg = buffer->front();
+ buffer->pop_front();
+ //delete msg;
+ }
+
+
+ /*
+ printf("c\n");
+ getchar();
+ */
+ }
+ catch(bad_alloc& error) {
+ return false;
+ }
+ return true;
+}
+
+bool Channel :: add_msgAtEnd (list<Message*>* buffer, Message* message) {
+ try {
+ buffer->push_back(message);
+ }
+ catch(bad_alloc& error) {
+ delete message;
+ return false;
+ }
+ return true;
+}
+
+bool del_msgAtEnd (list<Message*>* buffer) {
+ try {
+ 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<Message*>* dest_buffer, list<Message*>* 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; i<NumOfMsgsToMove; i++) {
+ if(add_msgAtEnd(dest_buffer, src_buffer->front())) {
+ if(!del_msgAtBegin(src_buffer)) {
+ return false;
+ }
+ }
+ else {
+ return false;
+ }
+ }
+ return true;
+ }
+ return false;
+}
+
+bool Channel :: trigger() {
+#ifdef PRINT
+ printf("Channel %s before: in_up %u, out_up %u, in_dn %u, out_dn %u,\n", name.c_str(), lInputMsgBufferUp.size(), lOutputMsgBufferUp.size(), lInputMsgBufferDown.size(), lOutputMsgBufferDown.size());
+#endif // PRINT
+
+ bool flag_worked = transferMsgs(&lOutputMsgBufferUp, &lInputMsgBufferUp) && transferMsgs(&lOutputMsgBufferDown, &lInputMsgBufferDown);
+
+#ifdef PRINT
+ printf("Channel %s after: in_up %u, out_up %u, in_dn %u, out_dn %u,\n", name.c_str(), lInputMsgBufferUp.size(), lOutputMsgBufferUp.size(), lInputMsgBufferDown.size(), lOutputMsgBufferDown.size());
+#endif // PRINT
+ return flag_worked;
+
+}
+
+
+void Channel::resetChannel() {
+
+ lInputMsgBufferUp.clear();
+ lOutputMsgBufferUp.clear();
+
+ lInputMsgBufferDown.clear();
+ lOutputMsgBufferDown.clear();
+
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/Channel.h b/SA-EWS_Version_2019.03.27/src/Channel.h
new file mode 100644
index 0000000..2c0850a
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/Channel.h
@@ -0,0 +1,75 @@
+#ifndef CHANNEL_HEADERFILE
+#define CHANNEL_HEADERFILE
+
+#include <list>
+#include "Message.h"
+//#include "Module.h"
+#include "Unit.h"
+
+#define MAX_BUFFER_LENGTH 100
+#define OPEN NULL
+
+using namespace std;
+
+class Channel : public Unit {
+//class Channel : public Module {
+
+ private:
+
+ list<Message*> lInputMsgBufferUp;
+ list<Message*> lOutputMsgBufferUp;
+
+ list<Message*> lInputMsgBufferDown;
+ list<Message*> lOutputMsgBufferDown;
+
+ unsigned int maxBufferLength;
+ unsigned int transferRate;
+
+ void init_channel();
+
+ bool add_msgAtBegin (list<Message*>* buffer, Message* message);
+ bool del_msgAtBegin (list<Message*>* buffer);
+
+ bool add_msgAtEnd (list<Message*>* buffer, Message* message);
+ bool del_msgAtEnd (list<Message*>* buffer);
+
+ public:
+ Channel();
+ Channel(string name);
+
+ bool setMaxBufferLength(unsigned int maxBufferLength);
+ unsigned int getMaxBufferLength();
+
+ unsigned int get_avlInputBufferUp();
+ unsigned int get_avlOutputBufferUp();
+ unsigned int get_avlInputBufferDown();
+ unsigned int get_avlOutputBufferDown();
+
+ bool setTransferRate(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<Message*>* dest_buffer, list<Message*>* src_buffer);
+
+ void resetChannel();
+
+};
+
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/ChannelSlotOfTestbench.cpp b/SA-EWS_Version_2019.03.27/src/ChannelSlotOfTestbench.cpp
new file mode 100644
index 0000000..480ce9c
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/ChannelSlotOfTestbench.cpp
@@ -0,0 +1,31 @@
+#include "ChannelSlotOfTestbench.h"
+
+#include <stdio.h>
+
+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;
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/ChannelSlotOfTestbench.h b/SA-EWS_Version_2019.03.27/src/ChannelSlotOfTestbench.h
new file mode 100644
index 0000000..9adc1b9
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/ChannelSlotOfTestbench.h
@@ -0,0 +1,21 @@
+#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();
+};
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/CombinedConfidenceModule.cpp b/SA-EWS_Version_2019.03.27/src/CombinedConfidenceModule.cpp
new file mode 100644
index 0000000..e69de29
diff --git a/SA-EWS_Version_2019.03.27/src/CombinedConfidenceModule.h b/SA-EWS_Version_2019.03.27/src/CombinedConfidenceModule.h
new file mode 100644
index 0000000..6f70f09
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/CombinedConfidenceModule.h
@@ -0,0 +1 @@
+#pragma once
diff --git a/SA-EWS_Version_2019.03.27/src/ConfidenceHandler.cpp b/SA-EWS_Version_2019.03.27/src/ConfidenceHandler.cpp
new file mode 100644
index 0000000..e0ecaa3
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/ConfidenceHandler.cpp
@@ -0,0 +1,34 @@
+#include "ConfidenceHandler.h"
+#include "printError.h"
+
+void ConfidenceHandler::initConfidenceHandler(char* name) {
+ setName(name);
+}
+
+ConfidenceHandler::ConfidenceHandler() {
+ initConfidenceHandler(NO_NAME);
+}
+
+ConfidenceHandler::ConfidenceHandler(char* name) {
+ initConfidenceHandler(name);
+}
+
+bool ConfidenceHandler::registerConfidenceModule(ConfidenceModule* confidenceModule) {
+ if (confidenceModule != NULL) {
+ for (auto &conMod : lConfidenceModules) {
+ if (conMod == confidenceModule) {
+ return false;
+ }
+ }
+ try {
+ lConfidenceModules.push_back(confidenceModule);
+ return true;
+ }
+ catch (bad_alloc& error) {
+ printError("bad_alloc caught: ", error.what());
+ }
+ }
+ return false;
+}
+
+
diff --git a/SA-EWS_Version_2019.03.27/src/ConfidenceHandler.h b/SA-EWS_Version_2019.03.27/src/ConfidenceHandler.h
new file mode 100644
index 0000000..2fd5faf
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/ConfidenceHandler.h
@@ -0,0 +1,29 @@
+#ifndef CONFIDENCEHANDLER_HEADERFILE
+#define CONFIDENCEHANDLER_HEADERFILE
+
+//#include "Module.h"
+#include "Unit.h"
+#include "ConfidenceModule.h"
+#include <list>
+
+using namespace std;
+
+class ConfidenceHandler : public Unit {
+//class ConfidenceHandler : public Module {
+
+private:
+
+ list<ConfidenceModule*> lConfidenceModules;
+
+ void initConfidenceHandler(char* name);
+
+public:
+ ConfidenceHandler();
+ ConfidenceHandler(char* name);
+
+ bool registerConfidenceModule(ConfidenceModule* confidenceModule);
+
+
+};
+
+#endif
diff --git a/SA-EWS_Version_2019.03.27/src/ConfidenceModule.cpp b/SA-EWS_Version_2019.03.27/src/ConfidenceModule.cpp
new file mode 100644
index 0000000..4b23c20
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/ConfidenceModule.cpp
@@ -0,0 +1,291 @@
+#include "ConfidenceModule.h"
+
+
+
+void ConfidenceModule::initConfidenceModule(char* name) {
+ setName(name);
+}
+
+
+ConfidenceModule::ConfidenceModule() {
+ initConfidenceModule(NO_NAME);
+}
+
+ConfidenceModule::ConfidenceModule(char* name) {
+ initConfidenceModule(name);
+}
+
+LinearFunction* ConfidenceModule::addFunction(bool flagLowerBoundaryExist, float lowerBoundary, bool flagUpperBoundaryExist, float upperBoundary, float inputValue1, float confidenceValue1, float inputValue2, float confidenceValue2) {
+ if (flagLowerBoundaryExist && flagUpperBoundaryExist) {
+ LinearFunction *linearFunction = new LinearFunction();
+
+ if (linearFunction->setDomain(flagLowerBoundaryExist, lowerBoundary, flagUpperBoundaryExist, upperBoundary) && linearFunction->setKandD(inputValue1, confidenceValue1, inputValue2, confidenceValue2)) {
+ if(lLinearFunctions.empty() || ((linearFunction->getDomain()->lowerBoundaryExist() && lLinearFunctions.back()->getDomain()->upperBoundaryExist()) && (linearFunction->getDomain()->getLowerBoundary() == lLinearFunctions.back()->getDomain()->getUpperBoundary()))) {
+ lLinearFunctions.push_back(linearFunction);
+ return linearFunction;
+ }
+ else if ((linearFunction->getDomain()->upperBoundaryExist() && lLinearFunctions.front()->getDomain()->lowerBoundaryExist()) && (linearFunction->getDomain()->getUpperBoundary() == lLinearFunctions.front()->getDomain()->getLowerBoundary())) {
+ lLinearFunctions.push_front(linearFunction);
+ return linearFunction;
+ }
+ }
+ delete linearFunction;
+ }
+ return NULL;
+}
+
+LinearFunction* ConfidenceModule::addFunction(bool flagLowerBoundaryExist, float lowerBoundary, bool flagUpperBoundaryExist, float inputValue1, float confidenceValue1, float inputValue2, float confidenceValue2) {
+ if (flagLowerBoundaryExist && !flagUpperBoundaryExist) {
+ LinearFunction *linearFunction = new LinearFunction();
+ if (linearFunction->setDomain(flagLowerBoundaryExist, lowerBoundary, flagUpperBoundaryExist) && linearFunction->setKandD(inputValue1, confidenceValue1, inputValue2, confidenceValue2)) {
+ if (lLinearFunctions.empty() || ((linearFunction->getDomain()->lowerBoundaryExist() && lLinearFunctions.back()->getDomain()->upperBoundaryExist()) && (linearFunction->getDomain()->getLowerBoundary() == lLinearFunctions.back()->getDomain()->getUpperBoundary()))) {
+ lLinearFunctions.push_back(linearFunction);
+ return linearFunction;
+ }
+ }
+ delete linearFunction;
+ }
+ return NULL;
+}
+
+LinearFunction* ConfidenceModule::addFunction(bool flagLowerBoundaryExist, bool flagUpperBoundaryExist, float upperBoundary, float inputValue1, float confidenceValue1, float inputValue2, float confidenceValue2) {
+ if (!flagLowerBoundaryExist && flagUpperBoundaryExist) {
+ LinearFunction *linearFunction = new LinearFunction();
+
+ if (linearFunction->setDomain(flagLowerBoundaryExist, flagUpperBoundaryExist, upperBoundary) && linearFunction->setKandD(inputValue1, confidenceValue1, inputValue2, confidenceValue2)) {
+ if (lLinearFunctions.empty() || ((linearFunction->getDomain()->upperBoundaryExist() && lLinearFunctions.front()->getDomain()->lowerBoundaryExist()) && (linearFunction->getDomain()->getUpperBoundary() == lLinearFunctions.front()->getDomain()->getLowerBoundary()))) {
+ lLinearFunctions.push_front(linearFunction);
+ return linearFunction;
+ }
+ }
+ delete linearFunction;
+ }
+ return NULL;
+}
+
+LinearFunction* ConfidenceModule::addFunction(bool flagLowerBoundaryExist, bool flagUpperBoundaryExist, float inputValue1, float confidenceValue1, float inputValue2, float confidenceValue2) {
+ if (!flagLowerBoundaryExist && !flagUpperBoundaryExist) {
+ LinearFunction *linearFunction = new LinearFunction();
+
+ if (linearFunction->setDomain(flagLowerBoundaryExist, flagUpperBoundaryExist) && linearFunction->setKandD(inputValue1, confidenceValue1, inputValue2, confidenceValue2)) {
+ if (lLinearFunctions.empty()) {
+ lLinearFunctions.push_back(linearFunction);
+ return linearFunction;
+ }
+ }
+ delete linearFunction;
+ }
+ return NULL;
+}
+
+
+
+
+
+
+
+float ConfidenceModule::limitConfidenceValue(float confidenceValue) {
+ if (confidenceValue < 0)
+ confidenceValue = 0;
+ else if (confidenceValue > 1)
+ confidenceValue = 1;
+ return confidenceValue;
+}
+
+float ConfidenceModule::getConfidenceValue(float value) {
+ float confidenceValue = 0;
+
+ if (value < lLinearFunctions.front()->getDomain()->getLowerBoundary()) {
+
+ }
+ else if (value > lLinearFunctions.front()->getDomain()->getUpperBoundary()) {
+
+ }
+ else {
+ for (auto &linearFunction : lLinearFunctions) {
+ if (value >= linearFunction->getDomain()->getLowerBoundary() && value <= linearFunction->getDomain()->getUpperBoundary()) {
+ confidenceValue = linearFunction->getY(value);
+ }
+ }
+ }
+
+ confidenceValue = limitConfidenceValue(confidenceValue);
+ return confidenceValue;
+}
+
+
+
+
+
+
+
+
+
+/*
+#include "HistoryModule.h"
+
+#include <stdio.h>
+
+//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) {
+setName(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) {
+setName(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/SA-EWS_Version_2019.03.27/src/ConfidenceModule.h b/SA-EWS_Version_2019.03.27/src/ConfidenceModule.h
new file mode 100644
index 0000000..78df912
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/ConfidenceModule.h
@@ -0,0 +1,89 @@
+#ifndef CONFIDENCEMODULE_HEADERFILE
+#define CONFIDENCEMODULE_HEADERFILE
+
+//#include "Module.h"
+#include "Unit.h"
+#include "LinearFunction.h"
+#include <list>
+
+using namespace std;
+
+//class ConfidenceModule : public Module {
+class ConfidenceModule : public Unit {
+
+ private:
+ list<LinearFunction*> lLinearFunctions;
+
+ //float confidenceValue;
+
+ void initConfidenceModule(char* name);
+ float limitConfidenceValue(float confidenceValue);
+
+ public:
+ ConfidenceModule();
+ ConfidenceModule(char* name);
+
+ LinearFunction* addFunction(bool flagLowerBoundaryExist, float lowerBoundary, bool flagUpperBoundaryExist, float upperBoundary, float inputValue1, float confidenceValue1, float inputValue2, float confidenceValue2);
+ LinearFunction* addFunction(bool flagLowerBoundaryExist, float lowerBoundary, bool flagUpperBoundaryExist, float inputValue1, float confidenceValue1, float inputValue2, float confidenceValue2);
+ LinearFunction* addFunction(bool flagLowerBoundaryExist, bool flagUpperBoundaryExist, float upperBoundary, float inputValue1, float confidenceValue1, float inputValue2, float confidenceValue2);
+ LinearFunction* addFunction(bool flagLowerBoundaryExist, bool flagUpperBoundaryExist, float inputValue1, float confidenceValue1, float inputValue2, float confidenceValue2);
+ float getConfidenceValue(float value);
+};
+
+#endif
+
+
+
+/*
+#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();
+
+
+};
+*/
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/ConfidenceModule_old.cpp b/SA-EWS_Version_2019.03.27/src/ConfidenceModule_old.cpp
new file mode 100644
index 0000000..364613d
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/ConfidenceModule_old.cpp
@@ -0,0 +1,169 @@
+/*
+#include "ConfidenceModule.h"
+#include "HistoryModule.h"
+
+#include <stdio.h>
+
+//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) {
+ setName(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) {
+ setName(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/SA-EWS_Version_2019.03.27/src/ConfidenceModule_old.h b/SA-EWS_Version_2019.03.27/src/ConfidenceModule_old.h
new file mode 100644
index 0000000..5d9137e
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/ConfidenceModule_old.h
@@ -0,0 +1,58 @@
+/*
+#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/SA-EWS_Version_2019.03.27/src/Continuous_Average.cpp b/SA-EWS_Version_2019.03.27/src/Continuous_Average.cpp
new file mode 100644
index 0000000..db02b65
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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() {
+ //setName(NO_NAME);
+ init_avg();
+}
+
+/*
+Continuous_Average :: Continuous_Average(char* name) {
+ setName(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/SA-EWS_Version_2019.03.27/src/Continuous_Average.h b/SA-EWS_Version_2019.03.27/src/Continuous_Average.h
new file mode 100644
index 0000000..c228de7
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/CrossReliabilityProfileModule.cpp b/SA-EWS_Version_2019.03.27/src/CrossReliabilityProfileModule.cpp
new file mode 100644
index 0000000..7ef4067
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/CrossReliabilityProfileModule.cpp
@@ -0,0 +1,48 @@
+#include "CrossReliabilityProfileModule.h"
+
+CrossReliabilityProfileModule::CrossReliabilityProfileModule() {
+
+}
+
+CrossReliabilityProfileModule::CrossReliabilityProfileModule(string name) : Unit(name) {
+
+}
+
+CrossReliabilityProfileModule::~CrossReliabilityProfileModule() {
+ //TODO: delete allocated memory
+}
+
+void CrossReliabilityProfileModule::setFunctionBlock(DiscreteFunctionBlock *discreteFunctionBlock, string agent1, string agent2) {
+
+ CrossReliabilityProfile* ReliabilityProfile = new CrossReliabilityProfile();
+
+ ReliabilityProfile->discreteFunctionBlock = discreteFunctionBlock;
+ ReliabilityProfile->agent1 = agent1;
+ ReliabilityProfile->agent2 = agent2;
+
+ crossReliabilityProfiles.push_back(ReliabilityProfile);
+}
+
+/*
+bool CrossReliabilityProfileModule::setFunctionBlocks(LinearFunctionBlock *reliabilityAbsolute, LinearFunctionBlock *reliabilitySlope) {
+
+ if (reliabilityAbsolute && reliabilitySlope) {
+ this->reliabilityAbsolute = reliabilityAbsolute;
+ this->reliabilitySlope = reliabilitySlope;
+ //printf(" > functionsBlocks set\n");
+ return true;
+ }
+
+ return false;
+}
+*/
+
+float CrossReliabilityProfileModule::getCrossReliabilityFromProfile(string agent1, string agent2, int scoreDiff) {
+ for (auto &cRp : crossReliabilityProfiles) {
+ if (cRp->agent1 == agent1 && cRp->agent2 == agent2) {
+ return cRp->discreteFunctionBlock->getY(scoreDiff);
+ }
+ }
+ printf("no Profile found\n");
+ return 0;
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/CrossReliabilityProfileModule.h b/SA-EWS_Version_2019.03.27/src/CrossReliabilityProfileModule.h
new file mode 100644
index 0000000..a8c5318
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/CrossReliabilityProfileModule.h
@@ -0,0 +1,35 @@
+#ifndef CROSSRELIABILITYPROFILEMODULE_HEADERFILE
+#define CROSSRELIABILITYPROFILEMODULE_HEADERFILE
+
+#include "DiscreteFunctionBlock.h"
+
+#include <string>
+
+struct CrossReliabilityProfile {
+ DiscreteFunctionBlock *discreteFunctionBlock;
+ string agent1, agent2;
+};
+
+class CrossReliabilityProfileModule : public Unit {
+
+private:
+ list<CrossReliabilityProfile*> crossReliabilityProfiles;
+
+public:
+ CrossReliabilityProfileModule();
+ CrossReliabilityProfileModule(string name);
+ ~CrossReliabilityProfileModule();
+
+ void setFunctionBlock(DiscreteFunctionBlock *discreteFunctionBlock, string agent1, string agent2);
+
+ float getCrossReliabilityFromProfile(string agent1, string agent2, int scoreDiff);
+
+ /*
+ float getAbsoluteReliability(float actualValue);
+ float getSlopeReliability(float actualValue, float lastValue, unsigned int valueSetCounter);
+ float getRelibility(float actualValue, float lastValue, unsigned int valueSetCounter);
+ */
+};
+
+
+#endif // ! CROSSRELIABILITYPROFILEMODULE_HEADERFILE
diff --git a/SA-EWS_Version_2019.03.27/src/Cross_Confidence_Validator.cpp b/SA-EWS_Version_2019.03.27/src/Cross_Confidence_Validator.cpp
new file mode 100644
index 0000000..969b813
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/Cross_Confidence_Validator.cpp
@@ -0,0 +1,80 @@
+#include "Cross_Confidence_Validator.h"
+
+#include <stdio.h>
+
+//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) {
+ setName(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) {
+ setName(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<num_of_input; in_ix++) {
+
+ //printf("input_is_valid[%i] = %i\n", in_ix, input_is_valid[in_ix]);
+
+ if(input_is_valid[in_ix]) {
+ num_of_valid++;
+
+ if(in_ix != proband) {
+ //TODO: kein hardcoded 0 ... könnte ja auch einen schlechten score bedeuten
+ if(input[in_ix] != 0) {
+ num_of_not_perfect++;
+ }
+ }
+ }
+ }
+
+ //printf("num_of_valid = %u, num_of_not_perfect = %u, divided = %f, \% = %f\n", num_of_valid, num_of_not_perfect, (float)num_of_not_perfect/(float)num_of_valid, percentage_of_inputs_must_be_bad);
+
+ //TO CHECK: passt das?
+ if(num_of_valid == 0) {
+ return false;
+ }
+
+ if((float)num_of_not_perfect/(float)num_of_valid >= 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/SA-EWS_Version_2019.03.27/src/Cross_Confidence_Validator.h b/SA-EWS_Version_2019.03.27/src/Cross_Confidence_Validator.h
new file mode 100644
index 0000000..515a4ae
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/Cross_Confidence_Validator.h
@@ -0,0 +1,26 @@
+#ifndef CROSS_CONFIDENCE_VALIDATOR_HEADERFILE
+#define CROSS_CONFIDENCE_VALIDATOR_HEADERFILE
+
+#include "Unit.h"
+//#include "Module.h"
+
+class Cross_Confidence_Validator : public Unit {
+//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/SA-EWS_Version_2019.03.27/src/DiscreteFunction.cpp b/SA-EWS_Version_2019.03.27/src/DiscreteFunction.cpp
new file mode 100644
index 0000000..1803562
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/DiscreteFunction.cpp
@@ -0,0 +1,19 @@
+#include "DiscreteFunction.h"
+
+#include <stdio.h>
+
+DiscreteFunction::DiscreteFunction(int x, float y) {
+ this->x = x;
+ this->y = y;
+
+ //printf("x = %i / y = %f\n", x, y);
+}
+
+
+int DiscreteFunction::getX() {
+ return x;
+}
+
+float DiscreteFunction::getY() {
+ return y;
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/DiscreteFunction.h b/SA-EWS_Version_2019.03.27/src/DiscreteFunction.h
new file mode 100644
index 0000000..8d26e15
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/DiscreteFunction.h
@@ -0,0 +1,17 @@
+#ifndef DISCRETEFUNCTION_HEADERFILE
+#define DISCRETEFUNCTION_HEADERFILE
+
+class DiscreteFunction {
+
+private:
+ int x;
+ float y;
+public:
+ DiscreteFunction(int x, float y);
+
+ int getX();
+ float getY();
+};
+
+
+#endif // ! DISCRETEFUNCTION_HEADERFILE
diff --git a/SA-EWS_Version_2019.03.27/src/DiscreteFunctionBlock.cpp b/SA-EWS_Version_2019.03.27/src/DiscreteFunctionBlock.cpp
new file mode 100644
index 0000000..01f7597
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/DiscreteFunctionBlock.cpp
@@ -0,0 +1,72 @@
+#include "DiscreteFunctionBlock.h"
+
+#include <iostream> // std::cout
+#include <fstream> // std::ifstream
+
+DiscreteFunctionBlock::DiscreteFunctionBlock() {
+ //printf(" > Linear Function Block created\n");
+}
+
+DiscreteFunctionBlock::DiscreteFunctionBlock(string name) : Unit(name) {
+ //printf(" > %s (id:%u) created\n", name.c_str(), id);
+}
+
+DiscreteFunctionBlock::DiscreteFunctionBlock(string name, string configFilePath) : Unit(name) {
+
+ //printf("load from file\n");
+
+ ifstream configfile(configFilePath);
+ string line;
+
+ bool fileExists = false;
+
+ while (getline(configfile, line))
+ {
+ fileExists = true;
+
+ string token1, token2;
+ size_t pos;
+
+ pos = line.find(";");
+ token1 = line.substr(0, pos);
+ token2 = line.substr(pos + 1);
+
+ if (token1[0] == 'i') {
+ this->defaultValue = stof(token2, NULL);
+
+ //printf("defaultValue: %f\n", this->defaultValue);
+ }
+ else {
+ int x = stoi(token1, NULL);
+ float y = stof(token2, NULL);
+
+ DiscreteFunction *discreteFunction = new DiscreteFunction(x, y);
+
+ addDiscreteFunction(discreteFunction);
+ }
+ }
+
+ if (fileExists == false) {
+ cout << "FILE DOES NOT EXIST!" << endl;
+ getchar();
+ }
+}
+
+
+DiscreteFunctionBlock::~DiscreteFunctionBlock() {
+ //TODO: delete allocated memory
+}
+
+
+float DiscreteFunctionBlock::getY(int x) {
+ for (auto &discreteFunction : lDiscreteFunctions) {
+ if (x == discreteFunction->getX())
+ return discreteFunction->getY();
+ }
+
+ return this->defaultValue;
+}
+
+void DiscreteFunctionBlock::addDiscreteFunction(DiscreteFunction *discreteFunction) {
+ lDiscreteFunctions.push_back(discreteFunction);
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/DiscreteFunctionBlock.h b/SA-EWS_Version_2019.03.27/src/DiscreteFunctionBlock.h
new file mode 100644
index 0000000..187846b
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/DiscreteFunctionBlock.h
@@ -0,0 +1,28 @@
+#ifndef DISCRETEFUNCTIONBLOCK_HEADERFILE
+#define DISCRETEFUNCTIONBLOCK_HEADERFILE
+
+#include <list>
+#include <string>
+
+#include "Unit.h"
+#include "DiscreteFunction.h"
+
+class DiscreteFunctionBlock : public Unit {
+
+private:
+ list<DiscreteFunction*> lDiscreteFunctions;
+ float defaultValue;
+
+public:
+
+ DiscreteFunctionBlock();
+ DiscreteFunctionBlock(string name);
+ DiscreteFunctionBlock(string name, string configFilePath);
+ ~DiscreteFunctionBlock();
+
+ float getY(int x);
+
+ void addDiscreteFunction(DiscreteFunction *discreteFunction);
+};
+
+#endif // ! DISCRETEFUNCTIONBLOCK_HEADERFILE
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/Discrete_Average.cpp b/SA-EWS_Version_2019.03.27/src/Discrete_Average.cpp
new file mode 100644
index 0000000..e69de29
diff --git a/SA-EWS_Version_2019.03.27/src/Discrete_Average.h b/SA-EWS_Version_2019.03.27/src/Discrete_Average.h
new file mode 100644
index 0000000..9ff7a4d
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/Domain.cpp b/SA-EWS_Version_2019.03.27/src/Domain.cpp
new file mode 100644
index 0000000..e6bb290
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/Domain.h b/SA-EWS_Version_2019.03.27/src/Domain.h
new file mode 100644
index 0000000..44d92f9
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/Evaluation.cpp b/SA-EWS_Version_2019.03.27/src/Evaluation.cpp
new file mode 100644
index 0000000..ba5db4e
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/Evaluation.cpp
@@ -0,0 +1,165 @@
+#include "Evaluation.h"
+#include <stdio.h>
+#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_ix<agent.get_number_of_mounted_sensors(); s_ix++) {
+ if(agent.get_flag_mounted_sensor_is_active(s_ix)) {
+ Sensor* sensor = agent.get_mounted_sensor(s_ix);
+ unsigned int number_of_scores = sensor->get_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; score<number_of_scores; score++) {
+ if(!is_it_lower_than_boundary(sensor, score, LOWER_BOUNDARY)) {
+ sensor->set_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; score<number_of_scores; score++) {
+ if(!is_it_higher_than_boundary(sensor, score, UPPER_BOUNDARY)) {
+ sensor->set_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; score<number_of_scores; score++) {
+ if(!is_it_lower_than_hardcoded_boundary(sensor, 0, LOWER_BOUNDARY)) {
+ sensor->set_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; score<number_of_scores; score++) {
+ if(!is_it_higher_than_hardcoded_boundary(sensor, 0, LOWER_BOUNDARY)) {
+ sensor->set_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->getName().c_str(), agent.getName().c_str(), 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_ix<agent.get_number_of_mounted_sensors(); s_ix++) {
+ if(agent.get_flag_mounted_sensor_is_active(s_ix)) {
+ score += agent.get_mounted_sensor(s_ix)->get_score();
+ }
+ }
+ for(unsigned int sa_ix=0; sa_ix<agent.get_num_of_mounted_slaveagents(); sa_ix++) {
+ if(agent.get_flag_mounted_subagent_is_active(sa_ix)) {
+ printf("aktiv - subscore: %i\n", agent.get_mounted_subagent(sa_ix)->get_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; sensor<MAX_NUM_OF_SENSORS; sensor++) {
+ if(agent->get_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; sensor<MAX_NUM_OF_SENSORS; sensor++) {
+ if(agent->get_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; sensor<MAX_NUM_OF_SENSORS; sensor++) {
+ if(agent->get_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/SA-EWS_Version_2019.03.27/src/Evaluation.h b/SA-EWS_Version_2019.03.27/src/Evaluation.h
new file mode 100644
index 0000000..3281084
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/Evaluation.h
@@ -0,0 +1,24 @@
+#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/SA-EWS_Version_2019.03.27/src/ExtremeValue.cpp b/SA-EWS_Version_2019.03.27/src/ExtremeValue.cpp
new file mode 100644
index 0000000..f11f05b
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/ExtremeValue.h b/SA-EWS_Version_2019.03.27/src/ExtremeValue.h
new file mode 100644
index 0000000..46756b7
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/FilterModule.cpp b/SA-EWS_Version_2019.03.27/src/FilterModule.cpp
new file mode 100644
index 0000000..10f9e9c
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/FilterModule.cpp
@@ -0,0 +1,13 @@
+#include "FilterModule.h"
+
+void FilterModule::initFilterModule(char* name) {
+
+}
+
+FilterModule::FilterModule() {
+ initFilterModule(NO_NAME);
+}
+
+FilterModule::FilterModule(char* name) {
+ initFilterModule(name);
+}
diff --git a/SA-EWS_Version_2019.03.27/src/FilterModule.h b/SA-EWS_Version_2019.03.27/src/FilterModule.h
new file mode 100644
index 0000000..b733b0e
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/FilterModule.h
@@ -0,0 +1,26 @@
+#ifndef FILTERMODULE_HEADERFILE
+#define FILTERMODULE_HEADERFILE
+
+//#include "Module.h"
+#include "Unit.h"
+
+//using namespace std;
+
+
+//https://kiritchatterjee.wordpress.com/2014/11/10/a-simple-digital-low-pass-filter-in-c/
+//https://cardinalpeak.com/blog/a-c-class-to-implement-low-pass-high-pass-and-band-pass-filters/
+
+
+//class FilterModule : public Module {
+class FilterModule : public Unit{
+
+ private:
+
+ void initFilterModule(char* name);
+
+ public:
+ FilterModule();
+ FilterModule(char* name);
+};
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/HandlerOfAgent.cpp b/SA-EWS_Version_2019.03.27/src/HandlerOfAgent.cpp
new file mode 100644
index 0000000..e69de29
diff --git a/SA-EWS_Version_2019.03.27/src/HandlerOfAgent.h b/SA-EWS_Version_2019.03.27/src/HandlerOfAgent.h
new file mode 100644
index 0000000..a05a9e2
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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<SlaveAgentSlotOfAgent*> 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/SA-EWS_Version_2019.03.27/src/Header.h b/SA-EWS_Version_2019.03.27/src/Header.h
new file mode 100644
index 0000000..6f70f09
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/Header.h
@@ -0,0 +1 @@
+#pragma once
diff --git a/SA-EWS_Version_2019.03.27/src/HistoryController.cpp b/SA-EWS_Version_2019.03.27/src/HistoryController.cpp
new file mode 100644
index 0000000..f922cf3
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/HistoryController.cpp
@@ -0,0 +1,61 @@
+#include "HistoryController.h"
+#include "printError.h"
+
+HistoryController::HistoryController() {
+
+}
+
+bool HistoryController::mountHistoryModule(HistoryModule* historyModule) {
+ if (historyModule != NULL) {
+ if (!historyModuleIsMounted(historyModule)) {
+ try {
+ vMountedHistoryModules.push_back(historyModule);
+ return true;
+ }
+ catch (bad_alloc& error) {
+ printError("bad_alloc caught: ", error.what());
+ }
+ }
+ }
+ return false;
+}
+
+bool HistoryController::historyModuleIsMounted(HistoryModule* historyModule) {
+ if (historyModule) {
+ for (auto &mountedHistoryModule : vMountedHistoryModules)
+ if (mountedHistoryModule == historyModule)
+ return true;
+ }
+ return false;
+}
+
+unsigned int HistoryController::getHistoryModuleSlotNumber(HistoryModule* historyModule) {
+ unsigned int slotNumber = 0;
+ for (auto &mountedHistoryModule : vMountedHistoryModules) {
+ if (mountedHistoryModule == historyModule) {
+ return slotNumber;
+ }
+ slotNumber++;
+ }
+ return NULL;
+}
+
+bool HistoryController::demountSensor(HistoryModule* historyModule) {
+ if (historyModule) {
+ if (historyModuleIsMounted(historyModule)) {
+ vMountedHistoryModules.erase(vMountedHistoryModules.begin() + getHistoryModuleSlotNumber(historyModule));
+ return true;
+ }
+ }
+ return false;
+}
+
+
+bool HistoryController::storeAllValues() {
+ for (auto &historyModule : vMountedHistoryModules) {
+ historyModule->storeValue();
+ }
+
+
+ return false;
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/HistoryController.h b/SA-EWS_Version_2019.03.27/src/HistoryController.h
new file mode 100644
index 0000000..eb9fb53
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/HistoryController.h
@@ -0,0 +1,25 @@
+#ifndef HISTORYCONTROLLER_HEADERFILE
+#define HISTORYCONTROLLER_HEADERFILE
+
+#include "HistoryModule.h"
+#include "Unit.h"
+#include <vector>
+
+class HistoryController : public Unit {
+
+private:
+ vector<HistoryModule*> vMountedHistoryModules;
+
+public:
+ HistoryController();
+
+ bool mountHistoryModule(HistoryModule* historyModule);
+ bool historyModuleIsMounted(HistoryModule* historyModule);
+ unsigned int getHistoryModuleSlotNumber(HistoryModule* historyModule);
+ bool demountSensor(HistoryModule* historyModule);
+
+ bool storeAllValues();
+
+};
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/HistoryEntry.cpp b/SA-EWS_Version_2019.03.27/src/HistoryEntry.cpp
new file mode 100644
index 0000000..6c5f188
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/HistoryEntry.cpp
@@ -0,0 +1,18 @@
+#include "HistoryEntry.h"
+
+HistoryEntry::HistoryEntry() {
+
+}
+
+HistoryEntry::HistoryEntry(float entryValue) {
+ this->entryValue = entryValue;
+}
+
+
+void HistoryEntry::set_entryValue(float entryValue) {
+ this->entryValue = entryValue;
+}
+
+float HistoryEntry::get_entryValue() {
+ return entryValue;
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/HistoryEntry.h b/SA-EWS_Version_2019.03.27/src/HistoryEntry.h
new file mode 100644
index 0000000..7b2d545
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/HistoryEntry.h
@@ -0,0 +1,20 @@
+#ifndef HISTORYENTRY_HEADERFILE
+#define HISTORYENTRY_HEADERFILE
+
+//TODO: save also time stamp or something similar
+class HistoryEntry {
+
+ private:
+ float entryValue;
+
+ public:
+ HistoryEntry();
+ HistoryEntry(float entryValue);
+
+ void set_entryValue(float entryValue);
+ float get_entryValue();
+
+};
+
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/HistoryModule.cpp b/SA-EWS_Version_2019.03.27/src/HistoryModule.cpp
new file mode 100644
index 0000000..71dc37d
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/HistoryModule.cpp
@@ -0,0 +1,143 @@
+#include "HistoryModule.h"
+#include "printError.h"
+#include <stdio.h>
+
+//using namespace std;
+
+void HistoryModule :: initHistoryModule(unsigned int maximumHistoryLength) {
+ //TODO: what to do if maximumHistoryLength to big?
+ this->maximumHistoryLength = maximumHistoryLength;
+ delimitationMode = DELIMITATE_MODE_FIFO;
+}
+
+
+
+HistoryModule::HistoryModule(unsigned int maximumHistoryLength) {
+ setName(NO_NAME);
+ initHistoryModule(maximumHistoryLength);
+}
+
+HistoryModule::HistoryModule(char* name, unsigned int maximumHistoryLength) {
+ setName(name);
+ initHistoryModule(maximumHistoryLength);
+}
+
+
+
+bool HistoryModule::setMaximumHistoryLength(unsigned int maximumHistoryLength) {
+ if(maximumHistoryLength <= lHistory.max_size()) {
+ this->maximumHistoryLength = maximumHistoryLength;
+ return true;
+ }
+ return false;
+}
+
+unsigned int HistoryModule ::getMaximumHistoryLength() {
+ return maximumHistoryLength;
+}
+
+
+
+bool HistoryModule :: setDelimitationMode(int delimitationMode) {
+ if(delimitationMode > DELIMITATE_MODE_LBOUND && delimitationMode < DELIMITATE_MODE_UBOUND) {
+ this->delimitationMode = delimitationMode;
+ return true;
+ }
+ return false;
+}
+
+int HistoryModule :: getDelimitationMode() {
+ return delimitationMode;
+}
+
+
+
+unsigned int HistoryModule :: getNumberOfEntries() {
+ return lHistory.size();
+}
+
+
+
+bool HistoryModule::setObservationPointer(float* observationPointer) {
+ if (observationPointer) {
+ this->observationPointerFloat = observationPointer;
+ printf("setPointer: %p - %p\n", observationPointerFloat, observationPointer);
+ getchar();
+
+ return true;
+ }
+ return false;
+}
+
+bool HistoryModule::setObservationPointer(int* observationPointer) {
+ if (observationPointer) {
+ this->observationPointerInt = observationPointer;
+ return true;
+ }
+ return false;
+}
+
+bool HistoryModule::deleteObservationPointer() {
+ if((!observationPointerFloat && observationPointerInt) || (observationPointerFloat && !observationPointerInt)) {
+ observationPointerFloat = NULL;
+ observationPointerInt = NULL;
+ return true;
+ }
+ return false;
+}
+
+
+list<HistoryEntry*>* HistoryModule::getObservationPointer() {
+ return &lHistory;
+}
+
+bool HistoryModule::storeValue() {
+ //TODO: other deleting/saving strategies
+ printf("1\n");
+ //while loop instead of if, for the case of overstepping maximumHistoryLength too far
+ while (lHistory.size() > maximumHistoryLength) {
+ if (!deleteOldestEntry())
+ break;
+ }
+ printf("2\n");
+ //TODO: do it also for non-float variables
+
+ if (!observationPointerFloat) {
+ printf("na!\n");
+
+ }
+ else {
+ printf("ja! %p\n", observationPointerFloat);
+ }
+ getchar();
+
+
+
+ HistoryEntry* historyEntry = new (nothrow) HistoryEntry(*observationPointerFloat);
+ if (historyEntry) {
+ try {
+ lHistory.push_back(historyEntry);
+ return true;
+ }
+ catch (bad_alloc& error) {
+ printError("bad_alloc caught: ", error.what());
+ }
+ printf("3\n");
+ }
+
+ //XXX - Only for testing
+ printf("History:\n");
+ for (auto &entry : lHistory) {
+ printf("%f\n", entry->get_entryValue());
+ }
+ printf("\n");
+
+}
+
+bool HistoryModule::deleteOldestEntry() {
+ if (lHistory.size() > 0) {
+ lHistory.pop_front();
+ return true;
+ }
+ return false;
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/HistoryModule.h b/SA-EWS_Version_2019.03.27/src/HistoryModule.h
new file mode 100644
index 0000000..24af743
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/HistoryModule.h
@@ -0,0 +1,59 @@
+#ifndef HISTORYMODULE_HEADERFILE
+#define HISTORYMODULE_HEADERFILE
+
+#include "HistoryEntry.h"
+//#include "Module.h"
+#include "Unit.h"
+#include <list>
+
+/*
+#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 {
+class HistoryModule : public Unit {
+
+ private:
+ list<HistoryEntry*> lHistory;
+ unsigned int maximumHistoryLength;
+ int delimitationMode;
+
+ void initHistoryModule(unsigned int maximumHistoryLength);
+
+ float* observationPointerFloat;
+ int* observationPointerInt;
+
+ public:
+ HistoryModule(unsigned int maximumHistoryLength);
+ HistoryModule(char* name, unsigned int maximumHistoryLength);
+
+ bool setMaximumHistoryLength(unsigned int maximumHistoryLength);
+ unsigned int getMaximumHistoryLength();
+
+ bool setDelimitationMode(int delimitationMode);
+ int getDelimitationMode();
+
+ unsigned int getNumberOfEntries();
+
+ bool setObservationPointer(float* observationPointer);
+ bool setObservationPointer(int* observationPointer);
+ bool deleteObservationPointer();
+
+ list<HistoryEntry*>* getObservationPointer();
+
+ bool storeValue();
+ bool deleteOldestEntry();
+
+};
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/LinearFunction.cpp b/SA-EWS_Version_2019.03.27/src/LinearFunction.cpp
new file mode 100644
index 0000000..e376d19
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/LinearFunction.cpp
@@ -0,0 +1,89 @@
+#include "LinearFunction.h"
+#include <stdio.h>
+
+
+LinearFunction::LinearFunction() {
+ //printf(" > Linear Function created\n");
+}
+
+//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;
+}
+
+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;
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/LinearFunction.h b/SA-EWS_Version_2019.03.27/src/LinearFunction.h
new file mode 100644
index 0000000..b63b6ba
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/LinearFunction.h
@@ -0,0 +1,34 @@
+#ifndef LINEARFUNCTION_HEADERFILE
+#define LINEARFUNCTION_HEADERFILE
+
+#include "Domain.h"
+
+class LinearFunction {
+
+ private:
+ Domain domain;
+ float k, d;
+
+ public:
+ LinearFunction();
+
+ 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();
+
+ 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
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/LinearFunctionBlock.cpp b/SA-EWS_Version_2019.03.27/src/LinearFunctionBlock.cpp
new file mode 100644
index 0000000..693b722
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/LinearFunctionBlock.cpp
@@ -0,0 +1,231 @@
+#include "LinearFunctionBlock.h"
+#include <iostream> // std::cout
+#include <fstream> // std::ifstream
+
+using namespace std;
+
+LinearFunctionBlock::LinearFunctionBlock() {
+ //printf(" > Linear Function Block created\n");
+}
+
+LinearFunctionBlock::LinearFunctionBlock(string name) : Unit(name) {
+ //printf(" > %s (id:%u) created\n", name.c_str(), id);
+}
+
+LinearFunctionBlock::LinearFunctionBlock(string name, string configFilePath) : Unit(name) {
+ //printf(" > %s (id:%u) created\n", name.c_str(), id);
+
+ ifstream configfile(configFilePath);
+ string line;
+
+ bool fileExists = false;
+
+ while (getline(configfile, line))
+ {
+ fileExists = true;
+
+ bool lbIncl, ubIncl;
+ bool x1inf, x2inf;
+ string token;
+ float x1, x2, kOrY1, dOrY2;
+ bool kD;
+
+ size_t pos1, pos2, pos3, pos4;
+
+ if (line[0] == '[')
+ lbIncl = true;
+ else if (line[0] == ']')
+ lbIncl = false;
+ else
+ continue;
+
+ pos1 = line.find(",");
+ if (pos1 != string::npos) {
+ if (pos1 < 2)
+ continue;
+ }
+ else
+ continue;
+
+ token = line.substr(1, pos1 - 1);
+
+ if (token.length() == 1 && token[0] == 'i')
+ x1inf = true;
+ else {
+ x1inf = false;
+ x1 = stof(token, NULL);
+ }
+
+ pos2 = line.find(";");
+ if (pos2 != string::npos)
+ if (pos2 >= 5)
+ if (line[pos2 - 1] == ']')
+ ubIncl = true;
+ else if (line[pos2 - 1] == '[')
+ ubIncl = false;
+ else
+ continue;
+ else
+ continue;
+ else
+ continue;
+
+ token = line.substr(pos1+1, pos2-pos1-2);
+
+ if (token.length() == 1 && token[0] == 'i') {
+ x2inf = true;
+ }
+ else {
+ x2inf = false;
+ x2 = stof(token, NULL);
+ }
+
+ if (pos2 < line.length()) {
+
+ if (line[pos2 + 1] == '(') {
+
+ pos4 = line.find(")", pos2);
+
+ if (pos4 != string::npos) {
+ if (pos4 < pos2 + 5)
+ continue;
+ kD = true;
+ }
+ else
+ continue;
+ }
+ else if (line[pos2 + 1] == '[') {
+
+ pos4 = line.find("]", pos2);
+
+ if (pos4 != string::npos) {
+ if (pos4 < pos2 + 5)
+ continue;
+ kD = false;
+ }
+ else
+ continue;
+ }
+ else
+ continue;
+
+ pos3 = line.find(",", pos2);
+
+ if (pos3 != string::npos) {
+ if (pos3 < pos2 + 3)
+ continue;
+ }
+ else
+ continue;
+
+ token = line.substr(pos2 + 2, pos3 - pos2 - 2);
+ kOrY1 = stof(token, NULL);
+
+ token = line.substr(pos3 + 1, pos4 - pos3 - 1);
+ dOrY2 = stof(token, NULL);
+
+
+ //TODO: consider unsteady functions
+ //TODO: differentiate between -infinity and +infinity
+ LinearFunction *linearFunction = new LinearFunction();
+ if (lbIncl == false && ubIncl == false)
+ linearFunction->setDomain(false, false);
+ else if(lbIncl == false)
+ linearFunction->setDomain(false, true, x2);
+ else if (ubIncl == false)
+ linearFunction->setDomain(true, x1, false);
+ else
+ linearFunction->setDomain(true, x1, true, x2);
+
+
+
+ if (kD == true)
+ linearFunction->setKandD(kOrY1, dOrY2);
+ else
+ linearFunction->setKandD(x1, kOrY1, x2, dOrY2);
+
+ addLinearFunction(linearFunction);
+ }
+ }
+
+ if (fileExists == false) {
+ cout << "FILE DOES NOT EXIST!" << endl;
+ getchar();
+ }
+
+ //printFunction();
+}
+
+
+LinearFunctionBlock::~LinearFunctionBlock() {
+ //TODO: delete allocated memory
+}
+
+//NOTE: for this time being, linear functions have to be filled beginning from lowest x value
+bool LinearFunctionBlock::addLinearFunction(LinearFunction *linearFunction) {
+ if (lLinearFunctions.empty()) {
+ //printf("empty\n");
+ if (!(linearFunction->getDomain()->lowerBoundaryExist())) {
+ lLinearFunctions.push_back(linearFunction);
+ //printf(" - added function\n");
+ return true;
+ }
+ }
+ else
+ {
+ //printf("nicht empty\n");
+ if (lLinearFunctions.back()->getDomain()->upperBoundaryExist() && linearFunction->getDomain()->lowerBoundaryExist()) {
+ //printf("last function ub = %f, new function lb = %f\n", lLinearFunctions.back()->getDomain()->getUpperBoundary(), linearFunction->getDomain()->getLowerBoundary());
+ if (lLinearFunctions.back()->getDomain()->getUpperBoundary() == linearFunction->getDomain()->getLowerBoundary()) {
+ lLinearFunctions.push_back(linearFunction);
+ //printf(" - added function\n");
+ return true;
+ }
+ }
+ }
+
+ printf(" - couldn't add function\n");
+ return false;
+}
+
+
+//TODO: jump discontinuity -> user must have the probability to set the value there
+float LinearFunctionBlock::getY(float x) {
+ for (auto &linearFunction : lLinearFunctions) {
+ //printf("x\n");
+ 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("hier?\n");
+
+ //TODO: default return value is maybe not the best
+ return 0;
+}
+
+
+void LinearFunctionBlock::printFunction() {
+
+ if (lLinearFunctions.empty())
+ cout << "is leer!" << endl;
+
+ for (auto &linearFunction : lLinearFunctions) {
+ printf("y = k*%f%+f for %+f < y < %+f\n", linearFunction->getK(), linearFunction->getD(), linearFunction->getDomain()->getLowerBoundary(), linearFunction->getDomain()->getUpperBoundary());
+ }
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/LinearFunctionBlock.h b/SA-EWS_Version_2019.03.27/src/LinearFunctionBlock.h
new file mode 100644
index 0000000..3b3b29f
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/LinearFunctionBlock.h
@@ -0,0 +1,31 @@
+#ifndef LINEARFUNCTIONBLOCK_HEADERFILE
+#define LINEARFUNCTIONBLOCK_HEADERFILE
+
+#include <list>
+#include <string>
+
+#include "LinearFunction.h"
+#include "Unit.h"
+
+using namespace std;
+
+class LinearFunctionBlock : public Unit{
+
+private:
+ //CHECK: list, vector or other container?
+ list<LinearFunction*> lLinearFunctions;
+
+public:
+ LinearFunctionBlock();
+ LinearFunctionBlock(string name);
+ LinearFunctionBlock(string name, string configFilePath);
+ ~LinearFunctionBlock();
+
+ bool addLinearFunction(LinearFunction *linearFunction);
+
+ float getY(float x);
+
+ void printFunction();
+};
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/Lookuptable.cpp b/SA-EWS_Version_2019.03.27/src/Lookuptable.cpp
new file mode 100644
index 0000000..ae36690
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/Lookuptable.cpp
@@ -0,0 +1,82 @@
+#include "Lookuptable.h"
+#include <stdio.h>
+
+Lookuptable :: Lookuptable() {
+ //setName(NO_NAME);
+ num_of_ranges = 0;
+}
+
+Lookuptable :: Lookuptable(string name) : Unit(name){
+ //setName(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<num_of_ranges; r_ix++) {
+
+ //printf("list_of_ranges[r_ix].get_lower_boundary() = %f\nlist_of_ranges[num_of_ranges].get_upper_boundary() = %f\n\n", list_of_ranges[r_ix].get_lower_boundary(), list_of_ranges[num_of_ranges].get_upper_boundary());
+ if(list_of_ranges[r_ix].get_lower_boundary() == list_of_ranges[num_of_ranges].get_upper_boundary()) {
+ //printf("drinnen1\n");
+
+ list_of_ranges[r_ix].set_range_below(&list_of_ranges[num_of_ranges]);
+ list_of_ranges[num_of_ranges].set_range_upon(&list_of_ranges[r_ix]);
+
+ }
+
+ //printf("list_of_ranges[r_ix].get_upper_boundary() = %f\nlist_of_ranges[num_of_ranges].get_lower_boundary() = %f\n\n", list_of_ranges[r_ix].get_upper_boundary(), list_of_ranges[num_of_ranges].get_lower_boundary());
+ if(list_of_ranges[r_ix].get_upper_boundary() == list_of_ranges[num_of_ranges].get_lower_boundary()) {
+ //printf("drinnen2\n");
+
+ list_of_ranges[r_ix].set_range_upon(&list_of_ranges[num_of_ranges]);
+ list_of_ranges[num_of_ranges].set_range_below(&list_of_ranges[r_ix]);
+
+ }
+ }
+
+ num_of_ranges++;
+
+ return true;
+ }
+ return false;
+}
+
+bool Lookuptable :: check_sort_and_activate() {
+ if(num_of_ranges > 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<num_of_ranges; i++) {
+ if(list_of_ranges[i].get_range_below() != nullptr)
+ printf("%i ist unten verbunden\n", i);
+ else
+ printf("%i ist unten NICHT verbunden\n", i);
+
+ if(list_of_ranges[i].get_range_upon() != nullptr)
+ printf("%i ist oben verbunden\n", i);
+ else
+ printf("%i ist oben NICHT verbunden\n", i);
+ }
+ printf("blub\n");
+ getchar();
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/Lookuptable.h b/SA-EWS_Version_2019.03.27/src/Lookuptable.h
new file mode 100644
index 0000000..6218a15
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/Lookuptable.h
@@ -0,0 +1,42 @@
+#ifndef LOOKUPTABLE_HEADERFILE
+#define LOOKUPTABLE_HEADERFILE
+
+#include <string>
+
+//#include "Module.h"
+#include "Unit.h"
+#include "Range.h"
+
+#define MAX_NUM_OF_RANGES 10
+
+#define INCLUDED true
+#define EXCLUDED false
+
+//class Lookuptable : public Module {
+class Lookuptable : public Unit {
+
+ private:
+ bool lookuptable_is_correct_and_active;
+ unsigned int num_of_ranges;
+
+ Range list_of_ranges[MAX_NUM_OF_RANGES];
+
+ public:
+ Lookuptable();
+ Lookuptable(string name);
+
+ bool add_range_to_lookuptable(int score, float lower_boundary, bool flag_lower_boundary_included, float upper_boundary, bool flag_upper_boundary_included);
+
+ bool check_sort_and_activate();
+
+ bool get_lookuptable_is_correct_and_active();
+
+ int get_score(float input);
+
+
+
+ //testing/debugging functions
+ void printf_ranges();
+};
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/MasterAgentHandlerOfAgent.cpp b/SA-EWS_Version_2019.03.27/src/MasterAgentHandlerOfAgent.cpp
new file mode 100644
index 0000000..e0eec99
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/MasterAgentHandlerOfAgent.cpp
@@ -0,0 +1,135 @@
+#include "MasterAgentHandlerOfAgent.h"
+
+#include "instruction_set_architecture.h"
+
+#include <iostream>
+
+#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<get_occSendBuffer(); i++)
+ while(get_occSendBuffer() > 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();
+ //printf("send something\n");
+ }
+ }
+ }
+ }
+ return false;
+}
+
+
+bool MasterAgentHandlerOfAgent::read_masterAgentValues() {
+
+ Channel* channel = masterAgentSlotOfAgent->get_comPort();
+
+ if (channel != NULL) {
+ int msg;
+ if (channel->get_MsgDown(&msg)) {
+ if (ISA_SuggestedAbstractedSensoryDataAndReliability) {
+ //printf("habe das richtige empfangen!\n");
+ while (channel->get_MsgDown(&msg)) {
+ float inputValue;
+ if (channel->get_MsgDown(&inputValue)) {
+ masterAgentSlotOfAgent->addSuggestedScore(msg, inputValue);
+ //cout << "added!!!!!!!!!!!!!" << endl;
+ }
+ else {
+ std::cout << "check das mal ab" << endl;
+ getchar();
+ return false;
+ }
+ }
+ //slaveAgentSlotOfAgent->increaseTimeSinceScoreChange();
+ return true;
+
+ }
+
+ }
+ }
+ return false;
+}
+
+void MasterAgentHandlerOfAgent::clearSuggestedScores() {
+ masterAgentSlotOfAgent->clearSuggestedScores();
+ //possibleScores.clear();
+}
+
+
+vector<PossibleScore*>* MasterAgentHandlerOfAgent::getSuggestedScores() {
+ return masterAgentSlotOfAgent->getSuggestedScores();
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/MasterAgentHandlerOfAgent.h b/SA-EWS_Version_2019.03.27/src/MasterAgentHandlerOfAgent.h
new file mode 100644
index 0000000..9da48ad
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/MasterAgentHandlerOfAgent.h
@@ -0,0 +1,42 @@
+#ifndef MASTERAGENTHANDLEROFAGENT_HEADERFILE
+#define MASTERAGENTHANDLEROFAGENT_HEADERFILE
+
+#include "MasterAgentSlotOfAgent.h"
+#include "Unit.h"
+
+#include <vector>
+#include "ScoreConfidenceModule.h"
+
+class MasterAgentHandlerOfAgent : public Unit {
+
+ private:
+ MasterAgentSlotOfAgent* masterAgentSlotOfAgent;
+
+ list<Message*> 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();
+
+ bool read_masterAgentValues();
+ void clearSuggestedScores();
+ vector<PossibleScore*>* getSuggestedScores();
+
+
+};
+
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/MasterAgentSlotOfAgent.cpp b/SA-EWS_Version_2019.03.27/src/MasterAgentSlotOfAgent.cpp
new file mode 100644
index 0000000..6123cbb
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/MasterAgentSlotOfAgent.cpp
@@ -0,0 +1,28 @@
+#include "MasterAgentSlotOfAgent.h"
+
+
+MasterAgentSlotOfAgent :: MasterAgentSlotOfAgent() {
+ suggestedScores = new vector<PossibleScore*>();
+}
+
+
+void MasterAgentSlotOfAgent::addSuggestedScore(int score, float reliability) {
+
+ PossibleScore* possibleScore = new PossibleScore;
+ possibleScore->score = score;
+ possibleScore->confOrRel = reliability; //=reliability!
+
+ //printf("bekommen: score = %i, reliability = %.2f\n", score, reliability);
+
+ suggestedScores->push_back(possibleScore);
+}
+
+void MasterAgentSlotOfAgent::clearSuggestedScores() {
+ //printf("size suggested before: %u\n", suggestedScores->size());
+ suggestedScores->clear();
+ //printf("size suggested after: %u\n", suggestedScores->size());
+}
+
+vector<PossibleScore*>* MasterAgentSlotOfAgent::getSuggestedScores() {
+ return suggestedScores;
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/MasterAgentSlotOfAgent.h b/SA-EWS_Version_2019.03.27/src/MasterAgentSlotOfAgent.h
new file mode 100644
index 0000000..098a7ec
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/MasterAgentSlotOfAgent.h
@@ -0,0 +1,22 @@
+#ifndef MASTERAGENTSLOTOFAGENT_HEADERFILE
+#define MASTERAGENTSLOTOFAGENT_HEADERFILE
+
+#include "SlotOfAgent.h"
+#include "ScoreConfidenceModule.h"
+
+class MasterAgentSlotOfAgent : public SlotOfAgent {
+
+ private:
+ MasterAgentSlotOfAgent* masterAgentSlotOfAgent;
+ vector<PossibleScore*>* suggestedScores;
+
+ public:
+ MasterAgentSlotOfAgent();
+ void addSuggestedScore(int score, float reliability);
+ void clearSuggestedScores();
+ vector<PossibleScore*>* getSuggestedScores();
+
+};
+
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/MaximumValue.cpp b/SA-EWS_Version_2019.03.27/src/MaximumValue.cpp
new file mode 100644
index 0000000..a709f21
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/MaximumValue.h b/SA-EWS_Version_2019.03.27/src/MaximumValue.h
new file mode 100644
index 0000000..520ea3b
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/Message.cpp b/SA-EWS_Version_2019.03.27/src/Message.cpp
new file mode 100644
index 0000000..469c6eb
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/Message.cpp
@@ -0,0 +1,58 @@
+#include "Message.h"
+
+#include <stdio.h>
+
+#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/SA-EWS_Version_2019.03.27/src/Message.h b/SA-EWS_Version_2019.03.27/src/Message.h
new file mode 100644
index 0000000..6e14395
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/MinumumValue.cpp b/SA-EWS_Version_2019.03.27/src/MinumumValue.cpp
new file mode 100644
index 0000000..5739c73
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/MinumumValue.h b/SA-EWS_Version_2019.03.27/src/MinumumValue.h
new file mode 100644
index 0000000..7228e91
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/Module.cpp b/SA-EWS_Version_2019.03.27/src/Module.cpp
new file mode 100644
index 0000000..753cd49
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/Module.cpp
@@ -0,0 +1,21 @@
+#include "Module.h"
+/*
+#include <string.h>
+
+Module :: Module() {
+ setName(NO_NAME);
+}
+
+Module :: Module(char* name) {
+ setName(name);
+}
+
+
+void Module :: setName(char* name) {
+ strncpy_s (this->name, name, MAX_LENGTH_NAME);
+}
+
+char* Module :: getName().c_str() {
+ return this->name;
+}
+*/
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/Module.h b/SA-EWS_Version_2019.03.27/src/Module.h
new file mode 100644
index 0000000..d2fc909
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/Module.h
@@ -0,0 +1,21 @@
+#ifndef MODULE_HEADERFILE
+#define MODULE_HEADERFILE
+/*
+#include "Unit.h"
+
+class Module : public Unit {
+
+ protected:
+ char name[MAX_LENGTH_NAME];
+
+ public:
+ Module();
+ Module(char* name);
+
+ void setName(char* name);
+ char* getName().c_str();
+
+};
+*/
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/Node.cpp b/SA-EWS_Version_2019.03.27/src/Node.cpp
new file mode 100644
index 0000000..27399c5
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/Node.cpp
@@ -0,0 +1,24 @@
+#include "Node.h"
+
+#define MAX_WORKCYCLE 4294967295
+
+Node :: Node() {
+ workingCycle = 1;
+}
+
+Node::Node(string name) : Unit(name) {
+ workingCycle = 1;
+}
+
+bool Node :: setWorkCycle(unsigned int workingCycle) {
+ if(workingCycle <= MAX_WORKCYCLE) {
+ this->workingCycle = workingCycle;
+ return true;
+ }
+ return false;
+}
+
+unsigned int Node :: getWorkCycle() {
+ return workingCycle;
+}
+
diff --git a/SA-EWS_Version_2019.03.27/src/Node.h b/SA-EWS_Version_2019.03.27/src/Node.h
new file mode 100644
index 0000000..d0a74f0
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/Node.h
@@ -0,0 +1,21 @@
+#ifndef NODE_HEADERFILE
+#define NODE_HEADERFILE
+
+#include "Unit.h"
+
+class Node : public Unit {
+
+ private:
+ unsigned int workingCycle;
+
+ public:
+ Node();
+ Node(string name);
+
+ bool setWorkCycle(unsigned int workingCycle);
+ unsigned int getWorkCycle();
+
+};
+
+#endif
+
diff --git a/SA-EWS_Version_2019.03.27/src/Range.cpp b/SA-EWS_Version_2019.03.27/src/Range.cpp
new file mode 100644
index 0000000..5977fd2
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/Range.cpp
@@ -0,0 +1,224 @@
+#include "Range.h"
+#include <stdio.h>
+
+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/SA-EWS_Version_2019.03.27/src/Range.h b/SA-EWS_Version_2019.03.27/src/Range.h
new file mode 100644
index 0000000..1c38cb8
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/ReliabilityModule.cpp b/SA-EWS_Version_2019.03.27/src/ReliabilityModule.cpp
new file mode 100644
index 0000000..cc8c2aa
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/ReliabilityModule.cpp
@@ -0,0 +1,75 @@
+#include "ReliabilityModule.h"
+#include <algorithm>
+
+//#define PRINT
+
+ReliabilityModule::ReliabilityModule() {
+ reliabilityAbsolute = NULL;
+ reliabilitySlope = NULL;
+ //printf(" > Reliability Module created\n");
+}
+
+ReliabilityModule::ReliabilityModule(string name) : Unit(name) {
+ //printf(" > %s (id:%u) created\n", name.c_str(), id);
+}
+
+ReliabilityModule::~ReliabilityModule() {
+ //TODO: delete allocated memory
+}
+
+bool ReliabilityModule::setFunctionBlocks(LinearFunctionBlock *reliabilityAbsolute, LinearFunctionBlock *reliabilitySlope) {
+ if (reliabilityAbsolute && reliabilitySlope) {
+ this->reliabilityAbsolute = reliabilityAbsolute;
+ this->reliabilitySlope = reliabilitySlope;
+ //printf(" > functionsBlocks set\n");
+ return true;
+ }
+ return false;
+}
+
+float ReliabilityModule::getAbsoluteReliability(float actualValue) {
+ float rAbs = reliabilityAbsolute->getY(actualValue);
+#ifdef PRINT
+ printf("relAbs = %f - ", rAbs);
+#endif // PRINT
+ return rAbs;
+}
+
+float ReliabilityModule::getSlopeReliability(float actualValue, float lastValue, unsigned int valueSetCounter/*, int actualScore, int lastScore*/) {
+
+ float rSlo = reliabilitySlope->getY((lastValue - actualValue) / (float)valueSetCounter);
+
+ /*
+ //NEW NEW NEW
+ if (actualScore == lastScore)
+ rSlo = 1;
+ */
+#ifdef PRINT
+ printf("relSlo = %f - ", rSlo);
+#endif // PRINT
+ return rSlo;
+}
+
+float ReliabilityModule::getRelibility(float actualValue, float lastValue, unsigned int valueSetCounter/*, int actualScore, int lastScore*/) {
+
+ float rel, relAbs, relSlo;
+
+ relAbs = getAbsoluteReliability(actualValue);
+ relSlo = getSlopeReliability(actualValue, lastValue, valueSetCounter/*, actualScore, lastScore*/);
+
+ //calculate signal input reliability
+ //NOTE: options would be multiply, average, AND (best to worst: average = AND > multiply)
+ //rel = relAbs * relSlo;
+ //rel = (relAbs + relSlo)/2;
+ rel = std::min(relAbs, relSlo);
+
+
+ return rel;
+
+ /*
+ if (relAbs <= relSlo)
+ return relAbs;
+ else
+ return relSlo;
+ */
+}
diff --git a/SA-EWS_Version_2019.03.27/src/ReliabilityModule.h b/SA-EWS_Version_2019.03.27/src/ReliabilityModule.h
new file mode 100644
index 0000000..ab6c183
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/ReliabilityModule.h
@@ -0,0 +1,26 @@
+#ifndef RELIABILITYMODULE_HEADERFILE
+#define RELIABILITYMODULE_HEADERFILE
+
+#include "LinearFunctionBlock.h"
+
+using namespace std;
+
+class ReliabilityModule : public Unit {
+
+private:
+ LinearFunctionBlock *reliabilityAbsolute, *reliabilitySlope;
+
+public:
+ ReliabilityModule();
+ ReliabilityModule(string name);
+ ~ReliabilityModule();
+
+ bool setFunctionBlocks(LinearFunctionBlock *reliabilityAbsolute, LinearFunctionBlock *reliabilitySlope);
+
+ float getAbsoluteReliability(float actualValue);
+ float getSlopeReliability(float actualValue, float lastValue, unsigned int valueSetCounter/*, int actualScore, int lastScore*/);
+ float getRelibility(float actualValue, float lastValue, unsigned int valueSetCounter/*, int actualScore, int lastScore*/);
+
+};
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/ScoreAndConfidence.cpp b/SA-EWS_Version_2019.03.27/src/ScoreAndConfidence.cpp
new file mode 100644
index 0000000..9446a35
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/ScoreAndConfidence.cpp
@@ -0,0 +1,14 @@
+#include "ScoreAndConfidence.h"
+
+ScoreAndConfidence::ScoreAndConfidence(int score, float confidence) {
+ this->score = score;
+ this->confidence = confidence;
+}
+
+int ScoreAndConfidence::getScore() {
+ return score;
+}
+
+float ScoreAndConfidence::getConfidence() {
+ return confidence;
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/ScoreAndConfidence.h b/SA-EWS_Version_2019.03.27/src/ScoreAndConfidence.h
new file mode 100644
index 0000000..57e551e
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/ScoreAndConfidence.h
@@ -0,0 +1,17 @@
+#ifndef SCOREANDCONFIDENCE_HEADERFILE
+#define SCOREANDCONFIDENCE_HEADERFILE
+
+class ScoreAndConfidence {
+
+private:
+ int score;
+ float confidence;
+
+public:
+ ScoreAndConfidence(int score, float confidence);
+
+ int getScore();
+ float getConfidence();
+};
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/ScoreConfidence.cpp b/SA-EWS_Version_2019.03.27/src/ScoreConfidence.cpp
new file mode 100644
index 0000000..a7e86f2
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/ScoreConfidence.cpp
@@ -0,0 +1,28 @@
+#include "ScoreConfidence.h"
+
+ScoreConfidence::ScoreConfidence(LinearFunctionBlock* linearFunctionBlock, int score) {
+ this->linearFunctionBlock = linearFunctionBlock;
+ this->score = score;
+}
+
+int ScoreConfidence::getScore() {
+ return score;
+}
+
+float ScoreConfidence::getConfidence(float value) {
+ return linearFunctionBlock->getY(value);
+}
+
+LinearFunctionBlock* ScoreConfidence::getLinearFunctionBlock() {
+ return linearFunctionBlock;
+}
+
+/*
+unsigned int ScoreConfidence::getNumberOfScoresWithConfidence() {
+
+}
+
+bool ScoreConfidence::getScoreAndConfidence(unsigned int rank, int* score, float* confidence) {
+
+}
+*/
diff --git a/SA-EWS_Version_2019.03.27/src/ScoreConfidence.h b/SA-EWS_Version_2019.03.27/src/ScoreConfidence.h
new file mode 100644
index 0000000..5fbcd85
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/ScoreConfidence.h
@@ -0,0 +1,26 @@
+#ifndef SCORECONFIDENCE_HEADERFILE
+#define SCORECONFIDENCE_HEADERFILE
+
+#include "LinearFunctionBlock.h"
+
+class ScoreConfidence {
+
+private:
+ LinearFunctionBlock* linearFunctionBlock;
+ int score;
+
+public:
+ ScoreConfidence(LinearFunctionBlock* linearFunctionBlock, int score);
+
+ int getScore();
+ float getConfidence(float value);
+ LinearFunctionBlock* getLinearFunctionBlock();
+
+ //unsigned int getNumberOfScoresWithConfidence();
+ //bool getScoreAndConfidence(unsigned int rank, int* score, float* confidence);
+};
+
+
+
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/ScoreConfidenceModule.cpp b/SA-EWS_Version_2019.03.27/src/ScoreConfidenceModule.cpp
new file mode 100644
index 0000000..a3218df
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/ScoreConfidenceModule.cpp
@@ -0,0 +1,93 @@
+#include "ScoreConfidenceModule.h"
+
+#include <algorithm>
+#include <iostream>
+
+ScoreConfidenceModule::ScoreConfidenceModule() {
+
+}
+
+bool ScoreConfidenceModule::addScoreConfidence(LinearFunctionBlock* linearFunctionBlock, int score) {
+ if (linearFunctionBlock) {
+ for (auto &sc : scoreConfidences)
+ if (sc->getScore() == score)
+ return false;
+
+ ScoreConfidence* scoreConfidence = new (nothrow) ScoreConfidence(linearFunctionBlock, score);
+
+ if (scoreConfidence) {
+ scoreConfidences.push_back(scoreConfidence);
+ return true;
+ }
+ }
+
+ return false;
+}
+
+
+//TODO: include RANK
+bool ScoreConfidenceModule::getScoreWithConfidence(float inputValue, unsigned int rank, int* score, float* confidence) {
+
+ if (rank < scoreConfidences.size()) {
+
+ bool scoreFound = false;
+ int scoreWithHighestConfidence;
+ float highestConfidence = 0;
+
+ for (auto &sC : scoreConfidences) {
+ float confidence = sC->getConfidence(inputValue);
+ if (confidence > highestConfidence) {
+ scoreFound = true;
+ scoreWithHighestConfidence = sC->getScore();
+ highestConfidence = confidence;
+ }
+ }
+
+ if (scoreFound) {
+ *score = scoreWithHighestConfidence;
+ *confidence = highestConfidence;
+
+ return true;
+ }
+ }
+
+ return false;
+}
+
+
+bool compareByConfidence(PossibleScore* a, PossibleScore* b)
+{
+ return a->confOrRel > b->confOrRel;
+}
+
+vector<PossibleScore*>* ScoreConfidenceModule::getScoresWithConfidences(float inputValue) {
+
+ //vector<PossibleScore*> possibleScores;
+ vector<PossibleScore*>* possibleScores = new vector<PossibleScore*>();
+
+
+ //printf("\n");
+
+ for (auto &sC : scoreConfidences) {
+
+ //printf("runde\n");
+
+ float confidence = sC->getConfidence(inputValue);
+ //if (confidence > 0) {
+
+ //printf("higher\n");
+
+ PossibleScore* possibleScore = new PossibleScore();
+ possibleScore->score = sC->getScore();
+ possibleScore->confOrRel = confidence;
+ possibleScores->push_back(possibleScore);
+ //}
+ }
+
+ //sort: highest confidence first - maybe useless because EWS agent checks all of them
+ std::sort(possibleScores->begin(), possibleScores->end(), compareByConfidence);
+
+ return possibleScores;
+}
+
+
diff --git a/SA-EWS_Version_2019.03.27/src/ScoreConfidenceModule.h b/SA-EWS_Version_2019.03.27/src/ScoreConfidenceModule.h
new file mode 100644
index 0000000..e6555d2
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/ScoreConfidenceModule.h
@@ -0,0 +1,39 @@
+#ifndef SCORECONFIDENCEMODULE_HEADERFILE
+#define SCORECONFIDENCEMODULE_HEADERFILE
+
+#include <vector>
+#include "ScoreConfidence.h"
+#include "ScoreAndConfidence.h"
+
+
+struct PossibleScore {
+ int score;
+ float confOrRel;
+};
+
+class ScoreConfidenceModule {
+
+private:
+ vector<ScoreConfidence*> scoreConfidences;
+
+ //bool compareByConfidence(ScoreAndConfidence* a, ScoreAndConfidence* b);
+
+public:
+ ScoreConfidenceModule();
+
+ bool addScoreConfidence(LinearFunctionBlock* linearFunctionBlock, int score);
+
+ bool getScoreWithConfidence(float inputValue, unsigned int rank, int* score, float* confidence);
+
+
+ vector<PossibleScore*>* getScoresWithConfidences(float inputValue);
+
+
+
+ //float getY(float x);
+};
+
+
+
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/Sensor.cpp b/SA-EWS_Version_2019.03.27/src/Sensor.cpp
new file mode 100644
index 0000000..28573c5
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/Sensor.cpp
@@ -0,0 +1,177 @@
+#include "Sensor.h"
+#include <stdio.h>
+
+//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() {
+ setName(NO_NAME);
+ initialize_sensor();
+}
+
+Sensor :: Sensor(string name) : Node(name) {
+ setName(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.c_str(), 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 < getWorkCycle())
+ 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;
+}
+
+void Sensor::resetSensor() {
+
+ this->flag_sensor_value_is_valid = INVALID;
+ this->flag_sensor_value_has_changed = NO;
+ this->flag_send_value_only_when_changed = NO;
+
+ workingCycleCounter = 1;
+
+}
+
diff --git a/SA-EWS_Version_2019.03.27/src/Sensor.h b/SA-EWS_Version_2019.03.27/src/Sensor.h
new file mode 100644
index 0000000..16df1d5
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/Sensor.h
@@ -0,0 +1,121 @@
+#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(string 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();
+
+ void resetSensor();
+
+};
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/SensorHandlerOfAgent.cpp b/SA-EWS_Version_2019.03.27/src/SensorHandlerOfAgent.cpp
new file mode 100644
index 0000000..f7f0d71
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/SensorHandlerOfAgent.cpp
@@ -0,0 +1,198 @@
+#include "SensorHandlerOfAgent.h"
+#include <stdio.h>
+#include "printError.h"
+
+#include <algorithm>
+
+#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
+SensorSlotOfAgent* 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);
+ return sensorSlotOfAgent;
+ }
+ else {
+ printError("Max number of mounted sensors is already reached!");
+ }
+ }
+ catch(bad_alloc& error) {
+ printError("bad_alloc caught: ", error.what());
+ }
+ }
+ else {
+ printError("Input port is no set!");
+ vMountedSensors.pop_back(); //TODO: check if it is right?!?!
+ }
+ }
+ else {
+ printError("Couldn't create SensorSlot!");
+ }
+ return NULL;
+}
+
+//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);
+ sensorSlotOfAgent->resetValueSetCounter();
+ //printf("%s - counter: %u\n", sensorSlotOfAgent->get_comPort()->getName().c_str(), sensorSlotOfAgent->getValueSetCounter());
+ return true;
+ }
+ else {
+ sensorSlotOfAgent->increaseValueSetCounter();
+ //printf("%s - counter: %u\n", sensorSlotOfAgent->get_comPort()->getName().c_str(), sensorSlotOfAgent->getValueSetCounter());
+ }
+ }
+ }
+ 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<SensorSlotOfAgent*>* SensorHandlerOfAgent:: get_vMountedSensors() {
+ return &vMountedSensors;
+}
+
+void SensorHandlerOfAgent::resetHandler() {
+ for (auto sensorSlot : vMountedSensors) {
+ if (sensorSlot)
+ sensorSlot->resetSlot();
+ }
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/SensorHandlerOfAgent.h b/SA-EWS_Version_2019.03.27/src/SensorHandlerOfAgent.h
new file mode 100644
index 0000000..1c3987c
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/SensorHandlerOfAgent.h
@@ -0,0 +1,56 @@
+#ifndef SENSORHANDLEROFAGENT_HEADERFILE
+#define SENSORHANDLEROFAGENT_HEADERFILE
+
+#include <vector>
+#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<SensorSlotOfAgent*> vMountedSensors;
+ unsigned int maxNumOf_mountedSensors;
+
+ void init_sensorHandler();
+
+ public:
+ SensorHandlerOfAgent();
+ //SensorHandler(char* name);
+
+ SensorSlotOfAgent* 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<SensorSlotOfAgent*>* get_vMountedSensors();
+
+
+ void resetHandler();
+
+};
+
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/SensorSlotOfAgent.cpp b/SA-EWS_Version_2019.03.27/src/SensorSlotOfAgent.cpp
new file mode 100644
index 0000000..5993e44
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/SensorSlotOfAgent.cpp
@@ -0,0 +1,123 @@
+#include <stdio.h>
+#include "SensorSlotOfAgent.h"
+
+
+//#define PRINT
+
+
+SensorSlotOfAgent :: SensorSlotOfAgent() {
+ flagSensorValueIsSet = false;
+ flagSensorValueHasChanged = false;
+
+ //SHORTCUT/WORKAUROUND -> TODO: make this better!
+ bool flagLastSensorValueIsSet = false;
+ valueSetCounter = 1;
+ historyCounter = 0;
+}
+
+void SensorSlotOfAgent :: set_sensorValue(float sensorValue) {
+
+ if (flagSensorValueIsSet) {
+
+ /*BEGIN GLÄTTUNG*/
+ //SHORTCUT/WORKAUROUND -> TODO: make this better!
+ if (historyCounter > 4) {
+ for (int i = 1; i <= 4; i++) {
+ tempHistory[i - 1] = tempHistory[i];
+ }
+ }
+
+ if (historyCounter <= 4) {
+ tempHistory[historyCounter] = this->sensorValue;
+ historyCounter++;
+ }
+ else {
+ tempHistory[4] = this->sensorValue;
+ }
+
+ float avg = 0;
+
+ for (int i = 0; i < historyCounter; i++) {
+ avg = avg + tempHistory[i];
+ }
+
+ avg = avg / historyCounter;
+
+ if (valueSetCounter < 2) {
+ lastSensorValue = avg;
+ }
+ else {
+ lastSensorValue = this->sensorValue;
+ }
+ /*ENDE GLÄTTUNG*/
+
+ //lastSensorValue = this->sensorValue; //DAS WAR URSPRÜNGLICH
+ flagLastSensorValueIsSet = true;
+ }
+
+ if (this->sensorValue != sensorValue) {
+ flagSensorValueHasChanged = true;
+ }
+
+ this->sensorValue = sensorValue;
+
+ flagSensorValueIsSet = true;
+}
+
+bool SensorSlotOfAgent :: get_sensorValue(float* sensorValue) {
+ if(flagSensorValueIsSet == true) {
+ *sensorValue = this->sensorValue;
+ return true;
+ }
+ return false;
+}
+
+bool SensorSlotOfAgent::getPreviousSensorValue(float* lastSensorValue) {
+ if (flagLastSensorValueIsSet == true) {
+ //printf("der is schon gesetzt!\n");
+ *lastSensorValue = this->lastSensorValue;
+ return true;
+ }
+ return false;
+}
+
+bool SensorSlotOfAgent :: get_flagSensorValueIsSet() {
+ return flagSensorValueIsSet;
+}
+
+bool SensorSlotOfAgent :: get_flagSensorValueHasChanged() {
+ return flagSensorValueHasChanged;
+}
+
+//SHORTCUT/WORKAUROUND -> TODO: make this better!
+void SensorSlotOfAgent::increaseValueSetCounter() {
+ valueSetCounter++;
+}
+
+void SensorSlotOfAgent::resetValueSetCounter() {
+ valueSetCounter = 1;
+}
+
+unsigned int SensorSlotOfAgent::getValueSetCounter() {
+ return valueSetCounter;
+}
+
+void SensorSlotOfAgent::resetSlot() {
+
+ flagSensorValueIsSet = false;
+ flagSensorValueHasChanged = false;
+
+ //SHORTCUT/WORKAUROUND -> TODO: make this better!
+ flagLastSensorValueIsSet = false;
+ valueSetCounter = 1;
+ historyCounter = 0;
+
+
+
+ sensorValue = 0;
+
+
+ //SHORTCUT/WORKAUROUND -> TODO: make this better!
+ lastSensorValue = 0;
+
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/SensorSlotOfAgent.h b/SA-EWS_Version_2019.03.27/src/SensorSlotOfAgent.h
new file mode 100644
index 0000000..4e21457
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/SensorSlotOfAgent.h
@@ -0,0 +1,40 @@
+#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;
+
+ //SHORTCUT/WORKAUROUND -> TODO: make this better!
+ float lastSensorValue;
+ bool flagLastSensorValueIsSet;
+ unsigned int valueSetCounter;
+ float tempHistory[5];
+ unsigned int historyCounter = 0;
+
+
+ public:
+ SensorSlotOfAgent();
+
+ void set_sensorValue(float sensorValue);
+ bool get_sensorValue(float* sensorValue);
+ bool getPreviousSensorValue(float* lastSensorValue);
+
+ bool get_flagSensorValueIsSet();
+ bool get_flagSensorValueHasChanged();
+
+ //SHORTCUT/WORKAUROUND -> TODO: make this better!
+ void increaseValueSetCounter();
+ void resetValueSetCounter();
+ unsigned int getValueSetCounter();
+
+ void resetSlot();
+};
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/SensorSlotOfTestbench.cpp b/SA-EWS_Version_2019.03.27/src/SensorSlotOfTestbench.cpp
new file mode 100644
index 0000000..1c7757a
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/SensorSlotOfTestbench.cpp
@@ -0,0 +1,51 @@
+#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;
+}
+
diff --git a/SA-EWS_Version_2019.03.27/src/SensorSlotOfTestbench.h b/SA-EWS_Version_2019.03.27/src/SensorSlotOfTestbench.h
new file mode 100644
index 0000000..46865d3
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/SensorSlotOfTestbench.h
@@ -0,0 +1,27 @@
+#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();
+};
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/Setup.cpp b/SA-EWS_Version_2019.03.27/src/Setup.cpp
new file mode 100644
index 0000000..cfbfd5f
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/Setup.cpp
@@ -0,0 +1,205 @@
+#include "Setup.hpp"
+
+#include <iostream>
+#include "rlutil.h"
+
+#include "Agent.h"
+#include "Sensor.h"
+
+//#define PRINT
+
+using namespace rlutil;
+
+Setup::Setup() {
+
+}
+
+Setup::~Setup() {
+
+}
+
+template<typename Unit> Unit* Setup::createUnit(string name) {
+
+ Unit *unit = new(nothrow)Unit(name);
+
+ if (unit) {
+#ifdef PRINT
+ setColor(LIGHTGREEN);
+ cout << " > ";
+ setColor(LIGHTCYAN);
+ cout << unit->getName() + " ";
+ setColor(GREY);
+ cout << "id:";
+ setColor(YELLOW);
+ cout << unit->getId();
+ setColor(LIGHTGREEN);
+ cout << " created" << endl;
+ setColor(GREY);
+#endif
+ }
+ else {
+#ifdef PRINT
+ setColor(LIGHTRED);
+ cout << " > Couldn't create " + unit->getName() << endl;
+ setColor(GREY);
+#endif
+ }
+
+ return unit;
+}
+template Agent* Setup::createUnit<Agent>(string name);
+template Channel* Setup::createUnit<Channel>(string name);
+template Sensor* Setup::createUnit<Sensor>(string name);
+
+
+
+template<typename Node> void Setup::setWorkCycle(Node *node, unsigned int workcycle) {
+
+ if (node) {
+ if (node->setWorkCycle(workcycle)) {
+#ifdef PRINT
+ setColor(LIGHTGREEN);
+ cout << " > ";
+ setColor(GREY);
+ cout << "Work Cycle of ";
+ setColor(LIGHTCYAN);
+ cout << node->getName() + " ";
+ setColor(GREY);
+ cout << "(id:";
+ setColor(YELLOW);
+ cout << node->getId();
+ setColor(GREY);
+ cout << ") ";
+ setColor(LIGHTGREEN);
+ cout << "set ";
+ setColor(GREY);
+ cout << "to ";
+ setColor(WHITE);
+ cout << workcycle << endl;
+ setColor(GREY);
+#endif
+ }
+ else {
+#ifdef PRINT
+ setColor(LIGHTRED);
+ cout << " > Couldn't set Work Cycle of ";
+ setColor(LIGHTCYAN);
+ cout << node->getName() + " ";
+ setColor(GREY);
+ cout << "(id:";
+ setColor(YELLOW);
+ cout << node->getId();
+ setColor(GREY);
+ cout << ") " << endl;
+#endif
+ }
+ }
+ else {
+#ifdef PRINT
+ setColor(LIGHTRED);
+ cout << " > Node is unknown!" << endl;
+ setColor(GREY);
+#endif
+ }
+}
+template void Setup::setWorkCycle<Agent>(Agent *agent, unsigned int workcycle);
+template void Setup::setWorkCycle<Sensor>(Sensor *sensor, unsigned int workcycle);
+
+
+/*
+template<typename Unit1, typename Unit2> void Setup::mountUnitInUnit(Unit *master, Unit2 *slave, Channel *channel) {
+
+
+
+
+
+
+
+
+}
+//template<> void Setup::mountUnitInUnit<Agent, Sensor>(Agent *master, Sensor *slave, Channel *channel);
+*/
+
+
+void Setup::setTransferRate(Channel *channel, unsigned int transferRate) {
+ if (channel->setTransferRate(transferRate)) {
+#ifdef PRINT
+ setColor(LIGHTGREEN);
+ cout << " > ";
+ setColor(GREY);
+ cout << "Transfer Rate of ";
+ setColor(LIGHTCYAN);
+ cout << channel->getName() + " ";
+ setColor(GREY);
+ cout << "(id:";
+ setColor(YELLOW);
+ cout << channel->getId();
+ setColor(GREY);
+ cout << ") ";
+ setColor(LIGHTGREEN);
+ cout << "set ";
+ setColor(GREY);
+ cout << "to ";
+ setColor(WHITE);
+ cout << transferRate;
+ setColor(GREY);
+ cout << " (0=immediately)" << endl;
+#endif
+ }
+ else {
+#ifdef PRINT
+ setColor(LIGHTRED);
+ cout << " > Couldn't set Transfer Rate of ";
+ setColor(LIGHTCYAN);
+ cout << channel->getName() + " ";
+ setColor(GREY);
+ cout << "(id:";
+ setColor(YELLOW);
+ cout << channel->getId();
+ setColor(GREY);
+ cout << ") " << endl;
+#endif
+ }
+}
+
+
+
+void Setup::setMaxBufferLength(Channel *channel, unsigned int maxBufferLength) {
+ if (channel->setMaxBufferLength(maxBufferLength)) {
+#ifdef PRINT
+ setColor(LIGHTGREEN);
+ cout << " > ";
+ setColor(GREY);
+ cout << "Max. Buffer Length of ";
+ setColor(LIGHTCYAN);
+ cout << channel->getName() + " ";
+ setColor(GREY);
+ cout << "(id:";
+ setColor(YELLOW);
+ cout << channel->getId();
+ setColor(GREY);
+ cout << ") ";
+ setColor(LIGHTGREEN);
+ cout << "set ";
+ setColor(GREY);
+ cout << "to ";
+ setColor(WHITE);
+ cout << maxBufferLength << endl;
+ setColor(GREY);
+#endif
+ }
+ else {
+#ifdef PRINT
+ setColor(LIGHTRED);
+ cout << " > Couldn't set max. Buffer Length of ";
+ setColor(LIGHTCYAN);
+ cout << channel->getName() + " ";
+ setColor(GREY);
+ cout << "(id:";
+ setColor(YELLOW);
+ cout << channel->getId();
+ setColor(GREY);
+ cout << ") " << endl;
+#endif
+ }
+}
diff --git a/SA-EWS_Version_2019.03.27/src/Setup.hpp b/SA-EWS_Version_2019.03.27/src/Setup.hpp
new file mode 100644
index 0000000..2eb932b
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/Setup.hpp
@@ -0,0 +1,36 @@
+#ifndef SETUP_HEADER
+#define SETUP_HEADER
+
+#include <string>
+
+#include "Channel.h"
+
+
+using namespace std;
+
+class Setup {
+
+public:
+ Setup();
+ ~Setup();
+
+ template<typename Unit> Unit* createUnit(string name);
+ template<typename Node> void setWorkCycle(Node *node, unsigned int workcycle);
+
+
+
+
+
+ template<typename Unit1, typename Unit2> void mountUnitInUnit(Unit *master, Unit2 *slave, Channel *channel);
+
+
+
+
+
+
+ void setTransferRate(Channel *channel, unsigned int transferRate);
+ void setMaxBufferLength(Channel *channel, unsigned int maxBufferLength);
+
+};
+
+#endif // !SETUP_HEADER
diff --git a/SA-EWS_Version_2019.03.27/src/SetupAgent.cpp b/SA-EWS_Version_2019.03.27/src/SetupAgent.cpp
new file mode 100644
index 0000000..73bf364
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/SetupAgent.cpp
@@ -0,0 +1,346 @@
+#include "SetupAgent.h"
+
+SetupAgent::SetupAgent() {
+ agent = NULL;
+ masterAgent = NULL;
+ channel = NULL;
+ agentSlot = NULL;
+}
+
+SetupAgent::SetupAgent(Agent* agent) {
+ this->agent = agent;
+ masterAgent = NULL;
+ channel = NULL;
+ agentSlot = NULL;
+}
+
+SetupAgent::SetupAgent(Agent* agent, Channel* channel) {
+ this->agent = agent;
+ masterAgent = NULL;
+ this->channel = channel;
+ agentSlot = NULL;
+}
+
+
+
+bool SetupAgent::setAgent(Agent* agent) {
+ if (agent) {
+ this->agent = agent;
+ return true;
+ }
+ return false;
+}
+
+bool SetupAgent::masterAgentIsSet() {
+ if (masterAgent == NULL)
+ return false;
+ return true;
+}
+
+Agent* SetupAgent::getAgent() {
+ return agent;
+}
+
+
+
+bool SetupAgent::setMasterAgent(Agent* masterAgent, Channel* channel) {
+ if (!this->masterAgent && masterAgent) {
+ if (this->agent->get_masterAgentHandlerOfAgent()->mount_masterAgentIntoSlaveAgentSlot(channel)) {
+ this->masterAgent = masterAgent;
+ return true;
+ }
+ }
+ return false;
+}
+
+Agent* SetupAgent::getMasterAgent() {
+ return masterAgent;
+}
+
+
+
+bool SetupAgent::mountAgent(Agent* agent, Channel* channel) {
+ if (this->agent && agent && channel) {
+ //Next line is because one agent is not allowed too be mounted twice
+ if (!agentIsMounted(agent)) {
+ SetupAgent* mountedAgent = new SetupAgent(agent, channel);
+
+ try {
+ vMountedAgents.push_back(mountedAgent);
+ }
+ catch (bad_alloc& error) {
+ delete mountedAgent;
+ return false;
+ }
+
+ //Mount it for real
+ SlaveAgentSlotOfAgent* agentSlot = this->agent->get_slaveAgentHandlerOfAgent()->mount_slaveAgentIntoSlaveAgentSlot(channel);
+
+ printf("Mounting: %p\n", agentSlot->getObservationPointer());
+ getchar();
+
+ if (agentSlot) {
+ if (mountedAgent->setAgentSlot(agentSlot)) {
+ return true;
+ }
+ else {
+ delete mountedAgent;
+ return false;
+ }
+ }
+ else {
+ delete mountedAgent;
+ return false;
+ }
+ }
+ }
+ return false;
+}
+
+bool SetupAgent::agentIsMounted(Agent* agent) {
+ for (auto &mountedAgent : vMountedAgents)
+ if (mountedAgent->getAgent() == agent)
+ return true;
+ return false;
+}
+
+SetupAgent* SetupAgent::getMountedAgent(Agent* agent) {
+ for (auto &mountedAgent : vMountedAgents)
+ if (mountedAgent->getAgent() == agent)
+ return mountedAgent;
+ return NULL;
+}
+
+SetupAgent* SetupAgent::getMountedAgent(Channel* channel) {
+ for (auto &mountedAgent : vMountedAgents)
+ if (mountedAgent->getChannel() == channel)
+ return mountedAgent;
+ return NULL;
+}
+
+
+/*
+bool SetupAgent::mountAgent(Agent* agent, Channel* channel) {
+ if (this->agent && agent && channel) {
+ if (!agentIsMounted(agent)) {
+ SetupMountedAgent* mountedAgent = new SetupMountedAgent(agent, channel);
+
+ try {
+ vMountedAgents.push_back(mountedAgent);
+ }
+ catch (bad_alloc& error) {
+ delete mountedAgent;
+ return false;
+ }
+
+ //Mount it for real
+ SlaveAgentSlotOfAgent* agentSlot = this->agent->get_slaveAgentHandlerOfAgent()->mount_slaveAgentIntoSlaveAgentSlot(channel);
+ if (agentSlot) {
+ if (mountedAgent->setAgentSlot(agentSlot)) {
+ return true;
+ }
+ else {
+ delete mountedAgent;
+ return false;
+ }
+ }
+ else {
+ delete mountedAgent;
+ return false;
+ }
+ }
+ }
+ return false;
+}
+
+bool SetupAgent::agentIsMounted(Agent* agent) {
+ for (auto &mountedAgent : vMountedAgents)
+ if (mountedAgent->getAgent() == agent)
+ return true;
+ return false;
+}
+
+SetupMountedAgent* SetupAgent::getMountedAgent(Agent* agent) {
+ for (auto &mountedAgent : vMountedAgents)
+ if (mountedAgent->getAgent() == agent)
+ return mountedAgent;
+ return NULL;
+}
+
+SetupMountedAgent* SetupAgent::getMountedAgent(Channel* channel) {
+ for (auto &mountedAgent : vMountedAgents)
+ if (mountedAgent->getChannel() == channel)
+ return mountedAgent;
+ return NULL;
+}
+*/
+
+
+bool SetupAgent::mountSensor(Sensor* sensor, Channel* channel) {
+ if (this->agent && sensor && channel) {
+ if (!sensorIsMounted(sensor)) {
+ SetupMountedSensor* mountedSensor = new SetupMountedSensor(sensor, channel);
+
+ try {
+ vMountedSensors.push_back(mountedSensor);
+ }
+ catch (bad_alloc& error) {
+ delete mountedSensor;
+ return false;
+ }
+
+ SensorSlotOfAgent* sensorSlot = this->agent->get_sensorHandlerOfAgent()->mount_sensorIntoSensorSlot(channel); //Mount it for real
+
+ if (sensorSlot) {
+ if (mountedSensor->setSensorSlot(sensorSlot)) {
+ return true;
+ }
+ else {
+ delete mountedSensor;
+ return false;
+ }
+ }
+ else {
+ delete mountedSensor;
+ return false;
+ }
+ }
+ }
+ return false;
+}
+
+bool SetupAgent::sensorIsMounted(Sensor* sensor) {
+ for (auto &mountedSensor : vMountedSensors)
+ if (mountedSensor->getSensor() == sensor)
+ return true;
+ return false;
+}
+
+SetupMountedSensor* SetupAgent::getMountedSensor(Sensor* sensor) {
+ for (auto &mountedSensor : vMountedSensors)
+ if (mountedSensor->getSensor() == sensor)
+ return mountedSensor;
+ return NULL;
+}
+
+SetupMountedSensor* SetupAgent::getMountedSensor(Channel* channel) {
+ for (auto &mountedSensor : vMountedSensors)
+ if (mountedSensor->getChannel() == channel)
+ return mountedSensor;
+ return NULL;
+}
+
+
+
+bool SetupAgent::mountHistoryModule(SetupMountedHistoryModule* mountedHistoryModule) {
+ if (this->agent && mountedHistoryModule) {
+ if (!historyModuleIsMounted(mountedHistoryModule)) {
+ //SetupMountedHistoryModule* mountedHistoryModule = new SetupMountedHistoryModule(historyModule);
+ try {
+ vMountedHistoryModules.push_back(mountedHistoryModule);
+ }
+ catch (bad_alloc& error) {
+ delete mountedHistoryModule;
+ return false;
+ }
+
+ //Next line mount it for real
+ if (this->agent->getHistoryController()->mountHistoryModule(mountedHistoryModule->getHistoryModule())) {
+ return mountedHistoryModule->setHostAgent(this->agent);
+ }
+ }
+ }
+ return false;
+}
+
+bool SetupAgent::historyModuleIsMounted(HistoryModule* historyModule) {
+ for (auto &mountedHistoryModule : vMountedHistoryModules)
+ if (mountedHistoryModule->getHistoryModule() == historyModule)
+ return true;
+ return false;
+}
+
+bool SetupAgent::historyModuleIsMounted(SetupMountedHistoryModule* historyModule) {
+ for (auto &mountedHistoryModule : vMountedHistoryModules)
+ if (mountedHistoryModule == historyModule)
+ return true;
+ return false;
+}
+
+SetupMountedHistoryModule* SetupAgent::getMountedHistoryModule(HistoryModule* historyModule) {
+ for (auto &mountedHistoryModule : vMountedHistoryModules)
+ if (mountedHistoryModule->getHistoryModule() == historyModule)
+ return mountedHistoryModule;
+ return NULL;
+}
+
+
+
+bool SetupAgent::mountStabilityModule(SetupStabilityModule* mountedStabilityModule) {
+ if (this->agent && mountedStabilityModule) {
+ if (!stabilityModuleIsMounted(mountedStabilityModule)) {
+ try {
+ vMountedStabilityModules.push_back(mountedStabilityModule);
+ }
+ catch (bad_alloc& error) {
+ delete mountedStabilityModule;
+ return false;
+ }
+
+ //Next line mount it for real
+ if (this->agent->getStabilityController()->mountStabilityModule(mountedStabilityModule->getStabilityModule())) {
+ return mountedStabilityModule->setHostAgent(this->agent);
+ }
+ }
+ }
+ return false;
+}
+
+bool SetupAgent::stabilityModuleIsMounted(StabilityModule* stabilityModule) {
+ for (auto &mountedStabilityModule : vMountedStabilityModules)
+ if (mountedStabilityModule->getStabilityModule() == stabilityModule)
+ return true;
+ return false;
+}
+
+bool SetupAgent::stabilityModuleIsMounted(SetupStabilityModule* setupStabilityModule) {
+ for (auto &mountedStabilityModule : vMountedStabilityModules)
+ if (mountedStabilityModule == setupStabilityModule)
+ return true;
+ return false;
+}
+
+SetupStabilityModule* SetupAgent::getStabilityModule(StabilityModule* stabilityModule) {
+ for (auto &mountedStabilityModule : vMountedStabilityModules)
+ if (mountedStabilityModule->getStabilityModule() == stabilityModule)
+ return mountedStabilityModule;
+ return NULL;
+}
+
+
+
+bool SetupAgent::setChannel(Channel* channel) {
+ if (channel) {
+ this->channel = channel;
+ return true;
+ }
+ return false;
+}
+
+Channel* SetupAgent::getChannel() {
+ return channel;
+}
+
+
+
+bool SetupAgent::setAgentSlot(SlaveAgentSlotOfAgent* agentSlot) {
+ if (agentSlot) {
+ this->agentSlot = agentSlot;
+ return true;
+ }
+ return false;
+}
+
+SlaveAgentSlotOfAgent* SetupAgent::getAgentSlot() {
+ return agentSlot;
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/SetupAgent.h b/SA-EWS_Version_2019.03.27/src/SetupAgent.h
new file mode 100644
index 0000000..56fa0e0
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/SetupAgent.h
@@ -0,0 +1,81 @@
+#ifndef SETUPAGENT_HEADERFILE
+#define SETUPAGENT_HEADERFILE
+
+#include "Agent.h"
+#include "Channel.h"
+#include "Sensor.h"
+//#include "SetupMountedAgent.h"
+#include "SetupMountedHistoryModule.h"
+#include "SetupMountedSensor.h"
+#include "SetupStabilityModule.h"
+#include "SlaveAgentSlotOfAgent.h"
+#include <vector>
+
+class SetupAgent {
+
+private:
+ Agent* agent; //itself
+
+ SlaveAgentSlotOfAgent* agentSlot;
+
+ Agent* masterAgent;
+
+ Channel* channel;
+
+ //vector<SetupMountedAgent*> vMountedAgents;
+ vector<SetupAgent*> vMountedAgents;
+ vector<SetupMountedHistoryModule*> vMountedHistoryModules;
+ vector<SetupStabilityModule*> vMountedStabilityModules;
+
+ //TODO: SetupMountedSensor -> SetupSensor
+ vector<SetupMountedSensor*> vMountedSensors;
+
+public:
+ SetupAgent();
+ SetupAgent(Agent* agent);
+ SetupAgent(Agent* agent, Channel* channel);
+
+ bool setAgent(Agent* agent);
+ bool masterAgentIsSet();
+ Agent* getAgent();
+
+ bool setMasterAgent(Agent* masterAgent, Channel* channel);
+ Agent* getMasterAgent();
+
+
+ bool mountAgent(Agent* agent, Channel* channel);
+ bool agentIsMounted(Agent* agent);
+ SetupAgent* getMountedAgent(Agent* agent);
+ SetupAgent* getMountedAgent(Channel* channel);
+
+ /*
+ bool mountAgent(Agent* agent, Channel* channel);
+ bool agentIsMounted(Agent* agent);
+ SetupMountedAgent* getMountedAgent(Agent* agent);
+ SetupMountedAgent* getMountedAgent(Channel* channel);
+ */
+
+ bool mountSensor(Sensor* sensor, Channel* channel);
+ bool sensorIsMounted(Sensor* sensor);
+ SetupMountedSensor* getMountedSensor(Sensor* sensor);
+ SetupMountedSensor* getMountedSensor(Channel* channel);
+
+ bool mountHistoryModule(SetupMountedHistoryModule* mountedHistoryModule);
+ bool historyModuleIsMounted(HistoryModule* historyModule);
+ bool historyModuleIsMounted(SetupMountedHistoryModule* historyModule);
+ SetupMountedHistoryModule* getMountedHistoryModule(HistoryModule* historyModule);
+
+ bool mountStabilityModule(SetupStabilityModule* mountedStabilityModule);
+ bool stabilityModuleIsMounted(StabilityModule* stabilityModule);
+ bool stabilityModuleIsMounted(SetupStabilityModule* setupStabilityModule);
+ SetupStabilityModule* getStabilityModule(StabilityModule* stabilityModule);
+
+ bool setChannel(Channel* channel);
+ Channel* getChannel();
+
+ bool setAgentSlot(SlaveAgentSlotOfAgent* agentSlot);
+ SlaveAgentSlotOfAgent* getAgentSlot();
+
+};
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/SetupMountedAgent.cpp b/SA-EWS_Version_2019.03.27/src/SetupMountedAgent.cpp
new file mode 100644
index 0000000..73dcaa9
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/SetupMountedAgent.cpp
@@ -0,0 +1,52 @@
+#include "SetupMountedAgent.h"
+
+SetupMountedAgent::SetupMountedAgent() {
+
+}
+
+SetupMountedAgent::SetupMountedAgent(Agent* agent, Channel* channel) {
+ this->agent = agent;
+ this->channel = channel;
+}
+
+
+
+bool SetupMountedAgent::setAgent(Agent* agent) {
+ if (agent) {
+ this->agent = agent;
+ return true;
+ }
+ return false;
+}
+
+Agent* SetupMountedAgent::getAgent() {
+ return agent;
+}
+
+
+
+bool SetupMountedAgent::setChannel(Channel* channel) {
+ if (channel) {
+ this->channel = channel;
+ return true;
+ }
+ return false;
+}
+
+Channel* SetupMountedAgent::getChannel() {
+ return channel;
+}
+
+
+
+bool SetupMountedAgent::setAgentSlot(SlaveAgentSlotOfAgent* agentSlot) {
+ if (agentSlot) {
+ this->agentSlot = agentSlot;
+ return true;
+ }
+ return false;
+}
+
+SlaveAgentSlotOfAgent* SetupMountedAgent::getAgentSlot() {
+ return agentSlot;
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/SetupMountedAgent.h b/SA-EWS_Version_2019.03.27/src/SetupMountedAgent.h
new file mode 100644
index 0000000..e54d8ce
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/SetupMountedAgent.h
@@ -0,0 +1,28 @@
+#ifndef SETUPMOUNTEDAGENT_HEADERFILE
+#define SETUPMOUNTEDAGENT_HEADERFILE
+
+#include "Agent.h"
+#include "Channel.h"
+
+class SetupMountedAgent {
+
+private:
+ Agent* agent;
+ Channel* channel;
+ SlaveAgentSlotOfAgent* agentSlot;
+
+public:
+ SetupMountedAgent();
+ SetupMountedAgent(Agent* agent, Channel* channel);
+
+ bool setAgent(Agent* agent);
+ Agent* getAgent();
+
+ bool setChannel(Channel* channel);
+ Channel* getChannel();
+
+ bool setAgentSlot(SlaveAgentSlotOfAgent* agentSlot);
+ SlaveAgentSlotOfAgent* getAgentSlot();
+};
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/SetupMountedHistoryModule.cpp b/SA-EWS_Version_2019.03.27/src/SetupMountedHistoryModule.cpp
new file mode 100644
index 0000000..4d309ac
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/SetupMountedHistoryModule.cpp
@@ -0,0 +1,37 @@
+#include "SetupMountedHistoryModule.h"
+
+SetupMountedHistoryModule::SetupMountedHistoryModule() {
+
+}
+
+SetupMountedHistoryModule::SetupMountedHistoryModule(HistoryModule* historyModule) {
+ this->historyModule = historyModule;
+}
+
+
+
+bool SetupMountedHistoryModule::setHistoryModule(HistoryModule* historyModule) {
+ if (historyModule) {
+ this->historyModule = historyModule;
+ return true;
+ }
+ return false;
+}
+
+HistoryModule* SetupMountedHistoryModule::getHistoryModule() {
+ return historyModule;
+}
+
+
+
+bool SetupMountedHistoryModule::setHostAgent(Agent* hostAgent) {
+ if (hostAgent) {
+ this->hostAgent = hostAgent;
+ return true;
+ }
+ return false;
+}
+
+Agent* SetupMountedHistoryModule::getHostAgent() {
+ return hostAgent;
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/SetupMountedHistoryModule.h b/SA-EWS_Version_2019.03.27/src/SetupMountedHistoryModule.h
new file mode 100644
index 0000000..f873bec
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/SetupMountedHistoryModule.h
@@ -0,0 +1,26 @@
+#ifndef SETUPMOUNTEDHISTORYMODULE_HEADERFILE
+#define SETUPMOUNTEDHISTORYMODULE_HEADERFILE
+
+#include "Agent.h"
+#include "HistoryModule.h"
+
+class SetupMountedHistoryModule {
+
+private:
+ HistoryModule* historyModule;
+
+ Agent* hostAgent;
+
+public:
+ SetupMountedHistoryModule();
+ SetupMountedHistoryModule(HistoryModule* historyModule);
+
+ bool setHistoryModule(HistoryModule* historyModule);
+ HistoryModule* getHistoryModule();
+
+ bool setHostAgent(Agent* hostAgent);
+ Agent* getHostAgent();
+
+};
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/SetupMountedSensor.cpp b/SA-EWS_Version_2019.03.27/src/SetupMountedSensor.cpp
new file mode 100644
index 0000000..8c2a2f4
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/SetupMountedSensor.cpp
@@ -0,0 +1,50 @@
+#include "SetupMountedSensor.h"
+
+SetupMountedSensor::SetupMountedSensor() {
+
+}
+
+SetupMountedSensor::SetupMountedSensor(Sensor* sensor, Channel* channel) {
+
+}
+
+
+bool SetupMountedSensor::setSensor(Sensor* sensor) {
+ if (sensor) {
+ this->sensor = sensor;
+ return true;
+ }
+ return false;
+}
+
+Sensor* SetupMountedSensor::getSensor() {
+ return sensor;
+}
+
+
+
+bool SetupMountedSensor::setChannel(Channel* channel) {
+ if (channel) {
+ this->channel = channel;
+ return true;
+ }
+ return false;
+}
+
+Channel* SetupMountedSensor::getChannel() {
+ return channel;
+}
+
+
+
+bool SetupMountedSensor::setSensorSlot(SensorSlotOfAgent* sensorSlot) {
+ if (sensorSlot) {
+ this->sensorSlot = sensorSlot;
+ return true;
+ }
+ return false;
+}
+
+SensorSlotOfAgent* SetupMountedSensor::getSensorSlot() {
+ return sensorSlot;
+}
diff --git a/SA-EWS_Version_2019.03.27/src/SetupMountedSensor.h b/SA-EWS_Version_2019.03.27/src/SetupMountedSensor.h
new file mode 100644
index 0000000..bd073ab
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/SetupMountedSensor.h
@@ -0,0 +1,34 @@
+#ifndef SETUPMOUNTEDSENSOR_HEADERFILE
+#define SETUPMOUNTEDSENSOR_HEADERFILE
+
+#include "Sensor.h"
+#include "SensorSlotOfAgent.h"
+
+class SetupMountedSensor {
+
+private:
+ Sensor* sensor;
+ Channel* channel;
+ SensorSlotOfAgent* sensorSlot;
+
+public:
+ SetupMountedSensor();
+ SetupMountedSensor(Sensor* sensor, Channel* channel);
+
+ //void mountSensor(Sensor* sensor, Channel* channel, SlaveAgentSlotOfAgent* slaveAgentSlotofAgent);
+
+ bool setSensor(Sensor* sensor);
+ Sensor* getSensor();
+
+ bool setChannel(Channel* channel);
+ Channel* getChannel();
+
+ bool setSensorSlot(SensorSlotOfAgent* sensorSlot);
+ SensorSlotOfAgent* getSensorSlot();
+
+
+
+};
+
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/SetupOLD.cpp b/SA-EWS_Version_2019.03.27/src/SetupOLD.cpp
new file mode 100644
index 0000000..cd6724b
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/SetupOLD.cpp
@@ -0,0 +1,435 @@
+#include "SetupOLD.h"
+#include "rlutil.h"
+
+using namespace rlutil;
+
+SetupOLD::SetupOLD() {
+
+}
+
+
+
+void SetupOLD::printMountingProcessImpossible() {
+ setColor(LIGHTRED);
+ printf(" > Process of Mounting is impossible\n");
+ setColor(GREY);
+}
+
+void SetupOLD::printAgentGotMounted(Agent* masterAgent, Agent* slaveAgent) {
+ printf(" > Agent ");
+ setColor(LIGHTCYAN);
+ printf("%s ", slaveAgent->getName().c_str());
+ setColor(GREY);
+ printf("(%03u) ", slaveAgent->getId());
+ setColor(LIGHTGREEN);
+ printf("mounted ");
+ setColor(GREY);
+ printf("in Agent ");
+ setColor(LIGHTCYAN);
+ printf("%s ", masterAgent->getName().c_str());
+ setColor(GREY);
+ printf("(%03u)\n", masterAgent->getId());
+}
+
+void SetupOLD::printAgentCouldntGetMounted(Agent* masterAgent, Agent* slaveAgent) {
+ setColor(LIGHTRED);
+ printf(" > Agent %s (%03u) couldn't get mounted in Agent %s (%03u)\n", slaveAgent->getName().c_str(), slaveAgent->getId(), masterAgent->getName().c_str(), masterAgent->getId());
+ setColor(GREY);
+}
+
+void SetupOLD::printHistoryModuleGotMounted(Agent* agent, HistoryModule* historyModule) {
+ printf(" > History Module ");
+ setColor(LIGHTCYAN);
+ printf("%s ", historyModule->getName().c_str());
+ setColor(GREY);
+ printf("(%03u) ", historyModule->getId());
+ setColor(LIGHTGREEN);
+ printf("mounted ");
+ setColor(GREY);
+ printf("in Agent ");
+ setColor(LIGHTCYAN);
+ printf("%s ", agent->getName().c_str());
+ setColor(GREY);
+ printf("(%03u)\n", agent->getId());
+}
+
+void SetupOLD::printHistoryModuleCouldntGetMounted(Agent* agent, HistoryModule* historyModule) {
+ setColor(LIGHTRED);
+ printf(" > History Module %s (%03u) couldn't get mounted in Agent %s (%03u)\n", historyModule->getName().c_str(), historyModule->getId(), agent->getName().c_str(), agent->getId());
+ setColor(GREY);
+}
+
+void SetupOLD::printSensorGotMounted(Agent* agent, Sensor* sensor) {
+ printf(" > Sensor ");
+ setColor(LIGHTCYAN);
+ printf("%s ", sensor->getName().c_str());
+ setColor(GREY);
+ printf("(%03u) ", sensor->getId());
+ setColor(LIGHTGREEN);
+ printf("mounted ");
+ setColor(GREY);
+ printf("in Agent ");
+ setColor(LIGHTCYAN);
+ printf("%s ", agent->getName().c_str());
+ setColor(GREY);
+ printf("(%03u)\n", agent->getId());
+}
+
+void SetupOLD::printSensorCouldntGetMounted(Agent* agent, Sensor* sensor) {
+ setColor(LIGHTRED);
+ printf(" > Agent %s (%03u) couldn't get mounted in Agent %s (%03u)\n", sensor->getName().c_str(), sensor->getId(), agent->getName().c_str(), agent->getId());
+ setColor(GREY);
+}
+
+
+void SetupOLD::printStabilityModuleGotMounted(Agent* agent, StabilityModule* stabilityModule) {
+ printf(" > Stability Module ");
+ setColor(LIGHTCYAN);
+ printf("%s ", stabilityModule->getName().c_str());
+ setColor(GREY);
+ printf("(%03u) ", stabilityModule->getId());
+ setColor(LIGHTGREEN);
+ printf("mounted ");
+ setColor(GREY);
+ printf("in Agent ");
+ setColor(LIGHTCYAN);
+ printf("%s ", agent->getName().c_str());
+ setColor(GREY);
+ printf("(%03u)\n", agent->getId());
+}
+
+void SetupOLD::printStabilityModuleCouldntGetMounted(Agent* agent, StabilityModule* stabilityModule) {
+ setColor(LIGHTRED);
+ printf(" > Stability Module %s (%03u) couldn't get mounted in Agent %s (%03u)\n", stabilityModule->getName().c_str(), stabilityModule->getId(), agent->getName().c_str(), agent->getId());
+ setColor(GREY);
+}
+
+
+void SetupOLD::printConnectionEstablished(Agent* hostAgent, HistoryModule* historyModule, Agent* slaveAgent) {
+ printf(" > Inside of Agent ");
+ setColor(LIGHTCYAN);
+ printf("%s ", hostAgent->getName().c_str());
+ setColor(GREY);
+ printf("(%03u): ", hostAgent->getId());
+ printf("History Module ");
+ setColor(LIGHTCYAN);
+ printf("%s ", historyModule->getName().c_str());
+ setColor(GREY);
+ printf("(%03u) is ", historyModule->getId());
+ setColor(LIGHTGREEN);
+ printf("connected ");
+ setColor(GREY);
+ printf("with Input of Agent ");
+ setColor(LIGHTCYAN);
+ printf("%s ", slaveAgent->getName().c_str());
+ setColor(GREY);
+ printf("(%03u)\n", slaveAgent->getId());
+}
+
+void SetupOLD::printConnectionEstablished(Agent* hostAgent, StabilityModule* stabilityModule, HistoryModule* historyModule, Agent* slaveAgent) {
+ printf(" > Inside of Agent ");
+ setColor(LIGHTCYAN);
+ printf("%s ", hostAgent->getName().c_str());
+ setColor(GREY);
+ printf("(%03u): ", hostAgent->getId());
+ printf("Stability Module ");
+ setColor(LIGHTCYAN);
+ printf("%s ", stabilityModule->getName().c_str());
+ setColor(GREY);
+ printf("(%03u) is ", stabilityModule->getId());
+ setColor(LIGHTGREEN);
+ printf("connected ");
+ setColor(GREY);
+ printf("with Input of Agent ");
+ setColor(LIGHTCYAN);
+ printf("%s ", slaveAgent->getName().c_str());
+ setColor(GREY);
+ printf("(%03u) and ", slaveAgent->getId());
+ printf("with History Module ");
+ setColor(LIGHTCYAN);
+ printf("%s ", historyModule->getName().c_str());
+ setColor(GREY);
+ printf("(%03u)\n", historyModule->getId());
+}
+
+void SetupOLD::printConnectionIsImpossible() {
+ setColor(LIGHTRED);
+ printf(" > Process of Connecting is impossible\n");
+ setColor(GREY);
+}
+
+
+
+void SetupOLD::mountAgentInAgent(Agent* masterAgent, Agent* slaveAgent, Channel* channel) {
+ if (masterAgent && slaveAgent && channel) {
+ //note: next line is because one slaveAgent can only be mounted once
+ if (!agentIsRegistered(slaveAgent) || !getRegisteredAgent(slaveAgent)->masterAgentIsSet()) {
+
+ SetupAgent* setupSlaveAgent = NULL;
+
+ if (agentIsRegistered(slaveAgent)) {
+ setupSlaveAgent = getRegisteredAgent(slaveAgent);
+ }
+ else {
+ setupSlaveAgent = registerAgent(slaveAgent);
+ }
+
+ SetupAgent* setupMasterAgent = NULL;
+
+ if (agentIsRegistered(masterAgent)) {
+ setupMasterAgent = getRegisteredAgent(masterAgent);
+ }
+ else {
+ setupMasterAgent = registerAgent(masterAgent);
+ }
+
+ if (setupMasterAgent->mountAgent(slaveAgent, channel)) {
+ if (setupSlaveAgent->setMasterAgent(masterAgent, channel)) {
+ printAgentGotMounted(masterAgent, slaveAgent);
+ }
+ else {
+ //TODO: unmount in real and in setup object
+ }
+ }
+ }
+ }
+}
+
+SetupAgent* SetupOLD::registerAgent(Agent* agent) {
+ SetupAgent* setupAgent = new SetupAgent(agent);
+ try {
+ vSetupAgents.push_back(setupAgent);
+ return setupAgent;
+ }
+ catch (bad_alloc& error) {
+ delete setupAgent;
+ }
+ return NULL;
+}
+
+bool SetupOLD::agentIsRegistered(Agent* agent) {
+ for (auto &registeredAgent : vSetupAgents)
+ if (registeredAgent->getAgent() == agent)
+ return true;
+ return false;
+}
+
+SetupAgent* SetupOLD::getRegisteredAgent(Agent* agent) {
+ for (auto &registeredAgent : vSetupAgents)
+ if (registeredAgent->getAgent() == agent) {
+ printf("DADRINN\n\n");
+ return registeredAgent;
+ }
+
+ return NULL;
+}
+
+
+
+void SetupOLD::mountSensorInAgent(Agent* agent, Sensor* sensor, Channel* channel) {
+ if (agent && sensor && channel) {
+ //note: next line is because one sensor can only be mounted once
+ if (!SensorIsRegistered(sensor)) {
+ SetupSensor* setupSensor = registerSensor(sensor);
+ SetupAgent* setupAgent = NULL;
+
+ if (agentIsRegistered(agent)) {
+ setupAgent = getRegisteredAgent(agent);
+ }
+ else {
+ setupAgent = registerAgent(agent);
+ }
+
+
+ if (setupAgent->mountSensor(sensor, channel)) {
+ if (setupSensor->setMasterAgent(agent, channel)) {
+ printSensorGotMounted(agent, sensor);
+ }
+ else {
+ //TODO: unmount in real and in setup object
+ }
+ }
+ }
+ }
+}
+
+SetupSensor* SetupOLD::registerSensor(Sensor* sensor) {
+ SetupSensor* setupSensor = new SetupSensor(sensor);
+ try {
+ vSetupSensors.push_back(setupSensor);
+ return setupSensor;
+ }
+ catch (bad_alloc& error) {
+ delete setupSensor;
+ }
+ return NULL;
+}
+
+bool SetupOLD::SensorIsRegistered(Sensor* sensor) {
+ for (auto &registeredSensor : vSetupSensors)
+ if (registeredSensor->getSensor() == sensor)
+ return true;
+ return false;
+}
+
+SetupSensor* SetupOLD::getRegisteredSensor(Sensor* sensor) {
+ for (auto &registeredSensor : vSetupSensors)
+ if (registeredSensor->getSensor() == sensor)
+ return registeredSensor;
+ return NULL;
+}
+
+
+
+void SetupOLD::mountHistoryModuleInAgent(Agent* agent, HistoryModule* historyModule) {
+ if (agent && historyModule) {
+ //NOTE: next line is because a history module can only be mounted once
+ if (!historyModuleIsRegistered(historyModule)) {
+ SetupMountedHistoryModule* setupMountedHistoryModule = registerHistoryModule(historyModule);
+ SetupAgent* setupAgent = NULL;
+
+ if (agentIsRegistered(agent)) {
+ setupAgent = getRegisteredAgent(agent);
+ }
+ else {
+ setupAgent = registerAgent(agent);
+ }
+
+ if (setupAgent->mountHistoryModule(setupMountedHistoryModule)) {
+ printHistoryModuleGotMounted(agent, historyModule);
+ return;
+ }
+ }
+ printHistoryModuleCouldntGetMounted(agent, historyModule);
+ return;
+ }
+ printMountingProcessImpossible();
+}
+
+SetupMountedHistoryModule* SetupOLD::registerHistoryModule(HistoryModule* historyModule) {
+ SetupMountedHistoryModule* setupMountedHistoryModule = new SetupMountedHistoryModule(historyModule);
+ try {
+ vSetupHistoryModules.push_back(setupMountedHistoryModule);
+ return setupMountedHistoryModule;
+ }
+ catch (bad_alloc& error) {
+ delete setupMountedHistoryModule;
+ }
+ return NULL;
+}
+
+bool SetupOLD::historyModuleIsRegistered(HistoryModule* historyModule) {
+ for (auto &registeredHistoryModule : vSetupHistoryModules)
+ if (registeredHistoryModule->getHistoryModule() == historyModule)
+ return true;
+ return false;
+}
+
+SetupMountedHistoryModule* SetupOLD::getRegisteredHistoryModule(HistoryModule* historyModule) {
+ for (auto &registeredHistoryModule : vSetupHistoryModules)
+ if (registeredHistoryModule->getHistoryModule() == historyModule)
+ return registeredHistoryModule;
+ return NULL;
+}
+
+
+//TODO: it is the same as the mountHistoryModule function -> template
+void SetupOLD::mountStabilityModules(Agent* agent, StabilityModule* stabilityModule) {
+ if(agent && stabilityModule) {
+ //NOTE: next line is because a history module can only be mounted once
+ if (!stabilityModuleIsRegistered(stabilityModule)) {
+ SetupStabilityModule* setupStabilityModule = registerStabilityModule(stabilityModule);
+ SetupAgent* setupAgent = NULL;
+
+ if (agentIsRegistered(agent)) {
+ setupAgent = getRegisteredAgent(agent);
+ }
+ else {
+ setupAgent = registerAgent(agent);
+ }
+
+ if (setupAgent->mountStabilityModule(setupStabilityModule)) {
+ printStabilityModuleGotMounted(agent, stabilityModule);
+ return;
+ }
+ }
+ printStabilityModuleCouldntGetMounted(agent, stabilityModule);
+ return;
+ }
+ printMountingProcessImpossible();
+}
+
+SetupStabilityModule* SetupOLD::registerStabilityModule(StabilityModule* stabilityModule) {
+ SetupStabilityModule* setupStabilityModule = new SetupStabilityModule(stabilityModule);
+ try {
+ vSetupStabilityModules.push_back(setupStabilityModule);
+ return setupStabilityModule;
+ }
+ catch (bad_alloc& error) {
+ delete setupStabilityModule;
+ }
+ return NULL;
+}
+
+bool SetupOLD::stabilityModuleIsRegistered(StabilityModule* stabilityModule) {
+ for (auto &registeredStabilityModule : vSetupStabilityModules)
+ if (registeredStabilityModule->getStabilityModule() == stabilityModule)
+ return true;
+ return false;
+}
+
+SetupStabilityModule* SetupOLD::getRegisteredStabilityModule(StabilityModule* stabilityModule) {
+ for (auto &registeredStabilityModule : vSetupStabilityModules)
+ if (registeredStabilityModule->getStabilityModule() == stabilityModule)
+ return registeredStabilityModule;
+ return NULL;
+}
+
+
+
+void SetupOLD::connect(HistoryModule* historyModule, Agent* slaveAgent) {
+ if (historyModule && slaveAgent) {
+ if (historyModuleIsRegistered(historyModule) && agentIsRegistered(slaveAgent)) {
+
+ SetupMountedHistoryModule* registeredHistoryModule = getRegisteredHistoryModule(historyModule);
+ Agent* hostAgent = registeredHistoryModule->getHostAgent();
+
+ printf("das is interessant\n");
+ SetupAgent* mountedAgent = getRegisteredAgent(slaveAgent);
+
+ if (hostAgent == mountedAgent->getMasterAgent()) {
+ //next line connect for real
+ if (historyModule->setObservationPointer(mountedAgent->getAgentSlot()->getObservationPointer())) {
+ printConnectionEstablished(hostAgent, historyModule, slaveAgent);
+ return;
+ }
+ }
+ }
+ }
+ printConnectionIsImpossible();
+}
+
+void SetupOLD::connect(HistoryModule* historyModule, Sensor* sensor) {
+ printConnectionIsImpossible();
+}
+
+void SetupOLD::connect(StabilityModule* stabilityModule, Agent* slaveAgent, HistoryModule* historyModule) {
+ if (stabilityModule && slaveAgent && historyModule) {
+ if (stabilityModuleIsRegistered(stabilityModule) && agentIsRegistered(slaveAgent) && historyModuleIsRegistered(historyModule)) {
+
+
+ SetupStabilityModule* registeredStabilityModule = getRegisteredStabilityModule(stabilityModule);
+ Agent* hostAgent = registeredStabilityModule->getHostAgent();
+ SetupMountedHistoryModule* registeredHistoryModule = getRegisteredHistoryModule(historyModule);
+ SetupAgent* mountedAgent = getRegisteredAgent(slaveAgent);
+ if (hostAgent == registeredHistoryModule->getHostAgent() && hostAgent == mountedAgent->getMasterAgent()) {
+ //next line connect for real
+ if (stabilityModule->setObservationPointer(mountedAgent->getAgentSlot()->getObservationPointer(), historyModule->getObservationPointer())) {
+ printConnectionEstablished(hostAgent, stabilityModule, historyModule, slaveAgent);
+ return;
+ }
+ }
+ }
+ }
+ printConnectionIsImpossible();
+}
diff --git a/SA-EWS_Version_2019.03.27/src/SetupOLD.h b/SA-EWS_Version_2019.03.27/src/SetupOLD.h
new file mode 100644
index 0000000..189a133
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/SetupOLD.h
@@ -0,0 +1,71 @@
+#ifndef SETUP_HEADERFILE
+#define SETUP_HEADERFILE
+
+#include "Agent.h"
+#include "Channel.h"
+#include "SetupAgent.h"
+#include "SetupMountedHistoryModule.h"
+#include "SetupStabilityModule.h"
+#include "SetupSensor.h"
+#include "Sensor.h"
+#include <vector>
+
+class SetupOLD {
+
+private:
+ vector<SetupAgent*> vSetupAgents;
+ vector<SetupMountedHistoryModule*> vSetupHistoryModules;
+ vector<SetupStabilityModule*> vSetupStabilityModules;
+ vector<SetupSensor*> vSetupSensors;
+
+
+ void printMountingProcessImpossible();
+
+ void printAgentGotMounted(Agent* masterAgent, Agent* slaveAgent);
+ void printAgentCouldntGetMounted(Agent* masterAgent, Agent* slaveAgent);
+
+ void printHistoryModuleGotMounted(Agent* agent, HistoryModule* historyModule);
+ void printHistoryModuleCouldntGetMounted(Agent* agent, HistoryModule* historyModule);
+
+ void printSensorGotMounted(Agent* agent, Sensor* sensor);
+ void printSensorCouldntGetMounted(Agent* agent, Sensor* sensor);
+
+ void printStabilityModuleGotMounted(Agent* agent, StabilityModule* stabilityModule);
+ void printStabilityModuleCouldntGetMounted(Agent* agent, StabilityModule* stabilityModule);
+
+ void printConnectionIsImpossible();
+
+ void printConnectionEstablished(Agent* hostAgent, HistoryModule* historyModule, Agent* slaveAgent);
+ void printConnectionEstablished(Agent* hostAgent, StabilityModule* stabilityModule, HistoryModule* historyModule, Agent* slaveAgent);
+
+public:
+ SetupOLD();
+
+ void mountAgentInAgent(Agent* masterAgent, Agent* slaveAgent, Channel* channel);
+ SetupAgent* registerAgent(Agent* agent);
+ bool agentIsRegistered(Agent* agent);
+ SetupAgent* getRegisteredAgent(Agent* agent);
+
+ void mountSensorInAgent(Agent* agent, Sensor* sensor, Channel* channel);
+ SetupSensor* registerSensor(Sensor* sensor);
+ bool SensorIsRegistered(Sensor* sensor);
+ SetupSensor* getRegisteredSensor(Sensor* sensor);
+
+ void mountHistoryModuleInAgent(Agent* agent, HistoryModule* historyModule);
+ SetupMountedHistoryModule* registerHistoryModule(HistoryModule* historyModule);
+ bool historyModuleIsRegistered(HistoryModule* historyModule);
+ SetupMountedHistoryModule* getRegisteredHistoryModule(HistoryModule* historyModule);
+
+ void mountStabilityModules(Agent* agent, StabilityModule* stabilityModule);
+ SetupStabilityModule* registerStabilityModule(StabilityModule* stabilityModule);
+ bool stabilityModuleIsRegistered(StabilityModule* stabilityModule);
+ SetupStabilityModule* getRegisteredStabilityModule(StabilityModule* stabilityModule);
+
+ void connect(HistoryModule* historyModule, Agent* slaveAgent);
+ void connect(HistoryModule* historyModule, Sensor* sensor);
+ void connect(StabilityModule* stabilityModule, Agent* slaveAgent, HistoryModule* historyModule);
+
+};
+
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/SetupSensor.cpp b/SA-EWS_Version_2019.03.27/src/SetupSensor.cpp
new file mode 100644
index 0000000..0c06e6c
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/SetupSensor.cpp
@@ -0,0 +1,43 @@
+#include "SetupSensor.h"
+#include <stdio.h>
+
+SetupSensor::SetupSensor() {
+ sensor = NULL;
+ masterAgent = NULL;
+}
+
+SetupSensor::SetupSensor(Sensor* sensor) {
+ this->sensor = sensor;
+ masterAgent = NULL;
+}
+
+
+
+bool SetupSensor::setSensor(Sensor* sensor) {
+ if (sensor) {
+ this->sensor = sensor;
+ return true;
+ }
+ return false;
+}
+
+Sensor* SetupSensor::getSensor() {
+ return sensor;
+}
+
+
+
+bool SetupSensor::setMasterAgent(Agent* masterAgent, Channel* channel) {
+ if (!this->masterAgent && masterAgent) {
+ if (sensor->mount_agent(channel)) {
+ this->masterAgent = masterAgent;
+ return true;
+ }
+ }
+ return false;
+
+}
+
+Agent* SetupSensor::getMasterAgent() {
+ return masterAgent;
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/SetupSensor.h b/SA-EWS_Version_2019.03.27/src/SetupSensor.h
new file mode 100644
index 0000000..4637400
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/SetupSensor.h
@@ -0,0 +1,28 @@
+#ifndef SETUPSENSOR_HEADERFILE
+#define SETUPSENSOR_HEADERFILE
+
+#include "Agent.h"
+#include "Channel.h"
+#include "Sensor.h"
+
+class SetupSensor {
+
+private:
+ Agent* masterAgent; //its master
+ Channel* channel; //channel to master
+
+ Sensor* sensor; //itself
+
+public:
+ SetupSensor();
+ SetupSensor(Sensor* sensor);
+
+ bool setSensor(Sensor* sensor);
+ Sensor* getSensor();
+
+ bool setMasterAgent(Agent* masterAgent, Channel* channel);
+ Agent* getMasterAgent();
+
+};
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/SetupStabilityModule.cpp b/SA-EWS_Version_2019.03.27/src/SetupStabilityModule.cpp
new file mode 100644
index 0000000..0f23c85
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/SetupStabilityModule.cpp
@@ -0,0 +1,38 @@
+#include "SetupStabilityModule.h"
+
+
+SetupStabilityModule::SetupStabilityModule() {
+
+}
+
+SetupStabilityModule::SetupStabilityModule(StabilityModule* stabilityModule) {
+ this->stabilityModule = stabilityModule;
+}
+
+
+
+bool SetupStabilityModule::setStabilityModule(StabilityModule* stabilityModule) {
+ if (stabilityModule) {
+ this->stabilityModule = stabilityModule;
+ return true;
+ }
+ return false;
+}
+
+StabilityModule* SetupStabilityModule::getStabilityModule() {
+ return stabilityModule;
+}
+
+
+
+bool SetupStabilityModule::setHostAgent(Agent* hostAgent) {
+ if (hostAgent) {
+ this->hostAgent = hostAgent;
+ return true;
+ }
+ return false;
+}
+
+Agent* SetupStabilityModule::getHostAgent() {
+ return hostAgent;
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/SetupStabilityModule.h b/SA-EWS_Version_2019.03.27/src/SetupStabilityModule.h
new file mode 100644
index 0000000..60a8c6e
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/SetupStabilityModule.h
@@ -0,0 +1,26 @@
+#ifndef SETUPSTABILITYMODULE_HEADERFILE
+#define SETUPSTABILITYMODULE_HEADERFILE
+
+#include "Agent.h"
+
+
+class SetupStabilityModule {
+
+private:
+ StabilityModule* stabilityModule;
+
+ Agent* hostAgent;
+
+public:
+ SetupStabilityModule();
+ SetupStabilityModule(StabilityModule* stabilityModule);
+
+ bool setStabilityModule(StabilityModule* stabilityModule);
+ StabilityModule* getStabilityModule();
+
+ bool setHostAgent(Agent* hostAgent);
+ Agent* getHostAgent();
+
+};
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/SineModule.cpp b/SA-EWS_Version_2019.03.27/src/SineModule.cpp
new file mode 100644
index 0000000..e6d33c6
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/SineModule.cpp
@@ -0,0 +1,62 @@
+#include "SineModule.h"
+
+#define TREND_INCREASING true
+#define TREND_DECREASING false
+
+
+void SineModule::initSineModule(char* name) {
+ setName(name);
+ lastValue = 0;
+ flagLastValueSet = false;
+ flagTrendKnown = false;
+}
+
+SineModule::SineModule() {
+ initSineModule(NO_NAME);
+}
+
+SineModule::SineModule(char* name) {
+ initSineModule(name);
+}
+
+bool SineModule::getAmplitude(float* amplitude, float actualValue) {
+
+ if (!flagLastValueSet) {
+ lastValue = actualValue;
+ return false;
+ }
+
+ if (!flagTrendKnown) {
+
+ if (actualValue > lastValue) {
+ flagTrendKnown = true;
+ flagTrend = TREND_INCREASING;
+ }
+ else if (actualValue < lastValue) {
+ flagTrendKnown = true;
+ flagTrend = TREND_DECREASING;
+ }
+ lastValue = actualValue;
+ return false;
+ }
+
+
+ if ((flagTrend == TREND_INCREASING && actualValue < lastValue) || (flagTrend == TREND_DECREASING && actualValue > lastValue)) {
+ *amplitude = lastValue;
+ lastValue = actualValue;
+ flagTrend = !flagTrend;
+ return true;
+ }
+
+ lastValue = actualValue;
+ return false;
+}
+
+bool SineModule::getAbsoluteAmplitude(float* amplitude, float actualValue) {
+ if (getAmplitude(amplitude, actualValue)) {
+ if (*amplitude < 0)
+ *amplitude = *amplitude * -1;
+ return true;
+ }
+ return false;
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/SineModule.h b/SA-EWS_Version_2019.03.27/src/SineModule.h
new file mode 100644
index 0000000..f9992f6
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/SineModule.h
@@ -0,0 +1,29 @@
+#ifndef SINEMODULE_HEADERFILE
+#define SINEMODULE_HEADERFILE
+
+#include "Unit.h"
+//#include "Module.h"
+
+//using namespace std;
+
+class SineModule : public Unit {
+//class SineModule : public Module {
+
+private:
+ float lastValue;
+ bool flagLastValueSet;
+ bool flagTrendKnown;
+ bool flagTrend;
+
+ void initSineModule(char* name);
+
+public:
+ SineModule();
+ SineModule(char* name);
+
+ bool getAmplitude(float* amplitude, float actualValue);
+ bool getAbsoluteAmplitude(float* amplitude, float actualValue);
+
+};
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/SlaveAgentHandlerOfAgent.cpp b/SA-EWS_Version_2019.03.27/src/SlaveAgentHandlerOfAgent.cpp
new file mode 100644
index 0000000..37e22fe
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/SlaveAgentHandlerOfAgent.cpp
@@ -0,0 +1,296 @@
+#include "SlaveAgentHandlerOfAgent.h"
+
+#include "instruction_set_architecture.h"
+#include <stdio.h>
+#include "printError.h"
+
+
+#include <algorithm>
+#include <iostream>
+
+#define MAXNUMOF_MOUNTEDSENSORS 100
+
+using namespace std;
+
+SlaveAgentHandlerOfAgent :: SlaveAgentHandlerOfAgent() {
+ initSlaveAgentHandler();
+}
+
+void SlaveAgentHandlerOfAgent :: initSlaveAgentHandler() {
+ maxNumOfMountedSlaveAgents = MAXNUMOF_MOUNTEDSENSORS;
+}
+
+SlaveAgentSlotOfAgent* 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);
+ return slaveAgentSlotOfAgent;
+ }
+ catch(bad_alloc& error) {
+ printError("bad_alloc caught: ", error.what());
+ delete slaveAgentSlotOfAgent;
+ }
+ }
+ else {
+ printError("Max number of mounted slaveAgents is already reached!");
+ delete slaveAgentSlotOfAgent;
+ }
+
+ }
+ else {
+ printError("Input port is no set!");
+ vMountedSlaveAgents.pop_back(); //TODO: check if it is right?!?!
+ delete slaveAgentSlotOfAgent;
+ }
+ }
+ else {
+ printError("Couldn't create SlaveAgentSlot!");
+ }
+ return NULL;
+}
+
+/*
+bool SlaveAgentHandlerOfAgent::mount_slaveAgentIntoSlaveAgentSlot(Channel* inputPort, StabilityModule* stabilityModule) {
+ SlaveAgentSlotOfAgent* slaveAgentSlotOfAgent = new SlaveAgentSlotOfAgent();
+ if (slaveAgentSlotOfAgent != NULL) {
+ if (slaveAgentSlotOfAgent->set_comPort(inputPort) && slaveAgentSlotOfAgent->mountStabilityModule(stabilityModule)) {
+ 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) {
+ //printf("master_reads1\n");
+ if(slaveAgentSlotOfAgent != NULL) {
+ //printf("master_reads2\n");
+ Channel* channel = slaveAgentSlotOfAgent->get_comPort();
+ if(channel != NULL) {
+ //printf("master_reads3\n");
+ int msg;
+ if (channel->get_MsgUp(&msg)) {
+ //printf("master_reads4\n");
+ if (ISA_AbstractedSensoryDataAndReliability) {
+ //printf("master_reads5\n");
+ while (channel->get_MsgUp(&msg)) {
+ //printf("master_reads6\n");
+ float inputValue;
+ if (channel->get_MsgUp(&inputValue)) {
+ //printf("master_reads7\n");
+ slaveAgentSlotOfAgent->addPossibleScore(msg, inputValue);
+ //cout << "added!!!!!!!!!!!!!" << endl;
+ }
+ else {
+ cout << "check das mal ab" << endl;
+ getchar();
+ return false;
+ }
+ }
+
+ slaveAgentSlotOfAgent->increaseTimeSinceScoreChange();
+
+ return true;
+
+ /*
+ if (channel->get_MsgUp(&msg)) {
+ slaveAgentSlotOfAgent->setScoreValue(msg);
+ float inputValue;
+ if (channel->get_MsgUp(&inputValue)) {
+ slaveAgentSlotOfAgent->setSlaveAgentValue(inputValue);
+ slaveAgentSlotOfAgent->setReliabilityValue(inputValue);
+ return true;
+ }
+ }
+ */
+ }
+ }
+ }
+ }
+ return false;
+}
+
+bool SlaveAgentHandlerOfAgent :: read_allSlaveAgentValues() {
+ bool flag_readSlaveAgent = true;
+
+ for(auto &slaveAgentSlot : vMountedSlaveAgents) {
+ if(!read_slaveAgentValue(slaveAgentSlot)) {
+ flag_readSlaveAgent = false;
+ }
+ }
+ 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<SlaveAgentSlotOfAgent*>* SlaveAgentHandlerOfAgent :: get_vMountedSlaveAgents() {
+
+ //printf("size: %u\n", vMountedSlaveAgents.size());
+
+ return &vMountedSlaveAgents;
+}
+
+bool SlaveAgentHandlerOfAgent::saveValueInHistory(SlaveAgentSlotOfAgent* slaveAgentSlotOfAgent) {
+ if (slaveAgentSlotOfAgent != NULL) {
+ //TODO: change this hardcoded value
+ while (slaveAgentSlotOfAgent->getHistoryLength() >= 10) {
+ slaveAgentSlotOfAgent->deleteOldestHistoryEntry();
+ }
+ return slaveAgentSlotOfAgent->saveValueInHistory();
+ }
+ return false;
+}
+
+bool SlaveAgentHandlerOfAgent::saveAllValuesInHistory() {
+ bool flagSavingSuccesful = true;
+ for (auto &slaveAgentSlot : vMountedSlaveAgents) {
+ if (!saveValueInHistory(slaveAgentSlot)) {
+ flagSavingSuccesful = false;
+ }
+ }
+ return flagSavingSuccesful;
+}
+
+
+void SlaveAgentHandlerOfAgent::resetHandler() {
+ for (auto &slaveAgentSlot : vMountedSlaveAgents) {
+ if (slaveAgentSlot)
+ slaveAgentSlot->resetSlot();
+ }
+}
+
+
diff --git a/SA-EWS_Version_2019.03.27/src/SlaveAgentHandlerOfAgent.h b/SA-EWS_Version_2019.03.27/src/SlaveAgentHandlerOfAgent.h
new file mode 100644
index 0000000..85bc81a
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/SlaveAgentHandlerOfAgent.h
@@ -0,0 +1,58 @@
+#ifndef SLAVEAGENTHANDLEROFAGENT_HEADERFILE
+#define SLAVEAGENTHANDLEROFAGENT_HEADERFILE
+
+#include "SlaveAgentSlotOfAgent.h"
+#include "Unit.h"
+#include "StabilityModule.h"
+#include <vector>
+
+using namespace std;
+
+class SlaveAgentHandlerOfAgent : public Unit {
+
+ private:
+
+ //TODO: set- and get function for maxNumOf_mountedSlaveAgents;
+ vector<SlaveAgentSlotOfAgent*> vMountedSlaveAgents;
+ unsigned int maxNumOfMountedSlaveAgents;
+
+ void initSlaveAgentHandler();
+
+ public:
+ SlaveAgentHandlerOfAgent();
+
+ SlaveAgentSlotOfAgent* mount_slaveAgentIntoSlaveAgentSlot(Channel* inputPort);
+ //bool mount_slaveAgentIntoSlaveAgentSlot(Channel* inputPort, StabilityModule* stabilityModule);
+ 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<SlaveAgentSlotOfAgent*>* get_vMountedSlaveAgents();
+
+ bool saveValueInHistory(SlaveAgentSlotOfAgent* slaveAgentSlotOfAgent);
+ bool saveAllValuesInHistory();
+
+
+ void resetHandler();
+
+};
+
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/SlaveAgentSlotOfAgent.cpp b/SA-EWS_Version_2019.03.27/src/SlaveAgentSlotOfAgent.cpp
new file mode 100644
index 0000000..b5d725a
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/SlaveAgentSlotOfAgent.cpp
@@ -0,0 +1,296 @@
+#include "SlaveAgentSlotOfAgent.h"
+
+#include "printError.h"
+#include "relationChecker.h"
+
+SlaveAgentSlotOfAgent :: SlaveAgentSlotOfAgent() {
+ flagSlaveAgentValueIsSet = false;
+ /*
+ flagSlaveAgentValueHasChanged = false;
+ flagSlaveAgentValueChangeIsSet = false;
+ /*
+ activeState = NULL;
+ backupState = NULL;
+ */
+
+
+ possibleScoreCount = 0;
+ timeSinceScoreChange = 0;
+ historySet = false;
+}
+
+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) {
+ //NOTE: For the case of overstep the history boundaries, I make a while-loop instead of an if-statement "if(getHistoryLength() >= MAXHISTORYLENGTH)".
+ while (getHistoryLength() >= MAXHISTORYLENGTH) {
+ if (!deleteOldestHistoryEntry())
+ return false;
+ }
+ 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;
+}
+
+
+
+
+
+void SlaveAgentSlotOfAgent::printHistory() {
+ printf("History: ");
+ for (auto &entry : lSlaveAgentHistory) {
+ printf("%f, ", entry);
+ }
+ printf("\n");
+}
+
+
+bool SlaveAgentSlotOfAgent::mountStabilityModule(StabilityModule* stabilityModule) {
+ if (this->stabilityModule == NULL && stabilityModule != NULL) {
+ this->stabilityModule = stabilityModule;
+ return true;
+ }
+ return false;
+}
+
+StabilityModule* SlaveAgentSlotOfAgent::getStabilityModule() {
+ return stabilityModule;
+}
+
+
+float* SlaveAgentSlotOfAgent::getObservationPointer() {
+
+ printf(" - was sagt er hier? %p\n", &slaveAgentValue);
+ getchar();
+
+ return &slaveAgentValue;
+}
+
+
+//SHORTCUT/WORKAUROUND -> TODO: make this better!
+void SlaveAgentSlotOfAgent::setScoreValue(int scoreValue) {
+ this->scoreValue = scoreValue;
+}
+int SlaveAgentSlotOfAgent::getScoreValue() {
+ return scoreValue;
+}
+void SlaveAgentSlotOfAgent::setReliabilityValue(float reliabilityValue) {
+ this->reliabilityValue = reliabilityValue;
+}
+float SlaveAgentSlotOfAgent::getReliabilityValue() {
+ return reliabilityValue;
+}
+
+void SlaveAgentSlotOfAgent::addPossibleScore(int score, float reliability) {
+
+ PossibleScore* possibleScore = new PossibleScore;
+ possibleScore->score = score;
+ possibleScore->confOrRel = reliability; //=reliability!
+
+ //printf("bekommen: score = %i, reliability = %.2f\n", score, reliability);
+
+ possibleScores.push_back(possibleScore);
+
+ flagSlaveAgentValueIsSet = true;
+}
+
+bool SlaveAgentSlotOfAgent::getPossibleScore(unsigned int rank, int* score, float* reliability) {
+
+ if (rank < possibleScores.size()) {
+ *score = possibleScores.at(rank)->score;
+ *reliability = possibleScores.at(rank)->confOrRel;
+ return true;
+ }
+
+ return false;
+}
+
+unsigned int SlaveAgentSlotOfAgent::getNumOfPossibleScores() {
+ return possibleScores.size();
+}
+
+void SlaveAgentSlotOfAgent::incPossibleScoreCount() {
+ if (possibleScoreCount >= possibleScores.size()-1)
+ possibleScoreCount = 0;
+ else
+ possibleScoreCount++;
+}
+
+unsigned int SlaveAgentSlotOfAgent::getPossibleScoreCount() {
+ return possibleScoreCount;
+}
+
+void SlaveAgentSlotOfAgent::resetPossibleScoreCount() {
+ possibleScoreCount = 0;
+}
+
+void SlaveAgentSlotOfAgent::clearPossibleScores() {
+ possibleScores.clear();
+}
+
+//NEW Journal
+void SlaveAgentSlotOfAgent::preSaveInScoreHistory() {
+ preLastScore = possibleScores.at(possibleScoreCount)->score;
+ preLastReliability = possibleScores.at(possibleScoreCount)->confOrRel;
+}
+
+void SlaveAgentSlotOfAgent::saveInScoreHistory() {
+
+ lastScore = preLastScore;
+ lastReliability = preLastReliability;
+ timeSinceScoreChange = 0;
+ historySet = true;
+
+}
+
+int SlaveAgentSlotOfAgent::getScoreFromHistory() {
+ return lastScore;
+}
+
+float SlaveAgentSlotOfAgent::getReliabilityFromHistory() {
+ return lastReliability;
+}
+
+void SlaveAgentSlotOfAgent::increaseTimeSinceScoreChange() {
+ timeSinceScoreChange++;
+}
+
+unsigned int SlaveAgentSlotOfAgent::getTimeSinceScoreChange() {
+ return timeSinceScoreChange;
+}
+
+bool SlaveAgentSlotOfAgent::isHistroySet() {
+ return historySet;
+}
+
+
+void SlaveAgentSlotOfAgent::resetSlot() {
+
+ flagSlaveAgentValueIsSet = false;
+ possibleScoreCount = 0;
+ timeSinceScoreChange = 0;
+ historySet = false;
+
+ lSlaveAgentHistory.clear();
+
+ scoreValue = 0;
+ reliabilityValue = 0;
+
+ possibleScores.clear();
+ preLastScore = 0;
+ lastScore = 0;
+ preLastReliability = 0;
+ lastReliability = 0;
+ timeSinceScoreChange = 0;
+ historySet = false;
+
+}
+
+
+bool SlaveAgentSlotOfAgent::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 SlaveAgentSlotOfAgent::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 SlaveAgentSlotOfAgent::get_avlSendBuffer() {
+ return maxBufferLength - get_occSendBuffer();
+}
+
+unsigned int SlaveAgentSlotOfAgent::get_occSendBuffer() {
+ return lSendBuffer.size();
+}
+
+bool SlaveAgentSlotOfAgent::send_msgs() {
+ Channel* comPort = 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<get_occSendBuffer(); i++)
+ while (get_occSendBuffer() > 0) {
+ //TODO: make message handler and shift following lines to it!
+ //TODO: try/catch for pushback function!
+ comPort->send_MsgDown(lSendBuffer.front());
+ lSendBuffer.pop_front();
+ }
+ }
+ }
+ return false;
+}
diff --git a/SA-EWS_Version_2019.03.27/src/SlaveAgentSlotOfAgent.h b/SA-EWS_Version_2019.03.27/src/SlaveAgentSlotOfAgent.h
new file mode 100644
index 0000000..d3e0966
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/SlaveAgentSlotOfAgent.h
@@ -0,0 +1,96 @@
+#ifndef SLAVEAGENTSLOTOFAGENT_HEADERFILE
+#define SLAVEAGENTSLOTOFAGENT_HEADERFILE
+
+#include "SlotOfAgent.h"
+//#include "State.h"
+#include "StabilityModule.h"
+
+#include <vector>
+#include "ScoreConfidenceModule.h"
+
+class SlaveAgentSlotOfAgent : public SlotOfAgent {
+
+ private:
+ //TODO: set- and get function for maxNumOf_mountedSensors;
+ float slaveAgentValue;
+ list<float> lSlaveAgentHistory;
+
+ bool flagSlaveAgentValueIsSet;
+
+ StabilityModule* stabilityModule;
+
+
+
+ //SHORTCUT/WORKAUROUND -> TODO: make this better!
+ int scoreValue;
+ float reliabilityValue;
+
+ //NEW Journal
+ vector<PossibleScore*> possibleScores;
+ unsigned int possibleScoreCount;
+ int preLastScore, lastScore;
+ float preLastReliability, lastReliability;
+ unsigned int timeSinceScoreChange;
+ bool historySet;
+
+ list<Message*> lSendBuffer;
+ unsigned int maxBufferLength;
+
+ 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);
+
+ void printHistory();
+
+
+ bool mountStabilityModule(StabilityModule* stabilityModule);
+ StabilityModule* getStabilityModule();
+
+ //TODO: do it with a function pointer
+ float* getObservationPointer();
+
+
+ //SHORTCUT/WORKAUROUND -> TODO: make this better!
+ void setScoreValue(int scoreValue);
+ int getScoreValue();
+ void setReliabilityValue(float reliabilityValue);
+ float getReliabilityValue();
+
+ void addPossibleScore(int score, float reliability);
+ bool getPossibleScore(unsigned int rank, int* score, float* reliability);
+ unsigned int getNumOfPossibleScores();
+ void incPossibleScoreCount();
+ unsigned int getPossibleScoreCount();
+ void resetPossibleScoreCount();
+ void clearPossibleScores();
+
+ //NEW Journal
+ void preSaveInScoreHistory();
+ void saveInScoreHistory();
+ int getScoreFromHistory();
+ float getReliabilityFromHistory();
+ void increaseTimeSinceScoreChange();
+ unsigned int getTimeSinceScoreChange();
+ bool isHistroySet();
+
+ void resetSlot();
+
+ bool pass_msgToSendBuffer(float msg);
+ bool pass_msgToSendBuffer(int msg);
+ unsigned int get_avlSendBuffer();
+ unsigned int get_occSendBuffer();
+ bool send_msgs();
+};
+
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/Slot.cpp b/SA-EWS_Version_2019.03.27/src/Slot.cpp
new file mode 100644
index 0000000..ea1be21
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/Slot.cpp
@@ -0,0 +1,20 @@
+#include "Slot.h"
+
+#include <stdio.h>
+
+
+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/SA-EWS_Version_2019.03.27/src/Slot.h b/SA-EWS_Version_2019.03.27/src/Slot.h
new file mode 100644
index 0000000..9fe673d
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/SlotOfAgent.cpp b/SA-EWS_Version_2019.03.27/src/SlotOfAgent.cpp
new file mode 100644
index 0000000..bfa8423
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/SlotOfAgent.cpp
@@ -0,0 +1,48 @@
+#include "SlotOfAgent.h"
+
+#include <stdio.h>
+
+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/SA-EWS_Version_2019.03.27/src/SlotOfAgent.h b/SA-EWS_Version_2019.03.27/src/SlotOfAgent.h
new file mode 100644
index 0000000..b923679
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/SlotOfAgent.h
@@ -0,0 +1,28 @@
+#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/SA-EWS_Version_2019.03.27/src/Source.cpp b/SA-EWS_Version_2019.03.27/src/Source.cpp
new file mode 100644
index 0000000..e69de29
diff --git a/SA-EWS_Version_2019.03.27/src/StabilityController.cpp b/SA-EWS_Version_2019.03.27/src/StabilityController.cpp
new file mode 100644
index 0000000..c9739df
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/StabilityController.cpp
@@ -0,0 +1,49 @@
+#include "StabilityController.h"
+#include "printError.h"
+
+StabilityController::StabilityController() {
+
+}
+
+bool StabilityController::mountStabilityModule(StabilityModule* stabilityModule) {
+ if (stabilityModule != NULL) {
+ if (getStabilityModuleSlotNumber(stabilityModule) == -1) {
+ try {
+ vStabilityModules.push_back(stabilityModule);
+ return true;
+ }
+ catch (bad_alloc& error) {
+ printError("bad_alloc caught: ", error.what());
+ }
+ }
+ }
+ return false;
+}
+
+int StabilityController::getStabilityModuleSlotNumber(StabilityModule* stabilityModule) {
+ unsigned int slotNumber = 0;
+ for (auto &stabilityModuleSlot : vStabilityModules) {
+ if (stabilityModuleSlot == stabilityModule) {
+ return slotNumber;
+ }
+ slotNumber++;
+ }
+ return -1;
+}
+
+
+bool StabilityController::demountStabilityModule(StabilityModule* stabilityModule) {
+ if (stabilityModule == NULL) {
+ int stabilityModuleSlot = getStabilityModuleSlotNumber(stabilityModule);
+ if (stabilityModuleSlot >= 0) {
+ try {
+ vStabilityModules.erase(vStabilityModules.begin() + stabilityModuleSlot);
+ return true;
+ }
+ catch (bad_alloc& error) {
+ //TODO
+ }
+ }
+ }
+ return false;
+}
diff --git a/SA-EWS_Version_2019.03.27/src/StabilityController.h b/SA-EWS_Version_2019.03.27/src/StabilityController.h
new file mode 100644
index 0000000..12e68bc
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/StabilityController.h
@@ -0,0 +1,22 @@
+#ifndef STABILITYCONTROLLER_HEADERFILE
+#define STABILITYCONTROLLER_HEADERFILE
+
+#include "Unit.h"
+#include "StabilityModule.h"
+#include <vector>
+
+class StabilityController : public Unit {
+
+ private:
+ vector<StabilityModule*> vStabilityModules;
+
+ public:
+ StabilityController();
+
+ bool mountStabilityModule(StabilityModule* stabilityModule);
+ int getStabilityModuleSlotNumber(StabilityModule* stabilityModule);
+ bool demountStabilityModule(StabilityModule* stabilityModule);
+
+};
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/StabilityModule.cpp b/SA-EWS_Version_2019.03.27/src/StabilityModule.cpp
new file mode 100644
index 0000000..60060ca
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/StabilityModule.cpp
@@ -0,0 +1,119 @@
+#include "StabilityModule.h"
+#include <limits>
+#include <string>
+
+#define MAXDEVIATION (float)0
+
+void StabilityModule::initStabilityModule(char* name) {
+
+ setName(name);
+
+ slidingWindowBufferSize = MAXHISTORYLENGTH;
+ minNumOfRelatedValuesToBeStable = MAXHISTORYLENGTH;
+ maxDeviationToBeStable = MAXDEVIATION;
+
+ confidenceModule = NULL;
+}
+
+StabilityModule::StabilityModule() {
+ initStabilityModule(NO_NAME);
+}
+
+StabilityModule::StabilityModule(char* name) {
+ initStabilityModule(name);
+}
+/*
+bool StabilityModule::mountConfidenceModule(ConfidenceModule *confidenceModule) {
+ if (confidenceModule != NULL) {
+ this->confidenceModule = confidenceValue;
+ return true;
+ }
+ return false;
+}
+
+bool StabilityModule::unmountConfidenceModule() {
+ if (confidenceModule != NULL) {
+ delete confidenceModule;
+ confidenceModule = NULL;
+ return true;
+ }
+ return false;
+}
+*/
+
+bool StabilityModule::installConfidenceModule() {
+ if (confidenceModule == NULL) {
+ confidenceModule = new ConfidenceModule();
+ return true;
+ }
+ return false;
+}
+
+bool StabilityModule::deleteConfidenceModule() {
+ if (confidenceModule != NULL) {
+ delete confidenceModule;
+ confidenceModule = NULL;
+ return true;
+ }
+ return false;
+}
+
+ConfidenceModule* StabilityModule::getConfidenceModule() {
+ return confidenceModule;
+}
+/*
+bool StabilityModule::setAgentSlot(SlaveAgentSlotOfAgent *slot) {
+ if (slot != NULL) {
+ this->slot = slot;
+ return true;
+ }
+ return false;
+}
+*/
+
+bool StabilityModule::setSlidingWindowBufferSize(unsigned int slidingWindowBufferSize) {
+ if (slidingWindowBufferSize <= MAXHISTORYLENGTH) {
+ this->slidingWindowBufferSize = slidingWindowBufferSize;
+ return true;
+ }
+ return false;
+}
+
+bool StabilityModule::setMinNumOfRelatedValuesToBeStable(unsigned int minNumOfRelatedValuesToBeStable) {
+ if (minNumOfRelatedValuesToBeStable <= slidingWindowBufferSize) {
+ this->minNumOfRelatedValuesToBeStable = minNumOfRelatedValuesToBeStable;
+ return true;
+ }
+ return false;
+}
+
+bool StabilityModule::setMaxDeviationToBeStable(float maxDeviationToBeStable) {
+ if (maxDeviationToBeStable <= UINT_MAX) {
+ this->maxDeviationToBeStable = maxDeviationToBeStable;
+ return true;
+ }
+ return false;
+}
+
+bool StabilityModule::setObservationPointer(float* observationPointerActualValue, list<HistoryEntry*>* observationPointerHistory) {
+ if (observationPointerActualValue && observationPointerHistory) {
+ this->observationPointerActualValueFloat = observationPointerActualValue;
+ this->observationPointerHistoryFloat = observationPointerHistory;
+ return true;
+ }
+ return false;
+}
+
+bool StabilityModule::setObservationPointer(int* observationPointerActualValue, list<HistoryEntry*>* observationPointerHistory) {
+ if (observationPointerActualValue && observationPointerHistory) {
+ this->observationPointerActualValueInt = observationPointerActualValue;
+ this->observationPointerHistoryInt = observationPointerHistory;
+ return true;
+ }
+ return false;
+}
+
+bool StabilityModule::deleteObservationPointer() {
+ //TODO
+ return false;
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/StabilityModule.h b/SA-EWS_Version_2019.03.27/src/StabilityModule.h
new file mode 100644
index 0000000..9497a31
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/StabilityModule.h
@@ -0,0 +1,58 @@
+#ifndef STABILITYMODULE_HEADERFILE
+#define STABILITYMODULE_HEADERFILE
+
+//#include "Module.h"
+#include "Unit.h"
+//#include "SlaveAgentSlotOfAgent.h"
+#include "ConfidenceModule.h"
+#include "HistoryEntry.h"
+#include <list>
+
+#define MAXHISTORYLENGTH 100
+
+class StabilityModule : public Unit {
+//class StabilityModule : public Module {
+
+private:
+ //SlaveAgentSlotOfAgent *slot;
+
+ ConfidenceModule *confidenceModule;
+ //float confidenceValue;
+
+ bool flagVariablesWereStable;
+ unsigned int slidingWindowBufferSize;
+ unsigned int minNumOfRelatedValuesToBeStable;
+ float maxDeviationToBeStable;
+
+ float* observationPointerActualValueFloat;
+ list<HistoryEntry*>* observationPointerHistoryFloat;
+
+ int* observationPointerActualValueInt;
+ list<HistoryEntry*>* observationPointerHistoryInt;
+
+
+ void initStabilityModule(char* name);
+
+public:
+ StabilityModule();
+ StabilityModule(char* name);
+
+ bool mountConfidenceModule(ConfidenceModule *confidenceModule);
+ bool unmountConfidenceModule();
+
+ bool installConfidenceModule();
+ bool deleteConfidenceModule();
+ ConfidenceModule* getConfidenceModule();
+
+ //bool setAgentSlot(SlaveAgentSlotOfAgent *slot);
+
+ bool setSlidingWindowBufferSize(unsigned int slidingWindowBufferSize);
+ bool setMinNumOfRelatedValuesToBeStable(unsigned int minNumOfRelatedValuesToBeStable);
+ bool setMaxDeviationToBeStable(float maxDeviationToBeStable);
+
+ bool setObservationPointer(float* observationPointerActualValue, list<HistoryEntry*>* observationPointerHistory);
+ bool setObservationPointer(int* observationPointerActualValue, list<HistoryEntry*>* observationPointerHistory);
+ bool deleteObservationPointer();
+};
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/State.cpp b/SA-EWS_Version_2019.03.27/src/State.cpp
new file mode 100644
index 0000000..53a9200
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/State.cpp
@@ -0,0 +1,253 @@
+#include "State.h"
+
+#include "printError.h"
+#include "relationChecker.h"
+
+#define INJECTIONPARTITIONING 10
+
+State::State() {
+ //discreteAveragePartitionSize = INJECTIONPARTITIONING;
+ discreteAveragePartitionCounter = 0;
+}
+/*
+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<SubState*>* 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<SubState*>* 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<SubState*>* 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);
+}
+
+
+
+/*
+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);
+}
+
+*/
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/State.h b/SA-EWS_Version_2019.03.27/src/State.h
new file mode 100644
index 0000000..c19d754
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/State.h
@@ -0,0 +1,73 @@
+#ifndef STATE_HEADERFILE
+#define STATE_HEADERFILE
+
+#include "SlaveAgentSlotOfAgent.h"
+#include "SubState.h"
+#include <vector>
+
+class State {
+
+ private:
+
+ vector<SubState*> vInputSubStates;
+ vector<SubState*> vOutputSubStates;
+
+ //unsigned int discreteAveragePartitionSize;
+ unsigned int discreteAveragePartitionCounter;
+
+ /*
+ StatisticValue continuousStatisticValue;
+ vector<AverageValue*> vDiscreteAveragePartition;
+
+ bool addDiscreteAveragePartition();
+ */
+
+ bool addSubState(vector<SubState*>* vSubStates, SlaveAgentSlotOfAgent* slot);
+
+ bool variablesAreRelated(vector<SubState*>* vSubStates, float thresholdToBeRelated);
+
+ bool checkSubStatesForNotDrifting(vector<SubState*>* vSubStates, unsigned int discreteAveragePartitionSize, unsigned int compareDistanceDiscreteAveragePartition, float thresholdNotDrift);
+
+ 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);
+
+
+
+ /*
+
+
+ bool injectValue(float value);
+ bool valueIsRelated(float value, float thresholdToAverage);
+
+ bool isNew();
+
+ unsigned int getNumberOfInjections();
+
+ void deleteState();
+ */
+
+
+};
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/StateHandler.cpp b/SA-EWS_Version_2019.03.27/src/StateHandler.cpp
new file mode 100644
index 0000000..1c12af0
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/StateHandler.cpp
@@ -0,0 +1,838 @@
+#include "StateHandler.h"
+
+#include <algorithm>
+#include "printError.h"
+#include "rlutil.h"
+
+//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
+
+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;
+
+
+ //XXX - only for now:
+ //csv_writer = new CSV_Writer("CSV Writer", "C:\\csv-data\\Bearing-DefectWithoutLoad.csv");
+ //csv_writer = new CSV_Writer("CSV Writer", "C:\\csv-data\\Bearing-DefectWithLoad.csv");
+ //csv_writer = new CSV_Writer("CSV Writer", "C:\\csv-data\\ChangeSpeed.csv");
+ //csv_writer = new CSV_Writer("CSV Writer", "C:\\csv-data\\WearOut.csv");
+ //csv_writer = new CSV_Writer("CSV Writer", "C:\\csv-data\\NormalOperationChangingLoad.csv");
+ //csv_writer = new CSV_Writer("CSV Writer", "C:\\csv-data\\NormalOperation.csv");
+ csv_writer = new CSV_Writer("C:\\csv-data\\NormalOperation.csv");
+
+ //csv_writer = new CSV_Writer("CSV Writer", "C:\\csv-data\\WearOut4pc.csv");
+ //csv_writer = new CSV_Writer("CSV Writer", "C:\\csv-data\\WearOut5pc.csv");
+ //csv_writer = new CSV_Writer("CSV Writer", "C:\\csv-data\\WearOut6pc.csv");
+ //csv_writer = new CSV_Writer("CSV Writer", "C:\\csv-data\\WearOut7pc.csv");
+ //csv_writer = new CSV_Writer("CSV Writer", "C:\\csv-data\\WearOut8pc.csv");
+ //csv_writer = new CSV_Writer("CSV Writer", "C:\\csv-data\\WearOut9pc.csv");
+ //csv_writer = new CSV_Writer("CSV Writer", "C:\\csv-data\\WearOut10pc.csv");
+ //csv_writer = new CSV_Writer("CSV Writer", "C:\\csv-data\\WearOut20pc.csv");
+ //csv_writer = new CSV_Writer("CSV Writer", "C:\\csv-data\\Wearing-out-HedyehNew.csv");
+
+
+
+
+ //printf("jetzt");
+ //getchar();
+}
+
+StateHandler::StateHandler() {
+ setName(NO_NAME);
+ initStateHandler();
+}
+
+StateHandler::StateHandler(char* name) {
+ setName(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<SlaveAgentSlotOfAgent*>* 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::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::variableIsStable(SlaveAgentSlotOfAgent* variable) {
+ if ((variable->getHistoryLength() >= slidingWindowBufferSize - 1) && (variable->getNumberOfRelativesToActualValue(thresholdToBeStable) >= minNumOfRelatedValuesToBeStable)) //-1 because actual value is not in the history
+ return true;
+ return false;
+}
+
+
+
+
+bool StateHandler::variablesAreStable(vector<SlaveAgentSlotOfAgent*>* 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;
+}
+
+
+State* StateHandler::makeNewState() {
+ printf(" >> New State\n");
+ 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;
+ }
+
+
+ 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<State*>::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);
+ }
+ }
+ */
+
+}
+
+
+
+
+//XXX - only for now
+bool test = true;
+unsigned int brokenCounter = 0, driftCounter = 0;
+
+void printDrift() {
+ driftCounter++;
+ setColor(YELLOW);
+ printf(" >> DRIFT\n");
+ setColor(GREY);
+ test = true;
+}
+
+void printBroken() {
+ brokenCounter++;
+ setColor(LIGHTRED);
+ printf(" >> BROKEN\n");
+ setColor(GREY);
+ test = true;
+}
+
+//XXX - only for now
+unsigned int old_cycle = 1;
+
+void StateHandler::trigger(unsigned int cycle) {
+ printf("cycle: %u\n", cycle);
+
+ //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;
+ //getchar();
+
+
+ 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();
+ }
+
+
+
+
+
+
+ /*
+ if (vStates.empty()) {
+ //XXX - What to do if addStateAndMakeItActive returns a false?
+ addStateAndMakeItActive();
+ //XXX - What to do if injectValues returns a false?
+ activeState->injectValues(discreteAveragePartitionSize);
+ }
+ else {
+ bool flagInputUnchanged = false;
+ bool flagOutputUnchanged = false;
+
+ if (activeState != NULL) {
+ activeState->inputVariablesAreRelated(thresholdToBeRelated);
+ activeState->outputVariablesAreRelated(thresholdToBeRelated);
+ }
+
+ if (flagInputUnchanged && flagOutputUnchanged) {
+
+ printf(" >> unchanged\n");
+
+ //XXX - What to do if injectValues returns a false?
+ activeState->injectValues(discreteAveragePartitionSize);
+
+ //Check for drift
+ if (!activeState->checkAllVariablesForNotDrifting(discreteAveragePartitionSize, compareDistanceDiscreteAveragePartition, thresholdNotDrift)) {
+ driftCounter++;
+ setColor(TXTCOLOR_YELLOW);
+ printf(" >> DRIFT\n");
+ setColor(GREY);
+ test = true;
+ }
+ }
+ else if ((!flagInputUnchanged && !flagOutputUnchanged)) {
+
+ printf(" >> changed\n");
+
+ eraseStatesWithLessInjections();
+
+ if (!findRelatedStateAndMakeItActive()) {
+ //XXX - What to do if addStateAndMakeItActive returns a false?
+ addStateAndMakeItActive();
+ }
+
+ //XXX - What to do if injectValues returns a false?
+ activeState->injectValues(discreteAveragePartitionSize);
+
+ //Check for drift NEUUUU!
+ if (!activeState->checkAllVariablesForNotDrifting(discreteAveragePartitionSize, compareDistanceDiscreteAveragePartition, thresholdNotDrift)) {
+ driftCounter++;
+ setColor(TXTCOLOR_YELLOW);
+ printf(" >> DRIFT\n");
+ setColor(GREY);
+ test = true;
+ }
+
+
+ }
+ else {
+ brokenCounter++;
+ setColor(LIGHTRED);
+ printf(" >> BROKEN\n");
+ setColor(GREY);
+ test = true;
+ }
+ }
+
+
+
+
+ printf(" -- Number of States: %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();
+}
+
+
+
+
+
+/*
+void StateHandler :: initStateHandler() {
+ //activeState = NULL;
+ thresholdToAverage = THRESHOLDTOAVG;
+ minNumOfChangedForValidStateChange = MINNUMCHANGEDFORVALIDSTATECHANGE;
+
+ minimumInjectionsForBeingState = MININJFORBEINGSTATE;
+}
+
+StateHandler :: StateHandler() {
+ setName(NO_NAME);
+ initStateHandler();
+}
+
+StateHandler :: StateHandler(char* name) {
+ setName(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<SlaveAgentSlotOfAgent*>::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;
+}
+*/
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/StateHandler.h b/SA-EWS_Version_2019.03.27/src/StateHandler.h
new file mode 100644
index 0000000..0587c7c
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/StateHandler.h
@@ -0,0 +1,115 @@
+#ifndef STATEHANDLER_HEADERFILE
+#define STATEHANDLER_HEADERFILE
+
+//#include "Module.h"
+#include "Unit.h"
+#include "SlaveAgentSlotOfAgent.h"
+#include "State.h"
+
+#include "StateVariable.h"
+#include <vector>
+
+//XXX - only for now
+#include "CSV_Writer.h"
+
+
+using namespace std;
+
+class StateHandler : public Unit {
+//class StateHandler : public Module {
+
+ private:
+ //XXX - Maybe Object "StateVariable" between StateHandler and Slot?!
+ vector<SlaveAgentSlotOfAgent*> vInputVariables;
+ vector<SlaveAgentSlotOfAgent*> vOutputVariables;
+
+ vector<State*> 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;
+
+
+ void initStateHandler();
+
+ bool addVariable(vector<SlaveAgentSlotOfAgent*>* vVariables, SlaveAgentSlotOfAgent* slot);
+ bool StateHandler::variableIsStable(SlaveAgentSlotOfAgent* variable);
+ bool variablesAreStable(vector<SlaveAgentSlotOfAgent*>* vVariables);
+
+ State* makeNewState();
+
+ bool addActiveStateToStateVector();
+ //bool addStateAndMakeItActive();
+
+ bool makeNewActiveState();
+
+ State* findRelatedState();
+ bool findRelatedStateAndMakeItActive();
+
+ void eraseStatesWithLessInjections();
+
+
+ //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();
+
+
+
+ /*
+ private:
+ vector<SlaveAgentSlotOfAgent*> 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
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/StateModule.cpp b/SA-EWS_Version_2019.03.27/src/StateModule.cpp
new file mode 100644
index 0000000..3722303
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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() {
+ setName(NO_NAME);
+ initStateModule();
+}
+
+StateModule :: StateModule(char* name) {
+ initStateModule();
+ setName(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/SA-EWS_Version_2019.03.27/src/StateModule.h b/SA-EWS_Version_2019.03.27/src/StateModule.h
new file mode 100644
index 0000000..56496d7
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/StateModule.h
@@ -0,0 +1,34 @@
+#ifndef STATEMODULE_HEADERFILE
+#define STATEMODULE_HEADERFILE
+/*
+#include "State.h"
+#include "Module.h"
+#include <vector>
+
+using namespace std;
+
+class StateModule : public Module {
+
+ private:
+ vector<State*> 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/SA-EWS_Version_2019.03.27/src/StateVariable.cpp b/SA-EWS_Version_2019.03.27/src/StateVariable.cpp
new file mode 100644
index 0000000..e785824
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/StateVariable.cpp
@@ -0,0 +1,5 @@
+#include "StateVariable.h"
+
+StateVariable::StateVariable() {
+
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/StateVariable.h b/SA-EWS_Version_2019.03.27/src/StateVariable.h
new file mode 100644
index 0000000..814ef8a
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/StatisticValue.cpp b/SA-EWS_Version_2019.03.27/src/StatisticValue.cpp
new file mode 100644
index 0000000..2c232df
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/StatisticValue.h b/SA-EWS_Version_2019.03.27/src/StatisticValue.h
new file mode 100644
index 0000000..966b8be
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/SubState.cpp b/SA-EWS_Version_2019.03.27/src/SubState.cpp
new file mode 100644
index 0000000..75a6070
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/SubState.cpp
@@ -0,0 +1,138 @@
+#include "SubState.h"
+
+#include "printError.h"
+#include "relationChecker.h"
+
+
+SubState::SubState() {
+
+
+}
+
+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();
+ }
+ }
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/SubState.h b/SA-EWS_Version_2019.03.27/src/SubState.h
new file mode 100644
index 0000000..79ea8a9
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/SubState.h
@@ -0,0 +1,42 @@
+#ifndef SUBSTATE_HEADERFILE
+#define SUBSTATE_HEADERFILE
+
+#include "SlaveAgentSlotOfAgent.h"
+#include "StatisticValue.h"
+
+#include <vector>
+
+class SubState {
+
+ private:
+ SlaveAgentSlotOfAgent* slot;
+ StatisticValue statisticValue;
+ vector<AverageValue*> vDiscreteAverage;
+
+ bool lastDiscreteAverageBlockIsCompleted(unsigned int discreteAveragePartitionSize);
+
+ 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);
+};
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/Testbench.cpp b/SA-EWS_Version_2019.03.27/src/Testbench.cpp
new file mode 100644
index 0000000..4bff4bb
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/Testbench.cpp
@@ -0,0 +1,264 @@
+#include "Testbench.h"
+
+#include "printError.h"
+#include <stdio.h>
+
+#define MAXNUMOF_REGISTEREDCAGENTS 1000
+#define MAXNUMOF_REGISTEREDCHANNELS 1000
+#define MAXNUMOF_REGISTEREDSENSORS 1000
+
+//#define PRINT
+//#define STOP_EVERY_CYCLE
+//#define STOP_EVERY_CYCLE_AFTER_SAMPLE 738
+
+
+using namespace std;
+
+void Testbench :: init_testbench() {
+ maxNumOf_registeredAgents = MAXNUMOF_REGISTEREDCAGENTS;
+ maxNumOf_registeredChannels = MAXNUMOF_REGISTEREDCHANNELS;
+ maxNumOf_registeredSensors = MAXNUMOF_REGISTEREDSENSORS;
+}
+
+Testbench :: Testbench() {
+ setName(NO_NAME);
+ init_testbench();
+}
+
+Testbench :: Testbench(char* name) {
+ setName(name);
+ init_testbench();
+}
+
+bool Testbench :: register_agent(Agent* agent) {
+ AgentSlotOfTestbench* agentSlot = new AgentSlotOfTestbench();
+ if(agentSlot != NULL) {
+ if(agentSlot->set_agent(agent)) {
+ try {
+ if(vector_registeredAgents.size() < maxNumOf_registeredAgents) {
+ 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() < maxNumOf_registeredSensors) {
+ 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() < maxNumOf_registeredChannels) {
+ 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 flagStop = true;
+
+
+void Testbench :: simulate(unsigned int rounds) {
+
+ for(unsigned int cycle =1; cycle <=rounds; cycle++) {
+
+#ifdef PRINT
+ printf("\n------------------- round %u -------------------\n", cycle);
+#endif // PRINT
+
+ //change the signals
+ for(auto &sensorSlot : vector_registeredSensors) {
+ Sensor *sensor = sensorSlot->get_sensor();
+ if(sensor != NULL) {
+ CSVreaderModule *csvReader = sensorSlot->get_csvReaderModule();
+ if(csvReader != NULL) {
+ float inputValue;
+ if(csvReader->get_next_value(&inputValue)) {
+ //printf("%s neuer wert\n", csvReader->getName().c_str());
+
+ sensor->set_sensorValue(inputValue);
+ sensor->set_flag_sensor_value_is_valid(true);
+
+ //printf("%s red: %f\n", csvReader->getName().c_str(), inputValue);
+ }
+ else {
+ //printf("%s NIX\n", csvReader->getName().c_str());
+ sensor->set_flag_sensor_value_is_valid(false);
+ }
+ }
+ }
+ }
+
+ //trigger sensors -> they send information to agents
+ for(auto &sensorSlot : vector_registeredSensors) {
+ Sensor *sensor = sensorSlot->get_sensor();
+ if(sensor != NULL) {
+ sensor->trigger();
+ }
+ }
+
+ //trigger channels -> they transport the information
+ for(auto &channelSlot : vector_registeredChannels) {
+ Channel *channel = channelSlot->get_channel();
+ if(channel != NULL) {
+ channel->trigger();
+ }
+ }
+
+ //trigger agents -> agents do their job
+ for(auto &agentSlot : vector_registeredAgents) {
+ Agent *agent = agentSlot->get_agent();
+ if(agent != NULL) {
+ agent->trigger(cycle);
+ }
+ }
+
+#ifdef STOP_EVERY_CYCLE_AFTER_SAMPLE
+#ifndef STOP_EVERY_CYCLE
+ if (cycle >= STOP_EVERY_CYCLE_AFTER_SAMPLE)
+ getchar();
+#endif // !STOP_EVERY_CYCLE
+#endif // STOP_EVERY_CYCLE_AFTER_SAMPLE
+#ifdef STOP_EVERY_CYCLE
+ if (flagStop == true) {
+ char c = getchar();
+ if (c == 'c')
+ flagStop = false;
+ }
+#endif // STOP_EVERY_CYCLE
+
+
+ }
+
+
+ /*
+ //XXX - only for now (close CSV-Files
+ for (auto &agentSlot : vector_registeredAgents) {
+ Agent *agent = agentSlot->get_agent();
+ if (agent != NULL) {
+ StateHandler *stateHandler = agent->get_stateHandler();
+ if (stateHandler != NULL) {
+ stateHandler->closeCsvFile();
+ }
+ }
+ }
+ */
+
+ //printf("close csv writer\n");
+ for (auto &agentSlot : vector_registeredAgents) {
+ agentSlot->get_agent()->closeCSV();
+ }
+
+}
+
+
+void Testbench::clearTestbench() {
+
+ for (auto &agentSlot : vector_registeredAgents) {
+ Agent *agent = agentSlot->get_agent();
+ if (agent != NULL) {
+ agent->resetAgent();
+ }
+ }
+
+ for (auto &sensorSlot : vector_registeredSensors) {
+
+ Sensor* sensor = sensorSlot->get_sensor();
+ if (sensor != NULL) {
+ sensor->resetSensor();
+ }
+ }
+
+ for (auto &channelSlot : vector_registeredChannels) {
+
+ Channel* channel = channelSlot->get_channel();
+ if (channel != NULL) {
+ channel->resetChannel();
+ }
+ }
+
+ vector_registeredAgents.clear();
+ vector_registeredChannels.clear();
+ vector_registeredSensors.clear();
+
+}
+
diff --git a/SA-EWS_Version_2019.03.27/src/Testbench.h b/SA-EWS_Version_2019.03.27/src/Testbench.h
new file mode 100644
index 0000000..21e971c
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/Testbench.h
@@ -0,0 +1,119 @@
+#ifndef TESTBENCH_HEADERFILE
+#define TESTBENCH_HEADERFILE
+
+#include "AgentSlotOfTestbench.h"
+#include "ChannelSlotOfTestbench.h"
+#include "CSVreaderModule.h"
+#include "SensorSlotOfTestbench.h"
+#include "Unit.h"
+#include <vector>
+
+/*
+#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;
+
+//class Testbench : public Module {
+class Testbench : public Unit {
+
+ private:
+ //TODO: set- and get function for maxNumOf_registeredAgents;
+ vector<AgentSlotOfTestbench*> vector_registeredAgents;
+ unsigned int maxNumOf_registeredAgents;
+
+ //TODO: set- and get function for maxNumOf_registeredChannels;
+ vector<ChannelSlotOfTestbench*> vector_registeredChannels;
+ unsigned int maxNumOf_registeredChannels;
+
+ //TODO: set- and get function for maxNumOf_registeredSensors;
+ vector<SensorSlotOfTestbench*> vector_registeredSensors;
+ unsigned int maxNumOf_registeredSensors;
+
+ void init_testbench();
+
+ public:
+ Testbench();
+ Testbench(char* name);
+
+ bool register_agent(Agent* agent);
+
+ bool register_sensor(Sensor* sensor);
+ SensorSlotOfTestbench* get_sensorSlotAddressOfTestbench(Sensor* sensor);
+
+ bool register_channel(Channel* channel);
+
+ void simulate(unsigned int rounds);
+
+ void clearTestbench();
+
+
+ /*
+ 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
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/Unit.cpp b/SA-EWS_Version_2019.03.27/src/Unit.cpp
new file mode 100644
index 0000000..3c99f53
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/Unit.cpp
@@ -0,0 +1,35 @@
+#include "Unit.h"
+#include <string.h>
+
+unsigned int Unit::numOfUnits = 0;
+unsigned int Unit::idCounter = 0;
+
+Unit::Unit() : id(idCounter) {
+ numOfUnits++;
+ idCounter++;
+}
+
+Unit::Unit(string name) : id(idCounter), name(name) {
+ numOfUnits++;
+ idCounter++;
+}
+
+Unit::~Unit() {
+ numOfUnits--;
+}
+
+unsigned int Unit::getId() {
+ return id;
+}
+
+unsigned int Unit::getNumOfUnits() {
+ return numOfUnits;
+}
+
+void Unit::setName(string name) {
+ this->name = name;
+}
+
+string Unit::getName() {
+ return name;
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/Unit.h b/SA-EWS_Version_2019.03.27/src/Unit.h
new file mode 100644
index 0000000..81b256b
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/Unit.h
@@ -0,0 +1,46 @@
+#ifndef UNIT_HEADERFILE
+#define UNIT_HEADERFILE
+
+//TODO: get rid of these preprocessor things
+#define NO_NAME "unnamed"
+#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
+
+#include <string>
+
+using namespace std;
+
+class Unit {
+
+ protected:
+ const unsigned int id;
+ static unsigned int numOfUnits;
+ static unsigned int idCounter;
+
+ string name;
+
+ public:
+
+ Unit();
+ Unit(string name);
+
+ ~Unit();
+
+ unsigned int getId();
+ unsigned int getNumOfUnits();
+
+ void setName(string name);
+ string getName();
+
+};
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/abstraction_functions.cpp b/SA-EWS_Version_2019.03.27/src/abstraction_functions.cpp
new file mode 100644
index 0000000..e69de29
diff --git a/SA-EWS_Version_2019.03.27/src/abstraction_functions.h b/SA-EWS_Version_2019.03.27/src/abstraction_functions.h
new file mode 100644
index 0000000..0b2db65
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/abstraction_interface.cpp b/SA-EWS_Version_2019.03.27/src/abstraction_interface.cpp
new file mode 100644
index 0000000..59ae617
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/abstraction_interface.h b/SA-EWS_Version_2019.03.27/src/abstraction_interface.h
new file mode 100644
index 0000000..0b0a7b6
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/attach_modules.cpp b/SA-EWS_Version_2019.03.27/src/attach_modules.cpp
new file mode 100644
index 0000000..61fa61f
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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(LIGHTCYAN);
+ printf("%s ", historyModule->getName().c_str());
+ setColor(GREY);
+ printf("(id: %03u) ", historyModule->getId());
+ if(sensorSlotOfAgent->set_historyModule(historyModule)) {
+ setColor(LIGHTGREEN);
+ printf("attached ");
+ setColor(GREY);
+ printf("to Sensor ");
+ setColor(LIGHTCYAN);
+ printf("%s ", sensor->getName().c_str());
+ setColor(GREY);
+ printf("(id: %03u) in Agent ", sensor->getId());
+ setColor(LIGHTCYAN);
+ printf("%s ", agent->getName().c_str());
+ setColor(GREY);
+ printf("(id: %03u)\n", agent->getId());
+ return true;
+ }
+ else {
+ setColor(LIGHTRED);
+ printf("Couldn't attach the HistoryModule!\n");
+ setColor(GREY);
+ }
+ }
+ else {
+ setColor(LIGHTRED);
+ printf(" > Couldn't attach the HistoryModule because Sensor isn't mounted in %s (id: %03u)!\n", agent->getName().c_str(), agent->getId());
+ setColor(GREY);
+ }
+ }
+ else {
+ setColor(LIGHTRED);
+ printf(" > Couldn't attach the HistoryModule because Agent, Channel, or HistoryModule is not valid!\n");
+ setColor(GREY);
+ }
+ return false;
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/attach_modules.h b/SA-EWS_Version_2019.03.27/src/attach_modules.h
new file mode 100644
index 0000000..1dc98a2
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/attach_modulesToTestbench.cpp b/SA-EWS_Version_2019.03.27/src/attach_modulesToTestbench.cpp
new file mode 100644
index 0000000..d292557
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/attach_modulesToTestbench.cpp
@@ -0,0 +1,60 @@
+#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) {
+#ifdef PRINT
+ printf(" > CSV-Reader ");
+ setColor(LIGHTCYAN);
+ printf("%s ", csvReaderModule->getName().c_str());
+ setColor(GREY);
+ printf("(id: %03u) ", csvReaderModule->getId());
+#endif // PRINT
+ if(sensorSlot->set_csvReaderModule(csvReaderModule)) {
+#ifdef PRINT
+ setColor(LIGHTGREEN);
+ printf("attached ");
+ setColor(GREY);
+ printf("to Sensor ");
+ setColor(LIGHTCYAN);
+ printf("%s ", sensor->getName().c_str());
+ setColor(GREY);
+ printf("(id: %03u) in Testbench ", sensor->getId());
+ setColor(LIGHTCYAN);
+ printf("%s ", testbench->getName().c_str());
+ setColor(GREY);
+ printf("(id: %03u)\n", testbench->getId());
+#endif // PRINT
+ return true;
+ }
+ else {
+#ifdef PRINT
+ setColor(LIGHTRED);
+ printf("Couldn't attach the CSVreaderModule!\n");
+ setColor(GREY);
+#endif // PRINT
+ }
+ }
+ else {
+#ifdef PRINT
+ setColor(LIGHTRED);
+ printf(" > Couldn't attach the CSVreaderModule because Sensor isn't registered in %s (id: %03u)!\n", testbench->getName().c_str(), testbench->getId());
+ setColor(GREY);
+#endif // PRINT
+ }
+ }
+ else {
+#ifdef PRINT
+ setColor(LIGHTRED);
+ printf(" > Couldn't attach the CSVreaderModule because Testbench, Sensorm or CSVreaderModule is not valid!\n");
+ setColor(GREY);
+#endif // PRINT
+ }
+ return false;
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/attach_modulesToTestbench.h b/SA-EWS_Version_2019.03.27/src/attach_modulesToTestbench.h
new file mode 100644
index 0000000..f4716f1
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/boundary_check.cpp b/SA-EWS_Version_2019.03.27/src/boundary_check.cpp
new file mode 100644
index 0000000..e994273
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/boundary_check.h b/SA-EWS_Version_2019.03.27/src/boundary_check.h
new file mode 100644
index 0000000..5b5fc88
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/clock.cpp b/SA-EWS_Version_2019.03.27/src/clock.cpp
new file mode 100644
index 0000000..43a8c5b
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/clock.cpp
@@ -0,0 +1,21 @@
+#include "clock.h"
+#include <Windows.h>
+#include <stdio.h>
+
+/*
+typedef struct timeval {
+ long tv_sec;
+ long tv_usec;
+} timeval;
+*/
+
+Clock :: Clock() {
+
+}
+
+void Clock :: initiate_clock() {
+ SYSTEMTIME st;
+ GetSystemTime(&st);
+
+ //printf("hour %i\n", st.wHour);
+}
diff --git a/SA-EWS_Version_2019.03.27/src/clock.h b/SA-EWS_Version_2019.03.27/src/clock.h
new file mode 100644
index 0000000..6cf7365
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/create_unit.cpp b/SA-EWS_Version_2019.03.27/src/create_unit.cpp
new file mode 100644
index 0000000..e629ef3
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/create_unit.cpp
@@ -0,0 +1,561 @@
+#include "create_unit.h"
+#include "rlutil.h"
+
+using namespace rlutil;
+
+//#define PRINT
+
+/*
+template<typename Unit> Unit createUnit(string name) {
+
+Unit unit(name);
+
+cout << " > ";
+setColor(LIGHTCYAN);
+cout << unit.getName() + " ";
+setColor(GREY);
+cout << "ID:";
+setColor(TXTCOLOR_YELLOW);
+cout << unit.getId();
+setColor(LIGHTGREEN);
+cout << " created\n";
+setColor(GREY);
+
+return unit;
+}
+
+template Agent createUnit<Agent>(string name);
+template Sensor createUnit<Sensor>(string name);
+*/
+
+
+
+Agent create_agent() {
+ return create_agent(NO_NAME);
+}
+
+Agent create_agent(char* name) {
+ Agent agent(name);
+#ifdef PRINT
+ printf(" > Agent ");
+ setColor(LIGHTCYAN);
+ printf("%s ", agent.getName().c_str());
+ setColor(GREY);
+ printf("(id: %03u) ", agent.getId());
+ setColor(LIGHTGREEN);
+ printf("created\n");
+ setColor(GREY);
+#endif
+ return agent;
+}
+
+
+Sensor create_sensor() {
+ return create_sensor(NO_NAME);
+}
+
+Sensor create_sensor(char* name) {
+ Sensor sensor(name);
+#ifdef PRINT
+ printf(" > Sensor ");
+ setColor(LIGHTCYAN);
+ printf("%s ", sensor.getName().c_str());
+ setColor(GREY);
+ printf("(id: %03u) ", sensor.getId());
+ setColor(LIGHTGREEN);
+ printf("created\n");
+ setColor(GREY);
+#endif
+ 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(LIGHTCYAN);
+ printf("%s ", historyModule.getName().c_str());
+ setColor(GREY);
+ printf("(id: %03u) ", historyModule.getId());
+ setColor(LIGHTGREEN);
+ printf("created\n");
+ setColor(GREY);
+ if(historyModule.set_maxHistoryLength(history_length)) {
+ printf(" > History length ");
+ setColor(LIGHTGREEN);
+ printf("set ");
+ setColor(GREY);
+ printf("to %u\n", history_length);
+ }
+ else {
+ setColor(LIGHTRED);
+ printf(" > historyLength could not set (out of allowed range).");
+ setColor(GREY);
+ }
+ if(historyModule.set_delimitationMode(delimitation_mode)) {
+ printf(" > Delimitation Mode ");
+ setColor(LIGHTGREEN);
+ printf("set ");
+ setColor(GREY);
+ printf("to %u\n", delimitation_mode);
+ }
+ else {
+ setColor(LIGHTRED);
+ printf(" > Delimitation Mode could not set (out of allowed range).");
+ setColor(GREY);
+ }
+
+ return historyModule;
+ */
+ return NULL;
+}
+
+Channel create_channel(unsigned int transferRate) {
+ return create_channel(NO_NAME, transferRate);
+}
+
+Channel create_channel(char* name, unsigned int transferRate) {
+
+ Channel channel(name);
+#ifdef PRINT
+ printf(" > Channel ");
+ setColor(LIGHTCYAN);
+ printf("%s ", channel.getName().c_str());
+ setColor(GREY);
+ printf("(id: %03u) ", channel.getId());
+ setColor(LIGHTGREEN);
+ printf("created\n");
+ setColor(GREY);
+#endif
+
+ if (channel.setTransferRate(transferRate)) {
+ if (transferRate != 0) {
+#ifdef PRINT
+ printf(" > transfer rate ");
+ setColor(LIGHTGREEN);
+ printf("set ");
+ setColor(GREY);
+ printf("to %i\n", transferRate);
+#endif
+ }
+ else {
+#ifdef PRINT
+ printf(" > transfer ");
+ setColor(LIGHTGREEN);
+ printf("set ");
+ setColor(GREY);
+ printf("to immediately transportation\n");
+#endif
+ }
+ }
+ else {
+#ifdef PRINT
+ setColor(LIGHTRED);
+ printf(" > Transfer Rate out of allowed bounds!\n");
+ setColor(GREY);
+#endif
+ }
+
+ return channel;
+}
+
+
+
+
+Testbench create_testbench() {
+ Testbench testbench;
+#ifdef PRINT
+ printf(" > ");
+ setColor(LIGHTCYAN);
+ printf("%s ", testbench.getName().c_str());
+ rlutil::setColor(GREY);
+ printf("(id: %03u) ", testbench.getId());
+ rlutil::setColor(LIGHTGREEN);
+ printf("created\n");
+ rlutil::setColor(GREY);
+#endif
+ return testbench;
+}
+
+Testbench create_testbench(char* name) {
+ Testbench testbench(name);
+#ifdef PRINT
+ printf(" > ");
+ rlutil::setColor(LIGHTCYAN);
+ printf("%s ", testbench.getName().c_str());
+ rlutil::setColor(GREY);
+ printf("(id: %03u) ", testbench.getId());
+ rlutil::setColor(LIGHTGREEN);
+ printf("created\n");
+ rlutil::setColor(GREY);
+#endif
+ return testbench;
+}
+
+
+Lookuptable create_lookuptable() {
+ Lookuptable lut;
+#ifdef PRINT
+ printf(" > ");
+ rlutil::setColor(LIGHTCYAN);
+ printf("%s ", lut.getName().c_str());
+ rlutil::setColor(GREY);
+ printf("(id: %03u) ", lut.getId());
+ rlutil::setColor(LIGHTGREEN);
+ printf("created\n");
+ rlutil::setColor(GREY);
+#endif
+ return lut;
+}
+
+Lookuptable create_lookuptable(char* name) {
+ Lookuptable lut(name);
+#ifdef PRINT
+ printf(" > ");
+ rlutil::setColor(LIGHTCYAN);
+ printf("%s ", lut.getName().c_str());
+ rlutil::setColor(GREY);
+ printf("(id: %03u) ", lut.getId());
+ rlutil::setColor(LIGHTGREEN);
+ printf("created\n");
+ rlutil::setColor(GREY);
+#endif
+ return lut;
+}
+/*
+void print_confidence_validator(Confidence_Validator conf_valid) {
+printf(" > ");
+rlutil::setColor(LIGHTCYAN);
+printf("%s ", conf_valid.getName().c_str());
+rlutil::setColor(GREY);
+printf("(id: %03u) ", conf_valid.getId());
+rlutil::setColor(LIGHTGREEN);
+printf("created\n");
+rlutil::setColor(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(LIGHTGREEN);
+printf("set\n");
+rlutil::setColor(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(LIGHTGREEN);
+printf("set\n");
+rlutil::setColor(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(AbstractionModule abstraction) {
+#ifdef PRINT
+ printf(" > ");
+ rlutil::setColor(LIGHTCYAN);
+ printf("%s ", abstraction.getName().c_str());
+ rlutil::setColor(GREY);
+ printf("(id: %03u) ", abstraction.getId());
+ rlutil::setColor(LIGHTGREEN);
+ printf("created\n");
+ rlutil::setColor(GREY);
+
+ //TODO: abstraction method printen
+ printf(" - abstraction method %u ", abstraction.get_abstraction_method());
+ rlutil::setColor(LIGHTGREEN);
+ printf("set\n");
+ rlutil::setColor(GREY);
+#endif
+
+ //TODO: auch das hier bissl schöner machen
+ if (abstraction.get_flag_lookuptable_exist(0)) {
+#ifdef PRINT
+ printf(" - position 0 connected mit Look up Table ");
+ rlutil::setColor(LIGHTCYAN);
+ printf("%s ", abstraction.get_lookuptable(0)->getName().c_str());
+ rlutil::setColor(GREY);
+ printf("(id: %03u) ", abstraction.get_lookuptable(0)->getId());
+ rlutil::setColor(LIGHTGREEN);
+ printf("set\n");
+ rlutil::setColor(GREY);
+#endif
+ }
+}
+
+AbstractionModule create_abstraction_module(Lookuptable* lut, unsigned int abstraction_method) {
+ AbstractionModule abstraction(lut, abstraction_method);
+ print_abstraction_module(abstraction);
+
+ return abstraction;
+}
+
+AbstractionModule create_abstraction_module(char* name, Lookuptable* lut, unsigned int abstraction_method) {
+ AbstractionModule abstraction(name, lut, abstraction_method);
+ print_abstraction_module(abstraction);
+
+ return abstraction;
+}
+/*
+void print_bunch_module(Bunch_Module bunch_module) {
+printf(" > ");
+rlutil::setColor(LIGHTCYAN);
+printf("%s ", bunch_module.getName().c_str());
+rlutil::setColor(GREY);
+printf("(id: %03u) ", bunch_module.getId());
+rlutil::setColor(LIGHTGREEN);
+printf("created\n");
+rlutil::setColor(GREY);
+
+//TODO: abstraction method printen
+printf(" - abstraction method %u ", bunch_module.get_bunch_method());
+rlutil::setColor(LIGHTGREEN);
+printf("set\n");
+rlutil::setColor(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(char* filepath, int mode) {
+
+ FILE* fpointer;
+ bool file_opened;
+
+ if (mode == CSV_MODE_READ) {
+ file_opened = fopen_s(&fpointer, filepath, "r");
+ }
+ else if (mode == CSV_MODE_WRITE) {
+ file_opened = fopen_s(&fpointer, filepath, "w");
+ }
+ else {
+#ifdef PRINT
+ printf("File pointer mode for \"%s\" ", filepath);
+ rlutil::setColor(LIGHTRED);
+ printf("is not supported!\n");
+ rlutil::setColor(GREY);
+#endif
+ return NULL;
+ }
+
+ if (file_opened == 0) {
+ return fpointer;
+ }
+#ifdef PRINT
+ printf("File pointer \"%s\" ", filepath);
+ rlutil::setColor(LIGHTRED);
+ printf("could not created!\n");
+ rlutil::setColor(GREY);
+#endif
+ return NULL;
+}
+
+void print_csv_reader(CSVreaderModule* csvReaderModule, char* filepath) {
+#ifdef PRINT
+ printf(" > ");
+ rlutil::setColor(LIGHTCYAN);
+ printf("%s ", csvReaderModule->getName().c_str());
+ rlutil::setColor(GREY);
+ printf("(id: %03u) for \"%s\" ", csvReaderModule->getId(), filepath);
+ rlutil::setColor(LIGHTGREEN);
+ printf("created\n");
+ rlutil::setColor(GREY);
+#endif
+}
+
+CSVreaderModule* create_CSVreaderModule(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, char* filepath, unsigned int column, unsigned int start_row) {
+
+ FILE* fpointer = make_file_pointer(filepath, CSV_MODE_READ);
+
+ //printf("filepathCSVreader: %s\n", filepath);
+
+ if (fpointer) {
+ CSVreaderModule* csvr = new CSVreaderModule(name, fpointer, column, start_row);
+ print_csv_reader(csvr, filepath);
+
+ return csvr;
+ }
+ else {
+ CSVreaderModule* csvr = new CSVreaderModule();
+ printf("file gibts nicht\n");
+ getchar();
+
+ return csvr;
+ }
+}
+
+
+StateHandler create_stateHandler() {
+ return create_stateHandler(NO_NAME);
+}
+
+StateHandler create_stateHandler(char* name) {
+ StateHandler stateHandler(name);
+ return stateHandler;
+}
+
+
+StabilityModule createStabilityModule(unsigned int slidingWindowBufferSize, unsigned int minNumOfRelatedValuesToBeStable, float maxDeviationToBeStable) {
+ return createStabilityModule(NO_NAME, slidingWindowBufferSize, minNumOfRelatedValuesToBeStable, maxDeviationToBeStable);
+}
+
+StabilityModule createStabilityModule(char* name, unsigned int slidingWindowBufferSize, unsigned int minNumOfRelatedValuesToBeStable, float maxDeviationToBeStable) {
+ StabilityModule stabilityModule(name);
+#ifdef PRINT
+ printf(" > Stability Module ");
+ rlutil::setColor(LIGHTCYAN);
+ printf("%s ", stabilityModule.getName().c_str());
+ rlutil::setColor(GREY);
+ printf("(id: %03u) ", stabilityModule.getId());
+ rlutil::setColor(LIGHTGREEN);
+ printf("created\n");
+ rlutil::setColor(GREY);
+#endif
+
+ if (stabilityModule.setSlidingWindowBufferSize(slidingWindowBufferSize)) {
+#ifdef PRINT
+ printf(" > Sliding Window Size ");
+ setColor(LIGHTGREEN);
+ printf("set ");
+ setColor(GREY);
+ printf("to %u\n", slidingWindowBufferSize);
+#endif
+ }
+ else {
+#ifdef PRINT
+ setColor(LIGHTRED);
+ printf(" > Sliding Window Size couldn't be set to %u\n", slidingWindowBufferSize);
+ setColor(GREY);
+#endif
+ }
+
+ if (stabilityModule.setMinNumOfRelatedValuesToBeStable(minNumOfRelatedValuesToBeStable)) {
+#ifdef PRINT
+ printf(" > Minimum Number of Related Values to be Stable ");
+ setColor(LIGHTGREEN);
+ printf("set ");
+ setColor(GREY);
+ printf("to %u\n", minNumOfRelatedValuesToBeStable);
+#endif
+ }
+ else {
+#ifdef PRINT
+ setColor(LIGHTRED);
+ printf(" > Minimum Number of Related Values to be Stable couldn't be set to %u\n", minNumOfRelatedValuesToBeStable);
+ setColor(GREY);
+#endif
+ }
+
+ if (stabilityModule.setMaxDeviationToBeStable(maxDeviationToBeStable)) {
+#ifdef PRINT
+ printf(" > Maximum Deviation to be Stable ");
+ setColor(LIGHTGREEN);
+ printf("set ");
+ setColor(GREY);
+ printf("to %f\n", maxDeviationToBeStable);
+#endif
+ }
+ else {
+#ifdef PRINT
+ setColor(LIGHTRED);
+ printf(" > Maximum Deviation to be Stable couldn't be set to %f\n", maxDeviationToBeStable);
+ setColor(GREY);
+#endif
+ }
+
+ return stabilityModule;
+}
+
+ConfidenceModule createConfidenceModule() {
+ return createConfidenceModule(NO_NAME);
+}
+
+ConfidenceModule createConfidenceModule(char* name) {
+ ConfidenceModule confidenceModule(name);
+#ifdef PRINT
+ printf(" > Confidence Module ");
+ rlutil::setColor(LIGHTCYAN);
+ printf("%s ", confidenceModule.getName().c_str());
+ rlutil::setColor(GREY);
+ printf("(id: %03u) ", confidenceModule.getId());
+ rlutil::setColor(LIGHTGREEN);
+ printf("created\n");
+ rlutil::setColor(GREY);
+#endif
+ return confidenceModule;
+}
+
+
+HistoryModule createHistoryModule(unsigned int maximumHistoryLength) {
+ return createHistoryModule(NO_NAME, maximumHistoryLength);
+}
+
+HistoryModule createHistoryModule(char* name, unsigned int maximumHistoryLength) {
+ HistoryModule historyModule(name, maximumHistoryLength);
+#ifdef PRINT
+ printf(" > History Module ");
+ rlutil::setColor(LIGHTCYAN);
+ printf("%s ", historyModule.getName().c_str());
+ rlutil::setColor(GREY);
+ printf("(id: %03u) ", historyModule.getId());
+ rlutil::setColor(LIGHTGREEN);
+ printf("created\n");
+ rlutil::setColor(GREY);
+#endif
+ return historyModule;
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/create_unit.h b/SA-EWS_Version_2019.03.27/src/create_unit.h
new file mode 100644
index 0000000..2434131
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/create_unit.h
@@ -0,0 +1,83 @@
+#ifndef CREATE_UNIT_HEADERFILE
+#define CREATE_UNIT_HEADERFILE
+
+#include "Agent.h"
+#include "CSVreaderModule.h"
+#include "HistoryModule.h"
+#include "Sensor.h"
+#include "Testbench.h"
+#include "StabilityModule.h"
+#include "ConfidenceModule.h"
+
+
+//#include "Testbench.h"
+#include "Lookuptable.h"
+#include "AbstractionModule.h"
+/*
+#include "ConfidenceModule.h"
+#include "Bunch_Module.h"
+*/
+
+#define CSV_MODE_READ 0
+#define CSV_MODE_WRITE 1
+
+
+//template<typename Unit> Unit createUnit(string name);
+
+
+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 transferRate);
+Channel create_channel(char* name, unsigned int transferRate);
+
+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(char* filepath, unsigned int column, unsigned int start_row);
+CSVreaderModule* create_CSVreaderModule(char* name, char* filepath, unsigned int column, unsigned int start_row);
+
+StateHandler create_stateHandler();
+StateHandler create_stateHandler(char* name);
+
+StabilityModule createStabilityModule(unsigned int slidingWindowBufferSize, unsigned int minNumOfRelatedValuesToBeStable, float maxDeviationToBeStable);
+StabilityModule createStabilityModule(char* name, unsigned int slidingWindowBufferSize, unsigned int minNumOfRelatedValuesToBeStable, float maxDeviationToBeStable);
+
+ConfidenceModule createConfidenceModule();
+ConfidenceModule createConfidenceModule(char* name);
+
+HistoryModule createHistoryModule(unsigned int maximumHistoryLength);
+HistoryModule createHistoryModule(char* name, unsigned int maximumHistoryLength);
+
+
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/csvparser.c b/SA-EWS_Version_2019.03.27/src/csvparser.c
new file mode 100644
index 0000000..ffd6ebc
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/csvparser.c
@@ -0,0 +1,239 @@
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <errno.h>
+
+#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);
+}
+
+const 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(const CsvRow *csvRow) {
+ return csvRow->numOfFields_;
+}
+
+const char **CsvParser_getFields(const 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/SA-EWS_Version_2019.03.27/src/csvparser.h b/SA-EWS_Version_2019.03.27/src/csvparser.h
new file mode 100644
index 0000000..3cb3612
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/csvparser.h
@@ -0,0 +1,48 @@
+#ifndef CSVPARSER_H
+#define CSVPARSER_H
+
+#include <stdio.h>
+
+#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);
+const CsvRow *CsvParser_getHeader(CsvParser *csvParser);
+CsvRow *CsvParser_getRow(CsvParser *csvParser);
+int CsvParser_getNumFields(const CsvRow *csvRow);
+const char **CsvParser_getFields(const 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/SA-EWS_Version_2019.03.27/src/extremaValues.cpp b/SA-EWS_Version_2019.03.27/src/extremaValues.cpp
new file mode 100644
index 0000000..e69de29
diff --git a/SA-EWS_Version_2019.03.27/src/extremaValues.h b/SA-EWS_Version_2019.03.27/src/extremaValues.h
new file mode 100644
index 0000000..f496826
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/gen_agent_test2.vcxproj b/SA-EWS_Version_2019.03.27/src/gen_agent_test2.vcxproj
new file mode 100644
index 0000000..cad37f9
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/gen_agent_test2.vcxproj
@@ -0,0 +1,331 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <ItemGroup Label="ProjectConfigurations">
+ <ProjectConfiguration Include="Debug|Win32">
+ <Configuration>Debug</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Debug|x64">
+ <Configuration>Debug</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release|Win32">
+ <Configuration>Release</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release|x64">
+ <Configuration>Release</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
+ </ItemGroup>
+ <PropertyGroup Label="Globals">
+ <ProjectGuid>{0C0999CA-0E04-4B84-BB4F-98008F98E2CA}</ProjectGuid>
+ <Keyword>Win32Proj</Keyword>
+ <RootNamespace>gen_agent_test2</RootNamespace>
+ <WindowsTargetPlatformVersion>10.0.15063.0</WindowsTargetPlatformVersion>
+ </PropertyGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+ <ConfigurationType>Application</ConfigurationType>
+ <UseDebugLibraries>true</UseDebugLibraries>
+ <PlatformToolset>v141</PlatformToolset>
+ <CharacterSet>Unicode</CharacterSet>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+ <ConfigurationType>Application</ConfigurationType>
+ <UseDebugLibraries>true</UseDebugLibraries>
+ <PlatformToolset>v141</PlatformToolset>
+ <CharacterSet>Unicode</CharacterSet>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+ <ConfigurationType>Application</ConfigurationType>
+ <UseDebugLibraries>false</UseDebugLibraries>
+ <PlatformToolset>v141</PlatformToolset>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ <CharacterSet>Unicode</CharacterSet>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+ <ConfigurationType>Application</ConfigurationType>
+ <UseDebugLibraries>false</UseDebugLibraries>
+ <PlatformToolset>v141</PlatformToolset>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ <CharacterSet>Unicode</CharacterSet>
+ </PropertyGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+ <ImportGroup Label="ExtensionSettings">
+ </ImportGroup>
+ <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <PropertyGroup Label="UserMacros" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+ <LinkIncremental>true</LinkIncremental>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+ <LinkIncremental>true</LinkIncremental>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+ <LinkIncremental>false</LinkIncremental>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+ <LinkIncremental>false</LinkIncremental>
+ </PropertyGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+ <ClCompile>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <WarningLevel>Level3</WarningLevel>
+ <Optimization>Disabled</Optimization>
+ <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ClCompile>
+ <Link>
+ <SubSystem>Console</SubSystem>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+ <ClCompile>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <WarningLevel>Level3</WarningLevel>
+ <Optimization>Disabled</Optimization>
+ <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ClCompile>
+ <Link>
+ <SubSystem>Console</SubSystem>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+ <ClCompile>
+ <WarningLevel>Level3</WarningLevel>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <Optimization>MaxSpeed</Optimization>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <IntrinsicFunctions>true</IntrinsicFunctions>
+ <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ClCompile>
+ <Link>
+ <SubSystem>Console</SubSystem>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <EnableCOMDATFolding>true</EnableCOMDATFolding>
+ <OptimizeReferences>true</OptimizeReferences>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+ <ClCompile>
+ <WarningLevel>Level3</WarningLevel>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <Optimization>MaxSpeed</Optimization>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <IntrinsicFunctions>true</IntrinsicFunctions>
+ <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ClCompile>
+ <Link>
+ <SubSystem>Console</SubSystem>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <EnableCOMDATFolding>true</EnableCOMDATFolding>
+ <OptimizeReferences>true</OptimizeReferences>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemGroup>
+ <ClCompile Include="abstraction_functions.cpp" />
+ <ClCompile Include="AbstractionModule.cpp" />
+ <ClCompile Include="abstraction_interface.cpp" />
+ <ClCompile Include="Agent.cpp" />
+ <ClCompile Include="AgentSlotOfTestbench.cpp" />
+ <ClCompile Include="attach_modules.cpp" />
+ <ClCompile Include="attach_modulesToTestbench.cpp" />
+ <ClCompile Include="AverageValue.cpp" />
+ <ClCompile Include="boundary_check.cpp" />
+ <ClCompile Include="Bunch_Module.cpp" />
+ <ClCompile Include="Channel.cpp" />
+ <ClCompile Include="ChannelSlotOfTestbench.cpp" />
+ <ClCompile Include="clock.cpp" />
+ <ClCompile Include="CombinedConfidenceModule.cpp" />
+ <ClCompile Include="ConfidenceModule.cpp" />
+ <ClCompile Include="ConfidenceHandler.cpp" />
+ <ClCompile Include="Continuous_Average.cpp" />
+ <ClCompile Include="create_unit.cpp" />
+ <ClCompile Include="CrossReliabilityProfileModule.cpp" />
+ <ClCompile Include="Cross_Confidence_Validator.cpp" />
+ <ClCompile Include="csvparser.c" />
+ <ClCompile Include="CSVreaderModule.cpp" />
+ <ClCompile Include="CSV_Writer.cpp" />
+ <ClCompile Include="DiscreteFunction.cpp" />
+ <ClCompile Include="DiscreteFunctionBlock.cpp" />
+ <ClCompile Include="Discrete_Average.cpp" />
+ <ClCompile Include="Domain.cpp" />
+ <ClCompile Include="Evaluation.cpp" />
+ <ClCompile Include="ExtremeValue.cpp" />
+ <ClCompile Include="FilterModule.cpp" />
+ <ClCompile Include="HandlerOfAgent.cpp" />
+ <ClCompile Include="HistoryController.cpp" />
+ <ClCompile Include="HistoryEntry.cpp" />
+ <ClCompile Include="HistoryModule.cpp" />
+ <ClCompile Include="inAgentsRegistrations.cpp" />
+ <ClCompile Include="LinearFunction.cpp" />
+ <ClCompile Include="LinearFunctionBlock.cpp" />
+ <ClCompile Include="Lookuptable.cpp" />
+ <ClCompile Include="main.cpp" />
+ <ClCompile Include="MasterAgentHandlerOfAgent.cpp" />
+ <ClCompile Include="MasterAgentSlotOfAgent.cpp" />
+ <ClCompile Include="MaximumValue.cpp" />
+ <ClCompile Include="Message.cpp" />
+ <ClCompile Include="MinumumValue.cpp" />
+ <ClCompile Include="Module.cpp" />
+ <ClCompile Include="mountModules.cpp" />
+ <ClCompile Include="mount_nodes.cpp" />
+ <ClCompile Include="Node.cpp" />
+ <ClCompile Include="ConfidenceModule_old.cpp" />
+ <ClCompile Include="printError.cpp" />
+ <ClCompile Include="Range.cpp" />
+ <ClCompile Include="register_in_testbench.cpp" />
+ <ClCompile Include="relationChecker.cpp" />
+ <ClCompile Include="ReliabilityModule.cpp" />
+ <ClCompile Include="ScoreConfidence.cpp" />
+ <ClCompile Include="ScoreConfidenceModule.cpp" />
+ <ClCompile Include="Sensor.cpp" />
+ <ClCompile Include="SensorHandlerOfAgent.cpp" />
+ <ClCompile Include="SensorSlotOfAgent.cpp" />
+ <ClCompile Include="Setup.cpp" />
+ <ClCompile Include="SetupOLD.cpp" />
+ <ClCompile Include="SetupAgent.cpp" />
+ <ClCompile Include="SetupMountedHistoryModule.cpp" />
+ <ClCompile Include="setupModule.cpp" />
+ <ClCompile Include="SetupMountedAgent.cpp" />
+ <ClCompile Include="SetupMountedSensor.cpp" />
+ <ClCompile Include="setupNode.cpp" />
+ <ClCompile Include="SetupSensor.cpp" />
+ <ClCompile Include="SetupStabilityModule.cpp" />
+ <ClCompile Include="setup_lookuptable.cpp" />
+ <ClCompile Include="SineModule.cpp" />
+ <ClCompile Include="SlaveAgentHandlerOfAgent.cpp" />
+ <ClCompile Include="SlaveAgentSlotOfAgent.cpp" />
+ <ClCompile Include="Slot.cpp" />
+ <ClCompile Include="SlotOfAgent.cpp" />
+ <ClCompile Include="Source.cpp" />
+ <ClCompile Include="StabilityController.cpp" />
+ <ClCompile Include="StabilityModule.cpp" />
+ <ClCompile Include="State.cpp" />
+ <ClCompile Include="StateHandler.cpp" />
+ <ClCompile Include="StateModule.cpp" />
+ <ClCompile Include="StateVariable.cpp" />
+ <ClCompile Include="StatisticValue.cpp" />
+ <ClCompile Include="SubState.cpp" />
+ <ClCompile Include="test1.cpp" />
+ <ClCompile Include="test2.cpp" />
+ <ClCompile Include="Testbench.cpp" />
+ <ClCompile Include="SensorSlotOfTestbench.cpp" />
+ <ClCompile Include="Unit.cpp" />
+ <ClCompile Include="user_method_abstraction.cpp" />
+ </ItemGroup>
+ <ItemGroup>
+ <ClInclude Include="abstraction_functions.h" />
+ <ClInclude Include="AbstractionModule.h" />
+ <ClInclude Include="abstraction_interface.h" />
+ <ClInclude Include="Agent.h" />
+ <ClInclude Include="AgentSlotOfTestbench.h" />
+ <ClInclude Include="attach_modules.h" />
+ <ClInclude Include="attach_modulesToTestbench.h" />
+ <ClInclude Include="AverageValue.h" />
+ <ClInclude Include="boundary_check.h" />
+ <ClInclude Include="Bunch_Module.h" />
+ <ClInclude Include="Channel.h" />
+ <ClInclude Include="ChannelSlotOfTestbench.h" />
+ <ClInclude Include="clock.h" />
+ <ClInclude Include="CombinedConfidenceModule.h" />
+ <ClInclude Include="ConfidenceModule.h" />
+ <ClInclude Include="ConfidenceHandler.h" />
+ <ClInclude Include="Continuous_Average.h" />
+ <ClInclude Include="create_unit.h" />
+ <ClInclude Include="CrossReliabilityProfileModule.h" />
+ <ClInclude Include="Cross_Confidence_Validator.h" />
+ <ClInclude Include="csvparser.h" />
+ <ClInclude Include="CSVreaderModule.h" />
+ <ClInclude Include="CSV_Writer.h" />
+ <ClInclude Include="DiscreteFunction.h" />
+ <ClInclude Include="DiscreteFunctionBlock.h" />
+ <ClInclude Include="Discrete_Average.h" />
+ <ClInclude Include="Domain.h" />
+ <ClInclude Include="Evaluation.h" />
+ <ClInclude Include="ExtremeValue.h" />
+ <ClInclude Include="FilterModule.h" />
+ <ClInclude Include="HandlerOfAgent.h" />
+ <ClInclude Include="HistoryController.h" />
+ <ClInclude Include="HistoryEntry.h" />
+ <ClInclude Include="HistoryModule.h" />
+ <ClInclude Include="inAgentsRegistrations.h" />
+ <ClInclude Include="instruction_set_architecture.h" />
+ <ClInclude Include="LinearFunction.h" />
+ <ClInclude Include="LinearFunctionBlock.h" />
+ <ClInclude Include="Lookuptable.h" />
+ <ClInclude Include="MasterAgentHandlerOfAgent.h" />
+ <ClInclude Include="MasterAgentSlotOfAgent.h" />
+ <ClInclude Include="MaximumValue.h" />
+ <ClInclude Include="Message.h" />
+ <ClInclude Include="MinumumValue.h" />
+ <ClInclude Include="Module.h" />
+ <ClInclude Include="mountModules.h" />
+ <ClInclude Include="mount_nodes.h" />
+ <ClInclude Include="Node.h" />
+ <ClInclude Include="ConfidenceModule_old.h" />
+ <ClInclude Include="printError.h" />
+ <ClInclude Include="project_settings.h" />
+ <ClInclude Include="Range.h" />
+ <ClInclude Include="register_in_testbench.h" />
+ <ClInclude Include="relationChecker.h" />
+ <ClInclude Include="ReliabilityModule.h" />
+ <ClInclude Include="rlutil.h" />
+ <ClInclude Include="ScoreConfidence.h" />
+ <ClInclude Include="ScoreConfidenceModule.h" />
+ <ClInclude Include="Sensor.h" />
+ <ClInclude Include="SensorHandlerOfAgent.h" />
+ <ClInclude Include="SensorSlotOfAgent.h" />
+ <ClInclude Include="settings.h" />
+ <ClInclude Include="Setup.hpp" />
+ <ClInclude Include="SetupOLD.h" />
+ <ClInclude Include="SetupAgent.h" />
+ <ClInclude Include="SetupMountedHistoryModule.h" />
+ <ClInclude Include="setupModule.h" />
+ <ClInclude Include="SetupMountedAgent.h" />
+ <ClInclude Include="SetupMountedSensor.h" />
+ <ClInclude Include="setupNode.h" />
+ <ClInclude Include="SetupSensor.h" />
+ <ClInclude Include="SetupStabilityModule.h" />
+ <ClInclude Include="setup_lookuptable.h" />
+ <ClInclude Include="SineModule.h" />
+ <ClInclude Include="SlaveAgentHandlerOfAgent.h" />
+ <ClInclude Include="SlaveAgentSlotOfAgent.h" />
+ <ClInclude Include="Slot.h" />
+ <ClInclude Include="SlotOfAgent.h" />
+ <ClInclude Include="StabilityController.h" />
+ <ClInclude Include="StabilityModule.h" />
+ <ClInclude Include="State.h" />
+ <ClInclude Include="StateHandler.h" />
+ <ClInclude Include="StateModule.h" />
+ <ClInclude Include="StateVariable.h" />
+ <ClInclude Include="StatisticValue.h" />
+ <ClInclude Include="SubState.h" />
+ <ClInclude Include="test1.h" />
+ <ClInclude Include="test2.h" />
+ <ClInclude Include="Testbench.h" />
+ <ClInclude Include="SensorSlotOfTestbench.h" />
+ <ClInclude Include="Unit.h" />
+ <ClInclude Include="user_method_abstraction.h" />
+ </ItemGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+ <ImportGroup Label="ExtensionTargets">
+ </ImportGroup>
+</Project>
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/gen_agent_test2.vcxproj.filters b/SA-EWS_Version_2019.03.27/src/gen_agent_test2.vcxproj.filters
new file mode 100644
index 0000000..d390cd1
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/gen_agent_test2.vcxproj.filters
@@ -0,0 +1,567 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <ItemGroup>
+ <Filter Include="Source Files">
+ <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
+ <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+ </Filter>
+ <Filter Include="Header Files">
+ <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
+ <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+ </Filter>
+ <Filter Include="Resource Files">
+ <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
+ <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
+ </Filter>
+ </ItemGroup>
+ <ItemGroup>
+ <ClCompile Include="main.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Agent.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Sensor.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Node.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Evaluation.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="boundary_check.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="clock.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Channel.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Testbench.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Unit.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="register_in_testbench.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="create_unit.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="mount_nodes.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="user_method_abstraction.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="abstraction_interface.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="abstraction_functions.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Lookuptable.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Range.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="setup_lookuptable.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Bunch_Module.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="CSV_Writer.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Cross_Confidence_Validator.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Continuous_Average.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Discrete_Average.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Slot.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="printError.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="HistoryModule.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="AbstractionModule.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="attach_modules.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="SensorSlotOfTestbench.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="ChannelSlotOfTestbench.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="AgentSlotOfTestbench.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="attach_modulesToTestbench.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="CSVreaderModule.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Module.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="HistoryEntry.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="StateModule.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="State.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="StateHandler.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="SlaveAgentSlotOfAgent.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="SlotOfAgent.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="SensorSlotOfAgent.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="SensorHandlerOfAgent.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="SlaveAgentHandlerOfAgent.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="HandlerOfAgent.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Message.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="MasterAgentHandlerOfAgent.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="MasterAgentSlotOfAgent.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="inAgentsRegistrations.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="AverageValue.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="MinumumValue.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="MaximumValue.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="ExtremeValue.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="StatisticValue.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="SubState.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="StateVariable.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="relationChecker.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="setupNode.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="SineModule.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="FilterModule.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="StabilityModule.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="ConfidenceModule_old.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="ConfidenceModule.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="LinearFunction.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Domain.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="setupModule.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="mountModules.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="CombinedConfidenceModule.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="ConfidenceHandler.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="StabilityController.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="test1.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="test2.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="SetupAgent.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="SetupMountedAgent.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="SetupMountedSensor.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="SetupSensor.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="SetupMountedHistoryModule.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="HistoryController.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="SetupStabilityModule.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="SetupOLD.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Setup.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="LinearFunctionBlock.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="ReliabilityModule.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="csvparser.c">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="ScoreConfidenceModule.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="Source.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="ScoreConfidence.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="DiscreteFunctionBlock.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="DiscreteFunction.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="CrossReliabilityProfileModule.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ </ItemGroup>
+ <ItemGroup>
+ <ClInclude Include="Agent.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="Sensor.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="project_settings.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="Node.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="Evaluation.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="boundary_check.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="clock.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="Channel.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="Testbench.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="Unit.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="rlutil.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="register_in_testbench.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="create_unit.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="mount_nodes.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="user_method_abstraction.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="settings.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="abstraction_interface.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="abstraction_functions.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="Lookuptable.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="Range.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="setup_lookuptable.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="Bunch_Module.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="CSV_Writer.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="Cross_Confidence_Validator.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="instruction_set_architecture.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="Continuous_Average.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="Discrete_Average.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="printError.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="HistoryModule.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="Slot.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="AbstractionModule.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="attach_modules.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="SensorSlotOfTestbench.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="ChannelSlotOfTestbench.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="AgentSlotOfTestbench.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="attach_modulesToTestbench.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="CSVreaderModule.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="Module.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="HistoryEntry.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="StateModule.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="State.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="StateHandler.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="SlaveAgentSlotOfAgent.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="SlotOfAgent.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="SensorSlotOfAgent.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="SensorHandlerOfAgent.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="SlaveAgentHandlerOfAgent.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="HandlerOfAgent.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="Message.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="MasterAgentHandlerOfAgent.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="MasterAgentSlotOfAgent.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="inAgentsRegistrations.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="AverageValue.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="MinumumValue.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="MaximumValue.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="ExtremeValue.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="StatisticValue.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="SubState.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="StateVariable.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="relationChecker.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="setupNode.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="SineModule.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="FilterModule.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="StabilityModule.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="ConfidenceModule_old.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="ConfidenceModule.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="LinearFunction.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="Domain.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="setupModule.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="mountModules.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="CombinedConfidenceModule.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="ConfidenceHandler.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="StabilityController.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="test1.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="test2.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="SetupAgent.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="SetupMountedAgent.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="SetupMountedSensor.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="SetupSensor.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="SetupMountedHistoryModule.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="HistoryController.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="SetupStabilityModule.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="SetupOLD.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="Setup.hpp">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="LinearFunctionBlock.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="ReliabilityModule.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="csvparser.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="ScoreConfidenceModule.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="ScoreConfidence.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="DiscreteFunctionBlock.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="DiscreteFunction.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ <ClInclude Include="CrossReliabilityProfileModule.h">
+ <Filter>Source Files</Filter>
+ </ClInclude>
+ </ItemGroup>
+</Project>
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/gen_agent_test2.vcxproj.user b/SA-EWS_Version_2019.03.27/src/gen_agent_test2.vcxproj.user
new file mode 100644
index 0000000..972cede
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/gen_agent_test2.vcxproj.user
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+ <LocalDebuggerCommandArguments>
+ </LocalDebuggerCommandArguments>
+ <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+ <LocalDebuggerCommandArguments>
+ </LocalDebuggerCommandArguments>
+ <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
+ </PropertyGroup>
+</Project>
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/inAgentsRegistrations.cpp b/SA-EWS_Version_2019.03.27/src/inAgentsRegistrations.cpp
new file mode 100644
index 0000000..db1e471
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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(LIGHTCYAN);
+ printf("%s ", channel->getName().c_str());
+ setColor(GREY);
+ printf("(id: %03u) ", channel->getId());
+ setColor(LIGHTGREEN);
+ printf("registered ");
+ setColor(GREY);
+ printf("as ");
+ setColor(LIGHTGREEN);
+ printf("Input Variable ");
+ setColor(GREY);
+ printf("in stateHandler of ");
+ setColor(LIGHTCYAN);
+ printf("%s ", masteragent->getName().c_str());
+ setColor(GREY);
+ printf("(id: %03u)\n", masteragent->getId());
+ return true;
+ }
+ else {
+ setColor(LIGHTRED);
+ printf(" > Channel %s (id: %03u) is not connected to Agent %s (id: %03u)\n", channel->getName().c_str(), channel->getId(), masteragent->getName().c_str(), masteragent->getId());
+ }
+ }
+ else {
+ setColor(LIGHTRED);
+ printf(" > Channel %s (id: %03u) is not connected to Agent %s (id: %03u)\n", channel->getName().c_str(), channel->getId(), masteragent->getName().c_str(), masteragent->getId());
+ }
+ }
+ else {
+ setColor(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(LIGHTCYAN);
+ printf("%s ", channel->getName().c_str());
+ setColor(GREY);
+ printf("(id: %03u) ", channel->getId());
+ setColor(LIGHTGREEN);
+ printf("registered ");
+ setColor(GREY);
+ printf("as ");
+ setColor(LIGHTGREEN);
+ printf("Output Variable ");
+ setColor(GREY);
+ printf("in stateHandler of ");
+ setColor(LIGHTCYAN);
+ printf("%s ", masteragent->getName().c_str());
+ setColor(GREY);
+ printf("(id: %03u)\n", masteragent->getId());
+ return true;
+ }
+ else {
+ setColor(LIGHTRED);
+ printf(" > Channel %s (id: %03u) is not connected to Agent %s (id: %03u)\n", channel->getName().c_str(), channel->getId(), masteragent->getName().c_str(), masteragent->getId());
+ }
+ }
+ else {
+ setColor(LIGHTRED);
+ printf(" > Channel %s (id: %03u) is not connected to Agent %s (id: %03u)\n", channel->getName().c_str(), channel->getId(), masteragent->getName().c_str(), masteragent->getId());
+ }
+ }
+ else {
+ setColor(LIGHTRED);
+ printf(" > Agent or Channel is not valid\n");
+ }
+ return false;
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/inAgentsRegistrations.h b/SA-EWS_Version_2019.03.27/src/inAgentsRegistrations.h
new file mode 100644
index 0000000..7b181d3
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/instruction_set_architecture.h b/SA-EWS_Version_2019.03.27/src/instruction_set_architecture.h
new file mode 100644
index 0000000..dfbaff9
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/instruction_set_architecture.h
@@ -0,0 +1,29 @@
+#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_AbstractedSensoryDataAndReliability 0x0210
+#define ISA_SuggestedAbstractedSensoryDataAndReliability 0x0211
+
+#define ISA_SlaveAgentData 0x0300
+#define ISA_SlaveAgentWithBinaryConfidenceTag 0x0301
+
+
+
+
+
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/main.cpp b/SA-EWS_Version_2019.03.27/src/main.cpp
new file mode 100644
index 0000000..178f52c
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/main.cpp
@@ -0,0 +1,536 @@
+#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 <iostream>
+#include <stdio.h>
+#include "Testbench.h"
+#include "setupModule.h"
+//#include "mountModules.h"
+
+//OLD STUFF
+#include "SetupOLD.h"
+#include "Lookuptable.h"
+#include "setup_lookuptable.h"
+#include "AbstractionModule.h"
+#include "ReliabilityModule.h"
+
+//#include "DiscreteFunctionBlock.h"
+#include "CrossReliabilityProfileModule.h"
+
+
+#include "Setup.hpp"
+
+
+#include "test1.h"
+
+
+#include "csvparser.h"
+
+
+int main(int argc, char* argv[])
+{
+
+ /*
+ DiscreteFunctionBlock test("relAbs:BTemp", "C:\\csv-data\\test.rff");
+ int x;
+
+ printf("loaded\n");
+
+ x = -1;
+ printf("x = %i -> y = %f\n", x, test.getY(x));
+ x = 0;
+ printf("x = %i -> y = %f\n", x, test.getY(x));
+ x = 1;
+ printf("x = %i -> y = %f\n", x, test.getY(x));
+ x = 2;
+ printf("x = %i -> y = %f\n", x, test.getY(x));
+ x = 3;
+ printf("x = %i -> y = %f\n", x, test.getY(x));
+ x = 4;
+ printf("x = %i -> y = %f\n", x, test.getY(x));
+
+ getchar();
+ */
+
+ /*
+ CrossReliabilityProfileModule test("bla");
+ printf("name: %s\n", test.getName().c_str());
+
+ getchar();
+ */
+
+
+
+ if (argc > 18) {
+
+ //Read configurations
+
+ char rootPath[300];
+ char datasetName[100];
+ char datasetPath[500];
+ unsigned int datasetLength;
+
+ sprintf_s(rootPath, "%s", argv[1]);
+ sprintf_s(datasetName, "%s", argv[2]);
+ sprintf_s(datasetPath, "%s\\Datasets\\%s", rootPath, datasetName);
+
+#ifdef PRINT
+ printf("datasetPath: %s\n", datasetPath);
+#endif // PRINT
+
+ datasetLength = (unsigned int)atoi(argv[3]);
+
+ unsigned int HR = (unsigned int)atoi(argv[4]);
+ unsigned int RR = (unsigned int)atoi(argv[5]);
+ unsigned int SPO2 = (unsigned int)atoi(argv[6]);
+ unsigned int BTemp = (unsigned int)atoi(argv[7]);
+ unsigned int BP = (unsigned int)atoi(argv[8]);
+
+ char destPath[600];
+
+ //sprintf_s(destPath, "%s\\output.csv", argv[16]);
+ sprintf_s(destPath, "%s", argv[9]);
+
+
+ unsigned int HRconfig = (unsigned int)atoi(argv[10]);
+ unsigned int RRconfig = (unsigned int)atoi(argv[11]);
+ unsigned int BPconfig = (unsigned int)atoi(argv[12]);
+ unsigned int SPO2config = (unsigned int)atoi(argv[13]);
+ unsigned int BTempconfig = (unsigned int)atoi(argv[14]);
+
+ unsigned int changeRightWrongDiffConfig = (unsigned int)atoi(argv[15]);
+ unsigned int changeRightWrongTimeConfig = (unsigned int)atoi(argv[16]);
+
+ unsigned int timeConfAndHistSize = (unsigned int)atoi(argv[17]);
+
+ char patientName[50];
+ sprintf_s(patientName, "%s", argv[18]);
+
+ unsigned int crossParam = stof(argv[19]);
+
+
+
+
+
+
+ //Configure RoSA so that it works as EWS system
+
+ unsigned int workingCycle = 1;
+
+ Setup setup;
+
+ Sensor *SensorHR = setup.createUnit<Sensor>("Sensor:HR");
+ setup.setWorkCycle(SensorHR, workingCycle);
+ Sensor *SensorRR = setup.createUnit<Sensor>("Sensor:RR");
+ setup.setWorkCycle(SensorRR, workingCycle);
+ Sensor *SensorBP = setup.createUnit<Sensor>("Sensor:BP");
+ setup.setWorkCycle(SensorBP, workingCycle);
+ Sensor *SensorSPO2 = setup.createUnit<Sensor>("Sensor:SPO2");
+ setup.setWorkCycle(SensorSPO2, workingCycle);
+ Sensor *SensorBTemp = setup.createUnit<Sensor>("Sensor:BTemp");
+ setup.setWorkCycle(SensorBTemp, workingCycle);
+
+ Agent *AgentHR = setup.createUnit<Agent>("Agent:HR");
+ setup.setWorkCycle(AgentHR, workingCycle);
+ Agent *AgentRR = setup.createUnit<Agent>("Agent:RR");
+ setup.setWorkCycle(AgentRR, workingCycle);
+ Agent *AgentBP = setup.createUnit<Agent>("Agent:BP");
+ setup.setWorkCycle(AgentBP, workingCycle);
+ Agent *AgentSPO2 = setup.createUnit<Agent>("Agent:SPO2");
+ setup.setWorkCycle(AgentSPO2, workingCycle);
+ Agent *AgentBTemp = setup.createUnit<Agent>("Agent:BTemp");
+ setup.setWorkCycle(AgentBTemp, workingCycle);
+ Agent *AgentSAEWS = setup.createUnit<Agent>("Agent:AgentSAEWS");
+ setup.setWorkCycle(AgentSAEWS, workingCycle);
+
+ //getchar();
+
+ Channel *channel1HR = setup.createUnit<Channel>("HR");
+ setup.setTransferRate(channel1HR, 0);
+ Channel *channel1RR = setup.createUnit<Channel>("RR");
+ setup.setTransferRate(channel1RR, 0);
+ Channel *channel1BP = setup.createUnit<Channel>("BP");
+ setup.setTransferRate(channel1BP, 0);
+ Channel *channel1SPO2 = setup.createUnit<Channel>("SPO2");
+ setup.setTransferRate(channel1SPO2, 0);
+ Channel *channel1BTemp = setup.createUnit<Channel>("BTemp");
+ setup.setTransferRate(channel1BTemp, 0);
+
+
+
+ Channel *channel2HR = setup.createUnit<Channel>("HR");
+ setup.setTransferRate(channel2HR, MAX_BUFFER_LENGTH);
+ Channel *channel2RR = setup.createUnit<Channel>("RR");
+ setup.setTransferRate(channel2RR, MAX_BUFFER_LENGTH);
+ Channel *channel2BP = setup.createUnit<Channel>("BP");
+ setup.setTransferRate(channel2BP, MAX_BUFFER_LENGTH);
+ Channel *channel2SPO2 = setup.createUnit<Channel>("SPO2");
+ setup.setTransferRate(channel2SPO2, MAX_BUFFER_LENGTH);
+ Channel *channel2BTemp = setup.createUnit<Channel>("BTemp");
+ setup.setTransferRate(channel2BTemp, MAX_BUFFER_LENGTH);
+
+
+ //printf("\nMount Sensors in Agents\n");
+ mount_sensorInAgent(AgentHR, SensorHR, channel1HR);
+ mount_sensorInAgent(AgentRR, SensorRR, channel1RR);
+ mount_sensorInAgent(AgentBP, SensorBP, channel1BP);
+ mount_sensorInAgent(AgentSPO2, SensorSPO2, channel1SPO2);
+ mount_sensorInAgent(AgentBTemp, SensorBTemp, channel1BTemp);
+
+ //printf("\nMount Agents in Agents\n");
+ mount_agentInAgent(AgentSAEWS, AgentHR, channel2HR);
+ mount_agentInAgent(AgentSAEWS, AgentRR, channel2RR);
+ mount_agentInAgent(AgentSAEWS, AgentBP, channel2BP);
+ mount_agentInAgent(AgentSAEWS, AgentSPO2, channel2SPO2);
+ mount_agentInAgent(AgentSAEWS, AgentBTemp, channel2BTemp);
+
+
+ //SHORTCUT/WORKAUROUND -> TODO: make this better!
+ //POLLAK ANGABEN:
+ //printf("\nCreate Reliability Modules\n");
+
+ char ewsConfigFilepath[600];
+
+
+ ReliabilityModule reliabilityHR("rm:HR");
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\rel\\reliabilityAbsoluteHR.rff", rootPath);
+ LinearFunctionBlock relAbsHR("relAbs:HR", ewsConfigFilepath);
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\rel\\reliabilitySlopeHR.rff", rootPath);
+ LinearFunctionBlock relSloHR("relSlo:HR", ewsConfigFilepath);
+ reliabilityHR.setFunctionBlocks(&relAbsHR, &relSloHR);
+
+ ReliabilityModule reliabilityRR("rm:RR");
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\rel\\reliabilityAbsoluteRR.rff", rootPath);
+ LinearFunctionBlock relAbsRR("relAbs:RR", ewsConfigFilepath);
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\rel\\reliabilitySlopeRR.rff", rootPath);
+ LinearFunctionBlock relSloRR("relSlo:RR", ewsConfigFilepath);
+ reliabilityRR.setFunctionBlocks(&relAbsRR, &relSloRR);
+
+ ReliabilityModule reliabilityBP("rm:BP");
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\rel\\reliabilityAbsoluteBP.rff", rootPath);
+ LinearFunctionBlock relAbsBP("relAbs:BP", ewsConfigFilepath);
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\rel\\reliabilitySlopeBP.rff", rootPath);
+ LinearFunctionBlock relSloBP("relSlo:BP", ewsConfigFilepath);
+ reliabilityBP.setFunctionBlocks(&relAbsBP, &relSloBP);
+
+ ReliabilityModule reliabilitySPO2("rm:SPO2");
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\rel\\reliabilityAbsoluteSPO2.rff", rootPath);
+ LinearFunctionBlock relAbsSPO2("relAbs:SPO2", ewsConfigFilepath);
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\rel\\reliabilitySlopeSPO2.rff", rootPath);
+ LinearFunctionBlock relSloSPO2("relSlo:SPO2", ewsConfigFilepath);
+ reliabilitySPO2.setFunctionBlocks(&relAbsSPO2, &relSloSPO2);
+
+ ReliabilityModule reliabilityBTemp("rm:BTemp");
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\rel\\reliabilityAbsoluteBTemp.rff", rootPath);
+ LinearFunctionBlock relAbsBTemp("relAbs:BTemp", ewsConfigFilepath);
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\rel\\reliabilitySlopeBTemp.rff", rootPath);
+ LinearFunctionBlock relSloBTemp("relSlo:BTemp", ewsConfigFilepath);
+ reliabilityBTemp.setFunctionBlocks(&relAbsBTemp, &relSloBTemp);
+
+ //printf("\nMount Reliability Modules in Agents\n");
+ AgentHR->setReliabilityModule(&reliabilityHR);
+ AgentRR->setReliabilityModule(&reliabilityRR);
+ AgentBP->setReliabilityModule(&reliabilityBP);
+ AgentSPO2->setReliabilityModule(&reliabilitySPO2);
+ AgentBTemp->setReliabilityModule(&reliabilityBTemp);
+
+
+
+
+
+
+ //Confidence Module
+ ScoreConfidenceModule scoreConfidencesHR;
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\HR\\%u\\confHRis0.rff", rootPath, HRconfig);
+ LinearFunctionBlock confHRis0("conf:HR=0", ewsConfigFilepath);
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\HR\\%u\\confHRis1.rff", rootPath, HRconfig);
+ LinearFunctionBlock confHRis1("conf:HR=1", ewsConfigFilepath);
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\HR\\%u\\confHRis2.rff", rootPath, HRconfig);
+ LinearFunctionBlock confHRis2("conf:HR=2", ewsConfigFilepath);
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\HR\\%u\\confHRis3.rff", rootPath, HRconfig);
+ LinearFunctionBlock confHRis3("conf:HR=3", ewsConfigFilepath);
+ scoreConfidencesHR.addScoreConfidence(&confHRis0, 0);
+ scoreConfidencesHR.addScoreConfidence(&confHRis1, 1);
+ scoreConfidencesHR.addScoreConfidence(&confHRis2, 2);
+ scoreConfidencesHR.addScoreConfidence(&confHRis3, 3);
+
+ ScoreConfidenceModule scoreConfidencesRR;
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\RR\\%u\\confRRis0.rff", rootPath, RRconfig);
+ LinearFunctionBlock confRRis0("conf:RR=0", ewsConfigFilepath);
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\RR\\%u\\confRRis1.rff", rootPath, RRconfig);
+ LinearFunctionBlock confRRis1("conf:RR=1", ewsConfigFilepath);
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\RR\\%u\\confRRis2.rff", rootPath, RRconfig);
+ LinearFunctionBlock confRRis2("conf:RR=2", ewsConfigFilepath);
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\RR\\%u\\confRRis3.rff", rootPath, RRconfig);
+ LinearFunctionBlock confRRis3("conf:RR=3", ewsConfigFilepath);
+ scoreConfidencesRR.addScoreConfidence(&confRRis0, 0);
+ scoreConfidencesRR.addScoreConfidence(&confRRis1, 1);
+ scoreConfidencesRR.addScoreConfidence(&confRRis2, 2);
+ scoreConfidencesRR.addScoreConfidence(&confRRis3, 3);
+
+ ScoreConfidenceModule scoreConfidencesBP;
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\BP\\%u\\confBPis0.rff", rootPath, BPconfig);
+ LinearFunctionBlock confBPis0("conf:BP=0", ewsConfigFilepath);
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\BP\\%u\\confBPis1.rff", rootPath, BPconfig);
+ LinearFunctionBlock confBPis1("conf:BP=1", ewsConfigFilepath);
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\BP\\%u\\confBPis2.rff", rootPath, BPconfig);
+ LinearFunctionBlock confBPis2("conf:BP=2", ewsConfigFilepath);
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\BP\\%u\\confBPis3.rff", rootPath, BPconfig);
+ LinearFunctionBlock confBPis3("conf:BP=3", ewsConfigFilepath);
+ scoreConfidencesBP.addScoreConfidence(&confBPis0, 0);
+ scoreConfidencesBP.addScoreConfidence(&confBPis1, 1);
+ scoreConfidencesBP.addScoreConfidence(&confBPis2, 2);
+ scoreConfidencesBP.addScoreConfidence(&confBPis3, 3);
+
+ ScoreConfidenceModule scoreConfidencesSPO2;
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\SPO2\\%u\\confSPO2is0.rff", rootPath, SPO2config);
+ LinearFunctionBlock confSPO2is0("conf:SPO2=0", ewsConfigFilepath);
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\SPO2\\%u\\confSPO2is1.rff", rootPath, SPO2config);
+ LinearFunctionBlock confSPO2is1("conf:SPO2=1", ewsConfigFilepath);
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\SPO2\\%u\\confSPO2is2.rff", rootPath, SPO2config);
+ LinearFunctionBlock confSPO2is2("conf:SPO2=2", ewsConfigFilepath);
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\SPO2\\%u\\confSPO2is3.rff", rootPath, SPO2config);
+ LinearFunctionBlock confSPO2is3("conf:SPO2=3", ewsConfigFilepath);
+ scoreConfidencesSPO2.addScoreConfidence(&confSPO2is0, 0);
+ scoreConfidencesSPO2.addScoreConfidence(&confSPO2is1, 1);
+ scoreConfidencesSPO2.addScoreConfidence(&confSPO2is2, 2);
+ scoreConfidencesSPO2.addScoreConfidence(&confSPO2is3, 3);
+
+ ScoreConfidenceModule scoreConfidencesBTemp;
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\BTemp\\%u\\confBTempIs0.rff", rootPath, BTempconfig);
+ LinearFunctionBlock confBTempIs0("conf:BTemp=0", ewsConfigFilepath);
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\BTemp\\%u\\confBTempIs1.rff", rootPath, BTempconfig);
+ LinearFunctionBlock confBTempIs1("conf:BTemp=1", ewsConfigFilepath);
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\BTemp\\%u\\confBTempIs2.rff", rootPath, BTempconfig);
+ LinearFunctionBlock confBTempIs2("conf:BTemp=2", ewsConfigFilepath);
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\BTemp\\%u\\confBTempIs3.rff", rootPath, BTempconfig);
+ LinearFunctionBlock confBTempIs3("conf:BTemp=3", ewsConfigFilepath);
+ scoreConfidencesBTemp.addScoreConfidence(&confBTempIs0, 0);
+ scoreConfidencesBTemp.addScoreConfidence(&confBTempIs1, 1);
+ scoreConfidencesBTemp.addScoreConfidence(&confBTempIs2, 2);
+ scoreConfidencesBTemp.addScoreConfidence(&confBTempIs3, 3);
+
+ //printf("\nMount Score Confidence Modules in Agents\n");
+ AgentHR->setScoreConfidenceModule(&scoreConfidencesHR);
+ AgentRR->setScoreConfidenceModule(&scoreConfidencesRR);
+ AgentBP->setScoreConfidenceModule(&scoreConfidencesBP);
+ AgentSPO2->setScoreConfidenceModule(&scoreConfidencesSPO2);
+ AgentBTemp->setScoreConfidenceModule(&scoreConfidencesBTemp);
+
+
+
+ //CONF CHANGE
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\ChangeRightWrongDiff\\%u\\confidenceChangeRightDiff.rff", rootPath, changeRightWrongDiffConfig);
+ LinearFunctionBlock confChangeRightDiff("conf:ChangeRightDiff", ewsConfigFilepath);
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\ChangeRightWrongDiff\\%u\\confidenceChangeWrongDiff.rff", rootPath, changeRightWrongDiffConfig);
+ LinearFunctionBlock confChangeWrongDiff("conf:ChangeWrongDiff", ewsConfigFilepath);
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\ChangeRightWrongTime\\%u\\confidenceChangeRightTime.rff", rootPath, changeRightWrongTimeConfig);
+ LinearFunctionBlock confChangeRightTime("conf:ChangeRightTime", ewsConfigFilepath);
+ sprintf_s(ewsConfigFilepath, "%s\\EWSconfig\\ChangeRightWrongTime\\%u\\confidenceChangeWrongTime.rff", rootPath, changeRightWrongTimeConfig);
+ LinearFunctionBlock confChangeWrongTime("conf:ChangeWrongTime", ewsConfigFilepath);
+
+ AgentHR->setConfidenceChange(&confChangeRightDiff, &confChangeWrongDiff, &confChangeRightTime, &confChangeWrongTime);
+ AgentRR->setConfidenceChange(&confChangeRightDiff, &confChangeWrongDiff, &confChangeRightTime, &confChangeWrongTime);
+ AgentBP->setConfidenceChange(&confChangeRightDiff, &confChangeWrongDiff, &confChangeRightTime, &confChangeWrongTime);
+ AgentSPO2->setConfidenceChange(&confChangeRightDiff, &confChangeWrongDiff, &confChangeRightTime, &confChangeWrongTime);
+ AgentBTemp->setConfidenceChange(&confChangeRightDiff, &confChangeWrongDiff, &confChangeRightTime, &confChangeWrongTime);
+ AgentSAEWS->setConfidenceChange(&confChangeRightDiff, &confChangeWrongDiff, &confChangeRightTime, &confChangeWrongTime);
+
+
+ //NEW FOR Springer Journal //NOTE: at the moment timeConfAndHistSize is casted from unsigned int to float
+ LinearFunctionBlock* confTimeScoreHasBeen = new LinearFunctionBlock("funcBlock:confValidStateDev");
+ LinearFunction *confTimeScoreHasBeen1 = new LinearFunction();
+ confTimeScoreHasBeen1->setDomain(false, true, (float)0);
+ confTimeScoreHasBeen1->setKandD((float)0, (float)1);
+ confTimeScoreHasBeen->addLinearFunction(confTimeScoreHasBeen1);
+ LinearFunction *confTimeScoreHasBeen2 = new LinearFunction();
+ confTimeScoreHasBeen2->setDomain(true, (float)0, true, (float)timeConfAndHistSize);
+ confTimeScoreHasBeen2->setKandD(0, (float)1, (float)timeConfAndHistSize, (float)0);
+ confTimeScoreHasBeen->addLinearFunction(confTimeScoreHasBeen2);
+ LinearFunction *confTimeScoreHasBeen3 = new LinearFunction();
+ confTimeScoreHasBeen3->setDomain(true, (float)timeConfAndHistSize, false);
+ confTimeScoreHasBeen3->setKandD((float)0, (float)0);
+ confTimeScoreHasBeen->addLinearFunction(confTimeScoreHasBeen3);
+
+ AgentHR->setConfTimeScoreHasBeen(confTimeScoreHasBeen);
+ AgentRR->setConfTimeScoreHasBeen(confTimeScoreHasBeen);
+ AgentBP->setConfTimeScoreHasBeen(confTimeScoreHasBeen);
+ AgentSPO2->setConfTimeScoreHasBeen(confTimeScoreHasBeen);
+ AgentBTemp->setConfTimeScoreHasBeen(confTimeScoreHasBeen);
+ AgentSAEWS->setConfTimeScoreHasBeen(confTimeScoreHasBeen);
+
+ AgentHR->setMaxHistSizePossScores(timeConfAndHistSize);
+ AgentRR->setMaxHistSizePossScores(timeConfAndHistSize);
+ AgentBP->setMaxHistSizePossScores(timeConfAndHistSize);
+ AgentSPO2->setMaxHistSizePossScores(timeConfAndHistSize);
+ AgentBTemp->setMaxHistSizePossScores(timeConfAndHistSize);
+ AgentSAEWS->setMaxHistSizePossScores(timeConfAndHistSize);
+
+
+ char crossProfileFilePath[800];
+
+ CrossReliabilityProfileModule profile("BP");
+ sprintf_s(crossProfileFilePath, "%s\\PatientProfiles\\%s\\BP-BTemp.rff", rootPath, patientName);
+ DiscreteFunctionBlock BPBTempFunctionBlock("BP-BTemp", crossProfileFilePath);
+ profile.setFunctionBlock(&BPBTempFunctionBlock, "BP", "BTemp");
+ sprintf_s(crossProfileFilePath, "%s\\PatientProfiles\\%s\\BP-HR.rff", rootPath, patientName);
+ DiscreteFunctionBlock BPHRFunctionBlock("BP-HR", crossProfileFilePath);
+ profile.setFunctionBlock(&BPHRFunctionBlock, "BP", "HR");
+ sprintf_s(crossProfileFilePath, "%s\\PatientProfiles\\%s\\BP-RR.rff", rootPath, patientName);
+ DiscreteFunctionBlock BPRRFunctionBlock("BP-RR", crossProfileFilePath);
+ profile.setFunctionBlock(&BPRRFunctionBlock, "BP", "RR");
+ sprintf_s(crossProfileFilePath, "%s\\PatientProfiles\\%s\\BP-SPO2.rff", rootPath, patientName);
+ DiscreteFunctionBlock BPSPO2FunctionBlock("BP-SPO2", crossProfileFilePath);
+ profile.setFunctionBlock(&BPSPO2FunctionBlock, "BP", "SPO2");
+
+ sprintf_s(crossProfileFilePath, "%s\\PatientProfiles\\%s\\BTemp-BP.rff", rootPath, patientName);
+ DiscreteFunctionBlock BTempBPFunctionBlock("BTemp-BP", crossProfileFilePath);
+ profile.setFunctionBlock(&BTempBPFunctionBlock, "BTemp", "BP");
+ sprintf_s(crossProfileFilePath, "%s\\PatientProfiles\\%s\\BTemp-HR.rff", rootPath, patientName);
+ DiscreteFunctionBlock BTempHRFunctionBlock("BTemp-HR", crossProfileFilePath);
+ profile.setFunctionBlock(&BTempHRFunctionBlock, "BTemp", "HR");
+ sprintf_s(crossProfileFilePath, "%s\\PatientProfiles\\%s\\BTemp-RR.rff", rootPath, patientName);
+ DiscreteFunctionBlock BTempRRFunctionBlock("BTemp-RR", crossProfileFilePath);
+ profile.setFunctionBlock(&BTempRRFunctionBlock, "BTemp", "RR");
+ sprintf_s(crossProfileFilePath, "%s\\PatientProfiles\\%s\\BTemp-SPO2.rff", rootPath, patientName);
+ DiscreteFunctionBlock BTempSPO2FunctionBlock("BTemp-SPO2", crossProfileFilePath);
+ profile.setFunctionBlock(&BTempSPO2FunctionBlock, "BTemp", "SPO2");
+
+ sprintf_s(crossProfileFilePath, "%s\\PatientProfiles\\%s\\HR-BP.rff", rootPath, patientName);
+ DiscreteFunctionBlock HRBPFunctionBlock("HR-BP", crossProfileFilePath);
+ profile.setFunctionBlock(&HRBPFunctionBlock, "HR", "BP");
+ sprintf_s(crossProfileFilePath, "%s\\PatientProfiles\\%s\\HR-BTemp.rff", rootPath, patientName);
+ DiscreteFunctionBlock HRBTempFunctionBlock("HR-BTemp", crossProfileFilePath);
+ profile.setFunctionBlock(&HRBTempFunctionBlock, "HR", "BTemp");
+ sprintf_s(crossProfileFilePath, "%s\\PatientProfiles\\%s\\HR-RR.rff", rootPath, patientName);
+ DiscreteFunctionBlock HRRRFunctionBlock("HR-RR", crossProfileFilePath);
+ profile.setFunctionBlock(&HRRRFunctionBlock, "HR", "RR");
+ sprintf_s(crossProfileFilePath, "%s\\PatientProfiles\\%s\\HR-SPO2.rff", rootPath, patientName);
+ DiscreteFunctionBlock HRSPO2FunctionBlock("HR-SPO2", crossProfileFilePath);
+ profile.setFunctionBlock(&HRSPO2FunctionBlock, "HR", "SPO2");
+
+ sprintf_s(crossProfileFilePath, "%s\\PatientProfiles\\%s\\RR-BP.rff", rootPath, patientName);
+ DiscreteFunctionBlock RRBPFunctionBlock("RR-BP", crossProfileFilePath);
+ profile.setFunctionBlock(&RRBPFunctionBlock, "RR", "BP");
+ sprintf_s(crossProfileFilePath, "%s\\PatientProfiles\\%s\\RR-BTemp.rff", rootPath, patientName);
+ DiscreteFunctionBlock RRBTempFunctionBlock("RR-BTemp", crossProfileFilePath);
+ profile.setFunctionBlock(&RRBTempFunctionBlock, "RR", "BTemp");
+ sprintf_s(crossProfileFilePath, "%s\\PatientProfiles\\%s\\RR-HR.rff", rootPath, patientName);
+ DiscreteFunctionBlock RRHRFunctionBlock("RR-HR", crossProfileFilePath);
+ profile.setFunctionBlock(&RRHRFunctionBlock, "RR", "HR");
+ sprintf_s(crossProfileFilePath, "%s\\PatientProfiles\\%s\\RR-SPO2.rff", rootPath, patientName);
+ DiscreteFunctionBlock RRSPO2FunctionBlock("RR-SPO2", crossProfileFilePath);
+ profile.setFunctionBlock(&RRSPO2FunctionBlock, "RR", "SPO2");
+
+ sprintf_s(crossProfileFilePath, "%s\\PatientProfiles\\%s\\SPO2-BP.rff", rootPath, patientName);
+ DiscreteFunctionBlock SPO2BPFunctionBlock("SPO2-BP", crossProfileFilePath);
+ profile.setFunctionBlock(&SPO2BPFunctionBlock, "SPO2", "BP");
+ sprintf_s(crossProfileFilePath, "%s\\PatientProfiles\\%s\\SPO2-BTemp.rff", rootPath, patientName);
+ DiscreteFunctionBlock SPO2BTempFunctionBlock("SPO2-BTemp", crossProfileFilePath);
+ profile.setFunctionBlock(&SPO2BTempFunctionBlock, "SPO2", "BTemp");
+ sprintf_s(crossProfileFilePath, "%s\\PatientProfiles\\%s\\SPO2-HR.rff", rootPath, patientName);
+ DiscreteFunctionBlock SPO2HRFunctionBlock("SPO2-HR", crossProfileFilePath);
+ profile.setFunctionBlock(&SPO2HRFunctionBlock, "SPO2", "HR");
+ sprintf_s(crossProfileFilePath, "%s\\PatientProfiles\\%s\\SPO2-RR.rff", rootPath, patientName);
+ DiscreteFunctionBlock SPO2RRFunctionBlock("SPO2-RR", crossProfileFilePath);
+ profile.setFunctionBlock(&SPO2RRFunctionBlock, "SPO2", "RR");
+
+ AgentSAEWS->setCrossReliabilityProfileModule(&profile);
+
+
+ //Workaround
+ unsigned int scoreHistoryLength = 30*changeRightWrongTimeConfig;
+
+
+ AgentHR->setScoreHistorLength(scoreHistoryLength);
+ AgentRR->setScoreHistorLength(scoreHistoryLength);
+ AgentBP->setScoreHistorLength(scoreHistoryLength);
+ AgentSPO2->setScoreHistorLength(scoreHistoryLength);
+ AgentBTemp->setScoreHistorLength(scoreHistoryLength);
+ AgentSAEWS->setScoreHistorLength(scoreHistoryLength);
+
+ AgentSAEWS->setCrossReliabiabilityParameter(crossParam);
+
+ /*
+ //TODO: basisklassen-pointer weitergeben, dann dynamic_cast machen
+ Unit *test = setup.createUnit<Agent>("test");
+ */
+
+ //printf("\nCreate Testbench\n");
+ Testbench tb1 = create_testbench("testbench1");
+
+
+ //TODO: load agents, sensors, channels, and csvreader from setup-object in testbench
+ //printf("\nLoad CSV-Files\n");
+ unsigned int row = 2;
+
+
+ CSVreaderModule* csvrHR;
+ CSVreaderModule* csvrRR;
+ CSVreaderModule* csvrSPO2;
+ CSVreaderModule* csvrBTemp;
+ CSVreaderModule* csvrBP;
+
+ //printf("ja... %s\n", destPath);
+ //getchar();
+
+
+ AgentSAEWS->setCSVWRiter(destPath);
+
+ char destPath2[700];
+ sprintf_s(destPath2, "%s-MoreData.csv", destPath);
+ AgentSAEWS->setSecondCSVWRiter(destPath2);
+
+
+ sprintf_s(datasetPath, "%s", datasetPath);
+ csvrHR = create_CSVreaderModule("csvr:HR", datasetPath, HR, row); //HR
+ csvrRR = create_CSVreaderModule("csvr:RR", datasetPath, RR, row); //RR
+ csvrSPO2 = create_CSVreaderModule("csvr:SPO2", datasetPath, SPO2, row); //SPO2
+ csvrBTemp = create_CSVreaderModule("csvr:BTemp", datasetPath, BTemp, row); //BTemp
+ csvrBP = create_CSVreaderModule("csvr:BP", datasetPath, BP, row); //BP
+
+
+ //printf("\nRegister all Sensors in Testbench\n");
+ register_sensorInTestbench(&tb1, SensorHR, csvrHR);
+ register_sensorInTestbench(&tb1, SensorRR, csvrRR);
+ register_sensorInTestbench(&tb1, SensorBP, csvrBP);
+ register_sensorInTestbench(&tb1, SensorSPO2, csvrSPO2);
+ register_sensorInTestbench(&tb1, SensorBTemp, csvrBTemp);
+
+ //printf("\nRegister all Agents in Testbench\n");
+ register_agentInTestbench(&tb1, AgentHR);
+ register_agentInTestbench(&tb1, AgentRR);
+ register_agentInTestbench(&tb1, AgentBP);
+ register_agentInTestbench(&tb1, AgentSPO2);
+ register_agentInTestbench(&tb1, AgentBTemp);
+ register_agentInTestbench(&tb1, AgentSAEWS);
+
+ //printf("\nRegister all Channels in Testbench\n");
+ register_channelInTestbench(&tb1, channel1HR);
+ register_channelInTestbench(&tb1, channel1RR);
+ register_channelInTestbench(&tb1, channel1BP);
+ register_channelInTestbench(&tb1, channel1SPO2);
+ register_channelInTestbench(&tb1, channel1BTemp);
+ register_channelInTestbench(&tb1, channel2HR);
+ register_channelInTestbench(&tb1, channel2RR);
+ register_channelInTestbench(&tb1, channel2BP);
+ register_channelInTestbench(&tb1, channel2SPO2);
+ register_channelInTestbench(&tb1, channel2BTemp);
+
+
+ //Start
+ tb1.simulate(datasetLength);
+
+ //tb1.clearTestbench();
+
+ }
+ else {
+ printf("Arguments wrong!");
+ }
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/mountModules.cpp b/SA-EWS_Version_2019.03.27/src/mountModules.cpp
new file mode 100644
index 0000000..0dfbf47
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/mountModules.cpp
@@ -0,0 +1,36 @@
+#include "mountModules.h"
+#include "rlutil.h"
+
+using namespace rlutil;
+/*
+bool mountConfidenceModuleinStabilityModule(StabilityModule* stabilityModule, ConfidenceModule* confidenceModule) {
+ if (stabilityModule != NULL && confidenceModule != NULL) {
+ printf(" > Confidence Module ");
+ setColor(LIGHTCYAN);
+ printf("%s ", confidenceModule->getName().c_str());
+ setColor(GREY);
+ printf("(id: %03u) ", confidenceModule->getId());
+ if (stabilityModule->mountConfidenceModule(confidenceModule)) {
+ setColor(LIGHTGREEN);
+ printf("mounted ");
+ setColor(GREY);
+ printf("in Stability Module ");
+ setColor(LIGHTCYAN);
+ printf("%s ", stabilityModule->getName().c_str());
+ setColor(GREY);
+ printf("(id: %03u)\n", stabilityModule->getId());
+ return true;
+ }
+ else {
+ setColor(LIGHTRED);
+ printf("couldn't be mounted in %s (id: %03u)\n", stabilityModule->getName().c_str(), stabilityModule->getId());
+ setColor(GREY);
+ }
+ }
+ else {
+ setColor(LIGHTRED);
+ printf(" > Confidence Module or Stability Module is not valid\n");
+ setColor(GREY);
+ }
+}
+*/
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/mountModules.h b/SA-EWS_Version_2019.03.27/src/mountModules.h
new file mode 100644
index 0000000..259a6e0
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/mountModules.h
@@ -0,0 +1,11 @@
+#ifndef MOUNTMODULES_HEADERFILE
+#define MOUNTMODULES_HEADERFILE
+
+#include "StabilityModule.h"
+#include "ConfidenceModule.h"
+
+//bool mountConfidenceModuleinStabilityModule(StabilityModule* stabilityModule, ConfidenceModule* confidenceModule);
+
+
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/mount_nodes.cpp b/SA-EWS_Version_2019.03.27/src/mount_nodes.cpp
new file mode 100644
index 0000000..d1f9c85
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/mount_nodes.cpp
@@ -0,0 +1,408 @@
+#include "attach_modules.h"
+#include "mount_nodes.h"
+#include "rlutil.h"
+#include <stdio.h>
+
+//#define PRINT
+
+using namespace rlutil;
+
+bool mount_sensorInAgent(Agent* agent, Sensor* sensor, Channel* channel) {
+ if (agent != NULL && sensor != NULL && channel != NULL) {
+#ifdef PRINT
+ printf(" > Sensor ");
+ setColor(TXTCOLOR_LIGHTCYAN);
+ printf("%s ", sensor->get_name());
+ setColor(TXTCOLOR_GREY);
+ printf("(id: %03u) ", sensor->get_id());
+#endif // PRINT
+ if (agent->get_sensorHandlerOfAgent()->mount_sensorIntoSensorSlot(channel) && sensor->mount_agent(channel)) {
+#ifdef PRINT
+ 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());
+#endif // PRINT
+ return true;
+ }
+ else {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTRED);
+ printf("couldn't be mounted in %s (id: %03u)\n", agent->get_name(), agent->get_id());
+ setColor(TXTCOLOR_GREY);
+#endif // PRINT
+ }
+ }
+ else {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTRED);
+ printf(" > Agent, Sensor, or Channel is not valid\n");
+ setColor(TXTCOLOR_GREY);
+#endif // PRINT
+ }
+ 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 {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTRED);
+ printf("Agent, Sensor, Channel, or HistoryModule is not valid\n");
+ setColor(TXTCOLOR_GREY);
+#endif // PRINT
+ }
+ 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)) {
+#ifdef PRINT
+ 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());
+#endif // PRINT
+ return true;
+ }
+ else {
+#ifdef PRINT
+ 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);
+#endif // PRINT
+ masteragent->get_slaveAgentHandlerOfAgent()->demount_slaveAgentIntoSlaveAgentSlot(channel);
+ }
+ }
+ }
+ else {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTRED);
+ printf(" > One of the Agents or Channel not valid\n");
+ setColor(TXTCOLOR_GREY);
+#endif // PRINT
+ }
+ 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/SA-EWS_Version_2019.03.27/src/mount_nodes.h b/SA-EWS_Version_2019.03.27/src/mount_nodes.h
new file mode 100644
index 0000000..0afa9ba
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/mount_nodes.h
@@ -0,0 +1,31 @@
+#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);
+//bool mount_agentInAgent(Agent *masteragent, Agent* slaveagent, Channel* channel, StabilityModule* stabilityModule);
+
+
+
+/*
+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/SA-EWS_Version_2019.03.27/src/printError.cpp b/SA-EWS_Version_2019.03.27/src/printError.cpp
new file mode 100644
index 0000000..85f8f2b
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/printError.cpp
@@ -0,0 +1,16 @@
+#include <stdio.h>
+#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/SA-EWS_Version_2019.03.27/src/printError.h b/SA-EWS_Version_2019.03.27/src/printError.h
new file mode 100644
index 0000000..a6af49f
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/project_settings.h b/SA-EWS_Version_2019.03.27/src/project_settings.h
new file mode 100644
index 0000000..3a5d949
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/register_in_testbench.cpp b/SA-EWS_Version_2019.03.27/src/register_in_testbench.cpp
new file mode 100644
index 0000000..28963df
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/register_in_testbench.cpp
@@ -0,0 +1,130 @@
+#include "register_in_testbench.h"
+
+#include "attach_modulesToTestbench.h"
+#include "rlutil.h"
+#include <stdio.h>
+
+//#define PRINT
+
+using namespace rlutil;
+
+bool register_agentInTestbench(Testbench *tb, Agent *agent) {
+ if (tb != NULL && agent != NULL) {
+#ifdef PRINT
+ printf(" > Agent ");
+ setColor(TXTCOLOR_LIGHTCYAN);
+ printf("%s ", agent->get_name());
+ setColor(TXTCOLOR_GREY);
+ printf("(id: %03u) ", agent->get_id());
+#endif // PRINT
+ if (tb->register_agent(agent)) {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTGREEN);
+ printf("registered ");
+ setColor(TXTCOLOR_GREY);
+ printf("in Testbench ");
+ setColor(TXTCOLOR_LIGHTCYAN);
+ printf("%s\n", tb->get_name());
+ setColor(TXTCOLOR_GREY);
+#endif // PRINT
+ return true;
+ }
+ else {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTRED);
+ printf("couldn't be registered in %s", tb->get_name());
+#endif // PRINT
+ }
+ }
+ else {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTRED);
+ printf(" > Testbench or Agent is not valid\n");
+#endif // PRINT
+ }
+ setColor(GREY);
+ return false;
+}
+
+bool register_sensorInTestbench(Testbench *tb, Sensor *sensor) {
+ if (tb != NULL && sensor != NULL) {
+#ifdef PRINT
+ printf(" > Sensor ");
+ setColor(TXTCOLOR_LIGHTCYAN);
+ printf("%s ", sensor->get_name());
+ setColor(TXTCOLOR_GREY);
+ printf("(id: %03u) ", sensor->get_id());
+#endif // PRINT
+ if (tb->register_sensor(sensor)) {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTGREEN);
+ printf("registered ");
+ setColor(TXTCOLOR_GREY);
+ printf("in ");
+ setColor(TXTCOLOR_LIGHTCYAN);
+ printf("%s\n", tb->get_name());
+ setColor(TXTCOLOR_GREY);
+#endif // PRINT
+ return true;
+ }
+ else {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTRED);
+ printf("couldn't be registered in %s\n", tb->get_name());
+#endif // PRINT
+ }
+ }
+ else {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTRED);
+ printf(" > Testbench or sensor is not valid\n");
+#endif // PRINT
+ }
+ setColor(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 {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTRED);
+ printf("Testbench or sensor is not valid\n");
+#endif // PRINT
+ }
+ setColor(GREY);
+ return false;
+}
+
+bool register_channelInTestbench(Testbench *tb, Channel *channel) {
+#ifdef PRINT
+ printf(" > Channel ");
+ setColor(TXTCOLOR_LIGHTCYAN);
+ printf("%s ", channel->get_name());
+ setColor(TXTCOLOR_GREY);
+ printf("(id: %03u) ", channel->get_id());
+#endif // PRINT
+ if (tb->register_channel(channel)) {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTGREEN);
+ printf("registered ");
+ setColor(TXTCOLOR_GREY);
+ printf("in Testbench ");
+ setColor(TXTCOLOR_LIGHTCYAN);
+ printf("%s\n", tb->get_name());
+#endif // PRINT
+ }
+ else {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTRED);
+ printf("couldn't be registered in %s\n", tb->get_name());
+#endif // PRINT
+ }
+ setColor(GREY);
+
+ return false;
+}
diff --git a/SA-EWS_Version_2019.03.27/src/register_in_testbench.h b/SA-EWS_Version_2019.03.27/src/register_in_testbench.h
new file mode 100644
index 0000000..b36f41e
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/relationChecker.cpp b/SA-EWS_Version_2019.03.27/src/relationChecker.cpp
new file mode 100644
index 0000000..943ca8a
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/relationChecker.cpp
@@ -0,0 +1,32 @@
+#include "relationChecker.h"
+
+#include <stdio.h>
+
+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/SA-EWS_Version_2019.03.27/src/relationChecker.h b/SA-EWS_Version_2019.03.27/src/relationChecker.h
new file mode 100644
index 0000000..569c798
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/relationChecker.h
@@ -0,0 +1,9 @@
+#ifndef RELATIONCHECKER_HEADERFILE
+#define RELATIONCHECKER_HEADERFILE
+
+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/SA-EWS_Version_2019.03.27/src/rlutil.h b/SA-EWS_Version_2019.03.27/src/rlutil.h
new file mode 100644
index 0000000..653686e
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/rlutil.h
@@ -0,0 +1,759 @@
+#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 <License>
+ */
+
+//#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 <iostream>
+ #include <string>
+ #include <cstdio> // for getch()
+ /// Namespace forward declarations
+ namespace rlutil {
+ RLUTIL_INLINE void locate(int x, int y);
+ }
+#else
+ #include <stdio.h> // for getch() / printf()
+ #include <string.h> // for strlen()
+ RLUTIL_INLINE void locate(int x, int y); // Forward declare for C to avoid warnings
+#endif // __cplusplus
+
+#ifdef _WIN32
+ #include <windows.h> // for WinAPI and Sleep()
+ #define _NO_OLDNAMES // for MinGW compatibility
+ #include <conio.h> // for getch() and kbhit()
+ #define getch _getch
+ #define kbhit _kbhit
+#else
+ #include <termios.h> // for getch() and kbhit()
+ #include <unistd.h> // for getch(), kbhit() and (u)sleep()
+ #include <sys/ioctl.h> // for getkey()
+ #include <sys/types.h> // for kbhit()
+ #include <sys/time.h> // 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.locate>.
+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 <getch>, <kbhit> and <gotoxy> 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 <Key codes for keyhit()>
+///
+/// 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 <Color Codes>
+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 <Color Codes>
+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 <Color Codes>
+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 <Color Codes>
+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 <Color Codes>
+/// See <resetColor>
+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 <Color Codes>
+/// See <setColor>
+/// See <saveDefaultColor>
+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 <class T> 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 <rlutil.hidecursor>.
+/// 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/SA-EWS_Version_2019.03.27/src/settings.h b/SA-EWS_Version_2019.03.27/src/settings.h
new file mode 100644
index 0000000..e69de29
diff --git a/SA-EWS_Version_2019.03.27/src/setupModule.cpp b/SA-EWS_Version_2019.03.27/src/setupModule.cpp
new file mode 100644
index 0000000..5a8afd6
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/setupModule.cpp
@@ -0,0 +1,229 @@
+#include "setupModule.h"
+#include "rlutil.h"
+
+#define SYMBOLINFINITY 236
+
+using namespace rlutil;
+
+//bounded both-sided
+bool addFunctionToConfidenceModule(ConfidenceModule *confidenceModule, bool flagLowerBoundaryExist, float lowerBoundary, bool flagUpperBoundaryExist, float upperBoundary, float inputValue1, float confidenceValue1, float inputValue2, float confidenceValue2) {
+ printf("hier1\n");
+ if (confidenceModule != NULL && flagLowerBoundaryExist && flagUpperBoundaryExist) {
+ LinearFunction *linFun = confidenceModule->addFunction(flagLowerBoundaryExist, lowerBoundary, flagUpperBoundaryExist, upperBoundary, inputValue1, confidenceValue1, inputValue2, confidenceValue2);
+ printf("hier2\n");
+ if (linFun != NULL) {
+ printf("hier3\n");
+ printf(" > Function has been ");
+ setColor(LIGHTGREEN);
+ printf("added");
+ setColor(GREY);
+ printf(":\n");
+ printf(" > Domain: %f to %f\n", lowerBoundary, upperBoundary);
+ printf(" > k = %f, d = %f\n", linFun->getK(), linFun->getD());
+ return true;
+ }
+ setColor(LIGHTRED);
+ printf(" > Function in th domain %f to %f couldn't been added\n", lowerBoundary, upperBoundary);
+ setColor(GREY);
+ }
+ setColor(LIGHTRED);
+ printf(" > Confidence Module is invalid, or Boundary Flags are set wrong\n");
+ setColor(GREY);
+
+ return false;
+}
+
+//bounded below
+bool addFunctionToConfidenceModule(ConfidenceModule *confidenceModule, bool flagLowerBoundaryExist, float lowerBoundary, bool flagUpperBoundaryExist, float inputValue1, float confidenceValue1, float inputValue2, float confidenceValue2) {
+ if (confidenceModule != NULL && flagLowerBoundaryExist && !flagUpperBoundaryExist) {
+ LinearFunction *linFun = confidenceModule->addFunction(flagLowerBoundaryExist, lowerBoundary, flagUpperBoundaryExist, inputValue1, confidenceValue1, inputValue2, confidenceValue2);
+
+ if (linFun != NULL) {
+ printf(" > Function has been ");
+ setColor(LIGHTGREEN);
+ printf("added");
+ setColor(GREY);
+ printf(":\n");
+ printf(" > Domain: %f to oo\n", lowerBoundary);
+ printf(" > k = %f, d = %f\n", linFun->getK(), linFun->getD());
+ return true;
+ }
+ setColor(LIGHTRED);
+ printf(" > Function in th domain %f to oo couldn't been added\n", lowerBoundary);
+ setColor(GREY);
+ }
+ setColor(LIGHTRED);
+ printf(" > Confidence Module is invalid, or Boundary Flags are set wrong\n");
+ setColor(GREY);
+
+ return false;
+}
+
+//bounded above
+bool addFunctionToConfidenceModule(ConfidenceModule *confidenceModule, bool flagLowerBoundaryExist, bool flagUpperBoundaryExist, float upperBoundary, float inputValue1, float confidenceValue1, float inputValue2, float confidenceValue2) {
+ if (confidenceModule != NULL && !flagLowerBoundaryExist && flagUpperBoundaryExist) {
+ LinearFunction *linFun = confidenceModule->addFunction(flagLowerBoundaryExist, flagUpperBoundaryExist, upperBoundary, inputValue1, confidenceValue1, inputValue2, confidenceValue2);
+
+ if (linFun != NULL) {
+ printf(" > Function has been ");
+ setColor(LIGHTGREEN);
+ printf("added");
+ setColor(GREY);
+ printf(":\n");
+ printf(" > Domain: -oo to %f\n", upperBoundary);
+ printf(" > k = %f, d = %f\n", linFun->getK(), linFun->getD());
+ return true;
+ }
+ setColor(LIGHTRED);
+ printf(" > Function in th domain -oo to %f couldn't been added\n", upperBoundary);
+ setColor(GREY);
+ }
+ setColor(LIGHTRED);
+ printf(" > Confidence Module is invalid, or Boundary Flags are set wrong\n");
+ setColor(GREY);
+
+ return false;
+}
+
+bool addFunctionToConfidenceModule(ConfidenceModule *confidenceModule, bool flagLowerBoundaryExist, bool flagUpperBoundaryExist, float inputValue1, float confidenceValue1, float inputValue2, float confidenceValue2) {
+ if (confidenceModule != NULL && !flagLowerBoundaryExist && !flagUpperBoundaryExist) {
+ LinearFunction *linFun = confidenceModule->addFunction(flagLowerBoundaryExist, flagUpperBoundaryExist, inputValue1, confidenceValue1, inputValue2, confidenceValue2);
+
+ if (linFun != NULL) {
+ printf(" > Function has been ");
+ setColor(LIGHTGREEN);
+ printf("added");
+ setColor(GREY);
+ printf(":\n");
+ printf(" > Domain: -oo to oo\n");
+ printf(" > k = %f, d = %f\n", linFun->getK(), linFun->getD());
+
+ //XXX - register in confidenceHandler
+
+
+ return true;
+ }
+ setColor(LIGHTRED);
+ printf(" > Function in th domain -oo to oo couldn't been added\n");
+ setColor(GREY);
+ }
+ setColor(LIGHTRED);
+ printf(" > Confidence Module is invalid, or Boundary Flags are set wrong\n");
+ setColor(GREY);
+
+ return false;
+}
+
+bool addFunctionToConfidenceModule(StabilityModule *stabilityModule, bool flagLowerBoundaryExist, float lowerBoundary, bool flagUpperBoundaryExist, float upperBoundary, float inputValue1, float confidenceValue1, float inputValue2, float confidenceValue2) {
+ if (stabilityModule != NULL) {
+ if (stabilityModule->installConfidenceModule()) {
+ setColor(BROWN);
+ printf(" Configure Confidence Module of Stability Module\n");
+ setColor(GREY);
+ return addFunctionToConfidenceModule(stabilityModule->getConfidenceModule(), flagLowerBoundaryExist, lowerBoundary, flagUpperBoundaryExist, upperBoundary, inputValue1, confidenceValue1, inputValue2, confidenceValue2);
+ }
+ else {
+ setColor(LIGHTRED);
+ printf(" > Confidence Module cannot be installed\n");
+ setColor(GREY);
+ }
+ }
+ else {
+ setColor(LIGHTRED);
+ printf(" > Stability Module is invalid\n");
+ setColor(GREY);
+ }
+ return false;
+}
+bool addFunctionToConfidenceModule(StabilityModule *stabilityModule, bool flagLowerBoundaryExist, float lowerBoundary, bool flagUpperBoundaryExist, float inputValue1, float confidenceValue1, float inputValue2, float confidenceValue2) {
+ if (stabilityModule != NULL) {
+ if (stabilityModule->installConfidenceModule()) {
+ setColor(BROWN);
+ printf(" Configure Confidence Module of Stability Module\n");
+ setColor(GREY);
+ return addFunctionToConfidenceModule(stabilityModule->getConfidenceModule(), flagLowerBoundaryExist, lowerBoundary, flagUpperBoundaryExist, inputValue1, confidenceValue1, inputValue2, confidenceValue2);
+ }
+ else {
+ setColor(LIGHTRED);
+ printf(" > Confidence Module cannot be installed\n");
+ setColor(GREY);
+ }
+ }
+ else {
+ setColor(LIGHTRED);
+ printf(" > Stability Module is invalid\n");
+ setColor(GREY);
+ }
+ return false;
+}
+bool addFunctionToConfidenceModule(StabilityModule *stabilityModule, bool flagLowerBoundaryExist, bool flagUpperBoundaryExist, float upperBoundary, float inputValue1, float confidenceValue1, float inputValue2, float confidenceValue2) {
+ if (stabilityModule != NULL) {
+ if (stabilityModule->installConfidenceModule()) {
+ setColor(BROWN);
+ printf(" Configure Confidence Module of Stability Module\n");
+ setColor(GREY);
+ return addFunctionToConfidenceModule(stabilityModule->getConfidenceModule(), flagLowerBoundaryExist, flagUpperBoundaryExist, upperBoundary, inputValue1, confidenceValue1, inputValue2, confidenceValue2);
+ }
+ else {
+ setColor(LIGHTRED);
+ printf(" > Confidence Module cannot be installed\n");
+ setColor(GREY);
+ }
+ }
+ else {
+ setColor(LIGHTRED);
+ printf(" > Stability Module is invalid\n");
+ setColor(GREY);
+ }
+ return false;
+}
+
+bool addFunctionToConfidenceModule(StabilityModule *stabilityModule, bool flagLowerBoundaryExist, bool flagUpperBoundaryExist, float inputValue1, float confidenceValue1, float inputValue2, float confidenceValue2) {
+ if (stabilityModule != NULL) {
+ if (stabilityModule->installConfidenceModule()) {
+ setColor(BROWN);
+ printf(" Configure Confidence Module of Stability Module\n");
+ setColor(GREY);
+ return addFunctionToConfidenceModule(stabilityModule->getConfidenceModule(), flagLowerBoundaryExist, flagUpperBoundaryExist, inputValue1, confidenceValue1, inputValue2, confidenceValue2);
+ }
+ else {
+ setColor(LIGHTRED);
+ printf(" > Confidence Module cannot be installed\n");
+ setColor(GREY);
+ }
+ }
+ else {
+ setColor(LIGHTRED);
+ printf(" > Stability Module is invalid\n");
+ setColor(GREY);
+ }
+ return false;
+}
+
+
+
+
+
+
+/*
+bool addFunctionToConfidenceModule(ConfidenceModule *confidenceModule, float lowerBoundary, float upperBoundary, float inputValue1, float confidenceValue1, float inputValue2, float confidenceValue2) {
+
+ LinearFunction *linFun = confidenceModule->addFunction(lowerBoundary, upperBoundary, inputValue1, confidenceValue1, inputValue2, confidenceValue2);
+
+ if (linFun != NULL) {
+ printf(" > Function has been ");
+ setColor(LIGHTGREEN);
+ printf("added");
+ setColor(GREY);
+ printf(":\n");
+ printf(" > Domain: %f to %f\n", lowerBoundary, upperBoundary);
+ printf(" > k = %f, d = %f\n", linFun->getK(), linFun->getD());
+ return true;
+ }
+
+ setColor(LIGHTRED);
+ printf(" > Function in th domain %f to %f couldn't been added\n", lowerBoundary, upperBoundary);
+ setColor(GREY);
+ return false;
+}
+*/
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/setupModule.h b/SA-EWS_Version_2019.03.27/src/setupModule.h
new file mode 100644
index 0000000..672f2eb
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/setupModule.h
@@ -0,0 +1,23 @@
+#ifndef SETUPMODULE_HEADERFILE
+#define SETUPMODULE_HEADERFILE
+
+#include "ConfidenceModule.h"
+#include "StabilityModule.h"
+
+bool addFunctionToConfidenceModule(ConfidenceModule *confidenceModule, bool flagLowerBoundaryExist, float lowerBoundary, bool flagUpperBoundaryExist, float upperBoundary, float inputValue1, float confidenceValue1, float inputValue2, float confidenceValue2);
+bool addFunctionToConfidenceModule(ConfidenceModule *confidenceModule, bool flagLowerBoundaryExist, float lowerBoundary, bool flagUpperBoundaryExist, float inputValue1, float confidenceValue1, float inputValue2, float confidenceValue2);
+bool addFunctionToConfidenceModule(ConfidenceModule *confidenceModule, bool flagLowerBoundaryExist, bool flagUpperBoundaryExist, float upperBoundary, float inputValue1, float confidenceValue1, float inputValue2, float confidenceValue2);
+bool addFunctionToConfidenceModule(ConfidenceModule *confidenceModule, bool flagLowerBoundaryExist, bool flagUpperBoundaryExist, float inputValue1, float confidenceValue1, float inputValue2, float confidenceValue2);
+
+bool addFunctionToConfidenceModule(StabilityModule *stabilityModule, bool flagLowerBoundaryExist, float lowerBoundary, bool flagUpperBoundaryExist, float upperBoundary, float inputValue1, float confidenceValue1, float inputValue2, float confidenceValue2);
+bool addFunctionToConfidenceModule(StabilityModule *stabilityModule, bool flagLowerBoundaryExist, float lowerBoundary, bool flagUpperBoundaryExist, float inputValue1, float confidenceValue1, float inputValue2, float confidenceValue2);
+bool addFunctionToConfidenceModule(StabilityModule *stabilityModule, bool flagLowerBoundaryExist, bool flagUpperBoundaryExist, float upperBoundary, float inputValue1, float confidenceValue1, float inputValue2, float confidenceValue2);
+bool addFunctionToConfidenceModule(StabilityModule *stabilityModule, bool flagLowerBoundaryExist, bool flagUpperBoundaryExist, float inputValue1, float confidenceValue1, float inputValue2, float confidenceValue2);
+
+
+
+//bool addFunctionToConfidenceModule(ConfidenceModule *confidenceModule, float lowerBoundary, float upperBoundary, float inputValue1, float confidenceValue1, float inputValue2, float confidenceValue2);
+
+
+
+#endif
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/setupNode.cpp b/SA-EWS_Version_2019.03.27/src/setupNode.cpp
new file mode 100644
index 0000000..dcd6a51
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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->setWorkCycle(workingCycle)) {
+ printf(" > WorkingCycle of Sensor ");
+ setColor(LIGHTCYAN);
+ printf("%s ", sensor->getName().c_str());
+ setColor(GREY);
+ printf("(id: %03u) ", sensor->getId());
+ setColor(LIGHTGREEN);
+ printf("set ");
+ setColor(GREY);
+ printf("to %u\n", workingCycle);
+
+ }
+ else {
+ setColor(LIGHTRED);
+ printf(" > Couldn't set WorkingCycle of Sensor %s (id: %03u)\n", sensor->getName().c_str(), sensor->getId());
+ setColor(GREY);
+ }
+}
+
+void setWorkingCycleOfAgent(Agent* agent, unsigned int workingCycle) {
+ if (agent->setWorkCycle(workingCycle)) {
+ printf(" > WorkingCycle of Agent ");
+ setColor(LIGHTCYAN);
+ printf("%s ", agent->getName().c_str());
+ setColor(GREY);
+ printf("(id: %03u) ", agent->getId());
+ setColor(LIGHTGREEN);
+ printf("set ");
+ setColor(GREY);
+ printf("to %u\n", workingCycle);
+
+ }
+ else {
+ setColor(LIGHTRED);
+ printf(" > Couldn't set WorkingCycle of Sensor %s (id: %03u)\n", agent->getName().c_str(), agent->getId());
+ setColor(GREY);
+ }
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/setupNode.h b/SA-EWS_Version_2019.03.27/src/setupNode.h
new file mode 100644
index 0000000..2df067d
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/setup_agent.cpp b/SA-EWS_Version_2019.03.27/src/setup_agent.cpp
new file mode 100644
index 0000000..13f01f4
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/setup_agent.cpp
@@ -0,0 +1,13 @@
+#include "setup_agent.h"
+
+#include <stdio.h>
+
+//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/SA-EWS_Version_2019.03.27/src/setup_agent.h b/SA-EWS_Version_2019.03.27/src/setup_agent.h
new file mode 100644
index 0000000..3888cbb
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/setup_lookuptable.cpp b/SA-EWS_Version_2019.03.27/src/setup_lookuptable.cpp
new file mode 100644
index 0000000..41e81d1
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/setup_lookuptable.cpp
@@ -0,0 +1,54 @@
+#include "setup_lookuptable.h"
+#include <stdio.h>
+#include "rlutil.h"
+
+using namespace rlutil;
+
+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(LIGHTGREEN);
+ printf("added ");
+ rlutil::setColor(GREY);
+ printf("to ");
+ rlutil::setColor(LIGHTCYAN);
+ printf("%s ", lut->getName().c_str());
+ rlutil::setColor(GREY);
+ printf("(id: %03u)\n", lut->getId());
+ }
+ else {
+ rlutil::setColor(LIGHTRED);
+ printf("couldn't be added to %s (id: %03u)\n", lut->getName().c_str(), lut->getId());
+ rlutil::setColor(GREY);
+ }
+}
+
+void check_and_activate_lookuptable(Lookuptable* lut) {
+ printf(" > ");
+ rlutil::setColor(LIGHTCYAN);
+ printf("%s ", lut->getName().c_str());
+ rlutil::setColor(GREY);
+ printf("(id: %03u) ", lut->getId());
+
+ if(lut->check_sort_and_activate()) {
+ printf("seems to be ");
+ rlutil::setColor(LIGHTGREEN);
+ printf("correct\n");
+ }
+ else {
+ rlutil::setColor(LIGHTRED);
+ printf("is not correct\n", lut->getName().c_str(), lut->getId());
+ }
+ rlutil::setColor(GREY);
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/setup_lookuptable.h b/SA-EWS_Version_2019.03.27/src/setup_lookuptable.h
new file mode 100644
index 0000000..c457db1
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/test1.cpp b/SA-EWS_Version_2019.03.27/src/test1.cpp
new file mode 100644
index 0000000..02b3e8d
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/test1.cpp
@@ -0,0 +1,19 @@
+#include "test1.h"
+#include <stdio.h>
+
+test1::test1() {
+ t = 1;
+}
+
+void test1::setT(float t) {
+ this->t = t;
+}
+
+float test1::getT() {
+ return t;
+}
+
+float* test1::getAdressT() {
+ printf("%p\n", &t);
+ return &t;
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/test1.h b/SA-EWS_Version_2019.03.27/src/test1.h
new file mode 100644
index 0000000..05e27fb
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/test1.h
@@ -0,0 +1,15 @@
+#pragma once
+
+#include "test2.h"
+
+class test1 {
+
+private:
+ float t;
+
+public:
+ test1();
+ void setT(float t);
+ float getT();
+ float* getAdressT();
+};
diff --git a/SA-EWS_Version_2019.03.27/src/test2.cpp b/SA-EWS_Version_2019.03.27/src/test2.cpp
new file mode 100644
index 0000000..cf92baf
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/test2.cpp
@@ -0,0 +1,16 @@
+#include "test2.h"
+#include <stdio.h>
+
+test2::test2() {
+ t = NULL;
+}
+
+float test2::getT() {
+ if(t != NULL)
+ return *t;
+ return -1;
+}
+
+void test2::setAdressT(float* t) {
+ this->t = t;
+}
\ No newline at end of file
diff --git a/SA-EWS_Version_2019.03.27/src/test2.h b/SA-EWS_Version_2019.03.27/src/test2.h
new file mode 100644
index 0000000..616f9af
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/test2.h
@@ -0,0 +1,15 @@
+#pragma once
+
+#include "test2.h"
+
+class test2 {
+
+private:
+ float* t;
+
+public:
+ test2();
+ float getT();
+ void setAdressT(float* t);
+};
+
diff --git a/SA-EWS_Version_2019.03.27/src/user_method_abstraction.cpp b/SA-EWS_Version_2019.03.27/src/user_method_abstraction.cpp
new file mode 100644
index 0000000..dcb30e5
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/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/SA-EWS_Version_2019.03.27/src/user_method_abstraction.h b/SA-EWS_Version_2019.03.27/src/user_method_abstraction.h
new file mode 100644
index 0000000..6826a78
--- /dev/null
+++ b/SA-EWS_Version_2019.03.27/src/user_method_abstraction.h
@@ -0,0 +1 @@
+void br_abstraction(float input, int* output);
\ No newline at end of file
diff --git a/Version_Max_07_05_2018_CMake/src/StateHandler.cpp b/Version_Max_07_05_2018_CMake/src/StateHandler.cpp
index 04c4137..aa88186 100755
--- a/Version_Max_07_05_2018_CMake/src/StateHandler.cpp
+++ b/Version_Max_07_05_2018_CMake/src/StateHandler.cpp
@@ -1,1206 +1,1206 @@
#include "StateHandler.h"
#include "config.h"
#include "printError.h"
#include "rlutil.h"
#include <algorithm>
#include "relationChecker.h"
#include "file_util.h"
#include "minmaxzeug.h"
#include <ctime>
#include <iostream>
//#define PRINT
-//#define WRITE_MORE_INFORMATION_IN_CSV
+#define WRITE_MORE_INFORMATION_IN_CSV
#ifdef PRINT
//#define STOP_WHEN_BROKEN
//#define STOP_AFTER_BROKEN
//#define STOP_WHEN_DRIFT
//#define STOP_WHEN_STATE_VALID
//#define STOP_WHEN_CHANGING_IN_OLD_STATE
//#define STOP_EVERY_TIME
//#define STOP_EVERY_TIME_AFTER_SAMPLENR 500000
#endif
// STANDARD_STATE_HISTORY_LENGTH is used for the history length of the number of
// values which will be compared to the current value
// NOTE: Fuzzy Functions FuncBlockConfSim2StateTime, FuncBlockConfDif2StateTime,
// FuncBlockConfValStateTime, and FuncBlockConfInvStateTime should have the same
// length NOTE: You can set the History Length with the function
// setMaxStateHistoryLength()
#define STANDARD_STATE_HISTORY_LENGTH 10 // 10
#define INJECTIONPARTITIONING 5
// 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() {
csv_writer = NULL;
discreteAveragePartitionSize = INJECTIONPARTITIONING;
activeState = NULL;
// TODO: Question from Maxi: Do we need following (outcommented block)? I
// (maxi) commented it out.
/*
time_t rawtime;
struct tm timeinfo;
// char output_file_name[200];
char datetime[80];
const std::string output_directory_name =
"../data/out/"; // "./output_data_csv/Opel/2018-08-09/"; there is no
// impact if we change it!
std::string output_file_name_str;
time(&rawtime);
// timeinfo = localtime(&rawtime);
#ifdef _WIN32
localtime_s(&timeinfo, &rawtime);
#else
localtime_r(&rawtime, &timeinfo);
#endif
strftime(datetime, sizeof(datetime), "%Y-%m-%d_%I-%M-%S", &timeinfo);
#ifndef INPUT_FILE_NAME
output_file_name_str = output_directory_name + "output" + datetime + ".csv";
#else
output_file_name_str =
output_directory_name + INPUT_FILE_NAME + datetime + ".csv";
#endif // INPUT_FILE_NAME
#ifdef PRINT
cout << output_file_name_str << endl;
#endif // PRINT
*/
}
StateHandler::StateHandler() {
set_name(NO_NAME);
initStateHandler();
}
StateHandler::StateHandler(std::string name) {
set_name(name);
initStateHandler();
}
StateHandler::StateHandler(std::string name, std::string csvWriterPath) {
set_name(name);
initStateHandler();
csv_writer = new CSV_Writer("CSV Writer", csvWriterPath);
}
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<SlaveAgentSlotOfAgent *> *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();
return true; // added by Ali, it is an error in VS.
}
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();
return true; // added by Ali, it is an error in VS.
}
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();
return true; // added by Ali, it is an error in VS.
}
// Sorting with bigger Value in Front
struct descending {
template <class T> bool operator()(T const &a, T const &b) const {
return a > b;
}
};
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() {
#ifdef PRINT
printf(" >> Save Active State\n");
#endif // PRINT
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::makeNewActiveState() {
State *state = makeNewState();
if (state != NULL) {
activeState = state;
return true;
}
return false;
}
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();
}
void StateHandler::setMaxStateHistoryLength(
unsigned int maxStateHistoryLength) {
this->maxStateHistoryLength = maxStateHistoryLength;
}
void StateHandler::setSimilarToStateDeviationFuzzyFunction(
LinearFunctionBlock *FuncBlockConfSim2StateDev) {
this->FuncBlockConfSim2StateDev = FuncBlockConfSim2StateDev;
}
LinearFunctionBlock *StateHandler::getSimilarToStateDeviationFuzzyFunction() {
return this->FuncBlockConfSim2StateDev;
}
void StateHandler::setSimilarToStateTimeFuzzyFunction(
LinearFunctionBlock *FuncBlockConfSim2StateTime) {
this->FuncBlockConfSim2StateTime = FuncBlockConfSim2StateTime;
}
LinearFunctionBlock *StateHandler::getSimilarToStateTimeFuzzyFunction() {
return this->FuncBlockConfSim2StateTime;
}
void StateHandler::setDifferentToStateFuzzyFunction(
LinearFunctionBlock *FuncBlockConfDif2StateDev) {
this->FuncBlockConfDif2StateDev = FuncBlockConfDif2StateDev;
}
LinearFunctionBlock *StateHandler::getDifferentToStateDeviationFuzzyFunction() {
return this->FuncBlockConfDif2StateDev;
}
void StateHandler::setDifferentToStateTimeFuzzyFunction(
LinearFunctionBlock *FuncBlockConfDif2StateTime) {
this->FuncBlockConfDif2StateTime = FuncBlockConfDif2StateTime;
}
LinearFunctionBlock *StateHandler::getDifferentToStateTimeFuzzyFunction() {
return this->FuncBlockConfDif2StateTime;
}
void StateHandler::setSimilarityInStateDeviationFuzzyFunction(
LinearFunctionBlock *FuncBlockConfValStateDev) {
this->FuncBlockConfValStateDev = FuncBlockConfValStateDev;
}
LinearFunctionBlock *
StateHandler::getSimilarityInStateDeviationFuzzyFunction() {
return this->FuncBlockConfValStateDev;
}
void StateHandler::setSimilarityInStateTimeFuzzyFunction(
LinearFunctionBlock *FuncBlockConfValStateTime) {
this->FuncBlockConfValStateTime = FuncBlockConfValStateTime;
}
LinearFunctionBlock *StateHandler::getSimilarityInStateTimeFuzzyFunction() {
return this->FuncBlockConfValStateTime;
}
void StateHandler::setUnsimilarityInStateDeviationFuzzyFunction(
LinearFunctionBlock *FuncBlockConfInvStateDev) {
this->FuncBlockConfInvStateDev = FuncBlockConfInvStateDev;
}
LinearFunctionBlock *
StateHandler::getUnsimilarityInStateDeviationFuzzyFunction() {
return this->FuncBlockConfInvStateDev;
}
void StateHandler::setUnsimilarityInStateTimeFuzzyFunction(
LinearFunctionBlock *FuncBlockConfInvStateTime) {
this->FuncBlockConfInvStateTime = FuncBlockConfInvStateTime;
}
LinearFunctionBlock *StateHandler::getUnsimilarityInStateTimeFuzzyFunction() {
return this->FuncBlockConfInvStateTime;
}
void StateHandler::setDriftFuzzyFunction(
LinearFunctionBlock *FuncBlockDriftDeviation) {
this->FuncBlockDriftDeviation = FuncBlockDriftDeviation;
}
LinearFunctionBlock *StateHandler::getDriftFuzzyFunction() {
return this->FuncBlockDriftDeviation;
}
void StateHandler::setBrokenFuzzyFunction(
LinearFunctionBlock *FuncBlockConfBrokenSamples) {
this->FuncBlockConfBrokenSamples = FuncBlockConfBrokenSamples;
}
LinearFunctionBlock *StateHandler::getBrokenFuzzyFunction() {
return this->FuncBlockConfBrokenSamples;
}
void StateHandler::setSimilarToStateFuzzyFunctions(
LinearFunctionBlock *FuncBlockConfSim2StateDev,
LinearFunctionBlock *FuncBlockConfSim2StateTime) {
this->FuncBlockConfSim2StateDev = FuncBlockConfSim2StateDev;
this->FuncBlockConfSim2StateTime = FuncBlockConfSim2StateTime;
}
void StateHandler::setDifferentToStateFuzzyFunctions(
LinearFunctionBlock *FuncBlockConfDif2StateDev,
LinearFunctionBlock *FuncBlockConfDif2StateTime) {
this->FuncBlockConfDif2StateDev = FuncBlockConfDif2StateDev;
this->FuncBlockConfDif2StateTime = FuncBlockConfDif2StateTime;
}
void StateHandler::setSimilarityInStateFuzzyFunctions(
LinearFunctionBlock *FuncBlockConfValStateDev,
LinearFunctionBlock *FuncBlockConfValStateTime) {
this->FuncBlockConfValStateDev = FuncBlockConfValStateDev;
this->FuncBlockConfValStateTime = FuncBlockConfValStateTime;
}
void StateHandler::setUnsimilarityInStateFuzzyFunctions(
LinearFunctionBlock *FuncBlockConfInvStateDev,
LinearFunctionBlock *FuncBlockConfInvStateTime) {
this->FuncBlockConfInvStateDev = FuncBlockConfInvStateDev;
this->FuncBlockConfInvStateTime = FuncBlockConfInvStateTime;
}
void StateHandler::setDriftAndBrokenFuzzyFunctions(
LinearFunctionBlock *FuncBlockDriftDeviation,
LinearFunctionBlock *FuncBlockConfBrokenSamples) {
this->FuncBlockDriftDeviation = FuncBlockDriftDeviation;
this->FuncBlockConfBrokenSamples = FuncBlockConfBrokenSamples;
}
StateHandler ::~StateHandler() {
delete_all_OuputVariables();
delete_all_InputVariables();
delete_allStates();
// delete csv_writer;
}
void StateHandler::printOK() {
setColor(TXTCOLOR_LIGHTGREEN);
printf("OK\n");
setColor(TXTCOLOR_GREY);
}
void StateHandler::printDrift() {
setColor(TXTCOLOR_YELLOW);
printf(" >> DRIFT\n");
setColor(TXTCOLOR_GREY);
}
void StateHandler::printBroken() {
setColor(TXTCOLOR_LIGHTRED);
printf(" >> BROKEN\n");
setColor(TXTCOLOR_GREY);
}
// XXX - only for now
unsigned int old_cycle = 1;
int brokentest = 0;
bool flagPrintHeader = false;
/*
* makes a new state and reports if there is a anomaly = hearth piece of CAM :-)
*/
void StateHandler::trigger(unsigned int cycle) {
#ifdef PRINT
printf("cycle: %u\n", cycle);
#endif // PRINT
bool flagGotValues = true;
#ifdef PRINT
printf("Input Sample Values:\n");
#endif // PRINT
for (auto &slot : vInputVariables) {
float sampleValue;
if (!(slot->get_slaveAgentValue(&sampleValue)))
flagGotValues = false;
#ifdef PRINT
printf("In, %s: %f\n", slot->get_comPort()->get_name().c_str(),
sampleValue);
#endif // PRINT
}
#ifdef PRINT
printf("Output Sample Values:\n");
#endif // PRINT
for (auto &slot : vOutputVariables) {
float sampleValue;
if (!(slot->get_slaveAgentValue(&sampleValue)))
flagGotValues = false;
#ifdef PRINT
printf("Out, %s: %f\n", slot->get_comPort()->get_name().c_str(),
sampleValue);
#endif // PRINT
}
if (flagPrintHeader == false) {
csv_writer->write_field("Nr of States");
csv_writer->make_new_field();
csv_writer->write_field("State Nr");
csv_writer->make_new_field();
#ifdef WRITE_MORE_INFORMATION_IN_CSV
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();
#endif // WRITE_MORE_INFORMATION_IN_CSV
csv_writer->write_field("Status");
csv_writer->make_new_field();
csv_writer->write_field("Conf Status");
// csv_writer->make_new_field();
if (flagGotValues == true)
csv_writer->make_new_line();
flagPrintHeader = true;
}
if (!flagGotValues) {
} else {
// printf("neu\n");
// in the beginning, a active state has to be created
if (activeState == NULL && vStates.empty()) {
brokenCounter = 0;
#ifdef PRINT
printf(" > new active state\n");
#endif // PRINT
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());
csv_writer->make_new_field();
ptrdiff_t stateNr = find(vStates.begin(), vStates.end(), activeState) -
vStates.begin() + 1;
csv_writer->write_field((int)stateNr);
csv_writer->make_new_field();
#ifdef WRITE_MORE_INFORMATION_IN_CSV
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();
#endif // WRITE_MORE_INFORMATION_IN_CSV
csv_writer->write_field(STATUS_OKAY); // OK
csv_writer->make_new_field();
// NOTE: Status Conf = 0 because conf valid = 0
csv_writer->write_field(0); // Status Conf
// csv_writer->make_new_field();
}
// there is an active state and/or other states
// XXXX - There is no if regarding an active state?!?!?
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);
// printf("input (sim/dif) %f/%f\noutput (sim/dif) %f/%f\n",
// confInputVarAreSim2ActiveState, confInputVarAreDif2ActiveState,
// confOutputVarAreSim2ActiveState, confOutputVarAreDif2ActiveState);
// bool flagActiveStateWasValid = false;
// if no change has detected -> same state
if ((confInputVarAreSim2ActiveState > confInputVarAreDif2ActiveState) &&
(confOutputVarAreSim2ActiveState > confOutputVarAreDif2ActiveState)) {
brokenCounter = 0;
#ifdef PRINT
printf(" > same state\n");
// printf("\nPROOF:\nconfInputVarAreSim2ActiveState =
// %f\nconfInputVarAreDif2ActiveState =
// %f\nconfOutputVarAreSim2ActiveState =
// %f\nconfOutputVarAreDif2ActiveState = %f\n",
// confInputVarAreSim2ActiveState, confInputVarAreDif2ActiveState,
// confOutputVarAreSim2ActiveState, confOutputVarAreDif2ActiveState);
#endif // PRINT
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());
csv_writer->make_new_field();
ptrdiff_t stateNr = find(vStates.begin(), vStates.end(), activeState) -
vStates.begin() + 1;
csv_writer->write_field((int)stateNr);
csv_writer->make_new_field();
#ifdef WRITE_MORE_INFORMATION_IN_CSV
// write conf valid
csv_writer->write_field(activeState->getConfStateValid());
csv_writer->make_new_field();
csv_writer->write_field(activeState->getConfStateInvalid());
csv_writer->make_new_field();
// write 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();
#endif // WRITE_MORE_INFORMATION_IN_CSV
confidenceDrift = activeState->checkAllVariablesForDriftingFuzzy(
discreteAveragePartitionSize, FuncBlockDriftDeviation);
float confidenceNoDrift = 1 - confidenceDrift;
//AAAAAAAAA (New: "&& activeState->isStateValidAfterReentrance()")
if (confidenceDrift > 0.5 && activeState->isStateValidAfterReentrance()) {
#ifdef PRINT
printDrift();
#endif // PRINT
#ifdef STOP_WHEN_DRIFT
getchar();
#endif // STOP_WHEN_DRIFT
// print drift
csv_writer->write_field(STATUS_DRIFT);
csv_writer->make_new_field();
// calc and print conf
// AAAAAAAAAAAAAAAA
float conf = fuzzyAND(
fuzzyAND(confInputVarAreSim2ActiveState,
confOutputVarAreSim2ActiveState),
fuzzyAND(confidenceDrift, activeState->getConfStateValid()));
csv_writer->write_field(conf);
// printf("drift bei (same state): %i\n", cycle);
} else {
#ifdef PRINT
printOK();
#endif // PRINT
// print ok
csv_writer->write_field(STATUS_OKAY);
csv_writer->make_new_field();
// calc and print conf
//AAAAAAAAAAA
//NOTE: next equation is without confOK because confOK = 1 anyway (because broken timer = 0)
float conf =
fuzzyAND(fuzzyOR(fuzzyAND(confInputVarAreSim2ActiveState,
confOutputVarAreSim2ActiveState),
fuzzyAND(confInputVarAreDif2ActiveState,
confOutputVarAreDif2ActiveState)),
fuzzyAND(activeState->getConfStateValid(),
confidenceNoDrift));
csv_writer->write_field(conf);
}
// csv_writer->make_new_field();
} // same state
// state change
else {
// search in vector for matching state //TODO in future: look for the
// best matching, Not for the first matching
bool flagFoundMatchingState = false;
bool flagFoundHalfMatchingState = false;
bool flagHalfMatchingStateIsActiveState = false;
bool flagHalfMatchingStateIsAnotherState = false;
float confInputVarAreSim2State;
float confInputVarAreDif2State;
float confOutputVarAreSim2State;
float confOutputVarAreDif2State;
State *activeStateBackup = activeState;
bool flagActiveStateWasValid = activeState->isStateValid();
float backupConfInputVarAreSim2ActiveState;
float backupConfInputVarAreDif2ActiveState;
float backupConfOutputVarAreSim2ActiveState;
float backupConfOutputVarAreDif2ActiveState;
float backupConfInputVarAreSim2State;
float backupConfInputVarAreDif2State;
float backupConfOutputVarAreSim2State;
float backupConfOutputVarAreDif2State;
float highestConfidenceDifferenceMatch = 0;
// compare with all states
for (auto &state : vStates) {
confInputVarAreSim2State = state->getConfInputVarAreSim2State(
FuncBlockConfSim2StateDev, FuncBlockConfSim2StateTime);
confInputVarAreDif2State = state->getConfInputVarAreDif2State(
FuncBlockConfDif2StateDev, FuncBlockConfDif2StateTime);
confOutputVarAreSim2State = state->getConfOutputVarAreSim2State(
FuncBlockConfSim2StateDev, FuncBlockConfSim2StateTime);
confOutputVarAreDif2State = state->getConfOutputVarAreDif2State(
FuncBlockConfDif2StateDev, FuncBlockConfDif2StateTime);
// state matches full with another state
if ((confInputVarAreSim2State > confInputVarAreDif2State) &&
(confOutputVarAreSim2State > confOutputVarAreDif2State)) {
// lastActiveState == activeState;
activeState = state;
flagFoundMatchingState = true;
backupConfInputVarAreSim2State = confInputVarAreSim2State;
backupConfInputVarAreDif2State = confInputVarAreDif2State;
backupConfOutputVarAreSim2State = confOutputVarAreSim2State;
backupConfOutputVarAreDif2State = confOutputVarAreDif2State;
#ifdef PRINT
ptrdiff_t stateNr = find(vStates.begin(), vStates.end(), state) -
vStates.begin() + 1;
setColor(TXTCOLOR_LIGHTGREEN);
printf("- Passt voll zu: %i\n", stateNr);
setColor(TXTCOLOR_GREY);
#endif // PRINT
break;
}
// state matches half with another state
else if ((confInputVarAreSim2State > confInputVarAreDif2State) ||
(confOutputVarAreSim2State > confOutputVarAreDif2State)) {
flagFoundHalfMatchingState = true;
// half matchin state is the active state
if (state == activeStateBackup) {
#ifdef PRINT
ptrdiff_t stateNr = find(vStates.begin(), vStates.end(), state) -
vStates.begin() + 1;
setColor(TXTCOLOR_YELLOW);
printf("- Passt halb zu: %i (active State)\n", stateNr);
setColor(TXTCOLOR_GREY);
#endif // PRINT
flagHalfMatchingStateIsActiveState = true;
backupConfInputVarAreSim2ActiveState = confInputVarAreSim2State;
backupConfInputVarAreDif2ActiveState = confInputVarAreDif2State;
backupConfOutputVarAreSim2ActiveState = confOutputVarAreSim2State;
backupConfOutputVarAreDif2ActiveState = confOutputVarAreDif2State;
}
// half matchin state is the another state
else {
#ifdef PRINT
ptrdiff_t stateNr = find(vStates.begin(), vStates.end(), state) -
vStates.begin() + 1;
setColor(TXTCOLOR_YELLOW);
printf("- Passt halb zu: %i (another State)\n", stateNr);
setColor(TXTCOLOR_GREY);
#endif // PRINT
flagHalfMatchingStateIsAnotherState = true;
float diffConfInputVarAreSim2State =
confInputVarAreSim2State - confInputVarAreDif2State;
float diffConfOutputVarAreSim2State =
confOutputVarAreSim2State - confOutputVarAreDif2State;
if (diffConfInputVarAreSim2State >
highestConfidenceDifferenceMatch) {
activeState = state;
highestConfidenceDifferenceMatch = diffConfInputVarAreSim2State;
backupConfInputVarAreSim2State = confInputVarAreSim2State;
backupConfInputVarAreDif2State = confInputVarAreDif2State;
backupConfOutputVarAreSim2State = confOutputVarAreSim2State;
backupConfOutputVarAreDif2State = confOutputVarAreDif2State;
}
if (diffConfOutputVarAreSim2State >
highestConfidenceDifferenceMatch) {
activeState = state;
highestConfidenceDifferenceMatch =
diffConfOutputVarAreSim2State;
backupConfInputVarAreSim2State = confInputVarAreSim2State;
backupConfInputVarAreDif2State = confInputVarAreDif2State;
backupConfOutputVarAreSim2State = confOutputVarAreSim2State;
backupConfOutputVarAreDif2State = confOutputVarAreDif2State;
}
}
}
}
// another state matches In- AND Outputs
if (flagFoundMatchingState == true) {
// new revision cam
activeState->resetNumOfInsertedSamples();
if (flagActiveStateWasValid == false) {
delete activeStateBackup;
// activeState = NULL;
#ifdef PRINT
printf(" > delete active state\n");
#endif // PRINT
}
// Found a matching state
brokenCounter = 0;
#ifdef PRINT
printf(" > change to existing state\n");
#endif // PRINT
#ifdef STOP_WHEN_CHANGING_IN_OLD_STATE
getchar();
#endif // STOP_WHEN_CHANGING_IN_OLD_STATE
// update state
// 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);
// printf("HIER3\n");
csv_writer->write_field((int)vStates.size());
csv_writer->make_new_field();
ptrdiff_t stateNr =
find(vStates.begin(), vStates.end(), activeState) -
vStates.begin() + 1;
csv_writer->write_field((int)stateNr);
csv_writer->make_new_field();
#ifdef WRITE_MORE_INFORMATION_IN_CSV
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(backupConfInputVarAreSim2State);
csv_writer->make_new_field();
csv_writer->write_field(backupConfInputVarAreDif2State);
csv_writer->make_new_field();
csv_writer->write_field(backupConfOutputVarAreSim2State);
csv_writer->make_new_field();
csv_writer->write_field(backupConfOutputVarAreDif2State);
csv_writer->make_new_field();
#endif // WRITE_MORE_INFORMATION_IN_CSV
confidenceDrift = activeState->checkAllVariablesForDriftingFuzzy(
discreteAveragePartitionSize, FuncBlockDriftDeviation);
float confidenceNoDrift = 1 - confidenceDrift;
// AAAAAAAAA (New: "&& activeState->isStateValidAfterReentrance()")
if (confidenceDrift > 0.5 &&
activeState->isStateValidAfterReentrance()) {
#ifdef PRINT
printDrift();
#endif // PRINT
#ifdef STOP_WHEN_DRIFT
getchar();
#endif // STOP_WHEN_DRIFT
// print drift
csv_writer->write_field(STATUS_DRIFT);
csv_writer->make_new_field();
// calc and print conf
//AAAAAAAAAAAAAAAA
float conf = fuzzyAND(
fuzzyAND(backupConfInputVarAreSim2State,
backupConfOutputVarAreSim2State),
fuzzyAND(confidenceDrift, activeState->getConfStateValid()));
csv_writer->write_field(conf);
// printf("drift bei (flagFoundMatchingState): %i\n", cycle);
} else {
#ifdef PRINT
printOK();
#endif // PRINT
// print ok
csv_writer->write_field(STATUS_OKAY);
csv_writer->make_new_field();
// calc and print conf
//AAAAA1
//NOTE: next equation is without confOK because confOK = 1 anyway (because broken timer = 0)
float conf =
fuzzyAND(fuzzyOR(fuzzyAND(backupConfInputVarAreSim2State,
backupConfOutputVarAreSim2State),
fuzzyAND(backupConfInputVarAreDif2State,
backupConfOutputVarAreDif2State)),
fuzzyAND(activeState->getConfStateValid(),
confidenceNoDrift));
csv_writer->write_field(conf);
}
// csv_writer->make_new_field();
}
// ONLY In- OR Outputs match one state
else if (flagFoundHalfMatchingState == true) {
// active state is half matching
if (flagHalfMatchingStateIsActiveState == true) {
activeState = activeStateBackup;
brokenCounter++;
backupConfInputVarAreSim2State =
backupConfInputVarAreSim2ActiveState;
backupConfInputVarAreDif2State =
backupConfInputVarAreDif2ActiveState;
backupConfOutputVarAreSim2State =
backupConfOutputVarAreSim2ActiveState;
backupConfOutputVarAreDif2State =
backupConfOutputVarAreDif2ActiveState;
}
// only other state(s) is half matching
else if (flagHalfMatchingStateIsAnotherState == true) {
// printf("IS ER HIER?\n");
activeState->resetNumOfInsertedSamples();
if (flagActiveStateWasValid == false) {
delete activeStateBackup;
// activeState = NULL;
#ifdef PRINT
printf(" > delete active state\n");
#endif // PRINT
}
} else {
printf("Error in halfmatching\n");
getchar();
}
// new revision cam
if (activeState->isStateValid() == false ||
activeState->isStateValidAfterReentrance() == false) {
brokenCounter = 0;
}
csv_writer->write_field((int)vStates.size());
csv_writer->make_new_field();
ptrdiff_t stateNr =
find(vStates.begin(), vStates.end(), activeState) -
vStates.begin() + 1;
csv_writer->write_field((int)stateNr);
csv_writer->make_new_field();
#ifdef WRITE_MORE_INFORMATION_IN_CSV
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(backupConfInputVarAreSim2State);
csv_writer->make_new_field();
csv_writer->write_field(backupConfInputVarAreDif2State);
csv_writer->make_new_field();
csv_writer->write_field(backupConfOutputVarAreSim2State);
csv_writer->make_new_field();
csv_writer->write_field(backupConfOutputVarAreDif2State);
csv_writer->make_new_field();
#endif // WRITE_MORE_INFORMATION_IN_CSV
// check broken counter
#ifdef PRINT
printf("brokenCounter: %u\n", brokenCounter);
#endif // PRINT
confidenceBroken =
FuncBlockConfBrokenSamples->getY((float)brokenCounter);
float confidenceOK = 1 - confidenceBroken;
if (confidenceBroken > 0.5) {
#ifdef PRINT
setColor(TXTCOLOR_LIGHTRED);
printf("BROKEN\n");
setColor(TXTCOLOR_GREY);
#endif // PRINT
#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 {
confidenceDrift = activeState->checkAllVariablesForDriftingFuzzy(
discreteAveragePartitionSize, FuncBlockDriftDeviation);
float confidenceNoDrift = 1 - confidenceDrift;
// AAAAAAAAA (New: "&& activeState->isStateValidAfterReentrance()")
if (confidenceDrift > 0.5 &&
activeState->isStateValidAfterReentrance()) {
#ifdef PRINT
printDrift();
#endif // PRINT
#ifdef STOP_WHEN_DRIFT
getchar();
#endif // STOP_WHEN_DRIFT
// print drift
csv_writer->write_field(STATUS_DRIFT);
csv_writer->make_new_field();
// calc and print conf
//AAAAAAAAAAAAA
float conf = fuzzyAND(
fuzzyAND(backupConfInputVarAreSim2State,
backupConfOutputVarAreSim2State),
fuzzyAND(confidenceDrift, activeState->getConfStateValid()));
csv_writer->write_field(conf);
} else {
#ifdef PRINT
printOK();
#endif // PRINT
// print ok
csv_writer->write_field(STATUS_OKAY);
csv_writer->make_new_field();
// calc and print conf
//AAAAAAAAAA
float conf =
fuzzyAND(fuzzyOR(fuzzyAND(backupConfInputVarAreSim2State,
backupConfOutputVarAreSim2State),
fuzzyAND(backupConfInputVarAreDif2State,
backupConfOutputVarAreDif2State)),
fuzzyAND(activeState->getConfStateValid(),
fuzzyAND(confidenceNoDrift, confidenceOK)));
csv_writer->write_field(conf);
}
}
// csv_writer->make_new_field();
}
// No State matches -> make new state
else {
// was active state valid? -> If not -> delete it
if (flagActiveStateWasValid == false) {
delete activeStateBackup;
// activeState = NULL;
#ifdef PRINT
printf(" > delete active state\n");
#endif // PRINT
}
brokenCounter = 0;
// create new state and update it
makeNewActiveState();
confInputVarAreSim2ActiveState = 0;
confInputVarAreDif2ActiveState = 0;
confOutputVarAreSim2ActiveState = 0;
confOutputVarAreDif2ActiveState = 0;
#ifdef PRINT
printf(" > new active state\n");
#endif // PRINT
// 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);
csv_writer->write_field((int)vStates.size());
csv_writer->make_new_field();
ptrdiff_t stateNr =
find(vStates.begin(), vStates.end(), activeState) -
vStates.begin() + 1;
csv_writer->write_field((int)stateNr);
csv_writer->make_new_field();
#ifdef WRITE_MORE_INFORMATION_IN_CSV
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(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();
#endif // WRITE_MORE_INFORMATION_IN_CSV
csv_writer->write_field(STATUS_OKAY); // OK
csv_writer->make_new_field();
// NOTE: Status Conf = 0 because conf valid = 0
csv_writer->write_field(0);
// csv_writer->make_new_field();
}
}
#ifdef PRINT
printf("isStateValid = %i\nValidAfterReentrance = %i\n",
activeState->isStateValid(),
activeState->isStateValidAfterReentrance());
ptrdiff_t pos = find(vStates.begin(), vStates.end(), activeState) -
vStates.begin() + 1;
printf("cycle: %u, \n STATES: %u\n ActualState: %u\n", cycle,
vStates.size(), pos);
#endif // PRINT
}
}
csv_writer->make_new_line();
if (brokentest)
getchar();
#ifdef STOP_EVERY_TIME
getchar();
#endif // STOP_EVERY_TIME
#ifdef STOP_EVERY_TIME_AFTER_SAMPLENR
if (cycle >= STOP_EVERY_TIME_AFTER_SAMPLENR)
getchar();
#endif // STOP_EVERY_TIME_AFTER_SAMPLENR
}
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];
std::string output_file_name_str;
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime(datetime, sizeof(datetime), "%Y-%m-%d_%I-%M-%S", timeinfo);
#ifndef INPUT_FILE_NAME
output_file_name_str =
output_directory_name + "output" + datetime + cfg_parameter + ".csv";
#else
string out_dir = "../data/out/";
output_file_name_str =
out_dir + INPUT_FILE_NAME + datetime + cfg_parameter + ".csv";
#endif // INPUT_FILE_NAME
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);
}
diff --git a/Version_Max_07_05_2018_CMake/src/Testbench.cpp b/Version_Max_07_05_2018_CMake/src/Testbench.cpp
index 8410a65..ba1d1de 100755
--- a/Version_Max_07_05_2018_CMake/src/Testbench.cpp
+++ b/Version_Max_07_05_2018_CMake/src/Testbench.cpp
@@ -1,684 +1,686 @@
#include "Testbench.h"
#include "printError.h"
#include <stdio.h>
using namespace std;
void Testbench :: init_testbench() {
//TODO
//some init source code to add, if necessary
}
Testbench :: Testbench() {
set_name(NO_NAME);
}
Testbench :: Testbench(std::string 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);
return true; //added by Ali, it is an error in VS.
}
vector<Testbench_Config*>& Testbench :: get_all_registered_testbench_configs()
{
return vector_registered_Configs;
}
void Testbench :: simulate(unsigned int rounds) {
for(unsigned int cycle = 1; cycle <=rounds; cycle++) {
//update sensor values
for(auto &sensorSlot : vector_registeredSensors) {
Sensor *sensor = sensorSlot->get_sensor();
//printf("Name of Sensor %s \n", sensor->get_name().c_str());
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);
}
}
}
+
+ //AFTER SIMULATION
//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<AgentSlotOfTestbench*>& 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();
}
return true; //added by Ali, it is an error in VS.
}
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<AgentSlotOfTestbench*> 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();
/*
//TODO: the Function Blocks of Statehandler should be private members of state handler. There already exist public set functions.
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);
*/
set_parameters_FuncBlockConfSim2StateDev(
cur_state_Handl->getSimilarToStateDeviationFuzzyFunction());
set_parameters_FuncBlockConfDif2StateDev(
cur_state_Handl->getDifferentToStateDeviationFuzzyFunction());
set_parameters_FuncBlockConfSim2StateTime(
cur_state_Handl->getSimilarToStateTimeFuzzyFunction());
set_parameters_FuncBlockConfDif2StateTime(
cur_state_Handl->getDifferentToStateTimeFuzzyFunction());
set_parameters_FuncBlockConfValStateDev(
cur_state_Handl->getSimilarityInStateDeviationFuzzyFunction());
set_parameters_FuncBlockConfInvStateDev(
cur_state_Handl->getUnsimilarityInStateDeviationFuzzyFunction());
set_parameters_FuncBlockConfValStateTime(
cur_state_Handl->getSimilarityInStateTimeFuzzyFunction());
set_parameters_FuncBlockConfInvStateTime(
cur_state_Handl->getUnsimilarityInStateTimeFuzzyFunction());
set_parameters_DriftDeviation(cur_state_Handl->getDriftFuzzyFunction());
set_parameters_FuncBlockConfBrokenSamples(
cur_state_Handl->getBrokenFuzzyFunction());
}
void Testbench :: set_parameters_FuncBlockConfSim2StateDev(LinearFunctionBlock* FuncBlockConfSim2StateDev)
{
LinearFunction* cur_Lin_Fun;
vector<LinearFunction*> 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<LinearFunction*> 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<LinearFunction*> 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<LinearFunction*> 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<LinearFunction*> 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<LinearFunction*> 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<LinearFunction*> 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<LinearFunction*> 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<LinearFunction*> 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<LinearFunction*> 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();
}

File Metadata

Mime Type
text/x-diff
Expires
Sat, May 17, 11:04 PM (1 d, 14 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
141603
Default Alt Text
(971 KB)

Event Timeline