feat(wifi_adb): 加局域网 ADB 设备扫描发现

新增 gui/gui_core_pkg/wifi_adb_scan.py(356 行):
- get_local_subnet:从本机 WLAN 出口 IP 推 /24 子网
- parse_subnet_spec:解析 192.168.5.0/24 / 192.168.5.1-100 / 192.168.5.5 / 逗号组合
- probe_adb_port:并发 TCP 探测(默认 0.3s 超时,64 线程并发)
- verify_adb_target:对每个开放端口的 IP 调 adb connect 区分 connected / unauthorized / failed
- discover_adb_devices:主入口,端到端只需 1.5 秒扫完 /24

GUI(gui/gui_app.py)"扫描局域网"按钮加在 WiFi 设备操作区:
- 自动推子网(默认)+ 手动输入支持 CIDR / 范围 / 单 IP / 逗号
- 后台线程扫描,进度条 + 阶段提示
- 列表展示 IP / 状态 / 设备型号 / adb connect 输出,列表中手动选
- 选中已 connected 的设备 → 回填 IP 到主对话框
- unauthorized 设备明确提示需手机端授权

新增 25 个 wifi_adb_scan 单元测试。真机端到端验证通过:1.5s 扫完
192.168.5.0/24 子网,发现 192.168.5.2:5555(PEPM00)connected。

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 19:59:19 +08:00
1 parent 23d370ae22
commit e89393693b
4 files changed
+794

No files matched your search

+11
View File
@@ -6,6 +6,7 @@
- adb find_adb_executable / list_adb_devices / resolve_adb_device
- wifi_adb 7 个 WiFi-ADB 函数
- wifi_adb_scan 局域网扫描发现 ADB 设备
- config CONFIG_PATH / read_config / write_config
- run_params RunParams dataclass
"""
@@ -24,6 +25,12 @@ from .wifi_adb import (
get_device_ip,
is_device_wifi_connected,
)
from .wifi_adb_scan import (
DiscoveredDevice,
discover_adb_devices,
get_local_subnet,
parse_subnet_spec,
)
from .config import (
CONFIG_PATH,
read_config,
@@ -42,6 +49,10 @@ __all__ = [
"disconnect_wifi_adb",
"get_device_ip",
"auto_connect_wifi_adb",
"DiscoveredDevice",
"discover_adb_devices",
"get_local_subnet",
"parse_subnet_spec",
"CONFIG_PATH",
"read_config",
"write_config",
+356
View File
@@ -0,0 +1,356 @@
"""gui_core_pkg.wifi_adb_scan - 局域网扫描发现 ADB-over-WiFi 设备
- get_local_subnet 从本机 WLAN 取出 /24 子网
- parse_subnet_spec 解析 192.168.5.0/24 / 192.168.5.1-100 / 192.168.5.5 等格式
- probe_adb_port 并发 TCP 探测一个 IP 的 5555 端口是否打开
- discover_adb_devices 主入口:扫描子网 + adb connect 验证 + 返回真正能连的设备
"""
from __future__ import annotations
import ipaddress
import re
import socket
import subprocess
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass, field
from typing import Callable, Iterable, Optional
DEFAULT_ADB_PORT = 5555
@dataclass
class DiscoveredDevice:
"""扫描发现的一台候选设备。"""
ip: str
port: int = DEFAULT_ADB_PORT
# adb connect 后的状态:connected / unauthorized / failed
adb_state: str = "unknown"
# adb connect 的原始消息
message: str = ""
# 设备型号(adb -s shell getprop ro.product.model 取到才有,可能为空)
model: str = ""
@property
def target(self) -> str:
return f"{self.ip}:{self.port}"
# ============================================================
# 子网推导 / 解析
# ============================================================
def get_local_subnet() -> Optional[str]:
"""取本机 WLAN 接口的 /24 子网,例如返回 "192.168.5.0/24"。
优先级:
1) socket.getsockname()(连一个外部地址,得到出口接口的 IP)
2) 本机所有 IPv4 中第一个非环回 / 非 169.254 的私有地址
取不到返回 None。
"""
ip = _get_outbound_ip()
if not ip:
ip = _get_first_private_ipv4()
if not ip:
return None
try:
# 返回 192.168.5.19 → 192.168.5.0/24
net = ipaddress.IPv4Network(f"{ip}/24", strict=False)
return str(net)
except Exception:
return None
def _get_outbound_ip() -> Optional[str]:
"""通过连一个外部 UDP 地址(不真的发包)让 OS 选一张接口,从而得到出口 IP。"""
s = None
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 8.8.8.8:80 不需要可达,只是让 OS 决定路由
s.settimeout(0.5)
s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
if ip and not ip.startswith("169.254.") and ip != "0.0.0.0":
return ip
except Exception:
pass
finally:
if s is not None:
try:
s.close()
except Exception:
pass
return None
def _get_first_private_ipv4() -> Optional[str]:
"""枚举本机 IPv4,返回第一个非环回 / 非 link-local 的私有地址。"""
try:
host = socket.gethostname()
infos = socket.getaddrinfo(host, None, family=socket.AF_INET)
except Exception:
return None
for info in infos:
ip = info[4][0]
if not ip:
continue
if ip.startswith("127.") or ip.startswith("169.254."):
continue
try:
addr = ipaddress.IPv4Address(ip)
if addr.is_private:
return str(addr)
except Exception:
continue
return None
def parse_subnet_spec(spec: str) -> list[str]:
"""把用户输入解析成 IP 列表。支持的格式:
- "192.168.5.0/24" → 网段下所有可用 IP(去掉网络/广播地址)
- "192.168.5.10-50" → 192.168.5.10 ~ 192.168.5.50
- "192.168.5.5" → 单个 IP
- "192.168.5.5,192.168.5.10/24" → 逗号分隔的多段(合并去重)
无法解析返回空列表。
"""
if not spec or not isinstance(spec, str):
return []
out: list[str] = []
seen: set[str] = set()
for part in spec.split(","):
part = part.strip()
if not part:
continue
# CIDR
if "/" in part:
try:
net = ipaddress.IPv4Network(part, strict=False)
for host in net.hosts():
s = str(host)
if s not in seen:
seen.add(s)
out.append(s)
continue
except Exception:
continue
# 192.168.5.10-50 (尾段范围)
m = re.match(
r"^(\d+)\.(\d+)\.(\d+)\.(\d+)-(\d+)$", part
)
if m:
a, b, c, lo, hi = m.groups()
try:
lo_i, hi_i = int(lo), int(hi)
if 0 <= lo_i <= hi_i <= 255:
for last in range(lo_i, hi_i + 1):
s = f"{a}.{b}.{c}.{last}"
if s not in seen:
seen.add(s)
out.append(s)
continue
except Exception:
pass
# 单个 IP
try:
addr = ipaddress.IPv4Address(part)
s = str(addr)
if s not in seen:
seen.add(s)
out.append(s)
except Exception:
continue
return out
# ============================================================
# TCP 端口探测
# ============================================================
def probe_adb_port(ip: str, port: int = DEFAULT_ADB_PORT, timeout: float = 0.3) -> bool:
"""TCP connect 探测端口是否开放(0.3s 超时,足够局域网)。"""
s = None
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(timeout)
s.connect((ip, port))
return True
except Exception:
return False
finally:
if s is not None:
try:
s.close()
except Exception:
pass
def scan_open_ports(
ips: Iterable[str],
port: int = DEFAULT_ADB_PORT,
timeout: float = 0.3,
max_workers: int = 64,
on_progress: Optional[Callable[[int, int], None]] = None,
) -> list[str]:
"""并发扫描一批 IP 的 port,返回开放的 IP 列表。
on_progress(done, total) 每完成一个回调一次(用于 GUI 进度条)。
"""
ip_list = list(ips)
total = len(ip_list)
if total == 0:
return []
open_ips: list[str] = []
done = 0
with ThreadPoolExecutor(max_workers=max_workers) as ex:
future_to_ip = {
ex.submit(probe_adb_port, ip, port, timeout): ip for ip in ip_list
}
for fut in as_completed(future_to_ip):
done += 1
if on_progress:
try:
on_progress(done, total)
except Exception:
pass
try:
if fut.result():
open_ips.append(future_to_ip[fut])
except Exception:
continue
# 按 IP 字面排序,扫描结果稳定
try:
open_ips.sort(key=lambda s: tuple(int(p) for p in s.split(".")))
except Exception:
open_ips.sort()
return open_ips
# ============================================================
# adb connect 验证 + 状态查询
# ============================================================
def _run_adb(adb_exe: str, args: list[str], timeout: float = 5.0) -> tuple[int, str]:
"""运行 adb 命令,返回 (returncode, stdout+stderr)。"""
try:
proc = subprocess.run(
[adb_exe, *args],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
check=False,
timeout=timeout,
)
except subprocess.TimeoutExpired:
return -1, "timeout"
except Exception as e:
return -1, str(e)
out = ((proc.stdout or "") + "\n" + (proc.stderr or "")).strip()
return proc.returncode, out
def verify_adb_target(adb_exe: str, target: str) -> tuple[str, str]:
"""对一个 ip:port 调 `adb connect <target>`,解析输出。
返回 (state, message):
- state="connected" adb connect 成功(含 "already connected")
- state="unauthorized" adb 协议握手成功但设备未授权
- state="failed" 其他失败
"""
rc, out = _run_adb(adb_exe, ["connect", target], timeout=5.0)
low = out.lower()
if "authenticate" in low or "unauthorized" in low:
return "unauthorized", out
if "connected" in low or "already connected" in low:
return "connected", out
return "failed", out or "未知错误"
def query_device_model(adb_exe: str, target: str) -> str:
"""对一个 connected 的 target 取 ro.product.model(失败返回空字符串)。"""
rc, out = _run_adb(
adb_exe, ["-s", target, "shell", "getprop", "ro.product.model"], timeout=3.0
)
if rc == 0:
return out.strip()
return ""
# ============================================================
# 主入口
# ============================================================
def discover_adb_devices(
adb_exe: str,
subnet_spec: Optional[str] = None,
port: int = DEFAULT_ADB_PORT,
probe_timeout: float = 0.3,
on_progress: Optional[Callable[[int, int], None]] = None,
on_phase: Optional[Callable[[str], None]] = None,
) -> list[DiscoveredDevice]:
"""扫描局域网,返回所有真的能 adb connect 的设备。
Args:
adb_exe: adb 可执行文件路径
subnet_spec: None 表示自动用本机子网;否则按 parse_subnet_spec 解析
port: 默认 5555
probe_timeout: 单个 IP 的 TCP 探测超时(秒)
on_progress: on_progress(done, total) 端口扫描进度回调
on_phase: on_phase("scanning subnet 192.168.5.0/24") 阶段提示回调
Returns:
list[DiscoveredDevice],按 IP 排序。state 为 connected / unauthorized / failed。
UI 通常只展示 state != "failed" 的项。
"""
# 1) 推导 IP 列表
if subnet_spec is None or not subnet_spec.strip():
subnet = get_local_subnet()
if not subnet:
return []
subnet_spec = subnet
ips = parse_subnet_spec(subnet_spec)
if not ips:
return []
if on_phase:
try:
on_phase(f"扫描 {subnet_spec}({len(ips)} 个 IP)")
except Exception:
pass
# 2) 端口扫描,过滤掉关 5555 的
open_ips = scan_open_ports(
ips,
port=port,
timeout=probe_timeout,
on_progress=on_progress,
)
if not open_ips:
return []
if on_phase:
try:
on_phase(f"发现 {len(open_ips)} 个开放 :{port} 的 IP,验证 ADB")
except Exception:
pass
# 3) 对每个开放 IP 调 adb connect 验证
results: list[DiscoveredDevice] = []
for ip in open_ips:
target = f"{ip}:{port}"
state, message = verify_adb_target(adb_exe, target)
dev = DiscoveredDevice(ip=ip, port=port, adb_state=state, message=message)
if state == "connected":
dev.model = query_device_model(adb_exe, target)
results.append(dev)
return results