优化:调整WiFi ADB连接逻辑,支持ip:port格式;改进USB设备选择逻辑,增强连接稳定性

This commit is contained in:
Your Name committed 2026-01-25 15:33:32 +08:00
1 parent 4903e50ff2
commit d057c1d84e
3 files changed
+52 -23

No files matched your search

+40 -17
View File
@@ -152,7 +152,11 @@ def connect_wifi_adb(
if not adb_exe or not ip_address:
return False, "ADB路径或IP地址为空"
target = f"{ip_address}:{port}"
# 支持 ip:port 或单纯 ip 的两种情况
if ":" in ip_address:
target = ip_address
else:
target = f"{ip_address}:{port}"
# 连接到设备
proc = subprocess.run(
@@ -166,8 +170,10 @@ def connect_wifi_adb(
)
output = (proc.stdout or "") + "\n" + (proc.stderr or "")
low = output.lower()
if proc.returncode == 0 and "connected" in output.lower():
# adb connect 在成功/已连接时常包含 'connected' 或 'already connected' 文本
if proc.returncode == 0 and ("connected" in low or "already connected" in low):
return True, f"成功连接到 {target}"
else:
return False, f"连接失败: {output}"
@@ -283,23 +289,37 @@ def auto_connect_wifi_adb(
if not adb_exe or not device_id:
return False, "ADB路径或设备ID为空"
# 步骤1: 启用WiFi ADB
# 先检查当前 adb 设备列表,看 device_id 是否已经以 WiFi 形式存在(ip:port)
try:
current = list_adb_devices(adb_exe)
except Exception:
current = []
# 如果 device_id 本身就是 ip:port 格式,且已经在 adb devices 中,则视为已连接
if is_device_wifi_connected(adb_exe, device_id) and device_id in current:
return True, f"设备已通过 WiFi 连接: {device_id}"
# 如果 device_id 是 ip:port 格式但不在 adb devices 中,尝试直接连接这个 target
if is_device_wifi_connected(adb_exe, device_id) and device_id not in current:
conn_ok, conn_msg = connect_wifi_adb(adb_exe, device_id)
if conn_ok:
return True, f"直接连接成功: {device_id}"
else:
return False, f"直接连接失败: {conn_msg}"
# 如果 device_id 是 USB 序列(非 ip:port),执行启用 tcpip 流程作为后备
enable_success, enable_msg = enable_wifi_adb(adb_exe, device_id)
if not enable_success:
return False, f"启用WiFi ADB失败: {enable_msg}"
# 等待设备重启
import time
# 等待设备重启开始
time.sleep(3)
time.sleep(3) # 等待3秒让设备开始重启
# 步骤2: 尝试多次获取IP并连接
# 尝试多次获取IP并连接(优先提取纯 IPv4 地址或 ip:port)
for attempt in range(max_attempts):
# 等待设备重启完成
wait_time = 5 + attempt * 2 # 逐渐增加等待时间
wait_time = 5 + attempt * 2
time.sleep(wait_time)
# 获取IP地址
ip_success, ip_msg = get_device_ip(adb_exe, device_id)
if not ip_success:
if attempt == max_attempts - 1:
@@ -307,15 +327,18 @@ def auto_connect_wifi_adb(
continue
ip_address = ip_msg
# 提取纯 IPv4 地址(有些设备返回类似 10.0.0.0/8 的网络)
m = re.search(r"(\d+\.\d+\.\d+\.\d+)", ip_address)
# 提取 ip 或 ip:port
m = re.search(r"(\d+\.\d+\.\d+\.\d+)(?::(\d+))?", ip_address)
if m:
ip_address = m.group(1)
host = m.group(1)
port_found = m.group(2) or "5555"
target = f"{host}:{port_found}"
else:
target = ip_address
# 尝试连接
connect_success, connect_msg = connect_wifi_adb(adb_exe, ip_address)
connect_success, connect_msg = connect_wifi_adb(adb_exe, target)
if connect_success:
return True, f"自动连接成功! IP: {ip_address}"
return True, f"自动连接成功! target: {target}"
if attempt == max_attempts - 1:
return False, f"连接失败: {connect_msg}"