Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4238ecd56e | |||
| 0baf371bbd | |||
| 6500e0108f | |||
| 80452a7a7d |
@@ -38,7 +38,7 @@ android {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(files("libs/unity-bridge-aar-debug-v1.3.0.aar"))
|
||||
implementation(files("libs/unity-bridge.aar"))
|
||||
implementation("androidx.core:core-ktx:1.12.0")
|
||||
implementation("androidx.appcompat:appcompat:1.6.1")
|
||||
implementation("androidx.fragment:fragment-ktx:1.6.2")
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -2,12 +2,54 @@ package com.kiwii.controlpanel.data
|
||||
|
||||
import android.app.Activity
|
||||
import com.kiwii.bridge.KiwiiRuntimeClientBridge
|
||||
import com.kiwii.controlpanel.ui.components.MotorTelemetrySnapshotCache
|
||||
import com.kiwii.controlpanel.model.OperationResult
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
class BridgeRepository {
|
||||
|
||||
private companion object {
|
||||
const val HANDLE_CACHE_MAX_AGE_MS = 5000L
|
||||
const val HANDLE_REFRESH_MIN_INTERVAL_MS = 1000L
|
||||
const val HANDLE_REFRESH_STUCK_RESET_MS = 5000L
|
||||
const val DONGLE_CACHE_MAX_AGE_MS = 3000L
|
||||
const val DONGLE_REFRESH_MIN_INTERVAL_MS = 1000L
|
||||
const val DONGLE_REFRESH_STUCK_RESET_MS = 5000L
|
||||
|
||||
@Volatile
|
||||
private var cachedHandleStateJson: String = ""
|
||||
|
||||
@Volatile
|
||||
private var cachedHandleStateAtMs: Long = 0L
|
||||
|
||||
@Volatile
|
||||
private var lastHandleRefreshAttemptMs: Long = 0L
|
||||
|
||||
private val handleRefreshInFlight = AtomicBoolean(false)
|
||||
private val handleRefreshExecutor = Executors.newCachedThreadPool { runnable ->
|
||||
Thread(runnable, "SDKPanelHandleStateRefresh").apply { isDaemon = true }
|
||||
}
|
||||
|
||||
@Volatile
|
||||
private var cachedDongleStateJson: String = ""
|
||||
|
||||
@Volatile
|
||||
private var cachedDongleStateAtMs: Long = 0L
|
||||
|
||||
@Volatile
|
||||
private var lastDongleRefreshAttemptMs: Long = 0L
|
||||
|
||||
private val dongleRefreshInFlight = AtomicBoolean(false)
|
||||
private val dongleRefreshExecutor = Executors.newCachedThreadPool { runnable ->
|
||||
Thread(runnable, "SDKPanelDongleStateRefresh").apply { isDaemon = true }
|
||||
}
|
||||
}
|
||||
|
||||
fun bind(activity: Activity): Boolean = KiwiiRuntimeClientBridge.bind(activity)
|
||||
fun unbind() = KiwiiRuntimeClientBridge.unbind()
|
||||
fun isBound(): Boolean = KiwiiRuntimeClientBridge.isBound()
|
||||
@@ -29,6 +71,72 @@ class BridgeRepository {
|
||||
fun requestRuntimeWarmStart(reason: String = ""): String = KiwiiRuntimeClientBridge.requestRuntimeWarmStart(reason)
|
||||
|
||||
fun getCameraStateJson(): String = KiwiiRuntimeClientBridge.getCameraStateJson()
|
||||
/**
|
||||
* Phase4B-v11.2 compile fix: keep the Phase4B camera observation API that CameraOps
|
||||
* and RuntimeStateSource already depend on. v11 overwrote BridgeRepository while adding
|
||||
* Dongle detail-state fusion and accidentally dropped this method.
|
||||
*/
|
||||
fun getCameraObservationStateJson(): String {
|
||||
return try {
|
||||
val method = KiwiiRuntimeClientBridge::class.java.getMethod("getCameraObservationStateJson")
|
||||
method.invoke(null) as? String ?: getCameraStateJson()
|
||||
} catch (_: Throwable) {
|
||||
try {
|
||||
val out = JSONObject()
|
||||
val camera = parseJsonOrEmpty(getCameraStateJson())
|
||||
val health = parseJsonOrEmpty(getHealthStateJson())
|
||||
val debug = runCatching { parseJsonOrEmpty(getDebugSnapshotJson()) }.getOrDefault(JSONObject())
|
||||
val latestPose2D = runCatching { getLatestPose2D() }.getOrDefault(FloatArray(0))
|
||||
val latestPose3D = runCatching { getLatestPose3D() }.getOrDefault(FloatArray(0))
|
||||
val runtimeStats = runCatching { getLatestRuntimeStats() }.getOrDefault(FloatArray(0))
|
||||
val statsActive = runtimeStats.any { value -> !value.isNaN() && !value.isInfinite() && value > 0.1f }
|
||||
|
||||
val pipeline = health.optJSONObject("realInternalCameraPipeline")
|
||||
?: camera.optJSONObject("realInternalCameraPipeline")
|
||||
?: debug.optJSONObject("realInternalCameraPipeline")
|
||||
?: JSONObject()
|
||||
val pose2DState = health.optJSONObject("pose2DState")
|
||||
?: camera.optJSONObject("pose2DState")
|
||||
?: debug.optJSONObject("pose2DState")
|
||||
?: JSONObject()
|
||||
val pose3DState = health.optJSONObject("pose3DState")
|
||||
?: camera.optJSONObject("pose3DState")
|
||||
?: debug.optJSONObject("pose3DState")
|
||||
?: JSONObject()
|
||||
|
||||
out.put("contractVersion", "kiwii.sdk-panel.camera-observation-display.v11.2")
|
||||
out.put("source", "SDK_Panel.camera-observation-compat")
|
||||
out.put("pipeline", JSONObject()
|
||||
.put("state", if (statsActive || latestPose2D.isNotEmpty() || latestPose3D.isNotEmpty()) "RUNNING" else "STARTING")
|
||||
.put("imx415OpenSucceeded", pipeline.optBoolean("imx415OpenSucceeded", health.optBoolean("imx415OpenSucceeded", false)))
|
||||
.put("rgaEnabled", pipeline.optBoolean("rgaEnabled", health.optBoolean("rgaEnabled", false)))
|
||||
.put("rknnYoloEnabled", pipeline.optBoolean("rknnYoloEnabled", health.optBoolean("rknnYoloEnabled", false)))
|
||||
.put("onnxInferenceEnabled", pipeline.optBoolean("onnxInferenceEnabled", health.optBoolean("onnxInferenceEnabled", false)))
|
||||
.put("videoPose3DEnabled", pipeline.optBoolean("videoPose3DEnabled", health.optBoolean("videoPose3DEnabled", false)))
|
||||
)
|
||||
out.put("pose2DLatest", JSONObject()
|
||||
.put("available", pose2DState.optBoolean("available", latestPose2D.isNotEmpty()))
|
||||
.put("sequenceId", pose2DState.optLong("pose2DSequenceId", 0L))
|
||||
.put("arrayLength", latestPose2D.size)
|
||||
)
|
||||
out.put("pose3DLatest", JSONObject()
|
||||
.put("available", pose3DState.optBoolean("available", latestPose3D.isNotEmpty()))
|
||||
.put("sequenceId", pose3DState.optLong("pose3DSequenceId", 0L))
|
||||
.put("arrayLength", latestPose3D.size)
|
||||
.put("pose3DModelFrames", pose3DState.optInt("pose3DModelFrames", pipeline.optInt("pose3DModelFrames", health.optInt("pose3DModelFrames", 27))))
|
||||
)
|
||||
out.put("runtimeStatsActive", statsActive)
|
||||
out.put("rawCameraState", camera)
|
||||
out.toString()
|
||||
} catch (t: Throwable) {
|
||||
JSONObject()
|
||||
.put("contractVersion", "kiwii.sdk-panel.camera-observation-display.v11.2")
|
||||
.put("error", t.javaClass.simpleName + ": " + (t.message ?: "unknown"))
|
||||
.toString()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun getPerceptionStateJson(): String = KiwiiRuntimeClientBridge.getPerceptionStateJson()
|
||||
fun getLatestPose2D(): FloatArray = KiwiiRuntimeClientBridge.getLatestPose2D()
|
||||
fun getLatestPose3D(): FloatArray = KiwiiRuntimeClientBridge.getLatestPose3D()
|
||||
@@ -37,28 +145,299 @@ class BridgeRepository {
|
||||
fun getLatestBodyPoseFrameJson(): String = KiwiiRuntimeClientBridge.getLatestBodyPoseFrameJson()
|
||||
|
||||
fun getLeftHandleIMULatest(): FloatArray = KiwiiRuntimeClientBridge.getLeftHandleIMULatest()
|
||||
|
||||
fun getLeftHandleIMUQueue(): Array<FloatArray> {
|
||||
val latest = KiwiiRuntimeClientBridge.getLeftHandleIMULatest()
|
||||
val queue = readHandleImuQueueCompat("getLeftHandleIMUQueue")
|
||||
if (queue.isNotEmpty()) return queue
|
||||
val latest = getLeftHandleIMULatest()
|
||||
return if (latest.isEmpty()) emptyArray() else arrayOf(latest)
|
||||
}
|
||||
|
||||
fun submitLeftStaticEffect(effectId: Int): String = KiwiiRuntimeClientBridge.submitLeftStaticEffect(effectId)
|
||||
fun submitLeftHeStream(streamId: Int, payload: String): String =
|
||||
KiwiiRuntimeClientBridge.submitLeftHeStream(streamId, payload)
|
||||
KiwiiRuntimeClientBridge.submitLeftHeStream(streamId, buildHeStreamPatternJson(streamId, payload))
|
||||
|
||||
fun getRightHandleIMULatest(): FloatArray = KiwiiRuntimeClientBridge.getRightHandleIMULatest()
|
||||
|
||||
fun getRightHandleIMUQueue(): Array<FloatArray> {
|
||||
val latest = KiwiiRuntimeClientBridge.getRightHandleIMULatest()
|
||||
val queue = readHandleImuQueueCompat("getRightHandleIMUQueue")
|
||||
if (queue.isNotEmpty()) return queue
|
||||
val latest = getRightHandleIMULatest()
|
||||
return if (latest.isEmpty()) emptyArray() else arrayOf(latest)
|
||||
}
|
||||
fun submitRightHeStream(streamId: Int, payload: String): String =
|
||||
KiwiiRuntimeClientBridge.submitRightHeStream(streamId, payload)
|
||||
|
||||
fun getHandleStateJson(): String = KiwiiRuntimeClientBridge.getHandleStateJson()
|
||||
fun submitRightStaticEffect(effectId: Int): String = KiwiiRuntimeClientBridge.submitRightStaticEffect(effectId)
|
||||
fun submitRightHeStream(streamId: Int, payload: String): String =
|
||||
KiwiiRuntimeClientBridge.submitRightHeStream(streamId, buildHeStreamPatternJson(streamId, payload))
|
||||
|
||||
fun getHandleStateJson(): String {
|
||||
val json = KiwiiRuntimeClientBridge.getHandleStateJson()
|
||||
cacheHandleStateIfValid(json)
|
||||
return json
|
||||
}
|
||||
|
||||
/**
|
||||
* Phase4B-v11.9: best-effort live HandleState refresh without blocking UI/poller callers.
|
||||
*
|
||||
* Important: some RuntimeHost debug/binder paths can block after long idle. A stuck refresh
|
||||
* must not permanently disable future refresh attempts, so the in-flight flag is allowed to
|
||||
* expire. The cached/last-known snapshot is never cleared on failure.
|
||||
*/
|
||||
fun requestHandleStateRefreshAsync(reason: String = "") {
|
||||
if (!isBound()) return
|
||||
val now = System.currentTimeMillis()
|
||||
val stuck = handleRefreshInFlight.get() &&
|
||||
lastHandleRefreshAttemptMs > 0L &&
|
||||
now - lastHandleRefreshAttemptMs > HANDLE_REFRESH_STUCK_RESET_MS
|
||||
if (stuck) {
|
||||
handleRefreshInFlight.set(false)
|
||||
}
|
||||
if (now - lastHandleRefreshAttemptMs < HANDLE_REFRESH_MIN_INTERVAL_MS) return
|
||||
if (!handleRefreshInFlight.compareAndSet(false, true)) return
|
||||
lastHandleRefreshAttemptMs = now
|
||||
handleRefreshExecutor.execute {
|
||||
try {
|
||||
val json = KiwiiRuntimeClientBridge.getHandleStateJson()
|
||||
cacheHandleStateIfValid(json)
|
||||
} catch (_: Throwable) {
|
||||
// Keep last-known snapshot. Never clear cached handle state on refresh failure.
|
||||
} finally {
|
||||
handleRefreshInFlight.set(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun getCachedRawHandleStateJsonOrUnavailable(): String {
|
||||
val now = System.currentTimeMillis()
|
||||
val cacheAgeMs = if (cachedHandleStateAtMs > 0L) now - cachedHandleStateAtMs else Long.MAX_VALUE
|
||||
return if (cachedHandleStateJson.isNotBlank()) {
|
||||
val obj = parseJsonOrEmpty(cachedHandleStateJson)
|
||||
obj.put("uiPath", "SDK_PANEL_CACHED_HANDLE_STATE")
|
||||
obj.put("cacheAgeMs", if (cacheAgeMs == Long.MAX_VALUE) -1L else cacheAgeMs)
|
||||
obj.put("cacheFresh", cacheAgeMs in 0..HANDLE_CACHE_MAX_AGE_MS)
|
||||
obj.toString()
|
||||
} else {
|
||||
JSONObject()
|
||||
.put("error", "no-cached-handle-state")
|
||||
.put("source", "SDK_Panel.cached-handle-state.v11.18")
|
||||
.put("cacheAgeMs", -1L)
|
||||
.put("cacheFresh", false)
|
||||
.toString()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Phase4B-v11.17: best-effort live Dongle transport refresh without blocking
|
||||
* home-card rendering. This reads RuntimeHost's fast transport-only dongle state;
|
||||
* the cached result is then used by both the home card and readDongleState detail.
|
||||
*/
|
||||
fun requestDongleStateRefreshAsync(reason: String = "") {
|
||||
if (!isBound()) return
|
||||
val now = System.currentTimeMillis()
|
||||
val stuck = dongleRefreshInFlight.get() &&
|
||||
lastDongleRefreshAttemptMs > 0L &&
|
||||
now - lastDongleRefreshAttemptMs > DONGLE_REFRESH_STUCK_RESET_MS
|
||||
if (stuck) {
|
||||
dongleRefreshInFlight.set(false)
|
||||
}
|
||||
if (now - lastDongleRefreshAttemptMs < DONGLE_REFRESH_MIN_INTERVAL_MS) return
|
||||
if (!dongleRefreshInFlight.compareAndSet(false, true)) return
|
||||
lastDongleRefreshAttemptMs = now
|
||||
dongleRefreshExecutor.execute {
|
||||
try {
|
||||
val json = KiwiiRuntimeClientBridge.getDongleStateJson()
|
||||
cacheDongleStateIfValid(json)
|
||||
} catch (_: Throwable) {
|
||||
// Keep last-known dongle state. Never clear cached state on refresh failure.
|
||||
} finally {
|
||||
dongleRefreshInFlight.set(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun getCachedRawDongleStateJsonOrUnavailable(): String {
|
||||
val now = System.currentTimeMillis()
|
||||
val cacheAgeMs = if (cachedDongleStateAtMs > 0L) now - cachedDongleStateAtMs else Long.MAX_VALUE
|
||||
return if (cachedDongleStateJson.isNotBlank()) {
|
||||
val obj = parseJsonOrEmpty(cachedDongleStateJson)
|
||||
obj.put("uiPath", "SDK_PANEL_CACHED_DONGLE_STATE")
|
||||
obj.put("cacheAgeMs", if (cacheAgeMs == Long.MAX_VALUE) -1L else cacheAgeMs)
|
||||
obj.put("cacheFresh", cacheAgeMs in 0..DONGLE_CACHE_MAX_AGE_MS)
|
||||
obj.toString()
|
||||
} else {
|
||||
JSONObject()
|
||||
.put("contractVersion", "kiwii.sdk-panel.cached-dongle-state.v11.17")
|
||||
.put("error", "no-cached-dongle-state")
|
||||
.put("source", "SDK_Panel.cached-dongle-state")
|
||||
.put("cacheAgeMs", -1L)
|
||||
.put("cacheFresh", false)
|
||||
.toString()
|
||||
}
|
||||
}
|
||||
|
||||
private fun cacheDongleStateIfValid(json: String) {
|
||||
if (json.isNotBlank() && !json.contains("\"error\"")) {
|
||||
cachedDongleStateJson = json
|
||||
cachedDongleStateAtMs = System.currentTimeMillis()
|
||||
}
|
||||
}
|
||||
|
||||
private fun cacheHandleStateIfValid(json: String) {
|
||||
if (json.isNotBlank() && !json.contains("\"error\"")) {
|
||||
cachedHandleStateJson = json
|
||||
cachedHandleStateAtMs = System.currentTimeMillis()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Phase4B-v11.9: last-known, no-blocking Handle detail data path.
|
||||
*
|
||||
* Left/Right Handle controls must preserve the three diagnostics users rely on:
|
||||
* 1) IMU latest, 2) IMU queue / ObservationBuffer summary, 3) overall HandleState.
|
||||
* However, the raw AAR methods for latest/queue/state can block after long idle periods.
|
||||
* These safe helpers therefore read only the last-known HandleState cached by
|
||||
* asynchronous refresh and return immediately. They never perform live binder calls.
|
||||
*/
|
||||
fun getCachedHandleStateJsonForUi(side: String = ""): String {
|
||||
val now = System.currentTimeMillis()
|
||||
val cacheAgeMs = if (cachedHandleStateAtMs > 0L) now - cachedHandleStateAtMs else Long.MAX_VALUE
|
||||
val hasLastKnown = cachedHandleStateJson.isNotBlank()
|
||||
val fresh = hasLastKnown && cacheAgeMs <= HANDLE_CACHE_MAX_AGE_MS
|
||||
val handle = if (hasLastKnown) parseJsonOrEmpty(cachedHandleStateJson) else JSONObject()
|
||||
val sideKey = normalizeHandleSide(side)
|
||||
val sideObj = if (sideKey.isNotBlank()) handle.optJSONObject(sideKey) ?: JSONObject() else JSONObject()
|
||||
|
||||
return JSONObject()
|
||||
.put("contractVersion", "kiwii.sdk-panel.handle-last-known-state.v11.9")
|
||||
.put("source", "SDK_Panel.last-known-handle-state")
|
||||
.put("noLiveBinderCall", true)
|
||||
.put("cacheFresh", fresh)
|
||||
.put("cacheStale", hasLastKnown && !fresh)
|
||||
.put("cacheAgeMs", if (cacheAgeMs == Long.MAX_VALUE) -1L else cacheAgeMs)
|
||||
.put("side", sideKey.ifBlank { "both" })
|
||||
.put("sideState", sideObj)
|
||||
.put("handleState", if (hasLastKnown) handle else JSONObject()
|
||||
.put("error", "no-cached-handle-state")
|
||||
.put("detail", "No last-known HandleState yet. Live binder query is intentionally skipped on UI button/state path."))
|
||||
.toString()
|
||||
}
|
||||
|
||||
fun getCachedHandleIMULatestText(side: String): String {
|
||||
val snapshot = cachedHandleSnapshot(side)
|
||||
if (!snapshot.hasLastKnown) {
|
||||
return "NO_CACHED_HANDLE_STATE\n" +
|
||||
"side=${snapshot.side}\n" +
|
||||
"detail=No last-known HandleState yet; live binder query skipped."
|
||||
}
|
||||
val h = snapshot.sideJson
|
||||
val freshness = if (snapshot.cacheFresh) "FRESH" else "STALE"
|
||||
val q = formatJsonArray(h.optJSONArray("quaternion"))
|
||||
val acc = formatJsonArray(h.optJSONArray("accelerationG"))
|
||||
return "IMU Latest (last-known HandleState / $freshness)\n" +
|
||||
"side=${snapshot.side}\n" +
|
||||
"available=${h.optBooleanFlexible("available")} connected=${h.optBooleanFlexible("connected")} streaming=${h.optBooleanFlexible("streaming")}\n" +
|
||||
"seq=${h.optLong("sequenceId", h.optLong("seq", 0L))} dataAgeMs=${h.optLong("dataAgeMs", -1L)} cacheAgeMs=${snapshot.cacheAgeMs}\n" +
|
||||
"latestArrayLength=${h.optInt("latestArrayLength", 0)} source=${h.optString("source", "")}\n" +
|
||||
"q=$q\n" +
|
||||
"accG=$acc"
|
||||
}
|
||||
|
||||
fun getCachedHandleIMUQueueText(side: String): String {
|
||||
val snapshot = cachedHandleSnapshot(side)
|
||||
if (!snapshot.hasLastKnown) {
|
||||
return "NO_CACHED_HANDLE_STATE\n" +
|
||||
"side=${snapshot.side}\n" +
|
||||
"detail=No last-known ObservationBuffer summary yet; live queue query skipped."
|
||||
}
|
||||
val h = snapshot.sideJson
|
||||
val freshness = if (snapshot.cacheFresh) "FRESH" else "STALE"
|
||||
val seq = h.optLong("sequenceId", h.optLong("seq", 0L))
|
||||
val q = formatJsonArray(h.optJSONArray("quaternion"))
|
||||
val acc = formatJsonArray(h.optJSONArray("accelerationG"))
|
||||
return "IMU Queue / ObservationBuffer Summary (last-known / $freshness)\n" +
|
||||
"side=${snapshot.side}\n" +
|
||||
"queueSize=${h.optInt("queueSize", 0)} latestArrayLength=${h.optInt("latestArrayLength", 0)}\n" +
|
||||
"seqLatest=$seq dataAgeMs=${h.optLong("dataAgeMs", -1L)} cacheAgeMs=${snapshot.cacheAgeMs}\n" +
|
||||
"observationBuffer=summary-only; raw frame dump not queried on this UI path\n" +
|
||||
"latest.q=$q\n" +
|
||||
"latest.accG=$acc"
|
||||
}
|
||||
|
||||
private data class CachedHandleSnapshot(
|
||||
val side: String,
|
||||
val hasLastKnown: Boolean,
|
||||
val cacheFresh: Boolean,
|
||||
val cacheAgeMs: Long,
|
||||
val handleJson: JSONObject,
|
||||
val sideJson: JSONObject
|
||||
)
|
||||
|
||||
private fun cachedHandleSnapshot(side: String): CachedHandleSnapshot {
|
||||
val now = System.currentTimeMillis()
|
||||
val cacheAge = if (cachedHandleStateAtMs > 0L) now - cachedHandleStateAtMs else Long.MAX_VALUE
|
||||
val hasLastKnown = cachedHandleStateJson.isNotBlank()
|
||||
val fresh = hasLastKnown && cacheAge <= HANDLE_CACHE_MAX_AGE_MS
|
||||
val handle = if (hasLastKnown) parseJsonOrEmpty(cachedHandleStateJson) else JSONObject()
|
||||
val sideKey = normalizeHandleSide(side)
|
||||
val sideObj = handle.optJSONObject(sideKey) ?: JSONObject()
|
||||
return CachedHandleSnapshot(
|
||||
side = sideKey,
|
||||
hasLastKnown = hasLastKnown,
|
||||
cacheFresh = fresh,
|
||||
cacheAgeMs = if (cacheAge == Long.MAX_VALUE) -1L else cacheAge,
|
||||
handleJson = handle,
|
||||
sideJson = sideObj
|
||||
)
|
||||
}
|
||||
|
||||
private fun normalizeHandleSide(side: String): String {
|
||||
val s = side.trim().lowercase()
|
||||
return when {
|
||||
s.startsWith("l") -> "left"
|
||||
s.startsWith("r") -> "right"
|
||||
else -> s
|
||||
}
|
||||
}
|
||||
|
||||
private fun formatJsonArray(arr: JSONArray?): String {
|
||||
if (arr == null || arr.length() == 0) return "[]"
|
||||
val out = ArrayList<String>()
|
||||
for (i in 0 until arr.length()) {
|
||||
out.add(String.format(java.util.Locale.US, "%.4f", arr.optDouble(i, 0.0)))
|
||||
}
|
||||
return out.joinToString(prefix = "[", postfix = "]")
|
||||
}
|
||||
|
||||
|
||||
fun setMotorWeightKg(weight: Float): com.kiwii.bridge.MotorCommandResult = KiwiiRuntimeClientBridge.setMotorWeightKg(weight)
|
||||
fun setMotorTrainingMode(mode: Int, param: Float): String = KiwiiRuntimeClientBridge.setMotorTrainingMode(mode, param)
|
||||
fun setMotorForceControlParamsJson(paramsJson: String): String {
|
||||
return try {
|
||||
val method = KiwiiRuntimeClientBridge::class.java.getMethod("setMotorForceControlParamsJson", String::class.java)
|
||||
method.invoke(null, paramsJson) as? String ?: "{\"error\":\"setMotorForceControlParamsJson returned null\"}"
|
||||
} catch (t: Throwable) {
|
||||
"{\"error\":\"setMotorForceControlParamsJson unavailable: ${t.message}\"}"
|
||||
}
|
||||
}
|
||||
fun queryMotorTrainingMode(axis: Int): String = KiwiiRuntimeClientBridge.queryMotorTrainingMode(axis)
|
||||
fun getLatestMotorStateJson(): String = KiwiiRuntimeClientBridge.getLatestMotorStateJson()
|
||||
fun getMotorControlStateJson(): String = KiwiiRuntimeClientBridge.getMotorControlStateJson()
|
||||
fun getMotorDisconnectDiagnosisJson(): String {
|
||||
return try {
|
||||
val method = KiwiiRuntimeClientBridge::class.java.getMethod("getMotorDisconnectDiagnosisJson")
|
||||
method.invoke(null) as? String ?: "{\"error\":\"getMotorDisconnectDiagnosisJson returned null\"}"
|
||||
} catch (t: Throwable) {
|
||||
"{\"error\":\"getMotorDisconnectDiagnosisJson unavailable: ${t.message}\"}"
|
||||
}
|
||||
}
|
||||
fun sendMotorHeartbeat(): String {
|
||||
return try {
|
||||
val method = KiwiiRuntimeClientBridge::class.java.getMethod("sendMotorHeartbeat")
|
||||
method.invoke(null) as? String ?: "{\"error\":\"sendMotorHeartbeat returned null\"}"
|
||||
} catch (t: Throwable) {
|
||||
"{\"error\":\"sendMotorHeartbeat unavailable: ${t.message}\"}"
|
||||
}
|
||||
}
|
||||
|
||||
fun getTelemetryStateJson(): String = KiwiiRuntimeClientBridge.getTelemetryStateJson()
|
||||
fun getSafetyStateJson(): String = KiwiiRuntimeClientBridge.getSafetyStateJson()
|
||||
@@ -66,6 +445,290 @@ class BridgeRepository {
|
||||
fun submitDeviceCommandDryRun(command: String): String = KiwiiRuntimeClientBridge.submitDeviceCommandDryRun(command)
|
||||
fun getDeviceCommandStateJson(): String = KiwiiRuntimeClientBridge.getDeviceCommandStateJson()
|
||||
|
||||
|
||||
/**
|
||||
* Phase4B-v11.9 SDK Panel no-blocking detail-state view for Dongle.
|
||||
*
|
||||
* Important design decision: this UI path must NOT call raw getDongleStateJson().
|
||||
* On current RuntimeHost builds that raw dongle query can block behind debug/global
|
||||
* state paths, causing the Dongle detail State panel to disappear and readDongleState
|
||||
* to return only a timeout.
|
||||
*
|
||||
* For the detail page we therefore use the non-blocking HandleState contract as the
|
||||
* operational evidence source and explicitly mark raw dongle slot/transport report as
|
||||
* not queried on this safe UI path. RuntimeHost/SmartBase transport health is still
|
||||
* validated by the home-card availability poll and logcat; this page is a per-component
|
||||
* diagnostic view and must remain responsive.
|
||||
*/
|
||||
fun getDongleDetailStateJson(): String {
|
||||
// Phase4B-v11.17: readDongleState remains zero-blocking, but no longer uses a
|
||||
// fake NOT_QUERIED placeholder as the primary state. The home-card poller keeps a
|
||||
// cached RuntimeHost dongle transport snapshot; this method displays that cached
|
||||
// raw state plus inferred slot evidence from cached Handle/Motor snapshots.
|
||||
requestDongleStateRefreshAsync("read-dongle-state-click")
|
||||
val now = System.currentTimeMillis()
|
||||
val handleCacheAgeMs = if (cachedHandleStateAtMs > 0L) now - cachedHandleStateAtMs else Long.MAX_VALUE
|
||||
val handleRaw = if (cachedHandleStateJson.isNotBlank()) {
|
||||
cachedHandleStateJson
|
||||
} else {
|
||||
JSONObject()
|
||||
.put("error", "no-cached-handle-state")
|
||||
.put("handleCacheAgeMs", if (handleCacheAgeMs == Long.MAX_VALUE) -1L else handleCacheAgeMs)
|
||||
.put("detail", "Safe Dongle detail path uses last-known HandleState only; live binder query skipped to avoid idle timeout.")
|
||||
.toString()
|
||||
}
|
||||
return buildDongleDetailStateJson(
|
||||
getCachedRawDongleStateJsonOrUnavailable(),
|
||||
handleRaw,
|
||||
if (handleCacheAgeMs == Long.MAX_VALUE) -1L else handleCacheAgeMs
|
||||
)
|
||||
}
|
||||
|
||||
fun getDongleSafePlaceholderStateJson(): String = buildSafeDonglePlaceholderJson()
|
||||
|
||||
private fun buildSafeDonglePlaceholderJson(): String {
|
||||
return JSONObject()
|
||||
.put("contractVersion", "kiwii.sdk-panel.dongle-safe-placeholder.v11.9")
|
||||
.put("source", "SDK_Panel.non-blocking-dongle-detail")
|
||||
.put("rawDongleQuery", "disabled-on-detail-ui-path")
|
||||
.put("transport", JSONObject()
|
||||
.put("state", "NOT_QUERIED")
|
||||
.put("rawDongleQuery", "disabled-on-detail-ui-path")
|
||||
.put("detail", "Live raw transport query skipped on no-blocking detail path."))
|
||||
.toString()
|
||||
}
|
||||
|
||||
private fun buildDongleDetailStateJson(dongleRaw: String, handleRaw: String, handleCacheAgeMs: Long): String {
|
||||
val dongle = parseJsonOrEmpty(dongleRaw)
|
||||
val handle = parseJsonOrEmpty(handleRaw)
|
||||
val out = JSONObject()
|
||||
out.put("contractVersion", "kiwii.sdk-panel.dongle-detail-state.v11.17")
|
||||
out.put("source", "SDK_Panel.cached-dongle-and-handle-state-detail")
|
||||
out.put("diagnosticSemantics", "transport-state-first; no-live-binder-call-on-dongle-detail; inferred-slot-report-secondary")
|
||||
out.put("handleCacheAgeMs", handleCacheAgeMs)
|
||||
out.put("handleCacheFresh", handleCacheAgeMs in 0..HANDLE_CACHE_MAX_AGE_MS)
|
||||
out.put("handleCacheStale", handleCacheAgeMs > HANDLE_CACHE_MAX_AGE_MS)
|
||||
out.put("generatedAtMs", System.currentTimeMillis())
|
||||
out.put("dongle", dongle)
|
||||
out.put("handleState", handle)
|
||||
|
||||
val transport = dongle.optJSONObject("transport") ?: JSONObject()
|
||||
out.put("transport", transport)
|
||||
out.put("slots", buildSdkPanelSlots(dongle, handle, handleCacheAgeMs))
|
||||
|
||||
val evidenceNote = buildSlotEvidenceNote(dongle, handle, handleCacheAgeMs)
|
||||
if (evidenceNote.isNotBlank()) out.put("slotEvidenceNote", evidenceNote)
|
||||
return out.toString()
|
||||
}
|
||||
|
||||
private fun buildSdkPanelSlots(dongle: JSONObject, handle: JSONObject, handleCacheAgeMs: Long): JSONArray {
|
||||
val sourceSlots = firstSlotArray(dongle)
|
||||
val slots = JSONArray()
|
||||
val left = handle.optJSONObject("left") ?: JSONObject()
|
||||
val right = handle.optJSONObject("right") ?: JSONObject()
|
||||
val motorSlotEvidence = MotorTelemetrySnapshotCache.dongleSlotEvidenceJson()
|
||||
|
||||
for (slotIndex in 0..3) {
|
||||
val reported = findSlotObject(slotIndex, sourceSlots)
|
||||
val slot = JSONObject()
|
||||
slot.put("slot", slotIndex)
|
||||
|
||||
val inferredHandle = when (slotIndex) {
|
||||
0 -> if (hasFreshHandleSlotEvidence(left, handleCacheAgeMs)) "LEFT_HANDLE" else ""
|
||||
1 -> if (hasFreshHandleSlotEvidence(right, handleCacheAgeMs)) "RIGHT_HANDLE" else ""
|
||||
else -> ""
|
||||
}
|
||||
|
||||
if (slotIndex == 3 && motorSlotEvidence != null) {
|
||||
val keys = motorSlotEvidence.keys()
|
||||
while (keys.hasNext()) {
|
||||
val key = keys.next()
|
||||
slot.put(key, motorSlotEvidence.opt(key))
|
||||
}
|
||||
} else if (inferredHandle.isNotBlank()) {
|
||||
val handleObj = if (slotIndex == 0) left else right
|
||||
slot.put("state", "CONNECTED")
|
||||
slot.put("connected", true)
|
||||
slot.put("device", inferredHandle)
|
||||
slot.put("source", "handle-state-fresh-inferred")
|
||||
slot.put("inferred", true)
|
||||
slot.put("sequenceId", handleObj.optLong("sequenceId", handleObj.optLong("seq", 0L)))
|
||||
slot.put("dataAgeMs", handleObj.optLong("dataAgeMs", -1L))
|
||||
slot.put("queueSize", handleObj.optInt("queueSize", 0))
|
||||
slot.put("stale", handleCacheAgeMs > HANDLE_CACHE_MAX_AGE_MS)
|
||||
slot.put("evidenceAgeMs", handleCacheAgeMs)
|
||||
val reportedState = reported?.optString("state", reported.optString("status", "")) ?: ""
|
||||
val rawSlotReport = when {
|
||||
reported == null -> if (dongle.optString("rawDongleQuery", "") == "disabled-on-detail-ui-path") "not-queried" else "missing"
|
||||
reportedState.isBlank() -> "present-without-state"
|
||||
reportedState.equals("CONNECTED", ignoreCase = true) -> "connected"
|
||||
else -> reportedState.lowercase()
|
||||
}
|
||||
slot.put("rawSlotReport", rawSlotReport)
|
||||
if (reportedState.isNotBlank() && !reportedState.equals("CONNECTED", ignoreCase = true)) {
|
||||
slot.put("detail", "Connected via fresh handle-state; rawSlot=$rawSlotReport")
|
||||
} else if (reported == null) {
|
||||
slot.put("detail", "Connected via fresh handle-state; rawSlot=$rawSlotReport")
|
||||
} else {
|
||||
slot.put("detail", "Connected via fresh handle-state")
|
||||
}
|
||||
} else if (reported != null) {
|
||||
val connected = reported.optBooleanFlexible("connected") ||
|
||||
reported.optBooleanFlexible("available") ||
|
||||
reported.optBooleanFlexible("active")
|
||||
val state = firstNonBlank(
|
||||
reported.optString("state", ""),
|
||||
reported.optString("status", ""),
|
||||
if (connected) "CONNECTED" else "DISCONNECTED"
|
||||
)
|
||||
slot.put("state", state)
|
||||
slot.put("connected", connected)
|
||||
slot.put("source", "dongle-slot-report")
|
||||
slot.put("inferred", false)
|
||||
copyIfPresent(reported, slot, "dev")
|
||||
copyIfPresent(reported, slot, "device")
|
||||
copyIfPresent(reported, slot, "deviceType")
|
||||
copyIfPresent(reported, slot, "deviceId")
|
||||
copyIfPresent(reported, slot, "sequenceId")
|
||||
copyIfPresent(reported, slot, "seq")
|
||||
copyIfPresent(reported, slot, "dataAgeMs")
|
||||
copyIfPresent(reported, slot, "ageMs")
|
||||
slot.put("detail", "Reported by dongle JSON")
|
||||
} else {
|
||||
slot.put("state", "UNKNOWN")
|
||||
slot.put("connected", false)
|
||||
slot.put("source", "missing-slot-report")
|
||||
slot.put("inferred", false)
|
||||
slot.put("detail", if (dongle.optString("rawDongleQuery", "") == "disabled-on-detail-ui-path") "Raw slot skipped" else "No raw slot report")
|
||||
}
|
||||
|
||||
slots.put(slot)
|
||||
}
|
||||
return slots
|
||||
}
|
||||
|
||||
private fun buildSlotEvidenceNote(dongle: JSONObject, handle: JSONObject, handleCacheAgeMs: Long): String {
|
||||
val sourceSlots = firstSlotArray(dongle)
|
||||
val right = handle.optJSONObject("right") ?: JSONObject()
|
||||
val rightFresh = hasFreshHandleSlotEvidence(right, handleCacheAgeMs)
|
||||
val reportedSlot1 = findSlotObject(1, sourceSlots)
|
||||
val reportedSlot1Connected = reportedSlot1?.let {
|
||||
it.optBooleanFlexible("connected") || it.optBooleanFlexible("available") || it.optBooleanFlexible("active") ||
|
||||
it.optString("state", "").equals("CONNECTED", ignoreCase = true) ||
|
||||
it.optString("status", "").equals("CONNECTED", ignoreCase = true)
|
||||
} ?: false
|
||||
val notes = mutableListOf<String>()
|
||||
if (rightFresh && !reportedSlot1Connected) notes += "Slot 1 inferred from cached Right Handle data."
|
||||
if (MotorTelemetrySnapshotCache.dongleSlotEvidenceJson() != null) notes += "Slot 3 inferred from explicit Motor runtime state."
|
||||
return notes.joinToString(" ")
|
||||
}
|
||||
|
||||
private fun firstSlotArray(obj: JSONObject): JSONArray? {
|
||||
obj.optJSONArray("slots")?.let { return it }
|
||||
obj.optJSONArray("slotStatus")?.let { return it }
|
||||
obj.optJSONArray("slotStates")?.let { return it }
|
||||
obj.optJSONObject("dongle")?.optJSONArray("slots")?.let { return it }
|
||||
obj.optJSONObject("status")?.optJSONArray("slots")?.let { return it }
|
||||
return null
|
||||
}
|
||||
|
||||
private fun findSlotObject(slotIndex: Int, slots: JSONArray?): JSONObject? {
|
||||
if (slots == null) return null
|
||||
for (i in 0 until slots.length()) {
|
||||
val obj = slots.optJSONObject(i) ?: continue
|
||||
val reportedIndex = obj.optIntOrNull("slot") ?: obj.optIntOrNull("slotId") ?: obj.optIntOrNull("index")
|
||||
if (reportedIndex == slotIndex) return obj
|
||||
}
|
||||
return slots.optJSONObject(slotIndex)
|
||||
}
|
||||
|
||||
private fun hasFreshHandleSlotEvidence(handle: JSONObject, handleCacheAgeMs: Long): Boolean {
|
||||
val available = handle.optBooleanFlexible("available")
|
||||
val connected = handle.optBooleanFlexible("connected")
|
||||
val streaming = handle.optBooleanFlexible("streaming")
|
||||
val seq = handle.optLong("sequenceId", handle.optLong("seq", 0L))
|
||||
val queueSize = handle.optInt("queueSize", 0)
|
||||
val dataAgeMs = handle.optLong("dataAgeMs", Long.MAX_VALUE)
|
||||
val cacheFresh = handleCacheAgeMs in 0..HANDLE_CACHE_MAX_AGE_MS
|
||||
val dataFresh = dataAgeMs in 0..HANDLE_CACHE_MAX_AGE_MS
|
||||
return cacheFresh && dataFresh && (available || connected || streaming) && seq > 0L && queueSize > 0
|
||||
}
|
||||
|
||||
private fun parseJsonOrEmpty(raw: String): JSONObject {
|
||||
return try {
|
||||
JSONObject(raw)
|
||||
} catch (_: Throwable) {
|
||||
JSONObject().put("raw", raw.take(500))
|
||||
}
|
||||
}
|
||||
|
||||
private fun copyIfPresent(src: JSONObject, dst: JSONObject, key: String) {
|
||||
if (src.has(key)) dst.put(key, src.opt(key))
|
||||
}
|
||||
|
||||
private fun JSONObject.optBooleanFlexible(key: String): Boolean {
|
||||
if (!has(key)) return false
|
||||
val raw = opt(key) ?: return false
|
||||
return when (raw) {
|
||||
is Boolean -> raw
|
||||
is Number -> raw.toInt() != 0
|
||||
is String -> raw.equals("true", ignoreCase = true) || raw == "1" || raw.equals("yes", ignoreCase = true) || raw.equals("connected", ignoreCase = true) || raw.equals("active", ignoreCase = true) || raw.equals("running", ignoreCase = true)
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
private fun JSONObject.optIntOrNull(key: String): Int? {
|
||||
if (!has(key)) return null
|
||||
return try { optInt(key) } catch (_: Throwable) { null }
|
||||
}
|
||||
|
||||
private fun firstNonBlank(vararg values: String): String = values.firstOrNull { it.isNotBlank() } ?: ""
|
||||
|
||||
private fun escapeJson(value: String): String = value.replace("\\", "\\\\").replace("\"", "\\\"")
|
||||
|
||||
|
||||
private fun readHandleImuQueueCompat(methodName: String): Array<FloatArray> {
|
||||
return try {
|
||||
val method = KiwiiRuntimeClientBridge::class.java.getMethod(methodName)
|
||||
when (val value = method.invoke(null)) {
|
||||
is Array<*> -> {
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
value.filterIsInstance<FloatArray>().toTypedArray()
|
||||
}
|
||||
is FloatArray -> splitFlatImuQueue(value)
|
||||
else -> emptyArray()
|
||||
}
|
||||
} catch (_: Throwable) {
|
||||
emptyArray()
|
||||
}
|
||||
}
|
||||
|
||||
private fun splitFlatImuQueue(flat: FloatArray): Array<FloatArray> {
|
||||
if (flat.isEmpty()) return emptyArray()
|
||||
val sampleSize = when {
|
||||
flat.size % 10 == 0 -> 10
|
||||
flat.size % 9 == 0 -> 9
|
||||
flat.size % 7 == 0 -> 7
|
||||
else -> flat.size
|
||||
}
|
||||
if (sampleSize <= 0) return emptyArray()
|
||||
val out = ArrayList<FloatArray>()
|
||||
var offset = 0
|
||||
while (offset < flat.size) {
|
||||
val end = minOf(offset + sampleSize, flat.size)
|
||||
out.add(flat.copyOfRange(offset, end))
|
||||
offset = end
|
||||
}
|
||||
return out.toTypedArray()
|
||||
}
|
||||
|
||||
private fun buildHeStreamPatternJson(streamId: Int, payload: String): String {
|
||||
val trimmed = payload.trim()
|
||||
if (trimmed.startsWith("{")) return trimmed
|
||||
val escaped = payload.replace("\\", "\\\\").replace("\"", "\\\"")
|
||||
return "{\"streamId\":$streamId,\"payload\":\"$escaped\"}"
|
||||
}
|
||||
|
||||
suspend fun <T> callAsync(block: () -> T): OperationResult<T> = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val result = block()
|
||||
|
||||
@@ -6,6 +6,7 @@ import com.kiwii.controlpanel.logging.SessionLogger
|
||||
import com.kiwii.controlpanel.model.ComponentCategory
|
||||
import com.kiwii.controlpanel.model.ComponentState
|
||||
import com.kiwii.controlpanel.model.ComponentType
|
||||
import com.kiwii.controlpanel.ui.components.MotorTelemetrySnapshotCache
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
@@ -26,20 +27,106 @@ class ComponentRegistry(
|
||||
private var previousStates = emptyMap<ComponentType, ComponentState>()
|
||||
|
||||
private companion object {
|
||||
const val MOTOR_TELEMETRY_FRESH_TIMEOUT_MS = 5000L
|
||||
const val TAG = "KiwiiSDKPanelState"
|
||||
const val HANDLE_DATA_AGE_FRESH_TIMEOUT_MS = 1500L
|
||||
const val HANDLE_SEQUENCE_PROGRESS_TIMEOUT_MS = 2500L
|
||||
const val DONGLE_SEQUENCE_PROGRESS_TIMEOUT_MS = 2500L
|
||||
const val DONGLE_TRANSPORT_FRESH_TIMEOUT_MS = 3_000L
|
||||
const val MOTOR_STATUS_FRESH_TIMEOUT_MS = 5_000L
|
||||
const val SLOT_STATUS_FRESH_TIMEOUT_MS = 5_000L
|
||||
const val DONGLE_RULE = "REQUIRE_FRESH_SMARTBASE_USB_TRANSPORT"
|
||||
}
|
||||
|
||||
// Motor is physically downstream of the SmartBase Dongle.
|
||||
// Keep the latest Dongle card decision from the same detection loop so Motor cannot remain green
|
||||
// after the Dongle transport is disconnected, while preserving v4 Dongle detection behavior.
|
||||
private data class SlotSignal(
|
||||
val slot: Int = -1,
|
||||
val dev: Int = 0,
|
||||
val name: String = "",
|
||||
val state: String = "",
|
||||
val connected: Boolean = false,
|
||||
val lastSeenAgeMs: Long = Long.MAX_VALUE,
|
||||
val source: String = ""
|
||||
) {
|
||||
val freshConnected: Boolean
|
||||
get() = connected && lastSeenAgeMs in 0..5_000L
|
||||
}
|
||||
|
||||
private data class HandleSignal(
|
||||
val side: String,
|
||||
val available: Boolean = false,
|
||||
val connected: Boolean = false,
|
||||
val streaming: Boolean = false,
|
||||
val sequenceId: Long = 0L,
|
||||
val dataAgeMs: Long = -1L,
|
||||
val queueSize: Int = 0,
|
||||
val health: String = "",
|
||||
val source: String = "",
|
||||
val slot: SlotSignal = SlotSignal()
|
||||
)
|
||||
|
||||
private data class DongleSignal(
|
||||
val valid: Boolean = false,
|
||||
val active: Boolean = false,
|
||||
val usbPresent: Boolean = false,
|
||||
val usbBridgeRegistered: Boolean = false,
|
||||
val readLoopRunning: Boolean = false,
|
||||
val stale: Boolean = true,
|
||||
val dataStale: Boolean = true,
|
||||
val lastUsbInAgeMs: Long = Long.MAX_VALUE,
|
||||
val cacheAgeMs: Long = Long.MAX_VALUE,
|
||||
val state: String = "",
|
||||
val source: String = "",
|
||||
val evidence: String = ""
|
||||
)
|
||||
|
||||
private data class HandleDashboardSignal(
|
||||
val valid: Boolean,
|
||||
val left: HandleSignal = HandleSignal("left"),
|
||||
val right: HandleSignal = HandleSignal("right"),
|
||||
val dongleStateLocated: Boolean = false,
|
||||
val observationBufferLocated: Boolean = false,
|
||||
val dongle: DongleSignal = DongleSignal(),
|
||||
val motorSlot: SlotSignal = SlotSignal(slot = 3, dev = 0x31, name = "MOTOR_POWER"),
|
||||
val leftProgressAgeMs: Long = Long.MAX_VALUE,
|
||||
val rightProgressAgeMs: Long = Long.MAX_VALUE,
|
||||
val dongleProgressAgeMs: Long = Long.MAX_VALUE,
|
||||
val handleCacheAgeMs: Long = Long.MAX_VALUE
|
||||
)
|
||||
|
||||
@Volatile
|
||||
private var latestDongleCardStateForMotorGate: ComponentState = ComponentState.GREY
|
||||
|
||||
@Volatile
|
||||
private var latestHandleSignalsForMotorSlot: SlotSignal? = null
|
||||
|
||||
private var lastLeftSequenceId: Long = 0L
|
||||
private var lastRightSequenceId: Long = 0L
|
||||
private var lastLeftSequenceProgressWallMs: Long = 0L
|
||||
private var lastRightSequenceProgressWallMs: Long = 0L
|
||||
private var lastDongleSequenceProgressWallMs: Long = 0L
|
||||
|
||||
fun startDetection() {
|
||||
scope.launch(Dispatchers.IO) {
|
||||
while (isActive) {
|
||||
val result = ComponentType.entries.associateWith { checkAvailability(it) }
|
||||
// 检测状态变化,记录日志
|
||||
val bound = repo.isBound()
|
||||
if (bound) {
|
||||
repo.requestHandleStateRefreshAsync("availability-poll")
|
||||
repo.requestDongleStateRefreshAsync("availability-poll")
|
||||
MotorTelemetrySnapshotCache.requestRuntimeStateRefreshAsync(repo, "availability-poll")
|
||||
}
|
||||
val handleJson = if (bound) repo.getCachedRawHandleStateJsonOrUnavailable() else "{\"error\":\"NOT_BOUND\"}"
|
||||
// Phase4B-v11.9: home-card availability must be cold-start safe and never block on
|
||||
// RuntimeHost debug/binder reads. Camera/Dongle/Telemetry home cards use binder-bound
|
||||
// runtime availability; detailed state buttons remain no-blocking/last-known.
|
||||
val runtimeStats = FloatArray(0)
|
||||
val cameraJson = if (bound) "{\"contractVersion\":\"kiwii.sdk-panel.camera-bound-placeholder.v11.9\",\"state\":\"BOUND_RUNTIME\",\"running\":true}" else "{\"error\":\"NOT_BOUND\"}"
|
||||
val dongleJson = if (bound) repo.getCachedRawDongleStateJsonOrUnavailable() else "{\"error\":\"NOT_BOUND\"}"
|
||||
val handleSignals = updateHandleSignals(bound, handleJson, dongleJson)
|
||||
|
||||
val result = ComponentType.entries.associateWith { type ->
|
||||
checkAvailability(type, bound, handleJson, runtimeStats, cameraJson, handleSignals)
|
||||
}
|
||||
|
||||
logDashboardSummary(bound, result, handleSignals, runtimeStats, cameraJson)
|
||||
logStateChanges(previousStates, result)
|
||||
previousStates = result
|
||||
_availability.value = result
|
||||
@@ -48,6 +135,292 @@ class ComponentRegistry(
|
||||
}
|
||||
}
|
||||
|
||||
private fun updateHandleSignals(bound: Boolean, handleJson: String, dongleJson: String): HandleDashboardSignal {
|
||||
val now = System.currentTimeMillis()
|
||||
val dongle = parseDongleSignal(bound, dongleJson)
|
||||
if (!bound || isUnavailable(handleJson)) {
|
||||
latestHandleSignalsForMotorSlot = SlotSignal(slot = 3, dev = 0x31, name = "MOTOR_POWER", source = "handle-unavailable")
|
||||
return HandleDashboardSignal(
|
||||
valid = false,
|
||||
dongle = dongle,
|
||||
leftProgressAgeMs = ageSince(now, lastLeftSequenceProgressWallMs),
|
||||
rightProgressAgeMs = ageSince(now, lastRightSequenceProgressWallMs),
|
||||
dongleProgressAgeMs = ageSince(now, lastDongleSequenceProgressWallMs)
|
||||
)
|
||||
}
|
||||
return try {
|
||||
val obj = JSONObject(handleJson)
|
||||
val handleCacheAgeMs = obj.optLong("cacheAgeMs", Long.MAX_VALUE)
|
||||
val slots = obj.optJSONArray("dongleSlots")
|
||||
val leftSlot = parseSlotSignal(slots, 0, 0x11, "LEFT_HANDLE")
|
||||
val rightSlot = parseSlotSignal(slots, 1, 0x12, "RIGHT_HANDLE")
|
||||
val motorSlot = parseSlotSignal(slots, 3, 0x31, "MOTOR_POWER")
|
||||
latestHandleSignalsForMotorSlot = motorSlot
|
||||
val left = parseHandleSignal("left", obj.optJSONObject("left"), leftSlot)
|
||||
val right = parseHandleSignal("right", obj.optJSONObject("right"), rightSlot)
|
||||
|
||||
val leftProgress = updateSequenceProgress(
|
||||
side = "left",
|
||||
sequenceId = left.sequenceId,
|
||||
hasLiveFlags = left.available || left.connected || left.streaming,
|
||||
now = now
|
||||
)
|
||||
val rightProgress = updateSequenceProgress(
|
||||
side = "right",
|
||||
sequenceId = right.sequenceId,
|
||||
hasLiveFlags = right.available || right.connected || right.streaming,
|
||||
now = now
|
||||
)
|
||||
if (leftProgress || rightProgress) {
|
||||
lastDongleSequenceProgressWallMs = now
|
||||
}
|
||||
|
||||
HandleDashboardSignal(
|
||||
valid = true,
|
||||
left = left,
|
||||
right = right,
|
||||
dongleStateLocated = obj.optBoolean("dongleStateLocated", obj.optJSONObject("debugTrace")?.optBoolean("dongleStateLocated", false) ?: false),
|
||||
observationBufferLocated = obj.optBoolean("observationBufferLocated", obj.optJSONObject("debugTrace")?.optBoolean("observationBufferLocated", false) ?: false),
|
||||
dongle = dongle,
|
||||
motorSlot = motorSlot,
|
||||
leftProgressAgeMs = ageSince(now, lastLeftSequenceProgressWallMs),
|
||||
rightProgressAgeMs = ageSince(now, lastRightSequenceProgressWallMs),
|
||||
dongleProgressAgeMs = ageSince(now, lastDongleSequenceProgressWallMs),
|
||||
handleCacheAgeMs = handleCacheAgeMs
|
||||
)
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "updateHandleSignals exception: ${t.message}")
|
||||
latestHandleSignalsForMotorSlot = SlotSignal(slot = 3, dev = 0x31, name = "MOTOR_POWER", source = "parse-exception")
|
||||
HandleDashboardSignal(
|
||||
valid = false,
|
||||
dongle = dongle,
|
||||
leftProgressAgeMs = ageSince(now, lastLeftSequenceProgressWallMs),
|
||||
rightProgressAgeMs = ageSince(now, lastRightSequenceProgressWallMs),
|
||||
dongleProgressAgeMs = ageSince(now, lastDongleSequenceProgressWallMs)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseHandleSignal(side: String, obj: JSONObject?, fallbackSlot: SlotSignal = SlotSignal()): HandleSignal {
|
||||
if (obj == null) return HandleSignal(side, slot = fallbackSlot)
|
||||
val embeddedSlot = SlotSignal(
|
||||
slot = obj.optInt("slot", fallbackSlot.slot),
|
||||
dev = obj.optInt("slotDev", fallbackSlot.dev),
|
||||
name = firstNonBlank(obj.optString("slotName", ""), fallbackSlot.name),
|
||||
state = firstNonBlank(obj.optString("slotState", ""), fallbackSlot.state),
|
||||
connected = obj.optBoolean("slotConnected", fallbackSlot.connected),
|
||||
lastSeenAgeMs = firstNonNegativeLong(obj.optLong("slotLastSeenAgeMs", Long.MIN_VALUE), fallbackSlot.lastSeenAgeMs),
|
||||
source = "handleState.embeddedSlot"
|
||||
)
|
||||
return HandleSignal(
|
||||
side = side,
|
||||
available = obj.optBoolean("available", false),
|
||||
connected = obj.optBoolean("connected", false),
|
||||
streaming = obj.optBoolean("streaming", false),
|
||||
sequenceId = obj.optLong("sequenceId", 0L),
|
||||
dataAgeMs = obj.optLong("dataAgeMs", -1L),
|
||||
queueSize = obj.optInt("queueSize", 0),
|
||||
health = obj.optString("health", ""),
|
||||
source = obj.optString("source", ""),
|
||||
slot = if (embeddedSlot.slot >= 0) embeddedSlot else fallbackSlot
|
||||
)
|
||||
}
|
||||
|
||||
private fun parseSlotSignal(slots: org.json.JSONArray?, expectedSlot: Int, expectedDev: Int, expectedName: String): SlotSignal {
|
||||
if (slots == null) return SlotSignal(slot = expectedSlot, dev = expectedDev, name = expectedName, source = "no-slots")
|
||||
for (i in 0 until slots.length()) {
|
||||
val obj = slots.optJSONObject(i) ?: continue
|
||||
val slot = obj.optInt("slot", -1)
|
||||
val dev = obj.optInt("dev", 0)
|
||||
val name = obj.optString("name", "")
|
||||
if (slot == expectedSlot || dev == expectedDev || name.equals(expectedName, ignoreCase = true)) {
|
||||
val state = obj.optString("state", "")
|
||||
return SlotSignal(
|
||||
slot = slot.takeIf { it >= 0 } ?: expectedSlot,
|
||||
dev = dev.takeIf { it != 0 } ?: expectedDev,
|
||||
name = firstNonBlank(name, expectedName),
|
||||
state = state,
|
||||
connected = state.equals("CONNECTED", ignoreCase = true) ||
|
||||
state.equals("CONNECTING", ignoreCase = true) ||
|
||||
state.equals("DISCOVERED", ignoreCase = true) ||
|
||||
obj.optBoolean("connected", false),
|
||||
lastSeenAgeMs = obj.optLong("lastSeenAgeMs", Long.MAX_VALUE),
|
||||
source = "handleState.dongleSlots"
|
||||
)
|
||||
}
|
||||
}
|
||||
return SlotSignal(slot = expectedSlot, dev = expectedDev, name = expectedName, source = "slot-not-found")
|
||||
}
|
||||
|
||||
|
||||
|
||||
private fun parseDongleSignal(bound: Boolean, json: String): DongleSignal {
|
||||
if (!bound || isUnavailable(json)) {
|
||||
return DongleSignal(valid = false, source = "unavailable")
|
||||
}
|
||||
return try {
|
||||
val obj = JSONObject(json)
|
||||
val transport = obj.optJSONObject("transport") ?: obj
|
||||
val state = firstNonBlank(
|
||||
transport.optString("state", ""),
|
||||
obj.optString("state", ""),
|
||||
obj.optString("transportState", "")
|
||||
)
|
||||
val usbPresent = boolAny(
|
||||
transport.optBoolean("usbPresent", false),
|
||||
transport.optBoolean("devicePresent", false),
|
||||
transport.optBoolean("attached", false),
|
||||
obj.optBoolean("usbPresent", false),
|
||||
obj.optBoolean("devicePresent", false),
|
||||
obj.optBoolean("attached", false)
|
||||
)
|
||||
val usbBridgeRegistered = boolAny(
|
||||
transport.optBoolean("usbBridgeRegistered", false),
|
||||
transport.optBoolean("bridgeRegistered", false),
|
||||
obj.optBoolean("usbBridgeRegistered", false),
|
||||
obj.optBoolean("bridgeRegistered", false)
|
||||
)
|
||||
val readLoopRunning = boolAny(
|
||||
transport.optBoolean("readLoopRunning", false),
|
||||
transport.optBoolean("bulkInRunning", false),
|
||||
transport.optBoolean("running", false),
|
||||
obj.optBoolean("readLoopRunning", false)
|
||||
)
|
||||
val activeFlags = boolAny(
|
||||
obj.optBoolean("active", false),
|
||||
obj.optBoolean("available", false),
|
||||
obj.optBoolean("connected", false),
|
||||
transport.optBoolean("active", false),
|
||||
transport.optBoolean("available", false),
|
||||
transport.optBoolean("connected", false),
|
||||
transport.optBoolean("usbConnected", false),
|
||||
transport.optBoolean("opened", false),
|
||||
transport.optBoolean("open", false),
|
||||
transport.optBoolean("isOpen", false)
|
||||
)
|
||||
val stale = boolAny(
|
||||
obj.optBoolean("stale", false),
|
||||
obj.optBoolean("dataStale", false),
|
||||
transport.optBoolean("stale", false),
|
||||
transport.optBoolean("dataStale", false)
|
||||
)
|
||||
val dataStale = boolAny(
|
||||
obj.optBoolean("dataStale", false),
|
||||
transport.optBoolean("dataStale", false)
|
||||
)
|
||||
val lastUsbInAgeMs = firstNonNegativeLong(
|
||||
transport.optLong("lastUsbInAgeMs", Long.MIN_VALUE),
|
||||
obj.optLong("lastUsbInAgeMs", Long.MIN_VALUE)
|
||||
)
|
||||
val cacheAgeMs = obj.optLong("cacheAgeMs", Long.MAX_VALUE)
|
||||
val stateActive = state.equals("CONNECTED", ignoreCase = true) ||
|
||||
state.equals("RUNNING", ignoreCase = true) ||
|
||||
state.equals("OPEN", ignoreCase = true) ||
|
||||
state.equals("OPENED", ignoreCase = true) ||
|
||||
state.equals("ACTIVE", ignoreCase = true) ||
|
||||
state.equals("READY", ignoreCase = true)
|
||||
|
||||
val usbTrafficFresh = lastUsbInAgeMs in 0..DONGLE_TRANSPORT_FRESH_TIMEOUT_MS
|
||||
val cacheFresh = cacheAgeMs == Long.MAX_VALUE || cacheAgeMs in 0..DONGLE_TRANSPORT_FRESH_TIMEOUT_MS
|
||||
val effectiveStale = stale || !cacheFresh || !usbTrafficFresh
|
||||
val effectiveDataStale = dataStale || !cacheFresh || !usbTrafficFresh
|
||||
val active = usbPresent &&
|
||||
usbBridgeRegistered &&
|
||||
readLoopRunning &&
|
||||
(activeFlags || stateActive) &&
|
||||
!effectiveStale &&
|
||||
usbTrafficFresh &&
|
||||
cacheFresh
|
||||
DongleSignal(
|
||||
valid = true,
|
||||
active = active,
|
||||
usbPresent = usbPresent,
|
||||
usbBridgeRegistered = usbBridgeRegistered,
|
||||
readLoopRunning = readLoopRunning,
|
||||
stale = effectiveStale,
|
||||
dataStale = effectiveDataStale,
|
||||
lastUsbInAgeMs = lastUsbInAgeMs,
|
||||
cacheAgeMs = cacheAgeMs,
|
||||
state = state,
|
||||
source = obj.optString("source", "getDongleStateJson"),
|
||||
evidence = "usbPresent=$usbPresent bridge=$usbBridgeRegistered readLoop=$readLoopRunning activeFlags=$activeFlags state=$state rawStale=$stale rawDataStale=$dataStale effectiveStale=$effectiveStale lastUsbInAgeMs=${printAge(lastUsbInAgeMs)} cacheAgeMs=${printAge(cacheAgeMs)}"
|
||||
)
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "parseDongleSignal exception: ${t.message}")
|
||||
DongleSignal(valid = false, source = "parse-exception", evidence = t.message ?: "unknown")
|
||||
}
|
||||
}
|
||||
|
||||
private fun boolAny(vararg values: Boolean?): Boolean = values.any { it == true }
|
||||
|
||||
private fun firstNonBlank(vararg values: String?): String {
|
||||
return values.firstOrNull { !it.isNullOrBlank() } ?: ""
|
||||
}
|
||||
|
||||
private fun firstNonNegativeLong(vararg values: Long): Long {
|
||||
return values.firstOrNull { it >= 0L } ?: Long.MAX_VALUE
|
||||
}
|
||||
|
||||
private fun updateSequenceProgress(side: String, sequenceId: Long, hasLiveFlags: Boolean, now: Long): Boolean {
|
||||
if (!hasLiveFlags || sequenceId <= 0L) return false
|
||||
return when (side) {
|
||||
"left" -> {
|
||||
val changed = sequenceId != lastLeftSequenceId
|
||||
if (changed) {
|
||||
lastLeftSequenceId = sequenceId
|
||||
lastLeftSequenceProgressWallMs = now
|
||||
}
|
||||
changed
|
||||
}
|
||||
"right" -> {
|
||||
val changed = sequenceId != lastRightSequenceId
|
||||
if (changed) {
|
||||
lastRightSequenceId = sequenceId
|
||||
lastRightSequenceProgressWallMs = now
|
||||
}
|
||||
changed
|
||||
}
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
private fun ageSince(now: Long, last: Long): Long {
|
||||
return if (last <= 0L) Long.MAX_VALUE else now - last
|
||||
}
|
||||
|
||||
private fun logDashboardSummary(
|
||||
bound: Boolean,
|
||||
states: Map<ComponentType, ComponentState>,
|
||||
handles: HandleDashboardSignal,
|
||||
runtimeStats: FloatArray,
|
||||
cameraJson: String
|
||||
) {
|
||||
val statsActive = runtimeStats.any { !it.isNaN() && !it.isInfinite() && it > 0.1f }
|
||||
val camera = runCatching { JSONObject(cameraJson) }.getOrNull()
|
||||
val cameraRunning = camera?.optBoolean("running", false) == true || camera?.optString("state", "") == "RUNNING"
|
||||
val imxOpen = camera?.optBoolean("imx415OpenSucceeded", false) == true ||
|
||||
camera?.optJSONObject("realInternalCameraPipeline")?.optBoolean("imx415OpenSucceeded", false) == true
|
||||
|
||||
Log.i(
|
||||
TAG,
|
||||
"Phase4B-v11.9 dashboard availability; bound=$bound; " +
|
||||
"camera=${states[ComponentType.CAMERA]}; right=${states[ComponentType.RIGHT_HANDLE]}; " +
|
||||
"dongle=${states[ComponentType.DONGLE]}; telemetry=${states[ComponentType.TELEMETRY_SAFETY]}; motor=${states[ComponentType.MOTOR]}; " +
|
||||
"right.available=${handles.right.available}; right.connected=${handles.right.connected}; right.streaming=${handles.right.streaming}; " +
|
||||
"right.seq=${handles.right.sequenceId}; right.dataAgeMs=${handles.right.dataAgeMs}; right.progressAgeMs=${printAge(handles.rightProgressAgeMs)}; right.cacheAgeMs=${printAge(handles.handleCacheAgeMs)}; " +
|
||||
"right.slotState=${handles.right.slot.state}; right.slotConnected=${handles.right.slot.connected}; right.slotAgeMs=${printAge(handles.right.slot.lastSeenAgeMs)}; " +
|
||||
"motor.slotState=${handles.motorSlot.state}; motor.slotConnected=${handles.motorSlot.connected}; motor.slotAgeMs=${printAge(handles.motorSlot.lastSeenAgeMs)}; " +
|
||||
"dongleStateLocated=${handles.dongleStateLocated}; observationBufferLocated=${handles.observationBufferLocated}; dongle.progressAgeMs=${printAge(handles.dongleProgressAgeMs)}; " +
|
||||
"dongle.usbActive=${handles.dongle.active}; dongle.usbPresent=${handles.dongle.usbPresent}; dongle.bridge=${handles.dongle.usbBridgeRegistered}; dongle.readLoop=${handles.dongle.readLoopRunning}; dongle.transportState=${handles.dongle.state}; " +
|
||||
"dongle.stale=${handles.dongle.stale}; dongle.dataStale=${handles.dongle.dataStale}; dongle.lastUsbInAgeMs=${printAge(handles.dongle.lastUsbInAgeMs)}; dongle.cacheAgeMs=${printAge(handles.dongle.cacheAgeMs)}; " +
|
||||
"statsActive=$statsActive; cameraRunning=$cameraRunning; imx415OpenSucceeded=$imxOpen; rule=$DONGLE_RULE"
|
||||
)
|
||||
}
|
||||
|
||||
private fun printAge(age: Long): String {
|
||||
return if (age == Long.MAX_VALUE) "NA" else age.toString()
|
||||
}
|
||||
|
||||
private fun logStateChanges(
|
||||
old: Map<ComponentType, ComponentState>,
|
||||
new: Map<ComponentType, ComponentState>
|
||||
@@ -64,168 +437,164 @@ class ComponentRegistry(
|
||||
result = "${oldState.name} -> ${newState.name}",
|
||||
isStateChange = true
|
||||
))
|
||||
Log.i(TAG, "Phase4B-v11.9 availability_change; component=${type.name}; ${oldState.name}->${newState.name}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun checkAvailability(type: ComponentType): ComponentState {
|
||||
dumpDebugOnce()
|
||||
private fun checkAvailability(
|
||||
type: ComponentType,
|
||||
bound: Boolean,
|
||||
handleJson: String,
|
||||
runtimeStats: FloatArray,
|
||||
cameraJson: String,
|
||||
handles: HandleDashboardSignal
|
||||
): ComponentState {
|
||||
return when (type.category) {
|
||||
ComponentCategory.ALWAYS_READY -> ComponentState.ACTIVE
|
||||
ComponentCategory.RUNTIME_HOST -> checkRuntimeHostComponent(type)
|
||||
ComponentCategory.PERIPHERAL -> checkPeripheral(type)
|
||||
ComponentCategory.RUNTIME_HOST -> checkRuntimeHostComponent(type, bound, runtimeStats, cameraJson)
|
||||
ComponentCategory.PERIPHERAL -> checkPeripheral(type, bound, handleJson, handles)
|
||||
}
|
||||
}
|
||||
|
||||
private fun checkRuntimeHostComponent(type: ComponentType): ComponentState {
|
||||
// RuntimeHostStatus 始终可交互(Bind 按钮需在未绑定时可用)
|
||||
private fun checkRuntimeHostComponent(
|
||||
type: ComponentType,
|
||||
bound: Boolean,
|
||||
runtimeStats: FloatArray,
|
||||
cameraJson: String
|
||||
): ComponentState {
|
||||
if (type == ComponentType.RUNTIME_HOST_STATUS) return ComponentState.ACTIVE
|
||||
if (!repo.isBound()) return ComponentState.GREY
|
||||
if (!bound) return ComponentState.GREY
|
||||
return when (type) {
|
||||
ComponentType.CAMERA -> checkCamera()
|
||||
// Phase4B-v11.9: do not let camera/home-card availability depend on a live camera
|
||||
// debug query during SDK_Panel cold start. Detail pages can still display richer state.
|
||||
ComponentType.CAMERA -> ComponentState.ACTIVE
|
||||
ComponentType.TELEMETRY_SAFETY -> ComponentState.ACTIVE
|
||||
else -> ComponentState.ACTIVE
|
||||
}
|
||||
}
|
||||
|
||||
private fun checkPeripheral(type: ComponentType): ComponentState {
|
||||
if (!repo.isBound()) return ComponentState.GREY
|
||||
private fun checkPeripheral(
|
||||
type: ComponentType,
|
||||
bound: Boolean,
|
||||
handleJson: String,
|
||||
handles: HandleDashboardSignal
|
||||
): ComponentState {
|
||||
if (!bound) return ComponentState.GREY
|
||||
return when (type) {
|
||||
ComponentType.LEFT_HANDLE -> checkHandle("left")
|
||||
ComponentType.RIGHT_HANDLE -> checkHandle("right")
|
||||
ComponentType.BALANCE_BOARD -> checkBalanceBoard()
|
||||
ComponentType.DONGLE -> checkDongle()
|
||||
ComponentType.LEFT_HANDLE -> checkHandle(handles.left, handles.leftProgressAgeMs)
|
||||
ComponentType.RIGHT_HANDLE -> checkHandle(handles.right, handles.rightProgressAgeMs)
|
||||
ComponentType.BALANCE_BOARD -> ComponentState.GREY // CoP not integrated yet.
|
||||
ComponentType.DONGLE -> checkDongle(handles)
|
||||
ComponentType.MOTOR -> checkMotor()
|
||||
else -> ComponentState.GREY
|
||||
}
|
||||
}
|
||||
|
||||
private var debugDumped = false
|
||||
|
||||
private fun dumpDebugOnce() {
|
||||
if (debugDumped || !repo.isBound()) return
|
||||
debugDumped = true
|
||||
// 首页首次检测不要调用 getDebugSnapshotJson / camera / motor 等重 API。
|
||||
// 这些 API 会触发 native snapshot 或 camera state 路径;RuntimeHost 刚启动时容易与
|
||||
// native init/camera warm-start 形成 Binder 等待,导致 NOT_BOUND 或 service ANR。
|
||||
val apis = mapOf(
|
||||
"isBound" to repo.isBound().toString(),
|
||||
"getDongleStateJson(first400)" to runCatching { repo.getDongleStateJson().take(400) }.getOrDefault("EXCEPTION")
|
||||
)
|
||||
for ((name, value) in apis) {
|
||||
logger.log(LogEntry(
|
||||
timestamp = System.currentTimeMillis(),
|
||||
component = null,
|
||||
action = "DEBUG_DUMP",
|
||||
params = name,
|
||||
result = value,
|
||||
isStateChange = false
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
private fun checkCamera(): ComponentState {
|
||||
private fun checkCamera(runtimeStats: FloatArray, cameraJson: String): ComponentState {
|
||||
// Home card means pipeline alive, not necessarily human detected.
|
||||
val statsActive = runtimeStats.any { !it.isNaN() && !it.isInfinite() && it > 0.1f }
|
||||
if (statsActive) return ComponentState.ACTIVE
|
||||
if (isUnavailable(cameraJson)) return ComponentState.GREY
|
||||
return try {
|
||||
val json = repo.getCameraStateJson()
|
||||
if (isUnavailable(json)) ComponentState.GREY else ComponentState.ACTIVE
|
||||
} catch (_: Exception) {
|
||||
ComponentState.GREY
|
||||
}
|
||||
}
|
||||
|
||||
private fun checkHandle(side: String): ComponentState {
|
||||
return try {
|
||||
val json = repo.getHandleStateJson()
|
||||
val obj = JSONObject(json)
|
||||
val sideObj = obj.optJSONObject(side) ?: return ComponentState.GREY
|
||||
// handle-state.v1: check available AND connected
|
||||
val available = sideObj.optBoolean("available", false)
|
||||
val connected = sideObj.optBoolean("connected", false)
|
||||
if (available || connected) ComponentState.ACTIVE else ComponentState.GREY
|
||||
} catch (_: Exception) {
|
||||
ComponentState.GREY
|
||||
}
|
||||
}
|
||||
|
||||
private fun checkBalanceBoard(): ComponentState {
|
||||
// BalanceBoard 没有专用 API,暂时用 debugSnapshot 判断
|
||||
// TODO: 确认 RuntimeHost debug snapshot 中 balance board 状态字段
|
||||
return try {
|
||||
val json = repo.getDebugSnapshotJson()
|
||||
if (isUnavailable(json)) return ComponentState.GREY
|
||||
val obj = JSONObject(json)
|
||||
val bb = obj.optJSONObject("balanceBoard") ?: obj.optJSONObject("balance_board")
|
||||
if (bb == null) ComponentState.GREY
|
||||
else if (bb.optBoolean("available", false) || bb.optBoolean("connected", false)) ComponentState.ACTIVE
|
||||
else ComponentState.GREY
|
||||
} catch (_: Exception) {
|
||||
ComponentState.GREY
|
||||
}
|
||||
}
|
||||
|
||||
private fun checkDongle(): ComponentState {
|
||||
val state = computeDongleState()
|
||||
latestDongleCardStateForMotorGate = state
|
||||
return state
|
||||
}
|
||||
|
||||
private fun computeDongleState(): ComponentState {
|
||||
return try {
|
||||
val json = repo.getDongleStateJson()
|
||||
if (isUnavailable(json)) return ComponentState.GREY
|
||||
val obj = JSONObject(json)
|
||||
val transport = obj.optJSONObject("transport") ?: return ComponentState.GREY
|
||||
|
||||
val active = obj.optBoolean("active", false) || obj.optBoolean("available", false) || obj.optBoolean("connected", false)
|
||||
val transportActive = transport.optBoolean("active", false) || transport.optBoolean("connected", false)
|
||||
val usbBridgeRegistered = transport.optBoolean("usbBridgeRegistered", false)
|
||||
val readLoopRunning = transport.optBoolean("readLoopRunning", false)
|
||||
val usbPresent = transport.optBoolean("usbPresent", false)
|
||||
val state = transport.optString("state", "")
|
||||
|
||||
// Dongle 首页卡片表达“USB transport 已经被 RuntimeHost 打开并注册”,
|
||||
// 不要求 lastUsbInAgeMs < 3s。是否有上行数据滞后由 detail page 的 dataStale/lastUsbInAgeMs 显示。
|
||||
if ((active || transportActive || state == "CONNECTED") &&
|
||||
usbPresent &&
|
||||
usbBridgeRegistered &&
|
||||
readLoopRunning
|
||||
) {
|
||||
val obj = JSONObject(cameraJson)
|
||||
val pipeline = obj.optJSONObject("realInternalCameraPipeline")
|
||||
val pose2D = obj.optJSONObject("pose2DState")
|
||||
val pose3D = obj.optJSONObject("pose3DState")
|
||||
val running = obj.optBoolean("running", false) || obj.optString("state", "") == "RUNNING"
|
||||
val imx415Open = obj.optBoolean("imx415OpenSucceeded", false) || pipeline?.optBoolean("imx415OpenSucceeded", false) == true
|
||||
val rga = obj.optBoolean("rgaEnabled", false) || pipeline?.optBoolean("rgaEnabled", false) == true
|
||||
val rknn = obj.optBoolean("rknnYoloEnabled", false) || pipeline?.optBoolean("rknnYoloEnabled", false) == true
|
||||
val videoPose3D = obj.optBoolean("videoPose3DEnabled", false) || pipeline?.optBoolean("videoPose3DEnabled", false) == true
|
||||
val pose2DAvailable = pose2D?.optBoolean("available", false) == true
|
||||
val pose3DAvailable = pose3D?.optBoolean("available", false) == true
|
||||
if (running || imx415Open || (rga && rknn) || videoPose3D || pose2DAvailable || pose3DAvailable) {
|
||||
ComponentState.ACTIVE
|
||||
} else {
|
||||
ComponentState.GREY
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "checkCamera exception: ${t.message}")
|
||||
ComponentState.GREY
|
||||
}
|
||||
}
|
||||
|
||||
private fun checkHandle(signal: HandleSignal, progressAgeMs: Long): ComponentState {
|
||||
if (signal.side.isBlank()) return ComponentState.GREY
|
||||
val liveFlags = signal.available || signal.connected || signal.streaming
|
||||
val dataFresh = signal.dataAgeMs in 0..HANDLE_DATA_AGE_FRESH_TIMEOUT_MS
|
||||
val sequenceProgressFresh = progressAgeMs <= HANDLE_SEQUENCE_PROGRESS_TIMEOUT_MS
|
||||
val hasPayload = signal.sequenceId > 0L && signal.queueSize > 0
|
||||
val streamingActive = liveFlags && hasPayload && (dataFresh || sequenceProgressFresh)
|
||||
val slotConnectedFresh = signal.slot.freshConnected
|
||||
// Phase4B-v11.19: home card should distinguish BLE connection from IMU stream.
|
||||
// A freshly connected Dongle slot is valid "connected" evidence even before
|
||||
// handle IMU frames arrive; stale last-known payload still cannot keep it green.
|
||||
val active = streamingActive || slotConnectedFresh
|
||||
Log.i(
|
||||
TAG,
|
||||
"Phase4B-v11.9 checkHandle; side=${signal.side}; available=${signal.available}; connected=${signal.connected}; streaming=${signal.streaming}; " +
|
||||
"sequenceId=${signal.sequenceId}; queueSize=${signal.queueSize}; dataAgeMs=${signal.dataAgeMs}; progressAgeMs=${printAge(progressAgeMs)}; " +
|
||||
"slotState=${signal.slot.state}; slotConnected=${signal.slot.connected}; slotAgeMs=${printAge(signal.slot.lastSeenAgeMs)}; " +
|
||||
"dataFresh=$dataFresh; sequenceProgressFresh=$sequenceProgressFresh; streamingActive=$streamingActive; slotConnectedFresh=$slotConnectedFresh; " +
|
||||
"decision=${if (active) "ACTIVE" else "GREY"}; rule=REQUIRE_FRESH_DATA_OR_FRESH_SLOT_CONNECTION"
|
||||
)
|
||||
return if (active) ComponentState.ACTIVE else ComponentState.GREY
|
||||
}
|
||||
|
||||
private fun checkDongle(handles: HandleDashboardSignal): ComponentState {
|
||||
val rightFresh = isHandleFreshForDongle(handles.right, handles.rightProgressAgeMs)
|
||||
val leftFresh = isHandleFreshForDongle(handles.left, handles.leftProgressAgeMs)
|
||||
val dongleProgressFresh = handles.dongleProgressAgeMs <= DONGLE_SEQUENCE_PROGRESS_TIMEOUT_MS
|
||||
val recentHandleProgress = dongleProgressFresh && (rightFresh || leftFresh)
|
||||
|
||||
// Phase4B-v11.17: Dongle card means SmartBase USB/CDC transport is actually alive.
|
||||
// Do not mark it ACTIVE merely because RuntimeHost is bound, a placeholder exists,
|
||||
// or a last-known Handle sample exists. Handles are useful detail-page slot evidence,
|
||||
// but they are not sufficient transport evidence for the Dongle home card.
|
||||
val transportActive = handles.dongle.valid && handles.dongle.active
|
||||
val active = transportActive
|
||||
val state = if (active) ComponentState.ACTIVE else ComponentState.GREY
|
||||
latestDongleCardStateForMotorGate = state
|
||||
Log.i(
|
||||
TAG,
|
||||
"Phase4B-v11.9 checkDongle; valid=${handles.valid}; dongleStateLocated=${handles.dongleStateLocated}; observationBufferLocated=${handles.observationBufferLocated}; " +
|
||||
"transportActive=$transportActive; usbPresent=${handles.dongle.usbPresent}; bridge=${handles.dongle.usbBridgeRegistered}; readLoop=${handles.dongle.readLoopRunning}; transportState=${handles.dongle.state}; " +
|
||||
"stale=${handles.dongle.stale}; dataStale=${handles.dongle.dataStale}; lastUsbInAgeMs=${printAge(handles.dongle.lastUsbInAgeMs)}; cacheAgeMs=${printAge(handles.dongle.cacheAgeMs)}; " +
|
||||
"rightFresh=$rightFresh; leftFresh=$leftFresh; recentHandleProgress=$recentHandleProgress; dongleProgressAgeMs=${printAge(handles.dongleProgressAgeMs)}; decision=${state.name}; " +
|
||||
"rule=$DONGLE_RULE; evidence=${handles.dongle.evidence}"
|
||||
)
|
||||
return state
|
||||
}
|
||||
|
||||
private fun isHandleFreshForDongle(signal: HandleSignal, progressAgeMs: Long): Boolean {
|
||||
val liveFlags = signal.available || signal.connected || signal.streaming
|
||||
val dataFresh = signal.dataAgeMs in 0..HANDLE_DATA_AGE_FRESH_TIMEOUT_MS
|
||||
val sequenceProgressFresh = progressAgeMs <= HANDLE_SEQUENCE_PROGRESS_TIMEOUT_MS
|
||||
return signal.slot.freshConnected || (liveFlags && signal.sequenceId > 0L && signal.queueSize > 0 && (dataFresh || sequenceProgressFresh))
|
||||
}
|
||||
|
||||
private fun checkMotor(): ComponentState {
|
||||
return try {
|
||||
// Motor is physically downstream of the SmartBase Dongle.
|
||||
// V7 requires fresh motor telemetry; stale cached telemetry after Dongle re-plug must not turn Motor green.
|
||||
if (latestDongleCardStateForMotorGate != ComponentState.ACTIVE) return ComponentState.GREY
|
||||
|
||||
val json = repo.getLatestMotorStateJson()
|
||||
if (isUnavailable(json)) return ComponentState.GREY
|
||||
|
||||
val obj = JSONObject(json)
|
||||
if (obj.optString("contractVersion", "") != "kiwii.motor-runtime-state.v1") return ComponentState.GREY
|
||||
if (obj.optBoolean("blockedByDongleTransport", false)) return ComponentState.GREY
|
||||
if (obj.optBoolean("blockedByMotorTelemetry", false)) return ComponentState.GREY
|
||||
if (!obj.optBoolean("available", false)) return ComponentState.GREY
|
||||
|
||||
val dataAgeMs = obj.optLong("dataAgeMs", Long.MAX_VALUE)
|
||||
if (dataAgeMs < 0L || dataAgeMs > MOTOR_TELEMETRY_FRESH_TIMEOUT_MS) return ComponentState.GREY
|
||||
|
||||
ComponentState.ACTIVE
|
||||
} catch (_: Exception) {
|
||||
ComponentState.GREY
|
||||
}
|
||||
// Phase4B-v11.14: Motor home-card state comes from explicit motor runtime-state
|
||||
// refreshed on a background thread, not from scatter-chart visibility. This remains
|
||||
// no-blocking and can become ACTIVE before the user opens the Motor detail page.
|
||||
val dongleActive = latestDongleCardStateForMotorGate == ComponentState.ACTIVE
|
||||
val motor = MotorTelemetrySnapshotCache.homeCardRuntimeStatus(MOTOR_STATUS_FRESH_TIMEOUT_MS)
|
||||
val motorSlotConnectedFresh = latestHandleSignalsForMotorSlot?.freshConnected ?: false
|
||||
val active = dongleActive && (motor.active || motorSlotConnectedFresh)
|
||||
val state = if (active) ComponentState.ACTIVE else ComponentState.GREY
|
||||
Log.i(
|
||||
TAG,
|
||||
"Phase4B-v11.14 checkMotor; dongleActive=$dongleActive; " +
|
||||
"contractOk=${motor.contractOk}; available=${motor.available}; connected=${motor.connected}; state=${motor.state}; " +
|
||||
"slotState=${latestHandleSignalsForMotorSlot?.state ?: ""}; slotConnected=${latestHandleSignalsForMotorSlot?.connected ?: false}; slotAgeMs=${printAge(latestHandleSignalsForMotorSlot?.lastSeenAgeMs ?: Long.MAX_VALUE)}; " +
|
||||
"blockedByDongleTransport=${motor.blockedByDongleTransport}; blockedByMotorTelemetry=${motor.blockedByMotorTelemetry}; " +
|
||||
"dataAgeMs=${printAge(motor.dataAgeMs)}; snapshotAgeMs=${printAge(motor.snapshotAgeMs)}; " +
|
||||
"reason=${if (motor.active) motor.reason else if (motorSlotConnectedFresh) "MOTOR_SLOT_CONNECTED_NO_TELEMETRY" else motor.reason}; decision=${state.name}; rule=EXPLICIT_MOTOR_RUNTIME_STATE_OR_FRESH_SLOT_CONNECTION"
|
||||
)
|
||||
return state
|
||||
}
|
||||
|
||||
/**
|
||||
* 通用不可用判断:含 error 字段、空 JSON、或 NOT_BOUND
|
||||
*/
|
||||
private fun isUnavailable(json: String): Boolean {
|
||||
if (json.isBlank() || json == "{}") return true
|
||||
if (json.contains("\"error\"")) return true
|
||||
|
||||
@@ -14,8 +14,10 @@ class AarProxyStateSource(private val bridge: BridgeRepository) : RuntimeStateSo
|
||||
ComponentType.CAMERA -> bridge.getCameraStateJson()
|
||||
ComponentType.LEFT_HANDLE, ComponentType.RIGHT_HANDLE -> bridge.getHandleStateJson()
|
||||
ComponentType.MOTOR -> bridge.getLatestMotorStateJson()
|
||||
ComponentType.BALANCE_BOARD -> bridge.getDebugSnapshotJson()
|
||||
ComponentType.DONGLE -> bridge.getDongleStateJson()
|
||||
ComponentType.BALANCE_BOARD -> "{\"contractVersion\":\"kiwii.sdk-panel.balance-placeholder.v1\",\"available\":false,\"reason\":\"Balance Board detail state is not wired yet\"}"
|
||||
// Phase4B-v11: Dongle detail state must include transport + slot0..3 + handle-state inference.
|
||||
// Do not use raw getDongleStateJson() directly for the detail State panel because slot cache can be empty/stale.
|
||||
ComponentType.DONGLE -> bridge.getDongleDetailStateJson()
|
||||
ComponentType.TELEMETRY_SAFETY -> bridge.getTelemetryStateJson()
|
||||
ComponentType.SESSION_LOG -> "{}"
|
||||
}
|
||||
|
||||
@@ -26,6 +26,13 @@ class StatePoller(
|
||||
private val pollIntervalMs = 1000L
|
||||
private var wasBound = false
|
||||
|
||||
@Volatile
|
||||
private var focusedComponent: ComponentType = ComponentType.RUNTIME_HOST_STATUS
|
||||
|
||||
fun setFocusedComponent(type: ComponentType) {
|
||||
focusedComponent = type
|
||||
}
|
||||
|
||||
fun startPolling() {
|
||||
scope.launch {
|
||||
while (isActive) {
|
||||
@@ -41,7 +48,7 @@ class StatePoller(
|
||||
isStateChange = true
|
||||
))
|
||||
}
|
||||
val snapshot = pollAllStates()
|
||||
val snapshot = pollFocusedStates()
|
||||
_states.value = snapshot
|
||||
} else {
|
||||
if (wasBound) {
|
||||
@@ -62,19 +69,17 @@ class StatePoller(
|
||||
}
|
||||
}
|
||||
|
||||
private fun pollAllStates(): Map<ComponentType, StateSnapshot> {
|
||||
private fun pollFocusedStates(): Map<ComponentType, StateSnapshot> {
|
||||
val now = System.currentTimeMillis()
|
||||
val polledTypes = listOf(
|
||||
ComponentType.RUNTIME_HOST_STATUS,
|
||||
ComponentType.CAMERA,
|
||||
ComponentType.LEFT_HANDLE,
|
||||
ComponentType.RIGHT_HANDLE,
|
||||
ComponentType.BALANCE_BOARD,
|
||||
ComponentType.DONGLE,
|
||||
ComponentType.MOTOR,
|
||||
ComponentType.TELEMETRY_SAFETY
|
||||
)
|
||||
return polledTypes.mapNotNull { type ->
|
||||
// Phase4B-v11: detail pages must not poll every component. The previous all-component
|
||||
// loop called heavy/global APIs such as getDebugSnapshotJson and could starve/hang the
|
||||
// current page after back/re-enter. Poll RuntimeHost + the currently visible component only.
|
||||
val types = linkedSetOf(ComponentType.RUNTIME_HOST_STATUS)
|
||||
if (focusedComponent != ComponentType.RUNTIME_HOST_STATUS && focusedComponent != ComponentType.SESSION_LOG) {
|
||||
types += focusedComponent
|
||||
}
|
||||
|
||||
return types.mapNotNull { type ->
|
||||
try {
|
||||
type to StateSnapshot(
|
||||
data = runtimeStateRepo.getComponentState(type),
|
||||
@@ -82,7 +87,6 @@ class StatePoller(
|
||||
isDebugChannel = runtimeStateRepo.isUsingDebugChannel()
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
// 异常必记
|
||||
logger.log(LogEntry(
|
||||
timestamp = now,
|
||||
component = type,
|
||||
@@ -92,7 +96,7 @@ class StatePoller(
|
||||
isStateChange = false
|
||||
))
|
||||
type to StateSnapshot(
|
||||
data = "{\"error\":\"${e.message}\"}",
|
||||
data = "{\"error\":\"${escapeJson(e.message ?: e.javaClass.simpleName)}\"}",
|
||||
updatedAt = now,
|
||||
isDebugChannel = runtimeStateRepo.isUsingDebugChannel(),
|
||||
hasError = true
|
||||
@@ -101,6 +105,8 @@ class StatePoller(
|
||||
}.toMap()
|
||||
}
|
||||
|
||||
private fun escapeJson(value: String): String = value.replace("\\", "\\\\").replace("\"", "\\\"")
|
||||
|
||||
fun stopPolling() {
|
||||
scope.cancel()
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.kiwii.controlpanel.ui.adapter
|
||||
|
||||
import android.util.Log
|
||||
import android.view.LayoutInflater
|
||||
import android.view.ViewGroup
|
||||
import androidx.core.content.ContextCompat
|
||||
@@ -32,6 +33,7 @@ class ComponentCardAdapter(
|
||||
RecyclerView.ViewHolder(binding.root) {
|
||||
|
||||
fun bind(type: ComponentType, state: ComponentState) {
|
||||
Log.i("KiwiiSDKPanelUI", "Phase4B-v6 bind home card; component=${type.name}; state=${state.name}")
|
||||
binding.tvComponentName.text = type.displayName
|
||||
binding.tvStatusSummary.text = when (state) {
|
||||
ComponentState.ACTIVE -> "Available"
|
||||
|
||||
@@ -16,25 +16,31 @@ class CameraOps(
|
||||
override fun createView(): View {
|
||||
val layout = verticalLayout()
|
||||
|
||||
// 预览占位
|
||||
layout.addView(TextView(context).apply {
|
||||
text = "Preview: Pending RuntimeHost debug channel"
|
||||
text = "Phase 4A Camera Observation\n2D/3D are split into LatestFastState + ObservationBuffer. 3D uses VideoPose3D 27F. Timestamps use hostArrivalNs / hostEstimatedSampleTimeNs."
|
||||
textSize = 12f
|
||||
setTextColor(ContextCompat.getColor(context, R.color.rhs_subtitle))
|
||||
setPadding(0, 0, 0, 16)
|
||||
})
|
||||
|
||||
layout.addView(createSection("SDK Operations"))
|
||||
layout.addView(createSection("Camera Observation Display"))
|
||||
layout.addView(createButton("getCameraObservationStateJson") {
|
||||
viewModel.executeOperation(ComponentType.CAMERA, "getCameraObservationStateJson") {
|
||||
viewModel.bridgeRepo.getCameraObservationStateJson()
|
||||
}
|
||||
})
|
||||
layout.addView(createButton("getCameraStateJson") {
|
||||
viewModel.executeOperation(ComponentType.CAMERA, "getCameraStateJson") {
|
||||
viewModel.bridgeRepo.getCameraStateJson()
|
||||
}
|
||||
})
|
||||
layout.addView(createButton("getPerceptionStateJson") {
|
||||
viewModel.executeOperation(ComponentType.CAMERA, "getPerceptionStateJson") {
|
||||
viewModel.bridgeRepo.getPerceptionStateJson()
|
||||
layout.addView(createButton("getHealthStateJson") {
|
||||
viewModel.executeOperation(ComponentType.CAMERA, "getHealthStateJson") {
|
||||
viewModel.bridgeRepo.getHealthStateJson()
|
||||
}
|
||||
})
|
||||
|
||||
layout.addView(createSection("Pose Payloads"))
|
||||
layout.addView(createButton("getLatestPose2D") {
|
||||
viewModel.executeOperation(ComponentType.CAMERA, "getLatestPose2D") {
|
||||
viewModel.bridgeRepo.getLatestPose2D()
|
||||
@@ -50,6 +56,13 @@ class CameraOps(
|
||||
viewModel.bridgeRepo.getLatestRuntimeStats()
|
||||
}
|
||||
})
|
||||
|
||||
layout.addView(createSection("Raw Runtime Queries"))
|
||||
layout.addView(createButton("getPerceptionStateJson") {
|
||||
viewModel.executeOperation(ComponentType.CAMERA, "getPerceptionStateJson") {
|
||||
viewModel.bridgeRepo.getPerceptionStateJson()
|
||||
}
|
||||
})
|
||||
layout.addView(createButton("getLatestPoseFrameJson") {
|
||||
viewModel.executeOperation(ComponentType.CAMERA, "getLatestPoseFrameJson") {
|
||||
viewModel.bridgeRepo.getLatestPoseFrameJson()
|
||||
|
||||
@@ -13,30 +13,12 @@ class DongleOps(
|
||||
override fun createView(): View {
|
||||
val layout = verticalLayout()
|
||||
|
||||
layout.addView(createSection("Dongle Transport"))
|
||||
layout.addView(createButton("getDongleStateJson") {
|
||||
viewModel.executeOperation(ComponentType.DONGLE, "getDongleStateJson") {
|
||||
viewModel.bridgeRepo.getDongleStateJson()
|
||||
}
|
||||
})
|
||||
|
||||
layout.addView(createButton("getDebugSnapshotJson") {
|
||||
viewModel.executeOperation(ComponentType.DONGLE, "getDebugSnapshotJson") {
|
||||
viewModel.bridgeRepo.getDebugSnapshotJson()
|
||||
}
|
||||
})
|
||||
|
||||
layout.addView(createSection("Transport Probe"))
|
||||
layout.addView(createButton("queryMotorTrainingMode") {
|
||||
viewModel.executeOperation(ComponentType.DONGLE, "queryMotorTrainingMode", "axis=0") {
|
||||
viewModel.bridgeRepo.queryMotorTrainingMode(0)
|
||||
}
|
||||
})
|
||||
|
||||
layout.addView(createSection("Expected fields"))
|
||||
layout.addView(createButton("Inspect transport + slots") {
|
||||
viewModel.executeOperation(ComponentType.DONGLE, "inspectDongleDiagnostics") {
|
||||
viewModel.bridgeRepo.getDongleStateJson()
|
||||
// Phase4B-v11: one action only. It reads the SDK Panel detail-state JSON and updates
|
||||
// both State panel and Session Log. It does not mutate RuntimeHost state.
|
||||
layout.addView(createSection("Dongle Diagnostics"))
|
||||
layout.addView(createButton("readDongleState") {
|
||||
viewModel.executeOperation(ComponentType.DONGLE, "readDongleState") {
|
||||
viewModel.bridgeRepo.getDongleDetailStateJson()
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -30,6 +30,16 @@ class LeftHandleOps(
|
||||
}
|
||||
})
|
||||
|
||||
layout.addView(createSection("Haptics"))
|
||||
val effectInput = createParameterInput("Effect ID (int)", android.text.InputType.TYPE_CLASS_NUMBER)
|
||||
val staticEffectAction = createButton("submitLeftStaticEffect") {
|
||||
val id = effectInput.text.toString().toIntOrNull() ?: 0
|
||||
viewModel.executeOperation(ComponentType.LEFT_HANDLE, "submitLeftStaticEffect", "effectId=$id") {
|
||||
viewModel.bridgeRepo.submitLeftStaticEffect(id)
|
||||
}
|
||||
}
|
||||
layout.addView(createParameterActionRow(staticEffectAction, effectInput))
|
||||
|
||||
val streamIdInput = createParameterInput("Stream ID (int)", android.text.InputType.TYPE_CLASS_NUMBER)
|
||||
val payloadInput = createParameterInput("Payload (String)", android.text.InputType.TYPE_CLASS_TEXT)
|
||||
val heStreamAction = createButton("submitLeftHeStream") {
|
||||
|
||||
+224
@@ -0,0 +1,224 @@
|
||||
package com.kiwii.controlpanel.ui.components
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Color
|
||||
import android.graphics.Typeface
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.util.Log
|
||||
import android.view.Gravity
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.TextView
|
||||
import com.kiwii.controlpanel.R
|
||||
import com.kiwii.controlpanel.data.BridgeRepository
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.ScheduledExecutorService
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/**
|
||||
* Phase4B-v11.17 Motor chart lifecycle/cache-poll fix.
|
||||
*
|
||||
* Design:
|
||||
* - Do not change Motor home-card connectivity semantics.
|
||||
* - Do not change Dongle / Handle / Camera / Session Log behavior.
|
||||
* - Keep the v11.14 explicit Motor runtime-state cache as the source of truth.
|
||||
* - Fix Motor page re-entry by restarting the chart poller from onAttachedToWindow().
|
||||
* - Keep the poller off the UI thread and catch all failures so one timeout/exception does
|
||||
* not permanently kill the chart refresh loop.
|
||||
* - Do not let the chart scheduler block on a live Binder call. It requests the shared
|
||||
* MotorTelemetrySnapshotCache refresh asynchronously, then renders the last-known fresh sample.
|
||||
*/
|
||||
internal class MotorRealtimeTelemetryPanel(
|
||||
context: Context,
|
||||
private val repo: BridgeRepository
|
||||
) : LinearLayout(context) {
|
||||
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
private val chartView = MotorTelemetryScatterChartView(context)
|
||||
private val headline = TextView(context)
|
||||
private val temperatureLine = TextView(context)
|
||||
private val subline = TextView(context)
|
||||
|
||||
@Volatile
|
||||
private var executor: ScheduledExecutorService? = null
|
||||
|
||||
@Volatile
|
||||
private var attached = false
|
||||
|
||||
private var renderedCount: Long = 0L
|
||||
private var lastRenderedWallTimeMs: Long = -1L
|
||||
private var lastPollLogMs: Long = 0L
|
||||
|
||||
init {
|
||||
orientation = VERTICAL
|
||||
setBackgroundResource(R.drawable.bg_rhs_log_area)
|
||||
setPadding(8.dp(), 8.dp(), 8.dp(), 8.dp())
|
||||
|
||||
addView(TextView(context).apply {
|
||||
text = "Realtime force / rope length / temperature"
|
||||
textSize = 12f
|
||||
typeface = Typeface.DEFAULT_BOLD
|
||||
setTextColor(Color.rgb(38, 50, 56))
|
||||
}, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT))
|
||||
|
||||
addView(headline.apply {
|
||||
text = "Force: — kgf Rope: — cm"
|
||||
textSize = 13f
|
||||
typeface = Typeface.MONOSPACE
|
||||
setTextColor(Color.rgb(20, 32, 40))
|
||||
setPadding(0, 6.dp(), 0, 0)
|
||||
}, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT))
|
||||
|
||||
addView(temperatureLine.apply {
|
||||
text = "Temp: — °C"
|
||||
textSize = 12f
|
||||
typeface = Typeface.DEFAULT_BOLD
|
||||
setTextColor(Color.rgb(20, 32, 40))
|
||||
setPadding(0, 3.dp(), 0, 0)
|
||||
}, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT))
|
||||
|
||||
addView(subline.apply {
|
||||
text = "Phase4B-v11.17 cached telemetry poll; buttons use last-known snapshot"
|
||||
textSize = 10f
|
||||
setTextColor(Color.rgb(96, 111, 123))
|
||||
setPadding(0, 2.dp(), 0, 6.dp())
|
||||
}, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT))
|
||||
|
||||
addView(chartView, LayoutParams(LayoutParams.MATCH_PARENT, 320.dp()))
|
||||
|
||||
addView(TextView(context).apply {
|
||||
text = "Display convention: force is shown as positive kgf resistance/tension. This is motor-side telemetry derived from current/torque and fm_rad, not a calibrated external load-cell reading. RuntimeHost keeps rawForceN for native-sign debugging. Rope length uses extensionM, or -positionRad × fm_rad fallback."
|
||||
textSize = 9.5f
|
||||
setTextColor(Color.rgb(96, 111, 123))
|
||||
gravity = Gravity.START
|
||||
setPadding(0, 6.dp(), 0, 0)
|
||||
}, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT))
|
||||
}
|
||||
|
||||
override fun onAttachedToWindow() {
|
||||
super.onAttachedToWindow()
|
||||
attached = true
|
||||
startPolling()
|
||||
}
|
||||
|
||||
override fun onDetachedFromWindow() {
|
||||
attached = false
|
||||
stopPolling()
|
||||
super.onDetachedFromWindow()
|
||||
}
|
||||
|
||||
private fun startPolling() {
|
||||
val current = executor
|
||||
if (current != null && !current.isShutdown && !current.isTerminated) return
|
||||
|
||||
Log.i(TAG, "Phase4B-v11.17 MotorTelemetryPanel start; cachePoll=true; directBinderOnScheduler=false; lifecycleSafe=true")
|
||||
executor = Executors.newSingleThreadScheduledExecutor { runnable ->
|
||||
Thread(runnable, "kiwii-motor-telemetry-panel-v11.17").apply { isDaemon = true }
|
||||
}.also { exec ->
|
||||
exec.scheduleWithFixedDelay({
|
||||
runCatching { pollOnce() }
|
||||
.onFailure { t ->
|
||||
val reason = t.message ?: t.javaClass.simpleName
|
||||
MotorTelemetrySnapshotCache.recordMotorStateError("motor-chart-poll failed: $reason")
|
||||
Log.w(TAG, "Phase4B-v11.17 MotorTelemetryPanel poll failed: $reason")
|
||||
postUnavailable("chart poll failed: $reason")
|
||||
}
|
||||
}, 0L, 200L, TimeUnit.MILLISECONDS)
|
||||
}
|
||||
}
|
||||
|
||||
private fun stopPolling() {
|
||||
Log.i(TAG, "Phase4B-v11.17 MotorTelemetryPanel stop")
|
||||
executor?.shutdownNow()
|
||||
executor = null
|
||||
mainHandler.removeCallbacksAndMessages(null)
|
||||
}
|
||||
|
||||
private fun pollOnce() {
|
||||
if (!attached) return
|
||||
|
||||
if (!repo.isBound()) {
|
||||
postUnavailable("RuntimeHost not bound")
|
||||
return
|
||||
}
|
||||
|
||||
// This call is non-blocking for the chart scheduler. The actual Binder read runs in
|
||||
// MotorTelemetrySnapshotCache's daemon refresh thread with stuck-refresh recovery.
|
||||
MotorTelemetrySnapshotCache.requestRuntimeStateRefreshAsync(repo, "motor-chart-poll")
|
||||
|
||||
val snapshot = MotorTelemetrySnapshotCache.chartSnapshot(freshTimeoutMs = 2_000L)
|
||||
val sample = snapshot.sample
|
||||
if (sample == null) {
|
||||
val reason = "${snapshot.reason}; effectiveAgeMs=${printAge(snapshot.effectiveAgeMs)}; snapshotAgeMs=${printAge(snapshot.snapshotAgeMs)}"
|
||||
logPollNoSample(reason)
|
||||
postUnavailable(reason)
|
||||
} else {
|
||||
if (sample.wallTimeMs == lastRenderedWallTimeMs) {
|
||||
logPollNoSample("NO_NEW_SAMPLE; effectiveAgeMs=${printAge(snapshot.effectiveAgeMs)}; snapshotAgeMs=${printAge(snapshot.snapshotAgeMs)}")
|
||||
}
|
||||
postSample(sample, snapshot.effectiveAgeMs)
|
||||
}
|
||||
}
|
||||
|
||||
private fun postSample(sample: MotorTelemetrySample, effectiveAgeMs: Long) {
|
||||
mainHandler.post {
|
||||
if (!attached) return@post
|
||||
updateSample(sample, effectiveAgeMs)
|
||||
}
|
||||
}
|
||||
|
||||
private fun postUnavailable(reason: String) {
|
||||
mainHandler.post {
|
||||
if (!attached) return@post
|
||||
setUnavailable(reason)
|
||||
}
|
||||
}
|
||||
|
||||
private fun updateSample(sample: MotorTelemetrySample, effectiveAgeMs: Long) {
|
||||
headline.text = "Force: ${fmt(sample.forceKg)} kgf Rope: ${fmt(sample.ropeLengthM * 100.0)} cm"
|
||||
temperatureLine.text = "Temp: ${fmt(sample.tempC)} °C"
|
||||
subline.text = "Force=${fmt(sample.forceN)} N I=${fmt(sample.currentA)} A V=${fmt(sample.voltageV)} V age=${printAge(effectiveAgeMs)} ms"
|
||||
|
||||
if (sample.wallTimeMs != lastRenderedWallTimeMs) {
|
||||
chartView.addSample(sample)
|
||||
lastRenderedWallTimeMs = sample.wallTimeMs
|
||||
renderedCount += 1L
|
||||
if (renderedCount == 1L || renderedCount % 10L == 0L) {
|
||||
Log.i(TAG, "Phase4B-v11.17 MotorTelemetryPanel render; count=$renderedCount; sampleWallTimeMs=${sample.wallTimeMs}; dataAgeMs=${sample.dataAgeMs}; effectiveAgeMs=$effectiveAgeMs")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun setUnavailable(reason: String) {
|
||||
headline.text = "Force: — kgf Rope: — cm"
|
||||
temperatureLine.text = "Temp: — °C"
|
||||
subline.text = reason
|
||||
}
|
||||
|
||||
private fun logPollNoSample(reason: String) {
|
||||
val now = System.currentTimeMillis()
|
||||
if (now - lastPollLogMs < 1000L) return
|
||||
lastPollLogMs = now
|
||||
Log.i(TAG, "Phase4B-v11.17 MotorTelemetryPanel poll; running=true; newSample=false; lastRenderedSampleWallTimeMs=$lastRenderedWallTimeMs; reason=$reason")
|
||||
}
|
||||
|
||||
private fun printAge(ageMs: Long): String {
|
||||
return if (ageMs == Long.MAX_VALUE) "NA" else ageMs.toString()
|
||||
}
|
||||
|
||||
private fun fmt(value: Double): String {
|
||||
if (!value.isFinite()) return "—"
|
||||
val absValue = kotlin.math.abs(value)
|
||||
return when {
|
||||
absValue >= 100.0 -> String.format("%.0f", value)
|
||||
absValue >= 10.0 -> String.format("%.1f", value)
|
||||
else -> String.format("%.2f", value)
|
||||
}
|
||||
}
|
||||
|
||||
private fun Int.dp(): Int = (this * resources.displayMetrics.density).toInt()
|
||||
|
||||
private companion object {
|
||||
const val TAG = "KiwiiSDKPanelMotor"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,512 @@
|
||||
package com.kiwii.controlpanel.ui.components
|
||||
|
||||
import com.kiwii.controlpanel.data.BridgeRepository
|
||||
import com.kiwii.controlpanel.logging.LogEntry
|
||||
import com.kiwii.controlpanel.logging.SessionLogger
|
||||
import com.kiwii.controlpanel.model.ComponentType
|
||||
import org.json.JSONObject
|
||||
import kotlin.math.abs
|
||||
|
||||
|
||||
internal data class MotorHomeCardRuntimeStatus(
|
||||
val active: Boolean,
|
||||
val contractOk: Boolean,
|
||||
val available: Boolean,
|
||||
val connected: Boolean,
|
||||
val state: String,
|
||||
val blockedByDongleTransport: Boolean,
|
||||
val blockedByMotorTelemetry: Boolean,
|
||||
val dataAgeMs: Long,
|
||||
val snapshotAgeMs: Long,
|
||||
val reason: String
|
||||
)
|
||||
|
||||
internal data class MotorTelemetrySample(
|
||||
val wallTimeMs: Long,
|
||||
val motorRuntimeSec: Double,
|
||||
val forceN: Double,
|
||||
val forceKg: Double,
|
||||
val ropeLengthM: Double,
|
||||
val currentA: Double,
|
||||
val voltageV: Double,
|
||||
val tempC: Double,
|
||||
val dataAgeMs: Long,
|
||||
val available: Boolean,
|
||||
val rawJson: String
|
||||
)
|
||||
|
||||
internal data class MotorTelemetryChartSnapshot(
|
||||
val sample: MotorTelemetrySample?,
|
||||
val rawJson: String?,
|
||||
val effectiveAgeMs: Long,
|
||||
val snapshotAgeMs: Long,
|
||||
val lastError: String?,
|
||||
val reason: String
|
||||
)
|
||||
|
||||
internal object MotorTelemetryParser {
|
||||
private const val STANDARD_GRAVITY_MPS2 = 9.80665
|
||||
private const val DEFAULT_PULLEY_RADIUS_M = 0.04
|
||||
private const val DEFAULT_MOTOR_KT_NM_PER_A = 1.0
|
||||
|
||||
fun parse(json: String, nowMs: Long = System.currentTimeMillis()): MotorTelemetrySample? {
|
||||
if (json.isBlank() || json.contains("NOT_BOUND")) return null
|
||||
val obj = runCatching { JSONObject(json) }.getOrNull() ?: return null
|
||||
if (obj.optString("contractVersion", "") != "kiwii.motor-runtime-state.v1") return null
|
||||
|
||||
val available = obj.optBoolean("available", false)
|
||||
val dataAgeMs = obj.optLong("dataAgeMs", Long.MAX_VALUE)
|
||||
if (!available || dataAgeMs < 0L || dataAgeMs > 2_000L) return null
|
||||
|
||||
val pulleyRadiusM = obj.firstFinite(
|
||||
DEFAULT_PULLEY_RADIUS_M,
|
||||
"pulleyRadiusM", "fm_rad", "fmRad", "radiusM"
|
||||
).takeIf { abs(it) > 1e-6 } ?: DEFAULT_PULLEY_RADIUS_M
|
||||
val motorKt = obj.firstFinite(DEFAULT_MOTOR_KT_NM_PER_A, "motorKtNmPerA", "ktNmPerA")
|
||||
|
||||
val currentA = obj.firstFinite(0.0, "currentA", "cur", "iqA", "iq")
|
||||
val torqueNm = obj.firstFinite(Double.NaN, "torqueNm", "estimatedTorqueNm")
|
||||
val signedForceN = obj.firstFinite(Double.NaN, "forceN", "outputForceN", "estimatedForceN")
|
||||
.takeIf { it.isFinite() }
|
||||
?: run {
|
||||
val rawForceN = if (torqueNm.isFinite()) torqueNm / pulleyRadiusM else currentA * motorKt / pulleyRadiusM
|
||||
-rawForceN
|
||||
}
|
||||
val forceN = abs(signedForceN)
|
||||
val forceKg = obj.firstFinite(Double.NaN, "forceKg", "forceKgEquivalent")
|
||||
.takeIf { it.isFinite() }
|
||||
?.let { abs(it) }
|
||||
?: forceN / STANDARD_GRAVITY_MPS2
|
||||
|
||||
val positionRad = obj.firstFinite(Double.NaN, "positionRad", "pos")
|
||||
val ropeLengthM = obj.firstFinite(Double.NaN, "ropeLengthM", "extensionM", "cableLengthM")
|
||||
.takeIf { it.isFinite() }
|
||||
?: if (positionRad.isFinite()) -positionRad * pulleyRadiusM else Double.NaN
|
||||
if (!forceKg.isFinite() || !ropeLengthM.isFinite()) return null
|
||||
|
||||
return MotorTelemetrySample(
|
||||
wallTimeMs = nowMs,
|
||||
motorRuntimeSec = obj.firstFinite(Double.NaN, "runtimeSec", "t"),
|
||||
forceN = forceN,
|
||||
forceKg = forceKg,
|
||||
ropeLengthM = ropeLengthM,
|
||||
currentA = currentA,
|
||||
voltageV = obj.firstFinite(Double.NaN, "voltageV", "volt"),
|
||||
tempC = obj.firstFinite(Double.NaN, "tempC", "temp"),
|
||||
dataAgeMs = dataAgeMs,
|
||||
available = available,
|
||||
rawJson = json
|
||||
)
|
||||
}
|
||||
|
||||
private fun JSONObject.firstFinite(fallback: Double, vararg keys: String): Double {
|
||||
for (key in keys) {
|
||||
if (!has(key) || isNull(key)) continue
|
||||
val value = optDouble(key, Double.NaN)
|
||||
if (value.isFinite()) return value
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Phase4B-v11.11 Motor safe UI snapshot cache.
|
||||
*
|
||||
* This cache is intentionally local to the Motor UI component package. It avoids changing
|
||||
* ComponentRegistry, BridgeRepository, Handle, Dongle, Camera, or RuntimeHost status logic.
|
||||
*
|
||||
* RuntimeHost motor debug/query methods have been observed to block the SDK Panel operation
|
||||
* timeout path after idle. The Motor page therefore keeps the chart polling on its own daemon
|
||||
* thread and exposes non-blocking last-known results for UI buttons.
|
||||
*/
|
||||
internal object MotorTelemetrySnapshotCache {
|
||||
private val lock = Any()
|
||||
private var lastRawJson: String? = null
|
||||
private var lastSample: MotorTelemetrySample? = null
|
||||
private var lastUpdateMs: Long = 0L
|
||||
private var lastError: String? = null
|
||||
private var lastErrorMs: Long = 0L
|
||||
private var lastCommandResult: String? = null
|
||||
private var lastCommandAtMs: Long = 0L
|
||||
|
||||
private val asyncLock = Any()
|
||||
private var refreshInFlight: Boolean = false
|
||||
private var lastRefreshAttemptMs: Long = 0L
|
||||
|
||||
private const val REFRESH_MIN_INTERVAL_MS = 500L
|
||||
private const val REFRESH_STUCK_RESET_MS = 15_000L
|
||||
|
||||
fun recordMotorStateJson(json: String, sample: MotorTelemetrySample?) {
|
||||
synchronized(lock) {
|
||||
lastRawJson = json
|
||||
lastSample = sample
|
||||
lastUpdateMs = System.currentTimeMillis()
|
||||
lastError = null
|
||||
lastErrorMs = 0L
|
||||
}
|
||||
}
|
||||
|
||||
fun recordMotorStateError(reason: String) {
|
||||
synchronized(lock) {
|
||||
lastError = reason.ifBlank { "unknown" }
|
||||
lastErrorMs = System.currentTimeMillis()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Phase4B-v11.14: refresh explicit motor runtime-state on a background thread.
|
||||
*
|
||||
* Home-card Motor availability must be based on RuntimeHost motor state, not on whether
|
||||
* the Motor detail page / scatter chart is currently visible. This method never blocks
|
||||
* the SDK Panel availability loop; if RuntimeHost's motor query stalls after idle, the
|
||||
* last-known snapshot remains available and the UI stays responsive.
|
||||
*/
|
||||
fun requestRuntimeStateRefreshAsync(repo: BridgeRepository, reason: String = "") {
|
||||
if (!repo.isBound()) return
|
||||
val now = System.currentTimeMillis()
|
||||
var shouldLaunch = false
|
||||
synchronized(asyncLock) {
|
||||
val stuck = refreshInFlight && lastRefreshAttemptMs > 0L && now - lastRefreshAttemptMs > REFRESH_STUCK_RESET_MS
|
||||
if (!refreshInFlight || stuck) {
|
||||
if (now - lastRefreshAttemptMs >= REFRESH_MIN_INTERVAL_MS || stuck) {
|
||||
refreshInFlight = true
|
||||
lastRefreshAttemptMs = now
|
||||
shouldLaunch = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!shouldLaunch) return
|
||||
|
||||
Thread({
|
||||
try {
|
||||
val json = repo.getLatestMotorStateJson()
|
||||
val sample = MotorTelemetryParser.parse(json)
|
||||
recordMotorStateJson(json, sample)
|
||||
} catch (t: Throwable) {
|
||||
recordMotorStateError("motor-state-refresh failed; reason=$reason; ${t.message ?: t.javaClass.simpleName}")
|
||||
} finally {
|
||||
synchronized(asyncLock) {
|
||||
refreshInFlight = false
|
||||
}
|
||||
}
|
||||
}, "kiwii-motor-state-refresh-v11.14").apply { isDaemon = true }.start()
|
||||
}
|
||||
|
||||
fun submitForceControlParamsAsync(repo: BridgeRepository, paramsJson: String): String {
|
||||
val requestId = "sdkpanel-force-${System.currentTimeMillis()}"
|
||||
Thread({
|
||||
val started = System.currentTimeMillis()
|
||||
val result = try {
|
||||
repo.setMotorForceControlParamsJson(paramsJson)
|
||||
} catch (t: Throwable) {
|
||||
JSONObject().put("error", "setMotorForceControlParamsJson async failed: ${t.message ?: t.javaClass.simpleName}").toString()
|
||||
}
|
||||
recordCommandResult("setMotorForceControlParamsJson", result)
|
||||
SessionLogger.log(LogEntry(
|
||||
timestamp = System.currentTimeMillis(),
|
||||
component = ComponentType.MOTOR,
|
||||
action = "setMotorForceControlParamsJson.asyncResult",
|
||||
params = "requestId=$requestId; elapsedMs=${System.currentTimeMillis() - started}",
|
||||
result = result
|
||||
))
|
||||
requestRuntimeStateRefreshAsync(repo, "after-force-control-command")
|
||||
}, "kiwii-motor-force-command-v11.14").apply { isDaemon = true }.start()
|
||||
|
||||
return JSONObject().apply {
|
||||
put("contractVersion", "kiwii.sdk-panel.motor-command-queued.v1")
|
||||
put("uiPath", "ASYNC_COMMAND_NO_UI_TIMEOUT")
|
||||
put("requestId", requestId)
|
||||
put("action", "setMotorForceControlParamsJson")
|
||||
put("queued", true)
|
||||
val parsedParams = runCatching { JSONObject(paramsJson) }.getOrNull()
|
||||
if (parsedParams != null) put("params", parsedParams) else put("paramsRaw", paramsJson)
|
||||
put("note", "Command is sent on a background thread so the Motor UI does not show a false 2000ms timeout after idle. The async result is appended to the Motor Session Log.")
|
||||
}.toString(2)
|
||||
}
|
||||
|
||||
fun sendMotorHeartbeatAsync(repo: BridgeRepository): String {
|
||||
val requestId = "sdkpanel-heartbeat-${System.currentTimeMillis()}"
|
||||
Thread({
|
||||
val started = System.currentTimeMillis()
|
||||
val result = try {
|
||||
repo.sendMotorHeartbeat()
|
||||
} catch (t: Throwable) {
|
||||
JSONObject().put("error", "sendMotorHeartbeat async failed: ${t.message ?: t.javaClass.simpleName}").toString()
|
||||
}
|
||||
recordCommandResult("sendMotorHeartbeat", result)
|
||||
SessionLogger.log(LogEntry(
|
||||
timestamp = System.currentTimeMillis(),
|
||||
component = ComponentType.MOTOR,
|
||||
action = "sendMotorHeartbeat.asyncResult",
|
||||
params = "requestId=$requestId; elapsedMs=${System.currentTimeMillis() - started}",
|
||||
result = result
|
||||
))
|
||||
requestRuntimeStateRefreshAsync(repo, "after-heartbeat")
|
||||
}, "kiwii-motor-heartbeat-command-v11.14").apply { isDaemon = true }.start()
|
||||
|
||||
return JSONObject().apply {
|
||||
put("contractVersion", "kiwii.sdk-panel.motor-command-queued.v1")
|
||||
put("uiPath", "ASYNC_COMMAND_NO_UI_TIMEOUT")
|
||||
put("requestId", requestId)
|
||||
put("action", "sendMotorHeartbeat")
|
||||
put("queued", true)
|
||||
}.toString(2)
|
||||
}
|
||||
|
||||
private fun recordCommandResult(action: String, result: String) {
|
||||
synchronized(lock) {
|
||||
lastCommandResult = "$action => ${result.take(500)}"
|
||||
lastCommandAtMs = System.currentTimeMillis()
|
||||
}
|
||||
}
|
||||
|
||||
fun homeCardRuntimeStatus(freshTimeoutMs: Long): MotorHomeCardRuntimeStatus {
|
||||
val snapshot = snapshot()
|
||||
val raw = snapshot.rawJson
|
||||
if (raw.isNullOrBlank()) {
|
||||
return MotorHomeCardRuntimeStatus(
|
||||
active = false,
|
||||
contractOk = false,
|
||||
available = false,
|
||||
connected = false,
|
||||
state = "NO_RAW_MOTOR_STATE",
|
||||
blockedByDongleTransport = false,
|
||||
blockedByMotorTelemetry = false,
|
||||
dataAgeMs = Long.MAX_VALUE,
|
||||
snapshotAgeMs = snapshot.snapshotAgeMs,
|
||||
reason = snapshot.lastError ?: "NO_MOTOR_RUNTIME_STATE_SNAPSHOT"
|
||||
)
|
||||
}
|
||||
|
||||
val obj = runCatching { JSONObject(raw) }.getOrNull()
|
||||
?: return MotorHomeCardRuntimeStatus(
|
||||
active = false,
|
||||
contractOk = false,
|
||||
available = false,
|
||||
connected = false,
|
||||
state = "RAW_MOTOR_STATE_NOT_JSON",
|
||||
blockedByDongleTransport = false,
|
||||
blockedByMotorTelemetry = false,
|
||||
dataAgeMs = Long.MAX_VALUE,
|
||||
snapshotAgeMs = snapshot.snapshotAgeMs,
|
||||
reason = "RAW_MOTOR_STATE_NOT_JSON"
|
||||
)
|
||||
|
||||
val contractOk = obj.optString("contractVersion", "") == "kiwii.motor-runtime-state.v1"
|
||||
val available = obj.optBoolean("available", false)
|
||||
val connected = obj.optBoolean("connected", false) ||
|
||||
obj.optBoolean("motorConnected", false) ||
|
||||
obj.optBoolean("online", false)
|
||||
val state = obj.optString("state", obj.optString("motorState", ""))
|
||||
val stateLooksConnected = state.equals("CONNECTED", ignoreCase = true) ||
|
||||
state.equals("ACTIVE", ignoreCase = true) ||
|
||||
state.equals("RUNNING", ignoreCase = true) ||
|
||||
state.equals("ONLINE", ignoreCase = true)
|
||||
val blockedByDongleTransport = obj.optBoolean("blockedByDongleTransport", false)
|
||||
val blockedByMotorTelemetry = obj.optBoolean("blockedByMotorTelemetry", false)
|
||||
val rawDataAgeMs = obj.optLong("dataAgeMs", Long.MAX_VALUE)
|
||||
val dataAgeMs = maxKnownAge(rawDataAgeMs, snapshot.snapshotAgeMs)
|
||||
val freshData = dataAgeMs in 0..freshTimeoutMs
|
||||
val active = contractOk &&
|
||||
!blockedByDongleTransport &&
|
||||
!blockedByMotorTelemetry &&
|
||||
(available || connected || stateLooksConnected) &&
|
||||
freshData
|
||||
|
||||
val reason = when {
|
||||
!contractOk -> "BAD_OR_MISSING_CONTRACT_VERSION"
|
||||
blockedByDongleTransport -> "BLOCKED_BY_DONGLE_TRANSPORT"
|
||||
blockedByMotorTelemetry -> "BLOCKED_BY_MOTOR_TELEMETRY"
|
||||
!(available || connected || stateLooksConnected) -> "MOTOR_RUNTIME_STATE_NOT_CONNECTED"
|
||||
!freshData -> "MOTOR_RUNTIME_STATE_STALE"
|
||||
else -> "MOTOR_RUNTIME_STATE_ACTIVE"
|
||||
}
|
||||
|
||||
return MotorHomeCardRuntimeStatus(
|
||||
active = active,
|
||||
contractOk = contractOk,
|
||||
available = available,
|
||||
connected = connected || stateLooksConnected,
|
||||
state = state.ifBlank { if (connected) "CONNECTED_FLAG" else "" },
|
||||
blockedByDongleTransport = blockedByDongleTransport,
|
||||
blockedByMotorTelemetry = blockedByMotorTelemetry,
|
||||
dataAgeMs = dataAgeMs,
|
||||
snapshotAgeMs = snapshot.snapshotAgeMs,
|
||||
reason = reason
|
||||
)
|
||||
}
|
||||
|
||||
fun latestMotorStateJsonForUi(): String {
|
||||
val snapshot = snapshot()
|
||||
val raw = snapshot.rawJson
|
||||
return if (raw != null) {
|
||||
val obj = runCatching { JSONObject(raw) }.getOrNull() ?: unavailableJson("getLatestMotorStateJson", snapshot).apply {
|
||||
put("rawSnippet", raw.take(240))
|
||||
put("reason", "LAST_RAW_MOTOR_STATE_NOT_JSON")
|
||||
}
|
||||
obj.apply {
|
||||
put("uiPath", "NO_LIVE_BINDER_CALL")
|
||||
put("source", "motor-telemetry-last-known")
|
||||
put("snapshotAgeMs", snapshot.snapshotAgeMs)
|
||||
put("effectiveDataAgeMs", snapshot.sample?.let { maxKnownAge(it.dataAgeMs, snapshot.snapshotAgeMs) } ?: JSONObject.NULL)
|
||||
put("parsedFreshSample", snapshot.sample != null)
|
||||
put("lastError", snapshot.lastError ?: JSONObject.NULL)
|
||||
}.toString(2)
|
||||
} else {
|
||||
unavailableJson("getLatestMotorStateJson", snapshot).toString(2)
|
||||
}
|
||||
}
|
||||
|
||||
fun motorControlStateJsonForUi(): String {
|
||||
val snapshot = snapshot()
|
||||
val sample = snapshot.sample
|
||||
return JSONObject().apply {
|
||||
put("contractVersion", "kiwii.sdk-panel.motor-control-state.ui.v1")
|
||||
put("uiPath", "NO_LIVE_BINDER_CALL")
|
||||
put("source", "motor-telemetry-last-known")
|
||||
put("available", sample != null)
|
||||
put("snapshotAgeMs", snapshot.snapshotAgeMs)
|
||||
put("lastError", snapshot.lastError ?: JSONObject.NULL)
|
||||
put("lastCommandResult", snapshot.lastCommandResult ?: JSONObject.NULL)
|
||||
put("lastCommandAgeMs", snapshot.lastCommandAgeMs)
|
||||
if (sample != null) {
|
||||
put("forceKg", sample.forceKg)
|
||||
put("forceN", sample.forceN)
|
||||
put("ropeLengthM", sample.ropeLengthM)
|
||||
put("currentA", sample.currentA)
|
||||
put("voltageV", sample.voltageV)
|
||||
put("tempC", sample.tempC)
|
||||
put("dataAgeMs", sample.dataAgeMs)
|
||||
put("effectiveDataAgeMs", maxKnownAge(sample.dataAgeMs, snapshot.snapshotAgeMs))
|
||||
put("note", "Control-state live query is intentionally disabled on this UI path because the RuntimeHost query can block after idle. Use RuntimeHost cached telemetry or native logs for raw control internals.")
|
||||
} else {
|
||||
put("reason", "NO_FRESH_MOTOR_TELEMETRY_SNAPSHOT")
|
||||
}
|
||||
}.toString(2)
|
||||
}
|
||||
|
||||
fun trainingModeQueryForUi(mode: Int): String {
|
||||
val snapshot = snapshot()
|
||||
return JSONObject().apply {
|
||||
put("contractVersion", "kiwii.sdk-panel.motor-training-mode-query.ui.v1")
|
||||
put("uiPath", "NO_LIVE_BINDER_CALL")
|
||||
put("requestedMode", mode)
|
||||
put("source", "motor-telemetry-last-known")
|
||||
put("snapshotAgeMs", snapshot.snapshotAgeMs)
|
||||
put("lastError", snapshot.lastError ?: JSONObject.NULL)
|
||||
put("lastCommandResult", snapshot.lastCommandResult ?: JSONObject.NULL)
|
||||
put("lastCommandAgeMs", snapshot.lastCommandAgeMs)
|
||||
put("available", snapshot.rawJson != null || snapshot.sample != null)
|
||||
put("reason", "Live queryMotorTrainingMode is disabled on SDK Panel button path to avoid 2000ms operation timeout after idle.")
|
||||
}.toString(2)
|
||||
}
|
||||
|
||||
fun disconnectDiagnosisForUi(): String {
|
||||
val snapshot = snapshot()
|
||||
return JSONObject().apply {
|
||||
put("contractVersion", "kiwii.sdk-panel.motor-disconnect-diagnosis.ui.v1")
|
||||
put("uiPath", "NO_LIVE_BINDER_CALL")
|
||||
put("source", "motor-telemetry-last-known")
|
||||
put("snapshotAgeMs", snapshot.snapshotAgeMs)
|
||||
put("lastError", snapshot.lastError ?: JSONObject.NULL)
|
||||
put("hasRawMotorState", snapshot.rawJson != null)
|
||||
put("hasFreshParsedTelemetry", snapshot.sample != null)
|
||||
put("diagnosis", when {
|
||||
snapshot.sample != null -> "FRESH_MOTOR_TELEMETRY_AVAILABLE"
|
||||
snapshot.rawJson != null -> "RAW_MOTOR_STATE_SEEN_BUT_NOT_FRESH_OR_NOT_PARSEABLE"
|
||||
snapshot.lastError != null -> "MOTOR_STATE_QUERY_ERROR_OR_TIMEOUT_ON_BACKGROUND_POLL"
|
||||
else -> "NO_MOTOR_TELEMETRY_SNAPSHOT_YET"
|
||||
})
|
||||
put("note", "This is a safe UI diagnosis. It does not perform raw live RuntimeHost motor queries.")
|
||||
}.toString(2)
|
||||
}
|
||||
|
||||
fun dongleSlotEvidenceJson(maxFreshMs: Long = 5_000L): JSONObject? {
|
||||
val status = homeCardRuntimeStatus(maxFreshMs)
|
||||
if (!status.contractOk) return null
|
||||
val hasConnectionEvidence = status.available || status.connected ||
|
||||
status.state.equals("CONNECTED", ignoreCase = true) ||
|
||||
status.state.equals("ACTIVE", ignoreCase = true) ||
|
||||
status.state.equals("RUNNING", ignoreCase = true) ||
|
||||
status.state.equals("ONLINE", ignoreCase = true)
|
||||
if (!hasConnectionEvidence) return null
|
||||
return JSONObject().apply {
|
||||
put("slot", 3)
|
||||
put("state", "CONNECTED")
|
||||
put("connected", true)
|
||||
put("device", "MOTOR_POWER")
|
||||
put("dev", "0x31")
|
||||
put("source", "motor-runtime-state-last-known")
|
||||
put("inferred", true)
|
||||
put("available", status.available)
|
||||
put("runtimeState", status.state)
|
||||
put("dataAgeMs", status.dataAgeMs)
|
||||
put("snapshotAgeMs", status.snapshotAgeMs)
|
||||
put("stale", !status.active)
|
||||
put("rawSlotReport", "not-queried")
|
||||
put("detail", "Connected via explicit motor runtime state; raw dongle slot query skipped")
|
||||
}
|
||||
}
|
||||
|
||||
fun chartSnapshot(freshTimeoutMs: Long = 2_000L): MotorTelemetryChartSnapshot {
|
||||
val snapshot = snapshot()
|
||||
val sample = snapshot.sample
|
||||
val effectiveAgeMs = sample?.let { maxKnownAge(it.dataAgeMs, snapshot.snapshotAgeMs) } ?: Long.MAX_VALUE
|
||||
val reason = when {
|
||||
sample == null && snapshot.rawJson == null -> snapshot.lastError ?: "NO_MOTOR_TELEMETRY_SNAPSHOT_YET"
|
||||
sample == null -> snapshot.lastError ?: "RAW_MOTOR_STATE_NOT_FRESH_OR_NOT_PARSEABLE"
|
||||
effectiveAgeMs !in 0..freshTimeoutMs -> "MOTOR_TELEMETRY_STALE"
|
||||
else -> "MOTOR_TELEMETRY_FRESH"
|
||||
}
|
||||
return MotorTelemetryChartSnapshot(
|
||||
sample = if (effectiveAgeMs in 0..freshTimeoutMs) sample else null,
|
||||
rawJson = snapshot.rawJson,
|
||||
effectiveAgeMs = effectiveAgeMs,
|
||||
snapshotAgeMs = snapshot.snapshotAgeMs,
|
||||
lastError = snapshot.lastError,
|
||||
reason = reason
|
||||
)
|
||||
}
|
||||
|
||||
private fun maxKnownAge(vararg ages: Long): Long {
|
||||
val known = ages.filter { it >= 0L && it != Long.MAX_VALUE }
|
||||
return if (known.isEmpty()) Long.MAX_VALUE else known.maxOrNull() ?: Long.MAX_VALUE
|
||||
}
|
||||
|
||||
private fun unavailableJson(action: String, snapshot: Snapshot): JSONObject {
|
||||
return JSONObject().apply {
|
||||
put("contractVersion", "kiwii.sdk-panel.motor-safe-ui.v1")
|
||||
put("action", action)
|
||||
put("uiPath", "NO_LIVE_BINDER_CALL")
|
||||
put("available", false)
|
||||
put("reason", "NO_MOTOR_TELEMETRY_SNAPSHOT_YET")
|
||||
put("snapshotAgeMs", snapshot.snapshotAgeMs)
|
||||
put("lastError", snapshot.lastError ?: JSONObject.NULL)
|
||||
}
|
||||
}
|
||||
|
||||
private fun snapshot(): Snapshot = synchronized(lock) {
|
||||
val now = System.currentTimeMillis()
|
||||
Snapshot(
|
||||
rawJson = lastRawJson,
|
||||
sample = lastSample,
|
||||
snapshotAgeMs = if (lastUpdateMs > 0L) now - lastUpdateMs else -1L,
|
||||
lastError = lastError?.let { err ->
|
||||
val age = if (lastErrorMs > 0L) now - lastErrorMs else -1L
|
||||
"$err; errorAgeMs=$age"
|
||||
},
|
||||
lastCommandResult = lastCommandResult,
|
||||
lastCommandAgeMs = if (lastCommandAtMs > 0L) now - lastCommandAtMs else -1L
|
||||
)
|
||||
}
|
||||
|
||||
private data class Snapshot(
|
||||
val rawJson: String?,
|
||||
val sample: MotorTelemetrySample?,
|
||||
val snapshotAgeMs: Long,
|
||||
val lastError: String?,
|
||||
val lastCommandResult: String?,
|
||||
val lastCommandAgeMs: Long
|
||||
)
|
||||
}
|
||||
@@ -30,6 +30,16 @@ class RightHandleOps(
|
||||
}
|
||||
})
|
||||
|
||||
layout.addView(createSection("Haptics"))
|
||||
val effectInput = createParameterInput("Effect ID (int)", android.text.InputType.TYPE_CLASS_NUMBER)
|
||||
val staticEffectAction = createButton("submitRightStaticEffect") {
|
||||
val id = effectInput.text.toString().toIntOrNull() ?: 0
|
||||
viewModel.executeOperation(ComponentType.RIGHT_HANDLE, "submitRightStaticEffect", "effectId=$id") {
|
||||
viewModel.bridgeRepo.submitRightStaticEffect(id)
|
||||
}
|
||||
}
|
||||
layout.addView(createParameterActionRow(staticEffectAction, effectInput))
|
||||
|
||||
val streamIdInput = createParameterInput("Stream ID (int)", android.text.InputType.TYPE_CLASS_NUMBER)
|
||||
val payloadInput = createParameterInput("Payload (String)", android.text.InputType.TYPE_CLASS_TEXT)
|
||||
val heStreamAction = createButton("submitRightHeStream") {
|
||||
|
||||
@@ -2,6 +2,9 @@ package com.kiwii.controlpanel.ui.components
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.util.Log
|
||||
import android.view.View
|
||||
import android.widget.TextView
|
||||
import android.widget.Toast
|
||||
@@ -16,6 +19,7 @@ class SessionLogOps(context: Context) : BaseOps(context) {
|
||||
|
||||
override fun createView(): View {
|
||||
val layout = verticalLayout()
|
||||
val handler = Handler(Looper.getMainLooper())
|
||||
|
||||
val logView = TextView(context).apply {
|
||||
textSize = 11f
|
||||
@@ -30,10 +34,30 @@ class SessionLogOps(context: Context) : BaseOps(context) {
|
||||
logView.text = entries.joinToString("\n") { entry ->
|
||||
val time = sdf.format(Date(entry.timestamp))
|
||||
val comp = entry.component?.displayName ?: "GLOBAL"
|
||||
"$time [$comp] ${entry.action}: ${entry.result?.take(60) ?: ""}"
|
||||
val params = entry.params?.let { " [$it]" } ?: ""
|
||||
"$time [$comp] ${entry.action}$params: ${entry.result?.take(120) ?: ""}"
|
||||
}.ifEmpty { "No logs" }
|
||||
Log.i(TAG_SESSION, "Phase4B-v7 session log refreshed; entries=${entries.size}")
|
||||
}
|
||||
|
||||
val refreshRunnable = object : Runnable {
|
||||
override fun run() {
|
||||
refreshLog()
|
||||
handler.postDelayed(this, 1000L)
|
||||
}
|
||||
}
|
||||
|
||||
layout.addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener {
|
||||
override fun onViewAttachedToWindow(v: View) {
|
||||
handler.removeCallbacks(refreshRunnable)
|
||||
handler.post(refreshRunnable)
|
||||
}
|
||||
|
||||
override fun onViewDetachedFromWindow(v: View) {
|
||||
handler.removeCallbacks(refreshRunnable)
|
||||
}
|
||||
})
|
||||
|
||||
layout.addView(createButton("Refresh") { refreshLog() })
|
||||
layout.addView(createButton("Export") {
|
||||
val uri = SessionLogger.export(context)
|
||||
@@ -58,4 +82,8 @@ class SessionLogOps(context: Context) : BaseOps(context) {
|
||||
|
||||
return layout
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG_SESSION = "KiwiiSDKPanelSession"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,7 +143,7 @@ class ComponentDetailFragment : Fragment() {
|
||||
viewModel.stateSnapshot.collect { snapshot ->
|
||||
if (snapshot != null) {
|
||||
latestStateText = JsonFormatter.format(snapshot.data)
|
||||
val items = parseStateItems(snapshot.data)
|
||||
val items = RuntimeHostStatusParser.parse(snapshot.data, viewModel.bridgeRepo.isBound())
|
||||
.ifEmpty { listOf(StatItem("State", "Updated")) }
|
||||
stateAdapter.submitList(items)
|
||||
val sdf = SimpleDateFormat("HH:mm:ss", Locale.getDefault())
|
||||
@@ -179,16 +179,6 @@ class ComponentDetailFragment : Fragment() {
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseStateItems(json: String): List<StatItem> {
|
||||
return if (componentType == ComponentType.MOTOR) {
|
||||
MotorRuntimeStateParser.parse(json).ifEmpty {
|
||||
RuntimeHostStatusParser.parse(json, viewModel.bridgeRepo.isBound())
|
||||
}
|
||||
} else {
|
||||
RuntimeHostStatusParser.parse(json, viewModel.bridgeRepo.isBound())
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun observeLogs() {
|
||||
viewModel.logEntries.collect { entries ->
|
||||
val visibleEntries = entries.takeLast(80).ifEmpty {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.kiwii.controlpanel.ui.detail
|
||||
|
||||
import android.util.Log
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.kiwii.controlpanel.data.AarProxyStateSource
|
||||
@@ -11,6 +12,7 @@ import com.kiwii.controlpanel.logging.SessionLogger
|
||||
import com.kiwii.controlpanel.model.ComponentType
|
||||
import com.kiwii.controlpanel.model.OperationResult
|
||||
import com.kiwii.controlpanel.model.StateSnapshot
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
@@ -19,21 +21,38 @@ import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.TimeoutException
|
||||
|
||||
private const val TAG_OPS = "KiwiiSDKPanelOps"
|
||||
|
||||
class ComponentDetailViewModel : ViewModel() {
|
||||
|
||||
val bridgeRepo = BridgeRepository()
|
||||
private val runtimeStateRepo = RuntimeStateRepository(AarProxyStateSource(bridgeRepo))
|
||||
private val statePoller = StatePoller(runtimeStateRepo, bridgeRepo, SessionLogger)
|
||||
private val operationExecutor = Executors.newCachedThreadPool()
|
||||
|
||||
private val _operationResult = MutableStateFlow<OperationResult<*>?>(null)
|
||||
val operationResult: StateFlow<OperationResult<*>?> = _operationResult
|
||||
|
||||
private val _componentType = MutableStateFlow(ComponentType.RUNTIME_HOST_STATUS)
|
||||
private val _manualStateSnapshot = MutableStateFlow<Pair<ComponentType, StateSnapshot>?>(null)
|
||||
|
||||
val stateSnapshot: StateFlow<StateSnapshot?> = _componentType
|
||||
.combine(statePoller.states) { type, map -> map[type] }
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), null)
|
||||
val stateSnapshot: StateFlow<StateSnapshot?> = combine(
|
||||
_componentType,
|
||||
statePoller.states,
|
||||
_manualStateSnapshot
|
||||
) { type, map, manual ->
|
||||
val polled = map[type]
|
||||
val manualSnapshot = if (manual?.first == type) manual.second else null
|
||||
when {
|
||||
manualSnapshot != null && (polled == null || manualSnapshot.updatedAt >= polled.updatedAt) -> manualSnapshot
|
||||
else -> polled
|
||||
}
|
||||
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), null)
|
||||
|
||||
private val _logEntries = MutableStateFlow<List<LogEntry>>(emptyList())
|
||||
val logEntries: StateFlow<List<LogEntry>> = _logEntries
|
||||
@@ -42,7 +61,7 @@ class ComponentDetailViewModel : ViewModel() {
|
||||
statePoller.startPolling()
|
||||
viewModelScope.launch {
|
||||
while (isActive) {
|
||||
_logEntries.value = SessionLogger.getEntriesForComponent(_componentType.value)
|
||||
refreshVisibleLogs()
|
||||
delay(1000)
|
||||
}
|
||||
}
|
||||
@@ -50,6 +69,8 @@ class ComponentDetailViewModel : ViewModel() {
|
||||
|
||||
fun setComponentType(type: ComponentType) {
|
||||
_componentType.value = type
|
||||
statePoller.setFocusedComponent(type)
|
||||
refreshVisibleLogs()
|
||||
}
|
||||
|
||||
fun <T> executeOperation(
|
||||
@@ -59,9 +80,21 @@ class ComponentDetailViewModel : ViewModel() {
|
||||
block: () -> T
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
val result = bridgeRepo.callAsync(block)
|
||||
val startedAt = System.currentTimeMillis()
|
||||
Log.i(TAG_OPS, "Phase4B-v11 control click started; component=$componentType; action=$actionName; params=${params ?: ""}")
|
||||
SessionLogger.log(LogEntry(
|
||||
timestamp = startedAt,
|
||||
component = componentType,
|
||||
action = "TX:$actionName",
|
||||
params = params,
|
||||
result = "STARTED"
|
||||
))
|
||||
refreshVisibleLogs()
|
||||
|
||||
val result = callBlockingWithTimeout(actionName, block)
|
||||
_operationResult.value = result
|
||||
|
||||
val now = System.currentTimeMillis()
|
||||
val resultStr = when (result) {
|
||||
is OperationResult.Success<*> -> result.data.toString()
|
||||
is OperationResult.Error -> "ERROR: ${result.exception.message}"
|
||||
@@ -69,20 +102,69 @@ class ComponentDetailViewModel : ViewModel() {
|
||||
is OperationResult.NoData -> "NO_DATA"
|
||||
}
|
||||
|
||||
if (componentType == _componentType.value && result is OperationResult.Success<*> && result.data is String) {
|
||||
val text = result.data.trim()
|
||||
if (text.startsWith("{")) {
|
||||
_manualStateSnapshot.value = componentType to StateSnapshot(
|
||||
data = result.data,
|
||||
updatedAt = now,
|
||||
isDebugChannel = false
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
val elapsedMs = now - startedAt
|
||||
Log.i(TAG_OPS, "Phase4B-v11 control click completed; component=$componentType; action=$actionName; elapsedMs=$elapsedMs; resultKind=${result.javaClass.simpleName}")
|
||||
SessionLogger.log(LogEntry(
|
||||
timestamp = System.currentTimeMillis(),
|
||||
timestamp = now,
|
||||
component = componentType,
|
||||
action = actionName,
|
||||
action = "RX:$actionName",
|
||||
params = params,
|
||||
result = resultStr
|
||||
))
|
||||
|
||||
_logEntries.value = SessionLogger.getEntriesForComponent(_componentType.value)
|
||||
refreshVisibleLogs()
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun <T> callBlockingWithTimeout(
|
||||
actionName: String,
|
||||
block: () -> T
|
||||
): OperationResult<T> = withContext(Dispatchers.IO) {
|
||||
val future = operationExecutor.submit<OperationResult<T>> {
|
||||
try {
|
||||
val result = block()
|
||||
if (result == null || (result is String && result.isBlank())) {
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
OperationResult.NoData as OperationResult<T>
|
||||
} else {
|
||||
OperationResult.Success(result)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
OperationResult.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
future.get(OPERATION_TIMEOUT_MS, TimeUnit.MILLISECONDS)
|
||||
} catch (e: TimeoutException) {
|
||||
future.cancel(true)
|
||||
OperationResult.Error(Exception("$actionName timed out after ${OPERATION_TIMEOUT_MS}ms"))
|
||||
} catch (e: Exception) {
|
||||
OperationResult.Error(Exception("$actionName failed: ${e.message}", e))
|
||||
}
|
||||
}
|
||||
|
||||
private fun refreshVisibleLogs() {
|
||||
_logEntries.value = SessionLogger.getEntriesForComponent(_componentType.value)
|
||||
}
|
||||
|
||||
override fun onCleared() {
|
||||
super.onCleared()
|
||||
statePoller.stopPolling()
|
||||
operationExecutor.shutdownNow()
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val OPERATION_TIMEOUT_MS = 2000L
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,13 @@ object LogColorizer {
|
||||
fun classify(entry: LogEntry): EntryType {
|
||||
if (entry.isStateChange) return EntryType.SYS
|
||||
val action = entry.action.lowercase()
|
||||
|
||||
// Phase4B-v10: explicit TX/RX action prefixes must win over result-based inference.
|
||||
// Otherwise a visible click marker such as action="TX:readDongleState" with
|
||||
// result="STARTED" is incorrectly rendered as [RX] TX:readDongleState => STARTED.
|
||||
if (action.startsWith("tx:")) return EntryType.TX
|
||||
if (action.startsWith("rx:")) return EntryType.RX
|
||||
|
||||
if (action.contains("poll") || action.contains("stream") || action == "snapshot" || action == "connection") {
|
||||
return EntryType.SYS
|
||||
}
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
package com.kiwii.controlpanel.ui.detail
|
||||
|
||||
import com.kiwii.bridge.MotorRuntimeState
|
||||
import java.util.Locale
|
||||
|
||||
/** 将 AAR 的 MotorRuntimeState 映射成详情页状态卡片。 */
|
||||
object MotorRuntimeStateParser {
|
||||
|
||||
fun parse(json: String): List<StatItem> {
|
||||
val state = try {
|
||||
MotorRuntimeState.fromJson(json)
|
||||
} catch (_: Throwable) {
|
||||
return emptyList()
|
||||
}
|
||||
|
||||
return listOf(
|
||||
StatItem("Available", state.available.toString()),
|
||||
StatItem("Last Key", formatKey(state.lastKey), "motor uplink key"),
|
||||
StatItem("Runtime", formatFloat(state.runtimeSec), "s"),
|
||||
StatItem("Current", formatFloat(state.currentA), "A"),
|
||||
StatItem("Torque", formatFloat(state.torqueNm), "N.m"),
|
||||
StatItem("Velocity Rad", formatFloat(state.velocityRadps), "rad/s"),
|
||||
StatItem("Velocity", formatFloat(state.velocityMps), "m/s"),
|
||||
StatItem("Position", formatFloat(state.positionRad), "rad"),
|
||||
StatItem("Extension", formatFloat(state.extensionM), "m"),
|
||||
StatItem("Voltage", formatFloat(state.voltageV), "V"),
|
||||
StatItem("Temperature", formatFloat(state.tempC), "C"),
|
||||
StatItem("Sys", state.sys.toString()),
|
||||
StatItem("Merr", state.merr.toString()),
|
||||
StatItem("OBD", state.obd.toString()),
|
||||
StatItem("Seq ID", state.seqId.toString()),
|
||||
StatItem("T Data", state.tDataUnixMs.toString(), "Unix ms"),
|
||||
StatItem("Fault", state.faultSummary.ifBlank { "none" }),
|
||||
StatItem("Host Arrival", state.hostArrivalNs.toString(), "ns"),
|
||||
StatItem("Last Upload", state.lastUploadNs.toString(), "ns"),
|
||||
StatItem("Data Age", state.dataAgeMs.toString(), "ms"),
|
||||
StatItem("Raw Line", state.rawLine.compact(), "raw debug")
|
||||
)
|
||||
}
|
||||
|
||||
private fun formatKey(key: Int): String = String.format(Locale.US, "0x%02X (%d)", key, key)
|
||||
|
||||
private fun formatFloat(value: Float): String = String.format(Locale.US, "%.4f", value)
|
||||
|
||||
private fun String.compact(): String {
|
||||
return if (length > 48) "${take(45)}..." else this
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.kiwii.controlpanel.ui.detail
|
||||
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
@@ -14,28 +15,36 @@ data class StatItem(
|
||||
val detail: String = ""
|
||||
)
|
||||
|
||||
/** 从 RuntimeState JSON 中动态提取所有顶层字段为 StatItem 列表 */
|
||||
/** 从 RuntimeState JSON 中动态提取字段为 StatItem 列表 */
|
||||
object RuntimeHostStatusParser {
|
||||
|
||||
fun parse(json: String, isBound: Boolean): List<StatItem> {
|
||||
val items = mutableListOf<StatItem>()
|
||||
|
||||
val obj = try {
|
||||
JSONObject(json)
|
||||
} catch (_: Exception) {
|
||||
return items
|
||||
return emptyList()
|
||||
}
|
||||
|
||||
if (looksLikeDongleState(obj)) {
|
||||
return parseDongleState(obj)
|
||||
}
|
||||
|
||||
val items = mutableListOf<StatItem>()
|
||||
val keys = obj.keys()
|
||||
while (keys.hasNext()) {
|
||||
val key = keys.next()
|
||||
val raw = obj.opt(key) ?: continue
|
||||
val item = when {
|
||||
raw is JSONObject -> StatItem(
|
||||
val item = when (raw) {
|
||||
is JSONObject -> StatItem(
|
||||
label = humanize(key),
|
||||
value = raw.optString("state", raw.optString("value", "…")).compactValue(),
|
||||
detail = raw.optString("detail", "")
|
||||
)
|
||||
is JSONArray -> StatItem(
|
||||
label = humanize(key),
|
||||
value = "${raw.length()} items",
|
||||
detail = raw.toString().compactDetail()
|
||||
)
|
||||
else -> StatItem(
|
||||
label = humanize(key),
|
||||
value = raw.toString().compactValue()
|
||||
@@ -47,6 +56,186 @@ object RuntimeHostStatusParser {
|
||||
return items
|
||||
}
|
||||
|
||||
private fun looksLikeDongleState(obj: JSONObject): Boolean {
|
||||
val contract = obj.optString("contractVersion", "").lowercase()
|
||||
if (contract.contains("dongle")) return true
|
||||
if (obj.has("dongle") && obj.has("handleState")) return true
|
||||
if (obj.has("transport") && (obj.has("slots") || obj.has("slotStatus") || obj.has("slotStates"))) return true
|
||||
if (obj.has("transport") && obj.optJSONObject("transport")?.has("usbPresent") == true) return true
|
||||
return false
|
||||
}
|
||||
|
||||
/** Phase4B-v11.5: Dongle State = operational state first; raw dongle query may be disabled on safe UI path. */
|
||||
private fun parseDongleState(obj: JSONObject): List<StatItem> {
|
||||
val items = mutableListOf<StatItem>()
|
||||
val transport = obj.optJSONObject("transport") ?: obj.optJSONObject("dongle")?.optJSONObject("transport") ?: JSONObject()
|
||||
|
||||
val transportState = firstNonBlank(
|
||||
transport.optString("state", ""),
|
||||
obj.optString("state", ""),
|
||||
if (transport.optBooleanFlexible("active") || transport.optBooleanFlexible("connected") || obj.optBooleanFlexible("active")) "ACTIVE" else "UNKNOWN"
|
||||
)
|
||||
|
||||
val usbPresent = transport.optBooleanFlexible("usbPresent")
|
||||
val bridge = transport.optBooleanFlexible("usbBridgeRegistered")
|
||||
val readLoop = transport.optBooleanFlexible("readLoopRunning")
|
||||
|
||||
items += StatItem(
|
||||
label = "Transport",
|
||||
value = transportState.compactValue(),
|
||||
detail = if (transport.optString("rawDongleQuery", "") == "disabled-on-detail-ui-path") "safe path; raw transport skipped" else "usb=${usbPresent.renderBool("present", "missing")}; bridge=${bridge.renderBool("registered", "no")}; readLoop=${readLoop.renderBool("running", "stopped")}"
|
||||
)
|
||||
items += StatItem(
|
||||
label = "USB",
|
||||
value = usbPresent.renderBool("PRESENT", "MISSING"),
|
||||
detail = endpointDetail(transport)
|
||||
)
|
||||
items += StatItem(
|
||||
label = "Bridge",
|
||||
value = bridge.renderBool("REGISTERED", "NO"),
|
||||
detail = "RuntimeHost USB bridge"
|
||||
)
|
||||
items += StatItem(
|
||||
label = "Read Loop",
|
||||
value = readLoop.renderBool("RUNNING", "STOPPED"),
|
||||
detail = ageDetail(transport)
|
||||
)
|
||||
|
||||
val slotEvidenceNote = firstNonBlank(
|
||||
obj.optString("slotEvidenceNote", ""),
|
||||
normalizeLegacySlotDiagnostic(obj.optString("slotDiagnostic", ""))
|
||||
)
|
||||
if (slotEvidenceNote.isNotBlank()) {
|
||||
items += StatItem(
|
||||
label = "Slot Evidence",
|
||||
value = "INFERRED",
|
||||
detail = slotEvidenceNote.compactDetail(72)
|
||||
)
|
||||
}
|
||||
|
||||
val slots = firstSlotArray(obj)
|
||||
for (slotIndex in 0..3) {
|
||||
items += parseSlot(slotIndex, slots)
|
||||
}
|
||||
|
||||
return items
|
||||
}
|
||||
|
||||
private fun firstSlotArray(obj: JSONObject): JSONArray? {
|
||||
obj.optJSONArray("slots")?.let { return it }
|
||||
obj.optJSONArray("slotStatus")?.let { return it }
|
||||
obj.optJSONArray("slotStates")?.let { return it }
|
||||
obj.optJSONObject("dongle")?.optJSONArray("slots")?.let { return it }
|
||||
obj.optJSONObject("status")?.optJSONArray("slots")?.let { return it }
|
||||
return null
|
||||
}
|
||||
|
||||
private fun parseSlot(slotIndex: Int, slots: JSONArray?): StatItem {
|
||||
val slot = findSlotObject(slotIndex, slots)
|
||||
if (slot == null) {
|
||||
return StatItem(
|
||||
label = "Slot $slotIndex",
|
||||
value = "UNKNOWN",
|
||||
detail = "No raw slot report"
|
||||
)
|
||||
}
|
||||
|
||||
val connected = slot.optBooleanFlexible("connected") || slot.optBooleanFlexible("available") || slot.optBooleanFlexible("active")
|
||||
val state = firstNonBlank(
|
||||
slot.optString("state", ""),
|
||||
slot.optString("status", ""),
|
||||
if (connected) "CONNECTED" else "DISCONNECTED"
|
||||
)
|
||||
val device = firstNonBlank(
|
||||
slot.optString("device", ""),
|
||||
slot.optString("dev", ""),
|
||||
slot.optString("deviceType", ""),
|
||||
slot.optString("deviceId", "")
|
||||
)
|
||||
val seq = firstNonBlank(slot.optString("sequenceId", ""), slot.optString("seq", ""))
|
||||
val source = slot.optString("source", "")
|
||||
val rawSlotReport = slot.optString("rawSlotReport", "")
|
||||
val inferred = slot.optBoolean("inferred", false)
|
||||
val explicitDetail = slot.optString("detail", "")
|
||||
|
||||
val detailParts = mutableListOf<String>()
|
||||
if (device.isNotBlank()) detailParts += "device=$device"
|
||||
if (seq.isNotBlank() && seq != "0") detailParts += "seq=$seq"
|
||||
val age = slot.optLongOrNull("dataAgeMs") ?: slot.optLongOrNull("ageMs")
|
||||
if (age != null && age >= 0L) detailParts += "age=${age}ms"
|
||||
if (source.isNotBlank()) detailParts += "source=$source"
|
||||
if (rawSlotReport.isNotBlank()) detailParts += "rawSlotReport=$rawSlotReport"
|
||||
if (inferred) detailParts += "inferred=true"
|
||||
if (explicitDetail.isNotBlank()) detailParts += explicitDetail
|
||||
|
||||
return StatItem(
|
||||
label = "Slot $slotIndex",
|
||||
value = state.compactValue(),
|
||||
detail = detailParts.joinToString("; ").ifBlank { "reported" }.compactDetail(72)
|
||||
)
|
||||
}
|
||||
|
||||
private fun findSlotObject(slotIndex: Int, slots: JSONArray?): JSONObject? {
|
||||
if (slots == null) return null
|
||||
for (i in 0 until slots.length()) {
|
||||
val obj = slots.optJSONObject(i) ?: continue
|
||||
val reportedIndex = obj.optIntOrNull("slot") ?: obj.optIntOrNull("slotId") ?: obj.optIntOrNull("index")
|
||||
if (reportedIndex == slotIndex) return obj
|
||||
}
|
||||
return slots.optJSONObject(slotIndex)
|
||||
}
|
||||
|
||||
private fun endpointDetail(transport: JSONObject): String {
|
||||
val epIn = firstNonBlank(transport.optString("epIn", ""), transport.optString("endpointIn", ""))
|
||||
val epOut = firstNonBlank(transport.optString("epOut", ""), transport.optString("endpointOut", ""))
|
||||
return when {
|
||||
epIn.isNotBlank() || epOut.isNotBlank() -> "in=$epIn out=$epOut".trim()
|
||||
else -> firstNonBlank(transport.optString("device", ""), transport.optString("product", ""), "USB CDC")
|
||||
}.compactDetail()
|
||||
}
|
||||
|
||||
private fun ageDetail(transport: JSONObject): String {
|
||||
val inAge = transport.optLongOrNull("lastUsbInAgeMs")
|
||||
val outAge = transport.optLongOrNull("lastUsbOutAgeMs")
|
||||
val parts = mutableListOf<String>()
|
||||
if (inAge != null) parts += "inAge=${inAge}ms"
|
||||
if (outAge != null) parts += "outAge=${outAge}ms"
|
||||
return parts.joinToString("; ").ifBlank { "USB read loop state" }
|
||||
}
|
||||
|
||||
private fun firstNonBlank(vararg values: String): String = values.firstOrNull { it.isNotBlank() } ?: ""
|
||||
|
||||
private fun normalizeLegacySlotDiagnostic(value: String): String {
|
||||
if (value.isBlank()) return ""
|
||||
if (value.contains("Right Handle is connected in handle-state", ignoreCase = true)) {
|
||||
return "Slot 1 inferred from Right Handle IMU; raw slot not queried."
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
private fun Boolean.renderBool(yes: String, no: String): String = if (this) yes else no
|
||||
|
||||
private fun JSONObject.optBooleanFlexible(key: String): Boolean {
|
||||
if (!has(key)) return false
|
||||
val raw = opt(key) ?: return false
|
||||
return when (raw) {
|
||||
is Boolean -> raw
|
||||
is Number -> raw.toInt() != 0
|
||||
is String -> raw.equals("true", ignoreCase = true) || raw == "1" || raw.equals("yes", ignoreCase = true) || raw.equals("connected", ignoreCase = true) || raw.equals("active", ignoreCase = true) || raw.equals("running", ignoreCase = true)
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
private fun JSONObject.optIntOrNull(key: String): Int? {
|
||||
if (!has(key)) return null
|
||||
return try { optInt(key) } catch (_: Exception) { null }
|
||||
}
|
||||
|
||||
private fun JSONObject.optLongOrNull(key: String): Long? {
|
||||
if (!has(key)) return null
|
||||
return try { optLong(key) } catch (_: Exception) { null }
|
||||
}
|
||||
|
||||
/** camelCase / snake_case → 可读标签 */
|
||||
private fun humanize(key: String): String {
|
||||
return key
|
||||
@@ -59,4 +248,9 @@ object RuntimeHostStatusParser {
|
||||
return replace("\"", "")
|
||||
.let { if (it.length > 16) "${it.take(14)}..." else it }
|
||||
}
|
||||
|
||||
private fun String.compactDetail(maxLen: Int = 48): String {
|
||||
return replace("\"", "")
|
||||
.let { if (it.length > maxLen) "${it.take(maxLen - 3)}..." else it }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
package com.kiwii.controlpanel
|
||||
|
||||
import com.kiwii.controlpanel.ui.detail.MotorRuntimeStateParser
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class MotorRuntimeStateParserTest {
|
||||
|
||||
@Test
|
||||
fun `parse maps new motor runtime fields`() {
|
||||
val json = """
|
||||
{
|
||||
"contractVersion": "kiwii.motor-runtime-state.v1",
|
||||
"available": true,
|
||||
"lastKey": 175,
|
||||
"runtimeSec": 12.5,
|
||||
"currentA": 1.25,
|
||||
"torqueNm": 2.5,
|
||||
"velocityRadps": 3.5,
|
||||
"velocityMps": 4.5,
|
||||
"positionRad": 5.5,
|
||||
"extensionM": 0.25,
|
||||
"voltageV": 24.0,
|
||||
"tempC": 36.5,
|
||||
"sys": 7,
|
||||
"merr": 8,
|
||||
"obd": 9,
|
||||
"seqId": 10,
|
||||
"tDataUnixMs": 1710000000000,
|
||||
"faultSummary": "ok",
|
||||
"hostArrivalNs": 111,
|
||||
"lastUploadNs": 222,
|
||||
"dataAgeMs": 333,
|
||||
"rawLine": "motor raw debug line",
|
||||
"rawJson": "{\"available\":true}"
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
val items = MotorRuntimeStateParser.parse(json)
|
||||
|
||||
assertEquals("true", items.first { it.label == "Available" }.value)
|
||||
assertEquals("0xAF (175)", items.first { it.label == "Last Key" }.value)
|
||||
assertEquals("12.5000", items.first { it.label == "Runtime" }.value)
|
||||
assertEquals("ms", items.first { it.label == "Data Age" }.detail)
|
||||
assertEquals("motor raw debug line", items.first { it.label == "Raw Line" }.value)
|
||||
assertTrue(items.none { it.label == "Raw Json" })
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user