"""截图操作模块 包含截图、图片裁剪等截图相关操作。 """ from __future__ import annotations import os import subprocess 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") -> bool: """截图3个adb命令需要2S左右的时间""" if path == "pic": out_dir = os.path.join(os.path.dirname(__file__), "pic") 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 with open(tmp_file, "wb") as f: subprocess.run( [adb, "-s", device_id, "exec-out", "screencap", "-p"], stdout=f, stderr=subprocess.DEVNULL, check=True, timeout=10, # 添加10秒超时,避免无限等待 ) if _valid_png(tmp_file): # 使用安全的文件替换函数 if _safe_replace_file(tmp_file, out_file): _mirror_screenshot_to_external(out_file) print(f"[{timetag}] [截图] ✓ 获取屏幕截图成功") 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: subprocess.run( [ adb, "-s", device_id, "shell", "screencap", "-p", "/sdcard/DCIM/screenshot.png", ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True, timeout=10, # 添加超时 ) subprocess.run( [adb, "-s", device_id, "pull", "/sdcard/DCIM/screenshot.png", tmp_file], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True, timeout=10, # 添加超时 ) if _valid_png(tmp_file): # 使用安全的文件替换函数 if _safe_replace_file(tmp_file, out_file): _mirror_screenshot_to_external(out_file) print("{} 获取屏幕截图".format(timetag)) 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 """ # 搜索目录优先级 search_dirs = [] if for_reading: # 读取时优先搜索当前目录的pic文件夹 search_dirs = [ os.path.join(os.path.dirname(__file__), "pic"), os.path.join(os.path.dirname(__file__), "target_pic"), os.path.dirname(__file__), # 当前目录 ] else: # 写入时优先使用pic目录 search_dirs = [ os.path.join(os.path.dirname(__file__), "pic"), ] # 尝试在每个目录中查找文件 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", ]