feat: 提交0.4加速版二维码直传与自动配网优化
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
/** 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 {
|
||||
/**
|
||||
* 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.os.Build
|
||||
import android.os.Bundle
|
||||
import android.util.Log
|
||||
import android.util.Range
|
||||
import android.util.Size
|
||||
import android.view.Gravity
|
||||
import android.view.MotionEvent
|
||||
import android.view.ScaleGestureDetector
|
||||
import android.view.ViewGroup
|
||||
import android.widget.Button
|
||||
import android.widget.FrameLayout
|
||||
@@ -55,10 +58,17 @@ class MainActivity : ComponentActivity() {
|
||||
private var qrLockOverlay: QrLockOverlay? = null
|
||||
private var scannerStatsText: TextView? = null
|
||||
private var scannerLockText: TextView? = null
|
||||
private var scannerZoomText: TextView? = null
|
||||
private var scannerMode = ScannerMode.NONE
|
||||
private var pendingScannerMode = ScannerMode.NONE
|
||||
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 titleText: TextView
|
||||
private lateinit var deviceText: TextView
|
||||
@@ -74,12 +84,20 @@ class MainActivity : ComponentActivity() {
|
||||
private var sendProgress: ProgressBar? = null
|
||||
private var sendButton: Button? = 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 ->
|
||||
if (granted) startScanner(pendingScannerMode) else showHome("需要相机权限才能扫描 QFT 二维码")
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
|
||||
@@ -118,6 +136,7 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
private fun showHome(message: String? = null) {
|
||||
pairConnectionAttempt++
|
||||
stopCamera()
|
||||
scannerMode = ScannerMode.NONE
|
||||
pairConsumed.set(false)
|
||||
@@ -125,6 +144,8 @@ class MainActivity : ComponentActivity() {
|
||||
pendingPair = null
|
||||
connectedNetwork = null
|
||||
connectedBaseUrl = null
|
||||
downloadRunning = false
|
||||
downloadStatusText = null
|
||||
selectedFiles.clear()
|
||||
|
||||
val root = pageColumn()
|
||||
@@ -146,10 +167,10 @@ class MainActivity : ComponentActivity() {
|
||||
) { requestScanner(ScannerMode.OPTICAL) })
|
||||
root.addView(space(16))
|
||||
root.addView(modeCard(
|
||||
title = "手机 → 电脑",
|
||||
badge = "扫码直连 · 快速发现 · 8路并行",
|
||||
body = "扫描电脑上的接收二维码,自动请求连接 QFT 临时 Wi-Fi,然后把文件直接上传到电脑指定文件夹。",
|
||||
buttonLabel = "扫码连接电脑",
|
||||
title = "扫码直传",
|
||||
badge = "手机上传 / 电脑下发 · 自动配网 · 快速发现",
|
||||
body = "扫描电脑二维码后自动连接 QFT 本地网络:接收二维码会进入手机选文件上传;下发二维码会自动下载并保存到 Downloads/QFT。",
|
||||
buttonLabel = "扫描电脑二维码",
|
||||
) { requestScanner(ScannerMode.PAIR) })
|
||||
root.addView(space(22))
|
||||
root.addView(text("本机设备:$receiverDeviceLabel", 13f, MUTED))
|
||||
@@ -158,6 +179,10 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
private fun requestScanner(mode: ScannerMode) {
|
||||
if (mode == ScannerMode.PAIR) {
|
||||
pairConnectionAttempt++
|
||||
wifiConnector.release()
|
||||
}
|
||||
pendingScannerMode = mode
|
||||
if (mode == ScannerMode.OPTICAL && Build.VERSION.SDK_INT <= 28 &&
|
||||
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
|
||||
@@ -181,11 +206,19 @@ class MainActivity : ComponentActivity() {
|
||||
future.addListener({
|
||||
val provider = future.get()
|
||||
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().
|
||||
// Apply a range actually advertised by the selected back camera via
|
||||
// Camera2Interop to both bound use cases.
|
||||
// CameraX exposes no public target-frame-rate setter for
|
||||
// ImageAnalysis. Apply the highest normal Camera2 range to both
|
||||
// bound use cases through the Camera2 interop layer.
|
||||
val previewBuilder = Preview.Builder()
|
||||
Camera2Interop.Extender(previewBuilder).setCaptureRequestOption(
|
||||
CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE,
|
||||
@@ -204,7 +237,7 @@ class MainActivity : ComponentActivity() {
|
||||
ScannerMode.NONE -> Unit
|
||||
}
|
||||
},
|
||||
onStats = { cameraFps, decodedFps, distinctFps, decodeMs ->
|
||||
onStats = { cameraFps, decodedFps, distinctFps, attemptedFps, decodeMs ->
|
||||
runOnUiThread {
|
||||
val quality = when (mode) {
|
||||
ScannerMode.PAIR -> when {
|
||||
@@ -221,11 +254,13 @@ class MainActivity : ComponentActivity() {
|
||||
ScannerMode.NONE -> "空闲" to MUTED
|
||||
}
|
||||
scannerStatsText?.text = if (mode == ScannerMode.OPTICAL) {
|
||||
"%s · 相机 %.1f FPS · 解码 %.1f/s · 新帧 %.1f/s · %.1fms/次".format(
|
||||
quality.first, cameraFps, decodedFps, distinctFps, decodeMs
|
||||
"%s · 相机 %.1f FPS · 解码 %.1f/s · 新帧 %.1f/s · 尝试 %.1f/s · %.1fms/次".format(
|
||||
quality.first, cameraFps, decodedFps, distinctFps, attemptedFps, decodeMs
|
||||
)
|
||||
} 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)
|
||||
}
|
||||
@@ -234,15 +269,19 @@ class MainActivity : ComponentActivity() {
|
||||
runOnUiThread {
|
||||
qrLockOverlay?.update(lock)
|
||||
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) {
|
||||
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)}% 画面"
|
||||
} else {
|
||||
"区域锁定:搜索中 · 让单个大二维码占取景框 50% 以上"
|
||||
}
|
||||
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()
|
||||
.setTargetResolution(targetSize)
|
||||
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
|
||||
.setImageQueueDepth(1)
|
||||
Camera2Interop.Extender(analysisBuilder).setCaptureRequestOption(
|
||||
CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE,
|
||||
requestedFps,
|
||||
)
|
||||
Camera2Interop.Extender(analysisBuilder).setCaptureRequestOption(
|
||||
CaptureRequest.CONTROL_AF_MODE,
|
||||
CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE,
|
||||
)
|
||||
val analysis = analysisBuilder.build().also { it.setAnalyzer(cameraExecutor, analyzer) }
|
||||
|
||||
provider.unbindAll()
|
||||
@@ -280,6 +324,7 @@ class MainActivity : ComponentActivity() {
|
||||
val fallbackAnalysis = ImageAnalysis.Builder()
|
||||
.setTargetResolution(targetSize)
|
||||
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
|
||||
.setImageQueueDepth(1)
|
||||
.build().also { it.setAnalyzer(cameraExecutor, analyzer) }
|
||||
scannerStatsText?.text = "设备拒绝显式高帧率请求 · 已回退相机自动 FPS · 等待首帧…"
|
||||
provider.bindToLifecycle(
|
||||
@@ -290,6 +335,7 @@ class MainActivity : ComponentActivity() {
|
||||
)
|
||||
}
|
||||
activeCamera = camera
|
||||
updateScannerZoom(camera.cameraInfo.zoomState.value?.zoomRatio ?: 1f)
|
||||
|
||||
previewView.post {
|
||||
if (previewView.width <= 0 || previewView.height <= 0) return@post
|
||||
@@ -338,24 +384,99 @@ class MainActivity : ComponentActivity() {
|
||||
} 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 {
|
||||
val manager = getSystemService(android.content.Context.CAMERA_SERVICE) as CameraManager
|
||||
val characteristics = manager.cameraIdList
|
||||
.asSequence()
|
||||
.map { manager.getCameraCharacteristics(it) }
|
||||
.firstOrNull { it.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_BACK }
|
||||
val ranges = characteristics?.get(CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES)
|
||||
?.toList().orEmpty()
|
||||
ranges
|
||||
.filter { it.upper <= 60 && it.lower <= 30 }
|
||||
.maxWithOrNull(compareBy<Range<Int>> { it.upper }.thenBy { it.lower })
|
||||
?: ranges.filter { it.upper <= 60 }
|
||||
.maxWithOrNull(compareBy<Range<Int>> { it.upper }.thenBy { it.lower })
|
||||
?: ranges.maxWithOrNull(compareBy<Range<Int>> { it.upper }.thenBy { it.lower })
|
||||
?: Range(30, 30)
|
||||
val normalRanges = characteristics
|
||||
?.get(CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES)
|
||||
?.filter { it.lower > 0 && it.upper >= it.lower }
|
||||
?.sortedWith(compareByDescending<Range<Int>> { it.upper }.thenByDescending { it.lower })
|
||||
.orEmpty()
|
||||
val highSpeed = characteristics
|
||||
?.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
|
||||
?.highSpeedVideoFpsRanges
|
||||
?.maxOfOrNull { it.upper }
|
||||
CameraFpsPlan(
|
||||
normalCandidates = normalRanges.ifEmpty { listOf(Range(30, 30)) },
|
||||
highestNormalFps = normalRanges.maxOfOrNull { it.upper } ?: 30,
|
||||
highestConstrainedHighSpeedFps = highSpeed,
|
||||
)
|
||||
} 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))
|
||||
qrLockOverlay = QrLockOverlay(this)
|
||||
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 {
|
||||
orientation = LinearLayout.HORIZONTAL
|
||||
@@ -404,6 +528,14 @@ class MainActivity : ComponentActivity() {
|
||||
12f, ACCENT
|
||||
)
|
||||
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)
|
||||
panel.addView(scannerStatsText, matchWrap(top = 4))
|
||||
panel.addView(progress, LinearLayout.LayoutParams(-1, dp(8)).apply { topMargin = dp(12) })
|
||||
@@ -426,7 +558,13 @@ class MainActivity : ComponentActivity() {
|
||||
runOnUiThread {
|
||||
stopCamera()
|
||||
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) {
|
||||
val attempt = ++pairConnectionAttempt
|
||||
showConnecting(pair, pair.wifi?.let { "正在请求连接 ${it.ssid}…" } ?: "正在使用当前局域网探测电脑…")
|
||||
wifiConnector.connect(
|
||||
pairing = pair,
|
||||
onStatus = { message -> runOnUiThread { updateConnectingStatus(message) } },
|
||||
onAvailable = { network ->
|
||||
onStatus = { message -> runOnUiThread {
|
||||
if (attempt == pairConnectionAttempt) updateConnectingStatus(message)
|
||||
} },
|
||||
onAvailable = available@{ network ->
|
||||
if (attempt != pairConnectionAttempt) return@available
|
||||
connectedNetwork = network
|
||||
transferExecutor.execute {
|
||||
if (attempt != pairConnectionAttempt) return@execute
|
||||
runOnUiThread { updateConnectingStatus("网络路由已就绪 · 正在 UDP 快速发现电脑…") }
|
||||
val discovered = UploadClient.discoverUdp(
|
||||
network = network,
|
||||
@@ -479,16 +622,35 @@ class MainActivity : ComponentActivity() {
|
||||
subnetEndpoints = subnet,
|
||||
)
|
||||
runOnUiThread {
|
||||
if (attempt != pairConnectionAttempt) return@runOnUiThread
|
||||
if (base == null) {
|
||||
showPairError(pair, "Wi-Fi 已连接,但快速发现、网关探测和当前子网扫描都未找到 QFT 接收服务。请保持 Windows 接收页开启,并在 Windows 防火墙首次弹窗时允许 QFT 访问专用网络。")
|
||||
} else {
|
||||
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) {
|
||||
// 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()
|
||||
root.addView(text("连接未完成", 28f, Color.WHITE, true))
|
||||
root.addView(text(message, 15f, WARNING), matchWrap(top = 12))
|
||||
@@ -572,6 +741,65 @@ class MainActivity : ComponentActivity() {
|
||||
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() {
|
||||
val total = selectedFiles.sumOf { it.size }
|
||||
sendFilesText?.text = if (selectedFiles.isEmpty()) {
|
||||
@@ -671,6 +899,7 @@ class MainActivity : ComponentActivity() {
|
||||
qrLockOverlay = null
|
||||
scannerStatsText = null
|
||||
scannerLockText = null
|
||||
scannerZoomText = null
|
||||
scannerMode = ScannerMode.NONE
|
||||
}
|
||||
|
||||
@@ -762,6 +991,7 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "QftCamera"
|
||||
private const val BG = 0xFF0B0E13.toInt()
|
||||
private const val CARD = 0xFF151A22.toInt()
|
||||
private const val MUTED = 0xFF9AA4B2.toInt()
|
||||
|
||||
@@ -17,29 +17,45 @@ data class PairingPayload(
|
||||
val port: Int,
|
||||
val endpoints: List<String>,
|
||||
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 {
|
||||
const val PREFIX_V2 = "QFTPAIR2:"
|
||||
const val PREFIX_SEND_V2 = "QFTSEND2:"
|
||||
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? {
|
||||
if (text.length > 4096) return null
|
||||
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))
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseV2(encoded: String): PairingPayload? {
|
||||
private fun parseV2(encoded: String, expectedDirection: TransferDirection): PairingPayload? {
|
||||
return try {
|
||||
val jsonBytes = decodeUrlBase64(encoded) ?: return null
|
||||
if (jsonBytes.size > 2048) return null
|
||||
val obj = JSONObject(jsonBytes.toString(Charsets.UTF_8))
|
||||
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")
|
||||
if (!validSession(session)) return null
|
||||
@@ -65,6 +81,16 @@ object PairingProtocol {
|
||||
// and the actual Wi-Fi gateway are probed after Android obtains an IP.
|
||||
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(
|
||||
version = 2,
|
||||
session = session,
|
||||
@@ -73,6 +99,10 @@ object PairingProtocol {
|
||||
port = port,
|
||||
endpoints = endpoints,
|
||||
wifi = wifi,
|
||||
direction = direction,
|
||||
fileName = fileName,
|
||||
fileSize = fileSize,
|
||||
sha256 = sha,
|
||||
)
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
@@ -118,6 +148,7 @@ object PairingProtocol {
|
||||
port = port,
|
||||
endpoints = endpoints,
|
||||
wifi = wifi,
|
||||
direction = TransferDirection.UPLOAD_TO_PC,
|
||||
)
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
@@ -132,6 +163,10 @@ object PairingProtocol {
|
||||
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
|
||||
* IPv4 addresses on the exact advertised port; public hosts and DNS names
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.qft.optical
|
||||
|
||||
import android.util.Log
|
||||
import androidx.camera.core.ImageAnalysis
|
||||
import androidx.camera.core.ImageProxy
|
||||
import com.google.zxing.BinaryBitmap
|
||||
@@ -31,11 +32,14 @@ class QrAnalyzer(
|
||||
cameraFramesPerSecond: Double,
|
||||
decodedPerSecond: Double,
|
||||
distinctPerSecond: Double,
|
||||
decodeAttemptsPerSecond: Double,
|
||||
averageDecodeMs: Double,
|
||||
) -> Unit = { _, _, _, _ -> },
|
||||
) -> Unit = { _, _, _, _, _ -> },
|
||||
private val onLock: (ScannerLockState) -> Unit = {},
|
||||
) : ImageAnalysis.Analyzer {
|
||||
private companion object { const val TAG = "QftScan" }
|
||||
enum class Profile { PAIR_FAST, OPTICAL_LOCKED }
|
||||
private enum class BinarizerMode { GLOBAL, HYBRID }
|
||||
|
||||
private val reader = QRCodeReader()
|
||||
private val grayBuffer = GrayFrameBuffer()
|
||||
@@ -49,8 +53,22 @@ class QrAnalyzer(
|
||||
|
||||
private var lockRegion: LockRect? = null
|
||||
private var lockMisses = 0
|
||||
private var lastMeasuredLock: LockRect? = null
|
||||
private var stableLockHits = 0
|
||||
private var lastReportedLock: LockRect? = null
|
||||
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) {
|
||||
try {
|
||||
@@ -80,16 +98,55 @@ class QrAnalyzer(
|
||||
}
|
||||
|
||||
private fun decodePair(image: ImageProxy): Result? {
|
||||
// Pairing QR is static. Center-first keeps the common path cheap while
|
||||
// still allowing off-center framing every second frame.
|
||||
val locked = pairRegion
|
||||
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 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)
|
||||
decodeDense(full, hybrid = false)?.let { return it }
|
||||
if (frameCounter % 6L == 0L) decodeDense(full, hybrid = true)?.let { return it }
|
||||
decodeDense(full, hybrid = false)?.let { result ->
|
||||
updatePairRegion(result, full)
|
||||
return result
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -100,23 +157,28 @@ class QrAnalyzer(
|
||||
// Fast hot path: only copy/decode the locked ROI. Most phones spend
|
||||
// far less time here than repeatedly scanning the entire frame.
|
||||
val crop = grayBuffer.capture(image, current)
|
||||
decodeDense(crop, hybrid = false)?.let { result ->
|
||||
lockMisses = 0
|
||||
updateLockFromResult(result, crop)
|
||||
val preferredHybrid = lockedBinarizer == BinarizerMode.HYBRID
|
||||
decodeDense(crop, hybrid = preferredHybrid)?.let { result ->
|
||||
acceptLockedResult(result, crop, preferredHybrid)
|
||||
return result
|
||||
}
|
||||
|
||||
lockMisses++
|
||||
// HybridBinarizer is slower but more robust against moire/exposure.
|
||||
// Use it sparingly rather than doubling work on every camera frame.
|
||||
if (lockMisses % 4 == 0) {
|
||||
decodeDense(crop, hybrid = true)?.let { result ->
|
||||
lockMisses = 0
|
||||
updateLockFromResult(result, crop)
|
||||
lockedBinarizerMisses++
|
||||
// A first Global miss commonly means display PWM/moire has made a
|
||||
// global threshold unsuitable. Switch immediately to Hybrid. Once
|
||||
// Hybrid is working, check Global only once every six misses so the
|
||||
// hot path stays at one ZXing decode per camera frame.
|
||||
val tryAlternative = !preferredHybrid || lockedBinarizerMisses >= 6
|
||||
if (tryAlternative && current.areaFraction(image.width, image.height) <= 0.72f) {
|
||||
decodeDense(crop, hybrid = !preferredHybrid)?.let { result ->
|
||||
acceptLockedResult(result, crop, !preferredHybrid)
|
||||
return result
|
||||
}
|
||||
if (preferredHybrid) lockedBinarizerMisses = 0
|
||||
}
|
||||
|
||||
lockMisses++
|
||||
|
||||
// Follow small hand movement without immediately returning to a
|
||||
// costly full-frame search. Only unlock after sustained misses.
|
||||
if (lockMisses == 3 || lockMisses == 6) {
|
||||
@@ -130,6 +192,10 @@ class QrAnalyzer(
|
||||
if (lockMisses >= 10) {
|
||||
lockRegion = null
|
||||
lockMisses = 0
|
||||
lastMeasuredLock = null
|
||||
stableLockHits = 0
|
||||
lockedBinarizer = BinarizerMode.GLOBAL
|
||||
lockedBinarizerMisses = 0
|
||||
publishLock(image, locked = false)
|
||||
}
|
||||
return null
|
||||
@@ -162,6 +228,13 @@ class QrAnalyzer(
|
||||
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? {
|
||||
if (gray.width < 96 || gray.height < 96) return null
|
||||
val source = PlanarYUVLuminanceSource(
|
||||
@@ -199,9 +272,18 @@ class QrAnalyzer(
|
||||
val measured = LockRect.fromPoints(points, gray.fullWidth, gray.fullHeight)
|
||||
?: lockRegion
|
||||
?: LockRect.centeredSearch(gray.fullWidth, gray.fullHeight, 0.62f)
|
||||
// Smooth small finder-point jitter so the crop and on-screen overlay do
|
||||
// not visibly vibrate while a dynamic QR is changing every frame.
|
||||
val next = lockRegion?.smoothToward(measured, 0.30f) ?: measured
|
||||
// Consecutive matching finder geometry drives a small confidence meter.
|
||||
// A fresh/unstable lock follows the code quickly; after three consistent
|
||||
// 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)
|
||||
lockRegion = next
|
||||
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) {
|
||||
publishLock(image.width, image.height, image.imageInfo.rotationDegrees, locked)
|
||||
}
|
||||
@@ -235,6 +329,7 @@ class QrAnalyzer(
|
||||
rotationDegrees = rotationDegrees,
|
||||
misses = lockMisses,
|
||||
searchAreaFraction = region?.areaFraction(frameWidth, frameHeight) ?: 1f,
|
||||
stability = (stableLockHits / 3f).coerceIn(0f, 1f),
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -245,7 +340,21 @@ class QrAnalyzer(
|
||||
if (elapsed < 1000L) return
|
||||
val seconds = elapsed / 1000.0
|
||||
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
|
||||
decodedCounter = 0
|
||||
distinctCounter = 0
|
||||
|
||||
@@ -64,7 +64,11 @@ class QrLockOverlay(context: Context) : View(context) {
|
||||
|
||||
val rect = mapRegionToView(region, s)
|
||||
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()
|
||||
stroke.strokeWidth = resources.displayMetrics.density * (if (pulse < 0.5f) 2.6f else 3.4f)
|
||||
canvas.drawRoundRect(rect, radius, radius, fill)
|
||||
@@ -83,7 +87,11 @@ class QrLockOverlay(context: Context) : View(context) {
|
||||
// pixels or the ImageAnalysis thread.
|
||||
val phase = (android.os.SystemClock.uptimeMillis() % 1200L) / 1200f
|
||||
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)
|
||||
postInvalidateDelayed(100L)
|
||||
}
|
||||
|
||||
@@ -8,4 +8,6 @@ data class ScannerLockState(
|
||||
val rotationDegrees: Int,
|
||||
val misses: Int,
|
||||
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 MAX_WORKERS = 8
|
||||
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? {
|
||||
var name = "qft-upload.bin"
|
||||
@@ -68,13 +72,15 @@ object UploadClient {
|
||||
return try {
|
||||
network?.bindSocket(socket)
|
||||
socket.broadcast = true
|
||||
socket.soTimeout = 220
|
||||
socket.soTimeout = 160
|
||||
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) {
|
||||
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) {
|
||||
val buf = ByteArray(512)
|
||||
val packet = DatagramPacket(buf, buf.size)
|
||||
@@ -117,13 +123,13 @@ object UploadClient {
|
||||
.filter { PairingProtocol.isAllowedLocalHttpEndpoint(it, pairing.port) }
|
||||
.distinct()
|
||||
|
||||
// Stage 1: expected gateway/QR addresses. Repeat quickly because a Wi-Fi
|
||||
// callback can precede ARP/firewall classification by a few hundred ms.
|
||||
val fastDeadline = android.os.SystemClock.elapsedRealtime() + 2_400
|
||||
// Stage 1: QR-carried endpoints and actual gateway. This is the normal
|
||||
// path and must complete well inside the 10-second pairing budget.
|
||||
val fastDeadline = android.os.SystemClock.elapsedRealtime() + 1_050
|
||||
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 }
|
||||
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
|
||||
@@ -135,16 +141,17 @@ object UploadClient {
|
||||
.filterNot { it in fast }
|
||||
.distinct()
|
||||
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 }
|
||||
}
|
||||
|
||||
// Final short retry for the expected addresses after the subnet scan.
|
||||
val deadline = android.os.SystemClock.elapsedRealtime() + 2_000
|
||||
// One short final pass covers a just-finished ARP/Windows firewall
|
||||
// transition without adding the former two-second tail latency.
|
||||
val deadline = android.os.SystemClock.elapsedRealtime() + 500
|
||||
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 }
|
||||
try { Thread.sleep(120) } catch (_: InterruptedException) { return null }
|
||||
try { Thread.sleep(50) } catch (_: InterruptedException) { return null }
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -169,7 +176,7 @@ object UploadClient {
|
||||
return try {
|
||||
val overallMs = (connectMs + readMs + 150).toLong() *
|
||||
((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) {
|
||||
val remaining = deadline - android.os.SystemClock.elapsedRealtime()
|
||||
if (remaining <= 0) return null
|
||||
@@ -220,9 +227,13 @@ object UploadClient {
|
||||
uploadParallel(resolver, network, baseUrl, pairing, deviceName, file, onProgress)
|
||||
return
|
||||
} catch (e: Exception) {
|
||||
// If the provider cannot sustain random access or the v2 endpoint
|
||||
// is unavailable, preserve compatibility with the v1 stream path.
|
||||
// Never mask a transient v2 failure by immediately switching to a
|
||||
// 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
|
||||
val message = e.message.orEmpty()
|
||||
if (!message.contains("HTTP 404") && !message.contains("HTTP 501")) throw e
|
||||
}
|
||||
}
|
||||
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 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(
|
||||
resolver: ContentResolver,
|
||||
network: Network?,
|
||||
@@ -301,7 +330,7 @@ object UploadClient {
|
||||
private fun initUpload(
|
||||
network: Network?, baseUrl: String, pairing: PairingPayload,
|
||||
deviceName: String, file: SelectedFile,
|
||||
): InitReply {
|
||||
): InitReply = retryLocalRequest("本地上传初始化失败") {
|
||||
val conn = open(network, URL("$baseUrl/qft/upload/init"))
|
||||
try {
|
||||
conn.requestMethod = "POST"
|
||||
@@ -318,7 +347,7 @@ object UploadClient {
|
||||
if (code != 200) error("初始化并行上传失败 HTTP $code")
|
||||
val body = conn.inputStream.bufferedReader().use { it.readText() }
|
||||
val obj = JSONObject(body)
|
||||
return InitReply(
|
||||
InitReply(
|
||||
uploadId = obj.getString("upload_id"),
|
||||
chunkSize = obj.getLong("chunk_size"),
|
||||
totalChunks = obj.getInt("total_chunks"),
|
||||
@@ -332,7 +361,7 @@ object UploadClient {
|
||||
network: Network?, baseUrl: String, pairing: PairingPayload, deviceName: String,
|
||||
uploadId: String, index: Int, channel: FileChannel, offset: Long, length: Long,
|
||||
buffer: ByteBuffer,
|
||||
) {
|
||||
) = retryLocalRequest("分块 $index 上传失败") {
|
||||
val conn = open(network, URL("$baseUrl/qft/upload/chunk/$uploadId/$index"))
|
||||
try {
|
||||
conn.requestMethod = "POST"
|
||||
@@ -370,7 +399,7 @@ object UploadClient {
|
||||
private fun finishUpload(
|
||||
network: Network?, baseUrl: String, pairing: PairingPayload,
|
||||
deviceName: String, uploadId: String,
|
||||
) {
|
||||
) = retryLocalRequest("本地上传完成确认失败") {
|
||||
val conn = open(network, URL("$baseUrl/qft/upload/finish/$uploadId"))
|
||||
try {
|
||||
conn.requestMethod = "POST"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.qft.optical
|
||||
|
||||
import android.content.Context
|
||||
import androidx.annotation.RequiresApi
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.LinkProperties
|
||||
import android.net.Network
|
||||
@@ -13,10 +14,13 @@ import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import java.net.Inet4Address
|
||||
import java.net.InetAddress
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
class WifiConnector(context: Context) {
|
||||
private companion object { const val TAG = "QftWifi" }
|
||||
private val appContext = context.applicationContext
|
||||
private val connectivity = appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
||||
private val wifiManager = appContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
|
||||
@@ -50,6 +54,8 @@ class WifiConnector(context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
@RequiresApi(29)
|
||||
@Suppress("MissingPermission")
|
||||
private fun connectModern(
|
||||
run: Int,
|
||||
wifi: WifiCredentials,
|
||||
@@ -58,6 +64,8 @@ class WifiConnector(context: Context) {
|
||||
onUnavailable: (String) -> Unit,
|
||||
) {
|
||||
onStatus("正在请求连接 ${wifi.ssid}…")
|
||||
Log.i(TAG, "attempt=$run request SSID=${wifi.ssid}")
|
||||
onStatus("正在等待 Android 系统连接确认;确认后本页将继续显示进度")
|
||||
val specifier = try {
|
||||
WifiNetworkSpecifier.Builder()
|
||||
.setSsid(wifi.ssid)
|
||||
@@ -73,14 +81,19 @@ class WifiConnector(context: Context) {
|
||||
.setNetworkSpecifier(specifier)
|
||||
.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() {
|
||||
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/路由…")
|
||||
waitUntilUsable(run, network, onStatus) {
|
||||
if (!delivered[0] && run == generation) {
|
||||
delivered[0] = true
|
||||
if (run == generation && !terminal.get() && delivered.compareAndSet(false, true)) {
|
||||
Log.i(TAG, "attempt=$run route ready network=$network")
|
||||
onStatus("QFT 本地网络已就绪,正在快速发现电脑…")
|
||||
onAvailable(network)
|
||||
}
|
||||
@@ -88,27 +101,37 @@ class WifiConnector(context: Context) {
|
||||
}
|
||||
|
||||
override fun onLinkPropertiesChanged(network: Network, linkProperties: LinkProperties) {
|
||||
if (run != generation || delivered[0]) return
|
||||
if (hasIpv4(linkProperties)) {
|
||||
delivered[0] = true
|
||||
if (run != generation || terminal.get() || delivered.get()) return
|
||||
if (hasIpv4(linkProperties) && delivered.compareAndSet(false, true)) {
|
||||
Log.i(TAG, "attempt=$run IPv4 ready network=$network")
|
||||
onStatus("QFT 本地网络已就绪,正在快速发现电脑…")
|
||||
onAvailable(network)
|
||||
}
|
||||
}
|
||||
|
||||
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 已开启并批准系统连接请求。")
|
||||
}
|
||||
|
||||
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
|
||||
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({
|
||||
if (run == generation && !delivered[0]) {
|
||||
if (run == generation && !terminal.get() && !delivered.get()) {
|
||||
onStatus("仍在等待系统完成配网…")
|
||||
}
|
||||
}, 8_000)
|
||||
@@ -118,7 +141,7 @@ class WifiConnector(context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
@Suppress("DEPRECATION", "MissingPermission")
|
||||
private fun connectLegacy(
|
||||
run: Int,
|
||||
wifi: WifiCredentials,
|
||||
@@ -198,6 +221,7 @@ class WifiConnector(context: Context) {
|
||||
poll()
|
||||
}
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
private fun bestWifiNetwork(): Network? = connectivity.allNetworks.firstOrNull { network ->
|
||||
val caps = connectivity.getNetworkCapabilities(network)
|
||||
caps?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true && hasIpv4(connectivity.getLinkProperties(network))
|
||||
|
||||
@@ -7,6 +7,16 @@ import java.nio.ByteOrder
|
||||
import java.util.zip.CRC32
|
||||
|
||||
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
|
||||
fun base45KnownVectors() {
|
||||
assertArrayEquals("AB".toByteArray(), Base45.decode("BB8"))
|
||||
|
||||
Reference in New Issue
Block a user