feat(web_gui): WebUI 启动时自动重连上次 WiFi 设备 + 智能匹配

新增 /api/wifi/auto-reconnect 端点,把桌面 GUI 的 _try_reconnect_last_wifi
逻辑搬到服务端:先 verify_adb_target 上次的 target → 失败则 discover_adb_devices
扫描 + pick_best_match 智能匹配。返回结构化 JSON 让前端渲染:

  action: noop | already_online | reconnected | matched | failed
  target / model / message / devices

webui/app.js DOMContentLoaded 末尾调用 tryAutoReconnectLastWifi(),
不阻塞页面加载。命中后自动刷新设备下拉并选中。

至此桌面 GUI 和 WebUI 在 WiFi 重连体验上完全对齐:换网段也能找回手机。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
CodexandClaude Opus 4.7 committed 2026-05-22 20:53:23 +08:00
1 parent 5966f461c3
commit cea3aced73
2 files changed
+210

No files matched your search

+166
View File
@@ -2167,6 +2167,172 @@ class Handler(BaseHTTPRequestHandler):
{"ok": False, "error": str(e)}, status=500
)
if u.path == "/api/wifi/auto-reconnect":
"""启动自动重连:先 verify 上次的 target,失败则扫描子网 + 智能匹配。
返回:
{
"ok": true,
"action": "noop" | "already_online" | "reconnected" | "matched" | "failed",
"target": "192.168.5.2:5555", # 当前选定的 target,可能为空
"model": "PEPM00", # 选中的 model,可能为空
"message": "...",
"devices": [...] # 扫描候选(仅 action 是 matched/failed 时返回)
}
"""
try:
from gui.gui_core_pkg import (
discover_adb_devices,
get_last_wifi_target,
pick_best_match,
set_last_wifi_target,
)
from gui.gui_core_pkg.wifi_adb_scan import verify_adb_target
except Exception as e:
return self._send_json(
{"ok": False, "error": f"import failed: {e}"}, status=500
)
adb = find_adb_executable()
last = get_last_wifi_target() or {}
target = str(last.get("target") or "")
model = str(last.get("model") or "")
if not target:
return self._send_json(
{
"ok": True,
"action": "noop",
"target": "",
"model": "",
"message": "无上次记录",
}
)
existing = list_adb_devices(adb) if adb else []
if target in existing:
return self._send_json(
{
"ok": True,
"action": "already_online",
"target": target,
"model": model,
"message": f"WiFi 设备已在线: {target}",
}
)
if existing:
return self._send_json(
{
"ok": True,
"action": "noop",
"target": existing[0],
"model": "",
"message": (
f"当前已有设备 {existing[0]},"
f"上次 WiFi 目标 {target} 不抢占"
),
}
)
# 直连
try:
state, _ = verify_adb_target(adb, target)
except Exception as e:
state = "failed"
_ = str(e)
if state == "connected":
return self._send_json(
{
"ok": True,
"action": "reconnected",
"target": target,
"model": model,
"message": f"自动重连成功: {target}",
}
)
if state == "unauthorized":
return self._send_json(
{
"ok": True,
"action": "failed",
"target": target,
"model": model,
"message": (
f"上次设备 {target} 未授权,请在手机上确认 ADB 调试授权"
),
}
)
# 不可达 → 扫描 + 智能匹配
try:
devs = discover_adb_devices(adb)
except Exception as e:
return self._send_json(
{
"ok": False,
"error": f"自动扫描失败: {e}",
},
status=500,
)
best = pick_best_match(devs, last)
payload_devs = [
{
"target": d.target,
"ip": d.ip,
"port": d.port,
"state": d.adb_state,
"model": d.model,
}
for d in devs
]
if best is None:
return self._send_json(
{
"ok": True,
"action": "failed",
"target": target,
"model": model,
"message": (
f"上次目标 {target} 不可达,"
f"扫描发现 {len(devs)} 台候选但无明确匹配"
if devs
else (
f"上次目标 {target} 不可达,扫描也未发现其它设备。"
f"请检查手机和电脑是否在同一 WiFi"
)
),
"devices": payload_devs,
}
)
# 命中:更新记忆并返回
try:
set_last_wifi_target(best.target, best.model or model)
except Exception:
pass
if best.target == target:
msg = f"自动重连成功(扫描确认): {best.target}"
else:
msg = (
f"上次目标 {target} 已变 → 智能匹配到 {best.target}"
+ (f" ({best.model})" if best.model else "")
+ "(已更新记忆)"
)
return self._send_json(
{
"ok": True,
"action": "matched",
"target": best.target,
"model": best.model or "",
"message": msg,
"devices": payload_devs,
}
)
if u.path == "/api/test-yanghao":
if RUNNER.is_running():
return self._send_json({"ok": False, "error": "running"}, status=409)
+44
View File
@@ -1853,6 +1853,47 @@ async function wifiDisconnect() {
setTextIfExists("wifiStatus", result.message || "断开命令已执行");
}
async function tryAutoReconnectLastWifi() {
// 启动时调一次 /api/wifi/auto-reconnect。后端做完所有判断(已在线 / 重连成功 /
// 智能匹配 / 失败),前端只负责把结果反馈到日志和设备下拉。
try {
const resp = await apiPost("/api/wifi/auto-reconnect", {});
if (!resp || resp.ok === false) return;
const action = resp.action || "noop";
if (action === "noop") return;
if (action === "already_online" || action === "reconnected" || action === "matched") {
try {
await refreshDevices();
} catch (_) {}
const sel = $("device");
if (sel && resp.target) {
// 选中设备到下拉框
for (const opt of sel.options) {
if (opt.value === resp.target) {
sel.value = resp.target;
break;
}
}
}
const status = $("wifiStatus");
if (status && resp.message) status.textContent = resp.message;
appendLog([`[启动] ${resp.message || action}`]);
return;
}
if (action === "failed") {
appendLog([`[启动] ${resp.message || "WiFi 自动重连失败"}`]);
const status = $("wifiStatus");
if (status && resp.message) status.textContent = resp.message;
return;
}
} catch (e) {
// 启动期任何异常都不打扰用户
console.warn("auto-reconnect failed", e);
}
}
async function wifiScan() {
const btn = $("btnWifiScan");
const status = $("wifiStatus");
@@ -2667,6 +2708,9 @@ window.addEventListener("DOMContentLoaded", async () => {
await refreshDevices();
await loadConfig();
// 启动时若无设备 + 有上次 WiFi 记录 → 后台自动重连(不阻塞)
tryAutoReconnectLastWifi();
startPolling();
startStatsPolling();
startShotPolling();