优化WiFi ADB快速扫描
This commit is contained in:
1 parent
e51d37890a
commit
24b58a8c6d
6 files changed
+155
-141
No files matched your search
@@ -25,7 +25,7 @@ def _handle_scan_result(
|
||||
open_pick_dialog: Callable[[Sequence], None],
|
||||
) -> None:
|
||||
if not devs:
|
||||
on_line("[扫描] 未发现开放 5555 端口的设备(同 WiFi 下设备需先启用 ADB 调试)")
|
||||
on_line("[扫描] 未发现 WiFi ADB 设备(同 WiFi 下设备需先启用 ADB 调试/无线调试)")
|
||||
return
|
||||
|
||||
connected = [d for d in devs if d.adb_state == "connected"]
|
||||
|
||||
@@ -61,7 +61,7 @@ def open_scan_dialog(
|
||||
|
||||
# 第二行:端口规格
|
||||
ttk.Label(top_frame, text="端口:").grid(row=1, column=0, sticky=W, pady=(6, 0))
|
||||
scan_port_var = tk.StringVar(value="5555")
|
||||
scan_port_var = tk.StringVar(value="")
|
||||
ttk.Entry(top_frame, textvariable=scan_port_var, width=32).grid(
|
||||
row=1, column=1, columnspan=3, padx=(6, 0), pady=(6, 0), sticky="we"
|
||||
)
|
||||
@@ -74,7 +74,7 @@ def open_scan_dialog(
|
||||
).grid(row=2, column=0, columnspan=4, sticky=W, pady=(4, 0))
|
||||
ttk.Label(
|
||||
top_frame,
|
||||
text="端口示例: 5555 | 5555,5556 | 37000-40000 (Android 11+ 无线调试随机端口在 37000-44999)",
|
||||
text="端口留空=快速自动;手动示例: 5555 | 5555,5556 | 37000-44000 (Android 无线调试随机端口)",
|
||||
font=("Arial", 8),
|
||||
foreground="gray",
|
||||
).grid(row=3, column=0, columnspan=4, sticky=W, pady=(2, 0))
|
||||
@@ -192,7 +192,7 @@ def open_scan_dialog(
|
||||
devs = discover_adb_devices(
|
||||
adb_exe_local,
|
||||
subnet_spec=spec,
|
||||
ports=port_list,
|
||||
ports=None if not scan_port_var.get().strip() else port_list,
|
||||
on_progress=on_progress,
|
||||
on_phase=on_phase,
|
||||
)
|
||||
@@ -216,7 +216,7 @@ def open_scan_dialog(
|
||||
)
|
||||
else:
|
||||
status_var.set("扫描完成,未发现设备")
|
||||
on_line_local("[扫描] 未发现开放 5555 的设备")
|
||||
on_line_local("[扫描] 未发现 WiFi ADB 设备")
|
||||
progress_var.set(100)
|
||||
scan_btn.config(state="normal")
|
||||
scanning["flag"] = False
|
||||
|
||||
+112
-103
@@ -22,15 +22,15 @@ DEFAULT_ADB_PORT = 5555
|
||||
HI_PORT_MIN = 37000
|
||||
HI_PORT_MAX = 44000
|
||||
# 高端口补扫先做一轮均匀采样,命中率够高时可以明显缩短等待。
|
||||
HI_PORT_SAMPLE_COUNT = 320
|
||||
HI_PORT_SAMPLE_COUNT = 192
|
||||
FAST_PROBE_TIMEOUT = 0.12
|
||||
FAST_CONNECT_TIMEOUT = 1.2
|
||||
MDNS_DISCOVERY_TIMEOUT = 0.8
|
||||
DEFAULT_SCAN_TIMEOUT = 0.12
|
||||
MAX_QUICK_HOSTS = 24
|
||||
|
||||
# 默认扫描端口集合:
|
||||
# - 5555 传统 adb tcpip 端口
|
||||
# - 37000-44999 Android 11+ "无线调试"会用这个范围里的随机端口
|
||||
# (来自 ADB pairing 协议;不是每次都同一个,所以扫描需要范围)
|
||||
# 注意:扫整个 8000 端口区间会慢,所以这里只默认扫 5555。
|
||||
# 用户可在 GUI/CLI 里把 ports 改成 "5555,37000-40000" 等。
|
||||
# 默认扫描端口集合:5555 是传统 adb tcpip 端口;Android 11+ 无线调试
|
||||
# 随机端口走 discover_adb_devices 的 mDNS / ARP / 上次目标快速路径补扫。
|
||||
DEFAULT_ADB_PORTS: tuple[int, ...] = (DEFAULT_ADB_PORT,)
|
||||
|
||||
|
||||
@@ -344,7 +344,7 @@ def parse_port_spec(spec) -> list[int]:
|
||||
continue
|
||||
if not (1 <= lo <= hi <= 65535):
|
||||
continue
|
||||
if (hi - lo + 1) > 1024:
|
||||
if (hi - lo + 1) > 1024 and not (lo == HI_PORT_MIN and hi == HI_PORT_MAX):
|
||||
continue
|
||||
for p in range(lo, hi + 1):
|
||||
if p not in seen:
|
||||
@@ -427,6 +427,72 @@ def _build_hi_port_candidates(last_port_hint: Optional[int] = None) -> list[int]
|
||||
return out
|
||||
|
||||
|
||||
def _append_unique_ip(out: list[str], seen: set[str], ip: str, subnet_specs: list[str]) -> None:
|
||||
try:
|
||||
ipaddress.IPv4Address(ip)
|
||||
except Exception:
|
||||
return
|
||||
if ip in seen or not _ip_in_subnets(ip, subnet_specs):
|
||||
return
|
||||
seen.add(ip)
|
||||
out.append(ip)
|
||||
|
||||
|
||||
def _build_quick_host_candidates(
|
||||
subnet_specs: list[str],
|
||||
*,
|
||||
last_ip: str = "",
|
||||
mdns_targets: Optional[list[tuple[str, int]]] = None,
|
||||
max_hosts: int = MAX_QUICK_HOSTS,
|
||||
) -> list[str]:
|
||||
"""Build a small online-likely host list for Android wireless-debug random ports."""
|
||||
out: list[str] = []
|
||||
seen: set[str] = set()
|
||||
|
||||
if last_ip:
|
||||
_append_unique_ip(out, seen, last_ip, subnet_specs)
|
||||
|
||||
for ip, _port in mdns_targets or []:
|
||||
_append_unique_ip(out, seen, ip, subnet_specs)
|
||||
if len(out) >= max_hosts:
|
||||
return out
|
||||
|
||||
arp_added = False
|
||||
for ip in _list_arp_ipv4_candidates(subnet_specs, max_hosts=max_hosts):
|
||||
_append_unique_ip(out, seen, ip, subnet_specs)
|
||||
arp_added = True
|
||||
if len(out) >= max_hosts:
|
||||
return out
|
||||
|
||||
# If ARP is empty, scan a small prefix of each subnet rather than the whole /24 high range.
|
||||
if not arp_added:
|
||||
for spec in subnet_specs:
|
||||
for ip in parse_subnet_spec(spec):
|
||||
_append_unique_ip(out, seen, ip, subnet_specs)
|
||||
if len(out) >= max_hosts:
|
||||
return out
|
||||
return out
|
||||
|
||||
|
||||
def _connect_last_target_fast(
|
||||
adb_exe: str,
|
||||
target: str,
|
||||
model: str = "",
|
||||
) -> Optional[DiscoveredDevice]:
|
||||
"""Try the remembered target before any broad scanning."""
|
||||
parsed = _parse_target_ip_port(target)
|
||||
if not parsed:
|
||||
return None
|
||||
ip, port = parsed
|
||||
state, message = verify_adb_target(adb_exe, f"{ip}:{port}", timeout=FAST_CONNECT_TIMEOUT)
|
||||
if state not in ("connected", "unauthorized"):
|
||||
return None
|
||||
dev = DiscoveredDevice(ip=ip, port=port, adb_state=state, message=message)
|
||||
if state == "connected":
|
||||
dev.model = model or query_device_model(adb_exe, dev.target)
|
||||
return dev
|
||||
|
||||
|
||||
# ============================================================
|
||||
# TCP 端口探测
|
||||
# ============================================================
|
||||
@@ -546,7 +612,7 @@ def discover_mdns_targets(adb_exe: str) -> list[tuple[str, int]]:
|
||||
"""
|
||||
if not adb_exe:
|
||||
return []
|
||||
rc, out = _run_adb(adb_exe, ["mdns", "services"], timeout=4.0)
|
||||
rc, out = _run_adb(adb_exe, ["mdns", "services"], timeout=MDNS_DISCOVERY_TIMEOUT)
|
||||
if rc != 0 or not out:
|
||||
return []
|
||||
targets: list[tuple[str, int]] = []
|
||||
@@ -575,7 +641,7 @@ def discover_mdns_targets(adb_exe: str) -> list[tuple[str, int]]:
|
||||
return targets
|
||||
|
||||
|
||||
def verify_adb_target(adb_exe: str, target: str) -> tuple[str, str]:
|
||||
def verify_adb_target(adb_exe: str, target: str, timeout: float = 5.0) -> tuple[str, str]:
|
||||
"""对一个 ip:port 调 `adb connect <target>`,解析输出。
|
||||
|
||||
返回 (state, message):
|
||||
@@ -583,7 +649,7 @@ def verify_adb_target(adb_exe: str, target: str) -> tuple[str, str]:
|
||||
- state="unauthorized" adb 协议握手成功但设备未授权
|
||||
- state="failed" 其他失败
|
||||
"""
|
||||
rc, out = _run_adb(adb_exe, ["connect", target], timeout=5.0)
|
||||
rc, out = _run_adb(adb_exe, ["connect", target], timeout=timeout)
|
||||
low = out.lower()
|
||||
if "authenticate" in low or "unauthorized" in low:
|
||||
return "unauthorized", out
|
||||
@@ -652,7 +718,7 @@ def discover_adb_devices(
|
||||
adb_exe: str,
|
||||
subnet_spec: Optional[str] = None,
|
||||
port: int = DEFAULT_ADB_PORT,
|
||||
probe_timeout: float = 0.3,
|
||||
probe_timeout: float = DEFAULT_SCAN_TIMEOUT,
|
||||
on_progress: Optional[Callable[[int, int], None]] = None,
|
||||
on_phase: Optional[Callable[[str], None]] = None,
|
||||
ports: Optional[Iterable[int]] = None,
|
||||
@@ -691,6 +757,7 @@ def discover_adb_devices(
|
||||
else:
|
||||
subnet_specs = [subnet_spec.strip()]
|
||||
|
||||
auto_ports_mode = ports is None or list(ports) == [DEFAULT_ADB_PORT]
|
||||
port_list = list(ports) if ports else [int(port)]
|
||||
if not port_list:
|
||||
port_list = [DEFAULT_ADB_PORT]
|
||||
@@ -698,8 +765,9 @@ def discover_adb_devices(
|
||||
# 1.5) 利用上次成功目标加速:优先直连上次 target;并把上次端口作为补充端口。
|
||||
last_target = ""
|
||||
last_model = ""
|
||||
last_ip_hint = ""
|
||||
last_port_hint: Optional[int] = None
|
||||
if port_list == [DEFAULT_ADB_PORT]:
|
||||
if auto_ports_mode:
|
||||
try:
|
||||
from . import config as wifi_config
|
||||
|
||||
@@ -715,34 +783,16 @@ def discover_adb_devices(
|
||||
if parsed_last:
|
||||
last_ip, last_port_hint_val = parsed_last
|
||||
if _ip_in_subnets(last_ip, subnet_specs):
|
||||
last_ip_hint = last_ip
|
||||
last_port_hint = last_port_hint_val
|
||||
if last_port_hint != DEFAULT_ADB_PORT and last_port_hint not in port_list:
|
||||
port_list = [DEFAULT_ADB_PORT, last_port_hint]
|
||||
if on_phase:
|
||||
try:
|
||||
on_phase(f"快速验证上次目标 {last_ip}:{last_port_hint}")
|
||||
except Exception:
|
||||
pass
|
||||
if _is_mocked_callable(get_last_wifi_target_fn) and probe_adb_port(
|
||||
last_ip,
|
||||
last_port_hint,
|
||||
timeout=min(max(probe_timeout, 0.01), FAST_PROBE_TIMEOUT),
|
||||
):
|
||||
state, message = verify_adb_target(
|
||||
adb_exe, f"{last_ip}:{last_port_hint}"
|
||||
)
|
||||
if state in ("connected", "unauthorized"):
|
||||
dev = DiscoveredDevice(
|
||||
ip=last_ip,
|
||||
port=last_port_hint,
|
||||
adb_state=state,
|
||||
message=message,
|
||||
)
|
||||
if state == "connected":
|
||||
dev.model = last_model
|
||||
if not dev.model:
|
||||
dev.model = query_device_model(adb_exe, dev.target)
|
||||
return [dev]
|
||||
dev = _connect_last_target_fast(adb_exe, f"{last_ip}:{last_port_hint}", last_model)
|
||||
if dev is not None:
|
||||
return [dev]
|
||||
|
||||
# 2) mDNS 发现(Android 11+ 无线调试常见随机端口)
|
||||
mdns_targets = discover_mdns_targets(adb_exe)
|
||||
@@ -752,6 +802,30 @@ def discover_adb_devices(
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
quick_open_targets: list[tuple[str, int]] = []
|
||||
if auto_ports_mode:
|
||||
quick_hosts = _build_quick_host_candidates(
|
||||
subnet_specs,
|
||||
last_ip=last_ip_hint,
|
||||
mdns_targets=mdns_targets,
|
||||
max_hosts=MAX_QUICK_HOSTS,
|
||||
)
|
||||
quick_ports = _build_hi_port_candidates(last_port_hint)
|
||||
if last_port_hint and last_port_hint not in quick_ports:
|
||||
quick_ports.insert(0, last_port_hint)
|
||||
if quick_hosts and quick_ports:
|
||||
if on_phase:
|
||||
try:
|
||||
on_phase(f"快速补扫 {len(quick_hosts)} 台在线候选 × {len(quick_ports)} 个无线调试高端口")
|
||||
except Exception:
|
||||
pass
|
||||
quick_open_targets = scan_open_ports(
|
||||
quick_hosts,
|
||||
ports=quick_ports,
|
||||
timeout=min(max(probe_timeout, 0.01), 0.025),
|
||||
max_workers=256,
|
||||
)
|
||||
|
||||
# 3) 端口扫描(支持多子网补扫)
|
||||
all_open_targets: list[tuple[str, int]] = []
|
||||
total_ips = 0
|
||||
@@ -770,9 +844,10 @@ def discover_adb_devices(
|
||||
on_phase(f"扫描 {spec}({len(ips)} 个 IP × {ports_label})")
|
||||
except Exception:
|
||||
pass
|
||||
base_ports = [DEFAULT_ADB_PORT] if auto_ports_mode else port_list
|
||||
open_targets = scan_open_ports(
|
||||
ips,
|
||||
ports=port_list,
|
||||
ports=base_ports,
|
||||
timeout=probe_timeout,
|
||||
on_progress=on_progress,
|
||||
)
|
||||
@@ -781,6 +856,7 @@ def discover_adb_devices(
|
||||
|
||||
# 合并 mDNS + 网段扫描,并去重
|
||||
all_targets = list(mdns_targets)
|
||||
all_targets.extend(quick_open_targets)
|
||||
all_targets.extend(all_open_targets)
|
||||
uniq_open: list[tuple[str, int]] = []
|
||||
seen_open: set[tuple[str, int]] = set()
|
||||
@@ -790,73 +866,6 @@ def discover_adb_devices(
|
||||
seen_open.add(t)
|
||||
uniq_open.append(t)
|
||||
|
||||
# 2.5) 随机端口补扫:
|
||||
# 在无线调试场景中,端口常落在 37000~44000;当 mDNS 为空且 5555 未命中时,
|
||||
# 对 ARP 里“看起来在线”的少量主机做一次窄范围补扫,提升命中率。
|
||||
default_or_hint_ports = port_list == [DEFAULT_ADB_PORT]
|
||||
if (
|
||||
not default_or_hint_ports
|
||||
and isinstance(last_port_hint, int)
|
||||
and last_port_hint != DEFAULT_ADB_PORT
|
||||
):
|
||||
default_or_hint_ports = port_list == [DEFAULT_ADB_PORT, last_port_hint]
|
||||
|
||||
if (
|
||||
auto_subnet_mode
|
||||
and not uniq_open
|
||||
and not mdns_targets
|
||||
and default_or_hint_ports
|
||||
):
|
||||
arp_ips = _list_arp_ipv4_candidates(subnet_specs, max_hosts=8)
|
||||
if not arp_ips:
|
||||
for spec in subnet_specs:
|
||||
for ip in parse_subnet_spec(spec):
|
||||
if ip not in arp_ips:
|
||||
arp_ips.append(ip)
|
||||
if len(arp_ips) >= 8:
|
||||
break
|
||||
if len(arp_ips) >= 8:
|
||||
break
|
||||
if arp_ips:
|
||||
sampled_hi_ports = _build_hi_port_candidates(last_port_hint)
|
||||
if on_phase:
|
||||
try:
|
||||
on_phase(
|
||||
f"5555 未命中,补扫 ARP 候选主机 {len(arp_ips)} 台的 {len(sampled_hi_ports)} 个高端口候选"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
hi_open = scan_open_ports(
|
||||
arp_ips,
|
||||
ports=sampled_hi_ports,
|
||||
timeout=min(probe_timeout, 0.05),
|
||||
max_workers=128,
|
||||
)
|
||||
# 候选端口没命中再做全范围兜底,兼顾速度和命中率。
|
||||
if not hi_open:
|
||||
if on_phase:
|
||||
try:
|
||||
on_phase("高端口候选未命中,执行 37000-44000 全范围兜底补扫(可能较慢)")
|
||||
except Exception:
|
||||
pass
|
||||
full_hi_ports = list(range(HI_PORT_MIN, HI_PORT_MAX + 1))
|
||||
for arp_ip in arp_ips:
|
||||
host_open = scan_open_ports(
|
||||
[arp_ip],
|
||||
ports=full_hi_ports,
|
||||
timeout=min(probe_timeout, 0.05),
|
||||
max_workers=128,
|
||||
)
|
||||
if host_open:
|
||||
hi_open.extend(host_open)
|
||||
# 一旦命中,先返回这一批,不再继续扫其它主机。
|
||||
break
|
||||
for t in hi_open:
|
||||
if t in seen_open:
|
||||
continue
|
||||
seen_open.add(t)
|
||||
uniq_open.append(t)
|
||||
|
||||
if not uniq_open:
|
||||
return []
|
||||
|
||||
|
||||
@@ -614,7 +614,7 @@ def handle_post(handler, u, runner, csrf_token: str) -> None:
|
||||
return handler._send_json({"ok": False, "error": "adb not found"}, status=422)
|
||||
subnet = str(body.get("subnet") or "").strip() or None
|
||||
try:
|
||||
probe_timeout = float(body.get("probe_timeout") or 0.3)
|
||||
probe_timeout = float(body.get("probe_timeout") or 0.12)
|
||||
except Exception:
|
||||
return handler._send_json({"ok": False, "error": "invalid probe_timeout"}, status=400)
|
||||
if probe_timeout <= 0:
|
||||
@@ -626,13 +626,14 @@ def handle_post(handler, u, runner, csrf_token: str) -> None:
|
||||
from gui.gui_core_pkg import parse_port_spec
|
||||
|
||||
port_list = parse_port_spec(ports_raw)
|
||||
ports_for_scan = None if ports_raw is None or str(ports_raw).strip() == "" else port_list
|
||||
except Exception:
|
||||
return handler._send_json({"ok": False, "error": "invalid ports"}, status=400)
|
||||
try:
|
||||
from gui.gui_core_pkg import discover_adb_devices, get_local_subnet, get_local_subnets
|
||||
|
||||
devs = discover_adb_devices(
|
||||
adb, subnet_spec=subnet, ports=port_list, probe_timeout=probe_timeout
|
||||
adb, subnet_spec=subnet, ports=ports_for_scan, probe_timeout=probe_timeout
|
||||
)
|
||||
tried_subnets = [subnet] if subnet else (get_local_subnets() or [])
|
||||
payload = [
|
||||
|
||||
@@ -200,7 +200,11 @@ def test_wifi_scan_includes_tried_subnets(monkeypatch):
|
||||
import gui.gui_core_pkg as core_pkg
|
||||
|
||||
monkeypatch.setattr(core_pkg, "parse_port_spec", lambda spec: [5555]) # noqa: ARG001
|
||||
monkeypatch.setattr(core_pkg, "discover_adb_devices", lambda *a, **k: [])
|
||||
captured = {}
|
||||
def fake_discover(*a, **k):
|
||||
captured.update(k)
|
||||
return []
|
||||
monkeypatch.setattr(core_pkg, "discover_adb_devices", fake_discover)
|
||||
monkeypatch.setattr(core_pkg, "get_local_subnet", lambda: "192.168.10.0/24")
|
||||
monkeypatch.setattr(core_pkg, "get_local_subnets", lambda: ["192.168.10.0/24", "10.0.0.0/24"])
|
||||
|
||||
@@ -208,6 +212,7 @@ def test_wifi_scan_includes_tried_subnets(monkeypatch):
|
||||
assert status == 200
|
||||
assert obj.get("ok") is True
|
||||
assert obj.get("subnets") == ["192.168.10.0/24", "10.0.0.0/24"]
|
||||
assert captured.get("ports") is None
|
||||
|
||||
|
||||
def test_wifi_disconnect_clears_last_target_only_on_exact_target(monkeypatch):
|
||||
|
||||
+29
-30
@@ -232,6 +232,12 @@ class TestParsePortSpec:
|
||||
result = scan.parse_port_spec("5555,1-2000")
|
||||
assert result == [5555]
|
||||
|
||||
def test_android_wireless_debug_range_allowed(self):
|
||||
result = scan.parse_port_spec("37000-44000")
|
||||
assert result[0] == 37000
|
||||
assert result[-1] == 44000
|
||||
assert len(result) == 7001
|
||||
|
||||
|
||||
# ============================================================
|
||||
# verify_adb_target
|
||||
@@ -401,12 +407,15 @@ class TestDiscoverAdbDevices:
|
||||
return [("10.0.0.9", 5555)]
|
||||
|
||||
with patch.object(scan, "get_local_subnets", return_value=["192.168.10.0/30", "10.0.0.8/30"]), \
|
||||
patch.object(scan, "discover_mdns_targets", return_value=[]), \
|
||||
patch.object(scan, "_list_arp_ipv4_candidates", return_value=[]), \
|
||||
patch.object(scan, "scan_open_ports", side_effect=fake_scan_ports), \
|
||||
patch.object(scan, "verify_adb_target", return_value=("connected", "ok")), \
|
||||
patch.object(scan, "query_device_model", return_value="PEPM00"):
|
||||
devs = scan.discover_adb_devices("/adb")
|
||||
|
||||
assert len(calls) == 2
|
||||
assert len(calls) == 3
|
||||
assert calls[0] == ["192.168.10.1", "192.168.10.2", "10.0.0.9", "10.0.0.10"]
|
||||
assert len(devs) == 1
|
||||
assert devs[0].target == "10.0.0.9:5555"
|
||||
|
||||
@@ -442,7 +451,6 @@ class TestDiscoverAdbDevices:
|
||||
def test_fast_path_hits_last_target_and_returns_early(self):
|
||||
with patch.object(scan, "get_local_subnets", return_value=["192.168.10.0/24"]), \
|
||||
patch("gui.gui_core_pkg.config.get_last_wifi_target", return_value={"target": "192.168.10.103:37697", "model": "Xiaomi 14"}), \
|
||||
patch.object(scan, "probe_adb_port", return_value=True), \
|
||||
patch.object(scan, "verify_adb_target", return_value=("connected", "ok")), \
|
||||
patch.object(scan, "query_device_model", return_value="SHOULD_NOT_CALL"), \
|
||||
patch.object(scan, "discover_mdns_targets", side_effect=AssertionError("should not reach mdns")), \
|
||||
@@ -463,42 +471,38 @@ class TestDiscoverAdbDevices:
|
||||
|
||||
with patch.object(scan, "get_local_subnets", return_value=["192.168.10.0/24"]), \
|
||||
patch("gui.gui_core_pkg.config.get_last_wifi_target", return_value={"target": "192.168.10.103:37697"}), \
|
||||
patch.object(scan, "probe_adb_port", return_value=False), \
|
||||
patch.object(scan, "verify_adb_target", return_value=("failed", "refused")), \
|
||||
patch.object(scan, "discover_mdns_targets", return_value=[]), \
|
||||
patch.object(scan, "scan_open_ports", side_effect=fake_scan_ports):
|
||||
_ = scan.discover_adb_devices("/adb")
|
||||
|
||||
assert captured_ports
|
||||
assert captured_ports[0] == [5555, 37697]
|
||||
assert captured_ports[0][0] == 37697
|
||||
assert 5555 not in captured_ports[0]
|
||||
assert captured_ports[1] == [5555]
|
||||
|
||||
def test_hi_port_fallback_uses_sample_then_full_per_host(self):
|
||||
def test_auto_mode_quick_high_port_scan_before_base_5555(self):
|
||||
calls = []
|
||||
|
||||
def fake_scan_ports(ips, **kwargs):
|
||||
ports = list(kwargs.get("ports") or [])
|
||||
calls.append((list(ips), len(ports)))
|
||||
# first subnet scan: no open
|
||||
if len(ips) > 1:
|
||||
return []
|
||||
# sampled pass miss
|
||||
if len(ports) < 1000:
|
||||
return []
|
||||
# full-range pass hit on first host
|
||||
return [("192.168.10.55", 40123)]
|
||||
if ports and ports[0] >= scan.HI_PORT_MIN:
|
||||
return [("192.168.10.55", 40123)]
|
||||
return []
|
||||
|
||||
with patch.object(scan, "get_local_subnets", return_value=["192.168.10.0/30"]), \
|
||||
with patch.object(scan, "get_local_subnets", return_value=["192.168.10.0/24"]), \
|
||||
patch("gui.gui_core_pkg.config.get_last_wifi_target", return_value={}), \
|
||||
patch.object(scan, "discover_mdns_targets", return_value=[]), \
|
||||
patch.object(scan, "_list_arp_ipv4_candidates", return_value=["192.168.10.55"]), \
|
||||
patch.object(scan, "scan_open_ports", side_effect=fake_scan_ports), \
|
||||
patch.object(scan, "verify_adb_target", return_value=("connected", "ok")), \
|
||||
patch.object(scan, "query_device_model", return_value="M"):
|
||||
devs = scan.discover_adb_devices("/adb")
|
||||
|
||||
assert len(devs) == 1
|
||||
# 第二次调用:ARP sampled;第三次调用:full-range per-host
|
||||
assert len(calls) >= 3
|
||||
assert calls[1][1] < 1000
|
||||
assert calls[2][1] == (scan.HI_PORT_MAX - scan.HI_PORT_MIN + 1)
|
||||
assert calls[0] == (["192.168.10.55"], scan.HI_PORT_SAMPLE_COUNT)
|
||||
assert calls[1][1] == 1
|
||||
|
||||
def test_hi_port_fallback_still_runs_when_last_port_hint_added(self):
|
||||
calls = []
|
||||
@@ -506,25 +510,20 @@ class TestDiscoverAdbDevices:
|
||||
def fake_scan_ports(ips, **kwargs):
|
||||
ports = list(kwargs.get("ports") or [])
|
||||
calls.append((list(ips), ports))
|
||||
# 基础子网扫描无命中
|
||||
if len(ips) > 1:
|
||||
return []
|
||||
# ARP sampled 补扫直接命中
|
||||
if len(ports) < 1000:
|
||||
if ports and ports[0] >= scan.HI_PORT_MIN:
|
||||
return [("192.168.10.55", 40123)]
|
||||
return []
|
||||
|
||||
with patch.object(scan, "get_local_subnets", return_value=["192.168.10.0/30"]), \
|
||||
with patch.object(scan, "get_local_subnets", return_value=["192.168.10.0/24"]), \
|
||||
patch("gui.gui_core_pkg.config.get_last_wifi_target", return_value={"target": "192.168.10.2:37697"}), \
|
||||
patch.object(scan, "probe_adb_port", return_value=False), \
|
||||
patch.object(scan, "verify_adb_target", return_value=("failed", "refused")), \
|
||||
patch.object(scan, "discover_mdns_targets", return_value=[]), \
|
||||
patch.object(scan, "_list_arp_ipv4_candidates", return_value=["192.168.10.55"]), \
|
||||
patch.object(scan, "scan_open_ports", side_effect=fake_scan_ports), \
|
||||
patch.object(scan, "verify_adb_target", return_value=("connected", "ok")), \
|
||||
patch.object(scan, "query_device_model", return_value="M"):
|
||||
devs = scan.discover_adb_devices("/adb")
|
||||
|
||||
assert len(devs) == 1
|
||||
# 第一次调用应包含 last_port_hint
|
||||
assert calls[0][1] == [5555, 37697]
|
||||
# 之后仍应进入 ARP sampled 补扫
|
||||
assert any(len(p) < 1000 for _ips, p in calls[1:])
|
||||
assert calls[0][0] == ["192.168.10.2", "192.168.10.55"]
|
||||
assert calls[0][1][0] == 37697
|
||||
assert calls[1][1] == [5555]
|
||||
Reference in new issue
Block a user