Explorar el Código

Merge branch 'master' of https://msdl.uantwerpen.be/git/claudio/HybridCosimulation

# Conflicts:
#	.gitignore
Cláudio Gomes hace 8 años
padre
commit
c5a2e3163b
Se han modificado 99 ficheros con 12943 adiciones y 0 borrados
  1. 1 0
      .gitignore
  2. 9 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/.classpath
  3. 34 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/.project
  4. 2 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/.settings/org.eclipse.core.resources.prefs
  5. 7 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/.settings/org.eclipse.jdt.core.prefs
  6. 22 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/META-INF/MANIFEST.MF
  7. 5 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/build.properties
  8. 23 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/input/plant.sa
  9. 32 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/input/powerwindow.sa
  10. 12 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/input/powerwindow_algebraic_loop_delay.sa
  11. 22 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/input/powerwindow_algebraic_loop_delay_BASE.sa
  12. 17 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/input/powerwindow_algebraic_loop_iteration.sa
  13. 106 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/input/powerwindow_algebraic_loop_iteration_BASE.sa
  14. 21 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/input/powerwindow_controller_delay.sa
  15. 75 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/input/powerwindow_controller_delay_BASE.sa
  16. 32 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/input/powerwindow_model_only.sa
  17. 9 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/input/powerwindow_multi_rate.sa
  18. 38 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/input/powerwindow_multi_rate_BASE.sa
  19. 29 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/input/test1.sa
  20. 22 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/input/window_obstacle_sa_loop_BASE.sa
  21. 26 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/input/window_obstacle_sa_loop_BASE_new.sa
  22. 16 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/input/window_obstacle_sa_multirate_BASE.sa
  23. 5 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/input/window_sa_BASE.sa
  24. 1 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/oracles/test1.txt
  25. 57 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/src/be/uantwerpen/ansymo/semanticadaptation/tests/AbstractSemanticAdaptationGeneratorTest.xtend
  26. 26 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/src/be/uantwerpen/ansymo/semanticadaptation/tests/AbstractSemanticAdaptationParserTest.xtend
  27. 120 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/src/be/uantwerpen/ansymo/semanticadaptation/tests/AbstractSemanticAdaptationTest.xtend
  28. 36 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/src/be/uantwerpen/ansymo/semanticadaptation/tests/SemanticAdaptationGeneratorTest.xtend
  29. 97 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/src/be/uantwerpen/ansymo/semanticadaptation/tests/SemanticAdaptationParsingTest.xtend
  30. 9 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/.classpath
  31. 34 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/.project
  32. 2 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/.settings/org.eclipse.core.resources.prefs
  33. 7 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/.settings/org.eclipse.jdt.core.prefs
  34. 29 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/META-INF/MANIFEST.MF
  35. 18 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/build.properties
  36. 10 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/plugin.xml
  37. 10 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/plugin.xml_gen
  38. 43 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/src/be/uantwerpen/ansymo/semanticadaptation/GenerateSemanticAdaptation.mwe2
  39. 375 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/src/be/uantwerpen/ansymo/semanticadaptation/SemanticAdaptation.xtext
  40. 24 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/src/be/uantwerpen/ansymo/semanticadaptation/SemanticAdaptationRuntimeModule.xtend
  41. 15 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/src/be/uantwerpen/ansymo/semanticadaptation/SemanticAdaptationStandaloneSetup.xtend
  42. 25 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/src/be/uantwerpen/ansymo/semanticadaptation/generator/SemanticAdaptationGenerator.xtend
  43. 111 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/src/be/uantwerpen/ansymo/semanticadaptation/generator/SemanticAdaptationPythonGenerator.xtend
  44. 68 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/src/be/uantwerpen/ansymo/semanticadaptation/interpreter/Interpreter.xtend
  45. 315 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/src/be/uantwerpen/ansymo/semanticadaptation/scoping/SemanticAdaptationScopeProvider.xtend
  46. 61 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/src/be/uantwerpen/ansymo/semanticadaptation/validation/SemanticAdaptationValidator.xtend
  47. 49 0
      DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/src/be/uantwerpen/ansymo/semanticadaptation/valueconverter/SemanticAdaptationValueConverters.xtend
  48. BIN
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_SEL/Debug/libFMI_SEL.dll
  49. 542 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_SEL/FMI_SEL.c
  50. 51 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_SEL/FMI_SEL.h
  51. 247 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_SEL/fmi2/fmi2FunctionTypes.h
  52. 339 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_SEL/fmi2/fmi2Functions.h
  53. 115 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_SEL/fmi2/fmi2TypesPlatform.h
  54. BIN
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_TD/Debug/libFMI_TD.dll
  55. 464 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_TD/FMI_TD.c
  56. 51 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_TD/FMI_TD.h
  57. 247 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_TD/fmi2/fmi2FunctionTypes.h
  58. 339 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_TD/fmi2/fmi2Functions.h
  59. 115 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_TD/fmi2/fmi2TypesPlatform.h
  60. BIN
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_Window_sa/Debug/libFMI_Window_sa.dll
  61. 490 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_Window_sa/FMI_Window_sa.c
  62. 50 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_Window_sa/FMI_Window_sa.h
  63. 72 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_Window_sa/fmi2/fmi2.h
  64. 247 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_Window_sa/fmi2/fmi2FunctionTypes.h
  65. 339 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_Window_sa/fmi2/fmi2Functions.h
  66. 115 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_Window_sa/fmi2/fmi2TypesPlatform.h
  67. 593 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_Window_sa/sim_support.c
  68. 44 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_Window_sa/sim_support.h
  69. BIN
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_control_master/Debug/libFMI_control_master.dll
  70. 535 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_control_master/FMI_CM.c
  71. 52 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_control_master/FMI_CM.h
  72. 72 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_control_master/fmi2/fmi2.h
  73. 247 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_control_master/fmi2/fmi2FunctionTypes.h
  74. 339 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_control_master/fmi2/fmi2Functions.h
  75. 115 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_control_master/fmi2/fmi2TypesPlatform.h
  76. 593 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_control_master/sim_support.c
  77. 44 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_control_master/sim_support.h
  78. BIN
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_generic_master/Debug/libFMI_generic_master.dll
  79. 602 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_generic_master/FMI_GM.c
  80. 52 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_generic_master/FMI_GM.h
  81. 72 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_generic_master/fmi2/fmi2.h
  82. 247 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_generic_master/fmi2/fmi2FunctionTypes.h
  83. 339 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_generic_master/fmi2/fmi2Functions.h
  84. 115 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_generic_master/fmi2/fmi2TypesPlatform.h
  85. 594 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_generic_master/sim_support.c
  86. 44 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_generic_master/sim_support.h
  87. BIN
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/PW_Controller/libpw_controller.dll
  88. 71 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/PW_Controller/modelDescription.xml
  89. BIN
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/PW_Controller/src/Debug/libpw_controller.dll
  90. 497 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/PW_Controller/src/PW_Controller.c
  91. 48 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/PW_Controller/src/PW_Controller.h
  92. 690 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/PW_Controller/src/Powerwindow.c
  93. 124 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/PW_Controller/src/Powerwindow.h
  94. 61 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/PW_Controller/src/PowerwindowRequired.c
  95. 82 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/PW_Controller/src/PowerwindowRequired.h
  96. 247 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/PW_Controller/src/fmi2/fmi2FunctionTypes.h
  97. 339 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/PW_Controller/src/fmi2/fmi2Functions.h
  98. 115 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/PW_Controller/src/fmi2/fmi2TypesPlatform.h
  99. 40 0
      SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/PW_Controller/src/sc_types.h

+ 1 - 0
.gitignore

@@ -7,4 +7,5 @@
 /SemanticAdaptationForFMI/FMIAbstraction/src/case_study/units/ct_based/*.pyc
 /SemanticAdaptationForFMI/FMIAbstraction/src/case_study/units/de_based/*.pyc
 /SemanticAdaptationForFMI/FMIAbstraction/src/master/*.pyc
+/DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/.antlr-generator-3.2.0-patch.jar
 /SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/log_statemachine.txt

+ 9 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/.classpath

@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+	<classpathentry kind="src" path="src"/>
+	<classpathentry kind="src" path="src-gen"/>
+	<classpathentry kind="src" path="xtend-gen"/>
+	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
+	<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+	<classpathentry kind="output" path="bin"/>
+</classpath>

+ 34 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/.project

@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+	<name>be.uantwerpen.ansymo.semanticadaptation.tests</name>
+	<comment></comment>
+	<projects>
+	</projects>
+	<buildSpec>
+		<buildCommand>
+			<name>org.eclipse.xtext.ui.shared.xtextBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>org.eclipse.jdt.core.javabuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>org.eclipse.pde.ManifestBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>org.eclipse.pde.SchemaBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+	</buildSpec>
+	<natures>
+		<nature>org.eclipse.xtext.ui.shared.xtextNature</nature>
+		<nature>org.eclipse.jdt.core.javanature</nature>
+		<nature>org.eclipse.pde.PluginNature</nature>
+	</natures>
+</projectDescription>

+ 2 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/.settings/org.eclipse.core.resources.prefs

@@ -0,0 +1,2 @@
+eclipse.preferences.version=1
+encoding/<project>=windows-1252

+ 7 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/.settings/org.eclipse.jdt.core.prefs

@@ -0,0 +1,7 @@
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
+org.eclipse.jdt.core.compiler.compliance=1.8
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.source=1.8

+ 22 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/META-INF/MANIFEST.MF

@@ -0,0 +1,22 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: be.uantwerpen.ansymo.semanticadaptation.tests
+Bundle-Vendor: My Company
+Bundle-Version: 1.0.0.qualifier
+Bundle-SymbolicName: be.uantwerpen.ansymo.semanticadaptation.tests; singleton:=true
+Bundle-ActivationPolicy: lazy
+Require-Bundle: be.uantwerpen.ansymo.semanticadaptation,
+ org.junit;bundle-version="4.7.0",
+ org.eclipse.xtext.junit4,
+ org.eclipse.xtext.xbase.junit,
+ org.eclipse.xtext.xbase.lib,
+ org.eclipse.jdt.core
+Bundle-RequiredExecutionEnvironment: JavaSE-1.8
+Export-Package: be.uantwerpen.ansymo.semanticadaptation.tests
+Import-Package: org.hamcrest.core,
+ org.junit;version="4.5.0",
+ org.junit.runners.model;version="4.5.0",
+ org.junit.runner;version="4.5.0",
+ org.junit.runners;version="4.5.0",
+ org.junit.runner.manipulation;version="4.5.0",
+ org.junit.runner.notification;version="4.5.0"

+ 5 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/build.properties

@@ -0,0 +1,5 @@
+source.. = src/,\
+           src-gen/,\
+           xtend-gen/
+bin.includes = .,\
+               META-INF/

+ 23 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/input/plant.sa

@@ -0,0 +1,23 @@
+semantic adaptation power_sa
+for continuous time
+input ports up, down, reaction_torque
+output ports armature_current, motor_speed
+in rules {} // needs to be detected exactly when reaction_torque starts to change rapidly -> zero crossing on derivative abs(reaction_torque') >! 100
+out rules {}
+control rules {}
+
+semantic adaptation window_sa
+for continuous time
+input ports motor_speed
+output ports height, window_reaction_torque
+in rules {}
+out rules {}
+control rules {}
+
+semantic adaptation obstacle_sa
+for continuous time
+input ports height
+output ports obstacle_reaction_torque
+in rules {}
+out rules {}
+control rules {}

+ 32 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/input/powerwindow.sa

@@ -0,0 +1,32 @@
+import PowerWindowModel
+
+semantic adaptation controller_sa
+for fmu controller
+input ports armature_current -> obj_detected, passenger_up, passenger_down, driver_up, driver_down, next
+output ports up, down
+triggered by signal == true or t >= get_next_time_step(controller)
+in rules with crossing absolute tolerance = 1e-8 and relative tolerance = 0.0001, no hold {
+	armature_current >! 5 -> obj_detected := true;
+	otherwise(armature_current) -> obj_detected := false;
+}
+out rules with zero order hold {
+	"up" -> up := 1;
+	"stop" -> { up := 0; down := 0; };
+	"down" -> down := 1;
+	delay at up and down;
+}
+
+semantic adaptation window_sa
+for fmu window
+out rules {
+	reaction_torque := -reaction_torque;
+}
+
+semantic adaptation window_obstacle_sa
+for fmu window_sa, obstacle
+multiply rate 10 times with first order interpolation
+successive substitution starts at height with absolute tolerance = 1e-8 and relative tolerance = 0.0001
+
+semantic adaptation plant_sa
+for fmu power, window_obstacle_sa
+successive substitution starts at reaction_torque with absolute tolerance = 1e-6 and relative tolerance = 1e-6

+ 12 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/input/powerwindow_algebraic_loop_delay.sa

@@ -0,0 +1,12 @@
+import PowerWindowModel
+import Controller_SA
+
+module Algebraic_Loop_SA
+
+// this one could be joined with the one below, if we assume certain priorities in executing the rules
+semantic adaptation window_sa
+for fmu window
+out rules {
+	reaction_torque := -reaction_torque;
+	delay at reaction_torque and height;
+}

+ 22 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/input/powerwindow_algebraic_loop_delay_BASE.sa

@@ -0,0 +1,22 @@
+import PowerWindowModel
+import Controller_SA
+
+// this one could be joined with the one below, if we assume certain priorities in executing the rules
+semantic adaptation window_sa
+for fmu window
+out rules {
+	true -> {reaction_torque := -reaction_torque; } --> { };
+}
+
+// algebraic loop, simply use delay... written in baseDSL
+semantic adaptation window_sa_delay //with master
+for fmu window_sa // inner SA, makes it possible to enforce order among adaptations this way
+param init_height = 0;
+param init_reaction_torque = 0;
+out var stored_height := init_height;
+out var stored_reaction_torque := init_reaction_torque;
+out rules {
+	true -> { var temp_height := height; height := stored_height; stored_height := temp_height; } --> { };
+	true -> { var temp_reaction_torque := reaction_torque; reaction_torque := stored_reaction_torque; stored_reaction_torque := temp_reaction_torque; } --> { }; 
+}
+

+ 17 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/input/powerwindow_algebraic_loop_iteration.sa

@@ -0,0 +1,17 @@
+import PowerWindowModel
+import Controller_SA
+
+// this one could be joined with the one below, if we assume certain priorities in executing the rules
+semantic adaptation window_sa
+for fmu window
+out rules {
+	reaction_torque := -reaction_torque;
+}
+
+// algebraic loop
+semantic adaptation power_window_obstacle_sa
+for fmu power, window_sa, obstacle
+input ports up, down // optional, can be figured out from model
+output ports armature_current // optional, can be figured out from model
+successive substitution starts at reaction_torque and height with absolute tolerance = 1e-8 and relative tolerance = 0.0001
+

+ 106 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/input/powerwindow_algebraic_loop_iteration_BASE.sa

@@ -0,0 +1,106 @@
+import PowerWindowModel
+import Controller_SA
+
+// this one could be joined with the one below, if we assume certain priorities in executing the rules
+semantic adaptation window_sa
+for fmu window
+out rules {
+	true -> {reaction_torque := -reaction_torque; } --> { };
+}
+
+// algebraic loop
+semantic adaptation power_window_obstacle_sa // without master -> not necessary: custom control rules override master
+for fmu power, window_sa, obstacle
+input ports up, down
+output ports armature_current
+//algebraic loop fix point iteration at reaction_torque and height with absolute tolerance = 1e-8 and relative tolerance = 0.0001
+param MAXITER = 100;
+param REL_TOL = 1e-8;
+param ABS_TOL = 1e-8;
+control {
+	// do_step will always use the last values, do_step does not advance time so will replace the last signal values! 
+	// therefore, we must set the signal at time t+h of reaction_torque and height
+	// this is done by a very weird statement:
+	reaction_torque := reaction_torque;
+	height := height;
+	// and just initialise other values at time t+h
+	armature_current := 0;
+	motor_speed := 0;
+	reaction_force := 0;
+	// now, all inputs are set at time t+h and we can start substituting them
+	var converged := false;
+	var temp_height; // to compare new value with previous value
+	var temp_reaction_torque; // to compare new value with previous value
+	for (var iter in 0 .. MAXITER) {
+		if (converged) {
+			break;
+		}
+		temp_height := height;
+		temp_reaction_torque := reaction_torque;
+		//local_step(power); // with delayed input for reaction_torque
+		//local_step(obstacle); // with delayed input for height
+		local_step(power);
+		local_step(obstacle);
+		local_step(window_sa);
+		//local_step(H, power, obstacle, window_sa); // acts like the Local master but cannot not advance time, so will always roll-back for safety (must be in one statements because a full step is done here), but how do we get the inner
+		if (is_close(temp_height, height, REL_TOL, ABS_TOL) and is_close(temp_reaction_torque, reaction_torque, REL_TOL, ABS_TOL)) { // todo: set tolerance
+			converged := true;
+		}
+	}
+	return H;
+}
+
+// this is the one for the paper
+semantic adaptation window_obstacle_sa_loop// overrides master -> not necessary: custom control rules override master
+for fmu window_sa, obstacle
+input ports motor_speed
+output ports reaction_torque
+param MAXITER = 100;
+param REL_TOL = 1e-8;
+param ABS_TOL = 1e-8;
+control {
+	var prev_height; // to compare new value with previous value
+	var window_state;
+	var obstacle_state;
+	height := height; // do_step will always use the last values, local_step does not advance time so will replace the last signal values! therefore, we must set the signal at time t+h of reaction_torque and height. this is done by a very weird statement:
+	reaction_force := 0; // and just initialise other values at time t+h
+	for (var iter in 0 .. MAXITER) {
+		prev_height := height;
+		local_step(obstacle); // with delayed input for height. overwrite current time step: basically a set_state (state at previous time step), do_step (with time step H)
+		local_step(window_sa);
+		if (is_close(prev_height, height, REL_TOL, ABS_TOL)) {
+			break;
+		}
+	}
+	return H;
+}
+
+// other version without local_step
+semantic adaptation window_obstacle_sa_loop2// overrides master -> not necessary: custom control rules override master
+for fmu window_sa, obstacle
+input ports motor_speed
+output ports reaction_torque
+param MAXITER = 100;
+param REL_TOL = 1e-8;
+param ABS_TOL = 1e-8;
+control {
+	var prev_height; // to compare new value with previous value
+	var window_state;
+	var obstacle_state;
+	for (var iter in 0 .. MAXITER) {
+		window_state := get_state(window_sa);
+		obstacle_state := get_state(obstacle);
+		prev_height := height;
+		do_step(obstacle, H); // with delayed input for height
+		do_step(window_sa, H);
+		if (is_close(prev_height, height, REL_TOL, ABS_TOL)) {
+			break;
+		} else {
+			set_state(window_sa, window_state);
+			set_state(obstacle, obstacle_state);
+		}
+	}
+	return H;
+}
+
+

+ 21 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/input/powerwindow_controller_delay.sa

@@ -0,0 +1,21 @@
+import PowerWindowModel
+
+module Controller_SA
+
+semantic adaptation armature_current_sa
+for fmu controller
+triggered by signal == true
+in rules with crossing absolute tolerance = 1e-8 and relative tolerance = 0.0001, no hold {
+	armature_current >! 5 -> obj_detected := true;
+	otherwise(armature_current) -> obj_detected := false;
+}
+
+semantic adaptation in_out_sa
+for fmu controller
+out rules with zero order hold {
+	"up" -> up := 1;
+	"stop" -> { up := 0; down := 0; };
+	"down" -> down := 1;
+	delay at up and down;
+}
+

+ 75 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/input/powerwindow_controller_delay_BASE.sa

@@ -0,0 +1,75 @@
+import PowerWindowModel
+
+module Controller_SA
+
+semantic adaptation controller_sa
+for fmu controller
+input ports armature_current -> obj_detected, passenger_up, passenger_down, driver_up, driver_down
+output ports up, down
+param REL_TOL = 0.0001;
+param ABS_TOL = 1e-8;
+param CROSSING = 5;
+param init_armature_current = CROSSING;
+param init_up = 0;
+param init_down = 0;
+control { // overwriting master! What to do in case of roll back? How to reuse generic algorithm
+	var step_size; // may be used to determine roll-back
+	if (signal == true or t >= internal_transition) {
+		step_size := do_step(controller, e+H); // do a step, then decide next internal transition
+	}
+	return step_size;
+}
+in var stored_armature_current := init_armature_current;
+in var internal_transition;
+in rules {
+	not is_set(internal_transition) -> { internal_transition := get_next_time_step(controller) + t; } --> { };
+	true -> {
+		obj_detected := false;
+		if (not (not is_close(stored_armature_current, CROSSING, REL_TOL, ABS_TOL) and stored_armature_current > CROSSING)
+					and (not is_close(armature_current, CROSSING, REL_TOL, ABS_TOL) and armature_current > CROSSING)) { // crossing, but not within tolerance
+			var negative_value := stored_armature_current - CROSSING;
+			var positive_value := armature_current - CROSSING;
+			var new_step_size := (H * (- negative_value)) / (positive_value - negative_value);
+			discard(new_step_size);
+		} else {
+			if (not (not is_close(stored_armature_current, CROSSING, REL_TOL, ABS_TOL) and stored_armature_current > CROSSING)
+						and is_close(armature_current, CROSSING, REL_TOL, ABS_TOL)) { // crossing within tolerance found
+				obj_detected := true;
+			}
+		}
+		stored_armature_current := armature_current;
+	} --> { };
+	
+}
+out var stored_up := init_up;
+out var stored_down := init_down;
+out rules {
+	true -> { internal_transition := get_next_time_step(controller) + t; } --> {};
+	up == true -> { up := 1; } --> { };
+	otherwise up -> { } --> { };
+	down == true -> { down := 1; } --> { };
+	otherwise down -> { } --> { };
+	stop == true -> { up := 0; down := 0; } --> { };
+	otherwise stop -> { } --> { };
+	true -> { up := stored_up; stored_up := up; } --> { };
+	true -> { down := stored_down; stored_down := down; } --> { }; 
+}
+
+
+// other suggestion for implementing get_next_time_step, making it easier to generate baseDSL code
+/*control { // overwriting master! What to do in case of roll back? How to reuse generic algorithm
+       var step_size; // may be used to determine roll-back
+       if (signal == true or t >= internal_transition) {
+             step_size := do_step(controller, e+H); // do a step, then decide next internal transition
+       }
+       return step_size;
+}
+in var internal_transition;
+in rules {
+       not is_set(internal_transition) -> {
+             if (not is_set(internal_transition)) {
+                    internal_transition := get_next_step(controller) + t;
+              }
+       } --> { internal_transition := get_next_step(controller) + t; };
+}*/
+

+ 32 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/input/powerwindow_model_only.sa

@@ -0,0 +1,32 @@
+module PowerWindowModel
+
+fmu environment
+type discrete event
+output ports passenger_up, passenger_down, driver_up, driver_down
+full internal dependencies
+
+fmu controller
+type discrete event
+input ports obj_detected, passenger_up, passenger_down, driver_up, driver_down
+output ports up, down, stop
+full internal dependencies
+
+fmu power
+type continuous time
+input ports up, down, reaction_torque (N.m)
+output ports armature_current (mA), motor_speed (m/s)
+full internal dependencies
+
+fmu window
+type continuous time
+input ports motor_speed (m/s), reaction_force (N)
+output ports height (cm), window_reaction_torque (N.m)
+full internal dependencies
+
+fmu obstacle
+type continuous time
+input ports height (m)
+output ports reaction_force (N)
+full internal dependencies
+
+armature_current -> obj_detected // only ports that change names need to be connected

+ 9 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/input/powerwindow_multi_rate.sa

@@ -0,0 +1,9 @@
+import PowerWindowModel
+import Controller_SA
+import Algebraic_Loop_SA
+
+// multi-rate for window and object
+semantic adaptation window_obstacle_sa
+for fmu window_sa, obstacle
+multiply rate 10 times with first order interpolation
+successive substitution starts at height with absolute tolerance = 1e-8 and relative tolerance = 0.0001

+ 38 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/input/powerwindow_multi_rate_BASE.sa

@@ -0,0 +1,38 @@
+import PowerWindowModel
+
+semantic adaptation window_sa
+for fmu window
+out rules {
+	true -> { } --> { reaction_torque := -reaction_torque; };
+}
+
+semantic adaptation window_obstacle_sa_loop
+for fmu window_sa, obstacle
+// just for the sake of declaring this, look at algebraic loop iteration
+
+semantic adaptation window_obstacle_sa_multirate //with master // multi-rate for window and object
+for fmu window_obstacle_sa_loop
+input ports motor_speed
+output ports reaction_torque
+param init_motor_speed = 0;
+control {
+	var h := H/10;
+	var proposed_h := H;
+	for (var iter in 0 .. 10) {
+		var returned_h := do_step(window_obstacle_sa_loop, h);
+		if (returned_h != h) { // for backtracking
+			 proposed_h := iter*h + returned_h;
+		}
+	}
+	return proposed_h;
+}
+in var stored_motor_speed := init_motor_speed;
+in var linear_increment;
+in rules {
+	true -> {
+		linear_increment := (motor_speed - stored_motor_speed) / 10;
+		stored_motor_speed := motor_speed;
+	} --> {
+		motor_speed := motor_speed + linear_increment;
+	};
+}

+ 29 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/input/test1.sa

@@ -0,0 +1,29 @@
+semantic adaptation TEST
+for discrete event
+input ports x[1 .. 2] (kg.m/s 2), y, z
+output ports a, b, c
+extract directionalderivative 
+{= (signal-signal[prev]) / h }
+{
+	def firstorder(s) {
+		var temp;
+		temp = s-s[prev];
+		return temp / h;
+	}
+	return firstorder(x);
+}
+
+in rules with zero crossing tolerance = 0.001, no hold { // for CT to inner DE
+	not x[prev]+3 > 2+2*floor(y[now]+round(8.2)) and y < 4 -> todo --> todo;
+	x >! 2 with tolerance = 0.0001 -> "high" --> no hold; // means condition -> IN action -> UPDATE IN action
+	x >! 1 or x <! 2 -> "low" --> no hold;
+	x <! 1 -> "off"; // i.e., no hold is the default
+	otherwise(x) -> null --> zero order hold;
+	quantize(y, "off", 1, "low", 2, "high") --> no hold;
+	quantize(z, ="event"+floor(z + 0.5)) --> no hold;
+	quantize(z, ="event"+round(z)) --> no hold;
+	quantize z every 2 offset 1 --> no hold;
+}
+//out rules with buffer[10] {}
+out rules {}
+control rules {}

+ 22 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/input/window_obstacle_sa_loop_BASE.sa

@@ -0,0 +1,22 @@
+semantic adaptation window_obstacle_sa_loop overrides master
+for fmu window_sa, obstacle
+input ports motor_speed
+output ports reaction_torque
+param MAXITER = 100;
+param REL_TOL = 1e-8;
+param ABS_TOL = 1e-8;
+in rules {
+	true -> {
+		height := height; // do_step will always use the last values, local_step does not advance time so will replace the last signal values! therefore, we must set the signal at time t+h of reaction_torque and height. this is done by a very weird statement:
+		reaction_force := 0; // and just initialise other values at time t+h
+		var prev_height; // to compare new value with previous value
+		for (var iter in 0 .. MAXITER) {
+			prev_height := height;
+			local_step(obstacle); // with delayed input for height
+			local_step(window_sa);
+			if (is_close(prev_height, height, REL_TOL, ABS_TOL)) {
+				break;
+			}
+		}
+	} --> { };
+}

+ 26 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/input/window_obstacle_sa_loop_BASE_new.sa

@@ -0,0 +1,26 @@
+semantic adaptation window_obstacle_sa_loop
+for fmu window_sa, obstacle
+input ports motor_speed
+output ports reaction_torque
+param MAXITER = 100;
+param REL_TOL = 1e-8;
+param ABS_TOL = 1e-8;
+control rules {
+	var prev_height;
+	var window_state;
+	var obstacle_state;
+	for (var iter in 0 .. MAXITER) {
+		window_state := get_state(window_sa);
+		obstacle_state := get_state(obstacle);
+		prev_height := height;
+		do_step(obstacle, H); // with delayed input for height
+		do_step(window_sa, H);
+		if (is_close(prev_height, height, REL_TOL, ABS_TOL)) {
+			break;
+		} else {
+			set_state(window_sa, window_state);
+			set_state(obstacle, obstacle_state);
+		}
+	}
+	return H;
+}

+ 16 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/input/window_obstacle_sa_multirate_BASE.sa

@@ -0,0 +1,16 @@
+semantic adaptation window_obstacle_sa_multirate
+for fmu window_obstacle_sa_loop
+input ports motor_speed
+output ports reaction_torque
+param init_motor_speed = 0;
+control rules { multiplied 10 times }
+in var stored_motor_speed := init_motor_speed;
+in var linear_increment;
+in rules {
+	true -> {
+		linear_increment := (motor_speed - stored_motor_speed) / 10;
+		stored_motor_speed := motor_speed;
+	} --> {
+		motor_speed := motor_speed + linear_increment;
+	};
+}

+ 5 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/input/window_sa_BASE.sa

@@ -0,0 +1,5 @@
+semantic adaptation window_sa
+for fmu window
+out rules {
+	true -> { } --> { reaction_torque := -reaction_torque; };
+}

+ 1 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/oracles/test1.txt

@@ -0,0 +1 @@
+Classes encountered: SemanticAdaptation, Definition, NumberLiteral, Evaluation, Multi, FunctionCall, NumberLiteral

+ 57 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/src/be/uantwerpen/ansymo/semanticadaptation/tests/AbstractSemanticAdaptationGeneratorTest.xtend

@@ -0,0 +1,57 @@
+/*
+ * generated by Xtext 2.10.0
+ */
+package be.uantwerpen.ansymo.semanticadaptation.tests
+
+import com.google.inject.Inject
+import org.eclipse.xtext.generator.IGenerator2
+import org.junit.Assert
+import org.eclipse.xtext.generator.InMemoryFileSystemAccess
+import org.eclipse.xtext.generator.IFileSystemAccess
+import be.uantwerpen.ansymo.semanticadaptation.generator.SemanticAdaptationPythonGenerator
+import be.uantwerpen.ansymo.semanticadaptation.semanticAdaptation.SemanticAdaptation
+
+abstract class AbstractSemanticAdaptationGeneratorTest extends AbstractSemanticAdaptationParserTest {
+
+	@Inject IGenerator2 generator
+	
+	InMemoryFileSystemAccess fsa = new InMemoryFileSystemAccess()
+	
+	/**
+	 * Generates an output file in the file system using the DSL's code generation
+	 */
+	def void generateOutputFile(SemanticAdaptation root) {
+		//println(root.statements)
+		//println(root.imports)
+		generator.doGenerate(root.eResource, this.fsa, null)
+	}
+	
+	/**
+	 * Compares the default file in memory to the given oracle file
+	 */
+	def void compareFiles(String oraclefilename) {
+		val inmemoryfilename = IFileSystemAccess::DEFAULT_OUTPUT+SemanticAdaptationPythonGenerator::FILENAME
+		compareFiles(inmemoryfilename, oraclefilename)
+	}
+	
+	/**
+	 * Compares a given file in memory to the given oracle file
+	 */
+	def void compareFiles(String inmemoryfilename, String oraclefilename) {
+		//println(this.fsa.allFiles)
+		Assert.assertTrue(inmemoryfilename + " not found", this.fsa.allFiles.containsKey(inmemoryfilename))
+		val actualtext = fsa.allFiles.get(inmemoryfilename)
+		val expectedtext = readFile('oracles/'+oraclefilename)
+		Assert.assertEquals(expectedtext, actualtext)
+	}
+	
+	/**
+	 * Parses a given input file, generates code, and compares this to the given oracle file
+	 */
+	def void parseAndGenerateAndCompare(String inputfilename, String oraclefilename) {
+		val root = parseInputFile(inputfilename)
+		generateOutputFile(root)
+		compareFiles(oraclefilename)
+	}
+
+}

+ 26 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/src/be/uantwerpen/ansymo/semanticadaptation/tests/AbstractSemanticAdaptationParserTest.xtend

@@ -0,0 +1,26 @@
+/*
+ * generated by Xtext 2.10.0
+ */
+package be.uantwerpen.ansymo.semanticadaptation.tests
+
+import be.uantwerpen.ansymo.semanticadaptation.semanticAdaptation.SemanticAdaptation
+import com.google.inject.Inject
+import org.eclipse.xtext.junit4.InjectWith
+import org.eclipse.xtext.junit4.XtextRunner
+import org.eclipse.xtext.junit4.util.ParseHelper
+import org.junit.runner.RunWith
+
+@RunWith(XtextRunner)
+@InjectWith(SemanticAdaptationInjectorProvider)
+abstract class AbstractSemanticAdaptationParserTest extends AbstractSemanticAdaptationTest {
+
+	@Inject extension ParseHelper<SemanticAdaptation>
+	
+	/**
+	 * parses from an input file
+	 */
+	def SemanticAdaptation parseInputFile(String filename) {
+		return readFile('input/'+filename).parse()
+	}
+
+}

+ 120 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/src/be/uantwerpen/ansymo/semanticadaptation/tests/AbstractSemanticAdaptationTest.xtend

@@ -0,0 +1,120 @@
+/*
+ * generated by Xtext 2.10.0
+ */
+package be.uantwerpen.ansymo.semanticadaptation.tests
+
+import org.eclipse.xtext.junit4.InjectWith
+import org.eclipse.xtext.junit4.XtextRunner
+import org.junit.runner.RunWith
+import java.io.FileReader
+import static extension com.google.common.io.CharStreams.*
+import java.util.ArrayList
+import org.eclipse.emf.ecore.EObject
+import org.eclipse.emf.common.util.BasicEList
+import org.eclipse.emf.ecore.util.EDataTypeEList
+import org.eclipse.emf.ecore.util.EObjectEList
+import org.eclipse.emf.common.util.EList
+import org.eclipse.xtext.generator.InMemoryFileSystemAccess
+import javax.inject.Inject
+import java.io.File
+import org.eclipse.emf.ecore.resource.ResourceSet
+
+@RunWith(XtextRunner)
+@InjectWith(SemanticAdaptationInjectorProvider)
+abstract class AbstractSemanticAdaptationTest {
+	
+	ArrayList<Integer> visited = new ArrayList<Integer>
+	
+	/*@Inject
+    private InMemoryFileSystemAccess fsa
+	
+	def __setUp(File dir) {
+		for (File f : dir.listFiles()) {
+			if (f.name.endsWith(".sa") && !fsa.isFile(f.name)) {
+				//println("adding " + f.name)
+				fsa.generateFile(f.name, new FileReader(f).readLines.join("\n"))
+			}
+		}
+		//println(fsa.allFiles.keySet)
+	}*/
+	
+	/**
+	 * reads a file from the permanent file system
+	 */
+	def String readFile(String basefilename) {
+		val f = new File(basefilename)
+		//println("testing " + f.name)
+		//__setUp(f.parentFile)
+		//return fsa.readTextFile(f.name).toString()
+		return new FileReader(f).readLines.join("\n")
+	}
+	
+	def print_ast(EObject root) {
+		visited.clear
+		println(root.eClass.name)
+		print_ast_element(root, 0)
+	}
+	
+	private def void print_ast_element(EObject element, int indent) {
+		if (visited.contains(element.hashCode)) {
+			return
+		}
+		visited.add(element.hashCode)
+		element.eClass.EAllStructuralFeatures.forEach[f | 
+			val feature = element.eGet(f)
+			if (feature != null) {
+				if (feature instanceof EList<?>) {
+					(feature as EObjectEList<?>).forEach[e | 
+						print(ind(indent+1) + f.name + "(" + feature.indexOf(e) + "): ")
+						//println("List<" + f.EType.name + ">")
+						if (feature instanceof EObjectEList<?>) {
+							print((e as EObject).class.simpleName.substring(0, (e as EObject).class.simpleName.length-4))
+							printObject((e as EObject), indent+1)
+						} else if (feature instanceof EDataTypeEList<?>) { // in case of enums
+							println(e.class.simpleName + " = " + e)
+						} else if (feature instanceof BasicEList<?>) {
+							throw new Exception(f.name + " other type of list: " + feature.class.name)
+						}
+					]
+				} else {
+					print(ind(indent+1) + f.name + ": ")
+					if (feature instanceof EObject) {
+						print(feature.class.simpleName.substring(0, feature.class.simpleName.length-4))
+						printObject((feature as EObject), indent+1)
+					} else if (feature instanceof String) {
+						println(feature.class.simpleName + " = '" + feature + "'")
+					} else {
+						println(feature.class.simpleName + " = " + feature)
+					}
+				}
+			} else { // filter out null values
+				print(ind(indent+1) + f.name + ": ")
+				println("null")
+			}
+		]
+		return
+	}
+	
+	private def void printObject(EObject element, int indent) {
+		if (visited.contains(element.hashCode)) {
+			val namelist = element.eClass.EAllStructuralFeatures.filter(e | e.name.equals("name"))
+			if (namelist.length == 0) {
+				throw new Exception("Reference " + element + " does not have a 'name' attribute")
+			}
+			println(" -> " + element.eGet(element.eClass.EAllStructuralFeatures.filter(e | e.name.equals("name")).get(0)))
+		} else {
+			println()
+			print_ast_element(element, indent)
+		}
+		return
+	}
+	
+	private def ind(int indent) {
+		var s = ""
+		for (var i = 0 ; i < indent ; i++) {
+			s += "|   "
+		}
+		return s
+	}
+
+}

+ 36 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/src/be/uantwerpen/ansymo/semanticadaptation/tests/SemanticAdaptationGeneratorTest.xtend

@@ -0,0 +1,36 @@
+/*
+ * generated by Xtext 2.10.0
+ */
+package be.uantwerpen.ansymo.semanticadaptation.tests
+
+import org.junit.Test
+import org.eclipse.xtext.xbase.compiler.CompilationTestHelper
+import com.google.inject.Inject
+import org.junit.runner.RunWith
+import org.eclipse.xtext.junit4.InjectWith
+import org.eclipse.xtext.junit4.XtextRunner
+import java.io.File
+
+@RunWith(XtextRunner)
+@InjectWith(SemanticAdaptationInjectorProvider)
+class SemanticAdaptationGeneratorTest extends AbstractSemanticAdaptationTest{
+	
+	@Inject extension CompilationTestHelper
+	
+	//@Test def powerwindow_model_only() { __generate('input/powerwindow_model_only.sa') }
+	@Test def powerwindow_algebraic_loop_delay_BASE() { __generate('input/powerwindow_algebraic_loop_delay_BASE.sa') }
+	//@Test def powerwindow_algebraic_loop_delay() { __generate('input/powerwindow_algebraic_loop_delay.sa') }
+	@Test def powerwindow_algebraic_loop_iteration_BASE() { __generate('input/powerwindow_algebraic_loop_iteration_BASE.sa') }
+	//@Test def powerwindow_algebraic_loop_iteration() { __generate('input/powerwindow_algebraic_loop_iteration.sa') }
+	//@Test def powerwindow_controller_delay() { __generate('input/powerwindow_controller_delay.sa') }
+	@Test def powerwindow_controller_delay_BASE() { __generate('input/powerwindow_controller_delay_BASE.sa') }
+	//@Test def powerwindow_multi_rate() { __generate('input/powerwindow_multi_rate.sa') }
+	@Test def powerwindow_multi_rate_BASE() { __generate('input/powerwindow_multi_rate_BASE.sa') }
+	//@Test def powerwindow() { __generate('input/powerwindow.sa') }
+	
+	def void __generate(String filename) {
+		val f = new File(filename)
+		readFile(filename).assertCompilesTo('oracles/test1.txt'/*readFile('oracles/' + f.name)*/)
+	}
+
+}

+ 97 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation.tests/src/be/uantwerpen/ansymo/semanticadaptation/tests/SemanticAdaptationParsingTest.xtend

@@ -0,0 +1,97 @@
+/*
+ * generated by Xtext 2.10.0
+ */
+package be.uantwerpen.ansymo.semanticadaptation.tests
+
+import org.eclipse.xtext.junit4.InjectWith
+import org.eclipse.xtext.junit4.XtextRunner
+import org.junit.Assert
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.eclipse.xtext.junit4.util.ParseHelper
+import com.google.inject.Inject
+import org.eclipse.xtext.junit4.validation.ValidationTestHelper
+import be.uantwerpen.ansymo.semanticadaptation.semanticAdaptation.*
+import org.eclipse.emf.ecore.EObject
+import java.util.regex.Pattern
+
+@RunWith(XtextRunner)
+@InjectWith(SemanticAdaptationInjectorProvider)
+class SemanticAdaptationParsingTest extends AbstractSemanticAdaptationTest{
+	
+	@Inject extension ParseHelper<SemanticAdaptation>
+	@Inject extension ValidationTestHelper
+
+//	@Test 
+//	def void loadModule() {
+//		//val root = this.parseInputFile('test1.sa')
+//		val root = readFile('input/test1.sa').parse
+//		root.assertNoErrors
+//		Assert.assertNotNull(root.adaptations.get(0))
+//		Assert.assertNotNull(root.adaptations.get(0).extractsensitivity)
+//		Assert.assertTrue(root.adaptations.get(0).extractsensitivity.length > 0)
+//		Assert.assertTrue(root.adaptations.get(0).inports.length > 0)
+//		Assert.assertEquals(root.adaptations.get(0).inports.get(0).name, 'x')
+//		print_ast(root)
+//	}
+
+	@Test def powerwindow_model_only() { __parseNoErrors('input/powerwindow_model_only.sa') }
+	@Test def powerwindow_algebraic_loop_delay_BASE() { __parseNoErrors('input/powerwindow_algebraic_loop_delay_BASE.sa') }
+	@Test def powerwindow_algebraic_loop_delay() { __parseNoErrors('input/powerwindow_algebraic_loop_delay.sa') }
+	@Test def powerwindow_algebraic_loop_iteration_BASE() { __parseNoErrors('input/powerwindow_algebraic_loop_iteration_BASE.sa') }
+	@Test def powerwindow_algebraic_loop_iteration() { __parseNoErrors('input/powerwindow_algebraic_loop_iteration.sa') }
+	@Test def powerwindow_controller_delay() { __parseNoErrors('input/powerwindow_controller_delay.sa') }
+	@Test def powerwindow_controller_delay_BASE() { __parseNoErrors('input/powerwindow_controller_delay_BASE.sa') }
+	@Test def powerwindow_multi_rate() { __parseNoErrors('input/powerwindow_multi_rate.sa') }
+	@Test def powerwindow_multi_rate_BASE() { __parseNoErrors('input/powerwindow_multi_rate_BASE.sa') }
+	@Test def powerwindow() { __parseNoErrors('input/powerwindow.sa') }
+	
+	def __parseNoErrors(String filename) {
+		val root = __parse(filename)
+		__assertNoParseErrors(root, filename)
+	}
+	
+	def __parseNoErrorsPrint(String filename) {
+		val root = __parse(filename)
+		print_ast(root)
+		__assertNoParseErrors(root, filename)
+	}
+	
+	def __parse(String filename) {
+		val model = readFile('input/powerwindow_controller_delay.sa').parse
+		val controller = readFile('input/powerwindow_model_only.sa').parse(model.eResource.resourceSet)
+		val algebraicloop = readFile('input/powerwindow_algebraic_loop_delay.sa').parse(controller.eResource.resourceSet)
+		return readFile(filename).parse(algebraicloop.eResource.resourceSet)
+	}
+	
+	def __assertNoParseErrors(EObject root, String filename) {
+		try {
+			root.assertNoErrors
+		} catch (AssertionError e) {
+			val p = Pattern.compile(".*, offset (?<offset>[0-9]+), length (?<length>[0-9]+)")
+			val code = readFile(filename)
+			for (String line : e.message.split("\n")) {
+				val m = p.matcher(line)
+				m.matches()
+				val count = __occurrencesInString(code.subSequence(0, Integer.valueOf(m.group("offset"))).toString(), "\n")
+				print(filename + " at line " + (count+1) + ": ")
+				println(line)
+			}
+			throw e
+		}
+	}
+	
+	def __occurrencesInString(String str, String findstr) {
+		var lastIndex = 0
+		var count = 0
+		while (lastIndex != -1) {
+			lastIndex = str.indexOf(findstr,lastIndex)
+			if (lastIndex != -1) {
+		        count ++
+		        lastIndex += findstr.length()
+		    }
+		}
+		return count
+	}
+
+}

+ 9 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/.classpath

@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+	<classpathentry kind="src" path="src"/>
+	<classpathentry kind="src" path="src-gen"/>
+	<classpathentry kind="src" path="xtend-gen"/>
+	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
+	<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+	<classpathentry kind="output" path="bin"/>
+</classpath>

+ 34 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/.project

@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+	<name>be.uantwerpen.ansymo.semanticadaptation</name>
+	<comment></comment>
+	<projects>
+	</projects>
+	<buildSpec>
+		<buildCommand>
+			<name>org.eclipse.xtext.ui.shared.xtextBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>org.eclipse.jdt.core.javabuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>org.eclipse.pde.ManifestBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>org.eclipse.pde.SchemaBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+	</buildSpec>
+	<natures>
+		<nature>org.eclipse.xtext.ui.shared.xtextNature</nature>
+		<nature>org.eclipse.jdt.core.javanature</nature>
+		<nature>org.eclipse.pde.PluginNature</nature>
+	</natures>
+</projectDescription>

+ 2 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/.settings/org.eclipse.core.resources.prefs

@@ -0,0 +1,2 @@
+eclipse.preferences.version=1
+encoding/<project>=windows-1252

+ 7 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/.settings/org.eclipse.jdt.core.prefs

@@ -0,0 +1,7 @@
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
+org.eclipse.jdt.core.compiler.compliance=1.8
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.source=1.8

+ 29 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/META-INF/MANIFEST.MF

@@ -0,0 +1,29 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: be.uantwerpen.ansymo.semanticadaptation
+Bundle-Vendor: University of Antwerp, Ansymo Lab
+Bundle-Version: 1.0.0.qualifier
+Bundle-SymbolicName: be.uantwerpen.ansymo.semanticadaptation; singleton:=true
+Bundle-ActivationPolicy: lazy
+Require-Bundle: org.eclipse.xtext,
+ org.eclipse.xtext.xbase,
+ org.eclipse.equinox.common;bundle-version="3.5.0",
+ org.eclipse.emf.ecore,
+ org.eclipse.xtext.xbase.lib,
+ org.antlr.runtime,
+ org.eclipse.xtext.util,
+ org.eclipse.xtend.lib,
+ org.eclipse.emf.common
+Bundle-RequiredExecutionEnvironment: JavaSE-1.8
+Export-Package: be.uantwerpen.ansymo.semanticadaptation.semanticAdaptation.util,
+ be.uantwerpen.ansymo.semanticadaptation.services,
+ be.uantwerpen.ansymo.semanticadaptation.scoping,
+ be.uantwerpen.ansymo.semanticadaptation,
+ be.uantwerpen.ansymo.semanticadaptation.semanticAdaptation.impl,
+ be.uantwerpen.ansymo.semanticadaptation.semanticAdaptation,
+ be.uantwerpen.ansymo.semanticadaptation.parser.antlr.internal,
+ be.uantwerpen.ansymo.semanticadaptation.serializer,
+ be.uantwerpen.ansymo.semanticadaptation.validation,
+ be.uantwerpen.ansymo.semanticadaptation.parser.antlr,
+ be.uantwerpen.ansymo.semanticadaptation.generator
+Import-Package: org.apache.log4j

+ 18 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/build.properties

@@ -0,0 +1,18 @@
+source.. = src/,\
+           src-gen/,\
+           xtend-gen/
+bin.includes = model/generated/,\
+               .,\
+               META-INF/,\
+               plugin.xml
+additional.bundles = org.eclipse.xtext.xbase,\
+                     org.eclipse.xtext.common.types,\
+                     org.eclipse.xtext.xtext.generator,\
+                     org.eclipse.emf.codegen.ecore,\
+                     org.eclipse.emf.mwe.utils,\
+                     org.eclipse.emf.mwe2.launch,\
+                     org.eclipse.emf.mwe2.lib,\
+                     org.objectweb.asm,\
+                     org.apache.commons.logging,\
+                     org.apache.log4j,\
+                     com.ibm.icu

+ 10 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/plugin.xml

@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="windows-1252"?>
+<?eclipse version="3.0"?>
+<plugin>
+	<extension point="org.eclipse.emf.ecore.generated_package">
+		<package 
+			uri = "http://www.uantwerpen.be/ansymo/semanticadaptation/SemanticAdaptation"
+			class = "be.uantwerpen.ansymo.semanticadaptation.semanticAdaptation.SemanticAdaptationPackage"
+			genModel = "model/generated/SemanticAdaptation.genmodel" />
+	</extension>
+</plugin>

+ 10 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/plugin.xml_gen

@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse version="3.0"?>
+<plugin>
+	<extension point="org.eclipse.emf.ecore.generated_package">
+		<package 
+			uri = "http://www.uantwerpen.be/ansymo/semanticadaptation/SemanticAdaptation"
+			class = "be.uantwerpen.ansymo.semanticadaptation.semanticAdaptation.SemanticAdaptationPackage"
+			genModel = "model/generated/SemanticAdaptation.genmodel" />
+	</extension>
+</plugin>

+ 43 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/src/be/uantwerpen/ansymo/semanticadaptation/GenerateSemanticAdaptation.mwe2

@@ -0,0 +1,43 @@
+module be.uantwerpen.ansymo.semanticadaptation.GenerateSemanticAdaptation
+
+import org.eclipse.xtext.xtext.generator.*
+import org.eclipse.xtext.xtext.generator.model.project.*
+
+var rootPath = ".."
+
+Workflow {
+	
+	component = XtextGenerator {
+		configuration = {
+			project = StandardProjectConfig {
+				baseName = "be.uantwerpen.ansymo.semanticadaptation"
+				rootPath = rootPath
+				runtimeTest = {
+					enabled = true
+				}
+				eclipsePlugin = {
+					enabled = true
+				}
+				eclipsePluginTest = {
+					enabled = true
+				}
+				createEclipseMetaData = true
+			}
+			code = {
+				encoding = "UTF-8"
+				fileHeader = "/*\n * generated by Xtext \${version}\n */"
+			}
+		}
+		language = StandardLanguage {
+			name = "be.uantwerpen.ansymo.semanticadaptation.SemanticAdaptation"
+			fileExtensions = "sa"
+
+			serializer = {
+				generateStub = false
+			}
+			validator = {
+				// composedCheck = "org.eclipse.xtext.validation.NamesAreUniqueValidator"
+			}
+		}
+	}
+}

+ 375 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/src/be/uantwerpen/ansymo/semanticadaptation/SemanticAdaptation.xtext

@@ -0,0 +1,375 @@
+grammar be.uantwerpen.ansymo.semanticadaptation.SemanticAdaptation with org.eclipse.xtext.common.Terminals
+
+import "http://www.eclipse.org/emf/2002/Ecore" as ecore
+generate semanticAdaptation "http://www.uantwerpen.be/ansymo/semanticadaptation/SemanticAdaptation"
+
+SemanticAdaptation:
+	(imports+=Import)*
+	('module' name=ID)?
+	(elements+=Component)*;
+
+Import:
+	'import' module=[SemanticAdaptation];
+	
+Component:
+	FMU | Connection;
+
+Connection:
+	src=[SpecifiedPort] '->' tgt=[SpecifiedPort];
+
+FMU:
+	AtomicFMU | CompositeFMU | Adaptation;
+
+AtomicFMU:
+	'fmu' name=ID
+	('type' type=ModelType)?
+	('input' 'ports' inports+=Port ("," inports+=Port)*)?
+	('output' 'ports' outports+=Port ("," outports+=Port)* )?
+	('full' 'internal' 'dependencies')?
+	;
+
+CompositeFMU:
+	'fmu' name=ID
+	'composed' 'of' instances+=[FMU] (',' instances+=[FMU])*
+	('input' 'ports' inports+=Port ("," inports+=Port)*)?
+	('output' 'ports' outports+=Port ("," outports+=Port)* )?;
+
+Adaptation:
+	({Adaptation} 'semantic' 'adaptation' name=ID | 
+	{AdaptationWithSpecificMaster} 'semantic' 'adaptation' name=ID 'without' 'master')
+	/*'for' type=ModelType*/ ('for' ('fmu' instances+=[FMU] (',' instances+=[FMU])* /*| 'signal' ports+=[SpecifiedPort] (',' ports+=[SpecifiedPort])**/) )? // only multiple instances in case of CT because we only have CT master?
+	('input' 'ports' inports+=Port ("," inports+=Port)*)? // only in case of instance-specific SA
+	('output' 'ports' outports+=Port ("," outports+=Port)* )? // only in case of instance-specific SA
+	('param' params+=ParamDeclaration)*
+//	(globalvars+=Declaration)*
+	// algebraic loop generates an FMU encapsulating the loop
+	// note that the order of semantic adaptations is prefixed in case of a algebraic loop:
+	// adaptations on internal signals of the loop are inner most, then the algebraic loop iteration, then adaptations on external signals
+	(generalrules+=GeneraleRule)*
+	(control=ControlRuleBlock)?
+	(in=InRulesBlock)?
+	(out=OutRulesBlock)?
+//	('contains' '{' adaptations+=Adaptation+ '}')? // I prefer no structural information here, this belongs to a graphical model
+	;
+	
+ModelType: DE | UT | CT | DT;
+	
+DE: 'DE' | 'de' | 'DiscreteEvent' | 'Discrete' 'Event' | 'discrete' 'event';
+UT: 'UT' | 'ut' | 'Untimed' | 'untimed';
+CT: 'CT' | 'ct' | 'ContinuousTime' | 'Continuous' 'Time' | 'continuous' 'time';
+DT: 'DT' | 'dt' | 'DiscreteTime' | 'Discrete' 'Time' | 'discrete' 'time';
+
+GeneraleRule:
+	AlgebraicLoopSolution | MultiRate | Derivative;
+
+AlgebraicLoopSolution:
+	{AlgebraicLoopSolutionFixPointIteration} 'successive' 'substitution' 'starts' 'at' signals+=[SpecifiedPort] (('and'|',') signals+=[SpecifiedPort])? 'with' params+=SettingAssignment ('and' params+=SettingAssignment)* | 
+	{AlgebraicLoopSolutionDelayIntroduction} 'delay' 'at' signals+=[SpecifiedPort] (('and'|',') signals+=[SpecifiedPort])?; // TODO: must be in in or out rule
+	
+MultiRate:
+	'multiply' 'rate' rate=INT 'times' ('with' interpolation=Interpolation)?; // default first order interpolation
+
+Interpolation:
+	({ZeroOrderInterpolation} 'no' | {FirstOrderInterpolation} 'first' 'order' | {SecondOrderInterpolation} 'second' 'order' | {ThirdOrderInterpolation} 'third' 'order' | {FourthOrderInterpolation} 'fourth' 'order') 'interpolation' | // automatically does lower order interpolation in the beginning of simulation when no previous signal values are available
+	{CustomOrderInterpolation} 'interpolation' 'of' 'order' order=INT | 
+	{CustomInterpolation} 'interpolation' function=AnonymousFunction;
+	
+Derivative:
+	{PredefinedDerivative} 'with' (directionalderivative?='directionalderivative'? & timederivative?='timederivative'?) |
+	{DefinedDerivative} 'extract' (extractdirectionalderivative?='directionalderivative'? & // decide sensitivity
+				extracttimederivative?='timederivative'? & // decide sensitivity
+				extractsensitivity+=AnonymousFunction* );  // new sensitivity definitions
+
+InOutRules:
+	InRulesBlock | OutRulesBlock;
+
+InRulesBlock:
+	{InRulesBlock} ('in' globalvars+=Declaration)* 'in' 'rules' ('with' setting+=GeneralSetting (',' setting+=GeneralSetting)*)? '{' iterationvars+=Declaration* rules+=DataRule* '}';
+
+OutRulesBlock:
+	{OutRulesBlock} ('out' globalvars+=Declaration)* 'out' 'rules' ('with' setting+=GeneralSetting (',' setting+=GeneralSetting)*)? '{' iterationvars+=Declaration* rules+=DataRule* '}';
+
+ControlRuleBlock:
+	/*('control' globalvars+=Declaration)**/ ControlRule; // TODO: multiple rules or just one?
+
+DataRule: // condition -> state transition --> output function
+	(((condition=RuleCondition "->" statetransitionfunction=StateTransitionFunction) | ConditionStateTransition | ConditionLessRule) ("-->" outputfunction=OutputFunction)? | AlgebraicLoopSolution) ';';
+
+GeneralSetting:
+	{GeneralVariableSetting} strategy=RuleStrategy params+=SettingAssignment ('and' params+=SettingAssignment)* | 
+	OutputFunction;
+	
+SettingAssignment:
+	setting=RuleSetting '=' expr=Expression;
+	
+RuleCondition:
+	{RuleCondition} condition=Expression (params+=SettingAssignment ('and' params+=SettingAssignment)*)? | 
+	{CompositeRuleCondition} '{' statements+=Statement* returnstatement=ReturnStatement '}';
+
+RuleSetting:
+	{AbsoluteTolerance} 'absolute' 'tolerance' | // todo relative/absolute tolerance (look up float equality)
+	{RelativeTolerance} 'relative' 'tolerance'; // todo relative/absolute tolerance (look up float equality)
+	// otherwise null
+	
+RuleStrategy:
+	{Crossing} 'crossing';
+	
+StateTransitionFunction:
+	{StateTransitionFunction} expression=Expression |
+	{StateTransitionFunction} '{' statements+=Statement* '}' |
+	{StateTransitionFunction} assignment=Assignment;// |
+	//{StoreNull} ('null' | 'nothing') |
+	//{StateTransitionFunction} 'todo';
+
+ConditionLessRule:
+	assignment=Assignment;
+
+ConditionStateTransition:
+	quantization=Quantize;
+
+Quantize returns ConditionStoreStrategy:
+	{FiniteQuantize} 'quantize' '(' signal=[SpecifiedPort] ',' zones+=StringLiteral (',' boundaries+=ArithmeticExpression ',' zones+=StringLiteral)* ')' |
+	{FunctionQuantize} 'quantize' '(' signal=[SpecifiedPort] ',' '=' function=ArithmeticExpression ')' |
+	{LinearQuantize} 'quantize' signal=[SpecifiedPort] 'every' steps=ArithmeticExpression ('with'? 'offset' offset=ArithmeticExpression)?;
+	
+OutputFunction:
+	{NoHold} 'no' 'hold' |
+	{ZeroOrderHold} (('zero' 'order' 'hold') | 'ZOH') |
+	{FirstOrderHold} (('first' 'order' 'hold') | 'FOH') |
+	{CustomOutputFunction} expr=Expression |
+	{CompositeOutputFunction} '{' statements+=Statement* (returnstatement=ReturnStatement)? '}';
+	
+ControlRule:
+	{ImpliedControlRule} 'implied' | // the default
+	{TriggeredControlRule} 'triggered' 'by' condition=Expression |
+	{PeriodicControlRule} 'periodic' ('at' init_time=REALTYPE)? 'every' period=REALTYPE | 
+	{MultipliedControlRule} 'multiplied' multiplication=INT 'times' | 
+	{CustomControlRule} 'control' '{' ControlRulestatements+=Statement* returnstatement=ReturnStatement '}'; // TODO: how do we know if control is given?
+
+AnonymousFunction: // has access to ports
+	{FunctionExpression} '{=' code=Expression '}'| 
+	{FunctionBody} '{' statements+=Statement* returnstatement=ReturnStatement '}' |  // should return something
+	FunctionDeclaration; // TODO: should return something
+	
+/*[SpecifiedPort]: // if ports need owners
+	port=[Port] |
+	{Output[SpecifiedPort]} owner=[FMU] '.' port=[Port] | 
+	{Input[SpecifiedPort]} owner=[FMU] '<-' port=[Port];*/
+SpecifiedPort: Port;
+
+Port:
+	// TODO: add initial values to ports (to do 1st, 2nd, ... order stuff)
+	// TODO: add internal destination/source of port
+	// Unity conversions: https://pint.readthedocs.io/en/0.7.2/
+	name=ID (':=' initval=LiteralOrArray)? ( multiplicity=Multiplicity )? ( '(' unity=Unity ')' )? ('->' target=[SpecifiedPort] | '-->' dependency+=[SpecifiedPort] (dependency+=[SpecifiedPort])*)?;
+	// TODO: -> output port of wrapped FMU to output port of SA FMU (only used in SA!)
+
+Multiplicity:
+	'[' (lower=INT '..')? upper=INT ']';
+
+Unity:
+	DivideUnity;
+	
+DivideUnity returns Unity:
+	MultiplyUnity (({DivideUnity.left=current} '/') right=MultiplyUnity)*;
+
+MultiplyUnity returns Unity:
+	AtomicUnity (({MultiplyUnity.left=current} '.') right=AtomicUnity)*;
+
+AtomicUnity:
+	name=ID ('^' (power=INT | power=INTTYPE))?; // somehow LETTERS as name does not work, so power will never be parsed...
+
+//FunctionBody:
+//	statements+=Statement* returnstatement=ReturnStatement;
+	
+Statement:
+	NestableStatement | FunctionDeclaration;
+
+NestableStatement:
+	Declaration | (Assignment  ';') | (Procedure  ';') | For | If | BreakStatement;
+	
+For:
+	'for' '(' 'var' iterator=DeclaredParameter 'in' iterable=Range ')' '{' (statements+=NestableStatement)* '}';
+	
+If:
+	'if' '(' ifcondition=Expression ')' '{' (ifstatements+=NestableStatement)* '}' ('else' '{' (elsestatements+=NestableStatement)* '}')?;
+	
+FunctionDeclaration:
+	'def' name=ID ('(' args+=DeclaredParameter (',' args+=DeclaredParameter)* ')')? 
+	'{' statements+=Statement* returnstatement=ReturnStatement '}';
+
+Declaration:
+	'var' name=ID (':=' expr=Expression)? ';';
+
+ParamDeclaration:
+	name=ID '=' expr=Expression ';';
+
+ReturnStatement:
+	'return' Expression ';';
+
+BreakStatement:
+	{BreakStatement} 'break' ';';
+
+DeclaredParameter:
+	name=ID;
+	
+AbstractDeclaration: // can contain overlapping elements as long as it is only used as reference
+	Port | ParamDeclaration | Declaration | DeclaredParameter | FunctionDeclaration;
+
+LValueDeclaration: // can contain overlapping elements as long as it is only used as reference
+	Port | ParamDeclaration | Declaration | DeclaredParameter; // TODO: fmu.port
+
+Assignment:
+	lvalue=Variable ':=' expr=Expression; // TODO: to what can be assigned? only local vars?
+
+Expression:
+	OrExpression;
+
+OrExpression returns Expression:
+	AndExpression ({Or.left=current} 'or' right=AndExpression)*;
+
+AndExpression returns Expression:
+	NotExpression ({And.left=current} 'and' right=NotExpression)*;
+	
+NotExpression returns Expression:
+	{Not} 'not' left=GreaterThanExpression | 
+	GreaterThanExpression;
+	
+GreaterThanExpression returns Expression:
+	LessThanExpression ({GreaterThan.left=current} '>' right=ArithmeticExpression)?;
+	
+LessThanExpression returns Expression:
+	GreaterThanOrEqualsExpression ({LessThan.left=current} '<' right=ArithmeticExpression)?;
+
+GreaterThanOrEqualsExpression returns Expression:
+	LessThanOrEqualsExpression ({GreaterThanOrEquals.left=current} '>=' right=ArithmeticExpression)?;
+	
+LessThanOrEqualsExpression returns Expression:
+	EqualsExpression ({LessThanOrEquals.left=current} '<=' right=ArithmeticExpression)?;
+
+EqualsExpression returns Expression:
+	NotEqualsExpression ({Equals.left=current} '==' right=ArithmeticExpression)?;
+	
+NotEqualsExpression returns Expression:
+	CrossesFromBelowExpression ({NotEquals.left=current} '!=' right=ArithmeticExpression)?;
+		
+CrossesFromBelowExpression returns Expression:
+	CrossesFromAboveExpression ({CrossesFromBelow.left=current} '>!' right=ArithmeticExpression)?;
+	
+CrossesFromAboveExpression returns Expression:
+	BooleanFunction ({CrossesFromAbove.left=current} '<!' right=BooleanFunction)?;
+	
+BooleanFunction returns Expression:
+	{Otherwise} 'otherwise' '(' ref=[SpecifiedPort] ')' |
+	{Otherwise} 'otherwise' ref=[SpecifiedPort] |
+	ArithmeticExpression;
+
+ArithmeticExpression returns Expression:
+	Addition;
+
+Addition returns Expression:
+	Multiplication (({Plus.left=current} '+' | {Minus.left=current} '-') right=Multiplication)*;
+
+Multiplication returns Expression:
+	Range (({Multi.left=current} '*' | {Div.left=current} '/') right=Range)*;
+
+Range returns Expression:
+	UnaryOrPrimaryExpression ({Range.left=current} '..' right=UnaryOrPrimaryExpression)?;
+
+UnaryOrPrimaryExpression returns Expression:
+	NegationExpression | PrimaryExpression;
+	
+NegationExpression returns Expression:
+	{Neg} '-' right=PrimaryExpression;
+
+PrimaryExpression returns Expression:
+	'(' Expression ')' | Literal | BuiltinFunction | Var;
+
+LiteralOrArray:
+	{ArrayLiteral} '[' elements+=Literal (',' elements+=Literal)* ']' |
+	Literal;
+
+Literal:
+	IntLiteral | RealLiteral | StringLiteral | BoolLiteral | NullLiteral; //| StepLiteral;
+
+IntLiteral:
+	value=INTTYPE | value=INT;
+	
+RealLiteral:
+	value=REALTYPE;
+	
+StringLiteral:
+	value=STRING;
+	
+BoolLiteral:
+	value=('true'|'false');
+	
+//StepLiteral:
+//	value=('accept'|'discard');
+	
+NullLiteral:
+	value='null';
+	
+BuiltinFunction:
+	{Floor} name='floor' '(' args+=ArithmeticExpression ')' | 
+	{Ceil} name='ceil' '(' args+=ArithmeticExpression ')' | 
+	{Round} name='round' '(' args+=ArithmeticExpression (',' args+=ArithmeticExpression)? ')' |
+	{Max} name='max' '(' args+=ArithmeticExpression ',' args+=ArithmeticExpression ')' |
+	{Min} name='min' '(' args+=ArithmeticExpression ',' args+=ArithmeticExpression ')' |
+	{Abs} name='abs' '(' args=ArithmeticExpression ')' |
+	{Close} name='is_close' '(' args+=ArithmeticExpression ',' args+=ArithmeticExpression ',' args+=ArithmeticExpression ',' args+=ArithmeticExpression ')' |  // a, b, relative tolerance, absolute tolerance 
+	{IsSet} name='is_set' '(' args=Variable ')' | 
+	{DoStepFun} name='do_step' '(' fmu=[FMU] ',' H=ArithmeticExpression ')' |
+	{GetState} name='get_state' '(' fmu=[FMU] ')' |
+	{GetNextInternalTimeStep} name='get_next_time_step' '(' fmu=[FMU] ')' | // is actually the time step returned by do_step(fmu), preceded by get_state and succeeded by set_state
+	{Elapsed} name='elapsed' '(' fmu=[FMU] ')';
+	
+Procedure:
+	{Reject} name='reject' |
+	{Step} name='local_step' '(' fmu=[FMU] ')' |
+	{Discard} name='discard' '(' args=Variable ')' |
+	{DoStep} name='do_step' '(' fmu=[FMU] ',' H=ArithmeticExpression ')' |
+	{SetState} name='set_state' '(' fmu=[FMU] ',' state=Var ')'; // arg: new proposed step size
+	
+Var:
+	{StepSize} name='H' | 
+	{CurrentTime} name='t' |
+	{ElapsedTime} name='e' | // min (elapsed(fmu1), elapsed(fmu2), ...)
+	{Max} name='MAX' |
+	{GenericSignal} name='signal' ('[' (
+		index=NOW | 
+		index=PREV | 
+		index=INTTYPE |
+		index=INT // TODO: int must be less than -1, TODO: expression
+		) ']')? |
+	Variable |
+	FunctionCall; // add "directionalderivative"
+	
+Variable:
+	ref=[LValueDeclaration] ('[' (
+		index=NOW | 
+		index=PREV | 
+		index=INTTYPE |
+		index=INT  // TODO: int must be less than -1, TODO: expression
+		) ']')?; // TODO: NO RECURSION (must terminate)
+
+FunctionCall:
+	ref=[FunctionDeclaration] '(' args+=ArithmeticExpression (',' args+=ArithmeticExpression)* ')'; // TODO: NO RECURSION (must terminate)
+
+//SignedInt returns ecore::EInt:
+//	('-'|'+')? INT;
+
+//SignedReal returns ecore::EBigDecimal:
+//	'-'? REAL;
+
+terminal INTTYPE returns ecore::EInt : '-' INT;
+	
+terminal REALTYPE returns ecore::EFloat : '-'? ((( INT '.' INT | '.' INT | INT '.') (('e'|'E') ('-'|'+') INT)?) | (INT ('e'|'E') ('-'|'+') INT));
+//terminal UNSREALTYPE returns ecore::EFloat : ((( INT '.' INT | '.' INT | INT '.') (('e'|'E') ('-'|'+') INT)?) | (INT ('e'|'E') ('-'|'+') INT));
+	
+terminal NOW returns ecore::EInt: 'now';
+terminal PREV returns ecore::EInt: 'prev';
+	
+//terminal REAL returns ecore::EBigDecimal: INT? '.' INT;
+
+//terminal LETTERS returns ecore::EString: ('a'..'z' | 'A'..'Z')+;

+ 24 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/src/be/uantwerpen/ansymo/semanticadaptation/SemanticAdaptationRuntimeModule.xtend

@@ -0,0 +1,24 @@
+/*
+ * generated by Xtext 2.10.0
+ */
+package be.uantwerpen.ansymo.semanticadaptation
+
+import be.uantwerpen.ansymo.semanticadaptation.valueconverter.SemanticAdaptationValueConverters
+import be.uantwerpen.ansymo.semanticadaptation.scoping.SemanticAdaptationScopeProvider
+import be.uantwerpen.ansymo.semanticadaptation.generator.SemanticAdaptationPythonGenerator
+
+/**
+ * Use this class to register components to be used at runtime / without the Equinox extension registry.
+ */
+class SemanticAdaptationRuntimeModule extends AbstractSemanticAdaptationRuntimeModule {
+	
+	override bindIValueConverterService() {
+		return SemanticAdaptationValueConverters
+	}
+	override bindIScopeProvider() {
+		return SemanticAdaptationScopeProvider
+	}
+	override bindIGenerator2() {
+		return SemanticAdaptationPythonGenerator
+	}
+}

+ 15 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/src/be/uantwerpen/ansymo/semanticadaptation/SemanticAdaptationStandaloneSetup.xtend

@@ -0,0 +1,15 @@
+/*
+ * generated by Xtext 2.10.0
+ */
+package be.uantwerpen.ansymo.semanticadaptation
+
+
+/**
+ * Initialization support for running Xtext languages without Equinox extension registry.
+ */
+class SemanticAdaptationStandaloneSetup extends SemanticAdaptationStandaloneSetupGenerated {
+
+	def static void doSetup() {
+		new SemanticAdaptationStandaloneSetup().createInjectorAndDoEMFRegistration()
+	}
+}

+ 25 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/src/be/uantwerpen/ansymo/semanticadaptation/generator/SemanticAdaptationGenerator.xtend

@@ -0,0 +1,25 @@
+/*
+ * generated by Xtext 2.10.0
+ */
+package be.uantwerpen.ansymo.semanticadaptation.generator
+
+import org.eclipse.emf.ecore.resource.Resource
+import org.eclipse.xtext.generator.AbstractGenerator
+import org.eclipse.xtext.generator.IFileSystemAccess2
+import org.eclipse.xtext.generator.IGeneratorContext
+
+/**
+ * Generates code from your model files on save.
+ * 
+ * See https://www.eclipse.org/Xtext/documentation/303_runtime_concepts.html#code-generation
+ */
+class SemanticAdaptationGenerator extends AbstractGenerator {
+
+	override void doGenerate(Resource resource, IFileSystemAccess2 fsa, IGeneratorContext context) {
+//		fsa.generateFile('greetings.txt', 'People to greet: ' + 
+//			resource.allContents
+//				.filter(typeof(Greeting))
+//				.map[name]
+//				.join(', '))
+	}
+}

+ 111 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/src/be/uantwerpen/ansymo/semanticadaptation/generator/SemanticAdaptationPythonGenerator.xtend

@@ -0,0 +1,111 @@
+/*
+ * generated by Xtext 2.10.0
+ */
+package be.uantwerpen.ansymo.semanticadaptation.generator
+
+import org.eclipse.emf.ecore.resource.Resource
+import org.eclipse.xtext.generator.AbstractGenerator
+import org.eclipse.xtext.generator.IFileSystemAccess2
+import org.eclipse.xtext.generator.IGeneratorContext
+import be.uantwerpen.ansymo.semanticadaptation.semanticAdaptation.*
+import org.eclipse.emf.ecore.EClass
+
+/**
+ * Generates code from your model files on save.
+ * 
+ * See https://www.eclipse.org/Xtext/documentation/303_runtime_concepts.html#code-generation
+ */
+class SemanticAdaptationPythonGenerator extends AbstractGenerator {
+	
+	public final static String FILENAME = 'output.test.txt'
+
+	override void doGenerate(Resource resource, IFileSystemAccess2 fsa, IGeneratorContext context) {
+		for (Adaptation a : resource.allContents.toIterable.filter(SemanticAdaptation).last.elements.filter(Adaptation)) {
+			fsa.generateFile(FILENAME, a.compile)
+			println(fsa.readTextFile(FILENAME))
+		}
+	}
+	
+	def compile(Adaptation a) '''
+import logging
+
+from abstract_units.AbstractSimulationUnit import AbstractSimulationUnit, \
+    STEP_ACCEPT
+«FOR fmu:a.instances.filter(AtomicFMU)»
+from case_study.units.ct_based.«fmu.name» import «fmu.name»
+«ENDFOR»
+«FOR i:a.instances.filter(Adaptation)»
+NOT YET IMPLEMENTED
+«ENDFOR»
+
+l = logging.getLogger()
+
+class PowerInputAdaptation_Event(AbstractSimulationUnit):
+    """
+    This is the adaptation of the events coming out of the Controller Statechart.
+    It gets as input an event, and output two signals, to be coupled to the power system.
+    Whenever it gets an input, it stores the appropriate signals for the output until another event comes along.
+    It's basically a ZOH.
+    
+    Example interaction:_______________
+    f = PowerInputAdaptation_Event(...)
+    f.enterInitMode()
+    f.setValues(...,"SomeInEvent")
+        This tells the FMU what the input is.
+        The sFMU will record this input (if not "") to the internal state. 
+        and initial input ("SomeInEvent").
+    (up,down) = f.getValues(...)
+        The values that can be returned are initial_up and initial_down
+    f.exitInitMode()
+    
+    f.setValues(..., "SomeInEvent")
+        The definition of a new event gets recorded by the fmu
+    f.doStep(..., H)
+        The internal state gets updated according to the new input event.
+        Or kept the same if the new event is ""
+    (up,down) = f.getValues(...)
+        The last event processed is in the output variable, ready to be collected.
+    ______________________________
+    
+    """
+    
+    def __init__(self, name):
+        
+        self.in_event = "in_event"
+        self.out_down = "out_down"
+        self.out_up = "out_up"
+        input_vars = [self.in_event]
+        state_vars = [self.out_down, self.out_up]
+        
+        algebraic_functions = {}
+        
+        AbstractSimulationUnit.__init__(self, name, algebraic_functions, state_vars, input_vars)
+    
+    def _doInternalSteps(self, time, step, iteration, step_size):
+        l.debug(">%s._doInternalSteps(%f, %d, %d, %f)", self._name, time, step, iteration, step_size)
+        
+        assert iteration == 0, "Fixed point iterations not supported yet."
+        
+        previous_output = self.getValues(step-1, iteration, self._getStateVars())
+        current_input = self.getValues(step, iteration, self._getInputVars())
+        
+        l.debug("%s.previous_output=%s", self._name, previous_output)
+        l.debug("%s.current_input=%s", self._name, current_input)
+        
+        next_output = previous_output
+        in_ev = current_input[self.in_event]
+        if in_ev != "":
+            l.debug("Updating internal state due to input %s...", in_ev)
+            next_out_up = 1.0 if in_ev=="up" else 0.0
+            next_out_down = 1.0 if in_ev=="down" else 0.0
+            next_output = {self.out_down: next_out_down, self.out_up: next_out_up}
+            
+        # Store the values into the state
+        self.setValues(step, iteration, {self.out_down: next_output[self.out_down],
+                                         self.out_up: next_output[self.out_up] })
+        
+        
+        l.debug("<%s._doInternalSteps() = (%s, %d)", self._name, STEP_ACCEPT, step_size)
+        return (STEP_ACCEPT, step_size)
+'''
+}

+ 68 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/src/be/uantwerpen/ansymo/semanticadaptation/interpreter/Interpreter.xtend

@@ -0,0 +1,68 @@
+/*******************************************************************************
+ * Copyright (c) 2015 itemis AG (http://www.itemis.eu) and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *******************************************************************************/
+package be.uantwerpen.ansymo.semanticadaptation.interpreter
+
+import com.google.common.collect.ImmutableMap
+import com.google.common.collect.Maps
+import java.math.BigDecimal
+import java.math.RoundingMode
+
+/** 
+ * an interpreter for instances of EClasses of the {@link ArithmeticsPackage}.
+ * It internally uses a polymorphic dispatcher to dispatch between the implementations for the different EClasses.
+ */
+class Interpreter {
+
+//	def BigDecimal evaluate(Expression obj) {
+//		return evaluate(obj, ImmutableMap.<String, BigDecimal>of())
+//	}
+//
+//	def BigDecimal evaluate(Expression obj, ImmutableMap<String, BigDecimal> values) {
+//		return internalEvaluate(obj, values)
+//	}
+//
+//	def dispatch protected internalEvaluate(NumberLiteral e, ImmutableMap<String, BigDecimal> values) {
+//		e.value
+//	}
+//
+//	/** 
+//	 * @param values the currently known values by name 
+//	 */
+//	def dispatch protected BigDecimal internalEvaluate(FunctionCall e, ImmutableMap<String, BigDecimal> values) {
+//		if (e.func instanceof DeclaredParameter) {
+//			return values.get(e.func.name)
+//		}
+//		switch d : e.func {
+//			Definition: {
+//				var params = Maps.newHashMap
+//				for (var int i = 0; i < e.args.size; i++) {
+//					var declaredParameter = d.args.get(i)
+//					var evaluate = evaluate(e.args.get(i), values)
+//					params.put(declaredParameter.getName(), evaluate)
+//				}
+//				return evaluate(d.expr, ImmutableMap.copyOf(params))
+//			}
+//		}
+//	}
+//
+//	def dispatch protected BigDecimal internalEvaluate(Plus plus, ImmutableMap<String, BigDecimal> values) {
+//		evaluate(plus.left, values) + evaluate(plus.right, values)
+//	}
+//
+//	def dispatch protected BigDecimal internalEvaluate(Minus minus, ImmutableMap<String, BigDecimal> values) {
+//		evaluate(minus.left, values) - evaluate(minus.right, values)
+//	}
+//
+//	def dispatch protected BigDecimal internalEvaluate(Div div, ImmutableMap<String, BigDecimal> values) {
+//		evaluate(div.left, values).divide(evaluate(div.right, values), 20, RoundingMode.HALF_UP)
+//	}
+//
+//	def dispatch protected BigDecimal internalEvaluate(Multi multi, ImmutableMap<String, BigDecimal> values) {
+//		evaluate(multi.left, values) * evaluate(multi.right, values)
+//	}
+}

+ 315 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/src/be/uantwerpen/ansymo/semanticadaptation/scoping/SemanticAdaptationScopeProvider.xtend

@@ -0,0 +1,315 @@
+/*******************************************************************************
+ * Copyright (c) 2015 itemis AG (http://www.itemis.eu) and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *******************************************************************************/
+package be.uantwerpen.ansymo.semanticadaptation.scoping
+
+import org.eclipse.emf.ecore.EReference
+import org.eclipse.xtext.EcoreUtil2
+import org.eclipse.xtext.scoping.IScope
+import org.eclipse.xtext.scoping.Scopes
+import be.uantwerpen.ansymo.semanticadaptation.semanticAdaptation.*
+import org.eclipse.emf.common.util.BasicEList
+import org.eclipse.xtext.scoping.impl.AbstractDeclarativeScopeProvider
+import org.eclipse.emf.ecore.EObject
+import org.eclipse.xtext.scoping.IGlobalScopeProvider
+import com.google.inject.Inject
+import org.eclipse.emf.ecore.resource.Resource
+import com.google.common.base.Predicate
+import org.eclipse.xtext.resource.IEObjectDescription
+import org.eclipse.xtext.scoping.impl.IScopeWrapper
+import org.eclipse.emf.common.util.EList
+import java.util.List
+import java.util.LinkedList
+
+/**
+ * This class contains custom scoping description.
+ * 
+ * See https://www.eclipse.org/Xtext/documentation/303_runtime_concepts.html#scoping
+ * on how and when to use it.
+ */
+ 
+class SemanticAdaptationScopeProvider extends AbstractDeclarativeScopeProvider  {
+	// comment out getScope for per-type scope
+
+	/* provides a global scope for all elements!
+	 * overrides all the remainder of this class
+	 */
+	override getScope(EObject context, EReference reference) {
+		if (reference === SemanticAdaptationPackage.Literals.IMPORT__MODULE) {
+			return getGlobalScope(context.eResource, reference)
+		}
+		val module = EcoreUtil2.getContainerOfType(context, SemanticAdaptation)
+		var result = IScope.NULLSCOPE
+		for (import : module.imports) {
+			if (!import.module.eIsProxy)
+				result = getModuleScope(context, reference, import.module, result)
+		}
+		result = getModuleScope(context, reference, module, result)
+		//println(Scopes.scopeFor(context.eResource.allContents.toList, result))
+		return Scopes.scopeFor(context.eResource.allContents.toList, result)
+	}
+	
+	// todo: only correct src and tgt references
+	def scope_Connection_src(Connection context, EReference r) {
+		return __getImportedScope(context, r).__addScope(__getAllPorts(context))
+	}
+	
+	def scope_Connection_tgt(Connection context, EReference r) {
+		return __getImportedScope(context, r).__addScope(__getAllPorts(context))
+	}
+	
+	def scope_Port_target(Port context, EReference r) {
+		return __getImportedScope(context, r).__addScope(__getAllPorts(context))
+	}
+	
+	def scope_AlgebraicLoopSolution_signals(AlgebraicLoopSolution context, EReference r) {
+		return __getImportedScope(context, r).__addScope(__getAllPorts(context))
+	}
+	
+	def scope_Variable_ref(Variable context, EReference r) {
+		//println(context.eContainer())
+		//var scope = __getImportedScope(context, r)
+		var EList<EObject> elements = __getAllPorts(context)
+		val outputfunction = EcoreUtil2.getContainerOfType(context, OutputFunction)
+		if (outputfunction != null) {
+			val rule = outputfunction.eContainer as DataRule
+			if (rule.statetransitionfunction != null) {
+				elements += rule.statetransitionfunction.statements
+			}
+		}
+		elements += context.__getFrom(If, "ifstatements", Declaration, true).flatten
+		elements += context.__getFrom(If, "ifstatements", FunctionDeclaration, true).flatten
+		elements += context.__getFrom(For, "iterator", null, true).flatten
+		elements += context.__getFromElement(StateTransitionFunction, "statements", Declaration)
+		elements += context.__getFromElement(StateTransitionFunction, "statements", FunctionDeclaration)
+		elements += context.__getFromElement(InOutRules, "globalvars")
+		elements += context.__getFromElement(InOutRules, "iterationvars")
+		elements += context.__getFromElement(Adaptation, "params")
+		
+		return __getImportedScope(context, r).__addScope(elements)
+	}
+	
+	def scope_Adaptation_instances(Adaptation context, EReference r) {
+		return __getImportedScope(context, r)
+	}
+	
+	def scope_Adaptation_ports(Adaptation context, EReference r) {
+		return __getImportedScope(context, r)
+	}
+	
+	def scope_CompositeFMU_instances(SemanticAdaptation context, EReference r) {
+		return __getImportedScope(context, r)
+	}
+	
+	def scope_Step_fmu(Step context, EReference r) {
+		return Scopes.scopeFor(EcoreUtil2.getContainerOfType(context, Adaptation).instances, IScope.NULLSCOPE)
+	}
+	
+	/*def EObject __getAncestorOfType(EObject object, Class<?> type) { // same as EcoreUtil2.getContainerOfType
+		val parent = object.eContainer
+		if (parent == null) {
+			return null
+		}
+		if (type.isAssignableFrom(parent.class)) {
+			return parent
+		} else{
+			return __getAncestorOfType(object.eContainer, type)
+		}
+	}*/
+	
+	def __addScope(IScope scope, EList elements) {
+		return Scopes.scopeFor(elements, scope)
+	}
+	
+	def __getAllPorts(EObject context) {
+		val module = EcoreUtil2.getContainerOfType(context, SemanticAdaptation)
+		var elementlist = new BasicEList<EObject>;
+		for (Component element : module.elements) {
+			if (element instanceof FMU) {
+				elementlist += element.inports+element.outports
+			}
+		}
+		return elementlist
+	}
+	
+	def __getFromElement(EObject context, Class<? extends EObject> containertype, String featurename, Class<? extends EObject> featuretype) {
+		/*val object = EcoreUtil2.getContainerOfType(context, containertype)
+		if (object != null) {
+			val feature = object.eClass.EAllStructuralFeatures.findFirst(f | f.name.equals(featurename))
+			if (feature != null) {
+				val featurevalue = object.eGet(feature)
+				if (featurevalue instanceof EList) {
+					if (featuretype != null) {
+						return featurevalue.filter(v | featuretype.isInstance(v))
+					} else {
+						return featurevalue
+					}
+				} else {
+					if (featuretype == null || featuretype.isInstance(featurevalue)) {
+						val featurevaluelist = new BasicEList()
+						featurevaluelist.add(featurevalue)
+						return featurevaluelist
+					}
+				}
+			} else {
+				throw new Exception("Feature " + featurename + " not found in object of type " + containertype.name)
+			}
+		}
+		return new BasicEList<EObject>()*/
+		return context.__getFrom(containertype, featurename, featuretype, false).flatten
+	}
+	
+	def __getFromElement(EObject context, Class<? extends EObject> containertype, String featurename) {
+		return context.__getFromElement(containertype, featurename, null)
+	}
+	
+	/**
+	 * Look from context to root for elements
+	 * @params:
+	 * 		context: element to start from
+	 * 		containertype: type of elements that have a feature that needs to be found
+	 * 		featurename: name of feature that must be a feature of containertype
+	 * 		featuretype: only take features of featuretype
+	 * 		all: if true: go through all instances of container type; if false: only the first encounter from context to root 
+	 * 
+	 * @returns:
+	 * 		all: list of lists of found elements (from context to root)
+	 * 		!all: list of found elements (first encounter from context to root)
+	 */
+	def List<? extends List<? extends EObject>> __getFrom(EObject context, Class<? extends EObject> containertype, String featurename, Class<? extends EObject> featuretype, boolean all) {
+		val List<List<EObject>> listOfElementLists = new LinkedList<List<EObject>>()
+		for (object : EcoreUtil2.getAllContainers(context)) {
+			if (containertype.isInstance(object)) {
+				val List<EObject> listOfElements = new LinkedList<EObject>()
+				val feature = object.eClass.EAllStructuralFeatures.findFirst(f | f.name.equals(featurename))
+				if (feature != null) {
+					val featurevalue = object.eGet(feature)
+					if (featurevalue instanceof EList) {
+						if (featuretype != null) {
+							listOfElements.addAll(featurevalue.filter(v | featuretype.isInstance(v)).map(v | v as EObject))
+						} else {
+							listOfElements.addAll(featurevalue)
+						}
+					} else if (featurevalue instanceof EObject) {
+						if (featuretype == null || featuretype.isInstance(featurevalue)) {
+							listOfElements.add(featurevalue)
+						}
+					} else {
+						throw new Exception("todo")
+					}
+				} else {
+					throw new Exception("Feature " + featurename + " not found in object of type " + containertype.name)
+				}
+				listOfElementLists.add(listOfElements)
+				if (!all) {
+					return listOfElementLists
+				}
+			}
+		}
+		return listOfElementLists
+	}
+	
+	
+	
+	
+	
+	
+	
+	
+	
+	
+	
+	
+	@Inject
+	private IGlobalScopeProvider globalScopeProvider;
+
+	def protected IScope getGlobalScope(Resource context, EReference reference) {
+		return getGlobalScope(context, reference, null);
+	}
+	
+	def protected IScope getGlobalScope(Resource context, EReference reference, Predicate<IEObjectDescription> filter) {
+		return wrap(globalScopeProvider.getScope(context, reference, filter));
+	}
+	
+	private IScopeWrapper scopeWrapper;
+	
+	def public void setWrapper(IScopeWrapper wrapper) {
+		this.scopeWrapper = wrapper;
+	}
+
+	def protected IScope wrap(IScope scope) {
+		if (scopeWrapper!=null){
+			return scopeWrapper.wrap(scope)
+		} else {
+			return scope
+		}
+	}
+	
+	def __getImportedScope(EObject context, EReference reference) {
+		if (reference === SemanticAdaptationPackage.Literals.IMPORT__MODULE) {
+			return getGlobalScope(context.eResource, reference)
+		}
+		val module = EcoreUtil2.getContainerOfType(context, SemanticAdaptation)
+		var result = IScope.NULLSCOPE
+		for (import : module.imports) {
+			if (!import.module.eIsProxy)
+				result = getModuleScope(context, reference, import.module, result)
+		}
+		result = getModuleScope(context, reference, module, result)
+		return result//getDefinitionScope(context, reference, result)
+	}
+	
+	def getModuleScope(EObject context, EReference reference, SemanticAdaptation module, IScope parent) {
+		// FMUs and ports are visible
+		val allDefinitions = module.elements.filter(FMU) + __getAllPorts(module)
+		//println(allDefinitions)
+		return Scopes.scopeFor(allDefinitions, parent)
+	}
+	
+	/*def getDefinitionScope(EObject context, EReference reference, IScope parent) {
+		val containingDef = EcoreUtil2.getContainerOfType(context, Definition)
+		if (containingDef === null) {
+			return parent
+		}
+		return Scopes.scopeFor(containingDef.args, parent)
+	}*/
+
+	
+//class SemanticAdaptationScopeProvider extends AbstractGlobalScopeDelegatingScopeProvider {
+
+//	override getScope(EObject context, EReference reference) {
+//		if (reference === SemanticAdaptationPackage.Literals.IMPORT__MODULE) {
+//			return super.getGlobalScope(context.eResource, reference)
+//		}
+//		val module = EcoreUtil2.getContainerOfType(context, Module)
+//		var result = IScope.NULLSCOPE
+//		for (import : module.imports) {
+//			if (!import.module.eIsProxy)
+//				result = getModuleScope(context, reference, import.module, result)
+//		}
+//		result = getModuleScope(context, reference, module, result)
+//		return getDefinitionScope(context, reference, result)
+//	}
+//	
+//	def getModuleScope(EObject context, EReference reference, Module module, IScope parent) {
+//		val allDefinitions = module.statements.filter(Definition)
+//		if (context instanceof FunctionCall) {
+//			return Scopes.scopeFor(allDefinitions.filter[context.args.size == args.size], parent)
+//		} else {
+//			return Scopes.scopeFor(allDefinitions, parent)
+//		}
+//	}
+//	
+//	def getDefinitionScope(EObject context, EReference reference, IScope parent) {
+//		val containingDef = EcoreUtil2.getContainerOfType(context, Definition)
+//		if (containingDef === null) {
+//			return parent
+//		}
+//		return Scopes.scopeFor(containingDef.args, parent)
+//	}
+
+}

+ 61 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/src/be/uantwerpen/ansymo/semanticadaptation/validation/SemanticAdaptationValidator.xtend

@@ -0,0 +1,61 @@
+/*******************************************************************************
+ * Copyright (c) 2015 itemis AG (http://www.itemis.eu) and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *******************************************************************************/
+package be.uantwerpen.ansymo.semanticadaptation.validation
+
+import com.google.inject.Inject
+import org.eclipse.xtext.EcoreUtil2
+import be.uantwerpen.ansymo.semanticadaptation.interpreter.Interpreter
+import org.eclipse.xtext.validation.Check
+import org.eclipse.xtext.validation.ValidationMessageAcceptor
+import be.uantwerpen.ansymo.semanticadaptation.semanticAdaptation.*
+
+import static be.uantwerpen.ansymo.semanticadaptation.semanticAdaptation.SemanticAdaptationPackage.Literals.*
+
+/**
+ * Custom validation rules. 
+ *
+ * See https://www.eclipse.org/Xtext/documentation/303_runtime_concepts.html#validation
+ */
+class SemanticAdaptationValidator extends AbstractSemanticAdaptationValidator {
+//	@Inject Interpreter interpreter
+//
+//	@Check
+//	def checkDivByZero(Div div) {
+//		val bigDecimal = interpreter.evaluate(div.right)
+//		if (bigDecimal.doubleValue()==0.0) 
+//			error("Division by zero detected.", DIV__RIGHT)
+//	}
+//	
+//	public static val String NORMALIZABLE = "normalizable-expression"
+//
+//	@Check
+//	def void checkNormalizable(Expression expr) {
+//		// ignore literals
+//		if (expr instanceof NumberLiteral || expr instanceof FunctionCall) 
+//			return;
+//		// ignore evaluations
+//		if (EcoreUtil2.getContainerOfType(expr, Evaluation)!=null)
+//			return;
+//		
+//		val contents = expr.eAllContents
+//		while(contents.hasNext()) {
+//			val next = contents.next()
+//			if (next instanceof FunctionCall) 
+//				return
+//		}
+//		val decimal = interpreter.evaluate(expr)
+//		if (decimal.toString().length()<=8) {
+//			warning(
+//					"Expression could be normalized to constant '"+decimal+"'", 
+//					null,
+//					ValidationMessageAcceptor.INSIGNIFICANT_INDEX,
+//					NORMALIZABLE,
+//					decimal.toString())
+//		}
+//	}
+}

+ 49 - 0
DSL_SemanticAdaptation/be.uantwerpen.ansymo.semanticadaptation/src/be/uantwerpen/ansymo/semanticadaptation/valueconverter/SemanticAdaptationValueConverters.xtend

@@ -0,0 +1,49 @@
+package be.uantwerpen.ansymo.semanticadaptation.valueconverter
+
+import org.eclipse.xtext.conversion.impl.AbstractDeclarativeValueConverterService
+import org.eclipse.xtext.conversion.ValueConverter
+import org.eclipse.xtext.conversion.impl.AbstractLexerBasedConverter
+import org.eclipse.xtext.nodemodel.INode
+
+class SemanticAdaptationValueConverters extends AbstractDeclarativeValueConverterService {
+	@ValueConverter(rule = "PREV")
+	def PREV() {
+		return new AbstractLexerBasedConverter<Integer> {    
+		    override toValue(String string, INode node) {
+				return -1
+		    }
+		};
+	}
+	
+	@ValueConverter(rule = "NOW")
+	def NOW() {
+		return new AbstractLexerBasedConverter<Integer> {    
+		    override toValue(String string, INode node) {
+				return 0
+		    }
+		};
+	}
+	
+	@ValueConverter(rule = "REALTYPE")
+	def REALTYPE() {
+		return new AbstractLexerBasedConverter<Float> {    
+		    override toValue(String string, INode node) {
+				return Float.valueOf(string)
+		    }
+		};
+	}
+	
+	/*@ValueConverter(rule = "AtomicUnity")
+	def AtomicUnity() {
+		return new AbstractLexerBasedConverter<Integer> {    
+		    override toValue(String string, INode node) {
+		    	println(string)
+				if (string.equals("0")) {
+					return 1
+				} else {
+					return Integer.valueOf(string)
+				}
+		    }
+		};
+	}*/
+}

BIN
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_SEL/Debug/libFMI_SEL.dll


+ 542 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_SEL/FMI_SEL.c

@@ -0,0 +1,542 @@
+/* ---------------------------------------------------------------------------*
+ * Sample implementation of an FMU - a power window controller
+ * The code is generated from a Yakindu SC
+ * ---------------------------------------------------------------------------*/
+/*
+Template for a sc FMU
+*/
+
+#define MODEL_IDENTIFIER SEL
+#define MODEL_GUID "{41f87101-edf2-4eef-90f3-42db56d4565f}"
+#define FMI2_FUNCTION_PREFIX PW_SEL
+
+
+#include <stdio.h>
+#include "string.h"
+#include "fmi2Functions.h"
+#include <float.h>
+#include "FMI_SEL.h"
+#include <math.h>
+
+
+#define NUMBER_OF_REALS 2
+#define NUMBER_OF_STRINGS 0
+#define NUMBER_OF_BOOLEANS 17
+#define NUMBER_OF_INTEGERS 0
+/*
+ * The input Signals (Real)
+ */
+#define _in_armature_current 0
+
+/*
+ * The input events
+ */
+#define _in_driver_up 0
+#define _in_driver_up_stop 1
+#define _in_driver_down 2
+#define _in_driver_down_stop 3
+#define _in_passenger_up 4
+#define _in_passenger_up_stop 5
+#define _in_passenger_down 6
+#define _in_passenger_down_stop 7
+
+/*
+ * The store
+ */
+#define _stored_armature_current 1
+
+/*
+ * The output events:
+ * */
+
+#define _out_obj_detected 8
+#define _out_driver_up 9
+#define _out_driver_up_stop 10
+#define _out_driver_down 11
+#define _out_driver_down_stop 12
+#define _out_passenger_up 13
+#define _out_passenger_up_stop 14
+#define _out_passenger_down 15
+#define _out_passenger_down_stop 16
+/*
+ * Control Signal
+ */
+#define _out_control 17
+
+/*
+ * Helper function for relative error
+ */
+ double relativeError(double a, double b){
+	return fabs((a - b) / a);
+}
+
+/*
+ * Helper function for absolute error
+ */
+ double absoluteError(double a, double b){
+	return fabs(a - b);
+}
+
+/*
+ * is_close function for double comparison
+ */
+ int is_close(double a, double b, double REL_TOL, double ABS_TOL){
+	return ((absoluteError(a,b)<ABS_TOL) && (relativeError(a,b)<REL_TOL));
+}
+
+
+fmi2Status fmi2SetDebugLogging(fmi2Component fc, fmi2Boolean loggingOn, size_t nCategories, const fmi2String categories[])
+{
+    return fmi2OK;
+}
+
+fmi2Status fmi2SetString(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, const fmi2String value[])
+{
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetString(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, fmi2String value[])
+{
+    return fmi2Error;
+}
+
+fmi2Status fmi2SetReal(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, const fmi2Real value[])
+{
+	FMUInstance* comp = (FMUInstance *)fc;
+		int i;
+	    for (i = 0; i < nvr; i++)
+		{
+	    	if(vr[i]>=5){
+	    		printf("Value reference: %d, cannot be set, it is a store element\n", vr[i]);
+	    	}else{
+	    		 printf("Value reference: %d\n", vr[i]);
+	    		 comp->r[vr[i]] = value[i];
+	    	}
+
+	        //setExposedReal(vr[i], value[i]);
+	        //comp->r[vr[i]] = value[i];
+	    }
+	    return fmi2OK;
+}
+
+fmi2Status fmi2GetReal(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, fmi2Real value[])
+{
+
+    FMUInstance* comp = (FMUInstance *)fc;
+	int i;
+    for (i = 0; i < nvr; i++)
+	{
+        value[i] = comp->r[(vr[i])];
+    }
+    return fmi2OK;
+}
+
+fmi2Status fmi2SetBoolean(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, const fmi2Boolean value[])
+{
+	FMUInstance* comp = (FMUInstance *)fc;
+	int i;
+	for (i = 0; i < nvr; i++)
+	{
+		comp->b[vr[i]] = value[i];
+	}
+    return fmi2OK;
+}
+
+fmi2Status fmi2GetBoolean(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, fmi2Boolean value[])
+{
+	FMUInstance* comp = (FMUInstance *)fc;
+	int i;
+	for (i = 0; i < nvr; i++)
+	{
+		value[i] = comp->b[vr[i]];
+	}
+    return fmi2OK;
+}
+
+fmi2Component fmi2Instantiate(fmi2String instanceName, fmi2Type fmuType, fmi2String fmuGUID, fmi2String fmuLocation, const fmi2CallbackFunctions* functions, fmi2Boolean visible, fmi2Boolean loggingOn)
+{
+
+	//Declare data structure for fmu instance
+    FMUInstance* fi;
+	printf("%s in fmiInstantiate\n",instanceName);
+
+    //Perform checks on passed callback functions
+    if (loggingOn) {
+
+        if (!functions->logger);
+        //return NULL;
+	}
+    //Check for instanceName
+    if (!instanceName || strlen(instanceName)==0) {
+
+        // print (and/or log) instanceName is missing
+        //return NULL;
+    }
+    //Check passed GUID to defined model GUID
+    if (strcmp(fmuGUID, MODEL_GUID))
+	{
+        // print (and/or log) GUID doesn't match
+        //return NULL;
+    }
+
+    //Allocate fmu instance Memory
+    // TODO check if "canNotUseMemoryManagementFunctions == true/false". If false memory allocation not possible
+    fi = (FMUInstance *)functions->allocateMemory(1, sizeof(FMUInstance));
+    fi->functions = functions;
+    if (fi) {
+        // Think about what to do with variable values. Using these structs and pointers slows down simulation computations. Maybe only necessary for input, output and tunable parameters??
+        fi->r = functions->allocateMemory(NUMBER_OF_REALS, sizeof(fmi2Real));
+        fi->i = functions->allocateMemory(NUMBER_OF_INTEGERS, sizeof(fmi2Integer));
+        fi->b = functions->allocateMemory(NUMBER_OF_BOOLEANS, sizeof(fmi2Boolean));
+        fi->s = functions->allocateMemory(NUMBER_OF_STRINGS,  sizeof(fmi2String));
+    } // variables in predefined arrays (performance issue) --> makes multiple instances of fmu impossible
+
+
+    fi->instanceName = functions->allocateMemory(1 + strlen(instanceName), sizeof(char));
+    fi->GUID = functions->allocateMemory(1 + strlen(fmuGUID), sizeof(char));
+
+    strcpy((char*)fi->instanceName, instanceName);
+    strcpy((char*)fi->GUID, fmuGUID);
+    fi->functions = functions;
+    fi->loggingOn = loggingOn;
+    fi->isVisible = visible;
+    fi->state = fmuInstantiated;
+    return fi;
+}
+
+fmi2Status fmi2SetupExperiment(fmi2Component fc, fmi2Boolean toleranceDefined, fmi2Real tolerance,
+                            fmi2Real startTime, fmi2Boolean stopTimeDefined, fmi2Real stopTime) {
+
+
+    FMUInstance* fi = (FMUInstance*) fc;
+	printf("%s in fmiSetupExperiment\n",fi->instanceName);
+	if (fi->state != fmuInstantiated)
+	{
+		printf("fmu: %s was not instatiated before calling fmiSetupExperiment\n", fi->instanceName);
+		return fmi2Error;
+	}
+	fi->currentTime = startTime;
+	fi->stopTimeDefined = stopTimeDefined;
+	fi->toleranceDefined = toleranceDefined;
+	if (stopTimeDefined)
+	{
+		fi->stopTime = stopTime;
+	}
+
+	if (toleranceDefined)
+	{
+		fi->tolerance = tolerance;
+	}
+	//TODO
+	//fi->stepSize = getStepSize();
+	fi->state = fmuExperimentSettedUp;
+    return fmi2OK;
+}
+
+fmi2Status fmi2EnterInitializationMode(fmi2Component fc)
+{
+	FMUInstance* fi = (FMUInstance*) fc;
+	printf("%s in fmiEnterInitializationMode\n",fi->instanceName);
+	if (fi->state != fmuExperimentSettedUp)
+	{
+		printf("fmu: %s experiment was not set-up before calling fmiEnterInitializationMode\n", fi->instanceName);
+		return fmi2Error;
+	}
+
+    fi->state = fmuInitMode;
+    return fmi2OK;
+}
+
+fmi2Status fmi2ExitInitializationMode(fmi2Component fc)
+{
+	FMUInstance* fi = (FMUInstance*) fc;
+	fmi2Status initStatus = fmi2OK;
+	printf("%s in fmiExitInitializationMode\n",fi->instanceName);
+	if (fi->state != fmuInitMode)
+	{
+		printf("fmu: %s did not enter Initialization Mode before calling fmiExitInitializationMode\n", fi->instanceName);
+		return fmi2Error;
+	}
+	// TODO
+	//initStatus = calculateInitialUnknownValues();
+	//initialize();
+    fi->state = fmuInitialized;
+    return initStatus;
+}
+
+fmi2Status fmi2DoStep(fmi2Component fc , fmi2Real currentCommPoint, fmi2Real commStepSize, fmi2Boolean noPrevFMUState)
+{
+	FMUInstance* fi = (FMUInstance *)fc;
+	fmi2Status simStatus = fmi2OK;
+    printf("%s in fmiDoStep()\n",fi->instanceName);
+
+    /*
+     * true -> {
+		obj_detected := ""; // or null value or something else
+		if (not
+			(not is_close(stored_armature_current, 5, REL_TOL, ABS_TOL) and stored_armature_current > 5)
+					and (not is_close(armature_current, 5, REL_TOL, ABS_TOL) and armature_current > 5)) {
+			var negative_value := stored_armature_current - 5;
+			var positive_value := armature_current - 5;
+			var new_step_size := (h * (- negative_value)) / (positive_value - negative_value);
+			discard(new_step_size);
+		} else {
+			if (not (not is_close(stored_armature_current, 5, REL_TOL, ABS_TOL) and stored_armature_current > 5)
+						and is_close(armature_current, 5, REL_TOL, ABS_TOL)) { // crossing found
+				obj_detected := "obj";
+			}
+		}
+		stored_armature_current := armature_current; // as there exists a target port obj_detected, the source port armature_current is used. If ports would have the same name (and thus same type), the value resulting from the crossing would be stored
+	} --> {
+	};*/
+    fi->b[_out_obj_detected] = 0;
+    if(!(! is_close(fi->r[_stored_armature_current], 5 , 0.0001, 1e-8) && fi->r[_stored_armature_current] > 5)
+    		&& (!is_close(fi->r[_in_armature_current],5, 0.0001, 1e-8) && fi->r[_in_armature_current] > 5)){ // should this be <
+    		double negative_value = fi->r[_stored_armature_current] - 5;
+    		double positive_value = fi->r[_in_armature_current] - 5;
+    		double new_step_size = (commStepSize * (-negative_value)) / (positive_value - negative_value);
+    		fi->currentTime = currentCommPoint + new_step_size;
+    		simStatus = fmi2Discard;
+
+    }else{
+    	if(!(! is_close(fi->r[_stored_armature_current],5,0.0001,1e-8) && fi->r[_stored_armature_current] > 5)
+    			&& is_close(fi->r[_in_armature_current],5, 0.0001, 1e-8)){
+    			fi->b[_out_obj_detected] = 1;
+    	}
+    }
+    /* Set out:*/
+    fi->b[_out_driver_down] = fi->b[_in_driver_down];
+    fi->b[_out_driver_down_stop] = fi->b[_in_driver_down_stop];
+    fi->b[_out_driver_up] = fi->b[_in_driver_up];
+    fi->b[_out_driver_up_stop] = fi->b[_in_driver_up_stop];
+    fi->b[_out_passenger_down] = fi->b[_in_passenger_down];
+    fi->b[_out_passenger_down_stop] = fi->b[_in_passenger_down_stop];
+    fi->b[_out_passenger_up] = fi->b[_in_passenger_up];
+    fi->b[_out_passenger_up_stop] = fi->b[_in_passenger_up_stop];
+
+    /*Control signal*/
+    if(fi->b[_out_driver_down] || fi->b[_out_driver_down_stop]|| fi->b[_out_driver_up] ||
+    		 fi->b[_out_driver_up_stop] || fi->b[_out_obj_detected] ||
+			 fi->b[_out_passenger_down] || fi->b[_out_passenger_down_stop] ||
+			 fi->b[_out_passenger_up] || fi->b[_out_passenger_up_stop]){
+    	fi->b[_out_control] = 1;
+    }
+	return simStatus;
+}
+
+fmi2Status fmi2Terminate(fmi2Component fc)
+{
+	FMUInstance* fi = (FMUInstance *)fc;
+	printf("%s in fmiTerminate\n",fi->instanceName);
+	// do check if fi may be terminated
+	fi->state = fmuTerminated;
+    return fmi2OK;
+}
+
+
+void fmi2FreeInstance(fmi2Component fc)
+{
+
+	FMUInstance* fi = (FMUInstance*) fc;
+	printf("%s in fmiFreeInstance\n",fi->instanceName);
+
+    if (fi) {
+
+        fi->functions->freeMemory(fi->r);
+        fi->functions->freeMemory(fi->i);
+        fi->functions->freeMemory(fi->b);
+        fi->functions->freeMemory(fi->s);// TODO has to be done with loop
+		fi->functions->freeMemory((void*)fi->instanceName);
+		fi->functions->freeMemory((void*)fi->GUID);
+		fi->functions->freeMemory((void*)fi);
+
+    }
+}
+
+//To be implemented
+
+const char* fmi2GetVersion() {
+	printf("Function fmiGetVersion not supported\n");
+    return NULL;
+}
+
+const char* fmi2GetTypesPlatform() {
+	printf("Function fmiGetTypesPlatform not supported\n");
+    return NULL;
+}
+
+fmi2Status fmi2Reset(fmi2Component fc)
+{
+	printf("Function fmiReset not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2SetInteger(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, const fmi2Integer value[])
+{
+    printf("Function fmiSetInteger not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetInteger(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, fmi2Integer value[])
+{
+    printf("Function fmiGetInteger not supported\n");
+    return fmi2Error;
+}
+
+
+/*******OWN IMPLEMENTATION OF Get/Set FMU state*******/
+fmi2Status fmi2GetFMUstate (fmi2Component c, fmi2FMUstate* FMUstate) {
+    FMUInstance* orig = (FMUInstance*)c;
+    FMUInstance* fi = (FMUInstance *)FMUstate;
+    fi = orig->functions->allocateMemory(1, sizeof(FMUInstance));
+    *FMUstate = fi;
+    if (fi) {
+        // Think about what to do with variable values. Using these structs and pointers slows down simulation computations. Maybe only necessary for input, output and tunable parameters??
+        fi->r = orig->functions->allocateMemory(NUMBER_OF_REALS, sizeof(fmi2Real));
+        fi->i = orig->functions->allocateMemory(NUMBER_OF_INTEGERS, sizeof(fmi2Integer));
+        fi->b = orig->functions->allocateMemory(NUMBER_OF_BOOLEANS, sizeof(fmi2Boolean));
+        fi->s = orig->functions->allocateMemory(NUMBER_OF_STRINGS,  sizeof(fmi2String));
+
+    } // variables in predefined arrays (performance issue) --> makes multiple instances of fmu impossible
+    fi->instanceName = orig->functions->allocateMemory(1 + strlen(orig->instanceName), sizeof(char));
+    fi->GUID = orig->functions->allocateMemory(1 + strlen(orig->GUID), sizeof(char));
+
+    strcpy((char *)fi->instanceName, (char *)orig->instanceName);
+    strcpy((char *)fi->GUID, (char *)orig->GUID);
+    fi->functions = orig->functions;
+    fi->loggingOn = orig->loggingOn;
+    fi->isVisible = orig->isVisible;
+    fi->state = orig->state;
+    fi->stepSize = orig->stepSize;
+    fi->startTime = orig->startTime;
+    fi->stopTime = orig->stopTime;
+	fi->currentTime = orig->currentTime;
+	//copy r
+	int i=0;
+	for (i=0; i< NUMBER_OF_REALS;i++){
+	    printf("Setting real: %i %f\n", i, orig->r[i]);
+        fi->r[i] = orig->r[i];
+        printf("Setted real: %i %f\n", i, fi->r[i]);
+	}
+	//copy s
+	for (i=0; i< NUMBER_OF_STRINGS;i++){
+        fi->s[i] = orig->s[i];
+	}
+	//copy i
+    for (i=0; i< NUMBER_OF_INTEGERS;i++){
+        fi->i[i] = orig->i[i];
+	}
+	//copy b
+	for (i=0; i< NUMBER_OF_BOOLEANS;i++){
+        fi->b[i] = orig->b[i];
+	}
+    return fmi2OK;
+}
+
+
+fmi2Status fmi2SetFMUstate (fmi2Component c, fmi2FMUstate FMUstate) {
+    FMUInstance* orig = (FMUInstance*)FMUstate;
+    FMUInstance* fi = (FMUInstance*)c;
+    //set time etc correct, name and GUID should still be ok ;-)
+    printf("setting time values from %f to %f\n", fi->currentTime, orig->currentTime);
+    fi->state = orig->state;
+    fi->stepSize = orig->stepSize;
+    fi->startTime = orig->startTime;
+    fi->stopTime = orig->stopTime;
+	fi->currentTime = orig->currentTime;
+	printf("setting real values\n");
+	//copy r
+	int i=0;
+	for (i=0; i< NUMBER_OF_REALS;i++){
+        fi->r[i] = orig->r[i];
+	}
+	printf("setting string values\n");
+	//copy s
+	for (i=0; i< NUMBER_OF_STRINGS;i++){
+
+        fi->s[i] = orig->s[i];
+	}
+	//copy i
+    for (i=0; i< NUMBER_OF_INTEGERS;i++){
+        fi->i[i] = orig->i[i];
+	}
+	//copy b
+	for (i=0; i< NUMBER_OF_BOOLEANS;i++){
+        fi->b[i] = orig->b[i];
+	}
+    return fmi2OK;
+
+
+}
+/****************************************************/
+
+fmi2Status fmi2FreeFMUstate(fmi2Component c, fmi2FMUstate* FMUstate) {
+    printf("Function fmiFreeFMUstate not supported\n");
+    return fmi2Error;
+}
+fmi2Status fmi2SerializedFMUstateSize(fmi2Component c, fmi2FMUstate FMUstate, size_t *size) {
+    printf("Function fmiSerializedFMUstateSize not supported\n");
+    return fmi2Error;
+}
+fmi2Status fmi2SerializeFMUstate (fmi2Component c, fmi2FMUstate FMUstate, fmi2Byte serializedState[], size_t size) {
+    printf("Function fmiSerializeFMUstate not supported\n");
+    return fmi2Error;
+}
+fmi2Status fmi2DeSerializeFMUstate (fmi2Component c, const fmi2Byte serializedState[], size_t size, fmi2FMUstate* FMUstate) {
+    printf("Function fmiDeSerializeFMUstate not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetDirectionalDerivative(fmi2Component c, const fmi2ValueReference vUnknown_ref[], size_t nUnknown,
+                const fmi2ValueReference vKnown_ref[] , size_t nKnown, const fmi2Real dvKnown[], fmi2Real dvUnknown[]) {
+    printf("Function fmiGetDirectionalDerivative not supported\n");
+    return fmi2Error;
+}
+
+
+fmi2Status fmi2SetRealInputDerivatives(fmi2Component c, const fmi2ValueReference vr[], size_t nvr,
+                                     const fmi2Integer order[], const fmi2Real value[]) {
+    printf("Function fmiGetDirectionalDerivative not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetRealOutputDerivatives(fmi2Component c, const fmi2ValueReference vr[], size_t nvr,
+                                      const fmi2Integer order[], fmi2Real value[]) {
+    printf("Function fmiGetDirectionalDerivative not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2CancelStep(fmi2Component c) {
+    printf("Function fmiGetDirectionalDerivative not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetStatus(fmi2Component c, const fmi2StatusKind s, fmi2Status *value) {
+    printf("Function fmiGetStatus not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetRealStatus(fmi2Component c, const fmi2StatusKind s, fmi2Real *value) {
+    if(s == fmi2LastSuccessfulTime){
+        FMUInstance* comp = (FMUInstance*) c;
+        *value = comp->currentTime;
+        return fmi2OK;
+    }
+    printf("Function fmiGetRealStatus not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetIntegerStatus(fmi2Component c, const fmi2StatusKind s, fmi2Integer *value) {
+    printf("Function fmiGetIntegerStatus not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetBooleanStatus(fmi2Component c, const fmi2StatusKind s, fmi2Boolean *value) {
+    printf("Function fmiGetBooleanStatus not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetStringStatus(fmi2Component c, const fmi2StatusKind s, fmi2String *value) {
+    printf("Function fmiGetStringStatus not supported\n");
+    return fmi2Error;
+}

+ 51 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_SEL/FMI_SEL.h

@@ -0,0 +1,51 @@
+/*
+ * PW_Controller.h
+ *
+ *  Created on: Jan 25, 2017
+ *      Author: Joachim
+ */
+
+#ifndef FMI_SEL_H_
+#define FMI_SEL_H_
+
+
+ double relativeError(double a, double b);
+ double absoluteError(double a, double b);
+ int is_close(double a, double b, double REL_TOL, double ABS_TOL);
+
+
+typedef enum {
+    fmuInstantiated = 0,
+    fmuInitMode  = 1,
+	fmuInitialized = 2,
+    fmuTerminated   = 3,
+    fmuError        = 4,
+    fmuExperimentSettedUp = 5
+} FMUState;
+
+
+
+typedef struct {
+	fmi2Real    *r;
+    fmi2Integer *i;
+    fmi2Boolean *b;
+    fmi2String  *s;
+    fmi2Boolean isVisible;
+    fmi2String instanceName;
+    fmi2String GUID;
+    const fmi2CallbackFunctions* functions;
+    fmi2Boolean loggingOn;
+    FMUState state;
+	fmi2Real stepSize;
+    fmi2Real startTime;
+    fmi2Real stopTime;
+	fmi2Real currentTime;
+    fmi2Boolean stopTimeDefined;
+    fmi2Real tolerance;
+    fmi2Boolean toleranceDefined;
+} FMUInstance; // At the moment, most of the variables not really used since multiple instances of an FMU are not supported at the moment (performance issues)
+
+
+
+
+#endif /* FMI_SEL_H_ */

+ 247 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_SEL/fmi2/fmi2FunctionTypes.h

@@ -0,0 +1,247 @@
+#ifndef fmi2FunctionTypes_h
+#define fmi2FunctionTypes_h
+
+#include "fmi2TypesPlatform.h"
+
+/* This header file must be utilized when compiling an FMU or an FMI master.
+   It declares data and function types for FMI 2.0
+
+   Revisions:
+   - Apr.  9, 2014: all prefixes "fmi" renamed to "fmi2" (decision from April 8)
+   - Apr.  3, 2014: Added #include <stddef.h> for size_t definition
+   - Mar. 27, 2014: Added #include "fmiTypesPlatform.h" (#179)
+   - Mar. 26, 2014: Introduced function argument "void" for the functions (#171)
+                      fmiGetTypesPlatformTYPE and fmiGetVersionTYPE
+   - Oct. 11, 2013: Functions of ModelExchange and CoSimulation merged:
+                      fmiInstantiateModelTYPE , fmiInstantiateSlaveTYPE  -> fmiInstantiateTYPE
+                      fmiFreeModelInstanceTYPE, fmiFreeSlaveInstanceTYPE -> fmiFreeInstanceTYPE
+                      fmiEnterModelInitializationModeTYPE, fmiEnterSlaveInitializationModeTYPE -> fmiEnterInitializationModeTYPE
+                      fmiExitModelInitializationModeTYPE , fmiExitSlaveInitializationModeTYPE  -> fmiExitInitializationModeTYPE
+                      fmiTerminateModelTYPE , fmiTerminateSlaveTYPE  -> fmiTerminate
+                      fmiResetSlave -> fmiReset (now also for ModelExchange and not only for CoSimulation)
+                    Functions renamed
+                      fmiUpdateDiscreteStatesTYPE -> fmiNewDiscreteStatesTYPE
+                    Renamed elements of the enumeration fmiEventInfo
+                      upcomingTimeEvent             -> nextEventTimeDefined // due to generic naming scheme: varDefined + var
+                      newUpdateDiscreteStatesNeeded -> newDiscreteStatesNeeded;
+   - June 13, 2013: Changed type fmiEventInfo
+                    Functions removed:
+                       fmiInitializeModelTYPE
+                       fmiEventUpdateTYPE
+                       fmiCompletedEventIterationTYPE
+                       fmiInitializeSlaveTYPE
+                    Functions added:
+                       fmiEnterModelInitializationModeTYPE
+                       fmiExitModelInitializationModeTYPE
+                       fmiEnterEventModeTYPE
+                       fmiUpdateDiscreteStatesTYPE
+                       fmiEnterContinuousTimeModeTYPE
+                       fmiEnterSlaveInitializationModeTYPE;
+                       fmiExitSlaveInitializationModeTYPE;
+   - Feb. 17, 2013: Added third argument to fmiCompletedIntegratorStepTYPE
+                    Changed function name "fmiTerminateType" to "fmiTerminateModelType" (due to #113)
+                    Changed function name "fmiGetNominalContinuousStateTYPE" to
+                                          "fmiGetNominalsOfContinuousStatesTYPE"
+                    Removed fmiGetStateValueReferencesTYPE.
+   - Nov. 14, 2011: First public Version
+
+
+   Copyright (C) 2011 MODELISAR consortium,
+               2012-2013 Modelica Association Project "FMI"
+               All rights reserved.
+   This file is licensed by the copyright holders under the BSD 2-Clause License
+   (http://www.opensource.org/licenses/bsd-license.html):
+
+   ----------------------------------------------------------------------------
+   Redistribution and use in source and binary forms, with or without
+   modification, are permitted provided that the following conditions are met:
+
+   - Redistributions of source code must retain the above copyright notice,
+     this list of conditions and the following disclaimer.
+   - Redistributions in binary form must reproduce the above copyright notice,
+     this list of conditions and the following disclaimer in the documentation
+     and/or other materials provided with the distribution.
+   - Neither the name of the copyright holders nor the names of its
+     contributors may be used to endorse or promote products derived
+     from this software without specific prior written permission.
+
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+   TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+   PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
+   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+   OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+   OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+   ----------------------------------------------------------------------------
+
+   with the extension:
+
+   You may distribute or publicly perform any modification only under the
+   terms of this license.
+   (Note, this means that if you distribute a modified file,
+    the modified file must also be provided under this license).
+*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* make sure all compiler use the same alignment policies for structures */
+#if defined _MSC_VER || defined __GNUC__
+#pragma pack(push,8)
+#endif
+
+/* Include stddef.h, in order that size_t etc. is defined */
+#include <stddef.h>
+
+
+/* Type definitions */
+typedef enum {
+    fmi2OK,
+    fmi2Warning,
+    fmi2Discard,
+    fmi2Error,
+    fmi2Fatal,
+    fmi2Pending
+} fmi2Status;
+
+typedef enum {
+    fmi2ModelExchange,
+    fmi2CoSimulation
+} fmi2Type;
+
+typedef enum {
+    fmi2DoStepStatus,
+    fmi2PendingStatus,
+    fmi2LastSuccessfulTime,
+    fmi2Terminated
+} fmi2StatusKind;
+
+typedef void      (*fmi2CallbackLogger)        (fmi2ComponentEnvironment, fmi2String, fmi2Status, fmi2String, fmi2String, ...);
+typedef void*     (*fmi2CallbackAllocateMemory)(size_t, size_t);
+typedef void      (*fmi2CallbackFreeMemory)    (void*);
+typedef void      (*fmi2StepFinished)          (fmi2ComponentEnvironment, fmi2Status);
+
+typedef struct {
+   const fmi2CallbackLogger         logger;
+   const fmi2CallbackAllocateMemory allocateMemory;
+   const fmi2CallbackFreeMemory     freeMemory;
+   const fmi2StepFinished           stepFinished;
+   const fmi2ComponentEnvironment   componentEnvironment;
+} fmi2CallbackFunctions;
+
+typedef struct {
+   fmi2Boolean newDiscreteStatesNeeded;
+   fmi2Boolean terminateSimulation;
+   fmi2Boolean nominalsOfContinuousStatesChanged;
+   fmi2Boolean valuesOfContinuousStatesChanged;
+   fmi2Boolean nextEventTimeDefined;
+   fmi2Real    nextEventTime;
+} fmi2EventInfo;
+
+
+/* reset alignment policy to the one set before reading this file */
+#if defined _MSC_VER || defined __GNUC__
+#pragma pack(pop)
+#endif
+
+
+/* Define fmi2 function pointer types to simplify dynamic loading */
+
+/***************************************************
+Types for Common Functions
+****************************************************/
+
+/* Inquire version numbers of header files and setting logging status */
+   typedef const char* fmi2GetTypesPlatformTYPE(void);
+   typedef const char* fmi2GetVersionTYPE(void);
+   typedef fmi2Status  fmi2SetDebugLoggingTYPE(fmi2Component, fmi2Boolean, size_t, const fmi2String[]);
+
+/* Creation and destruction of FMU instances and setting debug status */
+   typedef fmi2Component fmi2InstantiateTYPE (fmi2String, fmi2Type, fmi2String, fmi2String, const fmi2CallbackFunctions*, fmi2Boolean, fmi2Boolean);
+   typedef void          fmi2FreeInstanceTYPE(fmi2Component);
+
+/* Enter and exit initialization mode, terminate and reset */
+   typedef fmi2Status fmi2SetupExperimentTYPE        (fmi2Component, fmi2Boolean, fmi2Real, fmi2Real, fmi2Boolean, fmi2Real);
+   typedef fmi2Status fmi2EnterInitializationModeTYPE(fmi2Component);
+   typedef fmi2Status fmi2ExitInitializationModeTYPE (fmi2Component);
+   typedef fmi2Status fmi2TerminateTYPE              (fmi2Component);
+   typedef fmi2Status fmi2ResetTYPE                  (fmi2Component);
+
+/* Getting and setting variable values */
+   typedef fmi2Status fmi2GetRealTYPE   (fmi2Component, const fmi2ValueReference[], size_t, fmi2Real   []);
+   typedef fmi2Status fmi2GetIntegerTYPE(fmi2Component, const fmi2ValueReference[], size_t, fmi2Integer[]);
+   typedef fmi2Status fmi2GetBooleanTYPE(fmi2Component, const fmi2ValueReference[], size_t, fmi2Boolean[]);
+   typedef fmi2Status fmi2GetStringTYPE (fmi2Component, const fmi2ValueReference[], size_t, fmi2String []);
+
+   typedef fmi2Status fmi2SetRealTYPE   (fmi2Component, const fmi2ValueReference[], size_t, const fmi2Real   []);
+   typedef fmi2Status fmi2SetIntegerTYPE(fmi2Component, const fmi2ValueReference[], size_t, const fmi2Integer[]);
+   typedef fmi2Status fmi2SetBooleanTYPE(fmi2Component, const fmi2ValueReference[], size_t, const fmi2Boolean[]);
+   typedef fmi2Status fmi2SetStringTYPE (fmi2Component, const fmi2ValueReference[], size_t, const fmi2String []);
+
+/* Getting and setting the internal FMU state */
+   typedef fmi2Status fmi2GetFMUstateTYPE           (fmi2Component, fmi2FMUstate*);
+   typedef fmi2Status fmi2SetFMUstateTYPE           (fmi2Component, fmi2FMUstate);
+   typedef fmi2Status fmi2FreeFMUstateTYPE          (fmi2Component, fmi2FMUstate*);
+   typedef fmi2Status fmi2SerializedFMUstateSizeTYPE(fmi2Component, fmi2FMUstate, size_t*);
+   typedef fmi2Status fmi2SerializeFMUstateTYPE     (fmi2Component, fmi2FMUstate, fmi2Byte[], size_t);
+   typedef fmi2Status fmi2DeSerializeFMUstateTYPE   (fmi2Component, const fmi2Byte[], size_t, fmi2FMUstate*);
+
+/* Getting partial derivatives */
+   typedef fmi2Status fmi2GetDirectionalDerivativeTYPE(fmi2Component, const fmi2ValueReference[], size_t,
+                                                                   const fmi2ValueReference[], size_t,
+                                                                   const fmi2Real[], fmi2Real[]);
+
+/***************************************************
+Types for Functions for FMI2 for Model Exchange
+****************************************************/
+
+/* Enter and exit the different modes */
+   typedef fmi2Status fmi2EnterEventModeTYPE         (fmi2Component);
+   typedef fmi2Status fmi2NewDiscreteStatesTYPE      (fmi2Component, fmi2EventInfo*);
+   typedef fmi2Status fmi2EnterContinuousTimeModeTYPE(fmi2Component);
+   typedef fmi2Status fmi2CompletedIntegratorStepTYPE(fmi2Component, fmi2Boolean, fmi2Boolean*, fmi2Boolean*);
+
+/* Providing independent variables and re-initialization of caching */
+   typedef fmi2Status fmi2SetTimeTYPE            (fmi2Component, fmi2Real);
+   typedef fmi2Status fmi2SetContinuousStatesTYPE(fmi2Component, const fmi2Real[], size_t);
+
+/* Evaluation of the model equations */
+   typedef fmi2Status fmi2GetDerivativesTYPE               (fmi2Component, fmi2Real[], size_t);
+#ifdef FMU_EXPERIMENTAL
+   typedef fmi2Status fmi2GetSpecificDerivativesTYPE       (fmi2Component, fmi2Real[], const fmi2ValueReference [], size_t);
+#endif
+
+   typedef fmi2Status fmi2GetEventIndicatorsTYPE           (fmi2Component, fmi2Real[], size_t);
+   typedef fmi2Status fmi2GetContinuousStatesTYPE          (fmi2Component, fmi2Real[], size_t);
+   typedef fmi2Status fmi2GetNominalsOfContinuousStatesTYPE(fmi2Component, fmi2Real[], size_t);
+
+
+/***************************************************
+Types for Functions for FMI2 for Co-Simulation
+****************************************************/
+
+/* Simulating the slave */
+   typedef fmi2Status fmi2SetRealInputDerivativesTYPE (fmi2Component, const fmi2ValueReference [], size_t, const fmi2Integer [], const fmi2Real []);
+   typedef fmi2Status fmi2GetRealOutputDerivativesTYPE(fmi2Component, const fmi2ValueReference [], size_t, const fmi2Integer [], fmi2Real []);
+
+   typedef fmi2Status fmi2DoStepTYPE     (fmi2Component, fmi2Real, fmi2Real, fmi2Boolean);
+   typedef fmi2Status fmi2CancelStepTYPE (fmi2Component);
+
+/* Inquire slave status */
+   typedef fmi2Status fmi2GetStatusTYPE       (fmi2Component, const fmi2StatusKind, fmi2Status* );
+   typedef fmi2Status fmi2GetRealStatusTYPE   (fmi2Component, const fmi2StatusKind, fmi2Real*   );
+   typedef fmi2Status fmi2GetIntegerStatusTYPE(fmi2Component, const fmi2StatusKind, fmi2Integer*);
+   typedef fmi2Status fmi2GetBooleanStatusTYPE(fmi2Component, const fmi2StatusKind, fmi2Boolean*);
+   typedef fmi2Status fmi2GetStringStatusTYPE (fmi2Component, const fmi2StatusKind, fmi2String* );
+
+
+#ifdef __cplusplus
+}  /* end of extern "C" { */
+#endif
+
+#endif /* fmi2FunctionTypes_h */

+ 339 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_SEL/fmi2/fmi2Functions.h

@@ -0,0 +1,339 @@
+#ifndef fmi2Functions_h
+#define fmi2Functions_h
+
+/* This header file must be utilized when compiling a FMU.
+   It defines all functions of the
+         FMI 2.0 Model Exchange and Co-Simulation Interface.
+
+   In order to have unique function names even if several FMUs
+   are compiled together (e.g. for embedded systems), every "real" function name
+   is constructed by prepending the function name by "FMI2_FUNCTION_PREFIX".
+   Therefore, the typical usage is:
+
+      #define FMI2_FUNCTION_PREFIX MyModel_
+      #include "fmi2Functions.h"
+
+   As a result, a function that is defined as "fmi2GetDerivatives" in this header file,
+   is actually getting the name "MyModel_fmi2GetDerivatives".
+
+   This only holds if the FMU is shipped in C source code, or is compiled in a
+   static link library. For FMUs compiled in a DLL/sharedObject, the "actual" function
+   names are used and "FMI2_FUNCTION_PREFIX" must not be defined.
+
+   Revisions:
+   - Apr.  9, 2014: all prefixes "fmi" renamed to "fmi2" (decision from April 8)
+   - Mar. 26, 2014: FMI_Export set to empty value if FMI_Export and FMI_FUNCTION_PREFIX
+                    are not defined (#173)
+   - Oct. 11, 2013: Functions of ModelExchange and CoSimulation merged:
+                      fmiInstantiateModel , fmiInstantiateSlave  -> fmiInstantiate
+                      fmiFreeModelInstance, fmiFreeSlaveInstance -> fmiFreeInstance
+                      fmiEnterModelInitializationMode, fmiEnterSlaveInitializationMode -> fmiEnterInitializationMode
+                      fmiExitModelInitializationMode , fmiExitSlaveInitializationMode  -> fmiExitInitializationMode
+                      fmiTerminateModel, fmiTerminateSlave  -> fmiTerminate
+                      fmiResetSlave -> fmiReset (now also for ModelExchange and not only for CoSimulation)
+                    Functions renamed:
+                      fmiUpdateDiscreteStates -> fmiNewDiscreteStates
+   - June 13, 2013: Functions removed:
+                       fmiInitializeModel
+                       fmiEventUpdate
+                       fmiCompletedEventIteration
+                       fmiInitializeSlave
+                    Functions added:
+                       fmiEnterModelInitializationMode
+                       fmiExitModelInitializationMode
+                       fmiEnterEventMode
+                       fmiUpdateDiscreteStates
+                       fmiEnterContinuousTimeMode
+                       fmiEnterSlaveInitializationMode;
+                       fmiExitSlaveInitializationMode;
+   - Feb. 17, 2013: Portability improvements:
+                       o DllExport changed to FMI_Export
+                       o FUNCTION_PREFIX changed to FMI_FUNCTION_PREFIX
+                       o Allow undefined FMI_FUNCTION_PREFIX (meaning no prefix is used)
+                    Changed function name "fmiTerminate" to "fmiTerminateModel" (due to #113)
+                    Changed function name "fmiGetNominalContinuousState" to
+                                          "fmiGetNominalsOfContinuousStates"
+                    Removed fmiGetStateValueReferences.
+   - Nov. 14, 2011: Adapted to FMI 2.0:
+                       o Split into two files (fmiFunctions.h, fmiTypes.h) in order
+                         that code that dynamically loads an FMU can directly
+                         utilize the header files).
+                       o Added C++ encapsulation of C-part, in order that the header
+                         file can be directly utilized in C++ code.
+                       o fmiCallbackFunctions is passed as pointer to fmiInstantiateXXX
+                       o stepFinished within fmiCallbackFunctions has as first
+                         argument "fmiComponentEnvironment" and not "fmiComponent".
+                       o New functions to get and set the complete FMU state
+                         and to compute partial derivatives.
+   - Nov.  4, 2010: Adapted to specification text:
+                       o fmiGetModelTypesPlatform renamed to fmiGetTypesPlatform
+                       o fmiInstantiateSlave: Argument GUID     replaced by fmuGUID
+                                              Argument mimetype replaced by mimeType
+                       o tabs replaced by spaces
+   - Oct. 16, 2010: Functions for FMI for Co-simulation added
+   - Jan. 20, 2010: stateValueReferencesChanged added to struct fmiEventInfo (ticket #27)
+                    (by M. Otter, DLR)
+                    Added WIN32 pragma to define the struct layout (ticket #34)
+                    (by J. Mauss, QTronic)
+   - Jan.  4, 2010: Removed argument intermediateResults from fmiInitialize
+                    Renamed macro fmiGetModelFunctionsVersion to fmiGetVersion
+                    Renamed macro fmiModelFunctionsVersion to fmiVersion
+                    Replaced fmiModel by fmiComponent in decl of fmiInstantiateModel
+                    (by J. Mauss, QTronic)
+   - Dec. 17, 2009: Changed extension "me" to "fmi" (by Martin Otter, DLR).
+   - Dez. 14, 2009: Added eventInfo to meInitialize and added
+                    meGetNominalContinuousStates (by Martin Otter, DLR)
+   - Sept. 9, 2009: Added DllExport (according to Peter Nilsson's suggestion)
+                    (by A. Junghanns, QTronic)
+   - Sept. 9, 2009: Changes according to FMI-meeting on July 21:
+                    meInquireModelTypesVersion     -> meGetModelTypesPlatform
+                    meInquireModelFunctionsVersion -> meGetModelFunctionsVersion
+                    meSetStates                    -> meSetContinuousStates
+                    meGetStates                    -> meGetContinuousStates
+                    removal of meInitializeModelClass
+                    removal of meGetTime
+                    change of arguments of meInstantiateModel
+                    change of arguments of meCompletedIntegratorStep
+                    (by Martin Otter, DLR):
+   - July 19, 2009: Added "me" as prefix to file names (by Martin Otter, DLR).
+   - March 2, 2009: Changed function definitions according to the last design
+                    meeting with additional improvements (by Martin Otter, DLR).
+   - Dec. 3 , 2008: First version by Martin Otter (DLR) and Hans Olsson (Dynasim).
+
+   Copyright (C) 2008-2011 MODELISAR consortium,
+               2012-2013 Modelica Association Project "FMI"
+               All rights reserved.
+   This file is licensed by the copyright holders under the BSD 2-Clause License
+   (http://www.opensource.org/licenses/bsd-license.html):
+
+   ----------------------------------------------------------------------------
+   Redistribution and use in source and binary forms, with or without
+   modification, are permitted provided that the following conditions are met:
+
+   - Redistributions of source code must retain the above copyright notice,
+     this list of conditions and the following disclaimer.
+   - Redistributions in binary form must reproduce the above copyright notice,
+     this list of conditions and the following disclaimer in the documentation
+     and/or other materials provided with the distribution.
+   - Neither the name of the copyright holders nor the names of its
+     contributors may be used to endorse or promote products derived
+     from this software without specific prior written permission.
+
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+   TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+   PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
+   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+   OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+   OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+   ----------------------------------------------------------------------------
+
+   with the extension:
+
+   You may distribute or publicly perform any modification only under the
+   terms of this license.
+   (Note, this means that if you distribute a modified file,
+    the modified file must also be provided under this license).
+*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "fmi2TypesPlatform.h"
+#include "fmi2FunctionTypes.h"
+#include <stdlib.h>
+
+
+/*
+  Export FMI2 API functions on Windows and under GCC.
+  If custom linking is desired then the FMI2_Export must be
+  defined before including this file. For instance,
+  it may be set to __declspec(dllimport).
+*/
+#if !defined(FMI2_Export)
+  #if !defined(FMI2_FUNCTION_PREFIX)
+    #if defined _WIN32 || defined __CYGWIN__
+     /* Note: both gcc & MSVC on Windows support this syntax. */
+        #define FMI2_Export __declspec(dllexport)
+    #else
+      #if __GNUC__ >= 4
+        #define FMI2_Export __attribute__ ((visibility ("default")))
+      #else
+        #define FMI2_Export
+      #endif
+    #endif
+  #else
+    #define FMI2_Export
+  #endif
+#endif
+
+/* Macros to construct the real function name
+   (prepend function name by FMI2_FUNCTION_PREFIX) */
+#if defined(FMI2_FUNCTION_PREFIX)
+  #define fmi2Paste(a,b)     a ## b
+  #define fmi2PasteB(a,b)    fmi2Paste(a,b)
+  #define fmi2FullName(name) fmi2PasteB(FMI2_FUNCTION_PREFIX, name)
+#else
+  #define fmi2FullName(name) name
+#endif
+
+/***************************************************
+Common Functions
+****************************************************/
+#define fmi2GetTypesPlatform         fmi2FullName(fmi2GetTypesPlatform)
+#define fmi2GetVersion               fmi2FullName(fmi2GetVersion)
+#define fmi2SetDebugLogging          fmi2FullName(fmi2SetDebugLogging)
+#define fmi2Instantiate              fmi2FullName(fmi2Instantiate)
+#define fmi2FreeInstance             fmi2FullName(fmi2FreeInstance)
+#define fmi2SetupExperiment          fmi2FullName(fmi2SetupExperiment)
+#define fmi2EnterInitializationMode  fmi2FullName(fmi2EnterInitializationMode)
+#define fmi2ExitInitializationMode   fmi2FullName(fmi2ExitInitializationMode)
+#define fmi2Terminate                fmi2FullName(fmi2Terminate)
+#define fmi2Reset                    fmi2FullName(fmi2Reset)
+#define fmi2GetReal                  fmi2FullName(fmi2GetReal)
+#define fmi2GetInteger               fmi2FullName(fmi2GetInteger)
+#define fmi2GetBoolean               fmi2FullName(fmi2GetBoolean)
+#define fmi2GetString                fmi2FullName(fmi2GetString)
+#define fmi2SetReal                  fmi2FullName(fmi2SetReal)
+#define fmi2SetInteger               fmi2FullName(fmi2SetInteger)
+#define fmi2SetBoolean               fmi2FullName(fmi2SetBoolean)
+#define fmi2SetString                fmi2FullName(fmi2SetString)
+#define fmi2GetFMUstate              fmi2FullName(fmi2GetFMUstate)
+#define fmi2SetFMUstate              fmi2FullName(fmi2SetFMUstate)
+#define fmi2FreeFMUstate             fmi2FullName(fmi2FreeFMUstate)
+#define fmi2SerializedFMUstateSize   fmi2FullName(fmi2SerializedFMUstateSize)
+#define fmi2SerializeFMUstate        fmi2FullName(fmi2SerializeFMUstate)
+#define fmi2DeSerializeFMUstate      fmi2FullName(fmi2DeSerializeFMUstate)
+#define fmi2GetDirectionalDerivative fmi2FullName(fmi2GetDirectionalDerivative)
+
+
+/***************************************************
+Functions for FMI2 for Model Exchange
+****************************************************/
+#define fmi2EnterEventMode                fmi2FullName(fmi2EnterEventMode)
+#define fmi2NewDiscreteStates             fmi2FullName(fmi2NewDiscreteStates)
+#define fmi2EnterContinuousTimeMode       fmi2FullName(fmi2EnterContinuousTimeMode)
+#define fmi2CompletedIntegratorStep       fmi2FullName(fmi2CompletedIntegratorStep)
+#define fmi2SetTime                       fmi2FullName(fmi2SetTime)
+#define fmi2SetContinuousStates           fmi2FullName(fmi2SetContinuousStates)
+#define fmi2GetDerivatives                fmi2FullName(fmi2GetDerivatives)
+#ifdef FMU_EXPERIMENTAL
+#define fmi2GetSpecificDerivatives        fmi2FullName(fmi2GetSpecificDerivatives)
+#endif
+#define fmi2GetEventIndicators            fmi2FullName(fmi2GetEventIndicators)
+#define fmi2GetContinuousStates           fmi2FullName(fmi2GetContinuousStates)
+#define fmi2GetNominalsOfContinuousStates fmi2FullName(fmi2GetNominalsOfContinuousStates)
+
+
+/***************************************************
+Functions for FMI2 for Co-Simulation
+****************************************************/
+#define fmi2SetRealInputDerivatives      fmi2FullName(fmi2SetRealInputDerivatives)
+#define fmi2GetRealOutputDerivatives     fmi2FullName(fmi2GetRealOutputDerivatives)
+#define fmi2DoStep                       fmi2FullName(fmi2DoStep)
+#define fmi2CancelStep                   fmi2FullName(fmi2CancelStep)
+#define fmi2GetStatus                    fmi2FullName(fmi2GetStatus)
+#define fmi2GetRealStatus                fmi2FullName(fmi2GetRealStatus)
+#define fmi2GetIntegerStatus             fmi2FullName(fmi2GetIntegerStatus)
+#define fmi2GetBooleanStatus             fmi2FullName(fmi2GetBooleanStatus)
+#define fmi2GetStringStatus              fmi2FullName(fmi2GetStringStatus)
+
+/* Version number */
+#define fmi2Version "2.0"
+
+
+/***************************************************
+Common Functions
+****************************************************/
+
+/* Inquire version numbers of header files */
+   FMI2_Export fmi2GetTypesPlatformTYPE fmi2GetTypesPlatform;
+   FMI2_Export fmi2GetVersionTYPE       fmi2GetVersion;
+   FMI2_Export fmi2SetDebugLoggingTYPE  fmi2SetDebugLogging;
+
+/* Creation and destruction of FMU instances */
+   FMI2_Export fmi2InstantiateTYPE  fmi2Instantiate;
+   FMI2_Export fmi2FreeInstanceTYPE fmi2FreeInstance;
+
+/* Enter and exit initialization mode, terminate and reset */
+   FMI2_Export fmi2SetupExperimentTYPE         fmi2SetupExperiment;
+   FMI2_Export fmi2EnterInitializationModeTYPE fmi2EnterInitializationMode;
+   FMI2_Export fmi2ExitInitializationModeTYPE  fmi2ExitInitializationMode;
+   FMI2_Export fmi2TerminateTYPE               fmi2Terminate;
+   FMI2_Export fmi2ResetTYPE                   fmi2Reset;
+
+/* Getting and setting variables values */
+   FMI2_Export fmi2GetRealTYPE    fmi2GetReal;
+   FMI2_Export fmi2GetIntegerTYPE fmi2GetInteger;
+   FMI2_Export fmi2GetBooleanTYPE fmi2GetBoolean;
+   FMI2_Export fmi2GetStringTYPE  fmi2GetString;
+
+   FMI2_Export fmi2SetRealTYPE    fmi2SetReal;
+   FMI2_Export fmi2SetIntegerTYPE fmi2SetInteger;
+   FMI2_Export fmi2SetBooleanTYPE fmi2SetBoolean;
+   FMI2_Export fmi2SetStringTYPE  fmi2SetString;
+
+/* Getting and setting the internal FMU state */
+   FMI2_Export fmi2GetFMUstateTYPE            fmi2GetFMUstate;
+   FMI2_Export fmi2SetFMUstateTYPE            fmi2SetFMUstate;
+   FMI2_Export fmi2FreeFMUstateTYPE           fmi2FreeFMUstate;
+   FMI2_Export fmi2SerializedFMUstateSizeTYPE fmi2SerializedFMUstateSize;
+   FMI2_Export fmi2SerializeFMUstateTYPE      fmi2SerializeFMUstate;
+   FMI2_Export fmi2DeSerializeFMUstateTYPE    fmi2DeSerializeFMUstate;
+
+/* Getting partial derivatives */
+   FMI2_Export fmi2GetDirectionalDerivativeTYPE fmi2GetDirectionalDerivative;
+
+
+/***************************************************
+Functions for FMI2 for Model Exchange
+****************************************************/
+
+/* Enter and exit the different modes */
+   FMI2_Export fmi2EnterEventModeTYPE               fmi2EnterEventMode;
+   FMI2_Export fmi2NewDiscreteStatesTYPE            fmi2NewDiscreteStates;
+   FMI2_Export fmi2EnterContinuousTimeModeTYPE      fmi2EnterContinuousTimeMode;
+   FMI2_Export fmi2CompletedIntegratorStepTYPE      fmi2CompletedIntegratorStep;
+
+/* Providing independent variables and re-initialization of caching */
+   FMI2_Export fmi2SetTimeTYPE             fmi2SetTime;
+   FMI2_Export fmi2SetContinuousStatesTYPE fmi2SetContinuousStates;
+
+/* Evaluation of the model equations */
+   FMI2_Export fmi2GetDerivativesTYPE                fmi2GetDerivatives;
+#ifdef FMU_EXPERIMENTAL
+   FMI2_Export fmi2GetSpecificDerivativesTYPE        fmi2GetSpecificDerivatives;
+#endif
+   FMI2_Export fmi2GetEventIndicatorsTYPE            fmi2GetEventIndicators;
+   FMI2_Export fmi2GetContinuousStatesTYPE           fmi2GetContinuousStates;
+   FMI2_Export fmi2GetNominalsOfContinuousStatesTYPE fmi2GetNominalsOfContinuousStates;
+
+
+/***************************************************
+Functions for FMI2 for Co-Simulation
+****************************************************/
+
+/* Simulating the slave */
+   FMI2_Export fmi2SetRealInputDerivativesTYPE  fmi2SetRealInputDerivatives;
+   FMI2_Export fmi2GetRealOutputDerivativesTYPE fmi2GetRealOutputDerivatives;
+
+   FMI2_Export fmi2DoStepTYPE     fmi2DoStep;
+   FMI2_Export fmi2CancelStepTYPE fmi2CancelStep;
+
+/* Inquire slave status */
+   FMI2_Export fmi2GetStatusTYPE        fmi2GetStatus;
+   FMI2_Export fmi2GetRealStatusTYPE    fmi2GetRealStatus;
+   FMI2_Export fmi2GetIntegerStatusTYPE fmi2GetIntegerStatus;
+   FMI2_Export fmi2GetBooleanStatusTYPE fmi2GetBooleanStatus;
+   FMI2_Export fmi2GetStringStatusTYPE  fmi2GetStringStatus;
+
+#ifdef __cplusplus
+}  /* end of extern "C" { */
+#endif
+
+#endif /* fmi2Functions_h */

+ 115 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_SEL/fmi2/fmi2TypesPlatform.h

@@ -0,0 +1,115 @@
+#ifndef fmi2TypesPlatform_h
+#define fmi2TypesPlatform_h
+
+/* Standard header file to define the argument types of the
+   functions of the Functional Mock-up Interface 2.0.
+   This header file must be utilized both by the model and
+   by the simulation engine.
+
+   Revisions:
+   - Apr.  9, 2014: all prefixes "fmi" renamed to "fmi2" (decision from April 8)
+   - Mar   31, 2014: New datatype fmiChar introduced.
+   - Feb.  17, 2013: Changed fmiTypesPlatform from "standard32" to "default".
+                     Removed fmiUndefinedValueReference since no longer needed
+                     (because every state is defined in ScalarVariables).
+   - March 20, 2012: Renamed from fmiPlatformTypes.h to fmiTypesPlatform.h
+   - Nov.  14, 2011: Use the header file "fmiPlatformTypes.h" for FMI 2.0
+                     both for "FMI for model exchange" and for "FMI for co-simulation"
+                     New types "fmiComponentEnvironment", "fmiState", and "fmiByte".
+                     The implementation of "fmiBoolean" is change from "char" to "int".
+                     The #define "fmiPlatform" changed to "fmiTypesPlatform"
+                     (in order that #define and function call are consistent)
+   - Oct.   4, 2010: Renamed header file from "fmiModelTypes.h" to fmiPlatformTypes.h"
+                     for the co-simulation interface
+   - Jan.   4, 2010: Renamed meModelTypes_h to fmiModelTypes_h (by Mauss, QTronic)
+   - Dec.  21, 2009: Changed "me" to "fmi" and "meModel" to "fmiComponent"
+                     according to meeting on Dec. 18 (by Martin Otter, DLR)
+   - Dec.   6, 2009: Added meUndefinedValueReference (by Martin Otter, DLR)
+   - Sept.  9, 2009: Changes according to FMI-meeting on July 21:
+                     Changed "version" to "platform", "standard" to "standard32",
+                     Added a precise definition of "standard32" as comment
+                     (by Martin Otter, DLR)
+   - July  19, 2009: Added "me" as prefix to file names, added meTrue/meFalse,
+                     and changed meValueReferenced from int to unsigned int
+                     (by Martin Otter, DLR).
+   - March  2, 2009: Moved enums and function pointer definitions to
+                     ModelFunctions.h (by Martin Otter, DLR).
+   - Dec.  3, 2008 : First version by Martin Otter (DLR) and
+                     Hans Olsson (Dynasim).
+
+
+   Copyright (C) 2008-2011 MODELISAR consortium,
+               2012-2013 Modelica Association Project "FMI"
+               All rights reserved.
+   This file is licensed by the copyright holders under the BSD 2-Clause License
+   (http://www.opensource.org/licenses/bsd-license.html):
+
+   ----------------------------------------------------------------------------
+   Redistribution and use in source and binary forms, with or without
+   modification, are permitted provided that the following conditions are met:
+
+   - Redistributions of source code must retain the above copyright notice,
+     this list of conditions and the following disclaimer.
+   - Redistributions in binary form must reproduce the above copyright notice,
+     this list of conditions and the following disclaimer in the documentation
+     and/or other materials provided with the distribution.
+   - Neither the name of the copyright holders nor the names of its
+     contributors may be used to endorse or promote products derived
+     from this software without specific prior written permission.
+
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+   TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+   PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
+   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+   OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+   OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+   ----------------------------------------------------------------------------
+
+   with the extension:
+
+   You may distribute or publicly perform any modification only under the
+   terms of this license.
+   (Note, this means that if you distribute a modified file,
+    the modified file must also be provided under this license).
+*/
+
+/* Platform (unique identification of this header file) */
+#define fmi2TypesPlatform "default"
+
+/* Type definitions of variables passed as arguments
+   Version "default" means:
+
+   fmi2Component           : an opaque object pointer
+   fmi2ComponentEnvironment: an opaque object pointer
+   fmi2FMUstate            : an opaque object pointer
+   fmi2ValueReference      : handle to the value of a variable
+   fmi2Real                : double precision floating-point data type
+   fmi2Integer             : basic signed integer data type
+   fmi2Boolean             : basic signed integer data type
+   fmi2Char                : character data type
+   fmi2String              : a pointer to a vector of fmi2Char characters
+                             ('\0' terminated, UTF8 encoded)
+   fmi2Byte                : smallest addressable unit of the machine, typically one byte.
+*/
+   typedef void*           fmi2Component;               /* Pointer to FMU instance       */
+   typedef void*           fmi2ComponentEnvironment;    /* Pointer to FMU environment    */
+   typedef void*           fmi2FMUstate;                /* Pointer to internal FMU state */
+   typedef unsigned int    fmi2ValueReference;
+   typedef double          fmi2Real   ;
+   typedef int             fmi2Integer;
+   typedef int             fmi2Boolean;
+   typedef char            fmi2Char;
+   typedef const fmi2Char* fmi2String;
+   typedef char            fmi2Byte;
+
+/* Values for fmi2Boolean  */
+#define fmi2True  1
+#define fmi2False 0
+
+
+#endif /* fmi2TypesPlatform_h */

BIN
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_TD/Debug/libFMI_TD.dll


+ 464 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_TD/FMI_TD.c

@@ -0,0 +1,464 @@
+/* ---------------------------------------------------------------------------*
+ * Sample implementation of an FMU - a power window controller
+ * The code is generated from a Yakindu SC
+ * ---------------------------------------------------------------------------*/
+/*
+Template for a TD FMU
+*/
+
+#define MODEL_IDENTIFIER TD
+#define MODEL_GUID "{41f87101-edf2-4eef-90f3-42db56d4565f}"
+#define FMI2_FUNCTION_PREFIX PW_TD
+
+
+#include <stdio.h>
+#include "string.h"
+#include "fmi2Functions.h"
+#include <float.h>
+#include "FMI_TD.h"
+#include <math.h>
+
+
+#define NUMBER_OF_REALS 0
+#define NUMBER_OF_STRINGS 0
+#define NUMBER_OF_BOOLEANS 6
+#define NUMBER_OF_INTEGERS 0
+
+
+#define _in_motor_up  0
+#define _in_motor_down 1
+#define _store_motor_up 2
+#define _store_motor_down 3
+#define _out_motor_up 4
+#define _out_motor_down 5
+
+/*
+ * Helper function for relative error
+ */
+ double relativeError(double a, double b){
+	return fabs((a - b) / a);
+}
+
+/*
+ * Helper function for absolute error
+ */
+ double absoluteError(double a, double b){
+	return fabs(a - b);
+}
+
+/*
+ * is_close function for double comparison
+ */
+ int is_close(double a, double b, double REL_TOL, double ABS_TOL){
+	return ((absoluteError(a,b)<ABS_TOL) && (relativeError(a,b)<REL_TOL));
+}
+
+
+fmi2Status fmi2SetDebugLogging(fmi2Component fc, fmi2Boolean loggingOn, size_t nCategories, const fmi2String categories[])
+{
+    return fmi2OK;
+}
+
+fmi2Status fmi2SetString(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, const fmi2String value[])
+{
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetString(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, fmi2String value[])
+{
+    return fmi2Error;
+}
+
+fmi2Status fmi2SetReal(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, const fmi2Real value[])
+{
+	FMUInstance* comp = (FMUInstance *)fc;
+		int i;
+	    for (i = 0; i < nvr; i++)
+		{
+	    	if(vr[i]>=5){
+	    		printf("Value reference: %d, cannot be set, it is a store element\n", vr[i]);
+	    	}else{
+	    		 printf("Value reference: %d\n", vr[i]);
+	    		 comp->r[vr[i]] = value[i];
+	    	}
+
+	        //setExposedReal(vr[i], value[i]);
+	        //comp->r[vr[i]] = value[i];
+	    }
+	    return fmi2OK;
+}
+
+fmi2Status fmi2GetReal(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, fmi2Real value[])
+{
+
+    FMUInstance* comp = (FMUInstance *)fc;
+	int i;
+    for (i = 0; i < nvr; i++)
+	{
+        value[i] = comp->r[(vr[i])];
+    }
+    return fmi2OK;
+}
+
+fmi2Status fmi2SetBoolean(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, const fmi2Boolean value[])
+{
+	FMUInstance* comp = (FMUInstance *)fc;
+	int i;
+	for (i = 0; i < nvr; i++)
+	{
+		comp->b[vr[i]] = value[i];
+	}
+    return fmi2OK;
+}
+
+fmi2Status fmi2GetBoolean(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, fmi2Boolean value[])
+{
+	FMUInstance* comp = (FMUInstance *)fc;
+	int i;
+	for (i = 0; i < nvr; i++)
+	{
+		value[i] = comp->b[vr[i]];
+	}
+    return fmi2OK;
+}
+
+fmi2Component fmi2Instantiate(fmi2String instanceName, fmi2Type fmuType, fmi2String fmuGUID, fmi2String fmuLocation, const fmi2CallbackFunctions* functions, fmi2Boolean visible, fmi2Boolean loggingOn)
+{
+
+	//Declare data structure for fmu instance
+    FMUInstance* fi;
+	printf("%s in fmiInstantiate\n",instanceName);
+
+    //Perform checks on passed callback functions
+    if (loggingOn) {
+
+        if (!functions->logger);
+        //return NULL;
+	}
+    //Check for instanceName
+    if (!instanceName || strlen(instanceName)==0) {
+
+        // print (and/or log) instanceName is missing
+        //return NULL;
+    }
+    //Check passed GUID to defined model GUID
+    if (strcmp(fmuGUID, MODEL_GUID))
+	{
+        // print (and/or log) GUID doesn't match
+        //return NULL;
+    }
+
+    //Allocate fmu instance Memory
+    // TODO check if "canNotUseMemoryManagementFunctions == true/false". If false memory allocation not possible
+    fi = (FMUInstance *)functions->allocateMemory(1, sizeof(FMUInstance));
+    fi->functions = functions;
+    if (fi) {
+        // Think about what to do with variable values. Using these structs and pointers slows down simulation computations. Maybe only necessary for input, output and tunable parameters??
+        fi->r = functions->allocateMemory(NUMBER_OF_REALS, sizeof(fmi2Real));
+        fi->i = functions->allocateMemory(NUMBER_OF_INTEGERS, sizeof(fmi2Integer));
+        fi->b = functions->allocateMemory(NUMBER_OF_BOOLEANS, sizeof(fmi2Boolean));
+        fi->s = functions->allocateMemory(NUMBER_OF_STRINGS,  sizeof(fmi2String));
+    } // variables in predefined arrays (performance issue) --> makes multiple instances of fmu impossible
+
+
+    fi->instanceName = functions->allocateMemory(1 + strlen(instanceName), sizeof(char));
+    fi->GUID = functions->allocateMemory(1 + strlen(fmuGUID), sizeof(char));
+
+    strcpy((char*)fi->instanceName, instanceName);
+    strcpy((char*)fi->GUID, fmuGUID);
+    fi->functions = functions;
+    fi->loggingOn = loggingOn;
+    fi->isVisible = visible;
+    fi->state = fmuInstantiated;
+    return fi;
+}
+
+fmi2Status fmi2SetupExperiment(fmi2Component fc, fmi2Boolean toleranceDefined, fmi2Real tolerance,
+                            fmi2Real startTime, fmi2Boolean stopTimeDefined, fmi2Real stopTime) {
+
+
+    FMUInstance* fi = (FMUInstance*) fc;
+	printf("%s in fmiSetupExperiment\n",fi->instanceName);
+	if (fi->state != fmuInstantiated)
+	{
+		printf("fmu: %s was not instatiated before calling fmiSetupExperiment\n", fi->instanceName);
+		return fmi2Error;
+	}
+	fi->currentTime = startTime;
+	fi->stopTimeDefined = stopTimeDefined;
+	fi->toleranceDefined = toleranceDefined;
+	if (stopTimeDefined)
+	{
+		fi->stopTime = stopTime;
+	}
+
+	if (toleranceDefined)
+	{
+		fi->tolerance = tolerance;
+	}
+	//TODO
+	//fi->stepSize = getStepSize();
+	fi->state = fmuExperimentSettedUp;
+    return fmi2OK;
+}
+
+fmi2Status fmi2EnterInitializationMode(fmi2Component fc)
+{
+	FMUInstance* fi = (FMUInstance*) fc;
+	printf("%s in fmiEnterInitializationMode\n",fi->instanceName);
+	if (fi->state != fmuExperimentSettedUp)
+	{
+		printf("fmu: %s experiment was not set-up before calling fmiEnterInitializationMode\n", fi->instanceName);
+		return fmi2Error;
+	}
+
+    fi->state = fmuInitMode;
+    return fmi2OK;
+}
+
+fmi2Status fmi2ExitInitializationMode(fmi2Component fc)
+{
+	FMUInstance* fi = (FMUInstance*) fc;
+	fmi2Status initStatus = fmi2OK;
+	printf("%s in fmiExitInitializationMode\n",fi->instanceName);
+	if (fi->state != fmuInitMode)
+	{
+		printf("fmu: %s did not enter Initialization Mode before calling fmiExitInitializationMode\n", fi->instanceName);
+		return fmi2Error;
+	}
+	// TODO
+	//initStatus = calculateInitialUnknownValues();
+	//initialize();
+    fi->state = fmuInitialized;
+    return initStatus;
+}
+
+fmi2Status fmi2DoStep(fmi2Component fc , fmi2Real currentCommPoint, fmi2Real commStepSize, fmi2Boolean noPrevFMUState)
+{
+	FMUInstance* fi = (FMUInstance *)fc;
+	fmi2Status simStatus = fmi2OK;
+    printf("%s in fmiDoStep()\n",fi->instanceName);
+    fi->b[_out_motor_down] = fi->b[_store_motor_down];
+    fi->b[_out_motor_up] = fi->b[_store_motor_up];
+    fi->b[_store_motor_down] = fi->b[_in_motor_down];
+    fi->b[_store_motor_up] = fi->b[_in_motor_up];
+    fi->currentTime = currentCommPoint + commStepSize;
+	return simStatus;
+}
+
+fmi2Status fmi2Terminate(fmi2Component fc)
+{
+	FMUInstance* fi = (FMUInstance *)fc;
+	printf("%s in fmiTerminate\n",fi->instanceName);
+	// do check if fi may be terminated
+	fi->state = fmuTerminated;
+    return fmi2OK;
+}
+
+
+void fmi2FreeInstance(fmi2Component fc)
+{
+
+	FMUInstance* fi = (FMUInstance*) fc;
+	printf("%s in fmiFreeInstance\n",fi->instanceName);
+
+    if (fi) {
+
+        fi->functions->freeMemory(fi->r);
+        fi->functions->freeMemory(fi->i);
+        fi->functions->freeMemory(fi->b);
+        fi->functions->freeMemory(fi->s);// TODO has to be done with loop
+		fi->functions->freeMemory((void*)fi->instanceName);
+		fi->functions->freeMemory((void*)fi->GUID);
+		fi->functions->freeMemory((void*)fi);
+
+    }
+}
+
+//To be implemented
+
+const char* fmi2GetVersion() {
+	printf("Function fmiGetVersion not supported\n");
+    return NULL;
+}
+
+const char* fmi2GetTypesPlatform() {
+	printf("Function fmiGetTypesPlatform not supported\n");
+    return NULL;
+}
+
+fmi2Status fmi2Reset(fmi2Component fc)
+{
+	printf("Function fmiReset not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2SetInteger(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, const fmi2Integer value[])
+{
+    printf("Function fmiSetInteger not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetInteger(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, fmi2Integer value[])
+{
+    printf("Function fmiGetInteger not supported\n");
+    return fmi2Error;
+}
+
+
+/*******OWN IMPLEMENTATION OF Get/Set FMU state*******/
+fmi2Status fmi2GetFMUstate (fmi2Component c, fmi2FMUstate* FMUstate) {
+    FMUInstance* orig = (FMUInstance*)c;
+    FMUInstance* fi = (FMUInstance *)FMUstate;
+    fi = orig->functions->allocateMemory(1, sizeof(FMUInstance));
+    *FMUstate = fi;
+    if (fi) {
+        // Think about what to do with variable values. Using these structs and pointers slows down simulation computations. Maybe only necessary for input, output and tunable parameters??
+        fi->r = orig->functions->allocateMemory(NUMBER_OF_REALS, sizeof(fmi2Real));
+        fi->i = orig->functions->allocateMemory(NUMBER_OF_INTEGERS, sizeof(fmi2Integer));
+        fi->b = orig->functions->allocateMemory(NUMBER_OF_BOOLEANS, sizeof(fmi2Boolean));
+        fi->s = orig->functions->allocateMemory(NUMBER_OF_STRINGS,  sizeof(fmi2String));
+
+    } // variables in predefined arrays (performance issue) --> makes multiple instances of fmu impossible
+    fi->instanceName = orig->functions->allocateMemory(1 + strlen(orig->instanceName), sizeof(char));
+    fi->GUID = orig->functions->allocateMemory(1 + strlen(orig->GUID), sizeof(char));
+
+    strcpy((char *)fi->instanceName, (char *)orig->instanceName);
+    strcpy((char *)fi->GUID, (char *)orig->GUID);
+    fi->functions = orig->functions;
+    fi->loggingOn = orig->loggingOn;
+    fi->isVisible = orig->isVisible;
+    fi->state = orig->state;
+    fi->stepSize = orig->stepSize;
+    fi->startTime = orig->startTime;
+    fi->stopTime = orig->stopTime;
+	fi->currentTime = orig->currentTime;
+	//copy r
+	int i=0;
+	for (i=0; i< NUMBER_OF_REALS;i++){
+	    printf("Setting real: %i %f\n", i, orig->r[i]);
+        fi->r[i] = orig->r[i];
+        printf("Setted real: %i %f\n", i, fi->r[i]);
+	}
+	//copy s
+	for (i=0; i< NUMBER_OF_STRINGS;i++){
+        fi->s[i] = orig->s[i];
+	}
+	//copy i
+    for (i=0; i< NUMBER_OF_INTEGERS;i++){
+        fi->i[i] = orig->i[i];
+	}
+	//copy b
+	for (i=0; i< NUMBER_OF_BOOLEANS;i++){
+        fi->b[i] = orig->b[i];
+	}
+    return fmi2OK;
+}
+
+
+fmi2Status fmi2SetFMUstate (fmi2Component c, fmi2FMUstate FMUstate) {
+    FMUInstance* orig = (FMUInstance*)FMUstate;
+    FMUInstance* fi = (FMUInstance*)c;
+    //set time etc correct, name and GUID should still be ok ;-)
+    printf("setting time values from %f to %f\n", fi->currentTime, orig->currentTime);
+    fi->state = orig->state;
+    fi->stepSize = orig->stepSize;
+    fi->startTime = orig->startTime;
+    fi->stopTime = orig->stopTime;
+	fi->currentTime = orig->currentTime;
+	printf("setting real values\n");
+	//copy r
+	int i=0;
+	for (i=0; i< NUMBER_OF_REALS;i++){
+        fi->r[i] = orig->r[i];
+	}
+	printf("setting string values\n");
+	//copy s
+	for (i=0; i< NUMBER_OF_STRINGS;i++){
+
+        fi->s[i] = orig->s[i];
+	}
+	//copy i
+    for (i=0; i< NUMBER_OF_INTEGERS;i++){
+        fi->i[i] = orig->i[i];
+	}
+	//copy b
+	for (i=0; i< NUMBER_OF_BOOLEANS;i++){
+        fi->b[i] = orig->b[i];
+	}
+    return fmi2OK;
+
+
+}
+/****************************************************/
+
+fmi2Status fmi2FreeFMUstate(fmi2Component c, fmi2FMUstate* FMUstate) {
+    printf("Function fmiFreeFMUstate not supported\n");
+    return fmi2Error;
+}
+fmi2Status fmi2SerializedFMUstateSize(fmi2Component c, fmi2FMUstate FMUstate, size_t *size) {
+    printf("Function fmiSerializedFMUstateSize not supported\n");
+    return fmi2Error;
+}
+fmi2Status fmi2SerializeFMUstate (fmi2Component c, fmi2FMUstate FMUstate, fmi2Byte serializedState[], size_t size) {
+    printf("Function fmiSerializeFMUstate not supported\n");
+    return fmi2Error;
+}
+fmi2Status fmi2DeSerializeFMUstate (fmi2Component c, const fmi2Byte serializedState[], size_t size, fmi2FMUstate* FMUstate) {
+    printf("Function fmiDeSerializeFMUstate not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetDirectionalDerivative(fmi2Component c, const fmi2ValueReference vUnknown_ref[], size_t nUnknown,
+                const fmi2ValueReference vKnown_ref[] , size_t nKnown, const fmi2Real dvKnown[], fmi2Real dvUnknown[]) {
+    printf("Function fmiGetDirectionalDerivative not supported\n");
+    return fmi2Error;
+}
+
+
+fmi2Status fmi2SetRealInputDerivatives(fmi2Component c, const fmi2ValueReference vr[], size_t nvr,
+                                     const fmi2Integer order[], const fmi2Real value[]) {
+    printf("Function fmiGetDirectionalDerivative not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetRealOutputDerivatives(fmi2Component c, const fmi2ValueReference vr[], size_t nvr,
+                                      const fmi2Integer order[], fmi2Real value[]) {
+    printf("Function fmiGetDirectionalDerivative not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2CancelStep(fmi2Component c) {
+    printf("Function fmiGetDirectionalDerivative not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetStatus(fmi2Component c, const fmi2StatusKind s, fmi2Status *value) {
+    printf("Function fmiGetStatus not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetRealStatus(fmi2Component c, const fmi2StatusKind s, fmi2Real *value) {
+    if(s == fmi2LastSuccessfulTime){
+        FMUInstance* comp = (FMUInstance*) c;
+        *value = comp->currentTime;
+        return fmi2OK;
+    }
+    printf("Function fmiGetRealStatus not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetIntegerStatus(fmi2Component c, const fmi2StatusKind s, fmi2Integer *value) {
+    printf("Function fmiGetIntegerStatus not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetBooleanStatus(fmi2Component c, const fmi2StatusKind s, fmi2Boolean *value) {
+    printf("Function fmiGetBooleanStatus not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetStringStatus(fmi2Component c, const fmi2StatusKind s, fmi2String *value) {
+    printf("Function fmiGetStringStatus not supported\n");
+    return fmi2Error;
+}

+ 51 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_TD/FMI_TD.h

@@ -0,0 +1,51 @@
+/*
+ * PW_Controller.h
+ *
+ *  Created on: Jan 25, 2017
+ *      Author: Joachim
+ */
+
+#ifndef FMI_TD_H_
+#define FMI_TD_H_
+
+
+ double relativeError(double a, double b);
+ double absoluteError(double a, double b);
+ int is_close(double a, double b, double REL_TOL, double ABS_TOL);
+
+
+typedef enum {
+    fmuInstantiated = 0,
+    fmuInitMode  = 1,
+	fmuInitialized = 2,
+    fmuTerminated   = 3,
+    fmuError        = 4,
+    fmuExperimentSettedUp = 5
+} FMUState;
+
+
+
+typedef struct {
+	fmi2Real    *r;
+    fmi2Integer *i;
+    fmi2Boolean *b;
+    fmi2String  *s;
+    fmi2Boolean isVisible;
+    fmi2String instanceName;
+    fmi2String GUID;
+    const fmi2CallbackFunctions* functions;
+    fmi2Boolean loggingOn;
+    FMUState state;
+	fmi2Real stepSize;
+    fmi2Real startTime;
+    fmi2Real stopTime;
+	fmi2Real currentTime;
+    fmi2Boolean stopTimeDefined;
+    fmi2Real tolerance;
+    fmi2Boolean toleranceDefined;
+} FMUInstance; // At the moment, most of the variables not really used since multiple instances of an FMU are not supported at the moment (performance issues)
+
+
+
+
+#endif /* FMI_TD_H_ */

+ 247 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_TD/fmi2/fmi2FunctionTypes.h

@@ -0,0 +1,247 @@
+#ifndef fmi2FunctionTypes_h
+#define fmi2FunctionTypes_h
+
+#include "fmi2TypesPlatform.h"
+
+/* This header file must be utilized when compiling an FMU or an FMI master.
+   It declares data and function types for FMI 2.0
+
+   Revisions:
+   - Apr.  9, 2014: all prefixes "fmi" renamed to "fmi2" (decision from April 8)
+   - Apr.  3, 2014: Added #include <stddef.h> for size_t definition
+   - Mar. 27, 2014: Added #include "fmiTypesPlatform.h" (#179)
+   - Mar. 26, 2014: Introduced function argument "void" for the functions (#171)
+                      fmiGetTypesPlatformTYPE and fmiGetVersionTYPE
+   - Oct. 11, 2013: Functions of ModelExchange and CoSimulation merged:
+                      fmiInstantiateModelTYPE , fmiInstantiateSlaveTYPE  -> fmiInstantiateTYPE
+                      fmiFreeModelInstanceTYPE, fmiFreeSlaveInstanceTYPE -> fmiFreeInstanceTYPE
+                      fmiEnterModelInitializationModeTYPE, fmiEnterSlaveInitializationModeTYPE -> fmiEnterInitializationModeTYPE
+                      fmiExitModelInitializationModeTYPE , fmiExitSlaveInitializationModeTYPE  -> fmiExitInitializationModeTYPE
+                      fmiTerminateModelTYPE , fmiTerminateSlaveTYPE  -> fmiTerminate
+                      fmiResetSlave -> fmiReset (now also for ModelExchange and not only for CoSimulation)
+                    Functions renamed
+                      fmiUpdateDiscreteStatesTYPE -> fmiNewDiscreteStatesTYPE
+                    Renamed elements of the enumeration fmiEventInfo
+                      upcomingTimeEvent             -> nextEventTimeDefined // due to generic naming scheme: varDefined + var
+                      newUpdateDiscreteStatesNeeded -> newDiscreteStatesNeeded;
+   - June 13, 2013: Changed type fmiEventInfo
+                    Functions removed:
+                       fmiInitializeModelTYPE
+                       fmiEventUpdateTYPE
+                       fmiCompletedEventIterationTYPE
+                       fmiInitializeSlaveTYPE
+                    Functions added:
+                       fmiEnterModelInitializationModeTYPE
+                       fmiExitModelInitializationModeTYPE
+                       fmiEnterEventModeTYPE
+                       fmiUpdateDiscreteStatesTYPE
+                       fmiEnterContinuousTimeModeTYPE
+                       fmiEnterSlaveInitializationModeTYPE;
+                       fmiExitSlaveInitializationModeTYPE;
+   - Feb. 17, 2013: Added third argument to fmiCompletedIntegratorStepTYPE
+                    Changed function name "fmiTerminateType" to "fmiTerminateModelType" (due to #113)
+                    Changed function name "fmiGetNominalContinuousStateTYPE" to
+                                          "fmiGetNominalsOfContinuousStatesTYPE"
+                    Removed fmiGetStateValueReferencesTYPE.
+   - Nov. 14, 2011: First public Version
+
+
+   Copyright (C) 2011 MODELISAR consortium,
+               2012-2013 Modelica Association Project "FMI"
+               All rights reserved.
+   This file is licensed by the copyright holders under the BSD 2-Clause License
+   (http://www.opensource.org/licenses/bsd-license.html):
+
+   ----------------------------------------------------------------------------
+   Redistribution and use in source and binary forms, with or without
+   modification, are permitted provided that the following conditions are met:
+
+   - Redistributions of source code must retain the above copyright notice,
+     this list of conditions and the following disclaimer.
+   - Redistributions in binary form must reproduce the above copyright notice,
+     this list of conditions and the following disclaimer in the documentation
+     and/or other materials provided with the distribution.
+   - Neither the name of the copyright holders nor the names of its
+     contributors may be used to endorse or promote products derived
+     from this software without specific prior written permission.
+
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+   TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+   PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
+   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+   OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+   OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+   ----------------------------------------------------------------------------
+
+   with the extension:
+
+   You may distribute or publicly perform any modification only under the
+   terms of this license.
+   (Note, this means that if you distribute a modified file,
+    the modified file must also be provided under this license).
+*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* make sure all compiler use the same alignment policies for structures */
+#if defined _MSC_VER || defined __GNUC__
+#pragma pack(push,8)
+#endif
+
+/* Include stddef.h, in order that size_t etc. is defined */
+#include <stddef.h>
+
+
+/* Type definitions */
+typedef enum {
+    fmi2OK,
+    fmi2Warning,
+    fmi2Discard,
+    fmi2Error,
+    fmi2Fatal,
+    fmi2Pending
+} fmi2Status;
+
+typedef enum {
+    fmi2ModelExchange,
+    fmi2CoSimulation
+} fmi2Type;
+
+typedef enum {
+    fmi2DoStepStatus,
+    fmi2PendingStatus,
+    fmi2LastSuccessfulTime,
+    fmi2Terminated
+} fmi2StatusKind;
+
+typedef void      (*fmi2CallbackLogger)        (fmi2ComponentEnvironment, fmi2String, fmi2Status, fmi2String, fmi2String, ...);
+typedef void*     (*fmi2CallbackAllocateMemory)(size_t, size_t);
+typedef void      (*fmi2CallbackFreeMemory)    (void*);
+typedef void      (*fmi2StepFinished)          (fmi2ComponentEnvironment, fmi2Status);
+
+typedef struct {
+   const fmi2CallbackLogger         logger;
+   const fmi2CallbackAllocateMemory allocateMemory;
+   const fmi2CallbackFreeMemory     freeMemory;
+   const fmi2StepFinished           stepFinished;
+   const fmi2ComponentEnvironment   componentEnvironment;
+} fmi2CallbackFunctions;
+
+typedef struct {
+   fmi2Boolean newDiscreteStatesNeeded;
+   fmi2Boolean terminateSimulation;
+   fmi2Boolean nominalsOfContinuousStatesChanged;
+   fmi2Boolean valuesOfContinuousStatesChanged;
+   fmi2Boolean nextEventTimeDefined;
+   fmi2Real    nextEventTime;
+} fmi2EventInfo;
+
+
+/* reset alignment policy to the one set before reading this file */
+#if defined _MSC_VER || defined __GNUC__
+#pragma pack(pop)
+#endif
+
+
+/* Define fmi2 function pointer types to simplify dynamic loading */
+
+/***************************************************
+Types for Common Functions
+****************************************************/
+
+/* Inquire version numbers of header files and setting logging status */
+   typedef const char* fmi2GetTypesPlatformTYPE(void);
+   typedef const char* fmi2GetVersionTYPE(void);
+   typedef fmi2Status  fmi2SetDebugLoggingTYPE(fmi2Component, fmi2Boolean, size_t, const fmi2String[]);
+
+/* Creation and destruction of FMU instances and setting debug status */
+   typedef fmi2Component fmi2InstantiateTYPE (fmi2String, fmi2Type, fmi2String, fmi2String, const fmi2CallbackFunctions*, fmi2Boolean, fmi2Boolean);
+   typedef void          fmi2FreeInstanceTYPE(fmi2Component);
+
+/* Enter and exit initialization mode, terminate and reset */
+   typedef fmi2Status fmi2SetupExperimentTYPE        (fmi2Component, fmi2Boolean, fmi2Real, fmi2Real, fmi2Boolean, fmi2Real);
+   typedef fmi2Status fmi2EnterInitializationModeTYPE(fmi2Component);
+   typedef fmi2Status fmi2ExitInitializationModeTYPE (fmi2Component);
+   typedef fmi2Status fmi2TerminateTYPE              (fmi2Component);
+   typedef fmi2Status fmi2ResetTYPE                  (fmi2Component);
+
+/* Getting and setting variable values */
+   typedef fmi2Status fmi2GetRealTYPE   (fmi2Component, const fmi2ValueReference[], size_t, fmi2Real   []);
+   typedef fmi2Status fmi2GetIntegerTYPE(fmi2Component, const fmi2ValueReference[], size_t, fmi2Integer[]);
+   typedef fmi2Status fmi2GetBooleanTYPE(fmi2Component, const fmi2ValueReference[], size_t, fmi2Boolean[]);
+   typedef fmi2Status fmi2GetStringTYPE (fmi2Component, const fmi2ValueReference[], size_t, fmi2String []);
+
+   typedef fmi2Status fmi2SetRealTYPE   (fmi2Component, const fmi2ValueReference[], size_t, const fmi2Real   []);
+   typedef fmi2Status fmi2SetIntegerTYPE(fmi2Component, const fmi2ValueReference[], size_t, const fmi2Integer[]);
+   typedef fmi2Status fmi2SetBooleanTYPE(fmi2Component, const fmi2ValueReference[], size_t, const fmi2Boolean[]);
+   typedef fmi2Status fmi2SetStringTYPE (fmi2Component, const fmi2ValueReference[], size_t, const fmi2String []);
+
+/* Getting and setting the internal FMU state */
+   typedef fmi2Status fmi2GetFMUstateTYPE           (fmi2Component, fmi2FMUstate*);
+   typedef fmi2Status fmi2SetFMUstateTYPE           (fmi2Component, fmi2FMUstate);
+   typedef fmi2Status fmi2FreeFMUstateTYPE          (fmi2Component, fmi2FMUstate*);
+   typedef fmi2Status fmi2SerializedFMUstateSizeTYPE(fmi2Component, fmi2FMUstate, size_t*);
+   typedef fmi2Status fmi2SerializeFMUstateTYPE     (fmi2Component, fmi2FMUstate, fmi2Byte[], size_t);
+   typedef fmi2Status fmi2DeSerializeFMUstateTYPE   (fmi2Component, const fmi2Byte[], size_t, fmi2FMUstate*);
+
+/* Getting partial derivatives */
+   typedef fmi2Status fmi2GetDirectionalDerivativeTYPE(fmi2Component, const fmi2ValueReference[], size_t,
+                                                                   const fmi2ValueReference[], size_t,
+                                                                   const fmi2Real[], fmi2Real[]);
+
+/***************************************************
+Types for Functions for FMI2 for Model Exchange
+****************************************************/
+
+/* Enter and exit the different modes */
+   typedef fmi2Status fmi2EnterEventModeTYPE         (fmi2Component);
+   typedef fmi2Status fmi2NewDiscreteStatesTYPE      (fmi2Component, fmi2EventInfo*);
+   typedef fmi2Status fmi2EnterContinuousTimeModeTYPE(fmi2Component);
+   typedef fmi2Status fmi2CompletedIntegratorStepTYPE(fmi2Component, fmi2Boolean, fmi2Boolean*, fmi2Boolean*);
+
+/* Providing independent variables and re-initialization of caching */
+   typedef fmi2Status fmi2SetTimeTYPE            (fmi2Component, fmi2Real);
+   typedef fmi2Status fmi2SetContinuousStatesTYPE(fmi2Component, const fmi2Real[], size_t);
+
+/* Evaluation of the model equations */
+   typedef fmi2Status fmi2GetDerivativesTYPE               (fmi2Component, fmi2Real[], size_t);
+#ifdef FMU_EXPERIMENTAL
+   typedef fmi2Status fmi2GetSpecificDerivativesTYPE       (fmi2Component, fmi2Real[], const fmi2ValueReference [], size_t);
+#endif
+
+   typedef fmi2Status fmi2GetEventIndicatorsTYPE           (fmi2Component, fmi2Real[], size_t);
+   typedef fmi2Status fmi2GetContinuousStatesTYPE          (fmi2Component, fmi2Real[], size_t);
+   typedef fmi2Status fmi2GetNominalsOfContinuousStatesTYPE(fmi2Component, fmi2Real[], size_t);
+
+
+/***************************************************
+Types for Functions for FMI2 for Co-Simulation
+****************************************************/
+
+/* Simulating the slave */
+   typedef fmi2Status fmi2SetRealInputDerivativesTYPE (fmi2Component, const fmi2ValueReference [], size_t, const fmi2Integer [], const fmi2Real []);
+   typedef fmi2Status fmi2GetRealOutputDerivativesTYPE(fmi2Component, const fmi2ValueReference [], size_t, const fmi2Integer [], fmi2Real []);
+
+   typedef fmi2Status fmi2DoStepTYPE     (fmi2Component, fmi2Real, fmi2Real, fmi2Boolean);
+   typedef fmi2Status fmi2CancelStepTYPE (fmi2Component);
+
+/* Inquire slave status */
+   typedef fmi2Status fmi2GetStatusTYPE       (fmi2Component, const fmi2StatusKind, fmi2Status* );
+   typedef fmi2Status fmi2GetRealStatusTYPE   (fmi2Component, const fmi2StatusKind, fmi2Real*   );
+   typedef fmi2Status fmi2GetIntegerStatusTYPE(fmi2Component, const fmi2StatusKind, fmi2Integer*);
+   typedef fmi2Status fmi2GetBooleanStatusTYPE(fmi2Component, const fmi2StatusKind, fmi2Boolean*);
+   typedef fmi2Status fmi2GetStringStatusTYPE (fmi2Component, const fmi2StatusKind, fmi2String* );
+
+
+#ifdef __cplusplus
+}  /* end of extern "C" { */
+#endif
+
+#endif /* fmi2FunctionTypes_h */

+ 339 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_TD/fmi2/fmi2Functions.h

@@ -0,0 +1,339 @@
+#ifndef fmi2Functions_h
+#define fmi2Functions_h
+
+/* This header file must be utilized when compiling a FMU.
+   It defines all functions of the
+         FMI 2.0 Model Exchange and Co-Simulation Interface.
+
+   In order to have unique function names even if several FMUs
+   are compiled together (e.g. for embedded systems), every "real" function name
+   is constructed by prepending the function name by "FMI2_FUNCTION_PREFIX".
+   Therefore, the typical usage is:
+
+      #define FMI2_FUNCTION_PREFIX MyModel_
+      #include "fmi2Functions.h"
+
+   As a result, a function that is defined as "fmi2GetDerivatives" in this header file,
+   is actually getting the name "MyModel_fmi2GetDerivatives".
+
+   This only holds if the FMU is shipped in C source code, or is compiled in a
+   static link library. For FMUs compiled in a DLL/sharedObject, the "actual" function
+   names are used and "FMI2_FUNCTION_PREFIX" must not be defined.
+
+   Revisions:
+   - Apr.  9, 2014: all prefixes "fmi" renamed to "fmi2" (decision from April 8)
+   - Mar. 26, 2014: FMI_Export set to empty value if FMI_Export and FMI_FUNCTION_PREFIX
+                    are not defined (#173)
+   - Oct. 11, 2013: Functions of ModelExchange and CoSimulation merged:
+                      fmiInstantiateModel , fmiInstantiateSlave  -> fmiInstantiate
+                      fmiFreeModelInstance, fmiFreeSlaveInstance -> fmiFreeInstance
+                      fmiEnterModelInitializationMode, fmiEnterSlaveInitializationMode -> fmiEnterInitializationMode
+                      fmiExitModelInitializationMode , fmiExitSlaveInitializationMode  -> fmiExitInitializationMode
+                      fmiTerminateModel, fmiTerminateSlave  -> fmiTerminate
+                      fmiResetSlave -> fmiReset (now also for ModelExchange and not only for CoSimulation)
+                    Functions renamed:
+                      fmiUpdateDiscreteStates -> fmiNewDiscreteStates
+   - June 13, 2013: Functions removed:
+                       fmiInitializeModel
+                       fmiEventUpdate
+                       fmiCompletedEventIteration
+                       fmiInitializeSlave
+                    Functions added:
+                       fmiEnterModelInitializationMode
+                       fmiExitModelInitializationMode
+                       fmiEnterEventMode
+                       fmiUpdateDiscreteStates
+                       fmiEnterContinuousTimeMode
+                       fmiEnterSlaveInitializationMode;
+                       fmiExitSlaveInitializationMode;
+   - Feb. 17, 2013: Portability improvements:
+                       o DllExport changed to FMI_Export
+                       o FUNCTION_PREFIX changed to FMI_FUNCTION_PREFIX
+                       o Allow undefined FMI_FUNCTION_PREFIX (meaning no prefix is used)
+                    Changed function name "fmiTerminate" to "fmiTerminateModel" (due to #113)
+                    Changed function name "fmiGetNominalContinuousState" to
+                                          "fmiGetNominalsOfContinuousStates"
+                    Removed fmiGetStateValueReferences.
+   - Nov. 14, 2011: Adapted to FMI 2.0:
+                       o Split into two files (fmiFunctions.h, fmiTypes.h) in order
+                         that code that dynamically loads an FMU can directly
+                         utilize the header files).
+                       o Added C++ encapsulation of C-part, in order that the header
+                         file can be directly utilized in C++ code.
+                       o fmiCallbackFunctions is passed as pointer to fmiInstantiateXXX
+                       o stepFinished within fmiCallbackFunctions has as first
+                         argument "fmiComponentEnvironment" and not "fmiComponent".
+                       o New functions to get and set the complete FMU state
+                         and to compute partial derivatives.
+   - Nov.  4, 2010: Adapted to specification text:
+                       o fmiGetModelTypesPlatform renamed to fmiGetTypesPlatform
+                       o fmiInstantiateSlave: Argument GUID     replaced by fmuGUID
+                                              Argument mimetype replaced by mimeType
+                       o tabs replaced by spaces
+   - Oct. 16, 2010: Functions for FMI for Co-simulation added
+   - Jan. 20, 2010: stateValueReferencesChanged added to struct fmiEventInfo (ticket #27)
+                    (by M. Otter, DLR)
+                    Added WIN32 pragma to define the struct layout (ticket #34)
+                    (by J. Mauss, QTronic)
+   - Jan.  4, 2010: Removed argument intermediateResults from fmiInitialize
+                    Renamed macro fmiGetModelFunctionsVersion to fmiGetVersion
+                    Renamed macro fmiModelFunctionsVersion to fmiVersion
+                    Replaced fmiModel by fmiComponent in decl of fmiInstantiateModel
+                    (by J. Mauss, QTronic)
+   - Dec. 17, 2009: Changed extension "me" to "fmi" (by Martin Otter, DLR).
+   - Dez. 14, 2009: Added eventInfo to meInitialize and added
+                    meGetNominalContinuousStates (by Martin Otter, DLR)
+   - Sept. 9, 2009: Added DllExport (according to Peter Nilsson's suggestion)
+                    (by A. Junghanns, QTronic)
+   - Sept. 9, 2009: Changes according to FMI-meeting on July 21:
+                    meInquireModelTypesVersion     -> meGetModelTypesPlatform
+                    meInquireModelFunctionsVersion -> meGetModelFunctionsVersion
+                    meSetStates                    -> meSetContinuousStates
+                    meGetStates                    -> meGetContinuousStates
+                    removal of meInitializeModelClass
+                    removal of meGetTime
+                    change of arguments of meInstantiateModel
+                    change of arguments of meCompletedIntegratorStep
+                    (by Martin Otter, DLR):
+   - July 19, 2009: Added "me" as prefix to file names (by Martin Otter, DLR).
+   - March 2, 2009: Changed function definitions according to the last design
+                    meeting with additional improvements (by Martin Otter, DLR).
+   - Dec. 3 , 2008: First version by Martin Otter (DLR) and Hans Olsson (Dynasim).
+
+   Copyright (C) 2008-2011 MODELISAR consortium,
+               2012-2013 Modelica Association Project "FMI"
+               All rights reserved.
+   This file is licensed by the copyright holders under the BSD 2-Clause License
+   (http://www.opensource.org/licenses/bsd-license.html):
+
+   ----------------------------------------------------------------------------
+   Redistribution and use in source and binary forms, with or without
+   modification, are permitted provided that the following conditions are met:
+
+   - Redistributions of source code must retain the above copyright notice,
+     this list of conditions and the following disclaimer.
+   - Redistributions in binary form must reproduce the above copyright notice,
+     this list of conditions and the following disclaimer in the documentation
+     and/or other materials provided with the distribution.
+   - Neither the name of the copyright holders nor the names of its
+     contributors may be used to endorse or promote products derived
+     from this software without specific prior written permission.
+
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+   TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+   PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
+   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+   OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+   OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+   ----------------------------------------------------------------------------
+
+   with the extension:
+
+   You may distribute or publicly perform any modification only under the
+   terms of this license.
+   (Note, this means that if you distribute a modified file,
+    the modified file must also be provided under this license).
+*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "fmi2TypesPlatform.h"
+#include "fmi2FunctionTypes.h"
+#include <stdlib.h>
+
+
+/*
+  Export FMI2 API functions on Windows and under GCC.
+  If custom linking is desired then the FMI2_Export must be
+  defined before including this file. For instance,
+  it may be set to __declspec(dllimport).
+*/
+#if !defined(FMI2_Export)
+  #if !defined(FMI2_FUNCTION_PREFIX)
+    #if defined _WIN32 || defined __CYGWIN__
+     /* Note: both gcc & MSVC on Windows support this syntax. */
+        #define FMI2_Export __declspec(dllexport)
+    #else
+      #if __GNUC__ >= 4
+        #define FMI2_Export __attribute__ ((visibility ("default")))
+      #else
+        #define FMI2_Export
+      #endif
+    #endif
+  #else
+    #define FMI2_Export
+  #endif
+#endif
+
+/* Macros to construct the real function name
+   (prepend function name by FMI2_FUNCTION_PREFIX) */
+#if defined(FMI2_FUNCTION_PREFIX)
+  #define fmi2Paste(a,b)     a ## b
+  #define fmi2PasteB(a,b)    fmi2Paste(a,b)
+  #define fmi2FullName(name) fmi2PasteB(FMI2_FUNCTION_PREFIX, name)
+#else
+  #define fmi2FullName(name) name
+#endif
+
+/***************************************************
+Common Functions
+****************************************************/
+#define fmi2GetTypesPlatform         fmi2FullName(fmi2GetTypesPlatform)
+#define fmi2GetVersion               fmi2FullName(fmi2GetVersion)
+#define fmi2SetDebugLogging          fmi2FullName(fmi2SetDebugLogging)
+#define fmi2Instantiate              fmi2FullName(fmi2Instantiate)
+#define fmi2FreeInstance             fmi2FullName(fmi2FreeInstance)
+#define fmi2SetupExperiment          fmi2FullName(fmi2SetupExperiment)
+#define fmi2EnterInitializationMode  fmi2FullName(fmi2EnterInitializationMode)
+#define fmi2ExitInitializationMode   fmi2FullName(fmi2ExitInitializationMode)
+#define fmi2Terminate                fmi2FullName(fmi2Terminate)
+#define fmi2Reset                    fmi2FullName(fmi2Reset)
+#define fmi2GetReal                  fmi2FullName(fmi2GetReal)
+#define fmi2GetInteger               fmi2FullName(fmi2GetInteger)
+#define fmi2GetBoolean               fmi2FullName(fmi2GetBoolean)
+#define fmi2GetString                fmi2FullName(fmi2GetString)
+#define fmi2SetReal                  fmi2FullName(fmi2SetReal)
+#define fmi2SetInteger               fmi2FullName(fmi2SetInteger)
+#define fmi2SetBoolean               fmi2FullName(fmi2SetBoolean)
+#define fmi2SetString                fmi2FullName(fmi2SetString)
+#define fmi2GetFMUstate              fmi2FullName(fmi2GetFMUstate)
+#define fmi2SetFMUstate              fmi2FullName(fmi2SetFMUstate)
+#define fmi2FreeFMUstate             fmi2FullName(fmi2FreeFMUstate)
+#define fmi2SerializedFMUstateSize   fmi2FullName(fmi2SerializedFMUstateSize)
+#define fmi2SerializeFMUstate        fmi2FullName(fmi2SerializeFMUstate)
+#define fmi2DeSerializeFMUstate      fmi2FullName(fmi2DeSerializeFMUstate)
+#define fmi2GetDirectionalDerivative fmi2FullName(fmi2GetDirectionalDerivative)
+
+
+/***************************************************
+Functions for FMI2 for Model Exchange
+****************************************************/
+#define fmi2EnterEventMode                fmi2FullName(fmi2EnterEventMode)
+#define fmi2NewDiscreteStates             fmi2FullName(fmi2NewDiscreteStates)
+#define fmi2EnterContinuousTimeMode       fmi2FullName(fmi2EnterContinuousTimeMode)
+#define fmi2CompletedIntegratorStep       fmi2FullName(fmi2CompletedIntegratorStep)
+#define fmi2SetTime                       fmi2FullName(fmi2SetTime)
+#define fmi2SetContinuousStates           fmi2FullName(fmi2SetContinuousStates)
+#define fmi2GetDerivatives                fmi2FullName(fmi2GetDerivatives)
+#ifdef FMU_EXPERIMENTAL
+#define fmi2GetSpecificDerivatives        fmi2FullName(fmi2GetSpecificDerivatives)
+#endif
+#define fmi2GetEventIndicators            fmi2FullName(fmi2GetEventIndicators)
+#define fmi2GetContinuousStates           fmi2FullName(fmi2GetContinuousStates)
+#define fmi2GetNominalsOfContinuousStates fmi2FullName(fmi2GetNominalsOfContinuousStates)
+
+
+/***************************************************
+Functions for FMI2 for Co-Simulation
+****************************************************/
+#define fmi2SetRealInputDerivatives      fmi2FullName(fmi2SetRealInputDerivatives)
+#define fmi2GetRealOutputDerivatives     fmi2FullName(fmi2GetRealOutputDerivatives)
+#define fmi2DoStep                       fmi2FullName(fmi2DoStep)
+#define fmi2CancelStep                   fmi2FullName(fmi2CancelStep)
+#define fmi2GetStatus                    fmi2FullName(fmi2GetStatus)
+#define fmi2GetRealStatus                fmi2FullName(fmi2GetRealStatus)
+#define fmi2GetIntegerStatus             fmi2FullName(fmi2GetIntegerStatus)
+#define fmi2GetBooleanStatus             fmi2FullName(fmi2GetBooleanStatus)
+#define fmi2GetStringStatus              fmi2FullName(fmi2GetStringStatus)
+
+/* Version number */
+#define fmi2Version "2.0"
+
+
+/***************************************************
+Common Functions
+****************************************************/
+
+/* Inquire version numbers of header files */
+   FMI2_Export fmi2GetTypesPlatformTYPE fmi2GetTypesPlatform;
+   FMI2_Export fmi2GetVersionTYPE       fmi2GetVersion;
+   FMI2_Export fmi2SetDebugLoggingTYPE  fmi2SetDebugLogging;
+
+/* Creation and destruction of FMU instances */
+   FMI2_Export fmi2InstantiateTYPE  fmi2Instantiate;
+   FMI2_Export fmi2FreeInstanceTYPE fmi2FreeInstance;
+
+/* Enter and exit initialization mode, terminate and reset */
+   FMI2_Export fmi2SetupExperimentTYPE         fmi2SetupExperiment;
+   FMI2_Export fmi2EnterInitializationModeTYPE fmi2EnterInitializationMode;
+   FMI2_Export fmi2ExitInitializationModeTYPE  fmi2ExitInitializationMode;
+   FMI2_Export fmi2TerminateTYPE               fmi2Terminate;
+   FMI2_Export fmi2ResetTYPE                   fmi2Reset;
+
+/* Getting and setting variables values */
+   FMI2_Export fmi2GetRealTYPE    fmi2GetReal;
+   FMI2_Export fmi2GetIntegerTYPE fmi2GetInteger;
+   FMI2_Export fmi2GetBooleanTYPE fmi2GetBoolean;
+   FMI2_Export fmi2GetStringTYPE  fmi2GetString;
+
+   FMI2_Export fmi2SetRealTYPE    fmi2SetReal;
+   FMI2_Export fmi2SetIntegerTYPE fmi2SetInteger;
+   FMI2_Export fmi2SetBooleanTYPE fmi2SetBoolean;
+   FMI2_Export fmi2SetStringTYPE  fmi2SetString;
+
+/* Getting and setting the internal FMU state */
+   FMI2_Export fmi2GetFMUstateTYPE            fmi2GetFMUstate;
+   FMI2_Export fmi2SetFMUstateTYPE            fmi2SetFMUstate;
+   FMI2_Export fmi2FreeFMUstateTYPE           fmi2FreeFMUstate;
+   FMI2_Export fmi2SerializedFMUstateSizeTYPE fmi2SerializedFMUstateSize;
+   FMI2_Export fmi2SerializeFMUstateTYPE      fmi2SerializeFMUstate;
+   FMI2_Export fmi2DeSerializeFMUstateTYPE    fmi2DeSerializeFMUstate;
+
+/* Getting partial derivatives */
+   FMI2_Export fmi2GetDirectionalDerivativeTYPE fmi2GetDirectionalDerivative;
+
+
+/***************************************************
+Functions for FMI2 for Model Exchange
+****************************************************/
+
+/* Enter and exit the different modes */
+   FMI2_Export fmi2EnterEventModeTYPE               fmi2EnterEventMode;
+   FMI2_Export fmi2NewDiscreteStatesTYPE            fmi2NewDiscreteStates;
+   FMI2_Export fmi2EnterContinuousTimeModeTYPE      fmi2EnterContinuousTimeMode;
+   FMI2_Export fmi2CompletedIntegratorStepTYPE      fmi2CompletedIntegratorStep;
+
+/* Providing independent variables and re-initialization of caching */
+   FMI2_Export fmi2SetTimeTYPE             fmi2SetTime;
+   FMI2_Export fmi2SetContinuousStatesTYPE fmi2SetContinuousStates;
+
+/* Evaluation of the model equations */
+   FMI2_Export fmi2GetDerivativesTYPE                fmi2GetDerivatives;
+#ifdef FMU_EXPERIMENTAL
+   FMI2_Export fmi2GetSpecificDerivativesTYPE        fmi2GetSpecificDerivatives;
+#endif
+   FMI2_Export fmi2GetEventIndicatorsTYPE            fmi2GetEventIndicators;
+   FMI2_Export fmi2GetContinuousStatesTYPE           fmi2GetContinuousStates;
+   FMI2_Export fmi2GetNominalsOfContinuousStatesTYPE fmi2GetNominalsOfContinuousStates;
+
+
+/***************************************************
+Functions for FMI2 for Co-Simulation
+****************************************************/
+
+/* Simulating the slave */
+   FMI2_Export fmi2SetRealInputDerivativesTYPE  fmi2SetRealInputDerivatives;
+   FMI2_Export fmi2GetRealOutputDerivativesTYPE fmi2GetRealOutputDerivatives;
+
+   FMI2_Export fmi2DoStepTYPE     fmi2DoStep;
+   FMI2_Export fmi2CancelStepTYPE fmi2CancelStep;
+
+/* Inquire slave status */
+   FMI2_Export fmi2GetStatusTYPE        fmi2GetStatus;
+   FMI2_Export fmi2GetRealStatusTYPE    fmi2GetRealStatus;
+   FMI2_Export fmi2GetIntegerStatusTYPE fmi2GetIntegerStatus;
+   FMI2_Export fmi2GetBooleanStatusTYPE fmi2GetBooleanStatus;
+   FMI2_Export fmi2GetStringStatusTYPE  fmi2GetStringStatus;
+
+#ifdef __cplusplus
+}  /* end of extern "C" { */
+#endif
+
+#endif /* fmi2Functions_h */

+ 115 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_TD/fmi2/fmi2TypesPlatform.h

@@ -0,0 +1,115 @@
+#ifndef fmi2TypesPlatform_h
+#define fmi2TypesPlatform_h
+
+/* Standard header file to define the argument types of the
+   functions of the Functional Mock-up Interface 2.0.
+   This header file must be utilized both by the model and
+   by the simulation engine.
+
+   Revisions:
+   - Apr.  9, 2014: all prefixes "fmi" renamed to "fmi2" (decision from April 8)
+   - Mar   31, 2014: New datatype fmiChar introduced.
+   - Feb.  17, 2013: Changed fmiTypesPlatform from "standard32" to "default".
+                     Removed fmiUndefinedValueReference since no longer needed
+                     (because every state is defined in ScalarVariables).
+   - March 20, 2012: Renamed from fmiPlatformTypes.h to fmiTypesPlatform.h
+   - Nov.  14, 2011: Use the header file "fmiPlatformTypes.h" for FMI 2.0
+                     both for "FMI for model exchange" and for "FMI for co-simulation"
+                     New types "fmiComponentEnvironment", "fmiState", and "fmiByte".
+                     The implementation of "fmiBoolean" is change from "char" to "int".
+                     The #define "fmiPlatform" changed to "fmiTypesPlatform"
+                     (in order that #define and function call are consistent)
+   - Oct.   4, 2010: Renamed header file from "fmiModelTypes.h" to fmiPlatformTypes.h"
+                     for the co-simulation interface
+   - Jan.   4, 2010: Renamed meModelTypes_h to fmiModelTypes_h (by Mauss, QTronic)
+   - Dec.  21, 2009: Changed "me" to "fmi" and "meModel" to "fmiComponent"
+                     according to meeting on Dec. 18 (by Martin Otter, DLR)
+   - Dec.   6, 2009: Added meUndefinedValueReference (by Martin Otter, DLR)
+   - Sept.  9, 2009: Changes according to FMI-meeting on July 21:
+                     Changed "version" to "platform", "standard" to "standard32",
+                     Added a precise definition of "standard32" as comment
+                     (by Martin Otter, DLR)
+   - July  19, 2009: Added "me" as prefix to file names, added meTrue/meFalse,
+                     and changed meValueReferenced from int to unsigned int
+                     (by Martin Otter, DLR).
+   - March  2, 2009: Moved enums and function pointer definitions to
+                     ModelFunctions.h (by Martin Otter, DLR).
+   - Dec.  3, 2008 : First version by Martin Otter (DLR) and
+                     Hans Olsson (Dynasim).
+
+
+   Copyright (C) 2008-2011 MODELISAR consortium,
+               2012-2013 Modelica Association Project "FMI"
+               All rights reserved.
+   This file is licensed by the copyright holders under the BSD 2-Clause License
+   (http://www.opensource.org/licenses/bsd-license.html):
+
+   ----------------------------------------------------------------------------
+   Redistribution and use in source and binary forms, with or without
+   modification, are permitted provided that the following conditions are met:
+
+   - Redistributions of source code must retain the above copyright notice,
+     this list of conditions and the following disclaimer.
+   - Redistributions in binary form must reproduce the above copyright notice,
+     this list of conditions and the following disclaimer in the documentation
+     and/or other materials provided with the distribution.
+   - Neither the name of the copyright holders nor the names of its
+     contributors may be used to endorse or promote products derived
+     from this software without specific prior written permission.
+
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+   TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+   PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
+   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+   OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+   OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+   ----------------------------------------------------------------------------
+
+   with the extension:
+
+   You may distribute or publicly perform any modification only under the
+   terms of this license.
+   (Note, this means that if you distribute a modified file,
+    the modified file must also be provided under this license).
+*/
+
+/* Platform (unique identification of this header file) */
+#define fmi2TypesPlatform "default"
+
+/* Type definitions of variables passed as arguments
+   Version "default" means:
+
+   fmi2Component           : an opaque object pointer
+   fmi2ComponentEnvironment: an opaque object pointer
+   fmi2FMUstate            : an opaque object pointer
+   fmi2ValueReference      : handle to the value of a variable
+   fmi2Real                : double precision floating-point data type
+   fmi2Integer             : basic signed integer data type
+   fmi2Boolean             : basic signed integer data type
+   fmi2Char                : character data type
+   fmi2String              : a pointer to a vector of fmi2Char characters
+                             ('\0' terminated, UTF8 encoded)
+   fmi2Byte                : smallest addressable unit of the machine, typically one byte.
+*/
+   typedef void*           fmi2Component;               /* Pointer to FMU instance       */
+   typedef void*           fmi2ComponentEnvironment;    /* Pointer to FMU environment    */
+   typedef void*           fmi2FMUstate;                /* Pointer to internal FMU state */
+   typedef unsigned int    fmi2ValueReference;
+   typedef double          fmi2Real   ;
+   typedef int             fmi2Integer;
+   typedef int             fmi2Boolean;
+   typedef char            fmi2Char;
+   typedef const fmi2Char* fmi2String;
+   typedef char            fmi2Byte;
+
+/* Values for fmi2Boolean  */
+#define fmi2True  1
+#define fmi2False 0
+
+
+#endif /* fmi2TypesPlatform_h */

BIN
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_Window_sa/Debug/libFMI_Window_sa.dll


+ 490 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_Window_sa/FMI_Window_sa.c

@@ -0,0 +1,490 @@
+/* ---------------------------------------------------------------------------*
+ * Sample implementation of an control support master FMU -
+ * ---------------------------------------------------------------------------*/
+/*
+Template for a sc FMU
+*/
+
+#define MODEL_IDENTIFIER CM
+#define MODEL_GUID "{41f87101-edf2-4eef-90f3-42db56d4565f}"
+#define FMI2_FUNCTION_PREFIX FMI_WINDOW_SA
+
+
+#include <stdio.h>
+#include "string.h"
+#include "fmi2Functions.h"
+#include <float.h>
+#include "FMI_Window_sa.h"
+#include <math.h>
+#include "fmi2.h"
+#include "sim_support.h"
+
+
+#define NUMBER_OF_REALS 4
+#define NUMBER_OF_STRINGS 0
+#define NUMBER_OF_BOOLEANS 0
+#define NUMBER_OF_INTEGERS 0
+
+
+#define _in_speed_motor 0
+#define _out_window_height 1
+#define _out_window_speed 2
+#define _out_window_torque 3
+
+
+ double relativeError(double a, double b){
+	return fabs((a - b) / a);
+}
+
+/*
+ * Helper function for absolute error
+ */
+ double absoluteError(double a, double b){
+	return fabs(a - b);
+}
+
+/*
+ * is_close function for double comparison
+ */
+ int is_close(double a, double b, double REL_TOL, double ABS_TOL){
+	return ((absoluteError(a,b)<ABS_TOL) && (relativeError(a,b)<REL_TOL));
+}
+
+fmi2Status fmi2SetDebugLogging(fmi2Component fc, fmi2Boolean loggingOn, size_t nCategories, const fmi2String categories[])
+{
+    return fmi2OK;
+}
+
+fmi2Status fmi2SetString(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, const fmi2String value[])
+{
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetString(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, fmi2String value[])
+{
+    return fmi2Error;
+}
+
+fmi2Status fmi2SetReal(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, const fmi2Real value[])
+{
+	FMUInstance* comp = (FMUInstance *)fc;
+		int i;
+	    for (i = 0; i < nvr; i++)
+		{
+	    	if(vr[i]>=5){
+	    		printf("Value reference: %d, cannot be set, it is a store element\n", vr[i]);
+	    	}else{
+	    		 printf("Value reference: %d\n", vr[i]);
+	    		 comp->r[vr[i]] = value[i];
+	    	}
+
+	        //setExposedReal(vr[i], value[i]);
+	        //comp->r[vr[i]] = value[i];
+	    }
+	    return fmi2OK;
+}
+
+fmi2Status fmi2GetReal(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, fmi2Real value[])
+{
+
+    FMUInstance* comp = (FMUInstance *)fc;
+	int i;
+    for (i = 0; i < nvr; i++)
+	{
+        value[i] = comp->r[(vr[i])];
+    }
+    return fmi2OK;
+}
+
+fmi2Status fmi2SetBoolean(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, const fmi2Boolean value[])
+{
+	FMUInstance* comp = (FMUInstance *)fc;
+	int i;
+	for (i = 0; i < nvr; i++)
+	{
+		comp->b[vr[i]] = value[i];
+	}
+    return fmi2OK;
+}
+
+fmi2Status fmi2GetBoolean(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, fmi2Boolean value[])
+{
+	FMUInstance* comp = (FMUInstance *)fc;
+	int i;
+	for (i = 0; i < nvr; i++)
+	{
+		value[i] = comp->b[vr[i]];
+	}
+    return fmi2OK;
+}
+
+fmi2Component fmi2Instantiate(fmi2String instanceName, fmi2Type fmuType, fmi2String fmuGUID, fmi2String fmuLocation, const fmi2CallbackFunctions* functions, fmi2Boolean visible, fmi2Boolean loggingOn)
+{
+
+	//Declare data structure for fmu instance
+    FMUInstance* fi;
+	printf("%s in fmiInstantiate\n",instanceName);
+
+    //Perform checks on passed callback functions
+    if (loggingOn) {
+
+        if (!functions->logger);
+        //return NULL;
+	}
+    //Check for instanceName
+    if (!instanceName || strlen(instanceName)==0) {
+
+        // print (and/or log) instanceName is missing
+        //return NULL;
+    }
+    //Check passed GUID to defined model GUID
+    if (strcmp(fmuGUID, MODEL_GUID))
+	{
+        // print (and/or log) GUID doesn't match
+        //return NULL;
+    }
+
+    //Allocate fmu instance Memory
+    // TODO check if "canNotUseMemoryManagementFunctions == true/false". If false memory allocation not possible
+    fi = (FMUInstance *)functions->allocateMemory(1, sizeof(FMUInstance));
+    if (fi) {
+        // Think about what to do with variable values. Using these structs and pointers slows down simulation computations. Maybe only necessary for input, output and tunable parameters??
+        fi->r = functions->allocateMemory(NUMBER_OF_REALS, sizeof(fmi2Real));
+        fi->i = functions->allocateMemory(NUMBER_OF_INTEGERS, sizeof(fmi2Integer));
+        fi->b = functions->allocateMemory(NUMBER_OF_BOOLEANS, sizeof(fmi2Boolean));
+        fi->s = functions->allocateMemory(NUMBER_OF_STRINGS,  sizeof(fmi2String));
+    } // variables in predefined arrays (performance issue) --> makes multiple instances of fmu impossible
+
+
+    fi->instanceName = functions->allocateMemory(1 + strlen(instanceName), sizeof(char));
+    fi->GUID = functions->allocateMemory(1 + strlen(fmuGUID), sizeof(char));
+
+    strcpy((char*)fi->instanceName, instanceName);
+    strcpy((char*)fi->GUID, fmuGUID);
+    fi->functions = functions;
+    fi->loggingOn = loggingOn;
+    fi->isVisible = visible;
+    fi->state = fmuInstantiated;
+    /* Load the inner FMUs:*/
+    loadDll("PW_Window.dll", &(fi->inner), "PW_Window_");
+    fi->fmuResourceLocation_inner = "PW_Window_";
+    /*Instantiate inner components*/
+    fi->c_inner = fi->inner.instantiate("inner", fmi2CoSimulation, "1", fi->fmuResourceLocation_inner, fi->functions, visible, 0);
+    return fi;
+}
+
+fmi2Status fmi2SetupExperiment(fmi2Component fc, fmi2Boolean toleranceDefined, fmi2Real tolerance,
+                            fmi2Real startTime, fmi2Boolean stopTimeDefined, fmi2Real stopTime) {
+
+
+    FMUInstance* fi = (FMUInstance*) fc;
+	printf("%s in fmiSetupExperiment\n",fi->instanceName);
+	if (fi->state != fmuInstantiated)
+	{
+		printf("fmu: %s was not instatiated before calling fmiSetupExperiment\n", fi->instanceName);
+		return fmi2Error;
+	}
+	fi->currentTime = startTime;
+	fi->stopTimeDefined = stopTimeDefined;
+	fi->toleranceDefined = toleranceDefined;
+	if (stopTimeDefined)
+	{
+		fi->stopTime = stopTime;
+	}
+	if (toleranceDefined)
+	{
+		fi->tolerance = tolerance;
+	}
+
+	/*
+	 * setup inner
+	 */
+	fmi2Status fmi2Flag = fmi2OK;
+	fi->state = fmuExperimentSettedUp;
+	fmi2Flag = fi->inner.setupExperiment(fi->c_inner, toleranceDefined, tolerance, startTime, fmi2True, stopTime);
+	    if (fmi2Flag == fmi2Error){
+	    	fi->state = fmuError;
+	    }
+    return fmi2Flag;
+}
+
+fmi2Status fmi2EnterInitializationMode(fmi2Component fc)
+{
+	FMUInstance* fi = (FMUInstance*) fc;
+	printf("%s in fmiEnterInitializationMode\n",fi->instanceName);
+	if (fi->state != fmuExperimentSettedUp)
+	{
+		printf("fmu: %s experiment was not set-up before calling fmiEnterInitializationMode\n", fi->instanceName);
+		return fmi2Error;
+	}
+    fi->state = fmuInitMode;
+    fmi2Status fmi2Flag = fmi2OK;
+    fmi2Flag = fi->inner.enterInitializationMode(fi->c_inner);
+    if (fmi2Flag == fmi2Error){
+        return fi->state = fmuError;
+    }
+    return fmi2Flag;
+}
+
+fmi2Status fmi2ExitInitializationMode(fmi2Component fc)
+{
+	FMUInstance* fi = (FMUInstance*) fc;
+	printf("%s in fmiExitInitializationMode\n",fi->instanceName);
+	if (fi->state != fmuInitMode)
+	{
+		printf("fmu: %s did not enter Initialization Mode before calling fmiExitInitializationMode\n", fi->instanceName);
+		return fmi2Error;
+	}
+	// TODO
+	//initStatus = calculateInitialUnknownValues();
+	//initialize();
+    fi->state = fmuInitialized;
+    fmi2Status fmi2Flag = fmi2OK;
+    fmi2Flag = fi->inner.exitInitializationMode(fi->c_inner);
+    if (fmi2Flag == fmi2Error){
+           return fi->state = fmuError;
+    }
+    return fmi2Flag;
+}
+
+fmi2Status fmi2DoStep(fmi2Component fc , fmi2Real currentCommPoint, fmi2Real commStepSize, fmi2Boolean noPrevFMUState)
+{
+
+	FMUInstance* fi = (FMUInstance *)fc;
+	fmi2Status simStatus = fmi2OK;
+    printf("%s in fmiDoStep()\n",fi->instanceName);
+    fmi2ValueReference to_inner[1]={5};
+    fmi2ValueReference from_inner[3] = {7,9,10};
+    fi->inner.setReal(fi->c_inner,to_inner,1,&(fi->r[_in_speed_motor]));
+    fi->inner.doStep(fi->c_inner, currentCommPoint, commStepSize, noPrevFMUState);
+    fi->inner.getReal(fi->c_inner, from_inner, 3, &(fi->r[_out_window_height]));
+    /* SA */
+    fi->r[_out_window_torque] = -(fi->r[_out_window_torque]);
+	return simStatus;
+}
+
+fmi2Status fmi2Terminate(fmi2Component fc)
+{
+	FMUInstance* fi = (FMUInstance *)fc;
+	printf("%s in fmiTerminate\n",fi->instanceName);
+	// do check if fi may be terminated
+	fi->inner.terminate(fi->c_inner);
+	fi->state = fmuTerminated;
+    return fmi2OK;
+}
+
+
+void fmi2FreeInstance(fmi2Component fc)
+{
+
+	FMUInstance* fi = (FMUInstance*) fc;
+	printf("%s in fmiFreeInstance\n",fi->instanceName);
+
+    if (fi) {
+        fi->functions->freeMemory(fi->r);
+        fi->functions->freeMemory(fi->i);
+        fi->functions->freeMemory(fi->b);
+        fi->functions->freeMemory(fi->s);// TODO has to be done with loop
+		fi->functions->freeMemory((void*)fi->instanceName);
+		fi->functions->freeMemory((void*)fi->GUID);
+		fi->functions->freeMemory((void*)fi);
+
+    }
+}
+
+//To be implemented
+
+const char* fmi2GetVersion() {
+	printf("Function fmiGetVersion not supported\n");
+    return NULL;
+}
+
+const char* fmi2GetTypesPlatform() {
+	printf("Function fmiGetTypesPlatform not supported\n");
+    return NULL;
+}
+
+fmi2Status fmi2Reset(fmi2Component fc)
+{
+	printf("Function fmiReset not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2SetInteger(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, const fmi2Integer value[])
+{
+    printf("Function fmiSetInteger not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetInteger(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, fmi2Integer value[])
+{
+    printf("Function fmiGetInteger not supported\n");
+    return fmi2Error;
+}
+
+
+/*******OWN IMPLEMENTATION OF Get/Set FMU state*******/
+fmi2Status fmi2GetFMUstate (fmi2Component c, fmi2FMUstate* FMUstate) {
+    FMUInstance* orig = (FMUInstance*)c;
+    FMUInstance* fi = (FMUInstance *)FMUstate;
+    fi = orig->functions->allocateMemory(1, sizeof(FMUInstance));
+    *FMUstate = fi;
+    if (fi) {
+        // Think about what to do with variable values. Using these structs and pointers slows down simulation computations. Maybe only necessary for input, output and tunable parameters??
+        fi->r = orig->functions->allocateMemory(NUMBER_OF_REALS, sizeof(fmi2Real));
+        fi->i = orig->functions->allocateMemory(NUMBER_OF_INTEGERS, sizeof(fmi2Integer));
+        fi->b = orig->functions->allocateMemory(NUMBER_OF_BOOLEANS, sizeof(fmi2Boolean));
+        fi->s = orig->functions->allocateMemory(NUMBER_OF_STRINGS,  sizeof(fmi2String));
+
+    } // variables in predefined arrays (performance issue) --> makes multiple instances of fmu impossible
+    fi->instanceName = orig->functions->allocateMemory(1 + strlen(orig->instanceName), sizeof(char));
+    fi->GUID = orig->functions->allocateMemory(1 + strlen(orig->GUID), sizeof(char));
+
+    strcpy((char *)fi->instanceName, (char *)orig->instanceName);
+    strcpy((char *)fi->GUID, (char *)orig->GUID);
+    fi->functions = orig->functions;
+    fi->loggingOn = orig->loggingOn;
+    fi->isVisible = orig->isVisible;
+    fi->state = orig->state;
+    fi->stepSize = orig->stepSize;
+    fi->startTime = orig->startTime;
+    fi->stopTime = orig->stopTime;
+	fi->currentTime = orig->currentTime;
+	fi->inner = orig->inner;
+	orig->inner.getFMUstate(orig->c_inner,fi->c_inner);
+	fi->fmuResourceLocation_inner = fi->functions->allocateMemory(1+strlen(orig->fmuResourceLocation_inner), sizeof(char));
+	strcpy((char *)fi->fmuResourceLocation_inner,(char *)orig->fmuResourceLocation_inner);
+	//copy r
+	int i=0;
+	for (i=0; i< NUMBER_OF_REALS;i++){
+	    printf("Setting real: %i %f\n", i, orig->r[i]);
+        fi->r[i] = orig->r[i];
+        printf("Setted real: %i %f\n", i, fi->r[i]);
+	}
+	//copy s
+	for (i=0; i< NUMBER_OF_STRINGS;i++){
+        fi->s[i] = orig->s[i];
+	}
+	//copy i
+    for (i=0; i< NUMBER_OF_INTEGERS;i++){
+        fi->i[i] = orig->i[i];
+	}
+	//copy b
+	for (i=0; i< NUMBER_OF_BOOLEANS;i++){
+        fi->b[i] = orig->b[i];
+	}
+    return fmi2OK;
+}
+
+
+fmi2Status fmi2SetFMUstate (fmi2Component c, fmi2FMUstate FMUstate) {
+    FMUInstance* orig = (FMUInstance*)FMUstate;
+    FMUInstance* fi = (FMUInstance*)c;
+
+    fi->inner.setFMUstate(fi->c_inner,orig->c_inner);
+    fi->fmuResourceLocation_inner = orig->functions->allocateMemory(1+strlen(orig->fmuResourceLocation_inner), sizeof(char));
+    strcpy((char *)fi->fmuResourceLocation_inner,(char *)orig->fmuResourceLocation_inner);
+    //set time etc correct, name and GUID should still be ok ;-)
+    printf("setting time values from %f to %f\n", fi->currentTime, orig->currentTime);
+    fi->state = orig->state;
+    fi->stepSize = orig->stepSize;
+    fi->startTime = orig->startTime;
+    fi->stopTime = orig->stopTime;
+	fi->currentTime = orig->currentTime;
+
+	printf("setting real values\n");
+	//copy r
+	int i=0;
+	for (i=0; i< NUMBER_OF_REALS;i++){
+        fi->r[i] = orig->r[i];
+	}
+	printf("setting string values\n");
+	//copy s
+	for (i=0; i< NUMBER_OF_STRINGS;i++){
+
+        fi->s[i] = orig->s[i];
+	}
+	//copy i
+    for (i=0; i< NUMBER_OF_INTEGERS;i++){
+        fi->i[i] = orig->i[i];
+	}
+	//copy b
+	for (i=0; i< NUMBER_OF_BOOLEANS;i++){
+        fi->b[i] = orig->b[i];
+	}
+    return fmi2OK;
+
+
+}
+/****************************************************/
+
+fmi2Status fmi2FreeFMUstate(fmi2Component c, fmi2FMUstate* FMUstate) {
+    printf("Function fmiFreeFMUstate not supported\n");
+    return fmi2Error;
+}
+fmi2Status fmi2SerializedFMUstateSize(fmi2Component c, fmi2FMUstate FMUstate, size_t *size) {
+    printf("Function fmiSerializedFMUstateSize not supported\n");
+    return fmi2Error;
+}
+fmi2Status fmi2SerializeFMUstate (fmi2Component c, fmi2FMUstate FMUstate, fmi2Byte serializedState[], size_t size) {
+    printf("Function fmiSerializeFMUstate not supported\n");
+    return fmi2Error;
+}
+fmi2Status fmi2DeSerializeFMUstate (fmi2Component c, const fmi2Byte serializedState[], size_t size, fmi2FMUstate* FMUstate) {
+    printf("Function fmiDeSerializeFMUstate not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetDirectionalDerivative(fmi2Component c, const fmi2ValueReference vUnknown_ref[], size_t nUnknown,
+                const fmi2ValueReference vKnown_ref[] , size_t nKnown, const fmi2Real dvKnown[], fmi2Real dvUnknown[]) {
+    printf("Function fmiGetDirectionalDerivative not supported\n");
+    return fmi2Error;
+}
+
+
+fmi2Status fmi2SetRealInputDerivatives(fmi2Component c, const fmi2ValueReference vr[], size_t nvr,
+                                     const fmi2Integer order[], const fmi2Real value[]) {
+    printf("Function fmiGetDirectionalDerivative not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetRealOutputDerivatives(fmi2Component c, const fmi2ValueReference vr[], size_t nvr,
+                                      const fmi2Integer order[], fmi2Real value[]) {
+    printf("Function fmiGetDirectionalDerivative not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2CancelStep(fmi2Component c) {
+    printf("Function fmiGetDirectionalDerivative not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetStatus(fmi2Component c, const fmi2StatusKind s, fmi2Status *value) {
+    printf("Function fmiGetStatus not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetRealStatus(fmi2Component c, const fmi2StatusKind s, fmi2Real *value) {
+    if(s == fmi2LastSuccessfulTime){
+        FMUInstance* comp = (FMUInstance*) c;
+        *value = comp->currentTime;
+        return fmi2OK;
+    }
+    printf("Function fmiGetRealStatus not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetIntegerStatus(fmi2Component c, const fmi2StatusKind s, fmi2Integer *value) {
+    printf("Function fmiGetIntegerStatus not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetBooleanStatus(fmi2Component c, const fmi2StatusKind s, fmi2Boolean *value) {
+    printf("Function fmiGetBooleanStatus not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetStringStatus(fmi2Component c, const fmi2StatusKind s, fmi2String *value) {
+    printf("Function fmiGetStringStatus not supported\n");
+    return fmi2Error;
+}

+ 50 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_Window_sa/FMI_Window_sa.h

@@ -0,0 +1,50 @@
+/*
+ * PW_Controller.h
+ *
+ *  Created on: Jan 25, 2017
+ *      Author: Joachim
+ */
+
+#ifndef FMI_WINDOW_SA_H_
+#define FMI_WINDOW_SA_H_
+
+#include "fmi2.h"
+
+typedef enum {
+    fmuInstantiated = 0,
+    fmuInitMode  = 1,
+	fmuInitialized = 2,
+    fmuTerminated   = 3,
+    fmuError        = 4,
+    fmuExperimentSettedUp = 5
+} FMUState;
+
+
+
+typedef struct {
+	fmi2Real    *r;
+    fmi2Integer *i;
+    fmi2Boolean *b;
+    fmi2String  *s;
+    fmi2Boolean isVisible;
+    fmi2String instanceName;
+    fmi2String GUID;
+    const fmi2CallbackFunctions* functions;
+    fmi2Boolean loggingOn;
+    FMUState state;
+	fmi2Real stepSize;
+    fmi2Real startTime;
+    fmi2Real stopTime;
+	fmi2Real currentTime;
+    fmi2Boolean stopTimeDefined;
+    fmi2Real tolerance;
+    fmi2Boolean toleranceDefined;
+    FMU inner;
+    char *fmuResourceLocation_inner;
+    fmi2Component c_inner;
+} FMUInstance; // At the moment, most of the variables not really used since multiple instances of an FMU are not supported at the moment (performance issues)
+
+
+
+
+#endif /* FMI_WINDOW_SA_H_ */

+ 72 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_Window_sa/fmi2/fmi2.h

@@ -0,0 +1,72 @@
+/* -------------------------------------------------------------------------
+ * fmi.h
+ * Struct with the corresponding function pointers for FMI 2.0.
+ * Copyright QTronic GmbH. All rights reserved.
+ * -------------------------------------------------------------------------*/
+
+#ifndef FMI_H
+#define FMI_H
+
+#include "fmi2Functions.h"
+
+typedef struct {
+//    ModelDescription* modelDescription;
+
+    void  *dllHandle; // fmu.so handle
+    /***************************************************
+    Common Functions
+    ****************************************************/
+    fmi2GetTypesPlatformTYPE         *getTypesPlatform;
+    fmi2GetVersionTYPE               *getVersion;
+    fmi2SetDebugLoggingTYPE          *setDebugLogging;
+    fmi2InstantiateTYPE              *instantiate;
+    fmi2FreeInstanceTYPE             *freeInstance;
+    fmi2SetupExperimentTYPE          *setupExperiment;
+    fmi2EnterInitializationModeTYPE  *enterInitializationMode;
+    fmi2ExitInitializationModeTYPE   *exitInitializationMode;
+    fmi2TerminateTYPE                *terminate;
+    fmi2ResetTYPE                    *reset;
+    fmi2GetRealTYPE                  *getReal;
+    fmi2GetIntegerTYPE               *getInteger;
+    fmi2GetBooleanTYPE               *getBoolean;
+    fmi2GetStringTYPE                *getString;
+    fmi2SetRealTYPE                  *setReal;
+    fmi2SetIntegerTYPE               *setInteger;
+    fmi2SetBooleanTYPE               *setBoolean;
+    fmi2SetStringTYPE                *setString;
+    fmi2GetFMUstateTYPE              *getFMUstate;
+    fmi2SetFMUstateTYPE              *setFMUstate;
+    fmi2FreeFMUstateTYPE             *freeFMUstate;
+    fmi2SerializedFMUstateSizeTYPE   *serializedFMUstateSize;
+    fmi2SerializeFMUstateTYPE        *serializeFMUstate;
+    fmi2DeSerializeFMUstateTYPE      *deSerializeFMUstate;
+    fmi2GetDirectionalDerivativeTYPE *getDirectionalDerivative;
+    /***************************************************
+    Functions for FMI2 for Co-Simulation
+    ****************************************************/
+    fmi2SetRealInputDerivativesTYPE  *setRealInputDerivatives;
+    fmi2GetRealOutputDerivativesTYPE *getRealOutputDerivatives;
+    fmi2DoStepTYPE                   *doStep;
+    fmi2CancelStepTYPE               *cancelStep;
+    fmi2GetStatusTYPE                *getStatus;
+    fmi2GetRealStatusTYPE            *getRealStatus;
+    fmi2GetIntegerStatusTYPE         *getIntegerStatus;
+    fmi2GetBooleanStatusTYPE         *getBooleanStatus;
+    fmi2GetStringStatusTYPE          *getStringStatus;
+    /***************************************************
+    Functions for FMI2 for Model Exchange
+    ****************************************************/
+    fmi2EnterEventModeTYPE                *enterEventMode;
+    fmi2NewDiscreteStatesTYPE             *newDiscreteStates;
+    fmi2EnterContinuousTimeModeTYPE       *enterContinuousTimeMode;
+    fmi2CompletedIntegratorStepTYPE       *completedIntegratorStep;
+    fmi2SetTimeTYPE                       *setTime;
+    fmi2SetContinuousStatesTYPE           *setContinuousStates;
+    fmi2GetDerivativesTYPE                *getDerivatives;
+    fmi2GetEventIndicatorsTYPE            *getEventIndicators;
+    fmi2GetContinuousStatesTYPE           *getContinuousStates;
+    fmi2GetNominalsOfContinuousStatesTYPE *getNominalsOfContinuousStates;
+} FMU;
+
+#endif // FMI_H
+

+ 247 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_Window_sa/fmi2/fmi2FunctionTypes.h

@@ -0,0 +1,247 @@
+#ifndef fmi2FunctionTypes_h
+#define fmi2FunctionTypes_h
+
+#include "fmi2TypesPlatform.h"
+
+/* This header file must be utilized when compiling an FMU or an FMI master.
+   It declares data and function types for FMI 2.0
+
+   Revisions:
+   - Apr.  9, 2014: all prefixes "fmi" renamed to "fmi2" (decision from April 8)
+   - Apr.  3, 2014: Added #include <stddef.h> for size_t definition
+   - Mar. 27, 2014: Added #include "fmiTypesPlatform.h" (#179)
+   - Mar. 26, 2014: Introduced function argument "void" for the functions (#171)
+                      fmiGetTypesPlatformTYPE and fmiGetVersionTYPE
+   - Oct. 11, 2013: Functions of ModelExchange and CoSimulation merged:
+                      fmiInstantiateModelTYPE , fmiInstantiateSlaveTYPE  -> fmiInstantiateTYPE
+                      fmiFreeModelInstanceTYPE, fmiFreeSlaveInstanceTYPE -> fmiFreeInstanceTYPE
+                      fmiEnterModelInitializationModeTYPE, fmiEnterSlaveInitializationModeTYPE -> fmiEnterInitializationModeTYPE
+                      fmiExitModelInitializationModeTYPE , fmiExitSlaveInitializationModeTYPE  -> fmiExitInitializationModeTYPE
+                      fmiTerminateModelTYPE , fmiTerminateSlaveTYPE  -> fmiTerminate
+                      fmiResetSlave -> fmiReset (now also for ModelExchange and not only for CoSimulation)
+                    Functions renamed
+                      fmiUpdateDiscreteStatesTYPE -> fmiNewDiscreteStatesTYPE
+                    Renamed elements of the enumeration fmiEventInfo
+                      upcomingTimeEvent             -> nextEventTimeDefined // due to generic naming scheme: varDefined + var
+                      newUpdateDiscreteStatesNeeded -> newDiscreteStatesNeeded;
+   - June 13, 2013: Changed type fmiEventInfo
+                    Functions removed:
+                       fmiInitializeModelTYPE
+                       fmiEventUpdateTYPE
+                       fmiCompletedEventIterationTYPE
+                       fmiInitializeSlaveTYPE
+                    Functions added:
+                       fmiEnterModelInitializationModeTYPE
+                       fmiExitModelInitializationModeTYPE
+                       fmiEnterEventModeTYPE
+                       fmiUpdateDiscreteStatesTYPE
+                       fmiEnterContinuousTimeModeTYPE
+                       fmiEnterSlaveInitializationModeTYPE;
+                       fmiExitSlaveInitializationModeTYPE;
+   - Feb. 17, 2013: Added third argument to fmiCompletedIntegratorStepTYPE
+                    Changed function name "fmiTerminateType" to "fmiTerminateModelType" (due to #113)
+                    Changed function name "fmiGetNominalContinuousStateTYPE" to
+                                          "fmiGetNominalsOfContinuousStatesTYPE"
+                    Removed fmiGetStateValueReferencesTYPE.
+   - Nov. 14, 2011: First public Version
+
+
+   Copyright (C) 2011 MODELISAR consortium,
+               2012-2013 Modelica Association Project "FMI"
+               All rights reserved.
+   This file is licensed by the copyright holders under the BSD 2-Clause License
+   (http://www.opensource.org/licenses/bsd-license.html):
+
+   ----------------------------------------------------------------------------
+   Redistribution and use in source and binary forms, with or without
+   modification, are permitted provided that the following conditions are met:
+
+   - Redistributions of source code must retain the above copyright notice,
+     this list of conditions and the following disclaimer.
+   - Redistributions in binary form must reproduce the above copyright notice,
+     this list of conditions and the following disclaimer in the documentation
+     and/or other materials provided with the distribution.
+   - Neither the name of the copyright holders nor the names of its
+     contributors may be used to endorse or promote products derived
+     from this software without specific prior written permission.
+
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+   TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+   PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
+   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+   OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+   OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+   ----------------------------------------------------------------------------
+
+   with the extension:
+
+   You may distribute or publicly perform any modification only under the
+   terms of this license.
+   (Note, this means that if you distribute a modified file,
+    the modified file must also be provided under this license).
+*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* make sure all compiler use the same alignment policies for structures */
+#if defined _MSC_VER || defined __GNUC__
+#pragma pack(push,8)
+#endif
+
+/* Include stddef.h, in order that size_t etc. is defined */
+#include <stddef.h>
+
+
+/* Type definitions */
+typedef enum {
+    fmi2OK,
+    fmi2Warning,
+    fmi2Discard,
+    fmi2Error,
+    fmi2Fatal,
+    fmi2Pending
+} fmi2Status;
+
+typedef enum {
+    fmi2ModelExchange,
+    fmi2CoSimulation
+} fmi2Type;
+
+typedef enum {
+    fmi2DoStepStatus,
+    fmi2PendingStatus,
+    fmi2LastSuccessfulTime,
+    fmi2Terminated
+} fmi2StatusKind;
+
+typedef void      (*fmi2CallbackLogger)        (fmi2ComponentEnvironment, fmi2String, fmi2Status, fmi2String, fmi2String, ...);
+typedef void*     (*fmi2CallbackAllocateMemory)(size_t, size_t);
+typedef void      (*fmi2CallbackFreeMemory)    (void*);
+typedef void      (*fmi2StepFinished)          (fmi2ComponentEnvironment, fmi2Status);
+
+typedef struct {
+   const fmi2CallbackLogger         logger;
+   const fmi2CallbackAllocateMemory allocateMemory;
+   const fmi2CallbackFreeMemory     freeMemory;
+   const fmi2StepFinished           stepFinished;
+   const fmi2ComponentEnvironment   componentEnvironment;
+} fmi2CallbackFunctions;
+
+typedef struct {
+   fmi2Boolean newDiscreteStatesNeeded;
+   fmi2Boolean terminateSimulation;
+   fmi2Boolean nominalsOfContinuousStatesChanged;
+   fmi2Boolean valuesOfContinuousStatesChanged;
+   fmi2Boolean nextEventTimeDefined;
+   fmi2Real    nextEventTime;
+} fmi2EventInfo;
+
+
+/* reset alignment policy to the one set before reading this file */
+#if defined _MSC_VER || defined __GNUC__
+#pragma pack(pop)
+#endif
+
+
+/* Define fmi2 function pointer types to simplify dynamic loading */
+
+/***************************************************
+Types for Common Functions
+****************************************************/
+
+/* Inquire version numbers of header files and setting logging status */
+   typedef const char* fmi2GetTypesPlatformTYPE(void);
+   typedef const char* fmi2GetVersionTYPE(void);
+   typedef fmi2Status  fmi2SetDebugLoggingTYPE(fmi2Component, fmi2Boolean, size_t, const fmi2String[]);
+
+/* Creation and destruction of FMU instances and setting debug status */
+   typedef fmi2Component fmi2InstantiateTYPE (fmi2String, fmi2Type, fmi2String, fmi2String, const fmi2CallbackFunctions*, fmi2Boolean, fmi2Boolean);
+   typedef void          fmi2FreeInstanceTYPE(fmi2Component);
+
+/* Enter and exit initialization mode, terminate and reset */
+   typedef fmi2Status fmi2SetupExperimentTYPE        (fmi2Component, fmi2Boolean, fmi2Real, fmi2Real, fmi2Boolean, fmi2Real);
+   typedef fmi2Status fmi2EnterInitializationModeTYPE(fmi2Component);
+   typedef fmi2Status fmi2ExitInitializationModeTYPE (fmi2Component);
+   typedef fmi2Status fmi2TerminateTYPE              (fmi2Component);
+   typedef fmi2Status fmi2ResetTYPE                  (fmi2Component);
+
+/* Getting and setting variable values */
+   typedef fmi2Status fmi2GetRealTYPE   (fmi2Component, const fmi2ValueReference[], size_t, fmi2Real   []);
+   typedef fmi2Status fmi2GetIntegerTYPE(fmi2Component, const fmi2ValueReference[], size_t, fmi2Integer[]);
+   typedef fmi2Status fmi2GetBooleanTYPE(fmi2Component, const fmi2ValueReference[], size_t, fmi2Boolean[]);
+   typedef fmi2Status fmi2GetStringTYPE (fmi2Component, const fmi2ValueReference[], size_t, fmi2String []);
+
+   typedef fmi2Status fmi2SetRealTYPE   (fmi2Component, const fmi2ValueReference[], size_t, const fmi2Real   []);
+   typedef fmi2Status fmi2SetIntegerTYPE(fmi2Component, const fmi2ValueReference[], size_t, const fmi2Integer[]);
+   typedef fmi2Status fmi2SetBooleanTYPE(fmi2Component, const fmi2ValueReference[], size_t, const fmi2Boolean[]);
+   typedef fmi2Status fmi2SetStringTYPE (fmi2Component, const fmi2ValueReference[], size_t, const fmi2String []);
+
+/* Getting and setting the internal FMU state */
+   typedef fmi2Status fmi2GetFMUstateTYPE           (fmi2Component, fmi2FMUstate*);
+   typedef fmi2Status fmi2SetFMUstateTYPE           (fmi2Component, fmi2FMUstate);
+   typedef fmi2Status fmi2FreeFMUstateTYPE          (fmi2Component, fmi2FMUstate*);
+   typedef fmi2Status fmi2SerializedFMUstateSizeTYPE(fmi2Component, fmi2FMUstate, size_t*);
+   typedef fmi2Status fmi2SerializeFMUstateTYPE     (fmi2Component, fmi2FMUstate, fmi2Byte[], size_t);
+   typedef fmi2Status fmi2DeSerializeFMUstateTYPE   (fmi2Component, const fmi2Byte[], size_t, fmi2FMUstate*);
+
+/* Getting partial derivatives */
+   typedef fmi2Status fmi2GetDirectionalDerivativeTYPE(fmi2Component, const fmi2ValueReference[], size_t,
+                                                                   const fmi2ValueReference[], size_t,
+                                                                   const fmi2Real[], fmi2Real[]);
+
+/***************************************************
+Types for Functions for FMI2 for Model Exchange
+****************************************************/
+
+/* Enter and exit the different modes */
+   typedef fmi2Status fmi2EnterEventModeTYPE         (fmi2Component);
+   typedef fmi2Status fmi2NewDiscreteStatesTYPE      (fmi2Component, fmi2EventInfo*);
+   typedef fmi2Status fmi2EnterContinuousTimeModeTYPE(fmi2Component);
+   typedef fmi2Status fmi2CompletedIntegratorStepTYPE(fmi2Component, fmi2Boolean, fmi2Boolean*, fmi2Boolean*);
+
+/* Providing independent variables and re-initialization of caching */
+   typedef fmi2Status fmi2SetTimeTYPE            (fmi2Component, fmi2Real);
+   typedef fmi2Status fmi2SetContinuousStatesTYPE(fmi2Component, const fmi2Real[], size_t);
+
+/* Evaluation of the model equations */
+   typedef fmi2Status fmi2GetDerivativesTYPE               (fmi2Component, fmi2Real[], size_t);
+#ifdef FMU_EXPERIMENTAL
+   typedef fmi2Status fmi2GetSpecificDerivativesTYPE       (fmi2Component, fmi2Real[], const fmi2ValueReference [], size_t);
+#endif
+
+   typedef fmi2Status fmi2GetEventIndicatorsTYPE           (fmi2Component, fmi2Real[], size_t);
+   typedef fmi2Status fmi2GetContinuousStatesTYPE          (fmi2Component, fmi2Real[], size_t);
+   typedef fmi2Status fmi2GetNominalsOfContinuousStatesTYPE(fmi2Component, fmi2Real[], size_t);
+
+
+/***************************************************
+Types for Functions for FMI2 for Co-Simulation
+****************************************************/
+
+/* Simulating the slave */
+   typedef fmi2Status fmi2SetRealInputDerivativesTYPE (fmi2Component, const fmi2ValueReference [], size_t, const fmi2Integer [], const fmi2Real []);
+   typedef fmi2Status fmi2GetRealOutputDerivativesTYPE(fmi2Component, const fmi2ValueReference [], size_t, const fmi2Integer [], fmi2Real []);
+
+   typedef fmi2Status fmi2DoStepTYPE     (fmi2Component, fmi2Real, fmi2Real, fmi2Boolean);
+   typedef fmi2Status fmi2CancelStepTYPE (fmi2Component);
+
+/* Inquire slave status */
+   typedef fmi2Status fmi2GetStatusTYPE       (fmi2Component, const fmi2StatusKind, fmi2Status* );
+   typedef fmi2Status fmi2GetRealStatusTYPE   (fmi2Component, const fmi2StatusKind, fmi2Real*   );
+   typedef fmi2Status fmi2GetIntegerStatusTYPE(fmi2Component, const fmi2StatusKind, fmi2Integer*);
+   typedef fmi2Status fmi2GetBooleanStatusTYPE(fmi2Component, const fmi2StatusKind, fmi2Boolean*);
+   typedef fmi2Status fmi2GetStringStatusTYPE (fmi2Component, const fmi2StatusKind, fmi2String* );
+
+
+#ifdef __cplusplus
+}  /* end of extern "C" { */
+#endif
+
+#endif /* fmi2FunctionTypes_h */

+ 339 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_Window_sa/fmi2/fmi2Functions.h

@@ -0,0 +1,339 @@
+#ifndef fmi2Functions_h
+#define fmi2Functions_h
+
+/* This header file must be utilized when compiling a FMU.
+   It defines all functions of the
+         FMI 2.0 Model Exchange and Co-Simulation Interface.
+
+   In order to have unique function names even if several FMUs
+   are compiled together (e.g. for embedded systems), every "real" function name
+   is constructed by prepending the function name by "FMI2_FUNCTION_PREFIX".
+   Therefore, the typical usage is:
+
+      #define FMI2_FUNCTION_PREFIX MyModel_
+      #include "fmi2Functions.h"
+
+   As a result, a function that is defined as "fmi2GetDerivatives" in this header file,
+   is actually getting the name "MyModel_fmi2GetDerivatives".
+
+   This only holds if the FMU is shipped in C source code, or is compiled in a
+   static link library. For FMUs compiled in a DLL/sharedObject, the "actual" function
+   names are used and "FMI2_FUNCTION_PREFIX" must not be defined.
+
+   Revisions:
+   - Apr.  9, 2014: all prefixes "fmi" renamed to "fmi2" (decision from April 8)
+   - Mar. 26, 2014: FMI_Export set to empty value if FMI_Export and FMI_FUNCTION_PREFIX
+                    are not defined (#173)
+   - Oct. 11, 2013: Functions of ModelExchange and CoSimulation merged:
+                      fmiInstantiateModel , fmiInstantiateSlave  -> fmiInstantiate
+                      fmiFreeModelInstance, fmiFreeSlaveInstance -> fmiFreeInstance
+                      fmiEnterModelInitializationMode, fmiEnterSlaveInitializationMode -> fmiEnterInitializationMode
+                      fmiExitModelInitializationMode , fmiExitSlaveInitializationMode  -> fmiExitInitializationMode
+                      fmiTerminateModel, fmiTerminateSlave  -> fmiTerminate
+                      fmiResetSlave -> fmiReset (now also for ModelExchange and not only for CoSimulation)
+                    Functions renamed:
+                      fmiUpdateDiscreteStates -> fmiNewDiscreteStates
+   - June 13, 2013: Functions removed:
+                       fmiInitializeModel
+                       fmiEventUpdate
+                       fmiCompletedEventIteration
+                       fmiInitializeSlave
+                    Functions added:
+                       fmiEnterModelInitializationMode
+                       fmiExitModelInitializationMode
+                       fmiEnterEventMode
+                       fmiUpdateDiscreteStates
+                       fmiEnterContinuousTimeMode
+                       fmiEnterSlaveInitializationMode;
+                       fmiExitSlaveInitializationMode;
+   - Feb. 17, 2013: Portability improvements:
+                       o DllExport changed to FMI_Export
+                       o FUNCTION_PREFIX changed to FMI_FUNCTION_PREFIX
+                       o Allow undefined FMI_FUNCTION_PREFIX (meaning no prefix is used)
+                    Changed function name "fmiTerminate" to "fmiTerminateModel" (due to #113)
+                    Changed function name "fmiGetNominalContinuousState" to
+                                          "fmiGetNominalsOfContinuousStates"
+                    Removed fmiGetStateValueReferences.
+   - Nov. 14, 2011: Adapted to FMI 2.0:
+                       o Split into two files (fmiFunctions.h, fmiTypes.h) in order
+                         that code that dynamically loads an FMU can directly
+                         utilize the header files).
+                       o Added C++ encapsulation of C-part, in order that the header
+                         file can be directly utilized in C++ code.
+                       o fmiCallbackFunctions is passed as pointer to fmiInstantiateXXX
+                       o stepFinished within fmiCallbackFunctions has as first
+                         argument "fmiComponentEnvironment" and not "fmiComponent".
+                       o New functions to get and set the complete FMU state
+                         and to compute partial derivatives.
+   - Nov.  4, 2010: Adapted to specification text:
+                       o fmiGetModelTypesPlatform renamed to fmiGetTypesPlatform
+                       o fmiInstantiateSlave: Argument GUID     replaced by fmuGUID
+                                              Argument mimetype replaced by mimeType
+                       o tabs replaced by spaces
+   - Oct. 16, 2010: Functions for FMI for Co-simulation added
+   - Jan. 20, 2010: stateValueReferencesChanged added to struct fmiEventInfo (ticket #27)
+                    (by M. Otter, DLR)
+                    Added WIN32 pragma to define the struct layout (ticket #34)
+                    (by J. Mauss, QTronic)
+   - Jan.  4, 2010: Removed argument intermediateResults from fmiInitialize
+                    Renamed macro fmiGetModelFunctionsVersion to fmiGetVersion
+                    Renamed macro fmiModelFunctionsVersion to fmiVersion
+                    Replaced fmiModel by fmiComponent in decl of fmiInstantiateModel
+                    (by J. Mauss, QTronic)
+   - Dec. 17, 2009: Changed extension "me" to "fmi" (by Martin Otter, DLR).
+   - Dez. 14, 2009: Added eventInfo to meInitialize and added
+                    meGetNominalContinuousStates (by Martin Otter, DLR)
+   - Sept. 9, 2009: Added DllExport (according to Peter Nilsson's suggestion)
+                    (by A. Junghanns, QTronic)
+   - Sept. 9, 2009: Changes according to FMI-meeting on July 21:
+                    meInquireModelTypesVersion     -> meGetModelTypesPlatform
+                    meInquireModelFunctionsVersion -> meGetModelFunctionsVersion
+                    meSetStates                    -> meSetContinuousStates
+                    meGetStates                    -> meGetContinuousStates
+                    removal of meInitializeModelClass
+                    removal of meGetTime
+                    change of arguments of meInstantiateModel
+                    change of arguments of meCompletedIntegratorStep
+                    (by Martin Otter, DLR):
+   - July 19, 2009: Added "me" as prefix to file names (by Martin Otter, DLR).
+   - March 2, 2009: Changed function definitions according to the last design
+                    meeting with additional improvements (by Martin Otter, DLR).
+   - Dec. 3 , 2008: First version by Martin Otter (DLR) and Hans Olsson (Dynasim).
+
+   Copyright (C) 2008-2011 MODELISAR consortium,
+               2012-2013 Modelica Association Project "FMI"
+               All rights reserved.
+   This file is licensed by the copyright holders under the BSD 2-Clause License
+   (http://www.opensource.org/licenses/bsd-license.html):
+
+   ----------------------------------------------------------------------------
+   Redistribution and use in source and binary forms, with or without
+   modification, are permitted provided that the following conditions are met:
+
+   - Redistributions of source code must retain the above copyright notice,
+     this list of conditions and the following disclaimer.
+   - Redistributions in binary form must reproduce the above copyright notice,
+     this list of conditions and the following disclaimer in the documentation
+     and/or other materials provided with the distribution.
+   - Neither the name of the copyright holders nor the names of its
+     contributors may be used to endorse or promote products derived
+     from this software without specific prior written permission.
+
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+   TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+   PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
+   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+   OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+   OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+   ----------------------------------------------------------------------------
+
+   with the extension:
+
+   You may distribute or publicly perform any modification only under the
+   terms of this license.
+   (Note, this means that if you distribute a modified file,
+    the modified file must also be provided under this license).
+*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "fmi2TypesPlatform.h"
+#include "fmi2FunctionTypes.h"
+#include <stdlib.h>
+
+
+/*
+  Export FMI2 API functions on Windows and under GCC.
+  If custom linking is desired then the FMI2_Export must be
+  defined before including this file. For instance,
+  it may be set to __declspec(dllimport).
+*/
+#if !defined(FMI2_Export)
+  #if !defined(FMI2_FUNCTION_PREFIX)
+    #if defined _WIN32 || defined __CYGWIN__
+     /* Note: both gcc & MSVC on Windows support this syntax. */
+        #define FMI2_Export __declspec(dllexport)
+    #else
+      #if __GNUC__ >= 4
+        #define FMI2_Export __attribute__ ((visibility ("default")))
+      #else
+        #define FMI2_Export
+      #endif
+    #endif
+  #else
+    #define FMI2_Export
+  #endif
+#endif
+
+/* Macros to construct the real function name
+   (prepend function name by FMI2_FUNCTION_PREFIX) */
+#if defined(FMI2_FUNCTION_PREFIX)
+  #define fmi2Paste(a,b)     a ## b
+  #define fmi2PasteB(a,b)    fmi2Paste(a,b)
+  #define fmi2FullName(name) fmi2PasteB(FMI2_FUNCTION_PREFIX, name)
+#else
+  #define fmi2FullName(name) name
+#endif
+
+/***************************************************
+Common Functions
+****************************************************/
+#define fmi2GetTypesPlatform         fmi2FullName(fmi2GetTypesPlatform)
+#define fmi2GetVersion               fmi2FullName(fmi2GetVersion)
+#define fmi2SetDebugLogging          fmi2FullName(fmi2SetDebugLogging)
+#define fmi2Instantiate              fmi2FullName(fmi2Instantiate)
+#define fmi2FreeInstance             fmi2FullName(fmi2FreeInstance)
+#define fmi2SetupExperiment          fmi2FullName(fmi2SetupExperiment)
+#define fmi2EnterInitializationMode  fmi2FullName(fmi2EnterInitializationMode)
+#define fmi2ExitInitializationMode   fmi2FullName(fmi2ExitInitializationMode)
+#define fmi2Terminate                fmi2FullName(fmi2Terminate)
+#define fmi2Reset                    fmi2FullName(fmi2Reset)
+#define fmi2GetReal                  fmi2FullName(fmi2GetReal)
+#define fmi2GetInteger               fmi2FullName(fmi2GetInteger)
+#define fmi2GetBoolean               fmi2FullName(fmi2GetBoolean)
+#define fmi2GetString                fmi2FullName(fmi2GetString)
+#define fmi2SetReal                  fmi2FullName(fmi2SetReal)
+#define fmi2SetInteger               fmi2FullName(fmi2SetInteger)
+#define fmi2SetBoolean               fmi2FullName(fmi2SetBoolean)
+#define fmi2SetString                fmi2FullName(fmi2SetString)
+#define fmi2GetFMUstate              fmi2FullName(fmi2GetFMUstate)
+#define fmi2SetFMUstate              fmi2FullName(fmi2SetFMUstate)
+#define fmi2FreeFMUstate             fmi2FullName(fmi2FreeFMUstate)
+#define fmi2SerializedFMUstateSize   fmi2FullName(fmi2SerializedFMUstateSize)
+#define fmi2SerializeFMUstate        fmi2FullName(fmi2SerializeFMUstate)
+#define fmi2DeSerializeFMUstate      fmi2FullName(fmi2DeSerializeFMUstate)
+#define fmi2GetDirectionalDerivative fmi2FullName(fmi2GetDirectionalDerivative)
+
+
+/***************************************************
+Functions for FMI2 for Model Exchange
+****************************************************/
+#define fmi2EnterEventMode                fmi2FullName(fmi2EnterEventMode)
+#define fmi2NewDiscreteStates             fmi2FullName(fmi2NewDiscreteStates)
+#define fmi2EnterContinuousTimeMode       fmi2FullName(fmi2EnterContinuousTimeMode)
+#define fmi2CompletedIntegratorStep       fmi2FullName(fmi2CompletedIntegratorStep)
+#define fmi2SetTime                       fmi2FullName(fmi2SetTime)
+#define fmi2SetContinuousStates           fmi2FullName(fmi2SetContinuousStates)
+#define fmi2GetDerivatives                fmi2FullName(fmi2GetDerivatives)
+#ifdef FMU_EXPERIMENTAL
+#define fmi2GetSpecificDerivatives        fmi2FullName(fmi2GetSpecificDerivatives)
+#endif
+#define fmi2GetEventIndicators            fmi2FullName(fmi2GetEventIndicators)
+#define fmi2GetContinuousStates           fmi2FullName(fmi2GetContinuousStates)
+#define fmi2GetNominalsOfContinuousStates fmi2FullName(fmi2GetNominalsOfContinuousStates)
+
+
+/***************************************************
+Functions for FMI2 for Co-Simulation
+****************************************************/
+#define fmi2SetRealInputDerivatives      fmi2FullName(fmi2SetRealInputDerivatives)
+#define fmi2GetRealOutputDerivatives     fmi2FullName(fmi2GetRealOutputDerivatives)
+#define fmi2DoStep                       fmi2FullName(fmi2DoStep)
+#define fmi2CancelStep                   fmi2FullName(fmi2CancelStep)
+#define fmi2GetStatus                    fmi2FullName(fmi2GetStatus)
+#define fmi2GetRealStatus                fmi2FullName(fmi2GetRealStatus)
+#define fmi2GetIntegerStatus             fmi2FullName(fmi2GetIntegerStatus)
+#define fmi2GetBooleanStatus             fmi2FullName(fmi2GetBooleanStatus)
+#define fmi2GetStringStatus              fmi2FullName(fmi2GetStringStatus)
+
+/* Version number */
+#define fmi2Version "2.0"
+
+
+/***************************************************
+Common Functions
+****************************************************/
+
+/* Inquire version numbers of header files */
+   FMI2_Export fmi2GetTypesPlatformTYPE fmi2GetTypesPlatform;
+   FMI2_Export fmi2GetVersionTYPE       fmi2GetVersion;
+   FMI2_Export fmi2SetDebugLoggingTYPE  fmi2SetDebugLogging;
+
+/* Creation and destruction of FMU instances */
+   FMI2_Export fmi2InstantiateTYPE  fmi2Instantiate;
+   FMI2_Export fmi2FreeInstanceTYPE fmi2FreeInstance;
+
+/* Enter and exit initialization mode, terminate and reset */
+   FMI2_Export fmi2SetupExperimentTYPE         fmi2SetupExperiment;
+   FMI2_Export fmi2EnterInitializationModeTYPE fmi2EnterInitializationMode;
+   FMI2_Export fmi2ExitInitializationModeTYPE  fmi2ExitInitializationMode;
+   FMI2_Export fmi2TerminateTYPE               fmi2Terminate;
+   FMI2_Export fmi2ResetTYPE                   fmi2Reset;
+
+/* Getting and setting variables values */
+   FMI2_Export fmi2GetRealTYPE    fmi2GetReal;
+   FMI2_Export fmi2GetIntegerTYPE fmi2GetInteger;
+   FMI2_Export fmi2GetBooleanTYPE fmi2GetBoolean;
+   FMI2_Export fmi2GetStringTYPE  fmi2GetString;
+
+   FMI2_Export fmi2SetRealTYPE    fmi2SetReal;
+   FMI2_Export fmi2SetIntegerTYPE fmi2SetInteger;
+   FMI2_Export fmi2SetBooleanTYPE fmi2SetBoolean;
+   FMI2_Export fmi2SetStringTYPE  fmi2SetString;
+
+/* Getting and setting the internal FMU state */
+   FMI2_Export fmi2GetFMUstateTYPE            fmi2GetFMUstate;
+   FMI2_Export fmi2SetFMUstateTYPE            fmi2SetFMUstate;
+   FMI2_Export fmi2FreeFMUstateTYPE           fmi2FreeFMUstate;
+   FMI2_Export fmi2SerializedFMUstateSizeTYPE fmi2SerializedFMUstateSize;
+   FMI2_Export fmi2SerializeFMUstateTYPE      fmi2SerializeFMUstate;
+   FMI2_Export fmi2DeSerializeFMUstateTYPE    fmi2DeSerializeFMUstate;
+
+/* Getting partial derivatives */
+   FMI2_Export fmi2GetDirectionalDerivativeTYPE fmi2GetDirectionalDerivative;
+
+
+/***************************************************
+Functions for FMI2 for Model Exchange
+****************************************************/
+
+/* Enter and exit the different modes */
+   FMI2_Export fmi2EnterEventModeTYPE               fmi2EnterEventMode;
+   FMI2_Export fmi2NewDiscreteStatesTYPE            fmi2NewDiscreteStates;
+   FMI2_Export fmi2EnterContinuousTimeModeTYPE      fmi2EnterContinuousTimeMode;
+   FMI2_Export fmi2CompletedIntegratorStepTYPE      fmi2CompletedIntegratorStep;
+
+/* Providing independent variables and re-initialization of caching */
+   FMI2_Export fmi2SetTimeTYPE             fmi2SetTime;
+   FMI2_Export fmi2SetContinuousStatesTYPE fmi2SetContinuousStates;
+
+/* Evaluation of the model equations */
+   FMI2_Export fmi2GetDerivativesTYPE                fmi2GetDerivatives;
+#ifdef FMU_EXPERIMENTAL
+   FMI2_Export fmi2GetSpecificDerivativesTYPE        fmi2GetSpecificDerivatives;
+#endif
+   FMI2_Export fmi2GetEventIndicatorsTYPE            fmi2GetEventIndicators;
+   FMI2_Export fmi2GetContinuousStatesTYPE           fmi2GetContinuousStates;
+   FMI2_Export fmi2GetNominalsOfContinuousStatesTYPE fmi2GetNominalsOfContinuousStates;
+
+
+/***************************************************
+Functions for FMI2 for Co-Simulation
+****************************************************/
+
+/* Simulating the slave */
+   FMI2_Export fmi2SetRealInputDerivativesTYPE  fmi2SetRealInputDerivatives;
+   FMI2_Export fmi2GetRealOutputDerivativesTYPE fmi2GetRealOutputDerivatives;
+
+   FMI2_Export fmi2DoStepTYPE     fmi2DoStep;
+   FMI2_Export fmi2CancelStepTYPE fmi2CancelStep;
+
+/* Inquire slave status */
+   FMI2_Export fmi2GetStatusTYPE        fmi2GetStatus;
+   FMI2_Export fmi2GetRealStatusTYPE    fmi2GetRealStatus;
+   FMI2_Export fmi2GetIntegerStatusTYPE fmi2GetIntegerStatus;
+   FMI2_Export fmi2GetBooleanStatusTYPE fmi2GetBooleanStatus;
+   FMI2_Export fmi2GetStringStatusTYPE  fmi2GetStringStatus;
+
+#ifdef __cplusplus
+}  /* end of extern "C" { */
+#endif
+
+#endif /* fmi2Functions_h */

+ 115 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_Window_sa/fmi2/fmi2TypesPlatform.h

@@ -0,0 +1,115 @@
+#ifndef fmi2TypesPlatform_h
+#define fmi2TypesPlatform_h
+
+/* Standard header file to define the argument types of the
+   functions of the Functional Mock-up Interface 2.0.
+   This header file must be utilized both by the model and
+   by the simulation engine.
+
+   Revisions:
+   - Apr.  9, 2014: all prefixes "fmi" renamed to "fmi2" (decision from April 8)
+   - Mar   31, 2014: New datatype fmiChar introduced.
+   - Feb.  17, 2013: Changed fmiTypesPlatform from "standard32" to "default".
+                     Removed fmiUndefinedValueReference since no longer needed
+                     (because every state is defined in ScalarVariables).
+   - March 20, 2012: Renamed from fmiPlatformTypes.h to fmiTypesPlatform.h
+   - Nov.  14, 2011: Use the header file "fmiPlatformTypes.h" for FMI 2.0
+                     both for "FMI for model exchange" and for "FMI for co-simulation"
+                     New types "fmiComponentEnvironment", "fmiState", and "fmiByte".
+                     The implementation of "fmiBoolean" is change from "char" to "int".
+                     The #define "fmiPlatform" changed to "fmiTypesPlatform"
+                     (in order that #define and function call are consistent)
+   - Oct.   4, 2010: Renamed header file from "fmiModelTypes.h" to fmiPlatformTypes.h"
+                     for the co-simulation interface
+   - Jan.   4, 2010: Renamed meModelTypes_h to fmiModelTypes_h (by Mauss, QTronic)
+   - Dec.  21, 2009: Changed "me" to "fmi" and "meModel" to "fmiComponent"
+                     according to meeting on Dec. 18 (by Martin Otter, DLR)
+   - Dec.   6, 2009: Added meUndefinedValueReference (by Martin Otter, DLR)
+   - Sept.  9, 2009: Changes according to FMI-meeting on July 21:
+                     Changed "version" to "platform", "standard" to "standard32",
+                     Added a precise definition of "standard32" as comment
+                     (by Martin Otter, DLR)
+   - July  19, 2009: Added "me" as prefix to file names, added meTrue/meFalse,
+                     and changed meValueReferenced from int to unsigned int
+                     (by Martin Otter, DLR).
+   - March  2, 2009: Moved enums and function pointer definitions to
+                     ModelFunctions.h (by Martin Otter, DLR).
+   - Dec.  3, 2008 : First version by Martin Otter (DLR) and
+                     Hans Olsson (Dynasim).
+
+
+   Copyright (C) 2008-2011 MODELISAR consortium,
+               2012-2013 Modelica Association Project "FMI"
+               All rights reserved.
+   This file is licensed by the copyright holders under the BSD 2-Clause License
+   (http://www.opensource.org/licenses/bsd-license.html):
+
+   ----------------------------------------------------------------------------
+   Redistribution and use in source and binary forms, with or without
+   modification, are permitted provided that the following conditions are met:
+
+   - Redistributions of source code must retain the above copyright notice,
+     this list of conditions and the following disclaimer.
+   - Redistributions in binary form must reproduce the above copyright notice,
+     this list of conditions and the following disclaimer in the documentation
+     and/or other materials provided with the distribution.
+   - Neither the name of the copyright holders nor the names of its
+     contributors may be used to endorse or promote products derived
+     from this software without specific prior written permission.
+
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+   TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+   PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
+   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+   OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+   OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+   ----------------------------------------------------------------------------
+
+   with the extension:
+
+   You may distribute or publicly perform any modification only under the
+   terms of this license.
+   (Note, this means that if you distribute a modified file,
+    the modified file must also be provided under this license).
+*/
+
+/* Platform (unique identification of this header file) */
+#define fmi2TypesPlatform "default"
+
+/* Type definitions of variables passed as arguments
+   Version "default" means:
+
+   fmi2Component           : an opaque object pointer
+   fmi2ComponentEnvironment: an opaque object pointer
+   fmi2FMUstate            : an opaque object pointer
+   fmi2ValueReference      : handle to the value of a variable
+   fmi2Real                : double precision floating-point data type
+   fmi2Integer             : basic signed integer data type
+   fmi2Boolean             : basic signed integer data type
+   fmi2Char                : character data type
+   fmi2String              : a pointer to a vector of fmi2Char characters
+                             ('\0' terminated, UTF8 encoded)
+   fmi2Byte                : smallest addressable unit of the machine, typically one byte.
+*/
+   typedef void*           fmi2Component;               /* Pointer to FMU instance       */
+   typedef void*           fmi2ComponentEnvironment;    /* Pointer to FMU environment    */
+   typedef void*           fmi2FMUstate;                /* Pointer to internal FMU state */
+   typedef unsigned int    fmi2ValueReference;
+   typedef double          fmi2Real   ;
+   typedef int             fmi2Integer;
+   typedef int             fmi2Boolean;
+   typedef char            fmi2Char;
+   typedef const fmi2Char* fmi2String;
+   typedef char            fmi2Byte;
+
+/* Values for fmi2Boolean  */
+#define fmi2True  1
+#define fmi2False 0
+
+
+#endif /* fmi2TypesPlatform_h */

+ 593 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_Window_sa/sim_support.c

@@ -0,0 +1,593 @@
+/* -------------------------------------------------------------------------
+ * sim_support.c
+ * Functions used by both FMU simulators fmu20sim_me and fmu20sim_cs
+ * to parse command-line arguments, to unzip and load an fmu,
+ * to write CSV file, and more.
+ *
+ * Revision history
+ *  07.03.2014 initial version released in FMU SDK 2.0.0
+ *  10.04.2014 use FMI 2.0 headers that prefix function and type names with 'fmi2'.
+ *             When 'fmi2' functions are not found in loaded DLL, look also for
+ *             FMI 2.0 RC1 function names.
+ *
+ * Author: Adrian Tirea
+ * Copyright QTronic GmbH. All rights reserved.
+ * -------------------------------------------------------------------------*/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+#include <stdarg.h>
+#include <dlfcn.h>
+#include "fmi2.h"
+#include "sim_support.h"
+
+#define FMI_COSIMULATION
+
+
+//int unzip(const char *zipPath, const char *outPath) {
+//    int code;
+//    char cwd[BUFSIZE];
+//    char binPath[BUFSIZE];
+//    int n = strlen(UNZIP_CMD) + strlen(outPath) + 3 +  strlen(zipPath) + 9;
+//    char* cmd = (char*)calloc(sizeof(char), n);
+//
+//    // remember current directory
+//    if (!GetCurrentDirectory(BUFSIZE, cwd)) {
+//        printf ("error: Could not get current directory\n");
+//        return 0; // error
+//    }
+//
+//    // change to %FMUSDK_HOME%\bin to find 7z.dll and 7z.exe
+//    if (!GetEnvironmentVariable("FMUSDK_HOME", binPath, BUFSIZE)) {
+//        if (GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
+//            printf ("error: Environment variable FMUSDK_HOME not defined\n");
+//        }
+//        else {
+//            printf ("error: Could not get value of FMUSDK_HOME\n");
+//        }
+//        return 0; // error
+//    }
+//    strcat(binPath, "\\bin");
+//    if (!SetCurrentDirectory(binPath)) {
+//        printf ("error: could not change to directory '%s'\n", binPath);
+//        return 0; // error
+//    }
+//
+//    // run the unzip command
+//    // remove "> NUL" to see the unzip protocol
+//    sprintf(cmd, "%s\"%s\" \"%s\" > NUL", UNZIP_CMD, outPath, zipPath);
+//    // printf("cmd='%s'\n", cmd);
+//    code = system(cmd);
+//    free(cmd);
+//    if (code != SEVEN_ZIP_NO_ERROR) {
+//        printf("7z: ");
+//        switch (code) {
+//            case SEVEN_ZIP_WARNING:            printf("warning\n"); break;
+//            case SEVEN_ZIP_ERROR:              printf("error\n"); break;
+//            case SEVEN_ZIP_COMMAND_LINE_ERROR: printf("command line error\n"); break;
+//            case SEVEN_ZIP_OUT_OF_MEMORY:      printf("out of memory\n"); break;
+//            case SEVEN_ZIP_STOPPED_BY_USER:    printf("stopped by user\n"); break;
+//            default: printf("unknown problem\n");
+//        }
+//    }
+//
+//    // restore current directory
+//    SetCurrentDirectory(cwd);
+//    return (code == SEVEN_ZIP_NO_ERROR || code == SEVEN_ZIP_WARNING) ? 1 : 0;
+//}
+//
+//// fileName is an absolute path, e.g. C:\test\a.fmu
+//// or relative to the current dir, e.g. ..\test\a.fmu
+//// Does not check for existence of the file
+//static char* getFmuPath(const char* fileName){
+//    char pathName[MAX_PATH];
+//    int n = GetFullPathName(fileName, MAX_PATH, pathName, NULL);
+//    return n ? strdup(pathName) : NULL;
+//}
+//
+//static char* getTmpPath() {
+//    char tmpPath[BUFSIZE];
+//    if(! GetTempPath(BUFSIZE, tmpPath)) {
+//        printf ("error: Could not find temporary disk space\n");
+//        return NULL;
+//    }
+//    strcat(tmpPath, "fmu\\");
+//    return strdup(tmpPath);
+//}
+//
+//char *getTempResourcesLocation() {
+//    char *tempPath = getTmpPath();
+//    char *resourcesLocation = (char *)calloc(sizeof(char), 9 + strlen(RESOURCES_DIR) + strlen(tempPath));
+//    strcpy(resourcesLocation, "file:///");
+//    strcat(resourcesLocation, tempPath);
+//    strcat(resourcesLocation, RESOURCES_DIR);
+//    free(tempPath);
+//    return resourcesLocation;
+//}
+
+static void *getAdr(int *success, void *dllHandle, const char *functionName, const char* preamble) {
+
+    int length = strlen(preamble) + strlen(functionName) + 1;
+    char* new_name = malloc(length);  // allocate memory
+    strcpy(new_name, preamble);  // copy first string
+    strcat(new_name, functionName);
+    void* fp = dlsym(dllHandle, new_name);
+    if (!fp) {
+        printf("warning: Function %s not found in dll\n", new_name);
+        *success = 0;
+    }
+    free(new_name);
+    return fp;
+}
+
+// Load the given dll and set function pointers in fmu
+// Return 0 to indicate failure
+int loadDll(const char* dllPath, FMU *fmu, const char* preamble) {
+    int s = 1;
+    //HMODULE h = LoadLibrary(dllPath);
+    void *h = dlopen(dllPath, RTLD_LAZY);
+    printf("%s", dlerror());
+    if (!h) {
+        printf("error: Could not load %s\n", dllPath);
+        return 0; // failure
+    }
+    fmu->dllHandle = h;
+    fmu->getTypesPlatform          = (fmi2GetTypesPlatformTYPE *)      getAdr(&s, h, "fmi2GetTypesPlatform", preamble);
+    fmu->getVersion                = (fmi2GetVersionTYPE *)            getAdr(&s, h, "fmi2GetVersion", preamble);
+    fmu->setDebugLogging           = (fmi2SetDebugLoggingTYPE *)       getAdr(&s, h, "fmi2SetDebugLogging",preamble);
+    fmu->instantiate               = (fmi2InstantiateTYPE *)           getAdr(&s, h, "fmi2Instantiate", preamble);
+    fmu->freeInstance              = (fmi2FreeInstanceTYPE *)          getAdr(&s, h, "fmi2FreeInstance", preamble);
+    fmu->setupExperiment           = (fmi2SetupExperimentTYPE *)       getAdr(&s, h, "fmi2SetupExperiment", preamble);
+    fmu->enterInitializationMode   = (fmi2EnterInitializationModeTYPE *) getAdr(&s, h, "fmi2EnterInitializationMode", preamble);
+    fmu->exitInitializationMode    = (fmi2ExitInitializationModeTYPE *) getAdr(&s, h, "fmi2ExitInitializationMode", preamble);
+    fmu->terminate                 = (fmi2TerminateTYPE *)             getAdr(&s, h, "fmi2Terminate", preamble);
+    fmu->reset                     = (fmi2ResetTYPE *)                 getAdr(&s, h, "fmi2Reset", preamble);
+    fmu->getReal                   = (fmi2GetRealTYPE *)               getAdr(&s, h, "fmi2GetReal", preamble);
+    fmu->getInteger                = (fmi2GetIntegerTYPE *)            getAdr(&s, h, "fmi2GetInteger", preamble);
+    fmu->getBoolean                = (fmi2GetBooleanTYPE *)            getAdr(&s, h, "fmi2GetBoolean", preamble);
+    fmu->getString                 = (fmi2GetStringTYPE *)             getAdr(&s, h, "fmi2GetString", preamble);
+    fmu->setReal                   = (fmi2SetRealTYPE *)               getAdr(&s, h, "fmi2SetReal", preamble);
+    fmu->setInteger                = (fmi2SetIntegerTYPE *)            getAdr(&s, h, "fmi2SetInteger", preamble);
+    fmu->setBoolean                = (fmi2SetBooleanTYPE *)            getAdr(&s, h, "fmi2SetBoolean", preamble);
+    fmu->setString                 = (fmi2SetStringTYPE *)             getAdr(&s, h, "fmi2SetString", preamble);
+    fmu->getFMUstate               = (fmi2GetFMUstateTYPE *)           getAdr(&s, h, "fmi2GetFMUstate", preamble);
+    fmu->setFMUstate               = (fmi2SetFMUstateTYPE *)           getAdr(&s, h, "fmi2SetFMUstate", preamble);
+    fmu->freeFMUstate              = (fmi2FreeFMUstateTYPE *)          getAdr(&s, h, "fmi2FreeFMUstate", preamble);
+    fmu->serializedFMUstateSize    = (fmi2SerializedFMUstateSizeTYPE *) getAdr(&s, h, "fmi2SerializedFMUstateSize", preamble);
+    fmu->serializeFMUstate         = (fmi2SerializeFMUstateTYPE *)     getAdr(&s, h, "fmi2SerializeFMUstate", preamble);
+    fmu->deSerializeFMUstate       = (fmi2DeSerializeFMUstateTYPE *)   getAdr(&s, h, "fmi2DeSerializeFMUstate", preamble);
+    fmu->getDirectionalDerivative  = (fmi2GetDirectionalDerivativeTYPE *) getAdr(&s, h, "fmi2GetDirectionalDerivative", preamble);
+#ifdef FMI_COSIMULATION
+    fmu->setRealInputDerivatives   = (fmi2SetRealInputDerivativesTYPE *) getAdr(&s, h, "fmi2SetRealInputDerivatives", preamble);
+    fmu->getRealOutputDerivatives  = (fmi2GetRealOutputDerivativesTYPE *) getAdr(&s, h, "fmi2GetRealOutputDerivatives", preamble);
+    fmu->doStep                    = (fmi2DoStepTYPE *)                getAdr(&s, h, "fmi2DoStep", preamble);
+    fmu->cancelStep                = (fmi2CancelStepTYPE *)            getAdr(&s, h, "fmi2CancelStep", preamble);
+    fmu->getStatus                 = (fmi2GetStatusTYPE *)             getAdr(&s, h, "fmi2GetStatus", preamble);
+    fmu->getRealStatus             = (fmi2GetRealStatusTYPE *)         getAdr(&s, h, "fmi2GetRealStatus", preamble);
+    fmu->getIntegerStatus          = (fmi2GetIntegerStatusTYPE *)      getAdr(&s, h, "fmi2GetIntegerStatus", preamble);
+    fmu->getBooleanStatus          = (fmi2GetBooleanStatusTYPE *)      getAdr(&s, h, "fmi2GetBooleanStatus", preamble);
+    fmu->getStringStatus           = (fmi2GetStringStatusTYPE *)       getAdr(&s, h, "fmi2GetStringStatus", preamble);
+#else // FMI2 for Model Exchange
+    fmu->enterEventMode            = (fmi2EnterEventModeTYPE *)        getAdr(&s, h, "fmi2EnterEventMode", preamble);
+    fmu->newDiscreteStates         = (fmi2NewDiscreteStatesTYPE *)     getAdr(&s, h, "fmi2NewDiscreteStates", preamble);
+    fmu->enterContinuousTimeMode   = (fmi2EnterContinuousTimeModeTYPE *) getAdr(&s, h, "fmi2EnterContinuousTimeMode", preamble);
+    fmu->completedIntegratorStep   = (fmi2CompletedIntegratorStepTYPE *) getAdr(&s, h, "fmi2CompletedIntegratorStep", preamble);
+    fmu->setTime                   = (fmi2SetTimeTYPE *)               getAdr(&s, h, "fmi2SetTime", preamble);
+    fmu->setContinuousStates       = (fmi2SetContinuousStatesTYPE *)   getAdr(&s, h, "fmi2SetContinuousStates", preamble);
+    fmu->getDerivatives            = (fmi2GetDerivativesTYPE *)        getAdr(&s, h, "fmi2GetDerivatives", preamble);
+    fmu->getEventIndicators        = (fmi2GetEventIndicatorsTYPE *)    getAdr(&s, h, "fmi2GetEventIndicators", preamble);
+    fmu->getContinuousStates       = (fmi2GetContinuousStatesTYPE *)   getAdr(&s, h, "fmi2GetContinuousStates", preamble);
+    fmu->getNominalsOfContinuousStates = (fmi2GetNominalsOfContinuousStatesTYPE *) getAdr(&s, h, "fmi2GetNominalsOfContinuousStates", preamble);
+#endif
+
+    if (fmu->getVersion == NULL && fmu->instantiate == NULL) {
+        printf("warning: Functions from FMI 2.0 could not be found in %s\n", dllPath);
+        printf("warning: Simulator will look for FMI 2.0 RC1 functions names...\n");
+        fmu->getTypesPlatform          = (fmi2GetTypesPlatformTYPE *)      getAdr(&s, h, "fmiGetTypesPlatform", preamble);
+        fmu->getVersion                = (fmi2GetVersionTYPE *)            getAdr(&s, h, "fmiGetVersion", preamble);
+        fmu->setDebugLogging           = (fmi2SetDebugLoggingTYPE *)       getAdr(&s, h, "fmiSetDebugLogging", preamble);
+        fmu->instantiate               = (fmi2InstantiateTYPE *)           getAdr(&s, h, "fmiInstantiate", preamble);
+        fmu->freeInstance              = (fmi2FreeInstanceTYPE *)          getAdr(&s, h, "fmiFreeInstance", preamble);
+        fmu->setupExperiment           = (fmi2SetupExperimentTYPE *)       getAdr(&s, h, "fmiSetupExperiment", preamble);
+        fmu->enterInitializationMode   = (fmi2EnterInitializationModeTYPE *) getAdr(&s, h, "fmiEnterInitializationMode", preamble);
+        fmu->exitInitializationMode    = (fmi2ExitInitializationModeTYPE *) getAdr(&s, h, "fmiExitInitializationMode", preamble);
+        fmu->terminate                 = (fmi2TerminateTYPE *)             getAdr(&s, h, "fmiTerminate", preamble);
+        fmu->reset                     = (fmi2ResetTYPE *)                 getAdr(&s, h, "fmiReset", preamble);
+        fmu->getReal                   = (fmi2GetRealTYPE *)               getAdr(&s, h, "fmiGetReal", preamble);
+        fmu->getInteger                = (fmi2GetIntegerTYPE *)            getAdr(&s, h, "fmiGetInteger", preamble);
+        fmu->getBoolean                = (fmi2GetBooleanTYPE *)            getAdr(&s, h, "fmiGetBoolean", preamble);
+        fmu->getString                 = (fmi2GetStringTYPE *)             getAdr(&s, h, "fmiGetString", preamble);
+        fmu->setReal                   = (fmi2SetRealTYPE *)               getAdr(&s, h, "fmiSetReal", preamble);
+        fmu->setInteger                = (fmi2SetIntegerTYPE *)            getAdr(&s, h, "fmiSetInteger", preamble);
+        fmu->setBoolean                = (fmi2SetBooleanTYPE *)            getAdr(&s, h, "fmiSetBoolean", preamble);
+        fmu->setString                 = (fmi2SetStringTYPE *)             getAdr(&s, h, "fmiSetString", preamble);
+        fmu->getFMUstate               = (fmi2GetFMUstateTYPE *)           getAdr(&s, h, "fmiGetFMUstate", preamble);
+        fmu->setFMUstate               = (fmi2SetFMUstateTYPE *)           getAdr(&s, h, "fmiSetFMUstate", preamble);
+        fmu->freeFMUstate              = (fmi2FreeFMUstateTYPE *)          getAdr(&s, h, "fmiFreeFMUstate", preamble);
+        fmu->serializedFMUstateSize    = (fmi2SerializedFMUstateSizeTYPE *) getAdr(&s, h, "fmiSerializedFMUstateSize", preamble);
+        fmu->serializeFMUstate         = (fmi2SerializeFMUstateTYPE *)     getAdr(&s, h, "fmiSerializeFMUstate", preamble);
+        fmu->deSerializeFMUstate       = (fmi2DeSerializeFMUstateTYPE *)   getAdr(&s, h, "fmiDeSerializeFMUstate", preamble);
+        fmu->getDirectionalDerivative  = (fmi2GetDirectionalDerivativeTYPE *) getAdr(&s, h, "fmiGetDirectionalDerivative", preamble);
+    #ifdef FMI_COSIMULATION
+        fmu->setRealInputDerivatives   = (fmi2SetRealInputDerivativesTYPE *) getAdr(&s, h, "fmiSetRealInputDerivatives", preamble);
+        fmu->getRealOutputDerivatives  = (fmi2GetRealOutputDerivativesTYPE *) getAdr(&s, h, "fmiGetRealOutputDerivatives", preamble);
+        fmu->doStep                    = (fmi2DoStepTYPE *)                getAdr(&s, h, "fmiDoStep", preamble);
+        fmu->cancelStep                = (fmi2CancelStepTYPE *)            getAdr(&s, h, "fmiCancelStep", preamble);
+        fmu->getStatus                 = (fmi2GetStatusTYPE *)             getAdr(&s, h, "fmiGetStatus", preamble);
+        fmu->getRealStatus             = (fmi2GetRealStatusTYPE *)         getAdr(&s, h, "fmiGetRealStatus", preamble);
+        fmu->getIntegerStatus          = (fmi2GetIntegerStatusTYPE *)      getAdr(&s, h, "fmiGetIntegerStatus", preamble);
+        fmu->getBooleanStatus          = (fmi2GetBooleanStatusTYPE *)      getAdr(&s, h, "fmiGetBooleanStatus", preamble);
+        fmu->getStringStatus           = (fmi2GetStringStatusTYPE *)       getAdr(&s, h, "fmiGetStringStatus", preamble);
+    #else // FMI2 for Model Exchange
+        fmu->enterEventMode            = (fmi2EnterEventModeTYPE *)        getAdr(&s, h, "fmiEnterEventMode", preamble);
+        fmu->newDiscreteStates         = (fmi2NewDiscreteStatesTYPE *)     getAdr(&s, h, "fmiNewDiscreteStates", preamble);
+        fmu->enterContinuousTimeMode   = (fmi2EnterContinuousTimeModeTYPE *) getAdr(&s, h, "fmiEnterContinuousTimeMode", preamble);
+        fmu->completedIntegratorStep   = (fmi2CompletedIntegratorStepTYPE *) getAdr(&s, h, "fmiCompletedIntegratorStep", preamble);
+        fmu->setTime                   = (fmi2SetTimeTYPE *)               getAdr(&s, h, "fmiSetTime", preamble);
+        fmu->setContinuousStates       = (fmi2SetContinuousStatesTYPE *)   getAdr(&s, h, "fmiSetContinuousStates", preamble);
+        fmu->getDerivatives            = (fmi2GetDerivativesTYPE *)        getAdr(&s, h, "fmiGetDerivatives", preamble);
+        fmu->getEventIndicators        = (fmi2GetEventIndicatorsTYPE *)    getAdr(&s, h, "fmiGetEventIndicators", preamble);
+        fmu->getContinuousStates       = (fmi2GetContinuousStatesTYPE *)   getAdr(&s, h, "fmiGetContinuousStates", preamble);
+        fmu->getNominalsOfContinuousStates = (fmi2GetNominalsOfContinuousStatesTYPE *) getAdr(&s, h, "fmiGetNominalsOfContinuousStates", preamble);
+    #endif
+    }
+    return s;
+}
+
+//static void printModelDescription(ModelDescription* md){
+//    Element* e = (Element*)md;
+//    int i;
+//    int n; // number of attributes
+//    const char **attributes = getAttributesAsArray(e, &n);
+//    Component *component;
+//
+//    if (!attributes) {
+//        printf("ModelDescription printing aborted.");
+//        return;
+//    }
+//    printf("%s\n", getElementTypeName(e));
+//    for (i = 0; i < n; i += 2) {
+//        printf("  %s=%s\n", attributes[i], attributes[i+1]);
+//    }
+//    free((void *)attributes);
+//
+//#ifdef FMI_COSIMULATION
+//    component = getCoSimulation(md);
+//    if (!component) {
+//        printf("error: No CoSimulation element found in model description. This FMU is not for Co-Simulation.\n");
+//        exit(EXIT_FAILURE);
+//    }
+//#else // FMI_MODEL_EXCHANGE
+//    component = getModelExchange(md);
+//    if (!component) {
+//        printf("error: No ModelExchange element found in model description. This FMU is not for Model Exchange.\n");
+//        exit(EXIT_FAILURE);
+//    }
+//#endif
+//    printf("%s\n", getElementTypeName((Element *)component));
+//    attributes = getAttributesAsArray((Element *)component, &n);
+//    if (!attributes) {
+//        printf("ModelDescription printing aborted.");
+//        return;
+//    }
+//    for (i = 0; i < n; i += 2) {
+//        printf("  %s=%s\n", attributes[i], attributes[i+1]);
+//    }
+//
+//    free((void *)attributes);
+//}
+//
+//void loadFMU(const char* fmuFileName) {
+//    char* fmuPath;
+//    char* tmpPath;
+//    char* xmlPath;
+//    char* dllPath;
+//    const char *modelId;
+//
+//    // get absolute path to FMU, NULL if not found
+//    fmuPath = getFmuPath(fmuFileName);
+//    if (!fmuPath) exit(EXIT_FAILURE);
+//
+//    // unzip the FMU to the tmpPath directory
+//    tmpPath = getTmpPath();
+//    if (!unzip(fmuPath, tmpPath)) exit(EXIT_FAILURE);
+//
+//    // parse tmpPath\modelDescription.xml
+//    xmlPath = calloc(sizeof(char), strlen(tmpPath) + strlen(XML_FILE) + 1);
+//    sprintf(xmlPath, "%s%s", tmpPath, XML_FILE);
+//    fmu.modelDescription = parse(xmlPath);
+//    free(xmlPath);
+//    if (!fmu.modelDescription) exit(EXIT_FAILURE);
+//    printModelDescription(fmu.modelDescription);
+//#ifdef FMI_COSIMULATION
+//    modelId = getAttributeValue((Element *)getCoSimulation(fmu.modelDescription), att_modelIdentifier);
+//#else // FMI_MODEL_EXCHANGE
+//    modelId = getAttributeValue((Element *)getModelExchange(fmu.modelDescription), att_modelIdentifier);
+//#endif
+//    // load the FMU dll
+//    dllPath = calloc(sizeof(char), strlen(tmpPath) + strlen(DLL_DIR)
+//        + strlen(modelId) +  strlen(".dll") + 1);
+//    sprintf(dllPath, "%s%s%s.dll", tmpPath, DLL_DIR, modelId);
+//    if (!loadDll(dllPath, &fmu)) {
+//        exit(EXIT_FAILURE);
+//    }
+//    free(dllPath);
+//    free(fmuPath);
+//    free(tmpPath);
+//}
+//
+//void deleteUnzippedFiles() {
+//    const char *fmuTempPath = getTmpPath();
+//    char *cmd = (char *)calloc(15 + strlen(fmuTempPath), sizeof(char));
+//    sprintf(cmd, "rmdir /S /Q %s", fmuTempPath);
+//    system(cmd);
+//    free(cmd);
+//}
+//
+//static void doubleToCommaString(char* buffer, double r){
+//    char* comma;
+//    sprintf(buffer, "%.16g", r);
+//    comma = strchr(buffer, '.');
+//    if (comma) *comma = ',';
+//}
+//
+//// output time and all variables in CSV format
+//// if separator is ',', columns are separated by ',' and '.' is used for floating-point numbers.
+//// otherwise, the given separator (e.g. ';' or '\t') is to separate columns, and ',' is used
+//// as decimal dot in floating-point numbers.
+//void outputRow(FMU *fmu, fmi2Component c, double time, FILE* file, char separator, fmi2Boolean header) {
+//    int k;
+//    fmi2Real r;
+//    fmi2Integer i;
+//    fmi2Boolean b;
+//    fmi2String s;
+//    fmi2ValueReference vr;
+//    int n = getScalarVariableSize(fmu->modelDescription);
+//    char buffer[32];
+//
+//    // print first column
+//    if (header) {
+//        fprintf(file, "time");
+//    } else {
+//        if (separator==',')
+//            fprintf(file, "%.16g", time);
+//        else {
+//            // separator is e.g. ';' or '\t'
+//            doubleToCommaString(buffer, time);
+//            fprintf(file, "%s", buffer);
+//        }
+//    }
+//
+//    // print all other columns
+//    for (k = 0; k < n; k++) {
+//        ScalarVariable *sv = getScalarVariable(fmu->modelDescription, k);
+//        if (header) {
+//            // output names only
+//            if (separator == ',') {
+//                // treat array element, e.g. print a[1, 2] as a[1.2]
+//                const char *s = getAttributeValue((Element *)sv, att_name);
+//                fprintf(file, "%c", separator);
+//                while (*s) {
+//                    if (*s != ' ') {
+//                        fprintf(file, "%c", *s == ',' ? '.' : *s);
+//                    }
+//                    s++;
+//                }
+//            } else {
+//                fprintf(file, "%c%s", separator, getAttributeValue((Element *)sv, att_name));
+//            }
+//        } else {
+//            // output values
+//            vr = getValueReference(sv);
+//            switch (getElementType(getTypeSpec(sv))) {
+//                case elm_Real:
+//                    fmu->getReal(c, &vr, 1, &r);
+//                    if (separator == ',') {
+//                        fprintf(file, ",%.16g", r);
+//                    } else {
+//                        // separator is e.g. ';' or '\t'
+//                        doubleToCommaString(buffer, r);
+//                        fprintf(file, "%c%s", separator, buffer);
+//                    }
+//                    break;
+//                case elm_Integer:
+//                case elm_Enumeration:
+//                    fmu->getInteger(c, &vr, 1, &i);
+//                    fprintf(file, "%c%d", separator, i);
+//                    break;
+//                case elm_Boolean:
+//                    fmu->getBoolean(c, &vr, 1, &b);
+//                    fprintf(file, "%c%d", separator, b);
+//                    break;
+//                case elm_String:
+//                    fmu->getString(c, &vr, 1, &s);
+//                    fprintf(file, "%c%s", separator, s);
+//                    break;
+//                default:
+//                    fprintf(file, "%cNoValueForType=%d", separator, getElementType(getTypeSpec(sv)));
+//            }
+//        }
+//    } // for
+//
+//    // terminate this row
+//    fprintf(file, "\n");
+//}
+//
+static const char* fmi2StatusToString(fmi2Status status){
+    switch (status){
+        case fmi2OK:      return "ok";
+        case fmi2Warning: return "warning";
+        case fmi2Discard: return "discard";
+        case fmi2Error:   return "error";
+        case fmi2Fatal:   return "fatal";
+    #ifdef FMI_COSIMULATION
+        case fmi2Pending: return "fmi2Pending";
+    #endif
+        default:         return "?";
+    }
+}
+
+// search a fmu for the given variable, matching the type specified.
+// return NULL if not found
+//static ScalarVariable* getSV(FMU* fmu, char type, fmi2ValueReference vr) {
+//    return NULL;
+//    int i;
+//    int n = getScalarVariableSize(fmu->modelDescription);
+//    Elm tp;
+//
+//    switch (type) {
+//        case 'r': tp = elm_Real;    break;
+//        case 'i': tp = elm_Integer; break;
+//        case 'b': tp = elm_Boolean; break;
+//        case 's': tp = elm_String;  break;
+//        default : tp = elm_BAD_DEFINED;
+//    }
+//    for (i = 0; i < n; i++) {
+//        ScalarVariable* sv = getScalarVariable(fmu->modelDescription ,i);
+//        if (vr == getValueReference(sv) && tp == getElementType(getTypeSpec(sv))) {
+//            return sv;
+//        }
+//    }
+//    return NULL;
+//}
+
+// replace e.g. #r1365# by variable name and ## by # in message
+// copies the result to buffer
+static void replaceRefsInMessage(const char* msg, char* buffer, int nBuffer, FMU* fmu){
+    int i = 0; // position in msg
+    int k = 0; // position in buffer
+    int n;
+    char c = msg[i];
+    while (c != '\0' && k < nBuffer) {
+        if (c != '#') {
+            buffer[k++] = c;
+            i++;
+            c = msg[i];
+        } else {
+
+            char* end = strchr(msg + i + 1, '#');
+            if (!end) {
+                printf("unmatched '#' in '%s'\n", msg);
+                buffer[k++] = '#';
+                break;
+            }
+            n = end - (msg + i);
+            if (n == 1) {
+                // ## detected, output #
+                buffer[k++] = '#';
+                i += 2;
+                c = msg[i];
+
+            } else {
+                //char type = msg[i + 1]; // one of ribs
+                fmi2ValueReference vr;
+                int nvr = sscanf(msg + i + 2, "%u", &vr);
+                if (nvr == 1) {
+                    // vr of type detected, e.g. #r12#
+                    //ScalarVariable* sv = getSV(fmu, type, vr);
+                    //const char* name = sv ? getAttributeValue((Element *)sv, att_name) : "?";
+                    //sprintf(buffer + k, "%s", name);
+                    //k += strlen(name);
+                    //i += (n+1);
+                    //c = msg[i];
+
+                } else {
+                    // could not parse the number
+                    printf("illegal value reference at position %d in '%s'\n", i + 2, msg);
+                    buffer[k++] = '#';
+                    break;
+                }
+            }
+        }
+    } // while
+    buffer[k] = '\0';
+}
+
+#define MAX_MSG_SIZE 1000
+void fmuLogger(void *componentEnvironment, fmi2String instanceName, fmi2Status status,
+               fmi2String category, fmi2String message, ...) {
+    char msg[MAX_MSG_SIZE];
+    char* copy;
+    va_list argp;
+
+    // replace C format strings
+    va_start(argp, message);
+    vsprintf(msg, message, argp);
+    va_end(argp);
+
+    // replace e.g. ## and #r12#
+    copy = strdup(msg);
+//    replaceRefsInMessage(copy, msg, MAX_MSG_SIZE, NULL);
+    free(copy);
+
+    // print the final message
+    if (!instanceName) instanceName = "?";
+    if (!category) category = "?";
+    printf("%s %s (%s): %s\n", fmi2StatusToString(status), instanceName, category, msg);
+}
+
+int error(const char* message){
+    printf("%s\n", message);
+    return 0;
+}
+//
+//void parseArguments(int argc, char *argv[], const char **fmuFileName, double *tEnd, double *h,
+//                    int *loggingOn, char *csv_separator, int *nCategories, char **logCategories[]) {
+//    // parse command line arguments
+//    if (argc > 1) {
+//        *fmuFileName = argv[1];
+//    } else {
+//        printf("error: no fmu file\n");
+//        printHelp(argv[0]);
+//        exit(EXIT_FAILURE);
+//    }
+//    if (argc > 2) {
+//        if (sscanf(argv[2],"%lf", tEnd) != 1) {
+//            printf("error: The given end time (%s) is not a number\n", argv[2]);
+//            exit(EXIT_FAILURE);
+//        }
+//    }
+//    if (argc > 3) {
+//        if (sscanf(argv[3],"%lf", h) != 1) {
+//            printf("error: The given stepsize (%s) is not a number\n", argv[3]);
+//            exit(EXIT_FAILURE);
+//        }
+//    }
+//    if (argc > 4) {
+//        if (sscanf(argv[4],"%d", loggingOn) != 1 || *loggingOn < 0 || *loggingOn > 1) {
+//            printf("error: The given logging flag (%s) is not boolean\n", argv[4]);
+//            exit(EXIT_FAILURE);
+//        }
+//    }
+//    if (argc > 5) {
+//        if (strlen(argv[5]) != 1) {
+//            printf("error: The given CSV separator char (%s) is not valid\n", argv[5]);
+//            exit(EXIT_FAILURE);
+//        }
+//        switch (argv[5][0]) {
+//            case 'c': *csv_separator = ','; break; // comma
+//            case 's': *csv_separator = ';'; break; // semicolon
+//            default:  *csv_separator = argv[5][0]; break; // any other char
+//        }
+//    }
+//    if (argc > 6) {
+//        int i;
+//        *nCategories = argc - 6;
+//        *logCategories = (char **)calloc(sizeof(char *), *nCategories);
+//        for (i = 0; i < *nCategories; i++) {
+//            (*logCategories)[i] = argv[i + 6];
+//        }
+//    }
+//}
+//
+//void printHelp(const char *fmusim) {
+//    printf("command syntax: %s <model.fmu> <tEnd> <h> <loggingOn> <csv separator>\n", fmusim);
+//    printf("   <model.fmu> .... path to FMU, relative to current dir or absolute, required\n");
+//    printf("   <tEnd> ......... end  time of simulation,   optional, defaults to 1.0 sec\n");
+//    printf("   <h> ............ step size of simulation,   optional, defaults to 0.1 sec\n");
+//    printf("   <loggingOn> .... 1 to activate logging,     optional, defaults to 0\n");
+//    printf("   <csv separator>. separator in csv file,     optional, c for ',', s for';', defaults to c\n");
+//    printf("   <logCategories>. list of active categories, optional, see modelDescription.xml for possible values\n");
+//}

+ 44 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_Window_sa/sim_support.h

@@ -0,0 +1,44 @@
+/* ------------------------------------------------------------------------- 
+ * sim_support.h
+ * Functions used by the FMU simulations fmusim_me and fmusim_cs.
+ * Copyright QTronic GmbH. All rights reserved.
+ * -------------------------------------------------------------------------*/
+#ifndef __SIM_SUPPORT_H
+#define __SIM_SUPPORT_H
+
+// Used 7z options, version 4.57:
+// -x   Extracts files from an archive with their full paths in the current dir, or in an output dir if specified
+// -aoa Overwrite All existing files without prompt
+// -o   Specifies a destination directory where files are to be extracted
+#define UNZIP_CMD "7z x -aoa -o"
+#define XML_FILE  "modelDescription.xml"
+#define RESULT_FILE "result.csv"
+#define BUFSIZE 4096
+#ifdef _WIN64
+#define DLL_DIR   "binaries\\win64\\"
+#else
+#define DLL_DIR   "binaries\\win32\\"
+#endif
+#define RESOURCES_DIR "resources\\"
+
+// return codes of the 7z command line tool
+#define SEVEN_ZIP_NO_ERROR 0 // success
+#define SEVEN_ZIP_WARNING 1  // e.g., one or more files were locked during zip
+#define SEVEN_ZIP_ERROR 2
+#define SEVEN_ZIP_COMMAND_LINE_ERROR 7
+#define SEVEN_ZIP_OUT_OF_MEMORY 8
+#define SEVEN_ZIP_STOPPED_BY_USER 255
+
+void fmuLogger(fmi2Component c, fmi2String instanceName, fmi2Status status, fmi2String category, fmi2String message, ...);
+int unzip(const char *zipPath, const char *outPath);
+void parseArguments(int argc, char *argv[], const char **fmuFileName, double *tEnd, double *h,
+                    int *loggingOn, char *csv_separator, int *nCategories, char **logCategories[]);
+void loadFMU(const char *fmuFileName);
+int loadDll(const char* dllPath, FMU *fmu, const char* preamble);
+void deleteUnzippedFiles();
+void outputRow(FMU *fmu, fmi2Component c, double time, FILE* file, char separator, fmi2Boolean header);
+int error(const char *message);
+void printHelp(const char *fmusim);
+char *getTempResourcesLocation(); // caller has to free the result
+
+#endif

BIN
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_control_master/Debug/libFMI_control_master.dll


+ 535 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_control_master/FMI_CM.c

@@ -0,0 +1,535 @@
+/* ---------------------------------------------------------------------------*
+ * Sample implementation of an control support master FMU -
+ * ---------------------------------------------------------------------------*/
+/*
+Template for a sc FMU
+*/
+
+#define MODEL_IDENTIFIER CM
+#define MODEL_GUID "{41f87101-edf2-4eef-90f3-42db56d4565f}"
+#define FMI2_FUNCTION_PREFIX PW_CONTROL_MASTER
+
+
+#include <stdio.h>
+#include "string.h"
+#include "fmi2Functions.h"
+#include <float.h>
+#include "FMI_CM.h"
+#include <math.h>
+#include "fmi2.h"
+#include "sim_support.h"
+
+
+#define NUMBER_OF_REALS 0
+#define NUMBER_OF_STRINGS 0
+#define NUMBER_OF_BOOLEANS 12
+#define NUMBER_OF_INTEGERS 0
+/*
+ * The input
+ */
+
+#define _in_obj_detected 0
+#define _in_driver_up 1
+#define _in_driver_up_stop 2
+#define _in_driver_down 3
+#define _in_driver_down_stop 4
+#define _in_passenger_up 5
+#define _in_passenger_up_stop 6
+#define _in_passenger_down 7
+#define _in_passenger_down_stop 8
+
+/*
+ * Control in
+ */
+#define _in_control 9
+
+/*
+ * The output:
+*/
+
+#define _out_motor_up 10
+#define _out_motor_down 11
+
+ double relativeError(double a, double b){
+	return fabs((a - b) / a);
+}
+
+/*
+ * Helper function for absolute error
+ */
+ double absoluteError(double a, double b){
+	return fabs(a - b);
+}
+
+/*
+ * is_close function for double comparison
+ */
+ int is_close(double a, double b, double REL_TOL, double ABS_TOL){
+	return ((absoluteError(a,b)<ABS_TOL) && (relativeError(a,b)<REL_TOL));
+}
+
+fmi2Status fmi2SetDebugLogging(fmi2Component fc, fmi2Boolean loggingOn, size_t nCategories, const fmi2String categories[])
+{
+    return fmi2OK;
+}
+
+fmi2Status fmi2SetString(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, const fmi2String value[])
+{
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetString(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, fmi2String value[])
+{
+    return fmi2Error;
+}
+
+fmi2Status fmi2SetReal(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, const fmi2Real value[])
+{
+	FMUInstance* comp = (FMUInstance *)fc;
+		int i;
+	    for (i = 0; i < nvr; i++)
+		{
+	    	if(vr[i]>=5){
+	    		printf("Value reference: %d, cannot be set, it is a store element\n", vr[i]);
+	    	}else{
+	    		 printf("Value reference: %d\n", vr[i]);
+	    		 comp->r[vr[i]] = value[i];
+	    	}
+
+	        //setExposedReal(vr[i], value[i]);
+	        //comp->r[vr[i]] = value[i];
+	    }
+	    return fmi2OK;
+}
+
+fmi2Status fmi2GetReal(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, fmi2Real value[])
+{
+
+    FMUInstance* comp = (FMUInstance *)fc;
+	int i;
+    for (i = 0; i < nvr; i++)
+	{
+        value[i] = comp->r[(vr[i])];
+    }
+    return fmi2OK;
+}
+
+fmi2Status fmi2SetBoolean(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, const fmi2Boolean value[])
+{
+	FMUInstance* comp = (FMUInstance *)fc;
+	int i;
+	for (i = 0; i < nvr; i++)
+	{
+		comp->b[vr[i]] = value[i];
+	}
+    return fmi2OK;
+}
+
+fmi2Status fmi2GetBoolean(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, fmi2Boolean value[])
+{
+	FMUInstance* comp = (FMUInstance *)fc;
+	int i;
+	for (i = 0; i < nvr; i++)
+	{
+		value[i] = comp->b[vr[i]];
+	}
+    return fmi2OK;
+}
+
+fmi2Component fmi2Instantiate(fmi2String instanceName, fmi2Type fmuType, fmi2String fmuGUID, fmi2String fmuLocation, const fmi2CallbackFunctions* functions, fmi2Boolean visible, fmi2Boolean loggingOn)
+{
+
+	//Declare data structure for fmu instance
+    FMUInstance* fi;
+	printf("%s in fmiInstantiate\n",instanceName);
+
+    //Perform checks on passed callback functions
+    if (loggingOn) {
+
+        if (!functions->logger);
+        //return NULL;
+	}
+    //Check for instanceName
+    if (!instanceName || strlen(instanceName)==0) {
+
+        // print (and/or log) instanceName is missing
+        //return NULL;
+    }
+    //Check passed GUID to defined model GUID
+    if (strcmp(fmuGUID, MODEL_GUID))
+	{
+        // print (and/or log) GUID doesn't match
+        //return NULL;
+    }
+
+    //Allocate fmu instance Memory
+    // TODO check if "canNotUseMemoryManagementFunctions == true/false". If false memory allocation not possible
+    fi = (FMUInstance *)functions->allocateMemory(1, sizeof(FMUInstance));
+    if (fi) {
+        // Think about what to do with variable values. Using these structs and pointers slows down simulation computations. Maybe only necessary for input, output and tunable parameters??
+        fi->r = functions->allocateMemory(NUMBER_OF_REALS, sizeof(fmi2Real));
+        fi->i = functions->allocateMemory(NUMBER_OF_INTEGERS, sizeof(fmi2Integer));
+        fi->b = functions->allocateMemory(NUMBER_OF_BOOLEANS, sizeof(fmi2Boolean));
+        fi->s = functions->allocateMemory(NUMBER_OF_STRINGS,  sizeof(fmi2String));
+    } // variables in predefined arrays (performance issue) --> makes multiple instances of fmu impossible
+
+
+    fi->instanceName = functions->allocateMemory(1 + strlen(instanceName), sizeof(char));
+    fi->GUID = functions->allocateMemory(1 + strlen(fmuGUID), sizeof(char));
+
+    strcpy((char*)fi->instanceName, instanceName);
+    strcpy((char*)fi->GUID, fmuGUID);
+    fi->functions = functions;
+    fi->loggingOn = loggingOn;
+    fi->isVisible = visible;
+    fi->state = fmuInstantiated;
+    /* Load the inner FMUs:*/
+    loadDll("libpw_controller.dll", &(fi->inner), "PW_Controller");
+    fi->fmuResourceLocation_inner = "libpw_controller";
+    /*Instantiate inner components*/
+    fi->c_inner = fi->inner.instantiate("inner", fmi2CoSimulation, "1", fi->fmuResourceLocation_inner, fi->functions, visible, 0);
+    return fi;
+}
+
+fmi2Status fmi2SetupExperiment(fmi2Component fc, fmi2Boolean toleranceDefined, fmi2Real tolerance,
+                            fmi2Real startTime, fmi2Boolean stopTimeDefined, fmi2Real stopTime) {
+
+
+    FMUInstance* fi = (FMUInstance*) fc;
+	printf("%s in fmiSetupExperiment\n",fi->instanceName);
+	if (fi->state != fmuInstantiated)
+	{
+		printf("fmu: %s was not instatiated before calling fmiSetupExperiment\n", fi->instanceName);
+		return fmi2Error;
+	}
+	fi->currentTime = startTime;
+	fi->stopTimeDefined = stopTimeDefined;
+	fi->toleranceDefined = toleranceDefined;
+	if (stopTimeDefined)
+	{
+		fi->stopTime = stopTime;
+	}
+	if (toleranceDefined)
+	{
+		fi->tolerance = tolerance;
+	}
+
+	fi->accumulator = 0;
+	/*
+	 * setup inner
+	 */
+	fmi2Status fmi2Flag = fmi2OK;
+	fi->state = fmuExperimentSettedUp;
+	fmi2Flag = fi->inner.setupExperiment(fi->c_inner, toleranceDefined, tolerance, startTime, fmi2True, stopTime);
+	    if (fmi2Flag == fmi2Error){
+	    	fi->state = fmuError;
+	    }
+    return fmi2Flag;
+}
+
+fmi2Status fmi2EnterInitializationMode(fmi2Component fc)
+{
+	FMUInstance* fi = (FMUInstance*) fc;
+	printf("%s in fmiEnterInitializationMode\n",fi->instanceName);
+	if (fi->state != fmuExperimentSettedUp)
+	{
+		printf("fmu: %s experiment was not set-up before calling fmiEnterInitializationMode\n", fi->instanceName);
+		return fmi2Error;
+	}
+    fi->state = fmuInitMode;
+    fmi2Status fmi2Flag = fmi2OK;
+    fmi2Flag = fi->inner.enterInitializationMode(fi->c_inner);
+    if (fmi2Flag == fmi2Error){
+        return fi->state = fmuError;
+    }
+    return fmi2Flag;
+}
+
+fmi2Status fmi2ExitInitializationMode(fmi2Component fc)
+{
+	FMUInstance* fi = (FMUInstance*) fc;
+	printf("%s in fmiExitInitializationMode\n",fi->instanceName);
+	if (fi->state != fmuInitMode)
+	{
+		printf("fmu: %s did not enter Initialization Mode before calling fmiExitInitializationMode\n", fi->instanceName);
+		return fmi2Error;
+	}
+	// TODO
+	//initStatus = calculateInitialUnknownValues();
+	//initialize();
+    fi->state = fmuInitialized;
+    fmi2Status fmi2Flag = fmi2OK;
+    fmi2Flag = fi->inner.exitInitializationMode(fi->c_inner);
+    if (fmi2Flag == fmi2Error){
+           return fi->state = fmuError;
+    }
+    return fmi2Flag;
+}
+
+fmi2Status fmi2DoStep(fmi2Component fc , fmi2Real currentCommPoint, fmi2Real commStepSize, fmi2Boolean noPrevFMUState)
+{
+
+	FMUInstance* fi = (FMUInstance *)fc;
+	fmi2Status simStatus = fmi2OK;
+    printf("%s in fmiDoStep()\n",fi->instanceName);
+    /*
+     * Get next timer event:
+     */
+    fmi2ValueReference vr_nte[1] ={0};
+    fi->inner.getReal(fi->c_inner,vr_nte,1,&(fi->nextTimerEvent));
+
+    if(fi->b[_in_control]){
+        	fmi2ValueReference vr_booleans[9] = {0,1,2,3,4,5,6,7,8};
+        	fi->inner.setBoolean(fi->c_inner,vr_booleans,9,&(fi->b[0]));
+        	simStatus = fi->inner.doStep(fi->c_inner,currentCommPoint,fi->accumulator, fmi2True);
+        	if (simStatus == fmi2OK){
+        		fi->accumulator = 0;
+        	}
+    else if(fi->nextTimerEvent != 0 && fi->nextTimerEvent-(currentCommPoint+commStepSize) <= 0){
+    	if(is_close(fi->nextTimerEvent-(currentCommPoint+commStepSize),0,1e-4,1e-8)){
+    		simStatus = fi->inner.doStep(fi->c_inner,currentCommPoint,fi->accumulator, fmi2True);
+    		fi->accumulator = 0;
+    	}else{
+    		simStatus = fmi2Discard;
+    		fi->currentTime = fi->nextTimerEvent;
+    	}
+    }
+    }else{
+    	fi->accumulator+=commStepSize;
+
+    }
+
+    if(simStatus == fmi2OK){
+    	fmi2ValueReference vr_outvalues_inner[2] = {9,10};
+    	fi->inner.getBoolean(fi->c_inner,vr_outvalues_inner,2,&(fi->b[_out_motor_up]));
+    	const fmi2ValueReference vr_timer_next_event[1] = {0};
+    	fi->inner.getReal(fi->c_inner,vr_timer_next_event,1,&(fi->nextTimerEvent));
+    	fi->currentTime = currentCommPoint + commStepSize;
+    }
+	return simStatus;
+}
+
+fmi2Status fmi2Terminate(fmi2Component fc)
+{
+	FMUInstance* fi = (FMUInstance *)fc;
+	printf("%s in fmiTerminate\n",fi->instanceName);
+	// do check if fi may be terminated
+	fi->inner.terminate(fi->c_inner);
+	fi->state = fmuTerminated;
+    return fmi2OK;
+}
+
+
+void fmi2FreeInstance(fmi2Component fc)
+{
+
+	FMUInstance* fi = (FMUInstance*) fc;
+	printf("%s in fmiFreeInstance\n",fi->instanceName);
+
+    if (fi) {
+        fi->functions->freeMemory(fi->r);
+        fi->functions->freeMemory(fi->i);
+        fi->functions->freeMemory(fi->b);
+        fi->functions->freeMemory(fi->s);// TODO has to be done with loop
+		fi->functions->freeMemory((void*)fi->instanceName);
+		fi->functions->freeMemory((void*)fi->GUID);
+		fi->functions->freeMemory((void*)fi);
+
+    }
+}
+
+//To be implemented
+
+const char* fmi2GetVersion() {
+	printf("Function fmiGetVersion not supported\n");
+    return NULL;
+}
+
+const char* fmi2GetTypesPlatform() {
+	printf("Function fmiGetTypesPlatform not supported\n");
+    return NULL;
+}
+
+fmi2Status fmi2Reset(fmi2Component fc)
+{
+	printf("Function fmiReset not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2SetInteger(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, const fmi2Integer value[])
+{
+    printf("Function fmiSetInteger not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetInteger(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, fmi2Integer value[])
+{
+    printf("Function fmiGetInteger not supported\n");
+    return fmi2Error;
+}
+
+
+/*******OWN IMPLEMENTATION OF Get/Set FMU state*******/
+fmi2Status fmi2GetFMUstate (fmi2Component c, fmi2FMUstate* FMUstate) {
+    FMUInstance* orig = (FMUInstance*)c;
+    FMUInstance* fi = (FMUInstance *)FMUstate;
+    fi = orig->functions->allocateMemory(1, sizeof(FMUInstance));
+    *FMUstate = fi;
+    if (fi) {
+        // Think about what to do with variable values. Using these structs and pointers slows down simulation computations. Maybe only necessary for input, output and tunable parameters??
+        fi->r = orig->functions->allocateMemory(NUMBER_OF_REALS, sizeof(fmi2Real));
+        fi->i = orig->functions->allocateMemory(NUMBER_OF_INTEGERS, sizeof(fmi2Integer));
+        fi->b = orig->functions->allocateMemory(NUMBER_OF_BOOLEANS, sizeof(fmi2Boolean));
+        fi->s = orig->functions->allocateMemory(NUMBER_OF_STRINGS,  sizeof(fmi2String));
+
+    } // variables in predefined arrays (performance issue) --> makes multiple instances of fmu impossible
+    fi->instanceName = orig->functions->allocateMemory(1 + strlen(orig->instanceName), sizeof(char));
+    fi->GUID = orig->functions->allocateMemory(1 + strlen(orig->GUID), sizeof(char));
+
+    strcpy((char *)fi->instanceName, (char *)orig->instanceName);
+    strcpy((char *)fi->GUID, (char *)orig->GUID);
+    fi->functions = orig->functions;
+    fi->loggingOn = orig->loggingOn;
+    fi->isVisible = orig->isVisible;
+    fi->state = orig->state;
+    fi->stepSize = orig->stepSize;
+    fi->startTime = orig->startTime;
+    fi->stopTime = orig->stopTime;
+	fi->currentTime = orig->currentTime;
+	fi->inner = orig->inner;
+	orig->inner.getFMUstate(orig->c_inner,fi->c_inner);
+	fi->fmuResourceLocation_inner = fi->functions->allocateMemory(1+strlen(orig->fmuResourceLocation_inner), sizeof(char));
+	strcpy((char *)fi->fmuResourceLocation_inner,(char *)orig->fmuResourceLocation_inner);
+	//copy r
+	int i=0;
+	for (i=0; i< NUMBER_OF_REALS;i++){
+	    printf("Setting real: %i %f\n", i, orig->r[i]);
+        fi->r[i] = orig->r[i];
+        printf("Setted real: %i %f\n", i, fi->r[i]);
+	}
+	//copy s
+	for (i=0; i< NUMBER_OF_STRINGS;i++){
+        fi->s[i] = orig->s[i];
+	}
+	//copy i
+    for (i=0; i< NUMBER_OF_INTEGERS;i++){
+        fi->i[i] = orig->i[i];
+	}
+	//copy b
+	for (i=0; i< NUMBER_OF_BOOLEANS;i++){
+        fi->b[i] = orig->b[i];
+	}
+    return fmi2OK;
+}
+
+
+fmi2Status fmi2SetFMUstate (fmi2Component c, fmi2FMUstate FMUstate) {
+    FMUInstance* orig = (FMUInstance*)FMUstate;
+    FMUInstance* fi = (FMUInstance*)c;
+
+    fi->inner.setFMUstate(fi->c_inner,orig->c_inner);
+    fi->fmuResourceLocation_inner = orig->functions->allocateMemory(1+strlen(orig->fmuResourceLocation_inner), sizeof(char));
+    strcpy((char *)fi->fmuResourceLocation_inner,(char *)orig->fmuResourceLocation_inner);
+    //set time etc correct, name and GUID should still be ok ;-)
+    printf("setting time values from %f to %f\n", fi->currentTime, orig->currentTime);
+    fi->state = orig->state;
+    fi->stepSize = orig->stepSize;
+    fi->startTime = orig->startTime;
+    fi->stopTime = orig->stopTime;
+	fi->currentTime = orig->currentTime;
+	printf("setting real values\n");
+	//copy r
+	int i=0;
+	for (i=0; i< NUMBER_OF_REALS;i++){
+        fi->r[i] = orig->r[i];
+	}
+	printf("setting string values\n");
+	//copy s
+	for (i=0; i< NUMBER_OF_STRINGS;i++){
+
+        fi->s[i] = orig->s[i];
+	}
+	//copy i
+    for (i=0; i< NUMBER_OF_INTEGERS;i++){
+        fi->i[i] = orig->i[i];
+	}
+	//copy b
+	for (i=0; i< NUMBER_OF_BOOLEANS;i++){
+        fi->b[i] = orig->b[i];
+	}
+    return fmi2OK;
+
+
+}
+/****************************************************/
+
+fmi2Status fmi2FreeFMUstate(fmi2Component c, fmi2FMUstate* FMUstate) {
+    printf("Function fmiFreeFMUstate not supported\n");
+    return fmi2Error;
+}
+fmi2Status fmi2SerializedFMUstateSize(fmi2Component c, fmi2FMUstate FMUstate, size_t *size) {
+    printf("Function fmiSerializedFMUstateSize not supported\n");
+    return fmi2Error;
+}
+fmi2Status fmi2SerializeFMUstate (fmi2Component c, fmi2FMUstate FMUstate, fmi2Byte serializedState[], size_t size) {
+    printf("Function fmiSerializeFMUstate not supported\n");
+    return fmi2Error;
+}
+fmi2Status fmi2DeSerializeFMUstate (fmi2Component c, const fmi2Byte serializedState[], size_t size, fmi2FMUstate* FMUstate) {
+    printf("Function fmiDeSerializeFMUstate not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetDirectionalDerivative(fmi2Component c, const fmi2ValueReference vUnknown_ref[], size_t nUnknown,
+                const fmi2ValueReference vKnown_ref[] , size_t nKnown, const fmi2Real dvKnown[], fmi2Real dvUnknown[]) {
+    printf("Function fmiGetDirectionalDerivative not supported\n");
+    return fmi2Error;
+}
+
+
+fmi2Status fmi2SetRealInputDerivatives(fmi2Component c, const fmi2ValueReference vr[], size_t nvr,
+                                     const fmi2Integer order[], const fmi2Real value[]) {
+    printf("Function fmiGetDirectionalDerivative not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetRealOutputDerivatives(fmi2Component c, const fmi2ValueReference vr[], size_t nvr,
+                                      const fmi2Integer order[], fmi2Real value[]) {
+    printf("Function fmiGetDirectionalDerivative not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2CancelStep(fmi2Component c) {
+    printf("Function fmiGetDirectionalDerivative not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetStatus(fmi2Component c, const fmi2StatusKind s, fmi2Status *value) {
+    printf("Function fmiGetStatus not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetRealStatus(fmi2Component c, const fmi2StatusKind s, fmi2Real *value) {
+    if(s == fmi2LastSuccessfulTime){
+        FMUInstance* comp = (FMUInstance*) c;
+        *value = comp->currentTime;
+        return fmi2OK;
+    }
+    printf("Function fmiGetRealStatus not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetIntegerStatus(fmi2Component c, const fmi2StatusKind s, fmi2Integer *value) {
+    printf("Function fmiGetIntegerStatus not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetBooleanStatus(fmi2Component c, const fmi2StatusKind s, fmi2Boolean *value) {
+    printf("Function fmiGetBooleanStatus not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetStringStatus(fmi2Component c, const fmi2StatusKind s, fmi2String *value) {
+    printf("Function fmiGetStringStatus not supported\n");
+    return fmi2Error;
+}

+ 52 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_control_master/FMI_CM.h

@@ -0,0 +1,52 @@
+/*
+ * PW_Controller.h
+ *
+ *  Created on: Jan 25, 2017
+ *      Author: Joachim
+ */
+
+#ifndef FMI_CM_H_
+#define FMI_CM_H_
+
+#include "fmi2.h"
+
+typedef enum {
+    fmuInstantiated = 0,
+    fmuInitMode  = 1,
+	fmuInitialized = 2,
+    fmuTerminated   = 3,
+    fmuError        = 4,
+    fmuExperimentSettedUp = 5
+} FMUState;
+
+
+
+typedef struct {
+	fmi2Real    *r;
+    fmi2Integer *i;
+    fmi2Boolean *b;
+    fmi2String  *s;
+    fmi2Boolean isVisible;
+    fmi2String instanceName;
+    fmi2String GUID;
+    const fmi2CallbackFunctions* functions;
+    fmi2Boolean loggingOn;
+    FMUState state;
+	fmi2Real stepSize;
+    fmi2Real startTime;
+    fmi2Real stopTime;
+	fmi2Real currentTime;
+    fmi2Boolean stopTimeDefined;
+    fmi2Real tolerance;
+    fmi2Boolean toleranceDefined;
+    FMU inner;
+    char *fmuResourceLocation_inner;
+    fmi2Component c_inner;
+    fmi2Real accumulator;
+    fmi2Real nextTimerEvent;
+} FMUInstance; // At the moment, most of the variables not really used since multiple instances of an FMU are not supported at the moment (performance issues)
+
+
+
+
+#endif /* FMI_CM_H_ */

+ 72 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_control_master/fmi2/fmi2.h

@@ -0,0 +1,72 @@
+/* -------------------------------------------------------------------------
+ * fmi.h
+ * Struct with the corresponding function pointers for FMI 2.0.
+ * Copyright QTronic GmbH. All rights reserved.
+ * -------------------------------------------------------------------------*/
+
+#ifndef FMI_H
+#define FMI_H
+
+#include "fmi2Functions.h"
+
+typedef struct {
+//    ModelDescription* modelDescription;
+
+    void  *dllHandle; // fmu.so handle
+    /***************************************************
+    Common Functions
+    ****************************************************/
+    fmi2GetTypesPlatformTYPE         *getTypesPlatform;
+    fmi2GetVersionTYPE               *getVersion;
+    fmi2SetDebugLoggingTYPE          *setDebugLogging;
+    fmi2InstantiateTYPE              *instantiate;
+    fmi2FreeInstanceTYPE             *freeInstance;
+    fmi2SetupExperimentTYPE          *setupExperiment;
+    fmi2EnterInitializationModeTYPE  *enterInitializationMode;
+    fmi2ExitInitializationModeTYPE   *exitInitializationMode;
+    fmi2TerminateTYPE                *terminate;
+    fmi2ResetTYPE                    *reset;
+    fmi2GetRealTYPE                  *getReal;
+    fmi2GetIntegerTYPE               *getInteger;
+    fmi2GetBooleanTYPE               *getBoolean;
+    fmi2GetStringTYPE                *getString;
+    fmi2SetRealTYPE                  *setReal;
+    fmi2SetIntegerTYPE               *setInteger;
+    fmi2SetBooleanTYPE               *setBoolean;
+    fmi2SetStringTYPE                *setString;
+    fmi2GetFMUstateTYPE              *getFMUstate;
+    fmi2SetFMUstateTYPE              *setFMUstate;
+    fmi2FreeFMUstateTYPE             *freeFMUstate;
+    fmi2SerializedFMUstateSizeTYPE   *serializedFMUstateSize;
+    fmi2SerializeFMUstateTYPE        *serializeFMUstate;
+    fmi2DeSerializeFMUstateTYPE      *deSerializeFMUstate;
+    fmi2GetDirectionalDerivativeTYPE *getDirectionalDerivative;
+    /***************************************************
+    Functions for FMI2 for Co-Simulation
+    ****************************************************/
+    fmi2SetRealInputDerivativesTYPE  *setRealInputDerivatives;
+    fmi2GetRealOutputDerivativesTYPE *getRealOutputDerivatives;
+    fmi2DoStepTYPE                   *doStep;
+    fmi2CancelStepTYPE               *cancelStep;
+    fmi2GetStatusTYPE                *getStatus;
+    fmi2GetRealStatusTYPE            *getRealStatus;
+    fmi2GetIntegerStatusTYPE         *getIntegerStatus;
+    fmi2GetBooleanStatusTYPE         *getBooleanStatus;
+    fmi2GetStringStatusTYPE          *getStringStatus;
+    /***************************************************
+    Functions for FMI2 for Model Exchange
+    ****************************************************/
+    fmi2EnterEventModeTYPE                *enterEventMode;
+    fmi2NewDiscreteStatesTYPE             *newDiscreteStates;
+    fmi2EnterContinuousTimeModeTYPE       *enterContinuousTimeMode;
+    fmi2CompletedIntegratorStepTYPE       *completedIntegratorStep;
+    fmi2SetTimeTYPE                       *setTime;
+    fmi2SetContinuousStatesTYPE           *setContinuousStates;
+    fmi2GetDerivativesTYPE                *getDerivatives;
+    fmi2GetEventIndicatorsTYPE            *getEventIndicators;
+    fmi2GetContinuousStatesTYPE           *getContinuousStates;
+    fmi2GetNominalsOfContinuousStatesTYPE *getNominalsOfContinuousStates;
+} FMU;
+
+#endif // FMI_H
+

+ 247 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_control_master/fmi2/fmi2FunctionTypes.h

@@ -0,0 +1,247 @@
+#ifndef fmi2FunctionTypes_h
+#define fmi2FunctionTypes_h
+
+#include "fmi2TypesPlatform.h"
+
+/* This header file must be utilized when compiling an FMU or an FMI master.
+   It declares data and function types for FMI 2.0
+
+   Revisions:
+   - Apr.  9, 2014: all prefixes "fmi" renamed to "fmi2" (decision from April 8)
+   - Apr.  3, 2014: Added #include <stddef.h> for size_t definition
+   - Mar. 27, 2014: Added #include "fmiTypesPlatform.h" (#179)
+   - Mar. 26, 2014: Introduced function argument "void" for the functions (#171)
+                      fmiGetTypesPlatformTYPE and fmiGetVersionTYPE
+   - Oct. 11, 2013: Functions of ModelExchange and CoSimulation merged:
+                      fmiInstantiateModelTYPE , fmiInstantiateSlaveTYPE  -> fmiInstantiateTYPE
+                      fmiFreeModelInstanceTYPE, fmiFreeSlaveInstanceTYPE -> fmiFreeInstanceTYPE
+                      fmiEnterModelInitializationModeTYPE, fmiEnterSlaveInitializationModeTYPE -> fmiEnterInitializationModeTYPE
+                      fmiExitModelInitializationModeTYPE , fmiExitSlaveInitializationModeTYPE  -> fmiExitInitializationModeTYPE
+                      fmiTerminateModelTYPE , fmiTerminateSlaveTYPE  -> fmiTerminate
+                      fmiResetSlave -> fmiReset (now also for ModelExchange and not only for CoSimulation)
+                    Functions renamed
+                      fmiUpdateDiscreteStatesTYPE -> fmiNewDiscreteStatesTYPE
+                    Renamed elements of the enumeration fmiEventInfo
+                      upcomingTimeEvent             -> nextEventTimeDefined // due to generic naming scheme: varDefined + var
+                      newUpdateDiscreteStatesNeeded -> newDiscreteStatesNeeded;
+   - June 13, 2013: Changed type fmiEventInfo
+                    Functions removed:
+                       fmiInitializeModelTYPE
+                       fmiEventUpdateTYPE
+                       fmiCompletedEventIterationTYPE
+                       fmiInitializeSlaveTYPE
+                    Functions added:
+                       fmiEnterModelInitializationModeTYPE
+                       fmiExitModelInitializationModeTYPE
+                       fmiEnterEventModeTYPE
+                       fmiUpdateDiscreteStatesTYPE
+                       fmiEnterContinuousTimeModeTYPE
+                       fmiEnterSlaveInitializationModeTYPE;
+                       fmiExitSlaveInitializationModeTYPE;
+   - Feb. 17, 2013: Added third argument to fmiCompletedIntegratorStepTYPE
+                    Changed function name "fmiTerminateType" to "fmiTerminateModelType" (due to #113)
+                    Changed function name "fmiGetNominalContinuousStateTYPE" to
+                                          "fmiGetNominalsOfContinuousStatesTYPE"
+                    Removed fmiGetStateValueReferencesTYPE.
+   - Nov. 14, 2011: First public Version
+
+
+   Copyright (C) 2011 MODELISAR consortium,
+               2012-2013 Modelica Association Project "FMI"
+               All rights reserved.
+   This file is licensed by the copyright holders under the BSD 2-Clause License
+   (http://www.opensource.org/licenses/bsd-license.html):
+
+   ----------------------------------------------------------------------------
+   Redistribution and use in source and binary forms, with or without
+   modification, are permitted provided that the following conditions are met:
+
+   - Redistributions of source code must retain the above copyright notice,
+     this list of conditions and the following disclaimer.
+   - Redistributions in binary form must reproduce the above copyright notice,
+     this list of conditions and the following disclaimer in the documentation
+     and/or other materials provided with the distribution.
+   - Neither the name of the copyright holders nor the names of its
+     contributors may be used to endorse or promote products derived
+     from this software without specific prior written permission.
+
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+   TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+   PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
+   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+   OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+   OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+   ----------------------------------------------------------------------------
+
+   with the extension:
+
+   You may distribute or publicly perform any modification only under the
+   terms of this license.
+   (Note, this means that if you distribute a modified file,
+    the modified file must also be provided under this license).
+*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* make sure all compiler use the same alignment policies for structures */
+#if defined _MSC_VER || defined __GNUC__
+#pragma pack(push,8)
+#endif
+
+/* Include stddef.h, in order that size_t etc. is defined */
+#include <stddef.h>
+
+
+/* Type definitions */
+typedef enum {
+    fmi2OK,
+    fmi2Warning,
+    fmi2Discard,
+    fmi2Error,
+    fmi2Fatal,
+    fmi2Pending
+} fmi2Status;
+
+typedef enum {
+    fmi2ModelExchange,
+    fmi2CoSimulation
+} fmi2Type;
+
+typedef enum {
+    fmi2DoStepStatus,
+    fmi2PendingStatus,
+    fmi2LastSuccessfulTime,
+    fmi2Terminated
+} fmi2StatusKind;
+
+typedef void      (*fmi2CallbackLogger)        (fmi2ComponentEnvironment, fmi2String, fmi2Status, fmi2String, fmi2String, ...);
+typedef void*     (*fmi2CallbackAllocateMemory)(size_t, size_t);
+typedef void      (*fmi2CallbackFreeMemory)    (void*);
+typedef void      (*fmi2StepFinished)          (fmi2ComponentEnvironment, fmi2Status);
+
+typedef struct {
+   const fmi2CallbackLogger         logger;
+   const fmi2CallbackAllocateMemory allocateMemory;
+   const fmi2CallbackFreeMemory     freeMemory;
+   const fmi2StepFinished           stepFinished;
+   const fmi2ComponentEnvironment   componentEnvironment;
+} fmi2CallbackFunctions;
+
+typedef struct {
+   fmi2Boolean newDiscreteStatesNeeded;
+   fmi2Boolean terminateSimulation;
+   fmi2Boolean nominalsOfContinuousStatesChanged;
+   fmi2Boolean valuesOfContinuousStatesChanged;
+   fmi2Boolean nextEventTimeDefined;
+   fmi2Real    nextEventTime;
+} fmi2EventInfo;
+
+
+/* reset alignment policy to the one set before reading this file */
+#if defined _MSC_VER || defined __GNUC__
+#pragma pack(pop)
+#endif
+
+
+/* Define fmi2 function pointer types to simplify dynamic loading */
+
+/***************************************************
+Types for Common Functions
+****************************************************/
+
+/* Inquire version numbers of header files and setting logging status */
+   typedef const char* fmi2GetTypesPlatformTYPE(void);
+   typedef const char* fmi2GetVersionTYPE(void);
+   typedef fmi2Status  fmi2SetDebugLoggingTYPE(fmi2Component, fmi2Boolean, size_t, const fmi2String[]);
+
+/* Creation and destruction of FMU instances and setting debug status */
+   typedef fmi2Component fmi2InstantiateTYPE (fmi2String, fmi2Type, fmi2String, fmi2String, const fmi2CallbackFunctions*, fmi2Boolean, fmi2Boolean);
+   typedef void          fmi2FreeInstanceTYPE(fmi2Component);
+
+/* Enter and exit initialization mode, terminate and reset */
+   typedef fmi2Status fmi2SetupExperimentTYPE        (fmi2Component, fmi2Boolean, fmi2Real, fmi2Real, fmi2Boolean, fmi2Real);
+   typedef fmi2Status fmi2EnterInitializationModeTYPE(fmi2Component);
+   typedef fmi2Status fmi2ExitInitializationModeTYPE (fmi2Component);
+   typedef fmi2Status fmi2TerminateTYPE              (fmi2Component);
+   typedef fmi2Status fmi2ResetTYPE                  (fmi2Component);
+
+/* Getting and setting variable values */
+   typedef fmi2Status fmi2GetRealTYPE   (fmi2Component, const fmi2ValueReference[], size_t, fmi2Real   []);
+   typedef fmi2Status fmi2GetIntegerTYPE(fmi2Component, const fmi2ValueReference[], size_t, fmi2Integer[]);
+   typedef fmi2Status fmi2GetBooleanTYPE(fmi2Component, const fmi2ValueReference[], size_t, fmi2Boolean[]);
+   typedef fmi2Status fmi2GetStringTYPE (fmi2Component, const fmi2ValueReference[], size_t, fmi2String []);
+
+   typedef fmi2Status fmi2SetRealTYPE   (fmi2Component, const fmi2ValueReference[], size_t, const fmi2Real   []);
+   typedef fmi2Status fmi2SetIntegerTYPE(fmi2Component, const fmi2ValueReference[], size_t, const fmi2Integer[]);
+   typedef fmi2Status fmi2SetBooleanTYPE(fmi2Component, const fmi2ValueReference[], size_t, const fmi2Boolean[]);
+   typedef fmi2Status fmi2SetStringTYPE (fmi2Component, const fmi2ValueReference[], size_t, const fmi2String []);
+
+/* Getting and setting the internal FMU state */
+   typedef fmi2Status fmi2GetFMUstateTYPE           (fmi2Component, fmi2FMUstate*);
+   typedef fmi2Status fmi2SetFMUstateTYPE           (fmi2Component, fmi2FMUstate);
+   typedef fmi2Status fmi2FreeFMUstateTYPE          (fmi2Component, fmi2FMUstate*);
+   typedef fmi2Status fmi2SerializedFMUstateSizeTYPE(fmi2Component, fmi2FMUstate, size_t*);
+   typedef fmi2Status fmi2SerializeFMUstateTYPE     (fmi2Component, fmi2FMUstate, fmi2Byte[], size_t);
+   typedef fmi2Status fmi2DeSerializeFMUstateTYPE   (fmi2Component, const fmi2Byte[], size_t, fmi2FMUstate*);
+
+/* Getting partial derivatives */
+   typedef fmi2Status fmi2GetDirectionalDerivativeTYPE(fmi2Component, const fmi2ValueReference[], size_t,
+                                                                   const fmi2ValueReference[], size_t,
+                                                                   const fmi2Real[], fmi2Real[]);
+
+/***************************************************
+Types for Functions for FMI2 for Model Exchange
+****************************************************/
+
+/* Enter and exit the different modes */
+   typedef fmi2Status fmi2EnterEventModeTYPE         (fmi2Component);
+   typedef fmi2Status fmi2NewDiscreteStatesTYPE      (fmi2Component, fmi2EventInfo*);
+   typedef fmi2Status fmi2EnterContinuousTimeModeTYPE(fmi2Component);
+   typedef fmi2Status fmi2CompletedIntegratorStepTYPE(fmi2Component, fmi2Boolean, fmi2Boolean*, fmi2Boolean*);
+
+/* Providing independent variables and re-initialization of caching */
+   typedef fmi2Status fmi2SetTimeTYPE            (fmi2Component, fmi2Real);
+   typedef fmi2Status fmi2SetContinuousStatesTYPE(fmi2Component, const fmi2Real[], size_t);
+
+/* Evaluation of the model equations */
+   typedef fmi2Status fmi2GetDerivativesTYPE               (fmi2Component, fmi2Real[], size_t);
+#ifdef FMU_EXPERIMENTAL
+   typedef fmi2Status fmi2GetSpecificDerivativesTYPE       (fmi2Component, fmi2Real[], const fmi2ValueReference [], size_t);
+#endif
+
+   typedef fmi2Status fmi2GetEventIndicatorsTYPE           (fmi2Component, fmi2Real[], size_t);
+   typedef fmi2Status fmi2GetContinuousStatesTYPE          (fmi2Component, fmi2Real[], size_t);
+   typedef fmi2Status fmi2GetNominalsOfContinuousStatesTYPE(fmi2Component, fmi2Real[], size_t);
+
+
+/***************************************************
+Types for Functions for FMI2 for Co-Simulation
+****************************************************/
+
+/* Simulating the slave */
+   typedef fmi2Status fmi2SetRealInputDerivativesTYPE (fmi2Component, const fmi2ValueReference [], size_t, const fmi2Integer [], const fmi2Real []);
+   typedef fmi2Status fmi2GetRealOutputDerivativesTYPE(fmi2Component, const fmi2ValueReference [], size_t, const fmi2Integer [], fmi2Real []);
+
+   typedef fmi2Status fmi2DoStepTYPE     (fmi2Component, fmi2Real, fmi2Real, fmi2Boolean);
+   typedef fmi2Status fmi2CancelStepTYPE (fmi2Component);
+
+/* Inquire slave status */
+   typedef fmi2Status fmi2GetStatusTYPE       (fmi2Component, const fmi2StatusKind, fmi2Status* );
+   typedef fmi2Status fmi2GetRealStatusTYPE   (fmi2Component, const fmi2StatusKind, fmi2Real*   );
+   typedef fmi2Status fmi2GetIntegerStatusTYPE(fmi2Component, const fmi2StatusKind, fmi2Integer*);
+   typedef fmi2Status fmi2GetBooleanStatusTYPE(fmi2Component, const fmi2StatusKind, fmi2Boolean*);
+   typedef fmi2Status fmi2GetStringStatusTYPE (fmi2Component, const fmi2StatusKind, fmi2String* );
+
+
+#ifdef __cplusplus
+}  /* end of extern "C" { */
+#endif
+
+#endif /* fmi2FunctionTypes_h */

+ 339 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_control_master/fmi2/fmi2Functions.h

@@ -0,0 +1,339 @@
+#ifndef fmi2Functions_h
+#define fmi2Functions_h
+
+/* This header file must be utilized when compiling a FMU.
+   It defines all functions of the
+         FMI 2.0 Model Exchange and Co-Simulation Interface.
+
+   In order to have unique function names even if several FMUs
+   are compiled together (e.g. for embedded systems), every "real" function name
+   is constructed by prepending the function name by "FMI2_FUNCTION_PREFIX".
+   Therefore, the typical usage is:
+
+      #define FMI2_FUNCTION_PREFIX MyModel_
+      #include "fmi2Functions.h"
+
+   As a result, a function that is defined as "fmi2GetDerivatives" in this header file,
+   is actually getting the name "MyModel_fmi2GetDerivatives".
+
+   This only holds if the FMU is shipped in C source code, or is compiled in a
+   static link library. For FMUs compiled in a DLL/sharedObject, the "actual" function
+   names are used and "FMI2_FUNCTION_PREFIX" must not be defined.
+
+   Revisions:
+   - Apr.  9, 2014: all prefixes "fmi" renamed to "fmi2" (decision from April 8)
+   - Mar. 26, 2014: FMI_Export set to empty value if FMI_Export and FMI_FUNCTION_PREFIX
+                    are not defined (#173)
+   - Oct. 11, 2013: Functions of ModelExchange and CoSimulation merged:
+                      fmiInstantiateModel , fmiInstantiateSlave  -> fmiInstantiate
+                      fmiFreeModelInstance, fmiFreeSlaveInstance -> fmiFreeInstance
+                      fmiEnterModelInitializationMode, fmiEnterSlaveInitializationMode -> fmiEnterInitializationMode
+                      fmiExitModelInitializationMode , fmiExitSlaveInitializationMode  -> fmiExitInitializationMode
+                      fmiTerminateModel, fmiTerminateSlave  -> fmiTerminate
+                      fmiResetSlave -> fmiReset (now also for ModelExchange and not only for CoSimulation)
+                    Functions renamed:
+                      fmiUpdateDiscreteStates -> fmiNewDiscreteStates
+   - June 13, 2013: Functions removed:
+                       fmiInitializeModel
+                       fmiEventUpdate
+                       fmiCompletedEventIteration
+                       fmiInitializeSlave
+                    Functions added:
+                       fmiEnterModelInitializationMode
+                       fmiExitModelInitializationMode
+                       fmiEnterEventMode
+                       fmiUpdateDiscreteStates
+                       fmiEnterContinuousTimeMode
+                       fmiEnterSlaveInitializationMode;
+                       fmiExitSlaveInitializationMode;
+   - Feb. 17, 2013: Portability improvements:
+                       o DllExport changed to FMI_Export
+                       o FUNCTION_PREFIX changed to FMI_FUNCTION_PREFIX
+                       o Allow undefined FMI_FUNCTION_PREFIX (meaning no prefix is used)
+                    Changed function name "fmiTerminate" to "fmiTerminateModel" (due to #113)
+                    Changed function name "fmiGetNominalContinuousState" to
+                                          "fmiGetNominalsOfContinuousStates"
+                    Removed fmiGetStateValueReferences.
+   - Nov. 14, 2011: Adapted to FMI 2.0:
+                       o Split into two files (fmiFunctions.h, fmiTypes.h) in order
+                         that code that dynamically loads an FMU can directly
+                         utilize the header files).
+                       o Added C++ encapsulation of C-part, in order that the header
+                         file can be directly utilized in C++ code.
+                       o fmiCallbackFunctions is passed as pointer to fmiInstantiateXXX
+                       o stepFinished within fmiCallbackFunctions has as first
+                         argument "fmiComponentEnvironment" and not "fmiComponent".
+                       o New functions to get and set the complete FMU state
+                         and to compute partial derivatives.
+   - Nov.  4, 2010: Adapted to specification text:
+                       o fmiGetModelTypesPlatform renamed to fmiGetTypesPlatform
+                       o fmiInstantiateSlave: Argument GUID     replaced by fmuGUID
+                                              Argument mimetype replaced by mimeType
+                       o tabs replaced by spaces
+   - Oct. 16, 2010: Functions for FMI for Co-simulation added
+   - Jan. 20, 2010: stateValueReferencesChanged added to struct fmiEventInfo (ticket #27)
+                    (by M. Otter, DLR)
+                    Added WIN32 pragma to define the struct layout (ticket #34)
+                    (by J. Mauss, QTronic)
+   - Jan.  4, 2010: Removed argument intermediateResults from fmiInitialize
+                    Renamed macro fmiGetModelFunctionsVersion to fmiGetVersion
+                    Renamed macro fmiModelFunctionsVersion to fmiVersion
+                    Replaced fmiModel by fmiComponent in decl of fmiInstantiateModel
+                    (by J. Mauss, QTronic)
+   - Dec. 17, 2009: Changed extension "me" to "fmi" (by Martin Otter, DLR).
+   - Dez. 14, 2009: Added eventInfo to meInitialize and added
+                    meGetNominalContinuousStates (by Martin Otter, DLR)
+   - Sept. 9, 2009: Added DllExport (according to Peter Nilsson's suggestion)
+                    (by A. Junghanns, QTronic)
+   - Sept. 9, 2009: Changes according to FMI-meeting on July 21:
+                    meInquireModelTypesVersion     -> meGetModelTypesPlatform
+                    meInquireModelFunctionsVersion -> meGetModelFunctionsVersion
+                    meSetStates                    -> meSetContinuousStates
+                    meGetStates                    -> meGetContinuousStates
+                    removal of meInitializeModelClass
+                    removal of meGetTime
+                    change of arguments of meInstantiateModel
+                    change of arguments of meCompletedIntegratorStep
+                    (by Martin Otter, DLR):
+   - July 19, 2009: Added "me" as prefix to file names (by Martin Otter, DLR).
+   - March 2, 2009: Changed function definitions according to the last design
+                    meeting with additional improvements (by Martin Otter, DLR).
+   - Dec. 3 , 2008: First version by Martin Otter (DLR) and Hans Olsson (Dynasim).
+
+   Copyright (C) 2008-2011 MODELISAR consortium,
+               2012-2013 Modelica Association Project "FMI"
+               All rights reserved.
+   This file is licensed by the copyright holders under the BSD 2-Clause License
+   (http://www.opensource.org/licenses/bsd-license.html):
+
+   ----------------------------------------------------------------------------
+   Redistribution and use in source and binary forms, with or without
+   modification, are permitted provided that the following conditions are met:
+
+   - Redistributions of source code must retain the above copyright notice,
+     this list of conditions and the following disclaimer.
+   - Redistributions in binary form must reproduce the above copyright notice,
+     this list of conditions and the following disclaimer in the documentation
+     and/or other materials provided with the distribution.
+   - Neither the name of the copyright holders nor the names of its
+     contributors may be used to endorse or promote products derived
+     from this software without specific prior written permission.
+
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+   TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+   PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
+   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+   OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+   OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+   ----------------------------------------------------------------------------
+
+   with the extension:
+
+   You may distribute or publicly perform any modification only under the
+   terms of this license.
+   (Note, this means that if you distribute a modified file,
+    the modified file must also be provided under this license).
+*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "fmi2TypesPlatform.h"
+#include "fmi2FunctionTypes.h"
+#include <stdlib.h>
+
+
+/*
+  Export FMI2 API functions on Windows and under GCC.
+  If custom linking is desired then the FMI2_Export must be
+  defined before including this file. For instance,
+  it may be set to __declspec(dllimport).
+*/
+#if !defined(FMI2_Export)
+  #if !defined(FMI2_FUNCTION_PREFIX)
+    #if defined _WIN32 || defined __CYGWIN__
+     /* Note: both gcc & MSVC on Windows support this syntax. */
+        #define FMI2_Export __declspec(dllexport)
+    #else
+      #if __GNUC__ >= 4
+        #define FMI2_Export __attribute__ ((visibility ("default")))
+      #else
+        #define FMI2_Export
+      #endif
+    #endif
+  #else
+    #define FMI2_Export
+  #endif
+#endif
+
+/* Macros to construct the real function name
+   (prepend function name by FMI2_FUNCTION_PREFIX) */
+#if defined(FMI2_FUNCTION_PREFIX)
+  #define fmi2Paste(a,b)     a ## b
+  #define fmi2PasteB(a,b)    fmi2Paste(a,b)
+  #define fmi2FullName(name) fmi2PasteB(FMI2_FUNCTION_PREFIX, name)
+#else
+  #define fmi2FullName(name) name
+#endif
+
+/***************************************************
+Common Functions
+****************************************************/
+#define fmi2GetTypesPlatform         fmi2FullName(fmi2GetTypesPlatform)
+#define fmi2GetVersion               fmi2FullName(fmi2GetVersion)
+#define fmi2SetDebugLogging          fmi2FullName(fmi2SetDebugLogging)
+#define fmi2Instantiate              fmi2FullName(fmi2Instantiate)
+#define fmi2FreeInstance             fmi2FullName(fmi2FreeInstance)
+#define fmi2SetupExperiment          fmi2FullName(fmi2SetupExperiment)
+#define fmi2EnterInitializationMode  fmi2FullName(fmi2EnterInitializationMode)
+#define fmi2ExitInitializationMode   fmi2FullName(fmi2ExitInitializationMode)
+#define fmi2Terminate                fmi2FullName(fmi2Terminate)
+#define fmi2Reset                    fmi2FullName(fmi2Reset)
+#define fmi2GetReal                  fmi2FullName(fmi2GetReal)
+#define fmi2GetInteger               fmi2FullName(fmi2GetInteger)
+#define fmi2GetBoolean               fmi2FullName(fmi2GetBoolean)
+#define fmi2GetString                fmi2FullName(fmi2GetString)
+#define fmi2SetReal                  fmi2FullName(fmi2SetReal)
+#define fmi2SetInteger               fmi2FullName(fmi2SetInteger)
+#define fmi2SetBoolean               fmi2FullName(fmi2SetBoolean)
+#define fmi2SetString                fmi2FullName(fmi2SetString)
+#define fmi2GetFMUstate              fmi2FullName(fmi2GetFMUstate)
+#define fmi2SetFMUstate              fmi2FullName(fmi2SetFMUstate)
+#define fmi2FreeFMUstate             fmi2FullName(fmi2FreeFMUstate)
+#define fmi2SerializedFMUstateSize   fmi2FullName(fmi2SerializedFMUstateSize)
+#define fmi2SerializeFMUstate        fmi2FullName(fmi2SerializeFMUstate)
+#define fmi2DeSerializeFMUstate      fmi2FullName(fmi2DeSerializeFMUstate)
+#define fmi2GetDirectionalDerivative fmi2FullName(fmi2GetDirectionalDerivative)
+
+
+/***************************************************
+Functions for FMI2 for Model Exchange
+****************************************************/
+#define fmi2EnterEventMode                fmi2FullName(fmi2EnterEventMode)
+#define fmi2NewDiscreteStates             fmi2FullName(fmi2NewDiscreteStates)
+#define fmi2EnterContinuousTimeMode       fmi2FullName(fmi2EnterContinuousTimeMode)
+#define fmi2CompletedIntegratorStep       fmi2FullName(fmi2CompletedIntegratorStep)
+#define fmi2SetTime                       fmi2FullName(fmi2SetTime)
+#define fmi2SetContinuousStates           fmi2FullName(fmi2SetContinuousStates)
+#define fmi2GetDerivatives                fmi2FullName(fmi2GetDerivatives)
+#ifdef FMU_EXPERIMENTAL
+#define fmi2GetSpecificDerivatives        fmi2FullName(fmi2GetSpecificDerivatives)
+#endif
+#define fmi2GetEventIndicators            fmi2FullName(fmi2GetEventIndicators)
+#define fmi2GetContinuousStates           fmi2FullName(fmi2GetContinuousStates)
+#define fmi2GetNominalsOfContinuousStates fmi2FullName(fmi2GetNominalsOfContinuousStates)
+
+
+/***************************************************
+Functions for FMI2 for Co-Simulation
+****************************************************/
+#define fmi2SetRealInputDerivatives      fmi2FullName(fmi2SetRealInputDerivatives)
+#define fmi2GetRealOutputDerivatives     fmi2FullName(fmi2GetRealOutputDerivatives)
+#define fmi2DoStep                       fmi2FullName(fmi2DoStep)
+#define fmi2CancelStep                   fmi2FullName(fmi2CancelStep)
+#define fmi2GetStatus                    fmi2FullName(fmi2GetStatus)
+#define fmi2GetRealStatus                fmi2FullName(fmi2GetRealStatus)
+#define fmi2GetIntegerStatus             fmi2FullName(fmi2GetIntegerStatus)
+#define fmi2GetBooleanStatus             fmi2FullName(fmi2GetBooleanStatus)
+#define fmi2GetStringStatus              fmi2FullName(fmi2GetStringStatus)
+
+/* Version number */
+#define fmi2Version "2.0"
+
+
+/***************************************************
+Common Functions
+****************************************************/
+
+/* Inquire version numbers of header files */
+   FMI2_Export fmi2GetTypesPlatformTYPE fmi2GetTypesPlatform;
+   FMI2_Export fmi2GetVersionTYPE       fmi2GetVersion;
+   FMI2_Export fmi2SetDebugLoggingTYPE  fmi2SetDebugLogging;
+
+/* Creation and destruction of FMU instances */
+   FMI2_Export fmi2InstantiateTYPE  fmi2Instantiate;
+   FMI2_Export fmi2FreeInstanceTYPE fmi2FreeInstance;
+
+/* Enter and exit initialization mode, terminate and reset */
+   FMI2_Export fmi2SetupExperimentTYPE         fmi2SetupExperiment;
+   FMI2_Export fmi2EnterInitializationModeTYPE fmi2EnterInitializationMode;
+   FMI2_Export fmi2ExitInitializationModeTYPE  fmi2ExitInitializationMode;
+   FMI2_Export fmi2TerminateTYPE               fmi2Terminate;
+   FMI2_Export fmi2ResetTYPE                   fmi2Reset;
+
+/* Getting and setting variables values */
+   FMI2_Export fmi2GetRealTYPE    fmi2GetReal;
+   FMI2_Export fmi2GetIntegerTYPE fmi2GetInteger;
+   FMI2_Export fmi2GetBooleanTYPE fmi2GetBoolean;
+   FMI2_Export fmi2GetStringTYPE  fmi2GetString;
+
+   FMI2_Export fmi2SetRealTYPE    fmi2SetReal;
+   FMI2_Export fmi2SetIntegerTYPE fmi2SetInteger;
+   FMI2_Export fmi2SetBooleanTYPE fmi2SetBoolean;
+   FMI2_Export fmi2SetStringTYPE  fmi2SetString;
+
+/* Getting and setting the internal FMU state */
+   FMI2_Export fmi2GetFMUstateTYPE            fmi2GetFMUstate;
+   FMI2_Export fmi2SetFMUstateTYPE            fmi2SetFMUstate;
+   FMI2_Export fmi2FreeFMUstateTYPE           fmi2FreeFMUstate;
+   FMI2_Export fmi2SerializedFMUstateSizeTYPE fmi2SerializedFMUstateSize;
+   FMI2_Export fmi2SerializeFMUstateTYPE      fmi2SerializeFMUstate;
+   FMI2_Export fmi2DeSerializeFMUstateTYPE    fmi2DeSerializeFMUstate;
+
+/* Getting partial derivatives */
+   FMI2_Export fmi2GetDirectionalDerivativeTYPE fmi2GetDirectionalDerivative;
+
+
+/***************************************************
+Functions for FMI2 for Model Exchange
+****************************************************/
+
+/* Enter and exit the different modes */
+   FMI2_Export fmi2EnterEventModeTYPE               fmi2EnterEventMode;
+   FMI2_Export fmi2NewDiscreteStatesTYPE            fmi2NewDiscreteStates;
+   FMI2_Export fmi2EnterContinuousTimeModeTYPE      fmi2EnterContinuousTimeMode;
+   FMI2_Export fmi2CompletedIntegratorStepTYPE      fmi2CompletedIntegratorStep;
+
+/* Providing independent variables and re-initialization of caching */
+   FMI2_Export fmi2SetTimeTYPE             fmi2SetTime;
+   FMI2_Export fmi2SetContinuousStatesTYPE fmi2SetContinuousStates;
+
+/* Evaluation of the model equations */
+   FMI2_Export fmi2GetDerivativesTYPE                fmi2GetDerivatives;
+#ifdef FMU_EXPERIMENTAL
+   FMI2_Export fmi2GetSpecificDerivativesTYPE        fmi2GetSpecificDerivatives;
+#endif
+   FMI2_Export fmi2GetEventIndicatorsTYPE            fmi2GetEventIndicators;
+   FMI2_Export fmi2GetContinuousStatesTYPE           fmi2GetContinuousStates;
+   FMI2_Export fmi2GetNominalsOfContinuousStatesTYPE fmi2GetNominalsOfContinuousStates;
+
+
+/***************************************************
+Functions for FMI2 for Co-Simulation
+****************************************************/
+
+/* Simulating the slave */
+   FMI2_Export fmi2SetRealInputDerivativesTYPE  fmi2SetRealInputDerivatives;
+   FMI2_Export fmi2GetRealOutputDerivativesTYPE fmi2GetRealOutputDerivatives;
+
+   FMI2_Export fmi2DoStepTYPE     fmi2DoStep;
+   FMI2_Export fmi2CancelStepTYPE fmi2CancelStep;
+
+/* Inquire slave status */
+   FMI2_Export fmi2GetStatusTYPE        fmi2GetStatus;
+   FMI2_Export fmi2GetRealStatusTYPE    fmi2GetRealStatus;
+   FMI2_Export fmi2GetIntegerStatusTYPE fmi2GetIntegerStatus;
+   FMI2_Export fmi2GetBooleanStatusTYPE fmi2GetBooleanStatus;
+   FMI2_Export fmi2GetStringStatusTYPE  fmi2GetStringStatus;
+
+#ifdef __cplusplus
+}  /* end of extern "C" { */
+#endif
+
+#endif /* fmi2Functions_h */

+ 115 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_control_master/fmi2/fmi2TypesPlatform.h

@@ -0,0 +1,115 @@
+#ifndef fmi2TypesPlatform_h
+#define fmi2TypesPlatform_h
+
+/* Standard header file to define the argument types of the
+   functions of the Functional Mock-up Interface 2.0.
+   This header file must be utilized both by the model and
+   by the simulation engine.
+
+   Revisions:
+   - Apr.  9, 2014: all prefixes "fmi" renamed to "fmi2" (decision from April 8)
+   - Mar   31, 2014: New datatype fmiChar introduced.
+   - Feb.  17, 2013: Changed fmiTypesPlatform from "standard32" to "default".
+                     Removed fmiUndefinedValueReference since no longer needed
+                     (because every state is defined in ScalarVariables).
+   - March 20, 2012: Renamed from fmiPlatformTypes.h to fmiTypesPlatform.h
+   - Nov.  14, 2011: Use the header file "fmiPlatformTypes.h" for FMI 2.0
+                     both for "FMI for model exchange" and for "FMI for co-simulation"
+                     New types "fmiComponentEnvironment", "fmiState", and "fmiByte".
+                     The implementation of "fmiBoolean" is change from "char" to "int".
+                     The #define "fmiPlatform" changed to "fmiTypesPlatform"
+                     (in order that #define and function call are consistent)
+   - Oct.   4, 2010: Renamed header file from "fmiModelTypes.h" to fmiPlatformTypes.h"
+                     for the co-simulation interface
+   - Jan.   4, 2010: Renamed meModelTypes_h to fmiModelTypes_h (by Mauss, QTronic)
+   - Dec.  21, 2009: Changed "me" to "fmi" and "meModel" to "fmiComponent"
+                     according to meeting on Dec. 18 (by Martin Otter, DLR)
+   - Dec.   6, 2009: Added meUndefinedValueReference (by Martin Otter, DLR)
+   - Sept.  9, 2009: Changes according to FMI-meeting on July 21:
+                     Changed "version" to "platform", "standard" to "standard32",
+                     Added a precise definition of "standard32" as comment
+                     (by Martin Otter, DLR)
+   - July  19, 2009: Added "me" as prefix to file names, added meTrue/meFalse,
+                     and changed meValueReferenced from int to unsigned int
+                     (by Martin Otter, DLR).
+   - March  2, 2009: Moved enums and function pointer definitions to
+                     ModelFunctions.h (by Martin Otter, DLR).
+   - Dec.  3, 2008 : First version by Martin Otter (DLR) and
+                     Hans Olsson (Dynasim).
+
+
+   Copyright (C) 2008-2011 MODELISAR consortium,
+               2012-2013 Modelica Association Project "FMI"
+               All rights reserved.
+   This file is licensed by the copyright holders under the BSD 2-Clause License
+   (http://www.opensource.org/licenses/bsd-license.html):
+
+   ----------------------------------------------------------------------------
+   Redistribution and use in source and binary forms, with or without
+   modification, are permitted provided that the following conditions are met:
+
+   - Redistributions of source code must retain the above copyright notice,
+     this list of conditions and the following disclaimer.
+   - Redistributions in binary form must reproduce the above copyright notice,
+     this list of conditions and the following disclaimer in the documentation
+     and/or other materials provided with the distribution.
+   - Neither the name of the copyright holders nor the names of its
+     contributors may be used to endorse or promote products derived
+     from this software without specific prior written permission.
+
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+   TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+   PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
+   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+   OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+   OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+   ----------------------------------------------------------------------------
+
+   with the extension:
+
+   You may distribute or publicly perform any modification only under the
+   terms of this license.
+   (Note, this means that if you distribute a modified file,
+    the modified file must also be provided under this license).
+*/
+
+/* Platform (unique identification of this header file) */
+#define fmi2TypesPlatform "default"
+
+/* Type definitions of variables passed as arguments
+   Version "default" means:
+
+   fmi2Component           : an opaque object pointer
+   fmi2ComponentEnvironment: an opaque object pointer
+   fmi2FMUstate            : an opaque object pointer
+   fmi2ValueReference      : handle to the value of a variable
+   fmi2Real                : double precision floating-point data type
+   fmi2Integer             : basic signed integer data type
+   fmi2Boolean             : basic signed integer data type
+   fmi2Char                : character data type
+   fmi2String              : a pointer to a vector of fmi2Char characters
+                             ('\0' terminated, UTF8 encoded)
+   fmi2Byte                : smallest addressable unit of the machine, typically one byte.
+*/
+   typedef void*           fmi2Component;               /* Pointer to FMU instance       */
+   typedef void*           fmi2ComponentEnvironment;    /* Pointer to FMU environment    */
+   typedef void*           fmi2FMUstate;                /* Pointer to internal FMU state */
+   typedef unsigned int    fmi2ValueReference;
+   typedef double          fmi2Real   ;
+   typedef int             fmi2Integer;
+   typedef int             fmi2Boolean;
+   typedef char            fmi2Char;
+   typedef const fmi2Char* fmi2String;
+   typedef char            fmi2Byte;
+
+/* Values for fmi2Boolean  */
+#define fmi2True  1
+#define fmi2False 0
+
+
+#endif /* fmi2TypesPlatform_h */

+ 593 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_control_master/sim_support.c

@@ -0,0 +1,593 @@
+/* -------------------------------------------------------------------------
+ * sim_support.c
+ * Functions used by both FMU simulators fmu20sim_me and fmu20sim_cs
+ * to parse command-line arguments, to unzip and load an fmu,
+ * to write CSV file, and more.
+ *
+ * Revision history
+ *  07.03.2014 initial version released in FMU SDK 2.0.0
+ *  10.04.2014 use FMI 2.0 headers that prefix function and type names with 'fmi2'.
+ *             When 'fmi2' functions are not found in loaded DLL, look also for
+ *             FMI 2.0 RC1 function names.
+ *
+ * Author: Adrian Tirea
+ * Copyright QTronic GmbH. All rights reserved.
+ * -------------------------------------------------------------------------*/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+#include <stdarg.h>
+#include <dlfcn.h>
+#include "fmi2.h"
+#include "sim_support.h"
+
+#define FMI_COSIMULATION
+
+
+//int unzip(const char *zipPath, const char *outPath) {
+//    int code;
+//    char cwd[BUFSIZE];
+//    char binPath[BUFSIZE];
+//    int n = strlen(UNZIP_CMD) + strlen(outPath) + 3 +  strlen(zipPath) + 9;
+//    char* cmd = (char*)calloc(sizeof(char), n);
+//
+//    // remember current directory
+//    if (!GetCurrentDirectory(BUFSIZE, cwd)) {
+//        printf ("error: Could not get current directory\n");
+//        return 0; // error
+//    }
+//
+//    // change to %FMUSDK_HOME%\bin to find 7z.dll and 7z.exe
+//    if (!GetEnvironmentVariable("FMUSDK_HOME", binPath, BUFSIZE)) {
+//        if (GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
+//            printf ("error: Environment variable FMUSDK_HOME not defined\n");
+//        }
+//        else {
+//            printf ("error: Could not get value of FMUSDK_HOME\n");
+//        }
+//        return 0; // error
+//    }
+//    strcat(binPath, "\\bin");
+//    if (!SetCurrentDirectory(binPath)) {
+//        printf ("error: could not change to directory '%s'\n", binPath);
+//        return 0; // error
+//    }
+//
+//    // run the unzip command
+//    // remove "> NUL" to see the unzip protocol
+//    sprintf(cmd, "%s\"%s\" \"%s\" > NUL", UNZIP_CMD, outPath, zipPath);
+//    // printf("cmd='%s'\n", cmd);
+//    code = system(cmd);
+//    free(cmd);
+//    if (code != SEVEN_ZIP_NO_ERROR) {
+//        printf("7z: ");
+//        switch (code) {
+//            case SEVEN_ZIP_WARNING:            printf("warning\n"); break;
+//            case SEVEN_ZIP_ERROR:              printf("error\n"); break;
+//            case SEVEN_ZIP_COMMAND_LINE_ERROR: printf("command line error\n"); break;
+//            case SEVEN_ZIP_OUT_OF_MEMORY:      printf("out of memory\n"); break;
+//            case SEVEN_ZIP_STOPPED_BY_USER:    printf("stopped by user\n"); break;
+//            default: printf("unknown problem\n");
+//        }
+//    }
+//
+//    // restore current directory
+//    SetCurrentDirectory(cwd);
+//    return (code == SEVEN_ZIP_NO_ERROR || code == SEVEN_ZIP_WARNING) ? 1 : 0;
+//}
+//
+//// fileName is an absolute path, e.g. C:\test\a.fmu
+//// or relative to the current dir, e.g. ..\test\a.fmu
+//// Does not check for existence of the file
+//static char* getFmuPath(const char* fileName){
+//    char pathName[MAX_PATH];
+//    int n = GetFullPathName(fileName, MAX_PATH, pathName, NULL);
+//    return n ? strdup(pathName) : NULL;
+//}
+//
+//static char* getTmpPath() {
+//    char tmpPath[BUFSIZE];
+//    if(! GetTempPath(BUFSIZE, tmpPath)) {
+//        printf ("error: Could not find temporary disk space\n");
+//        return NULL;
+//    }
+//    strcat(tmpPath, "fmu\\");
+//    return strdup(tmpPath);
+//}
+//
+//char *getTempResourcesLocation() {
+//    char *tempPath = getTmpPath();
+//    char *resourcesLocation = (char *)calloc(sizeof(char), 9 + strlen(RESOURCES_DIR) + strlen(tempPath));
+//    strcpy(resourcesLocation, "file:///");
+//    strcat(resourcesLocation, tempPath);
+//    strcat(resourcesLocation, RESOURCES_DIR);
+//    free(tempPath);
+//    return resourcesLocation;
+//}
+
+static void *getAdr(int *success, void *dllHandle, const char *functionName, const char* preamble) {
+
+    int length = strlen(preamble) + strlen(functionName) + 1;
+    char* new_name = malloc(length);  // allocate memory
+    strcpy(new_name, preamble);  // copy first string
+    strcat(new_name, functionName);
+    void* fp = dlsym(dllHandle, new_name);
+    if (!fp) {
+        printf("warning: Function %s not found in dll\n", new_name);
+        *success = 0;
+    }
+    free(new_name);
+    return fp;
+}
+
+// Load the given dll and set function pointers in fmu
+// Return 0 to indicate failure
+int loadDll(const char* dllPath, FMU *fmu, const char* preamble) {
+    int s = 1;
+    //HMODULE h = LoadLibrary(dllPath);
+    void *h = dlopen(dllPath, RTLD_LAZY);
+    printf("%s", dlerror());
+    if (!h) {
+        printf("error: Could not load %s\n", dllPath);
+        return 0; // failure
+    }
+    fmu->dllHandle = h;
+    fmu->getTypesPlatform          = (fmi2GetTypesPlatformTYPE *)      getAdr(&s, h, "fmi2GetTypesPlatform", preamble);
+    fmu->getVersion                = (fmi2GetVersionTYPE *)            getAdr(&s, h, "fmi2GetVersion", preamble);
+    fmu->setDebugLogging           = (fmi2SetDebugLoggingTYPE *)       getAdr(&s, h, "fmi2SetDebugLogging",preamble);
+    fmu->instantiate               = (fmi2InstantiateTYPE *)           getAdr(&s, h, "fmi2Instantiate", preamble);
+    fmu->freeInstance              = (fmi2FreeInstanceTYPE *)          getAdr(&s, h, "fmi2FreeInstance", preamble);
+    fmu->setupExperiment           = (fmi2SetupExperimentTYPE *)       getAdr(&s, h, "fmi2SetupExperiment", preamble);
+    fmu->enterInitializationMode   = (fmi2EnterInitializationModeTYPE *) getAdr(&s, h, "fmi2EnterInitializationMode", preamble);
+    fmu->exitInitializationMode    = (fmi2ExitInitializationModeTYPE *) getAdr(&s, h, "fmi2ExitInitializationMode", preamble);
+    fmu->terminate                 = (fmi2TerminateTYPE *)             getAdr(&s, h, "fmi2Terminate", preamble);
+    fmu->reset                     = (fmi2ResetTYPE *)                 getAdr(&s, h, "fmi2Reset", preamble);
+    fmu->getReal                   = (fmi2GetRealTYPE *)               getAdr(&s, h, "fmi2GetReal", preamble);
+    fmu->getInteger                = (fmi2GetIntegerTYPE *)            getAdr(&s, h, "fmi2GetInteger", preamble);
+    fmu->getBoolean                = (fmi2GetBooleanTYPE *)            getAdr(&s, h, "fmi2GetBoolean", preamble);
+    fmu->getString                 = (fmi2GetStringTYPE *)             getAdr(&s, h, "fmi2GetString", preamble);
+    fmu->setReal                   = (fmi2SetRealTYPE *)               getAdr(&s, h, "fmi2SetReal", preamble);
+    fmu->setInteger                = (fmi2SetIntegerTYPE *)            getAdr(&s, h, "fmi2SetInteger", preamble);
+    fmu->setBoolean                = (fmi2SetBooleanTYPE *)            getAdr(&s, h, "fmi2SetBoolean", preamble);
+    fmu->setString                 = (fmi2SetStringTYPE *)             getAdr(&s, h, "fmi2SetString", preamble);
+    fmu->getFMUstate               = (fmi2GetFMUstateTYPE *)           getAdr(&s, h, "fmi2GetFMUstate", preamble);
+    fmu->setFMUstate               = (fmi2SetFMUstateTYPE *)           getAdr(&s, h, "fmi2SetFMUstate", preamble);
+    fmu->freeFMUstate              = (fmi2FreeFMUstateTYPE *)          getAdr(&s, h, "fmi2FreeFMUstate", preamble);
+    fmu->serializedFMUstateSize    = (fmi2SerializedFMUstateSizeTYPE *) getAdr(&s, h, "fmi2SerializedFMUstateSize", preamble);
+    fmu->serializeFMUstate         = (fmi2SerializeFMUstateTYPE *)     getAdr(&s, h, "fmi2SerializeFMUstate", preamble);
+    fmu->deSerializeFMUstate       = (fmi2DeSerializeFMUstateTYPE *)   getAdr(&s, h, "fmi2DeSerializeFMUstate", preamble);
+    fmu->getDirectionalDerivative  = (fmi2GetDirectionalDerivativeTYPE *) getAdr(&s, h, "fmi2GetDirectionalDerivative", preamble);
+#ifdef FMI_COSIMULATION
+    fmu->setRealInputDerivatives   = (fmi2SetRealInputDerivativesTYPE *) getAdr(&s, h, "fmi2SetRealInputDerivatives", preamble);
+    fmu->getRealOutputDerivatives  = (fmi2GetRealOutputDerivativesTYPE *) getAdr(&s, h, "fmi2GetRealOutputDerivatives", preamble);
+    fmu->doStep                    = (fmi2DoStepTYPE *)                getAdr(&s, h, "fmi2DoStep", preamble);
+    fmu->cancelStep                = (fmi2CancelStepTYPE *)            getAdr(&s, h, "fmi2CancelStep", preamble);
+    fmu->getStatus                 = (fmi2GetStatusTYPE *)             getAdr(&s, h, "fmi2GetStatus", preamble);
+    fmu->getRealStatus             = (fmi2GetRealStatusTYPE *)         getAdr(&s, h, "fmi2GetRealStatus", preamble);
+    fmu->getIntegerStatus          = (fmi2GetIntegerStatusTYPE *)      getAdr(&s, h, "fmi2GetIntegerStatus", preamble);
+    fmu->getBooleanStatus          = (fmi2GetBooleanStatusTYPE *)      getAdr(&s, h, "fmi2GetBooleanStatus", preamble);
+    fmu->getStringStatus           = (fmi2GetStringStatusTYPE *)       getAdr(&s, h, "fmi2GetStringStatus", preamble);
+#else // FMI2 for Model Exchange
+    fmu->enterEventMode            = (fmi2EnterEventModeTYPE *)        getAdr(&s, h, "fmi2EnterEventMode", preamble);
+    fmu->newDiscreteStates         = (fmi2NewDiscreteStatesTYPE *)     getAdr(&s, h, "fmi2NewDiscreteStates", preamble);
+    fmu->enterContinuousTimeMode   = (fmi2EnterContinuousTimeModeTYPE *) getAdr(&s, h, "fmi2EnterContinuousTimeMode", preamble);
+    fmu->completedIntegratorStep   = (fmi2CompletedIntegratorStepTYPE *) getAdr(&s, h, "fmi2CompletedIntegratorStep", preamble);
+    fmu->setTime                   = (fmi2SetTimeTYPE *)               getAdr(&s, h, "fmi2SetTime", preamble);
+    fmu->setContinuousStates       = (fmi2SetContinuousStatesTYPE *)   getAdr(&s, h, "fmi2SetContinuousStates", preamble);
+    fmu->getDerivatives            = (fmi2GetDerivativesTYPE *)        getAdr(&s, h, "fmi2GetDerivatives", preamble);
+    fmu->getEventIndicators        = (fmi2GetEventIndicatorsTYPE *)    getAdr(&s, h, "fmi2GetEventIndicators", preamble);
+    fmu->getContinuousStates       = (fmi2GetContinuousStatesTYPE *)   getAdr(&s, h, "fmi2GetContinuousStates", preamble);
+    fmu->getNominalsOfContinuousStates = (fmi2GetNominalsOfContinuousStatesTYPE *) getAdr(&s, h, "fmi2GetNominalsOfContinuousStates", preamble);
+#endif
+
+    if (fmu->getVersion == NULL && fmu->instantiate == NULL) {
+        printf("warning: Functions from FMI 2.0 could not be found in %s\n", dllPath);
+        printf("warning: Simulator will look for FMI 2.0 RC1 functions names...\n");
+        fmu->getTypesPlatform          = (fmi2GetTypesPlatformTYPE *)      getAdr(&s, h, "fmiGetTypesPlatform", preamble);
+        fmu->getVersion                = (fmi2GetVersionTYPE *)            getAdr(&s, h, "fmiGetVersion", preamble);
+        fmu->setDebugLogging           = (fmi2SetDebugLoggingTYPE *)       getAdr(&s, h, "fmiSetDebugLogging", preamble);
+        fmu->instantiate               = (fmi2InstantiateTYPE *)           getAdr(&s, h, "fmiInstantiate", preamble);
+        fmu->freeInstance              = (fmi2FreeInstanceTYPE *)          getAdr(&s, h, "fmiFreeInstance", preamble);
+        fmu->setupExperiment           = (fmi2SetupExperimentTYPE *)       getAdr(&s, h, "fmiSetupExperiment", preamble);
+        fmu->enterInitializationMode   = (fmi2EnterInitializationModeTYPE *) getAdr(&s, h, "fmiEnterInitializationMode", preamble);
+        fmu->exitInitializationMode    = (fmi2ExitInitializationModeTYPE *) getAdr(&s, h, "fmiExitInitializationMode", preamble);
+        fmu->terminate                 = (fmi2TerminateTYPE *)             getAdr(&s, h, "fmiTerminate", preamble);
+        fmu->reset                     = (fmi2ResetTYPE *)                 getAdr(&s, h, "fmiReset", preamble);
+        fmu->getReal                   = (fmi2GetRealTYPE *)               getAdr(&s, h, "fmiGetReal", preamble);
+        fmu->getInteger                = (fmi2GetIntegerTYPE *)            getAdr(&s, h, "fmiGetInteger", preamble);
+        fmu->getBoolean                = (fmi2GetBooleanTYPE *)            getAdr(&s, h, "fmiGetBoolean", preamble);
+        fmu->getString                 = (fmi2GetStringTYPE *)             getAdr(&s, h, "fmiGetString", preamble);
+        fmu->setReal                   = (fmi2SetRealTYPE *)               getAdr(&s, h, "fmiSetReal", preamble);
+        fmu->setInteger                = (fmi2SetIntegerTYPE *)            getAdr(&s, h, "fmiSetInteger", preamble);
+        fmu->setBoolean                = (fmi2SetBooleanTYPE *)            getAdr(&s, h, "fmiSetBoolean", preamble);
+        fmu->setString                 = (fmi2SetStringTYPE *)             getAdr(&s, h, "fmiSetString", preamble);
+        fmu->getFMUstate               = (fmi2GetFMUstateTYPE *)           getAdr(&s, h, "fmiGetFMUstate", preamble);
+        fmu->setFMUstate               = (fmi2SetFMUstateTYPE *)           getAdr(&s, h, "fmiSetFMUstate", preamble);
+        fmu->freeFMUstate              = (fmi2FreeFMUstateTYPE *)          getAdr(&s, h, "fmiFreeFMUstate", preamble);
+        fmu->serializedFMUstateSize    = (fmi2SerializedFMUstateSizeTYPE *) getAdr(&s, h, "fmiSerializedFMUstateSize", preamble);
+        fmu->serializeFMUstate         = (fmi2SerializeFMUstateTYPE *)     getAdr(&s, h, "fmiSerializeFMUstate", preamble);
+        fmu->deSerializeFMUstate       = (fmi2DeSerializeFMUstateTYPE *)   getAdr(&s, h, "fmiDeSerializeFMUstate", preamble);
+        fmu->getDirectionalDerivative  = (fmi2GetDirectionalDerivativeTYPE *) getAdr(&s, h, "fmiGetDirectionalDerivative", preamble);
+    #ifdef FMI_COSIMULATION
+        fmu->setRealInputDerivatives   = (fmi2SetRealInputDerivativesTYPE *) getAdr(&s, h, "fmiSetRealInputDerivatives", preamble);
+        fmu->getRealOutputDerivatives  = (fmi2GetRealOutputDerivativesTYPE *) getAdr(&s, h, "fmiGetRealOutputDerivatives", preamble);
+        fmu->doStep                    = (fmi2DoStepTYPE *)                getAdr(&s, h, "fmiDoStep", preamble);
+        fmu->cancelStep                = (fmi2CancelStepTYPE *)            getAdr(&s, h, "fmiCancelStep", preamble);
+        fmu->getStatus                 = (fmi2GetStatusTYPE *)             getAdr(&s, h, "fmiGetStatus", preamble);
+        fmu->getRealStatus             = (fmi2GetRealStatusTYPE *)         getAdr(&s, h, "fmiGetRealStatus", preamble);
+        fmu->getIntegerStatus          = (fmi2GetIntegerStatusTYPE *)      getAdr(&s, h, "fmiGetIntegerStatus", preamble);
+        fmu->getBooleanStatus          = (fmi2GetBooleanStatusTYPE *)      getAdr(&s, h, "fmiGetBooleanStatus", preamble);
+        fmu->getStringStatus           = (fmi2GetStringStatusTYPE *)       getAdr(&s, h, "fmiGetStringStatus", preamble);
+    #else // FMI2 for Model Exchange
+        fmu->enterEventMode            = (fmi2EnterEventModeTYPE *)        getAdr(&s, h, "fmiEnterEventMode", preamble);
+        fmu->newDiscreteStates         = (fmi2NewDiscreteStatesTYPE *)     getAdr(&s, h, "fmiNewDiscreteStates", preamble);
+        fmu->enterContinuousTimeMode   = (fmi2EnterContinuousTimeModeTYPE *) getAdr(&s, h, "fmiEnterContinuousTimeMode", preamble);
+        fmu->completedIntegratorStep   = (fmi2CompletedIntegratorStepTYPE *) getAdr(&s, h, "fmiCompletedIntegratorStep", preamble);
+        fmu->setTime                   = (fmi2SetTimeTYPE *)               getAdr(&s, h, "fmiSetTime", preamble);
+        fmu->setContinuousStates       = (fmi2SetContinuousStatesTYPE *)   getAdr(&s, h, "fmiSetContinuousStates", preamble);
+        fmu->getDerivatives            = (fmi2GetDerivativesTYPE *)        getAdr(&s, h, "fmiGetDerivatives", preamble);
+        fmu->getEventIndicators        = (fmi2GetEventIndicatorsTYPE *)    getAdr(&s, h, "fmiGetEventIndicators", preamble);
+        fmu->getContinuousStates       = (fmi2GetContinuousStatesTYPE *)   getAdr(&s, h, "fmiGetContinuousStates", preamble);
+        fmu->getNominalsOfContinuousStates = (fmi2GetNominalsOfContinuousStatesTYPE *) getAdr(&s, h, "fmiGetNominalsOfContinuousStates", preamble);
+    #endif
+    }
+    return s;
+}
+
+//static void printModelDescription(ModelDescription* md){
+//    Element* e = (Element*)md;
+//    int i;
+//    int n; // number of attributes
+//    const char **attributes = getAttributesAsArray(e, &n);
+//    Component *component;
+//
+//    if (!attributes) {
+//        printf("ModelDescription printing aborted.");
+//        return;
+//    }
+//    printf("%s\n", getElementTypeName(e));
+//    for (i = 0; i < n; i += 2) {
+//        printf("  %s=%s\n", attributes[i], attributes[i+1]);
+//    }
+//    free((void *)attributes);
+//
+//#ifdef FMI_COSIMULATION
+//    component = getCoSimulation(md);
+//    if (!component) {
+//        printf("error: No CoSimulation element found in model description. This FMU is not for Co-Simulation.\n");
+//        exit(EXIT_FAILURE);
+//    }
+//#else // FMI_MODEL_EXCHANGE
+//    component = getModelExchange(md);
+//    if (!component) {
+//        printf("error: No ModelExchange element found in model description. This FMU is not for Model Exchange.\n");
+//        exit(EXIT_FAILURE);
+//    }
+//#endif
+//    printf("%s\n", getElementTypeName((Element *)component));
+//    attributes = getAttributesAsArray((Element *)component, &n);
+//    if (!attributes) {
+//        printf("ModelDescription printing aborted.");
+//        return;
+//    }
+//    for (i = 0; i < n; i += 2) {
+//        printf("  %s=%s\n", attributes[i], attributes[i+1]);
+//    }
+//
+//    free((void *)attributes);
+//}
+//
+//void loadFMU(const char* fmuFileName) {
+//    char* fmuPath;
+//    char* tmpPath;
+//    char* xmlPath;
+//    char* dllPath;
+//    const char *modelId;
+//
+//    // get absolute path to FMU, NULL if not found
+//    fmuPath = getFmuPath(fmuFileName);
+//    if (!fmuPath) exit(EXIT_FAILURE);
+//
+//    // unzip the FMU to the tmpPath directory
+//    tmpPath = getTmpPath();
+//    if (!unzip(fmuPath, tmpPath)) exit(EXIT_FAILURE);
+//
+//    // parse tmpPath\modelDescription.xml
+//    xmlPath = calloc(sizeof(char), strlen(tmpPath) + strlen(XML_FILE) + 1);
+//    sprintf(xmlPath, "%s%s", tmpPath, XML_FILE);
+//    fmu.modelDescription = parse(xmlPath);
+//    free(xmlPath);
+//    if (!fmu.modelDescription) exit(EXIT_FAILURE);
+//    printModelDescription(fmu.modelDescription);
+//#ifdef FMI_COSIMULATION
+//    modelId = getAttributeValue((Element *)getCoSimulation(fmu.modelDescription), att_modelIdentifier);
+//#else // FMI_MODEL_EXCHANGE
+//    modelId = getAttributeValue((Element *)getModelExchange(fmu.modelDescription), att_modelIdentifier);
+//#endif
+//    // load the FMU dll
+//    dllPath = calloc(sizeof(char), strlen(tmpPath) + strlen(DLL_DIR)
+//        + strlen(modelId) +  strlen(".dll") + 1);
+//    sprintf(dllPath, "%s%s%s.dll", tmpPath, DLL_DIR, modelId);
+//    if (!loadDll(dllPath, &fmu)) {
+//        exit(EXIT_FAILURE);
+//    }
+//    free(dllPath);
+//    free(fmuPath);
+//    free(tmpPath);
+//}
+//
+//void deleteUnzippedFiles() {
+//    const char *fmuTempPath = getTmpPath();
+//    char *cmd = (char *)calloc(15 + strlen(fmuTempPath), sizeof(char));
+//    sprintf(cmd, "rmdir /S /Q %s", fmuTempPath);
+//    system(cmd);
+//    free(cmd);
+//}
+//
+//static void doubleToCommaString(char* buffer, double r){
+//    char* comma;
+//    sprintf(buffer, "%.16g", r);
+//    comma = strchr(buffer, '.');
+//    if (comma) *comma = ',';
+//}
+//
+//// output time and all variables in CSV format
+//// if separator is ',', columns are separated by ',' and '.' is used for floating-point numbers.
+//// otherwise, the given separator (e.g. ';' or '\t') is to separate columns, and ',' is used
+//// as decimal dot in floating-point numbers.
+//void outputRow(FMU *fmu, fmi2Component c, double time, FILE* file, char separator, fmi2Boolean header) {
+//    int k;
+//    fmi2Real r;
+//    fmi2Integer i;
+//    fmi2Boolean b;
+//    fmi2String s;
+//    fmi2ValueReference vr;
+//    int n = getScalarVariableSize(fmu->modelDescription);
+//    char buffer[32];
+//
+//    // print first column
+//    if (header) {
+//        fprintf(file, "time");
+//    } else {
+//        if (separator==',')
+//            fprintf(file, "%.16g", time);
+//        else {
+//            // separator is e.g. ';' or '\t'
+//            doubleToCommaString(buffer, time);
+//            fprintf(file, "%s", buffer);
+//        }
+//    }
+//
+//    // print all other columns
+//    for (k = 0; k < n; k++) {
+//        ScalarVariable *sv = getScalarVariable(fmu->modelDescription, k);
+//        if (header) {
+//            // output names only
+//            if (separator == ',') {
+//                // treat array element, e.g. print a[1, 2] as a[1.2]
+//                const char *s = getAttributeValue((Element *)sv, att_name);
+//                fprintf(file, "%c", separator);
+//                while (*s) {
+//                    if (*s != ' ') {
+//                        fprintf(file, "%c", *s == ',' ? '.' : *s);
+//                    }
+//                    s++;
+//                }
+//            } else {
+//                fprintf(file, "%c%s", separator, getAttributeValue((Element *)sv, att_name));
+//            }
+//        } else {
+//            // output values
+//            vr = getValueReference(sv);
+//            switch (getElementType(getTypeSpec(sv))) {
+//                case elm_Real:
+//                    fmu->getReal(c, &vr, 1, &r);
+//                    if (separator == ',') {
+//                        fprintf(file, ",%.16g", r);
+//                    } else {
+//                        // separator is e.g. ';' or '\t'
+//                        doubleToCommaString(buffer, r);
+//                        fprintf(file, "%c%s", separator, buffer);
+//                    }
+//                    break;
+//                case elm_Integer:
+//                case elm_Enumeration:
+//                    fmu->getInteger(c, &vr, 1, &i);
+//                    fprintf(file, "%c%d", separator, i);
+//                    break;
+//                case elm_Boolean:
+//                    fmu->getBoolean(c, &vr, 1, &b);
+//                    fprintf(file, "%c%d", separator, b);
+//                    break;
+//                case elm_String:
+//                    fmu->getString(c, &vr, 1, &s);
+//                    fprintf(file, "%c%s", separator, s);
+//                    break;
+//                default:
+//                    fprintf(file, "%cNoValueForType=%d", separator, getElementType(getTypeSpec(sv)));
+//            }
+//        }
+//    } // for
+//
+//    // terminate this row
+//    fprintf(file, "\n");
+//}
+//
+static const char* fmi2StatusToString(fmi2Status status){
+    switch (status){
+        case fmi2OK:      return "ok";
+        case fmi2Warning: return "warning";
+        case fmi2Discard: return "discard";
+        case fmi2Error:   return "error";
+        case fmi2Fatal:   return "fatal";
+    #ifdef FMI_COSIMULATION
+        case fmi2Pending: return "fmi2Pending";
+    #endif
+        default:         return "?";
+    }
+}
+
+// search a fmu for the given variable, matching the type specified.
+// return NULL if not found
+//static ScalarVariable* getSV(FMU* fmu, char type, fmi2ValueReference vr) {
+//    return NULL;
+//    int i;
+//    int n = getScalarVariableSize(fmu->modelDescription);
+//    Elm tp;
+//
+//    switch (type) {
+//        case 'r': tp = elm_Real;    break;
+//        case 'i': tp = elm_Integer; break;
+//        case 'b': tp = elm_Boolean; break;
+//        case 's': tp = elm_String;  break;
+//        default : tp = elm_BAD_DEFINED;
+//    }
+//    for (i = 0; i < n; i++) {
+//        ScalarVariable* sv = getScalarVariable(fmu->modelDescription ,i);
+//        if (vr == getValueReference(sv) && tp == getElementType(getTypeSpec(sv))) {
+//            return sv;
+//        }
+//    }
+//    return NULL;
+//}
+
+// replace e.g. #r1365# by variable name and ## by # in message
+// copies the result to buffer
+static void replaceRefsInMessage(const char* msg, char* buffer, int nBuffer, FMU* fmu){
+    int i = 0; // position in msg
+    int k = 0; // position in buffer
+    int n;
+    char c = msg[i];
+    while (c != '\0' && k < nBuffer) {
+        if (c != '#') {
+            buffer[k++] = c;
+            i++;
+            c = msg[i];
+        } else {
+
+            char* end = strchr(msg + i + 1, '#');
+            if (!end) {
+                printf("unmatched '#' in '%s'\n", msg);
+                buffer[k++] = '#';
+                break;
+            }
+            n = end - (msg + i);
+            if (n == 1) {
+                // ## detected, output #
+                buffer[k++] = '#';
+                i += 2;
+                c = msg[i];
+
+            } else {
+                //char type = msg[i + 1]; // one of ribs
+                fmi2ValueReference vr;
+                int nvr = sscanf(msg + i + 2, "%u", &vr);
+                if (nvr == 1) {
+                    // vr of type detected, e.g. #r12#
+                    //ScalarVariable* sv = getSV(fmu, type, vr);
+                    //const char* name = sv ? getAttributeValue((Element *)sv, att_name) : "?";
+                    //sprintf(buffer + k, "%s", name);
+                    //k += strlen(name);
+                    //i += (n+1);
+                    //c = msg[i];
+
+                } else {
+                    // could not parse the number
+                    printf("illegal value reference at position %d in '%s'\n", i + 2, msg);
+                    buffer[k++] = '#';
+                    break;
+                }
+            }
+        }
+    } // while
+    buffer[k] = '\0';
+}
+
+#define MAX_MSG_SIZE 1000
+void fmuLogger(void *componentEnvironment, fmi2String instanceName, fmi2Status status,
+               fmi2String category, fmi2String message, ...) {
+    char msg[MAX_MSG_SIZE];
+    char* copy;
+    va_list argp;
+
+    // replace C format strings
+    va_start(argp, message);
+    vsprintf(msg, message, argp);
+    va_end(argp);
+
+    // replace e.g. ## and #r12#
+    copy = strdup(msg);
+//    replaceRefsInMessage(copy, msg, MAX_MSG_SIZE, NULL);
+    free(copy);
+
+    // print the final message
+    if (!instanceName) instanceName = "?";
+    if (!category) category = "?";
+    printf("%s %s (%s): %s\n", fmi2StatusToString(status), instanceName, category, msg);
+}
+
+int error(const char* message){
+    printf("%s\n", message);
+    return 0;
+}
+//
+//void parseArguments(int argc, char *argv[], const char **fmuFileName, double *tEnd, double *h,
+//                    int *loggingOn, char *csv_separator, int *nCategories, char **logCategories[]) {
+//    // parse command line arguments
+//    if (argc > 1) {
+//        *fmuFileName = argv[1];
+//    } else {
+//        printf("error: no fmu file\n");
+//        printHelp(argv[0]);
+//        exit(EXIT_FAILURE);
+//    }
+//    if (argc > 2) {
+//        if (sscanf(argv[2],"%lf", tEnd) != 1) {
+//            printf("error: The given end time (%s) is not a number\n", argv[2]);
+//            exit(EXIT_FAILURE);
+//        }
+//    }
+//    if (argc > 3) {
+//        if (sscanf(argv[3],"%lf", h) != 1) {
+//            printf("error: The given stepsize (%s) is not a number\n", argv[3]);
+//            exit(EXIT_FAILURE);
+//        }
+//    }
+//    if (argc > 4) {
+//        if (sscanf(argv[4],"%d", loggingOn) != 1 || *loggingOn < 0 || *loggingOn > 1) {
+//            printf("error: The given logging flag (%s) is not boolean\n", argv[4]);
+//            exit(EXIT_FAILURE);
+//        }
+//    }
+//    if (argc > 5) {
+//        if (strlen(argv[5]) != 1) {
+//            printf("error: The given CSV separator char (%s) is not valid\n", argv[5]);
+//            exit(EXIT_FAILURE);
+//        }
+//        switch (argv[5][0]) {
+//            case 'c': *csv_separator = ','; break; // comma
+//            case 's': *csv_separator = ';'; break; // semicolon
+//            default:  *csv_separator = argv[5][0]; break; // any other char
+//        }
+//    }
+//    if (argc > 6) {
+//        int i;
+//        *nCategories = argc - 6;
+//        *logCategories = (char **)calloc(sizeof(char *), *nCategories);
+//        for (i = 0; i < *nCategories; i++) {
+//            (*logCategories)[i] = argv[i + 6];
+//        }
+//    }
+//}
+//
+//void printHelp(const char *fmusim) {
+//    printf("command syntax: %s <model.fmu> <tEnd> <h> <loggingOn> <csv separator>\n", fmusim);
+//    printf("   <model.fmu> .... path to FMU, relative to current dir or absolute, required\n");
+//    printf("   <tEnd> ......... end  time of simulation,   optional, defaults to 1.0 sec\n");
+//    printf("   <h> ............ step size of simulation,   optional, defaults to 0.1 sec\n");
+//    printf("   <loggingOn> .... 1 to activate logging,     optional, defaults to 0\n");
+//    printf("   <csv separator>. separator in csv file,     optional, c for ',', s for';', defaults to c\n");
+//    printf("   <logCategories>. list of active categories, optional, see modelDescription.xml for possible values\n");
+//}

+ 44 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_control_master/sim_support.h

@@ -0,0 +1,44 @@
+/* ------------------------------------------------------------------------- 
+ * sim_support.h
+ * Functions used by the FMU simulations fmusim_me and fmusim_cs.
+ * Copyright QTronic GmbH. All rights reserved.
+ * -------------------------------------------------------------------------*/
+#ifndef __SIM_SUPPORT_H
+#define __SIM_SUPPORT_H
+
+// Used 7z options, version 4.57:
+// -x   Extracts files from an archive with their full paths in the current dir, or in an output dir if specified
+// -aoa Overwrite All existing files without prompt
+// -o   Specifies a destination directory where files are to be extracted
+#define UNZIP_CMD "7z x -aoa -o"
+#define XML_FILE  "modelDescription.xml"
+#define RESULT_FILE "result.csv"
+#define BUFSIZE 4096
+#ifdef _WIN64
+#define DLL_DIR   "binaries\\win64\\"
+#else
+#define DLL_DIR   "binaries\\win32\\"
+#endif
+#define RESOURCES_DIR "resources\\"
+
+// return codes of the 7z command line tool
+#define SEVEN_ZIP_NO_ERROR 0 // success
+#define SEVEN_ZIP_WARNING 1  // e.g., one or more files were locked during zip
+#define SEVEN_ZIP_ERROR 2
+#define SEVEN_ZIP_COMMAND_LINE_ERROR 7
+#define SEVEN_ZIP_OUT_OF_MEMORY 8
+#define SEVEN_ZIP_STOPPED_BY_USER 255
+
+void fmuLogger(fmi2Component c, fmi2String instanceName, fmi2Status status, fmi2String category, fmi2String message, ...);
+int unzip(const char *zipPath, const char *outPath);
+void parseArguments(int argc, char *argv[], const char **fmuFileName, double *tEnd, double *h,
+                    int *loggingOn, char *csv_separator, int *nCategories, char **logCategories[]);
+void loadFMU(const char *fmuFileName);
+int loadDll(const char* dllPath, FMU *fmu, const char* preamble);
+void deleteUnzippedFiles();
+void outputRow(FMU *fmu, fmi2Component c, double time, FILE* file, char separator, fmi2Boolean header);
+int error(const char *message);
+void printHelp(const char *fmusim);
+char *getTempResourcesLocation(); // caller has to free the result
+
+#endif

BIN
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_generic_master/Debug/libFMI_generic_master.dll


+ 602 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_generic_master/FMI_GM.c

@@ -0,0 +1,602 @@
+/* ---------------------------------------------------------------------------*
+ * Sample implementation of an generic master FMU -
+ * ---------------------------------------------------------------------------*/
+/*
+Template for a  FMU
+*/
+
+#define MODEL_IDENTIFIER GM
+#define MODEL_GUID "{41f87101-edf2-4eef-90f3-42db56d4565f}"
+#define FMI2_FUNCTION_PREFIX PW_GENERIC_MASTER
+
+
+#include <stdio.h>
+#include "string.h"
+#include "fmi2Functions.h"
+#include <float.h>
+#include "FMI_GM.h"
+#include <math.h>
+#include "fmi2.h"
+#include "sim_support.h"
+
+
+
+#define NUMBER_OF_REALS 1
+#define NUMBER_OF_STRINGS 0
+#define NUMBER_OF_BOOLEANS 11
+#define NUMBER_OF_INTEGERS 0
+/*
+ * The input
+ */
+
+#define _in_armature_current 0
+
+
+#define _in_driver_up 0
+#define _in_driver_up_stop 1
+#define _in_driver_down 2
+#define _in_driver_down_stop 3
+#define _in_passenger_up 4
+#define _in_passenger_up_stop 5
+#define _in_passenger_down 6
+#define _in_passenger_down_stop 7
+
+
+
+/*
+ * The output:
+*/
+
+#define _out_motor_up 9
+#define _out_motor_down 10
+
+ double relativeError(double a, double b){
+	return fabs((a - b) / a);
+}
+
+/*
+ * Helper function for absolute error
+ */
+ double absoluteError(double a, double b){
+	return fabs(a - b);
+}
+
+/*
+ * is_close function for double comparison
+ */
+ int is_close(double a, double b, double REL_TOL, double ABS_TOL){
+	return ((absoluteError(a,b)<ABS_TOL) && (relativeError(a,b)<REL_TOL));
+}
+
+fmi2Status fmi2SetDebugLogging(fmi2Component fc, fmi2Boolean loggingOn, size_t nCategories, const fmi2String categories[])
+{
+    return fmi2OK;
+}
+
+fmi2Status fmi2SetString(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, const fmi2String value[])
+{
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetString(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, fmi2String value[])
+{
+    return fmi2Error;
+}
+
+fmi2Status fmi2SetReal(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, const fmi2Real value[])
+{
+	FMUInstance* comp = (FMUInstance *)fc;
+		int i;
+	    for (i = 0; i < nvr; i++)
+		{
+	    	if(vr[i]>=5){
+	    		printf("Value reference: %d, cannot be set, it is a store element\n", vr[i]);
+	    	}else{
+	    		 printf("Value reference: %d\n", vr[i]);
+	    		 comp->r[vr[i]] = value[i];
+	    	}
+
+	        //setExposedReal(vr[i], value[i]);
+	        //comp->r[vr[i]] = value[i];
+	    }
+	    return fmi2OK;
+}
+
+fmi2Status fmi2GetReal(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, fmi2Real value[])
+{
+
+    FMUInstance* comp = (FMUInstance *)fc;
+	int i;
+    for (i = 0; i < nvr; i++)
+	{
+        value[i] = comp->r[(vr[i])];
+    }
+    return fmi2OK;
+}
+
+fmi2Status fmi2SetBoolean(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, const fmi2Boolean value[])
+{
+	FMUInstance* comp = (FMUInstance *)fc;
+	int i;
+	for (i = 0; i < nvr; i++)
+	{
+		comp->b[vr[i]] = value[i];
+	}
+    return fmi2OK;
+}
+
+fmi2Status fmi2GetBoolean(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, fmi2Boolean value[])
+{
+	FMUInstance* comp = (FMUInstance *)fc;
+	int i;
+	for (i = 0; i < nvr; i++)
+	{
+		value[i] = comp->b[vr[i]];
+	}
+    return fmi2OK;
+}
+
+fmi2Component fmi2Instantiate(fmi2String instanceName, fmi2Type fmuType, fmi2String fmuGUID, fmi2String fmuLocation, const fmi2CallbackFunctions* functions, fmi2Boolean visible, fmi2Boolean loggingOn)
+{
+
+	//Declare data structure for fmu instance
+    FMUInstance* fi;
+	printf("%s in fmiInstantiate\n",instanceName);
+
+    //Perform checks on passed callback functions
+    if (loggingOn) {
+
+        if (!functions->logger);
+        //return NULL;
+	}
+    //Check for instanceName
+    if (!instanceName || strlen(instanceName)==0) {
+
+        // print (and/or log) instanceName is missing
+        //return NULL;
+    }
+    //Check passed GUID to defined model GUID
+    if (strcmp(fmuGUID, MODEL_GUID))
+	{
+        // print (and/or log) GUID doesn't match
+        //return NULL;
+    }
+
+    //Allocate fmu instance Memory
+    // TODO check if "canNotUseMemoryManagementFunctions == true/false". If false memory allocation not possible
+    fi = (FMUInstance *)functions->allocateMemory(1, sizeof(FMUInstance));
+    if (fi) {
+        // Think about what to do with variable values. Using these structs and pointers slows down simulation computations. Maybe only necessary for input, output and tunable parameters??
+        fi->r = functions->allocateMemory(NUMBER_OF_REALS, sizeof(fmi2Real));
+        fi->i = functions->allocateMemory(NUMBER_OF_INTEGERS, sizeof(fmi2Integer));
+        fi->b = functions->allocateMemory(NUMBER_OF_BOOLEANS, sizeof(fmi2Boolean));
+        fi->s = functions->allocateMemory(NUMBER_OF_STRINGS,  sizeof(fmi2String));
+    } // variables in predefined arrays (performance issue) --> makes multiple instances of fmu impossible
+
+
+    fi->instanceName = functions->allocateMemory(1 + strlen(instanceName), sizeof(char));
+    fi->GUID = functions->allocateMemory(1 + strlen(fmuGUID), sizeof(char));
+
+    strcpy((char*)fi->instanceName, instanceName);
+    strcpy((char*)fi->GUID, fmuGUID);
+    fi->functions = functions;
+    fi->loggingOn = loggingOn;
+    fi->isVisible = visible;
+    fi->state = fmuInstantiated;
+    /* Load the inner FMUs:*/
+    loadDll("libFMI_SEL.dll", &(fi->fmu_order[0]), "FMI_SEL");
+    loadDll("libFMI_control_master.dll", &(fi->fmu_order[1]),"FMI_control_master");
+    loadDll("libFMI_TD.dll", &(fi->fmu_order[2]), "FMI_TD");
+    fi->fmuResourceLocation_order[0] = "libFMI_SEL";
+    fi->fmuResourceLocation_order[1] = "libFMI_control_master";
+    fi->fmuResourceLocation_order[2] ="libFMI_TD";
+    /*Instantiate inner components*/
+    for (int i=0; i<3; i++){
+        fi->c_order[i] = fi->fmu_order[i].instantiate("inner", fmi2CoSimulation, "1", fi->fmuResourceLocation_order[i] , fi->functions, visible, 0);
+    }
+    return fi;
+}
+
+fmi2Status fmi2SetupExperiment(fmi2Component fc, fmi2Boolean toleranceDefined, fmi2Real tolerance,
+                            fmi2Real startTime, fmi2Boolean stopTimeDefined, fmi2Real stopTime) {
+
+
+    FMUInstance* fi = (FMUInstance*) fc;
+	printf("%s in fmiSetupExperiment\n",fi->instanceName);
+	if (fi->state != fmuInstantiated)
+	{
+		printf("fmu: %s was not instatiated before calling fmiSetupExperiment\n", fi->instanceName);
+		return fmi2Error;
+	}
+	fi->currentTime = startTime;
+	fi->stopTimeDefined = stopTimeDefined;
+	fi->toleranceDefined = toleranceDefined;
+	if (stopTimeDefined)
+	{
+		fi->stopTime = stopTime;
+	}
+	if (toleranceDefined)
+	{
+		fi->tolerance = tolerance;
+	}
+
+	fi->accumulator = 0;
+	/*
+	 * setup inner
+	 */
+	fmi2Status fmi2Flag = fmi2OK;
+	fi->state = fmuExperimentSettedUp;
+	for(int i=0; i<3; i++){
+		fmi2Flag = fi->fmu_order[i].setupExperiment(fi->c_order[i], toleranceDefined, tolerance, startTime, fmi2True, stopTime);
+			    if (fmi2Flag == fmi2Error){
+			    	fi->state = fmuError;
+			    }
+	}
+
+    return fmi2Flag;
+}
+
+fmi2Status fmi2EnterInitializationMode(fmi2Component fc)
+{
+	FMUInstance* fi = (FMUInstance*) fc;
+	printf("%s in fmiEnterInitializationMode\n",fi->instanceName);
+	if (fi->state != fmuExperimentSettedUp)
+	{
+		printf("fmu: %s experiment was not set-up before calling fmiEnterInitializationMode\n", fi->instanceName);
+		return fmi2Error;
+	}
+    fi->state = fmuInitMode;
+    fmi2Status fmi2Flag = fmi2OK;
+    for(int i=0; i<3; i++){
+    	fmi2Flag = fi->fmu_order[i].enterInitializationMode(fi->c_order[i]);
+    	    if (fmi2Flag == fmi2Error){
+    	        return fi->state = fmuError;
+    	    }
+    }
+
+    return fmi2Flag;
+}
+
+fmi2Status fmi2ExitInitializationMode(fmi2Component fc)
+{
+	FMUInstance* fi = (FMUInstance*) fc;
+	printf("%s in fmiExitInitializationMode\n",fi->instanceName);
+	if (fi->state != fmuInitMode)
+	{
+		printf("fmu: %s did not enter Initialization Mode before calling fmiExitInitializationMode\n", fi->instanceName);
+		return fmi2Error;
+	}
+	// TODO
+	//initStatus = calculateInitialUnknownValues();
+	//initialize();
+    fi->state = fmuInitialized;
+    fmi2Status fmi2Flag = fmi2OK;
+    for(int i=0; i<3;i++){
+    	fmi2Flag = fi->fmu_order[i].exitInitializationMode(fi->c_order[i]);
+    	if (fmi2Flag == fmi2Error){
+    	           return fi->state = fmuError;
+    	    }
+    }
+
+
+    return fmi2Flag;
+}
+
+fmi2Status fmi2DoStep(fmi2Component fc , fmi2Real currentCommPoint, fmi2Real commStepSize, fmi2Boolean noPrevFMUState)
+{
+	FMUInstance* fi = (FMUInstance *)fc;
+	fmi2Status simStatus = fmi2OK;
+    printf("%s in fmiDoStep()\n",fi->instanceName);
+    /*
+     * I only should save this when the call to save and restore comes from here.
+     * In this case, the call arises from higher up in the hierarchy so, a complete saved state is already made
+     * for this FMU because it was called earlier on.
+     * This lines are needed in a top level master, or a multi-rate master
+     **/
+    //for (int i=0;i<3;i++){
+    //	fi->fmu_order[i].getFMUstate(fi->c_order[i], fi->c_order_store[i]);
+    //}
+    // I expanded the loop here:
+    fmi2Status thestatus[3];
+    fmi2ValueReference vr_tosel_booleans[8] = {0,1,2,3,4,5,6,7};
+    fmi2ValueReference vr_to_sel_reals[1] = {0};
+    fi->fmu_order[0].setBoolean(fi->c_order[0], vr_tosel_booleans,8, &(fi->b[0]));
+    fi->fmu_order[0].setReal(fi->c_order[0], vr_to_sel_reals,1, &(fi->r[0]));
+    thestatus[0] = fi->fmu_order[0].doStep(fi->c_order[0], currentCommPoint, commStepSize, fmi2True);
+    fmi2ValueReference vr_fromsel_booleans[10]={8,9,10,11,12,13,14,15,16,17};
+    fmi2Boolean fromSel[10];
+    fi->fmu_order[0].getBoolean(fi->c_order[0],vr_fromsel_booleans,10,fromSel);
+    fmi2ValueReference vr_to_cm[10] = {0,1,2,3,4,5,6,7,8,9};
+    fi->fmu_order[1].setBoolean(fi->c_order[1],vr_to_cm,10,fromSel);
+    thestatus[1] = fi->fmu_order[1].doStep(fi->c_order[1],currentCommPoint,commStepSize, fmi2True);
+    fmi2ValueReference vr_from_cm[2]={10,11};
+    fmi2Boolean from_cm[2];
+    fi->fmu_order[1].getBoolean(fi->c_order[1], vr_from_cm,2,from_cm);
+    fmi2ValueReference vr_to_td[2]= {0,1};
+    fi->fmu_order[2].setBoolean(fi->c_order[2],vr_to_td,2,from_cm);
+    thestatus[2] = fi->fmu_order[2].doStep(fi->c_order[2],currentCommPoint,commStepSize, fmi2True);
+    fmi2ValueReference vr_from_td[2] = {4,5};
+    fi->fmu_order[2].getBoolean(fi->c_order[2], vr_from_td,2,&(fi->b[_out_motor_up]));
+
+    for(int i=0;i<3; i++){
+    	if(simStatus == fmi2OK && thestatus[i] == fmi2Discard){
+    		simStatus = fmi2Discard;
+    	}
+    	if((simStatus == fmi2OK|| simStatus == fmi2Discard) && thestatus[i]==fmi2Error){
+    		simStatus = fmi2Error;
+    	}
+    }
+
+    if(simStatus == fmi2Discard){
+    	 fmi2Real theNextTime = currentCommPoint + commStepSize;
+    	 for(int i=0; i<3; i++){
+    		 fmi2Real theFMUtime;
+    		 fi->fmu_order[i].getRealStatus(fi->c_order[i], fmi2LastSuccessfulTime, &theFMUtime);
+    		 if(theFMUtime<theNextTime){
+    			 theNextTime = theFMUtime;
+    		 }
+    	 }
+    	fi->currentTime = theNextTime;
+    }else if(simStatus == fmi2OK){
+    	fi->currentTime = currentCommPoint + commStepSize;
+    }else{
+
+    }
+
+    return simStatus;
+}
+
+fmi2Status fmi2Terminate(fmi2Component fc)
+{
+	FMUInstance* fi = (FMUInstance *)fc;
+	printf("%s in fmiTerminate\n",fi->instanceName);
+	// do check if fi may be terminated
+	for (int i=0;i<3;i++){
+		fi->fmu_order[i].terminate(fi->c_order[i]);
+	}
+
+	fi->state = fmuTerminated;
+    return fmi2OK;
+}
+
+
+void fmi2FreeInstance(fmi2Component fc)
+{
+
+	FMUInstance* fi = (FMUInstance*) fc;
+	printf("%s in fmiFreeInstance\n",fi->instanceName);
+	for(int i=0;i<3;i++){
+		fi->fmu_order[i].freeInstance(fi->c_order[i]);
+	}
+
+    if (fi) {
+        fi->functions->freeMemory(fi->r);
+        fi->functions->freeMemory(fi->i);
+        fi->functions->freeMemory(fi->b);
+        fi->functions->freeMemory(fi->s);// TODO has to be done with loop
+		fi->functions->freeMemory((void*)fi->instanceName);
+		fi->functions->freeMemory((void*)fi->GUID);
+		fi->functions->freeMemory((void*)fi);
+
+    }
+}
+
+//To be implemented
+
+const char* fmi2GetVersion() {
+	printf("Function fmiGetVersion not supported\n");
+    return NULL;
+}
+
+const char* fmi2GetTypesPlatform() {
+	printf("Function fmiGetTypesPlatform not supported\n");
+    return NULL;
+}
+
+fmi2Status fmi2Reset(fmi2Component fc)
+{
+	printf("Function fmiReset not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2SetInteger(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, const fmi2Integer value[])
+{
+    printf("Function fmiSetInteger not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetInteger(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, fmi2Integer value[])
+{
+    printf("Function fmiGetInteger not supported\n");
+    return fmi2Error;
+}
+
+
+/*******OWN IMPLEMENTATION OF Get/Set FMU state*******/
+fmi2Status fmi2GetFMUstate (fmi2Component c, fmi2FMUstate* FMUstate) {
+	FMUInstance* orig = (FMUInstance*)c;
+	FMUInstance* fi = (FMUInstance *)FMUstate;
+    fi = orig->functions->allocateMemory(1, sizeof(FMUInstance));
+    fi->functions = orig->functions;
+    *FMUstate = fi;
+
+    if (fi) {
+        // Think about what to do with variable values. Using these structs and pointers slows down simulation computations. Maybe only necessary for input, output and tunable parameters??
+        fi->r = fi->functions->allocateMemory(NUMBER_OF_REALS, sizeof(fmi2Real));
+        fi->i = fi->functions->allocateMemory(NUMBER_OF_INTEGERS, sizeof(fmi2Integer));
+        fi->b = fi->functions->allocateMemory(NUMBER_OF_BOOLEANS, sizeof(fmi2Boolean));
+        fi->s = fi->functions->allocateMemory(NUMBER_OF_STRINGS,  sizeof(fmi2String));
+
+    } // variables in predefined arrays (performance issue) --> makes multiple instances of fmu impossible
+    fi->instanceName = orig->functions->allocateMemory(1 + strlen(orig->instanceName), sizeof(char));
+    fi->GUID = orig->functions->allocateMemory(1 + strlen(orig->GUID), sizeof(char));
+
+    strcpy((char *)fi->instanceName, (char *)orig->instanceName);
+    strcpy((char *)fi->GUID, (char *)orig->GUID);
+    fi->functions = orig->functions;
+    fi->loggingOn = orig->loggingOn;
+    fi->isVisible = orig->isVisible;
+    fi->state = orig->state;
+    fi->stepSize = orig->stepSize;
+    fi->startTime = orig->startTime;
+    fi->stopTime = orig->stopTime;
+	fi->currentTime = orig->currentTime;
+    /* TODO: Store all the rest here.*/
+    fi->accumulator = orig->accumulator;
+    fi->nextTimerEvent = orig->nextTimerEvent;
+    fi->tolerance = orig->tolerance;
+    fi->toleranceDefined = orig->toleranceDefined;
+	/*
+	 * This is a hierarchical call. First let the lower FMUs do their state saving
+	 * We will store the saved fmu state in the fi->c_order[i]
+	 */
+    for(int i=0;i<3;i++){
+    	fi->fmu_order[i]=orig->fmu_order[i];
+    	orig->fmu_order[i].getFMUstate(orig->c_order[i],fi->c_order[i]);
+    	fi->fmuResourceLocation_order[i] = fi->functions->allocateMemory(1+strlen(orig->fmuResourceLocation_order[i]), sizeof(char));
+    	strcpy((char *)fi->fmuResourceLocation_order[i],(char *)orig->fmuResourceLocation_order[i]);
+    	/*make shallow copies of the stored fmus*/
+    }
+	//copy r
+	int i=0;
+	for (i=0; i< NUMBER_OF_REALS;i++){
+	    printf("Setting real: %i %f\n", i, orig->r[i]);
+        fi->r[i] = orig->r[i];
+        printf("Setted real: %i %f\n", i, fi->r[i]);
+	}
+	//copy s
+	for (i=0; i< NUMBER_OF_STRINGS;i++){
+        //fi->s[i] = orig->s[i]; // why are this not deep copies?
+		fi->s[i] = fi->functions->allocateMemory(1+strlen(orig->s[i]),sizeof(char));
+		strcpy((char *)fi->s[i],(char *)orig->s[i]);
+	}
+	//copy i
+    for (i=0; i< NUMBER_OF_INTEGERS;i++){
+        fi->i[i] = orig->i[i];
+	}
+	//copy b
+	for (i=0; i< NUMBER_OF_BOOLEANS;i++){
+        fi->b[i] = orig->b[i];
+	}
+    return fmi2OK;
+}
+
+fmi2Status fmi2SetFMUstate (fmi2Component c, fmi2FMUstate FMUstate) {
+    FMUInstance* orig = (FMUInstance*)FMUstate;
+    FMUInstance* fi = (FMUInstance*)c;
+    /*
+     * First restore the hierarchical fmus.
+     */
+    for(int i=0;i<3;i++){
+    	fi->fmu_order[i].setFMUstate(fi->c_order[i],orig->c_order[i]);
+    	fi->fmuResourceLocation_order[i] = orig->functions->allocateMemory(1+strlen(orig->fmuResourceLocation_order[i]), sizeof(char));
+    	strcpy((char *)fi->fmuResourceLocation_order[i],(char *)orig->fmuResourceLocation_order[i]);
+    }
+
+    //set time etc correct, name and GUID should still be ok ;-)
+    printf("setting time values from %f to %f\n", fi->currentTime, orig->currentTime);
+    fi->state = orig->state;
+    fi->stepSize = orig->stepSize;
+    fi->startTime = orig->startTime;
+    fi->stopTime = orig->stopTime;
+	fi->currentTime = orig->currentTime;
+    fi->accumulator = orig->accumulator;
+    fi->nextTimerEvent = orig->nextTimerEvent;
+    fi->tolerance = orig->tolerance;
+    fi->toleranceDefined = orig->toleranceDefined;
+	printf("setting real values\n");
+	//copy r
+	int i=0;
+	for (i=0; i< NUMBER_OF_REALS;i++){
+        fi->r[i] = orig->r[i];
+	}
+	printf("setting string values\n");
+	//copy s
+	for (i=0; i< NUMBER_OF_STRINGS;i++){
+
+        fi->s[i] = orig->s[i];
+	}
+	//copy i
+    for (i=0; i< NUMBER_OF_INTEGERS;i++){
+        fi->i[i] = orig->i[i];
+	}
+	//copy b
+	for (i=0; i< NUMBER_OF_BOOLEANS;i++){
+        fi->b[i] = orig->b[i];
+	}
+    return fmi2OK;
+
+
+}
+/****************************************************/
+
+fmi2Status fmi2FreeFMUstate(fmi2Component c, fmi2FMUstate* FMUstate) {
+    printf("Function fmiFreeFMUstate not supported\n");
+    return fmi2Error;
+}
+fmi2Status fmi2SerializedFMUstateSize(fmi2Component c, fmi2FMUstate FMUstate, size_t *size) {
+    printf("Function fmiSerializedFMUstateSize not supported\n");
+    return fmi2Error;
+}
+fmi2Status fmi2SerializeFMUstate (fmi2Component c, fmi2FMUstate FMUstate, fmi2Byte serializedState[], size_t size) {
+    printf("Function fmiSerializeFMUstate not supported\n");
+    return fmi2Error;
+}
+fmi2Status fmi2DeSerializeFMUstate (fmi2Component c, const fmi2Byte serializedState[], size_t size, fmi2FMUstate* FMUstate) {
+    printf("Function fmiDeSerializeFMUstate not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetDirectionalDerivative(fmi2Component c, const fmi2ValueReference vUnknown_ref[], size_t nUnknown,
+                const fmi2ValueReference vKnown_ref[] , size_t nKnown, const fmi2Real dvKnown[], fmi2Real dvUnknown[]) {
+    printf("Function fmiGetDirectionalDerivative not supported\n");
+    return fmi2Error;
+}
+
+
+fmi2Status fmi2SetRealInputDerivatives(fmi2Component c, const fmi2ValueReference vr[], size_t nvr,
+                                     const fmi2Integer order[], const fmi2Real value[]) {
+    printf("Function fmiGetDirectionalDerivative not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetRealOutputDerivatives(fmi2Component c, const fmi2ValueReference vr[], size_t nvr,
+                                      const fmi2Integer order[], fmi2Real value[]) {
+    printf("Function fmiGetDirectionalDerivative not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2CancelStep(fmi2Component c) {
+    printf("Function fmiGetDirectionalDerivative not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetStatus(fmi2Component c, const fmi2StatusKind s, fmi2Status *value) {
+    printf("Function fmiGetStatus not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetRealStatus(fmi2Component c, const fmi2StatusKind s, fmi2Real *value) {
+    if(s == fmi2LastSuccessfulTime){
+        FMUInstance* comp = (FMUInstance*) c;
+        *value = comp->currentTime;
+        return fmi2OK;
+    }
+    printf("Function fmiGetRealStatus not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetIntegerStatus(fmi2Component c, const fmi2StatusKind s, fmi2Integer *value) {
+    printf("Function fmiGetIntegerStatus not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetBooleanStatus(fmi2Component c, const fmi2StatusKind s, fmi2Boolean *value) {
+    printf("Function fmiGetBooleanStatus not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetStringStatus(fmi2Component c, const fmi2StatusKind s, fmi2String *value) {
+    printf("Function fmiGetStringStatus not supported\n");
+    return fmi2Error;
+}

+ 52 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_generic_master/FMI_GM.h

@@ -0,0 +1,52 @@
+/*
+ * PW_Controller.h
+ *
+ *  Created on: Jan 25, 2017
+ *      Author: Joachim
+ */
+
+#ifndef FMI_GM_H_
+#define FMI_GM_H_
+
+#include "fmi2.h"
+
+typedef enum {
+    fmuInstantiated = 0,
+    fmuInitMode  = 1,
+	fmuInitialized = 2,
+    fmuTerminated   = 3,
+    fmuError        = 4,
+    fmuExperimentSettedUp = 5
+} FMUState;
+
+
+
+typedef struct {
+	fmi2Real    *r;
+    fmi2Integer *i;
+    fmi2Boolean *b;
+    fmi2String  *s;
+    fmi2Boolean isVisible;
+    fmi2String instanceName;
+    fmi2String GUID;
+    const fmi2CallbackFunctions* functions;
+    fmi2Boolean loggingOn;
+    FMUState state;
+	fmi2Real stepSize;
+    fmi2Real startTime;
+    fmi2Real stopTime;
+	fmi2Real currentTime;
+    fmi2Boolean stopTimeDefined;
+    fmi2Real tolerance;
+    fmi2Boolean toleranceDefined;
+    FMU fmu_order[3];
+    char *fmuResourceLocation_order[3];
+    fmi2Component c_order[3];
+    fmi2Real accumulator;
+    fmi2Real nextTimerEvent;
+} FMUInstance; // At the moment, most of the variables not really used since multiple instances of an FMU are not supported at the moment (performance issues)
+
+
+
+
+#endif /* FMI_GM_H_ */

+ 72 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_generic_master/fmi2/fmi2.h

@@ -0,0 +1,72 @@
+/* -------------------------------------------------------------------------
+ * fmi.h
+ * Struct with the corresponding function pointers for FMI 2.0.
+ * Copyright QTronic GmbH. All rights reserved.
+ * -------------------------------------------------------------------------*/
+
+#ifndef FMI_H
+#define FMI_H
+
+#include "fmi2Functions.h"
+
+typedef struct {
+//    ModelDescription* modelDescription;
+
+    void  *dllHandle; // fmu.so handle
+    /***************************************************
+    Common Functions
+    ****************************************************/
+    fmi2GetTypesPlatformTYPE         *getTypesPlatform;
+    fmi2GetVersionTYPE               *getVersion;
+    fmi2SetDebugLoggingTYPE          *setDebugLogging;
+    fmi2InstantiateTYPE              *instantiate;
+    fmi2FreeInstanceTYPE             *freeInstance;
+    fmi2SetupExperimentTYPE          *setupExperiment;
+    fmi2EnterInitializationModeTYPE  *enterInitializationMode;
+    fmi2ExitInitializationModeTYPE   *exitInitializationMode;
+    fmi2TerminateTYPE                *terminate;
+    fmi2ResetTYPE                    *reset;
+    fmi2GetRealTYPE                  *getReal;
+    fmi2GetIntegerTYPE               *getInteger;
+    fmi2GetBooleanTYPE               *getBoolean;
+    fmi2GetStringTYPE                *getString;
+    fmi2SetRealTYPE                  *setReal;
+    fmi2SetIntegerTYPE               *setInteger;
+    fmi2SetBooleanTYPE               *setBoolean;
+    fmi2SetStringTYPE                *setString;
+    fmi2GetFMUstateTYPE              *getFMUstate;
+    fmi2SetFMUstateTYPE              *setFMUstate;
+    fmi2FreeFMUstateTYPE             *freeFMUstate;
+    fmi2SerializedFMUstateSizeTYPE   *serializedFMUstateSize;
+    fmi2SerializeFMUstateTYPE        *serializeFMUstate;
+    fmi2DeSerializeFMUstateTYPE      *deSerializeFMUstate;
+    fmi2GetDirectionalDerivativeTYPE *getDirectionalDerivative;
+    /***************************************************
+    Functions for FMI2 for Co-Simulation
+    ****************************************************/
+    fmi2SetRealInputDerivativesTYPE  *setRealInputDerivatives;
+    fmi2GetRealOutputDerivativesTYPE *getRealOutputDerivatives;
+    fmi2DoStepTYPE                   *doStep;
+    fmi2CancelStepTYPE               *cancelStep;
+    fmi2GetStatusTYPE                *getStatus;
+    fmi2GetRealStatusTYPE            *getRealStatus;
+    fmi2GetIntegerStatusTYPE         *getIntegerStatus;
+    fmi2GetBooleanStatusTYPE         *getBooleanStatus;
+    fmi2GetStringStatusTYPE          *getStringStatus;
+    /***************************************************
+    Functions for FMI2 for Model Exchange
+    ****************************************************/
+    fmi2EnterEventModeTYPE                *enterEventMode;
+    fmi2NewDiscreteStatesTYPE             *newDiscreteStates;
+    fmi2EnterContinuousTimeModeTYPE       *enterContinuousTimeMode;
+    fmi2CompletedIntegratorStepTYPE       *completedIntegratorStep;
+    fmi2SetTimeTYPE                       *setTime;
+    fmi2SetContinuousStatesTYPE           *setContinuousStates;
+    fmi2GetDerivativesTYPE                *getDerivatives;
+    fmi2GetEventIndicatorsTYPE            *getEventIndicators;
+    fmi2GetContinuousStatesTYPE           *getContinuousStates;
+    fmi2GetNominalsOfContinuousStatesTYPE *getNominalsOfContinuousStates;
+} FMU;
+
+#endif // FMI_H
+

+ 247 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_generic_master/fmi2/fmi2FunctionTypes.h

@@ -0,0 +1,247 @@
+#ifndef fmi2FunctionTypes_h
+#define fmi2FunctionTypes_h
+
+#include "fmi2TypesPlatform.h"
+
+/* This header file must be utilized when compiling an FMU or an FMI master.
+   It declares data and function types for FMI 2.0
+
+   Revisions:
+   - Apr.  9, 2014: all prefixes "fmi" renamed to "fmi2" (decision from April 8)
+   - Apr.  3, 2014: Added #include <stddef.h> for size_t definition
+   - Mar. 27, 2014: Added #include "fmiTypesPlatform.h" (#179)
+   - Mar. 26, 2014: Introduced function argument "void" for the functions (#171)
+                      fmiGetTypesPlatformTYPE and fmiGetVersionTYPE
+   - Oct. 11, 2013: Functions of ModelExchange and CoSimulation merged:
+                      fmiInstantiateModelTYPE , fmiInstantiateSlaveTYPE  -> fmiInstantiateTYPE
+                      fmiFreeModelInstanceTYPE, fmiFreeSlaveInstanceTYPE -> fmiFreeInstanceTYPE
+                      fmiEnterModelInitializationModeTYPE, fmiEnterSlaveInitializationModeTYPE -> fmiEnterInitializationModeTYPE
+                      fmiExitModelInitializationModeTYPE , fmiExitSlaveInitializationModeTYPE  -> fmiExitInitializationModeTYPE
+                      fmiTerminateModelTYPE , fmiTerminateSlaveTYPE  -> fmiTerminate
+                      fmiResetSlave -> fmiReset (now also for ModelExchange and not only for CoSimulation)
+                    Functions renamed
+                      fmiUpdateDiscreteStatesTYPE -> fmiNewDiscreteStatesTYPE
+                    Renamed elements of the enumeration fmiEventInfo
+                      upcomingTimeEvent             -> nextEventTimeDefined // due to generic naming scheme: varDefined + var
+                      newUpdateDiscreteStatesNeeded -> newDiscreteStatesNeeded;
+   - June 13, 2013: Changed type fmiEventInfo
+                    Functions removed:
+                       fmiInitializeModelTYPE
+                       fmiEventUpdateTYPE
+                       fmiCompletedEventIterationTYPE
+                       fmiInitializeSlaveTYPE
+                    Functions added:
+                       fmiEnterModelInitializationModeTYPE
+                       fmiExitModelInitializationModeTYPE
+                       fmiEnterEventModeTYPE
+                       fmiUpdateDiscreteStatesTYPE
+                       fmiEnterContinuousTimeModeTYPE
+                       fmiEnterSlaveInitializationModeTYPE;
+                       fmiExitSlaveInitializationModeTYPE;
+   - Feb. 17, 2013: Added third argument to fmiCompletedIntegratorStepTYPE
+                    Changed function name "fmiTerminateType" to "fmiTerminateModelType" (due to #113)
+                    Changed function name "fmiGetNominalContinuousStateTYPE" to
+                                          "fmiGetNominalsOfContinuousStatesTYPE"
+                    Removed fmiGetStateValueReferencesTYPE.
+   - Nov. 14, 2011: First public Version
+
+
+   Copyright (C) 2011 MODELISAR consortium,
+               2012-2013 Modelica Association Project "FMI"
+               All rights reserved.
+   This file is licensed by the copyright holders under the BSD 2-Clause License
+   (http://www.opensource.org/licenses/bsd-license.html):
+
+   ----------------------------------------------------------------------------
+   Redistribution and use in source and binary forms, with or without
+   modification, are permitted provided that the following conditions are met:
+
+   - Redistributions of source code must retain the above copyright notice,
+     this list of conditions and the following disclaimer.
+   - Redistributions in binary form must reproduce the above copyright notice,
+     this list of conditions and the following disclaimer in the documentation
+     and/or other materials provided with the distribution.
+   - Neither the name of the copyright holders nor the names of its
+     contributors may be used to endorse or promote products derived
+     from this software without specific prior written permission.
+
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+   TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+   PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
+   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+   OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+   OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+   ----------------------------------------------------------------------------
+
+   with the extension:
+
+   You may distribute or publicly perform any modification only under the
+   terms of this license.
+   (Note, this means that if you distribute a modified file,
+    the modified file must also be provided under this license).
+*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* make sure all compiler use the same alignment policies for structures */
+#if defined _MSC_VER || defined __GNUC__
+#pragma pack(push,8)
+#endif
+
+/* Include stddef.h, in order that size_t etc. is defined */
+#include <stddef.h>
+
+
+/* Type definitions */
+typedef enum {
+    fmi2OK,
+    fmi2Warning,
+    fmi2Discard,
+    fmi2Error,
+    fmi2Fatal,
+    fmi2Pending
+} fmi2Status;
+
+typedef enum {
+    fmi2ModelExchange,
+    fmi2CoSimulation
+} fmi2Type;
+
+typedef enum {
+    fmi2DoStepStatus,
+    fmi2PendingStatus,
+    fmi2LastSuccessfulTime,
+    fmi2Terminated
+} fmi2StatusKind;
+
+typedef void      (*fmi2CallbackLogger)        (fmi2ComponentEnvironment, fmi2String, fmi2Status, fmi2String, fmi2String, ...);
+typedef void*     (*fmi2CallbackAllocateMemory)(size_t, size_t);
+typedef void      (*fmi2CallbackFreeMemory)    (void*);
+typedef void      (*fmi2StepFinished)          (fmi2ComponentEnvironment, fmi2Status);
+
+typedef struct {
+   const fmi2CallbackLogger         logger;
+   const fmi2CallbackAllocateMemory allocateMemory;
+   const fmi2CallbackFreeMemory     freeMemory;
+   const fmi2StepFinished           stepFinished;
+   const fmi2ComponentEnvironment   componentEnvironment;
+} fmi2CallbackFunctions;
+
+typedef struct {
+   fmi2Boolean newDiscreteStatesNeeded;
+   fmi2Boolean terminateSimulation;
+   fmi2Boolean nominalsOfContinuousStatesChanged;
+   fmi2Boolean valuesOfContinuousStatesChanged;
+   fmi2Boolean nextEventTimeDefined;
+   fmi2Real    nextEventTime;
+} fmi2EventInfo;
+
+
+/* reset alignment policy to the one set before reading this file */
+#if defined _MSC_VER || defined __GNUC__
+#pragma pack(pop)
+#endif
+
+
+/* Define fmi2 function pointer types to simplify dynamic loading */
+
+/***************************************************
+Types for Common Functions
+****************************************************/
+
+/* Inquire version numbers of header files and setting logging status */
+   typedef const char* fmi2GetTypesPlatformTYPE(void);
+   typedef const char* fmi2GetVersionTYPE(void);
+   typedef fmi2Status  fmi2SetDebugLoggingTYPE(fmi2Component, fmi2Boolean, size_t, const fmi2String[]);
+
+/* Creation and destruction of FMU instances and setting debug status */
+   typedef fmi2Component fmi2InstantiateTYPE (fmi2String, fmi2Type, fmi2String, fmi2String, const fmi2CallbackFunctions*, fmi2Boolean, fmi2Boolean);
+   typedef void          fmi2FreeInstanceTYPE(fmi2Component);
+
+/* Enter and exit initialization mode, terminate and reset */
+   typedef fmi2Status fmi2SetupExperimentTYPE        (fmi2Component, fmi2Boolean, fmi2Real, fmi2Real, fmi2Boolean, fmi2Real);
+   typedef fmi2Status fmi2EnterInitializationModeTYPE(fmi2Component);
+   typedef fmi2Status fmi2ExitInitializationModeTYPE (fmi2Component);
+   typedef fmi2Status fmi2TerminateTYPE              (fmi2Component);
+   typedef fmi2Status fmi2ResetTYPE                  (fmi2Component);
+
+/* Getting and setting variable values */
+   typedef fmi2Status fmi2GetRealTYPE   (fmi2Component, const fmi2ValueReference[], size_t, fmi2Real   []);
+   typedef fmi2Status fmi2GetIntegerTYPE(fmi2Component, const fmi2ValueReference[], size_t, fmi2Integer[]);
+   typedef fmi2Status fmi2GetBooleanTYPE(fmi2Component, const fmi2ValueReference[], size_t, fmi2Boolean[]);
+   typedef fmi2Status fmi2GetStringTYPE (fmi2Component, const fmi2ValueReference[], size_t, fmi2String []);
+
+   typedef fmi2Status fmi2SetRealTYPE   (fmi2Component, const fmi2ValueReference[], size_t, const fmi2Real   []);
+   typedef fmi2Status fmi2SetIntegerTYPE(fmi2Component, const fmi2ValueReference[], size_t, const fmi2Integer[]);
+   typedef fmi2Status fmi2SetBooleanTYPE(fmi2Component, const fmi2ValueReference[], size_t, const fmi2Boolean[]);
+   typedef fmi2Status fmi2SetStringTYPE (fmi2Component, const fmi2ValueReference[], size_t, const fmi2String []);
+
+/* Getting and setting the internal FMU state */
+   typedef fmi2Status fmi2GetFMUstateTYPE           (fmi2Component, fmi2FMUstate*);
+   typedef fmi2Status fmi2SetFMUstateTYPE           (fmi2Component, fmi2FMUstate);
+   typedef fmi2Status fmi2FreeFMUstateTYPE          (fmi2Component, fmi2FMUstate*);
+   typedef fmi2Status fmi2SerializedFMUstateSizeTYPE(fmi2Component, fmi2FMUstate, size_t*);
+   typedef fmi2Status fmi2SerializeFMUstateTYPE     (fmi2Component, fmi2FMUstate, fmi2Byte[], size_t);
+   typedef fmi2Status fmi2DeSerializeFMUstateTYPE   (fmi2Component, const fmi2Byte[], size_t, fmi2FMUstate*);
+
+/* Getting partial derivatives */
+   typedef fmi2Status fmi2GetDirectionalDerivativeTYPE(fmi2Component, const fmi2ValueReference[], size_t,
+                                                                   const fmi2ValueReference[], size_t,
+                                                                   const fmi2Real[], fmi2Real[]);
+
+/***************************************************
+Types for Functions for FMI2 for Model Exchange
+****************************************************/
+
+/* Enter and exit the different modes */
+   typedef fmi2Status fmi2EnterEventModeTYPE         (fmi2Component);
+   typedef fmi2Status fmi2NewDiscreteStatesTYPE      (fmi2Component, fmi2EventInfo*);
+   typedef fmi2Status fmi2EnterContinuousTimeModeTYPE(fmi2Component);
+   typedef fmi2Status fmi2CompletedIntegratorStepTYPE(fmi2Component, fmi2Boolean, fmi2Boolean*, fmi2Boolean*);
+
+/* Providing independent variables and re-initialization of caching */
+   typedef fmi2Status fmi2SetTimeTYPE            (fmi2Component, fmi2Real);
+   typedef fmi2Status fmi2SetContinuousStatesTYPE(fmi2Component, const fmi2Real[], size_t);
+
+/* Evaluation of the model equations */
+   typedef fmi2Status fmi2GetDerivativesTYPE               (fmi2Component, fmi2Real[], size_t);
+#ifdef FMU_EXPERIMENTAL
+   typedef fmi2Status fmi2GetSpecificDerivativesTYPE       (fmi2Component, fmi2Real[], const fmi2ValueReference [], size_t);
+#endif
+
+   typedef fmi2Status fmi2GetEventIndicatorsTYPE           (fmi2Component, fmi2Real[], size_t);
+   typedef fmi2Status fmi2GetContinuousStatesTYPE          (fmi2Component, fmi2Real[], size_t);
+   typedef fmi2Status fmi2GetNominalsOfContinuousStatesTYPE(fmi2Component, fmi2Real[], size_t);
+
+
+/***************************************************
+Types for Functions for FMI2 for Co-Simulation
+****************************************************/
+
+/* Simulating the slave */
+   typedef fmi2Status fmi2SetRealInputDerivativesTYPE (fmi2Component, const fmi2ValueReference [], size_t, const fmi2Integer [], const fmi2Real []);
+   typedef fmi2Status fmi2GetRealOutputDerivativesTYPE(fmi2Component, const fmi2ValueReference [], size_t, const fmi2Integer [], fmi2Real []);
+
+   typedef fmi2Status fmi2DoStepTYPE     (fmi2Component, fmi2Real, fmi2Real, fmi2Boolean);
+   typedef fmi2Status fmi2CancelStepTYPE (fmi2Component);
+
+/* Inquire slave status */
+   typedef fmi2Status fmi2GetStatusTYPE       (fmi2Component, const fmi2StatusKind, fmi2Status* );
+   typedef fmi2Status fmi2GetRealStatusTYPE   (fmi2Component, const fmi2StatusKind, fmi2Real*   );
+   typedef fmi2Status fmi2GetIntegerStatusTYPE(fmi2Component, const fmi2StatusKind, fmi2Integer*);
+   typedef fmi2Status fmi2GetBooleanStatusTYPE(fmi2Component, const fmi2StatusKind, fmi2Boolean*);
+   typedef fmi2Status fmi2GetStringStatusTYPE (fmi2Component, const fmi2StatusKind, fmi2String* );
+
+
+#ifdef __cplusplus
+}  /* end of extern "C" { */
+#endif
+
+#endif /* fmi2FunctionTypes_h */

+ 339 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_generic_master/fmi2/fmi2Functions.h

@@ -0,0 +1,339 @@
+#ifndef fmi2Functions_h
+#define fmi2Functions_h
+
+/* This header file must be utilized when compiling a FMU.
+   It defines all functions of the
+         FMI 2.0 Model Exchange and Co-Simulation Interface.
+
+   In order to have unique function names even if several FMUs
+   are compiled together (e.g. for embedded systems), every "real" function name
+   is constructed by prepending the function name by "FMI2_FUNCTION_PREFIX".
+   Therefore, the typical usage is:
+
+      #define FMI2_FUNCTION_PREFIX MyModel_
+      #include "fmi2Functions.h"
+
+   As a result, a function that is defined as "fmi2GetDerivatives" in this header file,
+   is actually getting the name "MyModel_fmi2GetDerivatives".
+
+   This only holds if the FMU is shipped in C source code, or is compiled in a
+   static link library. For FMUs compiled in a DLL/sharedObject, the "actual" function
+   names are used and "FMI2_FUNCTION_PREFIX" must not be defined.
+
+   Revisions:
+   - Apr.  9, 2014: all prefixes "fmi" renamed to "fmi2" (decision from April 8)
+   - Mar. 26, 2014: FMI_Export set to empty value if FMI_Export and FMI_FUNCTION_PREFIX
+                    are not defined (#173)
+   - Oct. 11, 2013: Functions of ModelExchange and CoSimulation merged:
+                      fmiInstantiateModel , fmiInstantiateSlave  -> fmiInstantiate
+                      fmiFreeModelInstance, fmiFreeSlaveInstance -> fmiFreeInstance
+                      fmiEnterModelInitializationMode, fmiEnterSlaveInitializationMode -> fmiEnterInitializationMode
+                      fmiExitModelInitializationMode , fmiExitSlaveInitializationMode  -> fmiExitInitializationMode
+                      fmiTerminateModel, fmiTerminateSlave  -> fmiTerminate
+                      fmiResetSlave -> fmiReset (now also for ModelExchange and not only for CoSimulation)
+                    Functions renamed:
+                      fmiUpdateDiscreteStates -> fmiNewDiscreteStates
+   - June 13, 2013: Functions removed:
+                       fmiInitializeModel
+                       fmiEventUpdate
+                       fmiCompletedEventIteration
+                       fmiInitializeSlave
+                    Functions added:
+                       fmiEnterModelInitializationMode
+                       fmiExitModelInitializationMode
+                       fmiEnterEventMode
+                       fmiUpdateDiscreteStates
+                       fmiEnterContinuousTimeMode
+                       fmiEnterSlaveInitializationMode;
+                       fmiExitSlaveInitializationMode;
+   - Feb. 17, 2013: Portability improvements:
+                       o DllExport changed to FMI_Export
+                       o FUNCTION_PREFIX changed to FMI_FUNCTION_PREFIX
+                       o Allow undefined FMI_FUNCTION_PREFIX (meaning no prefix is used)
+                    Changed function name "fmiTerminate" to "fmiTerminateModel" (due to #113)
+                    Changed function name "fmiGetNominalContinuousState" to
+                                          "fmiGetNominalsOfContinuousStates"
+                    Removed fmiGetStateValueReferences.
+   - Nov. 14, 2011: Adapted to FMI 2.0:
+                       o Split into two files (fmiFunctions.h, fmiTypes.h) in order
+                         that code that dynamically loads an FMU can directly
+                         utilize the header files).
+                       o Added C++ encapsulation of C-part, in order that the header
+                         file can be directly utilized in C++ code.
+                       o fmiCallbackFunctions is passed as pointer to fmiInstantiateXXX
+                       o stepFinished within fmiCallbackFunctions has as first
+                         argument "fmiComponentEnvironment" and not "fmiComponent".
+                       o New functions to get and set the complete FMU state
+                         and to compute partial derivatives.
+   - Nov.  4, 2010: Adapted to specification text:
+                       o fmiGetModelTypesPlatform renamed to fmiGetTypesPlatform
+                       o fmiInstantiateSlave: Argument GUID     replaced by fmuGUID
+                                              Argument mimetype replaced by mimeType
+                       o tabs replaced by spaces
+   - Oct. 16, 2010: Functions for FMI for Co-simulation added
+   - Jan. 20, 2010: stateValueReferencesChanged added to struct fmiEventInfo (ticket #27)
+                    (by M. Otter, DLR)
+                    Added WIN32 pragma to define the struct layout (ticket #34)
+                    (by J. Mauss, QTronic)
+   - Jan.  4, 2010: Removed argument intermediateResults from fmiInitialize
+                    Renamed macro fmiGetModelFunctionsVersion to fmiGetVersion
+                    Renamed macro fmiModelFunctionsVersion to fmiVersion
+                    Replaced fmiModel by fmiComponent in decl of fmiInstantiateModel
+                    (by J. Mauss, QTronic)
+   - Dec. 17, 2009: Changed extension "me" to "fmi" (by Martin Otter, DLR).
+   - Dez. 14, 2009: Added eventInfo to meInitialize and added
+                    meGetNominalContinuousStates (by Martin Otter, DLR)
+   - Sept. 9, 2009: Added DllExport (according to Peter Nilsson's suggestion)
+                    (by A. Junghanns, QTronic)
+   - Sept. 9, 2009: Changes according to FMI-meeting on July 21:
+                    meInquireModelTypesVersion     -> meGetModelTypesPlatform
+                    meInquireModelFunctionsVersion -> meGetModelFunctionsVersion
+                    meSetStates                    -> meSetContinuousStates
+                    meGetStates                    -> meGetContinuousStates
+                    removal of meInitializeModelClass
+                    removal of meGetTime
+                    change of arguments of meInstantiateModel
+                    change of arguments of meCompletedIntegratorStep
+                    (by Martin Otter, DLR):
+   - July 19, 2009: Added "me" as prefix to file names (by Martin Otter, DLR).
+   - March 2, 2009: Changed function definitions according to the last design
+                    meeting with additional improvements (by Martin Otter, DLR).
+   - Dec. 3 , 2008: First version by Martin Otter (DLR) and Hans Olsson (Dynasim).
+
+   Copyright (C) 2008-2011 MODELISAR consortium,
+               2012-2013 Modelica Association Project "FMI"
+               All rights reserved.
+   This file is licensed by the copyright holders under the BSD 2-Clause License
+   (http://www.opensource.org/licenses/bsd-license.html):
+
+   ----------------------------------------------------------------------------
+   Redistribution and use in source and binary forms, with or without
+   modification, are permitted provided that the following conditions are met:
+
+   - Redistributions of source code must retain the above copyright notice,
+     this list of conditions and the following disclaimer.
+   - Redistributions in binary form must reproduce the above copyright notice,
+     this list of conditions and the following disclaimer in the documentation
+     and/or other materials provided with the distribution.
+   - Neither the name of the copyright holders nor the names of its
+     contributors may be used to endorse or promote products derived
+     from this software without specific prior written permission.
+
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+   TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+   PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
+   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+   OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+   OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+   ----------------------------------------------------------------------------
+
+   with the extension:
+
+   You may distribute or publicly perform any modification only under the
+   terms of this license.
+   (Note, this means that if you distribute a modified file,
+    the modified file must also be provided under this license).
+*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "fmi2TypesPlatform.h"
+#include "fmi2FunctionTypes.h"
+#include <stdlib.h>
+
+
+/*
+  Export FMI2 API functions on Windows and under GCC.
+  If custom linking is desired then the FMI2_Export must be
+  defined before including this file. For instance,
+  it may be set to __declspec(dllimport).
+*/
+#if !defined(FMI2_Export)
+  #if !defined(FMI2_FUNCTION_PREFIX)
+    #if defined _WIN32 || defined __CYGWIN__
+     /* Note: both gcc & MSVC on Windows support this syntax. */
+        #define FMI2_Export __declspec(dllexport)
+    #else
+      #if __GNUC__ >= 4
+        #define FMI2_Export __attribute__ ((visibility ("default")))
+      #else
+        #define FMI2_Export
+      #endif
+    #endif
+  #else
+    #define FMI2_Export
+  #endif
+#endif
+
+/* Macros to construct the real function name
+   (prepend function name by FMI2_FUNCTION_PREFIX) */
+#if defined(FMI2_FUNCTION_PREFIX)
+  #define fmi2Paste(a,b)     a ## b
+  #define fmi2PasteB(a,b)    fmi2Paste(a,b)
+  #define fmi2FullName(name) fmi2PasteB(FMI2_FUNCTION_PREFIX, name)
+#else
+  #define fmi2FullName(name) name
+#endif
+
+/***************************************************
+Common Functions
+****************************************************/
+#define fmi2GetTypesPlatform         fmi2FullName(fmi2GetTypesPlatform)
+#define fmi2GetVersion               fmi2FullName(fmi2GetVersion)
+#define fmi2SetDebugLogging          fmi2FullName(fmi2SetDebugLogging)
+#define fmi2Instantiate              fmi2FullName(fmi2Instantiate)
+#define fmi2FreeInstance             fmi2FullName(fmi2FreeInstance)
+#define fmi2SetupExperiment          fmi2FullName(fmi2SetupExperiment)
+#define fmi2EnterInitializationMode  fmi2FullName(fmi2EnterInitializationMode)
+#define fmi2ExitInitializationMode   fmi2FullName(fmi2ExitInitializationMode)
+#define fmi2Terminate                fmi2FullName(fmi2Terminate)
+#define fmi2Reset                    fmi2FullName(fmi2Reset)
+#define fmi2GetReal                  fmi2FullName(fmi2GetReal)
+#define fmi2GetInteger               fmi2FullName(fmi2GetInteger)
+#define fmi2GetBoolean               fmi2FullName(fmi2GetBoolean)
+#define fmi2GetString                fmi2FullName(fmi2GetString)
+#define fmi2SetReal                  fmi2FullName(fmi2SetReal)
+#define fmi2SetInteger               fmi2FullName(fmi2SetInteger)
+#define fmi2SetBoolean               fmi2FullName(fmi2SetBoolean)
+#define fmi2SetString                fmi2FullName(fmi2SetString)
+#define fmi2GetFMUstate              fmi2FullName(fmi2GetFMUstate)
+#define fmi2SetFMUstate              fmi2FullName(fmi2SetFMUstate)
+#define fmi2FreeFMUstate             fmi2FullName(fmi2FreeFMUstate)
+#define fmi2SerializedFMUstateSize   fmi2FullName(fmi2SerializedFMUstateSize)
+#define fmi2SerializeFMUstate        fmi2FullName(fmi2SerializeFMUstate)
+#define fmi2DeSerializeFMUstate      fmi2FullName(fmi2DeSerializeFMUstate)
+#define fmi2GetDirectionalDerivative fmi2FullName(fmi2GetDirectionalDerivative)
+
+
+/***************************************************
+Functions for FMI2 for Model Exchange
+****************************************************/
+#define fmi2EnterEventMode                fmi2FullName(fmi2EnterEventMode)
+#define fmi2NewDiscreteStates             fmi2FullName(fmi2NewDiscreteStates)
+#define fmi2EnterContinuousTimeMode       fmi2FullName(fmi2EnterContinuousTimeMode)
+#define fmi2CompletedIntegratorStep       fmi2FullName(fmi2CompletedIntegratorStep)
+#define fmi2SetTime                       fmi2FullName(fmi2SetTime)
+#define fmi2SetContinuousStates           fmi2FullName(fmi2SetContinuousStates)
+#define fmi2GetDerivatives                fmi2FullName(fmi2GetDerivatives)
+#ifdef FMU_EXPERIMENTAL
+#define fmi2GetSpecificDerivatives        fmi2FullName(fmi2GetSpecificDerivatives)
+#endif
+#define fmi2GetEventIndicators            fmi2FullName(fmi2GetEventIndicators)
+#define fmi2GetContinuousStates           fmi2FullName(fmi2GetContinuousStates)
+#define fmi2GetNominalsOfContinuousStates fmi2FullName(fmi2GetNominalsOfContinuousStates)
+
+
+/***************************************************
+Functions for FMI2 for Co-Simulation
+****************************************************/
+#define fmi2SetRealInputDerivatives      fmi2FullName(fmi2SetRealInputDerivatives)
+#define fmi2GetRealOutputDerivatives     fmi2FullName(fmi2GetRealOutputDerivatives)
+#define fmi2DoStep                       fmi2FullName(fmi2DoStep)
+#define fmi2CancelStep                   fmi2FullName(fmi2CancelStep)
+#define fmi2GetStatus                    fmi2FullName(fmi2GetStatus)
+#define fmi2GetRealStatus                fmi2FullName(fmi2GetRealStatus)
+#define fmi2GetIntegerStatus             fmi2FullName(fmi2GetIntegerStatus)
+#define fmi2GetBooleanStatus             fmi2FullName(fmi2GetBooleanStatus)
+#define fmi2GetStringStatus              fmi2FullName(fmi2GetStringStatus)
+
+/* Version number */
+#define fmi2Version "2.0"
+
+
+/***************************************************
+Common Functions
+****************************************************/
+
+/* Inquire version numbers of header files */
+   FMI2_Export fmi2GetTypesPlatformTYPE fmi2GetTypesPlatform;
+   FMI2_Export fmi2GetVersionTYPE       fmi2GetVersion;
+   FMI2_Export fmi2SetDebugLoggingTYPE  fmi2SetDebugLogging;
+
+/* Creation and destruction of FMU instances */
+   FMI2_Export fmi2InstantiateTYPE  fmi2Instantiate;
+   FMI2_Export fmi2FreeInstanceTYPE fmi2FreeInstance;
+
+/* Enter and exit initialization mode, terminate and reset */
+   FMI2_Export fmi2SetupExperimentTYPE         fmi2SetupExperiment;
+   FMI2_Export fmi2EnterInitializationModeTYPE fmi2EnterInitializationMode;
+   FMI2_Export fmi2ExitInitializationModeTYPE  fmi2ExitInitializationMode;
+   FMI2_Export fmi2TerminateTYPE               fmi2Terminate;
+   FMI2_Export fmi2ResetTYPE                   fmi2Reset;
+
+/* Getting and setting variables values */
+   FMI2_Export fmi2GetRealTYPE    fmi2GetReal;
+   FMI2_Export fmi2GetIntegerTYPE fmi2GetInteger;
+   FMI2_Export fmi2GetBooleanTYPE fmi2GetBoolean;
+   FMI2_Export fmi2GetStringTYPE  fmi2GetString;
+
+   FMI2_Export fmi2SetRealTYPE    fmi2SetReal;
+   FMI2_Export fmi2SetIntegerTYPE fmi2SetInteger;
+   FMI2_Export fmi2SetBooleanTYPE fmi2SetBoolean;
+   FMI2_Export fmi2SetStringTYPE  fmi2SetString;
+
+/* Getting and setting the internal FMU state */
+   FMI2_Export fmi2GetFMUstateTYPE            fmi2GetFMUstate;
+   FMI2_Export fmi2SetFMUstateTYPE            fmi2SetFMUstate;
+   FMI2_Export fmi2FreeFMUstateTYPE           fmi2FreeFMUstate;
+   FMI2_Export fmi2SerializedFMUstateSizeTYPE fmi2SerializedFMUstateSize;
+   FMI2_Export fmi2SerializeFMUstateTYPE      fmi2SerializeFMUstate;
+   FMI2_Export fmi2DeSerializeFMUstateTYPE    fmi2DeSerializeFMUstate;
+
+/* Getting partial derivatives */
+   FMI2_Export fmi2GetDirectionalDerivativeTYPE fmi2GetDirectionalDerivative;
+
+
+/***************************************************
+Functions for FMI2 for Model Exchange
+****************************************************/
+
+/* Enter and exit the different modes */
+   FMI2_Export fmi2EnterEventModeTYPE               fmi2EnterEventMode;
+   FMI2_Export fmi2NewDiscreteStatesTYPE            fmi2NewDiscreteStates;
+   FMI2_Export fmi2EnterContinuousTimeModeTYPE      fmi2EnterContinuousTimeMode;
+   FMI2_Export fmi2CompletedIntegratorStepTYPE      fmi2CompletedIntegratorStep;
+
+/* Providing independent variables and re-initialization of caching */
+   FMI2_Export fmi2SetTimeTYPE             fmi2SetTime;
+   FMI2_Export fmi2SetContinuousStatesTYPE fmi2SetContinuousStates;
+
+/* Evaluation of the model equations */
+   FMI2_Export fmi2GetDerivativesTYPE                fmi2GetDerivatives;
+#ifdef FMU_EXPERIMENTAL
+   FMI2_Export fmi2GetSpecificDerivativesTYPE        fmi2GetSpecificDerivatives;
+#endif
+   FMI2_Export fmi2GetEventIndicatorsTYPE            fmi2GetEventIndicators;
+   FMI2_Export fmi2GetContinuousStatesTYPE           fmi2GetContinuousStates;
+   FMI2_Export fmi2GetNominalsOfContinuousStatesTYPE fmi2GetNominalsOfContinuousStates;
+
+
+/***************************************************
+Functions for FMI2 for Co-Simulation
+****************************************************/
+
+/* Simulating the slave */
+   FMI2_Export fmi2SetRealInputDerivativesTYPE  fmi2SetRealInputDerivatives;
+   FMI2_Export fmi2GetRealOutputDerivativesTYPE fmi2GetRealOutputDerivatives;
+
+   FMI2_Export fmi2DoStepTYPE     fmi2DoStep;
+   FMI2_Export fmi2CancelStepTYPE fmi2CancelStep;
+
+/* Inquire slave status */
+   FMI2_Export fmi2GetStatusTYPE        fmi2GetStatus;
+   FMI2_Export fmi2GetRealStatusTYPE    fmi2GetRealStatus;
+   FMI2_Export fmi2GetIntegerStatusTYPE fmi2GetIntegerStatus;
+   FMI2_Export fmi2GetBooleanStatusTYPE fmi2GetBooleanStatus;
+   FMI2_Export fmi2GetStringStatusTYPE  fmi2GetStringStatus;
+
+#ifdef __cplusplus
+}  /* end of extern "C" { */
+#endif
+
+#endif /* fmi2Functions_h */

+ 115 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_generic_master/fmi2/fmi2TypesPlatform.h

@@ -0,0 +1,115 @@
+#ifndef fmi2TypesPlatform_h
+#define fmi2TypesPlatform_h
+
+/* Standard header file to define the argument types of the
+   functions of the Functional Mock-up Interface 2.0.
+   This header file must be utilized both by the model and
+   by the simulation engine.
+
+   Revisions:
+   - Apr.  9, 2014: all prefixes "fmi" renamed to "fmi2" (decision from April 8)
+   - Mar   31, 2014: New datatype fmiChar introduced.
+   - Feb.  17, 2013: Changed fmiTypesPlatform from "standard32" to "default".
+                     Removed fmiUndefinedValueReference since no longer needed
+                     (because every state is defined in ScalarVariables).
+   - March 20, 2012: Renamed from fmiPlatformTypes.h to fmiTypesPlatform.h
+   - Nov.  14, 2011: Use the header file "fmiPlatformTypes.h" for FMI 2.0
+                     both for "FMI for model exchange" and for "FMI for co-simulation"
+                     New types "fmiComponentEnvironment", "fmiState", and "fmiByte".
+                     The implementation of "fmiBoolean" is change from "char" to "int".
+                     The #define "fmiPlatform" changed to "fmiTypesPlatform"
+                     (in order that #define and function call are consistent)
+   - Oct.   4, 2010: Renamed header file from "fmiModelTypes.h" to fmiPlatformTypes.h"
+                     for the co-simulation interface
+   - Jan.   4, 2010: Renamed meModelTypes_h to fmiModelTypes_h (by Mauss, QTronic)
+   - Dec.  21, 2009: Changed "me" to "fmi" and "meModel" to "fmiComponent"
+                     according to meeting on Dec. 18 (by Martin Otter, DLR)
+   - Dec.   6, 2009: Added meUndefinedValueReference (by Martin Otter, DLR)
+   - Sept.  9, 2009: Changes according to FMI-meeting on July 21:
+                     Changed "version" to "platform", "standard" to "standard32",
+                     Added a precise definition of "standard32" as comment
+                     (by Martin Otter, DLR)
+   - July  19, 2009: Added "me" as prefix to file names, added meTrue/meFalse,
+                     and changed meValueReferenced from int to unsigned int
+                     (by Martin Otter, DLR).
+   - March  2, 2009: Moved enums and function pointer definitions to
+                     ModelFunctions.h (by Martin Otter, DLR).
+   - Dec.  3, 2008 : First version by Martin Otter (DLR) and
+                     Hans Olsson (Dynasim).
+
+
+   Copyright (C) 2008-2011 MODELISAR consortium,
+               2012-2013 Modelica Association Project "FMI"
+               All rights reserved.
+   This file is licensed by the copyright holders under the BSD 2-Clause License
+   (http://www.opensource.org/licenses/bsd-license.html):
+
+   ----------------------------------------------------------------------------
+   Redistribution and use in source and binary forms, with or without
+   modification, are permitted provided that the following conditions are met:
+
+   - Redistributions of source code must retain the above copyright notice,
+     this list of conditions and the following disclaimer.
+   - Redistributions in binary form must reproduce the above copyright notice,
+     this list of conditions and the following disclaimer in the documentation
+     and/or other materials provided with the distribution.
+   - Neither the name of the copyright holders nor the names of its
+     contributors may be used to endorse or promote products derived
+     from this software without specific prior written permission.
+
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+   TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+   PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
+   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+   OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+   OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+   ----------------------------------------------------------------------------
+
+   with the extension:
+
+   You may distribute or publicly perform any modification only under the
+   terms of this license.
+   (Note, this means that if you distribute a modified file,
+    the modified file must also be provided under this license).
+*/
+
+/* Platform (unique identification of this header file) */
+#define fmi2TypesPlatform "default"
+
+/* Type definitions of variables passed as arguments
+   Version "default" means:
+
+   fmi2Component           : an opaque object pointer
+   fmi2ComponentEnvironment: an opaque object pointer
+   fmi2FMUstate            : an opaque object pointer
+   fmi2ValueReference      : handle to the value of a variable
+   fmi2Real                : double precision floating-point data type
+   fmi2Integer             : basic signed integer data type
+   fmi2Boolean             : basic signed integer data type
+   fmi2Char                : character data type
+   fmi2String              : a pointer to a vector of fmi2Char characters
+                             ('\0' terminated, UTF8 encoded)
+   fmi2Byte                : smallest addressable unit of the machine, typically one byte.
+*/
+   typedef void*           fmi2Component;               /* Pointer to FMU instance       */
+   typedef void*           fmi2ComponentEnvironment;    /* Pointer to FMU environment    */
+   typedef void*           fmi2FMUstate;                /* Pointer to internal FMU state */
+   typedef unsigned int    fmi2ValueReference;
+   typedef double          fmi2Real   ;
+   typedef int             fmi2Integer;
+   typedef int             fmi2Boolean;
+   typedef char            fmi2Char;
+   typedef const fmi2Char* fmi2String;
+   typedef char            fmi2Byte;
+
+/* Values for fmi2Boolean  */
+#define fmi2True  1
+#define fmi2False 0
+
+
+#endif /* fmi2TypesPlatform_h */

+ 594 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_generic_master/sim_support.c

@@ -0,0 +1,594 @@
+/* -------------------------------------------------------------------------
+ * sim_support.c
+ * Functions used by both FMU simulators fmu20sim_me and fmu20sim_cs
+ * to parse command-line arguments, to unzip and load an fmu,
+ * to write CSV file, and more.
+ *
+ * Revision history
+ *  07.03.2014 initial version released in FMU SDK 2.0.0
+ *  10.04.2014 use FMI 2.0 headers that prefix function and type names with 'fmi2'.
+ *             When 'fmi2' functions are not found in loaded DLL, look also for
+ *             FMI 2.0 RC1 function names.
+ *
+ * Author: Adrian Tirea
+ * Copyright QTronic GmbH. All rights reserved.
+ * -------------------------------------------------------------------------*/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+#include <stdarg.h>
+#include <dlfcn.h>
+#include "fmi2.h"
+#include "sim_support.h"
+
+#define FMI_COSIMULATION
+extern FMU fmu;
+
+
+//int unzip(const char *zipPath, const char *outPath) {
+//    int code;
+//    char cwd[BUFSIZE];
+//    char binPath[BUFSIZE];
+//    int n = strlen(UNZIP_CMD) + strlen(outPath) + 3 +  strlen(zipPath) + 9;
+//    char* cmd = (char*)calloc(sizeof(char), n);
+//
+//    // remember current directory
+//    if (!GetCurrentDirectory(BUFSIZE, cwd)) {
+//        printf ("error: Could not get current directory\n");
+//        return 0; // error
+//    }
+//
+//    // change to %FMUSDK_HOME%\bin to find 7z.dll and 7z.exe
+//    if (!GetEnvironmentVariable("FMUSDK_HOME", binPath, BUFSIZE)) {
+//        if (GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
+//            printf ("error: Environment variable FMUSDK_HOME not defined\n");
+//        }
+//        else {
+//            printf ("error: Could not get value of FMUSDK_HOME\n");
+//        }
+//        return 0; // error
+//    }
+//    strcat(binPath, "\\bin");
+//    if (!SetCurrentDirectory(binPath)) {
+//        printf ("error: could not change to directory '%s'\n", binPath);
+//        return 0; // error
+//    }
+//
+//    // run the unzip command
+//    // remove "> NUL" to see the unzip protocol
+//    sprintf(cmd, "%s\"%s\" \"%s\" > NUL", UNZIP_CMD, outPath, zipPath);
+//    // printf("cmd='%s'\n", cmd);
+//    code = system(cmd);
+//    free(cmd);
+//    if (code != SEVEN_ZIP_NO_ERROR) {
+//        printf("7z: ");
+//        switch (code) {
+//            case SEVEN_ZIP_WARNING:            printf("warning\n"); break;
+//            case SEVEN_ZIP_ERROR:              printf("error\n"); break;
+//            case SEVEN_ZIP_COMMAND_LINE_ERROR: printf("command line error\n"); break;
+//            case SEVEN_ZIP_OUT_OF_MEMORY:      printf("out of memory\n"); break;
+//            case SEVEN_ZIP_STOPPED_BY_USER:    printf("stopped by user\n"); break;
+//            default: printf("unknown problem\n");
+//        }
+//    }
+//
+//    // restore current directory
+//    SetCurrentDirectory(cwd);
+//    return (code == SEVEN_ZIP_NO_ERROR || code == SEVEN_ZIP_WARNING) ? 1 : 0;
+//}
+//
+//// fileName is an absolute path, e.g. C:\test\a.fmu
+//// or relative to the current dir, e.g. ..\test\a.fmu
+//// Does not check for existence of the file
+//static char* getFmuPath(const char* fileName){
+//    char pathName[MAX_PATH];
+//    int n = GetFullPathName(fileName, MAX_PATH, pathName, NULL);
+//    return n ? strdup(pathName) : NULL;
+//}
+//
+//static char* getTmpPath() {
+//    char tmpPath[BUFSIZE];
+//    if(! GetTempPath(BUFSIZE, tmpPath)) {
+//        printf ("error: Could not find temporary disk space\n");
+//        return NULL;
+//    }
+//    strcat(tmpPath, "fmu\\");
+//    return strdup(tmpPath);
+//}
+//
+//char *getTempResourcesLocation() {
+//    char *tempPath = getTmpPath();
+//    char *resourcesLocation = (char *)calloc(sizeof(char), 9 + strlen(RESOURCES_DIR) + strlen(tempPath));
+//    strcpy(resourcesLocation, "file:///");
+//    strcat(resourcesLocation, tempPath);
+//    strcat(resourcesLocation, RESOURCES_DIR);
+//    free(tempPath);
+//    return resourcesLocation;
+//}
+
+static void *getAdr(int *success, void *dllHandle, const char *functionName, const char* preamble) {
+
+    int length = strlen(preamble) + strlen(functionName) + 1;
+    char* new_name = malloc(length);  // allocate memory
+    strcpy(new_name, preamble);  // copy first string
+    strcat(new_name, functionName);
+    void* fp = dlsym(dllHandle, new_name);
+    if (!fp) {
+        printf("warning: Function %s not found in dll\n", new_name);
+        *success = 0;
+    }
+    free(new_name);
+    return fp;
+}
+
+// Load the given dll and set function pointers in fmu
+// Return 0 to indicate failure
+int loadDll(const char* dllPath, FMU *fmu, const char* preamble) {
+    int x = 1, s = 1;
+    //HMODULE h = LoadLibrary(dllPath);
+    void *h = dlopen(dllPath, RTLD_LAZY);
+    printf("%s", dlerror());
+    if (!h) {
+        printf("error: Could not load %s\n", dllPath);
+        return 0; // failure
+    }
+    fmu->dllHandle = h;
+    fmu->getTypesPlatform          = (fmi2GetTypesPlatformTYPE *)      getAdr(&s, h, "fmi2GetTypesPlatform", preamble);
+    fmu->getVersion                = (fmi2GetVersionTYPE *)            getAdr(&s, h, "fmi2GetVersion", preamble);
+    fmu->setDebugLogging           = (fmi2SetDebugLoggingTYPE *)       getAdr(&s, h, "fmi2SetDebugLogging",preamble);
+    fmu->instantiate               = (fmi2InstantiateTYPE *)           getAdr(&s, h, "fmi2Instantiate", preamble);
+    fmu->freeInstance              = (fmi2FreeInstanceTYPE *)          getAdr(&s, h, "fmi2FreeInstance", preamble);
+    fmu->setupExperiment           = (fmi2SetupExperimentTYPE *)       getAdr(&s, h, "fmi2SetupExperiment", preamble);
+    fmu->enterInitializationMode   = (fmi2EnterInitializationModeTYPE *) getAdr(&s, h, "fmi2EnterInitializationMode", preamble);
+    fmu->exitInitializationMode    = (fmi2ExitInitializationModeTYPE *) getAdr(&s, h, "fmi2ExitInitializationMode", preamble);
+    fmu->terminate                 = (fmi2TerminateTYPE *)             getAdr(&s, h, "fmi2Terminate", preamble);
+    fmu->reset                     = (fmi2ResetTYPE *)                 getAdr(&s, h, "fmi2Reset", preamble);
+    fmu->getReal                   = (fmi2GetRealTYPE *)               getAdr(&s, h, "fmi2GetReal", preamble);
+    fmu->getInteger                = (fmi2GetIntegerTYPE *)            getAdr(&s, h, "fmi2GetInteger", preamble);
+    fmu->getBoolean                = (fmi2GetBooleanTYPE *)            getAdr(&s, h, "fmi2GetBoolean", preamble);
+    fmu->getString                 = (fmi2GetStringTYPE *)             getAdr(&s, h, "fmi2GetString", preamble);
+    fmu->setReal                   = (fmi2SetRealTYPE *)               getAdr(&s, h, "fmi2SetReal", preamble);
+    fmu->setInteger                = (fmi2SetIntegerTYPE *)            getAdr(&s, h, "fmi2SetInteger", preamble);
+    fmu->setBoolean                = (fmi2SetBooleanTYPE *)            getAdr(&s, h, "fmi2SetBoolean", preamble);
+    fmu->setString                 = (fmi2SetStringTYPE *)             getAdr(&s, h, "fmi2SetString", preamble);
+    fmu->getFMUstate               = (fmi2GetFMUstateTYPE *)           getAdr(&s, h, "fmi2GetFMUstate", preamble);
+    fmu->setFMUstate               = (fmi2SetFMUstateTYPE *)           getAdr(&s, h, "fmi2SetFMUstate", preamble);
+    fmu->freeFMUstate              = (fmi2FreeFMUstateTYPE *)          getAdr(&s, h, "fmi2FreeFMUstate", preamble);
+    fmu->serializedFMUstateSize    = (fmi2SerializedFMUstateSizeTYPE *) getAdr(&s, h, "fmi2SerializedFMUstateSize", preamble);
+    fmu->serializeFMUstate         = (fmi2SerializeFMUstateTYPE *)     getAdr(&s, h, "fmi2SerializeFMUstate", preamble);
+    fmu->deSerializeFMUstate       = (fmi2DeSerializeFMUstateTYPE *)   getAdr(&s, h, "fmi2DeSerializeFMUstate", preamble);
+    fmu->getDirectionalDerivative  = (fmi2GetDirectionalDerivativeTYPE *) getAdr(&s, h, "fmi2GetDirectionalDerivative", preamble);
+#ifdef FMI_COSIMULATION
+    fmu->setRealInputDerivatives   = (fmi2SetRealInputDerivativesTYPE *) getAdr(&s, h, "fmi2SetRealInputDerivatives", preamble);
+    fmu->getRealOutputDerivatives  = (fmi2GetRealOutputDerivativesTYPE *) getAdr(&s, h, "fmi2GetRealOutputDerivatives", preamble);
+    fmu->doStep                    = (fmi2DoStepTYPE *)                getAdr(&s, h, "fmi2DoStep", preamble);
+    fmu->cancelStep                = (fmi2CancelStepTYPE *)            getAdr(&s, h, "fmi2CancelStep", preamble);
+    fmu->getStatus                 = (fmi2GetStatusTYPE *)             getAdr(&s, h, "fmi2GetStatus", preamble);
+    fmu->getRealStatus             = (fmi2GetRealStatusTYPE *)         getAdr(&s, h, "fmi2GetRealStatus", preamble);
+    fmu->getIntegerStatus          = (fmi2GetIntegerStatusTYPE *)      getAdr(&s, h, "fmi2GetIntegerStatus", preamble);
+    fmu->getBooleanStatus          = (fmi2GetBooleanStatusTYPE *)      getAdr(&s, h, "fmi2GetBooleanStatus", preamble);
+    fmu->getStringStatus           = (fmi2GetStringStatusTYPE *)       getAdr(&s, h, "fmi2GetStringStatus", preamble);
+#else // FMI2 for Model Exchange
+    fmu->enterEventMode            = (fmi2EnterEventModeTYPE *)        getAdr(&s, h, "fmi2EnterEventMode", preamble);
+    fmu->newDiscreteStates         = (fmi2NewDiscreteStatesTYPE *)     getAdr(&s, h, "fmi2NewDiscreteStates", preamble);
+    fmu->enterContinuousTimeMode   = (fmi2EnterContinuousTimeModeTYPE *) getAdr(&s, h, "fmi2EnterContinuousTimeMode", preamble);
+    fmu->completedIntegratorStep   = (fmi2CompletedIntegratorStepTYPE *) getAdr(&s, h, "fmi2CompletedIntegratorStep", preamble);
+    fmu->setTime                   = (fmi2SetTimeTYPE *)               getAdr(&s, h, "fmi2SetTime", preamble);
+    fmu->setContinuousStates       = (fmi2SetContinuousStatesTYPE *)   getAdr(&s, h, "fmi2SetContinuousStates", preamble);
+    fmu->getDerivatives            = (fmi2GetDerivativesTYPE *)        getAdr(&s, h, "fmi2GetDerivatives", preamble);
+    fmu->getEventIndicators        = (fmi2GetEventIndicatorsTYPE *)    getAdr(&s, h, "fmi2GetEventIndicators", preamble);
+    fmu->getContinuousStates       = (fmi2GetContinuousStatesTYPE *)   getAdr(&s, h, "fmi2GetContinuousStates", preamble);
+    fmu->getNominalsOfContinuousStates = (fmi2GetNominalsOfContinuousStatesTYPE *) getAdr(&s, h, "fmi2GetNominalsOfContinuousStates", preamble);
+#endif
+
+    if (fmu->getVersion == NULL && fmu->instantiate == NULL) {
+        printf("warning: Functions from FMI 2.0 could not be found in %s\n", dllPath);
+        printf("warning: Simulator will look for FMI 2.0 RC1 functions names...\n");
+        fmu->getTypesPlatform          = (fmi2GetTypesPlatformTYPE *)      getAdr(&s, h, "fmiGetTypesPlatform", preamble);
+        fmu->getVersion                = (fmi2GetVersionTYPE *)            getAdr(&s, h, "fmiGetVersion", preamble);
+        fmu->setDebugLogging           = (fmi2SetDebugLoggingTYPE *)       getAdr(&s, h, "fmiSetDebugLogging", preamble);
+        fmu->instantiate               = (fmi2InstantiateTYPE *)           getAdr(&s, h, "fmiInstantiate", preamble);
+        fmu->freeInstance              = (fmi2FreeInstanceTYPE *)          getAdr(&s, h, "fmiFreeInstance", preamble);
+        fmu->setupExperiment           = (fmi2SetupExperimentTYPE *)       getAdr(&s, h, "fmiSetupExperiment", preamble);
+        fmu->enterInitializationMode   = (fmi2EnterInitializationModeTYPE *) getAdr(&s, h, "fmiEnterInitializationMode", preamble);
+        fmu->exitInitializationMode    = (fmi2ExitInitializationModeTYPE *) getAdr(&s, h, "fmiExitInitializationMode", preamble);
+        fmu->terminate                 = (fmi2TerminateTYPE *)             getAdr(&s, h, "fmiTerminate", preamble);
+        fmu->reset                     = (fmi2ResetTYPE *)                 getAdr(&s, h, "fmiReset", preamble);
+        fmu->getReal                   = (fmi2GetRealTYPE *)               getAdr(&s, h, "fmiGetReal", preamble);
+        fmu->getInteger                = (fmi2GetIntegerTYPE *)            getAdr(&s, h, "fmiGetInteger", preamble);
+        fmu->getBoolean                = (fmi2GetBooleanTYPE *)            getAdr(&s, h, "fmiGetBoolean", preamble);
+        fmu->getString                 = (fmi2GetStringTYPE *)             getAdr(&s, h, "fmiGetString", preamble);
+        fmu->setReal                   = (fmi2SetRealTYPE *)               getAdr(&s, h, "fmiSetReal", preamble);
+        fmu->setInteger                = (fmi2SetIntegerTYPE *)            getAdr(&s, h, "fmiSetInteger", preamble);
+        fmu->setBoolean                = (fmi2SetBooleanTYPE *)            getAdr(&s, h, "fmiSetBoolean", preamble);
+        fmu->setString                 = (fmi2SetStringTYPE *)             getAdr(&s, h, "fmiSetString", preamble);
+        fmu->getFMUstate               = (fmi2GetFMUstateTYPE *)           getAdr(&s, h, "fmiGetFMUstate", preamble);
+        fmu->setFMUstate               = (fmi2SetFMUstateTYPE *)           getAdr(&s, h, "fmiSetFMUstate", preamble);
+        fmu->freeFMUstate              = (fmi2FreeFMUstateTYPE *)          getAdr(&s, h, "fmiFreeFMUstate", preamble);
+        fmu->serializedFMUstateSize    = (fmi2SerializedFMUstateSizeTYPE *) getAdr(&s, h, "fmiSerializedFMUstateSize", preamble);
+        fmu->serializeFMUstate         = (fmi2SerializeFMUstateTYPE *)     getAdr(&s, h, "fmiSerializeFMUstate", preamble);
+        fmu->deSerializeFMUstate       = (fmi2DeSerializeFMUstateTYPE *)   getAdr(&s, h, "fmiDeSerializeFMUstate", preamble);
+        fmu->getDirectionalDerivative  = (fmi2GetDirectionalDerivativeTYPE *) getAdr(&s, h, "fmiGetDirectionalDerivative", preamble);
+    #ifdef FMI_COSIMULATION
+        fmu->setRealInputDerivatives   = (fmi2SetRealInputDerivativesTYPE *) getAdr(&s, h, "fmiSetRealInputDerivatives", preamble);
+        fmu->getRealOutputDerivatives  = (fmi2GetRealOutputDerivativesTYPE *) getAdr(&s, h, "fmiGetRealOutputDerivatives", preamble);
+        fmu->doStep                    = (fmi2DoStepTYPE *)                getAdr(&s, h, "fmiDoStep", preamble);
+        fmu->cancelStep                = (fmi2CancelStepTYPE *)            getAdr(&s, h, "fmiCancelStep", preamble);
+        fmu->getStatus                 = (fmi2GetStatusTYPE *)             getAdr(&s, h, "fmiGetStatus", preamble);
+        fmu->getRealStatus             = (fmi2GetRealStatusTYPE *)         getAdr(&s, h, "fmiGetRealStatus", preamble);
+        fmu->getIntegerStatus          = (fmi2GetIntegerStatusTYPE *)      getAdr(&s, h, "fmiGetIntegerStatus", preamble);
+        fmu->getBooleanStatus          = (fmi2GetBooleanStatusTYPE *)      getAdr(&s, h, "fmiGetBooleanStatus", preamble);
+        fmu->getStringStatus           = (fmi2GetStringStatusTYPE *)       getAdr(&s, h, "fmiGetStringStatus", preamble);
+    #else // FMI2 for Model Exchange
+        fmu->enterEventMode            = (fmi2EnterEventModeTYPE *)        getAdr(&s, h, "fmiEnterEventMode", preamble);
+        fmu->newDiscreteStates         = (fmi2NewDiscreteStatesTYPE *)     getAdr(&s, h, "fmiNewDiscreteStates", preamble);
+        fmu->enterContinuousTimeMode   = (fmi2EnterContinuousTimeModeTYPE *) getAdr(&s, h, "fmiEnterContinuousTimeMode", preamble);
+        fmu->completedIntegratorStep   = (fmi2CompletedIntegratorStepTYPE *) getAdr(&s, h, "fmiCompletedIntegratorStep", preamble);
+        fmu->setTime                   = (fmi2SetTimeTYPE *)               getAdr(&s, h, "fmiSetTime", preamble);
+        fmu->setContinuousStates       = (fmi2SetContinuousStatesTYPE *)   getAdr(&s, h, "fmiSetContinuousStates", preamble);
+        fmu->getDerivatives            = (fmi2GetDerivativesTYPE *)        getAdr(&s, h, "fmiGetDerivatives", preamble);
+        fmu->getEventIndicators        = (fmi2GetEventIndicatorsTYPE *)    getAdr(&s, h, "fmiGetEventIndicators", preamble);
+        fmu->getContinuousStates       = (fmi2GetContinuousStatesTYPE *)   getAdr(&s, h, "fmiGetContinuousStates", preamble);
+        fmu->getNominalsOfContinuousStates = (fmi2GetNominalsOfContinuousStatesTYPE *) getAdr(&s, h, "fmiGetNominalsOfContinuousStates", preamble);
+    #endif
+    }
+    return s;
+}
+
+//static void printModelDescription(ModelDescription* md){
+//    Element* e = (Element*)md;
+//    int i;
+//    int n; // number of attributes
+//    const char **attributes = getAttributesAsArray(e, &n);
+//    Component *component;
+//
+//    if (!attributes) {
+//        printf("ModelDescription printing aborted.");
+//        return;
+//    }
+//    printf("%s\n", getElementTypeName(e));
+//    for (i = 0; i < n; i += 2) {
+//        printf("  %s=%s\n", attributes[i], attributes[i+1]);
+//    }
+//    free((void *)attributes);
+//
+//#ifdef FMI_COSIMULATION
+//    component = getCoSimulation(md);
+//    if (!component) {
+//        printf("error: No CoSimulation element found in model description. This FMU is not for Co-Simulation.\n");
+//        exit(EXIT_FAILURE);
+//    }
+//#else // FMI_MODEL_EXCHANGE
+//    component = getModelExchange(md);
+//    if (!component) {
+//        printf("error: No ModelExchange element found in model description. This FMU is not for Model Exchange.\n");
+//        exit(EXIT_FAILURE);
+//    }
+//#endif
+//    printf("%s\n", getElementTypeName((Element *)component));
+//    attributes = getAttributesAsArray((Element *)component, &n);
+//    if (!attributes) {
+//        printf("ModelDescription printing aborted.");
+//        return;
+//    }
+//    for (i = 0; i < n; i += 2) {
+//        printf("  %s=%s\n", attributes[i], attributes[i+1]);
+//    }
+//
+//    free((void *)attributes);
+//}
+//
+//void loadFMU(const char* fmuFileName) {
+//    char* fmuPath;
+//    char* tmpPath;
+//    char* xmlPath;
+//    char* dllPath;
+//    const char *modelId;
+//
+//    // get absolute path to FMU, NULL if not found
+//    fmuPath = getFmuPath(fmuFileName);
+//    if (!fmuPath) exit(EXIT_FAILURE);
+//
+//    // unzip the FMU to the tmpPath directory
+//    tmpPath = getTmpPath();
+//    if (!unzip(fmuPath, tmpPath)) exit(EXIT_FAILURE);
+//
+//    // parse tmpPath\modelDescription.xml
+//    xmlPath = calloc(sizeof(char), strlen(tmpPath) + strlen(XML_FILE) + 1);
+//    sprintf(xmlPath, "%s%s", tmpPath, XML_FILE);
+//    fmu.modelDescription = parse(xmlPath);
+//    free(xmlPath);
+//    if (!fmu.modelDescription) exit(EXIT_FAILURE);
+//    printModelDescription(fmu.modelDescription);
+//#ifdef FMI_COSIMULATION
+//    modelId = getAttributeValue((Element *)getCoSimulation(fmu.modelDescription), att_modelIdentifier);
+//#else // FMI_MODEL_EXCHANGE
+//    modelId = getAttributeValue((Element *)getModelExchange(fmu.modelDescription), att_modelIdentifier);
+//#endif
+//    // load the FMU dll
+//    dllPath = calloc(sizeof(char), strlen(tmpPath) + strlen(DLL_DIR)
+//        + strlen(modelId) +  strlen(".dll") + 1);
+//    sprintf(dllPath, "%s%s%s.dll", tmpPath, DLL_DIR, modelId);
+//    if (!loadDll(dllPath, &fmu)) {
+//        exit(EXIT_FAILURE);
+//    }
+//    free(dllPath);
+//    free(fmuPath);
+//    free(tmpPath);
+//}
+//
+//void deleteUnzippedFiles() {
+//    const char *fmuTempPath = getTmpPath();
+//    char *cmd = (char *)calloc(15 + strlen(fmuTempPath), sizeof(char));
+//    sprintf(cmd, "rmdir /S /Q %s", fmuTempPath);
+//    system(cmd);
+//    free(cmd);
+//}
+//
+//static void doubleToCommaString(char* buffer, double r){
+//    char* comma;
+//    sprintf(buffer, "%.16g", r);
+//    comma = strchr(buffer, '.');
+//    if (comma) *comma = ',';
+//}
+//
+//// output time and all variables in CSV format
+//// if separator is ',', columns are separated by ',' and '.' is used for floating-point numbers.
+//// otherwise, the given separator (e.g. ';' or '\t') is to separate columns, and ',' is used
+//// as decimal dot in floating-point numbers.
+//void outputRow(FMU *fmu, fmi2Component c, double time, FILE* file, char separator, fmi2Boolean header) {
+//    int k;
+//    fmi2Real r;
+//    fmi2Integer i;
+//    fmi2Boolean b;
+//    fmi2String s;
+//    fmi2ValueReference vr;
+//    int n = getScalarVariableSize(fmu->modelDescription);
+//    char buffer[32];
+//
+//    // print first column
+//    if (header) {
+//        fprintf(file, "time");
+//    } else {
+//        if (separator==',')
+//            fprintf(file, "%.16g", time);
+//        else {
+//            // separator is e.g. ';' or '\t'
+//            doubleToCommaString(buffer, time);
+//            fprintf(file, "%s", buffer);
+//        }
+//    }
+//
+//    // print all other columns
+//    for (k = 0; k < n; k++) {
+//        ScalarVariable *sv = getScalarVariable(fmu->modelDescription, k);
+//        if (header) {
+//            // output names only
+//            if (separator == ',') {
+//                // treat array element, e.g. print a[1, 2] as a[1.2]
+//                const char *s = getAttributeValue((Element *)sv, att_name);
+//                fprintf(file, "%c", separator);
+//                while (*s) {
+//                    if (*s != ' ') {
+//                        fprintf(file, "%c", *s == ',' ? '.' : *s);
+//                    }
+//                    s++;
+//                }
+//            } else {
+//                fprintf(file, "%c%s", separator, getAttributeValue((Element *)sv, att_name));
+//            }
+//        } else {
+//            // output values
+//            vr = getValueReference(sv);
+//            switch (getElementType(getTypeSpec(sv))) {
+//                case elm_Real:
+//                    fmu->getReal(c, &vr, 1, &r);
+//                    if (separator == ',') {
+//                        fprintf(file, ",%.16g", r);
+//                    } else {
+//                        // separator is e.g. ';' or '\t'
+//                        doubleToCommaString(buffer, r);
+//                        fprintf(file, "%c%s", separator, buffer);
+//                    }
+//                    break;
+//                case elm_Integer:
+//                case elm_Enumeration:
+//                    fmu->getInteger(c, &vr, 1, &i);
+//                    fprintf(file, "%c%d", separator, i);
+//                    break;
+//                case elm_Boolean:
+//                    fmu->getBoolean(c, &vr, 1, &b);
+//                    fprintf(file, "%c%d", separator, b);
+//                    break;
+//                case elm_String:
+//                    fmu->getString(c, &vr, 1, &s);
+//                    fprintf(file, "%c%s", separator, s);
+//                    break;
+//                default:
+//                    fprintf(file, "%cNoValueForType=%d", separator, getElementType(getTypeSpec(sv)));
+//            }
+//        }
+//    } // for
+//
+//    // terminate this row
+//    fprintf(file, "\n");
+//}
+//
+static const char* fmi2StatusToString(fmi2Status status){
+    switch (status){
+        case fmi2OK:      return "ok";
+        case fmi2Warning: return "warning";
+        case fmi2Discard: return "discard";
+        case fmi2Error:   return "error";
+        case fmi2Fatal:   return "fatal";
+    #ifdef FMI_COSIMULATION
+        case fmi2Pending: return "fmi2Pending";
+    #endif
+        default:         return "?";
+    }
+}
+
+// search a fmu for the given variable, matching the type specified.
+// return NULL if not found
+//static ScalarVariable* getSV(FMU* fmu, char type, fmi2ValueReference vr) {
+//    return NULL;
+//    int i;
+//    int n = getScalarVariableSize(fmu->modelDescription);
+//    Elm tp;
+//
+//    switch (type) {
+//        case 'r': tp = elm_Real;    break;
+//        case 'i': tp = elm_Integer; break;
+//        case 'b': tp = elm_Boolean; break;
+//        case 's': tp = elm_String;  break;
+//        default : tp = elm_BAD_DEFINED;
+//    }
+//    for (i = 0; i < n; i++) {
+//        ScalarVariable* sv = getScalarVariable(fmu->modelDescription ,i);
+//        if (vr == getValueReference(sv) && tp == getElementType(getTypeSpec(sv))) {
+//            return sv;
+//        }
+//    }
+//    return NULL;
+//}
+
+// replace e.g. #r1365# by variable name and ## by # in message
+// copies the result to buffer
+static void replaceRefsInMessage(const char* msg, char* buffer, int nBuffer, FMU* fmu){
+    int i = 0; // position in msg
+    int k = 0; // position in buffer
+    int n;
+    char c = msg[i];
+    while (c != '\0' && k < nBuffer) {
+        if (c != '#') {
+            buffer[k++] = c;
+            i++;
+            c = msg[i];
+        } else {
+
+            char* end = strchr(msg + i + 1, '#');
+            if (!end) {
+                printf("unmatched '#' in '%s'\n", msg);
+                buffer[k++] = '#';
+                break;
+            }
+            n = end - (msg + i);
+            if (n == 1) {
+                // ## detected, output #
+                buffer[k++] = '#';
+                i += 2;
+                c = msg[i];
+
+            } else {
+                char type = msg[i + 1]; // one of ribs
+                fmi2ValueReference vr;
+                int nvr = sscanf(msg + i + 2, "%u", &vr);
+                if (nvr == 1) {
+                    // vr of type detected, e.g. #r12#
+                    //ScalarVariable* sv = getSV(fmu, type, vr);
+                    //const char* name = sv ? getAttributeValue((Element *)sv, att_name) : "?";
+                    //sprintf(buffer + k, "%s", name);
+                    //k += strlen(name);
+                    //i += (n+1);
+                    //c = msg[i];
+
+                } else {
+                    // could not parse the number
+                    printf("illegal value reference at position %d in '%s'\n", i + 2, msg);
+                    buffer[k++] = '#';
+                    break;
+                }
+            }
+        }
+    } // while
+    buffer[k] = '\0';
+}
+
+#define MAX_MSG_SIZE 1000
+void fmuLogger(void *componentEnvironment, fmi2String instanceName, fmi2Status status,
+               fmi2String category, fmi2String message, ...) {
+    char msg[MAX_MSG_SIZE];
+    char* copy;
+    va_list argp;
+
+    // replace C format strings
+    va_start(argp, message);
+    vsprintf(msg, message, argp);
+    va_end(argp);
+
+    // replace e.g. ## and #r12#
+    copy = strdup(msg);
+//    replaceRefsInMessage(copy, msg, MAX_MSG_SIZE, NULL);
+    free(copy);
+
+    // print the final message
+    if (!instanceName) instanceName = "?";
+    if (!category) category = "?";
+    printf("%s %s (%s): %s\n", fmi2StatusToString(status), instanceName, category, msg);
+}
+
+int error(const char* message){
+    printf("%s\n", message);
+    return 0;
+}
+//
+//void parseArguments(int argc, char *argv[], const char **fmuFileName, double *tEnd, double *h,
+//                    int *loggingOn, char *csv_separator, int *nCategories, char **logCategories[]) {
+//    // parse command line arguments
+//    if (argc > 1) {
+//        *fmuFileName = argv[1];
+//    } else {
+//        printf("error: no fmu file\n");
+//        printHelp(argv[0]);
+//        exit(EXIT_FAILURE);
+//    }
+//    if (argc > 2) {
+//        if (sscanf(argv[2],"%lf", tEnd) != 1) {
+//            printf("error: The given end time (%s) is not a number\n", argv[2]);
+//            exit(EXIT_FAILURE);
+//        }
+//    }
+//    if (argc > 3) {
+//        if (sscanf(argv[3],"%lf", h) != 1) {
+//            printf("error: The given stepsize (%s) is not a number\n", argv[3]);
+//            exit(EXIT_FAILURE);
+//        }
+//    }
+//    if (argc > 4) {
+//        if (sscanf(argv[4],"%d", loggingOn) != 1 || *loggingOn < 0 || *loggingOn > 1) {
+//            printf("error: The given logging flag (%s) is not boolean\n", argv[4]);
+//            exit(EXIT_FAILURE);
+//        }
+//    }
+//    if (argc > 5) {
+//        if (strlen(argv[5]) != 1) {
+//            printf("error: The given CSV separator char (%s) is not valid\n", argv[5]);
+//            exit(EXIT_FAILURE);
+//        }
+//        switch (argv[5][0]) {
+//            case 'c': *csv_separator = ','; break; // comma
+//            case 's': *csv_separator = ';'; break; // semicolon
+//            default:  *csv_separator = argv[5][0]; break; // any other char
+//        }
+//    }
+//    if (argc > 6) {
+//        int i;
+//        *nCategories = argc - 6;
+//        *logCategories = (char **)calloc(sizeof(char *), *nCategories);
+//        for (i = 0; i < *nCategories; i++) {
+//            (*logCategories)[i] = argv[i + 6];
+//        }
+//    }
+//}
+//
+//void printHelp(const char *fmusim) {
+//    printf("command syntax: %s <model.fmu> <tEnd> <h> <loggingOn> <csv separator>\n", fmusim);
+//    printf("   <model.fmu> .... path to FMU, relative to current dir or absolute, required\n");
+//    printf("   <tEnd> ......... end  time of simulation,   optional, defaults to 1.0 sec\n");
+//    printf("   <h> ............ step size of simulation,   optional, defaults to 0.1 sec\n");
+//    printf("   <loggingOn> .... 1 to activate logging,     optional, defaults to 0\n");
+//    printf("   <csv separator>. separator in csv file,     optional, c for ',', s for';', defaults to c\n");
+//    printf("   <logCategories>. list of active categories, optional, see modelDescription.xml for possible values\n");
+//}

+ 44 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/FMI_generic_master/sim_support.h

@@ -0,0 +1,44 @@
+/* ------------------------------------------------------------------------- 
+ * sim_support.h
+ * Functions used by the FMU simulations fmusim_me and fmusim_cs.
+ * Copyright QTronic GmbH. All rights reserved.
+ * -------------------------------------------------------------------------*/
+#ifndef __SIM_SUPPORT_H
+#define __SIM_SUPPORT_H
+
+// Used 7z options, version 4.57:
+// -x   Extracts files from an archive with their full paths in the current dir, or in an output dir if specified
+// -aoa Overwrite All existing files without prompt
+// -o   Specifies a destination directory where files are to be extracted
+#define UNZIP_CMD "7z x -aoa -o"
+#define XML_FILE  "modelDescription.xml"
+#define RESULT_FILE "result.csv"
+#define BUFSIZE 4096
+#ifdef _WIN64
+#define DLL_DIR   "binaries\\win64\\"
+#else
+#define DLL_DIR   "binaries\\win32\\"
+#endif
+#define RESOURCES_DIR "resources\\"
+
+// return codes of the 7z command line tool
+#define SEVEN_ZIP_NO_ERROR 0 // success
+#define SEVEN_ZIP_WARNING 1  // e.g., one or more files were locked during zip
+#define SEVEN_ZIP_ERROR 2
+#define SEVEN_ZIP_COMMAND_LINE_ERROR 7
+#define SEVEN_ZIP_OUT_OF_MEMORY 8
+#define SEVEN_ZIP_STOPPED_BY_USER 255
+
+void fmuLogger(fmi2Component c, fmi2String instanceName, fmi2Status status, fmi2String category, fmi2String message, ...);
+int unzip(const char *zipPath, const char *outPath);
+void parseArguments(int argc, char *argv[], const char **fmuFileName, double *tEnd, double *h,
+                    int *loggingOn, char *csv_separator, int *nCategories, char **logCategories[]);
+void loadFMU(const char *fmuFileName);
+int loadDll(const char* dllPath, FMU *fmu, const char* preamble);
+void deleteUnzippedFiles();
+void outputRow(FMU *fmu, fmi2Component c, double time, FILE* file, char separator, fmi2Boolean header);
+int error(const char *message);
+void printHelp(const char *fmusim);
+char *getTempResourcesLocation(); // caller has to free the result
+
+#endif

BIN
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/PW_Controller/libpw_controller.dll


+ 71 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/PW_Controller/modelDescription.xml

@@ -0,0 +1,71 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<fmiModelDescription
+  fmiVersion="2.0"
+  modelName="PW_Controller"
+  guid='{f4893318-1565-4931-b8c8-8a19fb3fcfda}'
+  numberOfEventIndicators="1">
+
+<CoSimulation
+  modelIdentifier="PW_Controller"
+  canHandleVariableCommunicationStepSize="true"/>
+
+<LogCategories>
+  <Category name="logAll"/>
+  <Category name="logError"/>
+  <Category name="logFmiCall"/>
+  <Category name="logEvent"/>
+</LogCategories>
+
+
+<ModelVariables>
+  <ScalarVariable name="driver_up" valueReference="0" description="driver push up button = 1; no push = 0"
+                  causality="input" variability="enum" initial="exact">
+    <Boolean start="0"/>
+  </ScalarVariable>
+  <ScalarVariable name="driver_down" valueReference="1" description="driver push down button = 1"
+                  causality="input" variability="discrete" initial="exact">
+    <Boolean start="0"/>
+  </ScalarVariable>
+  <ScalarVariable name="driver_up_stop" valueReference="2" description="driver stops push up button = 1"
+                  causality="input" variability="discrete" initial="exact">
+    <Boolean start="0"/>
+  </ScalarVariable>
+    <ScalarVariable name="driver_down_stop" valueReference="3" description="driver stops push down button = 1"
+                  causality="input" variability="discrete" initial="exact">
+    <Boolean start="0"/>
+  </ScalarVariable>
+    <ScalarVariable name="passenger_up" valueReference="4" description="passenger  push up button = 1"
+                  causality="input" variability="discrete" initial="exact">
+    <Boolean start="0"/>
+  </ScalarVariable>
+    <ScalarVariable name="passenger_down" valueReference="5" description="passenger  push down button = 1"
+                  causality="input" variability="discrete" initial="exact">
+    <Boolean start="0"/>
+  </ScalarVariable>
+    <ScalarVariable name="passenger_up_stop" valueReference="6" description="passenger stop push up button = 1"
+                  causality="input" variability="discrete" initial="exact">
+    <Boolean start="0"/>
+  </ScalarVariable>
+    <ScalarVariable name="passenger_down_stop" valueReference="7" description="passenger stop push down button = 1"
+                  causality="input" variability="discrete" initial="exact">
+    <Boolean start="0"/>
+  </ScalarVariable>
+      <ScalarVariable name="obj_detected" valueReference="8" description="Object detected"
+                  causality="input" variability="discrete" initial="exact">
+    <Boolean start="0"/>
+  </ScalarVariable>
+        <ScalarVariable name="motor_up" valueReference="9" description="motor command up = 1"
+                  causality="output" variability="discrete" initial="exact">
+    <Boolean start="0"/>
+  </ScalarVariable>
+        <ScalarVariable name="motor_down" valueReference="10" description="motor command down = 1"
+                  causality="output" variability="discrete" initial="exact">
+    <Boolean start="0"/>
+  </ScalarVariable>
+</ModelVariables>
+
+
+<ModelStructure>
+</ModelStructure>
+
+</fmiModelDescription>

BIN
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/PW_Controller/src/Debug/libpw_controller.dll


+ 497 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/PW_Controller/src/PW_Controller.c

@@ -0,0 +1,497 @@
+/* ---------------------------------------------------------------------------*
+ * Sample implementation of an FMU - a power window controller
+ * The code is generated from a Yakindu SC
+ * ---------------------------------------------------------------------------*/
+/*
+Template for a sc FMU
+*/
+
+#define MODEL_IDENTIFIER PW_Controller
+#define MODEL_GUID "{f4893318-1565-4931-b8c8-8a19fb3fcfda}"
+#define FMI2_FUNCTION_PREFIX PW_Controller
+
+
+#include <stdio.h>
+#include "string.h"
+#include "fmi2Functions.h"
+#include <float.h>
+#include "PW_Controller.h"
+#include "PowerwindowRequired.h"
+
+
+#define NUMBER_OF_REALS 1
+#define NUMBER_OF_STRINGS 0
+#define NUMBER_OF_BOOLEANS 11
+#define NUMBER_OF_INTEGERS 0
+/*
+ * The input events:
+ * */
+#define _in_obj_detected 0
+#define _in_driver_up 1
+#define _in_driver_up_stop 2
+#define _in_driver_down 3
+#define _in_driver_down_stop 4
+#define _in_passenger_up 5
+#define _in_passenger_up_stop 6
+#define _in_passenger_down 7
+#define _in_passenger_down_stop 8
+
+/*
+ * The output events
+ */
+#define _motor_up 9
+#define _motor_down 10
+
+#define _out_next_timer_event 0
+
+fmi2Status fmi2SetDebugLogging(fmi2Component fc, fmi2Boolean loggingOn, size_t nCategories, const fmi2String categories[])
+{
+    return fmi2OK;
+}
+
+fmi2Status fmi2SetString(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, const fmi2String value[])
+{
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetString(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, fmi2String value[])
+{
+    return fmi2Error;
+}
+
+fmi2Status fmi2SetReal(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, const fmi2Real value[])
+{
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetReal(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, fmi2Real value[])
+{
+
+    return fmi2Error;
+}
+
+fmi2Status fmi2SetBoolean(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, const fmi2Boolean value[])
+{
+	FMUInstance* comp = (FMUInstance *)fc;
+	int i;
+	for (i = 0; i < nvr; i++)
+	{
+		comp->b[vr[i]] = value[i];
+	}
+    return fmi2OK;
+}
+
+fmi2Status fmi2GetBoolean(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, fmi2Boolean value[])
+{
+	FMUInstance* comp = (FMUInstance *)fc;
+	int i;
+	for (i = 0; i < nvr; i++)
+	{
+		value[i] = comp->b[vr[i]];
+	}
+    return fmi2OK;
+}
+
+fmi2Component fmi2Instantiate(fmi2String instanceName, fmi2Type fmuType, fmi2String fmuGUID, fmi2String fmuLocation, const fmi2CallbackFunctions* functions, fmi2Boolean visible, fmi2Boolean loggingOn)
+{
+
+	//Declare data structure for fmu instance
+    FMUInstance* fi;
+	printf("%s in fmiInstantiate\n",instanceName);
+
+    //Perform checks on passed callback functions
+    if (loggingOn) {
+
+        if (!functions->logger);
+        //return NULL;
+	}
+    //Check for instanceName
+    if (!instanceName || strlen(instanceName)==0) {
+
+        // print (and/or log) instanceName is missing
+        //return NULL;
+    }
+    //Check passed GUID to defined model GUID
+    if (strcmp(fmuGUID, MODEL_GUID))
+	{
+        // print (and/or log) GUID doesn't match
+        //return NULL;
+    }
+
+    //Allocate fmu instance Memory
+    // TODO check if "canNotUseMemoryManagementFunctions == true/false". If false memory allocation not possible
+    fi = (FMUInstance *)functions->allocateMemory(1, sizeof(FMUInstance));
+    fi->functions = functions;
+    if (fi) {
+        // Think about what to do with variable values. Using these structs and pointers slows down simulation computations. Maybe only necessary for input, output and tunable parameters??
+        fi->r = functions->allocateMemory(NUMBER_OF_REALS, sizeof(fmi2Real));
+        fi->i = functions->allocateMemory(NUMBER_OF_INTEGERS, sizeof(fmi2Integer));
+        fi->b = functions->allocateMemory(NUMBER_OF_BOOLEANS, sizeof(fmi2Boolean));
+        fi->s = functions->allocateMemory(NUMBER_OF_STRINGS,  sizeof(fmi2String));
+        fi->Handle = functions->allocateMemory(1,sizeof(Powerwindow));
+        fi->thePWTimer = functions->allocateMemory(1,sizeof(fmi_timer));
+    } // variables in predefined arrays (performance issue) --> makes multiple instances of fmu impossible
+
+    fi->thePWTimer->callback = &powerwindow_raiseTimeEvent;
+    powerwindow_initTimer(fi->thePWTimer);
+    fi->instanceName = functions->allocateMemory(1 + strlen(instanceName), sizeof(char));
+    fi->GUID = functions->allocateMemory(1 + strlen(fmuGUID), sizeof(char));
+
+    strcpy((char*)fi->instanceName, instanceName);
+    strcpy((char*)fi->GUID, fmuGUID);
+    fi->loggingOn = loggingOn;
+    fi->isVisible = visible;
+    fi->state = fmuInstantiated;
+    return fi;
+}
+
+fmi2Status fmi2SetupExperiment(fmi2Component fc, fmi2Boolean toleranceDefined, fmi2Real tolerance,
+                            fmi2Real startTime, fmi2Boolean stopTimeDefined, fmi2Real stopTime) {
+
+
+    FMUInstance* fi = (FMUInstance*) fc;
+	printf("%s in fmiSetupExperiment\n",fi->instanceName);
+	if (fi->state != fmuInstantiated)
+	{
+		printf("fmu: %s was not instatiated before calling fmiSetupExperiment\n", fi->instanceName);
+		return fmi2Error;
+	}
+	fi->currentTime = startTime;
+	fi->stopTimeDefined = stopTimeDefined;
+	fi->toleranceDefined = toleranceDefined;
+	if (stopTimeDefined)
+	{
+		fi->stopTime = stopTime;
+	}
+
+	if (toleranceDefined)
+	{
+		fi->tolerance = tolerance;
+	}
+	//TODO
+	//fi->stepSize = getStepSize();
+	fi->state = fmuExperimentSettedUp;
+    return fmi2OK;
+}
+
+fmi2Status fmi2EnterInitializationMode(fmi2Component fc)
+{
+	FMUInstance* fi = (FMUInstance*) fc;
+	printf("%s in fmiEnterInitializationMode\n",fi->instanceName);
+	if (fi->state != fmuExperimentSettedUp)
+	{
+		printf("fmu: %s experiment was not set-up before calling fmiEnterInitializationMode\n", fi->instanceName);
+		return fmi2Error;
+	}
+
+    fi->state = fmuInitMode;
+    powerwindow_init(fi->Handle);
+    return fmi2OK;
+}
+
+fmi2Status fmi2ExitInitializationMode(fmi2Component fc)
+{
+	FMUInstance* fi = (FMUInstance*) fc;
+	fmi2Status initStatus = fmi2OK;
+	printf("%s in fmiExitInitializationMode\n",fi->instanceName);
+	if (fi->state != fmuInitMode)
+	{
+		printf("fmu: %s did not enter Initialization Mode before calling fmiExitInitializationMode\n", fi->instanceName);
+		return fmi2Error;
+	}
+	// TODO
+	//initStatus = calculateInitialUnknownValues();
+	//initialize();
+	powerwindow_enter(fi->Handle);
+    fi->state = fmuInitialized;
+    return initStatus;
+}
+
+fmi2Status fmi2DoStep(fmi2Component fc , fmi2Real currentCommPoint, fmi2Real commStepSize, fmi2Boolean noPrevFMUState)
+{
+	FMUInstance* fi = (FMUInstance *)fc;
+	fmi2Status simStatus = fmi2OK;
+    printf("%s in fmiDoStep()\n",fi->instanceName);
+    /*
+     * */
+    powerwindow_timeradvance(fi->thePWTimer, (currentCommPoint+commStepSize)*1000);
+
+    if (fi->b[_in_driver_up]){
+    	powerwindowIfaceInput_raise_driver_up(fi->Handle);}
+
+	if(fi->b[ _in_driver_down]){
+		powerwindowIfaceInput_raise_driver_down(fi->Handle);
+	}
+
+	if(fi->b[_in_driver_up_stop]){
+		powerwindowIfaceInput_raise_stop(fi->Handle);
+	}
+	if(fi->b[ _in_driver_down_stop]){
+		powerwindowIfaceInput_raise_stop(fi->Handle);
+	}
+	if(fi->b[_in_passenger_up]){
+		powerwindowIfaceInput_raise_passenger_up(fi->Handle);
+	}
+	if(fi->b[_in_passenger_down]){
+		powerwindowIfaceInput_raise_passenger_down(fi->Handle);
+	}
+	if(fi->b[_in_passenger_up_stop]){
+		powerwindowIfaceInput_raise_stop(fi->Handle);
+	}
+	if(fi->b[_in_passenger_down_stop]){
+		powerwindowIfaceInput_raise_stop(fi->Handle);
+	}
+	if(fi->b[_in_obj_detected]){
+		powerwindowIfaceInput_raise_obj_detected(fi->Handle);
+	}
+
+	powerwindow_runCycle(fi->Handle);
+
+
+	fi->b[_motor_up] = powerwindowIfaceOutput_get_down(fi->Handle);
+	fi->b[_motor_down] = powerwindowIfaceOutput_get_up(fi->Handle);
+	/*
+	 * Check timers and set
+	 */
+	if(fi->thePWTimer->active){
+		fi->r[_out_next_timer_event] = fi->thePWTimer->nextTime/1000;
+	}else{
+		fi->r[_out_next_timer_event] = 0;
+	}
+
+
+	fi->currentTime = currentCommPoint +  commStepSize;
+
+	return fmi2OK;
+}
+
+fmi2Status fmi2Terminate(fmi2Component fc)
+{
+	FMUInstance* fi = (FMUInstance *)fc;
+	printf("%s in fmiTerminate\n",fi->instanceName);
+	// do check if fi may be terminated
+	fi->state = fmuTerminated;
+
+    return fmi2OK;
+}
+
+
+void fmi2FreeInstance(fmi2Component fc)
+{
+
+	FMUInstance* fi = (FMUInstance*) fc;
+	printf("%s in fmiFreeInstance\n",fi->instanceName);
+
+    if (fi) {
+
+        fi->functions->freeMemory(fi->r);
+        fi->functions->freeMemory(fi->i);
+        fi->functions->freeMemory(fi->b);
+        fi->functions->freeMemory(fi->Handle);
+        fi->functions->freeMemory(fi->s);// TODO has to be done with loop
+        fi->functions->freeMemory(fi->Handle);
+		fi->functions->freeMemory((void*)fi->instanceName);
+		fi->functions->freeMemory((void*)fi->GUID);
+		fi->functions->freeMemory((void*)fi);
+
+
+    }
+}
+
+//To be implemented
+
+const char* fmi2GetVersion() {
+	printf("Function fmiGetVersion not supported\n");
+    return NULL;
+}
+
+const char* fmi2GetTypesPlatform() {
+	printf("Function fmiGetTypesPlatform not supported\n");
+    return NULL;
+}
+
+fmi2Status fmi2Reset(fmi2Component fc)
+{
+	printf("Function fmiReset not supported\n");
+    return fmi2Error;
+}
+
+
+
+
+fmi2Status fmi2SetInteger(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, const fmi2Integer value[])
+{
+    printf("Function fmiSetInteger not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetInteger(fmi2Component fc, const fmi2ValueReference vr[], size_t nvr, fmi2Integer value[])
+{
+    printf("Function fmiGetInteger not supported\n");
+    return fmi2Error;
+}
+
+
+/*******OWN IMPLEMENTATION OF Get/Set FMU state*******/
+fmi2Status fmi2GetFMUstate (fmi2Component c, fmi2FMUstate* FMUstate) {
+    FMUInstance* orig = (FMUInstance*)c;
+    FMUInstance* fi = (FMUInstance *)FMUstate;
+    fi = orig->functions->allocateMemory(1, sizeof(FMUInstance));
+    *FMUstate = fi;
+    if (fi) {
+        // Think about what to do with variable values. Using these structs and pointers slows down simulation computations. Maybe only necessary for input, output and tunable parameters??
+        fi->r = orig->functions->allocateMemory(NUMBER_OF_REALS, sizeof(fmi2Real));
+        fi->i = orig->functions->allocateMemory(NUMBER_OF_INTEGERS, sizeof(fmi2Integer));
+        fi->b = orig->functions->allocateMemory(NUMBER_OF_BOOLEANS, sizeof(fmi2Boolean));
+        fi->s = orig->functions->allocateMemory(NUMBER_OF_STRINGS,  sizeof(fmi2String));
+        fi->Handle = orig->functions->allocateMemory(1,sizeof(Powerwindow));
+
+    } // variables in predefined arrays (performance issue) --> makes multiple instances of fmu impossible
+    fi->instanceName = orig->functions->allocateMemory(1 + strlen(orig->instanceName), sizeof(char));
+    fi->GUID = orig->functions->allocateMemory(1 + strlen(orig->GUID), sizeof(char));
+
+    strcpy((char *)fi->instanceName, (char *)orig->instanceName);
+    strcpy((char *)fi->GUID, (char *)orig->GUID);
+    fi->functions = orig->functions;
+    fi->loggingOn = orig->loggingOn;
+    fi->isVisible = orig->isVisible;
+    fi->state = orig->state;
+    fi->stepSize = orig->stepSize;
+    fi->startTime = orig->startTime;
+    fi->stopTime = orig->stopTime;
+	fi->currentTime = orig->currentTime;
+	powerwindow_copy(orig->Handle, fi->Handle);
+	//copy r
+	int i=0;
+	for (i=0; i< NUMBER_OF_REALS;i++){
+	    printf("Setting real: %i %f\n", i, orig->r[i]);
+        fi->r[i] = orig->r[i];
+        printf("Setted real: %i %f\n", i, fi->r[i]);
+	}
+	//copy s
+	for (i=0; i< NUMBER_OF_STRINGS;i++){
+        fi->s[i] = orig->s[i];
+	}
+	//copy i
+    for (i=0; i< NUMBER_OF_INTEGERS;i++){
+        fi->i[i] = orig->i[i];
+	}
+	//copy b
+	for (i=0; i< NUMBER_OF_BOOLEANS;i++){
+        fi->b[i] = orig->b[i];
+	}
+
+	// copy pw
+
+    return fmi2OK;
+}
+
+
+fmi2Status fmi2SetFMUstate (fmi2Component c, fmi2FMUstate FMUstate) {
+    FMUInstance* orig = (FMUInstance*)FMUstate;
+    FMUInstance* fi = (FMUInstance*)c;
+    //set time etc correct, name and GUID should still be ok ;-)
+    printf("setting time values from %f to %f\n", fi->currentTime, orig->currentTime);
+    fi->state = orig->state;
+    fi->stepSize = orig->stepSize;
+    fi->startTime = orig->startTime;
+    fi->stopTime = orig->stopTime;
+	fi->currentTime = orig->currentTime;
+	printf("setting real values\n");
+	//copy r
+	int i=0;
+	for (i=0; i< NUMBER_OF_REALS;i++){
+        fi->r[i] = orig->r[i];
+	}
+	printf("setting string values\n");
+	//copy s
+	for (i=0; i< NUMBER_OF_STRINGS;i++){
+
+        fi->s[i] = orig->s[i];
+	}
+	//copy i
+    for (i=0; i< NUMBER_OF_INTEGERS;i++){
+        fi->i[i] = orig->i[i];
+	}
+	//copy b
+	for (i=0; i< NUMBER_OF_BOOLEANS;i++){
+        fi->b[i] = orig->b[i];
+	}
+	powerwindow_copy(orig->Handle,fi->Handle);
+
+    return fmi2OK;
+
+
+}
+/****************************************************/
+
+fmi2Status fmi2FreeFMUstate(fmi2Component c, fmi2FMUstate* FMUstate) {
+    printf("Function fmiFreeFMUstate not supported\n");
+    return fmi2Error;
+}
+fmi2Status fmi2SerializedFMUstateSize(fmi2Component c, fmi2FMUstate FMUstate, size_t *size) {
+    printf("Function fmiSerializedFMUstateSize not supported\n");
+    return fmi2Error;
+}
+fmi2Status fmi2SerializeFMUstate (fmi2Component c, fmi2FMUstate FMUstate, fmi2Byte serializedState[], size_t size) {
+    printf("Function fmiSerializeFMUstate not supported\n");
+    return fmi2Error;
+}
+fmi2Status fmi2DeSerializeFMUstate (fmi2Component c, const fmi2Byte serializedState[], size_t size, fmi2FMUstate* FMUstate) {
+    printf("Function fmiDeSerializeFMUstate not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetDirectionalDerivative(fmi2Component c, const fmi2ValueReference vUnknown_ref[], size_t nUnknown,
+                const fmi2ValueReference vKnown_ref[] , size_t nKnown, const fmi2Real dvKnown[], fmi2Real dvUnknown[]) {
+    printf("Function fmiGetDirectionalDerivative not supported\n");
+    return fmi2Error;
+}
+
+
+fmi2Status fmi2SetRealInputDerivatives(fmi2Component c, const fmi2ValueReference vr[], size_t nvr,
+                                     const fmi2Integer order[], const fmi2Real value[]) {
+    printf("Function fmiGetDirectionalDerivative not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetRealOutputDerivatives(fmi2Component c, const fmi2ValueReference vr[], size_t nvr,
+                                      const fmi2Integer order[], fmi2Real value[]) {
+    printf("Function fmiGetDirectionalDerivative not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2CancelStep(fmi2Component c) {
+    printf("Function fmiGetDirectionalDerivative not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetStatus(fmi2Component c, const fmi2StatusKind s, fmi2Status *value) {
+    printf("Function fmiGetStatus not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetRealStatus(fmi2Component c, const fmi2StatusKind s, fmi2Real *value) {
+    if(s == fmi2LastSuccessfulTime){
+        FMUInstance* comp = (FMUInstance*) c;
+        *value = comp->currentTime;
+        return fmi2OK;
+    }
+    printf("Function fmiGetRealStatus not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetIntegerStatus(fmi2Component c, const fmi2StatusKind s, fmi2Integer *value) {
+    printf("Function fmiGetIntegerStatus not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetBooleanStatus(fmi2Component c, const fmi2StatusKind s, fmi2Boolean *value) {
+    printf("Function fmiGetBooleanStatus not supported\n");
+    return fmi2Error;
+}
+
+fmi2Status fmi2GetStringStatus(fmi2Component c, const fmi2StatusKind s, fmi2String *value) {
+    printf("Function fmiGetStringStatus not supported\n");
+    return fmi2Error;
+}

+ 48 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/PW_Controller/src/PW_Controller.h

@@ -0,0 +1,48 @@
+/*
+ * PW_Controller.h
+ *
+ *  Created on: Jan 25, 2017
+ *      Author: Joachim
+ */
+
+#ifndef PW_CONTROLLER_H_
+#define PW_CONTROLLER_H_
+
+#include "Powerwindow.h"
+#include "PowerwindowRequired.h"
+
+typedef enum {
+    fmuInstantiated = 0,
+    fmuInitMode  = 1,
+	fmuInitialized = 2,
+    fmuTerminated   = 3,
+    fmuError        = 4,
+    fmuExperimentSettedUp = 5
+} FMUState;
+
+
+
+typedef struct {
+	fmi2Real    *r;
+    fmi2Integer *i;
+    fmi2Boolean *b;
+    fmi2String  *s;
+    fmi2Boolean isVisible;
+    fmi2String instanceName;
+    fmi2String GUID;
+    const fmi2CallbackFunctions* functions;
+    fmi2Boolean loggingOn;
+    FMUState state;
+	fmi2Real stepSize;
+    fmi2Real startTime;
+    fmi2Real stopTime;
+	fmi2Real currentTime;
+    fmi2Boolean stopTimeDefined;
+    fmi2Real tolerance;
+    fmi2Boolean toleranceDefined;
+    Powerwindow *Handle;
+    fmi_timer *thePWTimer;
+} FMUInstance; // At the moment, most of the variables not really used since multiple instances of an FMU are not supported at the moment (performance issues)
+
+
+#endif /* PW_CONTROLLER_H_ */

+ 690 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/PW_Controller/src/Powerwindow.c

@@ -0,0 +1,690 @@
+
+#include <stdlib.h>
+#include <string.h>
+#include "sc_types.h"
+#include "Powerwindow.h"
+#include "PowerwindowRequired.h"
+/*! \file Implementation of the state machine 'powerwindow'
+*/
+
+/* prototypes of all internal functions */
+static sc_boolean powerwindow_check_main_region_Normal_operation_tr0_tr0(const Powerwindow* handle);
+static sc_boolean powerwindow_check_main_region_Normal_operation_r1_Driver_neutral_tr0_tr0(const Powerwindow* handle);
+static sc_boolean powerwindow_check_main_region_Normal_operation_r1_Driver_neutral_tr1_tr1(const Powerwindow* handle);
+static sc_boolean powerwindow_check_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation_tr0_tr0(const Powerwindow* handle);
+static sc_boolean powerwindow_check_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation_tr1_tr1(const Powerwindow* handle);
+static sc_boolean powerwindow_check_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_down_tr0_tr0(const Powerwindow* handle);
+static sc_boolean powerwindow_check_main_region_Normal_operation_r1_Driver_down_tr0_tr0(const Powerwindow* handle);
+static sc_boolean powerwindow_check_main_region_Normal_operation_r1_Driver_up_tr0_tr0(const Powerwindow* handle);
+static sc_boolean powerwindow_check_main_region_Normal_operation_r1_Passenger_up_tr0_tr0(const Powerwindow* handle);
+static sc_boolean powerwindow_check_main_region_Emergency_operation_tr0_tr0(const Powerwindow* handle);
+static void powerwindow_effect_main_region_Normal_operation_tr0(Powerwindow* handle);
+static void powerwindow_effect_main_region_Normal_operation_r1_Driver_neutral_tr0(Powerwindow* handle);
+static void powerwindow_effect_main_region_Normal_operation_r1_Driver_neutral_tr1(Powerwindow* handle);
+static void powerwindow_effect_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation_tr0(Powerwindow* handle);
+static void powerwindow_effect_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation_tr1(Powerwindow* handle);
+static void powerwindow_effect_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_down_tr0(Powerwindow* handle);
+static void powerwindow_effect_main_region_Normal_operation_r1_Driver_down_tr0(Powerwindow* handle);
+static void powerwindow_effect_main_region_Normal_operation_r1_Driver_up_tr0(Powerwindow* handle);
+static void powerwindow_effect_main_region_Normal_operation_r1_Passenger_up_tr0(Powerwindow* handle);
+static void powerwindow_effect_main_region_Emergency_operation_tr0(Powerwindow* handle);
+static void powerwindow_enact_main_region_Emergency_operation(Powerwindow* handle);
+static void powerwindow_exact_main_region_Emergency_operation(Powerwindow* handle);
+static void powerwindow_enseq_main_region_Normal_operation_default(Powerwindow* handle);
+static void powerwindow_enseq_main_region_Normal_operation_r1_Driver_neutral_default(Powerwindow* handle);
+static void powerwindow_enseq_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation_default(Powerwindow* handle);
+static void powerwindow_enseq_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_down_default(Powerwindow* handle);
+static void powerwindow_enseq_main_region_Normal_operation_r1_Driver_down_default(Powerwindow* handle);
+static void powerwindow_enseq_main_region_Normal_operation_r1_Driver_up_default(Powerwindow* handle);
+static void powerwindow_enseq_main_region_Normal_operation_r1_Passenger_up_default(Powerwindow* handle);
+static void powerwindow_enseq_main_region_Emergency_operation_default(Powerwindow* handle);
+static void powerwindow_enseq_main_region_default(Powerwindow* handle);
+static void powerwindow_enseq_main_region_Normal_operation_r1_default(Powerwindow* handle);
+static void powerwindow_enseq_main_region_Normal_operation_r1_Driver_neutral_r1_default(Powerwindow* handle);
+static void powerwindow_exseq_main_region_Normal_operation(Powerwindow* handle);
+static void powerwindow_exseq_main_region_Normal_operation_r1_Driver_neutral(Powerwindow* handle);
+static void powerwindow_exseq_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation(Powerwindow* handle);
+static void powerwindow_exseq_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_down(Powerwindow* handle);
+static void powerwindow_exseq_main_region_Normal_operation_r1_Driver_down(Powerwindow* handle);
+static void powerwindow_exseq_main_region_Normal_operation_r1_Driver_up(Powerwindow* handle);
+static void powerwindow_exseq_main_region_Normal_operation_r1_Passenger_up(Powerwindow* handle);
+static void powerwindow_exseq_main_region_Emergency_operation(Powerwindow* handle);
+static void powerwindow_exseq_main_region(Powerwindow* handle);
+static void powerwindow_exseq_main_region_Normal_operation_r1(Powerwindow* handle);
+static void powerwindow_exseq_main_region_Normal_operation_r1_Driver_neutral_r1(Powerwindow* handle);
+static void powerwindow_react_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation(Powerwindow* handle);
+static void powerwindow_react_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_down(Powerwindow* handle);
+static void powerwindow_react_main_region_Normal_operation_r1_Driver_down(Powerwindow* handle);
+static void powerwindow_react_main_region_Normal_operation_r1_Driver_up(Powerwindow* handle);
+static void powerwindow_react_main_region_Normal_operation_r1_Passenger_up(Powerwindow* handle);
+static void powerwindow_react_main_region_Emergency_operation(Powerwindow* handle);
+static void powerwindow_react_main_region__entry_Default(Powerwindow* handle);
+static void powerwindow_react_main_region_Normal_operation_r1__entry_Default(Powerwindow* handle);
+static void powerwindow_react_main_region_Normal_operation_r1_Driver_neutral_r1__entry_Default(Powerwindow* handle);
+static void powerwindow_clearInEvents(Powerwindow* handle);
+static void powerwindow_clearOutEvents(Powerwindow* handle);	
+
+/*Created this myself... -> please */
+void powerwindow_copy(Powerwindow* original, Powerwindow* copy){
+	for (int i = 0; i<POWERWINDOW_MAX_ORTHOGONAL_STATES; i++){
+		copy->stateConfVector[i] =  original->stateConfVector[i];
+	}
+	copy->stateConfVectorPosition = original->stateConfVectorPosition;
+	copy->timeEvents.powerwindow_main_region_Emergency_operation_tev0_raised = original ->timeEvents.powerwindow_main_region_Emergency_operation_tev0_raised;
+	copy->ifaceInput = original->ifaceInput;
+	copy->ifaceOutput = original->ifaceOutput;
+
+}
+
+void powerwindow_init(Powerwindow* handle)
+{
+	sc_integer i;
+
+	for (i = 0; i < POWERWINDOW_MAX_ORTHOGONAL_STATES; ++i) {
+		handle->stateConfVector[i] = Powerwindow_last_state;
+	}
+	
+	
+	handle->stateConfVectorPosition = 0;
+
+	powerwindow_clearInEvents(handle);
+	powerwindow_clearOutEvents(handle);
+
+	/* Default init sequence for statechart powerwindow */
+	handle->ifaceOutput.up = bool_false;
+	handle->ifaceOutput.down = bool_false;
+
+}
+
+void powerwindow_enter(Powerwindow* handle)
+{
+	/* Default enter sequence for statechart powerwindow */
+	powerwindow_enseq_main_region_default(handle);
+}
+
+void powerwindow_exit(Powerwindow* handle)
+{
+	/* Default exit sequence for statechart powerwindow */
+	powerwindow_exseq_main_region(handle);
+}
+
+sc_boolean powerwindow_isActive(const Powerwindow* handle) {
+	sc_boolean result;
+	if (handle->stateConfVector[0] != Powerwindow_last_state)
+	{
+		result =  bool_true;
+	}
+	else
+	{
+		result = bool_false;
+	}
+	return result;
+}
+
+/* 
+ * Always returns 'false' since this state machine can never become final.
+ */
+sc_boolean powerwindow_isFinal(const Powerwindow* handle){
+   return bool_false;
+}
+
+static void powerwindow_clearInEvents(Powerwindow* handle) {
+	handle->ifaceInput.obj_detected_raised = bool_false;
+	handle->ifaceInput.passenger_up_raised = bool_false;
+	handle->ifaceInput.passenger_down_raised = bool_false;
+	handle->ifaceInput.driver_up_raised = bool_false;
+	handle->ifaceInput.driver_down_raised = bool_false;
+	handle->ifaceInput.stop_raised = bool_false;
+	handle->timeEvents.powerwindow_main_region_Emergency_operation_tev0_raised = bool_false; 
+}
+
+static void powerwindow_clearOutEvents(Powerwindow* handle) {
+}
+
+void powerwindow_runCycle(Powerwindow* handle) {
+	
+	powerwindow_clearOutEvents(handle);
+	
+	for (handle->stateConfVectorPosition = 0;
+		handle->stateConfVectorPosition < POWERWINDOW_MAX_ORTHOGONAL_STATES;
+		handle->stateConfVectorPosition++) {
+			
+		switch (handle->stateConfVector[handle->stateConfVectorPosition]) {
+		case Powerwindow_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation : {
+			powerwindow_react_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation(handle);
+			break;
+		}
+		case Powerwindow_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_down : {
+			powerwindow_react_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_down(handle);
+			break;
+		}
+		case Powerwindow_main_region_Normal_operation_r1_Driver_down : {
+			powerwindow_react_main_region_Normal_operation_r1_Driver_down(handle);
+			break;
+		}
+		case Powerwindow_main_region_Normal_operation_r1_Driver_up : {
+			powerwindow_react_main_region_Normal_operation_r1_Driver_up(handle);
+			break;
+		}
+		case Powerwindow_main_region_Normal_operation_r1_Passenger_up : {
+			powerwindow_react_main_region_Normal_operation_r1_Passenger_up(handle);
+			break;
+		}
+		case Powerwindow_main_region_Emergency_operation : {
+			powerwindow_react_main_region_Emergency_operation(handle);
+			break;
+		}
+		default:
+			break;
+		}
+	}
+	
+	powerwindow_clearInEvents(handle);
+}
+
+void powerwindow_raiseTimeEvent(const Powerwindow* handle, sc_eventid evid) {
+	if ( ((sc_intptr_t)evid) >= ((sc_intptr_t)&(handle->timeEvents))
+		&&  ((sc_intptr_t)evid) < ((sc_intptr_t)&(handle->timeEvents)) + sizeof(PowerwindowTimeEvents)) {
+		*(sc_boolean*)evid = bool_true;
+	}		
+}
+
+sc_boolean powerwindow_isStateActive(const Powerwindow* handle, PowerwindowStates state) {
+	sc_boolean result = bool_false;
+	switch (state) {
+		case Powerwindow_main_region_Normal_operation : 
+			result = (sc_boolean) (handle->stateConfVector[0] >= Powerwindow_main_region_Normal_operation
+				&& handle->stateConfVector[0] <= Powerwindow_main_region_Normal_operation_r1_Passenger_up);
+			break;
+		case Powerwindow_main_region_Normal_operation_r1_Driver_neutral : 
+			result = (sc_boolean) (handle->stateConfVector[0] >= Powerwindow_main_region_Normal_operation_r1_Driver_neutral
+				&& handle->stateConfVector[0] <= Powerwindow_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_down);
+			break;
+		case Powerwindow_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation : 
+			result = (sc_boolean) (handle->stateConfVector[0] == Powerwindow_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation
+			);
+			break;
+		case Powerwindow_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_down : 
+			result = (sc_boolean) (handle->stateConfVector[0] == Powerwindow_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_down
+			);
+			break;
+		case Powerwindow_main_region_Normal_operation_r1_Driver_down : 
+			result = (sc_boolean) (handle->stateConfVector[0] == Powerwindow_main_region_Normal_operation_r1_Driver_down
+			);
+			break;
+		case Powerwindow_main_region_Normal_operation_r1_Driver_up : 
+			result = (sc_boolean) (handle->stateConfVector[0] == Powerwindow_main_region_Normal_operation_r1_Driver_up
+			);
+			break;
+		case Powerwindow_main_region_Normal_operation_r1_Passenger_up : 
+			result = (sc_boolean) (handle->stateConfVector[0] == Powerwindow_main_region_Normal_operation_r1_Passenger_up
+			);
+			break;
+		case Powerwindow_main_region_Emergency_operation : 
+			result = (sc_boolean) (handle->stateConfVector[0] == Powerwindow_main_region_Emergency_operation
+			);
+			break;
+		default: 
+			result = bool_false;
+			break;
+	}
+	return result;
+}
+
+
+
+sc_boolean powerwindowIfaceOutput_get_up(const Powerwindow* handle) {
+	return handle->ifaceOutput.up;
+}
+sc_boolean powerwindowIfaceOutput_get_down(const Powerwindow* handle) {
+	return handle->ifaceOutput.down;
+}
+void powerwindowIfaceInput_raise_obj_detected(Powerwindow* handle) {
+	handle->ifaceInput.obj_detected_raised = bool_true;
+}
+void powerwindowIfaceInput_raise_passenger_up(Powerwindow* handle) {
+	handle->ifaceInput.passenger_up_raised = bool_true;
+}
+void powerwindowIfaceInput_raise_passenger_down(Powerwindow* handle) {
+	handle->ifaceInput.passenger_down_raised = bool_true;
+}
+void powerwindowIfaceInput_raise_driver_up(Powerwindow* handle) {
+	handle->ifaceInput.driver_up_raised = bool_true;
+}
+void powerwindowIfaceInput_raise_driver_down(Powerwindow* handle) {
+	handle->ifaceInput.driver_down_raised = bool_true;
+}
+void powerwindowIfaceInput_raise_stop(Powerwindow* handle) {
+	handle->ifaceInput.stop_raised = bool_true;
+}
+
+
+
+/* implementations of all internal functions */
+
+static sc_boolean powerwindow_check_main_region_Normal_operation_tr0_tr0(const Powerwindow* handle) {
+	return handle->ifaceInput.obj_detected_raised;
+}
+
+static sc_boolean powerwindow_check_main_region_Normal_operation_r1_Driver_neutral_tr0_tr0(const Powerwindow* handle) {
+	return handle->ifaceInput.driver_down_raised;
+}
+
+static sc_boolean powerwindow_check_main_region_Normal_operation_r1_Driver_neutral_tr1_tr1(const Powerwindow* handle) {
+	return handle->ifaceInput.driver_up_raised;
+}
+
+static sc_boolean powerwindow_check_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation_tr0_tr0(const Powerwindow* handle) {
+	return handle->ifaceInput.passenger_down_raised;
+}
+
+static sc_boolean powerwindow_check_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation_tr1_tr1(const Powerwindow* handle) {
+	return handle->ifaceInput.passenger_up_raised;
+}
+
+static sc_boolean powerwindow_check_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_down_tr0_tr0(const Powerwindow* handle) {
+	return handle->ifaceInput.stop_raised;
+}
+
+static sc_boolean powerwindow_check_main_region_Normal_operation_r1_Driver_down_tr0_tr0(const Powerwindow* handle) {
+	return handle->ifaceInput.stop_raised;
+}
+
+static sc_boolean powerwindow_check_main_region_Normal_operation_r1_Driver_up_tr0_tr0(const Powerwindow* handle) {
+	return handle->ifaceInput.stop_raised;
+}
+
+static sc_boolean powerwindow_check_main_region_Normal_operation_r1_Passenger_up_tr0_tr0(const Powerwindow* handle) {
+	return handle->ifaceInput.stop_raised;
+}
+
+static sc_boolean powerwindow_check_main_region_Emergency_operation_tr0_tr0(const Powerwindow* handle) {
+	return handle->timeEvents.powerwindow_main_region_Emergency_operation_tev0_raised;
+}
+
+static void powerwindow_effect_main_region_Normal_operation_tr0(Powerwindow* handle) {
+	powerwindow_exseq_main_region_Normal_operation(handle);
+	handle->ifaceOutput.down = bool_true;
+	powerwindow_enseq_main_region_Emergency_operation_default(handle);
+}
+
+static void powerwindow_effect_main_region_Normal_operation_r1_Driver_neutral_tr0(Powerwindow* handle) {
+	powerwindow_exseq_main_region_Normal_operation_r1_Driver_neutral(handle);
+	handle->ifaceOutput.down = bool_true;
+	powerwindow_enseq_main_region_Normal_operation_r1_Driver_down_default(handle);
+}
+
+static void powerwindow_effect_main_region_Normal_operation_r1_Driver_neutral_tr1(Powerwindow* handle) {
+	powerwindow_exseq_main_region_Normal_operation_r1_Driver_neutral(handle);
+	handle->ifaceOutput.up = bool_true;
+	powerwindow_enseq_main_region_Normal_operation_r1_Driver_up_default(handle);
+}
+
+static void powerwindow_effect_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation_tr0(Powerwindow* handle) {
+	powerwindow_exseq_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation(handle);
+	handle->ifaceOutput.down = bool_true;
+	powerwindow_enseq_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_down_default(handle);
+}
+
+static void powerwindow_effect_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation_tr1(Powerwindow* handle) {
+	powerwindow_exseq_main_region_Normal_operation_r1_Driver_neutral(handle);
+	handle->ifaceOutput.up = bool_true;
+	powerwindow_enseq_main_region_Normal_operation_r1_Passenger_up_default(handle);
+}
+
+static void powerwindow_effect_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_down_tr0(Powerwindow* handle) {
+	powerwindow_exseq_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_down(handle);
+	handle->ifaceOutput.down = bool_true;
+	powerwindow_enseq_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation_default(handle);
+}
+
+static void powerwindow_effect_main_region_Normal_operation_r1_Driver_down_tr0(Powerwindow* handle) {
+	powerwindow_exseq_main_region_Normal_operation_r1_Driver_down(handle);
+	handle->ifaceOutput.down = bool_false;
+	powerwindow_enseq_main_region_Normal_operation_r1_Driver_neutral_default(handle);
+}
+
+static void powerwindow_effect_main_region_Normal_operation_r1_Driver_up_tr0(Powerwindow* handle) {
+	powerwindow_exseq_main_region_Normal_operation_r1_Driver_up(handle);
+	handle->ifaceOutput.up = bool_false;
+	powerwindow_enseq_main_region_Normal_operation_r1_Driver_neutral_default(handle);
+}
+
+static void powerwindow_effect_main_region_Normal_operation_r1_Passenger_up_tr0(Powerwindow* handle) {
+	powerwindow_exseq_main_region_Normal_operation_r1_Passenger_up(handle);
+	handle->ifaceOutput.up = bool_false;
+	powerwindow_enseq_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation_default(handle);
+}
+
+static void powerwindow_effect_main_region_Emergency_operation_tr0(Powerwindow* handle) {
+	powerwindow_exseq_main_region_Emergency_operation(handle);
+	handle->ifaceOutput.down = bool_false;
+	powerwindow_enseq_main_region_Normal_operation_default(handle);
+}
+
+/* Entry action for state 'Emergency_operation'. */
+static void powerwindow_enact_main_region_Emergency_operation(Powerwindow* handle) {
+	/* Entry action for state 'Emergency_operation'. */
+	powerwindow_setTimer(handle, (sc_eventid) &(handle->timeEvents.powerwindow_main_region_Emergency_operation_tev0_raised) , 1 * 1000, bool_false);
+}
+
+/* Exit action for state 'Emergency_operation'. */
+static void powerwindow_exact_main_region_Emergency_operation(Powerwindow* handle) {
+	/* Exit action for state 'Emergency_operation'. */
+	powerwindow_unsetTimer(handle, (sc_eventid) &(handle->timeEvents.powerwindow_main_region_Emergency_operation_tev0_raised) );		
+}
+
+/* 'default' enter sequence for state Normal_operation */
+static void powerwindow_enseq_main_region_Normal_operation_default(Powerwindow* handle) {
+	/* 'default' enter sequence for state Normal_operation */
+	powerwindow_enseq_main_region_Normal_operation_r1_default(handle);
+}
+
+/* 'default' enter sequence for state Driver_neutral */
+static void powerwindow_enseq_main_region_Normal_operation_r1_Driver_neutral_default(Powerwindow* handle) {
+	/* 'default' enter sequence for state Driver_neutral */
+	powerwindow_enseq_main_region_Normal_operation_r1_Driver_neutral_r1_default(handle);
+}
+
+/* 'default' enter sequence for state Passenger_operation */
+static void powerwindow_enseq_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation_default(Powerwindow* handle) {
+	/* 'default' enter sequence for state Passenger_operation */
+	handle->stateConfVector[0] = Powerwindow_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation;
+	handle->stateConfVectorPosition = 0;
+}
+
+/* 'default' enter sequence for state Passenger_down */
+static void powerwindow_enseq_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_down_default(Powerwindow* handle) {
+	/* 'default' enter sequence for state Passenger_down */
+	handle->stateConfVector[0] = Powerwindow_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_down;
+	handle->stateConfVectorPosition = 0;
+}
+
+/* 'default' enter sequence for state Driver_down */
+static void powerwindow_enseq_main_region_Normal_operation_r1_Driver_down_default(Powerwindow* handle) {
+	/* 'default' enter sequence for state Driver_down */
+	handle->stateConfVector[0] = Powerwindow_main_region_Normal_operation_r1_Driver_down;
+	handle->stateConfVectorPosition = 0;
+}
+
+/* 'default' enter sequence for state Driver_up */
+static void powerwindow_enseq_main_region_Normal_operation_r1_Driver_up_default(Powerwindow* handle) {
+	/* 'default' enter sequence for state Driver_up */
+	handle->stateConfVector[0] = Powerwindow_main_region_Normal_operation_r1_Driver_up;
+	handle->stateConfVectorPosition = 0;
+}
+
+/* 'default' enter sequence for state Passenger_up */
+static void powerwindow_enseq_main_region_Normal_operation_r1_Passenger_up_default(Powerwindow* handle) {
+	/* 'default' enter sequence for state Passenger_up */
+	handle->stateConfVector[0] = Powerwindow_main_region_Normal_operation_r1_Passenger_up;
+	handle->stateConfVectorPosition = 0;
+}
+
+/* 'default' enter sequence for state Emergency_operation */
+static void powerwindow_enseq_main_region_Emergency_operation_default(Powerwindow* handle) {
+	/* 'default' enter sequence for state Emergency_operation */
+	powerwindow_enact_main_region_Emergency_operation(handle);
+	handle->stateConfVector[0] = Powerwindow_main_region_Emergency_operation;
+	handle->stateConfVectorPosition = 0;
+}
+
+/* 'default' enter sequence for region main region */
+static void powerwindow_enseq_main_region_default(Powerwindow* handle) {
+	/* 'default' enter sequence for region main region */
+	powerwindow_react_main_region__entry_Default(handle);
+}
+
+/* 'default' enter sequence for region r1 */
+static void powerwindow_enseq_main_region_Normal_operation_r1_default(Powerwindow* handle) {
+	/* 'default' enter sequence for region r1 */
+	powerwindow_react_main_region_Normal_operation_r1__entry_Default(handle);
+}
+
+/* 'default' enter sequence for region r1 */
+static void powerwindow_enseq_main_region_Normal_operation_r1_Driver_neutral_r1_default(Powerwindow* handle) {
+	/* 'default' enter sequence for region r1 */
+	powerwindow_react_main_region_Normal_operation_r1_Driver_neutral_r1__entry_Default(handle);
+}
+
+/* Default exit sequence for state Normal_operation */
+static void powerwindow_exseq_main_region_Normal_operation(Powerwindow* handle) {
+	/* Default exit sequence for state Normal_operation */
+	powerwindow_exseq_main_region_Normal_operation_r1(handle);
+}
+
+/* Default exit sequence for state Driver_neutral */
+static void powerwindow_exseq_main_region_Normal_operation_r1_Driver_neutral(Powerwindow* handle) {
+	/* Default exit sequence for state Driver_neutral */
+	powerwindow_exseq_main_region_Normal_operation_r1_Driver_neutral_r1(handle);
+}
+
+/* Default exit sequence for state Passenger_operation */
+static void powerwindow_exseq_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation(Powerwindow* handle) {
+	/* Default exit sequence for state Passenger_operation */
+	handle->stateConfVector[0] = Powerwindow_last_state;
+	handle->stateConfVectorPosition = 0;
+}
+
+/* Default exit sequence for state Passenger_down */
+static void powerwindow_exseq_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_down(Powerwindow* handle) {
+	/* Default exit sequence for state Passenger_down */
+	handle->stateConfVector[0] = Powerwindow_last_state;
+	handle->stateConfVectorPosition = 0;
+}
+
+/* Default exit sequence for state Driver_down */
+static void powerwindow_exseq_main_region_Normal_operation_r1_Driver_down(Powerwindow* handle) {
+	/* Default exit sequence for state Driver_down */
+	handle->stateConfVector[0] = Powerwindow_last_state;
+	handle->stateConfVectorPosition = 0;
+}
+
+/* Default exit sequence for state Driver_up */
+static void powerwindow_exseq_main_region_Normal_operation_r1_Driver_up(Powerwindow* handle) {
+	/* Default exit sequence for state Driver_up */
+	handle->stateConfVector[0] = Powerwindow_last_state;
+	handle->stateConfVectorPosition = 0;
+}
+
+/* Default exit sequence for state Passenger_up */
+static void powerwindow_exseq_main_region_Normal_operation_r1_Passenger_up(Powerwindow* handle) {
+	/* Default exit sequence for state Passenger_up */
+	handle->stateConfVector[0] = Powerwindow_last_state;
+	handle->stateConfVectorPosition = 0;
+}
+
+/* Default exit sequence for state Emergency_operation */
+static void powerwindow_exseq_main_region_Emergency_operation(Powerwindow* handle) {
+	/* Default exit sequence for state Emergency_operation */
+	handle->stateConfVector[0] = Powerwindow_last_state;
+	handle->stateConfVectorPosition = 0;
+	powerwindow_exact_main_region_Emergency_operation(handle);
+}
+
+/* Default exit sequence for region main region */
+static void powerwindow_exseq_main_region(Powerwindow* handle) {
+	/* Default exit sequence for region main region */
+	/* Handle exit of all possible states (of powerwindow.main_region) at position 0... */
+	switch(handle->stateConfVector[ 0 ]) {
+		case Powerwindow_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation : {
+			powerwindow_exseq_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation(handle);
+			break;
+		}
+		case Powerwindow_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_down : {
+			powerwindow_exseq_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_down(handle);
+			break;
+		}
+		case Powerwindow_main_region_Normal_operation_r1_Driver_down : {
+			powerwindow_exseq_main_region_Normal_operation_r1_Driver_down(handle);
+			break;
+		}
+		case Powerwindow_main_region_Normal_operation_r1_Driver_up : {
+			powerwindow_exseq_main_region_Normal_operation_r1_Driver_up(handle);
+			break;
+		}
+		case Powerwindow_main_region_Normal_operation_r1_Passenger_up : {
+			powerwindow_exseq_main_region_Normal_operation_r1_Passenger_up(handle);
+			break;
+		}
+		case Powerwindow_main_region_Emergency_operation : {
+			powerwindow_exseq_main_region_Emergency_operation(handle);
+			break;
+		}
+		default: break;
+	}
+}
+
+/* Default exit sequence for region r1 */
+static void powerwindow_exseq_main_region_Normal_operation_r1(Powerwindow* handle) {
+	/* Default exit sequence for region r1 */
+	/* Handle exit of all possible states (of powerwindow.main_region.Normal_operation.r1) at position 0... */
+	switch(handle->stateConfVector[ 0 ]) {
+		case Powerwindow_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation : {
+			powerwindow_exseq_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation(handle);
+			break;
+		}
+		case Powerwindow_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_down : {
+			powerwindow_exseq_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_down(handle);
+			break;
+		}
+		case Powerwindow_main_region_Normal_operation_r1_Driver_down : {
+			powerwindow_exseq_main_region_Normal_operation_r1_Driver_down(handle);
+			break;
+		}
+		case Powerwindow_main_region_Normal_operation_r1_Driver_up : {
+			powerwindow_exseq_main_region_Normal_operation_r1_Driver_up(handle);
+			break;
+		}
+		case Powerwindow_main_region_Normal_operation_r1_Passenger_up : {
+			powerwindow_exseq_main_region_Normal_operation_r1_Passenger_up(handle);
+			break;
+		}
+		default: break;
+	}
+}
+
+/* Default exit sequence for region r1 */
+static void powerwindow_exseq_main_region_Normal_operation_r1_Driver_neutral_r1(Powerwindow* handle) {
+	/* Default exit sequence for region r1 */
+	/* Handle exit of all possible states (of powerwindow.main_region.Normal_operation.r1.Driver_neutral.r1) at position 0... */
+	switch(handle->stateConfVector[ 0 ]) {
+		case Powerwindow_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation : {
+			powerwindow_exseq_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation(handle);
+			break;
+		}
+		case Powerwindow_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_down : {
+			powerwindow_exseq_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_down(handle);
+			break;
+		}
+		default: break;
+	}
+}
+
+/* The reactions of state Passenger_operation. */
+static void powerwindow_react_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation(Powerwindow* handle) {
+	/* The reactions of state Passenger_operation. */
+	if (powerwindow_check_main_region_Normal_operation_tr0_tr0(handle)) { 
+		powerwindow_effect_main_region_Normal_operation_tr0(handle);
+	}  else {
+		if (powerwindow_check_main_region_Normal_operation_r1_Driver_neutral_tr0_tr0(handle)) { 
+			powerwindow_effect_main_region_Normal_operation_r1_Driver_neutral_tr0(handle);
+		}  else {
+			if (powerwindow_check_main_region_Normal_operation_r1_Driver_neutral_tr1_tr1(handle)) { 
+				powerwindow_effect_main_region_Normal_operation_r1_Driver_neutral_tr1(handle);
+			}  else {
+				if (powerwindow_check_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation_tr0_tr0(handle)) { 
+					powerwindow_effect_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation_tr0(handle);
+				}  else {
+					if (powerwindow_check_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation_tr1_tr1(handle)) { 
+						powerwindow_effect_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation_tr1(handle);
+					} 
+				}
+			}
+		}
+	}
+}
+
+/* The reactions of state Passenger_down. */
+static void powerwindow_react_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_down(Powerwindow* handle) {
+	/* The reactions of state Passenger_down. */
+	if (powerwindow_check_main_region_Normal_operation_tr0_tr0(handle)) { 
+		powerwindow_effect_main_region_Normal_operation_tr0(handle);
+	}  else {
+		if (powerwindow_check_main_region_Normal_operation_r1_Driver_neutral_tr0_tr0(handle)) { 
+			powerwindow_effect_main_region_Normal_operation_r1_Driver_neutral_tr0(handle);
+		}  else {
+			if (powerwindow_check_main_region_Normal_operation_r1_Driver_neutral_tr1_tr1(handle)) { 
+				powerwindow_effect_main_region_Normal_operation_r1_Driver_neutral_tr1(handle);
+			}  else {
+				if (powerwindow_check_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_down_tr0_tr0(handle)) { 
+					powerwindow_effect_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_down_tr0(handle);
+				} 
+			}
+		}
+	}
+}
+
+/* The reactions of state Driver_down. */
+static void powerwindow_react_main_region_Normal_operation_r1_Driver_down(Powerwindow* handle) {
+	/* The reactions of state Driver_down. */
+	if (powerwindow_check_main_region_Normal_operation_tr0_tr0(handle)) { 
+		powerwindow_effect_main_region_Normal_operation_tr0(handle);
+	}  else {
+		if (powerwindow_check_main_region_Normal_operation_r1_Driver_down_tr0_tr0(handle)) { 
+			powerwindow_effect_main_region_Normal_operation_r1_Driver_down_tr0(handle);
+		} 
+	}
+}
+
+/* The reactions of state Driver_up. */
+static void powerwindow_react_main_region_Normal_operation_r1_Driver_up(Powerwindow* handle) {
+	/* The reactions of state Driver_up. */
+	if (powerwindow_check_main_region_Normal_operation_tr0_tr0(handle)) { 
+		powerwindow_effect_main_region_Normal_operation_tr0(handle);
+	}  else {
+		if (powerwindow_check_main_region_Normal_operation_r1_Driver_up_tr0_tr0(handle)) { 
+			powerwindow_effect_main_region_Normal_operation_r1_Driver_up_tr0(handle);
+		} 
+	}
+}
+
+/* The reactions of state Passenger_up. */
+static void powerwindow_react_main_region_Normal_operation_r1_Passenger_up(Powerwindow* handle) {
+	/* The reactions of state Passenger_up. */
+	if (powerwindow_check_main_region_Normal_operation_tr0_tr0(handle)) { 
+		powerwindow_effect_main_region_Normal_operation_tr0(handle);
+	}  else {
+		if (powerwindow_check_main_region_Normal_operation_r1_Passenger_up_tr0_tr0(handle)) { 
+			powerwindow_effect_main_region_Normal_operation_r1_Passenger_up_tr0(handle);
+		} 
+	}
+}
+
+/* The reactions of state Emergency_operation. */
+static void powerwindow_react_main_region_Emergency_operation(Powerwindow* handle) {
+	/* The reactions of state Emergency_operation. */
+	if (powerwindow_check_main_region_Emergency_operation_tr0_tr0(handle)) { 
+		powerwindow_effect_main_region_Emergency_operation_tr0(handle);
+	} 
+}
+
+/* Default react sequence for initial entry  */
+static void powerwindow_react_main_region__entry_Default(Powerwindow* handle) {
+	/* Default react sequence for initial entry  */
+	powerwindow_enseq_main_region_Normal_operation_default(handle);
+}
+
+/* Default react sequence for initial entry  */
+static void powerwindow_react_main_region_Normal_operation_r1__entry_Default(Powerwindow* handle) {
+	/* Default react sequence for initial entry  */
+	powerwindow_enseq_main_region_Normal_operation_r1_Driver_neutral_default(handle);
+}
+
+/* Default react sequence for initial entry  */
+static void powerwindow_react_main_region_Normal_operation_r1_Driver_neutral_r1__entry_Default(Powerwindow* handle) {
+	/* Default react sequence for initial entry  */
+	powerwindow_enseq_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation_default(handle);
+}
+
+

+ 124 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/PW_Controller/src/Powerwindow.h

@@ -0,0 +1,124 @@
+
+#ifndef POWERWINDOW_H_
+#define POWERWINDOW_H_
+
+#include "sc_types.h"
+
+#ifdef __cplusplus
+extern "C" { 
+#endif 
+
+/*! \file Header of the state machine 'powerwindow'.
+*/
+
+/*! Enumeration of all states */ 
+typedef enum {
+	Powerwindow_main_region_Normal_operation,
+	Powerwindow_main_region_Normal_operation_r1_Driver_neutral,
+	Powerwindow_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_operation,
+	Powerwindow_main_region_Normal_operation_r1_Driver_neutral_r1_Passenger_down,
+	Powerwindow_main_region_Normal_operation_r1_Driver_down,
+	Powerwindow_main_region_Normal_operation_r1_Driver_up,
+	Powerwindow_main_region_Normal_operation_r1_Passenger_up,
+	Powerwindow_main_region_Emergency_operation,
+	Powerwindow_last_state
+} PowerwindowStates;
+
+/*! Type definition of the data structure for the PowerwindowIfaceOutput interface scope. */
+typedef struct {
+	sc_boolean up;
+	sc_boolean down;
+} PowerwindowIfaceOutput;
+
+/*! Type definition of the data structure for the PowerwindowIfaceInput interface scope. */
+typedef struct {
+	sc_boolean obj_detected_raised;
+	sc_boolean passenger_up_raised;
+	sc_boolean passenger_down_raised;
+	sc_boolean driver_up_raised;
+	sc_boolean driver_down_raised;
+	sc_boolean stop_raised;
+} PowerwindowIfaceInput;
+
+/*! Type definition of the data structure for the PowerwindowTimeEvents interface scope. */
+typedef struct {
+	sc_boolean powerwindow_main_region_Emergency_operation_tev0_raised;
+} PowerwindowTimeEvents;
+
+
+/*! Define dimension of the state configuration vector for orthogonal states. */
+#define POWERWINDOW_MAX_ORTHOGONAL_STATES 1
+
+/*! 
+ * Type definition of the data structure for the Powerwindow state machine.
+ * This data structure has to be allocated by the client code. 
+ */
+typedef struct {
+	PowerwindowStates stateConfVector[POWERWINDOW_MAX_ORTHOGONAL_STATES];
+	sc_ushort stateConfVectorPosition; 
+	
+	PowerwindowIfaceOutput ifaceOutput;
+	PowerwindowIfaceInput ifaceInput;
+	PowerwindowTimeEvents timeEvents;
+} Powerwindow;
+
+void powerwindow_copy(Powerwindow* original, Powerwindow* copy);
+
+/*! Initializes the Powerwindow state machine data structures. Must be called before first usage.*/
+extern void powerwindow_init(Powerwindow* handle);
+
+/*! Activates the state machine */
+extern void powerwindow_enter(Powerwindow* handle);
+
+/*! Deactivates the state machine */
+extern void powerwindow_exit(Powerwindow* handle);
+
+/*! Performs a 'run to completion' step. */
+extern void powerwindow_runCycle(Powerwindow* handle);
+
+/*! Raises a time event. */
+extern void powerwindow_raiseTimeEvent(const Powerwindow* handle, sc_eventid evid);
+
+/*! Gets the value of the variable 'up' that is defined in the interface scope 'output'. */ 
+extern sc_boolean powerwindowIfaceOutput_get_up(const Powerwindow* handle);
+/*! Gets the value of the variable 'down' that is defined in the interface scope 'output'. */ 
+extern sc_boolean powerwindowIfaceOutput_get_down(const Powerwindow* handle);
+/*! Raises the in event 'obj_detected' that is defined in the interface scope 'input'. */ 
+extern void powerwindowIfaceInput_raise_obj_detected(Powerwindow* handle);
+
+/*! Raises the in event 'passenger_up' that is defined in the interface scope 'input'. */ 
+extern void powerwindowIfaceInput_raise_passenger_up(Powerwindow* handle);
+
+/*! Raises the in event 'passenger_down' that is defined in the interface scope 'input'. */ 
+extern void powerwindowIfaceInput_raise_passenger_down(Powerwindow* handle);
+
+/*! Raises the in event 'driver_up' that is defined in the interface scope 'input'. */ 
+extern void powerwindowIfaceInput_raise_driver_up(Powerwindow* handle);
+
+/*! Raises the in event 'driver_down' that is defined in the interface scope 'input'. */ 
+extern void powerwindowIfaceInput_raise_driver_down(Powerwindow* handle);
+
+/*! Raises the in event 'stop' that is defined in the interface scope 'input'. */ 
+extern void powerwindowIfaceInput_raise_stop(Powerwindow* handle);
+
+
+/*!
+ * Checks if the statemachine is active (until 2.4.1 this method was used for states).
+ * A statemachine is active if it was entered. It is inactive if it has not been entered at all or if it was exited.
+ */
+extern sc_boolean powerwindow_isActive(const Powerwindow* handle);
+
+/*!
+ * Checks if all active states are final. 
+ * If there are no active states then the statemachine is considered as inactive and this method returns false.
+ */
+extern sc_boolean powerwindow_isFinal(const Powerwindow* handle);
+
+/*! Checks if the specified state is active (until 2.4.1 the used method for states was calles isActive()). */
+extern sc_boolean powerwindow_isStateActive(const Powerwindow* handle, PowerwindowStates state);
+
+#ifdef __cplusplus
+}
+#endif 
+
+#endif /* POWERWINDOW_H_ */

+ 61 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/PW_Controller/src/PowerwindowRequired.c

@@ -0,0 +1,61 @@
+/*
+ * PowerwindowRequired.c
+ *
+ *  Created on: Jan 26, 2017
+ *      Author: Joachim
+ */
+
+
+#include "PowerwindowRequired.h"
+
+/*
+ * I only check on the bigger than compare with the double
+ * This should be changed
+ */
+
+ double relativeError(double a, double b){
+	return fabs((a - b) / a);
+}
+
+/*
+ * Helper function for absolute error
+ */
+ double absoluteError(double a, double b){
+	return fabs(a - b);
+}
+
+/*
+ * is_close function for double comparison
+ */
+ int is_close(double a, double b, double REL_TOL, double ABS_TOL){
+	return ((absoluteError(a,b)<ABS_TOL) && (relativeError(a,b)<REL_TOL));
+}
+
+void powerwindow_timeradvance(fmi_timer *theTimer, double currentTime){
+	theTimer->currentTime = currentTime;
+	if (theTimer->active && is_close(theTimer->nextTime, theTimer->currentTime,1e-4,1e-8)){
+		/* We have a timer event */
+		theTimer->callback(theTimer->handle, theTimer->evid);
+		if(theTimer->isPeriodic){
+			theTimer->nextTime = currentTime + theTimer->period;
+		}else{
+			theTimer->active = 0;
+		}
+	}
+}
+
+void powerwindow_initTimer(fmi_timer *timer){
+	thePWTimer = timer;
+}
+
+void powerwindow_setTimer(Powerwindow* handle, const sc_eventid evid, const sc_integer time_ms, const sc_boolean periodic){
+	thePWTimer->active = 1;
+	thePWTimer->handle = handle;
+	thePWTimer->evid = evid;
+	thePWTimer->period = time_ms;
+	thePWTimer->isPeriodic = periodic;
+}
+
+void powerwindow_unsetTimer(Powerwindow* handle, const sc_eventid evid){
+	thePWTimer->active = 0;
+}

+ 82 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/PW_Controller/src/PowerwindowRequired.h

@@ -0,0 +1,82 @@
+
+#ifndef POWERWINDOWREQUIRED_H_
+#define POWERWINDOWREQUIRED_H_
+
+#include "sc_types.h"
+#include "Powerwindow.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif 
+
+/*! \file This header defines prototypes for all functions that are required by the state machine implementation.
+
+This is a state machine uses time events which require access to a timing service. Thus the function prototypes:
+	- powerwindow_setTimer and
+	- powerwindow_unsetTimer
+are defined.
+
+These functions will be called during a 'run to completion step' (runCycle) of the statechart. 
+There are some constraints that have to be considered for the implementation of these functions:
+	- never call the statechart API functions from within these functions.
+	- make sure that the execution time is as short as possible.
+ 
+*/
+
+/*
+ * This is a simple hack; for a real FMI code gen for Yakindu, make this a bit more generic
+ */
+
+
+double relativeError(double a, double b);
+
+/*
+* Helper function for absolute error
+*/
+double absoluteError(double a, double b);
+
+/*
+* is_close function for double comparison
+*/
+int is_close(double a, double b, double REL_TOL, double ABS_TOL);
+
+typedef struct{
+	double nextTime;
+	double currentTime;
+	Powerwindow * handle;
+	sc_eventid evid;
+	int period;
+	int isPeriodic;
+	int active;
+	void (*callback) (Powerwindow*, sc_eventid evid);
+}fmi_timer;
+
+fmi_timer *thePWTimer;
+
+void powerwindow_timeradvance(fmi_timer *theTimer, double currentTime);
+void powerwindow_initTimer(fmi_timer *timer);
+/*!
+ * This is a timed state machine that requires timer services
+ */ 
+
+/*! This function has to set up timers for the time events that are required by the state machine. */
+/*! 
+	This function will be called for each time event that is relevant for a state when a state will be entered.
+	\param evid An unique identifier of the event.
+	\time_ms The time in milli seconds
+	\periodic Indicates the the time event must be raised periodically until the timer is unset 
+*/
+extern void powerwindow_setTimer(Powerwindow* handle, const sc_eventid evid, const sc_integer time_ms, const sc_boolean periodic);
+
+/*! This function has to unset timers for the time events that are required by the state machine. */
+/*! 
+	This function will be called for each time event taht is relevant for a state when a state will be left.
+	\param evid An unique identifier of the event.
+*/
+extern void powerwindow_unsetTimer(Powerwindow* handle, const sc_eventid evid);
+
+#ifdef __cplusplus
+}
+#endif 
+
+#endif /* POWERWINDOWREQUIRED_H_ */

+ 247 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/PW_Controller/src/fmi2/fmi2FunctionTypes.h

@@ -0,0 +1,247 @@
+#ifndef fmi2FunctionTypes_h
+#define fmi2FunctionTypes_h
+
+#include "fmi2TypesPlatform.h"
+
+/* This header file must be utilized when compiling an FMU or an FMI master.
+   It declares data and function types for FMI 2.0
+
+   Revisions:
+   - Apr.  9, 2014: all prefixes "fmi" renamed to "fmi2" (decision from April 8)
+   - Apr.  3, 2014: Added #include <stddef.h> for size_t definition
+   - Mar. 27, 2014: Added #include "fmiTypesPlatform.h" (#179)
+   - Mar. 26, 2014: Introduced function argument "void" for the functions (#171)
+                      fmiGetTypesPlatformTYPE and fmiGetVersionTYPE
+   - Oct. 11, 2013: Functions of ModelExchange and CoSimulation merged:
+                      fmiInstantiateModelTYPE , fmiInstantiateSlaveTYPE  -> fmiInstantiateTYPE
+                      fmiFreeModelInstanceTYPE, fmiFreeSlaveInstanceTYPE -> fmiFreeInstanceTYPE
+                      fmiEnterModelInitializationModeTYPE, fmiEnterSlaveInitializationModeTYPE -> fmiEnterInitializationModeTYPE
+                      fmiExitModelInitializationModeTYPE , fmiExitSlaveInitializationModeTYPE  -> fmiExitInitializationModeTYPE
+                      fmiTerminateModelTYPE , fmiTerminateSlaveTYPE  -> fmiTerminate
+                      fmiResetSlave -> fmiReset (now also for ModelExchange and not only for CoSimulation)
+                    Functions renamed
+                      fmiUpdateDiscreteStatesTYPE -> fmiNewDiscreteStatesTYPE
+                    Renamed elements of the enumeration fmiEventInfo
+                      upcomingTimeEvent             -> nextEventTimeDefined // due to generic naming scheme: varDefined + var
+                      newUpdateDiscreteStatesNeeded -> newDiscreteStatesNeeded;
+   - June 13, 2013: Changed type fmiEventInfo
+                    Functions removed:
+                       fmiInitializeModelTYPE
+                       fmiEventUpdateTYPE
+                       fmiCompletedEventIterationTYPE
+                       fmiInitializeSlaveTYPE
+                    Functions added:
+                       fmiEnterModelInitializationModeTYPE
+                       fmiExitModelInitializationModeTYPE
+                       fmiEnterEventModeTYPE
+                       fmiUpdateDiscreteStatesTYPE
+                       fmiEnterContinuousTimeModeTYPE
+                       fmiEnterSlaveInitializationModeTYPE;
+                       fmiExitSlaveInitializationModeTYPE;
+   - Feb. 17, 2013: Added third argument to fmiCompletedIntegratorStepTYPE
+                    Changed function name "fmiTerminateType" to "fmiTerminateModelType" (due to #113)
+                    Changed function name "fmiGetNominalContinuousStateTYPE" to
+                                          "fmiGetNominalsOfContinuousStatesTYPE"
+                    Removed fmiGetStateValueReferencesTYPE.
+   - Nov. 14, 2011: First public Version
+
+
+   Copyright (C) 2011 MODELISAR consortium,
+               2012-2013 Modelica Association Project "FMI"
+               All rights reserved.
+   This file is licensed by the copyright holders under the BSD 2-Clause License
+   (http://www.opensource.org/licenses/bsd-license.html):
+
+   ----------------------------------------------------------------------------
+   Redistribution and use in source and binary forms, with or without
+   modification, are permitted provided that the following conditions are met:
+
+   - Redistributions of source code must retain the above copyright notice,
+     this list of conditions and the following disclaimer.
+   - Redistributions in binary form must reproduce the above copyright notice,
+     this list of conditions and the following disclaimer in the documentation
+     and/or other materials provided with the distribution.
+   - Neither the name of the copyright holders nor the names of its
+     contributors may be used to endorse or promote products derived
+     from this software without specific prior written permission.
+
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+   TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+   PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
+   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+   OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+   OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+   ----------------------------------------------------------------------------
+
+   with the extension:
+
+   You may distribute or publicly perform any modification only under the
+   terms of this license.
+   (Note, this means that if you distribute a modified file,
+    the modified file must also be provided under this license).
+*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* make sure all compiler use the same alignment policies for structures */
+#if defined _MSC_VER || defined __GNUC__
+#pragma pack(push,8)
+#endif
+
+/* Include stddef.h, in order that size_t etc. is defined */
+#include <stddef.h>
+
+
+/* Type definitions */
+typedef enum {
+    fmi2OK,
+    fmi2Warning,
+    fmi2Discard,
+    fmi2Error,
+    fmi2Fatal,
+    fmi2Pending
+} fmi2Status;
+
+typedef enum {
+    fmi2ModelExchange,
+    fmi2CoSimulation
+} fmi2Type;
+
+typedef enum {
+    fmi2DoStepStatus,
+    fmi2PendingStatus,
+    fmi2LastSuccessfulTime,
+    fmi2Terminated
+} fmi2StatusKind;
+
+typedef void      (*fmi2CallbackLogger)        (fmi2ComponentEnvironment, fmi2String, fmi2Status, fmi2String, fmi2String, ...);
+typedef void*     (*fmi2CallbackAllocateMemory)(size_t, size_t);
+typedef void      (*fmi2CallbackFreeMemory)    (void*);
+typedef void      (*fmi2StepFinished)          (fmi2ComponentEnvironment, fmi2Status);
+
+typedef struct {
+   const fmi2CallbackLogger         logger;
+   const fmi2CallbackAllocateMemory allocateMemory;
+   const fmi2CallbackFreeMemory     freeMemory;
+   const fmi2StepFinished           stepFinished;
+   const fmi2ComponentEnvironment   componentEnvironment;
+} fmi2CallbackFunctions;
+
+typedef struct {
+   fmi2Boolean newDiscreteStatesNeeded;
+   fmi2Boolean terminateSimulation;
+   fmi2Boolean nominalsOfContinuousStatesChanged;
+   fmi2Boolean valuesOfContinuousStatesChanged;
+   fmi2Boolean nextEventTimeDefined;
+   fmi2Real    nextEventTime;
+} fmi2EventInfo;
+
+
+/* reset alignment policy to the one set before reading this file */
+#if defined _MSC_VER || defined __GNUC__
+#pragma pack(pop)
+#endif
+
+
+/* Define fmi2 function pointer types to simplify dynamic loading */
+
+/***************************************************
+Types for Common Functions
+****************************************************/
+
+/* Inquire version numbers of header files and setting logging status */
+   typedef const char* fmi2GetTypesPlatformTYPE(void);
+   typedef const char* fmi2GetVersionTYPE(void);
+   typedef fmi2Status  fmi2SetDebugLoggingTYPE(fmi2Component, fmi2Boolean, size_t, const fmi2String[]);
+
+/* Creation and destruction of FMU instances and setting debug status */
+   typedef fmi2Component fmi2InstantiateTYPE (fmi2String, fmi2Type, fmi2String, fmi2String, const fmi2CallbackFunctions*, fmi2Boolean, fmi2Boolean);
+   typedef void          fmi2FreeInstanceTYPE(fmi2Component);
+
+/* Enter and exit initialization mode, terminate and reset */
+   typedef fmi2Status fmi2SetupExperimentTYPE        (fmi2Component, fmi2Boolean, fmi2Real, fmi2Real, fmi2Boolean, fmi2Real);
+   typedef fmi2Status fmi2EnterInitializationModeTYPE(fmi2Component);
+   typedef fmi2Status fmi2ExitInitializationModeTYPE (fmi2Component);
+   typedef fmi2Status fmi2TerminateTYPE              (fmi2Component);
+   typedef fmi2Status fmi2ResetTYPE                  (fmi2Component);
+
+/* Getting and setting variable values */
+   typedef fmi2Status fmi2GetRealTYPE   (fmi2Component, const fmi2ValueReference[], size_t, fmi2Real   []);
+   typedef fmi2Status fmi2GetIntegerTYPE(fmi2Component, const fmi2ValueReference[], size_t, fmi2Integer[]);
+   typedef fmi2Status fmi2GetBooleanTYPE(fmi2Component, const fmi2ValueReference[], size_t, fmi2Boolean[]);
+   typedef fmi2Status fmi2GetStringTYPE (fmi2Component, const fmi2ValueReference[], size_t, fmi2String []);
+
+   typedef fmi2Status fmi2SetRealTYPE   (fmi2Component, const fmi2ValueReference[], size_t, const fmi2Real   []);
+   typedef fmi2Status fmi2SetIntegerTYPE(fmi2Component, const fmi2ValueReference[], size_t, const fmi2Integer[]);
+   typedef fmi2Status fmi2SetBooleanTYPE(fmi2Component, const fmi2ValueReference[], size_t, const fmi2Boolean[]);
+   typedef fmi2Status fmi2SetStringTYPE (fmi2Component, const fmi2ValueReference[], size_t, const fmi2String []);
+
+/* Getting and setting the internal FMU state */
+   typedef fmi2Status fmi2GetFMUstateTYPE           (fmi2Component, fmi2FMUstate*);
+   typedef fmi2Status fmi2SetFMUstateTYPE           (fmi2Component, fmi2FMUstate);
+   typedef fmi2Status fmi2FreeFMUstateTYPE          (fmi2Component, fmi2FMUstate*);
+   typedef fmi2Status fmi2SerializedFMUstateSizeTYPE(fmi2Component, fmi2FMUstate, size_t*);
+   typedef fmi2Status fmi2SerializeFMUstateTYPE     (fmi2Component, fmi2FMUstate, fmi2Byte[], size_t);
+   typedef fmi2Status fmi2DeSerializeFMUstateTYPE   (fmi2Component, const fmi2Byte[], size_t, fmi2FMUstate*);
+
+/* Getting partial derivatives */
+   typedef fmi2Status fmi2GetDirectionalDerivativeTYPE(fmi2Component, const fmi2ValueReference[], size_t,
+                                                                   const fmi2ValueReference[], size_t,
+                                                                   const fmi2Real[], fmi2Real[]);
+
+/***************************************************
+Types for Functions for FMI2 for Model Exchange
+****************************************************/
+
+/* Enter and exit the different modes */
+   typedef fmi2Status fmi2EnterEventModeTYPE         (fmi2Component);
+   typedef fmi2Status fmi2NewDiscreteStatesTYPE      (fmi2Component, fmi2EventInfo*);
+   typedef fmi2Status fmi2EnterContinuousTimeModeTYPE(fmi2Component);
+   typedef fmi2Status fmi2CompletedIntegratorStepTYPE(fmi2Component, fmi2Boolean, fmi2Boolean*, fmi2Boolean*);
+
+/* Providing independent variables and re-initialization of caching */
+   typedef fmi2Status fmi2SetTimeTYPE            (fmi2Component, fmi2Real);
+   typedef fmi2Status fmi2SetContinuousStatesTYPE(fmi2Component, const fmi2Real[], size_t);
+
+/* Evaluation of the model equations */
+   typedef fmi2Status fmi2GetDerivativesTYPE               (fmi2Component, fmi2Real[], size_t);
+#ifdef FMU_EXPERIMENTAL
+   typedef fmi2Status fmi2GetSpecificDerivativesTYPE       (fmi2Component, fmi2Real[], const fmi2ValueReference [], size_t);
+#endif
+
+   typedef fmi2Status fmi2GetEventIndicatorsTYPE           (fmi2Component, fmi2Real[], size_t);
+   typedef fmi2Status fmi2GetContinuousStatesTYPE          (fmi2Component, fmi2Real[], size_t);
+   typedef fmi2Status fmi2GetNominalsOfContinuousStatesTYPE(fmi2Component, fmi2Real[], size_t);
+
+
+/***************************************************
+Types for Functions for FMI2 for Co-Simulation
+****************************************************/
+
+/* Simulating the slave */
+   typedef fmi2Status fmi2SetRealInputDerivativesTYPE (fmi2Component, const fmi2ValueReference [], size_t, const fmi2Integer [], const fmi2Real []);
+   typedef fmi2Status fmi2GetRealOutputDerivativesTYPE(fmi2Component, const fmi2ValueReference [], size_t, const fmi2Integer [], fmi2Real []);
+
+   typedef fmi2Status fmi2DoStepTYPE     (fmi2Component, fmi2Real, fmi2Real, fmi2Boolean);
+   typedef fmi2Status fmi2CancelStepTYPE (fmi2Component);
+
+/* Inquire slave status */
+   typedef fmi2Status fmi2GetStatusTYPE       (fmi2Component, const fmi2StatusKind, fmi2Status* );
+   typedef fmi2Status fmi2GetRealStatusTYPE   (fmi2Component, const fmi2StatusKind, fmi2Real*   );
+   typedef fmi2Status fmi2GetIntegerStatusTYPE(fmi2Component, const fmi2StatusKind, fmi2Integer*);
+   typedef fmi2Status fmi2GetBooleanStatusTYPE(fmi2Component, const fmi2StatusKind, fmi2Boolean*);
+   typedef fmi2Status fmi2GetStringStatusTYPE (fmi2Component, const fmi2StatusKind, fmi2String* );
+
+
+#ifdef __cplusplus
+}  /* end of extern "C" { */
+#endif
+
+#endif /* fmi2FunctionTypes_h */

+ 339 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/PW_Controller/src/fmi2/fmi2Functions.h

@@ -0,0 +1,339 @@
+#ifndef fmi2Functions_h
+#define fmi2Functions_h
+
+/* This header file must be utilized when compiling a FMU.
+   It defines all functions of the
+         FMI 2.0 Model Exchange and Co-Simulation Interface.
+
+   In order to have unique function names even if several FMUs
+   are compiled together (e.g. for embedded systems), every "real" function name
+   is constructed by prepending the function name by "FMI2_FUNCTION_PREFIX".
+   Therefore, the typical usage is:
+
+      #define FMI2_FUNCTION_PREFIX MyModel_
+      #include "fmi2Functions.h"
+
+   As a result, a function that is defined as "fmi2GetDerivatives" in this header file,
+   is actually getting the name "MyModel_fmi2GetDerivatives".
+
+   This only holds if the FMU is shipped in C source code, or is compiled in a
+   static link library. For FMUs compiled in a DLL/sharedObject, the "actual" function
+   names are used and "FMI2_FUNCTION_PREFIX" must not be defined.
+
+   Revisions:
+   - Apr.  9, 2014: all prefixes "fmi" renamed to "fmi2" (decision from April 8)
+   - Mar. 26, 2014: FMI_Export set to empty value if FMI_Export and FMI_FUNCTION_PREFIX
+                    are not defined (#173)
+   - Oct. 11, 2013: Functions of ModelExchange and CoSimulation merged:
+                      fmiInstantiateModel , fmiInstantiateSlave  -> fmiInstantiate
+                      fmiFreeModelInstance, fmiFreeSlaveInstance -> fmiFreeInstance
+                      fmiEnterModelInitializationMode, fmiEnterSlaveInitializationMode -> fmiEnterInitializationMode
+                      fmiExitModelInitializationMode , fmiExitSlaveInitializationMode  -> fmiExitInitializationMode
+                      fmiTerminateModel, fmiTerminateSlave  -> fmiTerminate
+                      fmiResetSlave -> fmiReset (now also for ModelExchange and not only for CoSimulation)
+                    Functions renamed:
+                      fmiUpdateDiscreteStates -> fmiNewDiscreteStates
+   - June 13, 2013: Functions removed:
+                       fmiInitializeModel
+                       fmiEventUpdate
+                       fmiCompletedEventIteration
+                       fmiInitializeSlave
+                    Functions added:
+                       fmiEnterModelInitializationMode
+                       fmiExitModelInitializationMode
+                       fmiEnterEventMode
+                       fmiUpdateDiscreteStates
+                       fmiEnterContinuousTimeMode
+                       fmiEnterSlaveInitializationMode;
+                       fmiExitSlaveInitializationMode;
+   - Feb. 17, 2013: Portability improvements:
+                       o DllExport changed to FMI_Export
+                       o FUNCTION_PREFIX changed to FMI_FUNCTION_PREFIX
+                       o Allow undefined FMI_FUNCTION_PREFIX (meaning no prefix is used)
+                    Changed function name "fmiTerminate" to "fmiTerminateModel" (due to #113)
+                    Changed function name "fmiGetNominalContinuousState" to
+                                          "fmiGetNominalsOfContinuousStates"
+                    Removed fmiGetStateValueReferences.
+   - Nov. 14, 2011: Adapted to FMI 2.0:
+                       o Split into two files (fmiFunctions.h, fmiTypes.h) in order
+                         that code that dynamically loads an FMU can directly
+                         utilize the header files).
+                       o Added C++ encapsulation of C-part, in order that the header
+                         file can be directly utilized in C++ code.
+                       o fmiCallbackFunctions is passed as pointer to fmiInstantiateXXX
+                       o stepFinished within fmiCallbackFunctions has as first
+                         argument "fmiComponentEnvironment" and not "fmiComponent".
+                       o New functions to get and set the complete FMU state
+                         and to compute partial derivatives.
+   - Nov.  4, 2010: Adapted to specification text:
+                       o fmiGetModelTypesPlatform renamed to fmiGetTypesPlatform
+                       o fmiInstantiateSlave: Argument GUID     replaced by fmuGUID
+                                              Argument mimetype replaced by mimeType
+                       o tabs replaced by spaces
+   - Oct. 16, 2010: Functions for FMI for Co-simulation added
+   - Jan. 20, 2010: stateValueReferencesChanged added to struct fmiEventInfo (ticket #27)
+                    (by M. Otter, DLR)
+                    Added WIN32 pragma to define the struct layout (ticket #34)
+                    (by J. Mauss, QTronic)
+   - Jan.  4, 2010: Removed argument intermediateResults from fmiInitialize
+                    Renamed macro fmiGetModelFunctionsVersion to fmiGetVersion
+                    Renamed macro fmiModelFunctionsVersion to fmiVersion
+                    Replaced fmiModel by fmiComponent in decl of fmiInstantiateModel
+                    (by J. Mauss, QTronic)
+   - Dec. 17, 2009: Changed extension "me" to "fmi" (by Martin Otter, DLR).
+   - Dez. 14, 2009: Added eventInfo to meInitialize and added
+                    meGetNominalContinuousStates (by Martin Otter, DLR)
+   - Sept. 9, 2009: Added DllExport (according to Peter Nilsson's suggestion)
+                    (by A. Junghanns, QTronic)
+   - Sept. 9, 2009: Changes according to FMI-meeting on July 21:
+                    meInquireModelTypesVersion     -> meGetModelTypesPlatform
+                    meInquireModelFunctionsVersion -> meGetModelFunctionsVersion
+                    meSetStates                    -> meSetContinuousStates
+                    meGetStates                    -> meGetContinuousStates
+                    removal of meInitializeModelClass
+                    removal of meGetTime
+                    change of arguments of meInstantiateModel
+                    change of arguments of meCompletedIntegratorStep
+                    (by Martin Otter, DLR):
+   - July 19, 2009: Added "me" as prefix to file names (by Martin Otter, DLR).
+   - March 2, 2009: Changed function definitions according to the last design
+                    meeting with additional improvements (by Martin Otter, DLR).
+   - Dec. 3 , 2008: First version by Martin Otter (DLR) and Hans Olsson (Dynasim).
+
+   Copyright (C) 2008-2011 MODELISAR consortium,
+               2012-2013 Modelica Association Project "FMI"
+               All rights reserved.
+   This file is licensed by the copyright holders under the BSD 2-Clause License
+   (http://www.opensource.org/licenses/bsd-license.html):
+
+   ----------------------------------------------------------------------------
+   Redistribution and use in source and binary forms, with or without
+   modification, are permitted provided that the following conditions are met:
+
+   - Redistributions of source code must retain the above copyright notice,
+     this list of conditions and the following disclaimer.
+   - Redistributions in binary form must reproduce the above copyright notice,
+     this list of conditions and the following disclaimer in the documentation
+     and/or other materials provided with the distribution.
+   - Neither the name of the copyright holders nor the names of its
+     contributors may be used to endorse or promote products derived
+     from this software without specific prior written permission.
+
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+   TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+   PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
+   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+   OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+   OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+   ----------------------------------------------------------------------------
+
+   with the extension:
+
+   You may distribute or publicly perform any modification only under the
+   terms of this license.
+   (Note, this means that if you distribute a modified file,
+    the modified file must also be provided under this license).
+*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "fmi2TypesPlatform.h"
+#include "fmi2FunctionTypes.h"
+#include <stdlib.h>
+
+
+/*
+  Export FMI2 API functions on Windows and under GCC.
+  If custom linking is desired then the FMI2_Export must be
+  defined before including this file. For instance,
+  it may be set to __declspec(dllimport).
+*/
+#if !defined(FMI2_Export)
+  #if !defined(FMI2_FUNCTION_PREFIX)
+    #if defined _WIN32 || defined __CYGWIN__
+     /* Note: both gcc & MSVC on Windows support this syntax. */
+        #define FMI2_Export __declspec(dllexport)
+    #else
+      #if __GNUC__ >= 4
+        #define FMI2_Export __attribute__ ((visibility ("default")))
+      #else
+        #define FMI2_Export
+      #endif
+    #endif
+  #else
+    #define FMI2_Export
+  #endif
+#endif
+
+/* Macros to construct the real function name
+   (prepend function name by FMI2_FUNCTION_PREFIX) */
+#if defined(FMI2_FUNCTION_PREFIX)
+  #define fmi2Paste(a,b)     a ## b
+  #define fmi2PasteB(a,b)    fmi2Paste(a,b)
+  #define fmi2FullName(name) fmi2PasteB(FMI2_FUNCTION_PREFIX, name)
+#else
+  #define fmi2FullName(name) name
+#endif
+
+/***************************************************
+Common Functions
+****************************************************/
+#define fmi2GetTypesPlatform         fmi2FullName(fmi2GetTypesPlatform)
+#define fmi2GetVersion               fmi2FullName(fmi2GetVersion)
+#define fmi2SetDebugLogging          fmi2FullName(fmi2SetDebugLogging)
+#define fmi2Instantiate              fmi2FullName(fmi2Instantiate)
+#define fmi2FreeInstance             fmi2FullName(fmi2FreeInstance)
+#define fmi2SetupExperiment          fmi2FullName(fmi2SetupExperiment)
+#define fmi2EnterInitializationMode  fmi2FullName(fmi2EnterInitializationMode)
+#define fmi2ExitInitializationMode   fmi2FullName(fmi2ExitInitializationMode)
+#define fmi2Terminate                fmi2FullName(fmi2Terminate)
+#define fmi2Reset                    fmi2FullName(fmi2Reset)
+#define fmi2GetReal                  fmi2FullName(fmi2GetReal)
+#define fmi2GetInteger               fmi2FullName(fmi2GetInteger)
+#define fmi2GetBoolean               fmi2FullName(fmi2GetBoolean)
+#define fmi2GetString                fmi2FullName(fmi2GetString)
+#define fmi2SetReal                  fmi2FullName(fmi2SetReal)
+#define fmi2SetInteger               fmi2FullName(fmi2SetInteger)
+#define fmi2SetBoolean               fmi2FullName(fmi2SetBoolean)
+#define fmi2SetString                fmi2FullName(fmi2SetString)
+#define fmi2GetFMUstate              fmi2FullName(fmi2GetFMUstate)
+#define fmi2SetFMUstate              fmi2FullName(fmi2SetFMUstate)
+#define fmi2FreeFMUstate             fmi2FullName(fmi2FreeFMUstate)
+#define fmi2SerializedFMUstateSize   fmi2FullName(fmi2SerializedFMUstateSize)
+#define fmi2SerializeFMUstate        fmi2FullName(fmi2SerializeFMUstate)
+#define fmi2DeSerializeFMUstate      fmi2FullName(fmi2DeSerializeFMUstate)
+#define fmi2GetDirectionalDerivative fmi2FullName(fmi2GetDirectionalDerivative)
+
+
+/***************************************************
+Functions for FMI2 for Model Exchange
+****************************************************/
+#define fmi2EnterEventMode                fmi2FullName(fmi2EnterEventMode)
+#define fmi2NewDiscreteStates             fmi2FullName(fmi2NewDiscreteStates)
+#define fmi2EnterContinuousTimeMode       fmi2FullName(fmi2EnterContinuousTimeMode)
+#define fmi2CompletedIntegratorStep       fmi2FullName(fmi2CompletedIntegratorStep)
+#define fmi2SetTime                       fmi2FullName(fmi2SetTime)
+#define fmi2SetContinuousStates           fmi2FullName(fmi2SetContinuousStates)
+#define fmi2GetDerivatives                fmi2FullName(fmi2GetDerivatives)
+#ifdef FMU_EXPERIMENTAL
+#define fmi2GetSpecificDerivatives        fmi2FullName(fmi2GetSpecificDerivatives)
+#endif
+#define fmi2GetEventIndicators            fmi2FullName(fmi2GetEventIndicators)
+#define fmi2GetContinuousStates           fmi2FullName(fmi2GetContinuousStates)
+#define fmi2GetNominalsOfContinuousStates fmi2FullName(fmi2GetNominalsOfContinuousStates)
+
+
+/***************************************************
+Functions for FMI2 for Co-Simulation
+****************************************************/
+#define fmi2SetRealInputDerivatives      fmi2FullName(fmi2SetRealInputDerivatives)
+#define fmi2GetRealOutputDerivatives     fmi2FullName(fmi2GetRealOutputDerivatives)
+#define fmi2DoStep                       fmi2FullName(fmi2DoStep)
+#define fmi2CancelStep                   fmi2FullName(fmi2CancelStep)
+#define fmi2GetStatus                    fmi2FullName(fmi2GetStatus)
+#define fmi2GetRealStatus                fmi2FullName(fmi2GetRealStatus)
+#define fmi2GetIntegerStatus             fmi2FullName(fmi2GetIntegerStatus)
+#define fmi2GetBooleanStatus             fmi2FullName(fmi2GetBooleanStatus)
+#define fmi2GetStringStatus              fmi2FullName(fmi2GetStringStatus)
+
+/* Version number */
+#define fmi2Version "2.0"
+
+
+/***************************************************
+Common Functions
+****************************************************/
+
+/* Inquire version numbers of header files */
+   FMI2_Export fmi2GetTypesPlatformTYPE fmi2GetTypesPlatform;
+   FMI2_Export fmi2GetVersionTYPE       fmi2GetVersion;
+   FMI2_Export fmi2SetDebugLoggingTYPE  fmi2SetDebugLogging;
+
+/* Creation and destruction of FMU instances */
+   FMI2_Export fmi2InstantiateTYPE  fmi2Instantiate;
+   FMI2_Export fmi2FreeInstanceTYPE fmi2FreeInstance;
+
+/* Enter and exit initialization mode, terminate and reset */
+   FMI2_Export fmi2SetupExperimentTYPE         fmi2SetupExperiment;
+   FMI2_Export fmi2EnterInitializationModeTYPE fmi2EnterInitializationMode;
+   FMI2_Export fmi2ExitInitializationModeTYPE  fmi2ExitInitializationMode;
+   FMI2_Export fmi2TerminateTYPE               fmi2Terminate;
+   FMI2_Export fmi2ResetTYPE                   fmi2Reset;
+
+/* Getting and setting variables values */
+   FMI2_Export fmi2GetRealTYPE    fmi2GetReal;
+   FMI2_Export fmi2GetIntegerTYPE fmi2GetInteger;
+   FMI2_Export fmi2GetBooleanTYPE fmi2GetBoolean;
+   FMI2_Export fmi2GetStringTYPE  fmi2GetString;
+
+   FMI2_Export fmi2SetRealTYPE    fmi2SetReal;
+   FMI2_Export fmi2SetIntegerTYPE fmi2SetInteger;
+   FMI2_Export fmi2SetBooleanTYPE fmi2SetBoolean;
+   FMI2_Export fmi2SetStringTYPE  fmi2SetString;
+
+/* Getting and setting the internal FMU state */
+   FMI2_Export fmi2GetFMUstateTYPE            fmi2GetFMUstate;
+   FMI2_Export fmi2SetFMUstateTYPE            fmi2SetFMUstate;
+   FMI2_Export fmi2FreeFMUstateTYPE           fmi2FreeFMUstate;
+   FMI2_Export fmi2SerializedFMUstateSizeTYPE fmi2SerializedFMUstateSize;
+   FMI2_Export fmi2SerializeFMUstateTYPE      fmi2SerializeFMUstate;
+   FMI2_Export fmi2DeSerializeFMUstateTYPE    fmi2DeSerializeFMUstate;
+
+/* Getting partial derivatives */
+   FMI2_Export fmi2GetDirectionalDerivativeTYPE fmi2GetDirectionalDerivative;
+
+
+/***************************************************
+Functions for FMI2 for Model Exchange
+****************************************************/
+
+/* Enter and exit the different modes */
+   FMI2_Export fmi2EnterEventModeTYPE               fmi2EnterEventMode;
+   FMI2_Export fmi2NewDiscreteStatesTYPE            fmi2NewDiscreteStates;
+   FMI2_Export fmi2EnterContinuousTimeModeTYPE      fmi2EnterContinuousTimeMode;
+   FMI2_Export fmi2CompletedIntegratorStepTYPE      fmi2CompletedIntegratorStep;
+
+/* Providing independent variables and re-initialization of caching */
+   FMI2_Export fmi2SetTimeTYPE             fmi2SetTime;
+   FMI2_Export fmi2SetContinuousStatesTYPE fmi2SetContinuousStates;
+
+/* Evaluation of the model equations */
+   FMI2_Export fmi2GetDerivativesTYPE                fmi2GetDerivatives;
+#ifdef FMU_EXPERIMENTAL
+   FMI2_Export fmi2GetSpecificDerivativesTYPE        fmi2GetSpecificDerivatives;
+#endif
+   FMI2_Export fmi2GetEventIndicatorsTYPE            fmi2GetEventIndicators;
+   FMI2_Export fmi2GetContinuousStatesTYPE           fmi2GetContinuousStates;
+   FMI2_Export fmi2GetNominalsOfContinuousStatesTYPE fmi2GetNominalsOfContinuousStates;
+
+
+/***************************************************
+Functions for FMI2 for Co-Simulation
+****************************************************/
+
+/* Simulating the slave */
+   FMI2_Export fmi2SetRealInputDerivativesTYPE  fmi2SetRealInputDerivatives;
+   FMI2_Export fmi2GetRealOutputDerivativesTYPE fmi2GetRealOutputDerivatives;
+
+   FMI2_Export fmi2DoStepTYPE     fmi2DoStep;
+   FMI2_Export fmi2CancelStepTYPE fmi2CancelStep;
+
+/* Inquire slave status */
+   FMI2_Export fmi2GetStatusTYPE        fmi2GetStatus;
+   FMI2_Export fmi2GetRealStatusTYPE    fmi2GetRealStatus;
+   FMI2_Export fmi2GetIntegerStatusTYPE fmi2GetIntegerStatus;
+   FMI2_Export fmi2GetBooleanStatusTYPE fmi2GetBooleanStatus;
+   FMI2_Export fmi2GetStringStatusTYPE  fmi2GetStringStatus;
+
+#ifdef __cplusplus
+}  /* end of extern "C" { */
+#endif
+
+#endif /* fmi2Functions_h */

+ 115 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/PW_Controller/src/fmi2/fmi2TypesPlatform.h

@@ -0,0 +1,115 @@
+#ifndef fmi2TypesPlatform_h
+#define fmi2TypesPlatform_h
+
+/* Standard header file to define the argument types of the
+   functions of the Functional Mock-up Interface 2.0.
+   This header file must be utilized both by the model and
+   by the simulation engine.
+
+   Revisions:
+   - Apr.  9, 2014: all prefixes "fmi" renamed to "fmi2" (decision from April 8)
+   - Mar   31, 2014: New datatype fmiChar introduced.
+   - Feb.  17, 2013: Changed fmiTypesPlatform from "standard32" to "default".
+                     Removed fmiUndefinedValueReference since no longer needed
+                     (because every state is defined in ScalarVariables).
+   - March 20, 2012: Renamed from fmiPlatformTypes.h to fmiTypesPlatform.h
+   - Nov.  14, 2011: Use the header file "fmiPlatformTypes.h" for FMI 2.0
+                     both for "FMI for model exchange" and for "FMI for co-simulation"
+                     New types "fmiComponentEnvironment", "fmiState", and "fmiByte".
+                     The implementation of "fmiBoolean" is change from "char" to "int".
+                     The #define "fmiPlatform" changed to "fmiTypesPlatform"
+                     (in order that #define and function call are consistent)
+   - Oct.   4, 2010: Renamed header file from "fmiModelTypes.h" to fmiPlatformTypes.h"
+                     for the co-simulation interface
+   - Jan.   4, 2010: Renamed meModelTypes_h to fmiModelTypes_h (by Mauss, QTronic)
+   - Dec.  21, 2009: Changed "me" to "fmi" and "meModel" to "fmiComponent"
+                     according to meeting on Dec. 18 (by Martin Otter, DLR)
+   - Dec.   6, 2009: Added meUndefinedValueReference (by Martin Otter, DLR)
+   - Sept.  9, 2009: Changes according to FMI-meeting on July 21:
+                     Changed "version" to "platform", "standard" to "standard32",
+                     Added a precise definition of "standard32" as comment
+                     (by Martin Otter, DLR)
+   - July  19, 2009: Added "me" as prefix to file names, added meTrue/meFalse,
+                     and changed meValueReferenced from int to unsigned int
+                     (by Martin Otter, DLR).
+   - March  2, 2009: Moved enums and function pointer definitions to
+                     ModelFunctions.h (by Martin Otter, DLR).
+   - Dec.  3, 2008 : First version by Martin Otter (DLR) and
+                     Hans Olsson (Dynasim).
+
+
+   Copyright (C) 2008-2011 MODELISAR consortium,
+               2012-2013 Modelica Association Project "FMI"
+               All rights reserved.
+   This file is licensed by the copyright holders under the BSD 2-Clause License
+   (http://www.opensource.org/licenses/bsd-license.html):
+
+   ----------------------------------------------------------------------------
+   Redistribution and use in source and binary forms, with or without
+   modification, are permitted provided that the following conditions are met:
+
+   - Redistributions of source code must retain the above copyright notice,
+     this list of conditions and the following disclaimer.
+   - Redistributions in binary form must reproduce the above copyright notice,
+     this list of conditions and the following disclaimer in the documentation
+     and/or other materials provided with the distribution.
+   - Neither the name of the copyright holders nor the names of its
+     contributors may be used to endorse or promote products derived
+     from this software without specific prior written permission.
+
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+   TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+   PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
+   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+   OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+   OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+   ----------------------------------------------------------------------------
+
+   with the extension:
+
+   You may distribute or publicly perform any modification only under the
+   terms of this license.
+   (Note, this means that if you distribute a modified file,
+    the modified file must also be provided under this license).
+*/
+
+/* Platform (unique identification of this header file) */
+#define fmi2TypesPlatform "default"
+
+/* Type definitions of variables passed as arguments
+   Version "default" means:
+
+   fmi2Component           : an opaque object pointer
+   fmi2ComponentEnvironment: an opaque object pointer
+   fmi2FMUstate            : an opaque object pointer
+   fmi2ValueReference      : handle to the value of a variable
+   fmi2Real                : double precision floating-point data type
+   fmi2Integer             : basic signed integer data type
+   fmi2Boolean             : basic signed integer data type
+   fmi2Char                : character data type
+   fmi2String              : a pointer to a vector of fmi2Char characters
+                             ('\0' terminated, UTF8 encoded)
+   fmi2Byte                : smallest addressable unit of the machine, typically one byte.
+*/
+   typedef void*           fmi2Component;               /* Pointer to FMU instance       */
+   typedef void*           fmi2ComponentEnvironment;    /* Pointer to FMU environment    */
+   typedef void*           fmi2FMUstate;                /* Pointer to internal FMU state */
+   typedef unsigned int    fmi2ValueReference;
+   typedef double          fmi2Real   ;
+   typedef int             fmi2Integer;
+   typedef int             fmi2Boolean;
+   typedef char            fmi2Char;
+   typedef const fmi2Char* fmi2String;
+   typedef char            fmi2Byte;
+
+/* Values for fmi2Boolean  */
+#define fmi2True  1
+#define fmi2False 0
+
+
+#endif /* fmi2TypesPlatform_h */

+ 40 - 0
SemanticAdaptationForFMI/Experiments/power_window_case_study/fmu20/fmu/cs/PW_Controller/src/sc_types.h

@@ -0,0 +1,40 @@
+
+#ifndef SC_TYPES_H_
+#define SC_TYPES_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif 
+
+#include <stdint.h>
+#include <stdbool.h>
+
+#define sc_string		char*
+ 
+typedef bool			sc_boolean;
+typedef int_fast16_t	sc_short;
+typedef uint_fast16_t	sc_ushort;
+typedef int32_t			sc_integer; 
+typedef uint32_t		sc_uinteger; 
+typedef double			sc_real;
+
+typedef void*			sc_eventid;
+
+typedef intptr_t		sc_intptr_t;
+
+#ifdef __cplusplus
+}
+#endif
+
+#ifndef null
+	#ifdef __cplusplus
+		#define null 0
+	#else
+		#define null ((void *)0)
+	#endif
+#endif
+
+#define bool_true true
+#define bool_false false
+
+#endif /* SC_TYPES_H_ */