diff --git a/gui/gui_core.py b/gui/gui_core.py index 08c4302..1ba800c 100644 --- a/gui/gui_core.py +++ b/gui/gui_core.py @@ -1,3 +1,13 @@ +"""gui_core - gui_app / web_gui / webgui_launcher 共享后端。 + +历史巨型文件(1594 行)已部分拆出到 ``gui.gui_core_pkg``: +- adb / wifi_adb / config / run_params + +本文件保留 Runner 巨型类(1164 行,13 个实例方法 + self 状态), +其他符号通过 from-import 暴露,外部 from gui.gui_core import X 兼容。 +""" +from __future__ import annotations + import json import os import queue @@ -12,420 +22,23 @@ from typing import Optional from douyin.core import path_config -CONFIG_PATH = path_config.get_config_path() - - -def find_adb_executable() -> str: - """返回可用的 adb 可执行文件路径(优先 PATH,其次默认安装目录)。""" - adb = shutil.which("adb") - if adb: - return adb - - # 默认安装目录(我们之前下载的 platform-tools) - localapp = os.environ.get("LOCALAPPDATA") or "" - candidates = [] - if localapp: - candidates.append(os.path.join(localapp, "platform-tools", "adb.exe")) - - # 兼容某些人手动放到用户目录的情况 - userprofile = os.environ.get("USERPROFILE") or "" - if userprofile: - candidates.append( - os.path.join(userprofile, "AppData", "Local", "platform-tools", "adb.exe") - ) - - for p in candidates: - if os.path.exists(p): - return p - return "" - - -def list_adb_devices(adb_exe: str) -> list[str]: - try: - if not adb_exe: - return [] - proc = subprocess.run( - [adb_exe, "devices", "-l"], - capture_output=True, - text=True, - encoding="utf-8", - errors="replace", - check=False, - ) - except FileNotFoundError: - return [] - devices: list[str] = [] - for line in (proc.stdout or "").splitlines()[1:]: - parts = line.split() - if len(parts) >= 2 and parts[1] == "device": - devices.append(parts[0]) - return devices - - -def resolve_adb_device(adb_exe: str, requested_device_id: str = "") -> str: - device_id = str(requested_device_id or "").strip() - devices = list_adb_devices(adb_exe) - if device_id: - if device_id in devices: - return device_id - raise RuntimeError(f"指定的 device_id '{device_id}' 当前不可用") - if len(devices) == 1: - return devices[0] - if len(devices) > 1: - raise RuntimeError(f"检测到多台 adb 设备,请先明确选择 device_id: {', '.join(devices)}") - raise RuntimeError("未检测到可用的 adb 设备") - - -def is_device_wifi_connected(adb_exe: str, device_id: str) -> bool: - """检查设备是否已经在WiFi ADB模式下连接 - - Args: - adb_exe: ADB可执行文件路径 - device_id: 设备ID(IP:端口格式) - - Returns: - bool: 是否为WiFi连接 - """ - if not device_id or not adb_exe: - return False - - # 检查device_id是否为IP:端口格式 - if ":" in device_id and device_id.split(":")[0].count(".") == 3: - return True - - return False - - -def get_connected_wifi_devices(adb_exe: str) -> list[str]: - """获取已连接的WiFi ADB设备列表 - - Args: - adb_exe: ADB可执行文件路径 - - Returns: - list: WiFi连接的设备ID列表 - """ - devices = list_adb_devices(adb_exe) - wifi_devices = [] - - for device in devices: - if is_device_wifi_connected(adb_exe, device): - wifi_devices.append(device) - - return wifi_devices - - -def enable_wifi_adb(adb_exe: str, device_id: str) -> tuple[bool, str]: - """启用设备的WiFi ADB调试模式 - - Args: - adb_exe: ADB可执行文件路径 - device_id: 设备ID - - Returns: - tuple: (成功否, 消息) - """ - try: - if not adb_exe or not device_id: - return False, "ADB路径或设备ID为空" - - # 启用TCP/IP模式 - proc = subprocess.run( - [adb_exe, "-s", device_id, "tcpip", "5555"], - capture_output=True, - text=True, - encoding="utf-8", - errors="replace", - check=False, - timeout=10, - ) - - if proc.returncode == 0: - return True, "WiFi ADB已启用,请等待设备重启完成" - else: - error_msg = (proc.stdout or "") + "\n" + (proc.stderr or "") - return False, f"启用WiFi ADB失败: {error_msg}" - - except subprocess.TimeoutExpired: - return False, "启用WiFi ADB超时" - except Exception as e: - return False, f"启用WiFi ADB异常: {str(e)}" - - -def connect_wifi_adb( - adb_exe: str, ip_address: str, port: str = "5555" -) -> tuple[bool, str]: - """连接到WiFi ADB设备 - - Args: - adb_exe: ADB可执行文件路径 - ip_address: 设备IP地址 - port: 端口号,默认5555 - - Returns: - tuple: (成功否, 消息) - """ - try: - if not adb_exe or not ip_address: - return False, "ADB路径或IP地址为空" - - # 支持 ip:port 或单纯 ip 的两种情况 - if ":" in ip_address: - target = ip_address - else: - target = f"{ip_address}:{port}" - - # 连接到设备 - proc = subprocess.run( - [adb_exe, "connect", target], - capture_output=True, - text=True, - encoding="utf-8", - errors="replace", - check=False, - timeout=10, - ) - - output = (proc.stdout or "") + "\n" + (proc.stderr or "") - low = output.lower() - - # adb connect 在成功/已连接时常包含 'connected' 或 'already connected' 文本 - if proc.returncode == 0 and ("connected" in low or "already connected" in low): - return True, f"成功连接到 {target}" - else: - return False, f"连接失败: {output}" - - except subprocess.TimeoutExpired: - return False, "连接WiFi ADB超时" - except Exception as e: - return False, f"连接WiFi ADB异常: {str(e)}" - - -def disconnect_wifi_adb( - adb_exe: str, ip_address: str, port: str = "5555" -) -> tuple[bool, str]: - """断开WiFi ADB连接 - - Args: - adb_exe: ADB可执行文件路径 - ip_address: 设备IP地址 - port: 端口号,默认5555 - - Returns: - tuple: (成功否, 消息) - """ - try: - if not adb_exe or not ip_address: - return False, "ADB路径或IP地址为空" - - target = f"{ip_address}:{port}" - - # 断开连接 - proc = subprocess.run( - [adb_exe, "disconnect", target], - capture_output=True, - text=True, - encoding="utf-8", - errors="replace", - check=False, - timeout=10, - ) - - output = (proc.stdout or "") + "\n" + (proc.stderr or "") - - if proc.returncode == 0: - return True, f"成功断开连接 {target}" - else: - return False, f"断开连接失败: {output}" - - except subprocess.TimeoutExpired: - return False, "断开WiFi ADB超时" - except Exception as e: - return False, f"断开WiFi ADB异常: {str(e)}" - - -def get_device_ip(adb_exe: str, device_id: str) -> tuple[bool, str]: - """获取设备的IP地址 - - Args: - adb_exe: ADB可执行文件路径 - device_id: 设备ID - - Returns: - tuple: (成功否, IP地址或错误消息) - """ - try: - if not adb_exe or not device_id: - return False, "ADB路径或设备ID为空" - - # 获取网络接口信息 - proc = subprocess.run( - [adb_exe, "-s", device_id, "shell", "ip", "route"], - capture_output=True, - text=True, - encoding="utf-8", - errors="replace", - check=False, - timeout=10, - ) - - if proc.returncode == 0: - # 解析输出获取IP地址 - lines = proc.stdout.strip().split("\n") - for line in lines: - if "src" in line: - parts = line.split() - for part in parts: - if part.count(".") == 3: # IP地址格式 - return True, part - return False, "无法从设备获取IP地址" - else: - error_msg = (proc.stdout or "") + "\n" + (proc.stderr or "") - return False, f"获取IP地址失败: {error_msg}" - - except subprocess.TimeoutExpired: - return False, "获取设备IP超时" - except Exception as e: - return False, f"获取设备IP异常: {str(e)}" - - -def auto_connect_wifi_adb( - adb_exe: str, device_id: str, max_attempts: int = 3 -) -> tuple[bool, str]: - """自动启用WiFi ADB并连接设备 - - Args: - adb_exe: ADB可执行文件路径 - device_id: 设备ID - max_attempts: 最大尝试次数 - - Returns: - tuple: (成功否, 消息) - """ - try: - if not adb_exe or not device_id: - return False, "ADB路径或设备ID为空" - - # 先检查当前 adb 设备列表,看 device_id 是否已经以 WiFi 形式存在(ip:port) - try: - current = list_adb_devices(adb_exe) - except Exception: - current = [] - - # 如果 device_id 本身就是 ip:port 格式,且已经在 adb devices 中,则视为已连接 - if is_device_wifi_connected(adb_exe, device_id) and device_id in current: - return True, f"设备已通过 WiFi 连接: {device_id}" - - # 如果 device_id 是 ip:port 格式但不在 adb devices 中,尝试直接连接这个 target - if is_device_wifi_connected(adb_exe, device_id) and device_id not in current: - conn_ok, conn_msg = connect_wifi_adb(adb_exe, device_id) - if conn_ok: - return True, f"直接连接成功: {device_id}" - else: - return False, f"直接连接失败: {conn_msg}" - - # 如果 device_id 是 USB 序列(非 ip:port),执行启用 tcpip 流程作为后备 - enable_success, enable_msg = enable_wifi_adb(adb_exe, device_id) - if not enable_success: - return False, f"启用WiFi ADB失败: {enable_msg}" - - # 等待设备重启开始 - time.sleep(3) - - # 尝试多次获取IP并连接(优先提取纯 IPv4 地址或 ip:port) - for attempt in range(max_attempts): - wait_time = 5 + attempt * 2 - time.sleep(wait_time) - - ip_success, ip_msg = get_device_ip(adb_exe, device_id) - if not ip_success: - if attempt == max_attempts - 1: - return False, f"获取IP地址失败: {ip_msg}" - continue - - ip_address = ip_msg - # 提取 ip 或 ip:port - m = re.search(r"(\d+\.\d+\.\d+\.\d+)(?::(\d+))?", ip_address) - if m: - host = m.group(1) - port_found = m.group(2) or "5555" - target = f"{host}:{port_found}" - else: - target = ip_address - - connect_success, connect_msg = connect_wifi_adb(adb_exe, target) - if connect_success: - return True, f"自动连接成功! target: {target}" - - if attempt == max_attempts - 1: - return False, f"连接失败: {connect_msg}" - - return False, "自动连接超时,请稍后重试" - - except Exception as e: - return False, f"自动连接异常: {str(e)}" - - -def read_config() -> dict: - if not os.path.exists(CONFIG_PATH): - return {} - with open(CONFIG_PATH, "r", encoding="utf-8") as f: - return json.load(f) - - -def write_config(cfg: dict) -> None: - # GUI 表单通常只生成“已知字段”的子集;直接覆盖写会丢失其它键(例如 ROI rect/poly 等扩展配置)。 - # 这里做一次 merge:保留原配置中的未知键,再用新 cfg 覆盖同名键。 - merged = {} - try: - merged = read_config() - if not isinstance(merged, dict): - merged = {} - except Exception: - merged = {} - try: - if isinstance(cfg, dict): - merged.update(cfg) - except Exception: - pass - with open(CONFIG_PATH, "w", encoding="utf-8") as f: - json.dump(merged, f, ensure_ascii=False, indent=4) - f.write("\n") - - -@dataclass -class RunParams: - device_id: str - y_pianyi: int - needswitch: bool - wait_minutes: int - skip_if_countdown_gt_seconds: int - reset_after_swipes_enabled: bool - reset_after_swipes: int - enable_back_on_misses: bool - min_prize_value_yuan: float - min_participants: int - max_participants: int - auto_join_fansclub: bool - fansclub_fail_action: str - # Web端新增参数 - high_value_room_revisit_enabled: bool - high_value_room_revisit_only_current_run: bool - high_value_room_revisit_min_interval_seconds: int - high_value_room_revisit_max_per_run: int - high_value_room_revisit_min_prize_value: float - high_value_room_revisit_max_age_days: int - high_value_fudai_poll_before_seconds: float - reservation_back_verify_enabled: bool - reservation_back_swipe_delay: float - fudai_find_max_attempts: int - enable_ocr_mode1: bool - fudai_template_match_enabled: bool - fudai_template_match_threshold: float - # 只养号模式(仅执行推荐页养号) - yanghao_only: bool - # 只养号时的养号时长(秒),会传给 --yanghao-seconds - yanghao_seconds: int +# 从子包 re-export 顶层符号(保持兼容) +from gui.gui_core_pkg import ( + CONFIG_PATH, + RunParams, + auto_connect_wifi_adb, + connect_wifi_adb, + disconnect_wifi_adb, + enable_wifi_adb, + find_adb_executable, + get_connected_wifi_devices, + get_device_ip, + is_device_wifi_connected, + list_adb_devices, + read_config, + resolve_adb_device, + write_config, +) class Runner: diff --git a/gui/gui_core_pkg/__init__.py b/gui/gui_core_pkg/__init__.py new file mode 100644 index 0000000..96d0125 --- /dev/null +++ b/gui/gui_core_pkg/__init__.py @@ -0,0 +1,49 @@ +"""gui_core_pkg - gui_core 的 ADB / WiFi-ADB / 配置 / 参数子包。 + +原 gui/gui_core.py 拆出 12 个独立顶层函数 + RunParams dataclass +到本子包,Runner 巨型类(1164 行 / 13 实例方法 / 用 self 状态) +保留在原文件,仅做 shim re-export。 + +- adb find_adb_executable / list_adb_devices / resolve_adb_device +- wifi_adb 7 个 WiFi-ADB 函数 +- config CONFIG_PATH / read_config / write_config +- run_params RunParams dataclass +""" + +from .adb import ( + find_adb_executable, + list_adb_devices, + resolve_adb_device, +) +from .wifi_adb import ( + auto_connect_wifi_adb, + connect_wifi_adb, + disconnect_wifi_adb, + enable_wifi_adb, + get_connected_wifi_devices, + get_device_ip, + is_device_wifi_connected, +) +from .config import ( + CONFIG_PATH, + read_config, + write_config, +) +from .run_params import RunParams + +__all__ = [ + "find_adb_executable", + "list_adb_devices", + "resolve_adb_device", + "is_device_wifi_connected", + "get_connected_wifi_devices", + "enable_wifi_adb", + "connect_wifi_adb", + "disconnect_wifi_adb", + "get_device_ip", + "auto_connect_wifi_adb", + "CONFIG_PATH", + "read_config", + "write_config", + "RunParams", +] diff --git a/gui/gui_core_pkg/adb.py b/gui/gui_core_pkg/adb.py new file mode 100644 index 0000000..99ba565 --- /dev/null +++ b/gui/gui_core_pkg/adb.py @@ -0,0 +1,79 @@ +"""gui_core_pkg.adb - ADB 可执行文件查找与设备列表。 + +- find_adb_executable 在 PATH / 项目目录内查找 adb 可执行 +- list_adb_devices 列出当前已连接设备 +- resolve_adb_device 按 device_id 解析具体设备(含模糊匹配) +""" +from __future__ import annotations + +import os +import shutil +import subprocess +from typing import Optional + + +def find_adb_executable() -> str: + """返回可用的 adb 可执行文件路径(优先 PATH,其次默认安装目录)。""" + adb = shutil.which("adb") + if adb: + return adb + + # 默认安装目录(我们之前下载的 platform-tools) + localapp = os.environ.get("LOCALAPPDATA") or "" + candidates = [] + if localapp: + candidates.append(os.path.join(localapp, "platform-tools", "adb.exe")) + + # 兼容某些人手动放到用户目录的情况 + userprofile = os.environ.get("USERPROFILE") or "" + if userprofile: + candidates.append( + os.path.join(userprofile, "AppData", "Local", "platform-tools", "adb.exe") + ) + + for p in candidates: + if os.path.exists(p): + return p + return "" + + + + +def list_adb_devices(adb_exe: str) -> list[str]: + try: + if not adb_exe: + return [] + proc = subprocess.run( + [adb_exe, "devices", "-l"], + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + check=False, + ) + except FileNotFoundError: + return [] + devices: list[str] = [] + for line in (proc.stdout or "").splitlines()[1:]: + parts = line.split() + if len(parts) >= 2 and parts[1] == "device": + devices.append(parts[0]) + return devices + + + + +def resolve_adb_device(adb_exe: str, requested_device_id: str = "") -> str: + device_id = str(requested_device_id or "").strip() + devices = list_adb_devices(adb_exe) + if device_id: + if device_id in devices: + return device_id + raise RuntimeError(f"指定的 device_id '{device_id}' 当前不可用") + if len(devices) == 1: + return devices[0] + if len(devices) > 1: + raise RuntimeError(f"检测到多台 adb 设备,请先明确选择 device_id: {', '.join(devices)}") + raise RuntimeError("未检测到可用的 adb 设备") + + diff --git a/gui/gui_core_pkg/config.py b/gui/gui_core_pkg/config.py new file mode 100644 index 0000000..78314dd --- /dev/null +++ b/gui/gui_core_pkg/config.py @@ -0,0 +1,46 @@ +"""gui_core_pkg.config - 配置文件读写。 + +- CONFIG_PATH config.json 绝对路径 +- read_config 读取并返回 dict +- write_config 深度合并写回(保留未传字段) +""" +from __future__ import annotations + +import json +import os +import shutil + +from douyin.core import path_config + +CONFIG_PATH = path_config.get_config_path() + + +def read_config() -> dict: + if not os.path.exists(CONFIG_PATH): + return {} + with open(CONFIG_PATH, "r", encoding="utf-8") as f: + return json.load(f) + + + + +def write_config(cfg: dict) -> None: + # GUI 表单通常只生成“已知字段”的子集;直接覆盖写会丢失其它键(例如 ROI rect/poly 等扩展配置)。 + # 这里做一次 merge:保留原配置中的未知键,再用新 cfg 覆盖同名键。 + merged = {} + try: + merged = read_config() + if not isinstance(merged, dict): + merged = {} + except Exception: + merged = {} + try: + if isinstance(cfg, dict): + merged.update(cfg) + except Exception: + pass + with open(CONFIG_PATH, "w", encoding="utf-8") as f: + json.dump(merged, f, ensure_ascii=False, indent=4) + f.write("\n") + + diff --git a/gui/gui_core_pkg/run_params.py b/gui/gui_core_pkg/run_params.py new file mode 100644 index 0000000..e24df2e --- /dev/null +++ b/gui/gui_core_pkg/run_params.py @@ -0,0 +1,46 @@ +"""gui_core_pkg.run_params - RunParams dataclass。 + +封装 GUI 启动参数(device_id / y_pianyi / needswitch / wait_minutes 等), +传给 Runner.start(params) 用。 +""" +from __future__ import annotations + +from dataclasses import dataclass +from typing import Optional + + +@dataclass +class RunParams: + device_id: str + y_pianyi: int + needswitch: bool + wait_minutes: int + skip_if_countdown_gt_seconds: int + reset_after_swipes_enabled: bool + reset_after_swipes: int + enable_back_on_misses: bool + min_prize_value_yuan: float + min_participants: int + max_participants: int + auto_join_fansclub: bool + fansclub_fail_action: str + # Web端新增参数 + high_value_room_revisit_enabled: bool + high_value_room_revisit_only_current_run: bool + high_value_room_revisit_min_interval_seconds: int + high_value_room_revisit_max_per_run: int + high_value_room_revisit_min_prize_value: float + high_value_room_revisit_max_age_days: int + high_value_fudai_poll_before_seconds: float + reservation_back_verify_enabled: bool + reservation_back_swipe_delay: float + fudai_find_max_attempts: int + enable_ocr_mode1: bool + fudai_template_match_enabled: bool + fudai_template_match_threshold: float + # 只养号模式(仅执行推荐页养号) + yanghao_only: bool + # 只养号时的养号时长(秒),会传给 --yanghao-seconds + yanghao_seconds: int + + diff --git a/gui/gui_core_pkg/wifi_adb.py b/gui/gui_core_pkg/wifi_adb.py new file mode 100644 index 0000000..7445f06 --- /dev/null +++ b/gui/gui_core_pkg/wifi_adb.py @@ -0,0 +1,323 @@ +"""gui_core_pkg.wifi_adb - WiFi-ADB 连接管理。 + +- is_device_wifi_connected 判断设备是否通过 WiFi 连接 +- get_connected_wifi_devices 列出 WiFi 连接的设备 +- enable_wifi_adb 在设备上启用 WiFi-ADB +- connect_wifi_adb 通过 WiFi 连接到设备 +- disconnect_wifi_adb 断开 WiFi 连接 +- get_device_ip 获取设备 IP +- auto_connect_wifi_adb 自动连接:开启 + 获取 IP + 连接 +""" +from __future__ import annotations + +import os +import re +import subprocess +import time +from typing import Optional + +from .adb import find_adb_executable, list_adb_devices + + +def is_device_wifi_connected(adb_exe: str, device_id: str) -> bool: + """检查设备是否已经在WiFi ADB模式下连接 + + Args: + adb_exe: ADB可执行文件路径 + device_id: 设备ID(IP:端口格式) + + Returns: + bool: 是否为WiFi连接 + """ + if not device_id or not adb_exe: + return False + + # 检查device_id是否为IP:端口格式 + if ":" in device_id and device_id.split(":")[0].count(".") == 3: + return True + + return False + + + + +def get_connected_wifi_devices(adb_exe: str) -> list[str]: + """获取已连接的WiFi ADB设备列表 + + Args: + adb_exe: ADB可执行文件路径 + + Returns: + list: WiFi连接的设备ID列表 + """ + devices = list_adb_devices(adb_exe) + wifi_devices = [] + + for device in devices: + if is_device_wifi_connected(adb_exe, device): + wifi_devices.append(device) + + return wifi_devices + + + + +def enable_wifi_adb(adb_exe: str, device_id: str) -> tuple[bool, str]: + """启用设备的WiFi ADB调试模式 + + Args: + adb_exe: ADB可执行文件路径 + device_id: 设备ID + + Returns: + tuple: (成功否, 消息) + """ + try: + if not adb_exe or not device_id: + return False, "ADB路径或设备ID为空" + + # 启用TCP/IP模式 + proc = subprocess.run( + [adb_exe, "-s", device_id, "tcpip", "5555"], + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + check=False, + timeout=10, + ) + + if proc.returncode == 0: + return True, "WiFi ADB已启用,请等待设备重启完成" + else: + error_msg = (proc.stdout or "") + "\n" + (proc.stderr or "") + return False, f"启用WiFi ADB失败: {error_msg}" + + except subprocess.TimeoutExpired: + return False, "启用WiFi ADB超时" + except Exception as e: + return False, f"启用WiFi ADB异常: {str(e)}" + + + + +def connect_wifi_adb( + adb_exe: str, ip_address: str, port: str = "5555" +) -> tuple[bool, str]: + """连接到WiFi ADB设备 + + Args: + adb_exe: ADB可执行文件路径 + ip_address: 设备IP地址 + port: 端口号,默认5555 + + Returns: + tuple: (成功否, 消息) + """ + try: + if not adb_exe or not ip_address: + return False, "ADB路径或IP地址为空" + + # 支持 ip:port 或单纯 ip 的两种情况 + if ":" in ip_address: + target = ip_address + else: + target = f"{ip_address}:{port}" + + # 连接到设备 + proc = subprocess.run( + [adb_exe, "connect", target], + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + check=False, + timeout=10, + ) + + output = (proc.stdout or "") + "\n" + (proc.stderr or "") + low = output.lower() + + # adb connect 在成功/已连接时常包含 'connected' 或 'already connected' 文本 + if proc.returncode == 0 and ("connected" in low or "already connected" in low): + return True, f"成功连接到 {target}" + else: + return False, f"连接失败: {output}" + + except subprocess.TimeoutExpired: + return False, "连接WiFi ADB超时" + except Exception as e: + return False, f"连接WiFi ADB异常: {str(e)}" + + + + +def disconnect_wifi_adb( + adb_exe: str, ip_address: str, port: str = "5555" +) -> tuple[bool, str]: + """断开WiFi ADB连接 + + Args: + adb_exe: ADB可执行文件路径 + ip_address: 设备IP地址 + port: 端口号,默认5555 + + Returns: + tuple: (成功否, 消息) + """ + try: + if not adb_exe or not ip_address: + return False, "ADB路径或IP地址为空" + + target = f"{ip_address}:{port}" + + # 断开连接 + proc = subprocess.run( + [adb_exe, "disconnect", target], + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + check=False, + timeout=10, + ) + + output = (proc.stdout or "") + "\n" + (proc.stderr or "") + + if proc.returncode == 0: + return True, f"成功断开连接 {target}" + else: + return False, f"断开连接失败: {output}" + + except subprocess.TimeoutExpired: + return False, "断开WiFi ADB超时" + except Exception as e: + return False, f"断开WiFi ADB异常: {str(e)}" + + + + +def get_device_ip(adb_exe: str, device_id: str) -> tuple[bool, str]: + """获取设备的IP地址 + + Args: + adb_exe: ADB可执行文件路径 + device_id: 设备ID + + Returns: + tuple: (成功否, IP地址或错误消息) + """ + try: + if not adb_exe or not device_id: + return False, "ADB路径或设备ID为空" + + # 获取网络接口信息 + proc = subprocess.run( + [adb_exe, "-s", device_id, "shell", "ip", "route"], + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + check=False, + timeout=10, + ) + + if proc.returncode == 0: + # 解析输出获取IP地址 + lines = proc.stdout.strip().split("\n") + for line in lines: + if "src" in line: + parts = line.split() + for part in parts: + if part.count(".") == 3: # IP地址格式 + return True, part + return False, "无法从设备获取IP地址" + else: + error_msg = (proc.stdout or "") + "\n" + (proc.stderr or "") + return False, f"获取IP地址失败: {error_msg}" + + except subprocess.TimeoutExpired: + return False, "获取设备IP超时" + except Exception as e: + return False, f"获取设备IP异常: {str(e)}" + + + + +def auto_connect_wifi_adb( + adb_exe: str, device_id: str, max_attempts: int = 3 +) -> tuple[bool, str]: + """自动启用WiFi ADB并连接设备 + + Args: + adb_exe: ADB可执行文件路径 + device_id: 设备ID + max_attempts: 最大尝试次数 + + Returns: + tuple: (成功否, 消息) + """ + try: + if not adb_exe or not device_id: + return False, "ADB路径或设备ID为空" + + # 先检查当前 adb 设备列表,看 device_id 是否已经以 WiFi 形式存在(ip:port) + try: + current = list_adb_devices(adb_exe) + except Exception: + current = [] + + # 如果 device_id 本身就是 ip:port 格式,且已经在 adb devices 中,则视为已连接 + if is_device_wifi_connected(adb_exe, device_id) and device_id in current: + return True, f"设备已通过 WiFi 连接: {device_id}" + + # 如果 device_id 是 ip:port 格式但不在 adb devices 中,尝试直接连接这个 target + if is_device_wifi_connected(adb_exe, device_id) and device_id not in current: + conn_ok, conn_msg = connect_wifi_adb(adb_exe, device_id) + if conn_ok: + return True, f"直接连接成功: {device_id}" + else: + return False, f"直接连接失败: {conn_msg}" + + # 如果 device_id 是 USB 序列(非 ip:port),执行启用 tcpip 流程作为后备 + enable_success, enable_msg = enable_wifi_adb(adb_exe, device_id) + if not enable_success: + return False, f"启用WiFi ADB失败: {enable_msg}" + + # 等待设备重启开始 + time.sleep(3) + + # 尝试多次获取IP并连接(优先提取纯 IPv4 地址或 ip:port) + for attempt in range(max_attempts): + wait_time = 5 + attempt * 2 + time.sleep(wait_time) + + ip_success, ip_msg = get_device_ip(adb_exe, device_id) + if not ip_success: + if attempt == max_attempts - 1: + return False, f"获取IP地址失败: {ip_msg}" + continue + + ip_address = ip_msg + # 提取 ip 或 ip:port + m = re.search(r"(\d+\.\d+\.\d+\.\d+)(?::(\d+))?", ip_address) + if m: + host = m.group(1) + port_found = m.group(2) or "5555" + target = f"{host}:{port_found}" + else: + target = ip_address + + connect_success, connect_msg = connect_wifi_adb(adb_exe, target) + if connect_success: + return True, f"自动连接成功! target: {target}" + + if attempt == max_attempts - 1: + return False, f"连接失败: {connect_msg}" + + return False, "自动连接超时,请稍后重试" + + except Exception as e: + return False, f"自动连接异常: {str(e)}" + +