console.py 17 KB

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