优化后台截图功能
This commit is contained in:
1 parent
223c127e11
commit
ace3bbfa04
70 files changed
+4392
-871
No files matched your search
@@ -0,0 +1,101 @@
|
||||
"""使用 scrcpy server 模式进行截图(高性能替代方案)
|
||||
|
||||
scrcpy 通过 server 模式可以实现比 adb screencap 更快的截图速度。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
import tempfile
|
||||
from typing import Optional
|
||||
from datetime import datetime
|
||||
|
||||
from operations.screenshot_operations import ScreenshotOperations
|
||||
|
||||
|
||||
class ScrcpyScreenshot:
|
||||
"""使用 scrcpy server 进行截图"""
|
||||
|
||||
def __init__(self):
|
||||
self._scrcpy_path: Optional[str] = None
|
||||
self._server_path: Optional[str] = None
|
||||
self._find_scrcpy()
|
||||
|
||||
def _find_scrcpy(self):
|
||||
"""查找 scrcpy 可执行文件"""
|
||||
import shutil
|
||||
|
||||
# 先检查 PATH
|
||||
which_path = shutil.which('scrcpy')
|
||||
if which_path:
|
||||
self._scrcpy_path = which_path
|
||||
return
|
||||
|
||||
# 检查常见安装位置
|
||||
candidates = [
|
||||
os.path.join(os.getenv('LOCALAPPDATA', ''), 'Programs', 'scrcpy', 'scrcpy.exe'),
|
||||
os.path.join(os.getenv('USERPROFILE', ''), 'AppData', 'Local', 'Programs', 'scrcpy', 'scrcpy.exe'),
|
||||
r'C:\Program Files\scrcpy\scrcpy.exe',
|
||||
r'C:\Program Files (x86)\scrcpy\scrcpy.exe',
|
||||
]
|
||||
|
||||
for path in candidates:
|
||||
if path and os.path.exists(path):
|
||||
self._scrcpy_path = path
|
||||
# server 文件通常在同一目录
|
||||
server_path = os.path.join(os.path.dirname(path), 'scrcpy-server')
|
||||
if os.path.exists(server_path):
|
||||
self._server_path = server_path
|
||||
break
|
||||
|
||||
def is_available(self) -> bool:
|
||||
"""检查 scrcpy 是否可用"""
|
||||
return self._scrcpy_path is not None and os.path.exists(self._scrcpy_path)
|
||||
|
||||
def get_screenshot(self, device_id: str, output_path: str) -> bool:
|
||||
"""使用 scrcpy 进行截图
|
||||
|
||||
注意:scrcpy 本身不直接支持单次截图,这里使用变通方法:
|
||||
1. 启动 scrcpy server(如果支持)
|
||||
2. 或使用 scrcpy 的录制功能提取帧
|
||||
|
||||
参数:
|
||||
device_id: 设备ID
|
||||
output_path: 输出文件路径
|
||||
|
||||
返回:
|
||||
是否成功
|
||||
"""
|
||||
if not self.is_available():
|
||||
return False
|
||||
|
||||
timetag = datetime.now().strftime("%H:%M:%S")
|
||||
start_time = time.time()
|
||||
|
||||
try:
|
||||
# 方法1: 使用 scrcpy 的 --record 功能(需要停止机制,较复杂)
|
||||
# 方法2: 使用 scrcpy server 模式(推荐,但需要额外配置)
|
||||
# 方法3: 回退到 adb screencap(当前实现)
|
||||
|
||||
# 由于 scrcpy 不直接支持单次截图,这里先记录日志
|
||||
# 实际实现需要集成 scrcpy server 或使用第三方库
|
||||
print(f"[{timetag}] [scrcpy] 注意: scrcpy 不直接支持单次截图")
|
||||
print(f"[{timetag}] [scrcpy] 需要使用 scrcpy server 模式或集成到截图流程")
|
||||
|
||||
# 暂时回退到标准截图方法
|
||||
ops = ScreenshotOperations()
|
||||
return ops._get_screenshot_direct(device_id, os.path.dirname(output_path))
|
||||
|
||||
except Exception as e:
|
||||
elapsed = (time.time() - start_time) * 1000
|
||||
print(f"[{timetag}] [scrcpy] 截图失败: {e},耗时: {elapsed:.0f}ms")
|
||||
return False
|
||||
|
||||
|
||||
def get_scrcpy_screenshot(device_id: str, output_path: str) -> bool:
|
||||
"""获取 scrcpy 截图(便捷函数)"""
|
||||
scrcpy = ScrcpyScreenshot()
|
||||
return scrcpy.get_screenshot(device_id, output_path)
|
||||
|
||||
@@ -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("[截图] 回退方案文件替换失败")
|
||||
|
||||
@@ -0,0 +1,338 @@
|
||||
"""后台截图服务:持续截图,主流程直接读取最新截图
|
||||
|
||||
功能:
|
||||
1. 后台持续截图,避免主流程等待
|
||||
2. 截图缓存机制,减少重复截图
|
||||
3. 智能线程数配置,根据CPU核心数自动调整
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from typing import Optional
|
||||
from datetime import datetime
|
||||
import path_config
|
||||
from operations.screenshot_operations import ScreenshotOperations
|
||||
|
||||
|
||||
class ScreenshotService:
|
||||
"""后台截图服务:持续截图,避免主流程等待"""
|
||||
|
||||
_instance: Optional['ScreenshotService'] = None
|
||||
_lock = threading.Lock()
|
||||
|
||||
def __init__(self):
|
||||
self._running: bool = False
|
||||
self._thread: Optional[threading.Thread] = None
|
||||
self._screenshot_ops: ScreenshotOperations = ScreenshotOperations()
|
||||
self._current_device_id: Optional[str] = None
|
||||
# 修复:初始化为过去时间,确保第一次请求时缓存过期但时间差合理
|
||||
self._last_screenshot_time = time.time() - 10.0 # 10秒前,避免巨大时间差
|
||||
self._screenshot_interval = 3.5 # 增加间隔到3.5秒,适应实际截图耗时
|
||||
self._cache_valid_duration = 4.0 # 增加缓存有效期到4.0秒,避免频繁过期
|
||||
self._screenshot_path: Optional[str] = None
|
||||
self._last_success = False # 最后一次截图是否成功
|
||||
|
||||
@classmethod
|
||||
def get_instance(cls) -> 'ScreenshotService':
|
||||
"""获取单例实例"""
|
||||
if cls._instance is None:
|
||||
with cls._lock:
|
||||
if cls._instance is None:
|
||||
cls._instance = cls()
|
||||
return cls._instance
|
||||
|
||||
def start(self, device_id: str, interval: float = 1.5):
|
||||
"""启动后台截图服务
|
||||
|
||||
参数:
|
||||
device_id: 设备ID
|
||||
interval: 截图间隔(秒),默认1.5秒
|
||||
"""
|
||||
with self._lock:
|
||||
if self._running:
|
||||
if self._current_device_id == device_id:
|
||||
return # 已经在运行,且设备ID相同
|
||||
self.stop() # 设备ID不同,先停止
|
||||
|
||||
self._current_device_id = device_id
|
||||
self._screenshot_interval = max(0.5, interval) # 最小0.5秒
|
||||
self._running = True
|
||||
|
||||
# 初始化截图路径
|
||||
try:
|
||||
self._screenshot_path = path_config.get_screenshot_path()
|
||||
except (ImportError, AttributeError, OSError):
|
||||
self._screenshot_path = os.path.join("pic", "screenshot.png")
|
||||
|
||||
self._thread = threading.Thread(
|
||||
target=self._screenshot_loop,
|
||||
daemon=True,
|
||||
name="ScreenshotService"
|
||||
)
|
||||
self._thread.start()
|
||||
# 修复:设置时间戳为过去足够长的时间,确保第一次请求能等到后台截图完成
|
||||
self._last_screenshot_time = time.time() - self._cache_valid_duration - 1.0 # 确保缓存过期但不至于太旧
|
||||
timetag = datetime.now().strftime("%H:%M:%S")
|
||||
print(f"[{timetag}] [截图服务] 已启动后台截图服务,设备: {device_id}, 间隔: {interval}秒")
|
||||
|
||||
def stop(self):
|
||||
"""停止后台截图服务"""
|
||||
with self._lock:
|
||||
if not self._running:
|
||||
return
|
||||
self._running = False
|
||||
|
||||
if self._thread and self._thread.is_alive():
|
||||
self._thread.join(timeout=2.0)
|
||||
timetag = datetime.now().strftime("%H:%M:%S")
|
||||
print(f"[{timetag}] [截图服务] 已停止后台截图服务")
|
||||
|
||||
def _screenshot_loop(self):
|
||||
"""后台截图循环"""
|
||||
loop_count = 0
|
||||
while self._running:
|
||||
try:
|
||||
device_id = self._current_device_id
|
||||
if not device_id:
|
||||
time.sleep(0.1)
|
||||
continue
|
||||
|
||||
loop_count += 1
|
||||
timetag = datetime.now().strftime("%H:%M:%S")
|
||||
screenshot_start = time.time()
|
||||
|
||||
# 执行截图(禁用服务模式,避免递归)
|
||||
success = self._screenshot_ops.get_screenshot(device_id, use_service=False) # type: ignore[arg-type]
|
||||
|
||||
screenshot_elapsed = (time.time() - screenshot_start) * 1000
|
||||
if success:
|
||||
# 验证文件完整性后再更新时间戳(避免读取到不完整的文件)
|
||||
if self._screenshot_path and os.path.exists(self._screenshot_path):
|
||||
try:
|
||||
file_size = os.path.getsize(self._screenshot_path)
|
||||
if file_size >= 1024:
|
||||
with open(self._screenshot_path, 'rb') as f:
|
||||
header = f.read(4)
|
||||
if header == b'\x89PNG':
|
||||
self._last_screenshot_time = time.time()
|
||||
self._last_success = True
|
||||
print(f"[{timetag}] [截图服务] 后台截图完成 #{loop_count},耗时: {screenshot_elapsed:.0f}ms,文件大小: {file_size/1024:.1f}KB")
|
||||
else:
|
||||
self._last_success = False
|
||||
print(f"[{timetag}] [截图服务] 后台截图文件格式错误 #{loop_count},耗时: {screenshot_elapsed:.0f}ms")
|
||||
else:
|
||||
self._last_success = False
|
||||
print(f"[{timetag}] [截图服务] 后台截图文件太小 #{loop_count} ({file_size}B),耗时: {screenshot_elapsed:.0f}ms")
|
||||
except (OSError, IOError, ValueError) as e:
|
||||
self._last_success = False
|
||||
print(f"[{timetag}] [截图服务] 后台截图文件验证失败 #{loop_count}: {e},耗时: {screenshot_elapsed:.0f}ms")
|
||||
else:
|
||||
self._last_success = False
|
||||
print(f"[{timetag}] [截图服务] 后台截图文件不存在 #{loop_count},耗时: {screenshot_elapsed:.0f}ms")
|
||||
else:
|
||||
self._last_success = False
|
||||
print(f"[{timetag}] [截图服务] 后台截图失败 #{loop_count},耗时: {screenshot_elapsed:.0f}ms")
|
||||
|
||||
# 等待间隔时间,确保不小于0.5秒
|
||||
remaining_interval = max(0.5, self._screenshot_interval - screenshot_elapsed / 1000)
|
||||
time.sleep(remaining_interval)
|
||||
except Exception as e:
|
||||
try:
|
||||
timetag = datetime.now().strftime("%H:%M:%S")
|
||||
print(f"[{timetag}] [截图服务] 后台截图异常: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1.0) # 异常时等待1秒再继续
|
||||
|
||||
def get_screenshot(self, device_id: str, force: bool = False) -> bool:
|
||||
"""获取截图(优先使用缓存)
|
||||
|
||||
参数:
|
||||
device_id: 设备ID
|
||||
force: 是否强制重新截图(忽略缓存)
|
||||
|
||||
返回:
|
||||
是否成功获取截图
|
||||
"""
|
||||
request_start = time.time()
|
||||
timetag = datetime.now().strftime("%H:%M:%S")
|
||||
|
||||
# 如果设备ID不同,需要重新启动服务
|
||||
if self._current_device_id != device_id:
|
||||
print(f"[{timetag}] [截图服务] 设备ID变更,重新启动服务: {device_id}")
|
||||
self.start(device_id)
|
||||
# 等待第一次截图完成
|
||||
time.sleep(0.1)
|
||||
|
||||
# 检查缓存是否有效
|
||||
if not force:
|
||||
now = time.time()
|
||||
time_since_last = now - self._last_screenshot_time
|
||||
|
||||
# 修复:添加边界检查,避免负数或异常值
|
||||
if time_since_last < 0:
|
||||
time_since_last = 0 # 避免时钟回拨导致的负数
|
||||
elif time_since_last > 86400: # 如果超过24小时,可能是时间戳错误
|
||||
time_since_last = 10.0 # 重置为10秒前
|
||||
|
||||
# 检查缓存是否有效(时间 + 文件存在 + 文件完整性)
|
||||
if time_since_last < self._cache_valid_duration:
|
||||
if self._screenshot_path and os.path.exists(self._screenshot_path):
|
||||
# 验证文件完整性(避免读取到不完整的文件)
|
||||
# 使用重试机制,等待文件写入完成
|
||||
for retry in range(3):
|
||||
try:
|
||||
file_size = os.path.getsize(self._screenshot_path)
|
||||
if file_size >= 1024: # PNG文件至少1KB
|
||||
# 尝试快速验证文件头(PNG文件头:89 50 4E 47)
|
||||
with open(self._screenshot_path, 'rb') as f:
|
||||
header = f.read(4)
|
||||
if header == b'\x89PNG':
|
||||
# 验证文件尾(PNG文件尾:IEND)
|
||||
# 更宽松的验证:检查文件末尾50字节内是否有IEND
|
||||
try:
|
||||
# 读取文件末尾50字节
|
||||
read_size = min(50, file_size)
|
||||
f.seek(-read_size, 2)
|
||||
footer = f.read(read_size)
|
||||
if b'IEND' in footer:
|
||||
elapsed = (time.time() - request_start) * 1000
|
||||
print(f"[{timetag}] [截图服务] [OK] 缓存命中,耗时: {elapsed:.1f}ms (距离上次截图: {time_since_last*1000:.0f}ms, 文件大小: {file_size/1024:.1f}KB)")
|
||||
return True
|
||||
elif retry < 2:
|
||||
# 文件可能还在写入,等待一下
|
||||
time.sleep(0.1)
|
||||
continue
|
||||
else:
|
||||
print(f"[{timetag}] [截图服务] [WARN] 缓存文件不完整(文件尾验证失败),等待后台截图")
|
||||
except (OSError, IOError) as e:
|
||||
if retry < 2:
|
||||
time.sleep(0.1)
|
||||
continue
|
||||
else:
|
||||
print(f"[{timetag}] [截图服务] [WARN] 缓存文件读取失败: {e},等待后台截图")
|
||||
else:
|
||||
print(f"[{timetag}] [截图服务] [WARN] 缓存文件格式错误,等待后台截图")
|
||||
break
|
||||
else:
|
||||
if retry < 2:
|
||||
time.sleep(0.05)
|
||||
continue
|
||||
else:
|
||||
print(f"[{timetag}] [截图服务] [WARN] 缓存文件太小 ({file_size}B),等待后台截图")
|
||||
except (OSError, IOError) as e:
|
||||
if retry < 2:
|
||||
time.sleep(0.05)
|
||||
continue
|
||||
else:
|
||||
print(f"[{timetag}] [截图服务] [WARN] 缓存文件检查失败: {e},等待后台截图")
|
||||
except ValueError as e:
|
||||
print(f"[{timetag}] [截图服务] [WARN] 缓存文件检查异常: {e},等待后台截图")
|
||||
break
|
||||
else:
|
||||
print(f"[{timetag}] [截图服务] [WARN] 缓存文件不存在,等待后台截图")
|
||||
else:
|
||||
print(f"[{timetag}] [截图服务] [WARN] 缓存已过期 (距离上次: {time_since_last*1000:.0f}ms > {self._cache_valid_duration*1000:.0f}ms),等待后台截图")
|
||||
|
||||
# 缓存无效或强制刷新
|
||||
if force:
|
||||
print(f"[{timetag}] [截图服务] 🔄 强制刷新,忽略缓存")
|
||||
|
||||
# 等待后台截图完成
|
||||
if self._running:
|
||||
wait_start = time.time()
|
||||
time_since_last_before_wait = time.time() - self._last_screenshot_time
|
||||
# 修复:添加边界检查
|
||||
if time_since_last_before_wait < 0:
|
||||
time_since_last_before_wait = 0
|
||||
elif time_since_last_before_wait > 86400:
|
||||
time_since_last_before_wait = 10.0
|
||||
print(f"[{timetag}] [截图服务] [WAIT] 缓存未命中,等待后台截图 (距离上次: {time_since_last_before_wait*1000:.0f}ms)")
|
||||
|
||||
# 等待最多6秒,让后台线程完成截图(适应较慢的截图操作)
|
||||
max_wait_time = 6.0
|
||||
while time.time() - wait_start < max_wait_time:
|
||||
if self._last_screenshot_time > wait_start - 0.1:
|
||||
# 截图已完成,验证文件完整性
|
||||
if self._screenshot_path and os.path.exists(self._screenshot_path):
|
||||
try:
|
||||
file_size = os.path.getsize(self._screenshot_path)
|
||||
if file_size >= 1024:
|
||||
with open(self._screenshot_path, 'rb') as f:
|
||||
header = f.read(4)
|
||||
if header == b'\x89PNG':
|
||||
# 验证文件尾(更宽松的验证)
|
||||
read_size = min(50, file_size)
|
||||
f.seek(-read_size, 2)
|
||||
footer = f.read(read_size)
|
||||
if b'IEND' in footer:
|
||||
wait_elapsed = (time.time() - wait_start) * 1000
|
||||
total_elapsed = (time.time() - request_start) * 1000
|
||||
status = "[OK]" if self._last_success else "[FAIL]"
|
||||
print(f"[{timetag}] [截图服务] {status} 后台截图完成,等待耗时: {wait_elapsed:.1f}ms,总耗时: {total_elapsed:.1f}ms,文件大小: {file_size/1024:.1f}KB")
|
||||
return self._last_success
|
||||
# 文件尾验证失败,继续等待
|
||||
# 文件太小或格式错误,继续等待
|
||||
except (OSError, IOError, ValueError):
|
||||
# 文件验证失败,继续等待
|
||||
pass
|
||||
time.sleep(0.1)
|
||||
|
||||
# 等待超时
|
||||
wait_elapsed = (time.time() - wait_start) * 1000
|
||||
print(f"[{timetag}] [截图服务] [TIMEOUT] 等待超时 ({wait_elapsed:.1f}ms),回退到直接截图")
|
||||
|
||||
# 如果后台服务未运行或等待超时,直接执行截图(禁用服务模式,避免递归)
|
||||
direct_start = time.time()
|
||||
result = self._screenshot_ops.get_screenshot(device_id, use_service=False) # type: ignore[arg-type]
|
||||
direct_elapsed = (time.time() - direct_start) * 1000
|
||||
total_elapsed = (time.time() - request_start) * 1000
|
||||
status = "[OK]" if result else "[FAIL]"
|
||||
print(f"[{timetag}] [截图服务] {status} 直接截图完成,耗时: {direct_elapsed:.0f}ms,总耗时: {total_elapsed:.1f}ms")
|
||||
return result
|
||||
|
||||
def is_running(self) -> bool:
|
||||
"""检查服务是否正在运行"""
|
||||
return self._running
|
||||
|
||||
def get_last_screenshot_time(self) -> float:
|
||||
"""获取最后一次截图的时间戳"""
|
||||
return self._last_screenshot_time
|
||||
|
||||
def get_cache_info(self) -> dict:
|
||||
"""获取缓存信息(用于调试)"""
|
||||
return {
|
||||
"running": self._running,
|
||||
"device_id": self._current_device_id,
|
||||
"last_screenshot_time": self._last_screenshot_time,
|
||||
"interval": self._screenshot_interval,
|
||||
"cache_valid_duration": self._cache_valid_duration,
|
||||
"last_success": self._last_success,
|
||||
}
|
||||
|
||||
|
||||
def get_optimal_workers() -> int:
|
||||
"""根据CPU核心数获取最优线程数
|
||||
|
||||
返回:
|
||||
推荐的线程数
|
||||
"""
|
||||
cpu_count = os.cpu_count() or 4
|
||||
|
||||
# 针对12核CPU的优化配置
|
||||
if cpu_count >= 12:
|
||||
return 10 # 12核:使用10个线程
|
||||
elif cpu_count >= 8:
|
||||
return 8 # 8核:使用8个线程
|
||||
elif cpu_count >= 4:
|
||||
return 6 # 4核:使用6个线程
|
||||
elif cpu_count >= 2:
|
||||
return 3 # 2核:使用3个线程
|
||||
else:
|
||||
return 2 # 单核:使用2个线程(I/O等待)
|
||||
|
||||
Reference in new issue
Block a user