#!/usr/bin/env python3 """ 工具脚本:自动将通过 USB 连接的设备切换到 WiFi ADB 并建立连接。 用法示例: python tools/auto_connect_wifi_adb.py --all python tools/auto_connect_wifi_adb.py --device MB75DEFQZHZTGMLJ 该脚本依赖仓库中的 `gui.gui_core` 中的 ADB 辅助函数(如 `auto_connect_wifi_adb`)。 """ import argparse import sys import os from typing import List # 当从 tools 目录直接运行脚本时,Python 的 sys.path[0] 会是 tools/,需要把项目根目录加入路径 this_dir = os.path.dirname(os.path.abspath(__file__)) project_root = os.path.abspath(os.path.join(this_dir, "..")) if project_root not in sys.path: sys.path.insert(0, project_root) try: from gui.gui_core import ( find_adb_executable, list_adb_devices, get_connected_wifi_devices, auto_connect_wifi_adb, ) except Exception as e: print(f"无法导入 gui.gui_core: {e}", file=sys.stderr) sys.exit(2) def choose_targets(adb_exe: str, device_arg: str | None, all_flag: bool) -> List[str]: devices = list_adb_devices(adb_exe) wifi = get_connected_wifi_devices(adb_exe) usb_devices = [d for d in devices if d not in wifi] if device_arg: if device_arg not in devices: raise ValueError(f"指定的设备 {device_arg} 未在 adb 设备列表中: {devices}") return [device_arg] if all_flag: # 对所有 USB 设备尝试;如果没有 USB 设备但存在已连接的 WiFi 设备,则也尝试这些 WiFi 设备 if usb_devices: return usb_devices return wifi # 默认行为:如果只有一个 USB 设备则选择它;否则提示用户 if len(usb_devices) == 1: return [usb_devices[0]] if len(usb_devices) == 0: # 没有 USB 设备:如果有已连接的 WiFi 设备则回退到它们(便于仅通过 WiFi 的场景),否则返回空 if wifi: return wifi return [] raise ValueError( "检测到多个 USB 设备,请使用 --device 指定或者加上 --all 来对所有设备同时尝试" ) def main(): parser = argparse.ArgumentParser(description="自动启用并连接 WiFi ADB 的工具脚本") group = parser.add_mutually_exclusive_group() group.add_argument("-d", "--device", help="指定要自动连接的设备ID(adb serial)") group.add_argument( "-a", "--all", action="store_true", help="对所有检测到的 USB 设备尝试自动连接" ) parser.add_argument( "--max-attempts", type=int, default=3, help="每台设备尝试获取 IP 和连接的最大次数(默认3)", ) args = parser.parse_args() adb_exe = find_adb_executable() if not adb_exe: print( "未找到 adb 可执行文件,请安装 platform-tools 或确保 adb 在 PATH 中", file=sys.stderr, ) sys.exit(2) try: targets = choose_targets(adb_exe, args.device, args.all) except ValueError as e: print(str(e), file=sys.stderr) sys.exit(1) if not targets: print("未检测到可用于自动连接的 USB 设备(或指定的设备不在列表中)") sys.exit(0) print(f"即将对 {len(targets)} 台设备尝试自动连接: {targets}") overall_ok = True for dev in targets: print("\n-------------------------------") print(f"开始自动连接设备: {dev}") ok, msg = auto_connect_wifi_adb(adb_exe, dev, max_attempts=args.max_attempts) print(msg) if not ok: overall_ok = False print(f"设备 {dev} 自动连接失败", file=sys.stderr) else: print(f"设备 {dev} 已成功通过 WiFi 连接") if overall_ok: print("\n所有设备自动连接尝试已完成,全部成功(或至少有一台成功)") sys.exit(0) else: print( "\n部分设备自动连接失败,请查看上面的错误信息或使用 --device 指定单台设备重试" ) sys.exit(1) if __name__ == "__main__": main()