fix(screenshot): recover adb after empty screencap output
Windows Package CI / package-fresh-install (push) Waiting to run
Windows Package CI / package-fresh-install (push) Waiting to run
This commit is contained in:
1 parent
329b7756f4
commit
60306dd4e0
2 files changed
+125
-45
No files matched your search
@@ -224,60 +224,84 @@ class ScreenshotOperations:
|
||||
_ops_log(f"[截图] shell stdout回退失败:{e}")
|
||||
return False
|
||||
|
||||
def _format_adb_stderr(value: bytes | str | None) -> str:
|
||||
if value is None:
|
||||
return ""
|
||||
if isinstance(value, bytes):
|
||||
text = value.decode("utf-8", errors="replace")
|
||||
else:
|
||||
text = str(value)
|
||||
text = " ".join(text.strip().split())
|
||||
return text[-500:]
|
||||
|
||||
adb_recovered = False
|
||||
|
||||
def _recover_adb_once(reason: str) -> None:
|
||||
nonlocal adb_recovered
|
||||
if adb_recovered:
|
||||
return
|
||||
adb_recovered = True
|
||||
_ops_log(f"[截图] ADB截图输出异常,尝试重启ADB服务后重试: {reason}", "WARNING")
|
||||
for args, timeout in (
|
||||
([adb, "kill-server"], 5),
|
||||
([adb, "start-server"], 8),
|
||||
):
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
args,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
check=False,
|
||||
timeout=timeout,
|
||||
)
|
||||
if proc.returncode != 0:
|
||||
err = _format_adb_stderr(proc.stderr or proc.stdout)
|
||||
_ops_log(f"[截图] ADB恢复命令返回异常 rc={proc.returncode} err={err}", "WARNING")
|
||||
except Exception as exc:
|
||||
_ops_log(f"[截图] ADB恢复命令执行失败: {exc}", "WARNING")
|
||||
time.sleep(0.5)
|
||||
|
||||
# 优先走 exec-out:只需 1 次 adb 调用;不在手机端落盘,减少 I/O 与卡顿
|
||||
# 为避免被并发读取到"半写入文件",写入 tmp 后再原子替换。
|
||||
for _ in range(2):
|
||||
for attempt 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,
|
||||
result = subprocess.run(
|
||||
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
check=False,
|
||||
timeout=10,
|
||||
)
|
||||
exec_ms = (time.time() - t_exec_start) * 1000
|
||||
timetag2 = datetime.now().strftime("%H:%M:%S")
|
||||
out = result.stdout or b""
|
||||
err = _format_adb_stderr(result.stderr)
|
||||
if result.returncode != 0:
|
||||
reason = f"rc={result.returncode} bytes={len(out)} err={err or '<empty>'}"
|
||||
_ops_log(f"[截图] exec-out 返回异常: {reason}", "WARNING")
|
||||
if result.returncode == 4294967295:
|
||||
_ops_log(f"[截图] exec-out 异常:设备连接失败或ADB服务异常 (设备ID: {device_id})")
|
||||
if attempt == 0:
|
||||
_recover_adb_once(reason)
|
||||
continue
|
||||
if not _write_valid_png_bytes(out):
|
||||
reason = f"rc=0 bytes={len(out)} err={err or '<empty>'}"
|
||||
_ops_log(
|
||||
f"[截图] exec-out 输出无效: {reason} attempt={attempt + 1}/2",
|
||||
"WARNING",
|
||||
)
|
||||
|
||||
# 流式写入文件,避免等待整个命令完成
|
||||
with open(tmp_file, "wb") as f:
|
||||
while True:
|
||||
chunk = process.stdout.read(65536) # 64KB 缓冲
|
||||
if not chunk:
|
||||
break
|
||||
f.write(chunk)
|
||||
# 确保数据落盘,避免后续读取到半写文件
|
||||
try:
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 等待进程完成并检查返回码
|
||||
return_code = process.wait(timeout=10)
|
||||
if return_code != 0:
|
||||
# 特殊处理常见的adb错误码
|
||||
if return_code == 4294967295: # 0xFFFFFFFF
|
||||
raise subprocess.CalledProcessError(
|
||||
return_code,
|
||||
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
|
||||
f"设备连接失败或ADB服务异常 (错误码: {return_code})"
|
||||
)
|
||||
else:
|
||||
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")
|
||||
_ops_log(f"[{timetag2}] [DEBUG] exec-out duration: {exec_ms:.0f}ms (device_id={device_id})")
|
||||
|
||||
except subprocess.TimeoutExpired:
|
||||
# Popen 超时,记录并重新抛出异常
|
||||
_ops_log(f"[截图] exec-out 流式读取超时")
|
||||
raise
|
||||
if attempt == 0:
|
||||
_recover_adb_once(reason)
|
||||
continue
|
||||
_ops_log(
|
||||
f"[{timetag2}] [DEBUG] exec-out duration: {exec_ms:.0f}ms bytes={len(out)} (device_id={device_id})"
|
||||
)
|
||||
if _valid_png(tmp_file):
|
||||
# 使用安全的文件替换函数并二次验证目标文件,避免写入截断导致后续读取失败
|
||||
if _safe_replace_file(tmp_file, out_file):
|
||||
@@ -301,7 +325,10 @@ class ScreenshotOperations:
|
||||
_ops_log(f"[{timetag}] [截图] 文件替换失败,但截图已保存到临时文件,将尝试回退方案")
|
||||
except subprocess.TimeoutExpired:
|
||||
# 超时异常,记录并继续重试
|
||||
_ops_log(f"[截图] exec-out 超时,尝试重试或回退方案")
|
||||
reason = f"timeout device_id={device_id}"
|
||||
_ops_log(f"[截图] exec-out 超时,尝试重试或回退方案", "WARNING")
|
||||
if attempt == 0:
|
||||
_recover_adb_once(reason)
|
||||
try:
|
||||
if os.path.exists(tmp_file):
|
||||
os.remove(tmp_file)
|
||||
|
||||
Reference in new issue
Block a user