feat: 提交0.4加速版二维码直传与自动配网优化
This commit is contained in:
@@ -12,8 +12,8 @@ android {
|
|||||||
applicationId = "com.qft.optical"
|
applicationId = "com.qft.optical"
|
||||||
minSdk = 24
|
minSdk = 24
|
||||||
targetSdk = 35
|
targetSdk = 35
|
||||||
versionCode = 10
|
versionCode = 16
|
||||||
versionName = "0.4.0-rc2"
|
versionName = "0.4.0-rc8"
|
||||||
|
|
||||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||||
}
|
}
|
||||||
@@ -47,4 +47,7 @@ dependencies {
|
|||||||
implementation("com.google.zxing:core:3.5.3")
|
implementation("com.google.zxing:core:3.5.3")
|
||||||
|
|
||||||
testImplementation("junit:junit:4.13.2")
|
testImplementation("junit:junit:4.13.2")
|
||||||
|
// android.jar contains only a mockable JSONObject stub in local JVM tests.
|
||||||
|
// The app still uses the platform implementation on devices.
|
||||||
|
testImplementation("org.json:json:20240303")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,276 @@
|
|||||||
|
package com.qft.optical
|
||||||
|
|
||||||
|
import android.content.ContentResolver
|
||||||
|
import android.content.ContentValues
|
||||||
|
import android.content.Context
|
||||||
|
import android.net.Network
|
||||||
|
import android.net.Uri
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.Environment
|
||||||
|
import android.provider.MediaStore
|
||||||
|
import android.util.Log
|
||||||
|
import java.io.File
|
||||||
|
import java.io.FileInputStream
|
||||||
|
import java.io.FileOutputStream
|
||||||
|
import java.io.OutputStream
|
||||||
|
import java.net.HttpURLConnection
|
||||||
|
import java.net.URL
|
||||||
|
import java.security.MessageDigest
|
||||||
|
|
||||||
|
data class DownloadedFile(val name: String, val size: Long, val uri: Uri?)
|
||||||
|
|
||||||
|
/** PC → Android client. It persists an encrypted-app-private partial file so a
|
||||||
|
* short Direct-AP loss resumes with HTTP Range instead of restarting the file. */
|
||||||
|
object DownloadClient {
|
||||||
|
private const val TAG = "QftDownload"
|
||||||
|
private const val BUFFER_SIZE = 1024 * 1024
|
||||||
|
private const val ATTEMPTS = 5
|
||||||
|
|
||||||
|
fun download(
|
||||||
|
context: Context,
|
||||||
|
resolver: ContentResolver,
|
||||||
|
network: Network?,
|
||||||
|
baseUrl: String,
|
||||||
|
pairing: PairingPayload,
|
||||||
|
deviceName: String,
|
||||||
|
onProgress: (received: Long, total: Long) -> Unit,
|
||||||
|
): DownloadedFile {
|
||||||
|
require(pairing.direction == TransferDirection.DOWNLOAD_TO_PHONE)
|
||||||
|
val expectedName = requireNotNull(pairing.fileName)
|
||||||
|
val expectedSize = requireNotNull(pairing.fileSize)
|
||||||
|
val expectedSha = requireNotNull(pairing.sha256)
|
||||||
|
val partial = partialFile(context, pairing.session)
|
||||||
|
partial.parentFile?.let { if (!it.exists() && !it.mkdirs()) error("无法创建接收缓存目录") }
|
||||||
|
if (partial.length() > expectedSize) partial.delete()
|
||||||
|
|
||||||
|
var last: Exception? = null
|
||||||
|
repeat(ATTEMPTS) { attempt ->
|
||||||
|
try {
|
||||||
|
Log.i(TAG, "attempt=${attempt + 1}/$ATTEMPTS partial=${partial.length()}/$expectedSize endpoint=$baseUrl")
|
||||||
|
if (partial.length() < expectedSize) {
|
||||||
|
receiveAttempt(network, baseUrl, pairing, deviceName, partial, expectedSize, onProgress)
|
||||||
|
}
|
||||||
|
if (partial.length() != expectedSize) {
|
||||||
|
error("下载提前结束:${partial.length()}/$expectedSize")
|
||||||
|
}
|
||||||
|
verifySha256(partial, expectedSha)
|
||||||
|
val result = saveToDownloads(resolver, partial, expectedName, expectedSize)
|
||||||
|
partial.delete()
|
||||||
|
Log.i(TAG, "completed size=$expectedSize")
|
||||||
|
return result
|
||||||
|
} catch (e: Exception) {
|
||||||
|
last = e
|
||||||
|
Log.w(TAG, "attempt=${attempt + 1}/$ATTEMPTS failed partial=${partial.length()}/$expectedSize: ${failureDetail(e)}", e)
|
||||||
|
if (attempt + 1 < ATTEMPTS) {
|
||||||
|
try {
|
||||||
|
Thread.sleep(250L * (attempt + 1))
|
||||||
|
} catch (interrupted: InterruptedException) {
|
||||||
|
Thread.currentThread().interrupt()
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw IllegalStateException("从电脑下载失败,已重试 $ATTEMPTS 次:${failureDetail(last)}", last)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun receiveAttempt(
|
||||||
|
network: Network?,
|
||||||
|
baseUrl: String,
|
||||||
|
pairing: PairingPayload,
|
||||||
|
deviceName: String,
|
||||||
|
partial: File,
|
||||||
|
expectedSize: Long,
|
||||||
|
onProgress: (received: Long, total: Long) -> Unit,
|
||||||
|
) {
|
||||||
|
val requestedOffset = partial.length().coerceIn(0L, expectedSize)
|
||||||
|
val conn = open(network, URL("$baseUrl/qft/download"))
|
||||||
|
try {
|
||||||
|
conn.requestMethod = "GET"
|
||||||
|
conn.connectTimeout = 5_000
|
||||||
|
// A QFT LAN transfer should start immediately. The old 120-second
|
||||||
|
// read timeout let Huawei tear down a local-only Wi-Fi request
|
||||||
|
// before a retry could occur. A short timeout safely resumes from
|
||||||
|
// the persisted Range offset and finishes all retries sooner.
|
||||||
|
conn.readTimeout = 12_000
|
||||||
|
conn.useCaches = false
|
||||||
|
conn.setRequestProperty("Connection", "close")
|
||||||
|
conn.setRequestProperty("X-QFT-Token", pairing.session)
|
||||||
|
conn.setRequestProperty("X-QFT-Device", Base64Url.encode(deviceName.toByteArray(Charsets.UTF_8)))
|
||||||
|
if (requestedOffset > 0L) conn.setRequestProperty("Range", "bytes=$requestedOffset-")
|
||||||
|
|
||||||
|
val code = conn.responseCode
|
||||||
|
Log.i(TAG, "response code=$code requestedOffset=$requestedOffset contentLength=${conn.contentLengthLong} range=${conn.getHeaderField("Content-Range")}")
|
||||||
|
val resumed = code == HttpURLConnection.HTTP_PARTIAL
|
||||||
|
if (code != HttpURLConnection.HTTP_OK && !resumed) {
|
||||||
|
val message = try { conn.errorStream?.bufferedReader()?.use { it.readText().take(300) } } catch (_: Exception) { null }
|
||||||
|
error("电脑下载服务返回 HTTP $code${message?.let { ": $it" } ?: ""}")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Older desktop binaries return 200 even with Range. Restart only
|
||||||
|
// that request from zero, while current binaries return 206 and
|
||||||
|
// continue from the private partial file.
|
||||||
|
val offset = if (resumed) {
|
||||||
|
val range = conn.getHeaderField("Content-Range").orEmpty()
|
||||||
|
if (!range.startsWith("bytes $requestedOffset-")) {
|
||||||
|
error("下载服务返回了无效的断点范围:$range")
|
||||||
|
}
|
||||||
|
requestedOffset
|
||||||
|
} else {
|
||||||
|
0L
|
||||||
|
}
|
||||||
|
val expectedRemaining = expectedSize - offset
|
||||||
|
val contentLength = conn.contentLengthLong
|
||||||
|
if (contentLength >= 0L && contentLength != expectedRemaining) {
|
||||||
|
error("下载大小不匹配:$contentLength != $expectedRemaining")
|
||||||
|
}
|
||||||
|
onProgress(offset, expectedSize)
|
||||||
|
|
||||||
|
var received = offset
|
||||||
|
var lastReport = android.os.SystemClock.elapsedRealtime()
|
||||||
|
conn.inputStream.use { input ->
|
||||||
|
FileOutputStream(partial, offset > 0L).use { output ->
|
||||||
|
val buffer = ByteArray(BUFFER_SIZE)
|
||||||
|
while (true) {
|
||||||
|
val n = input.read(buffer)
|
||||||
|
if (n < 0) break
|
||||||
|
if (n == 0) continue
|
||||||
|
output.write(buffer, 0, n)
|
||||||
|
received += n.toLong()
|
||||||
|
if (received > expectedSize) error("下载数据超过二维码中的文件大小")
|
||||||
|
val now = android.os.SystemClock.elapsedRealtime()
|
||||||
|
if (now - lastReport >= 80L || received == expectedSize) {
|
||||||
|
onProgress(received, expectedSize)
|
||||||
|
lastReport = now
|
||||||
|
}
|
||||||
|
}
|
||||||
|
output.flush()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (received != expectedSize) error("下载提前结束:$received/$expectedSize")
|
||||||
|
Log.i(TAG, "response complete received=$received/$expectedSize")
|
||||||
|
} finally {
|
||||||
|
conn.disconnect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun verifySha256(file: File, expectedSha: String) {
|
||||||
|
val digest = MessageDigest.getInstance("SHA-256")
|
||||||
|
FileInputStream(file).use { input ->
|
||||||
|
val buffer = ByteArray(BUFFER_SIZE)
|
||||||
|
while (true) {
|
||||||
|
val n = input.read(buffer)
|
||||||
|
if (n < 0) break
|
||||||
|
if (n > 0) digest.update(buffer, 0, n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val actual = digest.digest().toHex()
|
||||||
|
if (!actual.equals(expectedSha, ignoreCase = true)) {
|
||||||
|
file.delete()
|
||||||
|
error("文件校验失败,已清除不完整缓存;请重试")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun saveToDownloads(
|
||||||
|
resolver: ContentResolver,
|
||||||
|
partial: File,
|
||||||
|
expectedName: String,
|
||||||
|
expectedSize: Long,
|
||||||
|
): DownloadedFile {
|
||||||
|
var target: DownloadTarget? = null
|
||||||
|
try {
|
||||||
|
val createdTarget = createTarget(resolver, expectedName)
|
||||||
|
target = createdTarget
|
||||||
|
FileInputStream(partial).use { input ->
|
||||||
|
createdTarget.output.use { output ->
|
||||||
|
val buffer = ByteArray(BUFFER_SIZE)
|
||||||
|
var copied = 0L
|
||||||
|
while (true) {
|
||||||
|
val n = input.read(buffer)
|
||||||
|
if (n < 0) break
|
||||||
|
if (n == 0) continue
|
||||||
|
output.write(buffer, 0, n)
|
||||||
|
copied += n.toLong()
|
||||||
|
}
|
||||||
|
output.flush()
|
||||||
|
if (copied != expectedSize) error("保存下载文件时大小发生变化")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
target.commit()
|
||||||
|
return DownloadedFile(expectedName, expectedSize, target.uri)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
target?.abort()
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun partialFile(context: Context, session: String): File {
|
||||||
|
val root = context.getExternalFilesDir("qft") ?: context.cacheDir
|
||||||
|
return File(root, "$session.qftpart")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun createTarget(resolver: ContentResolver, name: String): DownloadTarget {
|
||||||
|
if (Build.VERSION.SDK_INT >= 29) {
|
||||||
|
val values = ContentValues().apply {
|
||||||
|
put(MediaStore.Downloads.DISPLAY_NAME, name)
|
||||||
|
put(MediaStore.Downloads.MIME_TYPE, "application/octet-stream")
|
||||||
|
put(MediaStore.Downloads.RELATIVE_PATH, "${Environment.DIRECTORY_DOWNLOADS}/QFT")
|
||||||
|
put(MediaStore.Downloads.IS_PENDING, 1)
|
||||||
|
}
|
||||||
|
val uri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values)
|
||||||
|
?: error("无法创建 Downloads/QFT 文件")
|
||||||
|
val output = resolver.openOutputStream(uri, "w") ?: run {
|
||||||
|
resolver.delete(uri, null, null)
|
||||||
|
error("无法写入 Downloads/QFT 文件")
|
||||||
|
}
|
||||||
|
return DownloadTarget(
|
||||||
|
uri,
|
||||||
|
output,
|
||||||
|
commit = { resolver.update(uri, ContentValues().apply { put(MediaStore.Downloads.IS_PENDING, 0) }, null, null) },
|
||||||
|
abort = { resolver.delete(uri, null, null) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
val dir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "QFT")
|
||||||
|
if (!dir.exists() && !dir.mkdirs()) error("无法创建 Downloads/QFT")
|
||||||
|
val path = uniqueFile(dir, name)
|
||||||
|
return DownloadTarget(null, path.outputStream(), commit = {}, abort = { path.delete() })
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun uniqueFile(dir: File, original: String): File {
|
||||||
|
val clean = original.replace(Regex("[\\\\/:*?\"<>|]"), "_").take(180).ifBlank { "qft-download.bin" }
|
||||||
|
val dot = clean.lastIndexOf('.')
|
||||||
|
val stem = if (dot > 0) clean.substring(0, dot) else clean
|
||||||
|
val ext = if (dot > 0) clean.substring(dot) else ""
|
||||||
|
var candidate = File(dir, clean)
|
||||||
|
var n = 1
|
||||||
|
while (candidate.exists()) {
|
||||||
|
candidate = File(dir, "$stem ($n)$ext")
|
||||||
|
n++
|
||||||
|
}
|
||||||
|
return candidate
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun failureDetail(error: Throwable?): String {
|
||||||
|
if (error == null) return "未知错误"
|
||||||
|
return generateSequence(error) { it.cause }
|
||||||
|
.take(3)
|
||||||
|
.joinToString(" ← ") { cause ->
|
||||||
|
cause.message?.takeIf { it.isNotBlank() } ?: cause.javaClass.simpleName
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun open(network: Network?, url: URL): HttpURLConnection =
|
||||||
|
(network?.openConnection(url) ?: url.openConnection()) as HttpURLConnection
|
||||||
|
|
||||||
|
private data class DownloadTarget(
|
||||||
|
val uri: Uri?,
|
||||||
|
val output: OutputStream,
|
||||||
|
val commit: () -> Unit,
|
||||||
|
val abort: () -> Unit,
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun ByteArray.toHex(): String = buildString(size * 2) {
|
||||||
|
for (byte in this@toHex) append((byte.toInt() and 0xFF).toString(16).padStart(2, '0'))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -60,6 +60,18 @@ data class LockRect(
|
|||||||
return d > max(width, height) / 18
|
return d > max(width, height) / 18
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Intersection-over-union for consecutive finder-point measurements. */
|
||||||
|
fun overlap(other: LockRect?): Float {
|
||||||
|
if (other == null) return 0f
|
||||||
|
val l = max(left, other.left)
|
||||||
|
val t = max(top, other.top)
|
||||||
|
val r = min(right, other.right)
|
||||||
|
val b = min(bottom, other.bottom)
|
||||||
|
val intersection = max(0, r - l).toLong() * max(0, b - t).toLong()
|
||||||
|
val union = width.toLong() * height.toLong() + other.width.toLong() * other.height.toLong() - intersection
|
||||||
|
return if (union <= 0L) 0f else (intersection.toDouble() / union.toDouble()).toFloat()
|
||||||
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
/**
|
/**
|
||||||
* ZXing normally returns the finder-pattern centers. Their bounding box
|
* ZXing normally returns the finder-pattern centers. Their bounding box
|
||||||
|
|||||||
@@ -11,9 +11,12 @@ import android.hardware.camera2.CaptureRequest
|
|||||||
import android.net.Network
|
import android.net.Network
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
|
import android.util.Log
|
||||||
import android.util.Range
|
import android.util.Range
|
||||||
import android.util.Size
|
import android.util.Size
|
||||||
import android.view.Gravity
|
import android.view.Gravity
|
||||||
|
import android.view.MotionEvent
|
||||||
|
import android.view.ScaleGestureDetector
|
||||||
import android.view.ViewGroup
|
import android.view.ViewGroup
|
||||||
import android.widget.Button
|
import android.widget.Button
|
||||||
import android.widget.FrameLayout
|
import android.widget.FrameLayout
|
||||||
@@ -55,10 +58,17 @@ class MainActivity : ComponentActivity() {
|
|||||||
private var qrLockOverlay: QrLockOverlay? = null
|
private var qrLockOverlay: QrLockOverlay? = null
|
||||||
private var scannerStatsText: TextView? = null
|
private var scannerStatsText: TextView? = null
|
||||||
private var scannerLockText: TextView? = null
|
private var scannerLockText: TextView? = null
|
||||||
|
private var scannerZoomText: TextView? = null
|
||||||
private var scannerMode = ScannerMode.NONE
|
private var scannerMode = ScannerMode.NONE
|
||||||
private var pendingScannerMode = ScannerMode.NONE
|
private var pendingScannerMode = ScannerMode.NONE
|
||||||
private val pairConsumed = AtomicBoolean(false)
|
private val pairConsumed = AtomicBoolean(false)
|
||||||
|
|
||||||
|
private data class CameraFpsPlan(
|
||||||
|
val normalCandidates: List<Range<Int>>,
|
||||||
|
val highestNormalFps: Int,
|
||||||
|
val highestConstrainedHighSpeedFps: Int?,
|
||||||
|
)
|
||||||
|
|
||||||
private lateinit var previewView: PreviewView
|
private lateinit var previewView: PreviewView
|
||||||
private lateinit var titleText: TextView
|
private lateinit var titleText: TextView
|
||||||
private lateinit var deviceText: TextView
|
private lateinit var deviceText: TextView
|
||||||
@@ -74,12 +84,20 @@ class MainActivity : ComponentActivity() {
|
|||||||
private var sendProgress: ProgressBar? = null
|
private var sendProgress: ProgressBar? = null
|
||||||
private var sendButton: Button? = null
|
private var sendButton: Button? = null
|
||||||
private var connectingStatusText: TextView? = null
|
private var connectingStatusText: TextView? = null
|
||||||
|
private var downloadStatusText: TextView? = null
|
||||||
|
@Volatile private var downloadRunning = false
|
||||||
|
@Volatile private var pairConnectionAttempt = 0L
|
||||||
|
|
||||||
private val requestCamera = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
private val requestCamera = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||||
if (granted) startScanner(pendingScannerMode) else showHome("需要相机权限才能扫描 QFT 二维码")
|
if (granted) startScanner(pendingScannerMode) else showHome("需要相机权限才能扫描 QFT 二维码")
|
||||||
}
|
}
|
||||||
|
|
||||||
private val requestLegacyStorage = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
private val requestLegacyStorage = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||||
|
val pair = pendingPair
|
||||||
|
if (granted && pair?.direction == TransferDirection.DOWNLOAD_TO_PHONE) {
|
||||||
|
connectPair(pair)
|
||||||
|
return@registerForActivityResult
|
||||||
|
}
|
||||||
if (granted) requestScanner(pendingScannerMode) else showHome("Android 7~9 需要存储权限才能把光学接收文件保存到 Downloads/QFT")
|
if (granted) requestScanner(pendingScannerMode) else showHome("Android 7~9 需要存储权限才能把光学接收文件保存到 Downloads/QFT")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -118,6 +136,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun showHome(message: String? = null) {
|
private fun showHome(message: String? = null) {
|
||||||
|
pairConnectionAttempt++
|
||||||
stopCamera()
|
stopCamera()
|
||||||
scannerMode = ScannerMode.NONE
|
scannerMode = ScannerMode.NONE
|
||||||
pairConsumed.set(false)
|
pairConsumed.set(false)
|
||||||
@@ -125,6 +144,8 @@ class MainActivity : ComponentActivity() {
|
|||||||
pendingPair = null
|
pendingPair = null
|
||||||
connectedNetwork = null
|
connectedNetwork = null
|
||||||
connectedBaseUrl = null
|
connectedBaseUrl = null
|
||||||
|
downloadRunning = false
|
||||||
|
downloadStatusText = null
|
||||||
selectedFiles.clear()
|
selectedFiles.clear()
|
||||||
|
|
||||||
val root = pageColumn()
|
val root = pageColumn()
|
||||||
@@ -146,10 +167,10 @@ class MainActivity : ComponentActivity() {
|
|||||||
) { requestScanner(ScannerMode.OPTICAL) })
|
) { requestScanner(ScannerMode.OPTICAL) })
|
||||||
root.addView(space(16))
|
root.addView(space(16))
|
||||||
root.addView(modeCard(
|
root.addView(modeCard(
|
||||||
title = "手机 → 电脑",
|
title = "扫码直传",
|
||||||
badge = "扫码直连 · 快速发现 · 8路并行",
|
badge = "手机上传 / 电脑下发 · 自动配网 · 快速发现",
|
||||||
body = "扫描电脑上的接收二维码,自动请求连接 QFT 临时 Wi-Fi,然后把文件直接上传到电脑指定文件夹。",
|
body = "扫描电脑二维码后自动连接 QFT 本地网络:接收二维码会进入手机选文件上传;下发二维码会自动下载并保存到 Downloads/QFT。",
|
||||||
buttonLabel = "扫码连接电脑",
|
buttonLabel = "扫描电脑二维码",
|
||||||
) { requestScanner(ScannerMode.PAIR) })
|
) { requestScanner(ScannerMode.PAIR) })
|
||||||
root.addView(space(22))
|
root.addView(space(22))
|
||||||
root.addView(text("本机设备:$receiverDeviceLabel", 13f, MUTED))
|
root.addView(text("本机设备:$receiverDeviceLabel", 13f, MUTED))
|
||||||
@@ -158,6 +179,10 @@ class MainActivity : ComponentActivity() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun requestScanner(mode: ScannerMode) {
|
private fun requestScanner(mode: ScannerMode) {
|
||||||
|
if (mode == ScannerMode.PAIR) {
|
||||||
|
pairConnectionAttempt++
|
||||||
|
wifiConnector.release()
|
||||||
|
}
|
||||||
pendingScannerMode = mode
|
pendingScannerMode = mode
|
||||||
if (mode == ScannerMode.OPTICAL && Build.VERSION.SDK_INT <= 28 &&
|
if (mode == ScannerMode.OPTICAL && Build.VERSION.SDK_INT <= 28 &&
|
||||||
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
|
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
|
||||||
@@ -181,11 +206,19 @@ class MainActivity : ComponentActivity() {
|
|||||||
future.addListener({
|
future.addListener({
|
||||||
val provider = future.get()
|
val provider = future.get()
|
||||||
cameraProvider = provider
|
cameraProvider = provider
|
||||||
val requestedFps = chooseCameraFpsRange()
|
val fpsPlan = chooseCameraFpsPlan()
|
||||||
|
val requestedFps = fpsPlan.normalCandidates.first()
|
||||||
|
Log.i(
|
||||||
|
TAG,
|
||||||
|
"normalRanges=${fpsPlan.normalCandidates.joinToString()} " +
|
||||||
|
"highestNormal=${fpsPlan.highestNormalFps} " +
|
||||||
|
"constrainedHighSpeed=${fpsPlan.highestConstrainedHighSpeedFps} " +
|
||||||
|
"requested=$requestedFps",
|
||||||
|
)
|
||||||
|
|
||||||
// CameraX 1.4.x ImageAnalysis.Builder has no public setTargetFrameRate().
|
// CameraX exposes no public target-frame-rate setter for
|
||||||
// Apply a range actually advertised by the selected back camera via
|
// ImageAnalysis. Apply the highest normal Camera2 range to both
|
||||||
// Camera2Interop to both bound use cases.
|
// bound use cases through the Camera2 interop layer.
|
||||||
val previewBuilder = Preview.Builder()
|
val previewBuilder = Preview.Builder()
|
||||||
Camera2Interop.Extender(previewBuilder).setCaptureRequestOption(
|
Camera2Interop.Extender(previewBuilder).setCaptureRequestOption(
|
||||||
CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE,
|
CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE,
|
||||||
@@ -204,7 +237,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
ScannerMode.NONE -> Unit
|
ScannerMode.NONE -> Unit
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
onStats = { cameraFps, decodedFps, distinctFps, decodeMs ->
|
onStats = { cameraFps, decodedFps, distinctFps, attemptedFps, decodeMs ->
|
||||||
runOnUiThread {
|
runOnUiThread {
|
||||||
val quality = when (mode) {
|
val quality = when (mode) {
|
||||||
ScannerMode.PAIR -> when {
|
ScannerMode.PAIR -> when {
|
||||||
@@ -221,11 +254,13 @@ class MainActivity : ComponentActivity() {
|
|||||||
ScannerMode.NONE -> "空闲" to MUTED
|
ScannerMode.NONE -> "空闲" to MUTED
|
||||||
}
|
}
|
||||||
scannerStatsText?.text = if (mode == ScannerMode.OPTICAL) {
|
scannerStatsText?.text = if (mode == ScannerMode.OPTICAL) {
|
||||||
"%s · 相机 %.1f FPS · 解码 %.1f/s · 新帧 %.1f/s · %.1fms/次".format(
|
"%s · 相机 %.1f FPS · 解码 %.1f/s · 新帧 %.1f/s · 尝试 %.1f/s · %.1fms/次".format(
|
||||||
quality.first, cameraFps, decodedFps, distinctFps, decodeMs
|
quality.first, cameraFps, decodedFps, distinctFps, attemptedFps, decodeMs
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
"%s · 相机 %.1f FPS · 解码 %.1f/s · %.1fms/次".format(quality.first, cameraFps, decodedFps, decodeMs)
|
"%s · 相机 %.1f FPS · 解码 %.1f/s · 尝试 %.1f/s · %.1fms/次".format(
|
||||||
|
quality.first, cameraFps, decodedFps, attemptedFps, decodeMs
|
||||||
|
)
|
||||||
}
|
}
|
||||||
scannerStatsText?.setTextColor(quality.second)
|
scannerStatsText?.setTextColor(quality.second)
|
||||||
}
|
}
|
||||||
@@ -234,15 +269,19 @@ class MainActivity : ComponentActivity() {
|
|||||||
runOnUiThread {
|
runOnUiThread {
|
||||||
qrLockOverlay?.update(lock)
|
qrLockOverlay?.update(lock)
|
||||||
if (mode == ScannerMode.OPTICAL) {
|
if (mode == ScannerMode.OPTICAL) {
|
||||||
if (lock.locked && lock.misses == 0) maybeRefocusLockedQr()
|
if (lock.locked && lock.misses == 0 && lock.stability >= 0.67f) maybeRefocusLockedQr()
|
||||||
scannerLockText?.text = if (lock.locked) {
|
scannerLockText?.text = if (lock.locked) {
|
||||||
val lockHint = if (lock.misses == 0) "稳定锁定" else "保持锁定 · miss ${lock.misses}"
|
val lockHint = when {
|
||||||
|
lock.misses > 0 -> "保持锁定 · miss ${lock.misses}"
|
||||||
|
lock.stability < 0.67f -> "正在稳定取景框"
|
||||||
|
else -> "稳定锁定"
|
||||||
|
}
|
||||||
"$lockHint · 仅分析 ${(lock.searchAreaFraction * 100f).toInt().coerceIn(1, 100)}% 画面"
|
"$lockHint · 仅分析 ${(lock.searchAreaFraction * 100f).toInt().coerceIn(1, 100)}% 画面"
|
||||||
} else {
|
} else {
|
||||||
"区域锁定:搜索中 · 让单个大二维码占取景框 50% 以上"
|
"区域锁定:搜索中 · 让单个大二维码占取景框 50% 以上"
|
||||||
}
|
}
|
||||||
scannerLockText?.setTextColor(
|
scannerLockText?.setTextColor(
|
||||||
if (!lock.locked) ACCENT else if (lock.misses == 0) SUCCESS else WARNING
|
if (!lock.locked) ACCENT else if (lock.misses > 0) WARNING else if (lock.stability >= 0.67f) SUCCESS else ACCENT
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -257,10 +296,15 @@ class MainActivity : ComponentActivity() {
|
|||||||
val analysisBuilder = ImageAnalysis.Builder()
|
val analysisBuilder = ImageAnalysis.Builder()
|
||||||
.setTargetResolution(targetSize)
|
.setTargetResolution(targetSize)
|
||||||
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
|
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
|
||||||
|
.setImageQueueDepth(1)
|
||||||
Camera2Interop.Extender(analysisBuilder).setCaptureRequestOption(
|
Camera2Interop.Extender(analysisBuilder).setCaptureRequestOption(
|
||||||
CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE,
|
CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE,
|
||||||
requestedFps,
|
requestedFps,
|
||||||
)
|
)
|
||||||
|
Camera2Interop.Extender(analysisBuilder).setCaptureRequestOption(
|
||||||
|
CaptureRequest.CONTROL_AF_MODE,
|
||||||
|
CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE,
|
||||||
|
)
|
||||||
val analysis = analysisBuilder.build().also { it.setAnalyzer(cameraExecutor, analyzer) }
|
val analysis = analysisBuilder.build().also { it.setAnalyzer(cameraExecutor, analyzer) }
|
||||||
|
|
||||||
provider.unbindAll()
|
provider.unbindAll()
|
||||||
@@ -280,6 +324,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
val fallbackAnalysis = ImageAnalysis.Builder()
|
val fallbackAnalysis = ImageAnalysis.Builder()
|
||||||
.setTargetResolution(targetSize)
|
.setTargetResolution(targetSize)
|
||||||
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
|
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
|
||||||
|
.setImageQueueDepth(1)
|
||||||
.build().also { it.setAnalyzer(cameraExecutor, analyzer) }
|
.build().also { it.setAnalyzer(cameraExecutor, analyzer) }
|
||||||
scannerStatsText?.text = "设备拒绝显式高帧率请求 · 已回退相机自动 FPS · 等待首帧…"
|
scannerStatsText?.text = "设备拒绝显式高帧率请求 · 已回退相机自动 FPS · 等待首帧…"
|
||||||
provider.bindToLifecycle(
|
provider.bindToLifecycle(
|
||||||
@@ -290,6 +335,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
activeCamera = camera
|
activeCamera = camera
|
||||||
|
updateScannerZoom(camera.cameraInfo.zoomState.value?.zoomRatio ?: 1f)
|
||||||
|
|
||||||
previewView.post {
|
previewView.post {
|
||||||
if (previewView.width <= 0 || previewView.height <= 0) return@post
|
if (previewView.width <= 0 || previewView.height <= 0) return@post
|
||||||
@@ -338,24 +384,99 @@ class MainActivity : ComponentActivity() {
|
|||||||
} catch (_: Exception) {}
|
} catch (_: Exception) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun chooseCameraFpsRange(): Range<Int> {
|
private fun adjustScannerZoom(scale: Float) {
|
||||||
|
val camera = activeCamera ?: return
|
||||||
|
val zoom = camera.cameraInfo.zoomState.value ?: return
|
||||||
|
val next = (zoom.zoomRatio * scale).coerceIn(zoom.minZoomRatio, zoom.maxZoomRatio)
|
||||||
|
try {
|
||||||
|
camera.cameraControl.setZoomRatio(next)
|
||||||
|
updateScannerZoom(next)
|
||||||
|
} catch (_: Exception) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun updateScannerZoom(ratio: Float) {
|
||||||
|
scannerZoomText?.text = "缩放 %.1fx · 双指缩放,点按二维码处重新聚焦".format(ratio)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun focusScannerAt(x: Float, y: Float) {
|
||||||
|
val camera = activeCamera ?: return
|
||||||
|
if (previewView.width <= 0 || previewView.height <= 0) return
|
||||||
|
try {
|
||||||
|
val point = previewView.meteringPointFactory.createPoint(x, y)
|
||||||
|
val action = FocusMeteringAction.Builder(
|
||||||
|
point,
|
||||||
|
FocusMeteringAction.FLAG_AF or FocusMeteringAction.FLAG_AE,
|
||||||
|
).setAutoCancelDuration(3, TimeUnit.SECONDS).build()
|
||||||
|
camera.cameraControl.startFocusAndMetering(action)
|
||||||
|
scannerLockText?.text = "已在点按位置重新聚焦"
|
||||||
|
scannerLockText?.setTextColor(ACCENT)
|
||||||
|
} catch (_: Exception) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun installScannerGestures(target: android.view.View) {
|
||||||
|
var downX = 0f
|
||||||
|
var downY = 0f
|
||||||
|
var scaled = false
|
||||||
|
val detector = ScaleGestureDetector(this, object : ScaleGestureDetector.SimpleOnScaleGestureListener() {
|
||||||
|
override fun onScaleBegin(detector: ScaleGestureDetector): Boolean {
|
||||||
|
scaled = true
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onScale(detector: ScaleGestureDetector): Boolean {
|
||||||
|
adjustScannerZoom(detector.scaleFactor)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
})
|
||||||
|
target.setOnTouchListener { _, event ->
|
||||||
|
detector.onTouchEvent(event)
|
||||||
|
when (event.actionMasked) {
|
||||||
|
MotionEvent.ACTION_DOWN -> {
|
||||||
|
downX = event.x
|
||||||
|
downY = event.y
|
||||||
|
scaled = false
|
||||||
|
}
|
||||||
|
MotionEvent.ACTION_UP -> {
|
||||||
|
val dx = event.x - downX
|
||||||
|
val dy = event.y - downY
|
||||||
|
val tapSlop = dp(12).toFloat()
|
||||||
|
if (!scaled && dx * dx + dy * dy <= tapSlop * tapSlop) {
|
||||||
|
focusScannerAt(event.x, event.y)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
MotionEvent.ACTION_CANCEL -> scaled = false
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun chooseCameraFpsPlan(): CameraFpsPlan {
|
||||||
return try {
|
return try {
|
||||||
val manager = getSystemService(android.content.Context.CAMERA_SERVICE) as CameraManager
|
val manager = getSystemService(android.content.Context.CAMERA_SERVICE) as CameraManager
|
||||||
val characteristics = manager.cameraIdList
|
val characteristics = manager.cameraIdList
|
||||||
.asSequence()
|
.asSequence()
|
||||||
.map { manager.getCameraCharacteristics(it) }
|
.map { manager.getCameraCharacteristics(it) }
|
||||||
.firstOrNull { it.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_BACK }
|
.firstOrNull { it.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_BACK }
|
||||||
val ranges = characteristics?.get(CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES)
|
val normalRanges = characteristics
|
||||||
?.toList().orEmpty()
|
?.get(CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES)
|
||||||
ranges
|
?.filter { it.lower > 0 && it.upper >= it.lower }
|
||||||
.filter { it.upper <= 60 && it.lower <= 30 }
|
?.sortedWith(compareByDescending<Range<Int>> { it.upper }.thenByDescending { it.lower })
|
||||||
.maxWithOrNull(compareBy<Range<Int>> { it.upper }.thenBy { it.lower })
|
.orEmpty()
|
||||||
?: ranges.filter { it.upper <= 60 }
|
val highSpeed = characteristics
|
||||||
.maxWithOrNull(compareBy<Range<Int>> { it.upper }.thenBy { it.lower })
|
?.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
|
||||||
?: ranges.maxWithOrNull(compareBy<Range<Int>> { it.upper }.thenBy { it.lower })
|
?.highSpeedVideoFpsRanges
|
||||||
?: Range(30, 30)
|
?.maxOfOrNull { it.upper }
|
||||||
|
CameraFpsPlan(
|
||||||
|
normalCandidates = normalRanges.ifEmpty { listOf(Range(30, 30)) },
|
||||||
|
highestNormalFps = normalRanges.maxOfOrNull { it.upper } ?: 30,
|
||||||
|
highestConstrainedHighSpeedFps = highSpeed,
|
||||||
|
)
|
||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
Range(30, 30)
|
CameraFpsPlan(
|
||||||
|
normalCandidates = listOf(Range(30, 30)),
|
||||||
|
highestNormalFps = 30,
|
||||||
|
highestConstrainedHighSpeedFps = null,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -368,6 +489,9 @@ class MainActivity : ComponentActivity() {
|
|||||||
root.addView(previewView, FrameLayout.LayoutParams(-1, -1))
|
root.addView(previewView, FrameLayout.LayoutParams(-1, -1))
|
||||||
qrLockOverlay = QrLockOverlay(this)
|
qrLockOverlay = QrLockOverlay(this)
|
||||||
root.addView(qrLockOverlay, FrameLayout.LayoutParams(-1, -1))
|
root.addView(qrLockOverlay, FrameLayout.LayoutParams(-1, -1))
|
||||||
|
// The overlay is above PreviewView, so it owns both gestures: one-finger
|
||||||
|
// tap selects AF/AE, and a two-finger gesture adjusts CameraX zoom.
|
||||||
|
installScannerGestures(qrLockOverlay!!)
|
||||||
|
|
||||||
val top = LinearLayout(this).apply {
|
val top = LinearLayout(this).apply {
|
||||||
orientation = LinearLayout.HORIZONTAL
|
orientation = LinearLayout.HORIZONTAL
|
||||||
@@ -404,6 +528,14 @@ class MainActivity : ComponentActivity() {
|
|||||||
12f, ACCENT
|
12f, ACCENT
|
||||||
)
|
)
|
||||||
panel.addView(scannerLockText, matchWrap(top = 6))
|
panel.addView(scannerLockText, matchWrap(top = 6))
|
||||||
|
val zoomRow = LinearLayout(this).apply { gravity = Gravity.CENTER_VERTICAL }
|
||||||
|
val zoomOut = button("−").apply { setOnClickListener { adjustScannerZoom(0.80f) } }
|
||||||
|
val zoomIn = button("+").apply { setOnClickListener { adjustScannerZoom(1.25f) } }
|
||||||
|
scannerZoomText = text("缩放 1.0x · 双指缩放,点按二维码处重新聚焦", 12f, MUTED)
|
||||||
|
zoomRow.addView(zoomOut, LinearLayout.LayoutParams(dp(48), dp(42)))
|
||||||
|
zoomRow.addView(scannerZoomText, LinearLayout.LayoutParams(0, -2, 1f).apply { marginStart = dp(8); marginEnd = dp(8) })
|
||||||
|
zoomRow.addView(zoomIn, LinearLayout.LayoutParams(dp(48), dp(42)))
|
||||||
|
panel.addView(zoomRow, matchWrap(top = 6))
|
||||||
scannerStatsText = text("相机分析:等待首帧…", 12f, ACCENT)
|
scannerStatsText = text("相机分析:等待首帧…", 12f, ACCENT)
|
||||||
panel.addView(scannerStatsText, matchWrap(top = 4))
|
panel.addView(scannerStatsText, matchWrap(top = 4))
|
||||||
panel.addView(progress, LinearLayout.LayoutParams(-1, dp(8)).apply { topMargin = dp(12) })
|
panel.addView(progress, LinearLayout.LayoutParams(-1, dp(8)).apply { topMargin = dp(12) })
|
||||||
@@ -426,7 +558,13 @@ class MainActivity : ComponentActivity() {
|
|||||||
runOnUiThread {
|
runOnUiThread {
|
||||||
stopCamera()
|
stopCamera()
|
||||||
showConnecting(pair, "二维码已识别,正在准备本地连接…")
|
showConnecting(pair, "二维码已识别,正在准备本地连接…")
|
||||||
ensureWifiPermissionThenConnect(pair)
|
if (pair.direction == TransferDirection.DOWNLOAD_TO_PHONE && Build.VERSION.SDK_INT <= 28 &&
|
||||||
|
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
|
||||||
|
) {
|
||||||
|
requestLegacyStorage.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE)
|
||||||
|
} else {
|
||||||
|
ensureWifiPermissionThenConnect(pair)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -444,13 +582,18 @@ class MainActivity : ComponentActivity() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun connectPair(pair: PairingPayload) {
|
private fun connectPair(pair: PairingPayload) {
|
||||||
|
val attempt = ++pairConnectionAttempt
|
||||||
showConnecting(pair, pair.wifi?.let { "正在请求连接 ${it.ssid}…" } ?: "正在使用当前局域网探测电脑…")
|
showConnecting(pair, pair.wifi?.let { "正在请求连接 ${it.ssid}…" } ?: "正在使用当前局域网探测电脑…")
|
||||||
wifiConnector.connect(
|
wifiConnector.connect(
|
||||||
pairing = pair,
|
pairing = pair,
|
||||||
onStatus = { message -> runOnUiThread { updateConnectingStatus(message) } },
|
onStatus = { message -> runOnUiThread {
|
||||||
onAvailable = { network ->
|
if (attempt == pairConnectionAttempt) updateConnectingStatus(message)
|
||||||
|
} },
|
||||||
|
onAvailable = available@{ network ->
|
||||||
|
if (attempt != pairConnectionAttempt) return@available
|
||||||
connectedNetwork = network
|
connectedNetwork = network
|
||||||
transferExecutor.execute {
|
transferExecutor.execute {
|
||||||
|
if (attempt != pairConnectionAttempt) return@execute
|
||||||
runOnUiThread { updateConnectingStatus("网络路由已就绪 · 正在 UDP 快速发现电脑…") }
|
runOnUiThread { updateConnectingStatus("网络路由已就绪 · 正在 UDP 快速发现电脑…") }
|
||||||
val discovered = UploadClient.discoverUdp(
|
val discovered = UploadClient.discoverUdp(
|
||||||
network = network,
|
network = network,
|
||||||
@@ -479,16 +622,35 @@ class MainActivity : ComponentActivity() {
|
|||||||
subnetEndpoints = subnet,
|
subnetEndpoints = subnet,
|
||||||
)
|
)
|
||||||
runOnUiThread {
|
runOnUiThread {
|
||||||
|
if (attempt != pairConnectionAttempt) return@runOnUiThread
|
||||||
if (base == null) {
|
if (base == null) {
|
||||||
showPairError(pair, "Wi-Fi 已连接,但快速发现、网关探测和当前子网扫描都未找到 QFT 接收服务。请保持 Windows 接收页开启,并在 Windows 防火墙首次弹窗时允许 QFT 访问专用网络。")
|
showPairError(pair, "Wi-Fi 已连接,但快速发现、网关探测和当前子网扫描都未找到 QFT 接收服务。请保持 Windows 接收页开启,并在 Windows 防火墙首次弹窗时允许 QFT 访问专用网络。")
|
||||||
} else {
|
} else {
|
||||||
connectedBaseUrl = base
|
connectedBaseUrl = base
|
||||||
showSendReady(pair, base)
|
if (pair.direction == TransferDirection.DOWNLOAD_TO_PHONE) {
|
||||||
|
startDownloadFromPc(pair, base)
|
||||||
|
} else {
|
||||||
|
showSendReady(pair, base)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
onUnavailable = { message -> runOnUiThread { showPairError(pair, message) } },
|
onUnavailable = { message -> runOnUiThread {
|
||||||
|
if (attempt != pairConnectionAttempt) return@runOnUiThread
|
||||||
|
// Huawei can report onLost while a bound local-only HTTP
|
||||||
|
// socket is unwinding. Let DownloadClient surface its precise
|
||||||
|
// HTTP/timeout cause instead of replacing it with this generic
|
||||||
|
// message mid-retry.
|
||||||
|
if (pair.direction == TransferDirection.DOWNLOAD_TO_PHONE && downloadRunning) {
|
||||||
|
downloadStatusText?.apply {
|
||||||
|
text = "QFT 本地网络已断开,正在结束当前下载请求…"
|
||||||
|
setTextColor(WARNING)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
showPairError(pair, message)
|
||||||
|
}
|
||||||
|
} },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -518,6 +680,13 @@ class MainActivity : ComponentActivity() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun showPairError(pair: PairingPayload?, message: String) {
|
private fun showPairError(pair: PairingPayload?, message: String) {
|
||||||
|
// Do not unregister here: Android may still be displaying its
|
||||||
|
// Wi-Fi-selection sheet, and unregistering at that moment produces
|
||||||
|
// "the app cancelled the device selection request". The next attempt
|
||||||
|
// (or returning home) releases the previous request safely.
|
||||||
|
pairConnectionAttempt++
|
||||||
|
connectedNetwork = null
|
||||||
|
connectedBaseUrl = null
|
||||||
val root = pageColumn()
|
val root = pageColumn()
|
||||||
root.addView(text("连接未完成", 28f, Color.WHITE, true))
|
root.addView(text("连接未完成", 28f, Color.WHITE, true))
|
||||||
root.addView(text(message, 15f, WARNING), matchWrap(top = 12))
|
root.addView(text(message, 15f, WARNING), matchWrap(top = 12))
|
||||||
@@ -572,6 +741,65 @@ class MainActivity : ComponentActivity() {
|
|||||||
renderSelectedFiles()
|
renderSelectedFiles()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun startDownloadFromPc(pair: PairingPayload, baseUrl: String) {
|
||||||
|
val fileName = pair.fileName ?: "qft-download.bin"
|
||||||
|
val total = pair.fileSize ?: 0L
|
||||||
|
val root = pageColumn()
|
||||||
|
root.addView(text("正在接收文件", 28f, Color.WHITE, true))
|
||||||
|
root.addView(text("${pair.pcName} → $receiverDeviceLabel", 16f, ACCENT))
|
||||||
|
root.addView(space(18))
|
||||||
|
root.addView(card().apply {
|
||||||
|
addView(text("扫码配置已完成", 17f, SUCCESS, true))
|
||||||
|
addView(text("电脑已自动确认会话,正在通过本地网络直接传输。", 14f, MUTED), matchWrap(top = 8))
|
||||||
|
addView(text(fileName, 15f, Color.WHITE), matchWrap(top = 12))
|
||||||
|
addView(text(humanBytes(total), 13f, MUTED), matchWrap(top = 4))
|
||||||
|
})
|
||||||
|
root.addView(space(14))
|
||||||
|
val status = text("正在建立文件下载…", 14f, MUTED)
|
||||||
|
downloadStatusText = status
|
||||||
|
val bar = ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal).apply { max = 1000 }
|
||||||
|
root.addView(status)
|
||||||
|
root.addView(bar, LinearLayout.LayoutParams(-1, dp(9)).apply { topMargin = dp(12) })
|
||||||
|
root.addView(space(18))
|
||||||
|
root.addView(button("取消并返回首页").apply { setOnClickListener { showHome() } })
|
||||||
|
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
|
||||||
|
|
||||||
|
downloadRunning = true
|
||||||
|
transferExecutor.execute {
|
||||||
|
try {
|
||||||
|
val startedAt = android.os.SystemClock.elapsedRealtime()
|
||||||
|
val saved = DownloadClient.download(
|
||||||
|
context = this@MainActivity,
|
||||||
|
resolver = contentResolver,
|
||||||
|
network = connectedNetwork,
|
||||||
|
baseUrl = baseUrl,
|
||||||
|
pairing = pair,
|
||||||
|
deviceName = receiverDeviceLabel,
|
||||||
|
) { received, expected ->
|
||||||
|
runOnUiThread {
|
||||||
|
val fraction = if (expected <= 0) 0 else ((received * 1000L) / expected).toInt().coerceIn(0, 1000)
|
||||||
|
val elapsed = (android.os.SystemClock.elapsedRealtime() - startedAt).coerceAtLeast(1L)
|
||||||
|
val rate = received * 1000.0 / elapsed
|
||||||
|
bar.progress = fraction
|
||||||
|
status.text = "${humanBytes(received)} / ${humanBytes(expected)} · ${humanBytes(rate.toLong())}/s"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
runOnUiThread {
|
||||||
|
bar.progress = 1000
|
||||||
|
status.setTextColor(SUCCESS)
|
||||||
|
status.text = "接收完成:已保存到 Downloads/QFT/${saved.name}"
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
runOnUiThread {
|
||||||
|
downloadRunning = false
|
||||||
|
showPairError(pair, "从电脑接收失败:${e.message}")
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
downloadRunning = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun renderSelectedFiles() {
|
private fun renderSelectedFiles() {
|
||||||
val total = selectedFiles.sumOf { it.size }
|
val total = selectedFiles.sumOf { it.size }
|
||||||
sendFilesText?.text = if (selectedFiles.isEmpty()) {
|
sendFilesText?.text = if (selectedFiles.isEmpty()) {
|
||||||
@@ -671,6 +899,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
qrLockOverlay = null
|
qrLockOverlay = null
|
||||||
scannerStatsText = null
|
scannerStatsText = null
|
||||||
scannerLockText = null
|
scannerLockText = null
|
||||||
|
scannerZoomText = null
|
||||||
scannerMode = ScannerMode.NONE
|
scannerMode = ScannerMode.NONE
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -762,6 +991,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
private const val TAG = "QftCamera"
|
||||||
private const val BG = 0xFF0B0E13.toInt()
|
private const val BG = 0xFF0B0E13.toInt()
|
||||||
private const val CARD = 0xFF151A22.toInt()
|
private const val CARD = 0xFF151A22.toInt()
|
||||||
private const val MUTED = 0xFF9AA4B2.toInt()
|
private const val MUTED = 0xFF9AA4B2.toInt()
|
||||||
|
|||||||
@@ -17,29 +17,45 @@ data class PairingPayload(
|
|||||||
val port: Int,
|
val port: Int,
|
||||||
val endpoints: List<String>,
|
val endpoints: List<String>,
|
||||||
val wifi: WifiCredentials?,
|
val wifi: WifiCredentials?,
|
||||||
|
val direction: TransferDirection = TransferDirection.UPLOAD_TO_PC,
|
||||||
|
val fileName: String? = null,
|
||||||
|
val fileSize: Long? = null,
|
||||||
|
val sha256: String? = null,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
enum class TransferDirection { UPLOAD_TO_PC, DOWNLOAD_TO_PHONE }
|
||||||
|
|
||||||
object PairingProtocol {
|
object PairingProtocol {
|
||||||
const val PREFIX_V2 = "QFTPAIR2:"
|
const val PREFIX_V2 = "QFTPAIR2:"
|
||||||
|
const val PREFIX_SEND_V2 = "QFTSEND2:"
|
||||||
const val PREFIX_V1 = "QFTPAIR1:"
|
const val PREFIX_V1 = "QFTPAIR1:"
|
||||||
|
|
||||||
fun isPairingText(text: String): Boolean = text.startsWith(PREFIX_V2) || text.startsWith(PREFIX_V1)
|
fun isPairingText(text: String): Boolean =
|
||||||
|
text.startsWith(PREFIX_V2) || text.startsWith(PREFIX_SEND_V2) || text.startsWith(PREFIX_V1)
|
||||||
|
|
||||||
fun parse(text: String): PairingPayload? {
|
fun parse(text: String): PairingPayload? {
|
||||||
if (text.length > 4096) return null
|
if (text.length > 4096) return null
|
||||||
return when {
|
return when {
|
||||||
text.startsWith(PREFIX_V2) -> parseV2(text.substring(PREFIX_V2.length))
|
text.startsWith(PREFIX_V2) -> parseV2(text.substring(PREFIX_V2.length), TransferDirection.UPLOAD_TO_PC)
|
||||||
|
text.startsWith(PREFIX_SEND_V2) -> parseV2(text.substring(PREFIX_SEND_V2.length), TransferDirection.DOWNLOAD_TO_PHONE)
|
||||||
text.startsWith(PREFIX_V1) -> parseV1(text.substring(PREFIX_V1.length))
|
text.startsWith(PREFIX_V1) -> parseV1(text.substring(PREFIX_V1.length))
|
||||||
else -> null
|
else -> null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun parseV2(encoded: String): PairingPayload? {
|
private fun parseV2(encoded: String, expectedDirection: TransferDirection): PairingPayload? {
|
||||||
return try {
|
return try {
|
||||||
val jsonBytes = decodeUrlBase64(encoded) ?: return null
|
val jsonBytes = decodeUrlBase64(encoded) ?: return null
|
||||||
if (jsonBytes.size > 2048) return null
|
if (jsonBytes.size > 2048) return null
|
||||||
val obj = JSONObject(jsonBytes.toString(Charsets.UTF_8))
|
val obj = JSONObject(jsonBytes.toString(Charsets.UTF_8))
|
||||||
if (obj.optInt("v", 0) != 2) return null
|
if (obj.optInt("v", 0) != 2) return null
|
||||||
|
val encodedDirection = obj.optString("d", "u")
|
||||||
|
val direction = when (encodedDirection) {
|
||||||
|
"u" -> TransferDirection.UPLOAD_TO_PC
|
||||||
|
"d" -> TransferDirection.DOWNLOAD_TO_PHONE
|
||||||
|
else -> return null
|
||||||
|
}
|
||||||
|
if (direction != expectedDirection) return null
|
||||||
|
|
||||||
val session = obj.getString("s")
|
val session = obj.getString("s")
|
||||||
if (!validSession(session)) return null
|
if (!validSession(session)) return null
|
||||||
@@ -65,6 +81,16 @@ object PairingProtocol {
|
|||||||
// and the actual Wi-Fi gateway are probed after Android obtains an IP.
|
// and the actual Wi-Fi gateway are probed after Android obtains an IP.
|
||||||
if (wifi == null && endpoints.isEmpty()) return null
|
if (wifi == null && endpoints.isEmpty()) return null
|
||||||
|
|
||||||
|
val fileName = if (direction == TransferDirection.DOWNLOAD_TO_PHONE) {
|
||||||
|
obj.optString("f").trim().takeIf { validFileName(it) } ?: return null
|
||||||
|
} else null
|
||||||
|
val fileSize = if (direction == TransferDirection.DOWNLOAD_TO_PHONE) {
|
||||||
|
obj.optLong("z", -1L).takeIf { it >= 0L } ?: return null
|
||||||
|
} else null
|
||||||
|
val sha = if (direction == TransferDirection.DOWNLOAD_TO_PHONE) {
|
||||||
|
obj.optString("h").lowercase().takeIf { it.matches(Regex("^[0-9a-f]{64}$")) } ?: return null
|
||||||
|
} else null
|
||||||
|
|
||||||
PairingPayload(
|
PairingPayload(
|
||||||
version = 2,
|
version = 2,
|
||||||
session = session,
|
session = session,
|
||||||
@@ -73,6 +99,10 @@ object PairingProtocol {
|
|||||||
port = port,
|
port = port,
|
||||||
endpoints = endpoints,
|
endpoints = endpoints,
|
||||||
wifi = wifi,
|
wifi = wifi,
|
||||||
|
direction = direction,
|
||||||
|
fileName = fileName,
|
||||||
|
fileSize = fileSize,
|
||||||
|
sha256 = sha,
|
||||||
)
|
)
|
||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
null
|
null
|
||||||
@@ -118,6 +148,7 @@ object PairingProtocol {
|
|||||||
port = port,
|
port = port,
|
||||||
endpoints = endpoints,
|
endpoints = endpoints,
|
||||||
wifi = wifi,
|
wifi = wifi,
|
||||||
|
direction = TransferDirection.UPLOAD_TO_PC,
|
||||||
)
|
)
|
||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
null
|
null
|
||||||
@@ -132,6 +163,10 @@ object PairingProtocol {
|
|||||||
return ssid.isNotBlank() && ssid.toByteArray(Charsets.UTF_8).size <= 32 && passphrase.length in 8..63
|
return ssid.isNotBlank() && ssid.toByteArray(Charsets.UTF_8).size <= 32 && passphrase.length in 8..63
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun validFileName(value: String): Boolean =
|
||||||
|
value.isNotBlank() && value.length <= 180 &&
|
||||||
|
value.none { it.code <= 31 || it.code == 127 || it in "\\/:*?\"<>|" }
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Pairing QR is treated as untrusted input. QFT only probes literal local
|
* Pairing QR is treated as untrusted input. QFT only probes literal local
|
||||||
* IPv4 addresses on the exact advertised port; public hosts and DNS names
|
* IPv4 addresses on the exact advertised port; public hosts and DNS names
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.qft.optical
|
package com.qft.optical
|
||||||
|
|
||||||
|
import android.util.Log
|
||||||
import androidx.camera.core.ImageAnalysis
|
import androidx.camera.core.ImageAnalysis
|
||||||
import androidx.camera.core.ImageProxy
|
import androidx.camera.core.ImageProxy
|
||||||
import com.google.zxing.BinaryBitmap
|
import com.google.zxing.BinaryBitmap
|
||||||
@@ -31,11 +32,14 @@ class QrAnalyzer(
|
|||||||
cameraFramesPerSecond: Double,
|
cameraFramesPerSecond: Double,
|
||||||
decodedPerSecond: Double,
|
decodedPerSecond: Double,
|
||||||
distinctPerSecond: Double,
|
distinctPerSecond: Double,
|
||||||
|
decodeAttemptsPerSecond: Double,
|
||||||
averageDecodeMs: Double,
|
averageDecodeMs: Double,
|
||||||
) -> Unit = { _, _, _, _ -> },
|
) -> Unit = { _, _, _, _, _ -> },
|
||||||
private val onLock: (ScannerLockState) -> Unit = {},
|
private val onLock: (ScannerLockState) -> Unit = {},
|
||||||
) : ImageAnalysis.Analyzer {
|
) : ImageAnalysis.Analyzer {
|
||||||
|
private companion object { const val TAG = "QftScan" }
|
||||||
enum class Profile { PAIR_FAST, OPTICAL_LOCKED }
|
enum class Profile { PAIR_FAST, OPTICAL_LOCKED }
|
||||||
|
private enum class BinarizerMode { GLOBAL, HYBRID }
|
||||||
|
|
||||||
private val reader = QRCodeReader()
|
private val reader = QRCodeReader()
|
||||||
private val grayBuffer = GrayFrameBuffer()
|
private val grayBuffer = GrayFrameBuffer()
|
||||||
@@ -49,8 +53,22 @@ class QrAnalyzer(
|
|||||||
|
|
||||||
private var lockRegion: LockRect? = null
|
private var lockRegion: LockRect? = null
|
||||||
private var lockMisses = 0
|
private var lockMisses = 0
|
||||||
|
private var lastMeasuredLock: LockRect? = null
|
||||||
|
private var stableLockHits = 0
|
||||||
private var lastReportedLock: LockRect? = null
|
private var lastReportedLock: LockRect? = null
|
||||||
private var lastLockFlag = false
|
private var lastLockFlag = false
|
||||||
|
// Do not run Global and Hybrid thresholding on every locked frame. That
|
||||||
|
// doubled ZXing work and could make a 30 FPS camera deliver only ~25
|
||||||
|
// analyzable frames. Keep the last working method and probe the other one
|
||||||
|
// only after a sustained miss.
|
||||||
|
private var lockedBinarizer = BinarizerMode.GLOBAL
|
||||||
|
private var lockedBinarizerMisses = 0
|
||||||
|
|
||||||
|
// Pairing codes remain static long enough to benefit from the same ROI
|
||||||
|
// strategy as optical QFT2 frames. It removes the 82% frame copy and most
|
||||||
|
// finder-pattern work after the first successful pairing decode.
|
||||||
|
private var pairRegion: LockRect? = null
|
||||||
|
private var pairMisses = 0
|
||||||
|
|
||||||
override fun analyze(image: ImageProxy) {
|
override fun analyze(image: ImageProxy) {
|
||||||
try {
|
try {
|
||||||
@@ -80,16 +98,55 @@ class QrAnalyzer(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun decodePair(image: ImageProxy): Result? {
|
private fun decodePair(image: ImageProxy): Result? {
|
||||||
// Pairing QR is static. Center-first keeps the common path cheap while
|
val locked = pairRegion
|
||||||
// still allowing off-center framing every second frame.
|
if (locked != null) {
|
||||||
|
val crop = grayBuffer.capture(image, locked)
|
||||||
|
decodeDense(crop, hybrid = false)?.let { result ->
|
||||||
|
updatePairRegion(result, crop)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
// On an already small, known QR ROI the adaptive threshold costs
|
||||||
|
// little and recovers display PWM/moire frames that global
|
||||||
|
// thresholding misses. This is the main path to keep successful
|
||||||
|
// decodes close to the camera's delivered frame rate.
|
||||||
|
decodeDense(crop, hybrid = true)?.let { result ->
|
||||||
|
updatePairRegion(result, crop)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
pairMisses++
|
||||||
|
when (pairMisses) {
|
||||||
|
2 -> pairRegion = locked.expand(image.width, image.height, 1.18f)
|
||||||
|
6 -> {
|
||||||
|
pairRegion = null
|
||||||
|
pairMisses = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
// Acquisition is center-first, but unlike the old path it establishes
|
||||||
|
// a QR ROI immediately after the first hit. Full-frame work is only a
|
||||||
|
// recovery path for deliberately off-center QR codes.
|
||||||
val center = LockRect.centeredSearch(image.width, image.height, 0.82f)
|
val center = LockRect.centeredSearch(image.width, image.height, 0.82f)
|
||||||
val centered = grayBuffer.capture(image, center)
|
val centered = grayBuffer.capture(image, center)
|
||||||
decodeDense(centered, hybrid = false)?.let { return it }
|
decodeDense(centered, hybrid = false)?.let { result ->
|
||||||
|
updatePairRegion(result, centered)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
if (frameCounter % 2L == 0L) {
|
if (frameCounter % 3L == 0L) {
|
||||||
|
decodeDense(centered, hybrid = true)?.let { result ->
|
||||||
|
updatePairRegion(result, centered)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (frameCounter % 4L == 0L) {
|
||||||
val full = grayBuffer.capture(image)
|
val full = grayBuffer.capture(image)
|
||||||
decodeDense(full, hybrid = false)?.let { return it }
|
decodeDense(full, hybrid = false)?.let { result ->
|
||||||
if (frameCounter % 6L == 0L) decodeDense(full, hybrid = true)?.let { return it }
|
updatePairRegion(result, full)
|
||||||
|
return result
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
@@ -100,23 +157,28 @@ class QrAnalyzer(
|
|||||||
// Fast hot path: only copy/decode the locked ROI. Most phones spend
|
// Fast hot path: only copy/decode the locked ROI. Most phones spend
|
||||||
// far less time here than repeatedly scanning the entire frame.
|
// far less time here than repeatedly scanning the entire frame.
|
||||||
val crop = grayBuffer.capture(image, current)
|
val crop = grayBuffer.capture(image, current)
|
||||||
decodeDense(crop, hybrid = false)?.let { result ->
|
val preferredHybrid = lockedBinarizer == BinarizerMode.HYBRID
|
||||||
lockMisses = 0
|
decodeDense(crop, hybrid = preferredHybrid)?.let { result ->
|
||||||
updateLockFromResult(result, crop)
|
acceptLockedResult(result, crop, preferredHybrid)
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
lockMisses++
|
lockedBinarizerMisses++
|
||||||
// HybridBinarizer is slower but more robust against moire/exposure.
|
// A first Global miss commonly means display PWM/moire has made a
|
||||||
// Use it sparingly rather than doubling work on every camera frame.
|
// global threshold unsuitable. Switch immediately to Hybrid. Once
|
||||||
if (lockMisses % 4 == 0) {
|
// Hybrid is working, check Global only once every six misses so the
|
||||||
decodeDense(crop, hybrid = true)?.let { result ->
|
// hot path stays at one ZXing decode per camera frame.
|
||||||
lockMisses = 0
|
val tryAlternative = !preferredHybrid || lockedBinarizerMisses >= 6
|
||||||
updateLockFromResult(result, crop)
|
if (tryAlternative && current.areaFraction(image.width, image.height) <= 0.72f) {
|
||||||
|
decodeDense(crop, hybrid = !preferredHybrid)?.let { result ->
|
||||||
|
acceptLockedResult(result, crop, !preferredHybrid)
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
if (preferredHybrid) lockedBinarizerMisses = 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
lockMisses++
|
||||||
|
|
||||||
// Follow small hand movement without immediately returning to a
|
// Follow small hand movement without immediately returning to a
|
||||||
// costly full-frame search. Only unlock after sustained misses.
|
// costly full-frame search. Only unlock after sustained misses.
|
||||||
if (lockMisses == 3 || lockMisses == 6) {
|
if (lockMisses == 3 || lockMisses == 6) {
|
||||||
@@ -130,6 +192,10 @@ class QrAnalyzer(
|
|||||||
if (lockMisses >= 10) {
|
if (lockMisses >= 10) {
|
||||||
lockRegion = null
|
lockRegion = null
|
||||||
lockMisses = 0
|
lockMisses = 0
|
||||||
|
lastMeasuredLock = null
|
||||||
|
stableLockHits = 0
|
||||||
|
lockedBinarizer = BinarizerMode.GLOBAL
|
||||||
|
lockedBinarizerMisses = 0
|
||||||
publishLock(image, locked = false)
|
publishLock(image, locked = false)
|
||||||
}
|
}
|
||||||
return null
|
return null
|
||||||
@@ -162,6 +228,13 @@ class QrAnalyzer(
|
|||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun acceptLockedResult(result: Result, crop: GrayFrame, usedHybrid: Boolean) {
|
||||||
|
lockedBinarizer = if (usedHybrid) BinarizerMode.HYBRID else BinarizerMode.GLOBAL
|
||||||
|
lockedBinarizerMisses = 0
|
||||||
|
lockMisses = 0
|
||||||
|
updateLockFromResult(result, crop)
|
||||||
|
}
|
||||||
|
|
||||||
private fun decodeDense(gray: GrayFrame, hybrid: Boolean): Result? {
|
private fun decodeDense(gray: GrayFrame, hybrid: Boolean): Result? {
|
||||||
if (gray.width < 96 || gray.height < 96) return null
|
if (gray.width < 96 || gray.height < 96) return null
|
||||||
val source = PlanarYUVLuminanceSource(
|
val source = PlanarYUVLuminanceSource(
|
||||||
@@ -199,9 +272,18 @@ class QrAnalyzer(
|
|||||||
val measured = LockRect.fromPoints(points, gray.fullWidth, gray.fullHeight)
|
val measured = LockRect.fromPoints(points, gray.fullWidth, gray.fullHeight)
|
||||||
?: lockRegion
|
?: lockRegion
|
||||||
?: LockRect.centeredSearch(gray.fullWidth, gray.fullHeight, 0.62f)
|
?: LockRect.centeredSearch(gray.fullWidth, gray.fullHeight, 0.62f)
|
||||||
// Smooth small finder-point jitter so the crop and on-screen overlay do
|
// Consecutive matching finder geometry drives a small confidence meter.
|
||||||
// not visibly vibrate while a dynamic QR is changing every frame.
|
// A fresh/unstable lock follows the code quickly; after three consistent
|
||||||
val next = lockRegion?.smoothToward(measured, 0.30f) ?: measured
|
// hits it switches to slower smoothing, preventing the visible ROI from
|
||||||
|
// vibrating when 45/60 Hz QR frames are decoded.
|
||||||
|
stableLockHits = if (measured.overlap(lastMeasuredLock) >= 0.62f) {
|
||||||
|
(stableLockHits + 1).coerceAtMost(6)
|
||||||
|
} else {
|
||||||
|
1
|
||||||
|
}
|
||||||
|
lastMeasuredLock = measured
|
||||||
|
val alpha = if (stableLockHits >= 3) 0.22f else 0.42f
|
||||||
|
val next = lockRegion?.smoothToward(measured, alpha) ?: measured
|
||||||
val changed = next.materiallyDiffers(lockRegion)
|
val changed = next.materiallyDiffers(lockRegion)
|
||||||
lockRegion = next
|
lockRegion = next
|
||||||
lockMisses = 0
|
lockMisses = 0
|
||||||
@@ -215,6 +297,18 @@ class QrAnalyzer(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun updatePairRegion(result: Result, gray: GrayFrame) {
|
||||||
|
val points = result.resultPoints
|
||||||
|
?.map { (it.x + gray.originX) to (it.y + gray.originY) }
|
||||||
|
.orEmpty()
|
||||||
|
val measured = LockRect.fromPoints(points, gray.fullWidth, gray.fullHeight)
|
||||||
|
?.expand(gray.fullWidth, gray.fullHeight, 1.10f)
|
||||||
|
?: pairRegion
|
||||||
|
?: LockRect.centeredSearch(gray.fullWidth, gray.fullHeight, 0.72f)
|
||||||
|
pairRegion = pairRegion?.smoothToward(measured, 0.30f) ?: measured
|
||||||
|
pairMisses = 0
|
||||||
|
}
|
||||||
|
|
||||||
private fun publishLock(image: ImageProxy, locked: Boolean) {
|
private fun publishLock(image: ImageProxy, locked: Boolean) {
|
||||||
publishLock(image.width, image.height, image.imageInfo.rotationDegrees, locked)
|
publishLock(image.width, image.height, image.imageInfo.rotationDegrees, locked)
|
||||||
}
|
}
|
||||||
@@ -235,6 +329,7 @@ class QrAnalyzer(
|
|||||||
rotationDegrees = rotationDegrees,
|
rotationDegrees = rotationDegrees,
|
||||||
misses = lockMisses,
|
misses = lockMisses,
|
||||||
searchAreaFraction = region?.areaFraction(frameWidth, frameHeight) ?: 1f,
|
searchAreaFraction = region?.areaFraction(frameWidth, frameHeight) ?: 1f,
|
||||||
|
stability = (stableLockHits / 3f).coerceIn(0f, 1f),
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -245,7 +340,21 @@ class QrAnalyzer(
|
|||||||
if (elapsed < 1000L) return
|
if (elapsed < 1000L) return
|
||||||
val seconds = elapsed / 1000.0
|
val seconds = elapsed / 1000.0
|
||||||
val averageMs = if (decodeAttempts == 0L) 0.0 else decodeNanos / 1_000_000.0 / decodeAttempts
|
val averageMs = if (decodeAttempts == 0L) 0.0 else decodeNanos / 1_000_000.0 / decodeAttempts
|
||||||
onStats(frameCounter / seconds, decodedCounter / seconds, distinctCounter / seconds, averageMs)
|
onStats(
|
||||||
|
frameCounter / seconds,
|
||||||
|
decodedCounter / seconds,
|
||||||
|
distinctCounter / seconds,
|
||||||
|
decodeAttempts / seconds,
|
||||||
|
averageMs,
|
||||||
|
)
|
||||||
|
Log.i(
|
||||||
|
TAG,
|
||||||
|
"profile=$profile input=${"%.1f".format(frameCounter / seconds)} " +
|
||||||
|
"success=${"%.1f".format(decodedCounter / seconds)} " +
|
||||||
|
"distinct=${"%.1f".format(distinctCounter / seconds)} " +
|
||||||
|
"attempts=${"%.1f".format(decodeAttempts / seconds)} " +
|
||||||
|
"avg=${"%.1f".format(averageMs)}ms locked=${lockRegion != null}",
|
||||||
|
)
|
||||||
frameCounter = 0
|
frameCounter = 0
|
||||||
decodedCounter = 0
|
decodedCounter = 0
|
||||||
distinctCounter = 0
|
distinctCounter = 0
|
||||||
|
|||||||
@@ -64,7 +64,11 @@ class QrLockOverlay(context: Context) : View(context) {
|
|||||||
|
|
||||||
val rect = mapRegionToView(region, s)
|
val rect = mapRegionToView(region, s)
|
||||||
val radius = resources.displayMetrics.density * 14f
|
val radius = resources.displayMetrics.density * 14f
|
||||||
stroke.color = if (s.misses <= 2) 0xFF20E3A2.toInt() else 0xFFFFC857.toInt()
|
stroke.color = when {
|
||||||
|
s.misses > 2 -> 0xFFFFC857.toInt()
|
||||||
|
s.stability < 0.67f -> 0xFF6EA8FF.toInt()
|
||||||
|
else -> 0xFF20E3A2.toInt()
|
||||||
|
}
|
||||||
val pulse = ((android.os.SystemClock.uptimeMillis() / 180L) % 2L).toFloat()
|
val pulse = ((android.os.SystemClock.uptimeMillis() / 180L) % 2L).toFloat()
|
||||||
stroke.strokeWidth = resources.displayMetrics.density * (if (pulse < 0.5f) 2.6f else 3.4f)
|
stroke.strokeWidth = resources.displayMetrics.density * (if (pulse < 0.5f) 2.6f else 3.4f)
|
||||||
canvas.drawRoundRect(rect, radius, radius, fill)
|
canvas.drawRoundRect(rect, radius, radius, fill)
|
||||||
@@ -83,7 +87,11 @@ class QrLockOverlay(context: Context) : View(context) {
|
|||||||
// pixels or the ImageAnalysis thread.
|
// pixels or the ImageAnalysis thread.
|
||||||
val phase = (android.os.SystemClock.uptimeMillis() % 1200L) / 1200f
|
val phase = (android.os.SystemClock.uptimeMillis() % 1200L) / 1200f
|
||||||
val scanY = rect.top + rect.height() * phase
|
val scanY = rect.top + rect.height() * phase
|
||||||
sweep.color = if (s.misses <= 2) 0x9920E3A2.toInt() else 0x99FFC857.toInt()
|
sweep.color = when {
|
||||||
|
s.misses > 2 -> 0x99FFC857.toInt()
|
||||||
|
s.stability < 0.67f -> 0x996EA8FF.toInt()
|
||||||
|
else -> 0x9920E3A2.toInt()
|
||||||
|
}
|
||||||
canvas.drawLine(rect.left + rect.width() * 0.08f, scanY, rect.right - rect.width() * 0.08f, scanY, sweep)
|
canvas.drawLine(rect.left + rect.width() * 0.08f, scanY, rect.right - rect.width() * 0.08f, scanY, sweep)
|
||||||
postInvalidateDelayed(100L)
|
postInvalidateDelayed(100L)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,4 +8,6 @@ data class ScannerLockState(
|
|||||||
val rotationDegrees: Int,
|
val rotationDegrees: Int,
|
||||||
val misses: Int,
|
val misses: Int,
|
||||||
val searchAreaFraction: Float,
|
val searchAreaFraction: Float,
|
||||||
|
/** 0..1 confidence from consecutive, spatially consistent QR detections. */
|
||||||
|
val stability: Float,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -34,6 +34,10 @@ object UploadClient {
|
|||||||
private const val CHUNK_LARGE = 16L * 1024L * 1024L
|
private const val CHUNK_LARGE = 16L * 1024L * 1024L
|
||||||
private const val MAX_WORKERS = 8
|
private const val MAX_WORKERS = 8
|
||||||
private const val STREAM_BUFFER = 1024 * 1024
|
private const val STREAM_BUFFER = 1024 * 1024
|
||||||
|
// QFT Direct can briefly reset a TCP flow while the Android network route
|
||||||
|
// settles. Chunk PUTs and the init/finish control calls are safe to retry;
|
||||||
|
// the Windows receiver treats a repeated chunk as an idempotent success.
|
||||||
|
private const val LOCAL_REQUEST_ATTEMPTS = 3
|
||||||
|
|
||||||
fun describeFile(resolver: ContentResolver, uri: Uri): SelectedFile? {
|
fun describeFile(resolver: ContentResolver, uri: Uri): SelectedFile? {
|
||||||
var name = "qft-upload.bin"
|
var name = "qft-upload.bin"
|
||||||
@@ -68,13 +72,15 @@ object UploadClient {
|
|||||||
return try {
|
return try {
|
||||||
network?.bindSocket(socket)
|
network?.bindSocket(socket)
|
||||||
socket.broadcast = true
|
socket.broadcast = true
|
||||||
socket.soTimeout = 220
|
socket.soTimeout = 160
|
||||||
val request = "QFTDISC2:${pairing.session}".toByteArray(Charsets.US_ASCII)
|
val request = "QFTDISC2:${pairing.session}".toByteArray(Charsets.US_ASCII)
|
||||||
repeat(3) {
|
// Two directed/broadcast bursts fit within the initial routing
|
||||||
|
// window while keeping service discovery below 600 ms.
|
||||||
|
repeat(2) {
|
||||||
for (host in hosts) {
|
for (host in hosts) {
|
||||||
try { socket.send(DatagramPacket(request, request.size, host, DISCOVERY_PORT)) } catch (_: Exception) {}
|
try { socket.send(DatagramPacket(request, request.size, host, DISCOVERY_PORT)) } catch (_: Exception) {}
|
||||||
}
|
}
|
||||||
val deadline = android.os.SystemClock.elapsedRealtime() + 320
|
val deadline = android.os.SystemClock.elapsedRealtime() + 240
|
||||||
while (android.os.SystemClock.elapsedRealtime() < deadline) {
|
while (android.os.SystemClock.elapsedRealtime() < deadline) {
|
||||||
val buf = ByteArray(512)
|
val buf = ByteArray(512)
|
||||||
val packet = DatagramPacket(buf, buf.size)
|
val packet = DatagramPacket(buf, buf.size)
|
||||||
@@ -117,13 +123,13 @@ object UploadClient {
|
|||||||
.filter { PairingProtocol.isAllowedLocalHttpEndpoint(it, pairing.port) }
|
.filter { PairingProtocol.isAllowedLocalHttpEndpoint(it, pairing.port) }
|
||||||
.distinct()
|
.distinct()
|
||||||
|
|
||||||
// Stage 1: expected gateway/QR addresses. Repeat quickly because a Wi-Fi
|
// Stage 1: QR-carried endpoints and actual gateway. This is the normal
|
||||||
// callback can precede ARP/firewall classification by a few hundred ms.
|
// path and must complete well inside the 10-second pairing budget.
|
||||||
val fastDeadline = android.os.SystemClock.elapsedRealtime() + 2_400
|
val fastDeadline = android.os.SystemClock.elapsedRealtime() + 1_050
|
||||||
while (fast.isNotEmpty() && android.os.SystemClock.elapsedRealtime() < fastDeadline) {
|
while (fast.isNotEmpty() && android.os.SystemClock.elapsedRealtime() < fastDeadline) {
|
||||||
probeCandidatesParallel(network, pairing, deviceName, fast, workers = 8, connectMs = 320, readMs = 380)
|
probeCandidatesParallel(network, pairing, deviceName, fast, workers = 12, connectMs = 220, readMs = 260)
|
||||||
?.let { return it }
|
?.let { return it }
|
||||||
try { Thread.sleep(90) } catch (_: InterruptedException) { return null }
|
try { Thread.sleep(60) } catch (_: InterruptedException) { return null }
|
||||||
}
|
}
|
||||||
|
|
||||||
// Stage 2: actual connected subnet fallback. This specifically fixes the
|
// Stage 2: actual connected subnet fallback. This specifically fixes the
|
||||||
@@ -135,16 +141,17 @@ object UploadClient {
|
|||||||
.filterNot { it in fast }
|
.filterNot { it in fast }
|
||||||
.distinct()
|
.distinct()
|
||||||
if (scan.isNotEmpty()) {
|
if (scan.isNotEmpty()) {
|
||||||
probeCandidatesParallel(network, pairing, deviceName, scan, workers = 24, connectMs = 240, readMs = 300)
|
probeCandidatesParallel(network, pairing, deviceName, scan, workers = 48, connectMs = 180, readMs = 220)
|
||||||
?.let { return it }
|
?.let { return it }
|
||||||
}
|
}
|
||||||
|
|
||||||
// Final short retry for the expected addresses after the subnet scan.
|
// One short final pass covers a just-finished ARP/Windows firewall
|
||||||
val deadline = android.os.SystemClock.elapsedRealtime() + 2_000
|
// transition without adding the former two-second tail latency.
|
||||||
|
val deadline = android.os.SystemClock.elapsedRealtime() + 500
|
||||||
while (fast.isNotEmpty() && android.os.SystemClock.elapsedRealtime() < deadline) {
|
while (fast.isNotEmpty() && android.os.SystemClock.elapsedRealtime() < deadline) {
|
||||||
probeCandidatesParallel(network, pairing, deviceName, fast, workers = 8, connectMs = 450, readMs = 500)
|
probeCandidatesParallel(network, pairing, deviceName, fast, workers = 12, connectMs = 240, readMs = 260)
|
||||||
?.let { return it }
|
?.let { return it }
|
||||||
try { Thread.sleep(120) } catch (_: InterruptedException) { return null }
|
try { Thread.sleep(50) } catch (_: InterruptedException) { return null }
|
||||||
}
|
}
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
@@ -169,7 +176,7 @@ object UploadClient {
|
|||||||
return try {
|
return try {
|
||||||
val overallMs = (connectMs + readMs + 150).toLong() *
|
val overallMs = (connectMs + readMs + 150).toLong() *
|
||||||
((candidates.size + workers - 1) / workers).coerceAtLeast(1)
|
((candidates.size + workers - 1) / workers).coerceAtLeast(1)
|
||||||
val deadline = android.os.SystemClock.elapsedRealtime() + overallMs.coerceAtMost(4_500L)
|
val deadline = android.os.SystemClock.elapsedRealtime() + overallMs.coerceAtMost(2_400L)
|
||||||
repeat(candidates.size) {
|
repeat(candidates.size) {
|
||||||
val remaining = deadline - android.os.SystemClock.elapsedRealtime()
|
val remaining = deadline - android.os.SystemClock.elapsedRealtime()
|
||||||
if (remaining <= 0) return null
|
if (remaining <= 0) return null
|
||||||
@@ -220,9 +227,13 @@ object UploadClient {
|
|||||||
uploadParallel(resolver, network, baseUrl, pairing, deviceName, file, onProgress)
|
uploadParallel(resolver, network, baseUrl, pairing, deviceName, file, onProgress)
|
||||||
return
|
return
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
// If the provider cannot sustain random access or the v2 endpoint
|
// Never mask a transient v2 failure by immediately switching to a
|
||||||
// is unavailable, preserve compatibility with the v1 stream path.
|
// second full-file stream (the old behavior produced the opaque
|
||||||
|
// `unexpected end of stream` shown by Android). Only a confirmed
|
||||||
|
// missing v2 endpoint uses the compatibility route.
|
||||||
if (e is SecurityException) throw e
|
if (e is SecurityException) throw e
|
||||||
|
val message = e.message.orEmpty()
|
||||||
|
if (!message.contains("HTTP 404") && !message.contains("HTTP 501")) throw e
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
uploadLegacy(resolver, network, baseUrl, pairing, deviceName, file, onProgress)
|
uploadLegacy(resolver, network, baseUrl, pairing, deviceName, file, onProgress)
|
||||||
@@ -230,6 +241,24 @@ object UploadClient {
|
|||||||
|
|
||||||
private data class InitReply(val uploadId: String, val chunkSize: Long, val totalChunks: Int)
|
private data class InitReply(val uploadId: String, val chunkSize: Long, val totalChunks: Int)
|
||||||
|
|
||||||
|
private fun <T> retryLocalRequest(label: String, block: () -> T): T {
|
||||||
|
var last: Throwable? = null
|
||||||
|
repeat(LOCAL_REQUEST_ATTEMPTS) { attempt ->
|
||||||
|
try {
|
||||||
|
return block()
|
||||||
|
} catch (e: Throwable) {
|
||||||
|
last = e
|
||||||
|
if (attempt + 1 < LOCAL_REQUEST_ATTEMPTS) {
|
||||||
|
try { Thread.sleep(120L * (attempt + 1)) } catch (_: InterruptedException) {
|
||||||
|
Thread.currentThread().interrupt()
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw IllegalStateException("$label after $LOCAL_REQUEST_ATTEMPTS attempts", last)
|
||||||
|
}
|
||||||
|
|
||||||
private fun uploadParallel(
|
private fun uploadParallel(
|
||||||
resolver: ContentResolver,
|
resolver: ContentResolver,
|
||||||
network: Network?,
|
network: Network?,
|
||||||
@@ -301,7 +330,7 @@ object UploadClient {
|
|||||||
private fun initUpload(
|
private fun initUpload(
|
||||||
network: Network?, baseUrl: String, pairing: PairingPayload,
|
network: Network?, baseUrl: String, pairing: PairingPayload,
|
||||||
deviceName: String, file: SelectedFile,
|
deviceName: String, file: SelectedFile,
|
||||||
): InitReply {
|
): InitReply = retryLocalRequest("本地上传初始化失败") {
|
||||||
val conn = open(network, URL("$baseUrl/qft/upload/init"))
|
val conn = open(network, URL("$baseUrl/qft/upload/init"))
|
||||||
try {
|
try {
|
||||||
conn.requestMethod = "POST"
|
conn.requestMethod = "POST"
|
||||||
@@ -318,7 +347,7 @@ object UploadClient {
|
|||||||
if (code != 200) error("初始化并行上传失败 HTTP $code")
|
if (code != 200) error("初始化并行上传失败 HTTP $code")
|
||||||
val body = conn.inputStream.bufferedReader().use { it.readText() }
|
val body = conn.inputStream.bufferedReader().use { it.readText() }
|
||||||
val obj = JSONObject(body)
|
val obj = JSONObject(body)
|
||||||
return InitReply(
|
InitReply(
|
||||||
uploadId = obj.getString("upload_id"),
|
uploadId = obj.getString("upload_id"),
|
||||||
chunkSize = obj.getLong("chunk_size"),
|
chunkSize = obj.getLong("chunk_size"),
|
||||||
totalChunks = obj.getInt("total_chunks"),
|
totalChunks = obj.getInt("total_chunks"),
|
||||||
@@ -332,7 +361,7 @@ object UploadClient {
|
|||||||
network: Network?, baseUrl: String, pairing: PairingPayload, deviceName: String,
|
network: Network?, baseUrl: String, pairing: PairingPayload, deviceName: String,
|
||||||
uploadId: String, index: Int, channel: FileChannel, offset: Long, length: Long,
|
uploadId: String, index: Int, channel: FileChannel, offset: Long, length: Long,
|
||||||
buffer: ByteBuffer,
|
buffer: ByteBuffer,
|
||||||
) {
|
) = retryLocalRequest("分块 $index 上传失败") {
|
||||||
val conn = open(network, URL("$baseUrl/qft/upload/chunk/$uploadId/$index"))
|
val conn = open(network, URL("$baseUrl/qft/upload/chunk/$uploadId/$index"))
|
||||||
try {
|
try {
|
||||||
conn.requestMethod = "POST"
|
conn.requestMethod = "POST"
|
||||||
@@ -370,7 +399,7 @@ object UploadClient {
|
|||||||
private fun finishUpload(
|
private fun finishUpload(
|
||||||
network: Network?, baseUrl: String, pairing: PairingPayload,
|
network: Network?, baseUrl: String, pairing: PairingPayload,
|
||||||
deviceName: String, uploadId: String,
|
deviceName: String, uploadId: String,
|
||||||
) {
|
) = retryLocalRequest("本地上传完成确认失败") {
|
||||||
val conn = open(network, URL("$baseUrl/qft/upload/finish/$uploadId"))
|
val conn = open(network, URL("$baseUrl/qft/upload/finish/$uploadId"))
|
||||||
try {
|
try {
|
||||||
conn.requestMethod = "POST"
|
conn.requestMethod = "POST"
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.qft.optical
|
package com.qft.optical
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
|
import androidx.annotation.RequiresApi
|
||||||
import android.net.ConnectivityManager
|
import android.net.ConnectivityManager
|
||||||
import android.net.LinkProperties
|
import android.net.LinkProperties
|
||||||
import android.net.Network
|
import android.net.Network
|
||||||
@@ -13,10 +14,13 @@ import android.os.Build
|
|||||||
import android.os.Handler
|
import android.os.Handler
|
||||||
import android.os.Looper
|
import android.os.Looper
|
||||||
import android.os.SystemClock
|
import android.os.SystemClock
|
||||||
|
import android.util.Log
|
||||||
import java.net.Inet4Address
|
import java.net.Inet4Address
|
||||||
import java.net.InetAddress
|
import java.net.InetAddress
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean
|
||||||
|
|
||||||
class WifiConnector(context: Context) {
|
class WifiConnector(context: Context) {
|
||||||
|
private companion object { const val TAG = "QftWifi" }
|
||||||
private val appContext = context.applicationContext
|
private val appContext = context.applicationContext
|
||||||
private val connectivity = appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
private val connectivity = appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
||||||
private val wifiManager = appContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
|
private val wifiManager = appContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
|
||||||
@@ -50,6 +54,8 @@ class WifiConnector(context: Context) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@RequiresApi(29)
|
||||||
|
@Suppress("MissingPermission")
|
||||||
private fun connectModern(
|
private fun connectModern(
|
||||||
run: Int,
|
run: Int,
|
||||||
wifi: WifiCredentials,
|
wifi: WifiCredentials,
|
||||||
@@ -58,6 +64,8 @@ class WifiConnector(context: Context) {
|
|||||||
onUnavailable: (String) -> Unit,
|
onUnavailable: (String) -> Unit,
|
||||||
) {
|
) {
|
||||||
onStatus("正在请求连接 ${wifi.ssid}…")
|
onStatus("正在请求连接 ${wifi.ssid}…")
|
||||||
|
Log.i(TAG, "attempt=$run request SSID=${wifi.ssid}")
|
||||||
|
onStatus("正在等待 Android 系统连接确认;确认后本页将继续显示进度")
|
||||||
val specifier = try {
|
val specifier = try {
|
||||||
WifiNetworkSpecifier.Builder()
|
WifiNetworkSpecifier.Builder()
|
||||||
.setSsid(wifi.ssid)
|
.setSsid(wifi.ssid)
|
||||||
@@ -73,14 +81,19 @@ class WifiConnector(context: Context) {
|
|||||||
.setNetworkSpecifier(specifier)
|
.setNetworkSpecifier(specifier)
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
val delivered = booleanArrayOf(false)
|
// Callbacks are delivered from framework threads while waitUntilUsable
|
||||||
|
// runs on the main handler. An AtomicBoolean prevents both paths from
|
||||||
|
// launching a duplicate probe/download for the same Wi-Fi connection.
|
||||||
|
val delivered = AtomicBoolean(false)
|
||||||
|
val terminal = AtomicBoolean(false)
|
||||||
val cb = object : ConnectivityManager.NetworkCallback() {
|
val cb = object : ConnectivityManager.NetworkCallback() {
|
||||||
override fun onAvailable(network: Network) {
|
override fun onAvailable(network: Network) {
|
||||||
if (run != generation) return
|
if (run != generation || terminal.get()) return
|
||||||
|
Log.i(TAG, "attempt=$run framework onAvailable network=$network")
|
||||||
onStatus("Wi-Fi 已关联,正在等待本地 IP/路由…")
|
onStatus("Wi-Fi 已关联,正在等待本地 IP/路由…")
|
||||||
waitUntilUsable(run, network, onStatus) {
|
waitUntilUsable(run, network, onStatus) {
|
||||||
if (!delivered[0] && run == generation) {
|
if (run == generation && !terminal.get() && delivered.compareAndSet(false, true)) {
|
||||||
delivered[0] = true
|
Log.i(TAG, "attempt=$run route ready network=$network")
|
||||||
onStatus("QFT 本地网络已就绪,正在快速发现电脑…")
|
onStatus("QFT 本地网络已就绪,正在快速发现电脑…")
|
||||||
onAvailable(network)
|
onAvailable(network)
|
||||||
}
|
}
|
||||||
@@ -88,27 +101,37 @@ class WifiConnector(context: Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun onLinkPropertiesChanged(network: Network, linkProperties: LinkProperties) {
|
override fun onLinkPropertiesChanged(network: Network, linkProperties: LinkProperties) {
|
||||||
if (run != generation || delivered[0]) return
|
if (run != generation || terminal.get() || delivered.get()) return
|
||||||
if (hasIpv4(linkProperties)) {
|
if (hasIpv4(linkProperties) && delivered.compareAndSet(false, true)) {
|
||||||
delivered[0] = true
|
Log.i(TAG, "attempt=$run IPv4 ready network=$network")
|
||||||
onStatus("QFT 本地网络已就绪,正在快速发现电脑…")
|
onStatus("QFT 本地网络已就绪,正在快速发现电脑…")
|
||||||
onAvailable(network)
|
onAvailable(network)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onUnavailable() {
|
override fun onUnavailable() {
|
||||||
|
if (run != generation || !terminal.compareAndSet(false, true)) return
|
||||||
|
Log.w(TAG, "attempt=$run framework onUnavailable")
|
||||||
if (run == generation) onUnavailable("未能连接 QFT 临时网络。请确认 Wi-Fi 已开启并批准系统连接请求。")
|
if (run == generation) onUnavailable("未能连接 QFT 临时网络。请确认 Wi-Fi 已开启并批准系统连接请求。")
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onLost(network: Network) {
|
override fun onLost(network: Network) {
|
||||||
if (run == generation && delivered[0]) onUnavailable("QFT 临时网络已断开")
|
if (run != generation || !delivered.get() || !terminal.compareAndSet(false, true)) return
|
||||||
|
Log.w(TAG, "attempt=$run network lost network=$network")
|
||||||
|
if (run == generation && delivered.get()) onUnavailable("QFT 临时网络已断开")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
callback = cb
|
callback = cb
|
||||||
try {
|
try {
|
||||||
connectivity.requestNetwork(request, cb, 15_000)
|
// Do not give the framework a short request timeout here. Android
|
||||||
|
// closes an outstanding WifiNetworkSpecifier chooser at timeout
|
||||||
|
// and shows the misleading "the app cancelled the device
|
||||||
|
// selection request" message. The user can explicitly cancel the
|
||||||
|
// system sheet; otherwise keep this request alive while our page
|
||||||
|
// continues to show connection progress.
|
||||||
|
connectivity.requestNetwork(request, cb)
|
||||||
handler.postDelayed({
|
handler.postDelayed({
|
||||||
if (run == generation && !delivered[0]) {
|
if (run == generation && !terminal.get() && !delivered.get()) {
|
||||||
onStatus("仍在等待系统完成配网…")
|
onStatus("仍在等待系统完成配网…")
|
||||||
}
|
}
|
||||||
}, 8_000)
|
}, 8_000)
|
||||||
@@ -118,7 +141,7 @@ class WifiConnector(context: Context) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Suppress("DEPRECATION")
|
@Suppress("DEPRECATION", "MissingPermission")
|
||||||
private fun connectLegacy(
|
private fun connectLegacy(
|
||||||
run: Int,
|
run: Int,
|
||||||
wifi: WifiCredentials,
|
wifi: WifiCredentials,
|
||||||
@@ -198,6 +221,7 @@ class WifiConnector(context: Context) {
|
|||||||
poll()
|
poll()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
private fun bestWifiNetwork(): Network? = connectivity.allNetworks.firstOrNull { network ->
|
private fun bestWifiNetwork(): Network? = connectivity.allNetworks.firstOrNull { network ->
|
||||||
val caps = connectivity.getNetworkCapabilities(network)
|
val caps = connectivity.getNetworkCapabilities(network)
|
||||||
caps?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true && hasIpv4(connectivity.getLinkProperties(network))
|
caps?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true && hasIpv4(connectivity.getLinkProperties(network))
|
||||||
|
|||||||
@@ -7,6 +7,16 @@ import java.nio.ByteOrder
|
|||||||
import java.util.zip.CRC32
|
import java.util.zip.CRC32
|
||||||
|
|
||||||
class ProtocolTest {
|
class ProtocolTest {
|
||||||
|
@Test
|
||||||
|
fun parsesPcToPhoneAutomaticDownloadPairing() {
|
||||||
|
val json = """{"v":2,"s":"abcdefghijklmnopqrstuvwxyz012345","n":"DESKTOP-QFT","p":39393,"e":["http://192.168.49.1:39393"],"d":"d","f":"sample.bin","z":42,"h":"${"00".repeat(32)}"}"""
|
||||||
|
val text = "QFTSEND2:" + Base64Url.encode(json.toByteArray())
|
||||||
|
val payload = PairingProtocol.parse(text)!!
|
||||||
|
assertEquals(TransferDirection.DOWNLOAD_TO_PHONE, payload.direction)
|
||||||
|
assertEquals("sample.bin", payload.fileName)
|
||||||
|
assertEquals(42L, payload.fileSize)
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun base45KnownVectors() {
|
fun base45KnownVectors() {
|
||||||
assertArrayEquals("AB".toByteArray(), Base45.decode("BB8"))
|
assertArrayEquals("AB".toByteArray(), Base45.decode("BB8"))
|
||||||
|
|||||||
Generated
+1
-1
@@ -2587,7 +2587,7 @@ checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "qft-windows"
|
name = "qft-windows"
|
||||||
version = "0.4.0-rc2"
|
version = "0.4.0-rc6"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"base64",
|
"base64",
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "qft-windows"
|
name = "qft-windows"
|
||||||
version = "0.4.0-rc2"
|
version = "0.4.0-rc6"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
rust-version = "1.95"
|
rust-version = "1.95"
|
||||||
|
|
||||||
|
|||||||
+242
-4
@@ -5,21 +5,25 @@ mod pairing;
|
|||||||
mod protocol;
|
mod protocol;
|
||||||
mod qr;
|
mod qr;
|
||||||
mod receiver;
|
mod receiver;
|
||||||
|
mod sender;
|
||||||
|
|
||||||
use eframe::egui::{self, FontData, FontDefinitions, FontFamily, TextureHandle, TextureOptions};
|
use eframe::egui::{self, FontData, FontDefinitions, FontFamily, TextureHandle, TextureOptions};
|
||||||
use optical_cache::OpticalPrefetcher;
|
use optical_cache::OpticalPrefetcher;
|
||||||
use pairing::{PairingPayload, WifiCredentials};
|
use pairing::{PairingDirection, PairingPayload, WifiCredentials};
|
||||||
use protocol::{hex_sha256, TransferSource};
|
use protocol::{hex_sha256, TransferSource};
|
||||||
use receiver::{ReceiverEvent, ReceiverServer};
|
use receiver::{ReceiverEvent, ReceiverServer};
|
||||||
|
use sender::{SenderEvent, SenderServer};
|
||||||
use std::{
|
use std::{
|
||||||
path::{Path, PathBuf},
|
path::{Path, PathBuf},
|
||||||
sync::{mpsc, Arc},
|
sync::{mpsc, Arc},
|
||||||
time::{Duration, Instant},
|
time::{Duration, Instant},
|
||||||
};
|
};
|
||||||
|
|
||||||
const DEFAULT_CHUNK_SIZE: u16 = 450;
|
// A lower-density symbol gains more from reliable 25~30 FPS recognition than
|
||||||
|
// a nominally larger page that is only decoded 10~18 times per second.
|
||||||
|
const DEFAULT_CHUNK_SIZE: u16 = 320;
|
||||||
const UI_FONT_NAME: &str = "qft-ui";
|
const UI_FONT_NAME: &str = "qft-ui";
|
||||||
const APP_VERSION: &str = "0.4.0-rc2";
|
const APP_VERSION: &str = "0.4.0-rc6";
|
||||||
|
|
||||||
fn main() -> eframe::Result {
|
fn main() -> eframe::Result {
|
||||||
let options = eframe::NativeOptions {
|
let options = eframe::NativeOptions {
|
||||||
@@ -41,6 +45,7 @@ enum Screen {
|
|||||||
Home,
|
Home,
|
||||||
OpticalSend,
|
OpticalSend,
|
||||||
PhoneToPc,
|
PhoneToPc,
|
||||||
|
PcToPhone,
|
||||||
}
|
}
|
||||||
|
|
||||||
struct OpticalState {
|
struct OpticalState {
|
||||||
@@ -82,12 +87,27 @@ struct ReceiveState {
|
|||||||
rate_bps: f64,
|
rate_bps: f64,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct SendState {
|
||||||
|
file: Option<PathBuf>,
|
||||||
|
file_size: u64,
|
||||||
|
sha256: Option<String>,
|
||||||
|
use_direct_ap: bool,
|
||||||
|
server: Option<SenderServer>,
|
||||||
|
direct_ap: Option<direct_ap::DirectAp>,
|
||||||
|
events: Option<mpsc::Receiver<SenderEvent>>,
|
||||||
|
pair_texture: Option<TextureHandle>,
|
||||||
|
session_token: String,
|
||||||
|
status: String,
|
||||||
|
connected_device: String,
|
||||||
|
}
|
||||||
|
|
||||||
struct QftApp {
|
struct QftApp {
|
||||||
screen: Screen,
|
screen: Screen,
|
||||||
font_status: String,
|
font_status: String,
|
||||||
local_device: String,
|
local_device: String,
|
||||||
optical: OpticalState,
|
optical: OpticalState,
|
||||||
receive: ReceiveState,
|
receive: ReceiveState,
|
||||||
|
send: SendState,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl QftApp {
|
impl QftApp {
|
||||||
@@ -109,7 +129,7 @@ impl QftApp {
|
|||||||
page_index: 0,
|
page_index: 0,
|
||||||
round: 0,
|
round: 0,
|
||||||
playing: false,
|
playing: false,
|
||||||
fps: 45.0,
|
fps: 30.0,
|
||||||
cache_mib: 256,
|
cache_mib: 256,
|
||||||
control_width: 330.0,
|
control_width: 330.0,
|
||||||
qr_zoom: 1.0,
|
qr_zoom: 1.0,
|
||||||
@@ -139,6 +159,19 @@ impl QftApp {
|
|||||||
transfer_started: None,
|
transfer_started: None,
|
||||||
rate_bps: 0.0,
|
rate_bps: 0.0,
|
||||||
},
|
},
|
||||||
|
send: SendState {
|
||||||
|
file: None,
|
||||||
|
file_size: 0,
|
||||||
|
sha256: None,
|
||||||
|
use_direct_ap: true,
|
||||||
|
server: None,
|
||||||
|
direct_ap: None,
|
||||||
|
events: None,
|
||||||
|
pair_texture: None,
|
||||||
|
session_token: String::new(),
|
||||||
|
status: "选择文件后生成二维码;手机扫码会自动配网并开始下载。".into(),
|
||||||
|
connected_device: "等待 Android 扫码".into(),
|
||||||
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -153,6 +186,7 @@ impl QftApp {
|
|||||||
if self.screen != Screen::Home && ui.button("← 返回首页").clicked() {
|
if self.screen != Screen::Home && ui.button("← 返回首页").clicked() {
|
||||||
match self.screen {
|
match self.screen {
|
||||||
Screen::PhoneToPc => self.stop_receiver(),
|
Screen::PhoneToPc => self.stop_receiver(),
|
||||||
|
Screen::PcToPhone => self.stop_sender(),
|
||||||
Screen::OpticalSend => { self.optical.playing = false; self.optical.prefetch = None; },
|
Screen::OpticalSend => { self.optical.playing = false; self.optical.prefetch = None; },
|
||||||
Screen::Home => {}
|
Screen::Home => {}
|
||||||
}
|
}
|
||||||
@@ -203,6 +237,17 @@ impl QftApp {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
ui.add_space(18.0);
|
ui.add_space(18.0);
|
||||||
|
ui.group(|ui| {
|
||||||
|
ui.horizontal_wrapped(|ui| {
|
||||||
|
ui.heading("电脑 → Android · 扫码自动直传");
|
||||||
|
ui.separator();
|
||||||
|
ui.label("选择文件 · 生成 QFTSEND2 · 手机扫码后自动配网并下载到 Downloads/QFT");
|
||||||
|
if ui.add_sized([220.0, 42.0], egui::Button::new("直传文件到手机")).clicked() {
|
||||||
|
self.screen = Screen::PcToPhone;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
ui.add_space(18.0);
|
||||||
ui.group(|ui| {
|
ui.group(|ui| {
|
||||||
ui.label(format!("本机设备:{}", self.local_device));
|
ui.label(format!("本机设备:{}", self.local_device));
|
||||||
ui.small(&self.font_status);
|
ui.small(&self.font_status);
|
||||||
@@ -495,6 +540,88 @@ impl QftApp {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn pc_to_phone_ui(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
|
||||||
|
self.poll_sender_events();
|
||||||
|
ctx.request_repaint_after(Duration::from_millis(100));
|
||||||
|
let running = self.send.server.is_some();
|
||||||
|
ui.horizontal_wrapped(|ui| {
|
||||||
|
ui.heading("电脑 → Android · 扫码自动直传");
|
||||||
|
ui.separator();
|
||||||
|
ui.label("QFTSEND2 · 自动连接本地 Wi-Fi · 扫码后立即下载");
|
||||||
|
});
|
||||||
|
ui.add_space(10.0);
|
||||||
|
|
||||||
|
ui.group(|ui| {
|
||||||
|
ui.heading("1 · 选择发送文件");
|
||||||
|
ui.horizontal_wrapped(|ui| {
|
||||||
|
if ui.add_enabled(!running, egui::Button::new("选择文件")).clicked() {
|
||||||
|
if let Some(path) = rfd::FileDialog::new().pick_file() {
|
||||||
|
match TransferSource::open(&path, DEFAULT_CHUNK_SIZE) {
|
||||||
|
Ok(source) => {
|
||||||
|
self.send.file_size = source.manifest.file_size;
|
||||||
|
self.send.sha256 = Some(hex_sha256(&source.manifest.sha256));
|
||||||
|
self.send.file = Some(path);
|
||||||
|
self.send.status = "文件已就绪;生成二维码后,手机扫码会自动开始下载。".into();
|
||||||
|
}
|
||||||
|
Err(e) => self.send.status = format!("读取文件失败:{e:#}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(path) = &self.send.file {
|
||||||
|
ui.label(format!("{} · {}", path.display(), human_bytes(self.send.file_size)));
|
||||||
|
} else {
|
||||||
|
ui.label("尚未选择文件");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if let Some(sha) = &self.send.sha256 { ui.small(format!("SHA-256:{sha}")); }
|
||||||
|
});
|
||||||
|
ui.add_space(8.0);
|
||||||
|
|
||||||
|
ui.group(|ui| {
|
||||||
|
ui.heading("2 · 连接方式");
|
||||||
|
ui.add_enabled_ui(!running, |ui| {
|
||||||
|
ui.radio_value(&mut self.send.use_direct_ap, true, "QFT Direct(推荐)· Windows 自动创建临时 Wi-Fi");
|
||||||
|
ui.radio_value(&mut self.send.use_direct_ap, false, "当前局域网(备用)· 手机和电脑已在同一 Wi-Fi/LAN");
|
||||||
|
});
|
||||||
|
ui.small("手机扫描二维码后会自动请求连接;已经批准过同一台电脑的 QFT Direct 网络时,系统通常无需再次确认。");
|
||||||
|
});
|
||||||
|
ui.add_space(8.0);
|
||||||
|
|
||||||
|
ui.group(|ui| {
|
||||||
|
ui.heading("3 · 生成二维码并自动发送");
|
||||||
|
ui.horizontal_wrapped(|ui| {
|
||||||
|
if ui.add_enabled(!running && self.send.file.is_some(), egui::Button::new("启动直传并生成二维码")).clicked() {
|
||||||
|
self.start_sender(ctx);
|
||||||
|
}
|
||||||
|
if ui.add_enabled(running, egui::Button::new("停止直传")).clicked() { self.stop_sender(); }
|
||||||
|
});
|
||||||
|
ui.label(&self.send.status);
|
||||||
|
});
|
||||||
|
|
||||||
|
if self.send.server.is_some() {
|
||||||
|
ui.add_space(10.0);
|
||||||
|
ui.columns(2, |cols| {
|
||||||
|
cols[0].group(|ui| {
|
||||||
|
ui.heading("手机扫码 · QFTSEND2");
|
||||||
|
if let Some(texture) = &self.send.pair_texture {
|
||||||
|
let side = ui.available_width().min(420.0).max(260.0);
|
||||||
|
ui.vertical_centered(|ui| { ui.image((texture.id(), egui::vec2(side, side))); });
|
||||||
|
}
|
||||||
|
if let Some(ap) = &self.send.direct_ap {
|
||||||
|
ui.label(format!("临时网络:{}", ap.ssid));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
cols[1].group(|ui| {
|
||||||
|
ui.heading("发送状态");
|
||||||
|
ui.label(format!("电脑:{}", self.local_device));
|
||||||
|
ui.label(format!("手机:{}", self.send.connected_device));
|
||||||
|
ui.label(self.send.file.as_ref().map(|v| format!("文件:{}", v.display())).unwrap_or_default());
|
||||||
|
ui.small("二维码只在本次直传会话有效;停止直传后立即失效。");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn optical_pick_file(&mut self, ctx: &egui::Context) {
|
fn optical_pick_file(&mut self, ctx: &egui::Context) {
|
||||||
let Some(path) = rfd::FileDialog::new().pick_file() else { return };
|
let Some(path) = rfd::FileDialog::new().pick_file() else { return };
|
||||||
match TransferSource::open(&path, DEFAULT_CHUNK_SIZE) {
|
match TransferSource::open(&path, DEFAULT_CHUNK_SIZE) {
|
||||||
@@ -632,6 +759,10 @@ impl QftApp {
|
|||||||
port: server.port,
|
port: server.port,
|
||||||
endpoints: pairing::local_ipv4_endpoints(server.port),
|
endpoints: pairing::local_ipv4_endpoints(server.port),
|
||||||
wifi,
|
wifi,
|
||||||
|
direction: PairingDirection::Upload,
|
||||||
|
file_name: None,
|
||||||
|
file_size: None,
|
||||||
|
sha256: None,
|
||||||
};
|
};
|
||||||
let pair_text = match payload.encode_text() {
|
let pair_text = match payload.encode_text() {
|
||||||
Ok(v) => v,
|
Ok(v) => v,
|
||||||
@@ -663,6 +794,112 @@ impl QftApp {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn start_sender(&mut self, ctx: &egui::Context) {
|
||||||
|
let Some(file) = self.send.file.clone() else { return };
|
||||||
|
let Some(sha256) = self.send.sha256.clone() else { return };
|
||||||
|
let file_name = file.file_name().and_then(|v| v.to_str()).unwrap_or("qft-download.bin").to_owned();
|
||||||
|
self.stop_sender();
|
||||||
|
self.send.status = "正在初始化电脑发送服务…".into();
|
||||||
|
let token = pairing::new_session_token();
|
||||||
|
let (tx, rx) = mpsc::channel();
|
||||||
|
let server = match SenderServer::start(file, token.clone(), tx) {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(e) => { self.send.status = format!("发送服务启动失败:{e:#}"); return; }
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut direct_ap = None;
|
||||||
|
let wifi = if self.send.use_direct_ap {
|
||||||
|
let (ssid, passphrase) = match pairing::load_or_create_direct_ap_credentials(&self.local_device) {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(e) => {
|
||||||
|
drop(server);
|
||||||
|
self.send.status = format!("读取 QFT Direct 配网身份失败:{e:#}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
match direct_ap::DirectAp::start(ssid.clone(), passphrase.clone()) {
|
||||||
|
Ok(ap) => {
|
||||||
|
direct_ap = Some(ap);
|
||||||
|
Some(WifiCredentials { ssid, passphrase, security: "WPA2".into() })
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
drop(server);
|
||||||
|
self.send.status = format!("QFT Direct 启动失败:{e:#}\n可切换到“当前局域网”备用模式。");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else { None };
|
||||||
|
|
||||||
|
if direct_ap.is_some() { std::thread::sleep(Duration::from_millis(250)); }
|
||||||
|
let payload = PairingPayload {
|
||||||
|
v: 2,
|
||||||
|
session: token.clone(),
|
||||||
|
pc_name: self.local_device.clone(),
|
||||||
|
transport: "http-download-v2".into(),
|
||||||
|
port: server.port,
|
||||||
|
endpoints: pairing::local_ipv4_endpoints(server.port),
|
||||||
|
wifi,
|
||||||
|
direction: PairingDirection::Download,
|
||||||
|
file_name: Some(file_name),
|
||||||
|
file_size: Some(self.send.file_size),
|
||||||
|
sha256: Some(sha256),
|
||||||
|
};
|
||||||
|
let pair_text = match payload.encode_text() {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(e) => { self.send.status = format!("发送二维码信息生成失败:{e:#}"); return; }
|
||||||
|
};
|
||||||
|
let image = match qr::render_pair_qr(&pair_text, 520) {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(e) => { self.send.status = format!("发送二维码生成失败:{e:#}"); return; }
|
||||||
|
};
|
||||||
|
let port = server.port;
|
||||||
|
self.send.server = Some(server);
|
||||||
|
self.send.direct_ap = direct_ap;
|
||||||
|
self.send.events = Some(rx);
|
||||||
|
self.send.pair_texture = Some(ctx.load_texture("qft-send-code", image, TextureOptions::NEAREST));
|
||||||
|
self.send.session_token = token;
|
||||||
|
self.send.connected_device = "等待 Android 扫码".into();
|
||||||
|
self.send.status = if self.send.use_direct_ap {
|
||||||
|
format!("直传已就绪 · TCP {port} · 手机扫码后会自动配网并开始下载。")
|
||||||
|
} else {
|
||||||
|
format!("直传已就绪 · TCP {port} · 请让手机扫码并使用当前局域网。")
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
fn stop_sender(&mut self) {
|
||||||
|
self.send.events = None;
|
||||||
|
self.send.server = None;
|
||||||
|
self.send.direct_ap = None;
|
||||||
|
self.send.pair_texture = None;
|
||||||
|
self.send.session_token.clear();
|
||||||
|
self.send.connected_device = "等待 Android 扫码".into();
|
||||||
|
self.send.status = "直传已停止。".into();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_sender_events(&mut self) {
|
||||||
|
let mut pending = Vec::new();
|
||||||
|
if let Some(rx) = &self.send.events {
|
||||||
|
while let Ok(event) = rx.try_recv() { pending.push(event); }
|
||||||
|
}
|
||||||
|
for event in pending {
|
||||||
|
match event {
|
||||||
|
SenderEvent::ClientConnected { device } => {
|
||||||
|
self.send.connected_device = device;
|
||||||
|
self.send.status = "Android 已确认本次二维码会话,正在准备下载。".into();
|
||||||
|
}
|
||||||
|
SenderEvent::DownloadStarted { device, file_name, size } => {
|
||||||
|
self.send.connected_device = device;
|
||||||
|
self.send.status = format!("正在发送 {file_name} · {}", human_bytes(size));
|
||||||
|
}
|
||||||
|
SenderEvent::DownloadCompleted { device, file_name } => {
|
||||||
|
self.send.connected_device = device;
|
||||||
|
self.send.status = format!("发送完成:{file_name} 已由手机保存到 Downloads/QFT。");
|
||||||
|
}
|
||||||
|
SenderEvent::Error(message) => self.send.status = message,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn stop_receiver(&mut self) {
|
fn stop_receiver(&mut self) {
|
||||||
self.receive.events = None;
|
self.receive.events = None;
|
||||||
self.receive.server = None;
|
self.receive.server = None;
|
||||||
@@ -737,6 +974,7 @@ impl eframe::App for QftApp {
|
|||||||
Screen::Home => self.home_ui(ui),
|
Screen::Home => self.home_ui(ui),
|
||||||
Screen::OpticalSend => self.optical_ui(ui, &ctx),
|
Screen::OpticalSend => self.optical_ui(ui, &ctx),
|
||||||
Screen::PhoneToPc => self.receive_ui(ui, &ctx),
|
Screen::PhoneToPc => self.receive_ui(ui, &ctx),
|
||||||
|
Screen::PcToPhone => self.pc_to_phone_ui(ui, &ctx),
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
+54
-3
@@ -2,7 +2,7 @@ use anyhow::{Context, Result};
|
|||||||
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
|
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
|
||||||
use rand::RngCore;
|
use rand::RngCore;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use serde_json::json;
|
use serde_json::{json, Value};
|
||||||
use std::{
|
use std::{
|
||||||
fs,
|
fs,
|
||||||
net::{IpAddr, Ipv4Addr},
|
net::{IpAddr, Ipv4Addr},
|
||||||
@@ -10,6 +10,7 @@ use std::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
pub const PAIR_PREFIX: &str = "QFTPAIR2:";
|
pub const PAIR_PREFIX: &str = "QFTPAIR2:";
|
||||||
|
pub const SEND_PREFIX: &str = "QFTSEND2:";
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct PairingPayload {
|
pub struct PairingPayload {
|
||||||
@@ -20,6 +21,18 @@ pub struct PairingPayload {
|
|||||||
pub port: u16,
|
pub port: u16,
|
||||||
pub endpoints: Vec<String>,
|
pub endpoints: Vec<String>,
|
||||||
pub wifi: Option<WifiCredentials>,
|
pub wifi: Option<WifiCredentials>,
|
||||||
|
/// `upload` means Android uploads to this PC. `download` means the PC has
|
||||||
|
/// selected a file and Android downloads it immediately after pairing.
|
||||||
|
pub direction: PairingDirection,
|
||||||
|
pub file_name: Option<String>,
|
||||||
|
pub file_size: Option<u64>,
|
||||||
|
pub sha256: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum PairingDirection {
|
||||||
|
Upload,
|
||||||
|
Download,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
@@ -51,7 +64,7 @@ impl PairingPayload {
|
|||||||
self.endpoints.iter().take(3).map(String::as_str).collect()
|
self.endpoints.iter().take(3).map(String::as_str).collect()
|
||||||
};
|
};
|
||||||
let wifi = self.wifi.as_ref().map(|w| json!([w.ssid, w.passphrase]));
|
let wifi = self.wifi.as_ref().map(|w| json!([w.ssid, w.passphrase]));
|
||||||
let value = json!({
|
let mut value = json!({
|
||||||
"v": 2,
|
"v": 2,
|
||||||
"s": self.session,
|
"s": self.session,
|
||||||
"n": self.pc_name,
|
"n": self.pc_name,
|
||||||
@@ -59,8 +72,21 @@ impl PairingPayload {
|
|||||||
"e": endpoints,
|
"e": endpoints,
|
||||||
"w": wifi,
|
"w": wifi,
|
||||||
});
|
});
|
||||||
|
// Keep the common Android → PC QR as small as before. File metadata is
|
||||||
|
// needed only for the new PC → Android automatic-download QR.
|
||||||
|
if self.direction == PairingDirection::Download {
|
||||||
|
let object = value.as_object_mut().expect("pairing JSON object");
|
||||||
|
object.insert("d".into(), Value::String("d".into()));
|
||||||
|
object.insert("f".into(), serde_json::to_value(&self.file_name)?);
|
||||||
|
object.insert("z".into(), serde_json::to_value(self.file_size)?);
|
||||||
|
object.insert("h".into(), serde_json::to_value(&self.sha256)?);
|
||||||
|
}
|
||||||
let json = serde_json::to_vec(&value).context("serialize pairing payload")?;
|
let json = serde_json::to_vec(&value).context("serialize pairing payload")?;
|
||||||
Ok(format!("{PAIR_PREFIX}{}", URL_SAFE_NO_PAD.encode(json)))
|
let prefix = match self.direction {
|
||||||
|
PairingDirection::Upload => PAIR_PREFIX,
|
||||||
|
PairingDirection::Download => SEND_PREFIX,
|
||||||
|
};
|
||||||
|
Ok(format!("{prefix}{}", URL_SAFE_NO_PAD.encode(json)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -176,3 +202,28 @@ pub fn local_ipv4_endpoints(port: u16) -> Vec<String> {
|
|||||||
.map(|ip| format!("http://{ip}:{port}"))
|
.map(|ip| format!("http://{ip}:{port}"))
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn download_pairing_uses_dedicated_short_prefix() {
|
||||||
|
let payload = PairingPayload {
|
||||||
|
v: 2,
|
||||||
|
session: "abcdefghijklmnopqrstuvwxyz012345".into(),
|
||||||
|
pc_name: "DESKTOP-QFT".into(),
|
||||||
|
transport: "http-download-v2".into(),
|
||||||
|
port: 39393,
|
||||||
|
endpoints: vec!["http://192.168.49.1:39393".into()],
|
||||||
|
wifi: None,
|
||||||
|
direction: PairingDirection::Download,
|
||||||
|
file_name: Some("sample.bin".into()),
|
||||||
|
file_size: Some(42),
|
||||||
|
sha256: Some("00".repeat(32)),
|
||||||
|
};
|
||||||
|
let text = payload.encode_text().unwrap();
|
||||||
|
assert!(text.starts_with(SEND_PREFIX));
|
||||||
|
assert!(text.len() < 800);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+46
-12
@@ -46,6 +46,13 @@ struct UploadSession {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type SessionMap = Arc<Mutex<HashMap<String, Arc<Mutex<UploadSession>>>>>;
|
type SessionMap = Arc<Mutex<HashMap<String, Arc<Mutex<UploadSession>>>>>;
|
||||||
|
type CompletedMap = Arc<Mutex<HashMap<String, CompletedUpload>>>;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
struct CompletedUpload {
|
||||||
|
sha256: String,
|
||||||
|
size: u64,
|
||||||
|
}
|
||||||
|
|
||||||
pub struct ReceiverServer {
|
pub struct ReceiverServer {
|
||||||
pub port: u16,
|
pub port: u16,
|
||||||
@@ -65,23 +72,31 @@ impl ReceiverServer {
|
|||||||
|
|
||||||
let stop = Arc::new(AtomicBool::new(false));
|
let stop = Arc::new(AtomicBool::new(false));
|
||||||
let sessions: SessionMap = Arc::new(Mutex::new(HashMap::new()));
|
let sessions: SessionMap = Arc::new(Mutex::new(HashMap::new()));
|
||||||
|
let completed: CompletedMap = Arc::new(Mutex::new(HashMap::new()));
|
||||||
|
|
||||||
let stop_tcp = stop.clone();
|
let stop_tcp = stop.clone();
|
||||||
let sessions_tcp = sessions.clone();
|
let sessions_tcp = sessions.clone();
|
||||||
|
let completed_tcp = completed.clone();
|
||||||
let token_tcp = session_token.clone();
|
let token_tcp = session_token.clone();
|
||||||
let dir_tcp = save_dir.clone();
|
let dir_tcp = save_dir.clone();
|
||||||
let events_tcp = events.clone();
|
let events_tcp = events.clone();
|
||||||
let tcp_thread = thread::spawn(move || {
|
let tcp_thread = thread::spawn(move || {
|
||||||
while !stop_tcp.load(Ordering::Relaxed) {
|
while !stop_tcp.load(Ordering::Relaxed) {
|
||||||
match listener.accept() {
|
match listener.accept() {
|
||||||
Ok((stream, _)) => {
|
Ok((mut stream, _)) => {
|
||||||
let dir = dir_tcp.clone();
|
let dir = dir_tcp.clone();
|
||||||
let token = token_tcp.clone();
|
let token = token_tcp.clone();
|
||||||
let tx = events_tcp.clone();
|
let tx = events_tcp.clone();
|
||||||
let sessions = sessions_tcp.clone();
|
let sessions = sessions_tcp.clone();
|
||||||
|
let completed = completed_tcp.clone();
|
||||||
thread::spawn(move || {
|
thread::spawn(move || {
|
||||||
if let Err(e) = handle_client(stream, &dir, &token, &tx, &sessions) {
|
if let Err(e) = handle_client(&mut stream, &dir, &token, &tx, &sessions, &completed) {
|
||||||
let _ = tx.send(ReceiverEvent::Error(format!("接收失败:{e:#}")));
|
// Never turn a parse/write race into an opaque Android
|
||||||
|
// `unexpected end of stream`: make a best effort to
|
||||||
|
// return an HTTP status before closing the socket.
|
||||||
|
let message = format!("接收失败:{e:#}");
|
||||||
|
let _ = write_response(&mut stream, 500, "text/plain", message.as_bytes());
|
||||||
|
let _ = tx.send(ReceiverEvent::Error(message));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -147,11 +162,12 @@ impl Drop for ReceiverServer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn handle_client(
|
fn handle_client(
|
||||||
mut stream: TcpStream,
|
stream: &mut TcpStream,
|
||||||
save_dir: &Path,
|
save_dir: &Path,
|
||||||
token: &str,
|
token: &str,
|
||||||
events: &Sender<ReceiverEvent>,
|
events: &Sender<ReceiverEvent>,
|
||||||
sessions: &SessionMap,
|
sessions: &SessionMap,
|
||||||
|
completed: &CompletedMap,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
stream.set_nodelay(true).ok();
|
stream.set_nodelay(true).ok();
|
||||||
stream.set_read_timeout(Some(Duration::from_secs(120)))?;
|
stream.set_read_timeout(Some(Duration::from_secs(120)))?;
|
||||||
@@ -180,7 +196,7 @@ fn handle_client(
|
|||||||
|
|
||||||
let supplied = headers.get("x-qft-token").map(String::as_str).unwrap_or("");
|
let supplied = headers.get("x-qft-token").map(String::as_str).unwrap_or("");
|
||||||
if supplied != token {
|
if supplied != token {
|
||||||
return write_response(&mut stream, 403, "text/plain", b"invalid session");
|
return write_response(stream, 403, "text/plain", b"invalid session");
|
||||||
}
|
}
|
||||||
|
|
||||||
let device = decode_header(headers.get("x-qft-device")).unwrap_or_else(|| "Android".to_owned());
|
let device = decode_header(headers.get("x-qft-device")).unwrap_or_else(|| "Android".to_owned());
|
||||||
@@ -188,27 +204,27 @@ fn handle_client(
|
|||||||
|
|
||||||
if method == "GET" && path == "/qft/ping" {
|
if method == "GET" && path == "/qft/ping" {
|
||||||
let body = json!({"ok": true, "protocol": 2, "parallel": true}).to_string();
|
let body = json!({"ok": true, "protocol": 2, "parallel": true}).to_string();
|
||||||
return write_response(&mut stream, 200, "application/json", body.as_bytes());
|
return write_response(stream, 200, "application/json", body.as_bytes());
|
||||||
}
|
}
|
||||||
|
|
||||||
if method == "POST" && path == "/qft/upload/init" {
|
if method == "POST" && path == "/qft/upload/init" {
|
||||||
return init_parallel_upload(&mut stream, save_dir, &headers, &device, events, sessions);
|
return init_parallel_upload(stream, save_dir, &headers, &device, events, sessions);
|
||||||
}
|
}
|
||||||
|
|
||||||
if method == "POST" && path.starts_with("/qft/upload/chunk/") {
|
if method == "POST" && path.starts_with("/qft/upload/chunk/") {
|
||||||
return receive_parallel_chunk(&mut stream, &mut reader, path, &headers, events, sessions);
|
return receive_parallel_chunk(stream, &mut reader, path, &headers, events, sessions);
|
||||||
}
|
}
|
||||||
|
|
||||||
if method == "POST" && path.starts_with("/qft/upload/finish/") {
|
if method == "POST" && path.starts_with("/qft/upload/finish/") {
|
||||||
return finish_parallel_upload(&mut stream, path, events, sessions);
|
return finish_parallel_upload(stream, path, events, sessions, completed);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Compatibility path for old clients and content providers that cannot seek.
|
// Compatibility path for old clients and content providers that cannot seek.
|
||||||
if method == "POST" && path == "/qft/upload" {
|
if method == "POST" && path == "/qft/upload" {
|
||||||
return receive_legacy_stream(&mut stream, &mut reader, save_dir, &headers, &device, events);
|
return receive_legacy_stream(stream, &mut reader, save_dir, &headers, &device, events);
|
||||||
}
|
}
|
||||||
|
|
||||||
write_response(&mut stream, 404, "text/plain", b"not found")
|
write_response(stream, 404, "text/plain", b"not found")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn init_parallel_upload(
|
fn init_parallel_upload(
|
||||||
@@ -336,12 +352,24 @@ fn finish_parallel_upload(
|
|||||||
path: &str,
|
path: &str,
|
||||||
events: &Sender<ReceiverEvent>,
|
events: &Sender<ReceiverEvent>,
|
||||||
sessions: &SessionMap,
|
sessions: &SessionMap,
|
||||||
|
completed: &CompletedMap,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let upload_id = path.trim_start_matches("/qft/upload/finish/");
|
let upload_id = path.trim_start_matches("/qft/upload/finish/");
|
||||||
let session_arc = {
|
let session_arc = {
|
||||||
let map = sessions.lock().map_err(|_| anyhow::anyhow!("上传会话锁损坏"))?;
|
let map = sessions.lock().map_err(|_| anyhow::anyhow!("上传会话锁损坏"))?;
|
||||||
map.get(upload_id).cloned().context("上传会话不存在或已完成")?
|
map.get(upload_id).cloned()
|
||||||
};
|
};
|
||||||
|
if session_arc.is_none() {
|
||||||
|
// The client may lose the TCP response after the file was safely
|
||||||
|
// renamed. Finish is idempotent so its retry reports that committed
|
||||||
|
// result instead of surfacing an opaque connection/404 failure.
|
||||||
|
if let Some(done) = completed.lock().ok().and_then(|v| v.get(upload_id).cloned()) {
|
||||||
|
let body = json!({"ok": true, "sha256": done.sha256, "size": done.size, "duplicate": true}).to_string();
|
||||||
|
return write_response(stream, 200, "application/json", body.as_bytes());
|
||||||
|
}
|
||||||
|
bail!("上传会话不存在或已完成")
|
||||||
|
}
|
||||||
|
let session_arc = session_arc.expect("checked above");
|
||||||
|
|
||||||
let (device, file_name, size, part_path, final_path) = {
|
let (device, file_name, size, part_path, final_path) = {
|
||||||
let session = session_arc.lock().map_err(|_| anyhow::anyhow!("上传会话损坏"))?;
|
let session = session_arc.lock().map_err(|_| anyhow::anyhow!("上传会话损坏"))?;
|
||||||
@@ -363,6 +391,12 @@ fn finish_parallel_upload(
|
|||||||
let mut map = sessions.lock().map_err(|_| anyhow::anyhow!("上传会话锁损坏"))?;
|
let mut map = sessions.lock().map_err(|_| anyhow::anyhow!("上传会话锁损坏"))?;
|
||||||
map.remove(upload_id);
|
map.remove(upload_id);
|
||||||
}
|
}
|
||||||
|
if let Ok(mut finished) = completed.lock() {
|
||||||
|
// A QFT receive session is short-lived. Keep a bounded completion cache
|
||||||
|
// only for retrying a lost finish response.
|
||||||
|
if finished.len() >= 64 { finished.clear(); }
|
||||||
|
finished.insert(upload_id.to_owned(), CompletedUpload { sha256: sha.clone(), size });
|
||||||
|
}
|
||||||
let _ = events.send(ReceiverEvent::UploadCompleted {
|
let _ = events.send(ReceiverEvent::UploadCompleted {
|
||||||
device, file_name, saved_path: final_path, sha256: sha.clone(),
|
device, file_name, saved_path: final_path, sha256: sha.clone(),
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,290 @@
|
|||||||
|
use anyhow::{bail, Context, Result};
|
||||||
|
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
|
||||||
|
use serde_json::json;
|
||||||
|
use std::{
|
||||||
|
collections::HashMap,
|
||||||
|
fs::File,
|
||||||
|
io::{BufRead, BufReader, Read, Write},
|
||||||
|
net::{TcpListener, TcpStream, UdpSocket},
|
||||||
|
path::PathBuf,
|
||||||
|
sync::{
|
||||||
|
atomic::{AtomicBool, Ordering},
|
||||||
|
mpsc::Sender,
|
||||||
|
Arc,
|
||||||
|
},
|
||||||
|
thread::{self, JoinHandle},
|
||||||
|
time::Duration,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub const PREFERRED_PORT: u16 = 39393;
|
||||||
|
pub const DISCOVERY_PORT: u16 = 39392;
|
||||||
|
const IO_BUFFER: usize = 1024 * 1024;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub enum SenderEvent {
|
||||||
|
ClientConnected { device: String },
|
||||||
|
DownloadStarted { device: String, file_name: String, size: u64 },
|
||||||
|
DownloadCompleted { device: String, file_name: String },
|
||||||
|
Error(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A short-lived, token-protected local HTTP server for PC → Android transfer.
|
||||||
|
/// The actual file remains on disk and is streamed only after a phone scans the
|
||||||
|
/// QFTSEND2 QR, joins the advertised local network, and presents that token.
|
||||||
|
pub struct SenderServer {
|
||||||
|
pub port: u16,
|
||||||
|
stop: Arc<AtomicBool>,
|
||||||
|
tcp_thread: Option<JoinHandle<()>>,
|
||||||
|
udp_thread: Option<JoinHandle<()>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SenderServer {
|
||||||
|
pub fn start(file_path: PathBuf, session_token: String, events: Sender<SenderEvent>) -> Result<Self> {
|
||||||
|
let file_name = file_path.file_name()
|
||||||
|
.and_then(|v| v.to_str())
|
||||||
|
.filter(|v| !v.is_empty())
|
||||||
|
.unwrap_or("qft-download.bin")
|
||||||
|
.to_owned();
|
||||||
|
let size = std::fs::metadata(&file_path)
|
||||||
|
.with_context(|| format!("读取发送文件 {} 失败", file_path.display()))?
|
||||||
|
.len();
|
||||||
|
let listener = TcpListener::bind(("0.0.0.0", PREFERRED_PORT))
|
||||||
|
.or_else(|_| TcpListener::bind(("0.0.0.0", 0)))
|
||||||
|
.context("启动本地发送端口失败")?;
|
||||||
|
let port = listener.local_addr()?.port();
|
||||||
|
listener.set_nonblocking(true)?;
|
||||||
|
|
||||||
|
let stop = Arc::new(AtomicBool::new(false));
|
||||||
|
let tcp_stop = stop.clone();
|
||||||
|
let tcp_token = session_token.clone();
|
||||||
|
let tcp_events = events.clone();
|
||||||
|
let tcp_thread = thread::spawn(move || {
|
||||||
|
while !tcp_stop.load(Ordering::Relaxed) {
|
||||||
|
match listener.accept() {
|
||||||
|
Ok((mut stream, _)) => {
|
||||||
|
let token = tcp_token.clone();
|
||||||
|
let path = file_path.clone();
|
||||||
|
let name = file_name.clone();
|
||||||
|
let tx = tcp_events.clone();
|
||||||
|
thread::spawn(move || {
|
||||||
|
if let Err(e) = handle_client(&mut stream, &path, &name, size, &token, &tx) {
|
||||||
|
let message = format!("向手机发送失败:{e:#}");
|
||||||
|
let _ = write_response(&mut stream, 500, "text/plain", message.as_bytes());
|
||||||
|
let _ = tx.send(SenderEvent::Error(message));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => thread::sleep(Duration::from_millis(12)),
|
||||||
|
Err(e) => {
|
||||||
|
let _ = tcp_events.send(SenderEvent::Error(format!("发送端口监听失败:{e}")));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let udp_stop = stop.clone();
|
||||||
|
let udp_thread = thread::spawn(move || {
|
||||||
|
let socket = match UdpSocket::bind(("0.0.0.0", DISCOVERY_PORT)) {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(e) => {
|
||||||
|
let _ = events.send(SenderEvent::Error(format!("快速发现端口 {DISCOVERY_PORT} 不可用:{e}")));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let _ = socket.set_read_timeout(Some(Duration::from_millis(250)));
|
||||||
|
let expected = format!("QFTDISC2:{session_token}");
|
||||||
|
let response = format!("QFTHERE2:{session_token}:{port}");
|
||||||
|
let mut buf = [0u8; 512];
|
||||||
|
while !udp_stop.load(Ordering::Relaxed) {
|
||||||
|
match socket.recv_from(&mut buf) {
|
||||||
|
Ok((n, peer)) if std::str::from_utf8(&buf[..n]).ok() == Some(expected.as_str()) => {
|
||||||
|
let _ = socket.send_to(response.as_bytes(), peer);
|
||||||
|
}
|
||||||
|
Ok(_) => {}
|
||||||
|
Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => {}
|
||||||
|
Err(_) => break,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(Self { port, stop, tcp_thread: Some(tcp_thread), udp_thread: Some(udp_thread) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for SenderServer {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.stop.store(true, Ordering::Relaxed);
|
||||||
|
if let Some(handle) = self.tcp_thread.take() { let _ = handle.join(); }
|
||||||
|
if let Some(handle) = self.udp_thread.take() { let _ = handle.join(); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_client(
|
||||||
|
stream: &mut TcpStream,
|
||||||
|
file_path: &PathBuf,
|
||||||
|
file_name: &str,
|
||||||
|
size: u64,
|
||||||
|
token: &str,
|
||||||
|
events: &Sender<SenderEvent>,
|
||||||
|
) -> Result<()> {
|
||||||
|
stream.set_nodelay(true).ok();
|
||||||
|
stream.set_read_timeout(Some(Duration::from_secs(20)))?;
|
||||||
|
stream.set_write_timeout(Some(Duration::from_secs(120)))?;
|
||||||
|
let cloned = stream.try_clone()?;
|
||||||
|
let mut reader = BufReader::with_capacity(32 * 1024, cloned);
|
||||||
|
let mut request_line = String::new();
|
||||||
|
reader.read_line(&mut request_line)?;
|
||||||
|
if request_line.len() > 8192 { bail!("请求行过长") }
|
||||||
|
let mut headers = HashMap::<String, String>::new();
|
||||||
|
loop {
|
||||||
|
let mut line = String::new();
|
||||||
|
let n = reader.read_line(&mut line)?;
|
||||||
|
if n == 0 { bail!("连接在请求头前关闭") }
|
||||||
|
if line == "\r\n" || line == "\n" { break }
|
||||||
|
if line.len() > 16 * 1024 { bail!("请求头过长") }
|
||||||
|
if let Some((k, v)) = line.split_once(':') {
|
||||||
|
headers.insert(k.trim().to_ascii_lowercase(), v.trim().to_owned());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut parts = request_line.split_whitespace();
|
||||||
|
let method = parts.next().unwrap_or("");
|
||||||
|
let path = parts.next().unwrap_or("");
|
||||||
|
if headers.get("x-qft-token").map(String::as_str).unwrap_or("") != token {
|
||||||
|
return write_response(stream, 403, "text/plain", b"invalid session");
|
||||||
|
}
|
||||||
|
let device = decode_header(headers.get("x-qft-device")).unwrap_or_else(|| "Android".to_owned());
|
||||||
|
let _ = events.send(SenderEvent::ClientConnected { device: device.clone() });
|
||||||
|
if method == "GET" && path == "/qft/ping" {
|
||||||
|
let body = json!({"ok": true, "protocol": 2, "direction": "download"}).to_string();
|
||||||
|
return write_response(stream, 200, "application/json", body.as_bytes());
|
||||||
|
}
|
||||||
|
if method != "GET" || path != "/qft/download" {
|
||||||
|
return write_response(stream, 404, "text/plain", b"not found");
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut input = File::open(file_path)
|
||||||
|
.with_context(|| format!("发送文件已不可读取:{}", file_path.display()))?;
|
||||||
|
if input.metadata()?.len() != size {
|
||||||
|
bail!("发送文件在二维码生成后发生变化,请重新选择文件并生成二维码")
|
||||||
|
}
|
||||||
|
let offset = parse_range_start(headers.get("range"), size)?;
|
||||||
|
let remaining = size.saturating_sub(offset);
|
||||||
|
let _ = events.send(SenderEvent::DownloadStarted { device: device.clone(), file_name: file_name.to_owned(), size });
|
||||||
|
if offset == 0 {
|
||||||
|
write!(stream,
|
||||||
|
"HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nContent-Length: {remaining}\r\nAccept-Ranges: bytes\r\nConnection: close\r\nX-QFT-Filename: {}\r\n\r\n",
|
||||||
|
URL_SAFE_NO_PAD.encode(file_name.as_bytes()),
|
||||||
|
)?;
|
||||||
|
} else {
|
||||||
|
write!(stream,
|
||||||
|
"HTTP/1.1 206 Partial Content\r\nContent-Type: application/octet-stream\r\nContent-Length: {remaining}\r\nContent-Range: bytes {offset}-{}/{}\r\nAccept-Ranges: bytes\r\nConnection: close\r\nX-QFT-Filename: {}\r\n\r\n",
|
||||||
|
size - 1,
|
||||||
|
size,
|
||||||
|
URL_SAFE_NO_PAD.encode(file_name.as_bytes()),
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
use std::io::{Seek, SeekFrom};
|
||||||
|
input.seek(SeekFrom::Start(offset))?;
|
||||||
|
let mut buf = vec![0u8; IO_BUFFER];
|
||||||
|
loop {
|
||||||
|
let n = input.read(&mut buf)?;
|
||||||
|
if n == 0 { break }
|
||||||
|
stream.write_all(&buf[..n])?;
|
||||||
|
}
|
||||||
|
stream.flush()?;
|
||||||
|
let _ = events.send(SenderEvent::DownloadCompleted { device, file_name: file_name.to_owned() });
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_response(stream: &mut TcpStream, code: u16, content_type: &str, body: &[u8]) -> Result<()> {
|
||||||
|
let reason = match code { 200 => "OK", 403 => "Forbidden", 404 => "Not Found", _ => "Error" };
|
||||||
|
write!(stream, "HTTP/1.1 {code} {reason}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len())?;
|
||||||
|
stream.write_all(body)?;
|
||||||
|
stream.flush()?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn decode_header(value: Option<&String>) -> Option<String> {
|
||||||
|
let bytes = URL_SAFE_NO_PAD.decode(value?).ok()?;
|
||||||
|
String::from_utf8(bytes).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_range_start(value: Option<&String>, size: u64) -> Result<u64> {
|
||||||
|
let Some(value) = value else { return Ok(0) };
|
||||||
|
let suffix = value.trim().strip_prefix("bytes=").context("Range 格式无效")?;
|
||||||
|
let start = suffix.strip_suffix('-').context("只支持单段 Range")?
|
||||||
|
.parse::<u64>().context("Range 起点无效")?;
|
||||||
|
if start >= size { bail!("Range 超出文件范围") }
|
||||||
|
Ok(start)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::{handle_client, parse_range_start, SenderEvent};
|
||||||
|
use std::{
|
||||||
|
fs,
|
||||||
|
io::{Read, Write},
|
||||||
|
net::{TcpListener, TcpStream},
|
||||||
|
sync::mpsc,
|
||||||
|
thread,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn accepts_only_a_valid_resumable_byte_range() {
|
||||||
|
assert_eq!(parse_range_start(None, 10).unwrap(), 0);
|
||||||
|
assert_eq!(parse_range_start(Some(&"bytes=4-".to_owned()), 10).unwrap(), 4);
|
||||||
|
assert!(parse_range_start(Some(&"bytes=10-".to_owned()), 10).is_err());
|
||||||
|
assert!(parse_range_start(Some(&"bytes=-4".to_owned()), 10).is_err());
|
||||||
|
assert!(parse_range_start(Some(&"items=4-".to_owned()), 10).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn download_endpoint_returns_the_requested_range() {
|
||||||
|
let path = std::env::temp_dir().join(format!("qft-sender-{}-range.bin", std::process::id()));
|
||||||
|
fs::write(&path, b"abcdef").unwrap();
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||||
|
let address = listener.local_addr().unwrap();
|
||||||
|
let (events, _receiver) = mpsc::channel::<SenderEvent>();
|
||||||
|
let path_for_server = path.clone();
|
||||||
|
let server = thread::spawn(move || {
|
||||||
|
for _ in 0..2 {
|
||||||
|
let (mut stream, _) = listener.accept().unwrap();
|
||||||
|
handle_client(&mut stream, &path_for_server, "range.bin", 6, "session", &events).unwrap();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let full = request(address, None);
|
||||||
|
assert_response(&full, "HTTP/1.1 200 OK", "abcdef");
|
||||||
|
let resumed = request(address, Some("bytes=2-"));
|
||||||
|
assert_response(&resumed, "HTTP/1.1 206 Partial Content", "cdef");
|
||||||
|
let header = String::from_utf8_lossy(&resumed[..header_end(&resumed)]);
|
||||||
|
assert!(header.contains("Content-Range: bytes 2-5/6"));
|
||||||
|
|
||||||
|
server.join().unwrap();
|
||||||
|
fs::remove_file(path).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request(address: std::net::SocketAddr, range: Option<&str>) -> Vec<u8> {
|
||||||
|
let mut stream = TcpStream::connect(address).unwrap();
|
||||||
|
write!(
|
||||||
|
stream,
|
||||||
|
"GET /qft/download HTTP/1.1\r\nHost: localhost\r\nX-QFT-Token: session\r\n{}\r\n",
|
||||||
|
range.map(|v| format!("Range: {v}\r\n")).unwrap_or_default(),
|
||||||
|
).unwrap();
|
||||||
|
stream.flush().unwrap();
|
||||||
|
let mut bytes = Vec::new();
|
||||||
|
stream.read_to_end(&mut bytes).unwrap();
|
||||||
|
bytes
|
||||||
|
}
|
||||||
|
|
||||||
|
fn assert_response(response: &[u8], status: &str, body: &str) {
|
||||||
|
let end = header_end(response);
|
||||||
|
assert!(String::from_utf8_lossy(&response[..end]).starts_with(status));
|
||||||
|
assert_eq!(&response[end..], body.as_bytes());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn header_end(bytes: &[u8]) -> usize {
|
||||||
|
bytes.windows(4).position(|v| v == b"\r\n\r\n").unwrap() + 4
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user