Compare commits
3 Commits
551022215c
...
android-ma
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
69bd3d1d8e | ||
|
|
360b57e3e2 | ||
|
|
c5f4f854bf |
52
README.md
52
README.md
@@ -1,10 +1,11 @@
|
||||
# Tauri Demo (SvelteKit + TypeScript)
|
||||
# JE-Skin (SvelteKit + Tauri)
|
||||
|
||||
## 环境要求
|
||||
|
||||
- Node.js 18+(建议 LTS)
|
||||
- Rust stable(`rustup` + `cargo`)
|
||||
- Windows 下请确保已安装 WebView2 Runtime 和 MSVC C++ 构建工具
|
||||
- Android 构建需要 Android SDK + NDK
|
||||
|
||||
## 安装依赖
|
||||
|
||||
@@ -42,12 +43,61 @@ npm run build
|
||||
npm run tauri build
|
||||
```
|
||||
|
||||
构建 Android APK / AAB:
|
||||
|
||||
```sh
|
||||
npx tauri android build
|
||||
```
|
||||
|
||||
产物路径:
|
||||
- APK: `src-tauri/gen/android/app/build/outputs/apk/universal/release/app-universal-release.apk`
|
||||
- AAB: `src-tauri/gen/android/app/build/outputs/bundle/universalRelease/app-universal-release.aab`
|
||||
|
||||
Release APK 默认使用 debug keystore 签名(`src-tauri/gen/android/app/je-skin-debug.keystore`),可直接 `adb install` 到设备。
|
||||
|
||||
## 代码检查
|
||||
|
||||
```sh
|
||||
npm run check
|
||||
```
|
||||
|
||||
## v0.5.0 修改记录
|
||||
|
||||
### Android USB 串口接入
|
||||
|
||||
- **Tauri 插件注册**:Android 端通过 Rust builder 注册 `usb-serial` 插件,移除 `MainActivity` 中的手动加载逻辑
|
||||
- **USB 设备枚举**:使用 `usb-serial-for-android` 的 `UsbSerialProber` 识别串口设备,并返回设备名、厂商 ID、产品 ID、权限状态等信息
|
||||
- **USB 权限申请**:完善 Android USB 授权回调,支持按设备名、vendorId/productId 解析设备并处理授权后的打开流程
|
||||
- **串口数据桥接**:Kotlin 端打开 USB serial port 后通过 Unix socketpair 将 fd 交给 Rust,Rust 端继续复用 `serial_connect_fd` 数据采集链路
|
||||
- **资源释放**:关闭连接时同步释放桥接 fd、USB serial port 和 `UsbDeviceConnection`,避免重复打开后的资源残留
|
||||
|
||||
### Tauri 权限与构建
|
||||
|
||||
- 新增 `src-tauri/permissions/usb-serial/default.toml`,声明 Android USB serial 插件命令和前端所需本地命令权限
|
||||
- `default.json` 增加 USB serial 与本地命令权限,兼容 snake_case / camelCase 插件命令名
|
||||
- Android Gradle 仓库加入 JitPack,用于解析 USB serial 驱动依赖
|
||||
- ProGuard 增加 Tauri 插件注解、`UsbSerialPlugin` 和 `com.hoho.android.usbserial` 保留规则,避免 release 包混淆后插件命令失效
|
||||
- Android 构建下 `serial_enum` 返回空列表,并仅保留 fd 连接入口,避免桌面串口枚举依赖进入 Android 编译路径
|
||||
|
||||
## v0.4.0 修改记录
|
||||
|
||||
### 移动端性能优化
|
||||
|
||||
- **SignalChart / SummaryCurve**:在 `@media (max-width: 900px)` 下移除 SVG 路径上的 `filter: drop-shadow()`,避免移动端 GPU 软件回流导致卡顿
|
||||
- **SignalChart**:隐藏 `.scan-haze`(`mix-blend-mode: screen` 合成开销大),简化面板 `background` / `box-shadow`
|
||||
- **SummaryCurve**:移动端移除 `.summary-line` 和 `.summary-dot` 的 drop-shadow 滤镜
|
||||
- **页面级**:移动端隐藏 `.hud-noise`(`feTurbulence` SVG 滤镜是最大性能杀手),降低 `.hud-vignette` 透明度,简化 `.hud-gradient`
|
||||
- 移除 inactive 面板的 `filter: blur()` 过渡动画
|
||||
- 移除 transition 中的 `filter` 属性,添加 `will-change: d` 优化路径更新
|
||||
|
||||
### 移动端 UI 调整
|
||||
|
||||
- **隐藏三大金刚**:`@media (max-width: 900px)` 下隐藏标题栏右侧的最小化/最大化/关闭按钮(Android 系统自带窗口管理)
|
||||
|
||||
### Android 打包
|
||||
|
||||
- Release 构建配置使用 debug keystore 签名,输出签名 APK 而非 unsigned
|
||||
|
||||
## 推荐 IDE 插件
|
||||
|
||||
[VS Code](https://code.visualstudio.com/) + [Svelte](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode) + [Tauri](https://marketplace.visualstudio.com/items?itemName=tauri-apps.tauri-vscode) + [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer)
|
||||
|
||||
@@ -11,6 +11,13 @@
|
||||
"core:window:allow-set-size",
|
||||
"core:window:allow-start-dragging",
|
||||
"opener:default",
|
||||
"process:default"
|
||||
"process:default",
|
||||
"allow-usb-serial-list",
|
||||
"allow-usb-serial-open",
|
||||
"allow-usb-serial-close",
|
||||
"allow-usb-serial-list-camel",
|
||||
"allow-usb-serial-open-camel",
|
||||
"allow-usb-serial-close-camel",
|
||||
"allow-local-commands"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -43,6 +43,7 @@ android {
|
||||
.plus(getDefaultProguardFile("proguard-android-optimize.txt"))
|
||||
.toList().toTypedArray()
|
||||
)
|
||||
signingConfig = signingConfigs.getByName("debug")
|
||||
}
|
||||
}
|
||||
kotlinOptions {
|
||||
@@ -63,6 +64,7 @@ dependencies {
|
||||
implementation("androidx.activity:activity-ktx:1.10.1")
|
||||
implementation("com.google.android.material:material:1.12.0")
|
||||
implementation("androidx.lifecycle:lifecycle-process:2.10.0")
|
||||
implementation("com.github.mik3y:usb-serial-for-android:3.9.0")
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
androidTestImplementation("androidx.test.ext:junit:1.1.4")
|
||||
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.0")
|
||||
|
||||
13
src-tauri/gen/android/app/proguard-rules.pro
vendored
13
src-tauri/gen/android/app/proguard-rules.pro
vendored
@@ -19,3 +19,16 @@
|
||||
# If you keep the line number information, uncomment this to
|
||||
# hide the original source file name.
|
||||
#-renamesourcefileattribute SourceFile
|
||||
|
||||
-keepattributes RuntimeVisibleAnnotations,RuntimeInvisibleAnnotations,*Annotation*,Signature,InnerClasses,EnclosingMethod
|
||||
|
||||
-keep class app.tauri.annotation.** { *; }
|
||||
-keep class app.tauri.plugin.** { *; }
|
||||
|
||||
-keep class com.lenn.tauri_serial.MainActivity { *; }
|
||||
-keep class com.lenn.tauri_serial.UsbSerialPlugin { *; }
|
||||
-keepclassmembers class com.lenn.tauri_serial.UsbSerialPlugin {
|
||||
public *;
|
||||
}
|
||||
|
||||
-keep class com.hoho.android.usbserial.** { *; }
|
||||
|
||||
@@ -7,7 +7,5 @@ class MainActivity : TauriActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
enableEdgeToEdge()
|
||||
super.onCreate(savedInstanceState)
|
||||
val plugin = UsbSerialPlugin(this)
|
||||
pluginManager.load(null, "usb-serial", plugin, "")
|
||||
}
|
||||
}
|
||||
@@ -10,20 +10,36 @@ import android.hardware.usb.UsbDevice
|
||||
import android.hardware.usb.UsbDeviceConnection
|
||||
import android.hardware.usb.UsbManager
|
||||
import android.os.Build
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.system.Os
|
||||
import android.system.OsConstants
|
||||
import app.tauri.annotation.Command
|
||||
import app.tauri.annotation.TauriPlugin
|
||||
import app.tauri.plugin.Invoke
|
||||
import app.tauri.plugin.JSObject
|
||||
import app.tauri.plugin.Plugin
|
||||
import app.tauri.plugin.Invoke
|
||||
import com.hoho.android.usbserial.driver.UsbSerialDriver
|
||||
import com.hoho.android.usbserial.driver.UsbSerialPort
|
||||
import com.hoho.android.usbserial.driver.UsbSerialProber
|
||||
import java.io.FileDescriptor
|
||||
import java.io.FileInputStream
|
||||
import java.io.FileOutputStream
|
||||
import java.io.IOException
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import org.json.JSONArray
|
||||
|
||||
@TauriPlugin
|
||||
class UsbSerialPlugin(private val activity: Activity) : Plugin(activity) {
|
||||
companion object {
|
||||
private const val ACTION_USB_PERMISSION = "com.lenn.tauri_serial.USB_PERMISSION"
|
||||
private const val BAUD_RATE = 921600
|
||||
private const val READ_TIMEOUT_MS = 100
|
||||
private const val WRITE_TIMEOUT_MS = 100
|
||||
}
|
||||
|
||||
private var pendingConnectInvoke: Invoke? = null
|
||||
private var pendingConnectDevice: UsbDevice? = null
|
||||
private var pendingConnectDeviceName: String? = null
|
||||
private var activeBridge: SerialBridge? = null
|
||||
|
||||
private val usbPermissionReceiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
@@ -39,10 +55,10 @@ class UsbSerialPlugin(private val activity: Activity) : Plugin(activity) {
|
||||
|
||||
val granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)
|
||||
val invoke = pendingConnectInvoke
|
||||
val targetDevice = pendingConnectDevice
|
||||
val targetDeviceName = pendingConnectDeviceName
|
||||
|
||||
pendingConnectInvoke = null
|
||||
pendingConnectDevice = null
|
||||
pendingConnectDeviceName = null
|
||||
|
||||
if (invoke == null || device == null) return
|
||||
|
||||
@@ -51,8 +67,8 @@ class UsbSerialPlugin(private val activity: Activity) : Plugin(activity) {
|
||||
return
|
||||
}
|
||||
|
||||
if (targetDevice != null && device.deviceName == targetDevice.deviceName) {
|
||||
openAndReturn(invoke, device)
|
||||
if (targetDeviceName != null && device.deviceName == targetDeviceName) {
|
||||
openAndReturn(invoke, device.deviceName)
|
||||
} else {
|
||||
invoke.reject("USB device mismatch")
|
||||
}
|
||||
@@ -65,7 +81,9 @@ class UsbSerialPlugin(private val activity: Activity) : Plugin(activity) {
|
||||
val filter = IntentFilter(ACTION_USB_PERMISSION)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
activity.applicationContext.registerReceiver(
|
||||
usbPermissionReceiver, filter, Context.RECEIVER_NOT_EXPORTED
|
||||
usbPermissionReceiver,
|
||||
filter,
|
||||
Context.RECEIVER_NOT_EXPORTED
|
||||
)
|
||||
} else {
|
||||
activity.applicationContext.registerReceiver(usbPermissionReceiver, filter)
|
||||
@@ -74,45 +92,66 @@ class UsbSerialPlugin(private val activity: Activity) : Plugin(activity) {
|
||||
|
||||
override fun onDestroy() {
|
||||
super.onDestroy()
|
||||
activeBridge?.close()
|
||||
activeBridge = null
|
||||
try {
|
||||
activity.applicationContext.unregisterReceiver(usbPermissionReceiver)
|
||||
} catch (_: Exception) {}
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
}
|
||||
|
||||
@Command
|
||||
fun usb_serial_list(invoke: Invoke) {
|
||||
listDevices(invoke)
|
||||
}
|
||||
|
||||
@Command
|
||||
fun usbSerialList(invoke: Invoke) {
|
||||
listDevices(invoke)
|
||||
}
|
||||
|
||||
private fun listDevices(invoke: Invoke) {
|
||||
val usbManager = activity.getSystemService(Context.USB_SERVICE) as? UsbManager
|
||||
if (usbManager == null) {
|
||||
invoke.reject("USB service not available")
|
||||
return
|
||||
}
|
||||
|
||||
val devices = usbManager.deviceList
|
||||
val result = JSObject()
|
||||
val serialDevices = JSONArray()
|
||||
|
||||
val serialDevices = mutableListOf<JSObject>()
|
||||
for ((_, device) in devices) {
|
||||
if (isUsbSerialDevice(device)) {
|
||||
val obj = JSObject()
|
||||
obj.put("name", device.deviceName)
|
||||
obj.put("vendorId", device.vendorId)
|
||||
obj.put("productId", device.productId)
|
||||
obj.put("manufacturer", device.manufacturerName ?: "")
|
||||
obj.put("product", device.productName ?: "")
|
||||
obj.put("serial", device.serialNumber ?: "")
|
||||
obj.put("hasPermission", usbManager.hasPermission(device))
|
||||
serialDevices.add(obj)
|
||||
}
|
||||
for (driver in UsbSerialProber.getDefaultProber().findAllDrivers(usbManager)) {
|
||||
val device = driver.device
|
||||
val obj = JSObject()
|
||||
obj.put("name", device.deviceName)
|
||||
obj.put("vendorId", device.vendorId)
|
||||
obj.put("productId", device.productId)
|
||||
obj.put("manufacturer", safeDeviceString { device.manufacturerName })
|
||||
obj.put("product", safeDeviceString { device.productName })
|
||||
obj.put("serial", safeDeviceString { device.serialNumber })
|
||||
obj.put("hasPermission", usbManager.hasPermission(device))
|
||||
serialDevices.put(obj)
|
||||
}
|
||||
|
||||
result.put("devices", serialDevices.toTypedArray())
|
||||
result.put("devices", serialDevices)
|
||||
invoke.resolve(result)
|
||||
}
|
||||
|
||||
@Command
|
||||
fun usb_serial_open(invoke: Invoke) {
|
||||
openDevice(invoke)
|
||||
}
|
||||
|
||||
@Command
|
||||
fun usbSerialOpen(invoke: Invoke) {
|
||||
openDevice(invoke)
|
||||
}
|
||||
|
||||
private fun openDevice(invoke: Invoke) {
|
||||
val args = invoke.parseArgs(JSObject::class.java)
|
||||
val deviceName = args.optString("name", "")
|
||||
val vendorId = if (args.has("vendorId")) args.optInt("vendorId") else null
|
||||
val productId = if (args.has("productId")) args.optInt("productId") else null
|
||||
|
||||
val usbManager = activity.getSystemService(Context.USB_SERVICE) as? UsbManager
|
||||
if (usbManager == null) {
|
||||
@@ -120,98 +159,230 @@ class UsbSerialPlugin(private val activity: Activity) : Plugin(activity) {
|
||||
return
|
||||
}
|
||||
|
||||
val device = usbManager.deviceList[deviceName]
|
||||
val device = resolveDevice(usbManager, deviceName, vendorId, productId)
|
||||
if (device == null) {
|
||||
invoke.reject("USB device not found: $deviceName")
|
||||
val available = usbManager.deviceList.values.joinToString(", ") { it.deviceName }
|
||||
invoke.reject("USB device not found: $deviceName; available: $available")
|
||||
return
|
||||
}
|
||||
|
||||
if (!usbManager.hasPermission(device)) {
|
||||
synchronized(this) {
|
||||
pendingConnectInvoke = invoke
|
||||
pendingConnectDevice = device
|
||||
pendingConnectDeviceName = device.deviceName
|
||||
}
|
||||
|
||||
val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
PendingIntent.FLAG_MUTABLE
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
|
||||
} else {
|
||||
0
|
||||
PendingIntent.FLAG_UPDATE_CURRENT
|
||||
}
|
||||
val permissionRequest = Intent(ACTION_USB_PERMISSION).setPackage(activity.packageName)
|
||||
val permissionIntent = PendingIntent.getBroadcast(
|
||||
activity, 0, Intent(ACTION_USB_PERMISSION), flags
|
||||
activity,
|
||||
0,
|
||||
permissionRequest,
|
||||
flags
|
||||
)
|
||||
usbManager.requestPermission(device, permissionIntent)
|
||||
return
|
||||
}
|
||||
|
||||
openAndReturn(invoke, device)
|
||||
openAndReturn(invoke, device.deviceName)
|
||||
}
|
||||
|
||||
@Command
|
||||
fun usb_serial_close(invoke: Invoke) {
|
||||
closeBridge()
|
||||
invoke.resolve(JSObject())
|
||||
}
|
||||
|
||||
private fun openAndReturn(invoke: Invoke, device: UsbDevice) {
|
||||
@Command
|
||||
fun usbSerialClose(invoke: Invoke) {
|
||||
closeBridge()
|
||||
invoke.resolve(JSObject())
|
||||
}
|
||||
|
||||
private fun closeBridge() {
|
||||
activeBridge?.close()
|
||||
activeBridge = null
|
||||
}
|
||||
|
||||
private fun openAndReturn(invoke: Invoke, deviceName: String) {
|
||||
val usbManager = activity.getSystemService(Context.USB_SERVICE) as? UsbManager
|
||||
if (usbManager == null) {
|
||||
invoke.reject("USB service not available")
|
||||
return
|
||||
}
|
||||
|
||||
val connection: UsbDeviceConnection = usbManager.openDevice(device)
|
||||
?: run {
|
||||
invoke.reject("Failed to open USB device")
|
||||
return
|
||||
}
|
||||
|
||||
var claimedInterface = false
|
||||
for (i in 0 until device.interfaceCount) {
|
||||
val iface = device.getInterface(i)
|
||||
if (iface.endpointCount >= 2) {
|
||||
connection.claimInterface(iface, true)
|
||||
claimedInterface = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if (!claimedInterface) {
|
||||
invoke.reject("No usable USB interface found")
|
||||
val driver = findDriver(usbManager, deviceName)
|
||||
if (driver == null) {
|
||||
invoke.reject("USB serial driver not found: $deviceName")
|
||||
return
|
||||
}
|
||||
|
||||
val fd = connection.fileDescriptor
|
||||
val result = JSObject()
|
||||
result.put("fd", fd)
|
||||
result.put("name", device.deviceName)
|
||||
result.put("vendorId", device.vendorId)
|
||||
result.put("productId", device.productId)
|
||||
invoke.resolve(result)
|
||||
val connection = usbManager.openDevice(driver.device)
|
||||
if (connection == null) {
|
||||
invoke.reject("Failed to open USB device")
|
||||
return
|
||||
}
|
||||
|
||||
val port = driver.ports.firstOrNull()
|
||||
if (port == null) {
|
||||
connection.close()
|
||||
invoke.reject("No serial port found on USB device")
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
port.open(connection)
|
||||
port.setParameters(
|
||||
BAUD_RATE,
|
||||
UsbSerialPort.DATABITS_8,
|
||||
UsbSerialPort.STOPBITS_1,
|
||||
UsbSerialPort.PARITY_NONE
|
||||
)
|
||||
|
||||
val rustSide = FileDescriptor()
|
||||
val bridgeSide = FileDescriptor()
|
||||
Os.socketpair(OsConstants.AF_UNIX, OsConstants.SOCK_STREAM, 0, rustSide, bridgeSide)
|
||||
val rustFd = ParcelFileDescriptor.dup(rustSide).detachFd()
|
||||
Os.close(rustSide)
|
||||
|
||||
activeBridge?.close()
|
||||
activeBridge = SerialBridge(bridgeSide, port, connection).also { it.start() }
|
||||
|
||||
val result = JSObject()
|
||||
result.put("fd", rustFd)
|
||||
result.put("name", driver.device.deviceName)
|
||||
result.put("vendorId", driver.device.vendorId)
|
||||
result.put("productId", driver.device.productId)
|
||||
invoke.resolve(result)
|
||||
} catch (error: Exception) {
|
||||
try {
|
||||
port.close()
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
connection.close()
|
||||
invoke.reject(error.message ?: "Failed to open USB serial port")
|
||||
}
|
||||
}
|
||||
|
||||
private fun isUsbSerialDevice(device: UsbDevice): Boolean {
|
||||
for (i in 0 until device.interfaceCount) {
|
||||
val iface = device.getInterface(i)
|
||||
val classId = iface.interfaceClass
|
||||
if (classId == 0x02 || classId == 0xFF) {
|
||||
if (iface.endpointCount >= 2) {
|
||||
return true
|
||||
private fun findDriver(usbManager: UsbManager, deviceName: String): UsbSerialDriver? {
|
||||
return UsbSerialProber.getDefaultProber()
|
||||
.findAllDrivers(usbManager)
|
||||
.firstOrNull { it.device.deviceName == deviceName || it.device.deviceName.equals(deviceName, ignoreCase = true) }
|
||||
}
|
||||
|
||||
private fun resolveDevice(
|
||||
usbManager: UsbManager,
|
||||
deviceName: String,
|
||||
vendorId: Int?,
|
||||
productId: Int?
|
||||
): UsbDevice? {
|
||||
usbManager.deviceList[deviceName]?.let { return it }
|
||||
|
||||
val devices = usbManager.deviceList.values.toList()
|
||||
devices.firstOrNull { it.deviceName.equals(deviceName, ignoreCase = true) }?.let { return it }
|
||||
|
||||
if (vendorId != null && productId != null) {
|
||||
devices.firstOrNull { it.vendorId == vendorId && it.productId == productId }?.let { return it }
|
||||
}
|
||||
|
||||
val drivers = UsbSerialProber.getDefaultProber().findAllDrivers(usbManager)
|
||||
drivers.firstOrNull {
|
||||
it.device.deviceName == deviceName || it.device.deviceName.equals(deviceName, ignoreCase = true)
|
||||
}?.device?.let { return it }
|
||||
|
||||
if (drivers.size == 1) {
|
||||
return drivers.first().device
|
||||
}
|
||||
|
||||
if (devices.size == 1) {
|
||||
return devices.first()
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
private fun safeDeviceString(read: () -> String?): String {
|
||||
return try {
|
||||
read() ?: ""
|
||||
} catch (_: SecurityException) {
|
||||
""
|
||||
}
|
||||
}
|
||||
|
||||
private class SerialBridge(
|
||||
private val bridgeFd: FileDescriptor,
|
||||
private val port: UsbSerialPort,
|
||||
private val connection: UsbDeviceConnection
|
||||
) {
|
||||
private val running = AtomicBoolean(false)
|
||||
private lateinit var serialToRustThread: Thread
|
||||
private lateinit var rustToSerialThread: Thread
|
||||
|
||||
fun start() {
|
||||
running.set(true)
|
||||
serialToRustThread = Thread(::copySerialToRust, "JE-Skin-usb-serial-rx")
|
||||
rustToSerialThread = Thread(::copyRustToSerial, "JE-Skin-usb-serial-tx")
|
||||
serialToRustThread.start()
|
||||
rustToSerialThread.start()
|
||||
}
|
||||
|
||||
fun close() {
|
||||
if (!running.getAndSet(false)) return
|
||||
|
||||
try {
|
||||
Os.close(bridgeFd)
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
try {
|
||||
port.close()
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
connection.close()
|
||||
}
|
||||
|
||||
private fun copySerialToRust() {
|
||||
val output = FileOutputStream(bridgeFd)
|
||||
val buffer = ByteArray(4096)
|
||||
|
||||
while (running.get()) {
|
||||
try {
|
||||
val count = port.read(buffer, READ_TIMEOUT_MS)
|
||||
if (count > 0) {
|
||||
output.write(buffer, 0, count)
|
||||
output.flush()
|
||||
}
|
||||
} catch (_: IOException) {
|
||||
close()
|
||||
} catch (_: Exception) {
|
||||
close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val knownVendors = setOf(
|
||||
0x1A86, // CH340/CH341
|
||||
0x10C4, // CP210x
|
||||
0x0403, // FTDI
|
||||
0x067B, // PL2303
|
||||
0x2341, // Arduino
|
||||
0x239A, // Adafruit
|
||||
)
|
||||
if (device.vendorId in knownVendors) {
|
||||
return true
|
||||
}
|
||||
private fun copyRustToSerial() {
|
||||
val input = FileInputStream(bridgeFd)
|
||||
val buffer = ByteArray(4096)
|
||||
|
||||
return false
|
||||
while (running.get()) {
|
||||
try {
|
||||
val count = input.read(buffer)
|
||||
if (count < 0) {
|
||||
close()
|
||||
return
|
||||
}
|
||||
if (count > 0) {
|
||||
port.write(buffer.copyOf(count), WRITE_TIMEOUT_MS)
|
||||
}
|
||||
} catch (_: IOException) {
|
||||
close()
|
||||
} catch (_: Exception) {
|
||||
close()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,10 +13,10 @@ allprojects {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
maven(url = "https://jitpack.io")
|
||||
}
|
||||
}
|
||||
|
||||
tasks.register("clean").configure {
|
||||
delete("build")
|
||||
}
|
||||
|
||||
|
||||
66
src-tauri/permissions/usb-serial/default.toml
Normal file
66
src-tauri/permissions/usb-serial/default.toml
Normal file
@@ -0,0 +1,66 @@
|
||||
[default]
|
||||
description = "Allows Android USB serial plugin commands."
|
||||
permissions = [
|
||||
"allow-usb-serial-list",
|
||||
"allow-usb-serial-open",
|
||||
"allow-usb-serial-close",
|
||||
"allow-usb-serial-list-camel",
|
||||
"allow-usb-serial-open-camel",
|
||||
"allow-usb-serial-close-camel",
|
||||
"allow-local-commands"
|
||||
]
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-usb-serial-list"
|
||||
description = "Allows listing Android USB serial devices."
|
||||
commands.allow = ["plugin:usb-serial|usb_serial_list"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-usb-serial-open"
|
||||
description = "Allows opening Android USB serial devices."
|
||||
commands.allow = ["plugin:usb-serial|usb_serial_open"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-usb-serial-close"
|
||||
description = "Allows closing Android USB serial devices."
|
||||
commands.allow = ["plugin:usb-serial|usb_serial_close"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-usb-serial-list-camel"
|
||||
description = "Allows listing Android USB serial devices via camelCase command."
|
||||
commands.allow = ["plugin:usb-serial|usbSerialList"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-usb-serial-open-camel"
|
||||
description = "Allows opening Android USB serial devices via camelCase command."
|
||||
commands.allow = ["plugin:usb-serial|usbSerialOpen"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-usb-serial-close-camel"
|
||||
description = "Allows closing Android USB serial devices via camelCase command."
|
||||
commands.allow = ["plugin:usb-serial|usbSerialClose"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-local-commands"
|
||||
description = "Allows application commands used by the Android frontend."
|
||||
commands.allow = [
|
||||
"file_explorer_list",
|
||||
"serial_enum",
|
||||
"serial_connect",
|
||||
"serial_connect_fd",
|
||||
"serial_disconnect",
|
||||
"serial_export_csv",
|
||||
"serial_has_record_data",
|
||||
"serial_export_csv_to_path",
|
||||
"serial_import_csv",
|
||||
"serial_import_csv_from_path",
|
||||
"win_minimize",
|
||||
"win_toggle_maximize",
|
||||
"win_close",
|
||||
"devkit_status",
|
||||
"devkit_start",
|
||||
"devkit_stop",
|
||||
"devkit_get_config",
|
||||
"devkit_set_config",
|
||||
"devkit_process_export"
|
||||
]
|
||||
@@ -13,6 +13,7 @@ use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
use tauri::{async_runtime::JoinHandle, AppHandle, Manager, State};
|
||||
#[cfg(not(target_os = "android"))]
|
||||
use tokio_serial::{available_ports, SerialPortBuilderExt};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
@@ -113,22 +114,31 @@ pub async fn shutdown_active_session(
|
||||
|
||||
#[tauri::command]
|
||||
pub fn serial_enum() -> Result<Vec<String>, SerialError> {
|
||||
let ports = available_ports()
|
||||
.map_err(|_| SerialError::ScanError)?
|
||||
.into_iter()
|
||||
.filter_map(|p| {
|
||||
let name = p.port_name;
|
||||
#[cfg(unix)]
|
||||
if !name.contains("USB") {
|
||||
return None;
|
||||
}
|
||||
Some(name)
|
||||
})
|
||||
.collect();
|
||||
#[cfg(target_os = "android")]
|
||||
{
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
Ok(ports)
|
||||
#[cfg(not(target_os = "android"))]
|
||||
{
|
||||
let ports = available_ports()
|
||||
.map_err(|_| SerialError::ScanError)?
|
||||
.into_iter()
|
||||
.filter_map(|p| {
|
||||
let name = p.port_name;
|
||||
#[cfg(unix)]
|
||||
if !name.contains("USB") {
|
||||
return None;
|
||||
}
|
||||
Some(name)
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(ports)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "android"))]
|
||||
#[tauri::command]
|
||||
pub async fn serial_connect(
|
||||
app: AppHandle,
|
||||
|
||||
@@ -10,6 +10,16 @@ use commands::serial::SerialConnectionState;
|
||||
#[cfg(feature = "devkit")]
|
||||
use tauri::Manager;
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
fn usb_serial_plugin<R: tauri::Runtime>() -> tauri::plugin::TauriPlugin<R> {
|
||||
tauri::plugin::Builder::new("usb-serial")
|
||||
.setup(|_app, api| {
|
||||
api.register_android_plugin("com.lenn.tauri_serial", "UsbSerialPlugin")?;
|
||||
Ok(())
|
||||
})
|
||||
.build()
|
||||
}
|
||||
|
||||
#[cfg(feature = "devkit")]
|
||||
fn start_server_exe(exe_path: &std::path::Path) {
|
||||
let mut command = std::process::Command::new(exe_path);
|
||||
@@ -66,6 +76,9 @@ pub fn run() {
|
||||
.manage(SerialConnectionState::default())
|
||||
.plugin(tauri_plugin_opener::init());
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
let builder = builder.plugin(usb_serial_plugin());
|
||||
|
||||
#[cfg(not(any(target_os = "android", target_os = "ios")))]
|
||||
let builder = builder.plugin(tauri_plugin_updater::Builder::new().build());
|
||||
|
||||
@@ -177,7 +190,6 @@ pub fn run() {
|
||||
let builder = builder.invoke_handler(tauri::generate_handler![
|
||||
commands::file_explorer::file_explorer_list,
|
||||
commands::serial::serial_enum,
|
||||
commands::serial::serial_connect,
|
||||
commands::serial::serial_connect_fd,
|
||||
commands::serial::serial_disconnect,
|
||||
commands::serial::serial_export_csv,
|
||||
@@ -200,7 +212,6 @@ pub fn run() {
|
||||
let builder = builder.invoke_handler(tauri::generate_handler![
|
||||
commands::file_explorer::file_explorer_list,
|
||||
commands::serial::serial_enum,
|
||||
commands::serial::serial_connect,
|
||||
commands::serial::serial_connect_fd,
|
||||
commands::serial::serial_disconnect,
|
||||
commands::serial::serial_export_csv,
|
||||
|
||||
@@ -34,8 +34,9 @@ impl RawFdStream {
|
||||
|
||||
impl Drop for RawFdStream {
|
||||
fn drop(&mut self) {
|
||||
// We don't close the fd here - it's managed by the UsbDeviceConnection in Kotlin.
|
||||
// The Kotlin side is responsible for closing.
|
||||
unsafe {
|
||||
libc::close(*self.inner.get_ref());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -460,6 +460,12 @@
|
||||
color: rgb(var(--hud-orange-rgb) / 0.96);
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.window-controls {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
.control-bar {
|
||||
display: grid;
|
||||
gap: 0.45rem;
|
||||
|
||||
@@ -461,6 +461,28 @@
|
||||
const heightField = new Float32Array(instanceCount);
|
||||
const compactField = new Uint16Array(instanceCount);
|
||||
let lastFrameAt = performance.now();
|
||||
let lastStatsCurrent: number | null = null;
|
||||
let lastStatsMax: number | null = null;
|
||||
let lastStatsMin: number | null = null;
|
||||
|
||||
const syncStats = () => {
|
||||
const nextCurrent = summary?.latest ?? null;
|
||||
const nextMax = summary?.max ?? null;
|
||||
const nextMin = summary?.min ?? null;
|
||||
|
||||
if (nextCurrent === lastStatsCurrent && nextMax === lastStatsMax && nextMin === lastStatsMin) {
|
||||
return;
|
||||
}
|
||||
|
||||
lastStatsCurrent = nextCurrent;
|
||||
lastStatsMax = nextMax;
|
||||
lastStatsMin = nextMin;
|
||||
stats = {
|
||||
current: nextCurrent,
|
||||
max: nextMax,
|
||||
min: nextMin
|
||||
};
|
||||
};
|
||||
|
||||
const drawOverlay = () => {
|
||||
if (!viewerEl || !overlayEl) {
|
||||
@@ -623,12 +645,7 @@
|
||||
|
||||
renderer.render(scene, camera);
|
||||
drawOverlay();
|
||||
|
||||
stats = {
|
||||
current: summary?.latest ?? null,
|
||||
max: summary?.max ?? null,
|
||||
min: summary?.min ?? null
|
||||
};
|
||||
syncStats();
|
||||
});
|
||||
|
||||
return () => {
|
||||
|
||||
@@ -182,8 +182,7 @@
|
||||
transition:
|
||||
opacity var(--fade-ms) cubic-bezier(0.18, 0.88, 0.3, 1),
|
||||
transform var(--enter-ms) cubic-bezier(0.2, 0.9, 0.28, 1),
|
||||
border-color 460ms ease,
|
||||
filter 760ms ease;
|
||||
border-color 460ms ease;
|
||||
transition-delay: calc(var(--panel-index) * 140ms);
|
||||
}
|
||||
|
||||
@@ -200,7 +199,6 @@
|
||||
border-color: transparent;
|
||||
opacity: 0;
|
||||
transform: translateX(var(--offset-x)) scale(0.98) rotate(-0.6deg);
|
||||
filter: blur(1.3px);
|
||||
pointer-events: none;
|
||||
transition-delay: 0ms;
|
||||
}
|
||||
@@ -301,7 +299,6 @@
|
||||
stroke-width: 1.3;
|
||||
stroke-linecap: round;
|
||||
stroke-linejoin: round;
|
||||
filter: drop-shadow(0 0 2px rgb(0 0 0 / 0.42));
|
||||
}
|
||||
|
||||
.series-line.tone-cyan {
|
||||
@@ -397,6 +394,10 @@
|
||||
aspect-ratio: 1.5 / 1;
|
||||
min-block-size: 10.1rem;
|
||||
}
|
||||
|
||||
.chart-stage {
|
||||
block-size: clamp(5.7rem, 7.6vw, 6.9rem);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-height: 900px) {
|
||||
@@ -452,6 +453,17 @@
|
||||
inline-size: 100%;
|
||||
aspect-ratio: 1.7 / 1;
|
||||
min-block-size: 0;
|
||||
background: linear-gradient(160deg, rgb(var(--hud-surface-alt-rgb) / 0.86) 0%, rgb(var(--hud-surface-deep-rgb) / 0.9) 100%);
|
||||
box-shadow: inset 0 0 0 1px rgb(var(--hud-border-strong-rgb) / 0.08), 0 0 8px rgb(var(--hud-glow-rgb) / 0.1);
|
||||
}
|
||||
|
||||
.scan-haze {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.chart-stage {
|
||||
background: linear-gradient(180deg, rgb(var(--hud-surface-alt-rgb) / 0.78), rgb(var(--hud-surface-deep-rgb) / 0.88));
|
||||
box-shadow: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -11,22 +11,6 @@
|
||||
export let sessionStartedAt: number = Date.now();
|
||||
export let isRealtime = false;
|
||||
|
||||
let currentTimeSeconds = 0;
|
||||
let timerId: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
onMount(() => {
|
||||
timerId = setInterval(() => {
|
||||
currentTimeSeconds = Math.round((Date.now() - sessionStartedAt) / 100) / 10;
|
||||
}, 200);
|
||||
return () => {
|
||||
if (timerId != null) clearInterval(timerId);
|
||||
};
|
||||
});
|
||||
|
||||
$: i18n = locale === "zh-CN"
|
||||
? { now: "当前", min: "最小", max: "最大", waiting: "等待数据" }
|
||||
: { now: "Now", min: "Min", max: "Max", waiting: "Waiting" };
|
||||
|
||||
const viewportWidth = 120;
|
||||
const viewportHeight = 48;
|
||||
const plotInsetLeft = 13;
|
||||
@@ -34,6 +18,8 @@
|
||||
const plotInsetTop = 4;
|
||||
const plotInsetBottom = 9;
|
||||
const fixedYBounds = { min: 0, max: 25 };
|
||||
const maxCanvasDpr = 1.5;
|
||||
const minDrawIntervalMs = 66;
|
||||
|
||||
interface CurveSample {
|
||||
x: number;
|
||||
@@ -45,23 +31,25 @@
|
||||
y: number;
|
||||
}
|
||||
|
||||
interface AxisTick {
|
||||
value: number;
|
||||
label: string;
|
||||
plotX: number;
|
||||
plotY: number;
|
||||
}
|
||||
let canvasEl: HTMLCanvasElement | undefined;
|
||||
let chartStageEl: HTMLDivElement | undefined;
|
||||
let currentTimeSeconds = 0;
|
||||
let timerId: ReturnType<typeof setInterval> | null = null;
|
||||
let resizeObserver: ResizeObserver | null = null;
|
||||
let drawRequestId: number | null = null;
|
||||
let lastDrawAt = 0;
|
||||
let mounted = false;
|
||||
|
||||
$: i18n = locale === "zh-CN"
|
||||
? { now: "当前", min: "最小", max: "最大", waiting: "等待数据" }
|
||||
: { now: "Now", min: "Min", max: "Max", waiting: "Waiting" };
|
||||
|
||||
function clamp(value: number, min: number, max: number): number {
|
||||
return Math.min(max, Math.max(min, value));
|
||||
}
|
||||
|
||||
function formatValue(value: number | null): string {
|
||||
if (value === null) {
|
||||
return "--";
|
||||
}
|
||||
|
||||
return value.toFixed(1);
|
||||
return value === null ? "--" : value.toFixed(1);
|
||||
}
|
||||
|
||||
function formatAxisValue(value: number, axis: "x" | "y"): string {
|
||||
@@ -73,6 +61,7 @@
|
||||
if (value < 60) {
|
||||
return `${value.toFixed(1)}s`;
|
||||
}
|
||||
|
||||
const mins = Math.floor(value / 60);
|
||||
const secs = value - mins * 60;
|
||||
return `${mins}:${secs.toFixed(0).padStart(2, "0")}`;
|
||||
@@ -81,17 +70,6 @@
|
||||
return `${Math.round(value)} N`;
|
||||
}
|
||||
|
||||
function resolveDataBounds(values: number[]): { min: number; max: number } {
|
||||
if (values.length === 0) {
|
||||
return { min: 0, max: 1 };
|
||||
}
|
||||
|
||||
return {
|
||||
min: Math.min(...values),
|
||||
max: Math.max(...values)
|
||||
};
|
||||
}
|
||||
|
||||
function resolveBounds(values: number[]): { min: number; max: number } {
|
||||
if (values.length === 0) {
|
||||
return { min: 0, max: 1 };
|
||||
@@ -108,34 +86,23 @@
|
||||
return { min, max };
|
||||
}
|
||||
|
||||
function mapXToViewport(value: number, bounds: { min: number; max: number }): number {
|
||||
const span = bounds.max - bounds.min;
|
||||
const chartWidth = viewportWidth - plotInsetLeft - plotInsetRight;
|
||||
const ratio = span <= 0 ? 0.5 : (value - bounds.min) / span;
|
||||
const mappedX = plotInsetLeft + ratio * chartWidth;
|
||||
return Math.round(clamp(mappedX, plotInsetLeft, viewportWidth - plotInsetRight) * 100) / 100;
|
||||
}
|
||||
|
||||
function mapYToViewport(value: number, bounds: { min: number; max: number }): number {
|
||||
const span = bounds.max - bounds.min;
|
||||
const chartHeight = viewportHeight - plotInsetTop - plotInsetBottom;
|
||||
const ratio = span <= 0 ? 0.5 : (value - bounds.min) / span;
|
||||
const mappedY = viewportHeight - plotInsetBottom - ratio * chartHeight;
|
||||
return Math.round(clamp(mappedY, plotInsetTop, viewportHeight - plotInsetBottom) * 100) / 100;
|
||||
}
|
||||
|
||||
function buildSamples(rawYValues: number[], rawXValues: number[]): CurveSample[] {
|
||||
function buildSamples(rawYValues: number[], rawXValues: number[], currentSeconds: number): CurveSample[] {
|
||||
if (!rawYValues.length) {
|
||||
return [];
|
||||
}
|
||||
|
||||
let previousX = 0;
|
||||
const hasUsableXValues = rawXValues.length === rawYValues.length;
|
||||
const realtimeSpacing = isRealtime
|
||||
? Math.max(currentSeconds / Math.max(rawYValues.length - 1, 1), 0.1)
|
||||
: 1;
|
||||
const realtimeStart = isRealtime ? Math.max(0, currentSeconds - realtimeSpacing * (rawYValues.length - 1)) : 0;
|
||||
let previousX = realtimeStart;
|
||||
|
||||
return rawYValues.map((rawY, index) => {
|
||||
const x = rawXValues[index];
|
||||
const y = Number.isFinite(rawY) ? Number(rawY) : 0;
|
||||
const fallbackX = index === 0 ? 0 : previousX + 1;
|
||||
const resolvedX = Number.isFinite(x) ? Number(x) : fallbackX;
|
||||
const rawX = rawXValues[index];
|
||||
const fallbackX = isRealtime ? realtimeStart + index * realtimeSpacing : index + 1;
|
||||
const resolvedX = hasUsableXValues && Number.isFinite(rawX) ? Number(rawX) : fallbackX;
|
||||
const normalizedX = index === 0 ? resolvedX : Math.max(resolvedX, previousX);
|
||||
previousX = normalizedX;
|
||||
return { x: normalizedX, y };
|
||||
@@ -143,132 +110,274 @@
|
||||
}
|
||||
|
||||
function resolveXScaleBounds(
|
||||
samples: CurveSample[],
|
||||
samplesValue: CurveSample[],
|
||||
currentSeconds: number,
|
||||
realtime: boolean
|
||||
): { min: number; max: number } {
|
||||
if (samples.length === 0) {
|
||||
if (samplesValue.length === 0) {
|
||||
return { min: 0, max: 1 };
|
||||
}
|
||||
|
||||
const values = samples.map((sample) => sample.x);
|
||||
const dataBounds = resolveBounds(values);
|
||||
|
||||
if (!realtime) {
|
||||
return dataBounds;
|
||||
return resolveBounds(samplesValue.map((sample) => sample.x));
|
||||
}
|
||||
|
||||
const firstX = samples[0].x;
|
||||
const lastX = samples[samples.length - 1].x;
|
||||
const firstX = samplesValue[0].x;
|
||||
const lastX = samplesValue[samplesValue.length - 1].x;
|
||||
const axisMax = Math.max(lastX, currentSeconds);
|
||||
const positiveDiffs = samples
|
||||
.slice(1)
|
||||
.map((sample, index) => sample.x - samples[index].x)
|
||||
.filter((diff) => diff > 0);
|
||||
const averageSpacing =
|
||||
positiveDiffs.length > 0 ? positiveDiffs.reduce((sum, diff) => sum + diff, 0) / positiveDiffs.length : 1;
|
||||
const dataSpan = Math.max(lastX - firstX, 0);
|
||||
const windowSpan = Math.max(dataSpan, averageSpacing * Math.max(samples.length - 1, 1), 1);
|
||||
const axisMin = Math.max(0, axisMax - windowSpan);
|
||||
|
||||
const dataSpan = Math.max(lastX - firstX, 1);
|
||||
const axisMin = Math.max(0, axisMax - dataSpan);
|
||||
return resolveBounds([axisMin, axisMax]);
|
||||
}
|
||||
|
||||
function mapXToViewport(value: number, bounds: { min: number; max: number }): number {
|
||||
const span = bounds.max - bounds.min;
|
||||
const chartWidth = viewportWidth - plotInsetLeft - plotInsetRight;
|
||||
const ratio = span <= 0 ? 0.5 : (value - bounds.min) / span;
|
||||
return clamp(plotInsetLeft + ratio * chartWidth, plotInsetLeft, viewportWidth - plotInsetRight);
|
||||
}
|
||||
|
||||
function mapYToViewport(value: number, bounds: { min: number; max: number }): number {
|
||||
const span = bounds.max - bounds.min;
|
||||
const chartHeight = viewportHeight - plotInsetTop - plotInsetBottom;
|
||||
const ratio = span <= 0 ? 0.5 : (value - bounds.min) / span;
|
||||
return clamp(viewportHeight - plotInsetBottom - ratio * chartHeight, plotInsetTop, viewportHeight - plotInsetBottom);
|
||||
}
|
||||
|
||||
function convertPoints(
|
||||
samples: CurveSample[],
|
||||
samplesValue: CurveSample[],
|
||||
xBounds: { min: number; max: number },
|
||||
yBounds: { min: number; max: number }
|
||||
): PlotPoint[] {
|
||||
if (samples.length === 0) {
|
||||
if (samplesValue.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (samples.length === 1) {
|
||||
if (samplesValue.length === 1) {
|
||||
return [{ x: viewportWidth / 2, y: viewportHeight / 2 }];
|
||||
}
|
||||
|
||||
return samples.map((sample) => {
|
||||
return {
|
||||
x: mapXToViewport(sample.x, xBounds),
|
||||
y: mapYToViewport(sample.y, yBounds)
|
||||
};
|
||||
});
|
||||
return samplesValue.map((sample) => ({
|
||||
x: mapXToViewport(sample.x, xBounds),
|
||||
y: mapYToViewport(sample.y, yBounds)
|
||||
}));
|
||||
}
|
||||
|
||||
function buildYAxisTicks(
|
||||
yScaleBounds: { min: number; max: number },
|
||||
_yDataBounds: { min: number; max: number }
|
||||
): AxisTick[] {
|
||||
function scaleCanvas(context: CanvasRenderingContext2D): { width: number; height: number; dpr: number } | null {
|
||||
if (!canvasEl || !chartStageEl) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const width = chartStageEl.clientWidth;
|
||||
const height = chartStageEl.clientHeight;
|
||||
const dpr = Math.min(window.devicePixelRatio || 1, maxCanvasDpr);
|
||||
|
||||
if (width <= 0 || height <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const nextWidth = Math.round(width * dpr);
|
||||
const nextHeight = Math.round(height * dpr);
|
||||
if (canvasEl.width !== nextWidth || canvasEl.height !== nextHeight) {
|
||||
canvasEl.width = nextWidth;
|
||||
canvasEl.height = nextHeight;
|
||||
canvasEl.style.width = `${width}px`;
|
||||
canvasEl.style.height = `${height}px`;
|
||||
}
|
||||
|
||||
context.setTransform((width * dpr) / viewportWidth, 0, 0, (height * dpr) / viewportHeight, 0, 0);
|
||||
return { width, height, dpr };
|
||||
}
|
||||
|
||||
function drawGrid(context: CanvasRenderingContext2D, yBounds: { min: number; max: number }): void {
|
||||
const tickValues = [25, 20, 15, 10, 5, 0];
|
||||
return tickValues.map((value) => ({
|
||||
value,
|
||||
label: formatAxisValue(value, "y"),
|
||||
plotX: plotInsetLeft - 1.8,
|
||||
plotY: mapYToViewport(value, yScaleBounds)
|
||||
}));
|
||||
}
|
||||
|
||||
function buildXAxisTicks(xScaleBounds: { min: number; max: number }): AxisTick[] {
|
||||
if (!Number.isFinite(xScaleBounds.min) || !Number.isFinite(xScaleBounds.max)) {
|
||||
return [];
|
||||
context.save();
|
||||
context.lineWidth = 0.45;
|
||||
context.strokeStyle = "rgb(128 170 180 / 0.18)";
|
||||
context.fillStyle = "rgb(190 216 220 / 0.78)";
|
||||
context.font = "600 3.2px system-ui, sans-serif";
|
||||
context.textBaseline = "middle";
|
||||
|
||||
for (const tick of tickValues) {
|
||||
const y = mapYToViewport(tick, yBounds);
|
||||
context.beginPath();
|
||||
context.moveTo(plotInsetLeft, y);
|
||||
context.lineTo(viewportWidth - plotInsetRight, y);
|
||||
context.stroke();
|
||||
|
||||
context.textAlign = "right";
|
||||
context.fillText(formatAxisValue(tick, "y"), plotInsetLeft - 1.8, y + 0.6);
|
||||
}
|
||||
|
||||
const first = xScaleBounds.min;
|
||||
const middle = xScaleBounds.min + (xScaleBounds.max - xScaleBounds.min) / 2;
|
||||
const last = xScaleBounds.max;
|
||||
const tickValues = [first, middle, last];
|
||||
return tickValues.map((value) => ({
|
||||
value,
|
||||
label: formatAxisValue(value, "x"),
|
||||
plotX: mapXToViewport(value, xScaleBounds),
|
||||
plotY: viewportHeight - 0.9
|
||||
}));
|
||||
context.restore();
|
||||
}
|
||||
|
||||
function createLinePath(points: PlotPoint[]): string {
|
||||
if (points.length === 0) {
|
||||
return "";
|
||||
}
|
||||
function drawXAxis(context: CanvasRenderingContext2D, xBounds: { min: number; max: number }): void {
|
||||
const first = xBounds.min;
|
||||
const middle = xBounds.min + (xBounds.max - xBounds.min) / 2;
|
||||
const last = xBounds.max;
|
||||
const ticks = [first, middle, last];
|
||||
|
||||
return points.map((point, index) => `${index === 0 ? "M" : "L"} ${point.x} ${point.y}`).join(" ");
|
||||
context.save();
|
||||
context.fillStyle = "rgb(190 216 220 / 0.82)";
|
||||
context.font = "600 3.2px system-ui, sans-serif";
|
||||
context.textBaseline = "alphabetic";
|
||||
|
||||
ticks.forEach((tick, index) => {
|
||||
const x = mapXToViewport(tick, xBounds);
|
||||
context.textAlign = index === 0 ? "left" : index === ticks.length - 1 ? "right" : "center";
|
||||
context.fillText(formatAxisValue(tick, "x"), x, viewportHeight - 0.9);
|
||||
});
|
||||
|
||||
context.restore();
|
||||
}
|
||||
|
||||
function createAreaPath(points: PlotPoint[]): string {
|
||||
function drawArea(context: CanvasRenderingContext2D, points: PlotPoint[]): void {
|
||||
if (points.length < 2) {
|
||||
return "";
|
||||
return;
|
||||
}
|
||||
|
||||
const linePath = createLinePath(points);
|
||||
const firstPoint = points[0];
|
||||
const lastPoint = points[points.length - 1];
|
||||
const gradient = context.createLinearGradient(0, plotInsetTop, 0, viewportHeight - plotInsetBottom);
|
||||
gradient.addColorStop(0, "rgb(62 232 255 / 0.28)");
|
||||
gradient.addColorStop(1, "rgb(62 232 255 / 0.02)");
|
||||
|
||||
return `${linePath} L ${lastPoint.x} ${viewportHeight - plotInsetBottom} L ${firstPoint.x} ${viewportHeight - plotInsetBottom} Z`;
|
||||
context.save();
|
||||
context.beginPath();
|
||||
context.moveTo(firstPoint.x, firstPoint.y);
|
||||
for (let index = 1; index < points.length; index += 1) {
|
||||
context.lineTo(points[index].x, points[index].y);
|
||||
}
|
||||
context.lineTo(lastPoint.x, viewportHeight - plotInsetBottom);
|
||||
context.lineTo(firstPoint.x, viewportHeight - plotInsetBottom);
|
||||
context.closePath();
|
||||
context.fillStyle = gradient;
|
||||
context.fill();
|
||||
context.restore();
|
||||
}
|
||||
|
||||
function drawLine(context: CanvasRenderingContext2D, points: PlotPoint[]): void {
|
||||
if (!points.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
context.save();
|
||||
context.lineWidth = 1.35;
|
||||
context.lineCap = "round";
|
||||
context.lineJoin = "round";
|
||||
context.strokeStyle = "rgb(62 232 255 / 0.96)";
|
||||
context.beginPath();
|
||||
context.moveTo(points[0].x, points[0].y);
|
||||
for (let index = 1; index < points.length; index += 1) {
|
||||
context.lineTo(points[index].x, points[index].y);
|
||||
}
|
||||
context.stroke();
|
||||
|
||||
const lastPoint = points[points.length - 1];
|
||||
context.fillStyle = "rgb(133 255 68 / 0.98)";
|
||||
context.beginPath();
|
||||
context.arc(lastPoint.x, lastPoint.y, 1.7, 0, Math.PI * 2);
|
||||
context.fill();
|
||||
context.restore();
|
||||
}
|
||||
|
||||
function drawCanvas(): void {
|
||||
if (!canvasEl) {
|
||||
return;
|
||||
}
|
||||
|
||||
const context = canvasEl.getContext("2d", { alpha: true });
|
||||
if (!context) {
|
||||
return;
|
||||
}
|
||||
|
||||
const scaled = scaleCanvas(context);
|
||||
if (!scaled) {
|
||||
return;
|
||||
}
|
||||
|
||||
context.clearRect(0, 0, viewportWidth, viewportHeight);
|
||||
|
||||
if (sampleCount === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
drawGrid(context, yScaleBounds);
|
||||
drawArea(context, plotPoints);
|
||||
drawLine(context, plotPoints);
|
||||
drawXAxis(context, xScaleBounds);
|
||||
}
|
||||
|
||||
function scheduleDraw(): void {
|
||||
if (!mounted || typeof window === "undefined") {
|
||||
return;
|
||||
}
|
||||
|
||||
if (drawRequestId != null) {
|
||||
return;
|
||||
}
|
||||
|
||||
drawRequestId = window.requestAnimationFrame((timestamp) => {
|
||||
drawRequestId = null;
|
||||
|
||||
if (lastDrawAt > 0 && timestamp - lastDrawAt < minDrawIntervalMs) {
|
||||
scheduleDraw();
|
||||
return;
|
||||
}
|
||||
|
||||
lastDrawAt = timestamp;
|
||||
drawCanvas();
|
||||
});
|
||||
}
|
||||
|
||||
$: sourceYValues = yValues && yValues.length ? yValues : summary.points;
|
||||
$: sourceXValues = xValues && xValues.length ? xValues : summary.xValues ?? [];
|
||||
$: samples = (() => {
|
||||
const base = buildSamples(sourceYValues, sourceXValues);
|
||||
if (isRealtime && base.length > 0 && currentTimeSeconds > 0) {
|
||||
const lastSample = base[base.length - 1];
|
||||
base[base.length - 1] = { ...lastSample, x: Math.max(lastSample.x, currentTimeSeconds) };
|
||||
}
|
||||
return base;
|
||||
})();
|
||||
$: samples = buildSamples(sourceYValues, sourceXValues, currentTimeSeconds);
|
||||
$: sampleCount = samples.length;
|
||||
$: xScaleBounds = resolveXScaleBounds(samples, currentTimeSeconds, isRealtime);
|
||||
$: yScaleBounds = fixedYBounds;
|
||||
$: xDataBounds = resolveDataBounds(samples.map((sample) => sample.x));
|
||||
$: yDataBounds = resolveDataBounds(samples.map((sample) => sample.y));
|
||||
$: plotPoints = convertPoints(samples, xScaleBounds, yScaleBounds);
|
||||
$: linePath = createLinePath(plotPoints);
|
||||
$: areaPath = createAreaPath(plotPoints);
|
||||
$: lastPoint = plotPoints.length > 0 ? plotPoints[plotPoints.length - 1] : null;
|
||||
$: yAxisTicks = sampleCount > 0 ? buildYAxisTicks(yScaleBounds, yDataBounds) : [];
|
||||
$: xAxisTicks = sampleCount > 0 ? buildXAxisTicks(xScaleBounds) : [];
|
||||
$: latestValue = formatValue(summary.latest);
|
||||
$: minValue = formatValue(summary.min);
|
||||
$: maxValue = formatValue(summary.max);
|
||||
$: {
|
||||
sampleCount;
|
||||
plotPoints;
|
||||
xScaleBounds;
|
||||
locale;
|
||||
scheduleDraw();
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
mounted = true;
|
||||
currentTimeSeconds = Math.round((Date.now() - sessionStartedAt) / 100) / 10;
|
||||
scheduleDraw();
|
||||
|
||||
timerId = setInterval(() => {
|
||||
if (!isRealtime) {
|
||||
return;
|
||||
}
|
||||
|
||||
currentTimeSeconds = Math.round((Date.now() - sessionStartedAt) / 100) / 10;
|
||||
}, 500);
|
||||
|
||||
if (chartStageEl) {
|
||||
resizeObserver = new ResizeObserver(() => scheduleDraw());
|
||||
resizeObserver.observe(chartStageEl);
|
||||
}
|
||||
|
||||
return () => {
|
||||
mounted = false;
|
||||
if (timerId != null) clearInterval(timerId);
|
||||
if (drawRequestId != null) window.cancelAnimationFrame(drawRequestId);
|
||||
resizeObserver?.disconnect();
|
||||
timerId = null;
|
||||
drawRequestId = null;
|
||||
resizeObserver = null;
|
||||
};
|
||||
});
|
||||
</script>
|
||||
|
||||
<article
|
||||
@@ -290,52 +399,8 @@
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="chart-stage">
|
||||
<svg viewBox="0 0 {viewportWidth} {viewportHeight}" preserveAspectRatio="none" role="img" aria-label={summary.label}>
|
||||
<defs>
|
||||
<linearGradient id="summary-fill" x1="0%" y1="0%" x2="0%" y2="100%">
|
||||
<stop offset="0%" stop-color="rgb(62 232 255 / 0.28)" />
|
||||
<stop offset="100%" stop-color="rgb(62 232 255 / 0.02)" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
|
||||
<g class="grid-lines" aria-hidden="true">
|
||||
{#each yAxisTicks as tick (`grid-${tick.value}`)}
|
||||
<line x1={plotInsetLeft} y1={tick.plotY} x2={viewportWidth - plotInsetRight} y2={tick.plotY}></line>
|
||||
{/each}
|
||||
</g>
|
||||
|
||||
{#if areaPath}
|
||||
<path d={areaPath} class="summary-area"></path>
|
||||
{/if}
|
||||
|
||||
{#if linePath}
|
||||
<path d={linePath} class="summary-line"></path>
|
||||
{/if}
|
||||
|
||||
{#if lastPoint}
|
||||
<circle cx={lastPoint.x} cy={lastPoint.y} r="1.7" class="summary-dot"></circle>
|
||||
{/if}
|
||||
|
||||
<g class="axis-labels" aria-hidden="true">
|
||||
{#each yAxisTicks as tick, index (`y-${index}`)}
|
||||
<text class="axis-label y-axis-label" x={tick.plotX} y={tick.plotY + 1.1} text-anchor="end">
|
||||
{tick.label}
|
||||
</text>
|
||||
{/each}
|
||||
|
||||
{#each xAxisTicks as tick, index (`x-${index}`)}
|
||||
<text
|
||||
class="axis-label x-axis-label"
|
||||
x={tick.plotX}
|
||||
y={tick.plotY}
|
||||
text-anchor={index === 0 ? "start" : index === xAxisTicks.length - 1 ? "end" : "middle"}
|
||||
>
|
||||
{tick.label}
|
||||
</text>
|
||||
{/each}
|
||||
</g>
|
||||
</svg>
|
||||
<div class="chart-stage" bind:this={chartStageEl}>
|
||||
<canvas class="summary-canvas" bind:this={canvasEl} aria-label={summary.label}></canvas>
|
||||
|
||||
{#if sampleCount === 0}
|
||||
<div class="empty-state">
|
||||
@@ -389,8 +454,7 @@
|
||||
transition:
|
||||
opacity var(--fade-ms) cubic-bezier(0.18, 0.88, 0.3, 1),
|
||||
transform var(--enter-ms) cubic-bezier(0.2, 0.9, 0.28, 1),
|
||||
border-color 460ms ease,
|
||||
filter 760ms ease;
|
||||
border-color 460ms ease;
|
||||
transition-delay: calc(var(--panel-index) * 140ms);
|
||||
}
|
||||
|
||||
@@ -480,53 +544,12 @@
|
||||
radial-gradient(circle at 50% 0, rgb(var(--hud-glow-rgb) / 0.09), transparent 45%);
|
||||
}
|
||||
|
||||
svg {
|
||||
.summary-canvas {
|
||||
display: block;
|
||||
inline-size: 100%;
|
||||
block-size: 100%;
|
||||
}
|
||||
|
||||
.grid-lines line {
|
||||
stroke: rgb(var(--hud-border-strong-rgb) / 0.16);
|
||||
stroke-width: 0.45;
|
||||
}
|
||||
|
||||
.summary-area {
|
||||
fill: url(#summary-fill);
|
||||
}
|
||||
|
||||
.summary-line {
|
||||
fill: none;
|
||||
stroke: rgb(var(--hud-cyan-rgb) / 0.96);
|
||||
stroke-width: 1.35;
|
||||
stroke-linecap: round;
|
||||
stroke-linejoin: round;
|
||||
filter: drop-shadow(0 0 4px rgb(var(--hud-cyan-rgb) / 0.22));
|
||||
}
|
||||
|
||||
.summary-dot {
|
||||
fill: rgb(var(--hud-lime-rgb) / 0.98);
|
||||
filter: drop-shadow(0 0 6px rgb(var(--hud-lime-rgb) / 0.3));
|
||||
}
|
||||
|
||||
.axis-label {
|
||||
fill: rgb(var(--hud-text-main-rgb) / 0.88);
|
||||
font-size: 3.2px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.02em;
|
||||
text-shadow:
|
||||
0 1px 0 rgb(0 0 0 / 0.46),
|
||||
0 0 4px rgb(0 0 0 / 0.3);
|
||||
}
|
||||
|
||||
.y-axis-label {
|
||||
fill: rgb(var(--hud-text-dim-rgb) / 0.84);
|
||||
}
|
||||
|
||||
.x-axis-label {
|
||||
fill: rgb(var(--hud-text-dim-rgb) / 0.9);
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
@@ -637,6 +660,12 @@
|
||||
@media (max-width: 900px) {
|
||||
.signal-panel {
|
||||
inline-size: 100%;
|
||||
background: linear-gradient(160deg, rgb(var(--hud-surface-alt-rgb) / 0.86) 0%, rgb(var(--hud-surface-deep-rgb) / 0.9) 100%);
|
||||
box-shadow: inset 0 0 0 1px rgb(var(--hud-border-strong-rgb) / 0.08), 0 0 8px rgb(var(--hud-glow-rgb) / 0.1);
|
||||
}
|
||||
|
||||
.chart-stage {
|
||||
background: linear-gradient(180deg, rgb(var(--hud-surface-alt-rgb) / 0.78), rgb(var(--hud-surface-deep-rgb) / 0.88));
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -44,6 +44,29 @@
|
||||
dtsMs: number;
|
||||
}
|
||||
|
||||
interface AndroidUsbSerialDevice {
|
||||
name: string;
|
||||
vendorId: number;
|
||||
productId: number;
|
||||
manufacturer: string;
|
||||
product: string;
|
||||
serial: string;
|
||||
hasPermission: boolean;
|
||||
}
|
||||
|
||||
interface AndroidUsbSerialListResult {
|
||||
devices: AndroidUsbSerialDevice[];
|
||||
}
|
||||
|
||||
interface AndroidUsbSerialOpenResult {
|
||||
fd: number;
|
||||
name: string;
|
||||
vendorId: number;
|
||||
productId: number;
|
||||
}
|
||||
|
||||
type AndroidUsbSerialCommand = "list" | "open" | "close";
|
||||
|
||||
const copyByLocale: Record<LocaleCode, HudCopy> = {
|
||||
"zh-CN": {
|
||||
appName: "JE-Skin",
|
||||
@@ -168,6 +191,7 @@
|
||||
const pointsPerSeries = 28;
|
||||
const summaryPointsPerSeries = 42;
|
||||
const signalRenderTickMs = 1200;
|
||||
const hudRealtimeRenderMs = 33;
|
||||
const replayDefaultFrameMs = 40;
|
||||
const showSignalPanels = false;
|
||||
const mockToneCycle: SignalTone[] = ["cyan", "lime", "orange", "violet", "gold", "rose"];
|
||||
@@ -203,6 +227,7 @@
|
||||
let connectionState: ConnectionState = "offline";
|
||||
let serialPortValue = "COM14";
|
||||
let serialPortOptions = ["COM4", "COM9", "COM14", "COM16"];
|
||||
let androidUsbSerialDevices: AndroidUsbSerialDevice[] = [];
|
||||
let isRefreshingPorts = false;
|
||||
let connectionNotice = "";
|
||||
let connectionNoticeTone: HudNoticeTone = "info";
|
||||
@@ -261,6 +286,9 @@
|
||||
} | null = null;
|
||||
let devkitStatusTimer: number | null = null;
|
||||
let sessionStartedAt: number = Date.now();
|
||||
let pendingHudPacket: HudPacket | null = null;
|
||||
let hudFrameRequestId: number | null = null;
|
||||
let lastHudRenderAt = 0;
|
||||
|
||||
$: uiCopy = copyByLocale[locale];
|
||||
$: configLinks = buildConfigLinks(
|
||||
@@ -287,6 +315,66 @@
|
||||
return typeof window !== "undefined" && "__TAURI_INTERNALS__" in window;
|
||||
}
|
||||
|
||||
function isAndroidRuntime(): boolean {
|
||||
if (!isTauriRuntime() || typeof navigator === "undefined") {
|
||||
return false;
|
||||
}
|
||||
|
||||
return /Android/i.test(navigator.userAgent);
|
||||
}
|
||||
|
||||
function formatAndroidUsbSerialLabel(device: AndroidUsbSerialDevice): string {
|
||||
const product = device.product || device.manufacturer || "USB Serial";
|
||||
const ids = `${device.vendorId.toString(16).padStart(4, "0")}:${device.productId
|
||||
.toString(16)
|
||||
.padStart(4, "0")}`;
|
||||
return `${product} (${ids})`;
|
||||
}
|
||||
|
||||
function findAndroidUsbSerialDevice(name: string): AndroidUsbSerialDevice | null {
|
||||
return androidUsbSerialDevices.find((device) => device.name === name) ?? null;
|
||||
}
|
||||
|
||||
function normalizeAndroidUsbSerialDevices(value: unknown): AndroidUsbSerialDevice[] {
|
||||
if (Array.isArray(value)) {
|
||||
return value.filter((device): device is AndroidUsbSerialDevice => {
|
||||
return typeof device === "object" && device !== null && typeof (device as AndroidUsbSerialDevice).name === "string";
|
||||
});
|
||||
}
|
||||
|
||||
if (typeof value === "object" && value !== null) {
|
||||
return Object.values(value).filter((device): device is AndroidUsbSerialDevice => {
|
||||
return typeof device === "object" && device !== null && typeof (device as AndroidUsbSerialDevice).name === "string";
|
||||
});
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
async function invokeAndroidUsbSerial<T>(
|
||||
command: AndroidUsbSerialCommand,
|
||||
args?: Record<string, unknown>
|
||||
): Promise<T> {
|
||||
const commandNames: Record<AndroidUsbSerialCommand, [string, string]> = {
|
||||
list: ["usb_serial_list", "usbSerialList"],
|
||||
open: ["usb_serial_open", "usbSerialOpen"],
|
||||
close: ["usb_serial_close", "usbSerialClose"]
|
||||
};
|
||||
|
||||
const [primary, fallback] = commandNames[command];
|
||||
|
||||
try {
|
||||
return await invoke<T>(`plugin:usb-serial|${primary}`, args);
|
||||
} catch (error) {
|
||||
const message = String(error);
|
||||
if (!message.includes("No command")) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
return await invoke<T>(`plugin:usb-serial|${fallback}`, args);
|
||||
}
|
||||
}
|
||||
|
||||
function clamp(value: number, min: number, max: number): number {
|
||||
return Math.min(max, Math.max(min, value));
|
||||
}
|
||||
@@ -726,12 +814,10 @@
|
||||
const safeIndex = clamp(index, 0, replayFrames.length - 1);
|
||||
const startIndex = Math.max(0, safeIndex - summaryPointsPerSeries + 1);
|
||||
const points: number[] = [];
|
||||
const xSeconds: number[] = [];
|
||||
for (let cursor = startIndex; cursor <= safeIndex; cursor += 1) {
|
||||
points.push(replayFrameTotal(replayFrames[cursor]));
|
||||
xSeconds.push(replayFrames[cursor].dtsMs / 1000);
|
||||
}
|
||||
return buildSummary(points, xSeconds);
|
||||
return buildSummary(points);
|
||||
}
|
||||
|
||||
function applyReplayFrame(index: number): void {
|
||||
@@ -744,7 +830,9 @@
|
||||
replayHasDisplayedFrame = true;
|
||||
replayProgress = replayFrames.length > 1 ? safeIndex / (replayFrames.length - 1) : 1;
|
||||
pressureMatrix = frameValuesToMatrix(replayFrames[safeIndex].values);
|
||||
signalPanels = buildInactivePanels();
|
||||
if (signalPanels.length > 0) {
|
||||
signalPanels = buildInactivePanels();
|
||||
}
|
||||
summary = buildReplaySummaryAt(safeIndex);
|
||||
hasSignalData = true;
|
||||
}
|
||||
@@ -903,7 +991,6 @@
|
||||
function buildEmptySummary(): HudSummary {
|
||||
return {
|
||||
label: "Resultant Force",
|
||||
xValues: [],
|
||||
points: [],
|
||||
latest: null,
|
||||
min: null,
|
||||
@@ -923,19 +1010,13 @@
|
||||
return shouldHideSummary(summaryValue.points) ? buildEmptySummary() : summaryValue;
|
||||
}
|
||||
|
||||
function buildSummary(points: number[], xValues: number[] = []): HudSummary {
|
||||
function buildSummary(points: number[]): HudSummary {
|
||||
if (points.length === 0) {
|
||||
return buildEmptySummary();
|
||||
}
|
||||
|
||||
const resolvedXValues = points.map((_, index) => {
|
||||
const x = xValues[index];
|
||||
return Number.isFinite(x) ? Number(x) : index + 1;
|
||||
});
|
||||
|
||||
return {
|
||||
label: "Resultant Force",
|
||||
xValues: resolvedXValues,
|
||||
points,
|
||||
latest: points[points.length - 1],
|
||||
min: Math.min(...points),
|
||||
@@ -960,21 +1041,13 @@
|
||||
? summaryValue.points[summaryValue.points.length - 1]
|
||||
: randomBetween(280, 1600);
|
||||
const next = Math.round(clamp(previous + randomBetween(-160, 160), 120, 2400) * 10) / 10;
|
||||
const nowSeconds = Math.round((Date.now() - sessionStartedAt) / 100) / 10;
|
||||
const previousXValues =
|
||||
summaryValue.xValues && summaryValue.xValues.length === summaryValue.points.length
|
||||
? summaryValue.xValues
|
||||
: summaryValue.points.map((_, index) => nowSeconds);
|
||||
const points =
|
||||
summaryValue.points.length >= summaryPointsPerSeries
|
||||
? summaryValue.points.slice(1)
|
||||
: summaryValue.points.slice();
|
||||
const xValues =
|
||||
previousXValues.length >= summaryPointsPerSeries ? previousXValues.slice(1) : previousXValues.slice();
|
||||
|
||||
points.push(next);
|
||||
xValues.push(nowSeconds);
|
||||
return buildSummary(points, xValues);
|
||||
return buildSummary(points);
|
||||
}
|
||||
|
||||
function buildInactivePanels(): HudSignalPanel[] {
|
||||
@@ -985,23 +1058,66 @@
|
||||
if (replayHasData) {
|
||||
return;
|
||||
}
|
||||
signalPanels = showSignalPanels ? packet.panels : buildInactivePanels();
|
||||
if (packet.summary.points.length > 0) {
|
||||
const nowSeconds = Math.round((Date.now() - sessionStartedAt) / 100) / 10;
|
||||
const pointCount = packet.summary.points.length;
|
||||
const spacing =
|
||||
pointCount > 1 ? Math.min(1.2, nowSeconds / Math.max(pointCount - 1, 1)) : 0;
|
||||
const startX = Math.max(0, nowSeconds - spacing * Math.max(pointCount - 1, 0));
|
||||
const xValues = packet.summary.points.map((_, index) => Math.round((startX + index * spacing) * 10) / 10);
|
||||
summary = { ...packet.summary, xValues };
|
||||
} else {
|
||||
summary = packet.summary;
|
||||
if (showSignalPanels) {
|
||||
signalPanels = packet.panels;
|
||||
} else if (signalPanels.length > 0) {
|
||||
signalPanels = buildInactivePanels();
|
||||
}
|
||||
summary = packet.summary;
|
||||
pressureMatrix = packet.pressureMatrix;
|
||||
hasSignalData = signalPanels.length > 0 || packet.summary.points.length > 0;
|
||||
}
|
||||
|
||||
function getFrameClock(): number {
|
||||
return typeof performance !== "undefined" ? performance.now() : Date.now();
|
||||
}
|
||||
|
||||
function cancelPendingHudPacket(): void {
|
||||
pendingHudPacket = null;
|
||||
if (hudFrameRequestId != null && typeof window !== "undefined") {
|
||||
window.cancelAnimationFrame(hudFrameRequestId);
|
||||
hudFrameRequestId = null;
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleHudPacketFlush(): void {
|
||||
if (hudFrameRequestId != null || typeof window === "undefined") {
|
||||
return;
|
||||
}
|
||||
|
||||
hudFrameRequestId = window.requestAnimationFrame(flushPendingHudPacket);
|
||||
}
|
||||
|
||||
function flushPendingHudPacket(timestamp: number = getFrameClock()): void {
|
||||
hudFrameRequestId = null;
|
||||
|
||||
if (!pendingHudPacket) {
|
||||
return;
|
||||
}
|
||||
|
||||
const elapsed = timestamp - lastHudRenderAt;
|
||||
if (lastHudRenderAt > 0 && elapsed < hudRealtimeRenderMs) {
|
||||
scheduleHudPacketFlush();
|
||||
return;
|
||||
}
|
||||
|
||||
const packet = pendingHudPacket;
|
||||
pendingHudPacket = null;
|
||||
lastHudRenderAt = timestamp;
|
||||
applyPacket(packet);
|
||||
}
|
||||
|
||||
function enqueueHudPacket(packet: HudPacket): void {
|
||||
if (replayHasData) {
|
||||
return;
|
||||
}
|
||||
|
||||
pendingHudPacket = packet;
|
||||
scheduleHudPacketFlush();
|
||||
}
|
||||
|
||||
function clearHudPanels(): void {
|
||||
cancelPendingHudPacket();
|
||||
hasSignalData = false;
|
||||
signalPanels = buildInactivePanels();
|
||||
summary = buildEmptySummary();
|
||||
@@ -1221,6 +1337,10 @@
|
||||
|
||||
function handlePortChange(event: CustomEvent<string>): void {
|
||||
serialPortValue = event.detail;
|
||||
if (isAndroidRuntime()) {
|
||||
const selectedDevice = findAndroidUsbSerialDevice(serialPortValue);
|
||||
deviceValue = selectedDevice ? formatAndroidUsbSerialLabel(selectedDevice) : "Android USB Serial";
|
||||
}
|
||||
connectionState = "offline";
|
||||
connectionNotice = "";
|
||||
clearHudPanels();
|
||||
@@ -1256,7 +1376,7 @@
|
||||
case "InvalidConfig":
|
||||
return "当前串口配置无效,请重新选择端口。";
|
||||
default:
|
||||
return "串口连接失败,请稍后重试。";
|
||||
return `串口连接失败:${errorCode}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1277,7 +1397,7 @@
|
||||
case "InvalidConfig":
|
||||
return "The selected serial port is invalid. Choose another port.";
|
||||
default:
|
||||
return "Connection failed. Please try again.";
|
||||
return `Connection failed: ${errorCode}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1288,14 +1408,16 @@
|
||||
const errorCode = normalizeInvokeError(error);
|
||||
|
||||
if (locale === "zh-CN") {
|
||||
return errorCode === "ScanError"
|
||||
? "串口列表刷新失败,请确认系统串口服务正常。"
|
||||
: "刷新串口列表失败,请稍后重试。";
|
||||
if (errorCode === "ScanError") {
|
||||
return "串口列表刷新失败,请确认系统串口服务正常。";
|
||||
}
|
||||
|
||||
return `刷新串口列表失败:${errorCode}`;
|
||||
}
|
||||
|
||||
return errorCode === "ScanError"
|
||||
? "Refreshing serial ports failed. Check whether the OS serial service is available."
|
||||
: "Refreshing serial ports failed. Please try again.";
|
||||
: `Refreshing serial ports failed: ${errorCode}`;
|
||||
}
|
||||
|
||||
function resolveExportNotice(error: unknown): string {
|
||||
@@ -1350,6 +1472,33 @@
|
||||
isRefreshingPorts = true;
|
||||
|
||||
try {
|
||||
try {
|
||||
const result = await invokeAndroidUsbSerial<AndroidUsbSerialListResult>("list");
|
||||
androidUsbSerialDevices = normalizeAndroidUsbSerialDevices(result.devices);
|
||||
serialPortOptions = androidUsbSerialDevices.map((device) => device.name);
|
||||
|
||||
if (serialPortOptions.includes(serialPortValue)) {
|
||||
return;
|
||||
}
|
||||
|
||||
serialPortValue = serialPortOptions[0] ?? "";
|
||||
const selectedDevice = findAndroidUsbSerialDevice(serialPortValue);
|
||||
deviceValue = selectedDevice ? formatAndroidUsbSerialLabel(selectedDevice) : "Android USB Serial";
|
||||
|
||||
if (!serialPortValue) {
|
||||
connectionState = "offline";
|
||||
clearHudPanels();
|
||||
connectionNotice =
|
||||
locale === "zh-CN" ? "未发现 USB 串口设备,请确认已通过 OTG 接入设备。" : "No USB serial device found.";
|
||||
connectionNoticeTone = "warn";
|
||||
}
|
||||
return;
|
||||
} catch (androidError) {
|
||||
if (isAndroidRuntime()) {
|
||||
throw androidError;
|
||||
}
|
||||
}
|
||||
|
||||
const ports = await invoke<string[]>("serial_enum");
|
||||
serialPortOptions = ports;
|
||||
|
||||
@@ -1390,7 +1539,28 @@
|
||||
connectionNotice = "";
|
||||
|
||||
try {
|
||||
const result = await invoke<SerialConnectResult>("serial_connect", { port: event.detail });
|
||||
let result: SerialConnectResult;
|
||||
|
||||
if (isAndroidRuntime()) {
|
||||
const selectedDevice = findAndroidUsbSerialDevice(event.detail);
|
||||
const opened = await invokeAndroidUsbSerial<AndroidUsbSerialOpenResult>("open", {
|
||||
name: event.detail,
|
||||
vendorId: selectedDevice?.vendorId,
|
||||
productId: selectedDevice?.productId
|
||||
});
|
||||
result = await invoke<SerialConnectResult>("serial_connect_fd", {
|
||||
fd: opened.fd,
|
||||
deviceName: opened.name,
|
||||
device_name: opened.name
|
||||
});
|
||||
const openedDevice = findAndroidUsbSerialDevice(opened.name) ?? selectedDevice;
|
||||
deviceValue = openedDevice
|
||||
? formatAndroidUsbSerialLabel(openedDevice)
|
||||
: `USB Serial (${opened.vendorId.toString(16)}:${opened.productId.toString(16)})`;
|
||||
} else {
|
||||
result = await invoke<SerialConnectResult>("serial_connect", { port: event.detail });
|
||||
}
|
||||
|
||||
connectionState = result.connected ? "online" : "offline";
|
||||
serialPortValue = result.port;
|
||||
connectionNotice = "";
|
||||
@@ -1398,6 +1568,13 @@
|
||||
clearHudPanels();
|
||||
console.info("[serial] connect result:", result.message);
|
||||
} catch (error) {
|
||||
if (isAndroidRuntime()) {
|
||||
try {
|
||||
await invokeAndroidUsbSerial("close");
|
||||
} catch (closeError) {
|
||||
console.warn("USB serial close after failed connect failed:", closeError);
|
||||
}
|
||||
}
|
||||
connectionState = "offline";
|
||||
connectionNotice = resolveSerialNotice(error, "connect");
|
||||
connectionNoticeTone = "warn";
|
||||
@@ -1409,6 +1586,9 @@
|
||||
async function handleSerialDisconnect(): Promise<void> {
|
||||
try {
|
||||
const result = await invoke<SerialConnectResult>("serial_disconnect");
|
||||
if (isAndroidRuntime()) {
|
||||
await invokeAndroidUsbSerial("close");
|
||||
}
|
||||
connectionState = result.connected ? "online" : "offline";
|
||||
connectionNotice = "";
|
||||
connectionNoticeTone = "info";
|
||||
@@ -1758,7 +1938,7 @@
|
||||
void checkForAppUpdate();
|
||||
void pollDevKitStatus();
|
||||
devkitStatusTimer = window.setInterval(() => void pollDevKitStatus(), 3000);
|
||||
void startTauriHudStream(applyPacket)
|
||||
void startTauriHudStream(enqueueHudPacket)
|
||||
.then((unlisten) => {
|
||||
if (disposed) {
|
||||
unlisten();
|
||||
@@ -1788,11 +1968,12 @@
|
||||
console.error("Failed to listen for devkit_pzt_angle:", error);
|
||||
});
|
||||
} else {
|
||||
stopMockFeed = startMockFeed(applyPacket);
|
||||
stopMockFeed = startMockFeed(enqueueHudPacket);
|
||||
}
|
||||
|
||||
return () => {
|
||||
disposed = true;
|
||||
cancelPendingHudPacket();
|
||||
pauseReplayPlayback();
|
||||
stopMockFeed?.();
|
||||
unlistenHudStream?.();
|
||||
@@ -2014,6 +2195,27 @@
|
||||
mix-blend-mode: soft-light;
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.hud-noise {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.hud-vignette {
|
||||
opacity: 0.4;
|
||||
}
|
||||
|
||||
.hud-gradient {
|
||||
background:
|
||||
linear-gradient(170deg, var(--hud-bg-20) 0%, var(--hud-bg-10) 56%, var(--hud-bg-30) 100%);
|
||||
}
|
||||
|
||||
.hud-layout {
|
||||
gap: clamp(0.3rem, 1vw, 0.6rem);
|
||||
padding: clamp(0.4rem, 1.2vw, 0.8rem);
|
||||
box-shadow: inset 0 -12px 24px rgb(0 0 0 / 0.24);
|
||||
}
|
||||
}
|
||||
|
||||
.hud-layout {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
|
||||
Reference in New Issue
Block a user