Add stats collection and first-run on-glasses onboarding app

This commit is contained in:
James Babcock committed 2026-10-10 17:33:32 -07:00
1 parent 84baee9c76
commit 406cefe0c5
73 files changed
+3906 -98

No files matched your search

@@ -0,0 +1,44 @@
package com.faceclaw.app
import kotlin.jvm.JvmStatic
/**
* Process-wide counts of connection-reliability events: connect attempts,
* transport failures by reason, ack timeouts, CFW replays, arm drops, how long
* sessions lasted, and the like. The phone app's analytics drains them
* (app/native/connection-counters.ts, app/analytics/). Only counts under fixed
* event names are kept, never addresses or message contents. They pile up in
* memory whether or not analytics is on; the app throws a drain away when it
* is off.
*/
object ConnectionCounters {
/** Distinct names kept between drains; new names past this are dropped. */
private const val MAX_NAMES = 200
private val lock = protocolPlatform().createLock()
private var counts = LinkedHashMap<String, Long>()
@JvmStatic
fun increment(name: String) {
lock.withLock {
val current = counts[name]
if (current != null) counts[name] = current + 1
else if (counts.size < MAX_NAMES) counts[name] = 1
}
}
/** The counts since the last drain, as a JSON object of name to count, and starts over. */
@JvmStatic
fun drain(): String {
val drained = lock.withLock {
val out = counts
counts = LinkedHashMap()
out
}
return Json.write(drained)
}
/** An event name from fixed text: "CFW recovery retry limit" -> "cfw-recovery-retry-limit". */
@JvmStatic
fun slug(text: String): String = text.lowercase().replace(Regex("[^a-z0-9]+"), "-").trim('-').take(60)
}
@@ -359,6 +359,7 @@ internal fun GlassesSessionCore.firstUnpairedArm(): String? {
*/
internal fun GlassesSessionCore.handleUnpairedFailure(address: String) {
logError("Connect failed and $address is not paired; suspending reconnect")
ConnectionCounters.increment("g2.unpaired")
monitor.withLock { haltReconnectLocked("arm not paired: $address") }
if (!userDisconnectRequested) {
setStateDisplay(
@@ -387,6 +388,7 @@ internal fun GlassesSessionCore.handleIncompatibleFirmware() {
incompatibleFirmware = null
pending
} ?: return
ConnectionCounters.increment("g2.incompatible-firmware")
logError("Glasses report incompatible firmware L=" + info.leftVersion + " R=" + info.rightVersion
+ " ext=\"" + info.extension + "\" (need Faceclaw/" + requiredFirmwareRevision + "); suspending reconnect")
monitor.withLock { haltReconnectLocked("incompatible firmware") }
@@ -429,11 +431,13 @@ internal fun GlassesSessionCore.haltReconnectLocked(reason: String) {
*/
internal fun GlassesSessionCore.handleTransportFailure(reason: String?, displayStatus: String? = null) {
logError("Transport failure: $reason")
ConnectionCounters.increment("g2.failure." + ConnectionCounters.slug(reason ?: "unknown"))
val retryDelayMs: Long
monitor.withLock {
maybeEmitEvenAppConflictLocked(reason)
finishBenchmarkLocked(true, "transport failure")
val sessionWasReady = sessionReady
if (sessionWasReady) countSessionEnded("failure")
sessionReady = false
fixedLayoutCreated = false
startupProbePending = false
@@ -460,6 +464,23 @@ internal fun GlassesSessionCore.handleTransportFailure(reason: String?, displayS
interruptibleSleep.interrupt()
}
/**
* Counts a ready session ending, by [cause] and by how long it had been up
* (for the analytics in app/analytics/).
*/
internal fun GlassesSessionCore.countSessionEnded(cause: String) {
ConnectionCounters.increment("g2.session-end.$cause")
val minutes = (now() - lastSessionReadyAtMs) / 60_000
ConnectionCounters.increment(
"g2.session-length." + when {
minutes < 1 -> "under-1m"
minutes < 10 -> "1m-10m"
minutes < 60 -> "10m-1h"
else -> "over-1h"
}
)
}
/**
* Set [reconnectAfterMs] for the next attempt after a failure and return the delay. Repeated
* failures back off along RECONNECT_BACKOFF_MS; a session that stayed up for
@@ -737,6 +758,7 @@ internal fun GlassesSessionCore.maybeEmitEvenAppConflictLocked(reason: String?)
return
}
lastEvenAppConflictAtMs = now
ConnectionCounters.increment("g2.even-app-conflict")
emitEvenAppConflict("The Even Realities app still appears to be running. It can hold the glasses BLE link and cause Faceclaw write failures. Open its app settings and force stop it, then reconnect Faceclaw.")
}
@@ -410,6 +410,8 @@ class GlassesSessionCore(
releaseFaceclawFramebufferLease()
}
monitor.withLock {
ConnectionCounters.increment("g2.disconnect-requested")
if (sessionReady) countSessionEnded("requested")
userDisconnectRequested = true
running = false
audioCaptureActive = false
@@ -1384,6 +1386,7 @@ class GlassesSessionCore(
val ingress = if (message.isLeftArmMessage) leftAddress else rightAddress
if (message.sid == CfwTransport.SID && address.equals(ingress, ignoreCase = true) && message.magic == ack.streamId) {
message.acceptCfwAck(ack)
if (ack.nack) ConnectionCounters.increment("g2.cfw-nack")
logLine("CFW " + (if (ack.nack) "NACK" else "ACK") + " id=" + ack.streamId
+ " ordinal=" + ack.messageId + " lens=" + ack.lens + " txseq=" + (data[2].toInt() and 255)
+ " redundant=" + (ack !== acks[0])
@@ -1583,6 +1586,11 @@ class GlassesSessionCore(
if (decoded.eventType == BleProtocol.EVENT_ABNORMAL_EXIT || decoded.eventType == BleProtocol.EVENT_SYSTEM_EXIT) {
if (shutdownRequested) {
lastShutdownExitAtMs = now()
} else {
ConnectionCounters.increment(
if (decoded.eventType == BleProtocol.EVENT_ABNORMAL_EXIT) "g2.firmware-abnormal-exit"
else "g2.firmware-system-exit"
)
}
fixedLayoutCreated = false
displayedFingerprint = ""
@@ -1691,6 +1699,7 @@ class GlassesSessionCore(
ringReconnectAfterMs = now() + ConnectionOptions.RING_RECONNECT_DELAY_MS
}
}
ConnectionCounters.increment(if (connected) "ring.direct.connect" else "ring.direct.disconnect")
logLine(if (connected) "direct ring BLE connected" else "direct ring BLE disconnected")
interruptibleSleep.interrupt()
return
@@ -1709,6 +1718,12 @@ class GlassesSessionCore(
// dropping mid-setup): the connect sequence notices on its own and
// schedules the retry, so leave the backoff alone.
lostSession = sessionReady
if (lostSession) {
ConnectionCounters.increment(
if (address.equals(rightAddress, ignoreCase = true)) "g2.arm-drop.right" else "g2.arm-drop.left"
)
countSessionEnded("arm-drop")
}
sessionReady = false
fixedLayoutCreated = false
startupProbePending = false
@@ -1740,6 +1755,7 @@ class GlassesSessionCore(
wearState = -1
}
setStateDisplay("connecting", "Connecting to the glasses...")
ConnectionCounters.increment("g2.connect-attempt")
try {
// Dial both arms at once, so the left arm's attempt is already pending (and
// can land) while the right arm is being set up; they share one window.
@@ -1793,6 +1809,7 @@ class GlassesSessionCore(
}
}
setStateDisplay("connected", "Connected.")
ConnectionCounters.increment("g2.session-ready")
logLine("session ready")
monitor.withLock {
// Query settings at the start of every session so firmware
@@ -1999,6 +2016,7 @@ class GlassesSessionCore(
monitor.withLock {
if (!inFlightMessages.isEmpty()) {
clearInFlightMessagesLocked("security auth timeout")
ConnectionCounters.increment("g2.auth-unacknowledged")
logLine("security auth not acknowledged; continuing (2.2.9 stock requires it; older/custom firmware may not answer)")
return
}
@@ -2025,7 +2043,7 @@ class GlassesSessionCore(
prelude.onAck = MessageCallback {
}
prelude.onTimeout = MessageCallback {
handleTransportFailure("ack timeout")
handleTransportFailure("prelude ack timeout")
}
prelude.sentAtMs = now
writeMessage(prelude)
@@ -87,6 +87,7 @@ internal fun GlassesSessionCore.driveSession(): Long {
val oldest = inFlightMessages.firstOrNull()
val replay = CfwMessageWindow.replayWindow(inFlightMessages, now)
if (!replay.isEmpty()) {
ConnectionCounters.increment("g2.cfw-replay")
logLine("CFW recovery: replay " + replay.size
+ " unresolved message(s) from id=" + replay[0].magic)
for (candidate in replay) {
@@ -665,7 +666,7 @@ internal fun GlassesSessionCore.enqueueCreateLayoutLocked() {
}
startupProbePending = false
}
handleTransportFailure("ack timeout")
handleTransportFailure("create layout ack timeout")
}
pendingMessages.addLast(message)
logLine("queue create layout")
@@ -706,7 +707,7 @@ internal fun GlassesSessionCore.enqueueStartupProbeLocked() {
if (hasPendingOrInflightKindLocked("create-layout")) {
return@MessageCallback
}
handleTransportFailure("ack timeout")
handleTransportFailure("startup probe ack timeout")
}
pendingMessages.addLast(message)
startupProbePending = true
@@ -1279,6 +1280,7 @@ internal fun GlassesSessionCore.hasPendingMagicLocked(sid: Int, magic: Int): Boo
internal fun GlassesSessionCore.handleAckTimeoutLocked(message: OutboundMessage) {
consecutiveAckTimeouts += 1
ConnectionCounters.increment("g2.ack-timeout")
val onTimeout = message.onTimeout
if (onTimeout != null) {
@@ -584,6 +584,7 @@ class IosBleCentral(private val platform: ProtocolPlatform = IosProtocolPlatform
private fun onDisconnected(peripheral: CBPeripheral, error: NSError?) {
val peer = remember(peripheral)
if (error != null) ConnectionCounters.increment("ble.ios-disconnect-error." + error.code)
failPeer(peer, error?.localizedDescription ?: "Disconnected", notifyListeners = true)
}