From a71f6faed0e3c55df0c6f3977dc59f31c8347da6 Mon Sep 17 00:00:00 2001 From: Codex Date: Fri, 22 May 2026 20:16:37 +0800 Subject: [PATCH] =?UTF-8?q?feat(wifi=5Fadb):=20=E8=AE=B0=E4=BD=8F=E4=B8=8A?= =?UTF-8?q?=E6=AC=A1=E6=88=90=E5=8A=9F=E7=9A=84=20WiFi=20=E8=AE=BE?= =?UTF-8?q?=E5=A4=87=EF=BC=8CGUI=20=E5=90=AF=E5=8A=A8=E6=97=B6=E8=87=AA?= =?UTF-8?q?=E5=8A=A8=E9=87=8D=E8=BF=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增 gui/gui_core_pkg/config.py 三个 helper: - get_last_wifi_target / set_last_wifi_target / clear_last_wifi_target 配置以 last_wifi_target = {target, model, saved_at} 形式存在 config.json 顶层。 GUI 行为: - "扫描 WiFi" 选中或自动连上一台 connected 设备 → 写入 last_wifi_target - WiFi 选择对话框"使用选中"也写入 - 主窗口启动后延迟 300ms 后台尝试 verify_adb_target(last.target) - 已有设备:不打扰 - 重连成功:自动设为当前设备 - unauthorized:提示需手机端授权 - 不可达:提示换网了,引导点'扫描 WiFi' 新增 12 个 last_wifi_target 单元测试覆盖读写/清除/损坏值/缺文件等场景。 Co-Authored-By: Claude Opus 4.7 (1M context) --- gui/gui_app.py | 91 ++++++++++++++++++++++++- gui/gui_core_pkg/__init__.py | 6 ++ gui/gui_core_pkg/config.py | 76 +++++++++++++++++++++ tests/test_last_wifi_target.py | 118 +++++++++++++++++++++++++++++++++ 4 files changed, 290 insertions(+), 1 deletion(-) create mode 100644 tests/test_last_wifi_target.py diff --git a/gui/gui_app.py b/gui/gui_app.py index 601514a..7e3f359 100644 --- a/gui/gui_app.py +++ b/gui/gui_app.py @@ -35,9 +35,13 @@ from gui.gui_core import ( ) from gui.gui_core_pkg import ( DiscoveredDevice, + clear_last_wifi_target, discover_adb_devices, + get_last_wifi_target, get_local_subnet, + set_last_wifi_target, ) +from gui.gui_core_pkg.wifi_adb_scan import verify_adb_target, query_device_model from douyin.core.path_config import get_logs_dir from gui.components.mapping_table import create_mapping_tab @@ -342,6 +346,76 @@ def main(): scan_connect_btn.pack(side=LEFT, padx=(0, 20)) _scan_busy = {"flag": False} + def _try_reconnect_last_wifi(): + """启动时若 adb devices 为空且配置里有 last_wifi_target,后台尝试重连。 + + 策略: + - 已经有可用设备:什么都不做 + - 上次记录的 target 当前已 connected:直接选中作为当前设备 + - 否则后台 adb connect 一次;成功 → 选中;失败 → 日志提示但不打扰 + """ + last = {} + try: + last = get_last_wifi_target() + except Exception: + return + if not isinstance(last, dict) or not last.get("target"): + return + + target = str(last.get("target")) + model = str(last.get("model") or "") + + # 已经有设备时不打扰 + try: + existing = list_adb_devices(adb_exe) + except Exception: + existing = [] + if target in existing: + device_var.set(target) + on_line(f"[启动] WiFi 设备已在线: {target}" + (f" ({model})" if model else "")) + return + if existing: + on_line( + f"[启动] 当前已有设备 {existing[0]},上次 WiFi 目标 {target} 不抢占" + ) + return + + on_line(f"[启动] 尝试重连上次的 WiFi 设备: {target} ...") + + def worker(): + state, msg = "failed", "" + try: + state, msg = verify_adb_target(adb_exe, target) + except Exception as e: + msg = str(e) + + def render(): + if state == "connected": + refresh_devices() + device_var.set(target) + on_line( + f"[启动] 自动重连成功: {target}" + + (f" ({model})" if model else "") + ) + elif state == "unauthorized": + on_line( + f"[启动] 上次设备 {target} 未授权,请在手机上确认 ADB 调试" + ) + else: + on_line( + f"[启动] 上次设备 {target} 不可达,可能换网了。提示:点'扫描 WiFi'重新发现" + ) + + try: + root.after(0, render) + except Exception: + pass + + threading.Thread(target=worker, daemon=True).start() + + # 启动时延迟一点,等界面创建完成再尝试重连 + root.after(300, _try_reconnect_last_wifi) + def _on_scan_one_click(): """主窗口"扫描 WiFi"按钮:后台扫描 → 按结果数智能处理。 @@ -391,9 +465,15 @@ def main(): d = connected[0] refresh_devices() device_var.set(d.target) + # 记住,下次启动自动重连 + try: + set_last_wifi_target(d.target, d.model or "") + except Exception: + pass on_line( f"[扫描] 自动连接成功: {d.target}" + (f" ({d.model})" if d.model else "") + + "(已记住,下次 GUI 启动会自动重连)" ) return @@ -448,6 +528,9 @@ def main(): values = tree.item(sel[0])["values"] target = str(values[0]) state = str(values[1]) + model = str(values[2] or "").strip() + if model == "-": + model = "" if state != "connected": on_line( f"[扫描] {target} 当前状态={state},请先在手机上授权后重试" @@ -455,7 +538,13 @@ def main(): return refresh_devices() device_var.set(target) - on_line(f"[扫描] 已设为当前设备: {target}") + try: + set_last_wifi_target(target, model) + except Exception: + pass + on_line( + f"[扫描] 已设为当前设备: {target}(已记住,下次 GUI 启动会自动重连)" + ) pick_dlg.destroy() ttk.Button(bottom, text="使用选中", command=use_selected).pack(side=LEFT) diff --git a/gui/gui_core_pkg/__init__.py b/gui/gui_core_pkg/__init__.py index 4bea8ca..9a018e6 100644 --- a/gui/gui_core_pkg/__init__.py +++ b/gui/gui_core_pkg/__init__.py @@ -33,7 +33,10 @@ from .wifi_adb_scan import ( ) from .config import ( CONFIG_PATH, + clear_last_wifi_target, + get_last_wifi_target, read_config, + set_last_wifi_target, write_config, ) from .run_params import RunParams @@ -56,5 +59,8 @@ __all__ = [ "CONFIG_PATH", "read_config", "write_config", + "get_last_wifi_target", + "set_last_wifi_target", + "clear_last_wifi_target", "RunParams", ] diff --git a/gui/gui_core_pkg/config.py b/gui/gui_core_pkg/config.py index 78314dd..22cc996 100644 --- a/gui/gui_core_pkg/config.py +++ b/gui/gui_core_pkg/config.py @@ -3,6 +3,9 @@ - CONFIG_PATH config.json 绝对路径 - read_config 读取并返回 dict - write_config 深度合并写回(保留未传字段) +- get_last_wifi_target 读上次成功连接的 WiFi 目标(ip:port / ip / 空) +- set_last_wifi_target 写入上次成功连接的 WiFi 目标 +- clear_last_wifi_target 清除记录 """ from __future__ import annotations @@ -44,3 +47,76 @@ def write_config(cfg: dict) -> None: f.write("\n") +# ============================================================ +# last_wifi_target 持久化(GUI 扫描成功后保存,下次启动自动重连) +# ============================================================ + +_LAST_WIFI_KEY = "last_wifi_target" + + +def get_last_wifi_target() -> dict: + """返回上次成功连接的 WiFi 目标(dict);没有返回空 dict。 + + 存储格式(在 config.json 顶层): + "last_wifi_target": { + "target": "192.168.5.2:5555", + "model": "PEPM00", + "saved_at": 1717000000 + } + """ + try: + cfg = read_config() + except Exception: + return {} + if not isinstance(cfg, dict): + return {} + val = cfg.get(_LAST_WIFI_KEY) + if isinstance(val, dict) and val.get("target"): + return dict(val) + return {} + + +def set_last_wifi_target(target: str, model: str = "") -> None: + """保存上次成功连接的 WiFi 目标。 + + target 必须是 ip:port 形式;空字符串等价于 clear_last_wifi_target。 + """ + target = (target or "").strip() + if not target: + clear_last_wifi_target() + return + + import time + + try: + write_config( + { + _LAST_WIFI_KEY: { + "target": target, + "model": (model or "").strip(), + "saved_at": int(time.time()), + } + } + ) + except Exception: + pass + + +def clear_last_wifi_target() -> None: + """从配置里删除 last_wifi_target 记录。""" + try: + cfg = read_config() + except Exception: + return + if not isinstance(cfg, dict) or _LAST_WIFI_KEY not in cfg: + return + try: + cfg.pop(_LAST_WIFI_KEY, None) + # write_config 会做 merge,但 merge 不删键,所以这里直接覆盖写 + with open(CONFIG_PATH, "w", encoding="utf-8") as f: + json.dump(cfg, f, ensure_ascii=False, indent=4) + f.write("\n") + except Exception: + pass + + diff --git a/tests/test_last_wifi_target.py b/tests/test_last_wifi_target.py new file mode 100644 index 0000000..85ec143 --- /dev/null +++ b/tests/test_last_wifi_target.py @@ -0,0 +1,118 @@ +"""last_wifi_target 持久化 helper 单元测试。 + +覆盖: +- set_last_wifi_target 写入;get 读到正确字段 +- set_last_wifi_target("") 等价于 clear +- clear_last_wifi_target 删除已有键不影响其他键 +- 读不到键时 get 返回空 dict +- 损坏的键值(非 dict / 缺 target)返回空 dict +""" +from __future__ import annotations + +import json +from pathlib import Path +from unittest.mock import patch + +import pytest + +from gui.gui_core_pkg import config as cfg_mod + + +@pytest.fixture +def temp_config(tmp_path, monkeypatch): + """把 CONFIG_PATH 临时指向 tmp_path/config.json。""" + p = tmp_path / "config.json" + p.write_text("{}", encoding="utf-8") + monkeypatch.setattr(cfg_mod, "CONFIG_PATH", str(p)) + return p + + +class TestSetGetClearLastWifiTarget: + def test_initial_empty(self, temp_config): + assert cfg_mod.get_last_wifi_target() == {} + + def test_set_and_get(self, temp_config): + cfg_mod.set_last_wifi_target("192.168.5.2:5555", "PEPM00") + result = cfg_mod.get_last_wifi_target() + assert result["target"] == "192.168.5.2:5555" + assert result["model"] == "PEPM00" + assert isinstance(result.get("saved_at"), int) + assert result["saved_at"] > 0 + + def test_set_overwrites(self, temp_config): + cfg_mod.set_last_wifi_target("10.0.0.1:5555", "old") + cfg_mod.set_last_wifi_target("192.168.5.2:5555", "new") + result = cfg_mod.get_last_wifi_target() + assert result["target"] == "192.168.5.2:5555" + assert result["model"] == "new" + + def test_set_empty_clears(self, temp_config): + cfg_mod.set_last_wifi_target("192.168.5.2:5555", "PEPM00") + cfg_mod.set_last_wifi_target("", "") + assert cfg_mod.get_last_wifi_target() == {} + + def test_clear_removes_key(self, temp_config): + cfg_mod.set_last_wifi_target("192.168.5.2:5555", "PEPM00") + cfg_mod.clear_last_wifi_target() + assert cfg_mod.get_last_wifi_target() == {} + # 文件里不应再有 last_wifi_target 键 + data = json.loads(temp_config.read_text(encoding="utf-8")) + assert "last_wifi_target" not in data + + def test_clear_preserves_other_keys(self, temp_config): + # 先写入其它配置 + temp_config.write_text( + json.dumps({"theme": "dark", "y_pianyi": 100}), encoding="utf-8" + ) + cfg_mod.set_last_wifi_target("192.168.5.2:5555", "PEPM00") + cfg_mod.clear_last_wifi_target() + # 其他键应保留 + data = json.loads(temp_config.read_text(encoding="utf-8")) + assert data.get("theme") == "dark" + assert data.get("y_pianyi") == 100 + assert "last_wifi_target" not in data + + def test_set_preserves_other_keys(self, temp_config): + temp_config.write_text( + json.dumps({"theme": "dark", "y_pianyi": 100}), encoding="utf-8" + ) + cfg_mod.set_last_wifi_target("192.168.5.2:5555", "PEPM00") + data = json.loads(temp_config.read_text(encoding="utf-8")) + assert data.get("theme") == "dark" + assert data.get("y_pianyi") == 100 + assert data["last_wifi_target"]["target"] == "192.168.5.2:5555" + + +class TestGetLastWifiTargetRobustness: + def test_corrupted_value_returns_empty(self, temp_config): + """value 不是 dict 时返回空 dict。""" + temp_config.write_text( + json.dumps({"last_wifi_target": "not a dict"}), encoding="utf-8" + ) + assert cfg_mod.get_last_wifi_target() == {} + + def test_dict_without_target_returns_empty(self, temp_config): + """dict 但缺 target 字段 → 视为无效。""" + temp_config.write_text( + json.dumps({"last_wifi_target": {"model": "X", "saved_at": 0}}), + encoding="utf-8", + ) + assert cfg_mod.get_last_wifi_target() == {} + + def test_missing_config_file(self, tmp_path, monkeypatch): + """配置文件不存在时 get 返回空 dict 不抛异常。""" + non_existent = tmp_path / "no_such_config.json" + monkeypatch.setattr(cfg_mod, "CONFIG_PATH", str(non_existent)) + assert cfg_mod.get_last_wifi_target() == {} + + def test_set_with_whitespace_target(self, temp_config): + """target 周围空白应被 strip 后再处理。""" + cfg_mod.set_last_wifi_target(" 192.168.5.2:5555 ", "PEPM00") + result = cfg_mod.get_last_wifi_target() + assert result["target"] == "192.168.5.2:5555" + + def test_set_whitespace_only_clears(self, temp_config): + """target 全是空白等价于清除。""" + cfg_mod.set_last_wifi_target("192.168.5.2:5555", "X") + cfg_mod.set_last_wifi_target(" ", "") + assert cfg_mod.get_last_wifi_target() == {}