console.py 16 KB

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