limit wifi adb reconnect to lightweight ports

This commit is contained in:
Your Name committed 2026-06-05 15:45:37 +08:00
1 parent e3bf99149d
commit cd7615db3c
6 files changed
+229 -31

No files matched your search

+42 -2
View File
@@ -86,6 +86,18 @@ def try_reconnect_last_wifi(
on_line(f"[启动] 尝试重连上次的 WiFi 设备: {target} ...")
def worker():
light_ports: list[int] = []
last_ip = ""
try:
if ":" in target:
last_ip, port_s = target.rsplit(":", 1)
light_ports.append(int(port_s))
except Exception:
last_ip = ""
for candidate in (5555, 44219):
if candidate not in light_ports:
light_ports.append(candidate)
# 先直连
state, msg = "failed", ""
try:
@@ -112,6 +124,34 @@ def try_reconnect_last_wifi(
_safe_after(root, render_unauth, fallback=render_unauth)
return
# 先对同一个 IP 做轻量端口探测,避免直接进子网扫描。
if last_ip and light_ports:
for probe_port in light_ports:
probe_target = f"{last_ip}:{probe_port}"
if probe_target == target:
continue
try:
probe_state, _probe_msg = verify_adb_target(adb_exe, probe_target)
except Exception:
probe_state = "failed"
if probe_state != "connected":
continue
def render_same_ip_hit(probe_target=probe_target):
refresh_devices()
device_var.set(probe_target)
try:
set_last_wifi_target(probe_target, model)
except Exception:
pass
on_line(
f"[启动] 上次 IP 命中轻量端口 {probe_target}"
+ (f" ({model})" if model else "")
)
_safe_after(root, render_same_ip_hit, fallback=render_same_ip_hit)
return
# state == "failed" → 不可达。换网了?自动扫一下,看能不能在新网段找到
def notify_scan_start():
on_line(
@@ -120,8 +160,8 @@ def try_reconnect_last_wifi(
_safe_after(root, notify_scan_start, fallback=notify_scan_start)
try:
# 自动模式会先验证上次目标,再对在线候选主机补扫完整端口段。
devs = discover_adb_devices(adb_exe)
# 自动模式先对同 IP 轻量探测,失败后再对子网做轻量候选端口发现。
devs = discover_adb_devices(adb_exe, ports=light_ports)
except Exception as e:
def render_scan_err():
on_line(f"[启动] 自动扫描失败: {e}")
+39 -11
View File
@@ -11,8 +11,9 @@ from __future__ import annotations
import json
import os
import shutil
import threading
import time
import uuid
from douyin.core import path_config
@@ -27,6 +28,41 @@ def read_config() -> dict:
return json.load(f)
def _atomic_write_json(path: str, data: dict, *, retries: int = 5, retry_delay: float = 0.05) -> None:
dir_path = os.path.dirname(path) or "."
base_name = os.path.basename(path)
thread_id = threading.get_ident()
tmp_path = os.path.join(
dir_path,
f"{base_name}.{os.getpid()}.{thread_id}.{uuid.uuid4().hex[:8]}.tmp",
)
try:
with open(tmp_path, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=4)
f.write("\n")
last_error: Exception | None = None
for attempt in range(retries):
try:
os.replace(tmp_path, path)
return
except (PermissionError, OSError) as exc:
last_error = exc
if attempt >= retries - 1:
raise
time.sleep(retry_delay * (attempt + 1))
if last_error is not None:
raise last_error
finally:
try:
if os.path.exists(tmp_path):
os.remove(tmp_path)
except Exception:
pass
def write_config(cfg: dict) -> None:
@@ -54,11 +90,7 @@ def write_config(cfg: dict) -> None:
merged = _deep_merge(merged, cfg)
except Exception:
pass
tmp_path = CONFIG_PATH + ".tmp"
with open(tmp_path, "w", encoding="utf-8") as f:
json.dump(merged, f, ensure_ascii=False, indent=4)
f.write("\n")
os.replace(tmp_path, CONFIG_PATH)
_atomic_write_json(CONFIG_PATH, merged)
# ============================================================
@@ -128,11 +160,7 @@ def clear_last_wifi_target() -> None:
try:
cfg.pop(_LAST_WIFI_KEY, None)
# write_config 会做 merge,但 merge 不删键,所以这里直接覆盖写
tmp_path = CONFIG_PATH + ".tmp"
with open(tmp_path, "w", encoding="utf-8") as f:
json.dump(cfg, f, ensure_ascii=False, indent=4)
f.write("\n")
os.replace(tmp_path, CONFIG_PATH)
_atomic_write_json(CONFIG_PATH, cfg)
except Exception:
pass
+12 -9
View File
@@ -447,21 +447,24 @@ def _build_full_hi_port_range(last_port_hint: Optional[int] = None) -> list[int]
return out
def _build_full_port_range(last_port_hint: Optional[int] = None) -> list[int]:
"""完整端口段,仅用于少量在线候选主机,优先保证不漏随机端口。"""
def _build_quick_port_candidates(last_port_hint: Optional[int] = None) -> list[int]:
"""为同一候选 IP 构造轻量候选端口集合,避免完整端口扫描卡死。"""
out: list[int] = []
seen: set[int] = set()
preferred = [last_port_hint, DEFAULT_ADB_PORT]
preferred = [
last_port_hint,
DEFAULT_ADB_PORT,
44219,
37001,
37719,
39601,
]
for maybe_port in preferred:
if not isinstance(maybe_port, int):
continue
if FULL_PORT_MIN <= maybe_port <= FULL_PORT_MAX and maybe_port not in seen:
seen.add(maybe_port)
out.append(maybe_port)
for p in range(FULL_PORT_MIN, FULL_PORT_MAX + 1):
if p in seen:
continue
out.append(p)
return out
@@ -866,11 +869,11 @@ def discover_adb_devices(
mdns_targets=mdns_targets,
max_hosts=MAX_QUICK_HOSTS,
)
quick_ports = _build_full_port_range(last_port_hint)
quick_ports = _build_quick_port_candidates(last_port_hint)
if quick_hosts and quick_ports:
if on_phase:
try:
on_phase(f"完整补扫 {len(quick_hosts)} 台在线候选 × {len(quick_ports)} 个端口")
on_phase(f"轻量补扫 {len(quick_hosts)} 台在线候选 × {len(quick_ports)} 个候选端口")
except Exception:
pass
quick_open_targets = scan_open_ports(
+19
View File
@@ -82,6 +82,25 @@ class TestSetGetClearLastWifiTarget:
assert data.get("y_pianyi") == 100
assert data["last_wifi_target"]["target"] == "192.168.5.2:5555"
def test_clear_retries_replace_on_permission_error(self, temp_config, monkeypatch):
cfg_mod.set_last_wifi_target("192.168.5.2:5555", "PEPM00")
real_replace = cfg_mod.os.replace
calls = {"count": 0}
def flaky_replace(src, dst):
calls["count"] += 1
if calls["count"] == 1:
raise PermissionError("locked")
return real_replace(src, dst)
monkeypatch.setattr(cfg_mod.os, "replace", flaky_replace)
cfg_mod.clear_last_wifi_target()
data = json.loads(temp_config.read_text(encoding="utf-8"))
assert "last_wifi_target" not in data
assert calls["count"] >= 2
class TestGetLastWifiTargetRobustness:
def test_corrupted_value_returns_empty(self, temp_config):
+108
View File
@@ -0,0 +1,108 @@
from __future__ import annotations
import time
from unittest.mock import MagicMock, patch
from gui.components import wifi_adb_reconnect as reconnect
class _Root:
def after(self, _delay, callback):
callback()
class _Var:
def __init__(self):
self.value = ""
def set(self, value):
self.value = value
def _wait_until(predicate, timeout: float = 1.0) -> bool:
deadline = time.time() + timeout
while time.time() < deadline:
if predicate():
return True
time.sleep(0.01)
return bool(predicate())
def test_try_reconnect_last_wifi_uses_lightweight_discover(monkeypatch):
logs = []
captured = {}
monkeypatch.setattr(reconnect, "get_last_wifi_target", lambda: {"target": "192.168.10.105:44219", "model": "PEPM00"})
monkeypatch.setattr(reconnect, "list_adb_devices", lambda _adb: [])
monkeypatch.setattr(reconnect, "verify_adb_target", lambda _adb, _target: ("failed", "refused"))
def fake_discover(_adb, **kwargs):
captured.update(kwargs)
return []
monkeypatch.setattr(reconnect, "discover_adb_devices", fake_discover)
reconnect.try_reconnect_last_wifi(
_Root(),
adb_exe="adb",
device_var=_Var(),
on_line=logs.append,
refresh_devices=lambda: None,
)
assert captured.get("ports") == [44219, 5555]
def test_try_reconnect_last_wifi_picks_exact_verified_target_without_scan(monkeypatch):
device_var = _Var()
logs = []
monkeypatch.setattr(reconnect, "get_last_wifi_target", lambda: {"target": "192.168.10.105:44219", "model": "PEPM00"})
monkeypatch.setattr(reconnect, "list_adb_devices", lambda _adb: [])
monkeypatch.setattr(reconnect, "verify_adb_target", lambda _adb, _target: ("connected", "ok"))
monkeypatch.setattr(reconnect, "discover_adb_devices", lambda *_a, **_k: (_ for _ in ()).throw(AssertionError("should not scan")))
reconnect.try_reconnect_last_wifi(
_Root(),
adb_exe="adb",
device_var=device_var,
on_line=logs.append,
refresh_devices=lambda: None,
)
assert device_var.value == "192.168.10.105:44219"
assert any("自动重连成功" in line for line in logs)
def test_try_reconnect_last_wifi_hits_same_ip_lightweight_port_before_discover(monkeypatch):
device_var = _Var()
logs = []
calls = []
monkeypatch.setattr(reconnect, "get_last_wifi_target", lambda: {"target": "192.168.10.105:39021", "model": "PEPM00"})
monkeypatch.setattr(reconnect, "list_adb_devices", lambda _adb: [])
def fake_verify(_adb, target):
calls.append(target)
if target == "192.168.10.105:44219":
return ("connected", "ok")
return ("failed", "refused")
monkeypatch.setattr(reconnect, "verify_adb_target", fake_verify)
monkeypatch.setattr(reconnect, "discover_adb_devices", lambda *_a, **_k: (_ for _ in ()).throw(AssertionError("should not discover")))
reconnect.try_reconnect_last_wifi(
_Root(),
adb_exe="adb",
device_var=device_var,
on_line=logs.append,
refresh_devices=lambda: None,
)
assert calls[:3] == [
"192.168.10.105:39021",
"192.168.10.105:5555",
"192.168.10.105:44219",
]
assert _wait_until(lambda: device_var.value == "192.168.10.105:44219")
assert _wait_until(lambda: any("上次 IP 命中轻量端口" in line for line in logs))
+9 -9
View File
@@ -462,7 +462,7 @@ class TestDiscoverAdbDevices:
assert devs[0].model == "Xiaomi 14"
assert devs[0].adb_state == "connected"
def test_last_port_hint_added_to_base_scan_ports(self):
def test_last_port_hint_added_to_lightweight_scan_ports(self):
captured_ports = []
def fake_scan_ports(ips, **kwargs):
@@ -478,12 +478,12 @@ class TestDiscoverAdbDevices:
assert captured_ports
assert captured_ports[0][0] == 37697
assert captured_ports[0][1] == 5555
assert 5555 in captured_ports[0]
assert 44219 in captured_ports[0]
assert len(captured_ports[0]) == 65535
assert len(captured_ports[0]) <= 8
assert captured_ports[1] == [5555]
def test_auto_mode_full_port_scan_before_base_5555(self):
def test_auto_mode_lightweight_port_scan_before_base_5555(self):
calls = []
def fake_scan_ports(ips, **kwargs):
@@ -506,7 +506,7 @@ class TestDiscoverAdbDevices:
assert calls[0][0] == ["192.168.10.55"]
assert calls[0][1][0] == scan.DEFAULT_ADB_PORT
assert 44219 in calls[0][1]
assert len(calls[0][1]) == 65535
assert len(calls[0][1]) <= 8
assert calls[1][1] == [5555]
def test_hi_port_fallback_still_runs_when_last_port_hint_added(self):
@@ -532,12 +532,12 @@ class TestDiscoverAdbDevices:
assert calls[0][0] == ["192.168.10.2", "192.168.10.55"]
assert calls[0][1][0] == 37697
assert 44219 in calls[0][1]
assert len(calls[0][1]) == 65535
assert len(calls[0][1]) <= 8
assert calls[1][1] == [5555]
def test_full_port_scan_covers_44219(self):
ports = scan._build_full_port_range()
def test_lightweight_port_scan_covers_common_wifi_adb_ports(self):
ports = scan._build_quick_port_candidates()
assert len(ports) == 65535
assert ports[0] == scan.DEFAULT_ADB_PORT
assert 44219 in ports
assert len(ports) <= 8