From 6a47310dec40f5a2de30a2c1e7a61665be76eecc Mon Sep 17 00:00:00 2001 From: gitea Date: Thu, 9 Jan 2025 21:50:21 +0800 Subject: [PATCH] =?UTF-8?q?xCore=E9=80=9A=E4=BF=A1=E6=9A=82=E6=97=B6?= =?UTF-8?q?=E6=97=A0=E9=97=AE=E9=A2=98=E4=BA=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- code/aio.py | 100 ++++++++++++++++++++++------------------- code/common/clibs.py | 53 +++++++++++----------- code/common/openapi.py | 90 +++++++++++++++++++------------------ 3 files changed, 126 insertions(+), 117 deletions(-) diff --git a/code/aio.py b/code/aio.py index b798d71..99f8164 100644 --- a/code/aio.py +++ b/code/aio.py @@ -76,8 +76,8 @@ class App: self.om_sub_at = ctk.CTkOptionMenu(self.tabview_top.tab("自动测试"), width=160, dynamic_resizing=False, values=["tool33", "tool66", "tool100", "inertia"], font=self.f_common, text_color="#3C3C3C", button_color="#7B6B5B", fg_color="#8D8D8D") self.label_ip_at = ctk.CTkLabel(self.tabview_top.tab("自动测试"), anchor="e", text="IP", font=self.f_common) self.entry_ip_at = ctk.CTkEntry(self.tabview_top.tab("自动测试"), width=160, textvariable=self.entry_ip_atv, font=self.f_entry, text_color="#818181") - self.btn_conn = ctk.CTkButton(self.tabview_top.tab("自动测试"), text="连接", width=60, font=self.f_segbtn, fg_color="#979DA2", corner_radius=0, command=lambda: self.__thread_it(self.__conn_xcore)) - self.progressbar_at = ctk.CTkProgressBar(self.tabview_top.tab("自动测试"), width=160, mode="indeterminate") + self.btn_conn = ctk.CTkButton(self.tabview_top.tab("自动测试"), text="连接", width=60, font=self.f_segbtn, fg_color="#979DA2", corner_radius=0) + # self.progressbar_at = ctk.CTkProgressBar(self.tabview_top.tab("自动测试"), width=160, mode="indeterminate") self.label_path_at = ctk.CTkLabel(self.tabview_top.tab("自动测试"), width=50, anchor="e", text="Path", font=self.f_common) self.entry_path_at = ctk.CTkEntry(self.tabview_top.tab("自动测试"), width=80, state="disabled", textvariable=self.entry_path_atv, font=self.f_entry, text_color="#818181") self.frame_top = ctk.CTkFrame(self.tabview_top.tab("自动测试"), width=120, height=10, fg_color="#E9E9E9") @@ -132,7 +132,7 @@ class App: # ======================================================================== self.__draw() - def detect_network(self): + def __detect_network(self): while True: try: if clibs.c_hr.status: @@ -141,32 +141,7 @@ class App: self.btn_conn.configure(fg_color="#979DA2") except Exception as Err: self.btn_conn.configure(fg_color="#979DA2") - time.sleep(2) - - def __conn_xcore(self): - if self.btn_conn.cget("fg_color") == "#979DA2": - try: - if clibs.c_hr.status: - self.btn_conn.configure(fg_color="#2E8B57") - return - except Exception as Err: - ... - - clibs.ip_addr = self.entry_ip_atv.get().strip() - ip_pattern = re.compile(r'(([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])\.){3}([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])') - if not ip_pattern.fullmatch(clibs.ip_addr): - messagebox.showerror(title="非法地址", message=f"{clibs.ip_addr} 不是一个有效的 IP 地址") - clibs.insert_logdb("ERROR", "aio", f"connection: {clibs.ip_addr} 不是一个有效的 IP 地址") - return - # clibs.c_md = openapi.ModbusRequest(clibs.ip_addr, clibs.modbus_port) - clibs.c_hr = openapi.HmiRequest(clibs.ip_addr, clibs.socket_port, clibs.xService_port) - else: - try: - # clibs.c_md.close() - clibs.c_hr.close() - except Exception as Err: - ... - self.btn_conn.configure(fg_color="#979DA2") + time.sleep(3) def __robot_info(self): ... @@ -283,7 +258,6 @@ class App: exec_function() - @clibs.db_lock def __reset_state(self): def reset_methods(): self.btn_load.configure(fg_color="#979DA2") @@ -296,8 +270,13 @@ class App: res = messagebox.askyesno(title="状态重置", message="这将清空本次所有的输出以及日志记录,且不可恢复,请确认!", default=messagebox.NO, icon=messagebox.WARNING) if res: self.text_output.delete("1.0", ctk.END) - clibs.cursor.execute("delete from logs") - clibs.cursor.execute("delete from sqlite_sequence") # 主键归零 + try: + clibs.lock.acquire(True) + clibs.cursor.execute("delete from logs") + clibs.cursor.execute("delete from sqlite_sequence") # 主键归零 + finally: + clibs.lock.release() + self.treeview_logs.delete(*self.treeview_logs.get_children()) self.label_pages_logs.set("-.-.-.-.-.-") reset_methods() @@ -323,9 +302,9 @@ class App: self.label_pages_logs.set(f"{pages_all} / {pages_all}") self.treeview_logs.delete(*self.treeview_logs.get_children()) - remainder = len_records % 100 + remainder = len_records % 100 if len_records % 100 != 0 else 100 end = len_records - start = len_records-remainder+1 if len_records-remainder > 0 else 0 + start = len_records - remainder + 1 if len_records - remainder > 0 else 0 # clibs.cursor.execute("select * from logs order by id desc limit 100") clibs.cursor.execute(f"select * from logs where id between {start} and {end}") @@ -382,6 +361,7 @@ class App: @clibs.db_lock def get_next_page(): if self.btn_find.cget("fg_color") == "#979DA2": + # noinspection PyBroadException try: clibs.cursor.execute("select id from logs") len_records = len(clibs.cursor.fetchall()) @@ -401,8 +381,8 @@ class App: pages_all = len_records // 100 if len_records % 100 == 0 else len_records // 100 + 1 current_page = int(start) // 100 if int(start) % 100 == 0 else int(start) // 100 + 1 self.label_pages_logs.set(f"{current_page} / {pages_all}") - except Exception as ERR: - ... + except Exception as Err: + print(f"get_next_page-if: {Err}") else: len_records = len(clibs.f_records) pages_all = int(self.label_pages_logs.get().split("/")[1].strip()) @@ -426,8 +406,10 @@ class App: current_page = int(self.label_pages_logs.get().split("/")[0].strip()) pages_all = int(self.label_pages_logs.get().split("/")[1].strip()) if current_page == pages_all: - self.__get_realtime_log() - return + if self.btn_find.cget("fg_color") == "#979DA2": + self.__get_realtime_log() + return + get_next_page() def __load_log_db(self): @@ -614,6 +596,7 @@ class App: widget_toplevel.destroy() def double_click(event): + # noinspection PyBroadException try: e = event.widget iid = e.identify("item", event.x, event.y) @@ -640,8 +623,8 @@ class App: label_info.grid(row=0, column=0, padx=10, pady=10, sticky="we") text_content.grid(row=1, column=0, padx=10, pady=(0, 10), sticky="news") self.root.attributes("-disabled", 1) - except Exception as ERR: - ... + except Exception: + return @clibs.db_lock def jump2page(): @@ -867,6 +850,32 @@ class App: def show_popupmenu_ip(event): self.popupmenu_ip.post(event.x_root, event.y_root) + + def conn_change(event): + def conn_or_disconn(): + if self.btn_conn.cget("fg_color") == "#979DA2": + self.btn_conn.configure(state="disabled") + clibs.ip_addr = self.entry_ip_atv.get().strip() + ip_pattern = re.compile(r'(([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])\.){3}([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])') + if not ip_pattern.fullmatch(clibs.ip_addr): + messagebox.showerror(title="非法地址", message=f"{clibs.ip_addr} 不是一个有效的 IP 地址") + clibs.insert_logdb("ERROR", "aio", f"connection: {clibs.ip_addr} 不是一个有效的 IP 地址") + return + try: + # clibs.c_md = openapi.ModbusRequest(clibs.ip_addr, clibs.modbus_port) + clibs.c_hr = openapi.HmiRequest(clibs.ip_addr, clibs.socket_port, clibs.xService_port) + self.btn_conn.configure(state="normal", fg_color="#2E8B57") + except Exception as Err: + self.btn_conn.configure(state="normal", fg_color="#979DA2") + elif self.btn_conn.cget("fg_color") == "#2E8B57": + try: + # clibs.c_md.close() + clibs.c_hr.close() + finally: + self.btn_conn.configure(fg_color="#979DA2") + t = threading.Thread(target=conn_or_disconn) + t.daemon = True + t.start() # ======================================================================== self.root.rowconfigure(0, weight=1) self.root.rowconfigure(1, weight=99) @@ -914,7 +923,7 @@ class App: self.label_ip_at.grid(row=0, column=1, padx=(0, 10), pady=10, sticky="e") self.entry_ip_at.grid(row=0, column=2, padx=(0, 10), pady=10) self.btn_conn.grid(row=0, column=3, padx=(0, 10), pady=10) - self.progressbar_at.grid(row=0, column=4, padx=(0, 10), pady=10, sticky="e") + # self.progressbar_at.grid(row=0, column=4, padx=(0, 10), pady=10, sticky="e") self.label_path_at.grid(row=1, column=1, padx=(0, 10), pady=(0, 10), sticky="e") self.entry_path_at.grid(row=1, column=2, columnspan=3, padx=(0, 10), pady=(0, 10), sticky="we") self.frame_top.grid(row=2, column=0, columnspan=5, padx=0, pady=0, sticky="we") @@ -923,10 +932,11 @@ class App: self.btn_trig_estop.grid(row=0, column=2, padx=(0, 10), pady=0) self.btn_reset_estop.grid(row=0, column=3, padx=(0, 10), pady=0) - self.progressbar_at.start() - self.progressbar_at.configure(progress_color="red", fg_color="gray") + # self.progressbar_at.start() + # self.progressbar_at.configure(progress_color="red", fg_color="gray") self.entry_path_at.bind("", select_path) self.entry_ip_at.bind("", show_popupmenu_ip, add="+") + self.btn_conn.bind("", conn_change) # ======================================================================== self.tabview_bottom.tab("输出").grid_rowconfigure(0, weight=1) self.tabview_bottom.tab("输出").grid_columnconfigure(0, weight=1) @@ -972,11 +982,11 @@ class App: self.om_sensor_dp.configure(state="disabled") # ======================================================================== clibs.w2t = self.__w2t - clibs.insert_logdb("INFO", "aio", "AIO starts running......") + # clibs.insert_logdb("INFO", "aio", "AIO starts running......") def show(self): if self.server_vers: - t = threading.Thread(target=self.detect_network) + t = threading.Thread(target=self.__detect_network) t.daemon = True t.start() self.root.mainloop() diff --git a/code/common/clibs.py b/code/common/clibs.py index 00c19bc..7164230 100644 --- a/code/common/clibs.py +++ b/code/common/clibs.py @@ -2,7 +2,7 @@ import os import os.path import sqlite3 import threading -import json + def traversal_files(_path, _w2t): # 功能:以列表的形式分别返回指定路径下的文件和文件夹,不包含子目录 @@ -21,17 +21,15 @@ def traversal_files(_path, _w2t): return dirs, files -def init_logdb(conn, cursor): - conn = sqlite3.connect(":memory:", isolation_level=None, check_same_thread=False, cached_statements=4096) - # connect = sqlite3.connect("log.db", isolation_level=None, check_same_thread=False, cached_statements=256) - # time text default (datetime('now', 'localtime')), - cursor = conn.cursor() - cursor.execute("PRAGMA journal_mode=wal") - cursor.execute("PRAGMA wal_checkpoint=TRUNCATE") - cursor.execute("PRAGMA synchronous=normal") - cursor.execute("PRAGMA temp_store=memory") - cursor.execute("PRAGMA mmap_size=30000000000") - cursor.execute( +def init_logdb(_conn, _cursor): + _conn = sqlite3.connect(":memory:", isolation_level=None, check_same_thread=False, cached_statements=4096) + _cursor = _conn.cursor() + _cursor.execute("PRAGMA journal_mode=wal") + _cursor.execute("PRAGMA wal_checkpoint=TRUNCATE") + _cursor.execute("PRAGMA synchronous=normal") + _cursor.execute("PRAGMA temp_store=memory") + _cursor.execute("PRAGMA mmap_size=30000000000") + _cursor.execute( """ create table if not exists logs( id integer primary key autoincrement, @@ -42,7 +40,7 @@ def init_logdb(conn, cursor): ) """ ) - return conn, cursor + return _conn, _cursor def db_lock(func): @@ -53,6 +51,7 @@ def db_lock(func): finally: lock.release() return ret + return wrapper @@ -60,11 +59,12 @@ def db_lock(func): def insert_logdb(_level, _module, _content): if db_state == "readwrite": global conn, cursor, lock + if "move.monitor" in _content: + return data = [_level, _module, repr(_content)] cursor.execute("insert into logs (level, module, content) values (?, ?, ?)", data) - def insert_logdb_multi(data): if db_state == "readwrite": global conn, cursor, lock @@ -89,9 +89,10 @@ class GetThreadResult(threading.Thread): def get_result(self): threading.Thread.join(self) # 等待线程执行完毕 + # noinspection PyBroadException try: return self.result - except Exception as Err: + except Exception: return None @@ -131,17 +132,13 @@ lock = threading.Lock() conn, cursor = init_logdb(conn, cursor) +# ============== ↓↓↓DEBUG CODE↓↓↓ ============== # for i in range(100): -# insert_logdb("DEBUG", "clibs", 'this is a DEBUG log -0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-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,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n\t\t\t\t-0.0,\n') -# -# insert_logdb("DEBUG", "clibs", 'running') -# insert_logdb("INFO", "clibs", 'running') -# insert_logdb("WARNING", "clibs", 'running') -# insert_logdb("ERROR", "clibs", 'running') -with open(f"{log_path}/response.txt", mode="w", encoding="utf-8") as f_res: - f_res.write("") -with open(f"{log_path}/logs.txt", mode="w", encoding="utf-8") as f_res: - f_res.write("") \ No newline at end of file +# insert_logdb("DEBUG", "clibs", 'running') +# insert_logdb("INFO", "clibs", 'running') +# insert_logdb("WARNING", "clibs", 'running') +# insert_logdb("ERROR", "clibs", 'running') +# with open(f"{log_path}/response.txt", mode="w", encoding="utf-8") as f_res: +# f_res.write("") +# with open(f"{log_path}/logs.txt", mode="w", encoding="utf-8") as f_res: +# f_res.write("") diff --git a/code/common/openapi.py b/code/common/openapi.py index 486f09c..8e1e134 100644 --- a/code/common/openapi.py +++ b/code/common/openapi.py @@ -343,9 +343,10 @@ class HmiRequest(object): try: self.__close_hmi = True self.__is_connected = False - time.sleep(clibs.interval) + time.sleep(clibs.interval*2) self.__c.close() self.__c_xs.close() + time.sleep(clibs.interval*2) except: ... @@ -388,8 +389,8 @@ class HmiRequest(object): data = conn.recv(clibs.MAX_FRAME_SIZE) if data: # print(f"data = {data}") - with open(f"{clibs.log_path}/logs.txt", mode="a", encoding="utf-8") as f_logs: - f_logs.write(str(data) + "\n") + # with open(f"{clibs.log_path}/logs.txt", mode="a", encoding="utf-8") as f_logs: + # f_logs.write(str(data) + "\n") self.__get_response(data) else: sel.unregister(conn) @@ -407,16 +408,11 @@ class HmiRequest(object): clibs.insert_logdb("ERROR", "openapi", f"hr-unpackage: 报错信息 {Err}") def __get_headers(self, index, data): - print(f"index = {index}") if index + 8 < len(data): frm_value = int.from_bytes(data[index:index + 2], byteorder="big") pkg_value = int.from_bytes(data[index + 2:index + 6], byteorder="big") protocol = int.from_bytes(data[index + 6:index + 7], byteorder="big") reserved = int.from_bytes(data[index + 7:index + 8], byteorder="big") - print(f"reserved = {reserved}") - print(f"protocol = {protocol}") - print(f"frm_value = {frm_value}") - print(f"pkg_value = {pkg_value}") if reserved == 0 and protocol == 2: return index + 8, frm_value, pkg_value else: @@ -426,37 +422,32 @@ class HmiRequest(object): else: self.__half_pkg = data[index:] self.__half_pkg_flag = True - index += clibs.MAX_FRAME_SIZE - return index, 0, 0 + return -1, 0, 0 def __get_response(self, data): - if self.__half_pkg_flag: - print(f"self.__half_pkg = {self.__half_pkg}") - len_one = len(self.__half_pkg) - len_another = 8 - len_one - headers = self.__half_pkg + data[:len_another] - self.__index = len_another - frm_value = int.from_bytes(headers[0:2], byteorder="big") - pkg_value = int.from_bytes(headers[2:6], byteorder="big") - print(f"headers = {headers}") + frm_value, pkg_value, self.__index = 0, 0, 0 while self.__index < len(data): - print(f"top valid data = {self.__valid_data_length}") - if self.__valid_data_length < 0: - print(f"invalid data: {data}") - raise Exception() if self.__is_first_frame: if self.__half_pkg_flag: + len_one = len(self.__half_pkg) + len_another = 8 - len_one + headers = self.__half_pkg + data[:len_another] + self.__index = len_another + frm_value = int.from_bytes(headers[0:2], byteorder="big") + pkg_value = int.from_bytes(headers[2:6], byteorder="big") self.__half_pkg_flag = False else: self.__index, frm_value, pkg_value = self.__get_headers(self.__index, data) + if self.__half_pkg_flag: + break if frm_value - pkg_value == 6: if len(data[self.__index:]) >= pkg_value: self.__response = data[self.__index:self.__index + pkg_value] self.__index += pkg_value - with open(f"{clibs.log_path}/response.txt", mode="a", encoding="utf-8") as f_res: - f_res.write(f"{json.loads(self.__response.decode())}" + "\n") + # with open(f"{clibs.log_path}/response.txt", mode="a", encoding="utf-8") as f_res: + # f_res.write(f"{json.loads(self.__response.decode())}" + "\n") clibs.insert_logdb("DEBUG", "openapi", self.__response.decode()) self.__response = b"" self.__leftovers = 0 @@ -501,11 +492,13 @@ class HmiRequest(object): self.__valid_data_length -= self.__leftovers self.__leftovers = 0 if self.__valid_data_length == 0: - with open(f"{clibs.log_path}/response.txt", mode="a", encoding="utf-8") as f_res: - f_res.write(f"{json.loads(self.__response.decode())}" + "\n") + # with open(f"{clibs.log_path}/response.txt", mode="a", encoding="utf-8") as f_res: + # f_res.write(f"{json.loads(self.__response.decode())}" + "\n") clibs.insert_logdb("DEBUG", "openapi", self.__response.decode()) self.__response = b"" self.__is_first_frame = True + continue # 此时应该重新 get_headers + if len(data[self.__index:]) == 2: self.__half_frm = data[self.__index:] self.__index += clibs.MAX_FRAME_SIZE @@ -524,8 +517,8 @@ class HmiRequest(object): self.__response += data[:self.__leftovers] self.__index = self.__leftovers self.__leftovers = 0 - with open(f"{clibs.log_path}/response.txt", mode="a", encoding="utf-8") as f_res: - f_res.write(f"{json.loads(self.__response.decode())}" + "\n") + # with open(f"{clibs.log_path}/response.txt", mode="a", encoding="utf-8") as f_res: + # f_res.write(f"{json.loads(self.__response.decode())}" + "\n") clibs.insert_logdb("DEBUG", "openapi", self.__response.decode()) self.__response = b"" self.__is_first_frame = True @@ -537,9 +530,17 @@ class HmiRequest(object): # 4. len(data[self.__index:]) = 0 if self.__half_frm_flag != -1: if self.__half_frm_flag == 2: - self.__index = int.from_bytes(self.__half_frm) - self.__response += data[:self.__index] - self.__valid_data_length -= len(data[:self.__index]) + frm_value = int.from_bytes(self.__half_frm) + if len(data) >= frm_value: + self.__response += data[:frm_value] + self.__leftovers = 0 + self.__valid_data_length -= len(data[:frm_value]) + self.__index = frm_value + elif len(data) < frm_value: + self.__response += data + self.__leftovers = frm_value - len(data) + self.__valid_data_length -= len(data) + self.__index += clibs.MAX_FRAME_SIZE self.__half_frm_flag = -1 elif self.__half_frm_flag == 1: frm_value = int.from_bytes(self.__half_frm + data[0:1]) @@ -569,11 +570,13 @@ class HmiRequest(object): self.__half_frm_flag = -1 if self.__valid_data_length == 0: - with open(f"{clibs.log_path}/response.txt", mode="a", encoding="utf-8") as f_res: - f_res.write(f"{json.loads(self.__response.decode())}" + "\n") + # with open(f"{clibs.log_path}/response.txt", mode="a", encoding="utf-8") as f_res: + # f_res.write(f"{json.loads(self.__response.decode())}" + "\n") clibs.insert_logdb("DEBUG", "openapi", self.__response.decode()) self.__response = b"" self.__is_first_frame = True + continue + if len(data[self.__index:]) == 2: self.__half_frm = data[self.__index:] self.__index += clibs.MAX_FRAME_SIZE @@ -597,11 +600,13 @@ class HmiRequest(object): self.__index += frm_value self.__valid_data_length -= frm_value if self.__valid_data_length == 0: - with open(f"{clibs.log_path}/response.txt", mode="a", encoding="utf-8") as f_res: - f_res.write(f"{json.loads(self.__response.decode())}" + "\n") + # with open(f"{clibs.log_path}/response.txt", mode="a", encoding="utf-8") as f_res: + # f_res.write(f"{json.loads(self.__response.decode())}" + "\n") clibs.insert_logdb("DEBUG", "openapi", self.__response.decode()) self.__response = b"" self.__is_first_frame = True + continue + if len(data[self.__index:]) == 2: self.__index += clibs.MAX_FRAME_SIZE self.__half_frm = data[self.__index:] @@ -621,9 +626,8 @@ class HmiRequest(object): self.__valid_data_length -= len(data[self.__index:]) self.__index += clibs.MAX_FRAME_SIZE else: - self.__index += 1 - else: - self.__index = 0 + clibs.insert_logdb("ERROR", "openapi", "hr-get_response: Will never be here") + raise Exception("WillNeverBeHere") @staticmethod def __package_xs(cmd): @@ -667,18 +671,16 @@ class HmiRequest(object): if state is None: self.close() clibs.w2t(f"请求 {msg_id} 发送失败......", "red", "ReqSendFailed") - for _ in range(60): + for _ in range(3): + time.sleep(clibs.interval * 2) try: clibs.lock.acquire(True) - clibs.cursor.execute(f"select * from logs where content like '{f_text}'") + clibs.cursor.execute(f"select content from logs where content like '{f_text}'") res = len(clibs.cursor.fetchall()) finally: clibs.lock.release() if res >= 2: break - else: - time.sleep(clibs.interval*2) - continue else: clibs.insert_logdb("ERROR", "openapi", f"hr: 无法找到请求 {msg_id} 的响应") self.close()