feat: add M1 device diagnostics

This commit is contained in:
2026-09-12 11:50:59 +08:00
parent f043131579
commit 8c14c53a59
25 changed files with 1004 additions and 29 deletions
+4 -2
View File
@@ -2,13 +2,15 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:allowBackup="false"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.NESLite">
<activity
android:name=".MainActivity"
android:exported="true"
android:screenOrientation="unspecified">
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
+8
View File
@@ -1,5 +1,7 @@
#include <jni.h>
#include <unistd.h>
#include <string>
#include "native_smoke.h"
@@ -9,3 +11,9 @@ Java_org_neslite_app_NativeBridge_buildInfo(JNIEnv* env, jclass) {
const std::string info = "native protocol v" + std::to_string(neslite::native_protocol_version());
return env->NewStringUTF(info.c_str());
}
extern "C" JNIEXPORT jlong JNICALL
Java_org_neslite_app_NativeBridge_pageSizeBytes(JNIEnv*, jclass) {
const long page_size = sysconf(_SC_PAGESIZE);
return page_size > 0 ? static_cast<jlong>(page_size) : 0;
}
+333 -12
View File
@@ -1,30 +1,351 @@
package org.neslite.app
import android.content.Context
import android.hardware.input.InputManager
import android.net.Uri
import android.os.Bundle
import android.view.Gravity
import android.os.SystemClock
import android.text.method.ScrollingMovementMethod
import android.view.InputDevice
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.ViewGroup
import android.widget.Button
import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.result.contract.ActivityResultContracts
import org.json.JSONArray
import org.json.JSONObject
import org.neslite.app.diagnostics.ControllerSnapshot
import org.neslite.app.diagnostics.DeviceBaseline
import org.neslite.app.diagnostics.DeviceDiagnostics
import org.neslite.app.diagnostics.DiagnosticEventJson
import org.neslite.app.diagnostics.InputDiagnostics
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
class MainActivity : ComponentActivity(), InputManager.InputDeviceListener {
private val inputDiagnostics = InputDiagnostics()
private lateinit var inputManager: InputManager
private lateinit var baseline: DeviceBaseline
private lateinit var nativeProbe: NativeProbe
private lateinit var deviceText: TextView
private lateinit var controllerText: TextView
private lateinit var stateText: TextView
private lateinit var eventText: TextView
private var controllers: List<ControllerSnapshot> = emptyList()
private val createDocument = registerForActivityResult(
ActivityResultContracts.CreateDocument("application/json"),
) { uri ->
if (uri != null) exportDiagnostics(uri)
}
/** M0 骨架页:证明 Kotlin/View 与 JNI 已连通。M1 会将它替换为诊断页面。 */
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
inputManager = getSystemService(Context.INPUT_SERVICE) as InputManager
nativeProbe = probeNative()
baseline = DeviceDiagnostics.collectBaseline(this, nativeProbe.pageSizeBytes)
setContentView(createContentView())
refreshControllers()
}
val nativeInfo = runCatching { NativeBridge.buildInfo() }
.getOrElse { "JNI unavailable: ${it.javaClass.simpleName}" }
override fun onStart() {
super.onStart()
inputManager.registerInputDeviceListener(this, null)
refreshControllers()
}
setContentView(
LinearLayout(this).apply {
gravity = Gravity.CENTER
override fun onStop() {
inputDiagnostics.clearAll("activity_stopped", SystemClock.uptimeMillis())
inputManager.unregisterInputDeviceListener(this)
super.onStop()
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (!hasFocus && ::stateText.isInitialized) {
inputDiagnostics.clearAll("focus_lost", SystemClock.uptimeMillis())
renderInputState()
}
}
override fun onInputDeviceAdded(deviceId: Int) {
InputDevice.getDevice(deviceId)
?.takeIf(DeviceDiagnostics::isController)
?.let { inputDiagnostics.attach(deviceId) }
refreshControllers()
}
override fun onInputDeviceChanged(deviceId: Int) {
refreshControllers()
}
override fun onInputDeviceRemoved(deviceId: Int) {
inputDiagnostics.clearDevice(
deviceId,
"device_removed",
removeSession = true,
eventTimeMs = SystemClock.uptimeMillis(),
)
refreshControllers()
}
private fun handleKeyEvent(event: KeyEvent): Boolean {
if (event.keyCode != KeyEvent.KEYCODE_BACK && DeviceDiagnostics.isControllerSource(event.source)) {
val action = when (event.action) {
KeyEvent.ACTION_DOWN -> if (event.repeatCount > 0) "repeat" else "down"
KeyEvent.ACTION_UP -> "up"
else -> "action_${event.action}"
}
inputDiagnostics.recordKey(
deviceId = event.deviceId,
eventTimeMs = event.eventTime,
source = event.source,
action = action,
keyCode = event.keyCode,
keyName = KeyEvent.keyCodeToString(event.keyCode),
repeatCount = event.repeatCount,
)
renderInputState()
return true
}
return false
}
private fun handleMotionEvent(event: MotionEvent): Boolean {
val device = event.device
if (device != null && DeviceDiagnostics.isControllerSource(event.source)) {
device.motionRanges
.filter { range -> range.source and event.source == range.source }
.forEach { range ->
inputDiagnostics.recordAxis(
deviceId = event.deviceId,
eventTimeMs = event.eventTime,
source = event.source,
axis = range.axis,
axisName = MotionEvent.axisToString(range.axis) ?: "AXIS_${range.axis}",
value = event.getAxisValue(range.axis),
)
}
renderInputState()
return true
}
return false
}
private fun createContentView(): ScrollView = DiagnosticScrollView(
context = this,
keyHandler = ::handleKeyEvent,
motionHandler = ::handleMotionEvent,
).apply {
isFillViewport = true
addView(
LinearLayout(context).apply {
orientation = LinearLayout.VERTICAL
setPadding(32, 32, 32, 48)
addView(title(getString(R.string.diagnostics_title)))
addView(body(getString(R.string.diagnostics_instructions)))
addView(section(getString(R.string.section_native)))
addView(body(nativeProbe.render()))
addView(section(getString(R.string.section_device)))
deviceText = body(this@MainActivity.baseline.render())
addView(deviceText)
addView(section(getString(R.string.section_controllers)))
controllerText = body("")
addView(controllerText)
addView(section(getString(R.string.section_input_state)))
stateText = body("")
addView(stateText)
addView(section(getString(R.string.section_events)))
eventText = body("").apply {
movementMethod = ScrollingMovementMethod()
setTextIsSelectable(true)
}
addView(eventText)
addView(
TextView(context).apply {
text = getString(R.string.bootstrap_status, nativeInfo)
textSize = 18f
setPadding(48, 48, 48, 48)
Button(context).apply {
text = getString(R.string.export_diagnostics)
setOnClickListener { createDocument.launch(defaultExportName()) }
},
LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
).apply { topMargin = 24 },
)
},
)
}
private fun refreshControllers() {
val connectedIds = DeviceDiagnostics.controllerDeviceIds()
inputDiagnostics.attachedDeviceIds()
.filterNot(connectedIds::contains)
.forEach { deviceId ->
inputDiagnostics.clearDevice(
deviceId,
"device_missing",
removeSession = true,
eventTimeMs = SystemClock.uptimeMillis(),
)
}
controllers = DeviceDiagnostics.controllers(inputDiagnostics)
if (::controllerText.isInitialized) {
controllerText.text = if (controllers.isEmpty()) {
getString(R.string.no_controller)
} else {
controllers.joinToString("\n\n") { it.render() }
}
renderInputState()
}
}
private fun renderInputState() {
if (!::stateText.isInitialized) return
stateText.text = if (controllers.isEmpty()) {
getString(R.string.no_input_state)
} else {
controllers.joinToString("\n\n") { controller ->
val snapshot = inputDiagnostics.snapshot(controller.deviceId)
val keys = snapshot?.pressedKeys
?.sorted()
?.joinToString { KeyEvent.keyCodeToString(it) }
.orEmpty()
.ifEmpty { "无" }
val axes = snapshot?.axes
?.toSortedMap()
?.entries
?.joinToString { (axis, value) ->
"${MotionEvent.axisToString(axis) ?: "AXIS_$axis"}=${String.format(Locale.ROOT, "%.3f", value)}"
}
.orEmpty()
.ifEmpty { "未采样" }
"会话 ${controller.sessionId}:按键 [$keys]\n轴 [$axes]"
}
}
val events = inputDiagnostics.recordedEvents().takeLast(EVENT_LINES)
eventText.text = if (events.isEmpty()) {
getString(R.string.no_events)
} else {
events.joinToString("\n") { event ->
"#${event.sequence} s${event.sessionId} d${event.deviceId} ${event.kind}/${event.action} ${event.name}=${String.format(Locale.ROOT, "%.3f", event.value)} t=${event.eventTimeMs} src=0x${event.source.toUInt().toString(16)} repeat=${event.repeatCount}"
}
}
}
private fun exportDiagnostics(uri: Uri) {
val json = buildDiagnosticReport().toString(2)
runCatching {
contentResolver.openOutputStream(uri, "wt")?.bufferedWriter(Charsets.UTF_8).use { writer ->
requireNotNull(writer) { "系统未提供可写输出流" }
writer.write(json)
}
}.onSuccess {
Toast.makeText(this, R.string.export_success, Toast.LENGTH_LONG).show()
}.onFailure { error ->
Toast.makeText(
this,
getString(R.string.export_failed, error.javaClass.simpleName, error.message ?: "未知错误"),
Toast.LENGTH_LONG,
).show()
}
}
private fun buildDiagnosticReport(): JSONObject = JSONObject()
.put("formatVersion", 1)
.put("exportedAtEpochMs", System.currentTimeMillis())
.put("elapsedRealtimeMs", SystemClock.elapsedRealtime())
.put(
"application",
JSONObject()
.put("applicationId", BuildConfig.APPLICATION_ID)
.put("versionName", BuildConfig.VERSION_NAME)
.put("versionCode", BuildConfig.VERSION_CODE),
)
.put(
"native",
JSONObject()
.put("loaded", nativeProbe.loaded)
.put("buildInfo", nativeProbe.buildInfo ?: JSONObject.NULL)
.put("pageSizeBytes", nativeProbe.pageSizeBytes ?: JSONObject.NULL)
.put("error", nativeProbe.error ?: JSONObject.NULL),
)
.put("device", baseline.toJson())
.put("controllers", JSONArray().apply { controllers.forEach { put(it.toJson()) } })
.put("eventCapacity", InputDiagnostics.DEFAULT_CAPACITY)
.put("events", DiagnosticEventJson.toJsonArray(inputDiagnostics.recordedEvents()))
private fun probeNative(): NativeProbe = runCatching {
NativeProbe(
loaded = true,
buildInfo = NativeBridge.buildInfo(),
pageSizeBytes = NativeBridge.pageSizeBytes(),
error = null,
)
}.getOrElse { error ->
NativeProbe(
loaded = false,
buildInfo = null,
pageSizeBytes = null,
error = "${error.javaClass.name}: ${error.message ?: "无详细消息"}",
)
}
private fun title(text: String) = TextView(this).apply {
this.text = text
textSize = 26f
setTextIsSelectable(true)
}
private fun section(text: String) = TextView(this).apply {
this.text = text
textSize = 20f
setPadding(0, 28, 0, 8)
setTextIsSelectable(true)
}
private fun body(text: String) = TextView(this).apply {
this.text = text
textSize = 14f
setTextIsSelectable(true)
}
private fun defaultExportName(): String {
val timestamp = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.ROOT).format(Date())
return "neslite-diagnostics-$timestamp.json"
}
private data class NativeProbe(
val loaded: Boolean,
val buildInfo: String?,
val pageSizeBytes: Long?,
val error: String?,
) {
fun render(): String = if (loaded) {
"状态:成功\n入口:$buildInfo\n页大小:${pageSizeBytes ?: "未知"} bytes"
} else {
"状态:失败\n错误:$error"
}
}
private class DiagnosticScrollView(
context: Context,
private val keyHandler: (KeyEvent) -> Boolean,
private val motionHandler: (MotionEvent) -> Boolean,
) : ScrollView(context) {
override fun dispatchKeyEvent(event: KeyEvent): Boolean =
keyHandler(event) || super.dispatchKeyEvent(event)
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean =
motionHandler(event) || super.dispatchGenericMotionEvent(event)
}
companion object {
private const val EVENT_LINES = 30
}
}
@@ -7,4 +7,6 @@ object NativeBridge {
}
external fun buildInfo(): String
external fun pageSizeBytes(): Long
}
@@ -0,0 +1,176 @@
package org.neslite.app.diagnostics
import android.content.Context
import android.hardware.display.DisplayManager
import android.os.Build
import android.view.Display
import android.view.InputDevice
import android.view.MotionEvent
import org.json.JSONArray
import org.json.JSONObject
import java.util.Locale
data class DeviceBaseline(
val manufacturer: String,
val model: String,
val apiLevel: Int,
val release: String,
val supportedAbis: List<String>,
val pageSizeBytes: Long?,
val displayWidthPx: Int?,
val displayHeightPx: Int?,
val currentRefreshRateHz: Float?,
val availableRefreshRatesHz: List<Float>,
) {
fun toJson(): JSONObject = JSONObject()
.put("manufacturer", manufacturer)
.put("model", model)
.put("apiLevel", apiLevel)
.put("release", release)
.put("supportedAbis", JSONArray(supportedAbis))
.put("pageSizeBytes", pageSizeBytes ?: JSONObject.NULL)
.put("displayWidthPx", displayWidthPx ?: JSONObject.NULL)
.put("displayHeightPx", displayHeightPx ?: JSONObject.NULL)
.put("currentRefreshRateHz", currentRefreshRateHz ?: JSONObject.NULL)
.put("availableRefreshRatesHz", JSONArray(availableRefreshRatesHz))
fun render(): String = buildString {
appendLine("设备:$manufacturer $model")
appendLine("Android:$release (API $apiLevel)")
appendLine("ABI:${supportedAbis.ifEmpty { listOf("未知") }.joinToString()}")
appendLine("页大小:${pageSizeBytes?.let { "$it bytes" } ?: "未知"}")
appendLine(
"屏幕:${if (displayWidthPx != null && displayHeightPx != null) "${displayWidthPx}×$displayHeightPx px" else "未知"}",
)
append("刷新率:${currentRefreshRateHz?.formatHz() ?: "未知"};可用 ${availableRefreshRatesHz.joinToString { it.formatHz() }.ifEmpty { "未知" }}")
}
}
data class MotionRangeSnapshot(
val axis: Int,
val axisName: String,
val source: Int,
val min: Float,
val max: Float,
val flat: Float,
val fuzz: Float,
val resolution: Float,
) {
fun toJson(): JSONObject = JSONObject()
.put("axis", axis)
.put("axisName", axisName)
.put("source", source)
.put("sourceHex", "0x${source.toUInt().toString(16)}")
.put("min", min.toDouble())
.put("max", max.toDouble())
.put("flat", flat.toDouble())
.put("fuzz", fuzz.toDouble())
.put("resolution", resolution.toDouble())
}
data class ControllerSnapshot(
val deviceId: Int,
val sessionId: Long,
val name: String,
val descriptor: String,
val vendorId: Int,
val productId: Int,
val sources: Int,
val ranges: List<MotionRangeSnapshot>,
) {
fun toJson(): JSONObject = JSONObject()
.put("deviceId", deviceId)
.put("sessionId", sessionId)
.put("name", name)
.put("descriptor", descriptor)
.put("vendorId", vendorId)
.put("productId", productId)
.put("sources", sources)
.put("sourcesHex", "0x${sources.toUInt().toString(16)}")
.put("motionRanges", JSONArray().apply { ranges.forEach { put(it.toJson()) } })
fun render(): String = buildString {
appendLine("$name [本次会话 $sessionId / 临时 ID $deviceId]")
appendLine("descriptor:$descriptor")
appendLine("VID/PID:${vendorId.hex4()}/${productId.hex4()};sources=0x${sources.toUInt().toString(16)}")
if (ranges.isEmpty()) {
append("轴:未上报")
} else {
append(
ranges.joinToString(separator = "\n") {
"${it.axisName}: ${it.min.format()}..${it.max.format()} flat=${it.flat.format()} source=0x${it.source.toUInt().toString(16)}"
},
)
}
}
}
object DeviceDiagnostics {
fun collectBaseline(context: Context, pageSizeBytes: Long?): DeviceBaseline {
val displayManager = context.getSystemService(DisplayManager::class.java)
val display = displayManager?.getDisplay(Display.DEFAULT_DISPLAY)
val mode = display?.mode
val rates = display?.supportedModes
?.map { it.refreshRate }
?.distinctBy { (it * 100f).toInt() }
?.sorted()
.orEmpty()
return DeviceBaseline(
manufacturer = Build.MANUFACTURER.orUnknown(),
model = Build.MODEL.orUnknown(),
apiLevel = Build.VERSION.SDK_INT,
release = Build.VERSION.RELEASE.orUnknown(),
supportedAbis = Build.SUPPORTED_ABIS?.toList().orEmpty(),
pageSizeBytes = pageSizeBytes?.takeIf { it > 0L },
displayWidthPx = mode?.physicalWidth,
displayHeightPx = mode?.physicalHeight,
currentRefreshRateHz = mode?.refreshRate,
availableRefreshRatesHz = rates,
)
}
fun controllerDeviceIds(): Set<Int> = InputDevice.getDeviceIds().toList()
.mapNotNull(InputDevice::getDevice)
.filter(::isController)
.mapTo(linkedSetOf()) { it.id }
fun controllers(inputDiagnostics: InputDiagnostics): List<ControllerSnapshot> = InputDevice.getDeviceIds().toList()
.mapNotNull(InputDevice::getDevice)
.filter(::isController)
.sortedBy { it.name.lowercase(Locale.ROOT) }
.map { device ->
ControllerSnapshot(
deviceId = device.id,
sessionId = inputDiagnostics.attach(device.id),
name = device.name.orUnknown(),
descriptor = device.descriptor.orUnknown(),
vendorId = device.vendorId,
productId = device.productId,
sources = device.sources,
ranges = device.motionRanges.map { range ->
MotionRangeSnapshot(
axis = range.axis,
axisName = MotionEvent.axisToString(range.axis) ?: "AXIS_${range.axis}",
source = range.source,
min = range.min,
max = range.max,
flat = range.flat,
fuzz = range.fuzz,
resolution = range.resolution,
)
},
)
}
fun isController(device: InputDevice): Boolean = isControllerSource(device.sources)
fun isControllerSource(source: Int): Boolean =
source and InputDevice.SOURCE_GAMEPAD == InputDevice.SOURCE_GAMEPAD ||
source and InputDevice.SOURCE_JOYSTICK == InputDevice.SOURCE_JOYSTICK ||
source and InputDevice.SOURCE_DPAD == InputDevice.SOURCE_DPAD
}
private fun String?.orUnknown(): String = this?.takeIf { it.isNotBlank() } ?: "未知"
private fun Float.format(): String = String.format(Locale.ROOT, "%.3f", this)
private fun Float.formatHz(): String = String.format(Locale.ROOT, "%.2f Hz", this)
private fun Int.hex4(): String = "0x${toString(16).padStart(4, '0')}"
@@ -0,0 +1,21 @@
package org.neslite.app.diagnostics
data class DiagnosticEvent(
val sequence: Long,
val sessionId: Long,
val deviceId: Int,
val eventTimeMs: Long,
val source: Int,
val kind: String,
val action: String,
val code: Int,
val name: String,
val value: Float,
val repeatCount: Int,
)
data class InputSnapshot(
val sessionId: Long,
val pressedKeys: Set<Int>,
val axes: Map<Int, Float>,
)
@@ -0,0 +1,58 @@
package org.neslite.app.diagnostics
import org.json.JSONArray
import org.json.JSONObject
object DiagnosticEventJson {
const val FORMAT_VERSION = 1
fun encode(events: List<DiagnosticEvent>): String = JSONObject()
.put("formatVersion", FORMAT_VERSION)
.put("events", toJsonArray(events))
.toString(2)
fun decode(json: String): List<DiagnosticEvent> {
val root = JSONObject(json)
require(root.getInt("formatVersion") == FORMAT_VERSION) { "Unsupported diagnostic format" }
val array = root.getJSONArray("events")
return buildList(array.length()) {
for (index in 0 until array.length()) {
val item = array.getJSONObject(index)
add(
DiagnosticEvent(
sequence = item.getLong("sequence"),
sessionId = item.getLong("sessionId"),
deviceId = item.getInt("deviceId"),
eventTimeMs = item.getLong("eventTimeMs"),
source = item.getInt("source"),
kind = item.getString("kind"),
action = item.getString("action"),
code = item.getInt("code"),
name = item.getString("name"),
value = item.getDouble("value").toFloat(),
repeatCount = item.getInt("repeatCount"),
),
)
}
}
}
fun toJsonArray(events: List<DiagnosticEvent>): JSONArray = JSONArray().apply {
events.forEach { event ->
put(
JSONObject()
.put("sequence", event.sequence)
.put("sessionId", event.sessionId)
.put("deviceId", event.deviceId)
.put("eventTimeMs", event.eventTimeMs)
.put("source", event.source)
.put("kind", event.kind)
.put("action", event.action)
.put("code", event.code)
.put("name", event.name)
.put("value", event.value.toDouble())
.put("repeatCount", event.repeatCount),
)
}
}
}
@@ -0,0 +1,129 @@
package org.neslite.app.diagnostics
import java.util.ArrayDeque
class InputDiagnostics(private val capacity: Int = DEFAULT_CAPACITY) {
private val events = ArrayDeque<DiagnosticEvent>(capacity)
private val sessions = mutableMapOf<Int, Long>()
private val pressedKeys = mutableMapOf<Int, MutableSet<Int>>()
private val axes = mutableMapOf<Int, MutableMap<Int, Float>>()
private var nextSessionId = 1L
private var nextSequence = 1L
init {
require(capacity > 0) { "capacity must be positive" }
}
fun attach(deviceId: Int): Long = sessions.getOrPut(deviceId) { nextSessionId++ }
fun sessionId(deviceId: Int): Long? = sessions[deviceId]
fun attachedDeviceIds(): Set<Int> = sessions.keys.toSet()
fun recordKey(
deviceId: Int,
eventTimeMs: Long,
source: Int,
action: String,
keyCode: Int,
keyName: String,
repeatCount: Int,
) {
val sessionId = attach(deviceId)
val keys = pressedKeys.getOrPut(deviceId) { linkedSetOf() }
when (action) {
"down", "repeat" -> keys += keyCode
"up" -> keys -= keyCode
}
append(
DiagnosticEvent(
sequence = nextSequence++,
sessionId = sessionId,
deviceId = deviceId,
eventTimeMs = eventTimeMs,
source = source,
kind = "key",
action = action,
code = keyCode,
name = keyName,
value = if (action == "up") 0f else 1f,
repeatCount = repeatCount,
),
)
}
fun recordAxis(
deviceId: Int,
eventTimeMs: Long,
source: Int,
axis: Int,
axisName: String,
value: Float,
) {
val sessionId = attach(deviceId)
axes.getOrPut(deviceId) { linkedMapOf() }[axis] = value
append(
DiagnosticEvent(
sequence = nextSequence++,
sessionId = sessionId,
deviceId = deviceId,
eventTimeMs = eventTimeMs,
source = source,
kind = "axis",
action = "sample",
code = axis,
name = axisName,
value = value,
repeatCount = 0,
),
)
}
fun clearDevice(deviceId: Int, reason: String, removeSession: Boolean, eventTimeMs: Long = 0L) {
val sessionId = sessions[deviceId] ?: return
pressedKeys.remove(deviceId)
axes.remove(deviceId)
append(
DiagnosticEvent(
sequence = nextSequence++,
sessionId = sessionId,
deviceId = deviceId,
eventTimeMs = eventTimeMs,
source = 0,
kind = "state",
action = reason,
code = 0,
name = reason,
value = 0f,
repeatCount = 0,
),
)
if (removeSession) sessions.remove(deviceId)
}
fun clearAll(reason: String, eventTimeMs: Long = 0L) {
sessions.keys.toList().forEach {
clearDevice(it, reason, removeSession = false, eventTimeMs = eventTimeMs)
}
}
fun snapshot(deviceId: Int): InputSnapshot? {
val sessionId = sessions[deviceId] ?: return null
return InputSnapshot(
sessionId = sessionId,
pressedKeys = pressedKeys[deviceId]?.toSet().orEmpty(),
axes = axes[deviceId]?.toMap().orEmpty(),
)
}
fun recordedEvents(): List<DiagnosticEvent> = events.toList()
private fun append(event: DiagnosticEvent) {
if (events.size == capacity) events.removeFirst()
events.addLast(event)
}
companion object {
const val DEFAULT_CAPACITY = 512
}
}
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="48dp"
android:height="48dp"
android:viewportWidth="48"
android:viewportHeight="48">
<path
android:fillColor="#5E35B1"
android:pathData="M8,12h32a6,6 0,0 1,6 6v12a6,6 0,0 1,-6 6h-32a6,6 0,0 1,-6 -6v-12a6,6 0,0 1,6 -6z" />
<path
android:fillColor="#FFFFFF"
android:pathData="M12,18h4v4h4v4h-4v4h-4v-4h-4v-4h4zM34,19a3,3 0,1 1,0 6a3,3 0,0 1,0 -6zM40,25a3,3 0,1 1,0 6a3,3 0,0 1,0 -6z" />
</vector>
+13 -1
View File
@@ -1,4 +1,16 @@
<resources>
<string name="app_name">NESLite</string>
<string name="bootstrap_status">NESLite M0 baseline\n%s</string>
<string name="diagnostics_title">NESLite 0.1.x 设备诊断</string>
<string name="diagnostics_instructions">请使用 X5 Lite 原生安卓模式并关闭硬件连发。依次测试方向与 A/B 组合、全部松开、按住时拔出及重新连接;真实键码以页面和导出 JSON 为准。</string>
<string name="section_native">JNI 自检</string>
<string name="section_device">手机与显示</string>
<string name="section_controllers">已连接控制器</string>
<string name="section_input_state">实时输入状态</string>
<string name="section_events">最近 30 条事件(最多保留 512 条)</string>
<string name="no_controller">未检测到手柄。连接后此页会自动更新。</string>
<string name="no_input_state">连接手柄并操作后显示组合按键与轴值。</string>
<string name="no_events">尚无输入事件。</string>
<string name="export_diagnostics">导出诊断 JSON</string>
<string name="export_success">诊断 JSON 已导出</string>
<string name="export_failed">导出失败:%1$s — %2$s</string>
</resources>
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<full-backup-content>
<exclude
domain="root"
path="." />
</full-backup-content>
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<data-extraction-rules>
<cloud-backup disableIfNoEncryptionCapabilities="true">
<exclude
domain="root"
path="." />
</cloud-backup>
<device-transfer>
<exclude
domain="root"
path="." />
</device-transfer>
</data-extraction-rules>
@@ -7,6 +7,7 @@ class BuildIdentityTest {
@Test
fun debugBuildUsesTheDocumentedIdentity() {
assertEquals("org.neslite.app.debug", BuildConfig.APPLICATION_ID)
assertEquals("0.0.1-dev-debug", BuildConfig.VERSION_NAME)
assertEquals("0.1.3-debug", BuildConfig.VERSION_NAME)
assertEquals(1003, BuildConfig.VERSION_CODE)
}
}
@@ -0,0 +1,65 @@
package org.neslite.app.diagnostics
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class InputDiagnosticsTest {
@Test
fun combinationReleaseAndFocusLossClearState() {
val diagnostics = InputDiagnostics()
diagnostics.recordKey(7, 10, 0x401, "down", 19, "KEYCODE_DPAD_UP", 0)
diagnostics.recordKey(7, 11, 0x401, "down", 96, "KEYCODE_BUTTON_A", 0)
assertEquals(setOf(19, 96), diagnostics.snapshot(7)?.pressedKeys)
diagnostics.recordKey(7, 12, 0x401, "up", 19, "KEYCODE_DPAD_UP", 0)
assertEquals(setOf(96), diagnostics.snapshot(7)?.pressedKeys)
diagnostics.clearAll("focus_lost")
assertTrue(diagnostics.snapshot(7)?.pressedKeys.orEmpty().isEmpty())
assertEquals("focus_lost", diagnostics.recordedEvents().last().action)
}
@Test
fun removalClearsStateAndReconnectCreatesNewSession() {
val diagnostics = InputDiagnostics()
val firstSession = diagnostics.attach(4)
diagnostics.recordAxis(4, 20, 0x1000010, 15, "AXIS_HAT_X", -1f)
diagnostics.clearDevice(4, "device_removed", removeSession = true)
assertEquals(null, diagnostics.snapshot(4))
val secondSession = diagnostics.attach(4)
assertNotEquals(firstSession, secondSession)
assertTrue(diagnostics.snapshot(4)?.axes.orEmpty().isEmpty())
}
@Test
fun recorderIsBoundedAndPreservesNewestOrder() {
val diagnostics = InputDiagnostics(capacity = 3)
repeat(5) { index ->
diagnostics.recordAxis(1, index.toLong(), 0x1000010, index, "AXIS_$index", index.toFloat())
}
val events = diagnostics.recordedEvents()
assertEquals(3, events.size)
assertEquals(listOf(3L, 4L, 5L), events.map { it.sequence })
assertFalse(events.any { it.code < 2 })
}
@Test
fun exportedEventsRoundTripWithoutChangingOrderOrValues() {
val original = listOf(
DiagnosticEvent(1, 8, 3, 100, 0x401, "key", "down", 96, "KEYCODE_BUTTON_A", 1f, 0),
DiagnosticEvent(2, 8, 3, 101, 0x1000010, "axis", "sample", 15, "AXIS_HAT_X", -0.75f, 0),
DiagnosticEvent(3, 8, 3, 102, 0x401, "key", "up", 96, "KEYCODE_BUTTON_A", 0f, 0),
)
val decoded = DiagnosticEventJson.decode(DiagnosticEventJson.encode(original))
assertEquals(original, decoded)
}
}