diff --git a/gui/gui_app.py b/gui/gui_app.py index d4943ee..3e9f01a 100644 --- a/gui/gui_app.py +++ b/gui/gui_app.py @@ -33,6 +33,11 @@ from gui.gui_core import ( read_config, write_config, ) +from gui.gui_core_pkg import ( + DiscoveredDevice, + discover_adb_devices, + get_local_subnet, +) from douyin.core.path_config import get_logs_dir from gui.components.mapping_table import create_mapping_tab @@ -333,6 +338,194 @@ def main(): refresh_devices_btn.pack(side=LEFT, padx=(0, 20)) # WiFi ADB 功能 + def open_scan_dialog(parent, adb_exe_local, ip_var, on_line_local, refresh_cb): + """打开"扫描局域网"对话框:自动推子网或手动输入 → 后台扫描 → 列表展示。""" + scan_dlg = tk.Toplevel(parent) + scan_dlg.title("扫描局域网 ADB 设备") + scan_dlg.geometry("640x440") + scan_dlg.minsize(520, 360) + scan_dlg.transient(parent) + + # 顶部:子网输入 + 自动推按钮 + 开始扫描 + top_frame = ttk.LabelFrame(scan_dlg, text="扫描范围", padding=10) + top_frame.pack(fill=X, padx=10, pady=10) + + ttk.Label(top_frame, text="子网/范围:").grid(row=0, column=0, sticky=W) + subnet_var = tk.StringVar(value=get_local_subnet() or "") + subnet_entry = ttk.Entry(top_frame, textvariable=subnet_var, width=32) + subnet_entry.grid(row=0, column=1, padx=(6, 6), sticky="we") + top_frame.grid_columnconfigure(1, weight=1) + + def auto_fill(): + sub = get_local_subnet() + if sub: + subnet_var.set(sub) + on_line_local(f"[扫描] 自动推导子网: {sub}") + else: + on_line_local("[扫描] 无法推导本机子网,请手动输入") + + ttk.Button(top_frame, text="自动推", command=auto_fill).grid( + row=0, column=2, padx=(0, 6) + ) + scan_btn = ttk.Button(top_frame, text="开始扫描") + scan_btn.grid(row=0, column=3) + + ttk.Label( + top_frame, + text="支持: 192.168.5.0/24 | 192.168.5.1-100 | 192.168.5.5", + font=("Arial", 8), + foreground="gray", + ).grid(row=1, column=0, columnspan=4, sticky=W, pady=(4, 0)) + + # 中间:进度条 + 状态 + progress_frame = ttk.Frame(scan_dlg) + progress_frame.pack(fill=X, padx=10) + progress_var = tk.DoubleVar(value=0.0) + progress_bar = ttk.Progressbar( + progress_frame, mode="determinate", variable=progress_var, maximum=100 + ) + progress_bar.pack(fill=X, pady=(0, 4)) + status_var = tk.StringVar(value="待扫描") + ttk.Label(progress_frame, textvariable=status_var, font=("Arial", 9)).pack( + anchor=W + ) + + # 列表:IP / 状态 / 型号 / 备注 + list_frame = ttk.LabelFrame(scan_dlg, text="发现的设备", padding=10) + list_frame.pack(fill=BOTH, expand=True, padx=10, pady=(8, 0)) + + cols = ("target", "state", "model", "message") + tree = ttk.Treeview( + list_frame, columns=cols, show="headings", height=8 + ) + tree.heading("target", text="IP:Port") + tree.heading("state", text="状态") + tree.heading("model", text="设备型号") + tree.heading("message", text="adb connect 输出") + tree.column("target", width=140, anchor=W) + tree.column("state", width=80, anchor=W) + tree.column("model", width=100, anchor=W) + tree.column("message", width=240, anchor=W) + tree.pack(side=LEFT, fill=BOTH, expand=True) + sb = ttk.Scrollbar(list_frame, orient="vertical", command=tree.yview) + sb.pack(side=LEFT, fill="y") + tree.configure(yscrollcommand=sb.set) + + # 底部按钮 + bottom_frame = ttk.Frame(scan_dlg) + bottom_frame.pack(fill=X, padx=10, pady=10) + + def use_selected(): + sel = tree.selection() + if not sel: + on_line_local("[扫描] 请先在列表中选中一个设备") + return + item = tree.item(sel[0]) + target = item["values"][0] + state = item["values"][1] + if state == "unauthorized": + on_line_local( + f"[扫描] {target} 未授权,请先在手机上确认 ADB 调试授权再选" + ) + return + # 把 IP 部分填回主对话框 + ip_part = str(target).split(":")[0] + ip_var.set(ip_part) + on_line_local(f"[扫描] 已选中 {target},可在主对话框点'连接'或它已在 adb devices 中") + try: + refresh_cb() + except Exception: + pass + scan_dlg.destroy() + + use_btn = ttk.Button( + bottom_frame, text="使用选中设备", command=use_selected, state="disabled" + ) + use_btn.pack(side=LEFT) + ttk.Button(bottom_frame, text="关闭", command=scan_dlg.destroy).pack( + side=RIGHT + ) + + def on_select(_event=None): + sel = tree.selection() + use_btn.config(state="normal" if sel else "disabled") + + tree.bind("<>", on_select) + + # 扫描线程 + scanning = {"flag": False} + + def do_scan(): + if scanning["flag"]: + on_line_local("[扫描] 上次扫描尚未完成,请稍候") + return + spec = subnet_var.get().strip() + if not spec: + on_line_local("[扫描] 请输入子网/IP 范围") + return + scanning["flag"] = True + scan_btn.config(state="disabled") + tree.delete(*tree.get_children()) + progress_var.set(0) + + def on_progress(done, total): + try: + pct = (done * 100.0) / max(total, 1) + progress_var.set(pct) + status_var.set(f"端口扫描 {done}/{total}") + scan_dlg.update_idletasks() + except Exception: + pass + + def on_phase(text): + try: + status_var.set(text) + scan_dlg.update_idletasks() + except Exception: + pass + + def worker(): + try: + devs = discover_adb_devices( + adb_exe_local, + subnet_spec=spec, + on_progress=on_progress, + on_phase=on_phase, + ) + except Exception as e: + on_line_local(f"[扫描] 异常: {e}") + devs = [] + + # 回主线程更新 UI + def render(): + for d in devs: + tree.insert( + "", + "end", + values=(d.target, d.adb_state, d.model, d.message[:120]), + ) + if devs: + status_var.set(f"扫描完成,发现 {len(devs)} 台设备") + on_line_local( + f"[扫描] 完成:{len(devs)} 台候选 — " + + ", ".join(f"{d.target}({d.adb_state})" for d in devs[:5]) + ) + else: + status_var.set("扫描完成,未发现设备") + on_line_local("[扫描] 未发现开放 5555 的设备") + progress_var.set(100) + scan_btn.config(state="normal") + scanning["flag"] = False + + try: + scan_dlg.after(0, render) + except Exception: + pass + + threading.Thread(target=worker, daemon=True).start() + + scan_btn.config(command=do_scan) + def open_wifi_adb_dialog(): """打开WiFi ADB设置对话框""" dialog = tk.Toplevel(root) @@ -632,6 +825,13 @@ def main(): ttk.Button(wifi_buttons_frame, text="断开连接", command=disconnect_wifi).pack( side=LEFT ) + ttk.Button( + wifi_buttons_frame, + text="扫描局域网", + command=lambda: open_scan_dialog( + dialog, adb_exe, ip_var, on_line, refresh_device_lists + ), + ).pack(side=LEFT, padx=(10, 0)) # 说明文本 info_text = """重要说明: diff --git a/gui/gui_core_pkg/__init__.py b/gui/gui_core_pkg/__init__.py index 96d0125..4bea8ca 100644 --- a/gui/gui_core_pkg/__init__.py +++ b/gui/gui_core_pkg/__init__.py @@ -6,6 +6,7 @@ - adb find_adb_executable / list_adb_devices / resolve_adb_device - wifi_adb 7 个 WiFi-ADB 函数 +- wifi_adb_scan 局域网扫描发现 ADB 设备 - config CONFIG_PATH / read_config / write_config - run_params RunParams dataclass """ @@ -24,6 +25,12 @@ from .wifi_adb import ( get_device_ip, is_device_wifi_connected, ) +from .wifi_adb_scan import ( + DiscoveredDevice, + discover_adb_devices, + get_local_subnet, + parse_subnet_spec, +) from .config import ( CONFIG_PATH, read_config, @@ -42,6 +49,10 @@ __all__ = [ "disconnect_wifi_adb", "get_device_ip", "auto_connect_wifi_adb", + "DiscoveredDevice", + "discover_adb_devices", + "get_local_subnet", + "parse_subnet_spec", "CONFIG_PATH", "read_config", "write_config", diff --git a/gui/gui_core_pkg/wifi_adb_scan.py b/gui/gui_core_pkg/wifi_adb_scan.py new file mode 100644 index 0000000..09bafdd --- /dev/null +++ b/gui/gui_core_pkg/wifi_adb_scan.py @@ -0,0 +1,356 @@ +"""gui_core_pkg.wifi_adb_scan - 局域网扫描发现 ADB-over-WiFi 设备 + +- get_local_subnet 从本机 WLAN 取出 /24 子网 +- parse_subnet_spec 解析 192.168.5.0/24 / 192.168.5.1-100 / 192.168.5.5 等格式 +- probe_adb_port 并发 TCP 探测一个 IP 的 5555 端口是否打开 +- discover_adb_devices 主入口:扫描子网 + adb connect 验证 + 返回真正能连的设备 +""" +from __future__ import annotations + +import ipaddress +import re +import socket +import subprocess +from concurrent.futures import ThreadPoolExecutor, as_completed +from dataclasses import dataclass, field +from typing import Callable, Iterable, Optional + + +DEFAULT_ADB_PORT = 5555 + + +@dataclass +class DiscoveredDevice: + """扫描发现的一台候选设备。""" + + ip: str + port: int = DEFAULT_ADB_PORT + # adb connect 后的状态:connected / unauthorized / failed + adb_state: str = "unknown" + # adb connect 的原始消息 + message: str = "" + # 设备型号(adb -s shell getprop ro.product.model 取到才有,可能为空) + model: str = "" + + @property + def target(self) -> str: + return f"{self.ip}:{self.port}" + + +# ============================================================ +# 子网推导 / 解析 +# ============================================================ + +def get_local_subnet() -> Optional[str]: + """取本机 WLAN 接口的 /24 子网,例如返回 "192.168.5.0/24"。 + + 优先级: + 1) socket.getsockname()(连一个外部地址,得到出口接口的 IP) + 2) 本机所有 IPv4 中第一个非环回 / 非 169.254 的私有地址 + 取不到返回 None。 + """ + ip = _get_outbound_ip() + if not ip: + ip = _get_first_private_ipv4() + if not ip: + return None + try: + # 返回 192.168.5.19 → 192.168.5.0/24 + net = ipaddress.IPv4Network(f"{ip}/24", strict=False) + return str(net) + except Exception: + return None + + +def _get_outbound_ip() -> Optional[str]: + """通过连一个外部 UDP 地址(不真的发包)让 OS 选一张接口,从而得到出口 IP。""" + s = None + try: + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + # 8.8.8.8:80 不需要可达,只是让 OS 决定路由 + s.settimeout(0.5) + s.connect(("8.8.8.8", 80)) + ip = s.getsockname()[0] + if ip and not ip.startswith("169.254.") and ip != "0.0.0.0": + return ip + except Exception: + pass + finally: + if s is not None: + try: + s.close() + except Exception: + pass + return None + + +def _get_first_private_ipv4() -> Optional[str]: + """枚举本机 IPv4,返回第一个非环回 / 非 link-local 的私有地址。""" + try: + host = socket.gethostname() + infos = socket.getaddrinfo(host, None, family=socket.AF_INET) + except Exception: + return None + for info in infos: + ip = info[4][0] + if not ip: + continue + if ip.startswith("127.") or ip.startswith("169.254."): + continue + try: + addr = ipaddress.IPv4Address(ip) + if addr.is_private: + return str(addr) + except Exception: + continue + return None + + +def parse_subnet_spec(spec: str) -> list[str]: + """把用户输入解析成 IP 列表。支持的格式: + + - "192.168.5.0/24" → 网段下所有可用 IP(去掉网络/广播地址) + - "192.168.5.10-50" → 192.168.5.10 ~ 192.168.5.50 + - "192.168.5.5" → 单个 IP + - "192.168.5.5,192.168.5.10/24" → 逗号分隔的多段(合并去重) + + 无法解析返回空列表。 + """ + if not spec or not isinstance(spec, str): + return [] + + out: list[str] = [] + seen: set[str] = set() + + for part in spec.split(","): + part = part.strip() + if not part: + continue + # CIDR + if "/" in part: + try: + net = ipaddress.IPv4Network(part, strict=False) + for host in net.hosts(): + s = str(host) + if s not in seen: + seen.add(s) + out.append(s) + continue + except Exception: + continue + # 192.168.5.10-50 (尾段范围) + m = re.match( + r"^(\d+)\.(\d+)\.(\d+)\.(\d+)-(\d+)$", part + ) + if m: + a, b, c, lo, hi = m.groups() + try: + lo_i, hi_i = int(lo), int(hi) + if 0 <= lo_i <= hi_i <= 255: + for last in range(lo_i, hi_i + 1): + s = f"{a}.{b}.{c}.{last}" + if s not in seen: + seen.add(s) + out.append(s) + continue + except Exception: + pass + # 单个 IP + try: + addr = ipaddress.IPv4Address(part) + s = str(addr) + if s not in seen: + seen.add(s) + out.append(s) + except Exception: + continue + + return out + + +# ============================================================ +# TCP 端口探测 +# ============================================================ + +def probe_adb_port(ip: str, port: int = DEFAULT_ADB_PORT, timeout: float = 0.3) -> bool: + """TCP connect 探测端口是否开放(0.3s 超时,足够局域网)。""" + s = None + try: + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.settimeout(timeout) + s.connect((ip, port)) + return True + except Exception: + return False + finally: + if s is not None: + try: + s.close() + except Exception: + pass + + +def scan_open_ports( + ips: Iterable[str], + port: int = DEFAULT_ADB_PORT, + timeout: float = 0.3, + max_workers: int = 64, + on_progress: Optional[Callable[[int, int], None]] = None, +) -> list[str]: + """并发扫描一批 IP 的 port,返回开放的 IP 列表。 + + on_progress(done, total) 每完成一个回调一次(用于 GUI 进度条)。 + """ + ip_list = list(ips) + total = len(ip_list) + if total == 0: + return [] + + open_ips: list[str] = [] + done = 0 + with ThreadPoolExecutor(max_workers=max_workers) as ex: + future_to_ip = { + ex.submit(probe_adb_port, ip, port, timeout): ip for ip in ip_list + } + for fut in as_completed(future_to_ip): + done += 1 + if on_progress: + try: + on_progress(done, total) + except Exception: + pass + try: + if fut.result(): + open_ips.append(future_to_ip[fut]) + except Exception: + continue + # 按 IP 字面排序,扫描结果稳定 + try: + open_ips.sort(key=lambda s: tuple(int(p) for p in s.split("."))) + except Exception: + open_ips.sort() + return open_ips + + +# ============================================================ +# adb connect 验证 + 状态查询 +# ============================================================ + +def _run_adb(adb_exe: str, args: list[str], timeout: float = 5.0) -> tuple[int, str]: + """运行 adb 命令,返回 (returncode, stdout+stderr)。""" + try: + proc = subprocess.run( + [adb_exe, *args], + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + check=False, + timeout=timeout, + ) + except subprocess.TimeoutExpired: + return -1, "timeout" + except Exception as e: + return -1, str(e) + out = ((proc.stdout or "") + "\n" + (proc.stderr or "")).strip() + return proc.returncode, out + + +def verify_adb_target(adb_exe: str, target: str) -> tuple[str, str]: + """对一个 ip:port 调 `adb connect `,解析输出。 + + 返回 (state, message): + - state="connected" adb connect 成功(含 "already connected") + - state="unauthorized" adb 协议握手成功但设备未授权 + - state="failed" 其他失败 + """ + rc, out = _run_adb(adb_exe, ["connect", target], timeout=5.0) + low = out.lower() + if "authenticate" in low or "unauthorized" in low: + return "unauthorized", out + if "connected" in low or "already connected" in low: + return "connected", out + return "failed", out or "未知错误" + + +def query_device_model(adb_exe: str, target: str) -> str: + """对一个 connected 的 target 取 ro.product.model(失败返回空字符串)。""" + rc, out = _run_adb( + adb_exe, ["-s", target, "shell", "getprop", "ro.product.model"], timeout=3.0 + ) + if rc == 0: + return out.strip() + return "" + + +# ============================================================ +# 主入口 +# ============================================================ + +def discover_adb_devices( + adb_exe: str, + subnet_spec: Optional[str] = None, + port: int = DEFAULT_ADB_PORT, + probe_timeout: float = 0.3, + on_progress: Optional[Callable[[int, int], None]] = None, + on_phase: Optional[Callable[[str], None]] = None, +) -> list[DiscoveredDevice]: + """扫描局域网,返回所有真的能 adb connect 的设备。 + + Args: + adb_exe: adb 可执行文件路径 + subnet_spec: None 表示自动用本机子网;否则按 parse_subnet_spec 解析 + port: 默认 5555 + probe_timeout: 单个 IP 的 TCP 探测超时(秒) + on_progress: on_progress(done, total) 端口扫描进度回调 + on_phase: on_phase("scanning subnet 192.168.5.0/24") 阶段提示回调 + + Returns: + list[DiscoveredDevice],按 IP 排序。state 为 connected / unauthorized / failed。 + UI 通常只展示 state != "failed" 的项。 + """ + # 1) 推导 IP 列表 + if subnet_spec is None or not subnet_spec.strip(): + subnet = get_local_subnet() + if not subnet: + return [] + subnet_spec = subnet + + ips = parse_subnet_spec(subnet_spec) + if not ips: + return [] + + if on_phase: + try: + on_phase(f"扫描 {subnet_spec}({len(ips)} 个 IP)") + except Exception: + pass + + # 2) 端口扫描,过滤掉关 5555 的 + open_ips = scan_open_ports( + ips, + port=port, + timeout=probe_timeout, + on_progress=on_progress, + ) + + if not open_ips: + return [] + + if on_phase: + try: + on_phase(f"发现 {len(open_ips)} 个开放 :{port} 的 IP,验证 ADB") + except Exception: + pass + + # 3) 对每个开放 IP 调 adb connect 验证 + results: list[DiscoveredDevice] = [] + for ip in open_ips: + target = f"{ip}:{port}" + state, message = verify_adb_target(adb_exe, target) + dev = DiscoveredDevice(ip=ip, port=port, adb_state=state, message=message) + if state == "connected": + dev.model = query_device_model(adb_exe, target) + results.append(dev) + + return results diff --git a/tests/test_wifi_adb_scan.py b/tests/test_wifi_adb_scan.py new file mode 100644 index 0000000..94adb74 --- /dev/null +++ b/tests/test_wifi_adb_scan.py @@ -0,0 +1,227 @@ +"""gui_core_pkg.wifi_adb_scan 单元测试。 + +覆盖: +- parse_subnet_spec:CIDR / 范围 / 单 IP / 逗号 / 空 / 非法 +- get_local_subnet:mock socket 拿到出口 IP 的情况 +- probe_adb_port:开 / 关 / 超时 +- verify_adb_target:connected / unauthorized / failed +- discover_adb_devices:subnet 推导 → 端口扫描 → adb connect 验证 +""" +from __future__ import annotations + +import socket +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +import pytest + +from gui.gui_core_pkg import wifi_adb_scan as scan + + +def _proc(stdout: str = "", stderr: str = "", returncode: int = 0): + return SimpleNamespace(stdout=stdout, stderr=stderr, returncode=returncode) + + +# ============================================================ +# parse_subnet_spec +# ============================================================ + +class TestParseSubnetSpec: + def test_cidr_24(self): + ips = scan.parse_subnet_spec("192.168.5.0/24") + # /24 hosts 是 .1 ~ .254(去掉网络/广播) + assert len(ips) == 254 + assert ips[0] == "192.168.5.1" + assert ips[-1] == "192.168.5.254" + + def test_range(self): + ips = scan.parse_subnet_spec("192.168.5.10-13") + assert ips == ["192.168.5.10", "192.168.5.11", "192.168.5.12", "192.168.5.13"] + + def test_single_ip(self): + assert scan.parse_subnet_spec("10.0.0.42") == ["10.0.0.42"] + + def test_comma_dedupes(self): + ips = scan.parse_subnet_spec("10.0.0.5,10.0.0.5,10.0.0.6") + assert ips == ["10.0.0.5", "10.0.0.6"] + + def test_empty(self): + assert scan.parse_subnet_spec("") == [] + assert scan.parse_subnet_spec(None) == [] # type: ignore[arg-type] + + def test_invalid(self): + assert scan.parse_subnet_spec("not an ip") == [] + assert scan.parse_subnet_spec("999.999.999.999") == [] + + def test_range_invalid_order(self): + # 50-10 是反向范围,按规则不接受 + assert scan.parse_subnet_spec("192.168.5.50-10") == [] + + +# ============================================================ +# get_local_subnet +# ============================================================ + +class TestGetLocalSubnet: + def test_outbound_ip_to_subnet(self): + with patch.object(scan, "_get_outbound_ip", return_value="192.168.5.19"), \ + patch.object(scan, "_get_first_private_ipv4", return_value=None): + assert scan.get_local_subnet() == "192.168.5.0/24" + + def test_falls_back_to_first_private(self): + with patch.object(scan, "_get_outbound_ip", return_value=None), \ + patch.object(scan, "_get_first_private_ipv4", return_value="10.0.0.42"): + assert scan.get_local_subnet() == "10.0.0.0/24" + + def test_no_ip_returns_none(self): + with patch.object(scan, "_get_outbound_ip", return_value=None), \ + patch.object(scan, "_get_first_private_ipv4", return_value=None): + assert scan.get_local_subnet() is None + + +# ============================================================ +# probe_adb_port +# ============================================================ + +class TestProbeAdbPort: + def test_port_open(self): + fake_sock = MagicMock() + fake_sock.connect = MagicMock(return_value=None) + with patch("socket.socket", return_value=fake_sock): + assert scan.probe_adb_port("192.168.5.2") is True + + def test_port_closed(self): + fake_sock = MagicMock() + fake_sock.connect = MagicMock(side_effect=ConnectionRefusedError()) + with patch("socket.socket", return_value=fake_sock): + assert scan.probe_adb_port("192.168.5.99") is False + + def test_timeout(self): + fake_sock = MagicMock() + fake_sock.connect = MagicMock(side_effect=socket.timeout()) + with patch("socket.socket", return_value=fake_sock): + assert scan.probe_adb_port("192.168.5.99", timeout=0.01) is False + + +# ============================================================ +# scan_open_ports +# ============================================================ + +class TestScanOpenPorts: + def test_returns_only_open(self): + ips = ["192.168.5.2", "192.168.5.3", "192.168.5.4"] + # 只有 .2 和 .4 开 5555 + with patch.object( + scan, + "probe_adb_port", + side_effect=lambda ip, port=5555, timeout=0.3: ip in {"192.168.5.2", "192.168.5.4"}, + ): + opens = scan.scan_open_ports(ips, max_workers=4) + assert opens == ["192.168.5.2", "192.168.5.4"] + + def test_progress_callback(self): + progress = [] + with patch.object(scan, "probe_adb_port", return_value=False): + scan.scan_open_ports( + ["10.0.0.1", "10.0.0.2", "10.0.0.3"], + max_workers=2, + on_progress=lambda d, t: progress.append((d, t)), + ) + # 进度应该 1/3, 2/3, 3/3 各一次(顺序不保证) + assert len(progress) == 3 + assert all(t == 3 for d, t in progress) + + def test_empty_ips(self): + assert scan.scan_open_ports([]) == [] + + +# ============================================================ +# verify_adb_target +# ============================================================ + +class TestVerifyAdbTarget: + def test_connected(self): + with patch("subprocess.run", return_value=_proc("connected to 192.168.5.2:5555", "", 0)): + state, msg = scan.verify_adb_target("/adb", "192.168.5.2:5555") + assert state == "connected" + + def test_already_connected(self): + with patch("subprocess.run", return_value=_proc("already connected to 192.168.5.2:5555", "", 0)): + state, _ = scan.verify_adb_target("/adb", "192.168.5.2:5555") + assert state == "connected" + + def test_unauthorized(self): + with patch("subprocess.run", return_value=_proc("failed to authenticate to 192.168.5.2:5555", "", 0)): + state, _ = scan.verify_adb_target("/adb", "192.168.5.2:5555") + assert state == "unauthorized" + + def test_failed(self): + with patch("subprocess.run", return_value=_proc("cannot connect: refused", "", 1)): + state, _ = scan.verify_adb_target("/adb", "192.168.5.99:5555") + assert state == "failed" + + +# ============================================================ +# discover_adb_devices —— 主入口集成测试 +# ============================================================ + +class TestDiscoverAdbDevices: + def test_full_flow_one_connected(self): + """子网推导 → 1 个 IP 开 5555 → connect connected → 取 model。""" + with patch.object(scan, "get_local_subnet", return_value="192.168.5.0/24"), \ + patch.object( + scan, + "scan_open_ports", + return_value=["192.168.5.2"], + ), \ + patch.object( + scan, + "verify_adb_target", + return_value=("connected", "already connected to 192.168.5.2:5555"), + ), \ + patch.object(scan, "query_device_model", return_value="PEPM00"): + devs = scan.discover_adb_devices("/adb") + assert len(devs) == 1 + assert devs[0].ip == "192.168.5.2" + assert devs[0].port == 5555 + assert devs[0].adb_state == "connected" + assert devs[0].model == "PEPM00" + assert devs[0].target == "192.168.5.2:5555" + + def test_unauthorized_still_listed(self): + with patch.object(scan, "get_local_subnet", return_value="192.168.5.0/24"), \ + patch.object(scan, "scan_open_ports", return_value=["192.168.5.2"]), \ + patch.object( + scan, + "verify_adb_target", + return_value=("unauthorized", "failed to authenticate"), + ), \ + patch.object(scan, "query_device_model", return_value=""): + devs = scan.discover_adb_devices("/adb") + assert len(devs) == 1 + assert devs[0].adb_state == "unauthorized" + # unauthorized 不应再去 query model + assert devs[0].model == "" + + def test_no_subnet_returns_empty(self): + with patch.object(scan, "get_local_subnet", return_value=None): + devs = scan.discover_adb_devices("/adb") + assert devs == [] + + def test_explicit_subnet_overrides_auto(self): + captured = {} + + def fake_scan_ports(ips, **kwargs): + captured["ips"] = list(ips) + return [] + + with patch.object(scan, "scan_open_ports", side_effect=fake_scan_ports): + scan.discover_adb_devices("/adb", subnet_spec="10.0.0.5-7") + + assert captured["ips"] == ["10.0.0.5", "10.0.0.6", "10.0.0.7"] + + def test_no_open_ports_returns_empty(self): + with patch.object(scan, "get_local_subnet", return_value="192.168.5.0/24"), \ + patch.object(scan, "scan_open_ports", return_value=[]): + devs = scan.discover_adb_devices("/adb") + assert devs == []