Refactor code structure for improved readability and maintainability

This commit is contained in:
Your Name committed 2026-01-11 23:31:38 +08:00
1 parent 7e5d88d3f1
commit 54f3b35a26
14 files changed
+2054 -562

No files matched your search

+69 -22
View File
@@ -551,6 +551,7 @@ class underlying_operations:
pass
except Exception:
pass
service_success = False
# 如果启用服务模式,使用后台截图服务;若服务不可用或返回 False,则回退到直接截图
if use_service:
try:
@@ -574,8 +575,7 @@ class underlying_operations:
)
try:
service_result = service.get_screenshot(device_id, force=False)
if service_result:
if service.get_screenshot(device_id, force=False):
dur = (time_module.time() - start_ts) * 1000.0
logging.info(
"[截图] 使用后台服务耗时(ms)=%.1f device=%s", dur, device_id
@@ -612,7 +612,7 @@ class underlying_operations:
except Exception:
pass
# do not return here; let final return at function end
result = True
service_success = True
else:
timetag = datetime.now().strftime("%H:%M:%S")
logging.info(
@@ -627,8 +627,7 @@ class underlying_operations:
timetag,
e,
)
# ensure result exists
result = False
service_success = False
except ImportError as e:
timetag = datetime.now().strftime("%H:%M:%S")
logging.warning(
@@ -636,19 +635,18 @@ class underlying_operations:
timetag,
e,
)
result = False
service_success = False
except Exception as e:
timetag = datetime.now().strftime("%H:%M:%S")
logging.warning(
"[%s] [截图操作] 服务模式不可用,回退到直接截图: %s", timetag, e
)
result = False
service_success = False
# 原有的直接截图逻辑(保持向后兼容),测量其耗时
try:
# If result already set by service branch, skip direct call
if "result" in locals() and locals()["result"] is True:
# already successful via service
if service_success:
final_result = True
else:
final_result = self._get_screenshot_direct(device_id, path)
@@ -798,6 +796,12 @@ class underlying_operations:
# 优先走 exec-out:只需 1 次 adb 调用;不在手机端落盘,减少 I/O 与卡顿
# 为避免被并发读取到"半写入文件",写入 tmp 后再原子替换。
execout_timeout_sec = float(os.environ.get("ADB_EXECOUT_TIMEOUT_SEC", "10"))
execout_warn_after_sec = float(os.environ.get("ADB_EXECOUT_WARN_AFTER_SEC", "3"))
execout_heartbeat_interval_sec = float(
os.environ.get("ADB_EXECOUT_HEARTBEAT_INTERVAL_SEC", "5")
)
execout_heartbeat_max = int(os.environ.get("ADB_EXECOUT_HEARTBEAT_MAX", "3"))
for attempt in range(2):
try:
cleanup_start = time_module.time()
@@ -821,24 +825,58 @@ class underlying_operations:
bufsize=0, # 无缓冲,立即传输
)
# 使用更大的缓冲区(256KB)提高写入效率
if process.stdout is None:
raise RuntimeError("ADB process stdout is None")
with open(tmp_file, "wb", buffering=262144) as f:
while True:
chunk = process.stdout.read(262144) # 256KB chunks
if not chunk:
break
f.write(chunk)
# 注意:Windows 上 stdout.read() 可能永久阻塞(adb 卡住时不会退出),导致 wait(timeout=...) 永远到不了。
# 这里用 communicate(timeout=...) 保证超时可触发,从而进入重试/回退方案。
done_event = None
watchdog_thread = None
try:
import threading
# 等待进程完成
return_code = process.wait(timeout=10)
if return_code != 0:
done_event = threading.Event()
def _watchdog() -> None:
try:
if execout_warn_after_sec > 0:
if done_event.wait(timeout=execout_warn_after_sec):
return
start_wait = time_module.time()
for i in range(max(0, execout_heartbeat_max)):
if done_event.is_set():
return
waited = (time_module.time() - start_wait) * 1000.0
logging.warning(
"[截图] exec-out 仍在进行中:已等待(ms)=%.0f device=%s attempt=%s",
waited,
device_id,
attempt + 1,
)
if done_event.wait(
timeout=max(0.5, execout_heartbeat_interval_sec)
):
return
except Exception:
return
watchdog_thread = threading.Thread(
target=_watchdog, name="adb-execout-watchdog", daemon=True
)
watchdog_thread.start()
except Exception:
done_event = None
stdout_data, _ = process.communicate(timeout=execout_timeout_sec)
if done_event is not None:
done_event.set()
if process.returncode != 0:
raise subprocess.CalledProcessError(
return_code,
process.returncode,
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
)
with open(tmp_file, "wb", buffering=262144) as f:
f.write(stdout_data)
adb_subprocess_dur = (time_module.time() - adb_start) * 1000.0
# 合并ADB subprocess耗时到最终汇总日志中,不单独输出
@@ -847,6 +885,15 @@ class underlying_operations:
# 这样可以减少 10-50ms 的等待时间
except subprocess.TimeoutExpired:
process.kill()
try:
process.communicate(timeout=1)
except Exception:
pass
try:
if done_event is not None:
done_event.set()
except Exception:
pass
raise
validate_tmp_start = time_module.time()