launcher.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. print(f"{line}")
  38. if "[Server] Server program is ready..." in line:
  39. server_ready = True
  40. break
  41. if not server_ready:
  42. print("Server failed to start. Exiting.")
  43. server_process.kill()
  44. return
  45. print("Server is ready, starting client...")
  46. client_env = os.environ.copy()
  47. client_env["PLC_SIM_PORT"] = f"{port}"
  48. client_process = subprocess.Popen(["./PLC-SIM.exe"], env=client_env)
  49. try:
  50. while True:
  51. return_code = client_process.poll()
  52. if return_code is not None:
  53. print("Client process terminated with return code", return_code)
  54. break
  55. for line in iter(server_process.stdout.readline, ""):
  56. print(f"[Server] {line}")
  57. time.sleep(0.5)
  58. server_process.terminate()
  59. server_process.wait()
  60. except Exception as e:
  61. print(f"An error occurred: {str(e)}")
  62. server_process.terminate()
  63. client_process.terminate()
  64. server_process.wait()
  65. client_process.wait()
  66. sys.exit(1)
  67. # Usage:
  68. launcher = Launcher()
  69. launcher.run()