"""截图操作模块 包含截图、图片裁剪等截图相关操作。 支持后台截图服务和多线程优化。 """ from __future__ import annotations import os import subprocess import time from datetime import datetime from typing import Optional from Underlying_Operations import _safe_replace_file, _mirror_screenshot_to_external class ScreenshotOperations: """截图操作类""" @staticmethod def _adb() -> str: """返回adb命令路径""" import os adb = str(os.environ.get("ADB_EXECUTABLE", "adb") or "adb") # 始终加引号,避免路径带空格 / 版本混用 if adb.startswith('"') and adb.endswith('"'): return adb return f'"{adb}"' @staticmethod def _adb_path() -> str: """返回可用于 subprocess(list_args) 的 adb 路径(不带外层引号)。""" import os adb = str(os.environ.get("ADB_EXECUTABLE", "adb") or "adb") if adb.startswith('"') and adb.endswith('"'): adb = adb[1:-1] return adb 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 out_dir = path_config.get_pic_dir() except Exception: # 回退到旧路径(向后兼容) import path_config out_dir = path_config.get_pic_dir() else: out_dir = os.path.join(os.path.dirname(__file__), "target_pic") if not os.path.exists(out_dir): os.makedirs(out_dir) # 统一输出到固定文件名,兼容现有 cut_pic()/后续流程 out_file = os.path.join(out_dir, "screenshot.png") tmp_file = out_file + ".tmp" timetag = datetime.now().strftime("%H:%M:%S") adb = self._adb_path() def _valid_png(path0: str) -> bool: try: if not os.path.exists(path0): return False sz = os.path.getsize(path0) # PNG 通常远大于 1KB;0 字节/极小文件大概率是 adb 输出异常/中断 return sz >= 1024 except Exception: return False # 优先走 exec-out:只需 1 次 adb 调用;不在手机端落盘,减少 I/O 与卡顿 # 为避免被并发读取到"半写入文件",写入 tmp 后再原子替换。 for _ in range(2): try: try: if os.path.exists(tmp_file): os.remove(tmp_file) except Exception: pass # 使用 Popen 流式读取,边接收数据边写入文件,提高性能 t_exec_start = time.time() try: process = subprocess.Popen( [adb, "-s", device_id, "exec-out", "screencap", "-p"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, ) # 流式写入文件,避免等待整个命令完成 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) elapsed = (time.time() - direct_start) * 1000 print(f"[{timetag}] [截图] [OK] 获取屏幕截图成功 (流式截图,耗时: {elapsed:.0f}ms)") return True else: # 如果替换失败,但临时文件有效,仍然返回成功 # 后续代码可以读取临时文件或重试 print(f"[截图] 文件替换失败,但截图已保存到临时文件,将重试") # 不立即返回,继续尝试回退方案 except subprocess.TimeoutExpired: # 超时异常,记录并继续重试 print(f"[截图] exec-out 超时,尝试重试或回退方案") try: if os.path.exists(tmp_file): os.remove(tmp_file) except Exception: pass except Exception as e: # 继续回退/重试 print(f"[截图] exec-out 异常:{e}") try: if os.path.exists(tmp_file): os.remove(tmp_file) except Exception: pass # 回退方案:老式 shell screencap + pull(兼容极少数不支持 exec-out 的环境) try: # 测量设备端生成与传输两部分耗时,分别记录 t_shell_start = time.time() subprocess.run( [ adb, "-s", device_id, "shell", "screencap", "-p", "/sdcard/DCIM/screenshot.png", ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, 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, stderr=subprocess.DEVNULL, 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) elapsed = (time.time() - direct_start) * 1000 print(f"[{timetag}] [截图] [OK] 获取屏幕截图成功 (回退方案,耗时: {elapsed:.0f}ms)") return True else: print("[截图] 回退方案文件替换失败") return False else: print("[截图] 回退方案截图无效") return False except Exception as e: print(f"[截图] 回退方案失败:{e}") return False def _find_pic_path(self, picname: str, for_reading: bool = True) -> Optional[str]: """根据图片名称查找图片路径。 参数: picname: 图片文件名 for_reading: 是否用于读取(决定搜索的目录顺序) 返回: 图片的完整路径,如果未找到则返回 None """ # 搜索目录优先级 try: import path_config pic_dir = path_config.get_pic_dir() except Exception: import path_config pic_dir = path_config.get_pic_dir() search_dirs = [] if for_reading: # 读取时优先搜索当前目录的pic文件夹 search_dirs = [ pic_dir, os.path.join(os.path.dirname(__file__), "target_pic"), os.path.dirname(__file__), # 当前目录 ] else: # 写入时优先使用pic目录 search_dirs = [ pic_dir, ] # 尝试在每个目录中查找文件 for search_dir in search_dirs: if not os.path.exists(search_dir): continue pic_path = os.path.join(search_dir, picname) if os.path.exists(pic_path): return pic_path return None def cut_pic(self, left_up=(0, 63), right_down=(1080, 1620), target="", name=""): """裁剪图片:保持与原 fudai1.cut_pic 相同的坐标语义(1080x2400 基准)。""" # 这里应该实现图片裁剪逻辑 # 暂时从原文件导入以保持功能 from Underlying_Operations import underlying_operations instance = underlying_operations() return instance.cut_pic(left_up, right_down, target, name) def save_reward_pic(self, device_id): """保存奖励图片""" # 这里应该实现奖励图片保存逻辑 # 暂时从原文件导入以保持功能 from Underlying_Operations import underlying_operations instance = underlying_operations() return instance.save_reward_pic(device_id) # 全局截图操作实例 _screenshot_ops = ScreenshotOperations() def get_screenshot(device_id, path="pic") -> bool: """获取屏幕截图(向后兼容接口)""" return _screenshot_ops.get_screenshot(device_id, path) def _find_pic_path(picname: str, for_reading: bool = True) -> Optional[str]: """查找图片路径(向后兼容接口)""" return _screenshot_ops._find_pic_path(picname, for_reading) def cut_pic(left_up=(0, 63), right_down=(1080, 1620), target="", name=""): """裁剪图片(向后兼容接口)""" return _screenshot_ops.cut_pic(left_up, right_down, target, name) def save_reward_pic(device_id): """保存奖励图片(向后兼容接口)""" return _screenshot_ops.save_reward_pic(device_id) __all__ = [ "ScreenshotOperations", "get_screenshot", "_find_pic_path", "cut_pic", "save_reward_pic", ]