fix: 扫码后先在当前网络直连,不再无条件切 Direct AP

实测诊断给出了决定性信息:手机成功连上 Direct AP、拿到
192.168.137.200/24、网关 192.168.137.1,二维码也正确指向
192.168.137.1:39393,但那个地址上的 39393 不应答,整个 /24 扫了
253 个地址也没有。也就是说手机侧全对,是 Windows 没有在 ICS 虚拟
网卡上接受连接。

而这次切换本来就没有必要——两台设备当时已经在同一个 192.168.8.0/24
局域网里,且实测 192.168.8.68:39393 是通的。切到 Direct AP 反而引入了
ICS 虚拟网卡、该网卡独立的防火墙配置,以及实测一两分钟的配网等待。

改动

1. 二维码始终携带局域网地址(pairing.rs)
   此前开 Direct AP 时只放一个 AP 地址,手机因此**必须**切网才能连。
   现在无论是否开 AP 都带上常规局域网地址,多两个短地址对二维码密度
   的影响可以忽略。

2. 端点顺序修正(pairing.rs)
   此前无条件把 192.168.137.1 / 192.168.49.1 排在最前,即使本机根本
   没有这两块网卡——手机于是先去探测两个不存在的地址,真正可用的
   局域网地址被挤到后面。改为真实网卡优先、猜测性兜底地址殿后。

3. 先试当前网络(MainActivity)
   扫到带 Wi-Fi 凭据的码时,先用系统默认网络并发探测二维码里的地址
   (700ms 连接 / 900ms 读取)。通了就直接开始传输,完全跳过配网弹窗
   与虚拟网卡;不通才切 Direct AP。新增 UploadClient.probeEndpoints。

4. 配网请求复用加时间上限(WifiConnector)
   上一版为了避免「系统选网弹窗还开着就 unregister」而改成复用挂起的
   请求,但没有上限。系统偶尔会让请求既不回 onAvailable 也不回
   onUnavailable 地一直挂着,于是每次「重试连接」都只是再等一次那个
   死掉的请求——这正是本次「配网越来越慢、至少两分钟」的由来。
   超过 20 秒即推倒重来。

5. 网关探测过滤 0.0.0.0(WifiConnector)
   诊断截图里出现了 http://0.0.0.0:39393,来自默认路由的空网关,
   永远连不上却占着探测预算。回环与组播地址一并过滤。

Rust 侧 cargo test 40/40,含两项新用例:端点顺序、以及开 Direct AP 时
二维码仍携带局域网地址。Kotlin 侧本机无法编译,仅做结构检查。
This commit is contained in:
zhy200308
2026-08-11 21:39:46 +08:00
parent b5d124abe5
commit 22c7d7f22d
4 changed files with 163 additions and 17 deletions
@@ -604,6 +604,47 @@ class MainActivity : ComponentActivity() {
private fun connectPair(pair: PairingPayload) {
val attempt = ++pairConnectionAttempt
transferAbortReason = null
// 先在**当前网络**上试一把二维码给出的地址。
//
// 两台设备常常本来就在同一个局域网里,此时切到 Direct AP 是纯粹的
// 倒退:要等系统配网弹窗、要走 ICS 虚拟网卡、还得让那块网卡的防火墙
// 配置也放行,实测能耗掉一两分钟。只有当前网络确实够不着电脑时,
// 才值得付出切网的代价。
if (pair.wifi != null && pair.endpoints.isNotEmpty()) {
showConnecting(pair, "正在当前网络上尝试直连…")
transferExecutor.execute {
val direct = UploadClient.probeEndpoints(
network = null, // 用系统默认网络,不绑定
pairing = pair,
deviceName = receiverDeviceLabel,
endpoints = pair.endpoints,
connectMs = 700,
readMs = 900,
)
runOnUiThread {
if (attempt != pairConnectionAttempt) return@runOnUiThread
if (direct != null) {
connectedNetwork = null // 走默认网络即可
connectedBaseUrl = direct
updateConnectingStatus("当前网络已直连到电脑,无需切换 Wi-Fi。")
if (pair.direction == TransferDirection.DOWNLOAD_TO_PHONE) {
startDownloadFromPc(pair, direct)
} else {
showSendReady(pair, direct)
}
} else {
// 当前网络够不着,才切 Direct AP
connectViaWifi(pair, attempt)
}
}
}
return
}
connectViaWifi(pair, attempt)
}
private fun connectViaWifi(pair: PairingPayload, attempt: Long) {
showConnecting(pair, pair.wifi?.let { "正在请求连接 ${it.ssid}…" } ?: "正在使用当前局域网探测电脑…")
wifiConnector.connect(
pairing = pair,
@@ -159,6 +159,30 @@ object UploadClient {
return null
}
/**
* 在指定网络(`network` 为 null 表示系统默认网络)上并发探测一组地址,
* 返回第一个应答的。
*
* 供「切换 Wi-Fi 之前先试当前网络」这一步使用:两台设备本来就在同一个
* 局域网时,这一下就成功了,不必再走配网弹窗与虚拟网卡。
*/
fun probeEndpoints(
network: Network?,
pairing: PairingPayload,
deviceName: String,
endpoints: List<String>,
connectMs: Int,
readMs: Int,
): String? = probeCandidatesParallel(
network = network,
pairing = pairing,
deviceName = deviceName,
candidates = endpoints,
workers = endpoints.size.coerceAtMost(8).coerceAtLeast(1),
connectMs = connectMs,
readMs = readMs,
)
private fun probeCandidatesParallel(
network: Network?,
pairing: PairingPayload,
@@ -20,7 +20,11 @@ import java.net.InetAddress
import java.util.concurrent.atomic.AtomicBoolean
class WifiConnector(context: Context) {
private companion object { const val TAG = "QftWifi" }
private companion object {
const val TAG = "QftWifi"
/** 超过这个时长仍未出结果的配网请求视为卡死,重试时不再复用 */
const val REUSE_WINDOW_MS = 20_000L
}
private val appContext = context.applicationContext
private val connectivity = appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
private val wifiManager = appContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
@@ -65,7 +69,13 @@ class WifiConnector(context: Context) {
// 同一个 SSID 的请求还挂在系统那里且没有终结:换掉 UI 回调即可,
// 千万不要 unregister 再重新 requestNetwork。
if (wifi != null && callback != null && pendingSsid == wifi.ssid &&
// 复用必须有时间上限。系统偶尔会让一个 WifiNetworkSpecifier 请求
// 既不回 onAvailable 也不回 onUnavailable 地一直挂着;若无条件复用,
// 用户每次点「重试连接」都只是再等一次那个死掉的请求,表现就是
// 「配网越来越慢、几分钟都没反应」。超窗就推倒重来。
val reusable = pendingStartedAt > 0L &&
SystemClock.elapsedRealtime() - pendingStartedAt < REUSE_WINDOW_MS
if (wifi != null && callback != null && pendingSsid == wifi.ssid && reusable &&
pendingTerminal?.get() == false) {
Log.i(TAG, "reuse outstanding request SSID=${wifi.ssid}")
listener = Listener(onStatus, onAvailable, onUnavailable)
+86 -15
View File
@@ -54,15 +54,19 @@ impl PairingPayload {
/// a long transport string/security object and only keeps a small endpoint
/// fallback list. This materially lowers QR density and speeds phone scan.
pub fn encode_text(&self) -> Result<String> {
// Direct-AP pairing carries one short endpoint hint for the immediate
// happy path, while Android still treats the connected gateway + UDP
// discovery as authoritative fallbacks. One endpoint keeps QFTPAIR2
// compact but avoids a full discovery round on common Windows APs.
let endpoints: Vec<&str> = if self.wifi.is_some() {
self.endpoints.iter().take(1).map(String::as_str).collect()
} else {
self.endpoints.iter().take(3).map(String::as_str).collect()
};
// 开了 Direct AP 时,此前只放一个 AP 地址进二维码,手机因此**必须**
// 切到那张虚拟网卡才能连上。可两台设备本来常常已经在同一个局域网里,
// 切过去反而引入了 ICS 网卡、独立防火墙配置和几十秒的配网等待。
//
// 现在无论是否开 Direct AP,都把常规局域网地址一并带上,
// 手机可以先在当前网络直连,连不上再切 AP。多两个短地址对
// 二维码密度的影响可以忽略。
let endpoints: Vec<&str> = self
.endpoints
.iter()
.take(3)
.map(String::as_str)
.collect();
let wifi = self.wifi.as_ref().map(|w| json!([w.ssid, w.passphrase]));
let mut value = json!({
"v": 2,
@@ -213,6 +217,16 @@ pub fn local_ipv4_endpoints(port: u16) -> Vec<String> {
}
}
// 真实存在的网卡地址排在前面,其中 Direct AP 常用的两个网段优先;
// 随后才补上猜测性的兜底地址。此前无条件把 192.168.137.1 / 49.1 排在
// 最前,即使本机根本没有这两块网卡——手机于是先去探测两个不存在的
// 地址,真正可用的局域网地址反而被挤到后面。
ips.sort_by_key(|ip| {
if *ip == Ipv4Addr::new(192, 168, 137, 1) { 0 }
else if *ip == Ipv4Addr::new(192, 168, 49, 1) { 1 }
else if ip.is_private() { 2 }
else { 3 }
});
for fallback in [
Ipv4Addr::new(192, 168, 137, 1),
Ipv4Addr::new(192, 168, 49, 1),
@@ -221,12 +235,6 @@ pub fn local_ipv4_endpoints(port: u16) -> Vec<String> {
ips.push(fallback);
}
}
ips.sort_by_key(|ip| {
if *ip == Ipv4Addr::new(192, 168, 137, 1) { 0 }
else if *ip == Ipv4Addr::new(192, 168, 49, 1) { 1 }
else if ip.is_private() { 2 }
else { 3 }
});
ips.into_iter()
.map(|ip| format!("http://{ip}:{port}"))
.collect()
@@ -256,3 +264,66 @@ mod tests {
assert!(text.len() < 800);
}
}
#[cfg(test)]
mod endpoint_order_tests {
use super::*;
/// 二维码里的地址顺序直接决定手机先探测谁。真实网卡必须排在
/// 猜测性兜底地址之前,否则手机会先去连两个根本不存在的地址。
#[test]
fn real_interfaces_come_before_guessed_fallbacks() {
let endpoints = local_ipv4_endpoints(39393);
assert!(!endpoints.is_empty(), "至少应有兜底地址");
let real: Vec<Ipv4Addr> = local_ipv4_addresses();
let guessed = ["http://192.168.137.1:39393", "http://192.168.49.1:39393"];
for address in &real {
let endpoint = format!("http://{address}:39393");
let Some(position) = endpoints.iter().position(|e| *e == endpoint) else { continue };
for guess in guessed {
// 若某个兜底地址并非本机真实网卡,它必须排在真实网卡之后
if real.iter().any(|ip| format!("http://{ip}:39393") == guess) { continue }
if let Some(guess_position) = endpoints.iter().position(|e| e == guess) {
assert!(
position < guess_position,
"真实地址 {endpoint} 应排在猜测地址 {guess} 之前:{endpoints:?}"
);
}
}
}
}
#[test]
fn download_pairing_carries_lan_endpoints_even_with_direct_ap() {
// 开了 Direct AP 也要带上局域网地址,否则手机必须切网才能连
let payload = PairingPayload {
v: 2,
session: "abcdefghijklmnopqrstuvwxyz012345".into(),
pc_name: "PC".into(),
transport: "http-parallel-v2".into(),
port: 39393,
endpoints: vec![
"http://192.168.137.1:39393".into(),
"http://192.168.8.68:39393".into(),
],
wifi: Some(WifiCredentials {
ssid: "QFT-PC-abc".into(),
passphrase: "0123456789ab".into(),
security: "WPA2".into(),
}),
direction: PairingDirection::Upload,
file_name: None,
file_size: None,
sha256: None,
};
let text = payload.encode_text().unwrap();
let json = String::from_utf8(
base64::engine::general_purpose::URL_SAFE_NO_PAD
.decode(text.trim_start_matches(PAIR_PREFIX))
.unwrap(),
).unwrap();
assert!(json.contains("192.168.8.68"), "局域网地址必须进二维码:{json}");
assert!(json.contains("192.168.137.1"), "Direct AP 地址也应保留:{json}");
}
}