diff --git a/gui/gui_app.py b/gui/gui_app.py index ff6c3e1..92e8d15 100644 --- a/gui/gui_app.py +++ b/gui/gui_app.py @@ -39,6 +39,7 @@ from gui.gui_core_pkg import ( discover_adb_devices, get_last_wifi_target, get_local_subnet, + pick_best_match, set_last_wifi_target, ) from gui.gui_core_pkg.wifi_adb_scan import verify_adb_target, query_device_model @@ -350,9 +351,10 @@ def main(): """启动时若 adb devices 为空且配置里有 last_wifi_target,后台尝试重连。 策略: - - 已经有可用设备:什么都不做 - - 上次记录的 target 当前已 connected:直接选中作为当前设备 - - 否则后台 adb connect 一次;成功 → 选中;失败 → 日志提示但不打扰 + 1. 已经有可用设备:不打扰 + 2. 上次记录的 target 现在 verify_adb_target 成功 → 选中 + 3. verify 失败 → 自动扫描子网 + pick_best_match 智能匹配 + 4. 匹配上 → 选中,更新 last_wifi_target;匹配不上 → 日志提示 """ last = {} try: @@ -383,33 +385,86 @@ def main(): 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": + if state == "connected": + def render_ok(): refresh_devices() device_var.set(target) on_line( f"[启动] 自动重连成功: {target}" + (f" ({model})" if model else "") ) - elif state == "unauthorized": + root.after(0, render_ok) + return + + if state == "unauthorized": + def render_unauth(): on_line( f"[启动] 上次设备 {target} 未授权,请在手机上确认 ADB 调试" ) - else: - on_line( - f"[启动] 上次设备 {target} 不可达,可能换网了。提示:点'扫描 WiFi'重新发现" - ) + root.after(0, render_unauth) + return + + # state == "failed" → 不可达。换网了?自动扫一下,看能不能在新网段找到 + def notify_scan_start(): + on_line( + f"[启动] {target} 不可达,自动扫描局域网寻找匹配设备..." + ) + root.after(0, notify_scan_start) try: - root.after(0, render) - except Exception: - pass + devs = discover_adb_devices(adb_exe) + except Exception as e: + def render_scan_err(): + on_line(f"[启动] 自动扫描失败: {e}") + root.after(0, render_scan_err) + return + + best = pick_best_match(devs, last) + + def render_scan_done(): + if best is None: + if devs: + targets_str = ", ".join( + f"{d.target}({d.adb_state})" for d in devs[:5] + ) + on_line( + f"[启动] 扫描发现 {len(devs)} 台候选但无明确匹配: " + f"{targets_str}。请点'扫描 WiFi'手选" + ) + else: + on_line( + f"[启动] 上次设备 {target} 不可达,扫描也未发现其它设备。" + f"请检查手机和电脑是否在同一 WiFi" + ) + return + + refresh_devices() + device_var.set(best.target) + # 更新记忆 + try: + set_last_wifi_target(best.target, best.model or model) + except Exception: + pass + if best.target == target: + on_line( + f"[启动] 自动重连成功(扫描确认): {best.target}" + + (f" ({best.model})" if best.model else "") + ) + else: + on_line( + f"[启动] 上次目标 {target} 已变 → 智能匹配到 {best.target}" + + (f" ({best.model})" if best.model else "") + + "(已更新记忆)" + ) + + root.after(0, render_scan_done) threading.Thread(target=worker, daemon=True).start() diff --git a/gui/gui_core_pkg/__init__.py b/gui/gui_core_pkg/__init__.py index 9a018e6..acf3607 100644 --- a/gui/gui_core_pkg/__init__.py +++ b/gui/gui_core_pkg/__init__.py @@ -30,6 +30,7 @@ from .wifi_adb_scan import ( discover_adb_devices, get_local_subnet, parse_subnet_spec, + pick_best_match, ) from .config import ( CONFIG_PATH, @@ -56,6 +57,7 @@ __all__ = [ "discover_adb_devices", "get_local_subnet", "parse_subnet_spec", + "pick_best_match", "CONFIG_PATH", "read_config", "write_config", diff --git a/gui/gui_core_pkg/wifi_adb_scan.py b/gui/gui_core_pkg/wifi_adb_scan.py index 09bafdd..bc7ab6b 100644 --- a/gui/gui_core_pkg/wifi_adb_scan.py +++ b/gui/gui_core_pkg/wifi_adb_scan.py @@ -354,3 +354,74 @@ def discover_adb_devices( results.append(dev) return results + + +# ============================================================ +# 上次目标 → 扫描结果的智能匹配 +# ============================================================ + +def pick_best_match( + devs: list[DiscoveredDevice], + last: Optional[dict] = None, +) -> Optional[DiscoveredDevice]: + """根据上次记住的设备信息,在扫描结果里挑最可能"是同一台设备"的那个。 + + 匹配优先级(高 → 低,且只考虑 state=="connected" 的设备): + 1. target 完全一致 (IP 没换最理想) + 2. 同 model + 同 port (换 IP 但接同一台手机) + 3. 同主机段 + 同 port (换网段时一般不会命中,留作弱兜底) + 4. 唯一一台 connected (扫到就一台,可以认定就是它) + + 返回:匹配到的 DiscoveredDevice;找不到返回 None。 + """ + connected = [d for d in (devs or []) if d.adb_state == "connected"] + if not connected: + return None + + if not isinstance(last, dict): + last = {} + last_target = str(last.get("target") or "").strip() + last_model = str(last.get("model") or "").strip() + last_host = "" + last_port = DEFAULT_ADB_PORT + if last_target and ":" in last_target: + host_part, port_part = last_target.rsplit(":", 1) + last_host = host_part.strip() + try: + last_port = int(port_part) + except ValueError: + last_port = DEFAULT_ADB_PORT + elif last_target: + last_host = last_target + + # 1) target 完全一致 + if last_target: + for d in connected: + if d.target == last_target: + return d + + # 2) 同 model + 同 port(model 大小写敏感,因为 ro.product.model 是稳定字符串) + if last_model: + same_model = [d for d in connected if d.model == last_model and d.port == last_port] + if len(same_model) == 1: + return same_model[0] + if len(same_model) > 1: + # 多台同型号歧义太大,让用户手选 + return None + + # 4) 唯一一台 connected(注意:放在 model 之后,避免覆盖多台同型号的歧义判断) + if len(connected) == 1: + return connected[0] + + # 3) 同主机段(IP 前 3 段相同)+ 同 port —— 弱兜底,仅当唯一时才返回 + if last_host: + last_prefix = ".".join(last_host.split(".")[:3]) + same_prefix = [ + d + for d in connected + if d.port == last_port and d.ip.startswith(last_prefix + ".") + ] + if len(same_prefix) == 1: + return same_prefix[0] + + return None diff --git a/tests/test_pick_best_match.py b/tests/test_pick_best_match.py new file mode 100644 index 0000000..d1127ac --- /dev/null +++ b/tests/test_pick_best_match.py @@ -0,0 +1,136 @@ +"""pick_best_match 智能匹配单元测试。""" +from __future__ import annotations + +import pytest + +from gui.gui_core_pkg.wifi_adb_scan import DiscoveredDevice, pick_best_match + + +def _dev(ip: str, model: str = "", state: str = "connected", port: int = 5555): + return DiscoveredDevice(ip=ip, port=port, adb_state=state, model=model) + + +class TestPickBestMatch: + # ============================================================ + # 规则 1:target 完全一致 + # ============================================================ + + def test_exact_target_match(self): + d1 = _dev("192.168.5.2", "PEPM00") + d2 = _dev("192.168.5.3", "Other") + result = pick_best_match([d1, d2], {"target": "192.168.5.2:5555"}) + assert result is d1 + + def test_exact_match_takes_priority_over_model(self): + """target 命中时,即使 model 也匹配别的设备,仍返回 target 命中的那个。""" + d1 = _dev("192.168.5.2", "Other") # target 命中,model 不一样 + d2 = _dev("192.168.5.3", "PEPM00") # target 不命中,model 一样 + result = pick_best_match( + [d1, d2], {"target": "192.168.5.2:5555", "model": "PEPM00"} + ) + assert result is d1 + + # ============================================================ + # 规则 2:同 model + # ============================================================ + + def test_model_match_when_target_changed(self): + """换 IP 但仍是同型号手机。""" + d1 = _dev("10.0.0.5", "PEPM00") + d2 = _dev("10.0.0.7", "Other") + result = pick_best_match( + [d1, d2], {"target": "192.168.5.2:5555", "model": "PEPM00"} + ) + assert result is d1 + + def test_multiple_same_model_returns_none(self): + """多台同型号手机时无法判断,返回 None 让用户手选。""" + d1 = _dev("10.0.0.5", "PEPM00") + d2 = _dev("10.0.0.7", "PEPM00") + result = pick_best_match( + [d1, d2], {"target": "192.168.5.2:5555", "model": "PEPM00"} + ) + assert result is None + + def test_model_must_match_port_too(self): + """同 model 但 port 不一样不算匹配。""" + d1 = _dev("10.0.0.5", "PEPM00", port=5556) + d2 = _dev("10.0.0.7", "Other", port=5555) + # last 的 port 是 5555,d1 是 5556 → model 不匹配 + # d2 model 也不匹配 → 走规则 4 唯一 connected + result = pick_best_match( + [d1, d2], {"target": "192.168.5.2:5555", "model": "PEPM00"} + ) + # 只有 d2 是 5555 端口;但 d1 d2 都是 connected → 走不到规则 4,返回 None + assert result is None + + # ============================================================ + # 规则 4:唯一一台 connected + # ============================================================ + + def test_only_one_connected_returned(self): + d1 = _dev("192.168.5.2", "PEPM00") + result = pick_best_match([d1], {"target": "10.0.0.1:5555", "model": "Other"}) + assert result is d1 + + def test_only_one_connected_among_unauthorized(self): + """连接列表里有 unauthorized 的设备不影响"唯一 connected"判定。""" + d1 = _dev("192.168.5.2", "PEPM00") + d2 = _dev("192.168.5.3", "", state="unauthorized") + result = pick_best_match([d1, d2], {"target": "10.0.0.1:5555"}) + assert result is d1 + + # ============================================================ + # 规则 3:同主机段(弱兜底) + # ============================================================ + + def test_same_subnet_prefix_when_unique(self): + """同主机段 + 唯一一台 → 命中弱兜底规则 3。""" + d1 = _dev("192.168.5.7", "ModelA") # 同段 + d2 = _dev("10.0.0.5", "ModelB") # 不同段 + # last 是 192.168.5.* model 不匹配,唯一性也不成立(2 台 connected) + # 但只有 d1 同段 → 命中规则 3 + result = pick_best_match( + [d1, d2], {"target": "192.168.5.99:5555", "model": "Different"} + ) + assert result is d1 + + # ============================================================ + # 边界 + # ============================================================ + + def test_empty_devs(self): + assert pick_best_match([], {"target": "192.168.5.2:5555"}) is None + + def test_no_connected_returns_none(self): + d1 = _dev("192.168.5.2", "", state="unauthorized") + d2 = _dev("192.168.5.3", "", state="failed") + assert pick_best_match([d1, d2], {"target": "192.168.5.2:5555"}) is None + + def test_none_last(self): + d1 = _dev("192.168.5.2", "PEPM00") + # 唯一 connected 仍触发规则 4 + assert pick_best_match([d1], None) is d1 + + def test_empty_last_dict(self): + d1 = _dev("192.168.5.2", "PEPM00") + assert pick_best_match([d1], {}) is d1 + + def test_invalid_last_type(self): + """传入非 dict 时应当宽容,按空 last 处理。""" + d1 = _dev("192.168.5.2", "PEPM00") + # 类型断言: pick_best_match 接受 Optional[dict],传非 dict 应该也容错 + assert pick_best_match([d1], "not a dict") is d1 # type: ignore[arg-type] + + def test_target_without_port(self): + """last_target 缺 port 时按默认 5555 处理。""" + d1 = _dev("192.168.5.2", "PEPM00") + result = pick_best_match([d1], {"target": "192.168.5.2"}) + # 仍命中规则 4 唯一 connected(target 完全一致比较失败但唯一性兜底) + assert result is d1 + + def test_target_with_invalid_port_format(self): + """target 'host:abc' 不应抛异常。""" + d1 = _dev("192.168.5.2", "PEPM00") + result = pick_best_match([d1], {"target": "192.168.5.2:abc"}) + assert result is d1