server.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. from typing import Optional
  2. from flask import Flask, request, jsonify
  3. from flask_cors import CORS
  4. from program_core import ProgramCore
  5. from program_public_tools import ProgramPublicTools
  6. import time
  7. class Server:
  8. def __init__(self, server_ip: str = '0.0.0.0', server_port: Optional[int] = None):
  9. self.__pubtools: ProgramPublicTools = ProgramPublicTools()
  10. self.__server_ip: str = server_ip
  11. self.__server_port: Optional[int] = server_port
  12. self.__server_ip_init()
  13. self.__core: ProgramCore = ProgramCore(self.__pubtools)
  14. self.__core.start_core()
  15. self.__app = Flask(__name__)
  16. CORS(self.__app)
  17. self.__setup_routes()
  18. self.__send_server_completed_flag()
  19. self.__buffer_error_rate_percent_1_value = 0
  20. self.__buffer_error_rate_percent_1_time = time.time()
  21. self.__buffer_error_rate_percent_2_value = 0
  22. self.__buffer_error_rate_percent_2_time = time.time()
  23. self.__buffer_speed_kbps_1_value = 0
  24. self.__buffer_speed_kbps_1_time = time.time()
  25. self.__buffer_speed_kbps_2_value = 0
  26. self.__buffer_speed_kbps_2_time = time.time()
  27. @staticmethod
  28. def __send_server_completed_flag():
  29. print("[Server] Server program is ready......")
  30. def __server_ip_init(self):
  31. if self.__server_port is None:
  32. self.__server_port = self.__pubtools.find_available_server_port(number=1, address=self.__server_ip)[0]
  33. print(f"Server is running on port [{self.__server_port}].")
  34. print(f"Server is running on port [{self.__server_port}].")
  35. print(f"Server is running on port [{self.__server_port}].")
  36. def start(self):
  37. self.__app.run(host=self.__server_ip, port=self.__server_port, debug=False)
  38. self.__server_debug_output()
  39. def __server_debug_output(self):
  40. _, _, url = self.__core.instrument_controller.services.digital_oscilloscope.keep_listening()
  41. print(f"[Server Debug Output]: OSC Stream Server is running on <{url}>")
  42. print(f"[Server Debug Output]: OSC Stream Server is running on <{url}>")
  43. print(f"[Server Debug Output]: OSC Stream Server is running on <{url}>")
  44. print(f"[Server Debug Output]: OSC Stream Server is running on <{url}>")
  45. print(f"[Server Debug Output]: OSC Stream Server is running on <{url}>")
  46. @staticmethod
  47. def __instrument_get_not_connect_string(not_connect_list: list[str]) -> str:
  48. response_string: str = "not_connect_list:"
  49. for not_connect_item in not_connect_list:
  50. response_string = response_string + " " + not_connect_item
  51. return response_string
  52. def __setup_routes(self):
  53. @self.__app.route("/")
  54. def home():
  55. return "Server is running."
  56. @self.__app.route("/instrument/not_connect_list", methods=['GET'])
  57. def instrument_not_connect_list():
  58. # print("[Server] Response " + "" + ".")
  59. print("[Server] Response " + "/instrument/not_connect_list" + ".")
  60. not_connect_list: list[str] = self.__core.instrument_controller.services.check()
  61. return self.__instrument_get_not_connect_string(not_connect_list)
  62. @self.__app.route("/instrument/digital_multimeter/connection_status", methods=['GET'])
  63. def instrument_digital_multimeter_connection_status():
  64. # print("[Server] Response " + "" + ".")
  65. print("[Server] Response " + "/instrument/digital_multimeter/connection_status" + ".")
  66. connection_status: bool = (self.__core.instrument_controller.services.digital_multimeter is not None)
  67. return f"connection_status: {connection_status}"
  68. @self.__app.route("/instrument/digital_oscilloscope/connection_status", methods=['GET'])
  69. def instrument_digital_oscilloscope_connection_status():
  70. # print("[Server] Response " + "" + ".")
  71. print("[Server] Response " + "/instrument/digital_oscilloscope/connection_status" + ".")
  72. connection_status: bool = (self.__core.instrument_controller.services.digital_oscilloscope is not None)
  73. return f"connection_status: {connection_status}"
  74. @self.__app.route("/instrument/waveform_generator/connection_status", methods=['GET'])
  75. def instrument_waveform_generator_connection_status():
  76. # print("[Server] Response " + "" + ".")
  77. print("[Server] Response " + "/instrument/waveform_generator/connection_status" + ".")
  78. connection_status: bool = (self.__core.instrument_controller.services.waveform_generator is not None)
  79. return f"connection_status: {connection_status}"
  80. @self.__app.route("/instrument/analog_electronic_load/connection_status", methods=['GET'])
  81. def instrument_analog_electronic_load_connection_status():
  82. # print("[Server] Response " + "" + ".")
  83. print("[Server] Response " + "/instrument/analog_electronic_load/connection_status" + ".")
  84. connection_status: bool = (self.__core.instrument_controller.services.analog_electronic_load is not None)
  85. return f"connection_status: {connection_status}"
  86. @self.__app.route("/instrument/digital_multimeter/keep_listening", methods=['GET'])
  87. def instrument_digital_multimeter_keep_listening():
  88. # print("[Server] Response " + "" + ".")
  89. print("[Server] Response " + "/instrument/digital_multimeter/keep_listening" + ".")
  90. if self.__core.instrument_controller.services.digital_multimeter is not None:
  91. self.__core.instrument_controller.services.digital_multimeter.keep_listening()
  92. return f"keep_listening"
  93. else:
  94. return "None"
  95. @self.__app.route("/instrument/digital_multimeter/get_range", methods=['GET'])
  96. def instrument_digital_multimeter_get_range():
  97. # print("[Server] Response " + "" + ".")
  98. print("[Server] Response " + "/instrument/digital_multimeter/get_range" + ".")
  99. if self.__core.instrument_controller.services.digital_multimeter is not None:
  100. range_list: list[str] = self.__core.instrument_controller.services.digital_multimeter.get_range()
  101. response_string: str = "get_range:"
  102. for rang_type_item in range_list:
  103. response_string = response_string + " " + rang_type_item
  104. return response_string
  105. else:
  106. return "None"
  107. @self.__app.route("/instrument/digital_multimeter/set_range", methods=['GET'])
  108. def instrument_digital_multimeter_set_range():
  109. # print("[Server] Response " + "" + ".")
  110. print("[Server] Response " + "/instrument/digital_multimeter/set_range" + ".")
  111. if self.__core.instrument_controller.services.digital_multimeter is not None:
  112. range_string = request.args.get('range')
  113. range_type = self.__core.instrument_controller.services.digital_multimeter.solve_range_string(
  114. range_string)
  115. self.__core.instrument_controller.services.digital_multimeter.set_range(range_type)
  116. return f"set_range: {range_string}"
  117. else:
  118. return "None"
  119. @self.__app.route("/instrument/digital_multimeter/get_value", methods=['GET'])
  120. def instrument_digital_multimeter_get_value():
  121. # print("[Server] Response " + "" + ".")
  122. print("[Server] Response " + "/instrument/digital_multimeter/get_value" + ".")
  123. if self.__core.instrument_controller.services.digital_multimeter is not None:
  124. get_value = self.__core.instrument_controller.services.digital_multimeter.get_value_latest()
  125. return f"get_value: {get_value}"
  126. else:
  127. return "None"
  128. @self.__app.route("/instrument/digital_oscilloscope/keep_listening", methods=['GET'])
  129. def instrument_digital_oscilloscope_keep_listening():
  130. # print("[Server] Response " + "" + ".")
  131. print("[Server] Response " + "/instrument/digital_oscilloscope/keep_listening" + ".")
  132. if self.__core.instrument_controller.services.digital_oscilloscope is not None:
  133. _, v_port, v_url = self.__core.instrument_controller.services.digital_oscilloscope.keep_listening()
  134. return f"keep_listening: {v_port} {v_url}"
  135. else:
  136. return "None"
  137. @self.__app.route("/instrument/digital_oscilloscope/export_image", methods=['GET'])
  138. def instrument_digital_oscilloscope_export_image():
  139. # print("[Server] Response " + "" + ".")
  140. print("[Server] Response " + "/instrument/digital_oscilloscope/export_image" + ".")
  141. if self.__core.instrument_controller.services.digital_oscilloscope is not None:
  142. get_time: str = self.__core.instrument_controller.services.digital_oscilloscope.save_img()
  143. return get_time
  144. else:
  145. return "None"
  146. # self.__core.reboot_serial_controller()
  147. # return "success"
  148. @self.__app.route("/instrument/waveform_generator/output_start", methods=['GET'])
  149. def instrument_waveform_generator_output_start():
  150. # print("[Server] Response " + "" + ".")
  151. print("[Server] Response " + "/instrument/waveform_generator/output_start" + ".")
  152. if self.__core.instrument_controller.services.waveform_generator is not None:
  153. self.__core.instrument_controller.services.waveform_generator.output_start()
  154. return f"output_start"
  155. else:
  156. return "None"
  157. @self.__app.route("/instrument/waveform_generator/output_restart", methods=['GET'])
  158. def instrument_waveform_generator_output_restart():
  159. # print("[Server] Response " + "" + ".")
  160. print("[Server] Response " + "/instrument/waveform_generator/output_restart" + ".")
  161. if self.__core.instrument_controller.services.waveform_generator is not None:
  162. self.__core.instrument_controller.services.waveform_generator.output_restart()
  163. return f"output_restart"
  164. else:
  165. return "None"
  166. @self.__app.route("/instrument/waveform_generator/output_pause", methods=['GET'])
  167. def instrument_waveform_generator_output_pause():
  168. # print("[Server] Response " + "" + ".")
  169. print("[Server] Response " + "/instrument/waveform_generator/output_pause" + ".")
  170. if self.__core.instrument_controller.services.waveform_generator is not None:
  171. self.__core.instrument_controller.services.waveform_generator.output_pause()
  172. return f"output_pause"
  173. else:
  174. return "None"
  175. @self.__app.route("/instrument/waveform_generator/config/apply_config", methods=['GET'])
  176. def instrument_waveform_generator_config_apply_config():
  177. # print("[Server] Response " + "" + ".")
  178. print("[Server] Response " + "/instrument/waveform_generator/config/apply_config" + ".")
  179. if self.__core.instrument_controller.services.waveform_generator is not None:
  180. self.__core.instrument_controller.services.waveform_generator.apply_config(True)
  181. return "apply_config"
  182. else:
  183. return "None"
  184. @self.__app.route("/instrument/waveform_generator/config/set_enable", methods=['GET'])
  185. def instrument_waveform_generator_config_set_enable():
  186. # print("[Server] Response " + "" + ".")
  187. print("[Server] Response " + "/instrument/waveform_generator/config/set_enable" + ".")
  188. channel_string: str = request.args.get('channel')
  189. enable_string: str = request.args.get('enable').lower()
  190. if enable_string == "true":
  191. enable: bool = True
  192. else:
  193. enable: bool = False
  194. if self.__core.instrument_controller.services.waveform_generator is not None:
  195. channel = self.__core.instrument_controller.services.waveform_generator.set_enable(channel_string,
  196. enable)
  197. return f"set_enable: {channel} {enable}"
  198. else:
  199. return f"set_enable: None None"
  200. @self.__app.route("/instrument/waveform_generator/config/get_type", methods=['GET'])
  201. def instrument_waveform_generator_config_get_type():
  202. # print("[Server] Response " + "" + ".")
  203. print("[Server] Response " + "/instrument/waveform_generator/config/get_type" + ".")
  204. if self.__core.instrument_controller.services.waveform_generator is not None:
  205. res: str = self.__core.instrument_controller.services.waveform_generator.config_channel_1.get_type_string()
  206. return f"get_type: " + res
  207. else:
  208. return f"get_type: " + "None"
  209. @self.__app.route("/instrument/waveform_generator/config/set_type", methods=['GET'])
  210. def instrument_waveform_generator_config_set_type():
  211. # print("[Server] Response " + "" + ".")
  212. print("[Server] Response " + "/instrument/waveform_generator/config/set_type" + ".")
  213. channel_string: str = request.args.get('channel')
  214. type_string: str = request.args.get('type')
  215. if self.__core.instrument_controller.services.waveform_generator is not None:
  216. channel, config = self.__core.instrument_controller.services.waveform_generator.get_config(
  217. channel_string)
  218. config.type = config.match_type_string(type_string)
  219. return f"set_type: {channel} {type_string}"
  220. else:
  221. return f"set_type: None None"
  222. @self.__app.route("/instrument/waveform_generator/config/set_freq", methods=['GET'])
  223. def instrument_waveform_generator_config_set_freq():
  224. # print("[Server] Response " + "" + ".")
  225. print("[Server] Response " + "/instrument/waveform_generator/config/set_freq" + ".")
  226. channel_string: str = request.args.get('channel')
  227. freq: float = float(request.args.get('freq'))
  228. if self.__core.instrument_controller.services.waveform_generator is not None:
  229. channel, config = self.__core.instrument_controller.services.waveform_generator.get_config(
  230. channel_string)
  231. config.freq = freq
  232. return f"set_freq: {channel} {freq}"
  233. else:
  234. return f"set_freq: None None"
  235. @self.__app.route("/instrument/waveform_generator/config/get_freq_unit", methods=['GET'])
  236. def instrument_waveform_generator_config_get_freq_unit():
  237. # print("[Server] Response " + "" + ".")
  238. print("[Server] Response " + "/instrument/waveform_generator/config/get_freq_unit" + ".")
  239. if self.__core.instrument_controller.services.waveform_generator is not None:
  240. _, config = self.__core.instrument_controller.services.waveform_generator.get_config("1")
  241. unit_type_string: str = config.get_freq_unit_type_string()
  242. return f"get_freq_unit: {unit_type_string}"
  243. else:
  244. return f"get_freq_unit: None"
  245. @self.__app.route("/instrument/waveform_generator/config/set_freq_unit", methods=['GET'])
  246. def instrument_waveform_generator_config_set_freq_unit():
  247. # print("[Server] Response " + "" + ".")
  248. print("[Server] Response " + "/instrument/waveform_generator/config/set_freq_unit" + ".")
  249. channel_string: str = request.args.get('channel')
  250. freq_unit_string: str = request.args.get('freq_unit')
  251. if self.__core.instrument_controller.services.waveform_generator is not None:
  252. channel, config = self.__core.instrument_controller.services.waveform_generator.get_config(
  253. channel_string)
  254. config.freq_unit = config.match_freq_unit_type_string(freq_unit_string)
  255. return f"set_freq_unit: {channel} {freq_unit_string}"
  256. else:
  257. return f"set_freq_unit: None None"
  258. @self.__app.route("/instrument/waveform_generator/config/set_high_level", methods=['GET'])
  259. def instrument_waveform_generator_config_set_high_level():
  260. # print("[Server] Response " + "" + ".")
  261. print("[Server] Response " + "/instrument/waveform_generator/config/set_high_level" + ".")
  262. channel_string: str = request.args.get('channel')
  263. high_level: float = float(request.args.get('high_level'))
  264. if self.__core.instrument_controller.services.waveform_generator is not None:
  265. channel, config = self.__core.instrument_controller.services.waveform_generator.get_config(
  266. channel_string)
  267. config.high_level = high_level
  268. return f"set_high_level: {channel} {high_level}"
  269. else:
  270. return f"set_high_level: None None"
  271. @self.__app.route("/instrument/waveform_generator/config/set_low_level", methods=['GET'])
  272. def instrument_waveform_generator_config_set_low_level():
  273. # print("[Server] Response " + "" + ".")
  274. print("[Server] Response " + "/instrument/waveform_generator/config/set_low_level" + ".")
  275. channel_string: str = request.args.get('channel')
  276. low_level: float = float(request.args.get('low_level'))
  277. if self.__core.instrument_controller.services.waveform_generator is not None:
  278. channel, config = self.__core.instrument_controller.services.waveform_generator.get_config(
  279. channel_string)
  280. config.low_level = low_level
  281. return f"set_low_level: {channel} {low_level}"
  282. else:
  283. return f"set_low_level: None None"
  284. @self.__app.route("/instrument/waveform_generator/config/get_level_unit", methods=['GET'])
  285. def instrument_waveform_generator_config_get_level_unit():
  286. # print("[Server] Response " + "" + ".")
  287. print("[Server] Response " + "/instrument/waveform_generator/config/get_level_unit" + ".")
  288. if self.__core.instrument_controller.services.waveform_generator is not None:
  289. _, config = self.__core.instrument_controller.services.waveform_generator.get_config("1")
  290. unit_type_string: str = config.get_freq_unit_type_string()
  291. return f"get_freq_unit: {unit_type_string}"
  292. else:
  293. return f"get_freq_unit: None"
  294. @self.__app.route("/instrument/waveform_generator/config/set_high_level_unit", methods=['GET'])
  295. def instrument_waveform_generator_config_set_high_level_unit():
  296. # print("[Server] Response " + "" + ".")
  297. print("[Server] Response " + "/instrument/waveform_generator/config/set_high_level_unit" + ".")
  298. channel_string: str = request.args.get('channel')
  299. high_level_unit_string: str = request.args.get('high_level_unit')
  300. if self.__core.instrument_controller.services.waveform_generator is not None:
  301. channel, config = self.__core.instrument_controller.services.waveform_generator.get_config(
  302. channel_string)
  303. config.high_level_unit = config.match_level_unit_type_string(high_level_unit_string)
  304. return f"set_high_level_unit: {channel} {high_level_unit_string}"
  305. else:
  306. return f"set_high_level_unit: None {high_level_unit_string}"
  307. @self.__app.route("/instrument/waveform_generator/config/set_low_level_unit", methods=['GET'])
  308. def instrument_waveform_generator_config_set_low_level_unit():
  309. # print("[Server] Response " + "" + ".")
  310. print("[Server] Response " + "/instrument/waveform_generator/config/set_low_level_unit" + ".")
  311. channel_string: str = request.args.get('channel')
  312. low_level_unit_string: str = request.args.get('low_level_unit')
  313. if self.__core.instrument_controller.services.waveform_generator is not None:
  314. channel, config = self.__core.instrument_controller.services.waveform_generator.get_config(
  315. channel_string)
  316. config.low_level_unit = config.match_level_unit_type_string(low_level_unit_string)
  317. return f"set_low_level_unit: {channel} {low_level_unit_string}"
  318. else:
  319. return f"set_low_level_unit: None {low_level_unit_string}"
  320. @self.__app.route("/instrument/waveform_generator/config/apply_all_setting", methods=['GET'])
  321. def instrument_waveform_generator_config_apply_all_setting():
  322. # print("[Server] Response " + "" + ".")
  323. print("[Server] Response " + "/instrument/waveform_generator/config/apply_all_setting" + ".")
  324. if self.__core.instrument_controller.services.waveform_generator is not None:
  325. waveform_type: str = request.args.get('type')
  326. waveform_freq: float = float(request.args.get('freq'))
  327. waveform_freq_unit: str = request.args.get('freq_unit')
  328. waveform_voltage: float = float(request.args.get('voltage'))
  329. waveform_voltage_unit: str = request.args.get('voltage_unit')
  330. enable_ch1: bool = bool(request.args.get('ch1'))
  331. enable_ch2: bool = bool(request.args.get('ch2'))
  332. generator = self.__core.instrument_controller.services.waveform_generator
  333. _, config_ch1 = generator.get_config("1")
  334. _, config_ch2 = generator.get_config("2")
  335. for config_chx in [config_ch1, config_ch2]:
  336. config_chx.type = config_chx.match_type_string(waveform_type)
  337. config_chx.type_string = waveform_type
  338. config_chx.freq = waveform_freq
  339. config_chx.freq_unit = config_chx.match_freq_unit_type_string(waveform_freq_unit)
  340. config_chx.high_level = waveform_voltage
  341. config_chx.low_level = - waveform_voltage
  342. config_chx.high_level_unit = config_chx.match_level_unit_type_string(waveform_voltage_unit)
  343. config_chx.low_level_unit = config_chx.match_level_unit_type_string(waveform_voltage_unit)
  344. generator.set_enable("1", enable_ch1)
  345. generator.set_enable("2", enable_ch2)
  346. generator.apply_config(immediate_start=False)
  347. generator.output_start()
  348. return "True"
  349. else:
  350. return "None"
  351. @self.__app.route("/instrument/analog_electronic_load/set_resistance", methods=['GET'])
  352. def instrument_analog_electronic_load_set_resistance():
  353. # print("[Server] Response " + "" + ".")
  354. print("[Server] Response " + "/instrument/analog_electronic_load/set_resistance" + ".")
  355. if self.__core.instrument_controller.services.analog_electronic_load is not None:
  356. resistance: str = request.args.get('set_resistance')
  357. self.__core.instrument_controller.services.analog_electronic_load.set_resistance(resistance)
  358. return "True"
  359. else:
  360. return "False"
  361. @self.__app.route("/serial_device/port_list", methods=['GET'])
  362. def serial_device_port_list():
  363. # print("[Server] Response " + "" + ".")
  364. print("[Server] Response " + "/serial_device/port_list" + ".")
  365. port_list: list[str] = self.__core.serial_controller.get_port_list()
  366. response_string: str = "port_list:"
  367. if len(port_list) == 0:
  368. response_string = response_string + " " + "None"
  369. else:
  370. response_string = response_string + " " + "Empty"
  371. for port_name in port_list:
  372. response_string = response_string + " " + port_name
  373. return response_string
  374. @self.__app.route("/serial_device/auto_connect", methods=['GET'])
  375. def serial_device_auto_connect():
  376. # print("[Server] Response " + "" + ".")
  377. print("[Server] Response " + "/serial_device/auto_connect" + ".")
  378. matched_port_list, not_matched_port_list, cnc_matched = self.__core.serial_controller.auto_connect()
  379. response_data = {
  380. 'method': 'auto_connect',
  381. 'cnc_matched': cnc_matched,
  382. 'port_list': {
  383. 'matched': matched_port_list,
  384. 'not_matched': not_matched_port_list
  385. }
  386. }
  387. return jsonify(response_data), 200
  388. @self.__app.route("/serial_device/cnc/config_connection", methods=['GET'])
  389. def serial_device_cnc_config_connection():
  390. # print("[Server] Response " + "" + ".")
  391. print("[Server] Response " + "/serial_device/cnc/config_connection" + ".")
  392. port_name: str = request.args.get('port_name')
  393. com_connection = self.__core.serial_controller.try_build_connection(port_name, if_add_source_to_lib=True)
  394. if_success = self.__core.serial_controller.services.cnc_attenuator.match_connection(com_connection)
  395. return f"{if_success}"
  396. @self.__app.route("/serial_device/cnc/set", methods=['GET'])
  397. def serial_device_cnc_set():
  398. # print("[Server] Response " + "" + ".")
  399. print("[Server] Response " + "/serial_device/cnc/set" + ".")
  400. set_value: str = request.args.get('value')
  401. if_success = self.__core.serial_controller.services.cnc_attenuator.set(float(set_value))
  402. return f"{if_success}"
  403. @self.__app.route("/serial_device/plc/config_connection", methods=['GET'])
  404. def serial_device_plc_connect_sender():
  405. # print("[Server] Response " + "" + ".")
  406. print("[Server] Response " + "/serial_device/plc/config_connection" + ".")
  407. tester = self.__core.serial_controller.get_tester()
  408. tester.pause_test_service()
  409. port_name: str = request.args.get('port_name')
  410. plc_com_role: str = request.args.get('plc_com_role').lower()
  411. if_success: bool = False
  412. if (port_name is not None) and (port_name not in ["None", "", " "]):
  413. if port_name not in ["Empty", "empty"]:
  414. com_connection = self.__core.serial_controller.try_build_connection(port_name,
  415. if_add_source_to_lib=True)
  416. if com_connection is not None:
  417. if plc_com_role == "sender":
  418. if_success = self.__core.serial_controller.services.plc_sender.match_connection(com_connection)
  419. elif plc_com_role == "receiver":
  420. if_success = self.__core.serial_controller.services.plc_receiver.match_connection(
  421. com_connection)
  422. elif plc_com_role == "receiver2":
  423. if_success = self.__core.serial_controller.services.plc_receiver2.match_connection(
  424. com_connection)
  425. if if_success is True:
  426. self.__core.serial_controller.services.enable_multi_receiver = True
  427. else:
  428. if_success = False
  429. else:
  430. if plc_com_role == "receiver2":
  431. if_success = self.__core.serial_controller.services.plc_receiver2.match_connection(None)
  432. self.__core.serial_controller.services.enable_multi_receiver = False
  433. tester.task_add_reset_error_rate()
  434. else:
  435. if_success: bool = True
  436. # if_success = True
  437. # ports = self.__core.serial_controller.get_port_list()
  438. # self.__core.serial_controller.services.plc_sender.match_connection()
  439. get_sender_port_name: str = "None"
  440. if self.__core.serial_controller.services.plc_sender.com is not None:
  441. get_sender_port_name = self.__core.serial_controller.services.plc_sender.com.connection_port_name
  442. get_receiver_port_name: str = "None"
  443. if self.__core.serial_controller.services.plc_receiver.com is not None:
  444. get_receiver_port_name = self.__core.serial_controller.services.plc_receiver.com.connection_port_name
  445. self.__core.serial_controller.services.com_usr_config_success = if_success
  446. response_data = {
  447. 'method': 'config_connection',
  448. 'plc_com_role': plc_com_role,
  449. 'port_name': port_name,
  450. 'if_success': if_success,
  451. 'new_config': {
  452. 'sender_port': f"{get_sender_port_name}",
  453. 'receiver_port': f"{get_receiver_port_name}",
  454. },
  455. 'received_config': {
  456. 'role': f"{plc_com_role}",
  457. 'port': f"{port_name}",
  458. }
  459. }
  460. return jsonify(response_data), 200
  461. @self.__app.route("/serial_device/plc/check_connection", methods=['GET'])
  462. def serial_device_plc_check_connection():
  463. # print("[Server] Response " + "" + ".")
  464. print("[Server] Response " + "/serial_device/plc/check_connection" + ".")
  465. sender_port: Optional[str] = self.__core.serial_controller.services.plc_sender.com.connection_port_name
  466. receiver_port: Optional[str] = self.__core.serial_controller.services.plc_receiver.com.connection_port_name
  467. sender_connection_flag: bool = (sender_port is not None)
  468. receiver_connection_flag: bool = (receiver_port is not None)
  469. connection_flag: bool = (sender_connection_flag is True) and (receiver_connection_flag is True)
  470. response_data = {
  471. 'method': 'check_connection',
  472. 'connection_status': connection_flag,
  473. 'config': {
  474. 'sender_port': f"{self.__core.serial_controller.services.plc_sender.com.connection_port_name}",
  475. 'receiver_port': f"{self.__core.serial_controller.services.plc_receiver.com.connection_port_name}",
  476. }
  477. }
  478. return jsonify(response_data), 200
  479. @self.__app.route("/serial_device/plc/start", methods=['GET'])
  480. def serial_device_plc_start():
  481. # print("[Server] Response " + "" + ".")
  482. print("[Server] Response " + "/serial_device/plc/start" + ".")
  483. self.__pubtools.debug_output("[Server] Response " + "/serial_device/plc/start" + ".")
  484. if self.__core.serial_controller.services.com_usr_config_success is True:
  485. package_config: Optional[str] = request.args.get('package_config')
  486. sender = self.__core.serial_controller.services.plc_sender
  487. receiver = self.__core.serial_controller.services.plc_receiver
  488. sender_port, sender_url = sender.keep_send()
  489. receiver_port, receiver_url = receiver.keep_receive()
  490. receiver2 = None
  491. if self.__core.serial_controller.services.enable_multi_receiver is True:
  492. receiver2 = self.__core.serial_controller.services.plc_receiver2
  493. receiver2.keep_receive()
  494. tester = self.__core.serial_controller.get_tester()
  495. tester.start_test_service(sender, receiver, receiver2)
  496. if package_config == "单包1kbit":
  497. tester_frame_new: bytes = tester.send_package_1kbit
  498. elif package_config == "单包16kbit":
  499. tester_frame_new: bytes = tester.send_package_16kbit
  500. else:
  501. tester_frame_new: bytes = package_config.encode()
  502. if len(tester_frame_new) % 3 == 0:
  503. tester_frame_new += b'12\n'
  504. elif len(tester_frame_new) % 3 == 1: # b'1'
  505. tester_frame_new += b'1\n'
  506. elif len(tester_frame_new) % 3 == 2: # b'12'
  507. tester_frame_new += b'\n'
  508. else:
  509. tester_frame_new = b'12\n'
  510. tester.reset_frame_std_and_restart(tester_frame_new)
  511. else:
  512. sender_port, sender_url, receiver_port, receiver_url = 0, 0, 0, 0
  513. response_data = {
  514. 'method': 'start',
  515. 'sender': {
  516. 'port': f"{sender_port}",
  517. 'url': sender_url,
  518. },
  519. 'receiver': {
  520. 'port': f"{receiver_port}",
  521. 'url': receiver_url,
  522. }
  523. }
  524. return jsonify(response_data), 200
  525. @self.__app.route("/serial_device/plc/pause", methods=['GET'])
  526. def serial_device_plc_pause():
  527. # print("[Server] Response " + "" + ".")
  528. print("[Server] Response " + "/serial_device/plc/pause" + ".")
  529. # self.__core.serial_controller.services.plc_sender.pause()
  530. # self.__core.serial_controller.services.plc_receiver.pause()
  531. tester = self.__core.serial_controller.get_tester()
  532. tester.pause_test_service()
  533. return "pause"
  534. @self.__app.route("/serial_device/plc/clear", methods=['GET'])
  535. def serial_device_plc_clear():
  536. # print("[Server] Response " + "" + ".")
  537. print("[Server] Response " + "/serial_device/plc/clear" + ".")
  538. self.__core.serial_controller.get_tester().task_add_reset_error_rate()
  539. return "clear"
  540. @self.__app.route("/serial_device/plc/realtime_performance", methods=['GET'])
  541. def serial_device_plc_realtime_performance():
  542. # print("[Server] Response " + "" + ".")
  543. print("[Server] Response " + "/serial_device/plc/realtime_performance" + ".")
  544. tester = self.__core.serial_controller.get_tester()
  545. error_rate_percent: float = tester.error_rate_percent
  546. error_rate_percent2: float = tester.error_rate_percent2
  547. if self.__buffer_error_rate_percent_1_value == error_rate_percent:
  548. if abs(self.__buffer_error_rate_percent_1_time - time.time()) > 3:
  549. if error_rate_percent <= 99.5:
  550. error_rate_percent = 0
  551. else:
  552. pass
  553. else:
  554. self.__buffer_error_rate_percent_1_value = error_rate_percent
  555. self.__buffer_error_rate_percent_1_time = time.time()
  556. if self.__buffer_error_rate_percent_2_value == error_rate_percent2:
  557. if abs(self.__buffer_error_rate_percent_2_time - time.time()) > 3:
  558. if error_rate_percent2 <= 99.5:
  559. error_rate_percent2 = 0
  560. else:
  561. pass
  562. else:
  563. self.__buffer_error_rate_percent_2_value = error_rate_percent2
  564. self.__buffer_error_rate_percent_2_time = time.time()
  565. return f"realtime_performance: error_rate_percent={error_rate_percent} error_rate_percent2={error_rate_percent2}"
  566. @self.__app.route("/serial_device/plc/realtime_performance_speed", methods=['GET'])
  567. def serial_device_plc_realtime_performance_speed():
  568. # print("[Server] Response " + "" + ".")
  569. print("[Server] Response " + "/serial_device/plc/realtime_performance_speed" + ".")
  570. tester = self.__core.serial_controller.get_tester()
  571. speed_kbps: float = tester.speed_kbps
  572. speed_kbps2: float = tester.speed_kbps2
  573. if self.__buffer_speed_kbps_1_value == speed_kbps:
  574. if abs(self.__buffer_speed_kbps_1_time - time.time()) > 3:
  575. speed_kbps = 0
  576. else:
  577. pass
  578. else:
  579. self.__buffer_speed_kbps_1_value = speed_kbps
  580. self.__buffer_speed_kbps_1_time = time.time()
  581. if self.__buffer_speed_kbps_2_value == speed_kbps2:
  582. if abs(self.__buffer_speed_kbps_2_time - time.time()) > 3:
  583. speed_kbps2 = 0
  584. else:
  585. pass
  586. else:
  587. self.__buffer_speed_kbps_2_value = speed_kbps2
  588. self.__buffer_speed_kbps_2_time = time.time()
  589. return f"realtime_performance_speed: speed_kbps={speed_kbps} speed_kbps2={speed_kbps2}"
  590. @self.__app.route("/serial_device/plc/motor_mode", methods=['GET'])
  591. def serial_device_plc_motor_mode():
  592. # print("[Server] Response " + "" + ".")
  593. print("[Server] Response " + "/serial_device/plc/motor_mode" + ".")
  594. get_type: Optional[str] = request.args.get('type')
  595. mode_number: Optional[str] = request.args.get('mode')
  596. if get_type is not None and mode_number is not None:
  597. tester = self.__core.serial_controller.get_tester()
  598. use_msg = None
  599. if get_type == "motor":
  600. use_msg_list = tester.motor_msg_list
  601. if mode_number in ["1", "2", "3", "4"]:
  602. try:
  603. index = int(mode_number) - 1
  604. use_msg = use_msg_list[index]
  605. except ValueError:
  606. return "failed"
  607. except IndexError:
  608. return "failed"
  609. elif get_type == "relay":
  610. use_msg_list = tester.relay_msg_list
  611. if mode_number in ["1", "2"]:
  612. try:
  613. index = int(mode_number) - 1
  614. use_msg = use_msg_list[index]
  615. except ValueError:
  616. return "failed"
  617. except IndexError:
  618. return "failed"
  619. else:
  620. return "failed"
  621. if use_msg is not None:
  622. tester.set_circle_hook_to_msg_once_mode(use_msg)
  623. return "success"
  624. return "failed"
  625. @self.__app.route("/files/documents/start", methods=['GET'])
  626. def files_documents_start():
  627. # print("[Server] Response " + "" + ".")
  628. print("[Server] Response " + "/files/documents/start" + ".")
  629. host, port = self.__core.local_file_service.start()
  630. return f"documents: host={host} port={port}"
  631. if __name__ == "__main__":
  632. server: Server = Server(server_port=2023)
  633. server.start()