소스 검색

for yentl's testing purposes

Simon Van Mierlo 9 년 전
부모
커밋
e99c85c628
3개의 변경된 파일과 342개의 추가작업 그리고 244개의 파일을 삭제
  1. 1 0
      integration/code/pdevs_client.alc
  2. 320 244
      interface/PDEVS/console.py
  3. 21 0
      interface/PDEVS/register_service.py

+ 1 - 0
integration/code/pdevs_client.alc

@@ -6,6 +6,7 @@ include "object_operations.alh"
 Boolean function main(model : Element):
 	String port
     String the_input
+    String devs_model
 	port = comm_connect("pypdevs_simulator")
     
     log("Sending model...")

+ 320 - 244
interface/PDEVS/console.py

@@ -1,270 +1,346 @@
 import sys
 from modelverse import *
-import random, re, json, subprocess
+import random, re, json
 from interface import Controller
 from pprint import pprint
+from multiprocessing import Process, Pipe, freeze_support
 
-print("Init")
-init("msdl.uantwerpen.be:8001")
-print("Login")
-login("admin", "admin")
+def register_service():
+    sys.path.append('pypdevs/src')
 
-print("Remove ProductionSystem metamodel")
-try:
-    model_delete("formalisms/ProductionSystem")
-except ModelverseException:
-    pass
-    
-# Add the metamodel for ProductionSystem
-print("Add ProductionSystem metamodel")
-try:
-    model_add("formalisms/ProductionSystem", "formalisms/SimpleClassDiagrams", open("../../models/production_system_design.mvc").read())
-except ModelExists:
-    pass
-    
-print("Remove model")
-try:
-    model_delete("models/example_PS")
-except ModelverseException:
-    pass
+    from simulator import Controller
+    import threading, time
 
-print("Add model")
-try:
-    model_add("models/example_PS", "formalisms/ProductionSystem", open("../../models/example_PS.mvc").read())
-except ModelExists:
-    pass
-    
-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 'Registering service...'
 
-def traceability_PS2DEVS():
-    instantiate(None, "Association", ("ProductionSystem/Machine", "ParallelDEVS/BaseDEVSBlock"), ID="PS2DEVS_typelink")
-    instantiate(None, "Association", ("ProductionSystem/Machine", "ParallelDEVS/DEVSInstance"), ID="PS2DEVS_instancelink")
-    
-print("Remove PS->DEVS transformation model")
-try:
-    model_delete("models/ps_to_devs")
-except ModelverseException:
-    pass
+    init('msdl.uantwerpen.be:8001')
+    login("pypdevs_service", "my_password")
+
+    def pypdevs_service(port):
+        exec service_get(port) in globals()
+        controller = Controller(Root())
+
+        def inputter():
+            print "Waiting for input..."
+            while 1:
+                input = service_get(port)
+                print 'raw input = %s' % input
+                params = json.loads(input)
+                print 'json parsed = %s' % params
+                if not isinstance(params, list):
+                    params = [params]
+                print "Sending input to simulator: %s" % params
+                if (len(params) > 1):
+                    controller.addInput(Event(params[0], "request", params[1:]))
+                else:
+                    controller.addInput(Event(params[0], "request", []))
+        input_thread = threading.Thread(target=inputter)
+        input_thread.daemon = True
+        input_thread.start()
+
+        output_listener = controller.addOutputListener(["reply"])
+        def outputter():
+            print "Waiting for output..."
+            while 1:
+                output_val = output_listener.fetch(-1)
+                print "Got output from simulator: %s" % output_val
+                service_set(port, json.dumps({"name": output_val.getName(), "port": output_val.getPort(), "params": output_val.getParameters()}))
+        output_thread = threading.Thread(target=outputter)
+        output_thread.daemon = True
+        output_thread.start()
+        
+        controller.start()
+        
+    service_register("pypdevs_simulator", pypdevs_service)
 
-print("Add PS->DEVS transformation model")
-transformation_add_MT({"ProductionSystem": "formalisms/ProductionSystem"}, {"ParallelDEVS": "formalisms/ParallelDEVS"}, "models/ps_to_devs", open("../../models/ps_to_devs.mvc", 'r').read(), traceability_PS2DEVS)
+    try:
+        while True:
+            # Stay active, as we shouldn't exit while the service is running!
+            time.sleep(1)
+    finally:
+        service_stop()
+
+def start_pypdevs_client(conn):
+    init('msdl.uantwerpen.be:8001')
+    login("pypdevs_client", "my_password")
     
-print("Execute PS->DEVS transformation")
-transformation_execute_MT("models/ps_to_devs", {"ProductionSystem": "models/example_PS"}, {"ParallelDEVS": "models/example_PS_DEVS"}, tracability_model="models/PS_DEVS_traceability")
+    print("Remove ParallelDEVS simulator client")
+    try:
+        model_delete("models/paralleldevs_simulator")
+    except ModelverseException:
+        pass
+
+    # TODO: Make this a transformation to a trace metamodel
+    print("Add ParallelDEVS simulator client")
+    try:
+        transformation_add_AL({}, {}, "models/paralleldevs_simulator", open("../../integration/code/pdevs_client.alc", "r").read())
+    except ModelExists:
+        pass
 
-print("Remove MyString metamodel")
-try:
-    model_delete("formalisms/MyString")
-except ModelverseException:
-    pass
+    print("Starting PyPDEVS client...")
+    task_name = transformation_execute_AL("models/paralleldevs_simulator", {"MyString": "models/example_PS_DEVS_String"}, {})
+
+    conn.send(task_name)
+    conn.close()
+        
+if __name__ == '__main__':
+    freeze_support()    
+    p = Process(target=register_service)
+    p.start()
     
-# Add the metamodel for String
-print("Add MyString metamodel")
-try:
-    model_add("formalisms/MyString", "formalisms/SimpleClassDiagrams", open("../../models/string.mvc").read())
-except ModelExists:
-    pass
+    print("Init")
+    init("msdl.uantwerpen.be:8001")
+    print("Login")
+    login("admin", "admin")
+
+    print("Remove ProductionSystem metamodel")
+    try:
+        model_delete("formalisms/ProductionSystem")
+    except ModelverseException:
+        pass
+        
+    # Add the metamodel for ProductionSystem
+    print("Add ProductionSystem metamodel")
+    try:
+        model_add("formalisms/ProductionSystem", "formalisms/SimpleClassDiagrams", open("../../models/production_system_design.mvc").read())
+    except ModelExists:
+        pass
+        
+    print("Remove model")
+    try:
+        model_delete("models/example_PS")
+    except ModelverseException:
+        pass
+
+    print("Add model")
+    try:
+        model_add("models/example_PS", "formalisms/ProductionSystem", open("../../models/example_PS.mvc").read())
+    except ModelExists:
+        pass
+        
+    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 PDEVS model")
-try:
-    model_delete("models/produce_consume_pdevs")
-except ModelverseException:
-    pass
+    def traceability_PS2DEVS():
+        instantiate(None, "Association", ("ProductionSystem/Machine", "ParallelDEVS/BaseDEVSBlock"), ID="PS2DEVS_typelink")
+        instantiate(None, "Association", ("ProductionSystem/Machine", "ParallelDEVS/DEVSInstance"), ID="PS2DEVS_instancelink")
+        
+    print("Remove PS->DEVS transformation model")
+    try:
+        model_delete("models/ps_to_devs")
+    except ModelverseException:
+        pass
+
+    print("Add PS->DEVS transformation model")
+    transformation_add_MT({"ProductionSystem": "formalisms/ProductionSystem"}, {"ParallelDEVS": "formalisms/ParallelDEVS"}, "models/ps_to_devs", open("../../models/ps_to_devs.mvc", 'r').read(), traceability_PS2DEVS)
+        
+    print("Execute PS->DEVS transformation")
+    transformation_execute_MT("models/ps_to_devs", {"ProductionSystem": "models/example_PS"}, {"ParallelDEVS": "models/example_PS_DEVS"}, tracability_model="models/PS_DEVS_traceability")
 
-print("Add PDEVS model")
-try:
-    model_add("models/produce_consume_pdevs", "formalisms/ParallelDEVS", open("../../models/produce_consume_PDEVS.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")
+    try:
+        model_add("formalisms/MyString", "formalisms/SimpleClassDiagrams", open("../../models/string.mvc").read())
+    except ModelExists:
+        pass
 
-# Remove the action language code to transform between DEVS->String
-print("Remove DEVS->String transformation model")
-try:
-    model_delete("models/paralleldevs_to_string")
-except ModelverseException:
-    pass
+    # Remove the action language code to transform between DEVS->String
+    print("Remove DEVS->String transformation model")
+    try:
+        model_delete("models/paralleldevs_to_string")
+    except ModelverseException:
+        pass
 
-# Add the action language code to transform between DEVS->String
-print("Add DEVS->String transformation model")
-try:
-    transformation_add_AL({"ParallelDEVS": "formalisms/ParallelDEVS"}, {"MyString": "formalisms/MyString"}, "models/paralleldevs_to_string", open("../../models/devs_to_string.alc", "r").read())
-except ModelExists:
-    pass
+    # Add the action language code to transform between DEVS->String
+    print("Add DEVS->String transformation model")
+    try:
+        transformation_add_AL({"ParallelDEVS": "formalisms/ParallelDEVS"}, {"MyString": "formalisms/MyString"}, "models/paralleldevs_to_string", open("../../models/devs_to_string.alc", "r").read())
+    except ModelExists:
+        pass
+        
+    print("Execute DEVS->String transformation")
+    transformation_execute_AL("models/paralleldevs_to_string", {"ParallelDEVS": "models/example_PS_DEVS"}, {"MyString": "models/example_PS_DEVS_String"})
     
-print("Execute DEVS->String transformation")
-transformation_execute_AL("models/paralleldevs_to_string", {"ParallelDEVS": "models/example_PS_DEVS"}, {"MyString": "models/example_PS_DEVS_String"})
+    print("Starting PyPDEVS client")    
+    parent_conn, child_conn = Pipe()
+    p1 = Process(target=start_pypdevs_client, args=(child_conn,))
+    p1.start()
+    print 'got process output: %s' % parent_conn.recv()   # prints "[42, None, 'hello']"
 
-print("Remove ParallelDEVS simulator service")
-try:
-    model_delete("models/paralleldevs_simulator")
-except ModelverseException:
-    pass
+    """
+    print("Remove PDEVS model")
+    try:
+        model_delete("models/produce_consume_pdevs")
+    except ModelverseException:
+        pass
 
-# TODO: Make this a transformation to a trace metamodel
-print("Add ParallelDEVS simulator service")
-try:
-    transformation_add_AL({"MyString": "formalisms/MyString"}, {}, "models/paralleldevs_simulator", open("../../integration/code/pdevs_client.alc", "r").read())
-except ModelExists:
-    pass
+    print("Add PDEVS model")
+    try:
+        model_add("models/produce_consume_pdevs", "formalisms/ParallelDEVS", open("../../models/produce_consume_PDEVS.mvc").read())
+    except ModelExists:
+        pass
+    """
     
-controller = Controller()
+    '''
+    controller = Controller()
 
-def set_defaults(inp, defaultlist):
-    for i, v in enumerate(defaultlist):
-        if len(inp) == i + 1:
-            inp.append(v)
+    def set_defaults(inp, defaultlist):
+        for i, v in enumerate(defaultlist):
+            if len(inp) == i + 1:
+                inp.append(v)
 
-def get_bool(val):
-    if val.lower() in ["true", "yes", "1"]:
-        return True
-    else:
-        return False
-        
-def raw_inputter():
-    while 1:
-        inp = raw_input().split(" ")
-        action = inp[0]
-        if inp[0] == "simulate":
-            set_defaults(inp, ['inf'])
-            params = [{"termination_time": float(inp[1])}]
-        elif inp[0] == "big_step":
-            set_defaults(inp, ['inf'])
-            params = [{"termination_time": float(inp[1])}]
-        elif inp[0] == "realtime":
-            set_defaults(inp, [1.0, 'inf'])
-            params = [{"realtime_scale": float(inp[1]), "termination_time": float(inp[2])}]
-        elif inp[0] == "small_step":
-            set_defaults(inp, ['inf'])
-            params = [{"termination_time": float(inp[1])}]
-        elif inp[0] == "god_event":
-            if len(inp) != 4:
-                print("God Events require 3 parameters!")
-                continue
-            params = [{"model": inp[1], "attribute": inp[2], "value": inp[3]}]
-        elif inp[0] == "inject":
-            if len(inp) != 4:
-                print("Injects require 3 parameters!")
-                continue
-            params = [{"time": float(inp[1]), "port": inp[2], "event": inp[3]}]
-        elif inp[0] == "trace":
-            set_defaults(inp, [None])
-            params = [inp[1]]
-        elif inp[0] == "pause":
-            params = []
-        elif inp[0] == "exit" or inp[0] == "quit":
-            break
-        elif inp[0] == "add_breakpoint":
-            if len(inp) < 5:
-                print("Breakpoint removal requires 2 parameters!")
+    def get_bool(val):
+        if val.lower() in ["true", "yes", "1"]:
+            return True
+        else:
+            return False
+            
+    def raw_inputter():
+        while 1:
+            inp = raw_input().split(" ")
+            action = inp[0]
+            if inp[0] == "simulate":
+                set_defaults(inp, ['inf'])
+                params = [{"termination_time": float(inp[1])}]
+            elif inp[0] == "big_step":
+                set_defaults(inp, ['inf'])
+                params = [{"termination_time": float(inp[1])}]
+            elif inp[0] == "realtime":
+                set_defaults(inp, [1.0, 'inf'])
+                params = [{"realtime_scale": float(inp[1]), "termination_time": float(inp[2])}]
+            elif inp[0] == "small_step":
+                set_defaults(inp, ['inf'])
+                params = [{"termination_time": float(inp[1])}]
+            elif inp[0] == "god_event":
+                if len(inp) != 4:
+                    print("God Events require 3 parameters!")
+                    continue
+                params = [{"model": inp[1], "attribute": inp[2], "value": inp[3]}]
+            elif inp[0] == "inject":
+                if len(inp) != 4:
+                    print("Injects require 3 parameters!")
+                    continue
+                params = [{"time": float(inp[1]), "port": inp[2], "event": inp[3]}]
+            elif inp[0] == "trace":
+                set_defaults(inp, [None])
+                params = [inp[1]]
+            elif inp[0] == "pause":
+                params = []
+            elif inp[0] == "exit" or inp[0] == "quit":
+                break
+            elif inp[0] == "add_breakpoint":
+                if len(inp) < 5:
+                    print("Breakpoint removal requires 2 parameters!")
+                    continue
+                # Merge together the final part again
+                inp = [inp[0], inp[1], " ".join(inp[2:-2]).replace("\\n", "\n").replace('\\t', '\t'), get_bool(inp[-2]), get_bool(inp[-1])]
+                print("Generated parameters: " + str(inp))
+                params = inp[1:]
+            elif inp[0] == "del_breakpoint":
+                if len(inp) < 2:
+                    print("Breakpoint removal requires 1 parameter!")
+                    continue
+                params = [inp[1]]
+            elif inp[0] == "enable_breakpoint":
+                action = "toggle_breakpoint"
+                params = [inp[1], True]
+            elif inp[0] == "disable_breakpoint":
+                action = "toggle_breakpoint"
+                params = [inp[1], False]
+            elif inp[0] == "reset":
+                params = []
+            elif inp[0] == "backwards_step":
+                params = []
+            elif inp[0] == "help":
+                print("Supported operations:")
+                print("  simulate [termination_time]")
+                print("   --> Simulate until termination time is reached")
+                print("  big_step [termination_time]")
+                print("   --> Simulate a single step, unless termination time is reached")
+                print("  small_step [termination_time]")
+                print("   --> Simulate a single internal simulation step")
+                print("       Termination time is ONLY checked at the")
+                print("       check_termination phase")
+                print("  backwards_step")
+                print("   --> Step back to the previous time")
+                print("  realtime [termination_time [realtime_scale]]")
+                print("   --> Simulate in realtime until simulation time is reached")
+                print("       realtime_scale can speed up or slow down the pace")
+                print("  god_event model_name attribute_name new_value")
+                print("   --> Modify the internal state of an arbitrary model")
+                print("       model_name should be the fully qualified name")
+                print("       attribute_name is the name of the attribute to alter")
+                print("       new_value is the value to assign")
+                print("       new_value can only be a string due to string-only input")
+                print("  inject time port_name event")
+                print("   --> Put a user-defined event on an input port")
+                print("       port_name should be a fully qualified port name")
+                print("       event should be the event to put on it, string only")
+                print("  trace [filename]")
+                print("   --> Write out trace information to the specified file.")
+                print("       Leave empty to disable tracing.")
+                print("  add_breakpoint id function enabled disable_on_trigger")
+                print("   --> Add a breakpoint that will pause simulation when function returns True")
+                print("       the function should contain a definition of the 'breakpoint' function")
+                print("       and must take 3 parameters: time, model and transitioned")
+                print("       enabled indicates whether or not the breakpoint should be checked")
+                print("       disable_on_trigger determines if the breakpoint should auto-disable")
+                print("       after being triggered")
+                print("  del_breakpoint id")
+                print("   --> Remove a breakpoint")
+                print("  enable_breakpoint id")
+                print("   --> Enable the provided breakpoint")
+                print("  disable_breakpoint id")
+                print("   --> Disable the provided breakpoint")
+                print("  reset")
+                print("   --> Reset the simulation")
+                print("  exit")
+                print("   --> Stop the client")
+                print("  pause")
+                print("   --> Pause the simulation")
+                print("  quit")
+                print("   --> Stop the client")
+                print("")
+                print("Defaults: ")
+                print("  termination_time --> 'inf'")
+                print("  realtime_scale   --> 1.0")
                 continue
-            # Merge together the final part again
-            inp = [inp[0], inp[1], " ".join(inp[2:-2]).replace("\\n", "\n").replace('\\t', '\t'), get_bool(inp[-2]), get_bool(inp[-1])]
-            print("Generated parameters: " + str(inp))
-            params = inp[1:]
-        elif inp[0] == "del_breakpoint":
-            if len(inp) < 2:
-                print("Breakpoint removal requires 1 parameter!")
+            else:
+                print("Command not understood: " + str(inp))
                 continue
-            params = [inp[1]]
-        elif inp[0] == "enable_breakpoint":
-            action = "toggle_breakpoint"
-            params = [inp[1], True]
-        elif inp[0] == "disable_breakpoint":
-            action = "toggle_breakpoint"
-            params = [inp[1], False]
-        elif inp[0] == "reset":
-            params = []
-        elif inp[0] == "backwards_step":
-            params = []
-        elif inp[0] == "help":
-            print("Supported operations:")
-            print("  simulate [termination_time]")
-            print("   --> Simulate until termination time is reached")
-            print("  big_step [termination_time]")
-            print("   --> Simulate a single step, unless termination time is reached")
-            print("  small_step [termination_time]")
-            print("   --> Simulate a single internal simulation step")
-            print("       Termination time is ONLY checked at the")
-            print("       check_termination phase")
-            print("  backwards_step")
-            print("   --> Step back to the previous time")
-            print("  realtime [termination_time [realtime_scale]]")
-            print("   --> Simulate in realtime until simulation time is reached")
-            print("       realtime_scale can speed up or slow down the pace")
-            print("  god_event model_name attribute_name new_value")
-            print("   --> Modify the internal state of an arbitrary model")
-            print("       model_name should be the fully qualified name")
-            print("       attribute_name is the name of the attribute to alter")
-            print("       new_value is the value to assign")
-            print("       new_value can only be a string due to string-only input")
-            print("  inject time port_name event")
-            print("   --> Put a user-defined event on an input port")
-            print("       port_name should be a fully qualified port name")
-            print("       event should be the event to put on it, string only")
-            print("  trace [filename]")
-            print("   --> Write out trace information to the specified file.")
-            print("       Leave empty to disable tracing.")
-            print("  add_breakpoint id function enabled disable_on_trigger")
-            print("   --> Add a breakpoint that will pause simulation when function returns True")
-            print("       the function should contain a definition of the 'breakpoint' function")
-            print("       and must take 3 parameters: time, model and transitioned")
-            print("       enabled indicates whether or not the breakpoint should be checked")
-            print("       disable_on_trigger determines if the breakpoint should auto-disable")
-            print("       after being triggered")
-            print("  del_breakpoint id")
-            print("   --> Remove a breakpoint")
-            print("  enable_breakpoint id")
-            print("   --> Enable the provided breakpoint")
-            print("  disable_breakpoint id")
-            print("   --> Disable the provided breakpoint")
-            print("  reset")
-            print("   --> Reset the simulation")
-            print("  exit")
-            print("   --> Stop the client")
-            print("  pause")
-            print("   --> Pause the simulation")
-            print("  quit")
-            print("   --> Stop the client")
-            print("")
-            print("Defaults: ")
-            print("  termination_time --> 'inf'")
-            print("  realtime_scale   --> 1.0")
-            continue
-        else:
-            print("Command not understood: " + str(inp))
-            continue
-        params.insert(0, action)
-        controller.addInput(Event("mv_input", "input", [json.dumps(params)]))
-        
-input_thread = threading.Thread(target=raw_inputter)
-input_thread.daemon = True
-input_thread.start()
-
-output_listener = controller.addOutputListener(["output"])
-def outputter():
-    while 1:
-        msg = json.loads(output_listener.fetch(-1).getParameters()[0])
-        print("%s" % msg["name"])
-        pprint(msg["params"])
-output_thread = threading.Thread(target=outputter)
-output_thread.daemon = True
-output_thread.start()
+            params.insert(0, action)
+            controller.addInput(Event("mv_input", "input", [json.dumps(params)]))
+            
+    input_thread = threading.Thread(target=raw_inputter)
+    input_thread.daemon = True
+    input_thread.start()
 
-print("Starting PyPDEVS service...")
-transformation_execute_AL("models/paralleldevs_simulator", {"MyString": "models/example_PS_DEVS_String"}, {}, statechart=(controller, "mv_input", "mv_output"))
+    output_listener = controller.addOutputListener(["output"])
+    def outputter():
+        while 1:
+            msg = json.loads(output_listener.fetch(-1).getParameters()[0])
+            print("%s" % msg["name"])
+            pprint(msg["params"])
+    output_thread = threading.Thread(target=outputter)
+    output_thread.daemon = True
+    output_thread.start()
 
-print("Starting controller")
-controller.start()
+    print("Starting controller")
+    controller.start()
+    '''

+ 21 - 0
interface/PDEVS/register_service.py

@@ -46,6 +46,27 @@ def pypdevs_service(port):
     controller.start()
     
 service_register("pypdevs_simulator", pypdevs_service)
+
+print("Remove ParallelDEVS simulator service")
+try:
+    model_delete("models/paralleldevs_simulator")
+except ModelverseException:
+    pass
+
+# TODO: Make this a transformation to a trace metamodel
+print("Add ParallelDEVS simulator service")
+try:
+    transformation_add_AL({}, {}, "models/paralleldevs_simulator", open("../../integration/code/pdevs_client.alc", "r").read())
+except ModelExists:
+    pass
+    
+''' TODO RPC with task name '''
+
+print("Starting PyPDEVS service...")
+task_name = transformation_execute_AL("models/paralleldevs_simulator", {"MyString": "models/example_PS_DEVS_String"}, {})
+
+print(task_name)
+
 try:
     while True:
         # Stay active, as we shouldn't exit while the service is running!