Files
iOSAI/Module/DeviceInfo.py

450 lines
19 KiB
Python
Raw Normal View History

2025-09-11 22:46:55 +08:00
# -*- coding: utf-8 -*-
2025-08-15 20:04:59 +08:00
import os
2025-08-28 19:51:57 +08:00
import signal
2025-08-15 20:04:59 +08:00
import sys
2025-08-01 13:43:51 +08:00
import time
2025-09-17 22:23:57 +08:00
from concurrent.futures import ThreadPoolExecutor, as_completed
2025-08-15 20:04:59 +08:00
from pathlib import Path
from typing import List, Dict, Optional
2025-09-18 21:31:23 +08:00
import threading
import subprocess
import wda
2025-09-04 20:47:14 +08:00
from tidevice import Usbmux, ConnectionType
2025-09-08 13:48:21 +08:00
from tidevice._device import BaseDevice
2025-08-01 13:43:51 +08:00
from Entity.DeviceModel import DeviceModel
2025-08-14 15:51:17 +08:00
from Entity.Variables import WdaAppBundleId
2025-08-01 13:43:51 +08:00
from Module.FlaskSubprocessManager import FlaskSubprocessManager
from Utils.LogManager import LogManager
2025-09-17 22:23:57 +08:00
from Utils.SubprocessKit import check_output as sp_check_output, popen as sp_popen
2025-08-01 13:43:51 +08:00
class Deviceinfo(object):
2025-09-11 22:46:55 +08:00
"""设备生命周期管理:以 deviceModelList 为唯一真理源"""
2025-08-01 13:43:51 +08:00
def __init__(self):
2025-09-18 21:31:23 +08:00
# ✅ 连接线程池(最大 6 并发)
2025-09-17 22:23:57 +08:00
self._connect_pool = ThreadPoolExecutor(max_workers=6)
if os.name == "nt":
self._si = subprocess.STARTUPINFO()
self._si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
self._si.wShowWindow = subprocess.SW_HIDE # 0
else:
self._si = None
2025-08-01 13:43:51 +08:00
self.deviceIndex = 0
self.screenProxy = 9110
2025-09-11 22:46:55 +08:00
self.pidList: List[Dict] = [] # 仅记录 iproxy 进程
2025-08-01 13:43:51 +08:00
self.manager = FlaskSubprocessManager.get_instance()
2025-09-11 22:46:55 +08:00
self.deviceModelList: List[DeviceModel] = [] # 根基,不动
2025-08-18 22:20:23 +08:00
self.maxDeviceCount = 6
2025-09-11 22:46:55 +08:00
2025-08-28 19:51:57 +08:00
self._lock = threading.Lock()
2025-09-11 22:46:55 +08:00
self._model_index: Dict[str, DeviceModel] = {} # udid -> model
2025-09-18 21:31:23 +08:00
# ✅ 失踪时间戳记录(替代原来的 miss_count
2025-09-17 15:43:23 +08:00
self._last_seen: Dict[str, float] = {}
self._port_pool: List[int] = []
self._port_in_use: set[int] = set()
2025-09-08 13:48:21 +08:00
2025-09-18 21:31:23 +08:00
# ✅ 新增:全局 iproxy 进程注册表 udid -> Popen
self._iproxy_registry: Dict[str, subprocess.Popen] = {}
2025-09-17 15:43:23 +08:00
# region iproxy 初始化(原逻辑不变)
2025-08-18 22:20:23 +08:00
try:
2025-09-08 13:48:21 +08:00
self.iproxy_path = self._iproxy_path()
2025-08-18 22:20:23 +08:00
self.iproxy_dir = self.iproxy_path.parent
os.environ["PATH"] = str(self.iproxy_dir) + os.pathsep + os.environ.get("PATH", "")
try:
os.add_dll_directory(str(self.iproxy_dir))
except Exception:
pass
self._creationflags = 0x08000000 if os.name == "nt" else 0
2025-09-17 22:23:57 +08:00
2025-08-18 22:20:23 +08:00
self._popen_kwargs = dict(
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=str(self.iproxy_dir),
shell=False,
text=True,
2025-09-17 22:23:57 +08:00
creationflags=0x08000000 if os.name == "nt" else 0, # CREATE_NO_WINDOW
2025-08-18 22:20:23 +08:00
encoding="utf-8",
bufsize=1,
)
def _spawn_iproxy(udid: str, local_port: int, remote_port: int = 9100) -> subprocess.Popen:
args = [str(self.iproxy_path), "-u", udid, str(local_port), str(remote_port)]
p = subprocess.Popen(args, **self._popen_kwargs)
2025-09-18 21:31:23 +08:00
# ✅ 注册到全局表
self._iproxy_registry[udid] = p
2025-08-18 22:20:23 +08:00
def _pipe_to_log(name: str, stream):
try:
for line in iter(stream.readline, ''):
s = line.strip()
if s:
LogManager.info(f"[iproxy {name}] {s}", udid)
except Exception:
pass
2025-09-11 22:46:55 +08:00
threading.Thread(target=_pipe_to_log, args=("STDOUT", p.stdout), daemon=True).start()
threading.Thread(target=_pipe_to_log, args=("STDERR", p.stderr), daemon=True).start()
2025-08-18 22:20:23 +08:00
return p
2025-09-08 13:48:21 +08:00
self._spawn_iproxy = _spawn_iproxy
2025-08-18 22:20:23 +08:00
LogManager.info(f"iproxy 启动器已就绪,目录: {self.iproxy_dir}")
except Exception as e:
self.iproxy_path = None
self.iproxy_dir = None
self._spawn_iproxy = None
LogManager.error(f"初始化 iproxy 失败:{e}")
2025-09-11 22:46:55 +08:00
# endregion
2025-08-01 13:43:51 +08:00
2025-09-17 15:43:23 +08:00
# ------------------------------------------------------------------
2025-09-17 22:23:57 +08:00
# 主监听循环 → 只负责“发现”和“提交任务”
2025-09-17 15:43:23 +08:00
# ------------------------------------------------------------------
2025-08-01 13:43:51 +08:00
def startDeviceListener(self):
2025-09-17 22:23:57 +08:00
MISS_WINDOW = 5.0
2025-08-01 13:43:51 +08:00
while True:
2025-08-15 20:04:59 +08:00
try:
lists = Usbmux().device_list()
except Exception as e:
2025-09-11 22:46:55 +08:00
LogManager.warning(f"usbmuxd 连接失败: {e}2 秒后重试")
2025-08-15 20:04:59 +08:00
time.sleep(2)
continue
2025-09-08 13:48:21 +08:00
now_udids = {d.udid for d in lists if d.conn_type == ConnectionType.USB}
2025-09-17 15:43:23 +08:00
usb_sn_set = self._usb_enumerate_sn()
2025-09-11 22:46:55 +08:00
2025-09-17 22:23:57 +08:00
# 1. 失踪判定(同旧逻辑)
need_remove = []
2025-09-11 22:46:55 +08:00
with self._lock:
for udid in list(self._model_index.keys()):
if udid not in now_udids:
2025-09-17 15:43:23 +08:00
last = self._last_seen.get(udid, time.time())
if time.time() - last > MISS_WINDOW and udid not in usb_sn_set:
2025-09-17 22:23:57 +08:00
need_remove.append(udid)
2025-09-11 22:46:55 +08:00
else:
2025-09-17 15:43:23 +08:00
self._last_seen[udid] = time.time()
2025-09-17 22:23:57 +08:00
for udid in need_remove:
self._remove_model(udid)
2025-09-16 20:03:17 +08:00
2025-09-18 21:31:23 +08:00
# ✅ 实时清理孤儿 iproxy原 10 秒改为每次循环)
self._cleanup_orphan_iproxy()
# ✅ 设备全空时核平所有 iproxy
if not self.deviceModelList:
self._kill_all_iproxy()
2025-09-17 22:23:57 +08:00
# 2. 发现新设备 → 并发连接
with self._lock:
new_udids = [d.udid for d in lists
if d.conn_type == ConnectionType.USB and
d.udid not in self._model_index and
len(self.deviceModelList) < self.maxDeviceCount]
if new_udids:
futures = {self._connect_pool.submit(self._connect_device_task, udid): udid
for udid in new_udids}
for f in as_completed(futures, timeout=10):
udid = futures[f]
try:
f.result(timeout=8) # 单台 8 s 硬截止
except Exception as e:
LogManager.error(f"连接任务超时/失败: {e}", udid)
2025-09-04 20:47:14 +08:00
2025-08-01 13:43:51 +08:00
time.sleep(1)
2025-09-17 15:43:23 +08:00
# ------------------------------------------------------------------
2025-09-18 21:31:23 +08:00
# ✅ USB 层枚举 SN跨平台
2025-09-17 15:43:23 +08:00
# ------------------------------------------------------------------
def _usb_enumerate_sn(self) -> set[str]:
try:
2025-09-17 22:23:57 +08:00
out = sp_check_output(["idevice_id", "-l"], text=True, timeout=3)
2025-09-17 15:43:23 +08:00
return {line.strip() for line in out.splitlines() if line.strip()}
except Exception:
return set()
2025-09-18 21:31:23 +08:00
# ----------------------------------------------------------
# ✅ 清理孤儿 iproxy
# ----------------------------------------------------------
def _cleanup_orphan_iproxy(self):
live_udids = set(self._model_index.keys())
for udid, proc in list(self._iproxy_registry.items()):
if udid not in live_udids:
LogManager.warning(f"发现孤儿 iproxy 进程UDID 不在线:{udid},正在清理")
self._terminate_proc(proc)
self._iproxy_registry.pop(udid, None)
# ----------------------------------------------------------
# ✅ 核平所有 iproxyWindows / macOS 通用)
# ----------------------------------------------------------
def _kill_all_iproxy(self):
try:
if os.name == "nt":
subprocess.run(["taskkill", "/F", "/IM", "iproxy.exe"], check=False)
else:
subprocess.run(["pkill", "-f", "iproxy"], check=False)
self._iproxy_registry.clear()
LogManager.info("已强制清理所有 iproxy 进程")
except Exception as e:
LogManager.warning(f"强制清理 iproxy 失败:{e}")
# -------------------- 以下代码与原文件完全一致 --------------------
2025-09-15 22:40:45 +08:00
def _wda_health_checker(self):
while True:
time.sleep(1)
with self._lock:
2025-09-17 15:43:23 +08:00
online = [m for m in self.deviceModelList if m.ready]
2025-09-15 22:40:45 +08:00
for model in online:
udid = model.deviceId
if not self._wda_ok(udid):
LogManager.warning(f"WDA 异常,重启通道:{udid}", udid)
with self._lock:
self._remove_model(udid)
self.connectDevice(udid)
def _wda_ok(self, udid: str) -> bool:
try:
c = wda.USBClient(udid, 8100)
st = c.status()
if st.get("state") != "success":
return False
return True
except Exception as e:
LogManager.error(f"WDA health-check 异常:{e}", udid)
return False
2025-09-17 15:43:23 +08:00
# -------------------- 增删改查唯一入口(未改动) --------------------
2025-09-11 22:46:55 +08:00
def _has_model(self, udid: str) -> bool:
2025-09-12 13:44:26 +08:00
return udid in self._model_index
2025-09-11 22:46:55 +08:00
def _add_model(self, model: DeviceModel):
2025-09-12 13:44:26 +08:00
if model.deviceId in self._model_index:
2025-09-17 15:43:23 +08:00
return
2025-09-12 21:36:29 +08:00
model.ready = True
2025-09-12 13:44:26 +08:00
self.deviceModelList.append(model)
self._model_index[model.deviceId] = model
try:
self.manager.send(model.toDict())
except Exception as e:
2025-09-16 15:31:55 +08:00
LogManager.warning(f"{model.deviceId} 发送上线事件失败:{e}")
2025-09-17 15:43:23 +08:00
LogManager.method_info(f"{model.deviceId} 加入设备成功,当前在线数:{len(self.deviceModelList)}", method="device_count")
2025-09-16 21:33:44 +08:00
2025-09-11 22:46:55 +08:00
def _remove_model(self, udid: str):
2025-09-16 20:03:17 +08:00
print(f"【删】进入删除方法 udid={udid}")
2025-09-16 21:33:44 +08:00
LogManager.method_info(f"【删】进入删除方法 udid={udid}", method="device_count")
2025-09-16 20:03:17 +08:00
with self._lock:
print(f"【删】拿到锁 udid={udid}")
2025-09-17 15:43:23 +08:00
LogManager.method_info(f"【删】拿到锁 udid={udid}", method="device_count")
2025-09-16 20:03:17 +08:00
model = self._model_index.pop(udid, None)
if not model:
print(f"【删】模型已空,直接返回 udid={udid}")
2025-09-17 15:43:23 +08:00
LogManager.method_info(f"【删】模型已空,直接返回 udid={udid}", method="device_count")
2025-09-16 20:03:17 +08:00
return
if model.deleting:
print(f"【删】正在删除中,幂等返回 udid={udid}")
2025-09-16 21:33:44 +08:00
LogManager.method_info(method="device_count", text=f"【删】正在删除中,幂等返回 udid={udid}")
2025-09-16 20:03:17 +08:00
return
model.deleting = True
model.type = 2
print(f"【删】标记 deleting=True udid={udid}")
2025-09-17 15:43:23 +08:00
LogManager.method_info("【删】标记 deleting=True udid={udid}", "device_count")
2025-09-16 20:03:17 +08:00
before = len(self.deviceModelList)
self.deviceModelList = [m for m in self.deviceModelList if m.deviceId != udid]
after = len(self.deviceModelList)
print(f"【删】列表过滤 before={before} → after={after} udid={udid}")
2025-09-17 15:43:23 +08:00
LogManager.method_info(f"【删】列表过滤 before={before} → after={after} udid={udid}", "device_count")
2025-09-16 20:03:17 +08:00
self._port_in_use.discard(model.screenPort)
self._port_pool.append(model.screenPort)
print(f"【删】回收端口 port={model.screenPort} udid={udid}")
2025-09-16 21:33:44 +08:00
LogManager.method_info(f"【删】回收端口 port={model.screenPort} udid={udid}", method="device_count")
2025-09-16 20:03:17 +08:00
to_kill = [item for item in self.pidList if item.get("id") == udid]
self.pidList = [item for item in self.pidList if item.get("id") != udid]
print(f"【删】待杀进程数 count={len(to_kill)} udid={udid}")
2025-09-16 21:33:44 +08:00
LogManager.method_info(f"【删】待杀进程数 count={len(to_kill)} udid={udid}", method="device_count")
2025-09-16 20:03:17 +08:00
2025-09-18 21:31:23 +08:00
# ✅ 先清理注册表中的 iproxy
iproxy_proc = self._iproxy_registry.pop(udid, None)
if iproxy_proc:
self._terminate_proc(iproxy_proc)
2025-09-16 20:03:17 +08:00
for idx, item in enumerate(to_kill, 1):
print(f"【删】杀进程 {idx}/{len(to_kill)} pid={item.get('target').pid} udid={udid}")
2025-09-17 15:43:23 +08:00
LogManager.method_info(f"【删】杀进程 {idx}/{len(to_kill)} pid={item.get('target').pid} udid={udid}", method="device_count")
2025-09-16 20:03:17 +08:00
self._terminate_proc(item.get("target"))
print(f"【删】进程清理完成 udid={udid}")
2025-09-16 21:33:44 +08:00
LogManager.method_info(f"【删】进程清理完成 udid={udid}", method="device_count")
2025-09-16 20:03:17 +08:00
2025-09-11 22:46:55 +08:00
retry = 3
while retry:
try:
self.manager.send(model.toDict())
2025-09-16 20:03:17 +08:00
print(f"【删】下线事件已发送 udid={udid}")
2025-09-16 21:33:44 +08:00
LogManager.method_info(f"【删】下线事件已发送 udid={udid}", method="device_count")
2025-09-11 22:46:55 +08:00
break
except Exception as e:
retry -= 1
2025-09-16 20:03:17 +08:00
print(f"【删】发送事件失败 retry={retry} err={e} udid={udid}")
2025-09-16 21:33:44 +08:00
LogManager.method_error(f"【删】发送事件失败 retry={retry} err={e} udid={udid}", method="device_count")
2025-09-11 22:46:55 +08:00
time.sleep(0.2)
else:
2025-09-16 20:03:17 +08:00
print(f"【删】发送事件彻底失败,主动退出 udid={udid}")
2025-09-16 21:33:44 +08:00
LogManager.method_error(f"【删】发送事件彻底失败,主动退出 udid={udid}", method="device_count")
2025-09-11 22:46:55 +08:00
2025-09-16 20:03:17 +08:00
print(f"【删】===== 设备 {udid} 删除全流程结束 =====")
2025-09-16 21:33:44 +08:00
LogManager.method_info(f"【删】===== 设备 {udid} 删除全流程结束 =====", method="device_count")
2025-09-16 20:03:17 +08:00
print(len(self.deviceModelList))
2025-09-16 21:33:44 +08:00
LogManager.method_info(f"当前剩余设备数量:{len(self.deviceModelList)}", method="device_count")
2025-09-16 20:03:17 +08:00
2025-09-17 15:43:23 +08:00
# -------------------- 端口分配与回收(未改动) --------------------
2025-09-11 22:46:55 +08:00
def _alloc_port(self) -> int:
2025-09-12 13:44:26 +08:00
if self._port_pool:
port = self._port_pool.pop()
else:
self.screenProxy += 1
port = self.screenProxy
self._port_in_use.add(port)
return port
2025-09-11 22:46:55 +08:00
def _free_port(self, port: int):
2025-09-12 13:44:26 +08:00
if port in self._port_in_use:
self._port_in_use.remove(port)
self._port_pool.append(port)
2025-09-11 22:46:55 +08:00
2025-09-17 22:23:57 +08:00
# ------------------------------------------------------------------
# 线程池里真正干活的地方(原 connectDevice 逻辑搬过来)
# ------------------------------------------------------------------
def _connect_device_task(self, udid: str):
2025-09-11 22:46:55 +08:00
if not self.is_device_trusted(udid):
LogManager.warning("设备未信任,跳过 WDA 启动", udid)
return
try:
2025-09-11 22:46:55 +08:00
d = wda.USBClient(udid, 8100)
2025-08-15 20:04:59 +08:00
except Exception as e:
2025-09-11 22:46:55 +08:00
LogManager.error(f"启动 WDA 失败: {e}", udid)
2025-09-08 13:48:21 +08:00
return
2025-09-17 22:23:57 +08:00
2025-08-15 20:04:59 +08:00
width, height, scale = 0, 0, 1.0
try:
2025-08-13 20:20:13 +08:00
size = d.window_size()
2025-08-15 20:04:59 +08:00
width, height = size.width, size.height
2025-08-13 20:20:13 +08:00
scale = d.scale
2025-08-15 20:04:59 +08:00
except Exception as e:
2025-09-11 22:46:55 +08:00
LogManager.warning(f"读取屏幕信息失败:{e}", udid)
2025-09-17 22:23:57 +08:00
2025-09-11 22:46:55 +08:00
port = self._alloc_port()
model = DeviceModel(udid, port, width, height, scale, type=1)
2025-09-17 22:23:57 +08:00
# 先做完所有 IO再抢锁写内存
2025-08-15 20:04:59 +08:00
try:
d.app_start(WdaAppBundleId)
d.home()
except Exception as e:
2025-09-11 22:46:55 +08:00
LogManager.warning(f"启动/切回桌面失败:{e}", udid)
2025-09-17 22:23:57 +08:00
time.sleep(2) # 原逻辑保留
2025-09-11 22:46:55 +08:00
target = self.relayDeviceScreenPort(udid, port)
2025-09-17 22:23:57 +08:00
# 毫秒级临界区
with self._lock:
if udid in self._model_index: # 并发防重
return
self._add_model(model)
if target:
self.pidList.append({"target": target, "id": udid})
# ------------------------------------------------------------------
# 原函数保留(改名即可)
# ------------------------------------------------------------------
def connectDevice(self, udid: str):
"""对外保留接口,实际走线程池"""
self._connect_pool.submit(self._connect_device_task, udid)
2025-08-28 19:51:57 +08:00
2025-09-17 15:43:23 +08:00
# -------------------- 工具方法(未改动) --------------------
2025-09-11 22:46:55 +08:00
def is_device_trusted(self, udid: str) -> bool:
try:
d = BaseDevice(udid)
d.get_value("DeviceName")
return True
except Exception:
return False
def relayDeviceScreenPort(self, udid: str, port: int) -> Optional[subprocess.Popen]:
if not self._spawn_iproxy:
2025-09-16 15:31:55 +08:00
LogManager.error("iproxy 启动器未就绪", udid)
2025-09-11 22:46:55 +08:00
return None
2025-09-18 21:31:23 +08:00
for attempt in range(5):
if not self._is_port_open(port):
break
LogManager.warning(f"端口 {port} 仍被占用,第 {attempt+1} 次重试释放", udid)
2025-09-16 15:31:55 +08:00
pid = self._get_pid_by_port(port)
if pid and pid != os.getpid():
self._kill_pid_gracefully(pid)
2025-09-18 21:31:23 +08:00
time.sleep(0.2)
2025-09-11 22:46:55 +08:00
try:
p = self._spawn_iproxy(udid, port, 9100)
2025-09-16 15:31:55 +08:00
self._port_in_use.add(port)
2025-09-11 22:46:55 +08:00
LogManager.info(f"启动 iproxy 成功,本地 {port} -> 设备 9100", udid)
return p
except Exception as e:
LogManager.error(f"启动 iproxy 失败:{e}", udid)
return None
2025-09-16 15:31:55 +08:00
def _is_port_open(self, port: int) -> bool:
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
return s.connect_ex(("127.0.0.1", port)) == 0
def _get_pid_by_port(self, port: int) -> Optional[int]:
try:
if os.name == "nt":
2025-09-17 22:23:57 +08:00
out = sp_check_output(["netstat", "-ano", "-p", "tcp"], text=True)
2025-09-16 15:31:55 +08:00
for line in out.splitlines():
if f"127.0.0.1:{port}" in line and "LISTENING" in line:
return int(line.strip().split()[-1])
else:
2025-09-17 22:23:57 +08:00
out = sp_check_output(["lsof", "-t", f"-iTCP:{port}", "-sTCP:LISTEN"], text=True)
2025-09-16 15:31:55 +08:00
return int(out.strip().split()[0])
except Exception:
return None
def _kill_pid_gracefully(self, pid: int):
try:
os.kill(pid, signal.SIGTERM)
time.sleep(1)
os.kill(pid, signal.SIGKILL)
except Exception:
pass
2025-09-11 22:46:55 +08:00
def _terminate_proc(self, p: Optional[subprocess.Popen]):
if not p or p.poll() is not None:
2025-08-28 19:51:57 +08:00
return
try:
2025-09-08 13:48:21 +08:00
p.terminate()
2025-08-28 19:51:57 +08:00
p.wait(timeout=3)
except Exception:
try:
if os.name == "posix":
2025-09-11 22:46:55 +08:00
os.killpg(os.getpgid(p.pid), signal.SIGKILL)
2025-08-28 19:51:57 +08:00
else:
2025-09-08 13:48:21 +08:00
p.kill()
p.wait(timeout=2)
2025-08-28 19:51:57 +08:00
except Exception:
pass
2025-08-15 20:04:59 +08:00
def _base_dir(self) -> Path:
if getattr(sys, "frozen", False):
return Path(sys.executable).resolve().parent
2025-09-08 13:48:21 +08:00
return Path(__file__).resolve().parents[1]
2025-08-15 20:04:59 +08:00
def _iproxy_path(self) -> Path:
2025-08-18 15:51:09 +08:00
exe = "iproxy.exe" if os.name == "nt" else "iproxy"
2025-08-15 22:24:41 +08:00
base = self._base_dir()
2025-09-11 22:46:55 +08:00
candidates = [base / "resources" / "iproxy" / exe]
2025-08-15 22:24:41 +08:00
for p in candidates:
if p.exists():
return p
2025-09-18 21:31:23 +08:00
raise FileNotFoundError(f"iproxy not found, tried: {[str(c) for c in candidates]}")