Files
iOSAI/Module/DeviceInfo.py

295 lines
11 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
import wda
2025-08-15 20:04:59 +08:00
import threading
import subprocess
from pathlib import Path
from typing import List, Dict, Optional
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-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):
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
self._miss_count: Dict[str, int] = {} # udid -> 连续未扫描到次数
self._port_pool: List[int] = [] # 端口回收池
self._port_in_use: set[int] = set() # 正在使用的端口
2025-09-08 13:48:21 +08:00
2025-09-11 22:46:55 +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
self._popen_kwargs = dict(
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=str(self.iproxy_dir),
shell=False,
text=True,
2025-08-28 15:46:17 +08:00
creationflags=self._creationflags,
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)
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
def startDeviceListener(self):
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-11 22:46:55 +08:00
2025-09-12 13:44:26 +08:00
# 1. 失踪登记 & 累加
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-12 13:44:26 +08:00
self._miss_count[udid] = self._miss_count.get(udid, 0) + 1
2025-09-11 22:46:55 +08:00
if self._miss_count[udid] >= 3:
self._remove_model(udid)
self._miss_count.pop(udid, None)
else:
2025-09-12 13:44:26 +08:00
self._miss_count.pop(udid, None) # 设备又出现,清零
2025-09-11 22:46:55 +08:00
2025-09-12 13:44:26 +08:00
# 2. 全新插入(只处理未在线且信任且未满)
2025-09-11 22:46:55 +08:00
for d in lists:
if d.conn_type != ConnectionType.USB:
2025-09-08 13:48:21 +08:00
continue
2025-09-11 22:46:55 +08:00
udid = d.udid
with self._lock:
if udid in self._model_index:
2025-09-12 13:44:26 +08:00
continue # 已存在,跳过
2025-09-11 22:46:55 +08:00
if not self.is_device_trusted(udid):
continue
if len(self.deviceModelList) >= self.maxDeviceCount:
continue
2025-09-12 13:44:26 +08:00
port = self._alloc_port()
2025-09-11 22:46:55 +08:00
try:
self.connectDevice(udid) # 内部会 _add_model
except Exception as e:
LogManager.error(f"连接设备失败 {udid}: {e}", udid)
2025-09-04 20:47:14 +08:00
2025-08-01 13:43:51 +08:00
time.sleep(1)
2025-09-11 22:46:55 +08:00
# region ===================== 增删改查唯一入口(线程安全) =====================
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:
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:
LogManager.warning(f"发送上线事件失败:{e}", model.deviceId)
LogManager.info(f"设备上线,当前在线数:{len(self.deviceModelList)}", model.deviceId)
2025-09-11 22:46:55 +08:00
def _remove_model(self, udid: str):
2025-09-12 13:44:26 +08:00
print("进入删除方法")
2025-09-11 22:46:55 +08:00
model = self._model_index.pop(udid, None)
2025-09-12 13:44:26 +08:00
print(model)
2025-09-11 22:46:55 +08:00
if not model:
2025-09-12 13:44:26 +08:00
print("没有找到model")
2025-09-11 22:46:55 +08:00
return
model.type = 2
2025-09-12 13:44:26 +08:00
# 内存结构删除
try:
idx = self.deviceModelList.index(model)
self.deviceModelList.pop(idx)
except ValueError:
print("有错误了")
pass
# 端口回收(关键)
self._free_port(model.screenPort)
# 清理 iproxy
survivors = [item for item in self.pidList if item.get("id") != udid]
for item in self.pidList:
if item.get("id") == udid:
self._terminate_proc(item.get("target"))
self.pidList = survivors
# Socket 发送(无锁)
2025-09-11 22:46:55 +08:00
retry = 3
while retry:
try:
self.manager.send(model.toDict())
2025-09-12 13:44:26 +08:00
print("删除了")
2025-09-11 22:46:55 +08:00
break
except Exception as e:
2025-09-12 13:44:26 +08:00
print("有问题了", e)
2025-09-11 22:46:55 +08:00
retry -= 1
LogManager.error(f"发送下线事件失败,剩余重试 {retry}{e}", udid)
time.sleep(0.2)
else:
LogManager.error("发送下线事件彻底失败,主动崩溃防止状态不一致", udid)
os._exit(1)
LogManager.info(f"设备下线,当前在线数:{len(self.deviceModelList)}", udid)
# region ===================== 端口分配与回收 =====================
def _alloc_port(self) -> int:
2025-09-12 21:36:29 +08:00
print(self.screenProxy)
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
# endregion
# region ===================== 单台设备连接 =====================
def connectDevice(self, udid: str):
if not self.is_device_trusted(udid):
LogManager.warning("设备未信任,跳过 WDA 启动", udid)
return
2025-09-08 13:48:21 +08:00
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-08-13 20:20:13 +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-08-15 20:04:59 +08:00
2025-09-11 22:46:55 +08:00
port = self._alloc_port()
model = DeviceModel(udid, port, width, height, scale, type=1)
self._add_model(model)
2025-08-13 20:20:13 +08:00
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-08-06 22:11:33 +08:00
time.sleep(2)
2025-08-15 20:04:59 +08:00
2025-09-11 22:46:55 +08:00
# 先清旧进程再启动新进程
2025-09-12 13:44:26 +08:00
self.pidList = [item for item in self.pidList if item.get("id") != udid]
2025-09-11 22:46:55 +08:00
target = self.relayDeviceScreenPort(udid, port)
if target:
2025-09-12 13:44:26 +08:00
self.pidList.append({"target": target, "id": udid})
2025-08-28 19:51:57 +08:00
2025-09-11 22:46:55 +08:00
# endregion
# region ===================== 工具方法 =====================
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:
LogManager.error("iproxy 启动器未就绪,无法建立端口映射", udid)
return None
try:
p = self._spawn_iproxy(udid, port, 9100)
LogManager.info(f"启动 iproxy 成功,本地 {port} -> 设备 9100", udid)
return p
except Exception as e:
LogManager.error(f"启动 iproxy 失败:{e}", udid)
return None
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-08-18 22:20:23 +08:00
raise FileNotFoundError(f"iproxy not found, tried: {[str(c) for c in candidates]}")
2025-09-11 22:46:55 +08:00
# endregion