优化后台截图功能
This commit is contained in:
1 parent
223c127e11
commit
ace3bbfa04
70 files changed
+4392
-871
No files matched your search
@@ -1,12 +1,14 @@
|
||||
"""截图操作模块
|
||||
|
||||
包含截图、图片裁剪等截图相关操作。
|
||||
支持后台截图服务和多线程优化。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
@@ -35,8 +37,35 @@ class ScreenshotOperations:
|
||||
adb = adb[1:-1]
|
||||
return adb
|
||||
|
||||
def get_screenshot(self, device_id, path="pic") -> bool:
|
||||
"""截图3个adb命令需要2S左右的时间"""
|
||||
def get_screenshot(self, device_id, path="pic", use_service: bool = True) -> bool:
|
||||
"""截图(支持后台服务模式)
|
||||
|
||||
参数:
|
||||
device_id: 设备ID
|
||||
path: 路径(默认"pic")
|
||||
use_service: 是否使用后台截图服务(默认True,可显著提升性能)
|
||||
|
||||
返回:
|
||||
是否成功获取截图
|
||||
"""
|
||||
# 如果启用服务模式,使用后台截图服务
|
||||
if use_service:
|
||||
try:
|
||||
from operations.screenshot_service import ScreenshotService
|
||||
service = ScreenshotService.get_instance()
|
||||
return service.get_screenshot(device_id, force=False)
|
||||
except Exception as e:
|
||||
# 服务不可用时,回退到直接截图
|
||||
from datetime import datetime
|
||||
timetag = datetime.now().strftime("%H:%M:%S")
|
||||
print(f"[{timetag}] [截图操作] ⚠️ 服务模式失败,回退到直接截图: {e}")
|
||||
|
||||
# 原有的直接截图逻辑(保持向后兼容)
|
||||
return self._get_screenshot_direct(device_id, path)
|
||||
|
||||
def _get_screenshot_direct(self, device_id, path="pic") -> bool:
|
||||
"""直接截图(不使用服务模式)"""
|
||||
direct_start = time.time()
|
||||
if path == "pic":
|
||||
try:
|
||||
import path_config
|
||||
@@ -76,19 +105,43 @@ class ScreenshotOperations:
|
||||
os.remove(tmp_file)
|
||||
except Exception:
|
||||
pass
|
||||
with open(tmp_file, "wb") as f:
|
||||
subprocess.run(
|
||||
# 使用 Popen 流式读取,边接收数据边写入文件,提高性能
|
||||
t_exec_start = time.time()
|
||||
try:
|
||||
process = subprocess.Popen(
|
||||
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
|
||||
stdout=f,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL,
|
||||
check=True,
|
||||
timeout=10, # 添加10秒超时,避免无限等待
|
||||
)
|
||||
|
||||
# 流式写入文件,避免等待整个命令完成
|
||||
with open(tmp_file, "wb") as f:
|
||||
while True:
|
||||
chunk = process.stdout.read(65536) # 64KB 缓冲
|
||||
if not chunk:
|
||||
break
|
||||
f.write(chunk)
|
||||
|
||||
# 等待进程完成并检查返回码
|
||||
return_code = process.wait(timeout=10)
|
||||
if return_code != 0:
|
||||
raise subprocess.CalledProcessError(return_code, [adb, "-s", device_id, "exec-out", "screencap", "-p"])
|
||||
|
||||
t_exec_end = time.time()
|
||||
exec_ms = (t_exec_end - t_exec_start) * 1000
|
||||
timetag2 = datetime.now().strftime("%H:%M:%S")
|
||||
print(f"[{timetag2}] [DEBUG] exec-out streaming duration: {exec_ms:.0f}ms (device_id={device_id})")
|
||||
|
||||
except subprocess.TimeoutExpired:
|
||||
# Popen 超时,记录并重新抛出异常
|
||||
print(f"[截图] exec-out 流式读取超时")
|
||||
raise
|
||||
if _valid_png(tmp_file):
|
||||
# 使用安全的文件替换函数
|
||||
if _safe_replace_file(tmp_file, out_file):
|
||||
_mirror_screenshot_to_external(out_file)
|
||||
print(f"[{timetag}] [截图] ✓ 获取屏幕截图成功")
|
||||
elapsed = (time.time() - direct_start) * 1000
|
||||
print(f"[{timetag}] [截图] [OK] 获取屏幕截图成功 (流式截图,耗时: {elapsed:.0f}ms)")
|
||||
return True
|
||||
else:
|
||||
# 如果替换失败,但临时文件有效,仍然返回成功
|
||||
@@ -114,6 +167,8 @@ class ScreenshotOperations:
|
||||
|
||||
# 回退方案:老式 shell screencap + pull(兼容极少数不支持 exec-out 的环境)
|
||||
try:
|
||||
# 测量设备端生成与传输两部分耗时,分别记录
|
||||
t_shell_start = time.time()
|
||||
subprocess.run(
|
||||
[
|
||||
adb,
|
||||
@@ -129,6 +184,8 @@ class ScreenshotOperations:
|
||||
check=True,
|
||||
timeout=10, # 添加超时
|
||||
)
|
||||
t_shell_end = time.time()
|
||||
t_pull_start = time.time()
|
||||
subprocess.run(
|
||||
[adb, "-s", device_id, "pull", "/sdcard/DCIM/screenshot.png", tmp_file],
|
||||
stdout=subprocess.DEVNULL,
|
||||
@@ -136,11 +193,17 @@ class ScreenshotOperations:
|
||||
check=True,
|
||||
timeout=10, # 添加超时
|
||||
)
|
||||
t_pull_end = time.time()
|
||||
shell_ms = (t_shell_end - t_shell_start) * 1000
|
||||
pull_ms = (t_pull_end - t_pull_start) * 1000
|
||||
timetag3 = datetime.now().strftime("%H:%M:%S")
|
||||
print(f"[{timetag3}] [DEBUG] shell_screencap: {shell_ms:.0f}ms, pull: {pull_ms:.0f}ms (device_id={device_id})")
|
||||
if _valid_png(tmp_file):
|
||||
# 使用安全的文件替换函数
|
||||
if _safe_replace_file(tmp_file, out_file):
|
||||
_mirror_screenshot_to_external(out_file)
|
||||
print("{} 获取屏幕截图".format(timetag))
|
||||
elapsed = (time.time() - direct_start) * 1000
|
||||
print(f"[{timetag}] [截图] [OK] 获取屏幕截图成功 (回退方案,耗时: {elapsed:.0f}ms)")
|
||||
return True
|
||||
else:
|
||||
print("[截图] 回退方案文件替换失败")
|
||||
|
||||
Reference in new issue
Block a user