console.py 17 KB

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