V0.3.0版本优化传输速度和提示

This commit is contained in:
zhy
2026-08-10 15:45:04 +08:00
commit d885259e2b
58 changed files with 10284 additions and 0 deletions
+33
View File
@@ -0,0 +1,33 @@
# Android build fix v0.1.1
This revision intentionally uses the Android 15 / API 35 toolchain for the MVP.
The optical receiver does not use Android 16-only APIs, so API 36 is unnecessary for now.
Pinned stack:
- compileSdk / targetSdk: 35
- Android Gradle Plugin: 8.9.1
- Gradle: 8.11.1
- JDK: 17
- Build Tools: 35.0.0
- Kotlin Gradle Plugin: 2.1.20
- Activity: 1.10.1
- CameraX: 1.4.2
- ZXing core: 3.5.3
The manifest now references the local `@style/QftTheme`; the theme inherits the standard Android Material light no-action-bar theme.
## Windows one-command repair
From the `android` directory:
```powershell
Set-ExecutionPolicy -Scope Process Bypass
.\repair-windows.ps1 -Sdk "E:\SYSTEM\APPDATA\Android_SDK"
```
If your SDK lives elsewhere, change `-Sdk`.
After the script succeeds, the APK should be at:
`app\build\outputs\apk\debug\app-debug.apk`
+20
View File
@@ -0,0 +1,20 @@
# QFT Android v0.2.1 build fix
Fixes Kotlin compile error in `MainActivity.kt` line ~502.
Incorrect:
```kotlin
android.view.Space(this)
```
Correct:
```kotlin
android.widget.Space(this)
```
The accompanying `layoutParams` and type inference errors were cascading errors caused by the unresolved `Space` class.
Rebuild with:
```powershell
.\gradlew.bat :app:assembleDebug
```
+50
View File
@@ -0,0 +1,50 @@
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
}
android {
namespace = "com.qft.optical"
compileSdk = 35
buildToolsVersion = "35.0.0"
defaultConfig {
applicationId = "com.qft.optical"
minSdk = 24
targetSdk = 35
versionCode = 8
versionName = "0.3.0-rc3"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = "17"
}
}
dependencies {
implementation("androidx.activity:activity-ktx:1.10.1")
implementation("androidx.camera:camera-core:1.4.2")
implementation("androidx.camera:camera-camera2:1.4.2")
implementation("androidx.camera:camera-lifecycle:1.4.2")
implementation("androidx.camera:camera-view:1.4.2")
implementation("com.google.zxing:core:3.5.3")
testImplementation("junit:junit:4.13.2")
}
+1
View File
@@ -0,0 +1 @@
# MVP: no custom rules yet.
+32
View File
@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="28" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" android:maxSdkVersion="32" />
<uses-permission android:name="android.permission.NEARBY_WIFI_DEVICES" android:usesPermissionFlags="neverForLocation" />
<uses-feature android:name="android.hardware.camera.any" android:required="true" />
<uses-feature android:name="android.hardware.wifi" android:required="false" />
<application
android:allowBackup="false"
android:usesCleartextTraffic="true"
android:networkSecurityConfig="@xml/network_security_config"
android:label="QFT"
android:supportsRtl="true"
android:theme="@style/QftTheme">
<activity
android:name=".MainActivity"
android:exported="true"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
@@ -0,0 +1,60 @@
package com.qft.optical
/** Small URL-safe Base64 codec with no padding; works unchanged on Android 7+ and JVM unit tests. */
object Base64Url {
private const val ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
private val reverse = IntArray(128) { -1 }.also { table ->
ALPHABET.forEachIndexed { index, c -> table[c.code] = index }
}
fun encode(input: ByteArray): String {
if (input.isEmpty()) return ""
val out = StringBuilder((input.size * 4 + 2) / 3)
var i = 0
while (i + 2 < input.size) {
val n = ((input[i].toInt() and 0xff) shl 16) or
((input[i + 1].toInt() and 0xff) shl 8) or
(input[i + 2].toInt() and 0xff)
out.append(ALPHABET[(n ushr 18) and 63])
out.append(ALPHABET[(n ushr 12) and 63])
out.append(ALPHABET[(n ushr 6) and 63])
out.append(ALPHABET[n and 63])
i += 3
}
val remaining = input.size - i
if (remaining == 1) {
val n = (input[i].toInt() and 0xff) shl 16
out.append(ALPHABET[(n ushr 18) and 63])
out.append(ALPHABET[(n ushr 12) and 63])
} else if (remaining == 2) {
val n = ((input[i].toInt() and 0xff) shl 16) or ((input[i + 1].toInt() and 0xff) shl 8)
out.append(ALPHABET[(n ushr 18) and 63])
out.append(ALPHABET[(n ushr 12) and 63])
out.append(ALPHABET[(n ushr 6) and 63])
}
return out.toString()
}
fun decode(text: String): ByteArray? {
if (text.isEmpty()) return ByteArray(0)
if (text.length % 4 == 1) return null
val out = ByteArray((text.length * 6) / 8)
var outIndex = 0
var accumulator = 0
var bits = 0
for (c in text) {
val code = c.code
if (code >= reverse.size) return null
val value = reverse[code]
if (value < 0) return null
accumulator = (accumulator shl 6) or value
bits += 6
if (bits >= 8) {
bits -= 8
if (outIndex >= out.size) return null
out[outIndex++] = ((accumulator ushr bits) and 0xff).toByte()
}
}
return if (outIndex == out.size) out else out.copyOf(outIndex)
}
}
@@ -0,0 +1,43 @@
package com.qft.optical
import androidx.camera.core.ImageProxy
/**
* Copies only the Y plane.
*
* QFT deliberately keeps the camera buffer in sensor orientation. QR finder
* patterns are rotation independent, and the optical 2x2 layout is still a 2x2
* layout after a 90° rotation. Avoiding a second full-frame rotate/copy removes
* almost half of the memory traffic in the scanner hot path on portrait phones.
*/
data class GrayFrame(val width: Int, val height: Int, val luma: ByteArray) {
companion object {
fun from(image: ImageProxy): GrayFrame {
val plane = image.planes[0]
val src = plane.buffer.duplicate()
val rowStride = plane.rowStride
val pixelStride = plane.pixelStride
val w = image.width
val h = image.height
val raw = ByteArray(w * h)
if (pixelStride == 1 && rowStride == w) {
src.position(0)
src.get(raw, 0, raw.size)
} else if (pixelStride == 1) {
for (y in 0 until h) {
src.position(y * rowStride)
src.get(raw, y * w, w)
}
} else {
for (y in 0 until h) {
val rowStart = y * rowStride
for (x in 0 until w) {
raw[y * w + x] = src.get(rowStart + x * pixelStride)
}
}
}
return GrayFrame(w, h, raw)
}
}
}
@@ -0,0 +1,618 @@
package com.qft.optical
import android.Manifest
import android.content.pm.PackageManager
import android.content.res.ColorStateList
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.net.Network
import android.os.Build
import android.os.Bundle
import android.util.Size
import android.view.Gravity
import android.view.ViewGroup
import android.widget.Button
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.ScrollView
import android.widget.TextView
import androidx.activity.ComponentActivity
import androidx.activity.result.contract.ActivityResultContracts
import androidx.camera.core.CameraSelector
import androidx.camera.core.FocusMeteringAction
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
class MainActivity : ComponentActivity() {
private enum class ScannerMode { NONE, OPTICAL, PAIR }
private val receiverDeviceLabel: String by lazy { localDeviceLabel() }
private val cameraExecutor = Executors.newSingleThreadExecutor()
private val transferExecutor = Executors.newSingleThreadExecutor()
private val wifiConnector by lazy { WifiConnector(this) }
private lateinit var assembler: SessionAssembler
private var cameraProvider: ProcessCameraProvider? = null
private var currentAnalyzer: QrAnalyzer? = null
private var scannerStatsText: TextView? = null
private var scannerMode = ScannerMode.NONE
private var pendingScannerMode = ScannerMode.NONE
private val pairConsumed = AtomicBoolean(false)
private lateinit var previewView: PreviewView
private lateinit var titleText: TextView
private lateinit var deviceText: TextView
private lateinit var statusText: TextView
private lateinit var progress: ProgressBar
private var pendingPair: PairingPayload? = null
private var connectedNetwork: Network? = null
private var connectedBaseUrl: String? = null
private val selectedFiles = mutableListOf<SelectedFile>()
private var sendStatusText: TextView? = null
private var sendFilesText: TextView? = null
private var sendProgress: ProgressBar? = null
private var sendButton: Button? = null
private var connectingStatusText: TextView? = null
private val requestCamera = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
if (granted) startScanner(pendingScannerMode) else showHome("需要相机权限才能扫描 QFT 二维码")
}
private val requestLegacyStorage = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
if (granted) requestScanner(pendingScannerMode) else showHome("Android 7~9 需要存储权限才能把光学接收文件保存到 Downloads/QFT")
}
private val requestWifiPermissions = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { result ->
val denied = result.filterValues { !it }.keys
val pair = pendingPair
if (denied.isEmpty() && pair != null) {
connectPair(pair)
} else {
showPairError(pair, "需要附近 Wi-Fi/位置权限才能完成扫码配网")
}
}
private val pickFiles = registerForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->
selectedFiles.clear()
var unknown = 0
for (uri in uris) {
val file = UploadClient.describeFile(contentResolver, uri)
if (file != null) selectedFiles += file else unknown++
}
renderSelectedFiles()
if (unknown > 0) {
sendStatusText?.text = "有 $unknown 个文件无法确定大小,已跳过"
} else if (selectedFiles.isNotEmpty()) {
sendStatusText?.text = "已选择 ${selectedFiles.size} 个文件,点击“开始传输”"
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
window.statusBarColor = BG
window.navigationBarColor = BG
assembler = SessionAssembler(this) { event -> runOnUiThread { renderOpticalEvent(event) } }
showHome()
}
private fun showHome(message: String? = null) {
stopCamera()
scannerMode = ScannerMode.NONE
pairConsumed.set(false)
wifiConnector.release()
pendingPair = null
connectedNetwork = null
connectedBaseUrl = null
selectedFiles.clear()
val root = pageColumn()
root.addView(text("QFT", 30f, Color.WHITE, true))
root.addView(text("超速二维码文件传输", 16f, MUTED))
root.addView(space(26))
message?.let {
val banner = text(it, 14f, WARNING)
banner.setPadding(dp(14), dp(12), dp(14), dp(12))
banner.background = rounded(0xFF2B2112.toInt(), 14)
root.addView(banner, matchWrap(top = 0, bottom = 18))
}
root.addView(modeCard(
title = "电脑 → 手机",
badge = "光学零网络 · 4码并行 · 60FPS显示",
body = "手机摄像头连续读取电脑动态二维码。Wi-Fi、蓝牙、局域网和互联网都不参与文件数据传输。",
buttonLabel = "开始光学接收",
) { requestScanner(ScannerMode.OPTICAL) })
root.addView(space(16))
root.addView(modeCard(
title = "手机 → 电脑",
badge = "扫码直连 · 快速发现 · 8路并行",
body = "扫描电脑上的接收二维码,自动请求连接 QFT 临时 Wi-Fi,然后把文件直接上传到电脑指定文件夹。",
buttonLabel = "扫码连接电脑",
) { requestScanner(ScannerMode.PAIR) })
root.addView(space(22))
root.addView(text("本机设备:$receiverDeviceLabel", 13f, MUTED))
root.addView(text("QFT v0.3.0-rc3 · Android 7+ 到最新", 12f, MUTED))
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
}
private fun requestScanner(mode: ScannerMode) {
pendingScannerMode = mode
if (mode == ScannerMode.OPTICAL && Build.VERSION.SDK_INT <= 28 &&
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
) {
requestLegacyStorage.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE)
return
}
if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
startScanner(mode)
} else {
requestCamera.launch(Manifest.permission.CAMERA)
}
}
private fun startScanner(mode: ScannerMode) {
scannerMode = mode
pairConsumed.set(false)
setContentView(buildCameraUi(mode))
val future = ProcessCameraProvider.getInstance(this)
future.addListener({
val provider = future.get()
cameraProvider = provider
val preview = Preview.Builder().build().also { it.surfaceProvider = previewView.surfaceProvider }
val profile = if (mode == ScannerMode.PAIR) QrAnalyzer.Profile.PAIR_FAST else QrAnalyzer.Profile.OPTICAL_MULTI
currentAnalyzer?.close()
val analyzer = QrAnalyzer(
profile = profile,
onTexts = { values ->
when (scannerMode) {
ScannerMode.OPTICAL -> values.forEach(assembler::acceptText)
ScannerMode.PAIR -> values.firstOrNull { PairingProtocol.isPairingText(it) }?.let(::acceptPairCode)
ScannerMode.NONE -> Unit
}
},
onStats = { cameraFps, decodedFps ->
runOnUiThread {
val quality = when (mode) {
ScannerMode.PAIR -> when {
decodedFps >= 1.0 -> "识别稳定" to SUCCESS
cameraFps >= 18.0 -> "正在锁定二维码" to ACCENT
else -> "相机帧率偏低" to WARNING
}
ScannerMode.OPTICAL -> when {
decodedFps >= cameraFps.coerceAtLeast(1.0) * 1.5 -> "光学链路稳定" to SUCCESS
decodedFps >= 5.0 -> "可接收 · 建议保持手机稳定" to ACCENT
else -> "识别偏低 · 靠近屏幕或降低 Windows FPS" to WARNING
}
ScannerMode.NONE -> "空闲" to MUTED
}
scannerStatsText?.text = "%s · 相机 %.1f FPS · 有效 QR %.1f/s".format(quality.first, cameraFps, decodedFps)
scannerStatsText?.setTextColor(quality.second)
}
},
)
currentAnalyzer = analyzer
val targetSize = if (mode == ScannerMode.PAIR) Size(640, 480) else Size(1280, 720)
val analysis = ImageAnalysis.Builder()
.setTargetResolution(targetSize)
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
.build()
.also { it.setAnalyzer(cameraExecutor, analyzer) }
provider.unbindAll()
val camera = provider.bindToLifecycle(this, CameraSelector.DEFAULT_BACK_CAMERA, preview, analysis)
// Screen QR benefits from an immediate center AF/AE metering pass.
try {
val point = previewView.meteringPointFactory.createPoint(0.5f, 0.5f)
val action = FocusMeteringAction.Builder(
point,
FocusMeteringAction.FLAG_AF or FocusMeteringAction.FLAG_AE,
).setAutoCancelDuration(5, TimeUnit.SECONDS).build()
camera.cameraControl.startFocusAndMetering(action)
} catch (_: Exception) {}
}, mainExecutor)
}
private fun buildCameraUi(mode: ScannerMode): FrameLayout {
val root = FrameLayout(this).apply { setBackgroundColor(Color.BLACK) }
previewView = PreviewView(this).apply {
implementationMode = PreviewView.ImplementationMode.PERFORMANCE
scaleType = PreviewView.ScaleType.FILL_CENTER
}
root.addView(previewView, FrameLayout.LayoutParams(-1, -1))
val top = LinearLayout(this).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
setPadding(dp(14), dp(12), dp(14), dp(12))
setBackgroundColor(0xB80C0E12.toInt())
}
val back = button("‹ 返回").apply { setOnClickListener { showHome() } }
top.addView(back)
titleText = text(if (mode == ScannerMode.OPTICAL) "电脑 → 手机" else "扫码连接电脑", 19f, Color.WHITE, true)
top.addView(titleText, LinearLayout.LayoutParams(0, -2, 1f).apply { marginStart = dp(10) })
root.addView(top, FrameLayout.LayoutParams(-1, -2, Gravity.TOP))
val panel = LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
setPadding(dp(16), dp(14), dp(16), dp(16))
background = rounded(0xE80C0E12.toInt(), 18)
}
deviceText = text(
if (mode == ScannerMode.OPTICAL) "接收设备:$receiverDeviceLabel\n发送设备:等待 QFT1 MANIFEST…"
else "目标:等待 QFTPAIR2 配对二维码",
14f, Color.WHITE
)
statusText = text(
if (mode == ScannerMode.OPTICAL) "把电脑动态二维码完整放进取景框"
else "扫描 Windows“手机传电脑”页面上的二维码",
14f, MUTED
)
progress = ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal).apply { max = 1000; progress = 0 }
panel.addView(deviceText)
panel.addView(statusText, matchWrap(top = 7))
scannerStatsText = text("相机分析:等待首帧…", 12f, ACCENT)
panel.addView(scannerStatsText, matchWrap(top = 6))
panel.addView(progress, LinearLayout.LayoutParams(-1, dp(8)).apply { topMargin = dp(12) })
root.addView(panel, FrameLayout.LayoutParams(-1, -2, Gravity.BOTTOM).apply {
leftMargin = dp(12); rightMargin = dp(12); bottomMargin = dp(12)
})
return root
}
private fun acceptPairCode(text: String) {
if (!PairingProtocol.isPairingText(text)) return
if (!pairConsumed.compareAndSet(false, true)) return
val pair = PairingProtocol.parse(text)
if (pair == null) {
pairConsumed.set(false)
runOnUiThread { statusText.text = "配对二维码格式无效,请重新对准" }
return
}
pendingPair = pair
runOnUiThread {
stopCamera()
showConnecting(pair, "二维码已识别,正在准备本地连接…")
ensureWifiPermissionThenConnect(pair)
}
}
private fun ensureWifiPermissionThenConnect(pair: PairingPayload) {
if (pair.wifi == null) {
connectPair(pair)
return
}
val required = when {
Build.VERSION.SDK_INT >= 33 -> arrayOf(Manifest.permission.NEARBY_WIFI_DEVICES)
else -> arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)
}
val missing = required.filter { checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
if (missing.isEmpty()) connectPair(pair) else requestWifiPermissions.launch(missing.toTypedArray())
}
private fun connectPair(pair: PairingPayload) {
showConnecting(pair, pair.wifi?.let { "正在请求连接 ${it.ssid}…" } ?: "正在使用当前局域网探测电脑…")
wifiConnector.connect(
pairing = pair,
onStatus = { message -> runOnUiThread { updateConnectingStatus(message) } },
onAvailable = { network ->
connectedNetwork = network
transferExecutor.execute {
runOnUiThread { updateConnectingStatus("网络路由已就绪 · 正在 UDP 快速发现电脑…") }
val discovered = UploadClient.discoverUdp(
network = network,
pairing = pair,
hosts = wifiConnector.discoveryHosts(network),
)
runOnUiThread {
updateConnectingStatus(
if (discovered != null) "已通过 UDP 找到电脑 · 正在验证接收服务…"
else "UDP 未响应 · 正在并行探测网关与本地 IP…"
)
}
val gateways = wifiConnector.gatewayEndpoints(network, pair.port)
val subnet = wifiConnector.subnetEndpoints(network, pair.port)
if (discovered == null) {
runOnUiThread {
updateConnectingStatus("正在并行探测网关;必要时自动扫描当前 QFT 子网…")
}
}
val base = UploadClient.probeRobust(
network = network,
pairing = pair,
deviceName = receiverDeviceLabel,
preferredEndpoints = gateways,
discoveredEndpoint = discovered,
subnetEndpoints = subnet,
)
runOnUiThread {
if (base == null) {
showPairError(pair, "Wi-Fi 已连接,但快速发现、网关探测和当前子网扫描都未找到 QFT 接收服务。请保持 Windows 接收页开启,并在 Windows 防火墙首次弹窗时允许 QFT 访问专用网络。")
} else {
connectedBaseUrl = base
showSendReady(pair, base)
}
}
}
},
onUnavailable = { message -> runOnUiThread { showPairError(pair, message) } },
)
}
private fun showConnecting(pair: PairingPayload, message: String) {
val root = pageColumn()
root.addView(text("正在连接电脑", 28f, Color.WHITE, true))
root.addView(text(pair.pcName, 18f, ACCENT))
root.addView(space(22))
root.addView(card().apply {
addView(text("配对信息", 15f, MUTED))
addView(text("电脑:${pair.pcName}", 16f, Color.WHITE), matchWrap(top = 8))
addView(text("网络:${pair.wifi?.ssid ?: "当前局域网"}", 14f, Color.WHITE), matchWrap(top = 5))
addView(text("会话:${pair.session.take(10)}…", 12f, MUTED), matchWrap(top = 5))
})
root.addView(space(18))
val spinner = ProgressBar(this)
root.addView(spinner, LinearLayout.LayoutParams(dp(48), dp(48)).apply { gravity = Gravity.CENTER_HORIZONTAL })
connectingStatusText = text(message, 14f, MUTED).apply { gravity = Gravity.CENTER }
root.addView(connectingStatusText, matchWrap(top = 12))
root.addView(space(20))
root.addView(button("取消").apply { setOnClickListener { showHome() } })
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
}
private fun updateConnectingStatus(message: String) {
connectingStatusText?.text = message
}
private fun showPairError(pair: PairingPayload?, message: String) {
val root = pageColumn()
root.addView(text("连接未完成", 28f, Color.WHITE, true))
root.addView(text(message, 15f, WARNING), matchWrap(top = 12))
root.addView(space(24))
if (pair != null) {
root.addView(button("重试连接").apply { setOnClickListener { ensureWifiPermissionThenConnect(pair) } })
root.addView(space(10))
}
root.addView(button("重新扫码").apply { setOnClickListener { requestScanner(ScannerMode.PAIR) } })
root.addView(space(10))
root.addView(button("返回首页").apply { setOnClickListener { showHome() } })
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
}
private fun showSendReady(pair: PairingPayload, baseUrl: String) {
val root = pageColumn()
root.addView(text("已连接电脑", 28f, Color.WHITE, true))
root.addView(text("${receiverDeviceLabel} → ${pair.pcName}", 16f, ACCENT))
root.addView(space(18))
root.addView(card().apply {
addView(text("连接状态", 14f, MUTED))
addView(text("● 本地直连已就绪", 17f, SUCCESS, true), matchWrap(top = 8))
addView(text(if (pair.version >= 2) "Parallel v2 · 自适应最高 8 路并发 · 4/8/16 MiB 自适应分块" else "兼容单流模式", 13f, ACCENT), matchWrap(top = 5))
addView(text("目标:$baseUrl", 12f, MUTED), matchWrap(top = 6))
pair.wifi?.let { addView(text("QFT 临时网络:${it.ssid}", 12f, MUTED), matchWrap(top = 4)) }
})
root.addView(space(14))
root.addView(card().apply {
addView(text("选择文件", 17f, Color.WHITE, true))
sendFilesText = text("尚未选择文件", 14f, MUTED)
addView(sendFilesText, matchWrap(top = 8))
addView(button("选择文件(可多选)").apply {
setOnClickListener { pickFiles.launch(arrayOf("*/*")) }
}, matchWrap(top = 12))
})
root.addView(space(14))
root.addView(card().apply {
addView(text("传输进度", 17f, Color.WHITE, true))
sendStatusText = text("选择文件后点击开始传输", 14f, MUTED)
addView(sendStatusText, matchWrap(top = 8))
sendProgress = ProgressBar(this@MainActivity, null, android.R.attr.progressBarStyleHorizontal).apply { max = 1000; progress = 0 }
addView(sendProgress, LinearLayout.LayoutParams(-1, dp(9)).apply { topMargin = dp(12) })
sendButton = button("开始传输").apply {
isEnabled = selectedFiles.isNotEmpty()
setOnClickListener { startUploads(pair, baseUrl) }
}
addView(sendButton, matchWrap(top = 14))
})
root.addView(space(14))
root.addView(button("断开并返回首页").apply { setOnClickListener { showHome() } })
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
renderSelectedFiles()
}
private fun renderSelectedFiles() {
val total = selectedFiles.sumOf { it.size }
sendFilesText?.text = if (selectedFiles.isEmpty()) {
"尚未选择文件"
} else {
buildString {
selectedFiles.take(8).forEach { append("• ${it.name} ${humanBytes(it.size)}\n") }
if (selectedFiles.size > 8) append("…另外 ${selectedFiles.size - 8} 个文件\n")
append("共 ${selectedFiles.size} 个 · ${humanBytes(total)}")
}.trim()
}
sendButton?.isEnabled = selectedFiles.isNotEmpty() && connectedBaseUrl != null
}
private fun startUploads(pair: PairingPayload, baseUrl: String) {
if (selectedFiles.isEmpty()) return
val files = selectedFiles.toList()
sendButton?.isEnabled = false
transferExecutor.execute {
try {
files.forEachIndexed { index, file ->
val startedAt = android.os.SystemClock.elapsedRealtime()
runOnUiThread {
sendProgress?.progress = 0
sendStatusText?.text = "${index + 1}/${files.size} · 正在发送 ${file.name}"
}
UploadClient.upload(
resolver = contentResolver,
network = connectedNetwork,
baseUrl = baseUrl,
pairing = pair,
deviceName = receiverDeviceLabel,
file = file,
) { sent, total ->
runOnUiThread {
val p = if (total == 0L) 1000 else ((sent.toDouble() / total) * 1000).toInt().coerceIn(0, 1000)
val elapsedMs = (android.os.SystemClock.elapsedRealtime() - startedAt).coerceAtLeast(1L)
val bytesPerSecond = sent * 1000.0 / elapsedMs
val etaSeconds = if (bytesPerSecond > 1.0 && total > sent) (total - sent) / bytesPerSecond else 0.0
sendProgress?.progress = p
sendStatusText?.text = buildString {
append("${index + 1}/${files.size} · ${file.name}\n")
append("${humanBytes(sent)} / ${humanBytes(total)} · ${humanBytes(bytesPerSecond.toLong())}/s")
if (etaSeconds > 0.5) append(" · 剩余 ${humanDuration(etaSeconds)}")
}
}
}
}
runOnUiThread {
sendProgress?.progress = 1000
sendStatusText?.text = "全部完成 · 已发送 ${files.size} 个文件"
sendButton?.isEnabled = true
}
} catch (e: Exception) {
runOnUiThread {
sendStatusText?.text = "传输失败:${e.message}"
sendButton?.isEnabled = true
}
}
}
}
private fun renderOpticalEvent(event: ReceiveEvent) {
if (scannerMode != ScannerMode.OPTICAL) return
when (event) {
is ReceiveEvent.Started -> {
titleText.text = event.manifest.fileName
deviceText.text = "传输设备:${event.manifest.senderDevice} → $receiverDeviceLabel"
statusText.text = "已锁定会话,等待数据块…"
progress.progress = 0
}
is ReceiveEvent.Progress -> {
val total = event.total.coerceAtLeast(1)
val p = event.received.toDouble() / total.toDouble()
progress.progress = (p * 1000).toInt().coerceIn(0, 1000)
statusText.text = "已收到 ${event.received}/${event.total} · ${(p * 100).toInt()}% · 漏帧会在下一轮补齐"
}
is ReceiveEvent.Completed -> {
progress.progress = 1000
deviceText.text = "传输完成:${event.manifest.senderDevice} → $receiverDeviceLabel"
statusText.text = "完成:已保存到 Downloads/QFT/${event.savedName}"
}
is ReceiveEvent.Error -> statusText.text = event.message
}
}
private fun stopCamera() {
try { cameraProvider?.unbindAll() } catch (_: Exception) {}
cameraProvider = null
currentAnalyzer?.close()
currentAnalyzer = null
scannerStatsText = null
scannerMode = ScannerMode.NONE
}
private fun localDeviceLabel(): String {
val manufacturer = Build.MANUFACTURER.orEmpty().trim()
val model = Build.MODEL.orEmpty().trim()
return when {
model.isBlank() -> "Android"
manufacturer.isBlank() -> model
model.startsWith(manufacturer, ignoreCase = true) -> model
else -> "$manufacturer $model"
}
}
private fun pageColumn(): LinearLayout = LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
setPadding(dp(20), dp(28), dp(20), dp(28))
setBackgroundColor(BG)
}
private fun modeCard(title: String, badge: String, body: String, buttonLabel: String, onClick: () -> Unit): LinearLayout = card().apply {
addView(text(title, 23f, Color.WHITE, true))
addView(text(badge, 13f, ACCENT, true), matchWrap(top = 5))
addView(text(body, 14f, MUTED), matchWrap(top = 12))
addView(button(buttonLabel).apply { setOnClickListener { onClick() } }, matchWrap(top = 18))
}
private fun card(): LinearLayout = LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
setPadding(dp(18), dp(18), dp(18), dp(18))
background = rounded(CARD, 18)
}
private fun text(value: String, size: Float, color: Int, bold: Boolean = false): TextView = TextView(this).apply {
text = value
textSize = size
setTextColor(color)
if (bold) setTypeface(typeface, android.graphics.Typeface.BOLD)
setLineSpacing(0f, 1.12f)
}
private fun button(label: String): Button = Button(this).apply {
text = label
isAllCaps = false
setTextColor(Color.WHITE)
backgroundTintList = ColorStateList.valueOf(0xFF2667FF.toInt())
minHeight = dp(48)
}
private fun rounded(color: Int, radiusDp: Int): GradientDrawable = GradientDrawable().apply {
shape = GradientDrawable.RECTANGLE
setColor(color)
cornerRadius = dp(radiusDp).toFloat()
}
private fun space(heightDp: Int) = android.widget.Space(this).apply {
layoutParams = LinearLayout.LayoutParams(1, dp(heightDp))
}
private fun matchWrap(top: Int = 0, bottom: Int = 0) = LinearLayout.LayoutParams(-1, -2).apply {
topMargin = dp(top); bottomMargin = dp(bottom)
}
private fun dp(v: Int): Int = (v * resources.displayMetrics.density).toInt()
private fun humanDuration(seconds: Double): String {
if (!seconds.isFinite() || seconds <= 0.5) return "<1 秒"
val total = kotlin.math.ceil(seconds).toLong()
val minutes = total / 60
val secs = total % 60
return if (minutes > 0) "${minutes}分${secs}秒" else "${secs}秒"
}
private fun humanBytes(v: Long): String {
val units = arrayOf("B", "KB", "MB", "GB", "TB")
var n = v.toDouble()
var i = 0
while (n >= 1024.0 && i < units.lastIndex) { n /= 1024.0; i++ }
return if (i == 0) "$v ${units[i]}" else "%.2f %s".format(n, units[i])
}
override fun onDestroy() {
assembler.reset()
wifiConnector.release()
stopCamera()
cameraExecutor.shutdownNow()
transferExecutor.shutdownNow()
super.onDestroy()
}
companion object {
private const val BG = 0xFF0B0E13.toInt()
private const val CARD = 0xFF151A22.toInt()
private const val MUTED = 0xFF9AA4B2.toInt()
private const val ACCENT = 0xFF6EA8FF.toInt()
private const val SUCCESS = 0xFF69D38B.toInt()
private const val WARNING = 0xFFFFC56D.toInt()
}
}
@@ -0,0 +1,158 @@
package com.qft.optical
import org.json.JSONObject
import java.net.URI
data class WifiCredentials(
val ssid: String,
val passphrase: String,
val security: String,
)
data class PairingPayload(
val version: Int,
val session: String,
val pcName: String,
val transport: String,
val port: Int,
val endpoints: List<String>,
val wifi: WifiCredentials?,
)
object PairingProtocol {
const val PREFIX_V2 = "QFTPAIR2:"
const val PREFIX_V1 = "QFTPAIR1:"
fun isPairingText(text: String): Boolean = text.startsWith(PREFIX_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_V1) -> parseV1(text.substring(PREFIX_V1.length))
else -> null
}
}
private fun parseV2(encoded: String): 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 session = obj.getString("s")
if (!validSession(session)) return null
val port = obj.getInt("p")
if (port !in 1..65535) return null
val wifiArray = obj.optJSONArray("w")
val wifi = if (wifiArray != null && wifiArray.length() >= 2) {
val ssid = wifiArray.optString(0)
val passphrase = wifiArray.optString(1)
if (!validWifi(ssid, passphrase)) return null
WifiCredentials(ssid, passphrase, "WPA2")
} else null
val endpoints = mutableListOf<String>()
obj.optJSONArray("e")?.let { arr ->
for (i in 0 until arr.length()) {
val value = arr.optString(i).trim().removeSuffix("/")
if (isAllowedLocalHttpEndpoint(value, port) && value !in endpoints) endpoints += value
}
}
// QFT Direct v2 can work with no QR-carried endpoint because UDP discovery
// and the actual Wi-Fi gateway are probed after Android obtains an IP.
if (wifi == null && endpoints.isEmpty()) return null
PairingPayload(
version = 2,
session = session,
pcName = obj.optString("n", "Windows-PC").take(80),
transport = "http-parallel-v2",
port = port,
endpoints = endpoints,
wifi = wifi,
)
} catch (_: Exception) {
null
}
}
private fun parseV1(encoded: String): PairingPayload? {
return try {
val jsonBytes = decodeUrlBase64(encoded) ?: return null
if (jsonBytes.size > 3072) return null
val obj = JSONObject(jsonBytes.toString(Charsets.UTF_8))
if (obj.optInt("v", 0) != 1) return null
val session = obj.getString("session")
if (!validSession(session)) return null
val transport = obj.optString("transport", "")
if (transport != "http-stream-v1") return null
val port = obj.getInt("port")
if (port !in 1..65535) return null
val endpoints = mutableListOf<String>()
val endpointsJson = obj.getJSONArray("endpoints")
for (i in 0 until endpointsJson.length()) {
val value = endpointsJson.optString(i).trim().removeSuffix("/")
if (isAllowedLocalHttpEndpoint(value, port) && value !in endpoints) endpoints += value
}
if (endpoints.isEmpty()) return null
val wifiObj = obj.optJSONObject("wifi")
val wifi = wifiObj?.let {
val ssid = it.getString("ssid")
val passphrase = it.getString("passphrase")
val security = it.optString("security", "WPA2")
if (!validWifi(ssid, passphrase) || security != "WPA2") return null
WifiCredentials(ssid, passphrase, security)
}
PairingPayload(
version = 1,
session = session,
pcName = obj.optString("pc_name", "Windows-PC").take(80),
transport = transport,
port = port,
endpoints = endpoints,
wifi = wifi,
)
} catch (_: Exception) {
null
}
}
private fun decodeUrlBase64(encoded: String): ByteArray? = Base64Url.decode(encoded)
private fun validSession(session: String): Boolean = session.matches(Regex("^[A-Za-z0-9_-]{20,64}$"))
private fun validWifi(ssid: String, passphrase: String): Boolean {
return ssid.isNotBlank() && ssid.toByteArray(Charsets.UTF_8).size <= 32 && passphrase.length in 8..63
}
/**
* Pairing QR is treated as untrusted input. QFT only probes literal local
* IPv4 addresses on the exact advertised port; public hosts and DNS names
* are rejected even though the app permits cleartext HTTP for local QFT.
*/
fun isAllowedLocalHttpEndpoint(value: String, expectedPort: Int): Boolean {
val uri = try { URI(value) } catch (_: Exception) { return false }
if (uri.scheme != "http" || uri.userInfo != null || uri.query != null || uri.fragment != null) return false
if (uri.port != expectedPort) return false
val host = uri.host ?: return false
val octets = host.split('.').map { it.toIntOrNull() ?: return false }
if (octets.size != 4 || octets.any { it !in 0..255 }) return false
val a = octets[0]
val b = octets[1]
return when {
a == 10 -> true
a == 127 -> true
a == 169 && b == 254 -> true
a == 172 && b in 16..31 -> true
a == 192 && b == 168 -> true
else -> false
}
}
}
@@ -0,0 +1,108 @@
package com.qft.optical
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.zip.CRC32
enum class FrameKind(val wire: Int) {
MANIFEST(1), DATA(2), END(3);
companion object {
fun fromWire(v: Int): FrameKind = entries.firstOrNull { it.wire == v }
?: error("unknown frame kind: $v")
}
}
data class QftFrame(
val kind: FrameKind,
val sessionId: Long,
val seq: Long,
val totalChunks: Long,
val payload: ByteArray,
)
data class Manifest(
val sessionId: Long,
val senderDevice: String,
val fileName: String,
val fileSize: Long,
val chunkSize: Int,
val totalChunks: Long,
val sha256: ByteArray,
)
object QftProtocol {
const val PREFIX = "QFT1:"
private const val VERSION = 1
fun parseText(text: String): QftFrame? {
if (!text.startsWith(PREFIX)) return null
val binary = try {
Base64Url.decode(text.substring(PREFIX.length)) ?: return null
} catch (_: IllegalArgumentException) {
return null
}
if (binary.size < 28) return null
val bodySize = binary.size - 4
val expectedCrc = ByteBuffer.wrap(binary, bodySize, 4)
.order(ByteOrder.BIG_ENDIAN)
.int.toLong() and 0xffff_ffffL
val crc = CRC32().apply { update(binary, 0, bodySize) }.value
if (crc != expectedCrc) return null
val bb = ByteBuffer.wrap(binary, 0, bodySize).order(ByteOrder.BIG_ENDIAN)
val magic = ByteArray(4).also(bb::get)
if (!magic.contentEquals(byteArrayOf('Q'.code.toByte(), 'F'.code.toByte(), 'T'.code.toByte(), '1'.code.toByte()))) {
return null
}
val version = bb.get().toInt() and 0xff
if (version != VERSION) return null
val kind = try { FrameKind.fromWire(bb.get().toInt() and 0xff) } catch (_: Exception) { return null }
val sessionId = bb.long
val seq = bb.int.toLong() and 0xffff_ffffL
val totalChunks = bb.int.toLong() and 0xffff_ffffL
val payloadLen = bb.short.toInt() and 0xffff
if (payloadLen != bb.remaining()) return null
val payload = ByteArray(payloadLen).also(bb::get)
return QftFrame(kind, sessionId, seq, totalChunks, payload)
}
fun parseManifest(frame: QftFrame): Manifest? {
if (frame.kind != FrameKind.MANIFEST || frame.payload.size < 44) return null
val bb = ByteBuffer.wrap(frame.payload).order(ByteOrder.BIG_ENDIAN)
val fileSize = bb.long
val chunkSize = bb.short.toInt() and 0xffff
val sha = ByteArray(32).also(bb::get)
val nameLen = bb.short.toInt() and 0xffff
if (nameLen > bb.remaining()) return null
val nameBytes = ByteArray(nameLen).also(bb::get)
val name = nameBytes.toString(Charsets.UTF_8)
.replace(Regex("[\\/:*?\"<>|]"), "_")
.ifBlank { "qft.bin" }
val senderDevice = if (bb.remaining() >= 2) {
val deviceLen = bb.short.toInt() and 0xffff
if (deviceLen > bb.remaining()) return null
ByteArray(deviceLen).also(bb::get)
.toString(Charsets.UTF_8)
.replace(Regex("[\u0000-\u001F\u007F]"), "")
.trim()
.ifBlank { "Windows-PC" }
} else {
// Backward compatibility with v0.1/v0.1.2 manifests.
"Windows-PC"
}
if (chunkSize <= 0) return null
return Manifest(
sessionId = frame.sessionId,
senderDevice = senderDevice,
fileName = name,
fileSize = fileSize,
chunkSize = chunkSize,
totalChunks = frame.totalChunks,
sha256 = sha,
)
}
}
@@ -0,0 +1,162 @@
package com.qft.optical
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import com.google.zxing.BarcodeFormat
import com.google.zxing.BinaryBitmap
import com.google.zxing.DecodeHintType
import com.google.zxing.MultiFormatReader
import com.google.zxing.PlanarYUVLuminanceSource
import com.google.zxing.common.GlobalHistogramBinarizer
import com.google.zxing.common.HybridBinarizer
import java.util.concurrent.Callable
import java.util.concurrent.Executors
class QrAnalyzer(
private val profile: Profile,
private val onTexts: (List<String>) -> Unit,
private val onStats: (cameraFramesPerSecond: Double, decodedPerSecond: Double) -> Unit = { _, _ -> },
) : ImageAnalysis.Analyzer {
enum class Profile { PAIR_FAST, OPTICAL_MULTI }
private val readers = Array(5) { newReader() }
private val decodePool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors().coerceIn(2, 4))
private var frameCounter = 0L
private var decodedCounter = 0L
private var windowStarted = android.os.SystemClock.elapsedRealtime()
override fun analyze(image: ImageProxy) {
try {
val gray = GrayFrame.from(image)
frameCounter++
val results = when (profile) {
Profile.PAIR_FAST -> decodePair(gray)
Profile.OPTICAL_MULTI -> decodeOptical(gray)
}.distinct()
if (results.isNotEmpty()) {
decodedCounter += results.size
onTexts(results)
}
reportStatsIfNeeded()
} finally {
image.close()
}
}
private fun decodePair(gray: GrayFrame): List<String> {
// QFTPAIR2 is intentionally compact. Try a cheap centered GlobalHistogram
// pass first, then the full frame every time so off-axis scans do not wait
// several frames. HybridBinarizer is reserved for every third miss.
val marginX = (gray.width * 0.08).toInt()
val marginY = (gray.height * 0.08).toInt()
decodeRegion(
gray, marginX, marginY, gray.width - marginX * 2, gray.height - marginY * 2,
readers[0], hybridFallback = false,
)?.let { return listOf(it) }
decodeRegion(gray, 0, 0, gray.width, gray.height, readers[0], hybridFallback = false)
?.let { return listOf(it) }
if (frameCounter % 3L == 0L) {
decodeRegion(gray, 0, 0, gray.width, gray.height, readers[0], hybridFallback = true)
?.let { return listOf(it) }
}
return emptyList()
}
private fun decodeOptical(gray: GrayFrame): List<String> {
// v0.3 Windows can present a 2x2 grid. Decode quadrants concurrently.
// 8% overlap tolerates perspective/centering error around the middle.
val overlapX = (gray.width * 0.08).toInt()
val overlapY = (gray.height * 0.08).toInt()
val halfW = gray.width / 2
val halfH = gray.height / 2
val regions = arrayOf(
intArrayOf(0, 0, (halfW + overlapX).coerceAtMost(gray.width), (halfH + overlapY).coerceAtMost(gray.height)),
intArrayOf((halfW - overlapX).coerceAtLeast(0), 0, gray.width - (halfW - overlapX).coerceAtLeast(0), (halfH + overlapY).coerceAtMost(gray.height)),
intArrayOf(0, (halfH - overlapY).coerceAtLeast(0), (halfW + overlapX).coerceAtMost(gray.width), gray.height - (halfH - overlapY).coerceAtLeast(0)),
intArrayOf((halfW - overlapX).coerceAtLeast(0), (halfH - overlapY).coerceAtLeast(0), gray.width - (halfW - overlapX).coerceAtLeast(0), gray.height - (halfH - overlapY).coerceAtLeast(0)),
)
val tasks = regions.mapIndexed { index, r ->
Callable {
decodeRegion(gray, r[0], r[1], r[2], r[3], readers[index], hybridFallback = false)
}
}
val found = try {
decodePool.invokeAll(tasks).mapNotNull { future ->
try { future.get() } catch (_: Exception) { null }
}
} catch (_: Exception) {
emptyList()
}
if (found.isNotEmpty()) return found
// Backward-compatible single-QR fallback. Limit the expensive hybrid
// pass to every third frame so low-end Android 7 devices stay responsive.
return if (frameCounter % 3L == 0L) {
decodeRegion(gray, 0, 0, gray.width, gray.height, readers[4], hybridFallback = true)
?.let(::listOf) ?: emptyList()
} else emptyList()
}
private fun decodeRegion(
gray: GrayFrame,
left: Int,
top: Int,
width: Int,
height: Int,
reader: MultiFormatReader,
hybridFallback: Boolean,
): String? {
if (width < 80 || height < 80) return null
val source = try {
PlanarYUVLuminanceSource(
gray.luma, gray.width, gray.height,
left.coerceAtLeast(0), top.coerceAtLeast(0),
width.coerceAtMost(gray.width - left.coerceAtLeast(0)),
height.coerceAtMost(gray.height - top.coerceAtLeast(0)),
false,
)
} catch (_: Exception) { return null }
try {
return reader.decodeWithState(BinaryBitmap(GlobalHistogramBinarizer(source)))?.text
} catch (_: Exception) {
if (!hybridFallback) return null
} finally {
reader.reset()
}
return try {
reader.decodeWithState(BinaryBitmap(HybridBinarizer(source)))?.text
} catch (_: Exception) {
null
} finally {
reader.reset()
}
}
private fun reportStatsIfNeeded() {
val now = android.os.SystemClock.elapsedRealtime()
val elapsed = now - windowStarted
if (elapsed < 1000L) return
val seconds = elapsed / 1000.0
onStats(frameCounter / seconds, decodedCounter / seconds)
frameCounter = 0
decodedCounter = 0
windowStarted = now
}
fun close() {
decodePool.shutdownNow()
}
companion object {
private fun newReader() = MultiFormatReader().apply {
setHints(
mapOf(
DecodeHintType.POSSIBLE_FORMATS to listOf(BarcodeFormat.QR_CODE),
DecodeHintType.TRY_HARDER to false,
DecodeHintType.CHARACTER_SET to "UTF-8",
)
)
}
}
}
@@ -0,0 +1,192 @@
package com.qft.optical
import android.content.ContentValues
import android.content.Context
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import java.io.File
import java.io.FileInputStream
import java.io.RandomAccessFile
import java.security.MessageDigest
sealed interface ReceiveEvent {
data class Started(val manifest: Manifest) : ReceiveEvent
data class Progress(val manifest: Manifest, val received: Int, val total: Int) : ReceiveEvent
data class Completed(val manifest: Manifest, val savedName: String) : ReceiveEvent
data class Error(val message: String) : ReceiveEvent
}
class SessionAssembler(
private val context: Context,
private val onEvent: (ReceiveEvent) -> Unit,
) {
private var manifest: Manifest? = null
private var received: BooleanArray? = null
private var receivedCount = 0
private var tempFile: File? = null
private var raf: RandomAccessFile? = null
private var completedSession: Long? = null
@Synchronized
fun acceptText(text: String) {
val frame = QftProtocol.parseText(text) ?: return
if (completedSession == frame.sessionId) return
when (frame.kind) {
FrameKind.MANIFEST -> acceptManifest(frame)
FrameKind.DATA -> acceptData(frame)
FrameKind.END -> Unit
}
}
private fun acceptManifest(frame: QftFrame) {
val incoming = QftProtocol.parseManifest(frame) ?: return
val current = manifest
if (current?.sessionId == incoming.sessionId) return
reset()
if (incoming.totalChunks > Int.MAX_VALUE) {
onEvent(ReceiveEvent.Error("文件分片数过大"))
return
}
manifest = incoming
received = BooleanArray(incoming.totalChunks.toInt())
tempFile = File(context.cacheDir, "qft-${incoming.sessionId}.part")
raf = RandomAccessFile(tempFile!!, "rw").apply { setLength(incoming.fileSize) }
onEvent(ReceiveEvent.Started(incoming))
if (incoming.totalChunks == 0L) finalizeIfComplete()
}
private fun acceptData(frame: QftFrame) {
val m = manifest ?: return
if (frame.sessionId != m.sessionId) return
if (frame.totalChunks != m.totalChunks) return
if (frame.seq >= m.totalChunks) return
if (frame.payload.size > m.chunkSize) return
val expectedOffset = frame.seq * m.chunkSize.toLong()
val remaining = m.fileSize - expectedOffset
if (remaining < 0) return
val expectedLen = minOf(m.chunkSize.toLong(), remaining).toInt()
if (frame.payload.size != expectedLen) return
val flags = received ?: return
val index = frame.seq.toInt()
if (flags[index]) return
raf?.seek(expectedOffset)
raf?.write(frame.payload)
flags[index] = true
receivedCount++
onEvent(ReceiveEvent.Progress(m, receivedCount, flags.size))
finalizeIfComplete()
}
private fun finalizeIfComplete() {
val m = manifest ?: return
val flags = received ?: return
if (receivedCount != flags.size) return
raf?.fd?.sync()
raf?.close()
raf = null
val file = tempFile ?: return
val actual = sha256(file)
if (!actual.contentEquals(m.sha256)) {
onEvent(ReceiveEvent.Error("SHA-256 校验失败,等待下一会话重新发送"))
reset()
return
}
try {
saveToDownloads(file, m.fileName)
completedSession = m.sessionId
onEvent(ReceiveEvent.Completed(m, m.fileName))
reset(keepCompleted = true)
} catch (e: Exception) {
onEvent(ReceiveEvent.Error("保存失败:${e.message}"))
}
}
private fun sha256(file: File): ByteArray {
val digest = MessageDigest.getInstance("SHA-256")
FileInputStream(file).use { input ->
val buf = ByteArray(1024 * 1024)
while (true) {
val n = input.read(buf)
if (n <= 0) break
digest.update(buf, 0, n)
}
}
return digest.digest()
}
private fun saveToDownloads(source: File, name: String) {
if (Build.VERSION.SDK_INT >= 29) {
saveModern(source, name)
} else {
saveLegacy(source, name)
}
}
@android.annotation.TargetApi(29)
private fun saveModern(source: File, name: String) {
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 resolver = context.contentResolver
val uri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values)
?: error("MediaStore insert failed")
try {
resolver.openOutputStream(uri, "w")!!.use { out ->
source.inputStream().use { input -> input.copyTo(out, 1024 * 1024) }
}
values.clear()
values.put(MediaStore.Downloads.IS_PENDING, 0)
resolver.update(uri, values, null, null)
} catch (e: Exception) {
resolver.delete(uri, null, null)
throw e
}
}
@Suppress("DEPRECATION")
private fun saveLegacy(source: File, name: String) {
val dir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "QFT")
if (!dir.exists() && !dir.mkdirs()) error("无法创建 Downloads/QFT")
val target = uniqueLegacyFile(dir, name)
source.inputStream().use { input ->
target.outputStream().use { output -> input.copyTo(output, 1024 * 1024) }
}
}
private fun uniqueLegacyFile(dir: File, original: String): File {
var candidate = File(dir, original)
if (!candidate.exists()) return candidate
val dot = original.lastIndexOf('.')
val stem = if (dot > 0) original.substring(0, dot) else original
val ext = if (dot > 0) original.substring(dot) else ""
var n = 1
while (candidate.exists()) {
candidate = File(dir, "$stem ($n)$ext")
n++
}
return candidate
}
@Synchronized
fun reset(keepCompleted: Boolean = false) {
try { raf?.close() } catch (_: Exception) {}
raf = null
tempFile?.delete()
tempFile = null
manifest = null
received = null
receivedCount = 0
if (!keepCompleted) completedSession = null
}
}
@@ -0,0 +1,473 @@
package com.qft.optical
import android.content.ContentResolver
import android.database.Cursor
import android.net.Network
import android.net.Uri
import android.provider.OpenableColumns
import org.json.JSONObject
import java.io.FileInputStream
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.HttpURLConnection
import java.net.InetAddress
import java.net.URL
import java.nio.ByteBuffer
import java.nio.channels.FileChannel
import java.util.concurrent.ExecutorCompletionService
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicLong
data class SelectedFile(
val uri: Uri,
val name: String,
val size: Long,
)
object UploadClient {
private const val DISCOVERY_PORT = 39392
private const val CHUNK_SMALL = 4L * 1024L * 1024L
private const val CHUNK_DEFAULT = 8L * 1024L * 1024L
private const val CHUNK_LARGE = 16L * 1024L * 1024L
private const val MAX_WORKERS = 8
private const val STREAM_BUFFER = 1024 * 1024
fun describeFile(resolver: ContentResolver, uri: Uri): SelectedFile? {
var name = "qft-upload.bin"
var size = -1L
var cursor: Cursor? = null
try {
cursor = resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE), null, null, null)
if (cursor?.moveToFirst() == true) {
val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
val sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE)
if (nameIndex >= 0) name = cursor.getString(nameIndex) ?: name
if (sizeIndex >= 0 && !cursor.isNull(sizeIndex)) size = cursor.getLong(sizeIndex)
}
} finally {
cursor?.close()
}
if (size < 0) {
size = try { resolver.openAssetFileDescriptor(uri, "r")?.use { it.length } ?: -1L } catch (_: Exception) { -1L }
}
if (size < 0) return null
return SelectedFile(uri, name, size)
}
/** Fast path: ask the PC directly over UDP on the newly connected QFT Wi-Fi. */
fun discoverUdp(
network: Network?,
pairing: PairingPayload,
hosts: List<InetAddress>,
): String? {
if (hosts.isEmpty()) return null
val socket = DatagramSocket()
return try {
network?.bindSocket(socket)
socket.broadcast = true
socket.soTimeout = 220
val request = "QFTDISC2:${pairing.session}".toByteArray(Charsets.US_ASCII)
repeat(3) {
for (host in hosts) {
try { socket.send(DatagramPacket(request, request.size, host, DISCOVERY_PORT)) } catch (_: Exception) {}
}
val deadline = android.os.SystemClock.elapsedRealtime() + 320
while (android.os.SystemClock.elapsedRealtime() < deadline) {
val buf = ByteArray(512)
val packet = DatagramPacket(buf, buf.size)
try {
socket.receive(packet)
} catch (_: Exception) {
break
}
val text = String(packet.data, packet.offset, packet.length, Charsets.US_ASCII)
val prefix = "QFTHERE2:${pairing.session}:"
if (!text.startsWith(prefix)) continue
val port = text.substring(prefix.length).toIntOrNull() ?: continue
if (port != pairing.port) continue
val base = "http://${packet.address.hostAddress}:$port"
if (PairingProtocol.isAllowedLocalHttpEndpoint(base, pairing.port)) return base
}
}
null
} catch (_: Exception) {
null
} finally {
socket.close()
}
}
fun probeRobust(
network: Network?,
pairing: PairingPayload,
deviceName: String,
preferredEndpoints: List<String> = emptyList(),
discoveredEndpoint: String? = null,
subnetEndpoints: List<String> = emptyList(),
): String? {
val common = listOf(
"http://192.168.137.1:${pairing.port}",
"http://192.168.49.1:${pairing.port}",
)
val fast = (listOfNotNull(discoveredEndpoint) + preferredEndpoints + pairing.endpoints + common)
.map { it.trim().removeSuffix("/") }
.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
while (fast.isNotEmpty() && android.os.SystemClock.elapsedRealtime() < fastDeadline) {
probeCandidatesParallel(network, pairing, deviceName, fast, workers = 8, connectMs = 320, readMs = 380)
?.let { return it }
try { Thread.sleep(90) } catch (_: InterruptedException) { return null }
}
// Stage 2: actual connected subnet fallback. This specifically fixes the
// case where Windows Wi-Fi Direct is up but uses an unexpected gateway
// address. Up to /24 is scanned concurrently and still session-authenticated.
val scan = subnetEndpoints
.map { it.trim().removeSuffix("/") }
.filter { PairingProtocol.isAllowedLocalHttpEndpoint(it, pairing.port) }
.filterNot { it in fast }
.distinct()
if (scan.isNotEmpty()) {
probeCandidatesParallel(network, pairing, deviceName, scan, workers = 24, connectMs = 240, readMs = 300)
?.let { return it }
}
// Final short retry for the expected addresses after the subnet scan.
val deadline = android.os.SystemClock.elapsedRealtime() + 2_000
while (fast.isNotEmpty() && android.os.SystemClock.elapsedRealtime() < deadline) {
probeCandidatesParallel(network, pairing, deviceName, fast, workers = 8, connectMs = 450, readMs = 500)
?.let { return it }
try { Thread.sleep(120) } catch (_: InterruptedException) { return null }
}
return null
}
private fun probeCandidatesParallel(
network: Network?,
pairing: PairingPayload,
deviceName: String,
candidates: List<String>,
workers: Int,
connectMs: Int,
readMs: Int,
): String? {
if (candidates.isEmpty()) return null
val pool = Executors.newFixedThreadPool(candidates.size.coerceAtMost(workers).coerceAtLeast(1))
val completion = ExecutorCompletionService<String?>(pool)
candidates.forEach { base ->
completion.submit(java.util.concurrent.Callable<String?> {
if (probeOne(network, pairing, deviceName, base, connectMs, readMs)) base else null
})
}
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)
repeat(candidates.size) {
val remaining = deadline - android.os.SystemClock.elapsedRealtime()
if (remaining <= 0) return null
val future = completion.poll(remaining.coerceAtMost(350L), TimeUnit.MILLISECONDS) ?: return@repeat
val result = future.get()
if (result != null) return result
}
null
} catch (_: Exception) {
null
} finally {
pool.shutdownNow()
}
}
private fun probeOne(
network: Network?, pairing: PairingPayload, deviceName: String, base: String,
connectMs: Int, readMs: Int,
): Boolean {
var conn: HttpURLConnection? = null
return try {
conn = open(network, URL("$base/qft/ping"))
conn.requestMethod = "GET"
conn.connectTimeout = connectMs
conn.readTimeout = readMs
conn.useCaches = false
conn.setRequestProperty("X-QFT-Token", pairing.session)
conn.setRequestProperty("X-QFT-Device", b64(deviceName))
conn.responseCode == 200
} catch (_: Exception) {
false
} finally {
conn?.disconnect()
}
}
fun upload(
resolver: ContentResolver,
network: Network?,
baseUrl: String,
pairing: PairingPayload,
deviceName: String,
file: SelectedFile,
onProgress: (sent: Long, total: Long) -> Unit,
) {
if (pairing.version >= 2 && isSeekable(resolver, file)) {
try {
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.
if (e is SecurityException) throw e
}
}
uploadLegacy(resolver, network, baseUrl, pairing, deviceName, file, onProgress)
}
private data class InitReply(val uploadId: String, val chunkSize: Long, val totalChunks: Int)
private fun uploadParallel(
resolver: ContentResolver,
network: Network?,
baseUrl: String,
pairing: PairingPayload,
deviceName: String,
file: SelectedFile,
onProgress: (sent: Long, total: Long) -> Unit,
) {
val init = initUpload(network, baseUrl, pairing, deviceName, file)
if (init.totalChunks == 0) {
finishUpload(network, baseUrl, pairing, deviceName, init.uploadId)
onProgress(0, 0)
return
}
val cpuWorkers = Runtime.getRuntime().availableProcessors().coerceIn(2, MAX_WORKERS)
val workerCount = init.totalChunks.coerceAtMost(cpuWorkers).coerceAtLeast(1)
val pool = Executors.newFixedThreadPool(workerCount)
val next = AtomicInteger(0)
val sent = AtomicLong(0)
val lastReport = AtomicLong(0)
val failures = mutableListOf<Throwable>()
val futures = (0 until workerCount).map {
pool.submit {
resolver.openFileDescriptor(file.uri, "r")?.use { pfd ->
FileInputStream(pfd.fileDescriptor).use { input ->
val channel = input.channel
val buffer = ByteBuffer.allocate(STREAM_BUFFER)
while (!Thread.currentThread().isInterrupted) {
val index = next.getAndIncrement()
if (index >= init.totalChunks) break
val offset = index.toLong() * init.chunkSize
val length = minOf(init.chunkSize, file.size - offset)
sendChunk(
network, baseUrl, pairing, deviceName,
init.uploadId, index, channel, offset, length, buffer,
)
val totalSent = sent.addAndGet(length)
val now = android.os.SystemClock.elapsedRealtime()
val previous = lastReport.get()
if (now - previous >= 80 && lastReport.compareAndSet(previous, now)) {
onProgress(totalSent.coerceAtMost(file.size), file.size)
}
}
}
} ?: error("无法打开 ${file.name}")
}
}
try {
futures.forEach { future ->
try { future.get() } catch (e: Exception) { failures += (e.cause ?: e) }
}
} finally {
pool.shutdownNow()
}
if (failures.isNotEmpty()) throw failures.first()
finishUpload(network, baseUrl, pairing, deviceName, init.uploadId)
onProgress(file.size, file.size)
}
private fun desiredChunkSize(fileSize: Long): Long = when {
fileSize < 32L * 1024L * 1024L -> CHUNK_SMALL
fileSize >= 512L * 1024L * 1024L -> CHUNK_LARGE
else -> CHUNK_DEFAULT
}
private fun initUpload(
network: Network?, baseUrl: String, pairing: PairingPayload,
deviceName: String, file: SelectedFile,
): InitReply {
val conn = open(network, URL("$baseUrl/qft/upload/init"))
try {
conn.requestMethod = "POST"
conn.doOutput = true
conn.connectTimeout = 3_000
conn.readTimeout = 6_000
conn.setFixedLengthStreamingMode(0)
commonHeaders(conn, pairing, deviceName)
conn.setRequestProperty("X-QFT-Filename", b64(file.name))
conn.setRequestProperty("X-QFT-Size", file.size.toString())
conn.setRequestProperty("X-QFT-Chunk-Size", desiredChunkSize(file.size).toString())
conn.outputStream.close()
val code = conn.responseCode
if (code != 200) error("初始化并行上传失败 HTTP $code")
val body = conn.inputStream.bufferedReader().use { it.readText() }
val obj = JSONObject(body)
return InitReply(
uploadId = obj.getString("upload_id"),
chunkSize = obj.getLong("chunk_size"),
totalChunks = obj.getInt("total_chunks"),
)
} finally {
conn.disconnect()
}
}
private fun sendChunk(
network: Network?, baseUrl: String, pairing: PairingPayload, deviceName: String,
uploadId: String, index: Int, channel: FileChannel, offset: Long, length: Long,
buffer: ByteBuffer,
) {
val conn = open(network, URL("$baseUrl/qft/upload/chunk/$uploadId/$index"))
try {
conn.requestMethod = "POST"
conn.doOutput = true
conn.connectTimeout = 4_000
conn.readTimeout = 15_000
conn.setFixedLengthStreamingMode(length)
conn.setRequestProperty("Content-Type", "application/octet-stream")
commonHeaders(conn, pairing, deviceName)
channel.position(offset)
conn.outputStream.use { output ->
var remaining = length
val array = buffer.array()
while (remaining > 0) {
buffer.clear()
buffer.limit(minOf(array.size.toLong(), remaining).toInt())
val n = channel.read(buffer)
if (n <= 0) error("读取文件分块提前结束")
output.write(array, 0, n)
remaining -= n.toLong()
}
output.flush()
}
val code = conn.responseCode
if (code != 200) {
val message = try { conn.errorStream?.bufferedReader()?.use { it.readText() } } catch (_: Exception) { null }
error("分块 $index 上传失败 HTTP $code${message?.let { ": $it" } ?: ""}")
}
try { conn.inputStream.close() } catch (_: Exception) {}
} finally {
conn.disconnect()
}
}
private fun finishUpload(
network: Network?, baseUrl: String, pairing: PairingPayload,
deviceName: String, uploadId: String,
) {
val conn = open(network, URL("$baseUrl/qft/upload/finish/$uploadId"))
try {
conn.requestMethod = "POST"
conn.doOutput = true
conn.connectTimeout = 4_000
conn.readTimeout = 120_000
conn.setFixedLengthStreamingMode(0)
commonHeaders(conn, pairing, deviceName)
conn.outputStream.close()
val code = conn.responseCode
if (code != 200) {
val message = try { conn.errorStream?.bufferedReader()?.use { it.readText() } } catch (_: Exception) { null }
error("完成上传失败 HTTP $code${message?.let { ": $it" } ?: ""}")
}
conn.inputStream.close()
} finally {
conn.disconnect()
}
}
private fun uploadLegacy(
resolver: ContentResolver,
network: Network?,
baseUrl: String,
pairing: PairingPayload,
deviceName: String,
file: SelectedFile,
onProgress: (sent: Long, total: Long) -> Unit,
) {
val conn = open(network, URL("$baseUrl/qft/upload"))
conn.requestMethod = "POST"
conn.doOutput = true
conn.connectTimeout = 8_000
conn.readTimeout = 30_000
conn.setFixedLengthStreamingMode(file.size)
conn.setRequestProperty("Content-Type", "application/octet-stream")
commonHeaders(conn, pairing, deviceName)
conn.setRequestProperty("X-QFT-Filename", b64(file.name))
conn.setRequestProperty("X-QFT-Size", file.size.toString())
resolver.openInputStream(file.uri).use { input ->
requireNotNull(input) { "无法打开 ${file.name}" }
conn.outputStream.use { output ->
val buf = ByteArray(STREAM_BUFFER)
var sent = 0L
var lastReport = 0L
while (true) {
val n = input.read(buf)
if (n <= 0) break
output.write(buf, 0, n)
sent += n
val now = android.os.SystemClock.elapsedRealtime()
if (now - lastReport >= 100 || sent == file.size) {
onProgress(sent, file.size)
lastReport = now
}
}
output.flush()
}
}
val code = conn.responseCode
if (code != 200) {
val message = try { conn.errorStream?.bufferedReader()?.use { it.readText() } } catch (_: Exception) { null }
conn.disconnect()
error("电脑返回 HTTP $code${message?.let { ": $it" } ?: ""}")
}
conn.inputStream.close()
conn.disconnect()
}
private fun isSeekable(resolver: ContentResolver, file: SelectedFile): Boolean {
if (file.size <= 0) return true
return try {
resolver.openFileDescriptor(file.uri, "r")?.use { pfd ->
FileInputStream(pfd.fileDescriptor).use { input ->
val channel = input.channel
val target = minOf(file.size - 1, 4096L).coerceAtLeast(0)
channel.position(target)
channel.position() == target
}
} ?: false
} catch (_: Exception) {
false
}
}
private fun commonHeaders(conn: HttpURLConnection, pairing: PairingPayload, deviceName: String) {
conn.useCaches = false
conn.setRequestProperty("Connection", "close")
conn.setRequestProperty("X-QFT-Token", pairing.session)
conn.setRequestProperty("X-QFT-Device", b64(deviceName))
}
private fun open(network: Network?, url: URL): HttpURLConnection {
return (network?.openConnection(url) ?: url.openConnection()) as HttpURLConnection
}
private fun b64(value: String): String = Base64Url.encode(value.toByteArray(Charsets.UTF_8))
}
@@ -0,0 +1,310 @@
package com.qft.optical
import android.content.Context
import android.net.ConnectivityManager
import android.net.LinkProperties
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.net.wifi.WifiConfiguration
import android.net.wifi.WifiManager
import android.net.wifi.WifiNetworkSpecifier
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import java.net.Inet4Address
import java.net.InetAddress
class WifiConnector(context: Context) {
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
private val handler = Handler(Looper.getMainLooper())
private var callback: ConnectivityManager.NetworkCallback? = null
private var generation = 0
private var legacyPreviousNetworkId: Int? = null
private var legacyTargetNetworkId: Int? = null
fun connect(
pairing: PairingPayload,
onStatus: (String) -> Unit,
onAvailable: (Network?) -> Unit,
onUnavailable: (String) -> Unit,
) {
release(restoreLegacy = false)
generation++
val run = generation
val wifi = pairing.wifi
if (wifi == null) {
onStatus("正在使用当前局域网发现电脑…")
val wifiNetwork = bestWifiNetwork()
onAvailable(wifiNetwork ?: connectivity.activeNetwork)
return
}
if (Build.VERSION.SDK_INT >= 29) {
connectModern(run, wifi, onStatus, onAvailable, onUnavailable)
} else {
connectLegacy(run, wifi, onStatus, onAvailable, onUnavailable)
}
}
private fun connectModern(
run: Int,
wifi: WifiCredentials,
onStatus: (String) -> Unit,
onAvailable: (Network?) -> Unit,
onUnavailable: (String) -> Unit,
) {
onStatus("正在请求连接 ${wifi.ssid}…")
val specifier = try {
WifiNetworkSpecifier.Builder()
.setSsid(wifi.ssid)
.setWpa2Passphrase(wifi.passphrase)
.build()
} catch (e: Exception) {
onUnavailable("配网参数无效:${e.message}")
return
}
val request = NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.setNetworkSpecifier(specifier)
.build()
val delivered = booleanArrayOf(false)
val cb = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
if (run != generation) return
onStatus("Wi-Fi 已关联,正在等待本地 IP/路由…")
waitUntilUsable(run, network, onStatus) {
if (!delivered[0] && run == generation) {
delivered[0] = true
onStatus("QFT 本地网络已就绪,正在快速发现电脑…")
onAvailable(network)
}
}
}
override fun onLinkPropertiesChanged(network: Network, linkProperties: LinkProperties) {
if (run != generation || delivered[0]) return
if (hasIpv4(linkProperties)) {
delivered[0] = true
onStatus("QFT 本地网络已就绪,正在快速发现电脑…")
onAvailable(network)
}
}
override fun onUnavailable() {
if (run == generation) onUnavailable("未能连接 QFT 临时网络。请确认 Wi-Fi 已开启并批准系统连接请求。")
}
override fun onLost(network: Network) {
if (run == generation && delivered[0]) onUnavailable("QFT 临时网络已断开")
}
}
callback = cb
try {
connectivity.requestNetwork(request, cb, 15_000)
handler.postDelayed({
if (run == generation && !delivered[0]) {
onStatus("仍在等待系统完成配网…")
}
}, 8_000)
} catch (e: Exception) {
callback = null
onUnavailable("系统配网请求失败:${e.message}")
}
}
@Suppress("DEPRECATION")
private fun connectLegacy(
run: Int,
wifi: WifiCredentials,
onStatus: (String) -> Unit,
onAvailable: (Network?) -> Unit,
onUnavailable: (String) -> Unit,
) {
onStatus("Android ${Build.VERSION.RELEASE} 兼容配网:正在连接 ${wifi.ssid}…")
try {
if (!wifiManager.isWifiEnabled) {
wifiManager.isWifiEnabled = true
}
legacyPreviousNetworkId = wifiManager.connectionInfo?.networkId?.takeIf { it >= 0 }
val quoted = "\"${wifi.ssid}\""
val existing = try { wifiManager.configuredNetworks?.firstOrNull { it.SSID == quoted } } catch (_: Exception) { null }
val targetId = if (existing != null) {
existing.networkId
} else {
val config = WifiConfiguration().apply {
SSID = quoted
preSharedKey = "\"${wifi.passphrase}\""
allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK)
}
wifiManager.addNetwork(config)
}
if (targetId < 0) {
onUnavailable("Android 7~9 无法写入 QFT Wi-Fi 配置;请确认已授予位置权限。")
return
}
legacyTargetNetworkId = targetId
wifiManager.disconnect()
if (!wifiManager.enableNetwork(targetId, true)) {
onUnavailable("系统拒绝启用 QFT Wi-Fi 网络")
return
}
wifiManager.reconnect()
val started = SystemClock.elapsedRealtime()
fun poll() {
if (run != generation) return
val info = wifiManager.connectionInfo
val matches = info != null && (info.networkId == targetId || normalizeSsid(info.ssid) == wifi.ssid)
if (matches) {
val network = bestWifiNetwork()
if (network != null && hasIpv4(connectivity.getLinkProperties(network))) {
onStatus("QFT Wi-Fi 已连接,正在快速发现电脑…")
onAvailable(network)
return
}
}
if (SystemClock.elapsedRealtime() - started > 15_000) {
onUnavailable("连接 QFT Wi-Fi 超时。请确认电脑热点仍在运行。")
} else {
handler.postDelayed({ poll() }, 250)
}
}
handler.postDelayed({ poll() }, 250)
} catch (e: Exception) {
onUnavailable("Android 7~9 配网失败:${e.message}")
}
}
private fun waitUntilUsable(run: Int, network: Network, onStatus: (String) -> Unit, done: () -> Unit) {
val started = SystemClock.elapsedRealtime()
fun poll() {
if (run != generation) return
if (hasIpv4(connectivity.getLinkProperties(network))) {
done()
return
}
if (SystemClock.elapsedRealtime() - started > 6_000) {
onStatus("网络已连接但路由仍未就绪,继续尝试电脑发现…")
done()
} else {
handler.postDelayed({ poll() }, 120)
}
}
poll()
}
private fun bestWifiNetwork(): Network? = connectivity.allNetworks.firstOrNull { network ->
val caps = connectivity.getNetworkCapabilities(network)
caps?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true && hasIpv4(connectivity.getLinkProperties(network))
}
private fun hasIpv4(props: LinkProperties?): Boolean = props?.linkAddresses?.any { it.address is Inet4Address } == true
fun gatewayEndpoints(network: Network?, port: Int): List<String> {
if (network == null) return emptyList()
val props = connectivity.getLinkProperties(network) ?: return emptyList()
return props.routes
.asSequence()
.mapNotNull { it.gateway as? Inet4Address }
.map { "http://${it.hostAddress}:$port" }
.distinct()
.toList()
}
fun discoveryHosts(network: Network?): List<InetAddress> {
val out = mutableListOf<InetAddress>()
if (network != null) {
val props = connectivity.getLinkProperties(network)
props?.routes
?.mapNotNull { it.gateway as? Inet4Address }
?.forEach { if (it !in out) out += it }
// Directed broadcast is more reliable than 255.255.255.255 on some
// Wi-Fi drivers/local-only networks. Derive it from the actual link.
props?.linkAddresses
?.filter { it.address is Inet4Address }
?.mapNotNull { directedBroadcast(it.address as Inet4Address, it.prefixLength) }
?.forEach { if (it !in out) out += it }
}
try {
val broadcast = InetAddress.getByName("255.255.255.255")
if (broadcast !in out) out += broadcast
} catch (_: Exception) {}
return out
}
/**
* Last-resort receiver discovery. Enumerates at most one /24 around the
* phone's actual QFT Wi-Fi address (<=254 hosts) so a nonstandard Windows
* Direct-AP gateway can still be found without guessing 192.168.137.1.
*/
fun subnetEndpoints(network: Network?, port: Int): List<String> {
if (network == null) return emptyList()
val props = connectivity.getLinkProperties(network) ?: return emptyList()
val out = LinkedHashSet<String>()
for (link in props.linkAddresses) {
val addr = link.address as? Inet4Address ?: continue
val octets = addr.address.map { it.toInt() and 0xFF }
// Never scan more than /24. For a narrower real subnet (/25 etc),
// respect its prefix and enumerate fewer hosts.
val prefix = link.prefixLength.coerceIn(24, 30)
val ip = (octets[0] shl 24) or (octets[1] shl 16) or (octets[2] shl 8) or octets[3]
val mask = if (prefix == 0) 0 else (-1 shl (32 - prefix))
val networkInt = ip and mask
val broadcastInt = networkInt or mask.inv()
for (candidate in (networkInt + 1) until broadcastInt) {
if (candidate == ip) continue
val host = "%d.%d.%d.%d".format(
(candidate ushr 24) and 0xFF,
(candidate ushr 16) and 0xFF,
(candidate ushr 8) and 0xFF,
candidate and 0xFF,
)
out += "http://$host:$port"
}
}
return out.toList()
}
private fun directedBroadcast(address: Inet4Address, prefixLength: Int): InetAddress? {
if (prefixLength !in 1..30) return null
val b = address.address.map { it.toInt() and 0xFF }
val ip = (b[0] shl 24) or (b[1] shl 16) or (b[2] shl 8) or b[3]
val mask = -1 shl (32 - prefixLength)
val broadcast = (ip and mask) or mask.inv()
val bytes = byteArrayOf(
((broadcast ushr 24) and 0xFF).toByte(),
((broadcast ushr 16) and 0xFF).toByte(),
((broadcast ushr 8) and 0xFF).toByte(),
(broadcast and 0xFF).toByte(),
)
return try { InetAddress.getByAddress(bytes) } catch (_: Exception) { null }
}
@Suppress("DEPRECATION")
fun release(restoreLegacy: Boolean = true) {
generation++
callback?.let {
try { connectivity.unregisterNetworkCallback(it) } catch (_: Exception) {}
}
callback = null
handler.removeCallbacksAndMessages(null)
if (restoreLegacy && Build.VERSION.SDK_INT < 29) {
val previous = legacyPreviousNetworkId
if (previous != null && previous >= 0) {
try {
wifiManager.enableNetwork(previous, true)
wifiManager.reconnect()
} catch (_: Exception) {}
}
}
legacyPreviousNetworkId = null
legacyTargetNetworkId = null
}
private fun normalizeSsid(value: String?): String = value.orEmpty().removePrefix("\"").removeSuffix("\"")
}
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="QftTheme" parent="android:style/Theme.Material.Light.NoActionBar">
<item name="android:windowActionModeOverlay">true</item>
<item name="android:windowBackground">@android:color/black</item>
<item name="android:navigationBarColor">@android:color/black</item>
<item name="android:statusBarColor">@android:color/black</item>
</style>
</resources>
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<!-- QFTPAIR validation only permits literal private/local IPv4 endpoints.
Local HTTP is intentionally enabled because the direct PC hotspot has no
public DNS/certificate infrastructure. The per-session token still
authenticates every request. -->
<base-config cleartextTrafficPermitted="true" />
</network-security-config>
@@ -0,0 +1,75 @@
package com.qft.optical
import org.junit.Assert.*
import org.junit.Test
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.Base64
import java.util.zip.CRC32
class ProtocolTest {
@Test
fun parsesDataFrameAndRejectsCorruption() {
val payload = byteArrayOf(1, 2, 3, 4, 5)
val text = encode(kind = 2, session = 7L, seq = 9, total = 11, payload = payload)
val f = QftProtocol.parseText(text)!!
assertEquals(FrameKind.DATA, f.kind)
assertEquals(7L, f.sessionId)
assertEquals(9L, f.seq)
assertArrayEquals(payload, f.payload)
val corrupted = text.dropLast(1) + if (text.last() == 'A') "B" else "A"
assertNull(QftProtocol.parseText(corrupted))
}
@Test
fun parsesCrossLanguageKnownVector() {
val text = "QFT1:UUZUMQECAQIDBAUGBwgAAAADAAAACgAJaGVsbG8tcWZ0XhNTAg"
val f = QftProtocol.parseText(text)!!
assertEquals(FrameKind.DATA, f.kind)
assertEquals(0x0102030405060708L, f.sessionId)
assertEquals(3L, f.seq)
assertEquals(10L, f.totalChunks)
assertEquals("hello-qft", f.payload.toString(Charsets.UTF_8))
}
@Test
fun parsesManifestSenderDevice() {
val name = "test.txt".toByteArray()
val device = "DESKTOP-ZHY".toByteArray()
val sha = ByteArray(32) { it.toByte() }
val payload = ByteBuffer.allocate(8 + 2 + 32 + 2 + name.size + 2 + device.size)
.order(ByteOrder.BIG_ENDIAN)
.putLong(1234L)
.putShort(700.toShort())
.put(sha)
.putShort(name.size.toShort())
.put(name)
.putShort(device.size.toShort())
.put(device)
.array()
val text = encode(kind = 1, session = 77L, seq = 0, total = 2, payload = payload)
val frame = QftProtocol.parseText(text)!!
val manifest = QftProtocol.parseManifest(frame)!!
assertEquals("DESKTOP-ZHY", manifest.senderDevice)
assertEquals("test.txt", manifest.fileName)
assertEquals(1234L, manifest.fileSize)
assertEquals(700, manifest.chunkSize)
}
private fun encode(kind: Int, session: Long, seq: Int, total: Int, payload: ByteArray): String {
val bb = ByteBuffer.allocate(24 + payload.size + 4).order(ByteOrder.BIG_ENDIAN)
bb.put("QFT1".toByteArray())
bb.put(1)
bb.put(kind.toByte())
bb.putLong(session)
bb.putInt(seq)
bb.putInt(total)
bb.putShort(payload.size.toShort())
bb.put(payload)
val bodyLen = bb.position()
val crc = CRC32().apply { update(bb.array(), 0, bodyLen) }.value
bb.putInt(crc.toInt())
return "QFT1:" + Base64.getUrlEncoder().withoutPadding().encodeToString(bb.array())
}
}
+8
View File
@@ -0,0 +1,8 @@
$ErrorActionPreference = "Stop"
$jar = Join-Path $PSScriptRoot "gradle\wrapper\gradle-wrapper.jar"
$url = "https://raw.githubusercontent.com/gradle/gradle/v8.11.1/gradle/wrapper/gradle-wrapper.jar"
if (-not (Test-Path $jar)) {
Write-Host "Downloading Gradle wrapper jar..."
Invoke-WebRequest -Uri $url -OutFile $jar
}
Write-Host "Gradle wrapper ready: $jar"
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env sh
set -eu
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
JAR="$ROOT/gradle/wrapper/gradle-wrapper.jar"
URL="https://raw.githubusercontent.com/gradle/gradle/v8.11.1/gradle/wrapper/gradle-wrapper.jar"
if [ ! -f "$JAR" ]; then
echo "Downloading Gradle wrapper jar..."
if command -v curl >/dev/null 2>&1; then
curl -fL "$URL" -o "$JAR"
elif command -v wget >/dev/null 2>&1; then
wget -O "$JAR" "$URL"
else
echo "Need curl or wget" >&2
exit 1
fi
fi
echo "Gradle wrapper ready: $JAR"
+4
View File
@@ -0,0 +1,4 @@
plugins {
id("com.android.application") version "8.9.1" apply false
id("org.jetbrains.kotlin.android") version "2.1.20" apply false
}
+2
View File
@@ -0,0 +1,2 @@
org.gradle.jvmargs=-Xmx3g -Dfile.encoding=UTF-8
android.useAndroidX=true
+7
View File
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
APP_HOME=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
exec java -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
+3
View File
@@ -0,0 +1,3 @@
@echo off
set APP_HOME=%~dp0
java -classpath "%APP_HOME%gradle\wrapper\gradle-wrapper.jar" org.gradle.wrapper.GradleWrapperMain %*
+3
View File
@@ -0,0 +1,3 @@
# Copy this file to local.properties and point it to your Android SDK.
# Forward slashes avoid escaping problems on Windows.
sdk.dir=E:/SYSTEM/APPDATA/Android_SDK
+68
View File
@@ -0,0 +1,68 @@
param(
[string]$Sdk = "E:\SYSTEM\APPDATA\Android_SDK"
)
$ErrorActionPreference = "Stop"
$Project = $PSScriptRoot
$SdkManager = Join-Path $Sdk "cmdline-tools\latest\bin\sdkmanager.bat"
Write-Host "QFT Android build repair" -ForegroundColor Cyan
Write-Host "Project: $Project"
Write-Host "SDK: $Sdk"
if (-not (Test-Path $Sdk)) {
throw "Android SDK not found: $Sdk"
}
if (-not (Test-Path $SdkManager)) {
throw "sdkmanager not found: $SdkManager`nInstall Android SDK Command-line Tools (latest) from Android Studio > SDK Manager > SDK Tools."
}
$javaVersion = (& java -version 2>&1 | Select-Object -First 1)
Write-Host "Java: $javaVersion"
if (-not (Get-Command javac -ErrorAction SilentlyContinue)) {
throw "javac was not found. Configure Android Studio Gradle JDK to JDK 17 (full JDK, not a JRE)."
}
# Force Gradle and Android Studio project import to use the same SDK.
$SdkForProperties = $Sdk -replace '\\','/'
"sdk.dir=$SdkForProperties" | Set-Content -Encoding ASCII (Join-Path $Project "local.properties")
Write-Host "Installing/repairing API 35 platform and Build Tools 35.0.0..." -ForegroundColor Yellow
& $SdkManager --install "platforms;android-35" "build-tools;35.0.0" "platform-tools"
if ($LASTEXITCODE -ne 0) { throw "sdkmanager failed with exit code $LASTEXITCODE" }
$AndroidJar = Join-Path $Sdk "platforms\android-35\android.jar"
if (-not (Test-Path $AndroidJar)) {
throw "android-35/android.jar is still missing after installation: $AndroidJar"
}
Write-Host "Stopping Gradle daemons..."
Push-Location $Project
try {
if (-not (Test-Path (Join-Path $Project "gradle\wrapper\gradle-wrapper.jar"))) {
& (Join-Path $Project "bootstrap-wrapper.ps1")
}
& .\gradlew.bat --stop
Write-Host "Clearing project Gradle state..."
Remove-Item (Join-Path $Project ".gradle") -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item (Join-Path $Project "app\build") -Recurse -Force -ErrorAction SilentlyContinue
Write-Host "Gradle environment:" -ForegroundColor Cyan
& .\gradlew.bat --version
Write-Host "Building debug APK..." -ForegroundColor Green
& .\gradlew.bat clean :app:assembleDebug --stacktrace
if ($LASTEXITCODE -ne 0) { throw "Gradle build failed with exit code $LASTEXITCODE" }
$Apk = Join-Path $Project "app\build\outputs\apk\debug\app-debug.apk"
if (Test-Path $Apk) {
Write-Host "SUCCESS: $Apk" -ForegroundColor Green
} else {
Write-Warning "Build completed but APK was not found at the expected path: $Apk"
}
}
finally {
Pop-Location
}
+18
View File
@@ -0,0 +1,18 @@
pluginManagement {
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "QftOpticalAndroid"
include(":app")