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(