console.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. import sys
  2. from modelverse import *
  3. import random, re, json
  4. from interface import Controller
  5. from pprint import pprint
  6. from multiprocessing import Process, Pipe, freeze_support
  7. def register_service():
  8. sys.path.append('pypdevs/src')
  9. from simulator import Controller
  10. import threading, time
  11. print 'Registering service...'
  12. init('msdl.uantwerpen.be:8001')
  13. login("pypdevs_service", "my_password")
  14. def pypdevs_service(port):
  15. exec service_get(port) in globals()
  16. controller = Controller(Root())
  17. def inputter():
  18. print "Waiting for input..."
  19. while 1:
  20. input = service_get(port)
  21. print 'raw input = %s' % input
  22. params = json.loads(input)
  23. print 'json parsed = %s' % params
  24. if not isinstance(params, list):
  25. params = [params]
  26. print "Sending input to simulator: %s" % params
  27. if (len(params) > 1):
  28. controller.addInput(Event(params[0], "request", params[1:]))
  29. else:
  30. controller.addInput(Event(params[0], "request", []))
  31. input_thread = threading.Thread(target=inputter)
  32. input_thread.daemon = True
  33. input_thread.start()
  34. output_listener = controller.addOutputListener(["reply"])
  35. def outputter():
  36. print "Waiting for output..."
  37. while 1:
  38. output_val = output_listener.fetch(-1)
  39. print "Got output from simulator: %s" % output_val
  40. service_set(port, json.dumps({"name": output_val.getName(), "port": output_val.getPort(), "params": output_val.getParameters()}))
  41. output_thread = threading.Thread(target=outputter)
  42. output_thread.daemon = True
  43. output_thread.start()
  44. controller.start()
  45. service_register("pypdevs_simulator", pypdevs_service)
  46. try:
  47. while True:
  48. # Stay active, as we shouldn't exit while the service is running!
  49. time.sleep(1)
  50. finally:
  51. service_stop()
  52. def start_pypdevs_client(conn):
  53. init('msdl.uantwerpen.be:8001')
  54. login("admin", "admin")
  55. print("Remove ParallelDEVS simulator client")
  56. try:
  57. model_delete("models/paralleldevs_simulator")
  58. except ModelverseException:
  59. pass
  60. # TODO: Make this a transformation to a trace metamodel
  61. print("Add ParallelDEVS simulator client")
  62. try:
  63. transformation_add_AL({"MyString": "formalisms/MyString"}, {}, "models/paralleldevs_simulator", open("../../integration/code/pdevs_client.alc", "r").read())
  64. except ModelExists:
  65. pass
  66. print("Starting PyPDEVS client...")
  67. task_name = transformation_execute_AL("models/paralleldevs_simulator", {"MyString": "models/example_PS_DEVS_String"}, {})
  68. conn.send(task_name)
  69. conn.close()
  70. if __name__ == '__main__':
  71. freeze_support()
  72. p = Process(target=register_service)
  73. p.start()
  74. print("Init")
  75. init("msdl.uantwerpen.be:8001")
  76. print("Login")
  77. login("admin", "admin")
  78. if "example_PS_DEVS_String" not in model_list("models"):
  79. print("Remove ProductionSystem metamodel")
  80. try:
  81. model_delete("formalisms/ProductionSystem")
  82. except ModelverseException:
  83. pass
  84. # Add the metamodel for ProductionSystem
  85. print("Add ProductionSystem metamodel")
  86. try:
  87. model_add("formalisms/ProductionSystem", "formalisms/SimpleClassDiagrams", open("../../models/production_system_design.mvc").read())
  88. except ModelExists:
  89. pass
  90. print("Remove model")
  91. try:
  92. model_delete("models/example_PS")
  93. except ModelverseException:
  94. pass
  95. print("Add model")
  96. try:
  97. model_add("models/example_PS", "formalisms/ProductionSystem", open("../../models/example_PS.mvc").read())
  98. except ModelExists:
  99. pass
  100. print("Remove ParallelDEVS metamodel")
  101. try:
  102. model_delete("formalisms/ParallelDEVS")
  103. except ModelverseException:
  104. pass
  105. # Add the metamodel for Parallel DEVS
  106. print("Add ParallelDEVS metamodel")
  107. try:
  108. model_add("formalisms/ParallelDEVS", "formalisms/SimpleClassDiagrams", open("../../models/paralleldevs_design.mvc").read())
  109. except ModelExists:
  110. pass
  111. def traceability_PS2DEVS():
  112. instantiate(None, "Association", ("ProductionSystem/Machine", "ParallelDEVS/BaseDEVSBlock"), ID="PS2DEVS_typelink")
  113. instantiate(None, "Association", ("ProductionSystem/Machine", "ParallelDEVS/DEVSInstance"), ID="PS2DEVS_instancelink")
  114. print("Remove PS->DEVS transformation model")
  115. try:
  116. model_delete("models/ps_to_devs")
  117. except ModelverseException:
  118. pass
  119. print("Add PS->DEVS transformation model")
  120. transformation_add_MT({"ProductionSystem": "formalisms/ProductionSystem"}, {"ParallelDEVS": "formalisms/ParallelDEVS"}, "models/ps_to_devs", open("../../models/ps_to_devs.mvc", 'r').read(), traceability_PS2DEVS)
  121. print("Execute PS->DEVS transformation")
  122. transformation_execute_MT("models/ps_to_devs", {"ProductionSystem": "models/example_PS"}, {"ParallelDEVS": "models/example_PS_DEVS"}, tracability_model="models/PS_DEVS_traceability")
  123. print("Remove MyString metamodel")
  124. try:
  125. model_delete("formalisms/MyString")
  126. except ModelverseException:
  127. pass
  128. # Add the metamodel for String
  129. print("Add MyString metamodel")
  130. try:
  131. model_add("formalisms/MyString", "formalisms/SimpleClassDiagrams", open("../../models/string.mvc").read())
  132. except ModelExists:
  133. pass
  134. # Remove the action language code to transform between DEVS->String
  135. print("Remove DEVS->String transformation model")
  136. try:
  137. model_delete("models/paralleldevs_to_string")
  138. except ModelverseException:
  139. pass
  140. # Add the action language code to transform between DEVS->String
  141. print("Add DEVS->String transformation model")
  142. try:
  143. transformation_add_AL({"ParallelDEVS": "formalisms/ParallelDEVS"}, {"MyString": "formalisms/MyString"}, "models/paralleldevs_to_string", open("../../models/devs_to_string.alc", "r").read())
  144. except ModelExists:
  145. pass
  146. print("Execute DEVS->String transformation")
  147. transformation_execute_AL("models/paralleldevs_to_string", {"ParallelDEVS": "models/example_PS_DEVS"}, {"MyString": "models/example_PS_DEVS_String"})
  148. print("Starting PyPDEVS client")
  149. parent_conn, child_conn = Pipe()
  150. p1 = Process(target=start_pypdevs_client, args=(child_conn,))
  151. p1.start()
  152. print 'got process output: %s' % parent_conn.recv()
  153. """
  154. print("Remove PDEVS model")
  155. try:
  156. model_delete("models/produce_consume_pdevs")
  157. except ModelverseException:
  158. pass
  159. print("Add PDEVS model")
  160. try:
  161. model_add("models/produce_consume_pdevs", "formalisms/ParallelDEVS", open("../../models/produce_consume_PDEVS.mvc").read())
  162. except ModelExists:
  163. pass
  164. """
  165. '''
  166. controller = Controller()
  167. def set_defaults(inp, defaultlist):
  168. for i, v in enumerate(defaultlist):
  169. if len(inp) == i + 1:
  170. inp.append(v)
  171. def get_bool(val):
  172. if val.lower() in ["true", "yes", "1"]:
  173. return True
  174. else:
  175. return False
  176. def raw_inputter():
  177. while 1:
  178. inp = raw_input().split(" ")
  179. action = inp[0]
  180. if inp[0] == "simulate":
  181. set_defaults(inp, ['inf'])
  182. params = [{"termination_time": float(inp[1])}]
  183. elif inp[0] == "big_step":
  184. set_defaults(inp, ['inf'])
  185. params = [{"termination_time": float(inp[1])}]
  186. elif inp[0] == "realtime":
  187. set_defaults(inp, [1.0, 'inf'])
  188. params = [{"realtime_scale": float(inp[1]), "termination_time": float(inp[2])}]
  189. elif inp[0] == "small_step":
  190. set_defaults(inp, ['inf'])
  191. params = [{"termination_time": float(inp[1])}]
  192. elif inp[0] == "god_event":
  193. if len(inp) != 4:
  194. print("God Events require 3 parameters!")
  195. continue
  196. params = [{"model": inp[1], "attribute": inp[2], "value": inp[3]}]
  197. elif inp[0] == "inject":
  198. if len(inp) != 4:
  199. print("Injects require 3 parameters!")
  200. continue
  201. params = [{"time": float(inp[1]), "port": inp[2], "event": inp[3]}]
  202. elif inp[0] == "trace":
  203. set_defaults(inp, [None])
  204. params = [inp[1]]
  205. elif inp[0] == "pause":
  206. params = []
  207. elif inp[0] == "exit" or inp[0] == "quit":
  208. break
  209. elif inp[0] == "add_breakpoint":
  210. if len(inp) < 5:
  211. print("Breakpoint removal requires 2 parameters!")
  212. continue
  213. # Merge together the final part again
  214. inp = [inp[0], inp[1], " ".join(inp[2:-2]).replace("\\n", "\n").replace('\\t', '\t'), get_bool(inp[-2]), get_bool(inp[-1])]
  215. print("Generated parameters: " + str(inp))
  216. params = inp[1:]
  217. elif inp[0] == "del_breakpoint":
  218. if len(inp) < 2:
  219. print("Breakpoint removal requires 1 parameter!")
  220. continue
  221. params = [inp[1]]
  222. elif inp[0] == "enable_breakpoint":
  223. action = "toggle_breakpoint"
  224. params = [inp[1], True]
  225. elif inp[0] == "disable_breakpoint":
  226. action = "toggle_breakpoint"
  227. params = [inp[1], False]
  228. elif inp[0] == "reset":
  229. params = []
  230. elif inp[0] == "backwards_step":
  231. params = []
  232. elif inp[0] == "help":
  233. print("Supported operations:")
  234. print(" simulate [termination_time]")
  235. print(" --> Simulate until termination time is reached")
  236. print(" big_step [termination_time]")
  237. print(" --> Simulate a single step, unless termination time is reached")
  238. print(" small_step [termination_time]")
  239. print(" --> Simulate a single internal simulation step")
  240. print(" Termination time is ONLY checked at the")
  241. print(" check_termination phase")
  242. print(" backwards_step")
  243. print(" --> Step back to the previous time")
  244. print(" realtime [termination_time [realtime_scale]]")
  245. print(" --> Simulate in realtime until simulation time is reached")
  246. print(" realtime_scale can speed up or slow down the pace")
  247. print(" god_event model_name attribute_name new_value")
  248. print(" --> Modify the internal state of an arbitrary model")
  249. print(" model_name should be the fully qualified name")
  250. print(" attribute_name is the name of the attribute to alter")
  251. print(" new_value is the value to assign")
  252. print(" new_value can only be a string due to string-only input")
  253. print(" inject time port_name event")
  254. print(" --> Put a user-defined event on an input port")
  255. print(" port_name should be a fully qualified port name")
  256. print(" event should be the event to put on it, string only")
  257. print(" trace [filename]")
  258. print(" --> Write out trace information to the specified file.")
  259. print(" Leave empty to disable tracing.")
  260. print(" add_breakpoint id function enabled disable_on_trigger")
  261. print(" --> Add a breakpoint that will pause simulation when function returns True")
  262. print(" the function should contain a definition of the 'breakpoint' function")
  263. print(" and must take 3 parameters: time, model and transitioned")
  264. print(" enabled indicates whether or not the breakpoint should be checked")
  265. print(" disable_on_trigger determines if the breakpoint should auto-disable")
  266. print(" after being triggered")
  267. print(" del_breakpoint id")
  268. print(" --> Remove a breakpoint")
  269. print(" enable_breakpoint id")
  270. print(" --> Enable the provided breakpoint")
  271. print(" disable_breakpoint id")
  272. print(" --> Disable the provided breakpoint")
  273. print(" reset")
  274. print(" --> Reset the simulation")
  275. print(" exit")
  276. print(" --> Stop the client")
  277. print(" pause")
  278. print(" --> Pause the simulation")
  279. print(" quit")
  280. print(" --> Stop the client")
  281. print("")
  282. print("Defaults: ")
  283. print(" termination_time --> 'inf'")
  284. print(" realtime_scale --> 1.0")
  285. continue
  286. else:
  287. print("Command not understood: " + str(inp))
  288. continue
  289. params.insert(0, action)
  290. controller.addInput(Event("mv_input", "input", [json.dumps(params)]))
  291. input_thread = threading.Thread(target=raw_inputter)
  292. input_thread.daemon = True
  293. input_thread.start()
  294. output_listener = controller.addOutputListener(["output"])
  295. def outputter():
  296. while 1:
  297. msg = json.loads(output_listener.fetch(-1).getParameters()[0])
  298. print("%s" % msg["name"])
  299. pprint(msg["params"])
  300. output_thread = threading.Thread(target=outputter)
  301. output_thread.daemon = True
  302. output_thread.start()
  303. print("Starting controller")
  304. controller.start()
  305. '''