fix(wifi-adb): restore hi-port fallback path and harden reconnect/import edge cases

This commit is contained in:
Your Name committed 2026-06-01 11:05:47 +08:00
1 parent e33b42597c
commit a68307d7fd
5 files changed
+407 -9

No files matched your search

+20 -6
View File
@@ -15,7 +15,7 @@ from __future__ import annotations
import threading
import tkinter as tk
from typing import Callable
from typing import Callable, Optional
from gui.gui_core import list_adb_devices
from gui.gui_core_pkg import (
@@ -27,6 +27,20 @@ from gui.gui_core_pkg import (
from gui.gui_core_pkg.wifi_adb_scan import verify_adb_target
def _safe_after(root: tk.Misc, callback: Callable[[], None], *, fallback: Optional[Callable[[], None]] = None) -> None:
"""跨线程安全调度 UI 回调;主循环不可用时可走降级回调。"""
try:
root.after(0, callback)
return
except Exception:
pass
if fallback is not None:
try:
fallback()
except Exception:
pass
def try_reconnect_last_wifi(
root: tk.Misc,
*,
@@ -87,7 +101,7 @@ def try_reconnect_last_wifi(
f"[启动] 自动重连成功: {target}"
+ (f" ({model})" if model else "")
)
root.after(0, render_ok)
_safe_after(root, render_ok, fallback=lambda: on_line(f"[启动] 自动重连成功: {target}"))
return
if state == "unauthorized":
@@ -95,7 +109,7 @@ def try_reconnect_last_wifi(
on_line(
f"[启动] 上次设备 {target} 未授权,请在手机上确认 ADB 调试"
)
root.after(0, render_unauth)
_safe_after(root, render_unauth, fallback=render_unauth)
return
# state == "failed" → 不可达。换网了?自动扫一下,看能不能在新网段找到
@@ -103,7 +117,7 @@ def try_reconnect_last_wifi(
on_line(
f"[启动] {target} 不可达,自动扫描局域网寻找匹配设备..."
)
root.after(0, notify_scan_start)
_safe_after(root, notify_scan_start, fallback=notify_scan_start)
try:
# 如果上次记的端口非 5555,扫描时把它一起带上(覆盖 Android 11+ 随机端口)
@@ -118,7 +132,7 @@ def try_reconnect_last_wifi(
except Exception as e:
def render_scan_err():
on_line(f"[启动] 自动扫描失败: {e}")
root.after(0, render_scan_err)
_safe_after(root, render_scan_err, fallback=render_scan_err)
return
best = pick_best_match(devs, last)
@@ -159,7 +173,7 @@ def try_reconnect_last_wifi(
+ "(已更新记忆)"
)
root.after(0, render_scan_done)
_safe_after(root, render_scan_done, fallback=render_scan_done)
threading.Thread(target=worker, daemon=True).start()
+273 -1
View File
@@ -19,6 +19,11 @@ from typing import Callable, Iterable, Optional
DEFAULT_ADB_PORT = 5555
HI_PORT_MIN = 37000
HI_PORT_MAX = 44000
# 高端口补扫先做一轮均匀采样,命中率够高时可以明显缩短等待。
HI_PORT_SAMPLE_COUNT = 320
FAST_PROBE_TIMEOUT = 0.12
# 默认扫描端口集合:
# - 5555 传统 adb tcpip 端口
@@ -169,6 +174,63 @@ def get_local_subnets() -> list[str]:
return nets
def _list_arp_ipv4_candidates(
subnet_specs: Optional[list[str]] = None,
*,
max_hosts: int = 8,
) -> list[str]:
"""从 ARP 表提取可能在线的 IPv4 候选(用于随机端口补扫)。"""
rc, out = _run_adb.__globals__.get("_ARP_RUNNER", lambda: (0, ""))() # test hook
if out == "":
# 默认真实执行:跨平台用 `arp -a`
try:
proc = subprocess.run(
["arp", "-a"],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
check=False,
timeout=3.0,
)
rc = proc.returncode
out = ((proc.stdout or "") + "\n" + (proc.stderr or "")).strip()
except Exception:
return []
if rc != 0 or not out:
return []
# 解析子网白名单
allowed_nets: list[ipaddress.IPv4Network] = []
for spec in (subnet_specs or []):
try:
net = ipaddress.IPv4Network(spec, strict=False)
allowed_nets.append(net)
except Exception:
continue
local_ips = set(_list_private_ipv4s())
seen: set[str] = set()
out_ips: list[str] = []
for m in re.finditer(r"\b(\d{1,3}(?:\.\d{1,3}){3})\b", out):
ip = m.group(1)
if ip in seen or ip in local_ips:
continue
try:
addr = ipaddress.IPv4Address(ip)
if not addr.is_private:
continue
if allowed_nets and not any(addr in net for net in allowed_nets):
continue
except Exception:
continue
seen.add(ip)
out_ips.append(ip)
if len(out_ips) >= max_hosts:
break
return out_ips
def parse_subnet_spec(spec: str) -> list[str]:
"""把用户输入解析成 IP 列表。支持的格式:
@@ -300,6 +362,71 @@ def parse_port_spec(spec) -> list[int]:
return out or [DEFAULT_ADB_PORT]
def _parse_target_ip_port(target: str) -> Optional[tuple[str, int]]:
"""把 target 解析为 (ip, port);支持 ip 或 ip:port。"""
raw = str(target or "").strip()
if not raw:
return None
ip = raw
port = DEFAULT_ADB_PORT
if ":" in raw:
host, p = raw.rsplit(":", 1)
ip = host.strip()
try:
port = int(p)
except Exception:
return None
try:
ipaddress.IPv4Address(ip)
except Exception:
return None
if not (1 <= int(port) <= 65535):
return None
return ip, int(port)
def _ip_in_subnets(ip: str, subnet_specs: list[str]) -> bool:
"""判断 IP 是否落在任一子网中。子网为空时返回 True。"""
if not subnet_specs:
return True
try:
addr = ipaddress.IPv4Address(ip)
except Exception:
return False
for spec in subnet_specs:
try:
net = ipaddress.IPv4Network(spec, strict=False)
except Exception:
continue
if addr in net:
return True
return False
def _build_hi_port_candidates(last_port_hint: Optional[int] = None) -> list[int]:
"""构建一组优先高端口候选(均匀覆盖 + 上次端口优先)。"""
out: list[int] = []
seen: set[int] = set()
if (
isinstance(last_port_hint, int)
and HI_PORT_MIN <= last_port_hint <= HI_PORT_MAX
and last_port_hint not in seen
):
seen.add(last_port_hint)
out.append(last_port_hint)
span = HI_PORT_MAX - HI_PORT_MIN + 1
step = max(1, span // max(HI_PORT_SAMPLE_COUNT, 1))
for p in range(HI_PORT_MIN, HI_PORT_MAX + 1, step):
if p in seen:
continue
seen.add(p)
out.append(p)
if len(out) >= HI_PORT_SAMPLE_COUNT:
break
return out
# ============================================================
# TCP 端口探测
# ============================================================
@@ -462,9 +589,47 @@ def verify_adb_target(adb_exe: str, target: str) -> tuple[str, str]:
return "unauthorized", out
if "connected" in low or "already connected" in low:
return "connected", out
# adb connect 偶尔会先超时,但设备随后出现在 adb devices 里。
# 仅在超时类失败时做一次兜底检查,避免把所有失败都额外拖慢。
if out.strip().lower() == "timeout" or "timed out" in low:
state2, line2 = _query_target_state_from_devices(adb_exe, target)
if state2 in ("connected", "unauthorized"):
merged = out
if line2:
merged = f"{out}\n{line2}"
return state2, merged
return "failed", out or "未知错误"
def _query_target_state_from_devices(adb_exe: str, target: str) -> tuple[Optional[str], str]:
"""从 `adb devices -l` 查询 target 当前状态。"""
if not adb_exe or not target:
return None, ""
rc, out = _run_adb(adb_exe, ["devices", "-l"], timeout=2.5)
if rc != 0 or not out:
return None, ""
lines = out.splitlines()
if len(lines) <= 1:
return None, ""
for raw in lines[1:]:
line = str(raw or "").strip()
if not line:
continue
parts = line.split()
if len(parts) < 2:
continue
serial = parts[0].strip()
state = parts[1].strip().lower()
if serial != target:
continue
if state == "device":
return "connected", line
if state == "unauthorized":
return "unauthorized", line
return "failed", line
return None, ""
def query_device_model(adb_exe: str, target: str) -> str:
"""对一个 connected 的 target 取 ro.product.model(失败返回空字符串)。"""
rc, out = _run_adb(
@@ -505,7 +670,8 @@ def discover_adb_devices(
"""
# 1) 推导扫描子网列表
subnet_specs: list[str] = []
if subnet_spec is None or not subnet_spec.strip():
auto_subnet_mode = subnet_spec is None or not str(subnet_spec).strip()
if auto_subnet_mode:
subnet_specs = get_local_subnets()
# 兼容旧逻辑的兜底
if not subnet_specs:
@@ -521,6 +687,54 @@ def discover_adb_devices(
if not port_list:
port_list = [DEFAULT_ADB_PORT]
# 1.5) 利用上次成功目标加速:优先直连上次 target;并把上次端口作为补充端口。
last_target = ""
last_model = ""
last_port_hint: Optional[int] = None
if port_list == [DEFAULT_ADB_PORT]:
try:
from .config import get_last_wifi_target
last = get_last_wifi_target() or {}
if isinstance(last, dict):
last_target = str(last.get("target") or "").strip()
last_model = str(last.get("model") or "").strip()
except Exception:
last_target = ""
last_model = ""
parsed_last = _parse_target_ip_port(last_target) if last_target else None
if parsed_last:
last_ip, last_port_hint_val = parsed_last
if _ip_in_subnets(last_ip, subnet_specs):
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
# 先做一次短超时端口探测,避免无意义 adb connect 阻塞。
if 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":
# 命中快速路径时,优先复用记忆里的 model,失败再回查。
dev.model = last_model
if not dev.model:
dev.model = query_device_model(adb_exe, dev.target)
return [dev]
# 2) mDNS 发现(Android 11+ 无线调试常见随机端口)
mdns_targets = discover_mdns_targets(adb_exe)
if on_phase and mdns_targets:
@@ -567,6 +781,64 @@ 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 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 []
+3
View File
@@ -4,6 +4,9 @@ from __future__ import annotations
from douyin.core import path_config
DEFAULT_WEB_GUI_HOST = path_config.DEFAULT_WEB_GUI_HOST
DEFAULT_WEB_GUI_PORT = path_config.DEFAULT_WEB_GUI_PORT
def get_web_gui_host() -> str:
return path_config.get_web_gui_host()
+110 -1
View File
@@ -258,6 +258,24 @@ class TestVerifyAdbTarget:
state, _ = scan.verify_adb_target("/adb", "192.168.5.99:5555")
assert state == "failed"
def test_timeout_but_devices_shows_connected(self):
with patch.object(scan, "_run_adb", side_effect=[
(-1, "timeout"),
(0, "List of devices attached\n192.168.5.2:5555 device product:x model:y\n"),
]):
state, msg = scan.verify_adb_target("/adb", "192.168.5.2:5555")
assert state == "connected"
assert "192.168.5.2:5555 device" in msg
def test_timeout_but_devices_shows_unauthorized(self):
with patch.object(scan, "_run_adb", side_effect=[
(-1, "timeout"),
(0, "List of devices attached\n192.168.5.2:5555 unauthorized\n"),
]):
state, msg = scan.verify_adb_target("/adb", "192.168.5.2:5555")
assert state == "unauthorized"
assert "unauthorized" in msg
class TestDiscoverMdnsTargets:
def test_parse_ipv4_targets(self):
@@ -334,7 +352,8 @@ class TestDiscoverAdbDevices:
assert devs[0].model == ""
def test_no_subnet_returns_empty(self):
with patch.object(scan, "get_local_subnet", return_value=None):
with patch.object(scan, "get_local_subnets", return_value=[]), \
patch.object(scan, "get_local_subnet", return_value=None):
devs = scan.discover_adb_devices("/adb")
assert devs == []
@@ -419,3 +438,93 @@ class TestDiscoverAdbDevices:
assert devs[1].port == 37001
assert devs[0].target == "192.168.5.2:5555"
assert devs[1].target == "192.168.5.2:37001"
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")), \
patch.object(scan, "scan_open_ports", side_effect=AssertionError("should not scan ports")):
devs = scan.discover_adb_devices("/adb")
assert len(devs) == 1
assert devs[0].target == "192.168.10.103:37697"
assert devs[0].model == "Xiaomi 14"
assert devs[0].adb_state == "connected"
def test_last_port_hint_added_to_base_scan_ports(self):
captured_ports = []
def fake_scan_ports(ips, **kwargs):
captured_ports.append(list(kwargs.get("ports") or []))
return []
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, "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]
def test_hi_port_fallback_uses_sample_then_full_per_host(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)]
with patch.object(scan, "get_local_subnets", return_value=["192.168.10.0/30"]), \
patch("gui.gui_core_pkg.config.get_last_wifi_target", return_value={}), \
patch.object(scan, "discover_mdns_targets", 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="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)
def test_hi_port_fallback_still_runs_when_last_port_hint_added(self):
calls = []
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:
return [("192.168.10.55", 40123)]
return []
with patch.object(scan, "get_local_subnets", return_value=["192.168.10.0/30"]), \
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, "discover_mdns_targets", 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="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:])
+1 -1
View File
@@ -210,7 +210,7 @@ async function wifiScan() {
});
});
}
if (status) status.textContent = `扫描完成,发现 ${devs.length} 台设备`;
if (status) status.textContent = `扫描完成 (${subnetLabel}),发现 ${devs.length} 台设备`;
} catch (e) {
appendLog([`[WiFi ADB] 扫描异常: ${e}`]);
if (status) status.textContent = `扫描异常: ${e}`;