Fallback WiFi ADB connect to mdns port

This commit is contained in:
Your Name committed 2026-06-23 01:08:03 +08:00
1 parent 20e438ee13
commit 84b9143fa6
4 files changed
+118 -42

No files matched your search

+80 -42
View File
@@ -19,6 +19,63 @@ from typing import Optional
from .adb import find_adb_executable, list_adb_devices
def _discover_mdns_connect_targets(adb_exe: str) -> list[tuple[str, int]]:
try:
from .wifi_adb_scan import discover_mdns_targets
return discover_mdns_targets(adb_exe)
except Exception:
return []
def _connect_wifi_adb_once(adb_exe: str, target: str) -> tuple[bool, str, str]:
"""Run one adb connect and return (ok, message, raw_output)."""
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 "")).strip()
low = output.lower()
# adb connect 在很多失败场景下 returncode 也是 0,必须看输出文本
# 失败关键词优先判断
for fail_kw in (
"failed to authenticate",
"unauthorized",
"cannot connect",
"unable to connect",
"connection refused",
"no route to host",
"host is down",
"operation timed out",
"cannot resolve",
):
if fail_kw in low:
# 给"未授权"特别清晰的提示
if "authenticate" in low or "unauthorized" in low:
return False, (
f"未授权: {target} 尚未授权 ADB 调试。"
f"请在手机上确认弹窗(勾选'始终允许这台电脑调试'),然后重试。"
), output
return False, f"连接失败: {output}", output
if "connected" in low or "already connected" in low:
return True, f"成功连接到 {target}", output
# 兜底:returncode 非 0 视为失败
if proc.returncode != 0:
return False, f"连接失败: {output or '未知错误'}", output
# returncode == 0 但输出未匹配关键词(罕见),按成功处理但提示
return True, f"已发送连接请求到 {target}: {output}", output
def is_device_wifi_connected(adb_exe: str, device_id: str) -> bool:
"""检查设备是否已经在WiFi ADB模式下连接
@@ -121,51 +178,32 @@ def connect_wifi_adb(
# 支持 ip:port 或单纯 ip 的两种情况
target = ip_address if ":" in ip_address else 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,
)
ok, msg, output = _connect_wifi_adb_once(adb_exe, target)
if ok:
return True, msg
output = ((proc.stdout or "") + "\n" + (proc.stderr or "")).strip()
low = output.lower()
# adb connect 在很多失败场景下 returncode 也是 0,必须看输出文本
# 失败关键词优先判断
for fail_kw in (
"failed to authenticate",
"unauthorized",
"cannot connect",
"unable to connect",
"connection refused",
"no route to host",
"host is down",
"operation timed out",
"cannot resolve",
):
if fail_kw in low:
# 给"未授权"特别清晰的提示
if "authenticate" in low or "unauthorized" in low:
return False, (
f"未授权: {target} 尚未授权 ADB 调试。"
f"请在手机上确认弹窗(勾选'始终允许这台电脑调试'),然后重试。"
# Android 11+ 无线调试会使用 mDNS 随机 connect 端口。
# 用户只填 IP 或默认 5555 失败时,自动尝试同 IP 的 _adb-tls-connect 端口。
host = target.rsplit(":", 1)[0]
explicit_port = ":" in str(ip_address or "")
used_default_port = not explicit_port and str(port or "5555") == "5555"
if used_default_port:
for mdns_ip, mdns_port in _discover_mdns_connect_targets(adb_exe):
if mdns_ip != host:
continue
mdns_target = f"{mdns_ip}:{mdns_port}"
if mdns_target == target:
continue
mdns_ok, mdns_msg, _mdns_output = _connect_wifi_adb_once(
adb_exe, mdns_target
)
if mdns_ok:
return True, (
f"{mdns_msg}(默认端口 {target} 失败后,已自动改用无线调试端口 {mdns_target})"
)
return False, f"连接失败: {output}"
break
if "connected" in low or "already connected" in low:
return True, f"成功连接到 {target}"
# 兜底:returncode 非 0 视为失败
if proc.returncode != 0:
return False, f"连接失败: {output or '未知错误'}"
# returncode == 0 但输出未匹配关键词(罕见),按成功处理但提示
return True, f"已发送连接请求到 {target}: {output}"
return False, msg
except subprocess.TimeoutExpired:
return False, "连接WiFi ADB超时"
+4
View File
@@ -703,6 +703,10 @@ def discover_mdns_targets(adb_exe: str) -> list[tuple[str, int]]:
targets: list[tuple[str, int]] = []
seen: set[tuple[str, int]] = set()
for line in out.splitlines():
if "_adb-tls-pairing" in line:
continue
if "_adb" not in line:
continue
m = re.search(r"(\d{1,3}(?:\.\d{1,3}){3}):(\d{1,5})", line)
if not m:
continue
+24
View File
@@ -165,6 +165,30 @@ class TestConnectWifiAdb:
# adb connect 192.168.5.2:5555
assert captured["cmd"][-1] == "192.168.5.2:5555"
def test_default_port_failure_falls_back_to_mdns_connect_port_for_same_ip(self):
calls = []
def fake_run(cmd, **kwargs):
calls.append(cmd)
target = cmd[-1]
if target == "192.168.10.102:5555":
return _proc("cannot connect to 192.168.10.102:5555", "", 1)
if target == "192.168.10.102:45321":
return _proc("connected to 192.168.10.102:45321", "", 0)
return _proc("unexpected", "", 1)
with patch("subprocess.run", side_effect=fake_run), \
patch(
"gui.gui_core_pkg.wifi_adb._discover_mdns_connect_targets",
return_value=[("192.168.10.102", 45321)],
):
ok, msg = wifi_adb.connect_wifi_adb("/adb", "192.168.10.102")
assert ok is True
assert "192.168.10.102:45321" in msg
assert calls[0][-1] == "192.168.10.102:5555"
assert calls[1][-1] == "192.168.10.102:45321"
class TestDisconnectWifiAdb:
def test_ip_port_input_does_not_duplicate_port(self):
+10
View File
@@ -295,6 +295,16 @@ garbage line
targets = scan.discover_mdns_targets("/adb")
assert targets == [("10.0.0.9", 5555), ("192.168.10.66", 40075)]
def test_ignores_pairing_port_and_keeps_connect_port(self):
sample = """
List of discovered mdns services
adb-1234 _adb-tls-pairing._tcp. 192.168.10.66:35223
adb-1234 _adb-tls-connect._tcp. 192.168.10.66:45321
"""
with patch.object(scan, "_run_adb", return_value=(0, sample)):
targets = scan.discover_mdns_targets("/adb")
assert targets == [("192.168.10.66", 45321)]
def test_empty_on_error(self):
with patch.object(scan, "_run_adb", return_value=(1, "failed")):
assert scan.discover_mdns_targets("/adb") == []