launcher.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import os
  2. import subprocess
  3. import re
  4. import time
  5. import sys
  6. import configparser
  7. class Launcher(object):
  8. def __init__(self):
  9. pass
  10. @staticmethod
  11. def __terminal_output(message: str):
  12. print(f"[Launcher] {message}")
  13. def run(self):
  14. config = configparser.ConfigParser()
  15. config.read('instrument_setting.ini')
  16. server_env = os.environ.copy()
  17. variables_to_set = {
  18. "PLC_SIM_SERVER_DIGITAL_MULTIMETER": config['PLC_SIM_SERVER']['DIGITAL_MULTIMETER'],
  19. "PLC_SIM_SERVER_DIGITAL_OSCILLOSCOPE": config['PLC_SIM_SERVER']['DIGITAL_OSCILLOSCOPE'],
  20. "PLC_SIM_SERVER_WAVEFORM_GENERATOR": config['PLC_SIM_SERVER']['WAVEFORM_GENERATOR'],
  21. "PLC_SIM_SERVER_ANALOG_ELECTRONIC_LOAD": config['PLC_SIM_SERVER']['ANALOG_ELECTRONIC_LOAD']
  22. }
  23. for var, value in variables_to_set.items():
  24. server_env[var] = value
  25. print(f"Using config: {var} = {value}")
  26. server_process = subprocess.Popen(["./server/server.exe"], stdout=subprocess.PIPE,
  27. stderr=subprocess.STDOUT, text=True, bufsize=1, env=server_env)
  28. server_ready = False
  29. port: int = 1024
  30. for line in iter(server_process.stdout.readline, ""):
  31. print(f"line: {line}")
  32. match = re.search(r"Server is running on port \[(\d+)\].", line.strip())
  33. if match is not None:
  34. port = int(match.group(1))
  35. break
  36. for line in iter(server_process.stdout.readline, ""):
  37. if "[Server] Server program is ready..." in line:
  38. server_ready = True
  39. break
  40. if not server_ready:
  41. print("Server failed to start. Exiting.")
  42. server_process.kill()
  43. return
  44. print("Server is ready, starting client...")
  45. client_env = os.environ.copy()
  46. client_env["PLC_SIM_PORT"] = f"{port}"
  47. client_process = subprocess.Popen(["./PLC-SIM.exe"], env=client_env)
  48. try:
  49. while True:
  50. return_code = client_process.poll()
  51. if return_code is not None:
  52. print("Client process terminated with return code", return_code)
  53. break
  54. time.sleep(0.5)
  55. server_process.terminate()
  56. server_process.wait()
  57. except KeyboardInterrupt:
  58. server_process.terminate()
  59. client_process.terminate()
  60. server_process.wait()
  61. except Exception as e:
  62. print(f"An error occurred: {str(e)}")
  63. server_process.terminate()
  64. client_process.terminate()
  65. server_process.wait()
  66. client_process.wait()
  67. sys.exit(1)
  68. # Usage:
  69. launcher = Launcher()
  70. launcher.run()