diff --git a/.idea/workspace.xml b/.idea/workspace.xml index 8ce4d22..4dd45fc 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -5,14 +5,9 @@ - - - - - - - + + - - - @@ -128,29 +119,6 @@ + - - - - + - - + + + \ No newline at end of file diff --git a/Module/DeviceInfo.py b/Module/DeviceInfo.py index 73aad13..95dce34 100644 --- a/Module/DeviceInfo.py +++ b/Module/DeviceInfo.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- import os import signal import sys @@ -17,17 +18,23 @@ from Utils.LogManager import LogManager class Deviceinfo(object): + """设备生命周期管理:以 deviceModelList 为唯一真理源""" + def __init__(self): self.deviceIndex = 0 self.screenProxy = 9110 - self.pidList: List[Dict] = [] - self.deviceArray: List = [] + self.pidList: List[Dict] = [] # 仅记录 iproxy 进程 self.manager = FlaskSubprocessManager.get_instance() - self.deviceModelList: List[DeviceModel] = [] + self.deviceModelList: List[DeviceModel] = [] # 根基,不动 self.maxDeviceCount = 6 - self._lock = threading.Lock() - self._pending_udids = set() + self._lock = threading.Lock() + 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() # 正在使用的端口 + + # region iproxy 初始化 try: self.iproxy_path = self._iproxy_path() self.iproxy_dir = self.iproxy_path.parent @@ -62,102 +69,169 @@ class Deviceinfo(object): except Exception: pass - try: - 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() - except Exception: - pass - + 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() return p self._spawn_iproxy = _spawn_iproxy 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}") + # endregion - # ---------------------------- - # 监听设备连接(死循环,内部捕获异常) - # ---------------------------- def startDeviceListener(self): + """死循环监听设备插拔;以 deviceModelList 为准""" while True: try: lists = Usbmux().device_list() except Exception as e: - LogManager.warning( - f"usbmuxd 连接失败: {e}。请确认已安装 iTunes/Apple Mobile Device Support,并在手机上“信任此电脑”") + LogManager.warning(f"usbmuxd 连接失败: {e},2 秒后重试") time.sleep(2) continue now_udids = {d.udid for d in lists if d.conn_type == ConnectionType.USB} - # 1. 处理“已插入但未信任”的设备,一旦信任就补连接 - for udid in list(self._pending_udids): - if udid not in now_udids: - # 设备已拔出,从 pending 移除 - self._pending_udids.discard(udid) + + # 0. 首次失踪登记:已在线设备若突然扫不到,计数器归零 + with self._lock: + for udid in list(self._model_index.keys()): + if udid not in now_udids and udid not in self._miss_count: + self._miss_count[udid] = 0 + LogManager.info(f"[DEBUG] 首次失踪登记:{udid}", udid) + + # 1. 处理已在线设备的失联计数 + with self._lock: + for udid in list(self._miss_count.keys()): + if udid not in now_udids: + self._miss_count[udid] += 1 + LogManager.info(f"[DEBUG] 累加 {udid} -> {self._miss_count[udid]}", udid) + if self._miss_count[udid] >= 3: + print("设备下线了") + LogManager.info(f"[DEBUG] 触发下线 {udid}", udid) + self._remove_model(udid) + self._miss_count.pop(udid, None) + else: + LogManager.info(f"[DEBUG] 设备仍在,清零 {udid}", udid) + self._miss_count.pop(udid, None) + + # 2. 处理新插入 + for d in lists: + if d.conn_type != ConnectionType.USB: continue - if self.is_device_trusted(udid): - # 已信任,补连接 - self._pending_udids.discard(udid) - self.screenProxy += 1 - try: - self.connectDevice(udid) - # 补加入 deviceArray(用 usbmux 对象) - for d in lists: - if d.udid == udid: - self.deviceArray.append(d) - break - except Exception as e: - LogManager.error(f"补连接设备失败 {udid}: {e}", udid) + udid = d.udid + with self._lock: + if udid in self._model_index: + continue # 已存在 + if not self.is_device_trusted(udid): + LogManager.warning("设备未信任,跳过", udid) + continue + if len(self.deviceModelList) >= self.maxDeviceCount: + continue + try: + self.connectDevice(udid) # 内部会 _add_model + except Exception as e: + LogManager.error(f"连接设备失败 {udid}: {e}", udid) - # 2. 处理全新插入的设备 - for device in lists: - if device.conn_type == ConnectionType.USB and device not in self.deviceArray and len( - self.deviceArray) < self.maxDeviceCount: - if not self.is_device_trusted(device.udid): - # 未信任,记入 pending,下次循环再判 - self._pending_udids.add(device.udid) - LogManager.warning("设备未信任,已记录,等待信任后自动连接", device.udid) - continue - # 已信任,直接走完整流程 - self.screenProxy += 1 - try: - self.connectDevice(device.udid) - self.deviceArray.append(device) - except Exception as e: - LogManager.error(f"连接设备失败 {device.udid}: {e}", device.udid) - - # 3. 处理拔出 - self._removeDisconnected(lists) time.sleep(1) - # ---------------------------- - # 判断设备是否已信任 - # ---------------------------- - def is_device_trusted(self, udid: str) -> bool: - try: - d = BaseDevice(udid) - d.get_value("DeviceName") # 任意读取一个值,失败即未信任 - return True - except Exception: - return False + # endregion - # ---------------------------- - # 连接单台设备:先判断是否信任,再启动 WDA - # ---------------------------- - def connectDevice(self, identifier: str): - if not self.is_device_trusted(identifier): - LogManager.warning("设备未信任,跳过 WDA 启动,等待信任后再试", identifier) + # region ===================== 增删改查唯一入口(线程安全) ===================== + def _has_model(self, udid: str) -> bool: + with self._lock: + return udid in self._model_index + + def _add_model(self, model: DeviceModel): + with self._lock: + if model.deviceId in self._model_index: + return # 防重复 + 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) + + def _remove_model(self, udid: str): + model = self._model_index.pop(udid, None) + if not model: + return + model.type = 2 + print(model.toDict()) + # ① 关键:重试 3 次,必须送达,否则崩溃 + retry = 3 + while retry: + try: + self.manager.send(model.toDict()) + break + except Exception as e: + retry -= 1 + LogManager.error(f"发送下线事件失败,剩余重试 {retry}:{e}", udid) + time.sleep(0.2) + else: + LogManager.error("发送下线事件彻底失败,主动崩溃防止状态不一致", udid) + os._exit(1) + + # ② 安全删除 + try: + idx = self.deviceModelList.index(model) + self.deviceModelList.pop(idx) + print(len(self.deviceModelList)) + except Exception as e: + print("22222222") + print(f"[FlaskSubprocessManager] 发送失败,异常类型:{type(e).__name__},内容:{e}") + + + # ③ 回收端口 + self._free_port(model.screenPort) + + print("继续执行了") + + # ④ 清理 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 + print("设备下线。删除设备成功") + LogManager.info(f"设备下线,当前在线数:{len(self.deviceModelList)}", udid) + LogManager.info(f"[Deviceinfo] 下线包已送进队列 -> type=2", udid) + # endregion + + # region ===================== 端口分配与回收 ===================== + def _alloc_port(self) -> int: + with self._lock: + if self._port_pool: + port = self._port_pool.pop() + else: + self.screenProxy += 1 + port = self.screenProxy + self._port_in_use.add(port) + return port + + def _free_port(self, port: int): + with self._lock: + if port in self._port_in_use: + self._port_in_use.remove(port) + self._port_pool.append(port) + # endregion + + # region ===================== 单台设备连接 ===================== + def connectDevice(self, udid: str): + if not self.is_device_trusted(udid): + LogManager.warning("设备未信任,跳过 WDA 启动", udid) + return + if self._has_model(udid): + LogManager.warning("设备已存在,跳过重复连接", udid) return try: - d = wda.USBClient(identifier, 8100) - LogManager.info("启动 WDA 成功", identifier) + d = wda.USBClient(udid, 8100) except Exception as e: - LogManager.error(f"启动 WDA 失败,请检查手机是否已信任、WDA 是否正常。错误: {e}", identifier) + LogManager.error(f"启动 WDA 失败: {e}", udid) return width, height, scale = 0, 0, 1.0 @@ -166,35 +240,53 @@ class Deviceinfo(object): width, height = size.width, size.height scale = d.scale except Exception as e: - LogManager.warning(f"读取屏幕信息失败:{e}", identifier) + LogManager.warning(f"读取屏幕信息失败:{e}", udid) - model = DeviceModel(identifier, self.screenProxy, width, height, scale, type=1) - self.deviceModelList.append(model) - try: - self.manager.send(model.toDict()) - except Exception as e: - LogManager.warning(f"向前端发送设备模型失败:{e}", identifier) + port = self._alloc_port() + model = DeviceModel(udid, port, width, height, scale, type=1) + self._add_model(model) try: d.app_start(WdaAppBundleId) d.home() except Exception as e: - LogManager.warning(f"启动/切回桌面失败:{e}", identifier) + LogManager.warning(f"启动/切回桌面失败:{e}", udid) time.sleep(2) - target = self.relayDeviceScreenPort(identifier) - if target is not None: + # 先清旧进程再启动新进程 + with self._lock: + self.pidList = [item for item in self.pidList if item.get("id") != udid] + target = self.relayDeviceScreenPort(udid, port) + if target: with self._lock: - self.pidList.append({"target": target, "id": identifier}) + self.pidList.append({"target": target, "id": udid}) - # ---------------------------- - # 以下方法未改动,省略以节省篇幅 - # ---------------------------- - def _terminate_proc(self, p: subprocess.Popen): - if not p: - return - if p.poll() is not None: + # 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: return try: p.terminate() @@ -202,64 +294,13 @@ class Deviceinfo(object): except Exception: try: if os.name == "posix": - try: - os.killpg(os.getpgid(p.pid), signal.SIGKILL) - except Exception: - p.kill() + os.killpg(os.getpgid(p.pid), signal.SIGKILL) else: p.kill() p.wait(timeout=2) except Exception: pass - def _removeDisconnected(self, current_list): - try: - # 当前在线的 deviceId 集合(即 UDID) - now_device_ids = {d.udid for d in current_list if hasattr(d, 'udid')} - - # 上一次记录的 deviceId 集合 - prev_device_ids = {model.deviceId for model in self.deviceModelList} - except Exception as e: - LogManager.error(f"收集 deviceId 失败:{e}", "") - return - - removed_device_ids = prev_device_ids - now_device_ids - if not removed_device_ids: - return - - with self._lock: - # 清理 deviceModelList - for model in list(self.deviceModelList): - if model.deviceId in removed_device_ids: - model.type = 2 - try: - self.manager.send(model.toDict()) - except Exception as e: - LogManager.warning(f"发送下线事件失败:{e}", model.deviceId) - self.deviceModelList.remove(model) - - # 清理 pidList - survivors = [] - for item in self.pidList: - if item.get("id") in removed_device_ids: - p = item.get("target") - try: - self._terminate_proc(p) - except Exception as e: - LogManager.warning(f"关闭 iproxy 异常:{e}", item.get("id")) - else: - survivors.append(item) - self.pidList = survivors - - # 清理 deviceArray(也统一用 udid) - self.deviceArray = [d for d in self.deviceArray if getattr(d, 'udid', None) not in removed_device_ids] - - # >>> 新增:记录剩余设备数量 <<< - LogManager.info(f"设备拔出完成,当前剩余设备数:{len(self.deviceModelList)}", "") - - for device_id in removed_device_ids: - LogManager.info("设备已拔出,清理完成(下线通知 + 端口映射关闭 + 状态移除)", device_id) - def _base_dir(self) -> Path: if getattr(sys, "frozen", False): return Path(sys.executable).resolve().parent @@ -268,22 +309,9 @@ class Deviceinfo(object): def _iproxy_path(self) -> Path: exe = "iproxy.exe" if os.name == "nt" else "iproxy" base = self._base_dir() - candidates = [ - base / "resources" / "iproxy" / exe, - ] + candidates = [base / "resources" / "iproxy" / exe] for p in candidates: if p.exists(): return p raise FileNotFoundError(f"iproxy not found, tried: {[str(c) for c in candidates]}") - - def relayDeviceScreenPort(self, udid: str) -> Optional[subprocess.Popen]: - if not self._spawn_iproxy: - LogManager.error("iproxy 启动器未就绪,无法建立端口映射(初始化时未找到 iproxy)。", udid) - return None - try: - p = self._spawn_iproxy(udid, self.screenProxy, 9100) - LogManager.info(f"启动 iproxy 成功,本地 {self.screenProxy} -> 设备 9100", udid) - return p - except Exception as e: - LogManager.error(f"启动 iproxy 失败:{e}", udid) - return None \ No newline at end of file + # endregion \ No newline at end of file diff --git a/Module/FlaskService.py b/Module/FlaskService.py index 725d3ac..04a9882 100644 --- a/Module/FlaskService.py +++ b/Module/FlaskService.py @@ -87,13 +87,12 @@ def start_socket_listener(): listener_thread = threading.Thread(target=start_socket_listener, daemon=True) listener_thread.start() - # 获取设备列表 @app.route('/deviceList', methods=['GET']) def deviceList(): try: - with listLock: # 1. 加锁 - # 先一次性把队列全部消费完 + with listLock: + # 1. 一次性消费完队列 while not dataQueue.empty(): obj = dataQueue.get() if obj["type"] == 1: @@ -106,7 +105,11 @@ def deviceList(): d.get("screenPort") == obj.get("screenPort"): listData.pop(i) break # 同一端口同一设备只删一次 - return ResultData(data=listData.copy()).toJson() # 2. 返回副本 + + # 2. 兜底:只保留 type == 1 的在线设备 + listData[:] = [d for d in listData if d.get('type') == 1] + + return ResultData(data=listData.copy()).toJson() except Exception as e: LogManager.error("获取设备列表失败:", e) return ResultData(data=[]).toJson()