Explorar o código

started on the exporter for PDEVS

Simon Van Mierlo %!s(int64=9) %!d(string=hai) anos
pai
achega
9f7d657e53

+ 27 - 87
interface/PDEVS/.model.mvc

@@ -1,87 +1,27 @@
-include "primitives.alh"
-AtomicDEVSBlock Generator {
-	initialState = "generating"
-	name = "Generator"
-}
-AtomicDEVSBlock Processor {
-	initialState = "idle"
-	name = "Processor"
-}
-AtomicDEVSBlock Collector {
-	initialState = "waiting"
-	name = "Collector"
-}
-OutputPort g_out {name = "g_out"}
-InputPort p_in {name = "p_in"}
-OutputPort p_out {name = "p_out"}
-InputPort c_in {name = "c_in"}
-DEVSBlockToPort(Generator, g_out) {}
-DEVSBlockToPort(Processor, p_in) {}
-DEVSBlockToPort(Processor, p_out) {}
-DEVSBlockToPort(Collector, c_in) {}
-CoupledDEVSBlock CoupledProcessor {
-	name = "CoupledProcessor"
-}
-InputPort cp_in {name = "cp_in"}
-OutputPort cp_out {name = "cp_out"}
-DEVSBlockToPort (CoupledProcessor, cp_in) {}
-DEVSBlockToPort (CoupledProcessor, cp_out) {}
-DEVSInstance p1 {
-	name = "p1"
-	type = "Processor"
-}
-DEVSInstance p2 {
-	name = "p2"
-	type = "Processor"
-}
-SubModel (CoupledProcessor, p1) {}
-SubModel (CoupledProcessor, p2) {}
-InputPort p1_in {name = "p_in"}
-OutputPort p1_out {name = "p_out"}
-InputPort p2_in {name = "p_in"}
-OutputPort p2_out {name = "p_out"}
-DEVSInstanceToPort (p1, p1_in) {}
-DEVSInstanceToPort (p1, p1_out) {}
-DEVSInstanceToPort (p2, p2_in) {}
-DEVSInstanceToPort (p2, p2_out) {}
-Channel (cp_in, p1_in) {}
-Channel (p1_out, p2_in) {}
-Channel (p2_out, cp_out) {}
-CoupledDEVSBlock Root {
-	name = "Root"
-}
-DEVSInstance generator {
-	name = "generator"
-	type = "Generator"
-}
-DEVSInstance coupledprocessor {
-	name = "coupledprocessor"
-	type = "CoupledProcessor"
-}
-DEVSInstance processor {
-	name = "processor"
-	type = "Processor"
-}
-DEVSInstance collector {
-	name = "collector"
-	type = "Collector"
-}
-SubModel (Root, generator) {}
-SubModel (Root, coupledprocessor) {}
-SubModel (Root, processor) {}
-SubModel (Root, collector) {}
-OutputPort generator_out {name = "g_out"}
-InputPort coupledprocessor_in {name = "cp_in"}
-OutputPort coupledprocessor_out {name = "cp_out"}
-InputPort processor_in {name = "p_in"}
-OutputPort processor_out {name = "p_out"}
-InputPort collector_in {name = "c_in"}
-DEVSInstanceToPort (generator, generator_out) {}
-DEVSInstanceToPort (coupledprocessor, coupledprocessor_in) {}
-DEVSInstanceToPort (coupledprocessor, coupledprocessor_out) {}
-DEVSInstanceToPort (processor, processor_in) {}
-DEVSInstanceToPort (processor, processor_out) {}
-DEVSInstanceToPort (collector, collector_in) {}
-Channel (generator_out, coupledprocessor_in) {}
-Channel (coupledprocessor_out, processor_in) {}
-Channel (processor_out, collector_in) {}
+ComplexAttribute ActionCode {}
+SimpleAttribute String {}
+Class BaseDEVSBlock {
+	name: String	
+}
+Class AtomicDEVSBlock: BaseDEVSBlock {
+	timeAdvance: ActionCode
+	outputFunc: ActionCode
+	intTransition: ActionCode
+	extTransition: ActionCode
+	confTransition: ActionCode
+	initialState: String
+}
+Class CoupledDEVSBlock: BaseDEVSBlock {}
+Class DEVSInstance {
+	name: String
+	type: String
+}
+Association SubModel(CoupledDEVSBlock, DEVSInstance) {}
+Class Port {
+	name: String
+}
+Class InputPort: Port {}
+Class OutputPort: Port {}
+Association DEVSBlockToPort(BaseDEVSBlock, Port) {}
+Association DEVSInstanceToPort(DEVSInstance, Port) {}
+Association Channel (Port, Port) {}

+ 52 - 13
interface/PDEVS/console.py

@@ -1,6 +1,7 @@
 import sys
 from modelverse import *
 import random, re, json
+from interface import Controller
 
 def print_mv_with_input(value):
     print(value)
@@ -14,12 +15,24 @@ init()
 print("Login")
 login("admin", "admin")
 
+print("Remove ParallelDEVS metamodel")
+try:
+    model_delete("formalisms/ParallelDEVS")
+except ModelverseException:
+    pass
+    
 # Add the metamodel for Parallel DEVS
 print("Add ParallelDEVS metamodel")
 try:
     model_add("formalisms/ParallelDEVS", "formalisms/SimpleClassDiagrams", open("../../models/paralleldevs_design.mvc").read())
 except ModelExists:
     pass
+
+print("Remove MyString metamodel")
+try:
+    model_delete("formalisms/MyString")
+except ModelverseException:
+    pass
     
 # Add the metamodel for String
 print("Add MyString metamodel")
@@ -27,39 +40,65 @@ try:
     model_add("formalisms/MyString", "formalisms/SimpleClassDiagrams", open("../../models/string.mvc").read())
 except ModelExists:
     pass
+    
+print("Remove model")
+try:
+    model_delete("models/produce_consume_pdevs")
+except ModelverseException:
+    pass
 
 print("Add model")
 try:
-    model_add("produce_consume_devs", "formalisms/ParallelDEVS", open("../../models/produce_consume_pdevs.mvc").read())
+    model_add("models/produce_consume_pdevs", "formalisms/ParallelDEVS", open("../../models/produce_consume_PDEVS.mvc").read())
 except ModelExists:
     pass
 
 # Remove the action language code to transform between them
-print("Remove ParallelDEVS simulator model")
+print("Remove DEVS->String transformation model")
 try:
-    model_delete("models/paralleldevs_simulator")
+    model_delete("models/paralleldevs_to_string")
 except ModelverseException:
     pass
 
 # Add the action language code to transform between them
 # TODO: Make this a transformation to a trace metamodel
-print("Add ParallelDEVS simulator model")
+print("Add DEVS->String transformation model")
 try:
-    transformation_add_AL({"ParallelDEVS": "formalisms/ParallelDEVS"}, {}, "models/paralleldevs_simulator", open("../../models/paralleldevs_sim_interface.alc", "r").read())
+    transformation_add_AL({"ParallelDEVS": "formalisms/ParallelDEVS"}, {"MyString": "formalisms/MyString"}, "models/paralleldevs_to_string", open("../../models/devs_to_string.alc", "r").read())
 except ModelExists:
     pass
+    
+controller = Controller()
 
-# Remove the action language code to transform between them
-print("Remove DEVS->String transformation model")
+def raw_inputter():
+    while 1:
+        controller.addInput(Event("input", "input", [raw_input()]))
+input_thread = threading.Thread(target=raw_inputter)
+input_thread.daemon = True
+input_thread.start()
+
+output_listener = controller.addOutputListener(["output"])
+def outputter():
+    while 1:
+        print output_listener.fetch(-1)
+output_thread = threading.Thread(target=outputter)
+output_thread.daemon = True
+output_thread.start()
+    
+print("Execute DEVS->String transformation")
+transformation_execute_AL("models/paralleldevs_to_string", {"ParallelDEVS": "models/produce_consume_pdevs"}, {"MyString": "models/produce_consume_string"}, statechart=(controller, "mv_input", "mv_output"))
+
+print("Remove ParallelDEVS simulator model")
 try:
-    model_delete("models/paralleldevs_to_string")
+    model_delete("models/paralleldevs_simulator")
 except ModelverseException:
     pass
 
-# Add the action language code to transform between them
-# TODO: Make this a transformation to a trace metamodel
-print("Add DEVS->String transformation model")
+print("Add ParallelDEVS simulator model")
 try:
-    transformation_add_AL({"ParallelDEVS": "formalisms/ParallelDEVS"}, {"MyString": "formalisms/MyString"}, "models/paralleldevs_to_string", open("../../models/paralleldevs_sim_interface.alc", "r").read())
+    transformation_add_AL({"ParallelDEVS": "formalisms/ParallelDEVS"}, {}, "models/paralleldevs_simulator", open("../../models/paralleldevs_sim_interface.alc", "r").read())
 except ModelExists:
-    pass
+    pass
+
+print("Starting controller")
+controller.start()

+ 371 - 0
interface/PDEVS/http_client.py

@@ -0,0 +1,371 @@
+"""
+Generated by Statechart compiler by Glenn De Jonghe, Joeri Exelmans, Simon Van Mierlo, and Yentl Van Tendeloo (for the inspiration)
+
+Date:   Fri Aug 25 15:48:04 2017
+
+Model author: Yentl Van Tendeloo
+Model name:   HTTP client
+Model description:
+HTTP client.
+"""
+
+from sccd.runtime.statecharts_core import *
+import uuid
+
+# package "HTTP client"
+
+class HTTPClient(RuntimeClassBase):
+    def __init__(self, controller):
+        RuntimeClassBase.__init__(self, controller)
+        
+        self.semantics.big_step_maximality = StatechartSemantics.TakeMany
+        self.semantics.internal_event_lifeline = StatechartSemantics.Queue
+        self.semantics.input_event_lifeline = StatechartSemantics.FirstComboStep
+        self.semantics.priority = StatechartSemantics.SourceParent
+        self.semantics.concurrency = StatechartSemantics.Single
+        
+        # build Statechart structure
+        self.build_statechart_structure()
+        
+        # call user defined constructor
+        HTTPClient.user_defined_constructor(self)
+    
+    def user_defined_constructor(self):
+        self.socket = None
+        self.received_data = ""
+        self.send_data = ""
+        self.queue = []
+        self.IDs = []
+    
+    def user_defined_destructor(self):
+        pass
+    
+    
+    # builds Statechart structure
+    def build_statechart_structure(self):
+        
+        # state <root>
+        self.states[""] = State(0, "", self)
+        
+        # state /init
+        self.states["/init"] = State(1, "/init", self)
+        self.states["/init"].setEnter(self._init_enter)
+        
+        # state /waiting
+        self.states["/waiting"] = State(2, "/waiting", self)
+        self.states["/waiting"].setEnter(self._waiting_enter)
+        
+        # state /connecting
+        self.states["/connecting"] = State(3, "/connecting", self)
+        self.states["/connecting"].setEnter(self._connecting_enter)
+        self.states["/connecting"].setExit(self._connecting_exit)
+        
+        # state /connecting/connecting
+        self.states["/connecting/connecting"] = State(4, "/connecting/connecting", self)
+        self.states["/connecting/connecting"].setEnter(self._connecting_connecting_enter)
+        
+        # state /connecting/cooldown
+        self.states["/connecting/cooldown"] = State(5, "/connecting/cooldown", self)
+        self.states["/connecting/cooldown"].setEnter(self._connecting_cooldown_enter)
+        self.states["/connecting/cooldown"].setExit(self._connecting_cooldown_exit)
+        
+        # state /connected
+        self.states["/connected"] = ParallelState(6, "/connected", self)
+        
+        # state /connected/listening
+        self.states["/connected/listening"] = State(7, "/connected/listening", self)
+        
+        # state /connected/listening/listen
+        self.states["/connected/listening/listen"] = State(8, "/connected/listening/listen", self)
+        self.states["/connected/listening/listen"].setEnter(self._connected_listening_listen_enter)
+        
+        # state /connected/listening/close
+        self.states["/connected/listening/close"] = State(9, "/connected/listening/close", self)
+        
+        # state /connected/sending
+        self.states["/connected/sending"] = State(10, "/connected/sending", self)
+        
+        # state /connected/sending/waiting_for_data
+        self.states["/connected/sending/waiting_for_data"] = State(11, "/connected/sending/waiting_for_data", self)
+        
+        # state /connected/sending/transferring
+        self.states["/connected/sending/transferring"] = State(12, "/connected/sending/transferring", self)
+        
+        # state /connected/queueing
+        self.states["/connected/queueing"] = State(13, "/connected/queueing", self)
+        
+        # state /connected/queueing/queueing
+        self.states["/connected/queueing/queueing"] = State(14, "/connected/queueing/queueing", self)
+        self.states["/connected/queueing/queueing"].setEnter(self._connected_queueing_queueing_enter)
+        
+        # state /connected/parsing
+        self.states["/connected/parsing"] = State(15, "/connected/parsing", self)
+        
+        # state /connected/parsing/wait_for_header
+        self.states["/connected/parsing/wait_for_header"] = State(16, "/connected/parsing/wait_for_header", self)
+        
+        # state /connected/parsing/wait_for_payload
+        self.states["/connected/parsing/wait_for_payload"] = State(17, "/connected/parsing/wait_for_payload", self)
+        
+        # add children
+        self.states[""].addChild(self.states["/init"])
+        self.states[""].addChild(self.states["/waiting"])
+        self.states[""].addChild(self.states["/connecting"])
+        self.states[""].addChild(self.states["/connected"])
+        self.states["/connecting"].addChild(self.states["/connecting/connecting"])
+        self.states["/connecting"].addChild(self.states["/connecting/cooldown"])
+        self.states["/connected"].addChild(self.states["/connected/listening"])
+        self.states["/connected"].addChild(self.states["/connected/sending"])
+        self.states["/connected"].addChild(self.states["/connected/queueing"])
+        self.states["/connected"].addChild(self.states["/connected/parsing"])
+        self.states["/connected/listening"].addChild(self.states["/connected/listening/listen"])
+        self.states["/connected/listening"].addChild(self.states["/connected/listening/close"])
+        self.states["/connected/sending"].addChild(self.states["/connected/sending/waiting_for_data"])
+        self.states["/connected/sending"].addChild(self.states["/connected/sending/transferring"])
+        self.states["/connected/queueing"].addChild(self.states["/connected/queueing/queueing"])
+        self.states["/connected/parsing"].addChild(self.states["/connected/parsing/wait_for_header"])
+        self.states["/connected/parsing"].addChild(self.states["/connected/parsing/wait_for_payload"])
+        self.states[""].fixTree()
+        self.states[""].default_state = self.states["/init"]
+        self.states["/connecting"].default_state = self.states["/connecting/connecting"]
+        self.states["/connected/listening"].default_state = self.states["/connected/listening/listen"]
+        self.states["/connected/sending"].default_state = self.states["/connected/sending/waiting_for_data"]
+        self.states["/connected/queueing"].default_state = self.states["/connected/queueing/queueing"]
+        self.states["/connected/parsing"].default_state = self.states["/connected/parsing/wait_for_header"]
+        
+        # transition /init
+        _init_0 = Transition(self, self.states["/init"], [self.states["/waiting"]])
+        _init_0.setAction(self._init_0_exec)
+        _init_0.setTrigger(Event("created_socket", "socket_in"))
+        _init_0.setGuard(self._init_0_guard)
+        self.states["/init"].addTransition(_init_0)
+        
+        # transition /waiting
+        _waiting_0 = Transition(self, self.states["/waiting"], [self.states["/connecting"]])
+        _waiting_0.setAction(self._waiting_0_exec)
+        _waiting_0.setTrigger(Event("connect", "request_in"))
+        self.states["/waiting"].addTransition(_waiting_0)
+        
+        # transition /connecting/connecting
+        _connecting_connecting_0 = Transition(self, self.states["/connecting/connecting"], [self.states["/connecting/cooldown"]])
+        _connecting_connecting_0.setTrigger(Event("error_socket", "socket_in"))
+        self.states["/connecting/connecting"].addTransition(_connecting_connecting_0)
+        _connecting_connecting_1 = Transition(self, self.states["/connecting/connecting"], [self.states["/connected"]])
+        _connecting_connecting_1.setAction(self._connecting_connecting_1_exec)
+        _connecting_connecting_1.setTrigger(Event("connected_socket", "socket_in"))
+        _connecting_connecting_1.setGuard(self._connecting_connecting_1_guard)
+        self.states["/connecting/connecting"].addTransition(_connecting_connecting_1)
+        
+        # transition /connecting/cooldown
+        _connecting_cooldown_0 = Transition(self, self.states["/connecting/cooldown"], [self.states["/connecting/connecting"]])
+        _connecting_cooldown_0.setTrigger(Event("_1after"))
+        self.states["/connecting/cooldown"].addTransition(_connecting_cooldown_0)
+        
+        # transition /connected/listening/listen
+        _connected_listening_listen_0 = Transition(self, self.states["/connected/listening/listen"], [self.states["/connected/listening/listen"]])
+        _connected_listening_listen_0.setAction(self._connected_listening_listen_0_exec)
+        _connected_listening_listen_0.setTrigger(Event("received_socket", "socket_in"))
+        _connected_listening_listen_0.setGuard(self._connected_listening_listen_0_guard)
+        self.states["/connected/listening/listen"].addTransition(_connected_listening_listen_0)
+        _connected_listening_listen_1 = Transition(self, self.states["/connected/listening/listen"], [self.states["/connected/listening/close"]])
+        _connected_listening_listen_1.setTrigger(Event("received_socket", "socket_in"))
+        _connected_listening_listen_1.setGuard(self._connected_listening_listen_1_guard)
+        self.states["/connected/listening/listen"].addTransition(_connected_listening_listen_1)
+        
+        # transition /connected/sending/waiting_for_data
+        _connected_sending_waiting_for_data_0 = Transition(self, self.states["/connected/sending/waiting_for_data"], [self.states["/connected/sending/transferring"]])
+        _connected_sending_waiting_for_data_0.setAction(self._connected_sending_waiting_for_data_0_exec)
+        _connected_sending_waiting_for_data_0.setTrigger(None)
+        _connected_sending_waiting_for_data_0.setGuard(self._connected_sending_waiting_for_data_0_guard)
+        self.states["/connected/sending/waiting_for_data"].addTransition(_connected_sending_waiting_for_data_0)
+        
+        # transition /connected/sending/transferring
+        _connected_sending_transferring_0 = Transition(self, self.states["/connected/sending/transferring"], [self.states["/connected/sending/waiting_for_data"]])
+        _connected_sending_transferring_0.setAction(self._connected_sending_transferring_0_exec)
+        _connected_sending_transferring_0.setTrigger(Event("sent_socket", "socket_in"))
+        _connected_sending_transferring_0.setGuard(self._connected_sending_transferring_0_guard)
+        self.states["/connected/sending/transferring"].addTransition(_connected_sending_transferring_0)
+        
+        # transition /connected/queueing/queueing
+        _connected_queueing_queueing_0 = Transition(self, self.states["/connected/queueing/queueing"], [self.states["/connected/queueing/queueing"]])
+        _connected_queueing_queueing_0.setAction(self._connected_queueing_queueing_0_exec)
+        _connected_queueing_queueing_0.setTrigger(Event("HTTP_input", "request_in"))
+        self.states["/connected/queueing/queueing"].addTransition(_connected_queueing_queueing_0)
+        
+        # transition /connected/parsing/wait_for_header
+        _connected_parsing_wait_for_header_0 = Transition(self, self.states["/connected/parsing/wait_for_header"], [self.states["/connected/parsing/wait_for_payload"]])
+        _connected_parsing_wait_for_header_0.setAction(self._connected_parsing_wait_for_header_0_exec)
+        _connected_parsing_wait_for_header_0.setTrigger(None)
+        _connected_parsing_wait_for_header_0.setGuard(self._connected_parsing_wait_for_header_0_guard)
+        self.states["/connected/parsing/wait_for_header"].addTransition(_connected_parsing_wait_for_header_0)
+        
+        # transition /connected/parsing/wait_for_payload
+        _connected_parsing_wait_for_payload_0 = Transition(self, self.states["/connected/parsing/wait_for_payload"], [self.states["/connected/parsing/wait_for_header"]])
+        _connected_parsing_wait_for_payload_0.setAction(self._connected_parsing_wait_for_payload_0_exec)
+        _connected_parsing_wait_for_payload_0.setTrigger(None)
+        _connected_parsing_wait_for_payload_0.setGuard(self._connected_parsing_wait_for_payload_0_guard)
+        self.states["/connected/parsing/wait_for_payload"].addTransition(_connected_parsing_wait_for_payload_0)
+        _connected_parsing_wait_for_payload_1 = Transition(self, self.states["/connected/parsing/wait_for_payload"], [self.states["/connected/parsing/wait_for_header"]])
+        _connected_parsing_wait_for_payload_1.setAction(self._connected_parsing_wait_for_payload_1_exec)
+        _connected_parsing_wait_for_payload_1.setTrigger(None)
+        _connected_parsing_wait_for_payload_1.setGuard(self._connected_parsing_wait_for_payload_1_guard)
+        self.states["/connected/parsing/wait_for_payload"].addTransition(_connected_parsing_wait_for_payload_1)
+        
+        # transition /connecting
+        _connecting_0 = Transition(self, self.states["/connecting"], [self.states["/waiting"]])
+        _connecting_0.setAction(self._connecting_0_exec)
+        _connecting_0.setTrigger(Event("_0after"))
+        self.states["/connecting"].addTransition(_connecting_0)
+    
+    def _connecting_enter(self):
+        self.addTimer(0, self.timeout)
+    
+    def _connecting_exit(self):
+        self.removeTimer(0)
+    
+    def _init_enter(self):
+        self.ID = str(uuid.uuid4())
+        self.big_step.outputEvent(Event("create_socket", "socket_out", [self.ID]))
+    
+    def _waiting_enter(self):
+        self.big_step.outputEvent(Event("http_client_initialized", "request_out", []))
+    
+    def _connecting_connecting_enter(self):
+        self.big_step.outputEvent(Event("connect_socket", "socket_out", [self.socket, self.address]))
+    
+    def _connecting_cooldown_enter(self):
+        self.addTimer(1, 0.1)
+    
+    def _connecting_cooldown_exit(self):
+        self.removeTimer(1)
+    
+    def _connected_listening_listen_enter(self):
+        self.big_step.outputEvent(Event("recv_socket", "socket_out", [self.socket]))
+    
+    def _connected_queueing_queueing_enter(self):
+        pass
+    
+    def _connecting_0_exec(self, parameters):
+        self.big_step.outputEvent(Event("http_client_timeout", "request_out", []))
+    
+    def _init_0_exec(self, parameters):
+        socket = parameters[0]
+        ID = parameters[1]
+        self.socket = socket
+    
+    def _init_0_guard(self, parameters):
+        socket = parameters[0]
+        ID = parameters[1]
+        return self.ID == ID
+    
+    def _waiting_0_exec(self, parameters):
+        address = parameters[0]
+        timeout = parameters[1]
+        self.address = address
+        self.timeout = timeout
+    
+    def _connecting_connecting_1_exec(self, parameters):
+        socket = parameters[0]
+        self.big_step.outputEvent(Event("http_client_ready", "request_out", []))
+    
+    def _connecting_connecting_1_guard(self, parameters):
+        socket = parameters[0]
+        return self.socket == socket
+    
+    def _connected_listening_listen_0_exec(self, parameters):
+        socket = parameters[0]
+        data = parameters[1]
+        self.received_data += data
+    
+    def _connected_listening_listen_0_guard(self, parameters):
+        socket = parameters[0]
+        data = parameters[1]
+        return (self.socket == socket) and (len(data) > 0)
+    
+    def _connected_listening_listen_1_guard(self, parameters):
+        socket = parameters[0]
+        data = parameters[1]
+        return (self.socket == socket) and (len(data) == 0)
+    
+    def _connected_sending_waiting_for_data_0_exec(self, parameters):
+        self.big_step.outputEvent(Event("send_socket", "socket_out", [self.socket, self.send_data]))
+    
+    def _connected_sending_waiting_for_data_0_guard(self, parameters):
+        return len(self.send_data) > 0
+    
+    def _connected_sending_transferring_0_exec(self, parameters):
+        socket = parameters[0]
+        sent_bytes = parameters[1]
+        self.send_data = self.send_data[sent_bytes:]
+    
+    def _connected_sending_transferring_0_guard(self, parameters):
+        socket = parameters[0]
+        sent_bytes = parameters[1]
+        return self.socket == socket
+    
+    def _connected_queueing_queueing_0_exec(self, parameters):
+        data = parameters[0]
+        ID = parameters[1]
+        self.send_data += "POST / HTTP/1.0\r\n"
+        self.send_data += "Content-Length: %i\r\n" % len(str(data))
+        self.send_data += "\r\n"
+        self.send_data += data
+        self.IDs.append(ID)
+    
+    def _connected_parsing_wait_for_header_0_exec(self, parameters):
+        header, self.received_data = self.received_data.split("\r\n\r\n", 1)
+        header = header.lower()
+        if "content-length" in header:
+            _, after = header.split("content-length:", 1)
+            after, _ = after.split("\r\n", 1)
+            after = after.strip()
+            self.length = int(after)
+        else:
+            self.length = float('inf')
+    
+    def _connected_parsing_wait_for_header_0_guard(self, parameters):
+        return '\r\n\r\n' in self.received_data
+    
+    def _connected_parsing_wait_for_payload_0_exec(self, parameters):
+        data = self.received_data[:self.length]
+        self.received_data = self.received_data[self.length:]
+        self.big_step.outputEvent(Event("HTTP_output", "request_out", [data, self.IDs.pop(0)]))
+    
+    def _connected_parsing_wait_for_payload_0_guard(self, parameters):
+        return len(self.received_data) >= self.length and self.IDs[0] is not None
+    
+    def _connected_parsing_wait_for_payload_1_exec(self, parameters):
+        # Drop data
+        self.received_data = self.received_data[self.length:]
+        self.IDs.pop(0)
+    
+    def _connected_parsing_wait_for_payload_1_guard(self, parameters):
+        return len(self.received_data) >= self.length and self.IDs[0] is None
+    
+    def initializeStatechart(self):
+        # enter default state
+        self.default_targets = self.states["/init"].getEffectiveTargetStates()
+        RuntimeClassBase.initializeStatechart(self)
+
+class ObjectManager(ObjectManagerBase):
+    def __init__(self, controller):
+        ObjectManagerBase.__init__(self, controller)
+    
+    def instantiate(self, class_name, construct_params):
+        if class_name == "HTTPClient":
+            instance = HTTPClient(self.controller)
+            instance.associations = {}
+        else:
+            raise Exception("Cannot instantiate class " + class_name)
+        return instance
+
+class Controller(ThreadsControllerBase):
+    def __init__(self, keep_running = None, behind_schedule_callback = None):
+        if keep_running == None: keep_running = True
+        if behind_schedule_callback == None: behind_schedule_callback = None
+        ThreadsControllerBase.__init__(self, ObjectManager(self), keep_running, behind_schedule_callback)
+        self.addInputPort("socket_in")
+        self.addInputPort("request_in")
+        self.addOutputPort("socket_out")
+        self.addOutputPort("request_out")
+        self.object_manager.createInstance("HTTPClient", [])

+ 97 - 0
interface/PDEVS/interface.py

@@ -0,0 +1,97 @@
+"""
+Generated by Statechart compiler by Glenn De Jonghe, Joeri Exelmans, Simon Van Mierlo, and Yentl Van Tendeloo (for the inspiration)
+
+Date:   Fri Sep 29 15:11:02 2017
+
+Model author: Simon Van Mierlo
+Model name:   Translational Semantics Debugging Interface
+Model description:
+A debugging interface for a formalism with translational semantics.
+"""
+
+from sccd.runtime.statecharts_core import *
+
+# package "Translational Semantics Debugging Interface"
+
+class Interface(RuntimeClassBase):
+    def __init__(self, controller):
+        RuntimeClassBase.__init__(self, controller)
+        
+        self.semantics.big_step_maximality = StatechartSemantics.TakeMany
+        self.semantics.internal_event_lifeline = StatechartSemantics.Queue
+        self.semantics.input_event_lifeline = StatechartSemantics.FirstComboStep
+        self.semantics.priority = StatechartSemantics.SourceParent
+        self.semantics.concurrency = StatechartSemantics.Single
+        
+        # build Statechart structure
+        self.build_statechart_structure()
+        
+        # call user defined constructor
+        Interface.user_defined_constructor(self)
+    
+    def user_defined_constructor(self):
+        pass
+    
+    def user_defined_destructor(self):
+        pass
+    
+    
+    # builds Statechart structure
+    def build_statechart_structure(self):
+        
+        # state <root>
+        self.states[""] = State(0, "", self)
+        
+        # state /running
+        self.states["/running"] = State(1, "/running", self)
+        
+        # add children
+        self.states[""].addChild(self.states["/running"])
+        self.states[""].fixTree()
+        self.states[""].default_state = self.states["/running"]
+        
+        # transition /running
+        _running_0 = Transition(self, self.states["/running"], [self.states["/running"]])
+        _running_0.setAction(self._running_0_exec)
+        _running_0.setTrigger(Event("input", "mv_input"))
+        self.states["/running"].addTransition(_running_0)
+        _running_1 = Transition(self, self.states["/running"], [self.states["/running"]])
+        _running_1.setAction(self._running_1_exec)
+        _running_1.setTrigger(Event("input", "input"))
+        self.states["/running"].addTransition(_running_1)
+    
+    def _running_0_exec(self, parameters):
+        params = parameters[0]
+        self.big_step.outputEvent(Event("mv_output", "output", [params]))
+    
+    def _running_1_exec(self, parameters):
+        params = parameters[0]
+        self.big_step.outputEvent(Event("output", "mv_output", [params]))
+    
+    def initializeStatechart(self):
+        # enter default state
+        self.default_targets = self.states["/running"].getEffectiveTargetStates()
+        RuntimeClassBase.initializeStatechart(self)
+
+class ObjectManager(ObjectManagerBase):
+    def __init__(self, controller):
+        ObjectManagerBase.__init__(self, controller)
+    
+    def instantiate(self, class_name, construct_params):
+        if class_name == "Interface":
+            instance = Interface(self.controller)
+            instance.associations = {}
+        else:
+            raise Exception("Cannot instantiate class " + class_name)
+        return instance
+
+class Controller(ThreadsControllerBase):
+    def __init__(self, keep_running = None, behind_schedule_callback = None):
+        if keep_running == None: keep_running = True
+        if behind_schedule_callback == None: behind_schedule_callback = None
+        ThreadsControllerBase.__init__(self, ObjectManager(self), keep_running, behind_schedule_callback)
+        self.addInputPort("input")
+        self.addInputPort("mv_input")
+        self.addOutputPort("output")
+        self.addOutputPort("mv_output")
+        self.object_manager.createInstance("Interface", [])

+ 43 - 0
interface/PDEVS/interface.xml

@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<diagram author="Simon Van Mierlo" name="Translational Semantics Debugging Interface">
+    <description>
+        A debugging interface for a formalism with translational semantics.
+    </description>
+    
+    <top>
+        <![CDATA[
+        ]]>
+    </top>
+
+    <inport name="input" />
+    <outport name="output" />
+    <inport name="mv_input" />
+    <outport name="mv_output" />
+
+    <class name="Interface" default="true">
+        <relationships>
+        </relationships>
+        <constructor>
+            <body>
+                <![CDATA[
+                ]]>
+            </body>
+        </constructor>
+        <scxml initial="running">
+            <state id="running">
+                <transition event="input" port="mv_input" target=".">
+                    <parameter name="params" />
+                    <raise event="mv_output" port="output">
+                        <parameter expr="params" />
+                    </raise>
+                </transition>
+                <transition event="input" port="input" target=".">
+                    <parameter name="params" />
+                    <raise event="output" port="mv_output">
+                        <parameter expr="params" />
+                    </raise>
+                </transition>
+            </state>
+        </scxml>
+    </class>
+</diagram>

+ 249 - 228
interface/PDEVS/modelverse.py

@@ -1,13 +1,13 @@
 import urllib
-import urllib2
 import json
 import random
-from urllib2 import URLError
 import sys
 import time
 import threading
+import uuid
 
-COMPILER_PATH = "../../interface/HUTN"
+import sccd.runtime.socket2event as socket2event
+from sccd.runtime.statecharts_core import Event
 
 MODE_UNCONNECTED = 0
 MODE_UNAUTHORIZED = 1
@@ -17,10 +17,6 @@ MODE_DIALOG = 4
 MODE_MANUAL = 5
 MODE_SERVICE = 6
 
-# Bind to the compiler (might have to update path manually!)
-sys.path.append(COMPILER_PATH)
-from hutn_compiler.compiler import main as do_compile
-
 # Exceptions
 class ModelverseException(Exception):
     pass
@@ -60,12 +56,59 @@ class UnknownMetamodellingHierarchy(ModelverseException):
 
 # Helper functions and configuration: do not use yourself!
 taskname = None
-address = None
-last_output = None
 mode = MODE_UNCONNECTED
 prev_mode = None
 current_model = None
 registered_metamodels = {}
+outputs = {}
+ctrl_input = None
+ctrl_output = None
+
+def _output_thread(controller, outp, task):
+    req_out = controller.addOutputListener("request_out")
+    my_id = str(uuid.uuid4())
+
+    try:
+        while 1:
+            controller.addInput(Event("HTTP_input", "request_in", [urllib.urlencode({"op": "get_output", "taskname": task}), my_id]))
+            event = req_out.fetch(-1)
+
+            if event.parameters[1] == my_id:
+                outp[task].append(json.loads(event.parameters[0]))
+    except:
+        raise
+
+def _exec_on_statechart(statechart):
+    def _exec_sc(controller, inport, outport):
+        global taskname
+        op = controller.addOutputListener(outport)
+
+        while 1:
+            if len(outputs[taskname]) > 1:
+                # Is an output message of the Mv, so put it in the SC
+                del outputs[taskname][0]
+                output_event = outputs[taskname][0]
+
+                if output_event == "Success" or output_event == "Failure":
+                    # Is a stop event!
+                    controller.addInput(Event("terminate", inport, []))
+                    break
+                else:
+                    # Is just a normal event!
+                    controller.addInput(Event("input", inport, [output_event]))
+
+            input_event = op.fetch(0)
+            if input_event is not None:
+                # Expand the event and make it HTTP input
+                _input(input_event.parameters)
+                
+            time.sleep(0.02)
+        
+    thrd = threading.Thread(target=_exec_sc, args=statechart)
+    thrd.daemon = True
+    thrd.start()
+
+    return None
 
 def _get_metamodel(model):
     global registered_metamodels
@@ -114,77 +157,47 @@ def _goto_mode(new_mode, model_name=None):
         # Go to a mode that we have no automatic transfer to: raise exception
         raise InvalidMode("Required mode: %s, current mode: %s" % (new_mode, mode))
 
-def _input(value, port=None):
+def _input(value, task=None):
     # Ugly json encoding of primitives
     #print("[IN] %s" % value)
-    if port is None:
-        port = taskname
+    if task is None:
+        task = taskname
     if isinstance(value, type([])):
         value = json.dumps(value)
-        urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "data": value, "taskname": port}))).read()
+        ctrl_input.addInput(Event("HTTP_input", "request_in", [urllib.urlencode({"op": "set_input", "taskname": task, "data": value}), None]))
     else:
         value = json.dumps(value)
-        #print("Set input: " + str(value))
-        urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": value, "taskname": port}))).read()
+        ctrl_input.addInput(Event("HTTP_input", "request_in", [urllib.urlencode({"op": "set_input", "taskname": task, "value": value}), None]))
 
 def _input_raw(value, taskname):
     # Ugly json encoding of primitives
-    urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": value, "taskname": taskname}))).read()
-
-    #TODO check that this is actually a Modelverse!
-
-def _compile_AL(code):
-    # Compile an action language file and send the compiled code
-    code_fragments = code.split("\n")
-    code_fragments = [i for i in code_fragments if i.strip() != ""]
-    code_fragments = [i.replace("    ", "\t") for i in code_fragments]
-    initial_tabs = min([len(i) - len(i.lstrip("\t")) for i in code_fragments])
-    code_fragments = [i[initial_tabs:] for i in code_fragments]
-    code_fragments.append("")
-    code = "\n".join(code_fragments)
-
-    with open(".code.alc", "w") as f:
-        f.write(code)
-        f.flush()
-
-    compiled = do_compile(".code.alc", COMPILER_PATH + "/grammars/actionlanguage.g", "CS")
-    return compiled
-
-def _compile_model(code):
-    # Compile a model and send the compiled graph
-    # First change multiple spaces to a tab
-    code_fragments = code.split("\n")
-    code_fragments = [i for i in code_fragments if i.strip() != ""]
-    code_fragments = [i.replace("    ", "\t") for i in code_fragments]
-    initial_tabs = min([len(i) - len(i.lstrip("\t")) for i in code_fragments])
-    code_fragments = [i[initial_tabs:] for i in code_fragments]
-    code_fragments.append("")
-    code = "\n".join(code_fragments)
-
-    with open(".model.mvc", "w") as f:
-        f.write(code)
-        f.flush()
-
-    return do_compile(".model.mvc", COMPILER_PATH + "/grammars/modelling.g", "M")
-
-def _output(expected=None,port=None):
-    if port is None:
-        port = taskname
+    ctrl_input.addInput(Event("HTTP_input", "request_in", [urllib.urlencode({"op": "set_input", "taskname": taskname, "value": value}), None]))
+
+def _output(expected=None, task=None):
+    if task is None:
+        task = taskname
+
     try:
-        global last_output
-        last_output = json.loads(urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "get_output", "taskname": port}))).read())
-        #print("[OUT] %s" % last_output)
+        while len(outputs[task]) < 2:
+            time.sleep(0.02)
+
+        del outputs[task][0]
+        #print("[OUT] %s" % outputs[0])
     except:
         raise UnknownError()
-    if expected is not None and last_output != expected:
-        raise InterfaceMismatch(_last_output(), expected)
-    return last_output
 
-def _last_output():
-    return last_output
+    if expected is not None and _last_output(task) != expected:
+        raise InterfaceMismatch(_last_output(task), expected)
+    return _last_output(task)
+
+def _last_output(task=None):
+    if task is None:
+        task = taskname
+
+    return outputs[task][0]
 
 # Raise common exceptions
-def _handle_output(requested=None, split=None):
+def _handle_output(requested=None, split=False):
     value = _output()
     if value.startswith("Model exists: "):
         raise ModelExists(value.split(": ", 1)[1])
@@ -199,14 +212,14 @@ def _handle_output(requested=None, split=None):
     elif value.startswith("Attribute not found: "):
         raise NoSuchAttribute(value.split(": ", 1)[1])
     elif requested is not None and value.startswith(requested):
-        if split is None:
+        if not split:
             return value
         else:
-            splitted = value.strip().split(split, 1)
-            if len(splitted) == 1:
-                return ""
+            splitted = value.strip().split(" ", 1)
+            if len(splitted) > 1:
+                return splitted[1].split("\n")
             else:
-                return splitted[1].rstrip()
+                return []
     else:
         raise InterfaceMismatch(value)
     
@@ -251,25 +264,75 @@ def alter_context(model_name, metamodel_name):
     global registered_metamodels
     registered_metamodels[model_name] = metamodel_name
 
+def _start_http_client(addr, port, timeout):
+    import http_client
+    ctrl = http_client.Controller()
+    listener = ctrl.addOutputListener("request_out")
+    socket2event.boot_translation_service(ctrl)
+    thrd = threading.Thread(target=ctrl.start)
+    thrd.daemon = True
+    thrd.start()
+
+    evt = listener.fetch(-1)
+    if evt.name != "http_client_initialized":
+        raise Exception("HTTP client did not behave as expected during init: " + str(evt.name))
+
+    ctrl.addInput(Event("connect", "request_in", [(addr, port), timeout]))
+
+    evt = listener.fetch(-1)
+
+    if evt.name == "http_client_timeout":
+        raise Exception("HTTP client timeout")
+    if evt.name != "http_client_ready":
+        raise Exception("HTTP client did not behave as expected during connect: " + str(evt.name))
+
+    return ctrl
+
 # Main MvC operations
-def init(address_param="http://127.0.0.1:8001", timeout=20.0):
+def init(address_param="127.0.0.1:8001", timeout=20.0):
     """Starts up the connection to the Modelverse."""
-    global mode
+    # Start up the HTTP Client SC
+    global ctrl_input
+    global ctrl_output
+
+    if ctrl_input is not None:
+        ctrl_input.stop()
+    if ctrl_output is not None:
+        ctrl_output.stop()
+
     global address
-    global taskname
-    address = address_param
+    global port
+
+    address, port = address_param.split(":", 1)
+    port = int(port)
+    
+    ctrl_input = _start_http_client(address, port, timeout)
+    ctrl_output = _start_http_client(address, port, timeout) 
+    controllers = [ctrl_input, ctrl_output]
+
+    global mode
     start_time = time.time()
-    taskname = random.random()
-    while 1:
-        try:
-            _input_raw('"%s"' % taskname, "task_manager")
-            mode = MODE_UNAUTHORIZED
-            break
-        except URLError as e:
-            if time.time() - start_time > timeout:
-                raise ConnectionError(e.reason)
-            else:
-                time.sleep(0.1)
+    task = str(random.random())
+
+    _input_raw('"%s"' % task, "task_manager")
+
+    mode = MODE_UNAUTHORIZED
+
+    global outputs
+    global taskname
+    taskname = task
+    outputs = {}
+
+    _listen_to_output(ctrl_output, task)
+
+def _listen_to_output(controller, task):
+    global outputs
+    outputs[task] = [None]
+
+    # This re-assign also diconnects the previous get_output connections to the outputs variable
+    thrd = threading.Thread(target=_output_thread, args=[controller, outputs, task])
+    thrd.daemon = True
+    thrd.start()
 
 def login(username, password):
     """Log in a user, if user doesn't exist, it is created."""
@@ -305,34 +368,20 @@ def login(username, password):
     else:
         raise InterfaceMismatch(_last_output())
 
-def model_add(model_name, metamodel_name, model_code=None):
+def model_add(model_name, metamodel_name, model_code=""):
     """Instantiate a new model."""
     _goto_mode(MODE_MODELLING)
 
-    # Do this before creating the model, as otherwise compilation errors would make us inconsistent
-    if model_code is not None:
-        try:
-            compiled = _compile_model(model_code)
-        except Exception as e:
-            raise CompilationError(e)
-    else:
-        compiled = [0]
-
     _input(["model_add", metamodel_name, model_name])
     _handle_output("Waiting for model constructors...")
-    _input(compiled)
+    _input(model_code)
     _output("Success")
 
     global registered_metamodels
     registered_metamodels[model_name] = metamodel_name
 
 def upload_code(code):
-    try:
-        compiled = _compile_AL(code)
-    except Exception as e:
-        raise CompilationError(e)
-
-    _input(compiled)
+    _input(code)
 
 def model_delete(model_name):
     """Delete an existing model."""
@@ -345,19 +394,16 @@ def model_list(location):
     """List all models."""
     _goto_mode(MODE_MODELLING)
     _input(["model_list", location])
-    return set(_handle_output("Success: ", split=" ").split("\n"))
+    return set(_handle_output("Success: ", split=True))
 
 def model_list_full(location):
     """List full information on all models."""
     _goto_mode(MODE_MODELLING)
     _input(["model_list_full", location])
-    output = _handle_output("Success: ", split=" ")
-    if output == "":
-        return set([])
+    output = _handle_output("Success: ", split=True)
 
     lst = set([])
-    value = output.strip().split("\n")
-    for v in value:
+    for v in output:
         m = v.strip()
         perm, own, grp, m = m.split(" ", 3)
         lst.add((m, own, grp, perm))
@@ -372,23 +418,15 @@ def verify(model_name, metamodel_name=None):
         metamodel_name = _get_metamodel(model_name)
 
     _input(["verify", model_name, metamodel_name])
-    return _handle_output("Success: ", split=" ")
+    return _handle_output("Success: ", split=True)[0]
 
-def model_overwrite(model_name, new_model=None, metamodel_name=None):
+def model_overwrite(model_name, new_model="", metamodel_name=None):
     """Upload a new model and overwrite an existing model."""
     _goto_mode(MODE_MODIFY, model_name)
 
-    if new_model is not None:
-        try:
-            compiled = _compile_model(new_model)
-        except Exception as e:
-            raise CompilationError(e)
-    else:
-        compiled = [0]
-
     _input("upload")
     _handle_output("Waiting for model constructors...")
-    _input(compiled)
+    _input(new_model)
     _output("Success")
 
     if metamodel_name is not None:
@@ -414,30 +452,19 @@ def model_render(model_name, mapper_name):
     _goto_mode(MODE_MODELLING)
 
     _input(["model_render", model_name, mapper_name])
-    return json.loads(_handle_output("Success: ", split=" "))
+    return json.loads(_handle_output("Success: ", split=True)[0])
 
 def transformation_between(source, target):
     _goto_mode(MODE_MODELLING)
 
     _input(["transformation_between", source, target])
-    output = _handle_output("Success: ", split=" ")
-    if output == "":
-        return set([])
-    return set([v for v in output.split("\n")])
+    output = _handle_output("Success: ", split=True)
+    return set(output)
 
 def transformation_add_MT(source_metamodels, target_metamodels, operation_name, code, callback=lambda: None):
     """Create a new model transformation."""
     global mode
     _goto_mode(MODE_MODELLING)
-    import time
-
-    start = time.time()
-    try:
-        compiled = _compile_model(code)
-    except Exception as e:
-        raise CompilationError(e)
-    #print("Compilation took: %ss" % (time.time() - start))
-    start = time.time()
 
     mv_dict_rep = _dict_to_list(source_metamodels) + [""] + _dict_to_list(target_metamodels) + [""]
     _input(["transformation_add_MT"] + mv_dict_rep + [operation_name])
@@ -449,25 +476,17 @@ def transformation_add_MT(source_metamodels, target_metamodels, operation_name,
         callback()
         _input("exit")
         mode = MODE_MODELLING
-    #print("Callbacks took: %ss" % (time.time() - start))
-    start = time.time()
 
     # Done, so RAMify and upload the model
     _handle_output("Waiting for model constructors...")
-    _input(compiled)
+    _input(code)
     _handle_output("Success")
-    #print("Upload and RAMify took: %ss" % (time.time() - start))
 
 def transformation_add_AL(source_metamodels, target_metamodels, operation_name, code, callback=lambda: None):
     """Create a new action language model, which can be executed."""
     global mode
     _goto_mode(MODE_MODELLING)
 
-    try:
-        compiled = _compile_AL(code)
-    except Exception as e:
-        raise CompilationError(e)
-
     mv_dict_rep = _dict_to_list(source_metamodels) + [""] + _dict_to_list(target_metamodels) + [""]
     _input(["transformation_add_AL"] + mv_dict_rep + [operation_name])
 
@@ -480,7 +499,7 @@ def transformation_add_AL(source_metamodels, target_metamodels, operation_name,
         mode = MODE_MODELLING
 
     _handle_output("Waiting for code constructors...")
-    _input(compiled)
+    _input(code)
     _output("Success")
 
 def transformation_add_MANUAL(source_metamodels, target_metamodels, operation_name, callback=lambda: None):
@@ -501,7 +520,7 @@ def transformation_add_MANUAL(source_metamodels, target_metamodels, operation_na
 
     _handle_output("Success")
 
-def transformation_execute_AL(operation_name, input_models_dict, output_models_dict, callback=lambda i: None):
+def transformation_execute_AL(operation_name, input_models_dict, output_models_dict, statechart=None):
     """Execute an existing model operation."""
     global mode
     _goto_mode(MODE_MODELLING)
@@ -511,19 +530,21 @@ def transformation_execute_AL(operation_name, input_models_dict, output_models_d
     _input(["transformation_execute", operation_name] + mv_dict_rep)
     _handle_output("Success: ready for AL execution")
 
-    # We are now executing, so everything we get is part of the dialog, except if it is the string for transformation termination
-    while _output() not in ["Success", "Failure"]:
+    if statechart is not None:
+        # We are to delegate this information to another statechart, which wants interaction
+        # As such, we continue on a different thread, where we pipe the information, and let this call return immediately
         mode = MODE_DIALOG
-        reply = callback(_last_output())
+        _exec_on_statechart(statechart)
         mode = MODE_MODELLING
-        if reply is not None:
-            _input(reply)
-
-    # Got termination message, so we are done!
-    if _last_output() == "Success":
-        return True
+        return None
     else:
-        return False
+        # No statechart associated, so just wait until we are finished
+        while _output() not in ["Success", "Failure"]:
+            pass
+        if _last_output() == "Success":
+            return True
+        else:
+            return False
 
 def transformation_execute_MANUAL(operation_name, input_models_dict, output_models_dict, callback=lambda i: None):
     """Execute an existing model operation."""
@@ -552,7 +573,7 @@ def transformation_execute_MANUAL(operation_name, input_models_dict, output_mode
     else:
         return False
 
-def transformation_execute_MT(operation_name, input_models_dict, output_models_dict, callback=lambda i: None):
+def transformation_execute_MT(operation_name, input_models_dict, output_models_dict, statechart=None):
     """Execute an existing model operation."""
     global mode
     _goto_mode(MODE_MODELLING)
@@ -562,32 +583,31 @@ def transformation_execute_MT(operation_name, input_models_dict, output_models_d
     _input(["transformation_execute", operation_name] + mv_dict_rep)
     _handle_output("Success: ready for MT execution")
 
-    # We are now executing, so everything we get is part of the dialog, except if it is the string for transformation termination
-    while _output() not in ["Success", "Failure"]:
+    if statechart is not None:
+        # We are to delegate this information to another statechart, which wants interaction
+        # As such, we continue on a different thread, where we pipe the information, and let this call return immediately
         mode = MODE_DIALOG
-        reply = callback(_last_output())
+        _exec_on_statechart(statechart)
         mode = MODE_MODELLING
-        if reply is not None:
-            _input(reply)
-
-    # Got termination message, so we are done!
-    if _last_output() == "Success":
-        return True
+        return None
     else:
-        return False
+        # No statechart associated, so just wait until we are finished
+        while _output() not in ["Success", "Failure"]:
+            pass
+        if _last_output() == "Success":
+            return True
+        else:
+            return False
 
 def transformation_list():
     """List existing model operations."""
     _goto_mode(MODE_MODELLING)
 
     _input("transformation_list")
-    output = _handle_output("Success: ", split=" ")
-    if output == "":
-        return set([])
+    output = _handle_output("Success: ", split=True)
 
     lst = set([])
-    value = output.strip().split("\n")
-    for v in value:
+    for v in output:
         t, m = v.strip().split(" ", 1)
         t = t[1:-1].strip()
         m = m.strip().split(":")[0].strip()
@@ -709,10 +729,8 @@ def element_list(model_name):
 
     _input("list_full")
     lst = set([])
-    output = _handle_output("Success: ", split=" ")
-    if output == "":
-        return set([])
-    for v in output.split("\n"):
+    output = _handle_output("Success: ", split=True)
+    for v in output:
         m, mm = v.split(":")
         m = m.strip()
         mm = mm.strip()
@@ -725,10 +743,8 @@ def types(model_name):
 
     _input("types")
     lst = set([])
-    output = _handle_output("Success: ", split=" ")
-    if output == "":
-        return set([])
-    for v in output.split("\n"):
+    output = _handle_output("Success: ", split=True)
+    for v in output:
         m, mm = v.split(":")
         m = m.strip()
         lst.add(m)
@@ -740,10 +756,8 @@ def types_full(model_name):
 
     _input("types")
     lst = set([])
-    output = _handle_output("Success: ", split=" ")
-    if output == "":
-        return set([])
-    for v in output.split("\n"):
+    output = _handle_output("Success: ", split=True)
+    for v in output:
         m, mm = v.split(":")
         m = m.strip()
         mm = mm.strip()
@@ -755,8 +769,7 @@ def read(model_name, ID):
     _goto_mode(MODE_MODIFY, model_name)
 
     _input(["read", ID])
-    output = _handle_output("Success: ", split=" ")
-    v = output.split("\n")
+    v = _handle_output("Success: ", split=True)
     t = v[1].split(":")[1].strip()
     if (not v[2].startswith("Source:")):
         rval = (t, None)
@@ -771,11 +784,10 @@ def read_attrs(model_name, ID):
     _goto_mode(MODE_MODIFY, model_name)
 
     _input(["read", ID])
-    output = _handle_output("Success: ", split=" ")
-    v = output.split("\n")
+    output = _handle_output("Success: ", split=True)
     searching = True
     rval = {}
-    for r in v:
+    for r in output:
         if searching:
             if r == "Attributes:":
                 # Start working on attributes
@@ -804,7 +816,7 @@ def instantiate(model_name, typename, edge=None, ID=""):
         _input(["instantiate_node", typename, ID])
     else:
         _input(["instantiate_edge", typename, ID, edge[0], edge[1]])
-    return _handle_output("Success: ", split=" ")
+    return _handle_output("Success: ", split=True)[0]
 
 def delete_element(model_name, ID):
     """Delete the element with the given ID"""
@@ -824,16 +836,12 @@ def attr_assign(model_name, ID, attr, value):
 def attr_assign_code(model_name, ID, attr, code):
     """Assign a piece of Action Language code to the attribute"""
     _check_type(code)
-    try:
-        compiled = _compile_AL(code)
-    except Exception as e:
-        raise CompilationError(e)
 
     _goto_mode(MODE_MODIFY, model_name)
 
-    _input(["attr_add", ID, attr])
+    _input(["attr_add_code", ID, attr])
     _handle_output("Waiting for code constructors...")
-    _input(compiled)
+    _input(code)
     _output("Success")
 
 def attr_delete(model_name, ID, attr):
@@ -848,45 +856,47 @@ def read_outgoing(model_name, ID, typename):
     _goto_mode(MODE_MODIFY, model_name)
 
     _input(["read_outgoing", ID, typename])
-    output = _handle_output("Success: ", split=" ")
-    if output == "":
-        return set([])
-    else:
-        return set(output.split("\n"))
+    output = _handle_output("Success: ", split=True)
+    return set(output)
 
 def read_incoming(model_name, ID, typename):
     """Returns a list of all incoming associations of a specific type ("" = all)"""
     _goto_mode(MODE_MODIFY, model_name)
 
     _input(["read_incoming", ID, typename])
-    output = _handle_output("Success: ", split=" ")
-    if output == "":
-        return set([])
-    else:
-        return set(output.split("\n"))
+    output = _handle_output("Success: ", split=True)
+    return set(output)
 
 def read_association_source(model_name, ID):
     """Returns the source of an association."""
     _goto_mode(MODE_MODIFY, model_name)
 
     _input(["read_association_source", ID])
-    return _handle_output("Success: ", split=" ")
+    return _handle_output("Success: ", split=True)[0]
 
 def read_association_destination(model_name, ID):
     """Returns the destination of an association."""
     _goto_mode(MODE_MODIFY, model_name)
 
     _input(["read_association_destination", ID])
-    return _handle_output("Success: ", split=" ")
+    return _handle_output("Success: ", split=True)[0]
 
 ##### To document:
 
 def service_register(name, function):
     """Register a function as a service with a specific name."""
 
-    def service_process(port):
+    def service_process(service_task):
+        global address
+        global port
+
+        ctrl = _start_http_client(address, port, 10.0) 
+        _listen_to_output(ctrl, service_task)
         while 1:
-            thrd = threading.Thread(target=function, args=[service_get(port)])
+            client_task = service_get(service_task)
+            ctrl = _start_http_client(address, port, 10.0) 
+            _listen_to_output(ctrl, client_task)
+            thrd = threading.Thread(target=function, args=[client_task])
             thrd.daemon = True
             thrd.start()
 
@@ -897,10 +907,12 @@ def service_register(name, function):
 
     # Now we are in service-mode
     mode = MODE_SERVICE
-    port = _handle_output("Success: ", split=" ")
+    task = _handle_output("Success: ", split=True)[0]
 
     # Process events in the background!
-    threading.Thread(target=service_process, args=[port]).start()
+    thrd = threading.Thread(target=service_process, args=[task])
+    thrd.daemon = True
+    thrd.start()
 
 def service_stop():
     """Stop the currently executing process."""
@@ -911,18 +923,19 @@ def service_stop():
     global mode
     mode = MODE_MODELLING
 
-def service_get(port):
-    """Get the values on the specified port."""
+def service_get(task):
+    """Get the values on the specified task."""
     _goto_mode(MODE_SERVICE)
 
-    return _output(port=port)
+    val = _output(task=task)
+    return val
 
-def service_set(port, value):
-    """Set a value on a specified port."""
+def service_set(task, value):
+    """Set a value on a specified task."""
     _check_type_list(value)
     _goto_mode(MODE_SERVICE)
 
-    _input(value, port=port)
+    _input(value, task=task)
 
 def user_password(user, password):
     """Change a user's password."""
@@ -938,7 +951,7 @@ def element_list_nice(model_name):
 
     _input(["element_list_nice", model_name, _get_metamodel(model_name)])
 
-    data = _handle_output("Success: ", split=" ")
+    data = _handle_output("Success: ", split=True)[0]
     try:
         return json.loads(data)
     except:
@@ -950,29 +963,23 @@ def connections_between(model_name, source_element, target_element):
     _goto_mode(MODE_MODIFY, model_name)
 
     _input(["connections_between", source_element, target_element])
-    output = _handle_output("Success: ", split=" ")
-    if output == "":
-        return set([])
-    else:
-        return set(output.split("\n"))
+    output = _handle_output("Success: ", split=True)
+    return set(output)
 
 def define_attribute(model_name, node, attr_name, attr_type):
     """Create a new attribute, which can be instantiated one meta-level below."""
     _goto_mode(MODE_MODIFY, model_name)
 
     _input(["define_attribute", node, attr_name, attr_type])
-    return _handle_output("Success: ", split=" ")
+    return _handle_output("Success: ", split=True)[0]
 
 def all_instances(model_name, type_name):
     """Returns a list of all elements of a specific type."""
     _goto_mode(MODE_MODIFY, model_name)
 
     _input(["all_instances", type_name])
-    output = _handle_output("Success: ", split=" ")
-    if output == "":
-        return set([])
-    else:
-        return set(output.split("\n"))
+    output = _handle_output("Success: ", split=True)
+    return set(output)
 
 def service_poll(port):
     """Checks whether or not the Modelverse side has any input ready to be processed."""
@@ -996,6 +1003,20 @@ def add_conformance(model_name, metamodel_name, partial_type_mapping=None):
     _handle_output("Success")
 
 def folder_create(folder_name):
+    """Create a new folder."""
     _goto_mode(MODE_MODELLING)
     _input(["folder_create", folder_name])
     _handle_output("Success")
+
+def model_types(model_name):
+    """Fetch all typings defined for this specific model."""
+    _goto_mode(MODE_MODELLING)
+    _input(["model_types", model_name])
+    output = _handle_output("Success: ", split=True)
+    return set(output)
+
+import atexit
+def _close_model():
+    if mode == MODE_MODIFY:
+        _model_exit()
+atexit.register(_close_model)

+ 80 - 0
models/devs_to_string.alc

@@ -1,8 +1,88 @@
 include "primitives.alh"
 include "modelling.alh"
 include "object_operations.alh"
+include "typing.alh"
 
 Boolean function devs_to_string(model: Element):
+    log("Entering devs_to_string function!")
+
+    String model_rep
+    Element all_atomics
+    Element curr_atomic
+    Element all_coupleds
+    Element curr_coupled
+    Element string_element
+    Element all_ports
+    Element all_submodels
+    Element curr_port
+    String curr_port_name
+    String curr_port_type
+    String curr_submodel_name
+    String curr_submodel_type
+    
+    model_rep = ""
+    
+    all_atomics = allInstances(model, "ParallelDEVS/AtomicDEVSBlock")
+    while (read_nr_out(all_atomics) > 0):
+        curr_atomic = set_pop(all_atomics)
+        model_rep = ((model_rep + "class ") + cast_i2s(read_attribute(model, curr_atomic, "name"))) + "(AtomicDEVS):\n"
+        model_rep = ((model_rep + "\tdef __init__(self, name=") + cast_v2s(read_attribute(model, curr_atomic, "name"))) + "):\n"
+        model_rep = model_rep + "\t\tAtomicDEVS.__init__(self, name)\n"
+        model_rep = ((model_rep + "\t\tstate = {'name': ") + cast_v2s(read_attribute(model, curr_atomic, "initialState"))) + "}\n"
+        model_rep = model_rep + "\t\tself.my_ports = {"
+        all_ports = allAssociationDestinations(model, curr_atomic, "ParallelDEVS/DEVSBlockToPort")
+        while (read_nr_out(all_ports) > 0):
+            curr_port = set_pop(all_ports)
+            curr_port_name = cast_v2s(read_attribute(model, curr_port, "name"))
+            curr_port_type = read_type(model, curr_port)
+            if (curr_port_type == "ParallelDEVS/InputPort"):                
+                model_rep = (((model_rep + curr_port_name) + ": self.addInPort(") + curr_port_name) + ")"
+            if (curr_port_type == "ParallelDEVS/OutputPort"):                
+                model_rep = (((model_rep + curr_port_name) + ": self.addOutPort(") + curr_port_name) + ")"
+            if (read_nr_out(all_ports) > 0):
+                model_rep = model_rep + ", "
+        model_rep = model_rep + "}\n"
+        model_rep = ((model_rep + "\tdef timeAdvance(self):\n") + cast_i2s(read_attribute(model, curr_atomic, "timeAdvance"))) + "\n"
+        model_rep = ((model_rep + "\tdef outputFnc(self):\n") + cast_i2s(read_attribute(model, curr_atomic, "outputFnc"))) + "\n"
+        model_rep = ((model_rep + "\tdef intTransition(self):\n") + cast_i2s(read_attribute(model, curr_atomic, "intTransition"))) + "\n"
+        model_rep = ((model_rep + "\tdef extTransition(self):\n") + cast_i2s(read_attribute(model, curr_atomic, "extTransition"))) + "\n"
+        model_rep = ((model_rep + "\tdef confTransition(self):\n") + cast_i2s(read_attribute(model, curr_atomic, "confTransition"))) + "\n"
+        
+    all_coupleds = allInstances(model, "ParallelDEVS/CoupledDEVSBlock")
+    while (read_nr_out(all_coupleds) > 0):
+        curr_coupled = set_pop(all_coupleds)
+        model_rep = ((model_rep + "class ") + cast_i2s(read_attribute(model, curr_atomic, "name"))) + "(CoupledDEVS):\n"
+        model_rep = ((model_rep + "\tdef __init__(self, name=") + cast_v2s(read_attribute(model, curr_atomic, "name"))) + "):\n"
+        model_rep = model_rep + "\t\tCoupledDEVS.__init__(self, name)\n"
+        model_rep = model_rep + "\t\tself.my_ports = {"
+        all_ports = allAssociationDestinations(model, curr_atomic, "ParallelDEVS/DEVSBlockToPort")
+        while (read_nr_out(all_ports) > 0):
+            curr_port = set_pop(all_ports)
+            curr_port_name = cast_v2s(read_attribute(model, curr_port, "name"))
+            curr_port_type = read_type(model, curr_port)
+            log(curr_port_type)
+            if (curr_port_type == "ParallelDEVS/InputPort"):                
+                model_rep = (((model_rep + curr_port_name) + ": self.addInPort(") + curr_port_name) + ")"
+            if (curr_port_type == "ParallelDEVS/OutputPort"):                
+                model_rep = (((model_rep + curr_port_name) + ": self.addOutPort(") + curr_port_name) + ")"
+            if (read_nr_out(all_ports) > 0):
+                model_rep = model_rep + ", "
+        model_rep = model_rep + "}\n"
+        model_rep = model_rep + "\t\tself.submodels = {"
+        all_submodels = allAssociationDestinations(model, curr_atomic, "ParallelDEVS/SubModel")
+        while (read_nr_out(all_submodels) > 0):
+            curr_submodel = set_pop(all_submodels)
+            curr_submodel_name = cast_v2s(read_attribute(model, curr_port, "name"))
+            curr_submodel_type = cast_i2s(read_attribute(model, curr_port, "type"))
+            model_rep = ((((((model_rep + curr_submodel_name) + ": self.addSubModel(") + curr_submodel_type) + "(name=") + curr_submodel_name) + ")")) + ")"
+            if (read_nr_out(all_submodels) > 0):
+                model_rep = model_rep + ", "
+        model_rep = model_rep + "}\n"
+        
+    string_element = instantiate_node(model, "MyString/MyString", "my_string")
+    instantiate_attribute(model, string_element, "value", model_rep)
     
+    log("Printing model_rep...")
+    log("\n" + model_rep)
     
     return True!

+ 1 - 1
models/paralleldevs_design.mvc

@@ -7,7 +7,7 @@ Class BaseDEVSBlock {
 
 Class AtomicDEVSBlock: BaseDEVSBlock {
     timeAdvance: ActionCode
-    outputFunc: ActionCode
+    outputFnc: ActionCode
     intTransition: ActionCode
     extTransition: ActionCode
     confTransition: ActionCode

+ 93 - 8
models/produce_consume_PDEVS.mvc

@@ -4,24 +4,109 @@ AtomicDEVSBlock Generator {
     initialState = "generating"
     name = "Generator"
     
-    intTransition =
-    '''
-        Element function intTransition():
-            Element retValue
-            retValue = create_node()
-            dict_add_fast(retValue, 'g_out', 0.3)
-            return retValue!
-    '''
+    intTransition = """
+        if self.state['name'] == 'generating':
+            new_state = {}
+            new_state['name'] = 'generating'
+            return new_state
+    """
+    
+    timeAdvance = """
+        if self.state['name'] == 'generating':
+            return 1
+    """
+    
+    outputFnc = """
+        if self.state['name'] == 'generating':
+            return {self.my_ports['g_out']: {'type': 'Job', 'repr': {'duration': 0.3}}}
+    """
+    
+    extTransition = """
+        inputs = {k.getPortName(): v for k, v in my_inputs.iteritems()}
+        return AtomicDEVS.extTransition(self, my_inputs)
+    """
+    
+    confTransition = """
+        inputs = {k.getPortName(): v for k, v in my_inputs.iteritems()}
+        return AtomicDEVS.confTransition(self, my_inputs)
+    """
 }
 
 AtomicDEVSBlock Processor {
     initialState = "idle"
     name = "Processor"
+    
+    intTransition = """
+        if self.state['name'] == 'processing':
+            new_state = {}
+            new_state['name'] = 'idle'
+            return new_state
+    """
+    
+    timeAdvance = """
+        if self.state['name'] == 'processing':
+            return self.state['job']['duration']
+        if self.state['name'] == 'idle':
+            return INFINITY
+    """
+    
+    outputFnc = """
+        if self.state['name'] == 'processing':
+            return {self.my_ports['p_out']: {'type': 'Job', 'repr': self.state['job']}}
+        if self.state['name'] == 'idle':
+            return {}
+    """
+    
+    extTransition = """
+        inputs = {k.getPortName(): v for k, v in my_inputs.iteritems()}
+        if self.state['name'] == 'idle':
+            new_state = {}
+            new_state['name'] = 'processing'
+            new_state['job'] = inputs['p_in']['repr']
+            return new_state 
+        else:
+            return AtomicDEVS.extTransition(self, my_inputs)
+    """
+    
+    confTransition = """
+        inputs = {k.getPortName(): v for k, v in my_inputs.iteritems()}
+        return AtomicDEVS.confTransition(self, my_inputs)
+    """
 }
 
 AtomicDEVSBlock Collector {
     initialState = "waiting"
     name = "Collector"
+    
+    intTransition = """
+        return AtomicDEVS.intTransition(self, my_inputs)
+    """
+    
+    timeAdvance = """
+        if self.state['name'] == 'waiting':
+            return INFINITY
+    """
+    
+    outputFnc = """
+        if self.state['name'] == 'waiting':
+            return {}
+    """
+    
+    extTransition = """
+        inputs = {k.getPortName(): v for k, v in my_inputs.iteritems()}
+        if self.state['name'] == 'waiting':
+            new_state = {}
+            new_state['name'] = 'waiting'
+            new_state['nr_of_jobs'] = self.state['nr_of_jobs'] + 1
+            return new_state
+        else:
+            return AtomicDEVS.extTransition(self, my_inputs)
+    """
+    
+    confTransition = """
+        inputs = {k.getPortName(): v for k, v in my_inputs.iteritems()}
+        return AtomicDEVS.confTransition(self, my_inputs)
+    """
 }
 
 OutputPort g_out {name = "g_out"}