diff --git a/.gitignore b/.gitignore index 8515643e..6659b26a 100644 --- a/.gitignore +++ b/.gitignore @@ -67,3 +67,6 @@ native/kotlin/plugin/platforms/ios/ tests/kotlin/.gradle/ tests/kotlin/.kotlin/ tests/kotlin/build/ + +# tools/health-preview.cjs output (rendered PNGs, regenerate with the tool) +preview/ diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/AndroidSessionLink.kt b/App_Resources/Android/src/main/java/com/faceclaw/app/AndroidSessionLink.kt index 146c5006..2921e222 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/AndroidSessionLink.kt +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/AndroidSessionLink.kt @@ -6,6 +6,9 @@ import android.bluetooth.BluetoothGatt class AndroidSessionLink(private val bleManager: FaceclawBleManager) : SessionLink { override fun connect(address: String, timeoutMs: Int): Boolean = bleManager.connect(address, timeoutMs) + override fun connect(address: String, timeoutMs: Int, autoConnect: Boolean): Boolean = + bleManager.connect(address, timeoutMs, autoConnect) + override fun beginConnect(address: String, background: Boolean): Boolean = bleManager.beginConnect(address, background) override fun isConnected(address: String): Boolean = bleManager.isConnected(address) diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicator.kt b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicator.kt index cdc7d5a5..e384d0da 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicator.kt +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicator.kt @@ -2,6 +2,9 @@ package com.faceclaw.app import android.annotation.SuppressLint import android.app.KeyguardManager +import android.bluetooth.BluetoothDevice +import android.bluetooth.BluetoothManager +import android.bluetooth.BluetoothProfile import android.content.BroadcastReceiver import android.content.Context import android.content.Intent @@ -34,6 +37,40 @@ class FaceclawBleCommunicator(context: Context, rightAddress: String?, leftAddre fun getActive(): FaceclawBleCommunicator? { return activeInstance } + + /** + * The phone's own Bluetooth view of the ring, independent of whether a + * session is running or configured to talk to the ring: bond state, + * whether any app on the phone holds a GATT link, and the (hidden-API, + * best-effort) ACL connection. JSON; fields are null when unknown. + */ + @JvmStatic + fun getSystemBluetoothStateJson(context: Context, address: String?): String { + val result = org.json.JSONObject() + val trimmed = address?.trim()?.uppercase() ?: "" + result.put("address", trimmed) + try { + val manager = context.applicationContext.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager? + val adapter = manager?.adapter + if (manager == null || adapter == null || trimmed.isEmpty() || !android.bluetooth.BluetoothAdapter.checkBluetoothAddress(trimmed)) { + return result.toString() + } + val device = adapter.getRemoteDevice(trimmed) + result.put("bonded", device.bondState == BluetoothDevice.BOND_BONDED) + result.put("gattConnected", + manager.getConnectionState(device, BluetoothProfile.GATT) == BluetoothProfile.STATE_CONNECTED) + try { + val isConnected = BluetoothDevice::class.java.getMethod("isConnected") + result.put("aclConnected", isConnected.invoke(device) as Boolean) + } catch (_: Throwable) { + // Hidden API unavailable; leave unknown. + } + result.put("name", device.name ?: org.json.JSONObject.NULL) + } catch (t: Throwable) { + result.put("error", t.message ?: t.toString()) + } + return result.toString() + } } private val appContext: Context = context.applicationContext @@ -46,6 +83,7 @@ class FaceclawBleCommunicator(context: Context, rightAddress: String?, leftAddre private val mainHandler = Handler(Looper.getMainLooper()) private val mainDispatcher = SessionDispatcher { action -> mainHandler.post { action() } } @Volatile private var workerThread: Thread? = null + @Volatile private var ringWorkerThread: Thread? = null private var g2ScreenWakeLock: PowerManager.WakeLock? = null private var phoneLockReceiverRegistered = false @@ -83,6 +121,29 @@ class FaceclawBleCommunicator(context: Context, rightAddress: String?, leftAddre workerThread = null } + override fun startRingWorker(body: () -> Unit) { + val thread = Thread(body, "FaceclawRing") + ringWorkerThread = thread + thread.start() + } + + override fun interruptRingWorker() { + ringWorkerThread?.interrupt() + } + + override fun supportsRingHealth(): Boolean = true + + override fun appendRingFrameJournal(line: String) { + val folder = java.io.File(appContext.filesDir, "health") + if (!folder.isDirectory && !folder.mkdirs()) { + throw java.io.IOException("cannot create health folder") + } + java.io.FileOutputStream(java.io.File(folder, "ring-frames.jsonl"), true).use { out -> + out.write(line.toByteArray(Charsets.UTF_8)) + out.fd.sync() + } + } + override fun log(level: SessionLogLevel, tag: String, message: String, error: Throwable?) { when (level) { SessionLogLevel.DEBUG -> Log.d(tag, message) @@ -157,6 +218,18 @@ class FaceclawBleCommunicator(context: Context, rightAddress: String?, leftAddre fun isSessionReady(): Boolean = core.isSessionReady() + /** See [GlassesSessionCore.requestRingHealthNow]. */ + fun requestRingHealthNow() = core.requestRingHealthNow() + + /** See [GlassesSessionCore.takeRingHealthBatch]. */ + fun takeRingHealthBatch(): RingHealthBatch = core.takeRingHealthBatch() + + /** See [GlassesSessionCore.clearRingHealthRecordsBelow]. */ + fun clearRingHealthRecordsBelow(watermark: Long): Int = core.clearRingHealthRecordsBelow(watermark) + + /** See [GlassesSessionCore.getRingHealthRecords]. */ + fun getRingHealthRecords(): List = core.getRingHealthRecords() + /** See [GlassesSessionCore.isAudioCaptureActive]. */ fun isAudioCaptureActive(): Boolean = core.isAudioCaptureActive() @@ -189,6 +262,20 @@ class FaceclawBleCommunicator(context: Context, rightAddress: String?, leftAddre /** Status/results of the current or most recent benchmark run, as JSON. */ fun getBandwidthBenchmarkStatus(): String = core.getBandwidthBenchmarkStatus() + /** See [GlassesSessionCore.getRingStatus]. */ + fun getRingStatus(): String = core.getRingStatus() + + /** See [GlassesSessionCore.setGlassesRingLink]. */ + fun setGlassesRingLink(action: String, fallbackAddress: String?, fallbackName: String?): Boolean = + core.setGlassesRingLink(action, fallbackAddress, fallbackName) + + /** See [GlassesSessionCore.sendRingConfigCommand]. */ + fun sendRingConfigCommand(action: String, fallbackAddress: String?, fallbackName: String?): String = + core.sendRingConfigCommand(action, fallbackAddress, fallbackName) + + /** See [GlassesSessionCore.setDirectRingRole]. */ + fun setDirectRingRole(role: String?) = core.setDirectRingRole(role) + fun addImuListener(listener: FaceclawImuListener?) = core.addImuListener(listener) fun removeImuListener(listener: FaceclawImuListener?) = core.removeImuListener(listener) diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleManager.kt b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleManager.kt index 163b4ce5..fd303744 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleManager.kt +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleManager.kt @@ -41,7 +41,7 @@ class FaceclawBleManager(context: Context) { // devices, so every GATT operation in the process is serialized on this one lock, // across manager instances too (the session and each stock-firmware flow own one). // An operation holds it until its completion callback; waiting for a connection - // to come up does not. + // to come up, or backing off before a write retry, does not. private val bluetoothApiLock = Any() // Listener callbacks run here, in arrival order, instead of on the binder thread @@ -121,6 +121,7 @@ class FaceclawBleManager(context: Context) { private val links = ConcurrentHashMap() private val negotiatedMtus = ConcurrentHashMap() + private val messageLocks = ConcurrentHashMap() @Volatile private var pendingOp: PendingOp? = null @@ -192,9 +193,24 @@ class FaceclawBleManager(context: Context) { return startConnect(requireAddress(address), background) != null } - fun connect(address: String?, timeoutMs: Int): Boolean { + fun connect(address: String?, timeoutMs: Int): Boolean = connect(address, timeoutMs, false) + + /** + * EXPERIMENTAL (2026-09-11): the ring specifically needs autoConnect=true. + * Even's own vendor app connects the ring with Android's autoConnect flag + * set (confirmed via its own BLE debug log, "connect() - device: ..., + * auto: true"), while every other faceclaw connection (both glasses arms) + * uses autoConnect=false. Direct connect (false) is faster to establish + * but Android supervises it less patiently; a live test showed the + * ring-only direct connection dying almost exactly 5 seconds in, + * repeatedly, with nothing else competing for it. autoConnect=true can + * take much longer to actually complete (Android manages it as a + * background reconnect, not an immediate attempt), so this needs its own + * longer timeout. Like [connect], waits on an attempt already pending. + */ + fun connect(address: String?, timeoutMs: Int, autoConnect: Boolean): Boolean { val key = requireAddress(address) - val link = startConnect(key, false) ?: return false + val link = startConnect(key, autoConnect) ?: return false if (link.connected) { return true } @@ -403,6 +419,14 @@ class FaceclawBleManager(context: Context) { } } + /** + * Writes [frames] in order. The global API lock is held for each frame's + * write-and-callback (one GATT operation in flight process-wide), but not + * across the whole message or during retry backoff, so a slow or failing + * link (the direct ring) can't hold the glasses off the air for a whole + * retry cycle. The per-address lock keeps concurrent messages to the same + * device from interleaving their frames. + */ fun writeFrames( address: String, characteristicUuid: String, @@ -415,9 +439,13 @@ class FaceclawBleManager(context: Context) { } val startMs = System.currentTimeMillis() - synchronized(bluetoothApiLock) { - val gatt = requireGatt(address) - val characteristic = requireCharacteristic(gatt, characteristicUuid) + synchronized(messageLock(address)) { + val gatt: BluetoothGatt + val characteristic: BluetoothGattCharacteristic + synchronized(bluetoothApiLock) { + gatt = requireGatt(address) + characteristic = requireCharacteristic(gatt, characteristicUuid) + } for (i in frames.indices) { val frame = frames[i] @@ -443,45 +471,49 @@ class FaceclawBleManager(context: Context) { ): Boolean { var retryCount = 0 while (true) { - val op = PendingOp(address, OpKind.WRITE) - pendingOp = op - try { - if (!isConnected(address)) { - Log.w(TAG, "writeCharacteristic abandoned: link lost: address=$address") - return false - } - val result = gatt.writeCharacteristic(characteristic, data!!, writeType) - if (result != android.bluetooth.BluetoothStatusCodes.SUCCESS) { - if (!isConnected(address)) { + val retryReason: String + synchronized(bluetoothApiLock) { + val op = PendingOp(address, OpKind.WRITE) + pendingOp = op + try { + // The lock is released between frames and retries, so the client may + // have dropped (or been replaced by a reconnect) since the write started. + if (!isCurrentClient(address, gatt)) { Log.w(TAG, "writeCharacteristic abandoned: link lost: address=$address") return false } - val reason = if (result == android.bluetooth.BluetoothStatusCodes.ERROR_GATT_WRITE_REQUEST_BUSY) - "busy" - else - "start result=$result" - if (!sleepBeforeWriteRetry(address, reason, retryCount++)) { - return false + val result = gatt.writeCharacteristic(characteristic, data!!, writeType) + if (result != android.bluetooth.BluetoothStatusCodes.SUCCESS) { + if (!isCurrentClient(address, gatt)) { + Log.w(TAG, "writeCharacteristic abandoned: link lost: address=$address") + return false + } + retryReason = if (result == android.bluetooth.BluetoothStatusCodes.ERROR_GATT_WRITE_REQUEST_BUSY) + "busy" + else + "start result=$result" + } else { + if (!awaitLatch(op.latch, timeoutMs)) { + Log.w(TAG, "writeCharacteristic timed out after ${timeoutMs}ms waiting for completion: address=$address") + return false + } + val status = op.status + if (status == BluetoothGatt.GATT_SUCCESS) { + return true + } + if (status == STATUS_LINK_LOST) { + Log.w(TAG, "writeCharacteristic abandoned: link lost: address=$address") + return false + } + retryReason = "callback status=$status" } - continue + } finally { + pendingOp = null } - if (!awaitLatch(op.latch, timeoutMs)) { - Log.w(TAG, "writeCharacteristic timed out after ${timeoutMs}ms waiting for completion: address=$address") - return false - } - val status = op.status - if (status == BluetoothGatt.GATT_SUCCESS) { - return true - } - if (status == STATUS_LINK_LOST) { - Log.w(TAG, "writeCharacteristic abandoned: link lost: address=$address") - return false - } - if (!sleepBeforeWriteRetry(address, "callback status=$status", retryCount++)) { - return false - } - } finally { - pendingOp = null + } + // Back off outside the lock so other devices' operations proceed. + if (!sleepBeforeWriteRetry(address, retryReason, retryCount++)) { + return false } } } @@ -555,6 +587,17 @@ class FaceclawBleManager(context: Context) { } } + /** Whether [gatt] is still the connected client for [address]. */ + private fun isCurrentClient(address: String, gatt: BluetoothGatt): Boolean { + val link = links[address] + return link != null && link.connected && link.gatt === gatt + } + + /** Serializes whole multi-frame messages per device; taken before [bluetoothApiLock], never after. */ + private fun messageLock(address: String): Any { + return messageLocks.getOrPut(address) { Any() } + } + private fun requireAddress(address: String?): String { if (address == null || address.trim().isEmpty()) { throw IllegalArgumentException("address is required") diff --git a/App_Resources/iOS/Info.plist b/App_Resources/iOS/Info.plist index 99f28b6b..77b3edd1 100644 --- a/App_Resources/iOS/Info.plist +++ b/App_Resources/iOS/Info.plist @@ -13,7 +13,7 @@ CFBundleDisplayName Faceclaw CFBundleShortVersionString - 0.8.5 + 0.8.6 CFBundleVersion 1 LSRequiresIPhoneOS diff --git a/CHANGELOG b/CHANGELOG index 15db3649..125d7a77 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,17 +1,22 @@ # Changelog -## 0.8.6 - Future +## 0.8.6 - 2026-11-01 +* Connect directly to the R1 ring rather than indirectly via the glasses +* Add a Health app and glanceboard card for viewing R1 ring data * Add a distance unit option * Make BLE benchmark work on iOS * Ensure connection is re-set to 2M on reconnect -* Add support for embedded icons and custom layouts in Android notifications +* Android: Add support for embedded icons and custom layouts (enables messaging apps to show sender profile pictures in notifications) * Port the Developer app's resource-usage monitor and various test pages to iOS * iOS: Support Apple Intelligence as an on-device model for voice assistant/etc * iOS: Notifications are selectable via the task switcher * Android: Optionally sign in to Spotify's Web API for library browsing and other features +* Add options for custom OpenAI-compatible agents for the voice assistant +* Add integration option with Venice assistant * Mark stock firmware 2.4.0 as validated for installing custom firmware over + ## 0.8.5 - 2026-10-25 ### Features diff --git a/app/app.css b/app/app.css index 8b4ba544..0eb26377 100644 --- a/app/app.css +++ b/app/app.css @@ -407,3 +407,681 @@ Button.-primary { .ns-dark .transcript-play { color: #7da7f5; } + + + +/* + * The cover screen (phone-ui/cover-glance.xml): what the phone shows while the + * Fold is shut. It reuses .home-card and .home-section-title wholesale — the + * cover screen is the same product, laid out for a glance, not a second visual + * language — and adds only what a one-screenful layout needs. + */ +.cover-glance { + padding: 12 12 16 12; +} + +.cover-glance-card { + vertical-align: center; + margin-top: 0; +} + +.cover-glance-app { + font-size: 20; + font-weight: bold; + color: #222222; +} + +.cover-glance-text { + font-size: 15; + color: #444444; + margin-top: 6; +} + +.cover-glance-hint { + font-size: 12; + color: #888888; + text-align: center; + margin-top: 12; +} + +.ns-dark .cover-glance-app { + color: #f0f0f0; +} + +.ns-dark .cover-glance-text { + color: #cfcfcf; +} + +.ns-dark .cover-glance-hint { + color: #909090; +} + +/* + * Ghost's companion (phone-ui/ghost-companion.xml). The pilot's own palette is + * deliberately NOT ported: it was a black OLED mockup with phosphor-green + * accents standing in for a whole OS shell, and this screen lives inside the + * Faceclaw app, whose light/dark surfaces every other page already uses. What + * carries over is the structure — header, tab bar, one pane, docked compose — + * and the monospace treatment of the raw views, which is load-bearing. + */ +.ghost-app { + background-color: #ffffff; +} + +/* The one header row every companion view shares — phone-ui/exocortex-header + * .xml. One line, and it replaces BOTH the app-switch bar and the per-app + * wordmark/status header that used to stack above the content. */ +.exocortex-header { + padding: 5 14; + background-color: #f4f4f4; + border-bottom-width: 1; + border-bottom-color: #dddddd; +} + +/* The tap target back to the hub, so it is coloured like the link it is. */ +.exocortex-header-home { + font-family: monospace; + font-size: 12; + letter-spacing: 0.12; + color: #3b6fd6; +} + +.exocortex-header-sep { + font-size: 12; + color: #aaaaaa; + margin-left: 6; + margin-right: 6; +} + +/* The star column: the app name takes the slack and truncates before it + * pushes the connection status off the row. */ +.exocortex-header-app { + font-size: 13; + font-weight: bold; + color: #222222; +} + +.exocortex-header-status { + font-size: 12; + color: #666666; +} + +/* The two segments that came down from the ActionBar when main-page lost it + * (round 3). Both are collapsed-width by default in the grid, so they cost + * nothing horizontally until they are drawn — and nothing vertically ever, + * since the row was already there. The padding is the tap target: these are + * Labels, so without it the hit box is the glyph. */ + +/* The emoji brings its own yellow. Collapsed unless a warning is live. */ +.exocortex-header-warning { + font-size: 14; + padding: 2 4; + margin-left: 6; +} + +/* Coloured like the link it is, matching the "Exocortex" tap target at the + * other end of the row. */ +.exocortex-header-settings { + font-size: 15; + color: #3b6fd6; + padding: 2 4; + margin-left: 8; +} + +.ghost-tab-bar { + padding: 2 8 3 8; +} + +/* SHORTER, still four real buttons (Chris, round 2: "shrink the four pane-nav + * buttons - still functional, just shorter"). An Android Button carries a + * 48dp minimum height from the platform theme, so the explicit height is what + * actually shrinks it; padding alone would not. */ +.ghost-tab { + font-size: 12; + height: 30; + padding: 3 0; + margin: 0 2; + border-radius: 6; + background-color: #e2e2e2; + color: #333333; +} + +.ghost-tab-active { + background-color: #424242; + color: #ffffff; +} + +/* The explicit background is LOAD-BEARING, not decoration. Rich view used to + * survive the live-theme-switch bug (the app reads the system theme once at + * launch and never re-subscribes, so a mid-session switch leaves foreground + * and background disagreeing — Terminal and Doc go white-on-white) purely + * because every turn was a card carrying its own background colour. Removing + * those cards to fix the turn-grouping bug would have removed that immunity + * with them. Painting the pane body instead keeps background and text driven + * by the SAME .ns-dark state, at the container rather than per row. */ +.ghost-pane-body { + padding: 8 16 16 16; + background-color: #ffffff; +} + +.ghost-empty { + font-size: 14; + color: #666666; + padding: 24 0; + text-align: center; +} + +/* Rich view renders one logical TURN as a continuous block: consecutive prose + * runs together at one weight, and tool activity collapses to small muted + * marker lines BETWEEN the prose. Deliberately NOT a card per row — round 4 + * gave every transcript entry the same bordered box with a bold 16pt + * headline, so a one-line `Read foo.ts` marker outweighed the reply it sat + * inside. Same convention cc-web's own rich view already proves + * (apps/claude-code-web/src/public/style.css, `.rich-tool-lines`): "muted so + * prose stays primary." */ +.ghost-seg { + padding-left: 2; + padding-right: 2; +} + +/* The separator lives at the END of a logical turn, not between its own + * segments — that is what makes one reply read as one block. */ +.ghost-seg-end { + padding-bottom: 14; + margin-bottom: 14; + border-bottom-width: 1; + border-bottom-color: #e2e2e2; +} + +/* The segment the LENS has under its cursor. The phone and the glasses are + * two views of one session, so the phone says where the wearer is rather than + * keeping a cursor of its own. A left rule rather than a box, so marking it + * cannot reintroduce the per-segment card this pass removed. */ +.ghost-seg-current { + border-left-width: 3; + border-left-color: #3b6fd6; + padding-left: 9; +} + +.ghost-seg-who { + font-size: 11; + text-transform: uppercase; + letter-spacing: 0.08; + color: #666666; + margin-bottom: 3; +} + +/* Prose is the content. One weight, no headline split — splitHeadlineBody() + * is the glasses digest's convention and does not belong on a full reply. */ +.ghost-seg-prose { + font-size: 16; + color: #222222; + margin-top: 2; + margin-bottom: 2; +} + +/* Tool markers: small, monospace, muted, and almost no vertical space. */ +.ghost-seg-tool { + font-family: monospace; + font-size: 11; + color: #8a8a8a; + margin-top: 3; + margin-bottom: 3; +} + +/* Surfaced AskUserQuestion turns — a side channel, tinted so they do not read + * as something Ghost said mid-sentence. Must stay AFTER .ghost-seg-prose: + * both classes are applied to the same Label. */ +.ghost-seg-question { + border-left-width: 3; + border-left-color: #a371f7; + padding-left: 10; +} + +.ghost-seg-answer { + border-left-width: 3; + border-left-color: #3fb950; + padding-left: 10; +} + +/* Not a live terminal — the undigested feed. Monospace because the alignment + * is the point: this pane exists for the moment Rich view looks wrong. */ +.ghost-terminal { + font-family: monospace; + font-size: 12; + color: #222222; + padding: 12 16; +} + +.ghost-doc-bar { + padding: 10 16; + background-color: #f4f4f4; + border-bottom-width: 1; + border-bottom-color: #dddddd; +} + +.ghost-doc-path { + font-size: 13; + color: #666666; +} + +.ghost-doc-close { + font-size: 16; + color: #666666; + padding: 0 8; + background-color: transparent; +} + +/* The container the rendered markdown blocks sit in. `color` and `font-size` + * are inheritable in NativeScript, so every .doc-md Label below picks its body + * text up from here and only overrides what it actually changes. The explicit + * background is the same load-bearing one .ghost-pane-body carries: without it + * this pane goes white-on-white after a live theme switch. */ +.ghost-doc-body { + font-size: 15; + color: #222222; + background-color: #ffffff; + padding: 14 16 24 16; +} + +/* ── Doc viewer: rendered markdown (2026-09-03) ───────────────────────────── + * One Label per parsed block (phone-ui/markdown-render.ts). Block-level + * treatment lives here; the inline runs (bold / italic / code / link) are + * spans built in ghost-companion-view-model.ts, because a Span's weight and + * family cannot be reached from CSS. */ +.doc-md { + margin-bottom: 8; +} + +.doc-md-h1 { + font-size: 21; + margin-top: 14; + margin-bottom: 6; +} + +.doc-md-h2 { + font-size: 18; + margin-top: 14; + margin-bottom: 6; +} + +.doc-md-h3 { + font-size: 16; + margin-top: 12; + margin-bottom: 4; +} + +.doc-md-h4 { + font-size: 15; + margin-top: 12; + margin-bottom: 4; +} + +.doc-md-li { + margin-bottom: 4; +} + +/* Nesting depth, clamped at three by the parser so a deep list cannot indent + * itself off the side of a phone. */ +.doc-md-li-d0 { + margin-left: 4; +} + +.doc-md-li-d1 { + margin-left: 20; +} + +.doc-md-li-d2 { + margin-left: 36; +} + +.doc-md-li-d3 { + margin-left: 52; +} + +.doc-md-code { + font-family: monospace; + font-size: 13; + color: #333333; + background-color: #f2f2f2; + border-radius: 6; + padding: 8 10; +} + +.doc-md-quote { + border-left-width: 3; + border-left-color: #c8c8c8; + padding-left: 10; + color: #555555; +} + +/* An empty Label doing the job of an
: the block carries no text, so its + * height and colour are the whole rule. */ +.doc-md-rule { + height: 1; + margin: 12 0; + background-color: #dddddd; +} + +.ghost-setting { + padding: 10 12; + margin-bottom: 8; + border-radius: 10; + border-width: 1; + border-color: #dddddd; + background-color: #f4f4f4; +} + +.ghost-setting-label { + font-size: 15; + font-weight: bold; + color: #222222; +} + +.ghost-setting-desc { + font-size: 12; + color: #666666; + margin-top: 2; +} + +.ghost-setting-field { + font-size: 14; + color: #222222; + background-color: #ffffff; + margin-top: 6; +} + +/* The one thing this screen does that the lens cannot, so it is docked rather + * than reached for. */ +.ghost-compose { + padding: 8 12 12 12; + border-top-width: 1; + border-top-color: #dddddd; + background-color: #f4f4f4; +} + +/* 48, not the 88 it was. CHECKED, not assumed: NativeScript core has a + * minHeightProperty but NO max-height, so letting this auto-size would grow + * the docked bar without a ceiling as you type and push the panes off screen. + * A fixed height scrolls internally instead, which is the right behaviour for + * a bar docked under the content it is about. */ +.ghost-compose-input { + height: 48; + font-size: 15; + color: #222222; + background-color: #ffffff; + border-radius: 8; + padding: 8; +} + +.ghost-send { + margin-left: 8; +} + +.ghost-compose-status { + font-size: 12; + color: #a04040; + margin-top: 4; +} + +.ns-dark .ghost-app { + background-color: #1c1c1c; +} + +.ns-dark .exocortex-header, +.ns-dark .ghost-doc-bar, +.ns-dark .ghost-compose { + border-bottom-color: #4a4a4a; + border-top-color: #4a4a4a; +} + +.ns-dark .exocortex-header, +.ns-dark .ghost-doc-bar, +.ns-dark .ghost-compose { + background-color: #2e2e2e; +} + +.ns-dark .exocortex-header-app, +.ns-dark .ghost-seg-prose, +.ns-dark .ghost-terminal, +.ns-dark .ghost-doc-body, +.ns-dark .ghost-setting-label { + color: #f0f0f0; +} + +.ns-dark .exocortex-header-status, +.ns-dark .ghost-empty, +.ns-dark .ghost-seg-who, +.ns-dark .ghost-doc-path, +.ns-dark .ghost-setting-desc { + color: #a0a0a0; +} + +.ns-dark .exocortex-header-sep { + color: #6a6a6a; +} + +.ns-dark .ghost-seg-tool { + color: #909090; +} + +/* See .ghost-pane-body's own comment: this pairing is what keeps Rich view + * readable now that it no longer boxes every segment. */ +.ns-dark .ghost-pane-body { + background-color: #1e1e1e; +} + +.ns-dark .ghost-seg-end { + border-bottom-color: #3d3d3d; +} + +.ns-dark .exocortex-header-home, +.ns-dark .exocortex-header-settings { + color: #8ab0ff; +} + +.ns-dark .ghost-setting { + background-color: #2e2e2e; + border-color: #4a4a4a; +} + +.ns-dark .ghost-seg-current { + border-left-color: #8ab0ff; +} + +.ns-dark .ghost-setting-field, +.ns-dark .ghost-compose-input { + color: #f0f0f0; + background-color: #1c1c1c; +} + +.ns-dark .ghost-tab { + background-color: #3a3a3a; + color: #e0e0e0; +} + +.ns-dark .ghost-tab-active { + background-color: #8ab0ff; + color: #101010; +} + +.ns-dark .ghost-compose-status { + color: #ff9a8a; +} + +/* Exocortex's own phone settings screens (Settings, Notification sources, + * Apps on the glasses). Card rows rather than the flat `.settings-row` used + * by the mirror page's controls: these are a list you read down, and a + * comfortable thumb target matters more here than density. */ +.exo-row { + background-color: #f4f4f4; + border-color: #dddddd; + border-width: 1; + border-radius: 10; + padding: 12 14; + margin-bottom: 8; +} + +.settings-value { + font-size: 14; + color: #3b6fd6; + margin-left: 12; +} + +.app-order-button { + font-size: 18; + width: 40; + padding: 0; + margin: 0 0 0 4; + background-color: transparent; + color: #3b6fd6; +} + +.ns-dark .exo-row { + background-color: #2e2e2e; + border-color: #4a4a4a; +} + +.ns-dark .settings-value, +.ns-dark .app-order-button { + color: #8ab0ff; +} + +/* Doc viewer's rendered markdown, dark. Only what actually differs: the body + * text colour already comes from .ns-dark .ghost-doc-body above. */ +.ns-dark .ghost-doc-body { + background-color: #1c1c1c; +} + +.ns-dark .doc-md-code { + color: #d8d8d8; + background-color: #262626; +} + +.ns-dark .doc-md-quote { + border-left-color: #4a4a4a; + color: #b0b0b0; +} + +.ns-dark .doc-md-rule { + background-color: #3a3a3a; +} + +/* The app list's own container paints its own background (2026-09-03). The + * real cause of "the ghost app rendered on the app grid's background" was the + * broken visibility binding fixed in main-page.xml, not a transparent view — + * but the two bodies share one grid cell, so whichever is up must own its + * backdrop rather than depending on the other being gone. Belt as well as + * braces: the same class of bug (a view not painting its own background) is + * what the live-theme-switch failure was made of too. */ +.exocortex-home-body { + background-color: #ffffff; +} + +.ns-dark .exocortex-home-body { + background-color: #1c1c1c; +} + +/* ------------------------------------------------------------------------ + * HEALTH (phone-ui/health-page.xml) + * + * The chart is a grayscale bitmap produced by the same GrayImage renderer the + * glasses use, so it arrives as light-on-black whatever the phone theme is. + * Rather than fight that, the chart gets an explicit dark plate in BOTH + * themes - it reads as an instrument panel inset into the page, which is the + * one place a fixed dark surface is defensible in a light-themed app. The + * chrome around it (chips, stat rows) follows the theme normally. + */ + +.health-chart { + background-color: #101010; + border-radius: 10; + margin: 10 0 6 0; +} + +.health-chip { + font-size: 13; + color: #444444; + background-color: #f0f0f0; + border-color: #dddddd; + border-width: 1; + border-radius: 14; + padding: 6 12; + margin: 2 6 2 0; +} + +.health-chip-on { + color: #ffffff; + background-color: #222222; + border-color: #222222; +} + +.health-chip-scroll { + margin-top: 4; +} + +.health-stat-row { + padding: 7 2; +} + +.health-stat-label { + font-size: 13; + color: #666666; +} + +.health-stat-value { + font-size: 15; + font-weight: bold; + color: #222222; +} + +.health-stat-panel { + margin-left: 16; +} + +.health-badge { + font-size: 11; + color: #8a6d00; + background-color: #fff3cd; + border-color: #ffe08a; + border-width: 1; + border-radius: 8; + padding: 3 8; +} + +/* Not debug leftover - see health-page.xml's header. */ +.health-layout-meta { + font-size: 11; + color: #999999; + margin-top: 14; +} + +.ns-dark .health-chip { + color: #cccccc; + background-color: #2a2a2a; + border-color: #3a3a3a; +} + +.ns-dark .health-chip-on { + color: #111111; + background-color: #e8e8e8; + border-color: #e8e8e8; +} + +.ns-dark .health-stat-label { + color: #999999; +} + +.ns-dark .health-stat-value { + color: #f0f0f0; +} + +.ns-dark .health-badge { + color: #ffd97a; + background-color: #3a3320; + border-color: #5a4c1f; +} + +.ns-dark .health-layout-meta { + color: #777777; +} diff --git a/app/apps/all-apps.ts b/app/apps/all-apps.ts index 9e2494ed..9effebf0 100644 --- a/app/apps/all-apps.ts +++ b/app/apps/all-apps.ts @@ -8,6 +8,7 @@ import t3codeApp from "./t3code"; import filesApp from "./files"; import musicApp from "./music"; import nightscoutApp from "./nightscout"; +import healthApp from "./health"; import transcribeApp from "./transcribe"; import translateApp from "./translate"; import teleprompterApp from "./teleprompter"; @@ -44,6 +45,7 @@ export const ALL_APPS: readonly AppDefinition[] = [ filesApp, musicApp, nightscoutApp, + healthApp, transcribeApp, translateApp, teleprompterApp, diff --git a/app/apps/developer/developer-app.ts b/app/apps/developer/developer-app.ts index 08e9ca50..a7faf8cd 100644 --- a/app/apps/developer/developer-app.ts +++ b/app/apps/developer/developer-app.ts @@ -8,6 +8,7 @@ import { BandwidthBenchmarkLayer } from "./bandwidth-benchmark"; import { LightSensorDemoLayer } from "./light-sensor-demo"; import { MicrophonesMonitorLayer } from "./microphones-monitor"; import { ResourceUsageLayer } from "./resource-usage"; +import { RingStatusLayer } from "./ring-status"; import { LoadAppFromQrLayer, LoadAppFromUrlLayer } from "./load-app"; import { unicodeTestMenu } from "./unicode-test"; import { type AppContext } from "../app-definition"; @@ -66,6 +67,14 @@ function debugTestsMenu(openInputEvents: OpenPage, openMicrophones: OpenPage): M ctx.stack.push(new LightSensorDemoLayer(DEVELOPER_WINDOW_ID, ctx.actions.requestRender)); }, }, + { + label: "Ring status", + disabled: global.isIOS, + description: global.isIOS ? "Not available on iOS yet." : undefined, + onSelect: (ctx) => { + ctx.stack.push(new RingStatusLayer(DEVELOPER_WINDOW_ID, ctx.actions.requestRender)); + }, + }, { label: "Microphones", onSelect: openMicrophones, diff --git a/app/apps/developer/ring-status.ts b/app/apps/developer/ring-status.ts new file mode 100644 index 00000000..876aa506 --- /dev/null +++ b/app/apps/developer/ring-status.ts @@ -0,0 +1,302 @@ +import { getDefaultSmallFont } from "../../graphics/ui-fonts"; +import { GrayImage } from "../../graphics/image"; +import { type InputEvent } from "../../ui/gestures"; +import { Layer, type LayerContext } from "../../ui/layers"; +import { shell } from "../../ui/shell/shell"; +import { MenuLayer, type MenuItem } from "../../ui/menu"; +import { ringConnectionModeSetting } from "../../ui/dashboard-settings"; +import { loadDeviceAddresses } from "../../g2/device-addresses"; +import { + getRingSessionStatus, + getRingSystemBluetoothState, + sendRingConfigCommand, + setGlassesRingLink, + type GlassesRingLinkAction, + type RingConfigAction, + type RingSessionStatus, + type RingSystemBluetoothState, +} from "../../native/ring-status"; + +const POLL_INTERVAL_MS = 1_000; +const LEFT_X = 16; +const VALUE_X = 130; +const BUTTON_GAP = 8; + +type Row = { label: string; value: string; dim?: boolean }; +type Button = "glasses" | "ring" | "mode"; + +const BUTTONS: readonly Button[] = ["glasses", "ring", "mode"]; + +/** Glasses-side commands (sid 0x80 pair manager). */ +const GLASSES_ACTIONS: readonly { label: string; action: GlassesRingLinkAction }[] = [ + { label: "Disconnect ring", action: "disconnect" }, + { label: "Release ring", action: "release" }, + { label: "Unpair ring", action: "unpair" }, + { label: "Connect ring", action: "connect" }, +]; + +/** Ring-side commands over the direct link, and the combined flows. */ +const RING_ACTIONS: readonly { label: string; action: RingConfigAction }[] = [ + { label: "Bind to these glasses", action: "bind" }, + { label: "Unbind from glasses", action: "unbind" }, + { label: "Targets: these glasses", action: "targets-glasses" }, + { label: "Targets: clear (any)", action: "targets-clear" }, + { label: "Remove ring notify", action: "remove-ring" }, + { label: "Touch source on", action: "touch-on" }, + { label: "Touch source off", action: "touch-off" }, + { label: "Pair auth (phone role)", action: "pair-auth" }, +]; + +const ACTION_MENU_LAYOUT = { x: "center" as const, y: 8, width: 300, dimUnderneath: 0.35 }; + +/** + * Where R1 ring input is coming from: the phone's own Bluetooth link to the + * ring, the direct-link session state, and when input last arrived directly + * versus relayed by the glasses. The ring sends gestures only to whichever + * link holds its glasses role, so the two "input" rows are the quickest way + * to see which path is live. + * + * Everything below is EXPERIMENTAL (see GlassesSessionRing.kt and + * notes/ring-link-control.md). "Glasses..." sends sid 0x80 ring-link commands + * to the glasses; "Ring..." sends binding commands to the ring over the + * direct link (Mode must be direct and the link up), including Bind/Unbind, + * which do both halves in the official app's order. Mode flips the Developer + * "Ring connection" setting (applies on the next glasses connection). In + * Direct mode the session does the setup on its own (see + * GlassesSessionRing.runRingGlassesSetup); the menus are for experiments. + */ +export class RingStatusLayer implements Layer { + private session: RingSessionStatus | null = null; + private system: RingSystemBluetoothState | null = null; + private timer: ReturnType | null = null; + private selected = 0; + private notice = ""; + + constructor( + private readonly windowId: string, + private readonly requestRender: () => void, + ) { + this.poll(); + this.timer = setInterval(() => { + this.poll(); + if (shell.isWindowVisible(this.windowId)) this.requestRender(); + }, POLL_INTERVAL_MS); + } + + onRemoved(): void { + if (this.timer !== null) { + clearInterval(this.timer); + this.timer = null; + } + } + + private ringAddress(): string { + return this.session?.ringAddress || loadDeviceAddresses().ring; + } + + private poll(): void { + this.session = getRingSessionStatus(); + const address = this.ringAddress(); + this.system = address ? getRingSystemBluetoothState(address) : null; + } + + paint(ctx: LayerContext): GrayImage { + const font = getDefaultSmallFont(); + const { width, height } = ctx.stack.getBaseSize(); + const image = new GrayImage(width, height, 0); + const lineStep = font.lineHeight + 2; + const buttonHeight = font.lineHeight + 8; + const buttonTop = height - buttonHeight - 6; + + image.drawText(font, 18, 10, "Ring status", 230); + let y = 10 + lineStep + 4; + const rows = this.rows(); + if (this.notice) rows.push({ label: "", value: this.notice }); + for (const row of rows) { + if (y + font.lineHeight > buttonTop - 4) break; + image.drawText(font, LEFT_X, y, row.label, row.dim ? 100 : 150); + image.drawText(font, VALUE_X, y, row.value, row.dim ? 120 : 220); + y += lineStep; + } + + const buttonWidth = Math.floor((width - 2 * LEFT_X - BUTTON_GAP * (BUTTONS.length - 1)) / BUTTONS.length); + BUTTONS.forEach((button, index) => { + const x = LEFT_X + index * (buttonWidth + BUTTON_GAP); + const selected = index === this.selected; + if (selected) image.fillRoundedRect(x, buttonTop, buttonWidth, buttonHeight, 40, 4); + image.drawRoundedRect(x, buttonTop, buttonWidth, buttonHeight, selected ? 200 : 70, 4); + const text = buttonLabel(button); + image.drawText(font, x + Math.max(0, Math.floor((buttonWidth - font.measureText(text)) / 2)), + buttonTop + 4, text, selected ? 255 : 170); + }); + return image; + } + + private rows(): Row[] { + const s = this.session; + const address = this.ringAddress(); + const rows: Row[] = [ + { label: "Ring", value: address || "none paired" }, + { label: "Phone BT", value: describeSystem(this.system) }, + ]; + + if (!s) { + rows.push({ label: "Session", value: "not connected to glasses", dim: true }); + return rows; + } + + if (!s.directEnabled) { + const pending = ringConnectionModeSetting.get() !== "glasses"; + rows.push({ label: "Direct link", value: pending ? "on after glasses reconnect" : "off (only via glasses)", dim: true }); + } else { + const state = s.directNotificationsReady ? "subscribed" + : s.directConnected ? "connected, subscribing" + : "not connected"; + const since = s.directStateAgeMs >= 0 ? ` ${formatAge(s.directStateAgeMs)}` : ""; + const battery = s.directBattery >= 0 ? `, ${s.directBattery}%` : ""; + rows.push({ + label: "Direct link", + value: `${state}${since}, role ${s.directRole}, ${s.directConnectCount} connects${battery}`, + }); + } + if (s.directEnabled && s.directRole === "glasses") { + rows.push({ + label: "Direct auth", + value: s.directGlassesAuth ? `${s.directGlassesAuth} ${formatAge(s.directGlassesAuthAgeMs)} ago` : "not sent yet", + }); + } + if (s.directEnabled) { + const pull = s.healthWindowActive ? "pulling now (phone role)" + : s.lastHealthPull ? `${s.lastHealthPull} ${formatAge(s.lastHealthPullAgeMs)} ago` + : "no pull yet"; + const held = s.heldHealthRecords > 0 ? `, ${s.heldHealthRecords} records unstored` : ""; + rows.push({ label: "Health sync", value: pull + held }); + } + rows.push({ label: "Direct input", value: describeInput(s.lastDirectInputAgeMs, s.lastDirectInput) }); + if (s.directEnabled) { + rows.push({ label: "Direct pkts", value: describeAge(s.lastDirectNotifyAgeMs) }); + if (s.lastDirectRaw) { + rows.push({ label: "Direct raw", value: `${formatAge(s.lastDirectRawAgeMs)} ago: ${s.lastDirectRaw}` }); + } + } + rows.push({ label: "Glasses input", value: describeInput(s.lastGlassesInputAgeMs, s.lastGlassesInput) }); + rows.push({ + label: "Glasses ring", + value: (s.glassesRingBatteryAgeMs < 0 ? "battery not reported" + : `${s.glassesRingBattery >= 0 ? `battery ${s.glassesRingBattery}%` : "no battery"} ${formatAge(s.glassesRingBatteryAgeMs)} ago`) + + (s.glassesRingMac ? `, mac ${s.glassesRingMac}` : ""), + }); + if (s.lastGlassesReport) { + rows.push({ label: "Glasses said", value: `${s.lastGlassesReport} (${formatAge(s.lastGlassesReportAgeMs)} ago)` }); + } + if (s.lastRingCommand) { + rows.push({ + label: "Ring cmd", + value: `${s.lastRingCommand} ${formatAge(s.lastRingCommandAgeMs)} ago: ${s.lastRingCommandResult}`, + }); + } + if (s.lastCommand) { + rows.push({ label: "Glasses cmd", value: `${s.lastCommand} ${formatAge(s.lastCommandAgeMs)} ago` }); + rows.push({ label: "Glasses ack", value: `R ${s.lastCommandResultR}; L ${s.lastCommandResultL}` }); + } + if (s.lastDirectError) rows.push({ label: "Direct error", value: s.lastDirectError, dim: true }); + return rows; + } + + private activate(ctx: LayerContext): void { + switch (BUTTONS[this.selected]!) { + case "glasses": + ctx.stack.push(this.actionMenu("Glasses ring link", GLASSES_ACTIONS.map(({ label, action }) => ({ + label, + onSelect: (menuCtx) => { + this.runGlassesAction(label, action); + menuCtx.stack.pop(); + }, + })))); + return; + case "ring": + ctx.stack.push(this.actionMenu("Ring binding", RING_ACTIONS.map(({ label, action }) => ({ + label, + onSelect: (menuCtx) => { + this.notice = `${label}: ${sendRingConfigCommand(action, this.ringAddress(), this.system?.name ?? "")}`; + this.poll(); + menuCtx.stack.pop(); + }, + })))); + return; + case "mode": { + const next = ringConnectionModeSetting.set(ringConnectionModeSetting.next()); + this.notice = `Ring connection set to ${ringConnectionModeSetting.displayValue(next)}; applies on next glasses connection`; + return; + } + } + } + + private actionMenu(title: string, items: MenuItem[]): MenuLayer { + return new MenuLayer(title, items, ACTION_MENU_LAYOUT); + } + + private runGlassesAction(label: string, action: GlassesRingLinkAction): void { + this.notice = setGlassesRingLink(action, this.ringAddress(), this.system?.name ?? "") + ? `${label} sent (experimental)` + : `${label} not sent (no session or no ring address)`; + this.poll(); + } + + handleInput(event: InputEvent, ctx: LayerContext): void { + switch (event.type) { + case "scroll-up": + this.selected = (this.selected + BUTTONS.length - 1) % BUTTONS.length; + return; + case "scroll-down": + this.selected = (this.selected + 1) % BUTTONS.length; + return; + case "click": + this.activate(ctx); + return; + case "double-click": + ctx.stack.pop(); + return; + default: + return; + } + } +} + +function buttonLabel(button: Button): string { + switch (button) { + case "glasses": + return "Glasses..."; + case "ring": + return "Ring..."; + case "mode": + return `Mode: ${ringConnectionModeSetting.get()}`; + } +} + +function describeSystem(sys: RingSystemBluetoothState | null): string { + if (!sys) return "unknown"; + if (sys.error) return `error: ${sys.error}`; + if (sys.bonded === undefined) return "unknown"; + const parts = [sys.bonded ? "bonded" : "not bonded"]; + if (sys.gattConnected !== undefined) parts.push(sys.gattConnected ? "GATT up" : "no GATT"); + if (sys.aclConnected !== undefined) parts.push(sys.aclConnected ? "link up" : "no link"); + return parts.join(", "); +} + +function describeInput(ageMs: number, label: string): string { + if (ageMs < 0) return "never"; + return label ? `${formatAge(ageMs)} ago: ${label}` : `${formatAge(ageMs)} ago`; +} + +function describeAge(ageMs: number): string { + return ageMs < 0 ? "never" : `${formatAge(ageMs)} ago`; +} + +function formatAge(ageMs: number): string { + const seconds = Math.floor(ageMs / 1000); + if (seconds < 60) return `${seconds}s`; + const minutes = Math.floor(seconds / 60); + if (minutes < 60) return `${minutes}m ${seconds % 60}s`; + return `${Math.floor(minutes / 60)}h ${minutes % 60}m`; +} diff --git a/app/apps/glanceboard/glanceboard-settings.ts b/app/apps/glanceboard/glanceboard-settings.ts index 0aa587f2..4d729490 100644 --- a/app/apps/glanceboard/glanceboard-settings.ts +++ b/app/apps/glanceboard/glanceboard-settings.ts @@ -5,7 +5,7 @@ import { glanceWidgetSpans } from "./widgets"; export type GlanceSlotChoice = GlanceWidgetId | "none"; -const SLOT_CHOICES: readonly GlanceSlotChoice[] = ["none", "system-card", "calendar", "terminal", "t3code", "nightscout", "compass", "music"]; +const SLOT_CHOICES: readonly GlanceSlotChoice[] = ["none", "system-card", "calendar", "terminal", "t3code", "nightscout", "compass", "music", "health"]; const SLOT_CHOICE_LABELS: Record = { none: "Empty", @@ -16,6 +16,7 @@ const SLOT_CHOICE_LABELS: Record = { nightscout: "Nightscout", compass: "Compass", music: "Music", + health: "Health", }; export function glanceSlotChoiceLabel(choice: GlanceSlotChoice): string { diff --git a/app/apps/glanceboard/widget.ts b/app/apps/glanceboard/widget.ts index 8aa1095b..1d274c68 100644 --- a/app/apps/glanceboard/widget.ts +++ b/app/apps/glanceboard/widget.ts @@ -28,7 +28,7 @@ export interface GlanceWidget { paint(image: GrayImage): void; } -export type GlanceWidgetId = "system-card" | "nightscout" | "compass" | "music" | "calendar" | "terminal" | "t3code"; +export type GlanceWidgetId = "system-card" | "nightscout" | "compass" | "music" | "calendar" | "terminal" | "t3code" | "health"; export type GlanceWidgetDefinition = { id: GlanceWidgetId; diff --git a/app/apps/glanceboard/widgets/health-widget.ts b/app/apps/glanceboard/widgets/health-widget.ts new file mode 100644 index 00000000..5a6b3ac3 --- /dev/null +++ b/app/apps/glanceboard/widgets/health-widget.ts @@ -0,0 +1,56 @@ +import { type GrayImage } from "../../../graphics/image"; +import { getDefaultMediumFont, getDefaultSmallFont } from "../../../graphics/ui-fonts"; +import { dailySummary, nextBucketStart } from "../../../health/health-derive"; +import { drawHealthCard, type HealthCardData } from "../../../health/health-card"; +import { syncLiveRecords } from "../../../health/health-live"; +import { isFixtureData } from "../../../health/health-seed"; +import { healthStore } from "../../../health/health-store-files"; +import { startOfLocalDay } from "../../../health/health-types"; +import { type GlanceWidget } from "../widget"; + +/** Saved daily metrics, refreshed while visible without extra BLE polling. */ +export class HealthWidget implements GlanceWidget { + private data: HealthCardData = { kind: "empty" }; + private timer: ReturnType | null = null; + + start(requestRender: () => void): void { + this.stop(); + const refresh = (): void => { + this.refresh(); + requestRender(); + }; + refresh(); + this.timer = setInterval(refresh, 60_000); + } + + stop(): void { + if (this.timer !== null) clearInterval(this.timer); + this.timer = null; + } + + private refresh(): void { + try { + syncLiveRecords(); + if (isFixtureData()) { + this.data = { kind: "fixture" }; + return; + } + const today = startOfLocalDay(Date.now()); + const store = healthStore(); + const samples = store.samplesInRange(today, nextBucketStart(today, "day")); + const summary = dailySummary(samples, store.sleepSessions(), today); + this.data = samples.length || summary.sleep + ? { kind: "live", summary, + hasSteps: samples.some((sample) => sample.metric === "steps"), + hasCalories: samples.some((sample) => sample.metric === "calories") } + : { kind: "empty" }; + } catch (error) { + console.warn("health widget refresh failed", error); + this.data = { kind: "error" }; + } + } + + paint(image: GrayImage): void { + drawHealthCard(image, this.data, getDefaultSmallFont(), getDefaultMediumFont()); + } +} diff --git a/app/apps/glanceboard/widgets/index.ts b/app/apps/glanceboard/widgets/index.ts index 5691ef27..b07f7b7c 100644 --- a/app/apps/glanceboard/widgets/index.ts +++ b/app/apps/glanceboard/widgets/index.ts @@ -6,6 +6,7 @@ import { NightscoutWidget } from "./nightscout-widget"; import { SystemCardWidget, systemCardSettingsMenuItems } from "./system-card"; import { T3CodeWidget } from "./t3code-widget"; import { TerminalWidget } from "./terminal-widget"; +import { HealthWidget } from "./health-widget"; /** Every widget a board slot can hold. */ export const GLANCE_WIDGETS: readonly GlanceWidgetDefinition[] = [ @@ -16,6 +17,7 @@ export const GLANCE_WIDGETS: readonly GlanceWidgetDefinition[] = [ { id: "nightscout", label: "Nightscout", create: () => new NightscoutWidget() }, { id: "compass", label: "Compass", create: () => new CompassWidget() }, { id: "music", label: "Music", settingsMenuItems: musicSettingsMenuItems, create: () => new MusicWidget() }, + { id: "health", label: "Health", create: () => new HealthWidget() }, ]; export function findGlanceWidget(id: GlanceWidgetId | (string & {})): GlanceWidgetDefinition | null { diff --git a/app/apps/health/health-app.ts b/app/apps/health/health-app.ts new file mode 100644 index 00000000..cfea5e21 --- /dev/null +++ b/app/apps/health/health-app.ts @@ -0,0 +1,197 @@ +/** + * HEALTH - the glasses status page. + * + * This file is now PLUMBING ONLY: the store reads, the refresh timer, the + * scroll cursor, the window lifecycle. Every pixel is drawn by + * `health/health-glance.ts`, which has no NativeScript imports and therefore + * renders under plain node - see `tools/health-preview.cjs`, which produces a + * PNG of each page below without an emulator. The first pass drew and plumbed + * in one file and could only be looked at by booting an AVD; that is the + * difference this split buys, and it is the reason to keep the two apart. + * + * ## The surface, after Chris's 2026-09-10 review + * + * The overview is a SUMMARY - text only, no charts - and scrolling walks a + * cursor through a detail page per parameter, ending at sleep's own view. + * `GLANCE_PAGES` in `health-glance.ts` is the page list, and the doc comment + * there carries the reasoning for the carousel (including which parts of it are + * interpretation rather than spec). + */ + +import { getDefaultLargeFont, getDefaultSmallFont } from "../../graphics/ui-fonts"; +import { GrayImage } from "../../graphics/image"; +import { type InputEvent } from "../../ui/gestures"; +import { type Layer, type LayerContext } from "../../ui/layers"; +import { + createInProcessWindow, + YieldAtRootLayer, + type InProcessAppOptions, + type InProcessWindow, +} from "../../ui/shell/in-process-window"; +import { dailySummary, dailyHypnogram, rollupSeries, type DailySummary } from "../../health/health-derive"; +import { + drawGlancePage, + GLANCE_PAGES, + type GlanceData, +} from "../../health/health-glance"; +import { healthStore } from "../../health/health-store-files"; +import { requestFreshPull, syncLiveRecords } from "../../health/health-live"; +import { isFixtureData, seedFixturesIfNeeded } from "../../health/health-seed"; +import { + DAY_MS, + SAMPLE_METRICS, + startOfLocalDay, + type RollupPoint, + type SampleMetric, +} from "../../health/health-types"; + +export const HEALTH_WINDOW_ID = "health"; +export const HEALTH_SURFACE_ID = "window:health"; + +/** Cheap enough to re-read on a timer; the store is a few hundred rows a day. */ +const REFRESH_INTERVAL_MS = 60_000; + +class HealthLayer implements Layer { + private summary: DailySummary | null = null; + /** Today by hour, per metric - what the drill-down pages plot. */ + private hourly: Partial> = {}; + private stageBands: GlanceData["stageBands"] = []; + private fixture = false; + /** Index into GLANCE_PAGES. 0 is the overview. */ + private pageIndex = 0; + private timer: ReturnType | null = null; + private removed = false; + + constructor(private readonly requestRender: () => void) {} + + start(): void { + // Live data first: if the ring has been pulled this session, this stores it + // and wipes any fixtures out of the way. Only if that leaves us with + // nothing does seeding fill the screen, and seeding refuses outright once + // real data has ever landed. + syncLiveRecords(); + // Ask for something current rather than showing whatever the last + // automatic 30-minute pull happened to catch. Returns immediately; the + // pull takes ~15s and lands via the refresh tick below. + requestFreshPull(); + seedFixturesIfNeeded(); + this.reload(); + this.timer = setInterval(() => this.reload(), REFRESH_INTERVAL_MS); + } + + stop(): void { + if (this.removed) return; + this.removed = true; + if (this.timer !== null) clearInterval(this.timer); + this.timer = null; + } + + onRemoved(): void { + this.stop(); + } + + private reload(): void { + if (this.removed) return; + // Cheap on every tick: a no-op when the communicator has nothing new, and + // the store dedupes when it does, so a 30-minute pull shows up here within + // one refresh instead of waiting for the app to be reopened. + syncLiveRecords(); + try { + const store = healthStore(); + const today = startOfLocalDay(Date.now()); + const samples = store.samplesInRange(today, today + DAY_MS); + const sessions = store.sleepSessions(); + this.summary = dailySummary(samples, sessions, today); + // One pass per metric over a day's samples - a few hundred rows, and the + // drill-down has to be instant when the cursor lands on it. + const hourly: Partial> = {}; + for (const metric of SAMPLE_METRICS) { + hourly[metric] = rollupSeries(samples, { + metric, + granularity: "hour", + startMs: today, + endMs: today + DAY_MS, + }); + } + this.hourly = hourly; + this.stageBands = dailyHypnogram(sessions, today); + this.fixture = isFixtureData(); + } catch (error) { + console.warn("health glance reload failed", error); + } + this.requestRender(); + } + + paint(ctx: LayerContext): GrayImage { + const { width, height } = ctx.stack.getBaseSize(); + const image = new GrayImage(width, height, 0); + drawGlancePage( + image, + { width, height }, + { small: getDefaultSmallFont(), large: getDefaultLargeFont() }, + GLANCE_PAGES[this.pageIndex] ?? GLANCE_PAGES[0]!, + { + summary: this.summary, + hourly: this.hourly, + stageBands: this.stageBands, + nowMs: Date.now(), + fixture: this.fixture, + }, + ); + return image; + } + + /** + * Scrolling moves between the overview and the per-parameter detail pages. + * + * The cursor WRAPS. With seven pages and no back gesture available + * (`YieldAtRootLayer` takes double-click for back-out-to-home), wrapping is + * what guarantees the overview is always reachable by holding one direction - + * a user who has scrolled to the end never has to work out which way is back. + * Click advances too, so the drill-down is reachable without ever scrolling. + */ + handleInput(event: InputEvent, _ctx: LayerContext): void { + switch (event.type) { + case "scroll-down": + case "click": + this.movePage(1); + return; + case "scroll-up": + this.movePage(-1); + return; + default: + return; + } + } + + private movePage(delta: number): void { + const count = GLANCE_PAGES.length; + this.pageIndex = (this.pageIndex + delta + count) % count; + this.requestRender(); + } +} + +export function createHealthAppWindow(options: InProcessAppOptions): InProcessWindow { + let requestRender = () => {}; + const layer = new HealthLayer(() => requestRender()); + const app = createInProcessWindow({ + appId: "health", + windowId: HEALTH_WINDOW_ID, + title: "Health", + iconLetter: "H", + icon: "activity", + closeable: true, + actions: options.actions, + baseLayer: new YieldAtRootLayer(layer), + submitFrame: options.submitFrame, + setSurfaceVisible: options.setSurfaceVisible, + removeSurface: options.removeSurface, + onClosed: () => { + layer.stop(); + options.onClosed(); + }, + }); + requestRender = app.requestRender; + layer.start(); + return app; +} diff --git a/app/apps/health/index.ts b/app/apps/health/index.ts new file mode 100644 index 00000000..db4e1043 --- /dev/null +++ b/app/apps/health/index.ts @@ -0,0 +1,11 @@ +import { type AppDefinition } from "../app-definition"; +import { createHealthAppWindow, HEALTH_SURFACE_ID, HEALTH_WINDOW_ID } from "./health-app"; + +const healthApp: AppDefinition = { + appId: "health", + title: "Health", + icon: "activity", + launch: (ctx) => ctx.launchInProcessApp(HEALTH_WINDOW_ID, HEALTH_SURFACE_ID, createHealthAppWindow), +}; + +export default healthApp; diff --git a/app/bootstrap.android.ts b/app/bootstrap.android.ts index f5734a2f..82c23dd5 100644 --- a/app/bootstrap.android.ts +++ b/app/bootstrap.android.ts @@ -2,6 +2,7 @@ import { Application } from '@nativescript/core' import { registerShareIntentHandler } from './native/share-intents' import { installNativeUserAgent } from './util/http' import { registerPhoneRotation } from './native/phone-rotation' +import { startLiveHealthSync, startAlignedRingPull } from './health/health-live' installNativeUserAgent() registerShareIntentHandler() @@ -12,4 +13,15 @@ Application.on(Application.launchEvent, () => { setTimeout(() => require('./analytics/analytics-sources').startAppAnalytics(), 0) }) +// Ring health records live only in the communicator's memory until something +// stores them. Both health surfaces store on open, but a pull that lands while +// they are closed would be lost if the process restarted first, so this keeps +// them reaching disk regardless. No-op when there is nothing new. +startLiveHealthSync() + +// Collect from the ring on a wall-clock cadence (:01 and :31). Without this +// nothing drives a pull on a timer at all - only onRingReady() on reconnect - +// so a ring that stays connected is never read. +startAlignedRingPull() + Application.run({ moduleName: 'app-root' }) diff --git a/app/g2/dashboard-controller.ts b/app/g2/dashboard-controller.ts index d61e7b58..6da48736 100644 --- a/app/g2/dashboard-controller.ts +++ b/app/g2/dashboard-controller.ts @@ -19,6 +19,8 @@ import { ALL_NOTIFICATIONS, onAndroidNotificationPosted, onAndroidNotificationRe import { shouldShowNotificationOnGlasses } from "../native/notification-sources"; import { watchNotificationListenerBinding } from "../native/notification-access"; import { openEvenAppSettings, readEvenAppNotificationState } from "../native/even-app-conflict"; +import { defaultRingName, setGlassesRingLink } from "../native/ring-status"; +import { getBooleanSetting, setBooleanSetting } from "../native/settings-store"; import { grayImageToPreviewSource } from "../native/gray-image-preview"; import { firmwareIncompatibilityMessage, hasCompatibleFirmware } from "./firmware-compat"; import { hasExtractedEvenHubFonts } from "./firmware-builder"; @@ -76,7 +78,7 @@ import { loadPersistedOpenApps, savePersistedOpenApps } from "../ui/shell/open-a import { appViewportRect, isOnSwitcherEdge, sidebarStripVisible, type ScreenRect, type WindowHeightMode } from "../ui/shell/geometry"; import { type ContinuousCaptureOptions, type LayerActions, type TextSettingsEditToggle, type TranscriptionChoice } from "../ui/layers"; import { type KeyboardInputSession } from "../ui/shell/keyboard-input"; -import { appSwitcherPositionSetting, statusBarPositionSetting, statusBarVisibilitySetting, windowBorderSetting, assistantAllowProactiveSetting, assistantBackendSetting, assistantBridgeHostSetting, assistantBridgePortSetting, assistantBridgeTokenSetting, getBrightnessPreferences, displayLayoutSetting, navigateDisplayLayoutSetting, terminalDisplayLayoutSetting, elevenLabsApiKeySetting, getStringSettingById, openAiApiKeySetting, nightscoutApiTokenSetting, firmwareDebugFlagsSetting, whisperServerApiKeySetting, whisperServerLanguageSetting, whisperServerModelSetting, whisperServerUrlSetting, lockScreenEnabledSetting, nightscoutSiteUrlSetting, onAnySettingChanged, previewColorSetting, ringConnectionModeSetting, saveVoiceRecordingsSetting, sonioxApiKeySetting, screenTimeoutSetting, screenTimeoutSettingToMs, suspendEvenHubWhenScreenOffSetting, voiceProviderSetting, wakeWordActionSetting, type ConfigSettingString } from "../ui/dashboard-settings"; +import { appSwitcherPositionSetting, statusBarPositionSetting, statusBarVisibilitySetting, windowBorderSetting, assistantAllowProactiveSetting, assistantBackendSetting, assistantBridgeHostSetting, assistantBridgePortSetting, assistantBridgeTokenSetting, getBrightnessPreferences, displayLayoutSetting, navigateDisplayLayoutSetting, terminalDisplayLayoutSetting, elevenLabsApiKeySetting, getStringSettingById, openAiApiKeySetting, nightscoutApiTokenSetting, firmwareDebugFlagsSetting, whisperServerApiKeySetting, whisperServerLanguageSetting, whisperServerModelSetting, whisperServerUrlSetting, lockScreenEnabledSetting, nightscoutSiteUrlSetting, onAnySettingChanged, previewColorSetting, ringConnectionModeSetting, type RingConnectionMode, saveVoiceRecordingsSetting, sonioxApiKeySetting, screenTimeoutSetting, screenTimeoutSettingToMs, suspendEvenHubWhenScreenOffSetting, voiceProviderSetting, wakeWordActionSetting, type ConfigSettingString } from "../ui/dashboard-settings"; import { isIgnoringBatteryOptimizations, requestIgnoreBatteryOptimizations } from "../native/battery-optimization"; import { getInstalledEvenHubAppById, @@ -247,6 +249,9 @@ function sourceName(eventSource: number): string { return EventSourceTypeName[eventSource] ?? `SOURCE_${eventSource}`; } +/** Set while a Direct ring session may have taken the R1 from the glasses; see handRingBackToGlassesIfNeeded. */ +const RING_TAKEN_FROM_GLASSES_KEY = "developer.ringTakenFromGlasses"; + class DashboardController { private phase: ConnectionPhase = "disconnected"; private status = "Disconnected."; @@ -323,6 +328,8 @@ class DashboardController { /** Faceclaw's firmware at the required revision reported in; its extensions can be used. */ private customFirmwareConfirmed = false; private faceclawWakeLeaseState: boolean | null = null; + /** Ring connection mode the current session was started with (it applies per connection). */ + private ringModeAtConnect: RingConnectionMode = "glasses"; private glassesWorn: boolean | null = null; /** Put on while charging: Java reconnects on that, and the wake waits for the new session. */ private wakeAfterChargingReconnect = false; @@ -1027,6 +1034,25 @@ class DashboardController { this.evenHubSuspendTimer = null; } + /** + * A Direct-mode session may have unpaired the R1 from the glasses (see + * GlassesSessionRing.releaseRingFromGlassesLocked). The first session in + * another mode asks the glasses to connect to it again; the ring's own + * glasses targets were cleared, so it accepts them. Called on connect. + */ + private handRingBackToGlassesIfNeeded(): void { + if (this.ringModeAtConnect === "direct" || !getBooleanSetting(RING_TAKEN_FROM_GLASSES_KEY, false)) return; + const ring = loadDeviceAddresses().ring; + if (!ring) { + setBooleanSetting(RING_TAKEN_FROM_GLASSES_KEY, false); + return; + } + if (setGlassesRingLink("connect", ring, defaultRingName(ring))) { + setBooleanSetting(RING_TAKEN_FROM_GLASSES_KEY, false); + this.appendLog(`Handing the R1 ring ${ring} back to the glasses`); + } + } + private pushFirmwareDebugFlags(): void { if (!this.communicator) return; void this.communicator @@ -1453,10 +1479,14 @@ class DashboardController { this.setPhase("connecting"); this.setStatus("Connecting to the glasses..."); // "Only via glasses" (the default) means the phone never opens its own - // link to the ring: the glasses relay its gestures to us anyway, and the - // direct link is currently unreliable. An empty address disables every - // direct-ring code path in the communicator. - const ringAddress = ringConnectionModeSetting.get() === "direct" ? addresses.ring : ""; + // link to the ring: the glasses relay its gestures to us anyway. An empty + // address disables every direct-ring code path in the communicator. + const ringMode = ringConnectionModeSetting.get(); + this.ringModeAtConnect = ringMode; + const ringAddress = ringMode !== "glasses" ? addresses.ring : ""; + // Direct mode may unpair the ring from the glasses; remember to hand it + // back once a later session runs in another mode. + if (ringMode === "direct" && ringAddress) setBooleanSetting(RING_TAKEN_FROM_GLASSES_KEY, true); this.appendLog( `Using configured arms: R=${addresses.right} L=${addresses.left}${ringAddress ? ` ring=${ringAddress}` : ""}`, ); @@ -1476,6 +1506,10 @@ class DashboardController { right: addresses.right, left: addresses.left, ring: ringAddress, + // Direct mode acts as the ring's glasses (gestures, battery). Health + // sync needs the phone role, which the session borrows briefly for + // each pull (GlassesSessionRing.beginRingHealthWindowLocked). + ringRole: ringMode === "direct" ? "glasses" : "phone", }); this.communicator = communicator; // Size the compositor before anything else is awaited: windows opened @@ -1522,6 +1556,7 @@ class DashboardController { // mode-7 control message once the dashboard container is warmed up. this.pushFirmwareDebugFlags(); this.pushBrightness(true); + this.handRingBackToGlassesIfNeeded(); } if (mappedPhase !== "connected" && mappedPhase !== "charging") { // A wear snapshot is session-scoped. CFW reports a fresh value when diff --git a/app/health/health-card.ts b/app/health/health-card.ts new file mode 100644 index 00000000..bd0a9435 --- /dev/null +++ b/app/health/health-card.ts @@ -0,0 +1,55 @@ +import { type GrayImage, type UiFont } from "../graphics/image"; +import { truncateText } from "../graphics/textwrap"; +import { formatDuration, type DailySummary, type MetricSummary } from "./health-derive"; + +export type HealthCardData = + | { kind: "live"; summary: DailySummary; hasSteps: boolean; hasCalories: boolean } + | { kind: "fixture" | "empty" | "error" }; + +const PAD = 8; + +/** Three columns keep all six metrics legible in a 288 x 144 board slot. */ +export function drawHealthCard(image: GrayImage, data: HealthCardData, small: UiFont, medium: UiFont): void { + image.drawText(small, PAD, PAD, "Health", 180); + const today = "Today"; + image.drawText(small, image.width - PAD - small.measureText(today), PAD, today, 130); + + const top = PAD + small.lineHeight + 6; + if (data.kind !== "live") { + const title = data.kind === "fixture" ? "Sample data" + : data.kind === "error" ? "Health unavailable" : "No health data today"; + const subtitle = data.kind === "fixture" ? "Open Health for details" + : data.kind === "error" ? "Open Health to retry" : "Open Health to sync"; + const font = medium.measureText(title) <= image.width - PAD * 2 ? medium : small; + const y = Math.round(top + (image.height - PAD - top - font.lineHeight - small.lineHeight - 6) / 2); + const text = truncateText(font, title, image.width - PAD * 2); + image.drawText(font, Math.round((image.width - font.measureText(text)) / 2), y, text, 240); + const hint = truncateText(small, subtitle, image.width - PAD * 2); + image.drawText(small, Math.round((image.width - small.measureText(hint)) / 2), y + font.lineHeight + 6, hint, 150); + return; + } + + const average = (metric: MetricSummary, units: string): string => + metric.hasData ? `${Math.round(metric.avg)}${units}` : "--"; + const { summary } = data; + const cells: [string, string][] = [ + ["HR avg", average(summary.heartRate, " bpm")], + ["HRV avg", average(summary.hrv, " ms")], + ["SpO2 avg", average(summary.spo2, "%")], + ["Steps", data.hasSteps ? String(summary.steps) : "--"], + ["Cal (kcal)", data.hasCalories ? String(summary.calories) : "--"], + ["Sleep", summary.sleep ? formatDuration(summary.sleep.totalSec) : "--"], + ]; + const columnWidth = (image.width - PAD * 2) / 3; + const rowHeight = (image.height - PAD - top) / 2; + cells.forEach(([label, value], index) => { + const left = PAD + Math.floor((index % 3) * columnWidth); + const y = top + Math.floor(Math.floor(index / 3) * rowHeight); + const width = Math.floor(columnWidth) - 6; + const font = medium.measureText(value) <= width + && small.lineHeight + 2 + medium.lineHeight <= rowHeight - 2 ? medium : small; + const fittedLabel = label === "Cal (kcal)" && small.measureText(label) > width ? "kcal" : label; + image.drawText(small, left, y, truncateText(small, fittedLabel, width), 140); + image.drawText(font, left, y + small.lineHeight + 2, truncateText(font, value, width), 235); + }); +} diff --git a/app/health/health-chart.ts b/app/health/health-chart.ts new file mode 100644 index 00000000..53407055 --- /dev/null +++ b/app/health/health-chart.ts @@ -0,0 +1,684 @@ +/** + * The chart renderer, shared by both surfaces. + * + * Both the glasses glance and the phone graphs draw into a `GrayImage`, and + * the phone converts its one through `grayImageToPreviewSource()` - the same + * already-shipping path the glasses mirror uses to put a rendered frame on the + * phone screen. That is a deliberate reuse rather than a shortcut: it means + * one drawing implementation covers both surfaces, no new native code exists + * for the phone side, and the two screens cannot drift apart visually. + * + * ⚠ DESIGN CHOICE, not a spec (Chris said only "the Even app wasn't bad for + * this, I liked their summaries, but we can't copy it, we have to make our + * own"): the phone charts are MONOCHROME, because that is what + * `PreviewBitmapUtil.fromGray` produces and adding colour would mean new + * Kotlin. It lands somewhere deliberate rather than accidental - the phone + * already shows the glasses' grey mirror, so the health screens read as part + * of the same instrument - but colour is a real option later and would be a + * contained change: a second bitmap builder plus a palette here. + * + * Nothing in this file imports NativeScript, and that is load-bearing rather + * than incidental: `tools/health-preview.cjs` renders these functions under + * plain node and writes PNGs, so a layout can be looked at without an Android + * emulator in the loop. Keep it that way - the fonts arrive as `UiFont` + * arguments precisely so no drawing code ever has to reach for the platform. + */ + +import { GrayImage } from "../graphics/image"; +import { type UiFont } from "../graphics/image"; +import { + type RollupPoint, + type SampleMetric, + type SleepNight, + isCumulative, +} from "./health-types"; +import { bandIsMeaningful, formatValue, primaryValue } from "./health-derive"; +import { STAGE_MAPPING_CONFIRMED, type SleepStageName } from "./sleep-stages"; + +/** + * The grey ramp. Everything drawn here uses one of these. + * + * ⚠ RAISED FOR CONTRAST, 2026-09-10 (Chris, reviewing the first pass): "the + * chart axis labels/gridlines are too low-contrast - dark grey on black, hard + * to read". The old ramp put gridlines at 42 and axis labels at 148 on a black + * plate, which on the phone's dark chart surface left the gridlines essentially + * invisible and the numbers a squint. Gridlines, the axis line and label text + * all moved up. + * + * `faint` is new and is where the things that were DELIBERATELY quiet went - + * the sample-data badge, the column divider, an unmapped hypnogram block. They + * used to share `grid`'s value, so raising `grid` for legibility would have + * dragged them up too; splitting the token is what lets the chart get brighter + * without the furniture shouting. + */ +export const INK = { + background: 0, + /** Deliberately quiet furniture - badges, dividers, unmapped blocks. */ + faint: 46, + grid: 100, + axis: 145, + band: 82, + bar: 168, + line: 250, + label: 205, + title: 255, + dim: 125, +} as const; + +export type ChartRect = { x: number; y: number; width: number; height: number }; + +export type ChartOptions = { + /** Only used to pick the default mode and to read `avg` vs `sum`. */ + metric: SampleMetric; + points: readonly RollupPoint[]; + font: UiFont; + /** Formats a point's x-axis label; return "" to leave a tick unlabelled. */ + xLabel: (point: RollupPoint, index: number) => string; + /** + * `band` draws a min/max band with the average through it; `bars` draws a + * column per bucket from zero. Defaults to bars for the cumulative metrics. + */ + mode?: "band" | "bars"; +}; + +/** + * A min/max band with the average tracked through it, or bars for the + * cumulative metrics. + * + * Gaps are drawn as gaps. A ring is taken off to charge, so missing hours are + * the normal case, not an edge case, and a line that joins across them claims + * a continuity the data does not have. + */ +export function drawMetricChart(image: GrayImage, rect: ChartRect, options: ChartOptions): void { + const { metric, points, font } = options; + const labelWidth = Math.max(34, font.measureText("8888") + 6); + const labelHeight = font.lineHeight + 2; + const plot: ChartRect = { + x: rect.x + labelWidth, + y: rect.y, + width: Math.max(8, rect.width - labelWidth), + height: Math.max(8, rect.height - labelHeight), + }; + + const withData = points.filter((point) => point.count > 0); + if (withData.length === 0) { + drawNoData(image, rect, font); + return; + } + + const bars = options.mode ? options.mode === "bars" : isCumulative(metric); + const scale = valueScale(withData, bars); + const showBand = !bars && bandIsMeaningful(points); + + drawGrid(image, plot, scale, font, rect.x); + + const slotWidth = plot.width / points.length; + const yFor = (value: number): number => + plot.y + plot.height - ((value - scale.low) / scale.span) * plot.height; + + if (bars) { + const barWidth = Math.max(1, Math.floor(slotWidth * 0.62)); + for (let index = 0; index < points.length; index += 1) { + const point = points[index]!; + if (point.count === 0) continue; + const top = yFor(point.sum); + const left = Math.round(plot.x + index * slotWidth + (slotWidth - barWidth) / 2); + const height = Math.max(1, Math.round(plot.y + plot.height - top)); + image.fillRect(left, Math.round(top), barWidth, height, INK.bar); + } + } else { + if (showBand) { + for (let index = 0; index < points.length; index += 1) { + const point = points[index]!; + if (point.count === 0) continue; + const left = Math.round(plot.x + index * slotWidth); + const width = Math.max(1, Math.round(slotWidth)); + const top = Math.round(yFor(point.max)); + const bottom = Math.round(yFor(point.min)); + image.fillRect(left, top, width, Math.max(1, bottom - top), INK.band); + } + } + // The average line, drawn only between adjacent points that both have + // data, so a gap stays a gap. + let previous: { x: number; y: number } | null = null; + for (let index = 0; index < points.length; index += 1) { + const point = points[index]!; + if (point.count === 0) { + previous = null; + continue; + } + const cx = plot.x + index * slotWidth + slotWidth / 2; + const cy = yFor(primaryValue(point, metric)); + if (previous) image.drawLine(previous.x, previous.y, cx, cy, INK.line); + else image.fillRect(Math.round(cx), Math.round(cy), 1, 1, INK.line); + previous = { x: cx, y: cy }; + } + } + + drawXLabels(image, plot, points, font, rect, options.xLabel); +} + +function drawNoData(image: GrayImage, rect: ChartRect, font: UiFont): void { + const message = "No data for this range"; + image.drawText( + font, + rect.x + Math.round((rect.width - font.measureText(message)) / 2), + rect.y + Math.round(rect.height / 2) - font.lineHeight, + message, + INK.dim, + ); +} + +/** X labels along the bottom of a plot, thinned so they never collide. */ +function drawXLabels( + image: GrayImage, + plot: ChartRect, + points: readonly { startMs: number }[], + font: UiFont, + clip: ChartRect, + xLabel: (point: never, index: number) => string, +): void { + const slotWidth = plot.width / Math.max(1, points.length); + const step = Math.max(1, Math.ceil(46 / Math.max(1, slotWidth))); + const labelY = plot.y + plot.height + 2; + for (let index = 0; index < points.length; index += step) { + const text = xLabel(points[index]! as never, index); + if (!text) continue; + const cx = plot.x + index * slotWidth + slotWidth / 2; + const x = Math.round(cx - font.measureText(text) / 2); + if (x < clip.x || x + font.measureText(text) > clip.x + clip.width) continue; + image.drawText(font, x, labelY, text, INK.label); + } +} + +type Scale = { low: number; high: number; span: number }; + +function valueScale(points: readonly RollupPoint[], bars: boolean): Scale { + let low = Number.POSITIVE_INFINITY; + let high = Number.NEGATIVE_INFINITY; + for (const point of points) { + const top = bars ? point.sum : point.max; + const bottom = bars ? 0 : point.min; + if (bottom < low) low = bottom; + if (top > high) high = top; + } + if (!Number.isFinite(low) || !Number.isFinite(high)) return { low: 0, high: 1, span: 1 }; + if (bars) low = 0; + if (high - low < 1) { + // A flat series still needs somewhere to sit; centre it rather than + // letting it collapse onto the axis. + low -= 1; + high += 1; + } + // Bars are measured from zero, so only the top gets breathing room - padding + // the bottom too would put a negative tick under a count that cannot go + // negative, and float the bars off their own baseline. + const pad = (high - low) * 0.08; + const scale = { low: bars ? low : low - pad, high: high + pad, span: 0 }; + scale.span = scale.high - scale.low || 1; + return scale; +} + +function drawGrid( + image: GrayImage, + plot: ChartRect, + scale: Scale, + font: UiFont, + labelX: number, +): void { + const lines = 3; + for (let index = 0; index < lines; index += 1) { + const fraction = index / (lines - 1); + const value = scale.high - fraction * scale.span; + const y = Math.round(plot.y + fraction * plot.height); + image.drawLine(plot.x, y, plot.x + plot.width, y, INK.grid); + const text = `${Math.round(value)}`; + const textY = Math.min( + plot.y + plot.height - font.lineHeight, + Math.max(plot.y, y - Math.round(font.lineHeight / 2)), + ); + image.drawText(font, labelX, textY, text, INK.label); + } + image.drawLine(plot.x, plot.y, plot.x, plot.y + plot.height, INK.axis); +} + +// =========================================================================== +// Sleep + +/** + * Stage inks. + * + * ⚠ RAISED AND REORDERED, 2026-09-10, alongside the diverging sleep chart. + * Within the upward stack the ramp descends with height - deep (bottom) is the + * brightest, light (top) the dimmest - so the three read as one column with a + * clear internal order rather than three similar greys. + * + * `wake` is deliberately NOT the dimmest any more, which looks wrong in a list + * and is right on the chart: awake time is drawn BELOW the zero line, so it is + * separated from the stack spatially rather than by brightness. That frees it + * to be legible (Chris's contrast note applies to it as much as to the axes) + * without it reading as part of the sleep stack. + */ +const STAGE_INK: Readonly> = { + wake: 150, + rem: 180, + light: 112, + deep: 250, +}; + +export function stageInk(stage: SleepStageName): number { + return STAGE_INK[stage]; +} + +/** + * The night as a run of stage blocks. + * + * This is the ONE thing on either surface that depends on the raw stage-id + * mapping, so while `STAGE_MAPPING_CONFIRMED` is false the caller is expected + * to caption it as unconfirmed - `hypnogramCaption()` supplies the wording. + */ +export function drawHypnogram( + image: GrayImage, + rect: ChartRect, + bands: readonly { stage: SleepStageName | null; seconds: number }[], +): void { + let total = 0; + for (const band of bands) total += band.seconds; + if (total <= 0) return; + let x = rect.x; + for (const band of bands) { + const width = (band.seconds / total) * rect.width; + const drawn = Math.max(1, Math.round(width)); + // An unmapped stage id is drawn as a hatch-dim block rather than being + // dropped: the time happened, we just cannot name it. + const ink = band.stage ? STAGE_INK[band.stage] : INK.faint; + image.fillRect(Math.round(x), rect.y, drawn, rect.height, ink); + x += width; + } + image.drawRect(rect.x, rect.y, rect.width, rect.height, INK.axis); +} + +export function hypnogramCaption(): string { + return STAGE_MAPPING_CONFIRMED + ? "Sleep stages through the night" + : "Stage pattern - labels not yet confirmed on live data"; +} + +/** The same caption for the glasses, where the line is 300-odd pixels wide. */ +export function hypnogramCaptionShort(): string { + return STAGE_MAPPING_CONFIRMED ? "Stages through the night" : "Stages - labels unconfirmed"; +} + +// =========================================================================== +// The diverging nightly sleep chart (week / month / 3 months) + +/** + * A night as a DIVERGING stacked bar - Chris's design, 2026-09-10. + * + * Sleep stacks upward from zero in the order deep (bottom), REM (middle), + * light (top). Awake time stacks DOWNWARD, below the zero line, as its own + * segment. + * + * The divergence is the whole idea and it is a claim about the data, not a + * styling choice: awake time is not a kind of sleep, so stacking it with the + * others would make a restless night's column look like a long one. Putting it + * below the line means the upward height is always "how much you slept" and + * can be compared across nights at a glance, while the downward tail says what + * it cost. A legend names the four, because a monochrome stack is not + * self-describing. + * + * ⚠ The stage ORDER is specified (deep/REM/light bottom-to-top, awake below); + * the axis ticks, the 1px separators and the legend placement are mine. + */ +/** + * The upward stack, BOTTOM TO TOP. Deep is the foundation of the column. + * + * See `SLEEP_LANE_ORDER` for why this and the lane order only look like they + * disagree. + */ +export const SLEEP_STACK_ORDER: readonly SleepStageName[] = ["deep", "rem", "light"]; + +/** + * The one-night detail's lanes, TOP TO BOTTOM. + * + * ⚠ THESE TWO ORDERS LOOK CONTRADICTORY AND ARE NOT. Chris gave both in the + * same review, in opposite directions: the week/month chart stacks "Deep + * (bottom), REM (middle), light (top)" upward with awake below zero, and the + * one-day view lists "Awake, light, REM, Deep" downward. Stated that way they + * read as a conflict, which is why the brief flagged the difference as + * deliberate rather than a typo. + * + * Resolve both to the same direction and the conflict disappears. Top to + * bottom, the stack is light / REM / deep; top to bottom, the lanes are awake / + * light / REM / deep. The three sleep stages are in the SAME vertical order in + * both views - deep at the bottom, light nearest the top - so a reader who + * learns the arrangement on one screen reads the other correctly without + * relearning it. + * + * The one genuine difference is where awake goes: its own lane above the + * others here, its own bar below the zero line there. That follows from what + * each view is: a timeline has to show awake in sequence with everything else, + * and a stacked total must not add it to the sleep it interrupted. + * + * A test pins the agreement, so "fixing" either order breaks it loudly. + */ +export const SLEEP_LANE_ORDER: readonly SleepStageName[] = ["wake", "light", "rem", "deep"]; + +/** Descending "nice" ticks for the awake axis, in hours: 4h..5m. */ +const DOWN_TICK_HOURS = [4, 2, 1, 0.5, 0.25, 1 / 6, 1 / 12]; + +/** "2" for whole hours, "30m" below one - the awake side is usually minutes. */ +function formatHourTick(hours: number): string { + return hours >= 1 ? `${hours}` : `${Math.round(hours * 60)}m`; +} + +export function drawSleepStackChart( + image: GrayImage, + rect: ChartRect, + options: { + nights: readonly SleepNight[]; + font: UiFont; + xLabel: (night: SleepNight, index: number) => string; + }, +): void { + const { nights, font } = options; + const labelWidth = Math.max(34, font.measureText("-88m") + 6); + const legendHeight = font.lineHeight + 4; + const labelHeight = font.lineHeight + 2; + const plot: ChartRect = { + x: rect.x + labelWidth, + y: rect.y + legendHeight, + width: Math.max(8, rect.width - labelWidth), + height: Math.max(8, rect.height - labelHeight - legendHeight), + }; + + drawStageLegend(image, rect.x, rect.y, rect.width, font); + + const withData = nights.filter((night) => night.hasData); + if (withData.length === 0) { + drawNoData(image, rect, font); + return; + } + + const hours = (seconds: number): number => seconds / 3600; + let maxUp = 0; + let maxDown = 0; + for (const night of withData) { + const up = hours(night.deepSec + night.remSec + night.lightSec); + const down = hours(night.wakeSec); + if (up > maxUp) maxUp = up; + if (down > maxDown) maxDown = down; + } + // Headroom above, and a floor under the awake band so a night with almost no + // wake time still leaves the zero line off the bottom edge. + maxUp = Math.max(1, maxUp * 1.08); + maxDown = Math.max(0.5, maxDown * 1.15); + + const span = maxUp + maxDown; + const zeroY = Math.round(plot.y + (maxUp / span) * plot.height); + const pxPerHour = plot.height / span; + + // Gridlines: whole hours above zero, and one below for the awake side. + const upStep = maxUp > 9 ? 4 : maxUp > 4 ? 2 : 1; + for (let hour = upStep; hour <= maxUp; hour += upStep) { + const y = Math.round(zeroY - hour * pxPerHour); + if (y < plot.y) break; + image.drawLine(plot.x, y, plot.x + plot.width, y, INK.grid); + image.drawText(font, rect.x, y - Math.round(font.lineHeight / 2), `${hour}`, INK.label); + } + // The awake side needs its own tick ladder, not the hour steps used above. + // A typical night is six hours of sleep against ten or twenty minutes awake, + // so a whole-hour tick below zero falls off the bottom of the chart and the + // downward axis ends up unlabelled - which is what the first cut of this did. + const downTick = DOWN_TICK_HOURS.find((hours) => hours <= maxDown * 0.95); + if (downTick !== undefined) { + const downY = Math.round(zeroY + downTick * pxPerHour); + if (downY <= plot.y + plot.height) { + image.drawLine(plot.x, downY, plot.x + plot.width, downY, INK.grid); + image.drawText( + font, + rect.x, + downY - Math.round(font.lineHeight / 2), + `-${formatHourTick(downTick)}`, + INK.label, + ); + } + } + + const slotWidth = plot.width / nights.length; + const barWidth = Math.max(1, Math.floor(slotWidth * 0.68)); + + for (let index = 0; index < nights.length; index += 1) { + const night = nights[index]!; + if (!night.hasData) continue; + const left = Math.round(plot.x + index * slotWidth + (slotWidth - barWidth) / 2); + + // Upward: deep at the bottom, then REM, then light. Drawn from the zero + // line outward so rounding never opens a gap at the baseline. + let cursor = zeroY; + const secondsByStage: Record = { + deep: night.deepSec, + rem: night.remSec, + light: night.lightSec, + wake: night.wakeSec, + }; + const upward: [number, number][] = SLEEP_STACK_ORDER.map((stage) => [ + secondsByStage[stage], + STAGE_INK[stage], + ]); + for (const [seconds, ink] of upward) { + if (seconds <= 0) continue; + const height = Math.max(1, Math.round(hours(seconds) * pxPerHour)); + const top = Math.max(plot.y, cursor - height); + image.fillRect(left, top, barWidth, Math.max(1, cursor - top), ink); + cursor = top; + // A 1px unlit separator so two adjacent greys stay two segments. Only + // worth it when the bar is tall enough to still read as a block. + if (cursor > plot.y + 1 && height > 3) { + image.fillRect(left, cursor, barWidth, 1, INK.background); + } + } + + // Downward: awake, below the line. + if (night.wakeSec > 0) { + const height = Math.max(1, Math.round(hours(night.wakeSec) * pxPerHour)); + const bottom = Math.min(plot.y + plot.height, zeroY + 1 + height); + image.fillRect(left, zeroY + 1, barWidth, Math.max(1, bottom - zeroY - 1), STAGE_INK.wake); + } + } + + // The zero line last, so it sits on top of every bar that touches it - it is + // the reference the whole chart is read against. + image.drawLine(plot.x, zeroY, plot.x + plot.width, zeroY, INK.axis); + image.drawText(font, rect.x, zeroY - Math.round(font.lineHeight / 2), "0", INK.label); + image.drawLine(plot.x, plot.y, plot.x, plot.y + plot.height, INK.axis); + + drawXLabels( + image, + { ...plot, y: plot.y, height: plot.height }, + nights, + font, + { ...rect, y: plot.y, height: plot.height }, + ((night: SleepNight, index: number) => options.xLabel(night, index)) as never, + ); +} + +/** + * The four stages as swatch + name, on one line. + * + * Awake is listed last and marked, because its bar goes the other way and a + * legend that reads deep/REM/light/awake in a row would imply they stack + * together. + */ +export function drawStageLegend( + image: GrayImage, + x: number, + y: number, + width: number, + font: UiFont, +): void { + const entries: [string, number][] = [ + ["Deep", STAGE_INK.deep], + ["REM", STAGE_INK.rem], + ["Light", STAGE_INK.light], + ["Awake v", STAGE_INK.wake], + ]; + const swatch = Math.max(6, font.lineHeight - 4); + let cursor = x; + for (const [label, ink] of entries) { + const textWidth = font.measureText(label); + const entryWidth = swatch + 4 + textWidth + 12; + if (cursor + entryWidth > x + width) break; + image.fillRect(cursor, y + 2, swatch, swatch, ink); + image.drawRect(cursor, y + 2, swatch, swatch, INK.axis); + image.drawText(font, cursor + swatch + 4, y, label, INK.label); + cursor += entryWidth; + } +} + +// =========================================================================== +// The one-night sleep detail (the glasses drill-down) + +/** + * One night as four horizontal LANES, stacked top to bottom in the order + * Awake, Light, REM, Deep - Chris's ordering, 2026-09-10. It is stated in the + * opposite direction from the week chart's and therefore reads as a conflict + * with it; it is not one, and `SLEEP_LANE_ORDER` explains why. Both views put + * deep at the bottom. + * + * ⚠ PROPORTIONS ARE A DESIGN CALL. The stage order and the top-to-bottom + * orientation are specified; "exactly what arranged vertically should look + * like pixel-for-pixel wasn't specified further than that ordering". So: four + * equal-height lanes across the full width of the night, each lane's blocks + * filled where the sleeper was in that stage, with the lane's name and its + * total on the left. Equal heights rather than height-proportional-to-duration, + * because the lane's JOB is to show when that stage happened, and a 4%-of-night + * deep lane squeezed to a few pixels would show nothing. + */ +export function drawSleepLanes( + image: GrayImage, + rect: ChartRect, + options: { + bands: readonly { stage: SleepStageName | null; seconds: number }[]; + font: UiFont; + /** Left-column label + total for each lane, in lane order. */ + laneText: (stage: SleepStageName) => { label: string; value: string }; + }, +): void { + const { bands, font } = options; + const LANE_ORDER = SLEEP_LANE_ORDER; + + let total = 0; + for (const band of bands) total += band.seconds; + if (total <= 0) { + drawNoData(image, rect, font); + return; + } + + // The left column has to fit "Awake" plus its duration; measure rather than + // guess, so a larger UI font does not overrun the lanes. + let gutter = 0; + for (const stage of LANE_ORDER) { + const text = options.laneText(stage); + gutter = Math.max(gutter, font.measureText(text.label), font.measureText(text.value)); + } + gutter += 10; + + const laneX = rect.x + gutter; + const laneWidth = Math.max(8, rect.width - gutter); + const axisHeight = font.lineHeight + 2; + const laneGap = 4; + const laneHeight = Math.max( + 6, + Math.floor((rect.height - axisHeight - laneGap * (LANE_ORDER.length - 1)) / LANE_ORDER.length), + ); + + for (let index = 0; index < LANE_ORDER.length; index += 1) { + const stage = LANE_ORDER[index]!; + const top = rect.y + index * (laneHeight + laneGap); + const text = options.laneText(stage); + + // The lane's own track, so an empty stretch still reads as a lane rather + // than as nothing. + image.drawRect(laneX, top, laneWidth, laneHeight, INK.faint); + + let cursor = laneX; + for (const band of bands) { + const width = (band.seconds / total) * laneWidth; + if (band.stage === stage) { + image.fillRect(Math.round(cursor), top, Math.max(1, Math.round(width)), laneHeight, STAGE_INK[stage]); + } + cursor += width; + } + + // Name above its own duration, both in the gutter, vertically centred on + // the lane when there is room for two lines. + const twoLines = laneHeight >= font.lineHeight * 2; + const textTop = twoLines + ? top + Math.round((laneHeight - font.lineHeight * 2) / 2) + : top + Math.round((laneHeight - font.lineHeight) / 2); + image.drawText(font, rect.x, textTop, text.label, INK.label); + if (twoLines) image.drawText(font, rect.x, textTop + font.lineHeight, text.value, INK.line); + } + + // A time axis under the lanes: the night runs left to right, so mark its + // ends. Without this the lanes are a proportion with no anchor. + const axisY = rect.y + LANE_ORDER.length * (laneHeight + laneGap); + image.drawLine(laneX, axisY, laneX + laneWidth, axisY, INK.axis); +} + +// =========================================================================== +// Small shared pieces + +/** + * A "min / avg / max" readout, the shape both surfaces use for a metric. + * + * `whole` rounds all three. The glance passes it: an average heart rate + * printed as 72.7 reads as precision the measurement does not have, and on a + * screen you glance at rather than study, the tenth is noise. The phone's stat + * panel keeps the decimal, where comparing two averages is the point. + */ +export function tripleText( + summary: { min: number; max: number; avg: number; hasData: boolean }, + metric: SampleMetric, + options?: { whole?: boolean }, +): string { + if (!summary.hasData) return "--"; + const show = (value: number): string => + options?.whole ? `${Math.round(value)}` : formatValue(value, metric); + return `${show(summary.min)} / ${show(summary.avg)} / ${show(summary.max)}`; +} + +/** + * "60-98 bpm, avg 73" - the glance's metric line. + * + * ⚠ REPLACES the min/avg/max triple on the glasses overview, Chris 2026-09-10: + * three bare numbers under a "min / avg / max" legend made the reader do the + * decoding. A range and an average is the same information said in the shape a + * person would say it in, and it needs no legend line underneath. + * + * The separator is an ASCII hyphen, not an en dash: the glasses render through + * Terminus, and a codepoint the face does not carry comes back as the default + * char - a "?" in the middle of the number - rather than failing loudly. + */ +export function rangeAverageText( + summary: { min: number; max: number; avg: number; hasData: boolean }, + unit: string, +): string { + if (!summary.hasData) return "--"; + const whole = (value: number): string => `${Math.round(value)}`; + const range = `${whole(summary.min)}-${whole(summary.max)}`; + return unit ? `${range} ${unit}, avg ${whole(summary.avg)}` : `${range}, avg ${whole(summary.avg)}`; +} + +/** A right-aligned draw, for readouts that should line up on their last digit. */ +export function drawTextRight( + image: GrayImage, + font: UiFont, + right: number, + y: number, + text: string, + value: number, +): void { + image.drawText(font, Math.round(right - font.measureText(text)), y, text, value); +} diff --git a/app/health/health-derive.ts b/app/health/health-derive.ts new file mode 100644 index 00000000..ad6feaf6 --- /dev/null +++ b/app/health/health-derive.ts @@ -0,0 +1,437 @@ +/** + * Every derived number the two health surfaces show, in one place, with no + * NativeScript imports so it runs under plain node in `tests/`. + * + * The rule this file follows throughout: show what the ring actually said, or + * say we do not know. Nothing here invents a value to fill a gap, and the one + * composite score a health app is expected to have - a 0-100 "sleep quality" - + * is deliberately absent. See `sleepSummary` for why. + */ + +import { + DAY_MS, + HOUR_MS, + type HealthSample, + type Rollup, + type RollupPoint, + type SampleMetric, + type SleepNight, + type SleepSession, + isCumulative, + rollupOf, + startOfLocalDay, + startOfLocalHour, +} from "./health-types"; +import { STAGE_DISPLAY_ORDER, type SleepStageName, stageNameForId } from "./sleep-stages"; + +export type Granularity = "hour" | "day"; + +/** How far back a chart looks. Hour granularity only makes sense within a day. */ +export type RangeKey = "day" | "week" | "month" | "quarter"; + +export const RANGE_DAYS: Readonly> = { + day: 1, + week: 7, + month: 30, + quarter: 90, +}; + +export const RANGE_LABELS: Readonly> = { + day: "Day", + week: "Week", + month: "Month", + quarter: "3 months", +}; + +/** + * Bucket samples into a series of rollups on a fixed grid. + * + * The grid is built first and then filled, so a window with no data comes back + * as a gap (`count === 0`) at its real position rather than being silently + * dropped - a chart that closes over its gaps lies about continuity, which for + * a ring that is taken off to charge is the common case, not an edge case. + */ +export function rollupSeries( + samples: readonly HealthSample[], + options: { + metric: SampleMetric; + granularity: Granularity; + /** Inclusive local start of the plotted window. */ + startMs: number; + /** Exclusive local end. */ + endMs: number; + }, +): RollupPoint[] { + const { metric, granularity, startMs, endMs } = options; + const spanMs = granularity === "hour" ? HOUR_MS : DAY_MS; + const align = granularity === "hour" ? startOfLocalHour : startOfLocalDay; + + const buckets = new Map(); + for (const sample of samples) { + if (sample.metric !== metric) continue; + if (sample.startMs < startMs || sample.startMs >= endMs) continue; + const key = align(sample.startMs); + const list = buckets.get(key); + if (list) list.push(sample); + else buckets.set(key, [sample]); + } + + const points: RollupPoint[] = []; + // Walk by calendar step rather than adding spanMs, so a DST change does not + // shift every later bucket by an hour. + let cursor = align(startMs); + let guard = 0; + while (cursor < endMs && guard < 4000) { + guard += 1; + const inBucket = buckets.get(cursor) ?? []; + const rolled = rollupOf(inBucket); + points.push({ + startMs: cursor, + spanMs, + ...(rolled ?? { min: 0, max: 0, avg: 0, sum: 0, count: 0 }), + }); + cursor = nextBucketStart(cursor, granularity); + } + return points; +} + +export function nextBucketStart(startMs: number, granularity: Granularity): number { + const date = new Date(startMs); + if (granularity === "hour") date.setHours(date.getHours() + 1, 0, 0, 0); + else date.setDate(date.getDate() + 1); + return date.getTime(); +} + +/** The value a chart plots as "the" line for a metric. */ +export function primaryValue(point: Rollup, metric: SampleMetric): number { + return isCumulative(metric) ? point.sum : point.avg; +} + +// =========================================================================== +// The glasses status page's numbers + +export type MetricSummary = { + min: number; + max: number; + avg: number; + /** False when nothing was recorded - the UI shows a dash, not a zero. */ + hasData: boolean; +}; + +export type DailySummary = { + dayStartMs: number; + steps: number; + calories: number; + heartRate: MetricSummary; + spo2: MetricSummary; + /** + * ⚠ ADDED 2026-09-10. The first pass left HRV off the glance because Chris's + * original spec listed steps/calories/HR/SpO2/sleep and nothing else, and the + * return doc flagged the absence as deliberate rather than an oversight. He + * revised the spec on review: HRV gets a line alongside the others. + */ + hrv: MetricSummary; + sleep: SleepSummary | null; +}; + +const NO_DATA: MetricSummary = { min: 0, max: 0, avg: 0, hasData: false }; + +function summarise(samples: readonly HealthSample[], metric: SampleMetric): MetricSummary { + const rolled = rollupOf(samples.filter((sample) => sample.metric === metric)); + if (!rolled) return NO_DATA; + return { min: rolled.min, max: rolled.max, avg: rolled.avg, hasData: true }; +} + +function sumOf(samples: readonly HealthSample[], metric: SampleMetric): number { + let total = 0; + for (const sample of samples) if (sample.metric === metric) total += sample.total; + return total; +} + +/** + * Everything the glasses glance shows, for one local day. + * + * `sleepSessions` is searched for the night that ENDED on this day - the + * "last night's sleep" a morning glance means. A session is attributed to its + * wake-up day on ingest (`SleepSession.dayStartMs`), so this is a lookup, not + * a heuristic applied here. + */ +export function dailySummary( + samples: readonly HealthSample[], + sleepSessions: readonly SleepSession[], + dayStartMs: number, +): DailySummary { + const dayEndMs = nextBucketStart(dayStartMs, "day"); + const inDay = samples.filter( + (sample) => sample.startMs >= dayStartMs && sample.startMs < dayEndMs, + ); + const nights = sleepSessions.filter((session) => session.dayStartMs === dayStartMs); + return { + dayStartMs, + steps: Math.round(sumOf(inDay, "steps")), + calories: Math.round(sumOf(inDay, "calories")), + heartRate: summarise(inDay, "heartRate"), + spo2: summarise(inDay, "spo2"), + hrv: summarise(inDay, "hrv"), + sleep: combinedSleepSummary(nights), + }; +} + +// =========================================================================== +// Sleep + +export type SleepSummary = { + totalSec: number; + /** Whole hours and remaining minutes of `totalSec`, for "6h 42m". */ + hours: number; + minutes: number; + wakeSec: number; + /** Percentages OF TOTAL SLEEP TIME, from the record's named totals. */ + remPercent: number; + lightPercent: number; + deepPercent: number; + /** + * `total_time / (total_time + wake_time)`, as a percentage. + * + * This is sleep efficiency as the AASM's actigraphy scoring defines it - + * time asleep over time in bed - and it is a decades-old published standard, + * not something invented here. It is the one number added beyond Chris's + * stated spec, and it is included precisely because it is the opposite of + * the thing that was ruled out: it has a definition anyone can look up. + * + * Deliberately NOT here: a single 0-100 "sleep quality" score. Every + * consumer wearable has one, none of them publish the blend, and there is no + * generally-accepted formula - so it would be a number with the authority of + * a measurement and the content of an opinion. Stage percentages and + * efficiency are shown as themselves instead. + */ + efficiencyPercent: number; + /** Hypnogram bands, in display order. Empty when the record had no segments. */ + stageBands: readonly SleepStageBand[]; + /** False when the session could not be anchored to real wall-clock time. */ + timeResolved: boolean; +}; + +export type SleepStageBand = { + stage: SleepStageName; + seconds: number; + /** Share of total-time-in-bed (sleep + wake), so the bands sum to 100%. */ + percentOfBed: number; +}; + +export function sleepSummary(session: SleepSession): SleepSummary { + const total = Math.max(0, session.totalSec); + const wake = Math.max(0, session.wakeSec); + const inBed = total + wake; + const pctOfSleep = (value: number): number => (total > 0 ? (value / total) * 100 : 0); + const bedSeconds: Record = { + wake, + rem: Math.max(0, session.remSec), + light: Math.max(0, session.lightSec), + deep: Math.max(0, session.deepSec), + }; + return { + totalSec: total, + hours: Math.floor(total / 3600), + minutes: Math.round((total % 3600) / 60), + wakeSec: wake, + remPercent: pctOfSleep(session.remSec), + lightPercent: pctOfSleep(session.lightSec), + deepPercent: pctOfSleep(session.deepSec), + efficiencyPercent: inBed > 0 ? (total / inBed) * 100 : 0, + stageBands: STAGE_DISPLAY_ORDER.map((stage) => ({ + stage, + seconds: bedSeconds[stage], + percentOfBed: inBed > 0 ? (bedSeconds[stage] / inBed) * 100 : 0, + })), + timeResolved: session.timeResolved, + }; +} + +/** Every recorded block attributed to the day contributes to its headline. */ +export function combinedSleepSummary(sessions: readonly SleepSession[]): SleepSummary | null { + if (sessions.length === 0) return null; + const combined: SleepSession = { + ...sessions[0], totalSec: 0, wakeSec: 0, remSec: 0, lightSec: 0, deepSec: 0, + timeResolved: sessions.every((session) => session.timeResolved), + }; + for (const session of sessions) { + for (const field of ["totalSec", "wakeSec", "remSec", "lightSec", "deepSec"] as const) { + combined[field] += Math.max(0, session[field]); + } + } + return sleepSummary(combined); +} + +/** + * One stage's seconds, from the summary's own bands. + * + * Both surfaces label a stage lane with its duration, and both must take that + * number from the record's NAMED per-stage fields (which `sleepSummary` already + * resolved into `stageBands`) rather than by summing the hypnogram's blocks. + * The two should agree; when they do not it is the segment array that is + * suspect, because summing blocks depends on the stage-id mapping and the named + * fields do not. See `sleep-stages.ts`. + */ +export function stageSeconds(stage: SleepStageName, summary: SleepSummary): number { + return summary.stageBands.find((band) => band.stage === stage)?.seconds ?? 0; +} + +/** + * One entry per day in the window, carrying that night's four stage totals. + * + * Built for the diverging nightly chart (deep/REM/light stacked up, awake + * down). Like `rollupSeries`, the grid is laid out first and then filled, so a + * night with no record comes back as `hasData: false` at its real position + * rather than shifting every later night one column left. + * + * Sessions attributed to the same day are summed, as in `dailySummary`. + */ +export function sleepNights( + sessions: readonly SleepSession[], + startMs: number, + endMs: number, +): SleepNight[] { + const byDay = new Map(); + for (const session of sessions) { + if (session.dayStartMs < startMs || session.dayStartMs >= endMs) continue; + const entry = byDay.get(session.dayStartMs) ?? { + startMs: session.dayStartMs, + hasData: true, + deepSec: 0, + remSec: 0, + lightSec: 0, + wakeSec: 0, + }; + entry.deepSec += Math.max(0, session.deepSec); + entry.remSec += Math.max(0, session.remSec); + entry.lightSec += Math.max(0, session.lightSec); + entry.wakeSec += Math.max(0, session.wakeSec); + byDay.set(session.dayStartMs, entry); + } + + const nights: SleepNight[] = []; + let cursor = startOfLocalDay(startMs); + let guard = 0; + while (cursor < endMs && guard < 4000) { + guard += 1; + nights.push( + byDay.get(cursor) ?? { + startMs: cursor, + hasData: false, + deepSec: 0, + remSec: 0, + lightSec: 0, + wakeSec: 0, + }, + ); + cursor = nextBucketStart(cursor, "day"); + } + return nights; +} + +/** + * The hypnogram: the night as a run of stage blocks, in order. + * + * This is the ONE thing that depends on the raw stage-id mapping, which is why + * it is separated from `sleepSummary`'s percentages (those come from named + * fields and are unaffected). A segment whose id is not in the mapping is + * returned with `stage: null` rather than dropped or guessed at. + */ +export function hypnogram(session: SleepSession): { stage: SleepStageName | null; seconds: number }[] { + return session.segments.map((segment) => ({ + stage: stageNameForId(segment.stageId), + seconds: segment.halfMinutes * 30, + })); +} + +/** Chronological blocks, with unrecorded intervals left as unknown gaps. */ +export function dailyHypnogram(sessions: readonly SleepSession[], dayStartMs: number): ReturnType { + const result: ReturnType = []; + let previousEnd: number | null = null; + for (const session of sessions.filter((s) => s.dayStartMs === dayStartMs) + .sort((a, b) => a.startMs - b.startMs)) { + if (previousEnd !== null && session.timeResolved && session.startMs > previousEnd) { + result.push({ stage: null, seconds: (session.startMs - previousEnd) / 1000 }); + } + const bands = hypnogram(session); + result.push(...bands); + // A session without stage data still occupies its recorded interval. + const covered = bands.reduce((total, band) => total + band.seconds, 0); + const duration = session.timeResolved + ? Math.max(0, (session.endMs - session.startMs) / 1000) + : session.totalSec + session.wakeSec; + if (duration > covered) result.push({ stage: null, seconds: duration - covered }); + previousEnd = session.timeResolved ? Math.max(previousEnd ?? 0, session.endMs) : null; + } + return result; +} + +/** + * Date formatting, done by hand. + * + * ⚠ MEASURED, not a preference: `toLocaleDateString(undefined, { weekday: + * "short" })` in this NativeScript Android runtime IGNORES the options bag and + * returns the full `Fri Sep 04 2026`. It is the usual cause - a JS engine + * built without full ICU quietly falls back instead of failing - and it turned + * a week chart's axis into seven overlapping full dates. Anything that needs a + * specific date shape has to build it, so these are the only date formatters + * either surface uses. + * + * The cost is that they are English-only. That is a real limitation and the + * right place to fix it is the runtime's ICU, not here. + */ +const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] as const; +const MONTHS = [ + "Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", +] as const; + +/** "Fri". */ +export function shortWeekday(ms: number): string { + return WEEKDAYS[new Date(ms).getDay()] ?? ""; +} + +/** "Thu 10 Sep". */ +export function shortDate(ms: number): string { + const date = new Date(ms); + return `${WEEKDAYS[date.getDay()]} ${date.getDate()} ${MONTHS[date.getMonth()]}`; +} + +/** "6h 42m", or "--" when there is nothing to show. */ +export function formatDuration(seconds: number): string { + if (!Number.isFinite(seconds) || seconds <= 0) return "--"; + const hours = Math.floor(seconds / 3600); + const minutes = Math.round((seconds % 3600) / 60); + return hours > 0 ? `${hours}h ${minutes}m` : `${minutes}m`; +} + +/** One decimal at most, and never a trailing ".0". */ +export function formatValue(value: number, metric: SampleMetric): string { + if (!Number.isFinite(value)) return "--"; + if (isCumulative(metric)) return `${Math.round(value)}`; + const rounded = Math.round(value * 10) / 10; + return Number.isInteger(rounded) ? `${rounded}` : rounded.toFixed(1); +} + +/** + * Whether a metric's min/max band is worth drawing. + * + * Measured against the real export before this was written: heart rate's + * hourly min and max differ in 98% of buckets, but SpO2's and HRV's are + * IDENTICAL in 97% of them - the ring reports what amounts to a single reading + * per hour for those two. Drawing a band there produces a hairline that reads + * as a rendering fault rather than as "there is no spread", so the charts drop + * to a plain line when the spread is degenerate across the window. + */ +export function bandIsMeaningful(points: readonly RollupPoint[]): boolean { + let withData = 0; + let withSpread = 0; + for (const point of points) { + if (point.count === 0) continue; + withData += 1; + if (point.max > point.min) withSpread += 1; + } + if (withData === 0) return false; + return withSpread / withData >= 0.25; +} diff --git a/app/health/health-fixtures.ts b/app/health/health-fixtures.ts new file mode 100644 index 00000000..3bae7886 --- /dev/null +++ b/app/health/health-fixtures.ts @@ -0,0 +1,246 @@ +/** + * SAMPLE DATA. Not a capture, not anybody's health history. + * + * Every number below is generated from a seeded PRNG against hand-written + * ranges. Nothing here was copied out of an export. What WAS taken from the + * real export - by reading it, which is all this needed - is the *shape*: + * + * - heart rate, SpO2 and HRV arrive as HOURLY buckets carrying (avg, max, + * min); steps and calories as TEN-MINUTE buckets; sleep once per session. + * - heart rate's hourly min and max genuinely differ (they were equal in + * about 2% of real buckets), but SpO2's and HRV's are equal in about 97% + * of theirs - the ring effectively reports one reading an hour for those + * two. The generator reproduces that, because a chart that assumes a + * spread everywhere looks broken on the two metrics that do not have one. + * - roughly a third of a day's ten-minute step buckets are non-zero; the + * rest are flat, because people sit still. + * - a night is a handful of hours with a majority in light sleep, a smaller + * REM share, a smaller deep share again, and a short wake total. + * + * The ranges are round numbers chosen to sit in the same neighbourhood as + * those shapes, not measured constants, and the seed is fixed so a screenshot + * taken today matches one taken next week. + * + * `seedFixtures()` also drops a marker file, and both surfaces show a "Sample + * data" badge whenever it is present - so a screenshot of this can never be + * mistaken later for a screenshot of a real sync. + */ + +import { + DAY_MS, + HOUR_MS, + TEN_MINUTES_MS, + type HealthSample, + type SleepSession, + type SleepSegment, + startOfLocalDay, +} from "./health-types"; + +/** Bumped whenever the generator changes, so a reseed replaces old fixtures. */ +export const FIXTURE_VERSION = 1; + +/** Deterministic, tiny, and good enough for plausible-looking noise. */ +function mulberry32(seed: number): () => number { + let a = seed >>> 0; + return () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = Math.imul(a ^ (a >>> 15), 1 | a); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +function between(random: () => number, low: number, high: number): number { + return low + random() * (high - low); +} + +/** + * A daily activity curve: near-nothing overnight, a morning rise, a dip after + * lunch, an evening peak. Returns roughly 0..1 for an hour of the day. + */ +function activityCurve(hour: number): number { + if (hour < 6) return 0.03; + if (hour < 9) return 0.45; + if (hour < 12) return 0.7; + if (hour < 14) return 0.5; + if (hour < 18) return 0.75; + if (hour < 21) return 0.9; + return 0.25; +} + +export type Fixtures = { + samples: HealthSample[]; + sleep: SleepSession[]; +}; + +/** + * Generate `days` days of sample data ending with today (partially filled up + * to `nowMs`, so "today so far" looks like a day in progress rather than a + * complete one). + */ +export function buildFixtures(options: { days: number; nowMs: number; seed?: number }): Fixtures { + const { days, nowMs } = options; + const random = mulberry32(options.seed ?? 0x5eed); + const samples: HealthSample[] = []; + const sleep: SleepSession[] = []; + const today = startOfLocalDay(nowMs); + + for (let dayOffset = days - 1; dayOffset >= 0; dayOffset -= 1) { + const dayStart = startOfLocalDay(today - dayOffset * DAY_MS); + // A per-day baseline so consecutive days are not interchangeable. + const restingBase = between(random, 56, 66); + const hrvBase = between(random, 32, 55); + const spo2Base = between(random, 96, 98); + + for (let hour = 0; hour < 24; hour += 1) { + const bucketStart = dayStart + hour * HOUR_MS; + if (bucketStart > nowMs) break; + const effort = activityCurve(hour); + + // Heart rate: a real spread every hour. + const avg = restingBase + effort * between(random, 10, 34); + const spread = 4 + effort * between(random, 6, 26); + samples.push({ + metric: "heartRate", + startMs: bucketStart, + spanMs: HOUR_MS, + min: Math.round(avg - spread * between(random, 0.35, 0.6)), + max: Math.round(avg + spread * between(random, 0.5, 0.9)), + avg: Math.round(avg), + total: Math.round(avg), + }); + + // SpO2 and HRV: one reading an hour most of the time, so min == max. + const spo2 = Math.round(spo2Base + between(random, -2, 1.4)); + const spo2Flat = random() < 0.97; + samples.push({ + metric: "spo2", + startMs: bucketStart, + spanMs: HOUR_MS, + min: spo2Flat ? spo2 : spo2 - 1, + max: spo2Flat ? spo2 : spo2 + 1, + avg: spo2, + total: spo2, + }); + + const hrv = Math.round(Math.max(6, hrvBase + between(random, -14, 18) - effort * 8)); + const hrvFlat = random() < 0.97; + samples.push({ + metric: "hrv", + startMs: bucketStart, + spanMs: HOUR_MS, + min: hrvFlat ? hrv : Math.max(2, hrv - 4), + max: hrvFlat ? hrv : hrv + 5, + avg: hrv, + total: hrv, + }); + + // Steps and calories: six ten-minute buckets inside this hour. + for (let slot = 0; slot < 6; slot += 1) { + const bucket = bucketStart + slot * TEN_MINUTES_MS; + if (bucket > nowMs) break; + const moving = random() < effort * 0.55; + const steps = moving ? Math.round(between(random, 20, 430) * effort) : 0; + const resting = Math.round(between(random, 10, 13)); + const active = Math.round(steps * between(random, 0.03, 0.05)); + samples.push({ + metric: "steps", + startMs: bucket, + spanMs: TEN_MINUTES_MS, + min: steps, + max: steps, + avg: steps, + total: steps, + }); + samples.push({ + metric: "calories", + startMs: bucket, + spanMs: TEN_MINUTES_MS, + min: resting + active, + max: resting + active, + avg: resting + active, + total: resting + active, + }); + } + } + + sleep.push(buildNight(random, dayStart)); + } + + return { samples, sleep }; +} + +/** + * One night, attributed to the morning it ended on (`dayStart`). + * + * Built SEGMENTS FIRST, then the five duration totals summed out of them - + * the same direction a real record is consistent in. The decode found four + * arithmetic identities holding exactly on every real session, including + * `sum(half_minutes) * 30 == total_time + wake_time` and a per-stage sum + * matching each named total. Generating the totals first and the segments + * afterwards cannot satisfy those exactly once rounding is involved, so this + * goes the other way and the identities hold by construction. + */ +function buildNight(random: () => number, dayStart: number): SleepSession { + const inBedHalfMinutes = Math.round(between(random, 4.4, 6.6) * 120); + const bedMs = dayStart - inBedHalfMinutes * 30 * 1000; + const segments = buildSegments(random, inBedHalfMinutes); + + const perStage = new Map(); + for (const segment of segments) { + perStage.set(segment.stageId, (perStage.get(segment.stageId) ?? 0) + segment.halfMinutes); + } + const seconds = (stageId: number): number => (perStage.get(stageId) ?? 0) * 30; + const wakeSec = seconds(0); + const remSec = seconds(1); + const lightSec = seconds(2); + const deepSec = seconds(3); + const totalSec = remSec + lightSec + deepSec; + + return { + dayStartMs: dayStart, + startMs: bedMs, + endMs: bedMs + (totalSec + wakeSec) * 1000, + totalSec, + wakeSec, + remSec, + lightSec, + deepSec, + segments, + timeResolved: true, + }; +} + +/** + * A segment run filling exactly `inBedHalfMinutes`, cycling through the stages + * the way a night does: light, deep, light, REM, and the occasional wake block. + * + * Stage ids are the RAW ring ids (0 wake, 1 REM, 2 light, 3 deep). The fixture + * deliberately emits ids rather than friendly names, so anything downstream + * that forgets to resolve them through `stageNameForId` is wrong here too. + * + * The per-stage weights are what produce a plausible mix - light dominant, + * then deep, then REM, with a small wake share - matching the ordering the + * real export shows without reproducing its numbers. + */ +function buildSegments(random: () => number, inBedHalfMinutes: number): SleepSegment[] { + const cycle = [2, 3, 2, 1, 2, 0]; + const typicalLength: Record = { + 0: [1, 6], + 1: [8, 26], + 2: [14, 40], + 3: [10, 30], + }; + const segments: SleepSegment[] = []; + let remaining = inBedHalfMinutes; + let index = 0; + while (remaining > 0) { + const stage = cycle[index % cycle.length]!; + index += 1; + const [low, high] = typicalLength[stage]!; + const take = Math.min(remaining, Math.max(1, Math.round(between(random, low, high)))); + segments.push({ stageId: stage, halfMinutes: take }); + remaining -= take; + } + return segments; +} diff --git a/app/health/health-glance.ts b/app/health/health-glance.ts new file mode 100644 index 00000000..7b690331 --- /dev/null +++ b/app/health/health-glance.ts @@ -0,0 +1,528 @@ +/** + * HEALTH, the glasses surface - all of its DRAWING, and none of its plumbing. + * + * ## Why this is a separate file from `apps/health/health-app.ts` + * + * The app file owns the things only a running app can do: reading the store, + * the refresh timer, the input cursor, the window lifecycle. All of that needs + * NativeScript. The drawing needs nothing but a `GrayImage` and two fonts. + * + * Splitting them the way `health-store.ts` is split from `health-store-files.ts` + * buys the same thing it bought there: this file runs under plain node. That is + * what lets `tools/health-preview.cjs` render every one of these pages to a PNG + * with no emulator, no AVD and no device - the previews come out of the REAL + * paint code, so they cannot drift from what the glasses show the way a + * separate mockup can. The first pass verified its layout by booting a full + * Android emulator; this file is the reason that is no longer necessary. + * + * So the rule for this file: fonts and data arrive as arguments, nothing is + * imported from `native/` or `@nativescript/core`, and nothing reaches for a + * clock except through `data.nowMs`. + */ + +import { GrayImage, type UiFont } from "../graphics/image"; +import { lineStep } from "../ui/metrics"; +import { GESTURE_SCROLL } from "../ui/gestures"; +import { + drawSleepLanes, + drawMetricChart, + drawTextRight, + hypnogramCaptionShort, + INK, + rangeAverageText, +} from "./health-chart"; +import { + formatDuration, + shortDate, + stageSeconds, + type DailySummary, + type MetricSummary, +} from "./health-derive"; +import { + SAMPLE_METRIC_LABELS, + SAMPLE_METRIC_SHORT_LABELS, + SAMPLE_METRIC_UNITS, + type RollupPoint, + type SampleMetric, +} from "./health-types"; +import { stageLabel, type SleepStageName } from "./sleep-stages"; + +const MARGIN = 10; +const GUTTER = 14; +/** Below this the two columns stack instead. */ +const TWO_COLUMN_MIN_WIDTH = 380; + +export type GlanceFonts = { small: UiFont; large: UiFont }; + +/** + * One page of the glasses surface. + * + * ⚠ THE DRILL-DOWN IS A SCROLL CAROUSEL, AND THAT IS AN INTERPRETATION. + * Chris, 2026-09-10: "Scrolling to a parameter on the glasses overview should + * open that parameter's today/by-hour detail view... whichever line the user + * has scrolled to." Read literally, the act of scrolling to a parameter is what + * opens it - so scrolling walks a cursor through these pages and the page you + * land on IS the detail view, rather than scrolling moving a highlight that a + * second click then opens. + * + * Two things recommend the literal reading beyond its being literal. It costs + * one gesture instead of two, which matches the direction of every other note + * in that review (less on the glasses, not more). And it needs no back gesture: + * the shell already takes double-click for "back out to home" + * (`YieldAtRootLayer`), so a drill-down that needed its own back would have had + * to invent one out of the ring's three remaining gestures. Scrolling up to + * leave a page you scrolled down into needs nothing. + * + * Click is wired to advance as well, so a user who only ever clicks still gets + * round. Recorded as a call, not a spec. + */ +export type GlancePage = + | { kind: "overview" } + | { kind: "metric"; metric: SampleMetric } + | { kind: "sleep" }; + +/** + * The cursor's order. Overview first, then the five measured parameters in the + * order the overview lists them, then sleep - so scrolling down walks the + * summary top to bottom and falls off the end into last night, which is where + * the overview's right-hand column already pointed. + */ +export const GLANCE_PAGES: readonly GlancePage[] = [ + { kind: "overview" }, + { kind: "metric", metric: "heartRate" }, + { kind: "metric", metric: "spo2" }, + { kind: "metric", metric: "hrv" }, + { kind: "metric", metric: "steps" }, + { kind: "metric", metric: "calories" }, + { kind: "sleep" }, +]; + +export type GlanceData = { + summary: DailySummary | null; + /** Today's by-hour series, per metric. Only the drill-down pages use it. */ + hourly: Partial>; + /** Last night as a run of stage blocks, for the sleep detail lanes. */ + stageBands: readonly { stage: SleepStageName | null; seconds: number }[]; + /** Wall clock, passed in rather than read, so a preview can pin the date. */ + nowMs: number; + fixture: boolean; +}; + +export type GlanceSize = { width: number; height: number }; + +/** Paint whichever page the cursor is on. */ +export function drawGlancePage( + image: GrayImage, + size: GlanceSize, + fonts: GlanceFonts, + page: GlancePage, + data: GlanceData, +): void { + switch (page.kind) { + case "overview": + drawOverview(image, size, fonts, data); + break; + case "metric": + drawMetricDetail(image, size, fonts, page.metric, data); + break; + case "sleep": + drawSleepDetail(image, size, fonts, data); + break; + } + if (data.fixture) drawSampleDataModal(image, size, fonts); +} + +/** Keep example measurements unmistakable on every page until live data lands. */ +function drawSampleDataModal(image: GrayImage, size: GlanceSize, fonts: GlanceFonts): void { + const title = "Sample data"; + const lines = ["These are example measurements.", "No ring measurements saved yet."]; + const { small, large } = fonts; + const width = Math.min(size.width - 20, + Math.max(large.measureText(title), ...lines.map((line) => small.measureText(line))) + 40); + const height = large.lineHeight + 2 * lineStep(small) + 40; + const x = Math.round((size.width - width) / 2); + const y = Math.round((size.height - height) / 2); + // Bake before masking so deferred chart labels cannot appear above the box. + image.bakeDeferredDrawsInPlace(); + for (let i = 0; i < image.pixels.length; i++) image.pixels[i] = Math.round(image.pixels[i]! * 0.18); + image.fillRoundedRect(x, y, width, height, INK.background, 8); + image.drawRoundedRect(x, y, width, height, INK.title, 8); + image.drawText(large, Math.round((size.width - large.measureText(title)) / 2), y + 14, title, INK.title); + lines.forEach((line, index) => { + image.drawText(small, Math.round((size.width - small.measureText(line)) / 2), + y + 24 + large.lineHeight + index * lineStep(small), line, INK.title); + }); +} + +// =========================================================================== +// Header and footer, shared by every page + +function drawHeader( + image: GrayImage, + size: GlanceSize, + fonts: GlanceFonts, + title: string, + right: string, +): number { + const { small } = fonts; + image.drawText(small, MARGIN, MARGIN, title, INK.title); + drawTextRight(image, small, size.width - MARGIN, MARGIN, right, INK.label); + const bottom = MARGIN + small.lineHeight + 3; + image.drawLine(MARGIN, bottom, size.width - MARGIN, bottom, INK.axis); + return bottom; +} + +/** + * The scroll hint. + * + * The hint is not decoration: the drill-down has no on-screen affordance + * otherwise - a page that opens on a scroll looks identical to a page that does + * nothing until you try it. + */ +function drawFooter( + image: GrayImage, + size: GlanceSize, + fonts: GlanceFonts, + hint: string, +): void { + const { small } = fonts; + const y = size.height - small.lineHeight - 2; + image.drawText(small, MARGIN, y, hint, INK.faint); +} + +// =========================================================================== +// 1. The overview - a summary, and nothing but + +/** + * ⚠ CUT DOWN 2026-09-10 on Chris's review. What left this page and why: + * + * - The heart-rate trace chart. It was filling the left column's spare + * height and it is the single biggest thing on the page; "I think it just + * needs to be a summary". + * - The hypnogram strip under last night's stats, for the same reason. + * - The min/avg/max triple, replaced by range-and-average + * (`rangeAverageText`), which drops the "min / avg / max" legend line that + * existed only to decode the triple. + * + * What arrived: an HRV line, revising the first pass's spec. + * + * The net is that this page is now TEXT ONLY - no charts, no graphics. The + * charts did not die, they moved: the trace is the heart-rate drill-down page + * one scroll away, and the hypnogram became the sleep detail's four lanes. + * That is the actual shape of the revision - the glance got smaller because the + * drill-down gave its contents somewhere better to live. + */ +function drawOverview( + image: GrayImage, + size: GlanceSize, + fonts: GlanceFonts, + data: GlanceData, +): void { + const { small, large } = fonts; + const step = lineStep(small); + const headerBottom = drawHeader(image, size, fonts, "HEALTH", shortDate(data.nowMs)); + const summary = data.summary; + + if (!summary) { + image.drawText(small, MARGIN, headerBottom + step, "Waiting for ring data...", INK.dim); + drawFooter(image, size, fonts, ""); + return; + } + + const twoColumn = size.width >= TWO_COLUMN_MIN_WIDTH; + const columnWidth = twoColumn + ? Math.floor((size.width - MARGIN * 2 - GUTTER) / 2) + : size.width - MARGIN * 2; + const rightX = twoColumn ? MARGIN + columnWidth + GUTTER : MARGIN; + const top = headerBottom + 6; + + const todayBottom = drawTodayColumn(image, summary, { + x: MARGIN, + y: top, + width: columnWidth, + fonts, + step, + }); + const nightTop = twoColumn ? top : todayBottom + 8; + const nightBottom = drawNightColumn(image, summary, { + x: rightX, + y: nightTop, + width: columnWidth, + fonts, + step, + }); + + if (twoColumn) { + // The divider stops at the taller column rather than running to the footer. + // Now that the page is text-only the columns fill about a third of the + // height, and a rule continuing 300px past the last row reads as a drawing + // artefact instead of as structure. It also matters more than it looks: on + // the glasses an unlit pixel is TRANSPARENT, so every line drawn past the + // content is one more thing between the wearer and the world. + const divider = MARGIN + columnWidth + Math.floor(GUTTER / 2); + image.drawLine(divider, top, divider, Math.max(todayBottom, nightBottom), INK.faint); + } + + void large; + drawFooter(image, size, fonts, `${GESTURE_SCROLL} detail`); +} + +type ColumnLayout = { + x: number; + y: number; + width: number; + fonts: GlanceFonts; + step: number; +}; + +function drawTodayColumn(image: GrayImage, summary: DailySummary, layout: ColumnLayout): number { + const { x, width, fonts, step } = layout; + const { small, large } = fonts; + let y = layout.y; + + image.drawText(small, x, y, "TODAY", INK.label); + y += step; + + // Steps get the large font: it is the number a glance is most often for. + const stepsText = summary.steps > 0 ? summary.steps.toLocaleString() : "--"; + image.drawText(large, x, y, stepsText, INK.title); + const stepsWidth = large.measureText(stepsText); + image.drawText( + small, + x + stepsWidth + 6, + y + large.lineHeight - small.lineHeight - 1, + "steps", + INK.label, + ); + y += large.lineHeight + 4; + + const caloriesText = summary.calories > 0 ? `${summary.calories.toLocaleString()} kcal` : "-- kcal"; + image.drawText(small, x, y, caloriesText, INK.bar); + y += step + 4; + + // Range and average, one line each, no legend line underneath. + const rows: [string, MetricSummary, string][] = [ + ["HR", summary.heartRate, SAMPLE_METRIC_UNITS.heartRate], + ["SpO2", summary.spo2, SAMPLE_METRIC_UNITS.spo2], + ["HRV", summary.hrv, SAMPLE_METRIC_UNITS.hrv], + ]; + for (const [label, metricSummary, unit] of rows) { + image.drawText(small, x, y, label, INK.label); + drawTextRight(image, small, x + width, y, rangeAverageText(metricSummary, unit), INK.line); + y += step; + } + return y; +} + +function drawNightColumn(image: GrayImage, summary: DailySummary, layout: ColumnLayout): number { + const { x, width, fonts, step } = layout; + const { small, large } = fonts; + let y = layout.y; + + image.drawText(small, x, y, "LAST NIGHT", INK.label); + y += step; + + const sleep = summary.sleep; + if (!sleep) { + image.drawText(small, x, y, "No sleep record", INK.dim); + return y + step; + } + + image.drawText(large, x, y, formatDuration(sleep.totalSec), INK.title); + y += large.lineHeight + 4; + + image.drawText(small, x, y, "Efficiency", INK.label); + drawTextRight(image, small, x + width, y, `${Math.round(sleep.efficiencyPercent)}%`, INK.line); + y += step + 3; + + // The three stage shares Chris named, as percentages of time asleep. These + // come from the record's own named totals, so they are unaffected by the + // unconfirmed stage-id mapping the sleep detail's lanes depend on. + const rows: [string, number][] = [ + ["REM", sleep.remPercent], + ["Deep", sleep.deepPercent], + ["Light", sleep.lightPercent], + ]; + for (const [label, percent] of rows) { + image.drawText(small, x, y, label, INK.label); + drawTextRight(image, small, x + width, y, `${Math.round(percent)}%`, INK.line); + y += step; + } + return y; +} + +// =========================================================================== +// 4. The drill-down: one parameter, today, by hour + +/** + * What the phone's Day view shows for this metric, on the glasses. + * + * The headline repeats the overview's range-and-average line at full size, so + * the page answers the glance's question before the chart is read at all; the + * chart then says WHEN. That ordering is the point of the drill-down - "74 avg" + * and "and it was 130 at five o'clock" are different facts. + */ +function drawMetricDetail( + image: GrayImage, + size: GlanceSize, + fonts: GlanceFonts, + metric: SampleMetric, + data: GlanceData, +): void { + const { small, large } = fonts; + const step = lineStep(small); + const headerBottom = drawHeader( + image, + size, + fonts, + SAMPLE_METRIC_LABELS[metric].toUpperCase(), + "today, by hour", + ); + let y = headerBottom + 6; + + const summary = summaryFor(metric, data.summary); + const unit = SAMPLE_METRIC_UNITS[metric]; + + if (isCumulativeMetric(metric)) { + // Steps and calories are totals, not measurements with a spread, so the + // headline is the day's total rather than a range. + const total = metric === "steps" ? data.summary?.steps ?? 0 : data.summary?.calories ?? 0; + const text = total > 0 ? total.toLocaleString() : "--"; + image.drawText(large, MARGIN, y, text, INK.title); + const width = large.measureText(text); + if (unit) { + image.drawText( + small, + MARGIN + width + 6, + y + large.lineHeight - small.lineHeight - 1, + unit, + INK.label, + ); + } + y += large.lineHeight + 6; + } else { + image.drawText(small, MARGIN, y, rangeAverageText(summary, unit), INK.line); + y += step + 4; + } + + const points = data.hourly[metric] ?? []; + const footerHeight = small.lineHeight + 8; + const chartHeight = size.height - y - MARGIN - footerHeight; + if (chartHeight >= 40) { + drawMetricChart( + image, + { x: MARGIN, y, width: size.width - MARGIN * 2, height: chartHeight }, + { + metric, + points, + font: small, + // Just format the hour - `drawMetricChart` already thins labels to + // whatever the column width fits. Thinning here as well multiplies the + // two and leaves a single label at midnight. + xLabel: (point) => `${new Date(point.startMs).getHours()}`, + }, + ); + } + + drawFooter(image, size, fonts, `${GESTURE_SCROLL} ${pageHint(metric)}`); +} + +function summaryFor(metric: SampleMetric, summary: DailySummary | null): MetricSummary { + const empty: MetricSummary = { min: 0, max: 0, avg: 0, hasData: false }; + if (!summary) return empty; + if (metric === "heartRate") return summary.heartRate; + if (metric === "spo2") return summary.spo2; + if (metric === "hrv") return summary.hrv; + return empty; +} + +function isCumulativeMetric(metric: SampleMetric): boolean { + return metric === "steps" || metric === "calories"; +} + +/** "SpO2 · HRV" - what scrolling either way from here reaches. */ +function pageHint(metric: SampleMetric): string { + const index = GLANCE_PAGES.findIndex( + (page) => page.kind === "metric" && page.metric === metric, + ); + const previous = GLANCE_PAGES[index - 1]; + const next = GLANCE_PAGES[index + 1]; + return [pageName(previous), pageName(next)].filter(Boolean).join(" · "); +} + +function pageName(page: GlancePage | undefined): string { + if (!page) return ""; + if (page.kind === "overview") return "Summary"; + if (page.kind === "sleep") return "Sleep"; + return SAMPLE_METRIC_SHORT_LABELS[page.metric]; +} + +// =========================================================================== +// 4b. The drill-down's special case: one night, four lanes + +/** + * Sleep's own detail page: the four categories arranged vertically, top to + * bottom as Awake, Light, REM, Deep. + * + * The ordering is Chris's and is deliberately not the week chart's - see + * `drawSleepLanes`, which owns the drawing and carries the reasoning and the + * flagged proportions call. + * + * The unconfirmed-mapping caption rides along because this page IS the + * hypnogram: lanes are the only thing on either surface that depends on the raw + * stage ids, so it is the only place that has to hedge. The overview's + * percentages come from named totals and say so by not carrying this caption. + */ +function drawSleepDetail( + image: GrayImage, + size: GlanceSize, + fonts: GlanceFonts, + data: GlanceData, +): void { + const { small, large } = fonts; + const step = lineStep(small); + const sleep = data.summary?.sleep ?? null; + const headerBottom = drawHeader(image, size, fonts, "SLEEP", "last night"); + let y = headerBottom + 6; + + if (!sleep) { + image.drawText(small, MARGIN, y, "No sleep record", INK.dim); + drawFooter(image, size, fonts, `${GESTURE_SCROLL} Calories · Summary`); + return; + } + + // Total and efficiency on one line, so the lanes get the height. + const totalText = formatDuration(sleep.totalSec); + image.drawText(large, MARGIN, y, totalText, INK.title); + drawTextRight( + image, + small, + size.width - MARGIN, + y + large.lineHeight - small.lineHeight - 1, + `${Math.round(sleep.efficiencyPercent)}% efficiency`, + INK.label, + ); + y += large.lineHeight + 6; + + const footerHeight = small.lineHeight + 8; + const captionHeight = step; + const laneHeight = size.height - y - MARGIN - footerHeight - captionHeight; + if (laneHeight >= 40) { + drawSleepLanes( + image, + { x: MARGIN, y, width: size.width - MARGIN * 2, height: laneHeight }, + { + bands: data.stageBands, + font: small, + laneText: (stage) => ({ + label: stageLabel(stage), + value: formatDuration(stageSeconds(stage, sleep)), + }), + }, + ); + y += laneHeight; + } + + image.drawText(small, MARGIN, y, hypnogramCaptionShort(), INK.faint); + drawFooter(image, size, fonts, `${GESTURE_SCROLL} Calories · Summary`); +} diff --git a/app/health/health-ingest.ts b/app/health/health-ingest.ts new file mode 100644 index 00000000..70afcfc0 --- /dev/null +++ b/app/health/health-ingest.ts @@ -0,0 +1,311 @@ +/** + * Wire records -> stored samples. The one place that knows what the ring's + * decoded records mean in wall-clock terms. + * + * ## This is written but NOT wired up, on purpose + * + * The live BLE path lives on the `ring-health-protocol` branch, which this one + * deliberately does not touch. What is here is the whole conversion - the part + * with the judgement calls in it - written against a structural description of + * `RingProtocol.kt`'s record types rather than an import of them, so that + * branch and this one can be joined later without either having been built + * around the other. + * + * ## WHERE THE LIVE WIRING GOES - the follow-up, in full + * + * ⚠ HISTORICAL. This section is the plan, and it has since been built: + * `health-live.ts` is the caller. One detail of it is now WRONG - the live path + * must NOT use `getRingHealthRecords()`, which is a pure copy and left the + * Java-side buffer growing forever. It uses `takeRingHealthBatch()` and hands + * the records back with `clearRingHealthRecordsBelow()` once the store write + * has succeeded. Kept below for the reasoning, not as instructions. + * + * `FaceclawBleCommunicator` already accumulates decoded records into a capped + * in-memory list with a `getRingHealthRecords()` getter (implement-return, + * section 2). The bridge already exposes the native object to TypeScript: + * `FaceclawCommunicatorBridge.getNativeCommunicator()`. So the follow-up is: + * + * 1. In `dashboard-controller.ts`, after `connect()` succeeds, poll + * `communicator.getNativeCommunicator().getRingHealthRecords()` on the + * same 30-minute cadence the Java side already throttles health pulls to. + * 2. Map each Java record onto the `Wire*` shapes below - a field-for-field + * copy; the names were chosen to match. + * 3. Hand the result to `convertRecords()` and pass its `samples`/`sleep` + * straight to `healthStore().ingestSamples()` / `.ingestSleep()`. + * + * Doing it as a poll rather than a callback is what keeps it a small change: + * adding a method to `FaceclawBleCommunicatorListener` forces an edit on every + * implementer, which is exactly the reasoning that put the records in a getter + * in the first place. + * + * A note for whoever does it: ingest is idempotent (`HealthStore` dedupes on + * metric + bucket start), so re-reading the same capped list every poll is + * correct and costs one no-op per record. Do NOT drain the list on read - it + * is the only copy until this store has written it. + * + * No NativeScript imports here, so it runs under plain node in `tests/`. + */ + +import { + HOUR_MS, + TEN_MINUTES_MS, + type HealthSample, + type SleepSession, + type SleepSegment, + startOfLocalDay, +} from "./health-types"; + +/** `RingProtocol.HourlyRecord`, for heart rate (`01:01`), SpO2 (`02:01`), HRV (`04:01`). */ +export type WireHourlyRecord = { + kind: "hourly"; + metric: "heartRate" | "spo2" | "hrv"; + /** + * Absolute local ms the page's group index 0 refers to, from the record's + * own six-byte ANCHOR field, or null on a backlog page that carried six + * zero bytes instead. + */ + anchorMs: number | null; + groups: readonly { hourIndex: number; avg: number; max: number; min: number }[]; +}; + +/** `RingProtocol.StepsRecord` (`05:01`). */ +export type WireStepsRecord = { + kind: "steps"; + /** The day anchor. Steps pages always carried one in the capture. */ + anchorMs: number | null; + /** Raw buckets. `index` is the ring's own, whose meaning is NOT known. */ + buckets: readonly { index: number; steps: number; activeCalories: number; totalCalories: number }[]; +}; + +/** `RingProtocol.SleepRecord` (`06:01`). */ +export type WireSleepRecord = { + kind: "sleep"; + /** + * The ring's own `start_ts`/`end_ts`, in seconds. + * + * These were documented here as "ring-relative seconds - NOT Unix time", + * because nothing in the offline capture proved otherwise. The first real + * record off the hardware (2026-09-12) falsified that: `start_ts` decodes to + * a plain Unix timestamp kept on the RING'S clock, which runs ahead of real + * time. `clockCorrectionMs` is how a caller says by how much. + * + * Left as raw seconds here rather than corrected upstream so a caller with + * no correction to offer (an offline capture, a fixture) still gets the old, + * honestly-unresolved behaviour instead of a confidently wrong date. + */ + startTs: number; + endTs: number; + totalSec: number; + wakeSec: number; + remSec: number; + lightSec: number; + deepSec: number; + segments: readonly SleepSegment[]; + /** Wall-clock ms the record was received; the only real time in it. */ + receivedAtMs: number; + /** + * How far AHEAD of real wall-clock time `startTs`/`endTs` run, in ms, or + * omitted when the caller cannot say. Supplying it is what promotes the + * session from `timeResolved: false` to a real placement - see + * `convertSleep`. The value itself is the producer's problem, not this + * module's: see `sleepClockCorrectionMs` in `health-live.ts`. + */ + clockCorrectionMs?: number; +}; + +export type WireRecord = WireHourlyRecord | WireStepsRecord | WireSleepRecord; + +export type ConversionResult = { + samples: HealthSample[]; + sleep: SleepSession[]; + /** Every record or group deliberately not stored, with the reason. */ + skipped: { what: string; why: string }[]; +}; + +export function convertRecords(records: readonly WireRecord[]): ConversionResult { + const result: ConversionResult = { samples: [], sleep: [], skipped: [] }; + for (const record of records) { + if (record.kind === "hourly") convertHourly(record, result); + else if (record.kind === "steps") convertSteps(record, result); + else convertSleep(record, result); + } + return result; +} + +/** + * Hourly pages. An ANCHORED page dates itself exactly: group `i` is + * `anchor + i hours`, which the decode verified against every group that had a + * row to check against. + * + * An UNANCHORED (backlog) page is dropped rather than placed. The decode did + * solve where one such page landed, but explicitly could not derive the rule + * that produced it and warned that a future page anchored elsewhere would + * break it. `RingProtocol.kt` already made the matching call - it hands + * backlog groups out with `UNKNOWN_TIME` rather than an invented time - and a + * health chart is exactly the wrong place to be the first component that + * guesses. Dropping loses a page; guessing corrupts the history silently. + */ +function convertHourly(record: WireHourlyRecord, result: ConversionResult): void { + if (record.anchorMs === null) { + result.skipped.push({ + what: `${record.metric} page, ${record.groups.length} groups`, + why: "backlog page with no anchor - no verified rule for dating it", + }); + return; + } + for (const group of record.groups) { + const startMs = record.anchorMs + group.hourIndex * HOUR_MS; + result.samples.push({ + metric: record.metric, + startMs, + spanMs: HOUR_MS, + min: group.min, + max: group.max, + avg: group.avg, + total: group.avg, + }); + } +} + +/** + * Steps and calories, at TEN-MINUTE resolution. + * + * ## The index is cracked (2026-09-12) + * + * This used to emit one day-span sample holding the day's total, because the + * bucket index was only trusted as an identity, not as a time. It now resolves: + * **bucket `i` starts at `anchor + i * 10 minutes`**, with the anchor read + * offset-corrected like every other record type. + * + * Confirmed twice. The decisive check: a live ledger held 25 contiguous buckets + * (1-25) under a corrected anchor of 20:00, while the file's mtime was 00:18 + * local - and `20:00 + 25 * 10min` is 00:10-00:20, which is the window that was + * actually being filled. The older "index runs 0-34 then jumps to 130-132" + * observation came from an offline capture spanning more than one ring-day; + * indices are per-record and contiguous within one. + * + * ## What this changes downstream + * + * The day total is no longer readable off any field of a day's rollup - it is + * `sum`, and only `sum`, because `count` is now ~144 rather than 1. Checked on + * 2026-09-12: every steps/calories reader already uses the summing path + * (`dailySummary` -> `sumOf` -> `sample.total`; `rollupSeries` -> `rollupOf` -> + * `sum`; the phone view model's steps branch reads `point.sum`), so nothing had + * to change for this. Do not add a reader that takes `max` or `avg` for a step + * total. + * + * A ring-day starts at 20:00 local (the ring's clock runs 4h fast, so its + * midnight is our 20:00), which means one record's buckets straddle two + * calendar days. That is correct and is the reason the day figure moves when + * this lands: the evening buckets stop being filed under tomorrow. + */ +function convertSteps(record: WireStepsRecord, result: ConversionResult): void { + if (record.anchorMs === null) { + result.skipped.push({ + what: `steps page, ${record.buckets.length} buckets`, + why: "no anchor - cannot date the buckets", + }); + return; + } + const anchorMs = record.anchorMs; + for (const bucket of record.buckets) { + const startMs = anchorMs + bucket.index * TEN_MINUTES_MS; + result.samples.push({ + metric: "steps", + startMs, + spanMs: TEN_MINUTES_MS, + min: bucket.steps, + max: bucket.steps, + avg: bucket.steps, + total: bucket.steps, + }); + result.samples.push({ + metric: "calories", + startMs, + spanMs: TEN_MINUTES_MS, + min: bucket.totalCalories, + max: bucket.totalCalories, + avg: bucket.totalCalories, + total: bucket.totalCalories, + }); + } +} + +/** + * Sleep sessions. + * + * The durations are exact and need no anchoring - they come from named byte + * offsets and the decode reproduced a whole exported row from them. The + * SESSION TIME is the problem: `start_ts`/`end_ts` are ring-relative seconds, + * nothing in the record carries an absolute date, and the two unidentified + * fields that might have carried one were not cracked. Even's own app gets + * this wrong - one exported row is stamped 1979. + * + * RESOLVED, 2026-09-12, by the first real record off the hardware rather than + * by cracking `pay[3:9]`: `start_ts` is already a Unix timestamp, just kept on + * the ring's own clock. A caller that knows how far that clock runs ahead + * passes `clockCorrectionMs` and gets a genuinely placed session. + * + * ⚠ THE OLD FLAGGED GUESS SURVIVES for callers that do NOT pass it (offline + * captures, fixtures): the session is attributed to the local day it was + * RECEIVED on and `timeResolved` is false to say so. That guess is made rather + * than avoided because "last night's sleep" is half of what the glasses glance + * is for, and a record with no day at all cannot appear there. It is right + * whenever the ring is synced the same day it is worn and wrong for a backlog + * session pulled days later - which is why the UI never prints a date for an + * unresolved session, only "last night", and shows the unresolved marker. + */ +function convertSleep(record: WireSleepRecord, result: ConversionResult): void { + const durationSec = Math.max(0, record.endTs - record.startTs); + const common = { + totalSec: record.totalSec, + wakeSec: record.wakeSec, + remSec: record.remSec, + lightSec: record.lightSec, + deepSec: record.deepSec, + segments: record.segments, + }; + + if (typeof record.clockCorrectionMs === "number") { + const startMs = record.startTs * 1000 - record.clockCorrectionMs; + const endMs = (record.startTs + durationSec) * 1000 - record.clockCorrectionMs; + result.sleep.push({ + // The WAKE-UP day, which is what `dailySummary` looks a night up by, and + // what the old receivedAtMs guess was approximating. Taken from the end + // of the session so a night that starts before midnight still belongs to + // the morning it ends on. + dayStartMs: startOfLocalDay(endMs), + startMs, + endMs, + ...common, + timeResolved: true, + }); + return; + } + + result.sleep.push({ + dayStartMs: startOfLocalDay(record.receivedAtMs), + // Raw seconds are kept as-is so the pair still describes the night's + // length and ordering; `timeResolved` is what says not to read them as + // wall-clock time. + startMs: record.startTs * 1000, + endMs: (record.startTs + durationSec) * 1000, + ...common, + timeResolved: false, + }); +} + +/** + * The consistency check the decode found holds on every real record: the + * segment run must account for exactly the time in bed. Worth running on + * ingest - a record that fails it is a decode fault, not a strange night. + */ +export function sleepIdentityHolds(record: { + totalSec: number; + wakeSec: number; + segments: readonly SleepSegment[]; +}): boolean { + let half = 0; + for (const segment of record.segments) half += segment.halfMinutes; + return half * 30 === record.totalSec + record.wakeSec; +} diff --git a/app/health/health-live.ts b/app/health/health-live.ts new file mode 100644 index 00000000..7dc86c04 --- /dev/null +++ b/app/health/health-live.ts @@ -0,0 +1,639 @@ +/** + * Live ring → store. The producer side of `health-ingest.ts`. + * + * `health-ingest.ts` was built with a complete wire→domain conversion and no + * caller; this is the caller. It reads whatever `FaceclawBleCommunicator` has + * decoded off the ring this session, marshals the Java records into the + * `WireRecord` shapes that module already expects, and writes the result + * through the store's own deduping ingest. + * + * Three things worth knowing: + * + * 1. **It pulls, it does not subscribe, and it CONSUMES.** There is no push + * event for health records, so both surfaces call this when they open and on + * their existing refresh tick. `takeRingHealthBatch()` hands over what the + * communicator is holding together with a watermark, and once the store + * write has succeeded `clearRingHealthRecordsBelow()` hands that much back + * as consumed. Cut and paste, not copy paste. + * + * It used to be a pure copy, and nothing ever cleared the Java-side list, so + * every 60s tick re-processed the whole session's history. Measured + * 2026-09-12: `samples-2026-09.jsonl` grew 22,505 -> 28,552 lines in eight + * hours, the buffer climbing 12 -> 24 records and samples-written-per-cycle + * 8 -> 14. The store's dedupe kept the DATA right the whole time; it was the + * work and the file that grew without bound. + * + * 2. **Fixtures are purged, not just unlabelled, before the first real write.** + * `clearFixtureMarker()` only drops the badge; the 45 days of generated + * samples would stay in the store and become indistinguishable from real + * data the moment the badge went away. That is precisely the artefact + * `health-seed.ts`' own header warns about, so the first genuine record + * wipes the store files outright. + * + * 3. **Records the decode could not date are dropped, not placed.** + * `RingProtocol` hands out `UNKNOWN_TIME` (-1) for an unanchored backlog + * page rather than inventing a time; that maps to `anchorMs: null` here and + * `convertRecords` skips it with a reason. Do not "fix" this by substituting + * now() — a health chart is the wrong place to guess a timestamp. + */ + +import { + convertRecords, + type WireHourlyRecord, + type WireRecord, + type WireSleepRecord, + type WireStepsRecord, +} from "./health-ingest"; +import { markLiveData, purgeFixtureData } from "./health-seed"; +import { checkedFileOperation, healthStore } from "./health-store-files"; +import { startOfLocalDay, type SleepSegment } from "./health-types"; +import { File, knownFolders } from "@nativescript/core"; + +/** `RingProtocol.UNKNOWN_TIME` — the decoder's "I will not guess" sentinel. */ +const UNKNOWN_TIME = -1; + +/** `RingProtocol.CMD_HI_*`. */ +const CMD_HEART_RATE = 0x01; +const CMD_SPO2 = 0x02; +const CMD_HRV = 0x04; +const CMD_STEPS = 0x05; +const CMD_SLEEP = 0x06; + +/** `SleepRecord.recordState`: 2 is the empty end-of-list marker, not a night. */ +const SLEEP_STATE_EMPTY = 2; + +const HOURLY_METRIC: { [cmdHi: number]: WireHourlyRecord["metric"] } = { + [CMD_HEART_RATE]: "heartRate", + [CMD_SPO2]: "spo2", + [CMD_HRV]: "hrv", +}; + +function activeCommunicator(): any { + try { + return (com as any).faceclaw.app.FaceclawBleCommunicator.getActive() ?? null; + } catch { + return null; + } +} + +/** + * Legacy compensation for the incorrect extra timezone shift sent by the + * handshake. This is not a ring protocol requirement. Fresh HR timestamps on + * the PDT test ring run seven hours ahead, but older values and daily anchors + * do not share that shift. Keep this paired with the existing handshake until + * a controlled UTC migration; do not apply it retrospectively to raw history. + * See notes/ring-health-live-validation.md. + */ +function ringClockOffsetMs(atMs: number): number { + return new Date(atMs).getTimezoneOffset() * 60 * 1000; +} + +/** + * Inherited sleep-specific heuristic, still unvalidated on this ring (no sleep + * DATA page received yet). Firmware describes UTC timestamps, not a double + * timezone offset. Remove alongside the controlled clock migration, then + * validate against a recorded night; it is not evidence of correct placement. + */ +function sleepClockOffsetMs(atMs: number): number { + return 2 * ringClockOffsetMs(atMs); +} + +function anchorToMs(anchorUnixSeconds: number, applyClockOffset: boolean): number | null { + if (anchorUnixSeconds === UNKNOWN_TIME) return null; + const ms = anchorUnixSeconds * 1000; + return applyClockOffset ? ms - ringClockOffsetMs(ms) : ms; +} + +/** + * Per-day step-bucket ledger. + * + * **Why this has to exist.** The ring does not resend the whole day: a pull + * delivers only the buckets new since the last successful one, the same + * watermark model every other record type uses. Measured 2026-09-11: + * 25 buckets / 222 steps, then 3 / 0, then 2 / 0, then 2 / 70. A cumulative + * day total cannot go 222 → 0 → 70. + * + * `convertSteps()` sums the buckets it is handed and emits that as the day's + * total, which was right for the offline captures it was written against — + * there, one sync carried everything. Live, it means each pull overwrites the + * day with just that pull's increment, so the step count reads as "since the + * last pull" and lurches downward. So this keeps the day's buckets and hands + * `convertSteps()` the accumulated set, leaving that function pure. + * + * **Merge is max-by-index, not addition and not last-write-wins.** A bucket is + * a time window's own total, so a window redelivered later carries a larger + * value, not an increment to add — addition would double-count every open + * window. Taking the max rather than the last value makes the merge + * ORDER-INDEPENDENT, which matters because a single sync pass merges several + * records that overlap: measured 2026-09-12, four steps records in one pass + * agreed on every bucket's step count but disagreed on its calorie fields, so + * last-write-wins made the day's calorie total ping-pong 643 ↔ 671 forever, + * appending two lines to the sample shard every cycle. Max is consistent with + * the documented model (a window's total only grows as it fills) and settles. + * + * **The ledger holds MANY days, not one.** It used to hold exactly one, and + * kept it only while the incoming day matched — so the moment a record from + * another ring-day arrived, the whole accumulated day was discarded and + * rebuilt from that one pull. With `syncLiveRecords()` re-processing the + * communicator's entire record history every 60s, that produced a repeating + * cycle of partial sums, each written to the store as a genuine day total + * (measured: a 12-state cycle, repeated 132 times, 22k lines in a day). + * Holding every day makes the replay idempotent instead of destructive — and + * no theory about WHY records replay is needed for that to hold. + * + * The day key is `startOfLocalDay(corrected anchor)`, which is the ring's own + * day start, not calendar midnight — the ring's day begins at 20:00 local + * because its clock runs 4h fast. That is fine: the key is an identity, and + * the per-bucket timestamps carry the real wall-clock placement. + */ +type StepDayBuckets = { [index: string]: { steps: number; active: number; total: number } }; + +type StepBucketLedger = { + /** `dayStartMs` (as a string key) -> that day's buckets. */ + days: { [dayStartMs: string]: StepDayBuckets }; +}; + +/** The pre-2026-09-12 single-day shape, migrated on read rather than dropped. */ +type LegacyStepBucketLedger = { dayStartMs: number; buckets: StepDayBuckets }; + +/** How many ring-days to keep. Enough for a weekly chart, bounded on disk. */ +const LEDGER_DAYS_KEPT = 7; + +function ledgerPath(): string { + return `${knownFolders.documents().getFolder("health").path}/steps-ledger.json`; +} + +function readLedger(): StepBucketLedger | null { + try { + if (!File.exists(ledgerPath())) return null; + const parsed = JSON.parse(File.fromPath(ledgerPath()).readTextSync()) as + | StepBucketLedger + | LegacyStepBucketLedger; + if (parsed && (parsed as StepBucketLedger).days) return parsed as StepBucketLedger; + // Migrate the single-day shape rather than discarding it: the file on the + // phone holds real step data the ring may not re-deliver. + // + // ⚠ RE-KEY IT. The legacy `dayStartMs` was `startOfLocalDay(RAW anchor)`, + // computed before the anchor was offset-corrected, so carrying it across + // verbatim files the day 4h too late — under a key the corrected code will + // never write to again. The accumulated buckets would sit there stranded + // while the same ring-day restarted empty beside them. Measured doing + // exactly that on 2026-09-12: a ledger with "2 days" that were one day. + const legacy = parsed as LegacyStepBucketLedger; + if (typeof legacy?.dayStartMs === "number" && legacy.buckets) { + const corrected = legacy.dayStartMs - ringClockOffsetMs(legacy.dayStartMs); + return { days: { [String(startOfLocalDay(corrected))]: legacy.buckets } }; + } + return null; + } catch { + return null; + } +} + +/** Keep the ledger bounded. Newest `LEDGER_DAYS_KEPT` days survive. */ +function pruneLedger(ledger: StepBucketLedger): void { + const keys = Object.keys(ledger.days).sort((a, b) => Number(b) - Number(a)); + for (const key of keys.slice(LEDGER_DAYS_KEPT)) delete ledger.days[key]; +} + +function writeLedger(ledger: StepBucketLedger): void { + try { + File.fromPath(ledgerPath()).writeTextSync(JSON.stringify(ledger)); + } catch (error) { + console.warn("health live: steps ledger write failed", error); + } +} + +/** Merge this pull's buckets into that ring-day's ledger and return its full set. */ +function accumulateStepBuckets( + dayStartMs: number, + delivered: readonly { index: number; steps: number; activeCalories: number; totalCalories: number }[], +): { index: number; steps: number; activeCalories: number; totalCalories: number }[] { + const ledger: StepBucketLedger = readLedger() ?? { days: {} }; + const dayKey = String(dayStartMs); + const day: StepDayBuckets = ledger.days[dayKey] ?? {}; + ledger.days[dayKey] = day; + for (const bucket of delivered) { + const existing = day[String(bucket.index)]; + // Max, not overwrite — see the type's header. Keeps the merge order-independent. + day[String(bucket.index)] = { + steps: Math.max(existing?.steps ?? 0, bucket.steps), + active: Math.max(existing?.active ?? 0, bucket.activeCalories), + total: Math.max(existing?.total ?? 0, bucket.totalCalories), + }; + } + pruneLedger(ledger); + writeLedger(ledger); + const merged = Object.keys(day).map((key) => ({ + index: Number(key), + steps: day[key]!.steps, + activeCalories: day[key]!.active, + totalCalories: day[key]!.total, + })); + const steps = merged.reduce((acc, b) => acc + b.steps, 0); + const calories = merged.reduce((acc, b) => acc + b.totalCalories, 0); + console.log( + `health live: steps ledger +${delivered.length} delivered -> ${merged.length} buckets held ` + + `for ring-day ${new Date(dayStartMs).toISOString()}, ${steps} steps / ${calories} cal, ` + + `${Object.keys(ledger.days).length} days in ledger`, + ); + return merged; +} + +function toWire(record: any): WireRecord | null { + const cmdHi = Number(record.cmdHi); + + const metric = HOURLY_METRIC[cmdHi]; + if (metric) { + const groups: { hourIndex: number; avg: number; max: number; min: number }[] = []; + const raw = record.groups; + for (let i = 0; i < raw.length; i++) { + const group = raw[i]; + groups.push({ + hourIndex: Number(group.hourIndex), + avg: Number(group.avg), + max: Number(group.max), + min: Number(group.min), + }); + } + return { kind: "hourly", metric, anchorMs: anchorToMs(Number(record.anchorUnixSeconds), true), groups }; + } + + if (cmdHi === CMD_STEPS) { + const buckets: { index: number; steps: number; activeCalories: number; totalCalories: number }[] = []; + const raw = record.buckets; + for (let i = 0; i < raw.length; i++) { + const bucket = raw[i]; + buckets.push({ + index: Number(bucket.index), + steps: Number(bucket.steps), + // UNVERIFIED MAPPING. The decode never resolved which of the record's + // two calorie-like fields is active vs total burn, which is why the + // Java side names them calorieLike2/calorieLike3 rather than committing. + // convertSteps() sums totalCalories, so if the daily calorie figure + // reads wrong against Even's own export, swap these two — that is the + // whole fix, and it is the only thing here resting on a guess. + activeCalories: Number(bucket.calorieLike2), + totalCalories: Number(bucket.calorieLike3), + }); + } + // Offset-corrected like every other record type, as of 2026-09-12. + // + // This used to pass `false`, and the reasoning was that flooring the raw + // anchor to the local day "absorbed" the 4h shift and landed on the right + // date, where subtracting would push the day boundary back to 20:00 the + // previous evening. That was solving the wrong problem. The anchor was + // being asked to carry the DATE LABEL for a single day-blob sample, so it + // had to be bent until the label came out right. + // + // With the bucket index cracked (bucket i starts at anchor + i*10min), the + // anchor no longer carries a date at all — it is the true start instant of + // bucket 0, and each bucket now dates itself. So the anchor must simply be + // correct, and correct means offset-corrected: measured 2026-09-12 00:36, + // the raw anchor read 00:00 today while the record's own 25 buckets place + // the series start at 20:00 the previous evening, which is exactly the 4h. + // + // The ring's day really does begin at 20:00 local, because its clock runs + // 4h fast and its day starts at ITS midnight. A ring-day therefore straddles + // two calendar days, and the buckets land on whichever real day they fall + // in — which is the point. + const anchorMs = anchorToMs(Number(record.anchorUnixSeconds), true); + if (anchorMs === null) return { kind: "steps", anchorMs: null, buckets }; + // Hand convertSteps() the whole day, not just this pull's increment. + const accumulated = accumulateStepBuckets(startOfLocalDay(anchorMs), buckets); + return { kind: "steps", anchorMs, buckets: accumulated }; + } + + if (cmdHi === CMD_SLEEP) { + if (Number(record.recordState) === SLEEP_STATE_EMPTY) return null; + const segments: SleepSegment[] = []; + const raw = record.segments; + for (let i = 0; i < raw.length; i++) { + const segment = raw[i]; + // Java calls it `stage`, the domain type calls it `stageId` - both are + // the same raw 0-3 ring id, deliberately unresolved here (see sleep-stages.ts). + segments.push({ stageId: Number(segment.stage), halfMinutes: Number(segment.halfMinutes) }); + } + const startTs = Number(record.startTs); + const endTs = Number(record.endTs); + const correction = sleepClockOffsetMs(startTs * 1000); + // The assertion log for the -8h correction. One sleep record a night makes + // this cheap, and a wrong clock frame is otherwise invisible until someone + // reads a chart and disbelieves it. + console.log( + `health live: sleep raw ${new Date(startTs * 1000).toString()} -> corrected ` + + `${new Date(startTs * 1000 - correction).toString()} .. ` + + `${new Date(endTs * 1000 - correction).toString()} (-${correction / 3600000}h)`, + ); + return { + kind: "sleep", + startTs, + endTs, + clockCorrectionMs: correction, + totalSec: Number(record.totalTime), + wakeSec: Number(record.wakeTime), + remSec: Number(record.remTime), + lightSec: Number(record.lightTime), + deepSec: Number(record.deepTime), + segments, + receivedAtMs: Number(record.receivedAtMs), + }; + } + + return null; +} + +export type LiveSyncResult = { + /** Records the communicator was holding. 0 means no pull has landed yet. */ + seen: number; + /** Samples genuinely new to the store. */ + samplesWritten: number; + /** Sleep sessions genuinely new to the store. */ + sleepWritten: number; + /** Conversions deliberately declined, with reasons, from `convertRecords`. */ + skipped: { what: string; why: string }[]; +}; + +const EMPTY: LiveSyncResult = { seen: 0, samplesWritten: 0, sleepWritten: 0, skipped: [] }; + +/** + * Read the communicator's decoded records into the durable store. + * + * Safe to call on every open and every refresh: the store dedupes, and an + * absent communicator (no glasses process, preview build) is a no-op rather + * than an error. + */ +/** + * Tell the communicator the snapshot is durably stored and may be dropped. + * + * Deliberately swallows its own failure: a clear that does not happen costs a + * little growth, and there is nothing useful to do about it here. The bias runs + * one way throughout - under-clearing is cheap, over-clearing loses data. + */ +function consumeUpTo(communicator: any, watermark: number): void { + try { + const dropped = Number(communicator.clearRingHealthRecordsBelow(watermark)); + if (dropped > 0) { + console.log(`health live: consumed ${dropped} records (watermark ${watermark})`); + } + } catch (error) { + console.warn("health live: could not clear consumed records", error); + } +} + +/** The communicator's `java.util.List` of `RingProtocol.HealthRecord`s. */ +type JavaRecordList = { size(): number; get(index: number): any }; + +type StoreResult = Omit; + +/** + * Convert decoded records and store them durably. Throws if a store write + * fails, so the caller keeps whatever it would otherwise mark as consumed. + * Shared by the live batch and the journal replay. + */ +function storeRecords(records: JavaRecordList): StoreResult { + const wire: WireRecord[] = []; + const size = records.size(); + for (let i = 0; i < size; i++) { + try { + const converted = toWire(records.get(i)); + if (converted) wire.push(converted); + } catch (error) { + console.warn("health live: skipped an undecodable record", error); + } + } + if (wire.length === 0) return { samplesWritten: 0, sleepWritten: 0, skipped: [] }; + + const { samples, sleep, skipped } = convertRecords(wire); + if (samples.length === 0 && sleep.length === 0) { + return { samplesWritten: 0, sleepWritten: 0, skipped }; + } + + // First real data wins the store outright — see the header. + purgeFixtureData(); + + const store = healthStore(); + const samplesWritten = store.ingestSamples(samples); + const sleepWritten = store.ingestSleep(sleep); + // Also mark on a retry whose samples were already appended before a later + // write failed. Otherwise opening Health could seed fixtures over real data. + markLiveData(); + return { samplesWritten, sleepWritten, skipped }; +} + +/** + * Bump when the Kotlin decoders learn a layout they used to reject. The + * replay cursor records the version it ran under, and a cursor from an older + * decoder replays the whole journal: the frames it skipped are only on disk. + * + * 2: R1 firmware 2.3.x's four-byte page trailer (2026-11-01). Before it, + * every page that firmware sent was journaled, acknowledged and dropped. + */ +const JOURNAL_DECODER_VERSION = 2; + +type ReplayCursor = { version: number; throughReceivedAtMs: number }; + +function healthFilePath(name: string): string { + return `${knownFolders.documents().getFolder("health").path}/${name}`; +} + +function readReplayCursor(): ReplayCursor | null { + try { + const path = healthFilePath("journal-replay.json"); + if (!File.exists(path)) return null; + const parsed = JSON.parse(File.fromPath(path).readTextSync()) as ReplayCursor; + return typeof parsed?.version === "number" && typeof parsed.throughReceivedAtMs === "number" ? parsed : null; + } catch { + return null; + } +} + +let journalReplayed = false; + +/** + * Store the health pages in the communicator's frame journal + * (`ring-frames.jsonl`, written before each page is acknowledged) that have + * not been replayed under the current decoder. Once per process, before any + * live batch, so pages land oldest first and a newer live value is never + * overwritten by an older replayed one. + * + * The ring counts an acknowledged page as synced and does not send it again, + * so a page the decoder could not read at the time exists nowhere else. The + * store and the steps ledger are idempotent, so re-storing a page that was + * already ingested live is a no-op. + */ +function replayFrameJournalOnce(): void { + if (journalReplayed) return; + let ringProtocol: any; + try { + ringProtocol = (com as any).faceclaw.app.RingProtocol; + } catch { + ringProtocol = null; + } + const journalPath = healthFilePath("ring-frames.jsonl"); + if (!ringProtocol || !File.exists(journalPath)) { + journalReplayed = true; + return; + } + const cursor = readReplayCursor(); + const after = cursor?.version === JOURNAL_DECODER_VERSION ? cursor.throughReceivedAtMs : 0; + const records: JavaRecordList = ringProtocol.decodeFrameJournal(File.fromPath(journalPath).readTextSync(), after); + const size = records.size(); + if (size > 0) { + const result = storeRecords(records); + let through = after; + for (let i = 0; i < size; i++) through = Math.max(through, Number(records.get(i).receivedAtMs)); + const next: ReplayCursor = { version: JOURNAL_DECODER_VERSION, throughReceivedAtMs: through }; + checkedFileOperation((onError) => + File.fromPath(healthFilePath("journal-replay.json")).writeTextSync(JSON.stringify(next), onError), + ); + console.log( + `health live: replayed ${size} journaled pages -> ${result.samplesWritten} samples, ` + + `${result.sleepWritten} sleep` + (result.skipped.length ? `, ${result.skipped.length} skipped` : ""), + ); + } + journalReplayed = true; +} + +export function syncLiveRecords(): LiveSyncResult { + try { + replayFrameJournalOnce(); + } catch (error) { + // Not marked done: the next sync retries it, ahead of the live batch. + console.warn("health live: frame journal replay failed", error); + } + + const communicator = activeCommunicator(); + if (!communicator) return EMPTY; + + let batch: any; + try { + batch = communicator.takeRingHealthBatch(); + } catch (error) { + console.warn("health live: could not read ring records", error); + return EMPTY; + } + if (!batch) return EMPTY; + const records = batch.getRecords(); + // Identifies exactly this snapshot. Anything the ring pushes from here on is + // numbered above it and therefore cannot be cleared by this pass - which is + // what keeps a page landing mid-ingest from being dropped. + const watermark = Number(batch.getWatermark()); + if (!records || !records.size || records.size() === 0) return EMPTY; + const size = records.size(); + + const { samplesWritten, sleepWritten, skipped } = storeRecords(records); + + // ONLY here. Both store writes have returned, so the records are durable. + // If either threw, or the process died above this line, nothing is cleared + // and the same records arrive again next tick - which costs one repeated + // ingest (a no-op, the store refuses identical re-writes) instead of losing + // a night. Note `samplesWritten === 0` is NOT a failure: it means the store + // already held all of it, which is the steady state this change creates. + // Records that converted to nothing are consumed too: holding them would + // only re-run the same conversion every tick. + consumeUpTo(communicator, watermark); + + console.log( + `health live: ${size} records -> ${samplesWritten} samples, ${sleepWritten} sleep` + + (skipped.length ? `, ${skipped.length} skipped` : ""), + ); + return { seen: size, samplesWritten, sleepWritten, skipped }; +} + +/** + * Ask the ring for a fresh pull now, rather than waiting out the automatic + * 30-minute cycle. Returns immediately; the pull itself takes ~15s on the + * communicator's worker thread and lands through the next `syncLiveRecords()`. + * + * Throttled communicator-side to one a minute — see + * `requestRingHealthNow()`. Calling it on every open is fine. + */ +export function requestFreshPull(): void { + const communicator = activeCommunicator(); + if (!communicator) return; + try { + communicator.requestRingHealthNow(); + } catch (error) { + console.warn("health live: on-demand pull request failed", error); + } +} + +/** + * Keep decoded records reaching disk whether or not a surface is open. + * + * Without this, records live only in the communicator's memory until the + * health app or phone page is opened, so a pull that lands while both are + * closed is lost if the process restarts first. The store dedupes, so this is + * a no-op whenever there is nothing new. + * + * Called once from `app.ts`. Idempotent. + */ +const BACKGROUND_SYNC_INTERVAL_MS = 60 * 1000; +let backgroundSyncTimer: ReturnType | null = null; + +export function startLiveHealthSync(): void { + if (backgroundSyncTimer) return; + backgroundSyncTimer = setInterval(() => { + try { + syncLiveRecords(); + } catch (error) { + console.warn("health live: background sync failed", error); + } + }, BACKGROUND_SYNC_INTERVAL_MS); +} + +/** + * Pull the ring on a wall-clock-aligned cadence: :01 and :31, every hour. + * + * Chris, 2026-09-12: *"I think we should be polling the ring on the 30 minute + * cycle (that was my intent, not a floor honestly)."* The 30-minute value in + * `RING_HEALTH_MIN_PULL_INTERVAL_MS` was always meant as a collection rhythm + * and got built as a throttle, so a connected, stable ring pulled never — + * nothing in the system drives a pull on a timer at all. + * + * Two reasons this is aligned to the wall clock rather than a plain interval: + * + * 1. **The ring's own step buckets close on 10-minute boundaries.** Pulling on + * the boundary collects a just-closed bucket instead of a half-formed one. + * 2. **An elapsed timer drifts.** A pull at :07 sets the next at :37, then :07, + * wandering away from the boundary it is supposed to track. Re-arming + * against the clock each time cannot drift. + * + * The **one-minute offset is deliberate**: firing exactly at :00 risks catching + * the ring before it has finalised that bucket. + * + * This only *requests* a pull. The communicator still applies its own anti-spam + * floor, so an extra call here can never hammer the ring. + */ +const ALIGNED_PULL_MINUTES = [1, 31]; +let alignedPullTimer: ReturnType | null = null; + +function msUntilNextAlignedPull(now: Date): number { + const minutes = now.getMinutes(); + const withinHour = ALIGNED_PULL_MINUTES.filter((m) => m > minutes); + // Next slot this hour, or the first slot of the next hour. + const target = withinHour.length ? withinHour[0] : ALIGNED_PULL_MINUTES[0] + 60; + const msIntoMinute = now.getSeconds() * 1000 + now.getMilliseconds(); + return (target - minutes) * 60 * 1000 - msIntoMinute; +} + +export function startAlignedRingPull(): void { + if (alignedPullTimer) return; + const arm = () => { + const delay = msUntilNextAlignedPull(new Date()); + alignedPullTimer = setTimeout(() => { + alignedPullTimer = null; + try { + requestFreshPull(); + } catch (error) { + console.warn("health live: aligned ring pull failed", error); + } + arm(); // re-arm against the clock, never the elapsed time + }, delay); + }; + arm(); +} + +/** Exported for tests — the scheduling arithmetic, with no timer attached. */ +export const __alignedPullInternals = { msUntilNextAlignedPull, ALIGNED_PULL_MINUTES }; diff --git a/app/health/health-phone-chart.ts b/app/health/health-phone-chart.ts new file mode 100644 index 00000000..7d97f18c --- /dev/null +++ b/app/health/health-phone-chart.ts @@ -0,0 +1,101 @@ +/** + * The phone graph view's BITMAP, built without touching the phone. + * + * Same split, and for the same reason, as `health-glance.ts` is split out of + * the glasses app: `health-view-model.ts` owns the store reads, the measured + * box, the fold class and the `ImageSource` conversion - all NativeScript - and + * hands this file a size, a font and some already-selected data. What comes + * back is a `GrayImage`. + * + * The payoff is that `tools/health-preview.cjs` can render the phone chart at + * any width under plain node, which is how the narrow/wide layouts get checked + * without an emulator. It also means the chart the preview shows is built by + * the same function the phone calls, not a reimplementation of it. + */ + +import { GrayImage, type UiFont } from "../graphics/image"; +import { + drawMetricChart, + drawSleepLanes, + drawSleepStackChart, + INK, +} from "./health-chart"; +import type { RollupPoint, SampleMetric, SleepNight } from "./health-types"; +import type { SleepStageName } from "./sleep-stages"; + +/** + * What to draw. Three shapes, because the redesign gave sleep two charts of + * its own that are not "a series of numbers over time": + * + * - `metric` the five measured types, banded or barred (unchanged) + * - `nights` sleep over a week/month/quarter: the diverging stacked bar + * - `lanes` sleep over ONE day: the four stage lanes, which is the same + * view the glasses drill-down shows, so the two surfaces agree + * about what "sleep, today" looks like + */ +export type PhoneChartContent = + | { + kind: "metric"; + metric: SampleMetric; + points: readonly RollupPoint[]; + mode: "band" | "bars"; + xLabel: (point: RollupPoint, index: number) => string; + } + | { + kind: "nights"; + nights: readonly SleepNight[]; + xLabel: (night: SleepNight, index: number) => string; + } + | { + kind: "lanes"; + bands: readonly { stage: SleepStageName | null; seconds: number }[]; + laneText: (stage: SleepStageName) => { label: string; value: string }; + }; + +export type PhoneChartRequest = { + /** Pixels, already scaled by RENDER_SCALE. */ + width: number; + height: number; + font: UiFont; + content: PhoneChartContent; +}; + +/** The inset between the bitmap's edge and the plot. */ +const INSET = 8; + +export function renderPhoneChart(request: PhoneChartRequest): GrayImage { + const { width, height, font, content } = request; + const image = new GrayImage(width, height, INK.background); + const rect = { + x: INSET, + y: INSET, + width: Math.max(8, width - INSET * 2), + height: Math.max(8, height - INSET * 2), + }; + + switch (content.kind) { + case "metric": + drawMetricChart(image, rect, { + metric: content.metric, + points: content.points, + font, + mode: content.mode, + xLabel: content.xLabel, + }); + return image; + case "nights": + drawSleepStackChart(image, rect, { + nights: content.nights, + font, + xLabel: content.xLabel, + }); + return image; + case "lanes": + drawSleepLanes(image, rect, { + bands: content.bands, + font, + laneText: content.laneText, + }); + return image; + } +} diff --git a/app/health/health-seed.ts b/app/health/health-seed.ts new file mode 100644 index 00000000..0d55589a --- /dev/null +++ b/app/health/health-seed.ts @@ -0,0 +1,143 @@ +/** + * Seeding the store with sample data, and the marker that keeps a screenshot + * of it honest. + * + * Without live ring hardware there is nothing in the store, and two empty + * screens prove nothing. So the preview build seeds `health-fixtures.ts`' + * generated data and drops `fixture-marker.json` beside it; both surfaces read + * `isFixtureData()` and show a "Sample data" badge whenever it is there. + * + * The badge is the point. A health screen full of plausible numbers with no + * provenance is the one artefact from this work that could be mistaken for a + * real capture later, so the marker travels with the data rather than living + * in someone's memory of how a screenshot was taken. + * + * Real ingest never writes the marker, so the first genuine sync leaves it + * exactly as it was - which is why `clearFixtures()` exists and why the live + * wiring should call it before its first write. + */ + +import { File, knownFolders } from "@nativescript/core"; + +import { buildFixtures, FIXTURE_VERSION } from "./health-fixtures"; +import { checkedFileOperation, healthStore } from "./health-store-files"; + +const MARKER_FILE = "fixture-marker.json"; + +function markerPath(): string { + return `${knownFolders.documents().getFolder("health").path}/${MARKER_FILE}`; +} + +type Marker = { version: number; seededAtMs: number; days: number }; + +function readMarker(): Marker | null { + try { + if (!File.exists(markerPath())) return null; + const parsed = JSON.parse(File.fromPath(markerPath()).readTextSync()) as Marker; + return typeof parsed?.version === "number" ? parsed : null; + } catch { + return null; + } +} + +/** True when the store currently holds generated sample data. */ +export function isFixtureData(): boolean { + return readMarker() !== null; +} + +/** Written by `health-live.ts` the first time real ring data lands. */ +const LIVE_FILE = "live-marker.json"; + +function livePath(): string { + return `${knownFolders.documents().getFolder("health").path}/${LIVE_FILE}`; +} + +/** True once this install has ever stored a record decoded off the ring. */ +export function hasLiveData(): boolean { + try { + return File.exists(livePath()); + } catch { + return false; + } +} + +/** Record that real data has been stored. Called by the live ingest path. */ +export function markLiveData(): void { + if (hasLiveData()) return; + checkedFileOperation((onError) => + File.fromPath(livePath()).writeTextSync(JSON.stringify({ firstAtMs: Date.now() }), onError), + ); +} + +/** + * Delete every stored sample, session and rollup, and the fixture badge with + * them. Called before the first genuine ingest. + * + * `clearFixtureMarker()` is not enough on its own and never was: dropping the + * badge while leaving 45 days of generated samples in the store produces + * exactly the artefact this file's header warns about — plausible numbers with + * no provenance, now unlabelled. Real data gets a clean store or none. + */ +export function purgeFixtureData(): void { + if (!isFixtureData()) return; + try { + const folder = knownFolders.documents().getFolder("health"); + for (const entity of folder.getEntitiesSync()) { + const name = entity.name; + const isStoreFile = + (name.startsWith("samples-") && name.endsWith(".jsonl")) || + name === "sleep.jsonl" || + name === "rollups.json"; + if (isStoreFile) { + checkedFileOperation((onError) => File.fromPath(entity.path).removeSync(onError)); + } + } + // Keep the badge until every fixture file is gone. A failed purge must + // stop live ingest so it cannot mix real records with remaining fixtures. + clearFixtureMarker(); + } finally { + // Also invalidate after a partial purge; cached rows no longer match disk. + healthStore().resetCache(); + } +} + +/** + * Seed sample data if none is present, or if the generator has changed since + * the last seed. A no-op once seeded, so it is safe to call on every launch. + * + * Refuses outright once real ring data has ever been stored — otherwise a + * version bump to the generator would inject fixtures back on top of a real + * history, which is worse than an empty screen. + */ +export function seedFixturesIfNeeded(days = 45): boolean { + if (hasLiveData()) return false; + const marker = readMarker(); + if (marker && marker.version === FIXTURE_VERSION && marker.days >= days) return false; + return seedFixtures(days); +} + +export function seedFixtures(days = 45): boolean { + try { + const store = healthStore(); + const { samples, sleep } = buildFixtures({ days, nowMs: Date.now() }); + // Label before the first append so a failed seed remains identifiable and + // can be purged before real data is ingested. + const marker: Marker = { version: FIXTURE_VERSION, seededAtMs: Date.now(), days }; + checkedFileOperation((onError) => + File.fromPath(markerPath()).writeTextSync(JSON.stringify(marker), onError), + ); + store.ingestSamples(samples); + store.ingestSleep(sleep); + return true; + } catch (error) { + console.warn("health fixture seed failed", error); + return false; + } +} + +/** Drop the marker. Call before the first real ingest. */ +export function clearFixtureMarker(): void { + if (File.exists(markerPath())) { + checkedFileOperation((onError) => File.fromPath(markerPath()).removeSync(onError)); + } +} diff --git a/app/health/health-store-files.ts b/app/health/health-store-files.ts new file mode 100644 index 00000000..10eb33b2 --- /dev/null +++ b/app/health/health-store-files.ts @@ -0,0 +1,81 @@ +/** + * The real, on-device backing for `HealthStore`: files under the app's + * documents folder, using the same `@nativescript/core` File API that + * `open-apps-persistence.ts` already uses for the open-window list. + * + * Split out from `health-store.ts` purely so that module can stay free of + * NativeScript imports and run under plain node in `tests/`; all the logic + * worth testing is over there. + */ + +import { File, Folder, knownFolders } from "@nativescript/core"; + +import { HealthStore, type HealthStorageBackend } from "./health-store"; + +const FOLDER_NAME = "health"; + +function healthFolder(): Folder { + return knownFolders.documents().getFolder(FOLDER_NAME); +} + +function pathFor(name: string): string { + return `${healthFolder().path}/${name}`; +} + +class FileBackend implements HealthStorageBackend { + exists(name: string): boolean { + try { + return File.exists(pathFor(name)); + } catch { + return false; + } + } + + read(name: string): string | null { + try { + if (!File.exists(pathFor(name))) return null; + return File.fromPath(pathFor(name)).readTextSync(); + } catch (error) { + console.warn(`health store read failed (${name})`, error); + return null; + } + } + + append(name: string, text: string): void { + // NativeScript reports IO failures through callbacks as well as throws. + // Propagate both so the caller retains the unconsumed ring batch. + checkedFileOperation((onError) => File.fromPath(pathFor(name)).appendTextSync(text, onError)); + } + + write(name: string, text: string): void { + checkedFileOperation((onError) => File.fromPath(pathFor(name)).writeTextSync(text, onError)); + } + + list(): string[] { + try { + return healthFolder() + .getEntitiesSync() + .map((entity) => entity.name); + } catch (error) { + console.warn("health store list failed", error); + return []; + } + } +} + +/** Convert a synchronous NativeScript error callback into a thrown failure. */ +export function checkedFileOperation(operation: (onError: (error: any) => void) => void): void { + let failure: Error | undefined; + operation((error) => { + failure = error instanceof Error ? error : new Error(error?.message ?? String(error)); + }); + if (failure) throw failure; +} + +let store: HealthStore | null = null; + +/** The app's one health store. Created on first use. */ +export function healthStore(): HealthStore { + if (!store) store = new HealthStore(new FileBackend()); + return store; +} diff --git a/app/health/health-store.ts b/app/health/health-store.ts new file mode 100644 index 00000000..beb93e7a --- /dev/null +++ b/app/health/health-store.ts @@ -0,0 +1,453 @@ +/** + * Durable local storage for decoded ring health records. + * + * ## Why this exists at all, and why it is not a cache + * + * Live testing on 2026-09-10 found that the ring appears to advance its own + * delivery watermark when it sends the RSP to a health request, whether or not + * the DATA page that should follow ever arrives - so a request that loses the + * race can PERMANENTLY DISCARD backlog, silently, with no error anywhere in + * the protocol (implement-return, section 11). The practical consequence: + * the moment a record is successfully decoded may be the only moment it is + * ever available. It has to hit durable storage right then. + * + * The existing `ringHealthRecords` list on `FaceclawBleCommunicator` is + * explicitly a capped, ephemeral ring buffer (256 records, oldest dropped) and + * is not a store. This is the store. + * + * ## The layout, and why it is shaped this way + * + * health/samples-YYYY-MM.jsonl append-only, one JSON object per line + * health/sleep.jsonl append-only, one session per line + * health/rollups.json DERIVED daily rollups - a rebuildable cache + * + * The raw shards are the truth and are never rewritten in place, only appended + * to. That is the property the paragraph above demands: a crash, a bad parse, + * or a bug in the rollup code can never destroy a record that was once + * received, because nothing ever rewrites the file that holds it. + * + * `rollups.json` is the answer to "pre-aggregate on write, or aggregate on + * render?" - and the answer is BOTH, at different layers, because they are + * asked by different screens: + * + * - The glasses glance and the by-hour charts want one day at fine + * resolution. That comes from raw shards, aggregated on render. At ~360 + * samples a day the work is trivial, and it stays exact. + * - The by-day charts want weeks or months. Aggregating those on render + * means parsing every shard in the range - about 9 MB a year of JSONL, and + * growing without bound. So daily rollups are maintained on write and + * served straight from this one small file, and a quarter-long chart never + * opens a shard at all. + * + * Because the rollup file is derived, it carries no risk: if it is missing, + * corrupt, or written by an older version, `rebuildRollups()` regenerates it + * from the shards. Deleting it is always safe. + * + * ## No new dependency + * + * SQLite is not a dependency of this project and adding one for this would be + * the largest change in the feature. Everything the phone view needs is a + * key-ordered scan over a few tens of thousands of rows, which is what the + * above does with the `File` API already used by `open-apps-persistence.ts` + * for the same kind of job. + * + * This module has NO NativeScript imports - the filesystem arrives through + * `HealthStorageBackend` - so its durability and dedupe semantics run under + * plain node in `tests/health-store.test.cjs`. The real backend is + * `health-store-files.ts`. + */ + +import { + type HealthSample, + type Rollup, + type SampleMetric, + type SleepSession, + SAMPLE_METRICS, + monthKey, + rollupOf, + startOfLocalDay, +} from "./health-types"; + +export interface HealthStorageBackend { + exists(name: string): boolean; + read(name: string): string | null; + /** Must create the file if absent. Durable before returning. */ + append(name: string, text: string): void; + write(name: string, text: string): void; + /** Every file in the health folder. Used to rebuild the rollup cache. */ + list(): string[]; +} + +const SAMPLE_PREFIX = "samples-"; +const SAMPLE_SUFFIX = ".jsonl"; +const SLEEP_FILE = "sleep.jsonl"; +const ROLLUP_FILE = "rollups.json"; +const ROLLUP_VERSION = 1; + +/** On-disk sample line. Short keys: this is the file that grows. */ +type SampleLine = { + m: SampleMetric; + t: number; + s: number; + n: number; + x: number; + a: number; + u: number; +}; + +type RollupFile = { + version: number; + /** `YYYY-MM-DD` -> metric -> rollup. */ + days: Record>>; +}; + +function sampleKey(sample: { metric: SampleMetric; startMs: number; spanMs: number }): string { + return `${sample.metric}|${sample.startMs}|${sample.spanMs}`; +} + +function dayKey(ms: number): string { + const date = new Date(startOfLocalDay(ms)); + const month = `${date.getMonth() + 1}`.padStart(2, "0"); + const day = `${date.getDate()}`.padStart(2, "0"); + return `${date.getFullYear()}-${month}-${day}`; +} + +function shardName(ms: number): string { + return `${SAMPLE_PREFIX}${monthKey(ms)}${SAMPLE_SUFFIX}`; +} + +export class HealthStore { + /** Shard name -> dedupe key -> sample. Loaded lazily, per shard. */ + private readonly shards = new Map>(); + private sleep: SleepSession[] | null = null; + private rollups: RollupFile | null = null; + private rollupsDirty = false; + + constructor(private readonly backend: HealthStorageBackend) {} + + /** Forget cached data after the backing files have been purged. */ + resetCache(): void { + this.shards.clear(); + this.sleep = null; + this.rollups = null; + this.rollupsDirty = false; + } + + // ------------------------------------------------------------------------- + // Writing + + /** + * Store decoded samples. Durable before this returns. + * + * Returns how many were genuinely new or changed. Re-storing a bucket that + * is already held is a no-op on disk, which matters because the live poller + * re-requests the current hour every 30 minutes and would otherwise append a + * duplicate line each time. + * + * ## This no-op is real, and it is the ONLY place it needs to be + * + * Re-checked 2026-09-12 while chasing a shard that reached 22k lines in a + * day. The suspicion was that identical re-writes were being appended; they + * were not. `sameSample` below compares every stored field, `spanMs` is part + * of the key, and an unchanged sample never reaches `append`. + * + * What was actually appending was a genuinely CHANGING value: the steps + * ledger merged overlapping records with last-write-wins, and those records + * disagreed about each bucket's calorie fields, so one day's calorie total + * ping-ponged 643 <-> 671 and wrote two new lines every sync cycle. An + * append-only store recording a value that really does flip-flop is correct + * behaviour; the fix belonged upstream, in `health-live.ts`' merge, and is + * there now (max-by-index, order-independent). + * + * So: do NOT add a second dedupe layer at a caller or in the file backend. + * If the shard grows again, the value is changing and the question is why. + */ + ingestSamples(samples: readonly HealthSample[]): number { + const byShard = new Map>(); + for (const sample of samples) { + if (!Number.isFinite(sample.startMs) || sample.spanMs <= 0) continue; + const name = shardName(sample.startMs); + const shard = this.loadShard(name); + const key = sampleKey(sample); + const pending = byShard.get(name) ?? new Map(); + const existing = pending.get(key) ?? shard.get(key); + if (existing && sameSample(existing, sample)) continue; + pending.set(key, sample); + byShard.set(name, pending); + } + let written = 0; + for (const [name, pending] of byShard) { + const list = [...pending.values()]; + const text = list.map((sample) => `${JSON.stringify(toLine(sample))}\n`).join(""); + // A failed append can leave an incomplete final line. Start each batch + // on a fresh line so retrying cannot concatenate a valid record onto it. + this.backend.append(name, `\n${text}`); + this.rollupsDirty = true; + // Only durable values participate in deduplication. If another shard + // fails, a retry skips this successful append and retries the rest. + const shard = this.loadShard(name); + for (const [key, sample] of pending) shard.set(key, sample); + written += list.length; + } + if (this.rollupsDirty) { + this.updateRollupsFor(samples); + this.rollupsDirty = false; + } + return written; + } + + /** + * Store sleep sessions. Durable before this returns. + * + * Deduped on the session's own start time, so a night re-delivered by a + * later sync replaces rather than duplicates. + */ + ingestSleep(sessions: readonly SleepSession[]): number { + const held = this.loadSleep().slice(); + const fresh: SleepSession[] = []; + for (const session of sessions) { + const index = held.findIndex( + (candidate) => + candidate.startMs === session.startMs && candidate.timeResolved === session.timeResolved, + ); + if (index >= 0) { + if (JSON.stringify(held[index]) === JSON.stringify(session)) continue; + held[index] = session; + } else { + held.push(session); + } + fresh.push(session); + } + if (fresh.length > 0) { + this.backend.append(SLEEP_FILE, "\n" + fresh.map((s) => `${JSON.stringify(s)}\n`).join("")); + this.sleep = held; + } + return fresh.length; + } + + // ------------------------------------------------------------------------- + // Reading + + /** Every stored sample overlapping [startMs, endMs). Exact - reads shards. */ + samplesInRange(startMs: number, endMs: number): HealthSample[] { + const out: HealthSample[] = []; + for (const name of this.shardNamesInRange(startMs, endMs)) { + for (const sample of this.loadShard(name).values()) { + if (sample.startMs >= startMs && sample.startMs < endMs) out.push(sample); + } + } + out.sort((a, b) => a.startMs - b.startMs); + return out; + } + + /** Sleep sessions, newest first. */ + sleepSessions(): SleepSession[] { + return this.loadSleep().slice().sort((a, b) => b.startMs - a.startMs); + } + + /** + * Daily rollups over a range, served from the derived cache. + * + * This is the path a month- or quarter-long chart takes, and it deliberately + * never opens a sample shard. A day with no entry comes back absent, and the + * caller renders a gap. + */ + dailyRollups(metric: SampleMetric, startMs: number, endMs: number): Map { + const file = this.loadRollups(); + const out = new Map(); + let cursor = startOfLocalDay(startMs); + let guard = 0; + while (cursor < endMs && guard < 2000) { + guard += 1; + const entry = file.days[dayKey(cursor)]?.[metric]; + if (entry) out.set(cursor, entry); + const next = new Date(cursor); + next.setDate(next.getDate() + 1); + cursor = next.getTime(); + } + return out; + } + + /** Local midnight of the earliest day with any stored data, or null. */ + earliestDayMs(): number | null { + const file = this.loadRollups(); + const keys = Object.keys(file.days).sort(); + if (keys.length === 0) return null; + const parts = keys[0]!.split("-").map(Number); + return new Date(parts[0]!, parts[1]! - 1, parts[2]!).getTime(); + } + + /** How many sample rows are held, across every loaded shard. */ + loadedSampleCount(): number { + let total = 0; + for (const shard of this.shards.values()) total += shard.size; + return total; + } + + // ------------------------------------------------------------------------- + // The derived cache + + /** + * Rebuild `rollups.json` from the raw shards. Safe to call at any time; the + * recovery path when the cache is missing, corrupt or from an older version. + */ + rebuildRollups(): void { + const days: RollupFile["days"] = {}; + const perDay = new Map>(); + for (const name of this.backend.list()) { + if (!name.startsWith(SAMPLE_PREFIX) || !name.endsWith(SAMPLE_SUFFIX)) continue; + for (const sample of this.loadShard(name).values()) { + const key = dayKey(sample.startMs); + let byMetric = perDay.get(key); + if (!byMetric) { + byMetric = new Map(); + perDay.set(key, byMetric); + } + const list = byMetric.get(sample.metric); + if (list) list.push(sample); + else byMetric.set(sample.metric, [sample]); + } + } + for (const [key, byMetric] of perDay) { + const entry: Partial> = {}; + for (const metric of SAMPLE_METRICS) { + const rolled = rollupOf(byMetric.get(metric) ?? []); + if (rolled) entry[metric] = rolled; + } + days[key] = entry; + } + this.rollups = { version: ROLLUP_VERSION, days }; + this.persistRollups(); + } + + private updateRollupsFor(samples: readonly HealthSample[]): void { + const file = this.loadRollups(); + const touched = new Set(); + for (const sample of samples) touched.add(dayKey(sample.startMs)); + for (const key of touched) { + const parts = key.split("-").map(Number); + const dayStart = new Date(parts[0]!, parts[1]! - 1, parts[2]!).getTime(); + const dayEnd = new Date(parts[0]!, parts[1]! - 1, parts[2]! + 1).getTime(); + const inDay = this.samplesInRange(dayStart, dayEnd); + const entry: Partial> = {}; + for (const metric of SAMPLE_METRICS) { + const rolled = rollupOf(inDay.filter((sample) => sample.metric === metric)); + if (rolled) entry[metric] = rolled; + } + file.days[key] = entry; + } + this.persistRollups(); + } + + private persistRollups(): void { + if (!this.rollups) return; + this.backend.write(ROLLUP_FILE, JSON.stringify(this.rollups)); + } + + // ------------------------------------------------------------------------- + // Loading + + private shardNamesInRange(startMs: number, endMs: number): string[] { + const names: string[] = []; + const cursor = new Date(startOfLocalDay(startMs)); + cursor.setDate(1); + let guard = 0; + while (cursor.getTime() < endMs && guard < 240) { + guard += 1; + names.push(`${SAMPLE_PREFIX}${monthKey(cursor.getTime())}${SAMPLE_SUFFIX}`); + cursor.setMonth(cursor.getMonth() + 1); + } + return names; + } + + private loadShard(name: string): Map { + const held = this.shards.get(name); + if (held) return held; + const shard = new Map(); + this.shards.set(name, shard); + const text = this.backend.exists(name) ? this.backend.read(name) : null; + if (!text) return shard; + for (const line of text.split("\n")) { + if (line.length === 0) continue; + const sample = fromLine(line); + // Later lines win: an append is how a re-synced bucket is corrected. + if (sample) shard.set(sampleKey(sample), sample); + } + return shard; + } + + private loadSleep(): SleepSession[] { + if (this.sleep) return this.sleep; + const sessions: SleepSession[] = []; + const text = this.backend.exists(SLEEP_FILE) ? this.backend.read(SLEEP_FILE) : null; + if (text) { + for (const line of text.split("\n")) { + if (line.length === 0) continue; + try { + const parsed = JSON.parse(line) as SleepSession; + if (typeof parsed?.startMs !== "number") continue; + const index = sessions.findIndex((s) => s.startMs === parsed.startMs); + if (index >= 0) sessions[index] = parsed; + else sessions.push(parsed); + } catch { + // One unreadable line must not cost the rest of the file. + } + } + } + this.sleep = sessions; + return sessions; + } + + private loadRollups(): RollupFile { + if (this.rollups) return this.rollups; + const text = this.backend.exists(ROLLUP_FILE) ? this.backend.read(ROLLUP_FILE) : null; + if (text) { + try { + const parsed = JSON.parse(text) as RollupFile; + if (parsed?.version === ROLLUP_VERSION && parsed.days) { + this.rollups = parsed; + return parsed; + } + } catch { + // Falls through to a rebuild - the cache is always reconstructible. + } + } + this.rollups = { version: ROLLUP_VERSION, days: {} }; + this.rebuildRollups(); + return this.rollups; + } +} + +function sameSample(a: HealthSample, b: HealthSample): boolean { + return a.min === b.min && a.max === b.max && a.avg === b.avg && a.total === b.total; +} + +function toLine(sample: HealthSample): SampleLine { + return { + m: sample.metric, + t: sample.startMs, + s: sample.spanMs, + n: sample.min, + x: sample.max, + a: sample.avg, + u: sample.total, + }; +} + +function fromLine(line: string): HealthSample | null { + try { + const parsed = JSON.parse(line) as SampleLine; + if (typeof parsed?.t !== "number" || typeof parsed?.m !== "string") return null; + return { + metric: parsed.m, + startMs: parsed.t, + spanMs: parsed.s, + min: parsed.n, + max: parsed.x, + avg: parsed.a, + total: parsed.u, + }; + } catch { + return null; + } +} diff --git a/app/health/health-types.ts b/app/health/health-types.ts new file mode 100644 index 00000000..f9aeb698 --- /dev/null +++ b/app/health/health-types.ts @@ -0,0 +1,231 @@ +/** + * The health record shapes, normalised for storage and display. + * + * These mirror `RingProtocol.kt`'s `HourlyRecord` / `StepsRecord` / + * `SleepRecord` (on the `ring-health-protocol` branch) but deliberately are + * NOT the same types: the Java types are wire-shaped - raw hour indices, raw + * stage ids, ring-relative timestamps, a per-page anchor that may be absent. + * Everything here is already resolved into wall-clock time, or explicitly + * marked as not resolvable. The conversion is `fromRingRecords()` in + * `health-ingest.ts`, which is the only place that has to know about the wire. + * + * Keeping the two apart is what lets this app's storage and UI be built and + * tested with no BLE anywhere near them. + */ + +/** The five metrics the phone view can graph. */ +export type SeriesMetric = "heartRate" | "spo2" | "hrv" | "steps" | "sleep"; + +/** Metrics stored as bucketed samples. Sleep is per-session and excluded. */ +export type SampleMetric = "heartRate" | "spo2" | "hrv" | "steps" | "calories"; + +export const SAMPLE_METRICS: readonly SampleMetric[] = [ + "heartRate", + "spo2", + "hrv", + "steps", + "calories", +]; + +/** Metrics whose bucket value is a SUM over the bucket, not a measurement. */ +export const CUMULATIVE_METRICS: readonly SampleMetric[] = ["steps", "calories"]; + +export function isCumulative(metric: SampleMetric): boolean { + return CUMULATIVE_METRICS.includes(metric); +} + +export const HOUR_MS = 3_600_000; +export const TEN_MINUTES_MS = 600_000; +export const DAY_MS = 86_400_000; + +/** + * One stored bucket. + * + * `min`/`max`/`avg` are what the ring reports for the physiological metrics. + * For the cumulative ones (steps, calories) the ring reports a single count + * per bucket, so all three carry that count and `total` carries it as well - + * which keeps one shape for everything and lets a rollup sum `total` while + * banding `min`/`max` without special-casing the reader. + * + * `startMs` is the LOCAL wall-clock start of the bucket. A record whose time + * could not be resolved (a backlog page with no anchor; see the decode doc's + * section 4) is not stored at all rather than stored with an invented time - + * see `health-ingest.ts`. + */ +export type HealthSample = { + metric: SampleMetric; + startMs: number; + spanMs: number; + min: number; + max: number; + avg: number; + total: number; +}; + +/** + * One sleep session. + * + * All five duration fields come from NAMED byte offsets in the record and need + * no stage-id mapping (see `sleep-stages.ts`). `segments` is the hypnogram and + * carries RAW stage ids - resolve them through `stageNameForId`, never inline. + * + * `timeResolved` matters and is not decoration: the decode found that the + * ring's `start_ts`/`end_ts` are ring-relative seconds, not Unix time, and + * that nothing in the record dates the session (decode section 6, "genuinely + * unresolved"). Even's own app gets this wrong - one exported row is stamped + * 1979. When we cannot anchor a session we say so rather than plotting it at a + * time we made up. + */ +export type SleepSession = { + /** Local midnight of the day the session is attributed to (the wake-up day). */ + dayStartMs: number; + startMs: number; + endMs: number; + totalSec: number; + wakeSec: number; + remSec: number; + lightSec: number; + deepSec: number; + segments: readonly SleepSegment[]; + /** False when startMs/endMs are ring-relative and could not be anchored. */ + timeResolved: boolean; +}; + +export type SleepSegment = { + /** RAW ring stage id, 0-3. Resolve via `stageNameForId`. */ + stageId: number; + halfMinutes: number; +}; + +/** + * One night's stage breakdown, in seconds, positioned on the day axis. + * + * This is what the diverging nightly sleep chart plots (week / month / 3 + * months). It is a separate shape from `RollupPoint` because a night is not a + * rollup of anything - it has four named parts that stack, three up and one + * down, and flattening it to a single `sum` is exactly the information the + * redesigned chart exists to stop throwing away. + */ +export type SleepNight = { + /** Local midnight of the day the session is attributed to (the wake-up day). */ + startMs: number; + /** False when no session was recorded for this day - drawn as a gap. */ + hasData: boolean; + deepSec: number; + remSec: number; + lightSec: number; + wakeSec: number; +}; + +/** A min/max/avg/sum rollup over some window. `count` is buckets contributing. */ +export type Rollup = { + min: number; + max: number; + avg: number; + sum: number; + count: number; +}; + +/** A rollup positioned on the time axis - what the charts actually plot. */ +export type RollupPoint = Rollup & { + /** Local wall-clock start of the window this rollup covers. */ + startMs: number; + spanMs: number; +}; + +export function emptyRollup(): Rollup { + return { min: 0, max: 0, avg: 0, sum: 0, count: 0 }; +} + +/** Combine samples into one rollup. Returns null when nothing contributed. */ +export function rollupOf(samples: readonly HealthSample[]): Rollup | null { + if (samples.length === 0) return null; + let min = Number.POSITIVE_INFINITY; + let max = Number.NEGATIVE_INFINITY; + let sum = 0; + let weighted = 0; + for (const sample of samples) { + if (sample.min < min) min = sample.min; + if (sample.max > max) max = sample.max; + sum += sample.total; + weighted += sample.avg; + } + return { + min, + max, + avg: weighted / samples.length, + sum, + count: samples.length, + }; +} + +export const METRIC_LABELS: Readonly> = { + heartRate: "Heart rate", + spo2: "Blood oxygen", + hrv: "HRV", + steps: "Steps", + sleep: "Sleep", +}; + +export const METRIC_UNITS: Readonly> = { + heartRate: "bpm", + spo2: "%", + hrv: "ms", + steps: "", + sleep: "h", +}; + +/** + * The same two maps over SampleMetric rather than SeriesMetric. + * + * These exist because the two enums differ at both ends: the phone GRAPHS + * sleep (which is not a sample metric) and the glasses drill-down walks + * calories (which is not a series metric, because the phone never got a + * calories chart). A screen that iterates the sample metrics needs a label for + * all five, so it gets its own map instead of special-casing the missing one. + */ +export const SAMPLE_METRIC_LABELS: Readonly> = { + heartRate: "Heart rate", + spo2: "Blood oxygen", + hrv: "HRV", + steps: "Steps", + calories: "Calories", +}; + +export const SAMPLE_METRIC_UNITS: Readonly> = { + heartRate: "bpm", + spo2: "%", + hrv: "ms", + steps: "", + calories: "kcal", +}; + +/** The short form the glance uses, where a column is ~300px wide. */ +export const SAMPLE_METRIC_SHORT_LABELS: Readonly> = { + heartRate: "HR", + spo2: "SpO2", + hrv: "HRV", + steps: "Steps", + calories: "Calories", +}; + +/** Local midnight of the day containing `ms`. */ +export function startOfLocalDay(ms: number): number { + const date = new Date(ms); + date.setHours(0, 0, 0, 0); + return date.getTime(); +} + +/** Local top-of-hour containing `ms`. */ +export function startOfLocalHour(ms: number): number { + const date = new Date(ms); + date.setMinutes(0, 0, 0); + return date.getTime(); +} + +/** `YYYY-MM`, in local time - the storage shard key. */ +export function monthKey(ms: number): string { + const date = new Date(ms); + const month = `${date.getMonth() + 1}`.padStart(2, "0"); + return `${date.getFullYear()}-${month}`; +} diff --git a/app/health/sleep-stages.ts b/app/health/sleep-stages.ts new file mode 100644 index 00000000..2c1c2a44 --- /dev/null +++ b/app/health/sleep-stages.ts @@ -0,0 +1,93 @@ +/** + * THE RING'S SLEEP STAGE-TYPE IDS — the single place the 0-3 -> stage mapping + * is decided. If this ever turns out wrong, this file is the whole fix. + * + * ## What the ring sends + * + * A `06:01` sleep record carries two independent descriptions of the same + * night (see the protocol decode, section 6): + * + * 1. Five NAMED per-stage totals at fixed byte offsets - `total_time`, + * `wake_time`, `rem_time`, `light_time`, `deep_time`. These are named, + * not guessed: the decode reproduced a whole exported row byte-for-byte + * from them, so a percentage computed from these fields needs no mapping + * at all and is not affected by anything in this file. + * + * 2. A segment array of `[stage_type, half_minutes]` pairs - the hypnogram, + * the shape of the night. `stage_type` is a raw 0-3 id, and *which* id is + * which stage was the open question this file answers. + * + * So: STAGE PERCENTAGES DO NOT DEPEND ON THIS MAPPING. Only the hypnogram + * strip does. `health-derive.ts` computes percentages from the named totals + * and never consults `STAGE_NAME_BY_ID` for them. + * + * ## How the mapping was determined + * + * The implementation return doc listed this as guess #3 - "never cracked", + * expected to need a live-hardware comparison against Even's own app after a + * night's sleep. It did not, because that comparison was already sitting in + * the exported history: the export IS Even's app's own report, and its + * `rem_time`/`light_time`/`deep_time`/`wake_time` columns are Even's own + * labels for the same night whose raw segment array sits in the same row. + * + * Cross-check performed 2026-09-10 over all 34 exported sessions: for each + * session, sum `half_minutes * 30` per stage id and ask which named total it + * equals. + * + * stage id 0 -> wake_time 34/34 sessions, no other total matched + * stage id 1 -> rem_time 34/34 sessions, no other total matched + * stage id 2 -> light_time 34/34 sessions, no other total matched + * stage id 3 -> deep_time 34/34 sessions, no other total matched + * + * Not one session produced an ambiguous match (an id equalling two totals) or + * an unmatched id, and the decode's own sum identity + * (`sum(half_minutes) * 30 == total_time + wake_time`) held in all 34. + * + * ## Why it is still marked unconfirmed + * + * `STAGE_MAPPING_CONFIRMED` stays `false` until the same result is seen on a + * record faceclaw decoded off the wire ITSELF, rather than one Even's app + * exported. The arithmetic above is strong evidence about what the *ids mean*, + * but every session it was computed from reached the CSV through Even's app, + * so it cannot rule out that the app relabels ids on the way in. That is a + * narrow doubt, and the live check Chris planned still closes it in one night. + * + * While this is `false` the UI labels the hypnogram as unconfirmed rather than + * asserting "this band is REM"; see `health-chart.ts`. Flipping it to `true` + * is the whole of the change once a live record agrees. + */ + +export type SleepStageName = "wake" | "rem" | "light" | "deep"; + +/** Raw `stage_type` id -> stage. See this file's header for the evidence. */ +export const STAGE_NAME_BY_ID: Readonly> = { + 0: "wake", + 1: "rem", + 2: "light", + 3: "deep", +}; + +/** + * False until a record faceclaw decoded off the wire itself confirms the + * mapping above. Read by the UI, which softens its stage labels while it is + * false. Flip to `true` after a live cross-check agrees. + */ +export const STAGE_MAPPING_CONFIRMED = false; + +/** The order stages are stacked/listed in, deepest sleep last. */ +export const STAGE_DISPLAY_ORDER: readonly SleepStageName[] = ["wake", "rem", "light", "deep"]; + +export function stageNameForId(stageId: number): SleepStageName | null { + return STAGE_NAME_BY_ID[stageId] ?? null; +} + +/** Human label for a stage, hedged while the mapping is unconfirmed. */ +export function stageLabel(stage: SleepStageName): string { + const labels: Record = { + wake: "Awake", + rem: "REM", + light: "Light", + deep: "Deep", + }; + return labels[stage]; +} diff --git a/app/native/faceclaw-communicator.ios.ts b/app/native/faceclaw-communicator.ios.ts index edd8cd4b..ea6fd304 100644 --- a/app/native/faceclaw-communicator.ios.ts +++ b/app/native/faceclaw-communicator.ios.ts @@ -248,7 +248,7 @@ export class FaceclawCommunicatorBridge { return FaceclawCommunicatorBridge.active; } - constructor(addresses: { right: string; left: string; ring?: string }) { + constructor(addresses: { right: string; left: string; ring?: string; ringRole?: string }) { this.communicator = FaceclawKitIosGlassesSession.alloc().initWithRightAddressLeftAddressRingAddress( String(addresses.right ?? "").toUpperCase(), String(addresses.left ?? "").toUpperCase(), @@ -256,6 +256,10 @@ export class FaceclawCommunicatorBridge { ); // The shared session halts on any other firmware ("incompatible-firmware"). this.communicator.setRequiredFirmwareRevisionRevision(REQUIRED_FACECLAW_FIRMWARE_VERSION); + // Guarded: an older framework build may not export it yet. + if (addresses.ringRole && typeof this.communicator.setDirectRingRoleRole === "function") { + this.communicator.setDirectRingRoleRole(addresses.ringRole); + } this.listenerProxy = SessionListener.new() as SessionListener; this.listenerProxy.bridge = this; this.communicator.setListenerListener(this.listenerProxy); diff --git a/app/native/faceclaw-communicator.ts b/app/native/faceclaw-communicator.ts index 6b58f7fb..a459d348 100644 --- a/app/native/faceclaw-communicator.ts +++ b/app/native/faceclaw-communicator.ts @@ -169,7 +169,7 @@ export class FaceclawCommunicatorBridge { private readonly firmwareInfoListeners = new Set<(info: FirmwareInfo) => void>(); private readonly previewAnimationListeners = new Set<() => void>(); - constructor(addresses: { right: string; left: string; ring?: string }) { + constructor(addresses: { right: string; left: string; ring?: string; ringRole?: string }) { const context = Utils.android.getApplicationContext(); if (!context) throw new Error("Android application context unavailable"); @@ -181,6 +181,8 @@ export class FaceclawCommunicatorBridge { ); // The shared session halts on any other firmware ("incompatible-firmware"). this.communicator.setRequiredFirmwareRevision(REQUIRED_FACECLAW_FIRMWARE_VERSION); + // Which R1 role the direct ring link claims; only matters with a ring address. + if (addresses.ringRole) this.communicator.setDirectRingRole(addresses.ringRole); this.listenerProxy = new com.faceclaw.app.FaceclawBleCommunicatorListener({ onStateChange: (phase: string, status: string) => { const state = { diff --git a/app/native/ring-status.ts b/app/native/ring-status.ts new file mode 100644 index 00000000..43c115d3 --- /dev/null +++ b/app/native/ring-status.ts @@ -0,0 +1,158 @@ +import { Utils } from "@nativescript/core"; + +declare const com: any; + +/** + * R1 ring diagnostics (Developer > Debug tests > Ring status). Session-side + * state comes from the active communicator; the phone's own Bluetooth view of + * the ring (bond, GATT/ACL link) is queried separately so it is available + * even with no session or with the direct ring link disabled. + */ + +/** GlassesSessionCore.getRingStatus. Ages are ms before now, -1 = never. */ +export type RingSessionStatus = { + directEnabled: boolean; + ringAddress: string; + glassesConnected: boolean; + sessionReady: boolean; + directConnected: boolean; + directNotificationsReady: boolean; + directConnectCount: number; + directStateAgeMs: number; + directBattery: number; + lastDirectNotifyAgeMs: number; + lastDirectInputAgeMs: number; + lastDirectInput: string; + glassesRingBattery: number; + glassesRingBatteryAgeMs: number; + lastGlassesInputAgeMs: number; + lastGlassesInput: string; + lastDirectError: string; + /** Ring MAC as the glasses reported it (wire byte order, hex), "" if not yet seen. */ + glassesRingMac: string; + glassesRingName: string; + lastGlassesReport: string; + lastGlassesReportAgeMs: number; + lastCommand: string; + lastCommandAgeMs: number; + lastCommandResultR: string; + lastCommandResultL: string; + /** Which ring role the direct link claims: "phone" or "glasses". */ + directRole: string; + /** Glasses role only: the link is temporarily in the phone role for a health pull. */ + healthWindowActive: boolean; + /** Outcome of the last health pull ("completed, 12 pages", "aborted, 0 pages", ...), "" if none. */ + lastHealthPull: string; + lastHealthPullAgeMs: number; + /** Decoded health records not yet stored by the TypeScript ingest. */ + heldHealthRecords: number; + /** Glasses role only: what the ring made of our legacy pair-auth this connection ("" = not sent). */ + directGlassesAuth: string; + directGlassesAuthAgeMs: number; + lastRingCommand: string; + lastRingCommandAgeMs: number; + lastRingCommandResult: string; + /** Last direct-link notification nothing decoded: characteristic prefix and hex. */ + lastDirectRaw: string; + lastDirectRawAgeMs: number; +}; + +/** + * EXPERIMENTAL glasses-side ring link control (sid 0x80 pair manager): + * "disconnect" drops the glasses' ring link, "release" also clears their + * connect mode (may hold off auto-reconnect), "unpair" makes them forget the + * ring, "connect" hands the ring back. + */ +export type GlassesRingLinkAction = "disconnect" | "release" | "unpair" | "connect"; + +/** + * EXPERIMENTAL ring-side binding commands over the direct link (see + * GlassesSessionCore.sendRingConfigCommand). "bind" and "unbind" combine the + * ring and glasses halves in the official app's order. + */ +export type RingConfigAction = + | "bind" + | "unbind" + | "pair-auth" + | "targets-glasses" + | "targets-clear" + | "touch-on" + | "touch-off" + | "remove-ring"; + +export type RingSystemBluetoothState = { + address: string; + bonded?: boolean; + gattConnected?: boolean; + aclConnected?: boolean; + name?: string | null; + error?: string; +}; + +function activeCommunicator(): any { + if (!global.isAndroid) return null; + try { + return com.faceclaw.app.FaceclawBleCommunicator.getActive(); + } catch { + return null; + } +} + +/** Null when there is no active glasses session (or on iOS). */ +export function getRingSessionStatus(): RingSessionStatus | null { + const active = activeCommunicator(); + if (!active) return null; + try { + return JSON.parse(String(active.getRingStatus())) as RingSessionStatus; + } catch (error) { + console.warn(`getRingStatus failed: ${error}`); + return null; + } +} + +/** Null on iOS or when the query itself fails. */ +export function getRingSystemBluetoothState(address: string): RingSystemBluetoothState | null { + if (!global.isAndroid) return null; + try { + const json = com.faceclaw.app.FaceclawBleCommunicator.getSystemBluetoothStateJson( + Utils.android.getApplicationContext(), address); + return JSON.parse(String(json)) as RingSystemBluetoothState; + } catch (error) { + console.warn(`getSystemBluetoothStateJson failed: ${error}`); + return null; + } +} + +/** False when there is no session or the command could not be queued. */ +export function setGlassesRingLink(action: GlassesRingLinkAction, fallbackAddress: string, fallbackName: string): boolean { + const active = activeCommunicator(); + if (!active) return false; + try { + return Boolean(active.setGlassesRingLink(action, fallbackAddress, fallbackName)); + } catch (error) { + console.warn(`setGlassesRingLink failed: ${error}`); + return false; + } +} + +/** A one-line outcome for the UI. */ +export function sendRingConfigCommand(action: RingConfigAction, fallbackAddress: string, fallbackName: string): string { + const active = activeCommunicator(); + if (!active) return "not sent: no glasses session"; + try { + return String(active.sendRingConfigCommand(action, fallbackAddress, fallbackName)); + } catch (error) { + console.warn(`sendRingConfigCommand failed: ${error}`); + return `failed: ${error}`; + } +} + +/** + * The R1's advertised name, "EVEN R1_" plus the last three address bytes + * (e.g. FF:AA:F1:F6:7E:28 -> "EVEN R1_F67E28"). The glasses store it with the + * ring's MAC when told to connect. + */ +export function defaultRingName(address: string): string { + const hex = address.replace(/[^0-9a-fA-F]/g, "").toUpperCase(); + return hex.length === 12 ? `EVEN R1_${hex.slice(6)}` : ""; +} diff --git a/app/ui/dashboard-settings.ts b/app/ui/dashboard-settings.ts index 0e94e5af..69381c2e 100644 --- a/app/ui/dashboard-settings.ts +++ b/app/ui/dashboard-settings.ts @@ -834,17 +834,24 @@ export const showBleBandwidthSetting = new ConfigSettingBoolean({ "Show Bluetooth messages and bytes sent, throughput, acknowledged display fps, and bytes per frame at the bottom of the phone screen. Rates use a five-second window; bytes include control traffic and protocol framing.", }); -export type RingConnectionMode = "glasses" | "direct"; +/** + * How the phone talks to the R1. The ring has one phone role (health sync) and + * one glasses role (gestures, battery pushes), so "health" and "direct" are + * the two ways a phone link can be useful; see + * GlassesSessionCore.setDirectRingRole and notes/ring-link-control.md. + */ +export type RingConnectionMode = "glasses" | "health" | "direct"; export const ringConnectionModeSetting = new ConfigSettingEnum({ id: "ring-connection-mode", label: "Ring connection", storageKey: "developer.ringConnectionMode", defaultValue: "glasses", - values: ["glasses", "direct"], - formatValue: (value) => (value === "direct" ? "Direct" : "Only via glasses"), + values: ["glasses", "health", "direct"], + formatValue: (value) => + value === "direct" ? "Direct to phone" : value === "health" ? "Via glasses + health sync" : "Only via glasses", description: - "How R1 ring input reaches the phone. Only via glasses: the ring's own link to the glasses carries its gestures, and the phone never opens a Bluetooth connection to the ring. Direct: also connect to the ring from the phone (currently unreliable). Takes effect on the next connection to the glasses.", + "How the R1 ring reaches the phone. Only via glasses: the glasses relay the ring's gestures and the phone never connects to it. Via glasses + health sync: the same, plus the phone connects to the ring to sync health data. Direct to phone (experimental): the phone takes the ring over from the glasses and gets its gestures and battery itself; the glasses lose ring input. Health still syncs, but each sync (on opening Health, and at :01 and :31) pauses ring gestures for up to a minute while the phone briefly reconnects to the ring in its health role. Leaving Direct hands the ring back to the glasses. Takes effect on the next connection to the glasses.", }); // "whisper" (no "onboard-" prefix) is OpenAI's CLOUD realtime model diff --git a/app/ui/dashboard/settings-menus.ts b/app/ui/dashboard/settings-menus.ts index d75edd82..ff57b84a 100644 --- a/app/ui/dashboard/settings-menus.ts +++ b/app/ui/dashboard/settings-menus.ts @@ -222,8 +222,8 @@ function settingsSections(): SettingsSection[] { { label: "Developer", items: [ - // Whether the phone opens its own BLE link to the R1 ring; the - // glasses relay ring gestures either way. Applied at connect time. + // Whether and how the phone opens its own BLE link to the R1 ring. + // Applied at connect time. enumSettingMenuItem(ringConnectionModeSetting), toggleSettingMenuItem(saveVoiceRecordingsSetting), toggleSettingMenuItem(firmwareDebugFlagsSetting), diff --git a/app/version.ts b/app/version.ts index 41655119..c24da02f 100644 --- a/app/version.ts +++ b/app/version.ts @@ -1,2 +1,2 @@ -export const FACECLAW_VERSION = "0.8.6-pre"; +export const FACECLAW_VERSION = "0.8.6"; export const USER_AGENT = "Faceclaw/"+FACECLAW_VERSION; diff --git a/evenhub-extensions/README.md b/evenhub-extensions/README.md index a66250c8..0cf9d007 100644 --- a/evenhub-extensions/README.md +++ b/evenhub-extensions/README.md @@ -14,7 +14,7 @@ timeout, window lifecycle events, voice-assistant tools, and the user's API keys (with their consent). In the stock Even app the extensions are absent, and the app runs as usual. -- [API reference](docs/api/README.md) +- [API reference](https://github.com/jimrandomh/faceclaw/blob/main/evenhub-extensions/docs/api/README.md) ## Install @@ -104,7 +104,7 @@ If you use the global directly and never import the package, add it to ## API overview -The [API reference](docs/api/README.md) documents every member in full. +The [API reference](https://github.com/jimrandomh/faceclaw/blob/main/evenhub-extensions/docs/api/README.md) documents every member in full. | Member | What it does | | --- | --- | diff --git a/evenhub-extensions/package.json b/evenhub-extensions/package.json index 2ac15741..dc610ff2 100644 --- a/evenhub-extensions/package.json +++ b/evenhub-extensions/package.json @@ -1,6 +1,6 @@ { "name": "@faceclaw/evenhub-extensions", - "version": "0.1.0", + "version": "0.8.6", "description": "Types and a helper for EvenHub apps to detect Faceclaw and use its extension APIs on the Even Realities G2 glasses.", "license": "MIT", "repository": { diff --git a/native/kotlin/migrated-java-sources.json b/native/kotlin/migrated-java-sources.json index 955b1e4e..e20c60a5 100644 --- a/native/kotlin/migrated-java-sources.json +++ b/native/kotlin/migrated-java-sources.json @@ -406,5 +406,9 @@ { "java": "com/faceclaw/app/util/InterruptibleSleep.java", "kotlin": "native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/util/Concurrency.kt" + }, + { + "java": "com/faceclaw/app/g2protocol/RingProtocol.java", + "kotlin": "native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/RingProtocol.kt" } ] diff --git a/native/kotlin/shared/src/androidMain/kotlin/com/faceclaw/app/PlatformUtil.android.kt b/native/kotlin/shared/src/androidMain/kotlin/com/faceclaw/app/PlatformUtil.android.kt index 1af070c1..7e1e63f9 100644 --- a/native/kotlin/shared/src/androidMain/kotlin/com/faceclaw/app/PlatformUtil.android.kt +++ b/native/kotlin/shared/src/androidMain/kotlin/com/faceclaw/app/PlatformUtil.android.kt @@ -28,6 +28,10 @@ actual fun formatLocalTime(epochMs: Long, pattern: String): String { return format.format(Date(epochMs)) } +actual fun localUtcOffsetMs(epochMs: Long): Int = java.util.TimeZone.getDefault().getOffset(epochMs) + +actual fun localTimeZoneId(): String = java.util.TimeZone.getDefault().id + actual object PlatformLog { actual fun i(tag: String, message: String) { android.util.Log.i(tag, message) diff --git a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/BleProtocol.kt b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/BleProtocol.kt index e52379ff..16fa3610 100644 --- a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/BleProtocol.kt +++ b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/BleProtocol.kt @@ -22,10 +22,36 @@ class BleProtocol { const val RENDER_NOTIFY_UUID: String = "00002760-08c2-11e1-9073-0e8ac72e6402" - const val R1_PHONE_NOTIFY_CHAR_UUID: String = "bae80011-4f05-4503-8e65-3af1f7329d1f" + // R1 ring, vendor service bae80001-4f05-4503-8e65-3af1f7329d1f. The service + // holds two write/notify pairs: bae80010 (write) + bae80011 (notify), and + // bae80012 (write) + bae80013 (notify). The health-data protocol + // (RingProtocol) rides the SECOND pair. The first is the legacy channel + // the glasses use: enabling its CCCD gives a link the ring's glasses + // role, and the ring sends gestures and battery there (RingProtocol's + // legacy-channel section). + const val R1_LEGACY_NOTIFY_CHAR_UUID: String = "bae80011-4f05-4503-8e65-3af1f7329d1f" + + /** Legacy-channel writes (write without response), e.g. the glasses' 00 35 88 00. */ + const val R1_LEGACY_WRITE_CHAR_UUID: String = "bae80010-4f05-4503-8e65-3af1f7329d1f" const val R1_NOTIFY_CHAR_UUID: String = "bae80013-4f05-4503-8e65-3af1f7329d1f" + /** + * Where health-data requests and page ACKs are written. Properties are + * 0x04 (write without response), so writes use ConnectionOptions.WRITE_MODE + * (WITHOUT_RESPONSE) — which is also what the reference capture shows + * (ATT opcode 0x52 Write Command, never 0x12 Write Request). + * + * Resolved from the phone's own cached GATT database, not guessed: the + * bugreport taken alongside the capture contains a [gatt_cache_c73eb8f9c7c5] + * block (keyed by the ring's MAC C7:3E:B8:F9:C7:C5) listing + * Characteristic: declaration_handle=0x0014, value_handle=0x0015, + * uuid=bae80012-4f05-4503-8e65-3af1f7329d1f, prop=0x04 + * and 0x0015 is exactly the ATT handle every protocol write in the capture + * targets. See knowledge/staging/faceclaw-ring-protocol-implement-return.md. + */ + const val R1_WRITE_CHAR_UUID: String = "bae80012-4f05-4503-8e65-3af1f7329d1f" + const val PRELUDE_ACK_SID: Int = 0x01 const val PRELUDE_ACK_MAGIC: Int = 156 @@ -42,6 +68,18 @@ class BleProtocol { private const val SECURITY_AUTH_CMD: Int = 4 + // DevCfgDataPackage ring commands on sid 0x80 (dev_config_protocol / + // dev_pair_manager). Wire shapes from g2-kit-unofficial's generated + // protos; handler behavior only from openCFW's decompilation + // (pb_service_pair_mgr.c) - not captured from the Even app and not + // hardware-verified. + private const val DEV_CFG_RING_CONNECT_INFO_CMD: Int = 6 + private const val DEV_CFG_DISCONNECT_INFO_CMD: Int = 8 + private const val DEV_CFG_UNPAIR_INFO_CMD: Int = 9 + + /** sid 0x91 RingDataPackage: glasses-side ring events (g2.ring). */ + const val SID_RING_DATA: Int = 0x91 + const val SID_APP_LAUNCH: Int = 0x01 const val SID_EVENHUB: Int = 0xe0 @@ -170,6 +208,12 @@ class BleProtocol { const val EVENT_HEAD_UP: Int = 12 + /** Faceclaw/18: R1 touch-down, before the gesture is known (R1 2.3.0+, wire type 10). */ + const val EVENT_RING_PRESS: Int = 14 + + /** CFW's SysEvent for an R1 wire type it has no mapping for; diagnostics only. */ + const val EVENT_RING_UNKNOWN: Int = 127 + /** Faceclaw/38: IMU head-down (the head returning after a lift), forwarded while a page is up. */ const val EVENT_HEAD_DOWN: Int = 15 @@ -491,6 +535,99 @@ class BleProtocol { ) } + /** + * DISCONNECT_INFO(8) with DisconnectInfo{dev=RING(0), ringMac}: ask the glasses to drop + * their link to the ring. In openCFW's decompilation the handler ignores the payload, + * resets the ring retry counter and posts the ring-disconnect event, leaving the stored + * ring target alone (unlike RING_CONNECT_INFO, which overwrites it). + */ + @JvmStatic + fun buildRingDisconnectRequest(magic: Int, ringMac: ByteArray): ByteArray { + return concat( + CollectionUtils.listOf( + encodeVarintField(1, DEV_CFG_DISCONNECT_INFO_CMD), + encodeVarintField(2, magic), + encodeMessageField(7, concat(CollectionUtils.listOf( + encodeVarintField(1, 0), + encodeBytesField(2, ringMac), + ))), + ) + ) + } + + /** + * UNPAIR_INFO(9) with UnpairInfo{dev=RING(0), ringMac}: the glasses forget their stored ring + * pairing. Never dev=RING_GLASSES(2): openCFW's decompilation shows that also enters OTA + * mode and unpairs the phone from the glasses. The handler uses the MAC only when it is + * exactly 6 bytes; whether it compares it against the stored ring is unknown. + */ + @JvmStatic + fun buildRingUnpairRequest(magic: Int, ringMac: ByteArray): ByteArray { + return concat( + CollectionUtils.listOf( + encodeVarintField(1, DEV_CFG_UNPAIR_INFO_CMD), + encodeVarintField(2, magic), + encodeMessageField(8, concat(CollectionUtils.listOf( + encodeVarintField(1, 0), + encodeBytesField(2, ringMac), + ))), + ) + ) + } + + /** + * RING_CONNECT_INFO(6) with RingInfo{connectRing, ringMac, ringName}. connectRing is + * declared `bytes` but read by the firmware as one byte. Every call overwrites the glasses' + * ring target with ringMac/ringName, so pass the target the glasses themselves reported + * when one is known. Only the ring-owning temple acts on connect=true; the firmware + * ignores connect requests closer than ~20 s apart. + */ + @JvmStatic + fun buildRingConnectRequest(magic: Int, connect: Boolean, ringMac: ByteArray, ringName: ByteArray): ByteArray { + return concat( + CollectionUtils.listOf( + encodeVarintField(1, DEV_CFG_RING_CONNECT_INFO_CMD), + encodeVarintField(2, magic), + encodeMessageField(5, concat(CollectionUtils.listOf( + encodeBytesField(1, byteArrayOf(if (connect) 1 else 0)), + encodeBytesField(2, ringMac), + encodeBytesField(3, ringName), + ))), + ) + ) + } + + /** A RingInfo (from RING_CONNECT_INFO) or RingEvent (from sid 0x91) the glasses sent. */ + class GlassesRingReport( + @JvmField val source: String, + @JvmField val ringMac: ByteArray?, + @JvmField val ringName: String, + /** connRet for RingInfo (0 = connected, 90 = timeout), eventId for RingEvent; -1 absent. */ + @JvmField val code: Int, + ) + + /** Decode a sid-0x80 RING_CONNECT_INFO frame (notification or ack), else null. */ + @JvmStatic + fun parseRingConnectInfo(pb: ByteArray?): GlassesRingReport? { + if (pb == null) return null + val root = stripTrailingCrc(pb) + if (readVarintFieldValue(root, 1, -1) != DEV_CFG_RING_CONNECT_INFO_CMD) return null + val info = readFieldBytes(root, 5) ?: return null + val name = readFieldBytes(info, 3) + return GlassesRingReport("connect-info", readFieldBytes(info, 2), + if (name == null) "" else name.decodeToString(), readVarintFieldValue(info, 4, -1)) + } + + /** Decode a sid-0x91 RingDataPackage EVENT(1) frame, else null. */ + @JvmStatic + fun parseRingDataEvent(pb: ByteArray?): GlassesRingReport? { + if (pb == null) return null + val root = stripTrailingCrc(pb) + if (readVarintFieldValue(root, 1, -1) != 1) return null + val event = readFieldBytes(root, 3) ?: return null + return GlassesRingReport("ring-event", readFieldBytes(event, 1), "", readVarintFieldValue(event, 2, -1)) + } + /** * True when `pb` (trailing CRC still attached) is the success notification for the * authentication request sent with `magic`: command 4, the same magic, and an EMPTY field-3 diff --git a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/ConnectionOptions.kt b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/ConnectionOptions.kt index 41609c20..069953b9 100644 --- a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/ConnectionOptions.kt +++ b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/ConnectionOptions.kt @@ -16,6 +16,13 @@ class ConnectionOptions { const val DESCRIPTOR_TIMEOUT_MS = 5_000 const val RING_DESIRED_MTU = 247 const val RING_RECONNECT_DELAY_MS = 2_000 + // Cap for the exponential backoff on repeated direct-ring connect failures. + const val RING_RECONNECT_MAX_DELAY_MS = 60_000L + // The ring connects with autoConnect=true (see SessionLink.connect's + // 3-arg overload) - Android manages that as a background reconnect rather + // than an immediate attempt, so it needs far more room than the glasses' + // direct-connect CONNECT_TIMEOUT_MS. Untuned guess, not measured. + const val RING_CONNECT_TIMEOUT_MS = 20_000 const val WRITE_TIMEOUT_MS = 2_000 const val PRELUDE_TIMEOUT_MS = 2_000 // Application security-auth exchange (sid 0x80). The success notification diff --git a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/FaceclawRingEventDecoder.kt b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/FaceclawRingEventDecoder.kt index 651f18a9..5e086a7c 100644 --- a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/FaceclawRingEventDecoder.kt +++ b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/FaceclawRingEventDecoder.kt @@ -10,57 +10,50 @@ class FaceclawRingEventDecoder { if (((raw == null) || (raw.size == 0))) { return null } - var chargerGesture: DirectRingEvent? = decodeChargerGesture(raw) - if ((chargerGesture != null)) { - return chargerGesture + var report: DirectRingEvent? = decodeRingReport(raw) + if ((report != null)) { + return report } return decodeDirectGesture(raw) } - private fun decodeChargerGesture(raw: ByteArray): DirectRingEvent? { - if ((raw.size != 11)) { + /** + * The R1's standard input report, `00 09 61 00 TYPE AUX SPEED TICK_LE32`: the same + * 11 bytes the ring sends the glasses, which CFW's gesture_fwd.c forwards as an EvenHub + * SysEvent. TYPE maps exactly as CFW maps it, and the raw fields ride along as ring + * metadata, so direct and glasses-relayed input look the same to the TypeScript side + * (including RingInputFilter's 100-tick suppression). Unmapped types become + * EVENT_RING_UNKNOWN, which is kept for diagnostics but never routed as a gesture. + */ + private fun decodeRingReport(raw: ByteArray): DirectRingEvent? { + if (raw.size != 11 || u8(raw[0]) != 0x00 || u8(raw[1]) != 0x09 || + u8(raw[2]) != 0x61 || u8(raw[3]) != 0x00) { return null } - if ( - ((((u8(raw[0]) != 0x00) || (u8(raw[1]) != 0x09)) || (u8(raw[2]) != 0x61)) || - (u8(raw[3]) != 0x00)) - ) { - return null + val type = u8(raw[4]) + val aux = u8(raw[5]) + val speed = u8(raw[6]) + val tick = (u8(raw[7]) or (u8(raw[8]) shl 8) or (u8(raw[9]) shl 16) or (u8(raw[10]) shl 24)) + .toLong() and 0xffffffffL + val label = ringReportTypeName(type) + val eventType = when (type) { + 0x00 -> BleProtocol.EVENT_RING_LONG_PRESS + 0x01 -> BleProtocol.EVENT_CLICK + 0x02 -> BleProtocol.EVENT_DOUBLE_CLICK + 0x04 -> BleProtocol.EVENT_SCROLL_TOP + 0x05 -> BleProtocol.EVENT_SCROLL_BOTTOM + 0x08 -> BleProtocol.EVENT_RING_LONG_PRESS_RELEASE + 0x09 -> BleProtocol.EVENT_SHORT_THEN_LONG_PRESS + 0x0a -> BleProtocol.EVENT_RING_PRESS + else -> BleProtocol.EVENT_RING_UNKNOWN } - var code: Int = u8(raw[4]) - var param: Int = (u8(raw[5]) or (u8(raw[6]) shl 8)) - var tick: Long = - ((((u8(raw[7]) or (u8(raw[8]) shl 8)) or (u8(raw[9]) shl 16)) or - (u8(raw[10]) shl 24)) - .toLong() and 0xffffffffL) - var detail: String = - "code=0x${code.toString(16).padStart(2, '0')}(${chargerCodeName(code)}) param=0x${param.toString(16).padStart(4, '0')} tick=$tick" - when (code) { - 0x00 -> { - return event(BleProtocol.EVENT_RING_LONG_PRESS, "LONG_PRESS", detail) - } - 0x01 -> { - return event(BleProtocol.EVENT_CLICK, "TAP", detail) - } - 0x02 -> { - return event(BleProtocol.EVENT_DOUBLE_CLICK, "DOUBLE_TAP", detail) - } - 0x04 -> { - return event(BleProtocol.EVENT_SCROLL_TOP, "SWIPE_UP", detail) - } - 0x05 -> { - return event(BleProtocol.EVENT_SCROLL_BOTTOM, "SWIPE_DOWN", detail) - } - 0x08 -> { - return event( - BleProtocol.EVENT_RING_LONG_PRESS_RELEASE, - "LONG_PRESS_RELEASE", - detail, - ) - } - else -> { - return null - } + val detail = "type=0x${type.toString(16).padStart(2, '0')}($label) " + + "aux=0x${aux.toString(16).padStart(2, '0')} speed=0x${speed.toString(16).padStart(2, '0')} tick=$tick" + return event(eventType, label, detail).also { + it.event.ringTick = tick + it.event.ringType = type + it.event.ringAux = aux + it.event.ringSpeed = speed } } @@ -96,29 +89,17 @@ class FaceclawRingEventDecoder { return DirectRingEvent(event, label, detail) } - private fun chargerCodeName(code: Int): String { - when (code) { - 0x00 -> { - return "LONG_PRESS" - } - 0x01 -> { - return "TAP" - } - 0x02 -> { - return "DOUBLE_TAP" - } - 0x04 -> { - return "SWIPE_UP" - } - 0x05 -> { - return "SWIPE_DOWN" - } - 0x08 -> { - return "LONG_PRESS_RELEASE" - } - else -> { - return "unknown" - } + private fun ringReportTypeName(type: Int): String { + return when (type) { + 0x00 -> "LONG_PRESS" + 0x01 -> "TAP" + 0x02 -> "DOUBLE_TAP" + 0x04 -> "SWIPE_UP" + 0x05 -> "SWIPE_DOWN" + 0x08 -> "LONG_PRESS_RELEASE" + 0x09 -> "TAP_THEN_HOLD" + 0x0a -> "TOUCH_DOWN" + else -> "UNKNOWN" } } diff --git a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/MessageBuilder.kt b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/MessageBuilder.kt index c82180d2..485565c9 100644 --- a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/MessageBuilder.kt +++ b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/MessageBuilder.kt @@ -43,6 +43,22 @@ class MessageBuilder { ) } + /** A sid-0x80 DevCfgDataPackage ring command (see BleProtocol.buildRingConnectRequest). */ + fun ringLinkCommand(label: String, leftArm: Boolean, build: (Int) -> ByteArray): OutboundMessage { + var magic: Int = magicPool.allocate() + return OutboundMessage( + "ring-link", + (label + (if (leftArm) " L" else " R")), + BleProtocol.SID_SECURITY_AUTH, + BleProtocol.FLAG_SECURITY_AUTH, + magic, + build(magic), + ACK_TIMEOUT_MS, + -1, + leftArm, + ) + } + fun shutdown(exitMode: Int): OutboundMessage { var magic: Int = magicPool.allocate() return OutboundMessage( diff --git a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/RingProtocol.kt b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/RingProtocol.kt new file mode 100644 index 00000000..b9f6c264 --- /dev/null +++ b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/RingProtocol.kt @@ -0,0 +1,1047 @@ +package com.faceclaw.app + +import kotlin.jvm.JvmField +import kotlin.jvm.JvmStatic + +/** + * RingProtocol: frame build/parse plus per-record decoding for the Even R1 + * ring's health-data channel. Does _not_ include code for actually sending + * anything; for that, see GlassesSessionRing.kt (same split as BleProtocol). + * + * Platform-neutral and free of Android imports; the Java-facing surface + * (static members, public fields) is kept so the JVM self-test in + * tests/kotlin and the TypeScript health ingest read it unchanged. + * + * **This is a different protocol from BleProtocol's.** The glasses speak + * an `aa21` envelope with a CRC-16/CCITT; the ring speaks a 15-byte + * `64 .. 64` header with a CRC-32C. Nothing is shared between them, and + * in particular [crc32] must never be pointed at a glasses frame. + * + * Wire format (offsets from the start of the ATT value): + * ``` + * off size field + * 0 1 FLAG 0x00 normally; 0x01 = fragmented, a continuation follows + * 1 4 CRC32 little-endian, over bytes [5:] of the *reassembled* frame + * 5 1 0x64 constant magic + * 6 1 CHAN 0x01 device/system, 0x02 health data + * 7 1 0x64 constant magic + * 8 1 SEQ phone-side: one counter shared by both channels + * 9 1 0x00 constant + * 10 1 KIND 0x00 REQ, 0x01 ACK, 0x02 DATA, 0x03 RSP + * 11 1 CMD_HI + * 12 1 CMD_LO + * 13 2 PLEN little-endian; equals (total frame length - 5) + * 15 .. PAYLOAD PLEN - 10 bytes; PAYLOAD[0:2] is a free per-message nonce + * ``` + * + * Protocol spec and its evidence: + * knowledge/staging/faceclaw-ring-protocol-decode-return.md in the TLC + * knowledge base. Everything below is implemented from that document; the + * places where it is explicitly *not* solved are marked UNSOLVED and are + * surfaced raw rather than guessed at. + */ +class RingProtocol private constructor() { + companion object { + /** CRC-32C polynomial, MSB-first / non-reflected form. Not CRC-32 (0x04C11DB7). */ + private const val CRC32C_POLY: Int = 0x1EDC6F41 + + const val MAGIC: Int = 0x64 + const val HEADER_LEN: Int = 15 + /** A continuation frame is FLAG(1) + CRC32(4) and then raw remainder bytes. */ + const val CONTINUATION_PREFIX_LEN: Int = 5 + + const val FLAG_PLAIN: Int = 0x00 + const val FLAG_FRAGMENTED: Int = 0x01 + + const val CHAN_DEVICE: Int = 0x01 + const val CHAN_HEALTH: Int = 0x02 + + const val KIND_REQ: Int = 0x00 + const val KIND_ACK: Int = 0x01 + const val KIND_DATA: Int = 0x02 + const val KIND_RSP: Int = 0x03 + + /** Every health record type uses CMD_LO = 0x01; the type lives in CMD_HI. */ + const val CMD_LO_HEALTH: Int = 0x01 + const val CMD_HI_HEART_RATE: Int = 0x01 + const val CMD_HI_SPO2: Int = 0x02 + const val CMD_HI_HRV: Int = 0x04 + const val CMD_HI_STEPS: Int = 0x05 + const val CMD_HI_SLEEP: Int = 0x06 + + /** Device/system channel commands all have CMD_HI = 0x00. */ + const val CMD_HI_DEVICE: Int = 0x00 + const val CMD_LO_PAGE_ACK: Int = 0x7E + + /** + * System-channel (00:xx) commands that configure the ring's binding. + * Subcommand numbers and handler behavior are from openCFW's R1 + * decompilation (r1/src/r1_dispatch.c, r1/docs/correlation/ + * CONNECTION-CONTROL-CORRELATION.md); g2-kit-unofficial's ring.ts names + * the same table. Only pairAuth and advStart have been seen in a capture + * of Even's app. + */ + const val CMD_LO_TOUCH_SWITCH: Int = 0x07 + const val CMD_LO_PAIR_AUTH: Int = 0x08 + const val CMD_LO_ADV_START: Int = 0x0A + const val CMD_LO_REMOVE_RING_NOTIFY: Int = 0x82 + /** touchSwitch selector for the glasses touch source; selector 1 (phone) is diagnostic-only. */ + const val TOUCH_SWITCH_SELECTOR_GLASSES: Int = 2 + + /** + * The five health pulls, in the order Even's own app issues them: + * heart rate, HRV, SpO2, sleep, steps. That order is identical in all four + * sync bursts of the reference capture. (It is NOT the order the spec + * document happens to list them in — that is just its presentation order.) + * Whether the order matters to the ring is untested; matching the app is + * the cheapest way not to find out the hard way. + */ + @JvmField val HEALTH_COMMANDS: IntArray = intArrayOf( + CMD_HI_HEART_RATE, + CMD_HI_HRV, + CMD_HI_SPO2, + CMD_HI_SLEEP, + CMD_HI_STEPS, + ) + + /** Returned by anchor/timestamp accessors when the value is not known. */ + const val UNKNOWN_TIME: Long = -1L + + /** + * Bytes R1 firmware 2.3.x appends to every health DATA page, after the + * last group/bucket. Seen on 2.3.0.0005 and 2.3.2.0008: every one of + * the 30 hourly and activity pages journaled 2026-10-06..11-01 carries + * it (values `6e050000`, `00000000`, `ad5e0000`; meaning unknown). + * Firmware 2.0.7.0003 sent none (notes/ring-health-live-validation.md), + * so the decoders accept a page with or without it. The group or + * bucket count is explicit, so the two lengths cannot be confused. + */ + const val HEALTH_PAGE_TRAILER_LEN: Int = 4 + + private val JOURNAL_RECEIVED_AT = Regex("\"receivedAtMs\":(\\d+)") + private val JOURNAL_RAW = Regex("\"raw\":\"([0-9a-fA-F]+)\"") + + private val EMPTY = ByteArray(0) + + // ------------------------------------------------------------------ + // CRC + // ------------------------------------------------------------------ + + /** + * CRC-32C over `data[from, to)`: polynomial 0x1EDC6F41, MSB-first, + * init 0, no reflection, no final xor. Verified against 188/188 frames in + * the reference capture. + */ + @JvmStatic + fun crc32(data: ByteArray, from: Int, to: Int): Int { + var crc = 0 + for (i in from until to) { + crc = crc xor ((data[i].toInt() and 0xff) shl 24) + for (bit in 0 until 8) { + crc = if ((crc and 0x80000000.toInt()) != 0) { + (crc shl 1) xor CRC32C_POLY + } else { + crc shl 1 + } + } + } + return crc + } + + @JvmStatic + fun crc32(data: ByteArray?): Int = if (data == null) 0 else crc32(data, 0, data.size) + + // ------------------------------------------------------------------ + // Frame building + // ------------------------------------------------------------------ + + /** + * Build one complete, CRC-correct frame. Fragmentation is a receive-side + * concern only: nothing we send approaches the 244-byte ATT ceiling. + */ + @JvmStatic + fun buildFrame(chan: Int, kind: Int, cmdHi: Int, cmdLo: Int, seq: Int, payload: ByteArray?): ByteArray { + val body = payload ?: EMPTY + val total = HEADER_LEN + body.size + val frame = ByteArray(total) + frame[0] = FLAG_PLAIN.toByte() + frame[5] = MAGIC.toByte() + frame[6] = (chan and 0xff).toByte() + frame[7] = MAGIC.toByte() + frame[8] = (seq and 0xff).toByte() + frame[9] = 0x00 + frame[10] = (kind and 0xff).toByte() + frame[11] = (cmdHi and 0xff).toByte() + frame[12] = (cmdLo and 0xff).toByte() + val plen = total - 5 + frame[13] = (plen and 0xff).toByte() + frame[14] = ((plen ushr 8) and 0xff).toByte() + body.copyInto(frame, HEADER_LEN) + writeIntLe(frame, 1, crc32(frame, 5, total)) + return frame + } + + /** + * A request frame. Health requests carry no arguments at all: the payload + * is the 2-byte nonce and nothing else. + * + * The nonce is a free per-message id — it is covered by the frame CRC but + * is not content-derived, so any value works. It is encoded little-endian. + */ + @JvmStatic + fun buildRequest(chan: Int, cmdHi: Int, cmdLo: Int, seq: Int, nonce: Int): ByteArray { + return buildFrame(chan, KIND_REQ, cmdHi, cmdLo, seq, nonceBytes(nonce)) + } + + /** One of the five health pulls; see [HEALTH_COMMANDS]. */ + @JvmStatic + fun buildHealthRequest(cmdHi: Int, seq: Int, nonce: Int): ByteArray { + return buildRequest(CHAN_HEALTH, cmdHi, CMD_LO_HEALTH, seq, nonce) + } + + /** + * The per-page acknowledgement: command 00:7E on the DEVICE channel, + * echoing the sequence number of the DATA page being acknowledged. + * + * Payload is 12 bytes: the usual 2-byte nonce, then + * `02 00 `, then five zero bytes. (Note + * the echoed page seq is at payload offset 6, after the nonce — a spec doc + * that describes the payload as starting at `02` is off by the nonce.) + * + * The frame's own SEQ is the phone's shared counter, NOT the echoed page + * seq: across 20 ACKs in the reference capture the two are always different, + * and the header SEQ continues the same +1 sequence used by every other + * phone-to-ring write on both channels. + * + * Whether the ring actually *requires* this is untested — Even's app + * sends one for every page without exception (20/20), but no page has ever + * been deliberately left unacknowledged to see what happens. + */ + @JvmStatic + fun buildPageAck(seq: Int, nonce: Int, ackedCmdHi: Int, ackedCmdLo: Int, pageSeq: Int): ByteArray { + val payload = ByteArray(12) + payload[0] = (nonce and 0xff).toByte() + payload[1] = ((nonce ushr 8) and 0xff).toByte() + payload[2] = 0x02 + payload[3] = (ackedCmdHi and 0xff).toByte() + payload[4] = (ackedCmdLo and 0xff).toByte() + payload[5] = 0x00 + payload[6] = (pageSeq and 0xff).toByte() + // payload[7..11] stay zero. + return buildFrame(CHAN_DEVICE, KIND_ACK, CMD_HI_DEVICE, CMD_LO_PAGE_ACK, seq, payload) + } + + /** + * The ring's phone-direction model checksum: the two bytes that sit + * where [buildFrame]'s callers put a "nonce". It is a CRC-16 (Nordic + * crc16_compute, init 0xFFFF) over header bytes 5-8 and 10-14 (skipping + * the high byte of the 16-bit serial) and then the arguments. Verified + * against five captured Even-app frames; see GlassesRingLinkTest. + * + * Most of our frames still carry a counter there instead and the ring + * answers them anyway, so the ring does not seem to enforce it; the + * binding commands below compute it so they do not depend on that. + */ + @JvmStatic + fun phoneChecksum(chan: Int, seq: Int, kind: Int, cmdHi: Int, cmdLo: Int, args: ByteArray): Int { + val plen = HEADER_LEN + 2 + args.size - 5 + val header = byteArrayOf( + MAGIC.toByte(), chan.toByte(), MAGIC.toByte(), seq.toByte(), + kind.toByte(), cmdHi.toByte(), cmdLo.toByte(), plen.toByte(), (plen ushr 8).toByte(), + ) + var crc = 0xffff + for (b in header + args) { + crc = ((crc ushr 8) or (crc shl 8)) and 0xffff + crc = crc xor (b.toInt() and 0xff) + crc = crc xor ((crc and 0xff) ushr 4) + crc = crc xor ((crc shl 12) and 0xffff) + crc = crc xor (((crc and 0xff) shl 5) and 0xffff) + } + return crc + } + + /** A frame whose two leading payload bytes are the [phoneChecksum] of `args`. */ + @JvmStatic + fun buildCheckedFrame(chan: Int, kind: Int, cmdHi: Int, cmdLo: Int, seq: Int, args: ByteArray): ByteArray { + val crc = phoneChecksum(chan, seq, kind, cmdHi, cmdLo, args) + return buildFrame(chan, kind, cmdHi, cmdLo, seq, nonceBytes(crc) + args) + } + + /** + * pairAuth (00:08) with role byte 1: claims the ring's phone role, after + * which the ring asks for link security (bonding) and starts answering + * requests. For seq 1 this is byte-identical to Even's captured frame. + */ + @JvmStatic + fun buildPairAuth(seq: Int): ByteArray = + buildCheckedFrame(CHAN_DEVICE, KIND_REQ, CMD_HI_DEVICE, CMD_LO_PAIR_AUTH, seq, byteArrayOf(0x01)) + + /** + * advStart (00:0A): the two glasses addresses the ring will accept as + * its glasses peer, each in wire order (least-significant byte first). + * The ring persists them, disconnects a connected glasses peer that + * matches neither (after ~20 s), and treats a slot of all 00 or all FF + * as unset; with both unset it accepts any glasses peer. Sent with the + * REQ status byte because that is what Even's captured frames use. + */ + @JvmStatic + fun buildAdvStart(seq: Int, first: ByteArray, second: ByteArray): ByteArray { + require(first.size == 6 && second.size == 6) { "advStart targets must be 6 bytes each" } + return buildCheckedFrame(CHAN_DEVICE, KIND_REQ, CMD_HI_DEVICE, CMD_LO_ADV_START, seq, first + second) + } + + /** + * touchSwitch (00:07) SET: [selector, value]. Selector 2 opens (value 1) + * or closes (value 0) the glasses touch source; the phone selector does + * nothing in the decompiled handler. + */ + @JvmStatic + fun buildTouchSwitch(seq: Int, selector: Int, on: Boolean): ByteArray = + buildCheckedFrame(CHAN_DEVICE, KIND_DATA, CMD_HI_DEVICE, CMD_LO_TOUCH_SWITCH, seq, + byteArrayOf(selector.toByte(), if (on) 1 else 0)) + + /** + * removeRingNotify (00:82) SET, one byte: the ring clears its + * glasses-connected flag and erases both advStart targets. The retail + * handler acts on any nonempty payload; 1 is our choice. + */ + @JvmStatic + fun buildRemoveRingNotify(seq: Int): ByteArray = + buildCheckedFrame(CHAN_DEVICE, KIND_DATA, CMD_HI_DEVICE, CMD_LO_REMOVE_RING_NOTIFY, seq, byteArrayOf(0x01)) + + /** + * The outcome a ring response's status byte carries: `0x03 | code << 2` + * with code 0 ok, 1 error, 2 refused, 3 unsupported. Null when `kind` is + * not a response. + */ + @JvmStatic + fun responseResult(kind: Int): String? { + if ((kind and 0x03) != KIND_RSP) return null + return when ((kind ushr 2) and 0x03) { + 0 -> "ok" + 1 -> "error" + 2 -> "refused" + else -> "unsupported" + } + } + + // ------------------------------------------------------------------ + // Legacy (glasses-role) channel: bae80010 write / bae80011 notify + // + // Raw frames with the opcode in byte 2, not the 0x64 models above. What + // the G2 sends and what the ring answers come from g2-firmware-emulator + // (docs/r1-command88-native.md, r1-cccd-frontier.md) running the stock + // firmwares; the gesture report shape is in FaceclawRingEventDecoder. + // ------------------------------------------------------------------ + + /** + * The G2's legacy pair-auth, opcode 0x88, captured from the stock glasses + * firmware writing it right after enabling the bae80011 CCCD. The ring + * marks the link as its glasses peer and checks it against the advStart + * targets: accepted (a target matches, or none are set) answers with a + * battery report; rejected answers [LEGACY_TARGET_REJECTED] and drops the + * link about 20 s later. + */ + @JvmField val LEGACY_GLASSES_PAIR_AUTH: ByteArray = byteArrayOf(0x00, 0x35, 0x88.toByte(), 0x00) + + /** The ring's "non-target glasses connected" notice, opcode 0x96. */ + @JvmField val LEGACY_TARGET_REJECTED: ByteArray = byteArrayOf(0x00, 0x01, 0x96.toByte(), 0x00) + + /** + * The ring's battery report to its glasses peer, `00 09 8B 00 + * `: sent when a glasses pair-auth is accepted and whenever the + * percentage changes. Null for anything else. + */ + @JvmStatic + fun parseLegacyBattery(raw: ByteArray?): DeviceStatus? { + if (raw == null || raw.size != 6 || raw[0].toInt() != 0x00 || raw[1].toInt() != 0x09 || + (raw[2].toInt() and 0xff) != 0x8B || raw[3].toInt() != 0x00) return null + val battery = raw[4].toInt() and 0xff + if (battery > 100) return null + return DeviceStatus(battery, if (raw[5].toInt() != 0) 1 else 0) + } + + @JvmStatic + fun isLegacyTargetRejected(raw: ByteArray?): Boolean = + raw != null && raw.contentEquals(LEGACY_TARGET_REJECTED) + + private fun nonceBytes(nonce: Int): ByteArray { + return byteArrayOf((nonce and 0xff).toByte(), ((nonce ushr 8) and 0xff).toByte()) + } + + // ------------------------------------------------------------------ + // Frame parsing + // ------------------------------------------------------------------ + + /** True when a value could be the start of a frame (magic bytes in place). */ + @JvmStatic + fun looksLikeHeader(value: ByteArray?): Boolean { + return value != null + && value.size >= HEADER_LEN + && (value[5].toInt() and 0xff) == MAGIC + && (value[7].toInt() and 0xff) == MAGIC + } + + /** Total frame length declared by PLEN, or -1 when this is not a header. */ + @JvmStatic + fun declaredLength(value: ByteArray?): Int { + if (value == null || !looksLikeHeader(value)) { + return -1 + } + val plen = (value[13].toInt() and 0xff) or ((value[14].toInt() and 0xff) shl 8) + val total = plen + 5 + return if (total < HEADER_LEN) -1 else total + } + + /** Parse a complete (already reassembled) frame. Returns null if malformed. */ + @JvmStatic + fun parse(frame: ByteArray?): Frame? { + if (frame == null || frame.size < HEADER_LEN) { + return null + } + if ((frame[5].toInt() and 0xff) != MAGIC || (frame[7].toInt() and 0xff) != MAGIC) { + return null + } + val plen = (frame[13].toInt() and 0xff) or ((frame[14].toInt() and 0xff) shl 8) + if (plen + 5 != frame.size) { + return null + } + val storedCrc = readIntLe(frame, 1) + val actualCrc = crc32(frame, 5, frame.size) + val payload = frame.copyOfRange(HEADER_LEN, frame.size) + return Frame( + frame[0].toInt() and 0xff, + frame[6].toInt() and 0xff, + frame[8].toInt() and 0xff, + frame[10].toInt() and 0xff, + frame[11].toInt() and 0xff, + frame[12].toInt() and 0xff, + payload, + frame, + storedCrc == actualCrc, + ) + } + + // ------------------------------------------------------------------ + // Record decoding + // ------------------------------------------------------------------ + + /** + * Decode a health DATA page. Returns null when the frame is not a health + * DATA page or its body does not match the layout for its type. + */ + @JvmStatic + fun decode(frame: Frame?, receivedAtMs: Long): HealthRecord? { + if (frame == null || !frame.crcOk || !frame.isHealth() || frame.kind != KIND_DATA) { + return null + } + if (frame.cmdLo != CMD_LO_HEALTH) { + return null + } + return when (frame.cmdHi) { + CMD_HI_HEART_RATE, CMD_HI_SPO2, CMD_HI_HRV -> decodeHourly(frame, receivedAtMs) + CMD_HI_STEPS -> decodeSteps(frame, receivedAtMs) + CMD_HI_SLEEP -> decodeSleep(frame, receivedAtMs) + else -> null + } + } + + /** + * Decode the health DATA pages in a ring frame journal - the JSON lines + * `{"receivedAtMs":N,"raw":""}` the session writes before + * acknowledging each frame - received after [afterReceivedAtMs], in + * file order. Anything that is not a decodable health DATA page is + * skipped. Lets pages the ring will never send again (it counts an + * acknowledged page as synced) be stored after a decoder fix. + */ + @JvmStatic + fun decodeFrameJournal(text: String, afterReceivedAtMs: Long): List { + val records = ArrayList() + for (line in text.lineSequence()) { + val receivedAtMs = JOURNAL_RECEIVED_AT.find(line)?.groupValues?.get(1)?.toLongOrNull() ?: continue + if (receivedAtMs <= afterReceivedAtMs) continue + val raw = JOURNAL_RAW.find(line)?.groupValues?.get(1) ?: continue + if (raw.length % 2 != 0) continue + val bytes = ByteArray(raw.length / 2) { raw.substring(it * 2, it * 2 + 2).toInt(16).toByte() } + val record = try { + decode(parse(bytes), receivedAtMs) + } catch (_: Throwable) { + null + } ?: continue + records.add(record) + } + return records + } + + /** + * Heart rate / SpO2 / HRV: an hourly `[index][avg][max][min]` series. + * + * Layout follows openR1 r1_health_encode_daily_u8/u16 in r1_health.c: + * count, signed timezone minutes, day start, optional latest timestamp/value, + * then count groups, then (firmware 2.3.x only) [HEALTH_PAGE_TRAILER_LEN] + * trailing bytes. HR/SpO2 values are one byte; HRV values are two; the + * width comes from the command, never from the length, which is what + * once misdecoded a one-group HRV page as one-byte values. + */ + @JvmStatic + fun decodeHourly(frame: Frame, receivedAtMs: Long): HourlyRecord? { + val pay = frame.payload + if (pay.size < 9) { + return null + } + val count = pay[2].toInt() and 0xff + val anchor = anchorUnixSeconds(pay) + val width = if (frame.cmdHi == CMD_HI_HRV) 2 else 1 + val groupBytes = count * (1 + 3 * width) + val nonGroupBytes = pay.size - groupBytes + // 9 or 13+width without the trailer; 13 or 17+width with it. All distinct. + val trailer = if (nonGroupBytes == 9 + HEALTH_PAGE_TRAILER_LEN + || nonGroupBytes == 13 + width + HEALTH_PAGE_TRAILER_LEN) HEALTH_PAGE_TRAILER_LEN else 0 + val prefixLength = nonGroupBytes - trailer + val hasLatest = prefixLength == 13 + width + if (count > 24 || (!hasLatest && prefixLength != 9)) return null + val tag = if (hasLatest) readUInt32Le(pay, 9) else UNKNOWN_TIME + val current = if (hasLatest) readUIntLe(pay, 13, width) else -1 + var offset = prefixLength + val groups = arrayOfNulls(count) + for (i in 0 until count) { + val hourIndex = pay[offset].toInt() and 0xff + if (hourIndex >= 24) return null + offset++ + val avg = readUIntLe(pay, offset, width) + offset += width + val max = readUIntLe(pay, offset, width) + offset += width + val min = readUIntLe(pay, offset, width) + offset += width + val unix = if (anchor == UNKNOWN_TIME) UNKNOWN_TIME else anchor + hourIndex * 3600L + groups[i] = HourlyGroup(hourIndex, avg, max, min, unix) + } + @Suppress("UNCHECKED_CAST") + return HourlyRecord(frame.cmdHi, receivedAtMs, anchor, tag, current, width, groups as Array) + } + + /** + * Steps / activity buckets: `[index][v1][v2][v3]` after the record + * prefix. v1 (steps) is proven against a full-day total; v2 and v3 are + * calorie-shaped but unconfirmed, and the bucket index does NOT map to a + * known wall-clock time (see [StepsBucket]). + */ + @JvmStatic + fun decodeSteps(frame: Frame, receivedAtMs: Long): StepsRecord? { + val pay = frame.payload + if (pay.size < 9) { + return null + } + val count = pay[2].toInt() and 0xff + val bucketsEnd = 9 + count * 7 + if (count > 144 || (pay.size != bucketsEnd && pay.size != bucketsEnd + HEALTH_PAGE_TRAILER_LEN)) { + return null + } + val anchor = anchorUnixSeconds(pay) + var offset = 9 + val buckets = arrayOfNulls(count) + for (i in 0 until count) { + val index = pay[offset].toInt() and 0xff + if (index >= 144) return null + val steps = readUInt16Le(pay, offset + 1) + val v2 = readUInt16Le(pay, offset + 3) + val v3 = readUInt16Le(pay, offset + 5) + offset += 7 + buckets[i] = StepsBucket(index, steps, v2, v3) + } + @Suppress("UNCHECKED_CAST") + return StepsRecord(receivedAtMs, anchor, buckets as Array) + } + + /** + * A sleep session. The ring transmits pre-classified stages, per-stage + * totals and the session boundaries; nothing is computed phone-side. + * + * `startTs`/`endTs` are ring-relative seconds, NOT Unix + * timestamps — see [SleepRecord]. + */ + @JvmStatic + fun decodeSleep(frame: Frame, receivedAtMs: Long): SleepRecord? { + val pay = frame.payload + if (pay.size < 3) { + return null + } + val recordState = pay[2].toInt() and 0xff + val unknownA = safeRange(pay, 3, 9) + val unknownTag = if (pay.size >= 13) readUInt32Le(pay, 9) else UNKNOWN_TIME + if (recordState != 1) { + // RECSTATE 2 is the empty / end-of-list marker. + return SleepRecord( + receivedAtMs, recordState, unknownA, unknownTag, + 0, 0, 0, 0, 0, 0, 0, arrayOf()) + } + if (pay.size < 34) return null + + val startTs = readUInt32Le(pay, 14) + val endTs = readUInt32Le(pay, 18) + val totalTime = readUInt16Le(pay, 22) + val wakeTime = readUInt16Le(pay, 24) + val remTime = readUInt16Le(pay, 26) + val lightTime = readUInt16Le(pay, 28) + val deepTime = readUInt16Le(pay, 30) + val segmentCount = readUInt16Le(pay, 32) + // The 2.3.x trailer is assumed here too: no sleep DATA page has been + // seen from that firmware yet. + val segmentsEnd = 34 + segmentCount * 3 + if (pay.size != segmentsEnd && pay.size != segmentsEnd + HEALTH_PAGE_TRAILER_LEN) { + return null + } + var offset = 34 + val segments = Array(segmentCount) { + val stage = pay[offset].toInt() and 0xff + val halfMinutes = readUInt16Le(pay, offset + 1) + offset += 3 + SleepSegment(stage, halfMinutes) + } + return SleepRecord( + receivedAtMs, recordState, unknownA, unknownTag, + startTs, endTs, totalTime, wakeTime, remTime, lightTime, deepTime, segments) + } + + /** + * The record's day anchor as Unix epoch seconds, or [UNKNOWN_TIME] + * when the day timestamp is zero or the timezone offset is invalid. + * + * **UNSOLVED:** a backlog page's true base is not understood as a + * general rule. One capture's backlog base landed at 2026-09-08 23:48:49 + * local, which is the moment that sync ran plus a per-type offset — it is + * not a fixed offset from midnight and must not be hardcoded. Callers get + * [UNKNOWN_TIME] and the raw hour index instead of an invented + * absolute time. + */ + @JvmStatic + fun anchorUnixSeconds(payload: ByteArray?): Long { + if (payload == null || payload.size < 9) { + return UNKNOWN_TIME + } + // These two bytes are an int16 timezone offset, not magic. 10 ff is + // -240 minutes (EDT); Pacific time, UTC and eastern zones differ. + val timezoneMinutes = readUInt16Le(payload, 3).toShort().toInt() + val anchor = readUInt32Le(payload, 5) + return if (timezoneMinutes >= -840 && timezoneMinutes <= 840 && anchor != 0L) anchor else UNKNOWN_TIME + } + + /** Device-channel 00:01 response, matching openR1 get_device_status(). */ + @JvmStatic + fun decodeDeviceStatus(frame: Frame?): DeviceStatus? { + if (frame == null || !frame.crcOk || frame.chan != CHAN_DEVICE + || frame.kind != KIND_RSP || frame.cmdHi != 0 || frame.cmdLo != 1 + || frame.payload.size != 9) return null + val battery = frame.payload[2].toInt() and 0xff + val charge = frame.payload[3].toInt() and 0xff + if (battery > 100 || charge > 3) return null + return DeviceStatus(battery, if (charge == 0) -1 else if (charge == 2) 0 else 1) + } + + /** Hex, for logs. Mirrors GlassesSessionCore.hex(). */ + @JvmStatic + fun hex(data: ByteArray?): String { + if (data == null || data.isEmpty()) { + return "" + } + val out = CharArray(data.size * 2) + for (i in data.indices) { + val value = data[i].toInt() and 0xff + out[i * 2] = HEX_DIGITS[value ushr 4] + out[i * 2 + 1] = HEX_DIGITS[value and 0x0f] + } + return out.concatToString() + } + + /** The five health requests, ready to write, sharing one ascending seq run. */ + @JvmStatic + fun buildHealthRequestBurst(firstSeq: Int, firstNonce: Int): List { + val frames = ArrayList(HEALTH_COMMANDS.size) + var seq = firstSeq + var nonce = firstNonce + for (cmdHi in HEALTH_COMMANDS) { + frames.add(buildHealthRequest(cmdHi, seq, nonce)) + seq = (seq + 1) and 0xff + nonce = (nonce + 1) and 0xffff + } + return frames + } + + // ------------------------------------------------------------------ + // Little-endian and formatting helpers + // ------------------------------------------------------------------ + + private const val HEX_DIGITS = "0123456789abcdef" + + /** Two lowercase hex digits, like `%02x` for a byte-sized value. */ + internal fun hex2(value: Int): String { + val v = value and 0xff + return "" + HEX_DIGITS[v ushr 4] + HEX_DIGITS[v and 0x0f] + } + + private fun writeIntLe(out: ByteArray, offset: Int, value: Int) { + out[offset] = (value and 0xff).toByte() + out[offset + 1] = ((value ushr 8) and 0xff).toByte() + out[offset + 2] = ((value ushr 16) and 0xff).toByte() + out[offset + 3] = ((value ushr 24) and 0xff).toByte() + } + + private fun readIntLe(data: ByteArray, offset: Int): Int { + return (data[offset].toInt() and 0xff) or + ((data[offset + 1].toInt() and 0xff) shl 8) or + ((data[offset + 2].toInt() and 0xff) shl 16) or + ((data[offset + 3].toInt() and 0xff) shl 24) + } + + private fun readUInt32Le(data: ByteArray, offset: Int): Long { + return readIntLe(data, offset).toLong() and 0xffffffffL + } + + private fun readUInt16Le(data: ByteArray, offset: Int): Int { + return (data[offset].toInt() and 0xff) or ((data[offset + 1].toInt() and 0xff) shl 8) + } + + private fun readUIntLe(data: ByteArray, offset: Int, width: Int): Int { + var value = 0 + for (i in 0 until width) { + value = value or ((data[offset + i].toInt() and 0xff) shl (8 * i)) + } + return value + } + + private fun safeRange(data: ByteArray?, from: Int, to: Int): ByteArray { + if (data == null || from >= data.size) { + return EMPTY + } + return data.copyOfRange(from, minOf(to, data.size)) + } + } + + // ------------------------------------------------------------------ + // Fragment reassembly + // ------------------------------------------------------------------ + + /** + * Feeds raw ATT notification values in and produces complete frames, + * rejoining fragmented ones. + * + * Fragmentation (spec §2.3): when a frame exceeds the 244-byte ATT + * ceiling the ring sets FLAG=0x01, sends the first 244 bytes, and later + * sends a continuation frame in a different, headerless shape — FLAG(1), + * CRC32(4), then the remaining bytes verbatim. + * + * Two things the spec document does not say, both measured from the + * reference capture and both load-bearing here: + * - **The continuation is not adjacent.** In one of the six captured + * fragmentations three unrelated complete frames arrive between the + * first fragment and its continuation, so a "next value is the rest" + * rule mis-joins. Complete frames are therefore still parsed normally + * while a fragment is outstanding. + * - **The continuation's own CRC field is not reliably the reassembled + * CRC.** It matched in five of six cases and differed in the sixth + * (whose join is nonetheless byte-exact and CRC-valid), so the + * continuation must not be matched by comparing CRC fields. + * + * What is reliable, in all six cases, is length: a continuation carries + * exactly `CONTINUATION_PREFIX_LEN + bytesStillNeeded` bytes and does + * not itself look like a header. The reassembled frame's CRC is the real + * validator and is always checked. + */ + class Reassembler { + private companion object { + /** + * Give up on an outstanding fragment after this many intervening + * complete frames. The observed worst case is 3; this is slack, not a + * measured bound. + */ + const val MAX_INTERLEAVED_FRAMES = 16 + } + + private var pending: ByteArray? = null + private var pendingTotal = 0 + private var interleaved = 0 + + fun hasPending(): Boolean = pending != null + + fun reset() { + pending = null + pendingTotal = 0 + interleaved = 0 + } + + /** + * Offer one ATT notification value. The result says whether the value + * belonged to this protocol at all (so the caller can fall through to + * the gesture decoder) and carries a frame once one is complete. + */ + fun accept(value: ByteArray?): Intake { + if (value == null || value.isEmpty()) { + return Intake.ignored() + } + + val held = pending + if (held != null) { + val needed = pendingTotal - held.size + if (value.size == CONTINUATION_PREFIX_LEN + needed && !looksLikeHeader(value)) { + val joined = ByteArray(pendingTotal) + held.copyInto(joined, 0) + value.copyInto(joined, held.size, CONTINUATION_PREFIX_LEN, CONTINUATION_PREFIX_LEN + needed) + reset() + return complete(joined) + } + if (!looksLikeHeader(value)) { + val dropped = pendingTotal + reset() + return Intake.consumed( + "dropped $dropped-byte fragment: continuation was ${value.size} bytes, expected ${CONTINUATION_PREFIX_LEN + needed}") + } + if (++interleaved > MAX_INTERLEAVED_FRAMES) { + val dropped = pendingTotal + reset() + // Fall through and parse this value as a fresh frame. + val result = acceptFresh(value) + return result.withNote("dropped $dropped-byte fragment: continuation never arrived") + } + } + + return acceptFresh(value) + } + + private fun acceptFresh(value: ByteArray): Intake { + val total = declaredLength(value) + if (total < 0) { + return Intake.ignored() + } + if (value.size >= total) { + return complete(value.copyOf(total)) + } + // Only one fragment is ever outstanding in the reference capture, + // but never silently clobber one if that assumption breaks. + val clobbered = if (pending == null) null else "dropped $pendingTotal-byte fragment: a new fragment started" + pending = value.copyOf() + pendingTotal = total + interleaved = 0 + return Intake.consumed("fragment start, ${value.size} of $total bytes").withNote(clobbered) + } + + private fun complete(raw: ByteArray): Intake { + val frame = parse(raw) ?: return Intake.consumed("malformed frame, " + raw.size + " bytes") + return Intake.frame(frame) + } + } + + /** The outcome of offering one ATT value to a [Reassembler]. */ + class Intake private constructor( + /** True when the value belonged to this protocol and must not be re-handled. */ + @JvmField val consumed: Boolean, + /** Non-null once a complete frame is available. Check [Frame.crcOk]. */ + @JvmField val frame: Frame?, + /** Human-readable detail for logging, or null. */ + @JvmField val note: String?, + ) { + internal companion object { + fun ignored(): Intake = Intake(false, null, null) + + fun consumed(note: String?): Intake = Intake(true, null, note) + + fun frame(frame: Frame): Intake = Intake(true, frame, null) + } + + internal fun withNote(extra: String?): Intake { + if (extra == null) { + return this + } + return Intake(consumed, frame, if (note == null) extra else "$note; $extra") + } + } + + /** One complete frame. */ + class Frame internal constructor( + @JvmField val flag: Int, + @JvmField val chan: Int, + @JvmField val seq: Int, + @JvmField val kind: Int, + @JvmField val cmdHi: Int, + @JvmField val cmdLo: Int, + /** PLEN - 10 bytes. payload[0:2] is the sender's nonce. */ + @JvmField val payload: ByteArray, + @JvmField val raw: ByteArray, + @JvmField val crcOk: Boolean, + ) { + fun isHealth(): Boolean = chan == CHAN_HEALTH + + fun commandLabel(): String = hex2(cmdHi) + ":" + hex2(cmdLo) + + fun describe(): String = + "chan=" + hex2(chan) + " kind=" + hex2(kind) + " cmd=" + commandLabel() + " seq=" + hex2(seq) + " len=" + raw.size + } + + class DeviceStatus internal constructor( + @JvmField val battery: Int, + @JvmField val charging: Int, + ) + + // ------------------------------------------------------------------ + // Decoded record types + // ------------------------------------------------------------------ + + /** Common supertype so one store can hold every decoded page. */ + abstract class HealthRecord internal constructor( + @JvmField val cmdHi: Int, + @JvmField val receivedAtMs: Long, + ) { + /** The metric name, for logs. */ + fun metric(): String = when (cmdHi) { + CMD_HI_HEART_RATE -> "heart_rate" + CMD_HI_SPO2 -> "spo2" + CMD_HI_HRV -> "hrv" + CMD_HI_STEPS -> "steps" + CMD_HI_SLEEP -> "sleep" + else -> "cmd" + hex2(cmdHi) + } + + /** A one-line summary safe to put in a log. */ + abstract fun summary(): String + } + + /** Heart rate, SpO2 or HRV: one page of hourly buckets. */ + class HourlyRecord internal constructor( + cmdHi: Int, + receivedAtMs: Long, + /** Day anchor in Unix seconds, or [UNKNOWN_TIME] on a backlog page. */ + @JvmField val anchorUnixSeconds: Long, + /** Per-metric "last measured at". See the 4-hour skew note in the spec. */ + @JvmField val tagRaw: Long, + /** The metric's latest value. */ + @JvmField val current: Int, + /** 1 byte for HR/SpO2, 2 for HRV, as defined by the metric serializer. */ + @JvmField val valueWidth: Int, + @JvmField val groups: Array, + ) : HealthRecord(cmdHi, receivedAtMs) { + /** True when this page has no anchor, i.e. it is a backlog page. */ + fun isBacklog(): Boolean = anchorUnixSeconds == UNKNOWN_TIME + + override fun summary(): String = + metric() + " groups=" + groups.size + " width=" + valueWidth + " current=" + current + + " anchor=" + (if (isBacklog()) "backlog(unanchored)" else anchorUnixSeconds.toString()) + + " tag=" + tagRaw + } + + /** One hourly bucket. */ + class HourlyGroup internal constructor( + /** Raw index as sent. On an anchored page this is hours since the anchor. */ + @JvmField val hourIndex: Int, + @JvmField val avg: Int, + @JvmField val max: Int, + @JvmField val min: Int, + /** + * Absolute Unix seconds for this bucket, or [UNKNOWN_TIME] on a + * backlog page — where the base is UNSOLVED and deliberately not guessed. + */ + @JvmField val unixSeconds: Long, + ) + + /** One page of activity buckets. */ + class StepsRecord internal constructor( + receivedAtMs: Long, + @JvmField val anchorUnixSeconds: Long, + @JvmField val buckets: Array, + ) : HealthRecord(CMD_HI_STEPS, receivedAtMs) { + fun totalSteps(): Int = buckets.sumOf { it.steps } + + override fun summary(): String = + "steps buckets=" + buckets.size + " total=" + totalSteps() + + " anchor=" + (if (anchorUnixSeconds == UNKNOWN_TIME) "none" else anchorUnixSeconds.toString()) + } + + /** + * One activity bucket. + * + * **UNSOLVED:** [index] does not map to a known wall-clock + * time. It runs 0-7, 10, 11, 13-34 and then jumps to 130+, and no bucket + * width at any base reproduces the app's own per-bucket distribution — even + * though the steps total across all buckets is exactly right. The raw index + * is stored as sent; no time-of-day mapping is invented. + */ + class StepsBucket internal constructor( + @JvmField val index: Int, + /** Confirmed: summed over a page this equals the app's daily step total. */ + @JvmField val steps: Int, + /** UNCONFIRMED: calorie-shaped (v3 - v2 tracks per-bucket resting kcal). */ + @JvmField val calorieLike2: Int, + /** UNCONFIRMED: calorie-shaped. */ + @JvmField val calorieLike3: Int, + ) + + /** + * One sleep session. + * + * **[startTs] and [endTs] are ring-relative seconds, not Unix time.** + * Even's own app gets this wrong and stamps live-pushed sessions with + * timestamps in 1979. Do not feed them to a date formatter. + * + * **UNSOLVED:** [unknownPrefix] (6 bytes) and [unknownTag] (u32) are not + * decoded; one of them probably carries the session date, which would + * remove the anchoring problem. They are stored raw rather than interpreted. + */ + class SleepRecord internal constructor( + receivedAtMs: Long, + /** 1 = a real record, 2 = the empty / end-of-list marker. */ + @JvmField val recordState: Int, + /** UNSOLVED per-record 6-byte field (payload[3:9]). Stored raw. */ + @JvmField val unknownPrefix: ByteArray, + /** UNSOLVED u32 tag (payload[9:13]). Stored raw. */ + @JvmField val unknownTag: Long, + /** Ring-relative seconds, NOT Unix. */ + @JvmField val startTs: Long, + /** Ring-relative seconds, NOT Unix. */ + @JvmField val endTs: Long, + @JvmField val totalTime: Int, + @JvmField val wakeTime: Int, + @JvmField val remTime: Int, + @JvmField val lightTime: Int, + @JvmField val deepTime: Int, + /** + * The stage series. Stage ids are the same 0-3 encoding the app's own + * export uses, but which id means wake/rem/light/deep is NOT stated by + * the spec and is deliberately not guessed here — see + * [halfMinutesForStage]. + */ + @JvmField val segments: Array, + ) : HealthRecord(CMD_HI_SLEEP, receivedAtMs) { + fun isRealRecord(): Boolean = recordState == 1 + + fun totalHalfMinutes(): Int = segments.sumOf { it.halfMinutes } + + fun halfMinutesForStage(stage: Int): Int = segments.filter { it.stage == stage }.sumOf { it.halfMinutes } + + /** + * The two whole-record arithmetic identities from the spec, which held + * exactly for all ten real records in the reference capture. A false + * result means the body was mis-parsed. + */ + fun identitiesHold(): Boolean { + if (!isRealRecord()) { + return true + } + val seconds = totalHalfMinutes() * 30 + return seconds == totalTime + wakeTime && seconds == (endTs - startTs).toInt() + } + + override fun summary(): String { + if (!isRealRecord()) { + return "sleep marker state=$recordState" + } + return "sleep segments=" + segments.size + " total=" + totalTime + "s wake=" + wakeTime + + " rem=" + remTime + " light=" + lightTime + " deep=" + deepTime + + " relStart=" + startTs + " relEnd=" + endTs + " identities=" + identitiesHold() + } + } + + /** One stage run: a stage id and a duration in half-minutes (30 s units). */ + class SleepSegment internal constructor( + @JvmField val stage: Int, + @JvmField val halfMinutes: Int, + ) +} diff --git a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionControls.kt b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionControls.kt index 91747738..1731f7de 100644 --- a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionControls.kt +++ b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionControls.kt @@ -501,6 +501,8 @@ internal fun GlassesSessionCore.scheduleReconnectLocked(sessionWasReady: Boolean internal fun GlassesSessionCore.resetSessionStateLocked() { ringBattery = -1 ringCharging = -1 + directRingBattery = -1 + directRingCharging = -1 sessionReady = false shutdownRequested = false fixedLayoutCreated = false @@ -709,8 +711,11 @@ internal fun GlassesSessionCore.emitPhoneLockStateIfChanged(force: Boolean) { } internal fun GlassesSessionCore.emitBatteryState(headsetBattery: Int, headsetCharging: Int) { - val reportedRingBattery = ringBattery - val reportedRingCharging = ringCharging + // A missing glasses-side report must not erase a verified direct + // reading. Fall back to the glasses cache when the direct link drops. + val useDirect = ringConnected && directRingBattery >= 0 + val reportedRingBattery = if (useDirect) directRingBattery else ringBattery + val reportedRingCharging = if (useDirect) directRingCharging else ringCharging val current = listener ?: return host.postToMain { try { diff --git a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionCore.kt b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionCore.kt index 2985306e..3b403efb 100644 --- a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionCore.kt +++ b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionCore.kt @@ -145,6 +145,115 @@ class GlassesSessionCore( internal var leftConnected = false internal var ringConnected = false internal var ringNotificationsReady = false + // Ring connect/write/health waits must never park the glasses sender; they + // run on their own worker (see GlassesSessionRing.kt). The link serializes + // GATT operations per device address. Counted down when that worker exits. + @Volatile internal var ringWorkerDone: Latch? = null + // R1 health-data protocol (RingProtocol). The reassembler and the outbound + // queue are both guarded by `monitor`. Page ACKs are queued rather than + // written inline because notifications arrive on the GATT callback thread + // and link.writeFrames() blocks waiting for the write callback, which that + // same thread has to deliver — writing there would deadlock until the + // write timeout. The ring worker drains the queue instead. + internal val ringReassembler = RingProtocol.Reassembler() + internal val ringOutbound = ArrayDeque() + /** + * Ring-write backoff after a failed write (see writeRingFrame). Every ring + * write shares the platform's GATT pipeline with the glasses, and a failing + * one can hold it for the whole write timeout, so failures must not be + * retried at ring-worker tick rate. Reset on each ring connect. Guarded by + * `monitor`. + */ + internal var ringWriteBlockedUntilMs = 0L + internal var ringWriteFailures = 0 + /** Consecutive failed direct-ring connect attempts; stretches the retry delay. Guarded by `monitor`. */ + internal var ringConnectFailures = 0 + internal val ringHealthRecords = ArrayList() + /** + * Total records ever appended to [ringHealthRecords], including every + * one already consumed or evicted. Never reset. + * + * This is the identity behind the ingest watermark. Record N is the Nth + * ever decoded this session, so a consumer that has durably stored + * everything below some N can ask for exactly that much to be dropped + * without racing the pages still arriving above it - see + * [takeRingHealthBatch] and [clearRingHealthRecordsBelow]. A plain "clear + * the list" could not do that: a page landing between the read and the + * clear would be thrown away having never been ingested. Guarded by + * `monitor`. + */ + internal var ringHealthTotalAdded = 0L + /** + * The phone-side sequence counter. One counter shared by BOTH ring channels + * (measured: 78 phone-to-ring writes in the reference capture step by + * exactly +1 regardless of channel, restarting at 1 on a new connection). + */ + internal var ringSeq = 0 + internal var ringNonce = 0 + /** + * Response-driven health-pull state (2026-09-11). Set from + * handleRingHealthNotification (GATT callback thread), waited on from + * requestRingHealth (ring worker), both guarded by `monitor`. Replaces a + * blind fixed-sleep loop - see requestRingHealth's own doc for why: a real + * successful Even sync (extracted from `/tmp/btsnoop_fresh.log` on + * bazzite-desktop, 2026-09-11) is response-paced, not sleep-paced, and + * ACKs each DATA page immediately rather than after the whole run. + */ + internal var ringHealthRspSeen = false + /** Bumped once per decoded health DATA page (any type) so a waiter can + * detect "a page just arrived" without polling ringHealthRecords. */ + internal var ringHealthPageCounter = 0 + /** + * now() of the last time requestRingHealth() was attempted, or 0 if never. + * Health data updates hourly at the source (heart rate/HRV/SpO2) or + * slower, but a ring reconnect can happen far more often than that (BLE + * drops, Doze, app restarts - live testing saw reconnects every few + * seconds under load). Pulling on every reconnect would be pure waste even + * ignoring the risk below; given the race condition documented on + * requestRingHealth() - a request that loses its race may silently discard + * real backlog rather than just delay it - it is actively worse than + * waste, so this is throttled. + */ + internal var ringHealthLastRequestedAtMs = 0L + /** + * Set by [requestRingHealthNow] from whatever thread the UI is on; + * cleared by the ring worker, which is the only thread allowed to run the + * pull. Guarded by `monitor`. + */ + internal var ringHealthPullRequested = false + /** + * Aborted-pull retries spent since the last pull that COMPLETED its + * sequence. Guarded by `monitor`. See RING_HEALTH_ABORTED_RETRY_LIMIT. + */ + internal var ringHealthAbortedRetries = 0 + /** + * Direct mode (configured role "glasses") only: the direct link has been + * handed to the phone role for one health pull, and returns to the glasses + * role when that pull ends, or at [ringHealthWindowDeadlineMs] if the + * phone-role link never comes up. See beginRingHealthWindowLocked. + * Guarded by `monitor`. + */ + internal var ringHealthWindowActive = false + internal var ringHealthWindowDeadlineMs = 0L + /** Outcome of the last health pull, for the Ring status page. Guarded by `monitor`. */ + internal var lastRingHealthPullResult = "" + internal var lastRingHealthPullAtMs = 0L + /** + * Timeout waiting for a health REQ's own RSP. In the reference capture + * (a real successful Even sync) RSPs land within ~150ms; this only needs + * to bound the pathological "ring stopped answering entirely" case. + * Variable only so tests can shorten it. + */ + internal var ringHealthRspTimeoutMs = 3000L + /** + * How long to keep waiting after the most recent DATA page for a health + * type before deciding its transfer is over (or that there was never + * going to be one). Chosen from the same reference capture: consecutive + * pages for one type land well under a second apart, so 1.5s covers + * that with real margin while still moving on quickly when a type + * genuinely has nothing new. Variable only so tests can shorten it. + */ + internal var ringHealthDataIdleMs = 1500L internal var sessionReady = false internal var fixedLayoutCreated = false internal var shutdownRequested = false @@ -230,6 +339,55 @@ class GlassesSessionCore( internal var headsetCharging = -1 internal var ringBattery = -1 internal var ringCharging = -1 + // Battery read over the direct ring link (device-channel 00:01); preferred + // over the glasses-relayed ringBattery while the ring is connected. + internal var directRingBattery = -1 + internal var directRingCharging = -1 + // Ring diagnostics for the Developer > Ring status page (now() clock, 0 = never). + internal var lastDirectRingNotifyAtMs = 0L + internal var lastDirectRingInputAtMs = 0L + internal var lastDirectRingInputLabel = "" + internal var lastGlassesRingInputAtMs = 0L + internal var lastGlassesRingInputLabel = "" + internal var lastGlassesRingBatteryAtMs = 0L + internal var ringConnectedChangedAtMs = 0L + internal var ringConnectCount = 0 + internal var lastDirectRingError = "" + // What the glasses themselves said about their ring link (sid 0x80 + // RING_CONNECT_INFO / sid 0x91 ring events). The MAC is kept in wire byte + // order so a reconnect can echo it back without guessing the order. + internal var glassesRingMac: ByteArray? = null + internal var glassesRingName = "" + internal var lastGlassesRingReport = "" + internal var lastGlassesRingReportAtMs = 0L + // The last glasses ring-link command we sent, and how each temple answered. + internal var lastRingLinkCommand = "" + internal var lastRingLinkCommandAtMs = 0L + internal var lastRingLinkResultR = "" + internal var lastRingLinkResultL = "" + // Which of the ring's two roles the direct link claims; see setDirectRingRole. + internal var directRingRole = DIRECT_RING_ROLE_PHONE + internal var ringRoleReconnectPending = false + // Glasses-role direct link: the per-connection setup (legacy pair-auth + + // touch source on) still to be written, what the ring made of the + // pair-auth, and the once-per-connection target clear after a rejection. + internal var ringGlassesSetupPending = false + internal var directGlassesAuth = "" + internal var directGlassesAuthAtMs = 0L + internal var directGlassesAuthRetried = false + // Last time we asked the glasses to unpair the ring for the direct link. + internal var lastRingReleaseAtMs = 0L + // Ring-side binding commands (system channel) waiting for the ring worker, + // the one written and not yet answered, and the last one's outcome. + internal val ringConfigQueue = ArrayDeque() + internal var ringConfigAwaiting: RingConfigCommand? = null + internal var lastRingConfigCommand = "" + internal var lastRingConfigCommandAtMs = 0L + internal var lastRingConfigResult = "" + // Last direct-link notification nothing decoded (e.g. legacy-channel + // frames while claiming the glasses role). + internal var lastDirectRingRaw = "" + internal var lastDirectRingRawAtMs = 0L // Last charging-case reading reported to the listener (-1 = none yet this // connection). See updateCaseInfoLocked. internal var caseBattery = -1 @@ -405,6 +563,17 @@ class GlassesSessionCore( incompatibleFirmware = null shutdownRequested = false host.startWorker { run() } + if (hasRingAddress()) { + val done = Latch(1, platform) + ringWorkerDone = done + host.startRingWorker { + try { + runRingWorker() + } finally { + done.countDown() + } + } + } return true } } @@ -424,10 +593,15 @@ class GlassesSessionCore( running = false audioCaptureActive = false audioPacketListener = null + monitor.signalAll() } setStateDisplay("disconnecting", "Disconnecting...") interruptibleSleep.interrupt() + val ringDone = ringWorkerDone + if (ringDone != null) host.interruptRingWorker() host.joinWorker(5_000) + ringDone?.await(5_000) + ringWorkerDone = null monitor.withLock { resetSessionStateLocked() clearAllMessagesLocked("disconnect") @@ -504,6 +678,82 @@ class GlassesSessionCore( } } + // --------------------------------------------------------------------- + // Direct ring health (see GlassesSessionRing.kt) + + /** + * Ask for a health pull as soon as the ring worker can run one. Safe to + * call from any thread; returns immediately without blocking. + * + * Called when the health app opens, so a glance shows something current + * rather than whatever the last automatic pull happened to catch. Subject + * to a one-minute on-demand floor; a request inside that window is dropped + * rather than queued, because a stale duplicate pull has no value and + * every pull carries the discard risk documented on requestRingHealth(). + */ + fun requestRingHealthNow() { + monitor.withLock { + ringHealthPullRequested = true + monitor.signalAll() + } + interruptibleSleep.interrupt() + } + + /** + * Snapshot of everything the ring has pushed and not yet been consumed, + * with the watermark needed to hand it back as consumed. + */ + fun takeRingHealthBatch(): RingHealthBatch { + monitor.withLock { + return RingHealthBatch(ArrayList(ringHealthRecords), ringHealthTotalAdded) + } + } + + /** + * Drop every held record whose identity is below [watermark] - that is, + * everything the caller has durably stored. + * + * "Cut and paste instead of copy paste. If you didn't receive the pull + * then it should not delete yet." Call this ONLY after the store write has + * succeeded; a caller that dies before calling it simply sees the same + * records again, which is a no-op at the store. + * + * Records that arrived after the snapshot sit above the watermark and + * are left alone, so a page landing during an ingest is never lost. If the + * buffer evicted its oldest in the meantime the arithmetic accounts for it + * via ringHealthTotalAdded rather than clearing the wrong end. + * + * @return how many records were actually removed. + */ + fun clearRingHealthRecordsBelow(watermark: Long): Int { + monitor.withLock { + val firstHeldIndex = ringHealthTotalAdded - ringHealthRecords.size + var toRemove = watermark - firstHeldIndex + if (toRemove <= 0) { + return 0 + } + if (toRemove > ringHealthRecords.size) { + toRemove = ringHealthRecords.size.toLong() + } + ringHealthRecords.subList(0, toRemove.toInt()).clear() + return toRemove.toInt() + } + } + + /** + * Snapshot of everything the ring has pushed this session, WITHOUT + * consuming it. + * + * Kept for callers that only want to look. The ingest path must use + * [takeRingHealthBatch] instead - a pure copy is what let the buffer grow + * unbounded and every tick re-process the whole session. + */ + fun getRingHealthRecords(): List { + monitor.withLock { + return ArrayList(ringHealthRecords) + } + } + fun isSessionReady(): Boolean { monitor.withLock { return running && sessionReady @@ -756,6 +1006,147 @@ class GlassesSessionCore( interruptibleSleep.interrupt() } + /** + * Ring connection/input diagnostics as JSON. Times are reported as ages + * in ms (-1 = never) so the caller needs no access to this clock. + */ + fun getRingStatus(): String { + monitor.withLock { + val now = now() + fun age(atMs: Long): Long = if (atMs == 0L) -1L else maxOf(0L, now - atMs) + val status = linkedMapOf() + status["directEnabled"] = hasRingAddress() + status["ringAddress"] = ringAddress + status["glassesConnected"] = rightConnected && leftConnected + status["sessionReady"] = sessionReady + status["directConnected"] = ringConnected + status["directNotificationsReady"] = ringNotificationsReady + status["directConnectCount"] = ringConnectCount + status["directStateAgeMs"] = age(ringConnectedChangedAtMs) + status["directBattery"] = directRingBattery + status["lastDirectNotifyAgeMs"] = age(lastDirectRingNotifyAtMs) + status["lastDirectInputAgeMs"] = age(lastDirectRingInputAtMs) + status["lastDirectInput"] = lastDirectRingInputLabel + status["glassesRingBattery"] = ringBattery + status["glassesRingBatteryAgeMs"] = age(lastGlassesRingBatteryAtMs) + status["lastGlassesInputAgeMs"] = age(lastGlassesRingInputAtMs) + status["lastGlassesInput"] = lastGlassesRingInputLabel + status["lastDirectError"] = lastDirectRingError + status["glassesRingMac"] = glassesRingMac?.let { hex(it) } ?: "" + status["glassesRingName"] = glassesRingName + status["lastGlassesReport"] = lastGlassesRingReport + status["lastGlassesReportAgeMs"] = age(lastGlassesRingReportAtMs) + status["lastCommand"] = lastRingLinkCommand + status["lastCommandAgeMs"] = age(lastRingLinkCommandAtMs) + status["lastCommandResultR"] = lastRingLinkResultR + status["lastCommandResultL"] = lastRingLinkResultL + status["directRole"] = directRingRole + status["healthWindowActive"] = ringHealthWindowActive + status["lastHealthPull"] = lastRingHealthPullResult + status["lastHealthPullAgeMs"] = age(lastRingHealthPullAtMs) + status["heldHealthRecords"] = ringHealthRecords.size + status["directGlassesAuth"] = directGlassesAuth + status["directGlassesAuthAgeMs"] = age(directGlassesAuthAtMs) + status["lastRingCommand"] = lastRingConfigCommand + status["lastRingCommandAgeMs"] = age(lastRingConfigCommandAtMs) + status["lastRingCommandResult"] = lastRingConfigResult + status["lastDirectRaw"] = lastDirectRingRaw + status["lastDirectRawAgeMs"] = age(lastDirectRingRawAtMs) + return try { Json.write(status) } catch (e: Exception) { "{}" } + } + } + + /** + * Which ring role the direct link claims. The R1 holds one phone role and + * one glasses role, on separate links, and sends gestures and battery + * pushes only to the glasses role: + * - "phone" (default): pairAuth on the system channel and health sync, + * with only the data CCCD, like Even's app. The glasses keep the ring. + * - "glasses": act as the ring's glasses (legacy CCCD, legacy pair-auth, + * touch source on; see runRingGlassesSetup) and take the ring over from + * the glasses when they still hold it. The ring answers system requests + * (health included) only on a phone-role link, so each health pull + * briefly reconnects the link in the phone role and then returns it + * (see beginRingHealthWindowLocked). + * Asking for both on one link (the old behavior) made the ring drop the + * link every ~6 s while the glasses held it. A change while the direct + * link is up reconnects it. + */ + fun setDirectRingRole(role: String?) { + val normalized = if (role == DIRECT_RING_ROLE_GLASSES) DIRECT_RING_ROLE_GLASSES else DIRECT_RING_ROLE_PHONE + monitor.withLock { + if (normalized == directRingRole) return + directRingRole = normalized + // A health window only exists to borrow the phone role from the glasses role. + ringHealthWindowActive = false + if (ringConnected || ringNotificationsReady) { + ringRoleReconnectPending = true + monitor.signalAll() + } + } + logLine("direct ring role set to $normalized") + } + + /** + * EXPERIMENTAL: ring-side binding commands over the direct link, plus the + * two combined flows. Returns a one-line outcome for the UI. Actions: + * "pair-auth", "targets-glasses", "targets-clear", "touch-on", + * "touch-off", "remove-ring" (see [queueRingConfigCommandLocked]); + * "bind" = advStart(our glasses), then after the ring answers the glasses + * RING_CONNECT_INFO connect=1 (the official app's order); "unbind" = the + * glasses' UNPAIR_INFO, then removeRingNotify to the ring. + * `fallbackAddress`/`fallbackName` are the ring's, for the glasses side. + */ + fun sendRingConfigCommand(action: String, fallbackAddress: String?, fallbackName: String?): String { + val outcome = monitor.withLock { + if (!running || !sessionReady) return "not sent: no glasses session" + val directReady = ringNotificationsReady + when (action) { + "bind" -> { + if (!directReady) return "not sent: direct ring link not ready" + queueRingConfigCommandLocked("targets-glasses", "connect", fallbackAddress ?: "", fallbackName ?: "") + } + "unbind" -> { + val glasses = queueGlassesRingLinkCommandLocked("unpair", fallbackAddress ?: "", fallbackName ?: "") + val ring = directReady && queueRingConfigCommandLocked("remove-ring", null, "", "") == null + when { + glasses && ring -> null + glasses -> "glasses unpair sent; ring part skipped (direct link not ready)" + ring -> "ring part sent; glasses unpair skipped (no ring address)" + else -> "not sent: no ring address and no direct link" + } + } + else -> { + if (!directReady) return "not sent: direct ring link not ready" + queueRingConfigCommandLocked(action, null, "", "") + } + } + } + interruptibleSleep.interrupt() + return outcome ?: "sent" + } + + /** + * EXPERIMENTAL: ask the glasses to drop, forget or re-establish their own + * link to the ring, so the phone can take the ring over directly and later + * hand it back. `action` is "disconnect", "release", "unpair" or "connect"; see + * [queueGlassesRingLinkCommandLocked]. `fallbackAddress` ("AA:BB:..") and + * `fallbackName` are used only when the glasses have not reported their + * ring target this session. False when no session is up. + */ + fun setGlassesRingLink(action: String, fallbackAddress: String?, fallbackName: String?): Boolean { + monitor.withLock { + if (!running || !sessionReady) { + logLine("skip glasses ring link command; session not ready") + return false + } + val ok = queueGlassesRingLinkCommandLocked(action, fallbackAddress ?: "", fallbackName ?: "") + if (!ok) return false + } + interruptibleSleep.interrupt() + return true + } + /** Status/results of the current or most recent benchmark run, as JSON. */ fun getBandwidthBenchmarkStatus(): String { monitor.withLock { @@ -1348,11 +1739,6 @@ class GlassesSessionCore( continue } - if (shouldAttemptRingConnect()) { - tryConnectRing("retry") - continue - } - val sleepMs = driveSession() if (sleepMs > 0) { interruptibleSleep.sleep(sleepMs) @@ -1443,6 +1829,10 @@ class GlassesSessionCore( wearState = decodedWearState emitWearState = true } + if (frame.ok + && (frame.sid == BleProtocol.SID_SECURITY_AUTH || frame.sid == BleProtocol.SID_RING_DATA)) { + recordGlassesRingReportLocked(frame, address) + } var faceclawWakeNotification = false if (shutdownRequested && frame.ok @@ -1522,7 +1912,9 @@ class GlassesSessionCore( if (ring != null) { ringBattery = ring.battery ringCharging = ring.charging + lastGlassesRingBatteryAtMs = now() emitBatteryState(headsetBattery, headsetCharging) + if (ring.battery >= 0) releaseRingFromGlassesLocked("glasses report the ring connected") } } // CFW mic status (field 104) rides both standalone pushes and @@ -1600,6 +1992,11 @@ class GlassesSessionCore( && decoded.eventType == BleProtocol.EVENT_IMU_DATA_REPORT if (!pureImuSample) { lastConnectionOrInputAtMs = lastIncomingAtMs + if (decoded.eventSource == BleProtocol.EVENT_SOURCE_RING) { + lastGlassesRingInputAtMs = lastIncomingAtMs + lastGlassesRingInputLabel = decoded.kind + " type=" + decoded.eventType + releaseRingFromGlassesLocked("ring input relayed by the glasses") + } } if ("list-click" == decoded.kind || "text-click" == decoded.kind) { // Container-routed touchpad input reached us, so the @@ -1671,8 +2068,19 @@ class GlassesSessionCore( } internal fun handleDirectRingNotification(characteristicUuid: String, data: ByteArray) { + monitor.withLock { lastDirectRingNotifyAtMs = now() } + if (handleRingHealthNotification(characteristicUuid, data)) { + return + } + if (handleRingLegacyControl(data)) { + return + } val decoded = FaceclawRingEventDecoder.decode(data) if (decoded == null) { + monitor.withLock { + lastDirectRingRaw = characteristicUuid.take(8) + " " + hex(data.copyOf(minOf(data.size, 24))) + lastDirectRingRawAtMs = now() + } logDebug("direct ring notify ignored: characteristicUuid=" + characteristicUuid + " raw=" + hex(data)) return } @@ -1682,6 +2090,8 @@ class GlassesSessionCore( monitor.withLock { lastIncomingAtMs = arrivalMs lastConnectionOrInputAtMs = arrivalMs + lastDirectRingInputAtMs = arrivalMs + lastDirectRingInputLabel = decoded.label + " " + decoded.detail } logLine("direct ring " + decoded.label + " " + decoded.detail + " raw=" + hex(data)) val frameId = frameTimings.startFrame("input:ring:" + decoded.label) @@ -1715,6 +2125,8 @@ class GlassesSessionCore( } if (isConfiguredRingAddress(address)) { monitor.withLock { + if (connected != ringConnected) ringConnectedChangedAtMs = now() + if (connected && !ringConnected) ringConnectCount++ ringConnected = connected if (connected) { // A background connect landed: finish setting it up right away. @@ -1722,11 +2134,20 @@ class GlassesSessionCore( } else { ringNotificationsReady = false ringReconnectAfterMs = now() + ConnectionOptions.RING_RECONNECT_DELAY_MS + // Half-received fragments and unsent ACKs do not survive the + // link; the sequence counter restarts on the next connect. + ringReassembler.reset() + ringOutbound.clear() + dropRingConfigCommandsLocked("direct link dropped") + directRingBattery = -1 + directRingCharging = -1 + emitBatteryState(headsetBattery, headsetCharging) } + // Wakes the ring worker, which owns ring connect/setup. + monitor.signalAll() } 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 } var lostSession = false @@ -1858,7 +2279,8 @@ class GlassesSessionCore( // drive loop sends it once the layout is up. caseInfoReadPending = true } - tryConnectRing("initial") + // Wake the ring worker; it owns the (blocking) ring connect. + monitor.signalAll() } catch (t: Throwable) { logLine("connect failed: " + safeMessage(t)) val unpairedArm = firstUnpairedArm() @@ -1939,8 +2361,6 @@ class GlassesSessionCore( && sessionReady && !ringNotificationsReady && now >= ringReconnectAfterMs - && pendingMessages.isEmpty() - && inFlightMessages.isEmpty() } } @@ -1949,10 +2369,11 @@ class GlassesSessionCore( return } try { - // The ring is often out of range or bound to the glasses. Rather than block this - // worker (and every frame and heartbeat behind it) on a timed connect, keep a - // low-duty background connection pending; its callback wakes us to finish setup. - // The periodic recheck re-arms it if the attempt died without a callback. + // The ring is often out of range or bound to the glasses. Rather than block the + // ring worker (and the health ACKs behind it) on a timed connect, keep a + // low-duty background connection pending; its callback wakes the worker to + // finish setup. The periodic recheck re-arms it if the attempt died without a + // callback. if (!link.isConnected(ringAddress) && link.beginConnect(ringAddress, true)) { monitor.withLock { ringReconnectAfterMs = now() + ConnectionOptions.RING_RECONNECT_DELAY_MS @@ -1961,12 +2382,21 @@ class GlassesSessionCore( } connectRing() } catch (t: Throwable) { - monitor.withLock { + // Back off exponentially: each attempt's setup steps hold the + // GATT pipeline the glasses share, and an unreachable ring (e.g. + // held by the glasses) fails the same way every time. + val retryDelayMs = monitor.withLock { + val delay = minOf(ConnectionOptions.RING_RECONNECT_MAX_DELAY_MS, + ConnectionOptions.RING_RECONNECT_DELAY_MS.toLong() shl minOf(ringConnectFailures, 5)) + ringConnectFailures++ ringConnected = false ringNotificationsReady = false - ringReconnectAfterMs = now() + ConnectionOptions.RING_RECONNECT_DELAY_MS + ringReconnectAfterMs = now() + delay + lastDirectRingError = "connect failed: " + safeMessage(t) + delay } - logLine("direct ring connect failed (" + reason + "): " + safeMessage(t)) + logLine("direct ring connect failed (" + reason + "): " + safeMessage(t) + + "; retry in " + (retryDelayMs / 1000) + "s") // Start the next attempt from a fresh connection rather than retrying setup on // one that just failed it. link.disconnect(ringAddress) @@ -1975,20 +2405,59 @@ class GlassesSessionCore( internal fun connectRing() { logLine("connecting direct ring $ringAddress") - if (!link.connect(ringAddress, ConnectionOptions.CONNECT_TIMEOUT_MS)) { + // autoConnect=true (see SessionLink.connect's 3-arg overload) - + // matches what Even's own app does for this device specifically. + // Direct connect (false, the default used for the glasses) was + // measured dying ~5s into an otherwise-idle ring connection, + // repeatedly, with nothing else competing for it. + if (!link.connect(ringAddress, ConnectionOptions.RING_CONNECT_TIMEOUT_MS, true)) { throw IllegalStateException("connect failed: $ringAddress") } - link.requestHighPriority(ringAddress) + // Deliberately NOT requesting CONNECTION_PRIORITY_HIGH here (2026-09-11). + // Even's own app never requests any priority for the ring at all - it + // logs no requestConnectionPriority/onConnectionUpdated call anywhere - + // and just runs on whatever Android's default (BALANCED) parameters are. + // HIGH negotiated interval=12 (15ms) / timeout=500 (5000ms) here, and a + // live test found the ring-only connection reliably dying at + // 5.5-5.7s, matching that 5000ms supervision timeout almost exactly, + // on every attempt, with nothing else competing for the ring. If the + // ring's firmware occasionally needs more than 5s of headroom after a + // burst of writes, HIGH priority's short timeout would kill the link + // while Even's default (longer) one wouldn't - untested but the timing + // match is exact, not approximate. Leaving default priority for the + // ring only; the glasses' own HIGH-priority request is untouched. link.requestMtu(ringAddress, ConnectionOptions.RING_DESIRED_MTU, ConnectionOptions.CONNECT_TIMEOUT_MS) if (!link.discoverServices(ringAddress, ConnectionOptions.SERVICES_TIMEOUT_MS)) { throw IllegalStateException("discoverServices failed: $ringAddress") } - val phoneNotify = enableRingNotification(BleProtocol.R1_PHONE_NOTIFY_CHAR_UUID) + // Even's app subscribes only to the health-data notify CCCD (ATT + // handle 24) and never touches the phone-notify one (handle 19). That + // difference was briefly suspected on 2026-09-11 of causing the ring's + // total silence and this call was dropped to match - it changed + // nothing, and the real cause turned out to be the malformed 00:08 + // frame (see sendRingHandshake). Restored, because the phone-notify + // channel is plausibly what carries ring-as-remote gesture events, + // which are a daily-driver feature; matching Even byte-for-byte here + // buys nothing and risks breaking them. + // + // Per openCFW's R1 decompilation, the "phone-notify" characteristic + // (bae80011) is really the legacy channel the glasses use. Enabling its + // CCCD appears to be what assigns a link the ring's glasses role (BAE8 + // service events 6/7), and the ring sends gestures (00 09 61 00 ...) + // only to that role. The direct ring + // role setting decides which CCCDs we enable; see setDirectRingRole. + val configuredRole: String + val role = monitor.withLock { + configuredRole = directRingRole + effectiveRingRoleLocked() + } + val legacyNotify = role == DIRECT_RING_ROLE_GLASSES + && enableRingNotification(BleProtocol.R1_LEGACY_NOTIFY_CHAR_UUID) val dataNotify = enableRingNotification(BleProtocol.R1_NOTIFY_CHAR_UUID) - if (!phoneNotify && !dataNotify) { + if (!legacyNotify && !dataNotify) { throw IllegalStateException("no R1 notify characteristic subscribed") } @@ -1996,8 +2465,31 @@ class GlassesSessionCore( ringConnected = true ringNotificationsReady = true ringReconnectAfterMs = 0 + // The ring's sequence counter restarts with the connection. + ringSeq = 0 + ringNonce = 0 + ringReassembler.reset() + ringOutbound.clear() + ringWriteBlockedUntilMs = 0L + ringWriteFailures = 0 + ringConnectFailures = 0 + // The ring forgets touch-source state with the link, so every + // glasses-role connection repeats the setup (runRingGlassesSetup). + ringGlassesSetupPending = role == DIRECT_RING_ROLE_GLASSES + directGlassesAuth = "" + directGlassesAuthAtMs = 0L + directGlassesAuthRetried = false + } + logLine("direct ring ready role=$role legacyNotify=$legacyNotify dataNotify=$dataNotify" + + (if (role != configuredRole) " (health window; configured role $configuredRole)" else "")) + + // The glasses role means no pairAuth (it would ask for the phone role + // on the same link) and therefore no health sync. Direct mode gets its + // health through a temporary phone-role connection instead (see + // beginRingHealthWindowLocked), which takes this branch. + if (dataNotify && host.supportsRingHealth() && role == DIRECT_RING_ROLE_PHONE) { + onRingDataChannelReady() } - logLine("direct ring ready phoneNotify=$phoneNotify dataNotify=$dataNotify") } internal fun enableRingNotification(characteristicUuid: String): Boolean { @@ -2138,7 +2630,7 @@ class GlassesSessionCore( if (!isConfiguredRingAddress(address) || characteristicUuid == null) { return false } - return BleProtocol.R1_PHONE_NOTIFY_CHAR_UUID == characteristicUuid + return BleProtocol.R1_LEGACY_NOTIFY_CHAR_UUID == characteristicUuid || BleProtocol.R1_NOTIFY_CHAR_UUID == characteristicUuid } diff --git a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionRing.kt b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionRing.kt new file mode 100644 index 00000000..63b46f7b --- /dev/null +++ b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionRing.kt @@ -0,0 +1,1309 @@ +package com.faceclaw.app + +/** + * The direct R1 ring link: its dedicated worker, the health-data protocol + * (RingProtocol) branch of the notification path, and the response-driven + * health pull. Extension functions on [GlassesSessionCore] like the sibling + * GlassesSessionSend.kt / GlassesSessionControls.kt; the state lives in the + * core's class body. + */ + +/** + * Cap on decoded ring health pages held in memory. A full backlog sync is + * ~40 pages, so this holds several syncs; oldest is dropped first. This is a + * holding area until TypeScript ingests the records, not storage. + */ +private const val RING_HEALTH_MAX_RECORDS = 256 + +/** + * Floor between health pulls, independent of how often the ring + * reconnects. Heart rate/HRV/SpO2 update hourly at the source and steps + * every 10 minutes (confirmed from the real export, + * `knowledge/inbox/Even_health_data/`). + * + * **Reduced 30min -> 5min on 2026-09-12, and its JOB CHANGED.** The + * 30-minute figure was always meant as a CADENCE - how often to collect - + * but it was implemented here as a floor, which is a different thing. The + * result was that a connected, stable ring pulled *never*: nothing + * drives a pull on a timer, only `onRingReady()` on reconnect, so the + * floor was the only clock in the system and it gated a pull that had + * nothing to trigger it. + * + * The cadence now lives where it belongs, on a wall-clock-aligned tick + * (:01 and :31) in `health-live.ts`. What remains here is purely an + * ANTI-SPAM floor: stop a burst of reconnects turning into a burst of + * requests against the race documented on [requestRingHealth]. + * That job needs 5 minutes, not 30. + */ +private const val RING_HEALTH_MIN_PULL_INTERVAL_MS = 5L * 60L * 1000L + +/** + * Floor for a pull the user actually asked for by opening the health app, + * as opposed to the automatic one above. + * + * Deliberately much shorter than the automatic interval but **not + * zero**. An automatic pull is speculative — nobody is waiting for it, so + * there is no reason to spend a request. Opening the health app is the + * opposite: it is an explicit ask, and the response-driven + * [requestRingHealth] waits for each type's DATA and ACKs its pages before + * advancing, which is what made the backlog-discard race survivable in the + * first place. A floor still has to exist, because the discard risk + * documented on `requestRingHealth()` is real and open/close/open would + * otherwise hammer the ring. + */ +private const val RING_HEALTH_ON_DEMAND_MIN_INTERVAL_MS = 60L * 1000L + +/** + * How many times a pull that ABORTED may be resumed inside the anti-spam + * floor before it goes back to waiting that floor out. + * + * The floor exists to stop SPECULATIVE repeat pulls, because a request + * that loses its race can permanently consume backlog - see + * [requestRingHealth]. Resuming a pull that never got a single answer is a + * different thing: nothing was ever in flight to be lost. + * + * Measured 2026-09-12: the 09:33 pull got `no RSP` for 0x1, 0x4 + * and 0x2 and then died on `write error: IllegalStateException: Not + * connected`. Every attempt after it was refused by the 30-minute floor, so + * the rest of that night's data was simply never requested again - the + * night's second sleep block went with it. The floor was protecting against + * the wrong thing. + * + * Bounded and non-looping on purpose: the budget is spent whether or not + * the retries help, and a pull that completes resets it. Worst case is two + * extra attempts, then silence until the floor expires. + * + * ⚠ UNTESTED, and worth knowing before trusting this: whether an aborted + * pull's data is still on the ring at all, or was discarded when the ring + * RSP'd (it did not RSP here, which is the reason to think it survives). + * Nobody knows. The retry costs little if the data is gone. + */ +private const val RING_HEALTH_ABORTED_RETRY_LIMIT = 2 + +/** + * Gap before an aborted pull may be resumed. Short, but not zero - a link + * that just failed a write needs time to come back, and a tight loop + * against a dead connection helps nobody. + */ +private const val RING_HEALTH_ABORTED_RETRY_GAP_MS = 60L * 1000L + +/** + * Direct mode: floor between health windows (see beginRingHealthWindowLocked). + * A window costs the user ring gestures for the length of two reconnects and a + * pull, so opening and closing the Health app must not keep bouncing the link. + * The aligned :01/:31 pulls are well outside it. + */ +private const val RING_HEALTH_WINDOW_MIN_INTERVAL_MS = 5L * 60L * 1000L + +/** + * Direct mode: how long a health window waits for its phone-role link to be + * up before giving up and handing the link back to the glasses role. Bounds + * only the connect; a pull that has started runs to completion on the ring + * worker before the deadline is looked at again. + */ +private const val RING_HEALTH_WINDOW_CONNECT_TIMEOUT_MS = 60_000L + +/** + * Direct mode: a requested health window waits until the ring has been idle + * this long, so it does not take the ring away in the middle of a gesture + * sequence. The request stays pending meanwhile. + */ +private const val RING_HEALTH_WINDOW_INPUT_IDLE_MS = 5_000L + +/** + * Pause between dropping the direct link and reconnecting it in another role. + * The ring frees a role when the connection ends, but Android keeps the LE + * link up for a moment after the last client closes, and a new client + * registered in that moment reuses it - the ring would then see the old + * role's handle ask for the other role, which stock firmware treats as a + * fatal assertion (openCFW CONNECTION-ROLE-ASSIGNMENT-CORRELATION.md). + */ +private const val RING_ROLE_SWITCH_SETTLE_MS = 3_000L + +/** First pause after a failed ring write; doubles per consecutive failure. See [writeRingFrame]. */ +private const val RING_WRITE_BACKOFF_MS = 1_000L +private const val RING_WRITE_BACKOFF_MAX_MS = 15_000L + +/** + * Device-channel commands Even's real app fires in the gaps between + * health requests - battery (0x01), firmware version (0x02), device id + * (0x0b) - found by extracting the literal wire order of a real + * successful sync (same capture as ringHealthRspTimeoutMs; two + * independent syncs in it agree). Rotated one-per-health-type here rather + * than replicated exactly (Even's real cadence isn't perfectly regular + * either - compare the two syncs in the capture), since which of these, + * if any, is actually load-bearing for the ring answering has never + * been isolated. This is matching cadence, not a confirmed protocol + * requirement. + * + * Even's sync also sends 0x0a, which used to be replayed here with the + * capture's "opaque blob". 0x0a is advStart: the blob was the capturing + * phone's two glasses MACs, which the ring persists as the only glasses it + * accepts. It is now sent only on request (queueRingConfigCommandLocked), + * with our own glasses' addresses. + */ +private val RING_DEVICE_PING_CMD_LO = intArrayOf(0x01, 0x02, 0x0b) + +/** + * A snapshot of the health buffer together with the watermark identifying + * it. + * + * The two have to come out under ONE lock. Reading the list and the + * count separately would let a page land in between, and the consumer would + * then clear a record nothing had ingested - the exact failure the + * watermark exists to prevent. + */ +class RingHealthBatch internal constructor( + val records: List, + /** Total-ever-added at the instant of the snapshot. */ + val watermark: Long, +) + +/** Sole owner of blocking ring operations; callbacks only enqueue ACKs. */ +internal fun GlassesSessionCore.runRingWorker() { + while (running) { + try { + expireRingHealthWindow() + restartRingLinkForRoleChange() + if (shouldAttemptRingConnect()) tryConnectRing("ring worker") + if (!running) break + flushRingConfigCommands() + runRingGlassesSetup() + flushRingOutbound() + runRequestedRingHealthPull() + resumeAbortedRingHealthPull() + monitor.withLock { + if (running) monitor.awaitMs(100) + } + } catch (t: Throwable) { + if (!running) { + // disconnect() interrupted a blocking wait; nothing to recover. + break + } + logLine("ring worker error: " + GlassesSessionCore.safeMessage(t)) + // A ring failure must not tear down the glasses session. + monitor.withLock { + ringConnected = false + ringNotificationsReady = false + ringReconnectAfterMs = now() + ConnectionOptions.RING_RECONNECT_DELAY_MS + lastDirectRingError = "worker error: " + GlassesSessionCore.safeMessage(t) + } + link.disconnect(ringAddress) + } + } + logLine("ring worker stop") +} + +/** + * The R1 health-data protocol branch. Returns true when the value belonged + * to that protocol and must not fall through to the gesture decoder. + * + * Runs on the GATT callback thread, so it only ever queues writes. + * + * Restricted to R1_NOTIFY_CHAR_UUID because that is the notify + * characteristic (ATT handle 0x0017) the reference capture shows this + * protocol on; gesture traffic on the other notify characteristic is left + * strictly alone rather than being offered to the reassembler. + */ +internal fun GlassesSessionCore.handleRingHealthNotification(characteristicUuid: String, data: ByteArray): Boolean { + if (BleProtocol.R1_NOTIFY_CHAR_UUID != characteristicUuid || !host.supportsRingHealth()) { + return false + } + + val intake = monitor.withLock { ringReassembler.accept(data) } + if (!intake.consumed) { + return false + } + + val arrivalMs = now() + monitor.withLock { + lastIncomingAtMs = arrivalMs + } + if (intake.note != null) { + logLine("ring frame: " + intake.note) + } + val frame = intake.frame + if (frame == null) { + // Genuinely silent by default: the reassembler consumed these + // bytes (e.g. as a fragment awaiting its continuation) without + // yet producing a complete frame, and intake.note was null too. + // This exact blind spot cost real debugging time on 2026-09-10 - + // DATA appeared to simply never arrive, when the actual cause + // (once found, by temporarily logging every raw notification + // unconditionally) was a real handshake gap, not a dropped + // frame here. If DATA ever looks like it's going missing again + // with nothing logged at all, re-add that raw hex dump here + // rather than assuming nothing arrived on the wire. + logLine("ring frame: consumed, no complete frame yet, len=" + data.size) + return true + } + if (!frame.crcOk) { + // Never act on a frame whose CRC failed: the payload offsets below + // are only meaningful for an intact frame. + logLine("ring frame CRC mismatch " + frame.describe()) + return true + } + + // Keep the original bytes before acknowledging them. Ring firmware + // variants can have layouts we cannot decode yet, and the ring may + // never deliver an acknowledged page again. This private journal also + // lets us diagnose a new device without repeatedly draining its data. + if (!journalRingFrame(frame)) return true + + // Route on the CHAN byte, not on the shape of the payload. + if (frame.chan != RingProtocol.CHAN_HEALTH) { + val status = RingProtocol.decodeDeviceStatus(frame) + if (status != null) { + monitor.withLock { + directRingBattery = status.battery + directRingCharging = status.charging + emitBatteryState(headsetBattery, headsetCharging) + } + logLine("direct ring battery " + status.battery + "% charging=" + status.charging) + } + recordRingConfigResponse(frame) + logDebug("ring device frame " + frame.describe()) + return true + } + + if (frame.kind == RingProtocol.KIND_RSP) { + logDebug("ring health rsp " + frame.describe()) + monitor.withLock { + ringHealthRspSeen = true + monitor.signalAll() + } + return true + } + if (frame.kind != RingProtocol.KIND_DATA) { + logDebug("ring health frame " + frame.describe()) + return true + } + + var record: RingProtocol.HealthRecord? = null + try { + record = RingProtocol.decode(frame, currentTimeMillis()) + } catch (t: Throwable) { + logLine("ring health decode error " + frame.describe() + ": " + GlassesSessionCore.safeMessage(t)) + } + if (record == null) { + logLine("ring health page undecoded " + frame.describe()) + } else { + monitor.withLock { + if (ringHealthRecords.size >= RING_HEALTH_MAX_RECORDS) { + // This was silent. An eviction here drops a record that + // nothing has ingested yet - real data lost inside the + // phone, with no trace anywhere. Say so. With the consume + // path in place the buffer should never reach this size; + // if this line ever appears, the consumer has stopped. + logLine("ring health: buffer FULL at " + RING_HEALTH_MAX_RECORDS + + " - dropping the oldest UNINGESTED record") + ringHealthRecords.removeAt(0) + } + ringHealthRecords.add(record) + ringHealthTotalAdded++ + } + logLine("ring health " + record.summary()) + } + + // Acknowledge the page regardless of whether we could decode it: the + // ACK is what keeps the ring sending, and a decode gap must not stall + // the rest of the transfer. + queueRingPageAck(frame) + return true +} + +internal fun GlassesSessionCore.queueRingPageAck(page: RingProtocol.Frame) { + monitor.withLock { + if (!ringNotificationsReady) { + return + } + val ack = RingProtocol.buildPageAck( + nextRingSeqLocked(), + nextRingNonceLocked(), + page.cmdHi, + page.cmdLo, + page.seq + ) + ringOutbound.addLast(ack) + ringHealthPageCounter++ + // Wakes the ring worker, independently of the glasses. + monitor.signalAll() + } +} + +internal fun GlassesSessionCore.journalRingFrame(frame: RingProtocol.Frame): Boolean { + return try { + host.appendRingFrameJournal( + "\n{\"receivedAtMs\":" + currentTimeMillis() + ",\"raw\":\"" + GlassesSessionCore.hex(frame.raw) + "\"}\n") + true + } catch (error: Throwable) { + logLine("ring frame persistence failed; page not acknowledged: " + GlassesSessionCore.safeMessage(error)) + false + } +} + +/** + * The ring's data channel is subscribed: send the device-channel handshake, + * then run a health pull unless the anti-spam floor says one ran recently. + * Ring worker only (blocking). + */ +internal fun GlassesSessionCore.onRingDataChannelReady() { + try { + // The handshake mirrors what Even's own app repeats on every one + // of its sync bursts (confirmed in the reference capture), so + // sending it on every reconnect matches known-working behavior. + // The actual health pull is throttled separately below - see + // ringHealthLastRequestedAtMs and requestRingHealth()'s own + // race-condition warning for why. + sendRingHandshake() + val now = now() + val dueForHealthPull: Boolean + val lastRequestedAtMs: Long + monitor.withLock { + lastRequestedAtMs = ringHealthLastRequestedAtMs + // A health window was opened for exactly this pull, and its own + // floor was applied when it opened. + dueForHealthPull = ringHealthWindowActive || ringHealthPullDueLocked(now) + if (dueForHealthPull) { + ringHealthLastRequestedAtMs = now + } + } + if (dueForHealthPull) { + runRingHealthPull() + } else { + logLine("ring health: pull skipped, last one was " + ((now - lastRequestedAtMs) / 1000) + "s ago") + } + } finally { + // Completed, aborted or threw: either way the link goes back to the + // glasses role, so a failed pull never costs the user gestures for + // longer than the attempt. + monitor.withLock { endRingHealthWindowLocked("pull finished") } + } +} + +/** + * The direct link's role for its next setup: the configured one, except the + * phone role while a health window is open. Caller holds `monitor`. + */ +internal fun GlassesSessionCore.effectiveRingRoleLocked(): String = + if (ringHealthWindowActive) DIRECT_RING_ROLE_PHONE else directRingRole + +/** + * Direct mode's health sync. Caller holds `monitor`. + * + * In Direct mode the direct link holds the ring's glasses role (gestures, + * battery), and the ring answers system requests - health included - only to + * its phone role. One link cannot hold both: the stock role setter treats the + * same connection asking for the second role as a fatal assertion, and live + * "both" links died every ~6 s (notes/ring-link-control.md). So a pull borrows + * the phone role: drop the link, reconnect it with only the data CCCD (the + * health-mode setup, which runs the handshake and the pull), then drop it + * again and reconnect in the glasses role. Ring gestures stop for that long, + * typically well under a minute; the glasses' own touch input is unaffected. + * + * Every exit returns the link to the glasses role: the pull finishing + * ([onRingDataChannelReady]), the connect deadline ([expireRingHealthWindow]), + * or a role change ([GlassesSessionCore.setDirectRingRole]). + * + * Not yet hardware-tested: whether the ring restores the bonded peer's legacy + * CCCD on the phone-role reconnect and assigns the glasses role from it. If it + * does, the phone-role pairAuth would be refused or the link dropped, the pull + * would abort, and the window would close; look for "health window" in the log. + */ +internal fun GlassesSessionCore.beginRingHealthWindowLocked(now: Long, reason: String) { + ringHealthWindowActive = true + ringHealthWindowDeadlineMs = now + RING_HEALTH_WINDOW_CONNECT_TIMEOUT_MS + // Counts as the attempt for the window floor whether or not it succeeds, + // so a ring that never comes up in the phone role is retried at most + // once per floor. + ringHealthLastRequestedAtMs = now + // A link already set up in the glasses role has to be dropped. One that + // is still connecting sets up in the phone role when it lands. + if (ringNotificationsReady) { + ringRoleReconnectPending = true + } + monitor.signalAll() + logLine("ring health: opening a health window ($reason): direct link to the phone role for one pull") +} + +/** Close a health window and put the link back in the glasses role. Caller holds `monitor`. */ +internal fun GlassesSessionCore.endRingHealthWindowLocked(reason: String) { + if (!ringHealthWindowActive) return + ringHealthWindowActive = false + ringHealthWindowDeadlineMs = 0L + // Only a link that finished its phone-role setup has to be dropped; one + // still connecting picks up the glasses role when it sets up. + if (directRingRole == DIRECT_RING_ROLE_GLASSES && ringNotificationsReady) { + ringRoleReconnectPending = true + } + monitor.signalAll() + logLine("ring health: closing the health window ($reason); direct link back to the glasses role") +} + +/** Ring-worker tick: give up on a health window whose phone-role link never came up. */ +internal fun GlassesSessionCore.expireRingHealthWindow() { + monitor.withLock { + if (!ringHealthWindowActive || now() < ringHealthWindowDeadlineMs) return + lastRingHealthPullResult = "not run: phone-role link did not come up" + lastRingHealthPullAtMs = now() + endRingHealthWindowLocked("phone-role link not up after " + + (RING_HEALTH_WINDOW_CONNECT_TIMEOUT_MS / 1000L) + "s") + } +} + +/** + * Direct mode's on-demand pull: open a health window for an explicit request + * (Health app opened, aligned :01/:31 tick), and once per session without one + * so the first pull does not wait for the next aligned tick. Ring worker only. + */ +private fun GlassesSessionCore.startRequestedRingHealthWindow() { + val now = now() + monitor.withLock { + if (!host.supportsRingHealth()) { + ringHealthPullRequested = false + return + } + if (ringHealthWindowActive) { + // The open window pulls as soon as its link is up. + ringHealthPullRequested = false + return + } + val firstThisSession = ringHealthLastRequestedAtMs == 0L + if (!ringHealthPullRequested && !firstThisSession) return + // The ring is only dialed once the glasses session is up + // (shouldAttemptRingConnect); opening sooner would spend the + // window's connect deadline waiting on the glasses. + if (!running || !sessionReady) return + if (!firstThisSession && now - ringHealthLastRequestedAtMs < RING_HEALTH_WINDOW_MIN_INTERVAL_MS) { + ringHealthPullRequested = false + logLine("ring health: health window skipped, last pull attempt was " + + ((now - ringHealthLastRequestedAtMs) / 1000) + "s ago") + return + } + if (lastDirectRingInputAtMs != 0L && now - lastDirectRingInputAtMs < RING_HEALTH_WINDOW_INPUT_IDLE_MS) { + return // the ring is in use; try again on a later tick + } + ringHealthPullRequested = false + beginRingHealthWindowLocked(now, if (firstThisSession) "first pull this session" else "requested") + } +} + +/** + * Whether an automatic pull may run now. Caller must hold `monitor`. + * + * Two ways to be due: the ordinary anti-spam floor has expired, or the + * last pull ABORTED and still has retry budget. The second is not a + * speculative repeat - see RING_HEALTH_ABORTED_RETRY_LIMIT. + */ +internal fun GlassesSessionCore.ringHealthPullDueLocked(now: Long): Boolean { + if (ringHealthLastRequestedAtMs == 0L) { + return true + } + val since = now - ringHealthLastRequestedAtMs + if (since >= RING_HEALTH_MIN_PULL_INTERVAL_MS) { + return true + } + return ringHealthAbortedRetries > 0 && since >= RING_HEALTH_ABORTED_RETRY_GAP_MS +} + +/** + * Run a pull and account for whether it finished. The ONLY place + * [requestRingHealth] may be called from, so that every path shares one + * definition of "aborted". + */ +internal fun GlassesSessionCore.runRingHealthPull() { + val pagesBefore = monitor.withLock { ringHealthPageCounter } + val completed = requestRingHealth() + monitor.withLock { + val pages = ringHealthPageCounter - pagesBefore + lastRingHealthPullResult = (if (completed) "completed" else "aborted") + ", $pages pages" + lastRingHealthPullAtMs = now() + if (completed) { + ringHealthAbortedRetries = 0 + } else if (ringHealthAbortedRetries < RING_HEALTH_ABORTED_RETRY_LIMIT) { + ringHealthAbortedRetries++ + logLine("ring health: aborted pull may resume in " + + (RING_HEALTH_ABORTED_RETRY_GAP_MS / 1000L) + "s (retry " + + ringHealthAbortedRetries + "/" + RING_HEALTH_ABORTED_RETRY_LIMIT + ")") + } else { + ringHealthAbortedRetries = 0 + logLine("ring health: aborted pull retry budget spent, back to the " + + (RING_HEALTH_MIN_PULL_INTERVAL_MS / 60000L) + "-minute anti-spam floor") + } + } +} + +/** + * Ring-worker tick that resumes a pull which ABORTED. + * + * Distinct from [runRequestedRingHealthPull]: nobody asked for this one. It + * exists because the automatic pull otherwise only fires from the ring-ready + * path, so an abort that is not followed by a reconnect would never be + * retried at all. + */ +internal fun GlassesSessionCore.resumeAbortedRingHealthPull() { + val now = now() + monitor.withLock { + if (ringHealthAbortedRetries == 0) { + return + } + // Direct mode does not resume here: a retry would mean another pair + // of role switches, so the next requested or aligned window retries. + if (!ringConnected || !ringNotificationsReady || directRingRole == DIRECT_RING_ROLE_GLASSES) { + return + } + if (now - ringHealthLastRequestedAtMs < RING_HEALTH_ABORTED_RETRY_GAP_MS) { + return + } + ringHealthLastRequestedAtMs = now + } + logLine("ring health: resuming an aborted pull") + runRingHealthPull() +} + +/** Ring-worker side of [GlassesSessionCore.requestRingHealthNow]. */ +internal fun GlassesSessionCore.runRequestedRingHealthPull() { + if (monitor.withLock { directRingRole == DIRECT_RING_ROLE_GLASSES }) { + // Direct mode used to drop every request here, so the Health app + // never got data; the pull has to borrow the phone role instead. + startRequestedRingHealthWindow() + return + } + val now = now() + monitor.withLock { + if (!ringHealthPullRequested) { + return + } + ringHealthPullRequested = false + if (!ringConnected || !ringNotificationsReady) { + logLine("ring health: on-demand pull skipped, ring not ready") + return + } + if (ringHealthLastRequestedAtMs != 0L + && now - ringHealthLastRequestedAtMs < RING_HEALTH_ON_DEMAND_MIN_INTERVAL_MS) { + logLine("ring health: on-demand pull skipped, last one was " + + ((now - ringHealthLastRequestedAtMs) / 1000) + "s ago") + return + } + ringHealthLastRequestedAtMs = now + } + logLine("ring health: on-demand pull requested") + runRingHealthPull() +} + +/** + * Device-channel initialization. 00:0e enables health recording; 00:05 sets + * the clock (signed timezone minutes plus Unix seconds). + * + * The inherited extra timezone shift is WRONG: on this PDT ring, fresh HR + * timestamps track receipt time + 7h. Firmware expects UTC seconds and + * applies the timezone separately. Do not simply deploy a seven-hour + * rewind: stock firmware can format its health database on a backward + * jump >= 1h. Existing pages also contain mixed clock domains and invalid + * daily anchors, so their dates cannot be repaired by one subtraction. + * + * TODO: controlled UTC migration after preserving ring history. Retain the + * existing wire behavior until that migration is authorized and validated. + * See notes/ring-health-live-validation.md for evidence and the next test. + */ +internal fun GlassesSessionCore.sendRingHandshake() { + val nowMs = currentTimeMillis() + val utcOffsetMs = localUtcOffsetMs(nowMs) + val clockOffsetSeconds = -utcOffsetMs / 1000L + val liveClockSeconds = (nowMs / 1000L) + clockOffsetSeconds + logLine("ring handshake legacy clock offset seconds = " + clockOffsetSeconds + + " (tz " + localTimeZoneId() + ")") + val clock = le32(liveClockSeconds) + + val seqs = IntArray(6) + val nonces = IntArray(6) + monitor.withLock { + for (i in 0 until 6) { + seqs[i] = nextRingSeqLocked() + nonces[i] = nextRingNonceLocked() + } + } + + val frames = arrayOf( + // pairAuth. Its bytes after the header must be exactly 3f 01 01: + // measured 2026-09-11 across all four btsnoop captures, 46 real + // 00:08 writes, zero exceptions: + // 3f0101 (3 bytes) -> 3 writes, ALL answered (12-21 notifications each) + // 01003f0101 (5 bytes) -> 43 writes, ALL silent (zero notifications) + // The 5-byte form was ours, failing and retrying all night. The + // first two bytes are not a nonce: they are the frame's phone + // checksum (3f01 is its value at seq 1), and the role byte 01 must + // follow it directly. A nonce in front shifted the role byte, so the + // ring never assigned us the phone role and ignored everything after. + // buildPairAuth computes the checksum; at seq 1 it is the captured + // frame byte for byte (see GlassesRingLinkTest). + RingProtocol.buildPairAuth(seqs[0]), + RingProtocol.buildFrame(RingProtocol.CHAN_DEVICE, RingProtocol.KIND_DATA, 0x00, 0x0e, seqs[1], + le16(nonces[1]) + clock + byteArrayOf(0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)), + RingProtocol.buildFrame(RingProtocol.CHAN_DEVICE, RingProtocol.KIND_DATA, 0x00, 0x05, seqs[2], + le16(nonces[2]) + le16(utcOffsetMs / 60000) + clock), + // Battery, firmware version, device id - all bare nonce-only REQs, + // same shape as the health requests. + RingProtocol.buildFrame(RingProtocol.CHAN_DEVICE, RingProtocol.KIND_REQ, 0x00, 0x01, seqs[3], + le16(nonces[3])), + RingProtocol.buildFrame(RingProtocol.CHAN_DEVICE, RingProtocol.KIND_REQ, 0x00, 0x02, seqs[4], + le16(nonces[4])), + RingProtocol.buildFrame(RingProtocol.CHAN_DEVICE, RingProtocol.KIND_REQ, 0x00, 0x0b, seqs[5], + le16(nonces[5])), + // Even's handshake ends with advStart (00:0A) naming its glasses; it is + // not replayed here (see RING_DEVICE_PING_CMD_LO). + ) + for (frame in frames) { + if (!writeRingFrame(frame, "handshake")) { + return + } + } + logLine("ring health: sent device-channel handshake (" + frames.size + " frames)") +} + +private fun le16(value: Int): ByteArray = byteArrayOf(value.toByte(), (value ushr 8).toByte()) + +private fun le32(value: Long): ByteArray = + byteArrayOf(value.toByte(), (value ushr 8).toByte(), (value ushr 16).toByte(), (value ushr 24).toByte()) + +/** + * Pull the five health record types. Each request is a bare 17-byte frame + * carrying only a nonce; the ring answers with an RSP on the same + * sequence number, then - sometimes - pushes one or more DATA pages, + * which arrive through [handleRingHealthNotification]. + * + * **Response-driven, not sleep-driven (rewritten 2026-09-11).** + * The original version fired all five REQs on a blind fixed sleep and + * only flushed queued page ACKs after the whole loop finished - a real + * successful Even sync does the opposite: it waits for each REQ's own RSP, + * waits for DATA to go idle, ACKs immediately, then interleaves one + * device-channel command before the next health type. This version does + * the same, using the monitor's await/signalAll idiom already used + * elsewhere in the session. + * + * **Race condition, confirmed live 2026-09-10 - this is what the + * rewrite above addresses, not a reason to remove this warning.** The + * ring appears to hold only one health type's response in flight at a + * time. Sending the next health REQ before the previous type's DATA + * page(s) have actually arrived silently drops the earlier type's DATA: + * you still get its RSP, you never get its DATA, and nothing in the + * protocol signals an error. Evidence: five REQs fired back-to-back (the + * old blind-sleep version, badly timed) got five RSPs and zero DATA + * pages over more than a minute of waiting. + * + * **Worse: a lost race may PERMANENTLY discard that backlog, not + * just delay it.** On 2026-09-10, real HRV/SpO2/sleep backlog that + * should have existed (unreported since that morning, confirmed against + * the hourly export cadence in `knowledge/inbox/Even_health_data`) + * did not come back on a later, more carefully spaced retry. The working + * theory - not proven, but treat it as true until disproven, because the + * downside of being wrong is silent data loss with nothing to catch it + * - is that the ring advances its own "last delivered" watermark for a + * type as soon as it RSPs a REQ for it, whether or not the DATA page + * actually made it out. **Do not send a speculative or test health REQ + * for a type unless you intend to actually receive and persist its + * DATA** - re-requesting will not recover what an earlier, raced + * request already consumed. Waiting for DATA to go idle before advancing + * reduces how often this can happen but does not prove it can no longer + * happen (e.g. if the ring's real per-type timeout is shorter than + * ringHealthDataIdleMs for some type). + * + * A separate, completely ordinary case looks identical from the wire + * alone: an RSP with no DATA can also just mean the ring genuinely has + * nothing new for that metric since the last successful pull. There is + * currently no way to tell "raced and silently discarded" apart from + * "genuinely nothing new" other than knowing independently whether fresh + * data should exist (e.g. from the export's own sampling cadence). + * + * Runs on the ring worker, which is the only thread allowed to call the + * blocking write path - the wait loops below block that same thread, which + * is why [flushRingOutbound] is called inside the response and DATA waits + * rather than relying on the ring loop's own call to it. + */ +internal fun GlassesSessionCore.requestRingHealth(): Boolean { + // A previous attempt may have left an ACK queued after a failed write. + // Never start another type's request ahead of that acknowledgement. + if (flushRingOutbound() < 0) return false + val commands = RingProtocol.HEALTH_COMMANDS + var rspCount = 0 + for (i in commands.indices) { + val command = commands[i] + val frame = monitor.withLock { + ringHealthRspSeen = false + RingProtocol.buildHealthRequest(command, nextRingSeqLocked(), nextRingNonceLocked()) + } + if (!writeRingFrame(frame, "health request 0x" + command.toString(16))) { + // ABORTED: the sequence stopped partway. Distinct from "the + // ring had nothing for a type", which is an ordinary outcome + // and leaves the loop running - see the return below. + logLine("ring health: pull ABORTED on write at 0x" + command.toString(16) + + " (" + i + " of " + commands.size + " types attempted, " + + rspCount + " answered)") + return false + } + + if (awaitRingHealthRsp(ringHealthRspTimeoutMs)) { + rspCount++ + if (!awaitRingHealthDataIdle(ringHealthDataIdleMs)) { + logLine("ring health: pull ABORTED while acknowledging DATA") + return false + } + } else { + logLine("ring health: pull ABORTED waiting for RSP at 0x" + command.toString(16)) + return false + } + + if (i < commands.size - 1) { + sendRingDevicePing(RING_DEVICE_PING_CMD_LO[i % RING_DEVICE_PING_CMD_LO.size]) + } + } + + // Two more ways to have not really completed, both distinguishable from + // "completed but empty": + // + // - the link dropped while the loop was running, so the later types + // were written into nothing; + // - the ring answered NONE of the five. A type with no backlog still + // RSPs (measured: five REQs, five RSPs, zero DATA), so zero RSPs + // across the whole sequence means the ring was not answering at + // all, not that there was nothing to send. + // + // An RSP with no DATA remains ambiguous per type and is NOT treated as + // a failure here - that is the ordinary "nothing new" case. + val stillConnected = monitor.withLock { ringConnected } + if (!stillConnected || rspCount == 0) { + logLine("ring health: pull ABORTED - ran all " + commands.size + " types but " + + (if (stillConnected) "the ring answered none of them" else "the link dropped")) + return false + } + logLine("ring health: requested " + commands.size + " record types, " + rspCount + " answered") + return true +} + +/** Block (ring worker) until the health RSP flag is set or the timeout + * elapses. Not correlated to a specific command/seq - like the rest of + * this protocol's request path, it trusts the ring answers in order. */ +internal fun GlassesSessionCore.awaitRingHealthRsp(timeoutMs: Long): Boolean { + val deadline = now() + timeoutMs + while (true) { + // A DATA notification may precede its RSP. Writes must happen + // outside the lock so GATT callbacks can continue delivering pages. + if (flushRingOutbound() < 0) return false + monitor.withLock { + if (!running || !ringConnected) return false + if (ringHealthRspSeen) return true + if (ringOutbound.isEmpty()) { + val remaining = deadline - now() + if (remaining <= 0) { + return false + } + monitor.awaitMs(minOf(remaining, 100L)) + } + } + } +} + +/** Block (ring worker) until DATA pages go idle for [idleMs], extending + * the window on every new page so a real multi-page backlog transfer isn't + * cut short. Not filtered by health type - correct given the ring only has + * one type in flight at a time (see [requestRingHealth]), so any page + * arriving here belongs to the type just requested. */ +internal fun GlassesSessionCore.awaitRingHealthDataIdle(idleMs: Long): Boolean { + var idleDeadline = now() + idleMs + var lastSeenCounter = -1 + while (true) { + // The next page can depend on this ACK. Waiting for idle first + // mistakes an ACK-paced transfer for a completed transfer. + val acknowledged = flushRingOutbound() + if (acknowledged < 0) return false + monitor.withLock { + if (!running || !ringConnected) return false + if (acknowledged > 0 || ringHealthPageCounter != lastSeenCounter) { + lastSeenCounter = ringHealthPageCounter + // Start the next-page window AFTER the blocking ACK write. + idleDeadline = now() + idleMs + } + // A callback may have queued a page between flush and lock. + if (ringOutbound.isEmpty()) { + val remaining = idleDeadline - now() + if (remaining <= 0) return true + monitor.awaitMs(minOf(remaining, 100L)) + } + } + } +} + +/** + * Fire one bare device-channel REQ in the gap between health types, + * matching (without waiting on a response) the cadence a real Even sync + * uses. See RING_DEVICE_PING_CMD_LO for provenance and caveats. + */ +internal fun GlassesSessionCore.sendRingDevicePing(cmdLo: Int) { + val frame = monitor.withLock { + RingProtocol.buildRequest(RingProtocol.CHAN_DEVICE, 0x00, cmdLo, nextRingSeqLocked(), nextRingNonceLocked()) + } + writeRingFrame(frame, "device ping 0x" + cmdLo.toString(16)) +} + +/** + * Write one already-built ring frame. Ring worker only (blocking). + * + * After a failure, further writes fail immediately (without touching the + * link) until an exponential backoff expires. The ring worker otherwise + * retries a queued ACK every 100ms tick, and each failing attempt can occupy + * the GATT pipeline the glasses' display writes need for up to the write + * timeout. + */ +internal fun GlassesSessionCore.writeRingFrame( + frame: ByteArray, what: String, characteristicUuid: String = BleProtocol.R1_WRITE_CHAR_UUID, +): Boolean { + val blockedForMs = monitor.withLock { ringWriteBlockedUntilMs - now() } + if (blockedForMs > 0) { + return false + } + val ok = try { + val written = link.writeFrames( + ringAddress, + characteristicUuid, + listOf(frame), + ConnectionOptions.WRITE_MODE, + ConnectionOptions.WRITE_TIMEOUT_MS + ) + if (!written) { + logLine("ring $what write failed") + } + written + } catch (t: Throwable) { + logLine("ring " + what + " write error: " + GlassesSessionCore.safeMessage(t)) + false + } + monitor.withLock { + if (ok) { + ringWriteFailures = 0 + } else { + val backoffMs = minOf(RING_WRITE_BACKOFF_MAX_MS, RING_WRITE_BACKOFF_MS shl minOf(ringWriteFailures, 4)) + ringWriteFailures++ + ringWriteBlockedUntilMs = now() + backoffMs + logLine("ring writes paused for " + backoffMs + "ms after " + ringWriteFailures + " consecutive failure(s)") + } + } + return ok +} + +/** + * Drain queued ring frames (page ACKs). Ring worker only. Returns the + * number written, or -1 if the link is unavailable or a write failed. + */ +internal fun GlassesSessionCore.flushRingOutbound(): Int { + var acknowledged = 0 + while (true) { + val frame = monitor.withLock { + if (!ringNotificationsReady) return -1 + ringOutbound.firstOrNull() ?: return acknowledged + } + if (!writeRingFrame(frame, "page ack")) return -1 + monitor.withLock { + // Keep failed writes queued for retry. A disconnect can clear + // the queue during the write, so remove this exact frame only. + val index = ringOutbound.indexOfFirst { it === frame } + if (index >= 0) ringOutbound.removeAt(index) + acknowledged++ + } + } +} + +internal fun GlassesSessionCore.nextRingSeqLocked(): Int { + ringSeq = (ringSeq + 1) and 0xff + if (ringSeq == 0) { + ringSeq = 1 + } + return ringSeq +} + +internal fun GlassesSessionCore.nextRingNonceLocked(): Int { + ringNonce = (ringNonce + 1) and 0xffff + return ringNonce +} + +// --------------------------------------------------------------------------- +// The glasses' own link to the ring (sid 0x80 pair-manager commands) +// +// While the glasses hold the ring, it reports gestures only to them, so a +// direct phone link sees nothing. These ask the glasses to let go of it, to +// forget it, and to take it back. Shapes and handler behavior come from +// g2-kit-unofficial's protos and openCFW's decompilation of +// pb_service_pair_mgr.c; the connect form also matches the official app's +// decompiled builder. None of it has been verified on hardware. UNPAIR_INFO +// wipes the glasses' stored ring pairing; the Even app can re-pair. + +/** + * Parse "AA:BB:CC:DD:EE:FF" into wire order, least-significant byte first, + * for both ring and glasses addresses. The official app's + * StringExt.macToBytes reverses the same way for RING_CONNECT_INFO, and the + * R1 (a Nordic part) compares advStart targets against its little-endian + * peer addresses. + */ +internal fun macWireBytes(address: String): ByteArray? { + val parts = address.trim().split(':') + if (parts.size != 6) return null + val bytes = ByteArray(6) + for (i in 0 until 6) { + val value = parts[i].toIntOrNull(16) ?: return null + bytes[5 - i] = value.toByte() + } + return bytes +} + +/** + * Queue one ring-link command to both temples (only the ring-owning temple + * acts on a connect; either may hold the link). Actions: + * - "disconnect": DISCONNECT_INFO. Drops the link and resets the retry + * counter without touching the stored ring target; the glasses' own + * reconnect policy may take the ring back later. + * - "release": RING_CONNECT_INFO connect=0. Also cancels pending connect + * timeouts and clears the connect mode, so it may hold off auto-reconnect. + * - "connect": RING_CONNECT_INFO connect=1 with the ring's MAC and name. + * - "unpair": UNPAIR_INFO dev=RING. The glasses forget the ring, so they + * stop reconnecting to it until something sends "connect" again. + * Both RING_CONNECT_INFO forms overwrite the stored target, so they echo the + * target the glasses reported when there is one. + */ +internal fun GlassesSessionCore.queueGlassesRingLinkCommandLocked( + action: String, fallbackAddress: String, fallbackName: String, +): Boolean { + val reported = glassesRingMac + val mac = reported ?: macWireBytes(fallbackAddress) + if (mac == null) { + logLine("glasses ring $action skipped: no ring address") + return false + } + val name = (if (reported != null && glassesRingName.isNotEmpty()) glassesRingName else fallbackName) + .encodeToByteArray() + val macSource = if (reported != null) "glasses-reported" else "configured" + lastRingLinkCommand = "$action mac=${GlassesSessionCore.hex(mac)} ($macSource)" + lastRingLinkCommandAtMs = now() + lastRingLinkResultR = "sent" + lastRingLinkResultL = "sent" + for (leftArm in booleanArrayOf(false, true)) { + val message = messageBuilder.ringLinkCommand("glasses ring $action", leftArm) { magic -> + when (action) { + "disconnect" -> BleProtocol.buildRingDisconnectRequest(magic, mac) + "unpair" -> BleProtocol.buildRingUnpairRequest(magic, mac) + "release" -> BleProtocol.buildRingConnectRequest(magic, false, mac, name) + else -> BleProtocol.buildRingConnectRequest(magic, true, mac, name) + } + } + message.onAck = MessageCallback { + val result = "ack " + GlassesSessionCore.hex(message.ackPayload) + if (leftArm) lastRingLinkResultL = result else lastRingLinkResultR = result + logLine("glasses ring $action ${if (leftArm) "L" else "R"} $result") + } + message.onTimeout = MessageCallback { + if (leftArm) lastRingLinkResultL = "no ack" else lastRingLinkResultR = "no ack" + logLine("glasses ring $action ${if (leftArm) "L" else "R"} ack timeout") + } + pendingMessages.addLast(message) + } + logLine("queue glasses ring $action mac=${GlassesSessionCore.hex(mac)} ($macSource) name=${name.decodeToString()}") + return true +} + +/** + * Note ring-link reports from the glasses: RING_CONNECT_INFO notifications + * (connRet 0 = connected, 90 = connect timeout) and sid-0x91 ring events, + * both carrying the ring MAC in the glasses' byte order. Acks to our own + * commands are skipped for the MAC so it never just echoes our guess. + */ +internal fun GlassesSessionCore.recordGlassesRingReportLocked(frame: BleProtocol.ParsedFrame, address: String) { + val report = if (frame.sid == BleProtocol.SID_RING_DATA) BleProtocol.parseRingDataEvent(frame.pb) + else BleProtocol.parseRingConnectInfo(frame.pb) + if (report == null) return + val arm = if (address.equals(leftAddress, ignoreCase = true)) "L" else "R" + val ownAck = inFlightMessages.any { it.sid == frame.sid && it.magic == frame.msgSeq } + val mac = report.ringMac + lastGlassesRingReport = report.source + " " + arm + " code=" + report.code + + (if (mac != null) " mac=" + GlassesSessionCore.hex(mac) else "") + + (if (report.ringName.isNotEmpty()) " name=" + report.ringName else "") + + (if (ownAck) " (ack)" else "") + lastGlassesRingReportAtMs = now() + if (!ownAck && mac != null && mac.size == 6 && mac.any { it.toInt() != 0 }) { + glassesRingMac = mac.copyOf() + if (report.ringName.isNotEmpty()) glassesRingName = report.ringName + } + logLine("glasses ring report: $lastGlassesRingReport") + if (!ownAck && frame.sid != BleProtocol.SID_RING_DATA && report.code == 0) { + releaseRingFromGlassesLocked("glasses connected the ring") + } +} + +// --------------------------------------------------------------------------- +// The ring's own binding state (system-channel commands over the direct link) +// +// The R1 keeps one phone role and one glasses role, and a pair of glasses +// addresses (advStart targets) it will accept in the glasses role; gestures go +// only to the glasses role. Behavior is from openCFW's R1 decompilation +// (r1/docs/correlation/CONNECTION-CONTROL-CORRELATION.md and +// ADV-START-TOUCH-SWITCH-HANDLERS-CORRELATION.md); the official app's order +// (advStart, then RING_CONNECT_INFO to the glasses) is from its decompiled +// EvConnect.startRingAdvForCurrentGlasses. Not verified on hardware. + +internal const val DIRECT_RING_ROLE_PHONE = "phone" +internal const val DIRECT_RING_ROLE_GLASSES = "glasses" + +/** How long a command with a follow-up waits for the ring's answer before running it anyway. */ +private const val RING_CONFIG_RESPONSE_TIMEOUT_MS = 3_000L + +/** Six 0xFF bytes: an unset advStart target, the value removeRingNotify writes. */ +private val RING_TARGET_UNSET = ByteArray(6) { 0xff.toByte() } + +/** + * One queued ring command. `followUp` is a glasses ring-link action (see + * [queueGlassesRingLinkCommandLocked]) to queue once the ring has answered. + */ +internal class RingConfigCommand( + val label: String, + val frame: ByteArray, + val cmdLo: Int, + val followUp: String?, + val followUpAddress: String, + val followUpName: String, +) + +/** + * Queue one ring-side command for the ring worker. Actions: + * - "pair-auth": pairAuth, claiming the phone role (the handshake already does). + * - "targets-glasses": advStart with this session's right and left arms. + * - "targets-clear": advStart with both targets unset (any glasses accepted). + * - "touch-on" / "touch-off": touchSwitch on the glasses touch source. + * - "remove-ring": removeRingNotify (clears both targets and the + * glasses-connected flag). + * Returns null when queued, else why not. + */ +internal fun GlassesSessionCore.queueRingConfigCommandLocked( + action: String, followUp: String?, followUpAddress: String, followUpName: String, +): String? { + val seq = nextRingSeqLocked() + val label: String + val frame: ByteArray + when (action) { + "pair-auth" -> { + label = "pairAuth" + frame = RingProtocol.buildPairAuth(seq) + } + "targets-glasses" -> { + val right = macWireBytes(rightAddress) + val left = macWireBytes(leftAddress) + if (right == null || left == null) return "not sent: glasses addresses unparseable" + label = "advStart R=$rightAddress L=$leftAddress" + frame = RingProtocol.buildAdvStart(seq, right, left) + } + "targets-clear" -> { + label = "advStart cleared" + frame = RingProtocol.buildAdvStart(seq, RING_TARGET_UNSET, RING_TARGET_UNSET) + } + "touch-on", "touch-off" -> { + label = "touchSwitch glasses " + (if (action == "touch-on") "on" else "off") + frame = RingProtocol.buildTouchSwitch(seq, RingProtocol.TOUCH_SWITCH_SELECTOR_GLASSES, action == "touch-on") + } + "remove-ring" -> { + label = "removeRingNotify" + frame = RingProtocol.buildRemoveRingNotify(seq) + } + else -> return "not sent: unknown ring action $action" + } + val cmdLo = frame[12].toInt() and 0xff + ringConfigQueue.addLast(RingConfigCommand(label, frame, cmdLo, followUp, followUpAddress, followUpName)) + lastRingConfigCommand = label + (if (followUp != null) " then glasses $followUp" else "") + lastRingConfigCommandAtMs = now() + lastRingConfigResult = "queued" + logLine("queue ring command $label seq=$seq" + (if (followUp != null) " then glasses $followUp" else "")) + monitor.signalAll() + return null +} + +/** The direct link went away: queued commands (and their follow-ups) are not sent. */ +internal fun GlassesSessionCore.dropRingConfigCommandsLocked(reason: String) { + lastRingConfigResult = when { + ringConfigQueue.isNotEmpty() -> "dropped: $reason" + ringConfigAwaiting != null -> "no answer: $reason" + else -> return + } + ringConfigQueue.clear() + ringConfigAwaiting = null + monitor.signalAll() +} + +/** + * Write queued ring commands. Ring worker only. A command with a follow-up + * waits for the ring's answer (or a timeout), then queues the glasses half. + * A failed write leaves the command queued for the next tick. + */ +internal fun GlassesSessionCore.flushRingConfigCommands() { + while (true) { + val command = monitor.withLock { + if (!ringNotificationsReady) return + ringConfigQueue.firstOrNull() ?: return + } + if (!writeRingFrame(command.frame, command.label)) return + monitor.withLock { + val index = ringConfigQueue.indexOfFirst { it === command } + if (index >= 0) ringConfigQueue.removeAt(index) + ringConfigAwaiting = command + lastRingConfigResult = "sent, awaiting ring" + } + logLine("ring command ${command.label} written: " + GlassesSessionCore.hex(command.frame)) + val followUp = command.followUp ?: continue + val answered = awaitRingConfigResponse(command) + val queued = monitor.withLock { + if (!running || !sessionReady) false + else queueGlassesRingLinkCommandLocked(followUp, command.followUpAddress, command.followUpName) + } + logLine("ring command ${command.label}: " + (if (answered) "answered" else "no answer") + + "; glasses $followUp " + (if (queued) "queued" else "not sent")) + interruptibleSleep.interrupt() + } +} + +private fun GlassesSessionCore.awaitRingConfigResponse(command: RingConfigCommand): Boolean { + val deadline = now() + RING_CONFIG_RESPONSE_TIMEOUT_MS + monitor.withLock { + while (running && ringConfigAwaiting === command) { + val remaining = deadline - now() + if (remaining <= 0) break + monitor.awaitMs(remaining) + } + return ringConfigAwaiting !== command + } +} + +/** Match a system-channel response to the command awaiting one. GATT callback thread. */ +internal fun GlassesSessionCore.recordRingConfigResponse(frame: RingProtocol.Frame) { + if (frame.cmdHi != RingProtocol.CMD_HI_DEVICE) return + val result = RingProtocol.responseResult(frame.kind) ?: return + val label = monitor.withLock { + val awaiting = ringConfigAwaiting + if (awaiting == null || awaiting.cmdLo != frame.cmdLo) return + ringConfigAwaiting = null + lastRingConfigResult = result + " (status " + RingProtocol.hex2(frame.kind) + ")" + monitor.signalAll() + awaiting.label + } + logLine("ring command $label answered: $result " + frame.describe()) +} + +/** + * Apply a role change (a [GlassesSessionCore.setDirectRingRole] change, or a + * health window opening or closing) by reconnecting the direct link. Ring + * worker only. + */ +internal fun GlassesSessionCore.restartRingLinkForRoleChange() { + val role = monitor.withLock { + if (!ringRoleReconnectPending) return + ringRoleReconnectPending = false + ringConnected = false + ringNotificationsReady = false + // Let the old connection end before dialing again; see RING_ROLE_SWITCH_SETTLE_MS. + ringReconnectAfterMs = now() + RING_ROLE_SWITCH_SETTLE_MS + ringOutbound.clear() + dropRingConfigCommandsLocked("role change") + effectiveRingRoleLocked() + } + logLine("direct ring: reconnecting to take the $role role") + link.disconnect(ringAddress) +} + +// --------------------------------------------------------------------------- +// Acting as the ring's glasses (direct ring role "glasses") +// +// Mirrors what the stock G2 does on connecting to its ring +// (g2-firmware-emulator docs/r1-cccd-frontier.md, r1-command88-native.md): +// enable the legacy CCCD (connectRing), then write the legacy pair-auth. We +// add touchSwitch "glasses source on", without which a link gets no +// gestures (hardware, 2026-10-06). The ring keeps its targets and the +// glasses keep their unpairing across connections, so those are sent only +// when the ring or the glasses show they are still bound to each other. + +/** Floor between automatic glasses unpair requests, so a fight with something re-binding the ring stays slow. */ +private const val RING_RELEASE_MIN_INTERVAL_MS = 2L * 60L * 1000L + +/** + * The per-connection glasses-role setup. Ring worker only; a failed write + * leaves it pending for the next tick (after writeRingFrame's backoff). + */ +internal fun GlassesSessionCore.runRingGlassesSetup() { + monitor.withLock { + if (!ringGlassesSetupPending || !ringNotificationsReady) return + // Before the write: the ring answers within milliseconds. + directGlassesAuth = "sent" + directGlassesAuthAtMs = now() + } + if (!writeRingFrame(RingProtocol.LEGACY_GLASSES_PAIR_AUTH, "glasses pair-auth", BleProtocol.R1_LEGACY_WRITE_CHAR_UUID)) { + return + } + val touch = monitor.withLock { + RingProtocol.buildTouchSwitch(nextRingSeqLocked(), RingProtocol.TOUCH_SWITCH_SELECTOR_GLASSES, true) + } + if (!writeRingFrame(touch, "touch source on")) { + return + } + monitor.withLock { ringGlassesSetupPending = false } + logLine("direct ring: sent glasses pair-auth and touch source on") +} + +/** + * Legacy-channel control frames that are not input: the battery report and + * the target rejection. Returns true when consumed. GATT callback thread. + */ +internal fun GlassesSessionCore.handleRingLegacyControl(data: ByteArray): Boolean { + val battery = RingProtocol.parseLegacyBattery(data) + if (battery != null) { + monitor.withLock { + directRingBattery = battery.battery + directRingCharging = battery.charging + // Only the accepted glasses peer gets these. + directGlassesAuth = "accepted" + directGlassesAuthAtMs = now() + emitBatteryState(headsetBattery, headsetCharging) + } + logLine("direct ring battery " + battery.battery + "% charging=" + battery.charging + " (legacy report)") + return true + } + if (!RingProtocol.isLegacyTargetRejected(data)) { + return false + } + // The ring's advStart targets name other glasses (normally ours, from the + // Even app's pairing), so it drops this link in ~20 s. Clear them once per + // connection, then repeat the pair-auth so it is checked again. + val clearing = monitor.withLock { + directGlassesAuthAtMs = now() + if (directGlassesAuthRetried) { + directGlassesAuth = "rejected again: ring is bound to other glasses" + false + } else { + directGlassesAuthRetried = true + directGlassesAuth = "rejected: clearing the ring's glasses targets" + queueRingConfigCommandLocked("remove-ring", null, "", "") + ringGlassesSetupPending = true + true + } + } + logLine("direct ring: glasses pair-auth rejected (ring bound to other glasses)" + + if (clearing) "; clearing its targets and retrying" else "; giving up for this connection") + return true +} + +/** + * The glasses still hold the ring while the direct link wants its glasses + * role: ask them to unpair it (UNPAIR_INFO), which they remember until + * something re-pairs them. Rate-limited. Caller holds `monitor`. + */ +internal fun GlassesSessionCore.releaseRingFromGlassesLocked(reason: String) { + if (!hasRingAddress() || directRingRole != DIRECT_RING_ROLE_GLASSES || !running || !sessionReady) return + val now = now() + if (lastRingReleaseAtMs != 0L && now - lastRingReleaseAtMs < RING_RELEASE_MIN_INTERVAL_MS) return + lastRingReleaseAtMs = now + logLine("direct ring: the glasses still hold the ring ($reason); asking them to unpair it") + if (queueGlassesRingLinkCommandLocked("unpair", ringAddress, glassesRingName)) { + interruptibleSleep.interrupt() + } +} diff --git a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionSend.kt b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionSend.kt index 997c911f..86723582 100644 --- a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionSend.kt +++ b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionSend.kt @@ -1042,6 +1042,7 @@ internal fun GlassesSessionCore.createBatteryQueryMessageLocked(): OutboundMessa // Old firmware and missing/malformed extensions must clear any prior reading. ringBattery = if (ring == null) -1 else ring.battery ringCharging = if (ring == null) -1 else ring.charging + if (ringBattery >= 0) releaseRingFromGlassesLocked("glasses report the ring connected") val snapshot = BleProtocol.parseSettingsBattery(message.ackPayload) if (snapshot != null) { headsetBattery = snapshot.battery diff --git a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/SessionPorts.kt b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/SessionPorts.kt index 99a8beec..94f5e0d2 100644 --- a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/SessionPorts.kt +++ b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/SessionPorts.kt @@ -16,6 +16,12 @@ interface SessionLink { /** Connect, waiting up to [timeoutMs]; waits on an attempt already started by [beginConnect]. */ fun connect(address: String, timeoutMs: Int): Boolean + /** + * [connect] with the platform's background-reconnect mode (Android's autoConnect) when + * [autoConnect] is set. The R1 ring needs it; platforms without the distinction ignore it. + */ + fun connect(address: String, timeoutMs: Int, autoConnect: Boolean): Boolean = connect(address, timeoutMs) + /** * Start connecting without waiting, so the attempt can land while the caller does other * work. [background] asks for a low-duty-cycle attempt that stays pending until the @@ -106,6 +112,31 @@ interface SessionHost { fun joinWorker(timeoutMs: Long) fun log(level: SessionLogLevel, tag: String, message: String, error: Throwable?) + + /** + * Start the direct-ring worker thread running [body] once. Ring connect/write/health waits + * run there so they never park the glasses sender. The core joins it through its own latch. + */ + fun startRingWorker(body: () -> Unit) = startThread("FaceclawRing", false, body) + + /** Interrupt the ring worker's blocking waits where the platform supports it. */ + fun interruptRingWorker() {} + + /** + * Whether this platform runs the R1 health-data protocol (handshake, pulls, page ACKs). + * Requires [appendRingFrameJournal] and a consumer for the decoded records; without + * one, ring notifications only feed the gesture decoder. + */ + fun supportsRingHealth(): Boolean = false + + /** + * Durably append one line to the private ring-frame journal (health/ring-frames.jsonl in + * the app's files directory), syncing before returning. Throws when the line could not be + * stored; the caller then withholds the page ACK so the ring keeps the data. + */ + fun appendRingFrameJournal(line: String) { + throw UnsupportedOperationException("no ring frame journal on this platform") + } } /** diff --git a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/util/PlatformUtil.kt b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/util/PlatformUtil.kt index a7813a56..9de7748e 100644 --- a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/util/PlatformUtil.kt +++ b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/util/PlatformUtil.kt @@ -19,6 +19,12 @@ expect fun currentTimeMillis(): Long /** Formats [epochMs] in local time with a Unicode/SimpleDateFormat-style [pattern] (e.g. "yyyyMMdd-HHmmss-SSS"). */ expect fun formatLocalTime(epochMs: Long, pattern: String): String +/** The local time zone's offset from UTC at [epochMs], in milliseconds (DST included). */ +expect fun localUtcOffsetMs(epochMs: Long): Int + +/** The local time zone's identifier (e.g. "America/Los_Angeles"), for logs. */ +expect fun localTimeZoneId(): String + expect object PlatformLog { fun i(tag: String, message: String) diff --git a/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/PlatformUtil.ios.kt b/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/PlatformUtil.ios.kt index 185bdfcb..b89c02ff 100644 --- a/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/PlatformUtil.ios.kt +++ b/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/PlatformUtil.ios.kt @@ -21,6 +21,8 @@ import platform.Foundation.NSDateFormatter import platform.Foundation.NSLocale import platform.Foundation.NSLog import platform.Foundation.NSThread +import platform.Foundation.NSTimeZone +import platform.Foundation.localTimeZone import platform.Foundation.dateWithTimeIntervalSince1970 import platform.Foundation.timeIntervalSince1970 import platform.posix.F_OK @@ -62,6 +64,11 @@ actual fun formatLocalTime(epochMs: Long, pattern: String): String { return formatter.stringFromDate(NSDate.dateWithTimeIntervalSince1970(epochMs / 1000.0)) } +actual fun localUtcOffsetMs(epochMs: Long): Int = + NSTimeZone.localTimeZone.secondsFromGMTForDate(NSDate.dateWithTimeIntervalSince1970(epochMs / 1000.0)).toInt() * 1000 + +actual fun localTimeZoneId(): String = NSTimeZone.localTimeZone.name + actual object PlatformLog { // NSLog's vararg bridge cannot take a Kotlin String (it segfaults), so the message becomes // the format string itself with '%' escaped. diff --git a/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/ble/IosGlassesSession.kt b/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/ble/IosGlassesSession.kt index 6114b182..18acc3bd 100644 --- a/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/ble/IosGlassesSession.kt +++ b/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/ble/IosGlassesSession.kt @@ -177,6 +177,12 @@ class IosGlassesSession internal constructor( fun cancelBandwidthBenchmark() = core.cancelBandwidthBenchmark() fun getBandwidthBenchmarkStatus(): String = core.getBandwidthBenchmarkStatus() + fun getRingStatus(): String = core.getRingStatus() + fun setGlassesRingLink(action: String, fallbackAddress: String?, fallbackName: String?): Boolean = + core.setGlassesRingLink(action, fallbackAddress, fallbackName) + fun sendRingConfigCommand(action: String, fallbackAddress: String?, fallbackName: String?): String = + core.sendRingConfigCommand(action, fallbackAddress, fallbackName) + fun setDirectRingRole(role: String?) = core.setDirectRingRole(role) fun addImuListener(listener: FaceclawImuListener?) = core.addImuListener(listener) diff --git a/scripts/kotlin-build.cjs b/scripts/kotlin-build.cjs index cff94868..38a7fba6 100644 --- a/scripts/kotlin-build.cjs +++ b/scripts/kotlin-build.cjs @@ -62,7 +62,14 @@ async function buildKotlin(platform, configuration = 'debug') { if (files.length !== 1) throw new Error(`Expected one Kotlin AAR, found: ${files.join(', ')}`); const source = path.join(output, files[0]); const aar = path.join(destination, 'faceclaw-shared.aar'); - if (!sameContents(source, aar)) cpSync(source, aar); + if (!sameContents(source, aar)) { + cpSync(source, aar); + // NativeScript's buildMetadata task tracks dependency jars by path, not + // contents, so a new AAR at the same path leaves the JS metadata stale: + // a method added in Kotlin is then "not a function" at runtime. Removing + // the task's outputs makes Gradle run it again. + rmSync(path.join(root, 'platforms/android/app/src/main/assets/metadata'), { recursive: true, force: true }); + } } else { const framework = path.join(destination, 'FaceclawKit.xcframework'); const source = path.join(kotlin, `shared/build/XCFrameworks/${configuration}/FaceclawKit.xcframework`); diff --git a/tests/health-card.test.cjs b/tests/health-card.test.cjs new file mode 100644 index 00000000..b1cf0992 --- /dev/null +++ b/tests/health-card.test.cjs @@ -0,0 +1,30 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const { drawHealthCard } = require("../.test-build/app/health/health-card.js"); +const { dailySummary } = require("../.test-build/app/health/health-derive.js"); + +function render(data) { + const draws = []; + const font = { lineHeight: 21, measureText: (text) => text.length * 10 }; + const image = { width: 288, height: 144, drawText(font, x, y, text) { + assert.ok(x >= 0 && x + font.measureText(text) <= 288, `horizontal overflow: ${text}`); + assert.ok(y >= 0 && y + font.lineHeight <= 144, `vertical overflow: ${text}`); + draws.push(text); + } }; + drawHealthCard(image, data, font, font); + return draws; +} + +test("health card distinguishes an observed zero from missing metrics", () => { + const summary = dailySummary([], [], 0); + const text = render({ kind: "live", summary, hasSteps: true, hasCalories: false }); + assert.equal(text.filter((value) => value === "0").length, 1); + assert.equal(text.filter((value) => value === "--").length, 5); +}); + +test("health card prominently labels fixtures without displaying sample measurements", () => { + const text = render({ kind: "fixture" }); + assert.ok(text.includes("Sample data")); + assert.ok(!text.includes("HR avg")); + for (const kind of ["empty", "error"]) render({ kind }); +}); diff --git a/tests/health-live.test.cjs b/tests/health-live.test.cjs new file mode 100644 index 00000000..9b2b2e25 --- /dev/null +++ b/tests/health-live.test.cjs @@ -0,0 +1,212 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const path = require("node:path"); +const vm = require("node:vm"); +const ts = require("typescript"); + +// Run the actual live ingest, seed and file-backend modules with NativeScript +// files and the Java communicator replaced at their platform boundaries. +function liveEnvironment({ ringProtocol } = {}) { + const files = new Map(); + const cache = new Map(); + const faults = { append: null, remove: null, write: null }; + const today = new Date(); + today.setHours(0, 0, 0, 0); + const start = today.getTime(); + let consumed = false; + const record = { + cmdHi: 1, + anchorUnixSeconds: (start + today.getTimezoneOffset() * 60000) / 1000, + groups: [{ hourIndex: 0, min: 40, max: 50, avg: 45 }], + }; + const communicator = { + takeRingHealthBatch: () => ({ + getWatermark: () => 1, + getRecords: () => ({ size: () => consumed ? 0 : 1, get: () => record }), + }), + clearRingHealthRecordsBelow: () => { consumed = true; return 1; }, + }; + const native = { + File: { + exists: (name) => files.has(name), + fromPath: (name) => ({ + readTextSync: () => files.get(name), + appendTextSync: (text, onError) => { + if (faults.append) return onError(faults.append); + files.set(name, (files.get(name) ?? "") + text); + }, + writeTextSync: (text, onError) => { + if (faults.write) return onError(faults.write); + files.set(name, text); + }, + removeSync: (onError) => { + if (faults.remove) return onError(faults.remove); + files.delete(name); + }, + }), + }, + knownFolders: { documents: () => ({ getFolder: () => ({ + path: "/health", + getEntitiesSync: () => [...files.keys()].map((name) => ({ path: name, name: path.basename(name) })), + }) }) }, + }; + function load(filename) { + if (!filename.endsWith(".ts")) filename += ".ts"; + if (cache.has(filename)) return cache.get(filename).exports; + const module = { exports: {} }; + cache.set(filename, module); + const code = ts.transpileModule(fs.readFileSync(filename, "utf8"), { + compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 }, + }).outputText; + vm.runInNewContext(code, { + module, exports: module.exports, Date, + require: (name) => name === "@nativescript/core" ? native : load(path.resolve(path.dirname(filename), name)), + console: { log() {}, warn() {} }, + com: { faceclaw: { app: { FaceclawBleCommunicator: { getActive: () => communicator }, RingProtocol: ringProtocol } } }, + }, { filename }); + return module.exports; + } + return { + files, faults, start, record, consumed: () => consumed, + load: (name) => load(path.join(__dirname, "../app/health", name)), + }; +} + +test("first live sync removes fixture samples, sleep and rollups from memory and disk", () => { + const env = liveEnvironment(); + const seed = env.load("health-seed"); + const store = env.load("health-store-files").healthStore(); + assert.equal(seed.seedFixturesIfNeeded(2), true); + assert.ok(store.sleepSessions().length > 0); + assert.ok(store.samplesInRange(env.start, env.start + 86400000).length > 1); + + env.load("health-live").syncLiveRecords(); + assert.equal(seed.isFixtureData(), false); + assert.equal(env.consumed(), true); + assert.equal(store.sleepSessions().length, 0); + const samples = store.samplesInRange(env.start, env.start + 86400000); + assert.equal(samples.length, 1); + assert.equal(samples[0].avg, 45); + const rollups = JSON.parse(env.files.get("/health/rollups.json")); + assert.equal(Object.keys(rollups.days).length, 1); + const day = Object.values(rollups.days)[0]; + assert.deepEqual(Object.keys(day), ["heartRate"]); + assert.equal(day.heartRate.count, 1); +}); + +test("a failed fixture purge retains the badge and ring batch until retry succeeds", () => { + const env = liveEnvironment(); + const seed = env.load("health-seed"); + seed.seedFixturesIfNeeded(2); + const live = env.load("health-live"); + env.faults.remove = new Error("delete failed"); + assert.throws(() => live.syncLiveRecords(), /delete failed/); + assert.equal(env.consumed(), false); + assert.equal(seed.isFixtureData(), true); + env.faults.remove = null; + live.syncLiveRecords(); + assert.equal(env.consumed(), true); + assert.equal(seed.isFixtureData(), false); +}); + +test("NativeScript append callback failures retain the batch and retry persists it", () => { + const env = liveEnvironment(); + const live = env.load("health-live"); + env.faults.append = { message: "disk full" }; + assert.throws(() => live.syncLiveRecords(), /disk full/); + assert.equal(env.consumed(), false); + assert.equal([...env.files.keys()].filter((name) => name.includes("samples-")).length, 0); + env.faults.append = null; + assert.equal(live.syncLiveRecords().samplesWritten, 1); + assert.equal(env.consumed(), true); + assert.equal([...env.files.keys()].filter((name) => name.includes("samples-")).length, 1); +}); + +test("NativeScript rollup write callback failures propagate without consuming the batch", () => { + const env = liveEnvironment(); + env.faults.write = { message: "write failed" }; + assert.throws(() => env.load("health-live").syncLiveRecords(), /write failed/); + assert.equal(env.consumed(), false); + env.faults.write = null; + assert.equal(env.load("health-live").syncLiveRecords().samplesWritten, 0); + assert.equal(env.consumed(), true); + assert.equal(env.files.has("/health/rollups.json"), true); + assert.equal(env.load("health-seed").hasLiveData(), true); + assert.equal(env.load("health-seed").seedFixturesIfNeeded(), false); +}); + +test("a failed fixture append stays labelled and is purged before live ingest", () => { + const env = liveEnvironment(); + const seed = env.load("health-seed"); + env.faults.append = new Error("disk full"); + assert.equal(seed.seedFixturesIfNeeded(2), false); + assert.equal(seed.isFixtureData(), true); + env.faults.append = null; + env.load("health-live").syncLiveRecords(); + assert.equal(seed.isFixtureData(), false); + assert.equal(env.load("health-store-files").healthStore().sleepSessions().length, 0); +}); + +test("journaled pages are replayed once, before the live batch, and again after a decoder upgrade", () => { + const calls = []; + let journalRecords = []; + const ringProtocol = { + decodeFrameJournal: (text, after) => { + calls.push({ text, after }); + const list = journalRecords.filter((r) => r.receivedAtMs > after); + return { size: () => list.length, get: (i) => list[i] }; + }, + }; + const env = liveEnvironment({ ringProtocol }); + const seed = env.load("health-seed"); + seed.seedFixturesIfNeeded(2); + env.files.set("/health/ring-frames.jsonl", "journal text"); + // A page the ring sent an hour earlier, never decoded at the time. + journalRecords = [{ ...env.record, groups: [{ hourIndex: 1, min: 50, max: 60, avg: 55 }], receivedAtMs: 1000 }]; + const live = env.load("health-live"); + const store = env.load("health-store-files").healthStore(); + + live.syncLiveRecords(); + assert.deepEqual(calls.map((c) => [c.text, c.after]), [["journal text", 0]]); + assert.equal(seed.isFixtureData(), false); + // A wide range: on a DST-change day the fixture record's hour 0 falls before local midnight. + const avgs = Array.from(store.samplesInRange(env.start - 86400000, env.start + 2 * 86400000), (s) => s.avg).sort(); + assert.deepEqual(avgs, [45, 55]); + assert.deepEqual(JSON.parse(env.files.get("/health/journal-replay.json")), + { version: 2, throughReceivedAtMs: 1000 }); + + // Once per process. + live.syncLiveRecords(); + assert.equal(calls.length, 1); + + // The next process resumes after the cursor... + const next = liveEnvironment({ ringProtocol }); + for (const [name, text] of env.files) next.files.set(name, text); + next.load("health-live").syncLiveRecords(); + assert.equal(calls.at(-1).after, 1000); + + // ...unless the cursor came from an older decoder, which may have skipped pages. + const upgraded = liveEnvironment({ ringProtocol }); + for (const [name, text] of env.files) upgraded.files.set(name, text); + upgraded.files.set("/health/journal-replay.json", JSON.stringify({ version: 1, throughReceivedAtMs: 1000 })); + upgraded.load("health-live").syncLiveRecords(); + assert.equal(calls.at(-1).after, 0); +}); + +test("a failed journal replay is retried on the next sync and never blocks the live batch", () => { + let failures = 1; + const ringProtocol = { + decodeFrameJournal: () => { + if (failures-- > 0) throw new Error("decode blew up"); + return { size: () => 0, get: () => null }; + }, + }; + const env = liveEnvironment({ ringProtocol }); + env.files.set("/health/ring-frames.jsonl", "journal text"); + const live = env.load("health-live"); + assert.equal(live.syncLiveRecords().samplesWritten, 1); + assert.equal(env.consumed(), true); + live.syncLiveRecords(); + assert.equal(failures, -1, "replay was not retried"); +}); diff --git a/tests/health-revisions.test.cjs b/tests/health-revisions.test.cjs new file mode 100644 index 00000000..ae49c78c --- /dev/null +++ b/tests/health-revisions.test.cjs @@ -0,0 +1,189 @@ +// The 2026-09-10 design revisions, pinned where getting them wrong would be +// silent. +// +// These are not tests of "does it draw" - a chart's appearance is checked by +// rendering it (tools/health-preview.cjs writes a PNG of every surface without +// an emulator). What is worth a test here is the handful of places where the +// revision put a SPECIFIC rule in the code that a later reader would plausibly +// undo: +// +// 1. The two sleep stage orders, which differ ON PURPOSE and therefore look +// exactly like a typo to anyone who meets one without the other. +// 2. The nightly sleep series, which the diverging chart plots - a gap has to +// stay at its own position or every later night shifts a column. +// 3. The stat rows, where "Buckets" was removed because it was an +// implementation detail on screen. +// +// Everything runs on generated fixtures. No real health data is read. + +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { buildFixtures } = require("../.test-build/app/health/health-fixtures.js"); +const { + dailySummary, + dailyHypnogram, + sleepNights, + sleepSummary, + stageSeconds, +} = require("../.test-build/app/health/health-derive.js"); +const { + SLEEP_LANE_ORDER, + SLEEP_STACK_ORDER, + rangeAverageText, +} = require("../.test-build/app/health/health-chart.js"); +const { GLANCE_PAGES } = require("../.test-build/app/health/health-glance.js"); +const { startOfLocalDay, DAY_MS, SAMPLE_METRICS } = require("../.test-build/app/health/health-types.js"); + +test("the two sleep stage orders are stated in opposite directions but agree on screen", () => { + // Week/month/quarter: stacked upward from zero, deep at the bottom. + assert.deepEqual([...SLEEP_STACK_ORDER], ["deep", "rem", "light"]); + // One night: lanes listed downward, awake at the top. + assert.deepEqual([...SLEEP_LANE_ORDER], ["wake", "light", "rem", "deep"]); + + // The point worth pinning. The two orders were given in opposite directions + // (one bottom-to-top, one top-to-bottom) and therefore READ as contradictory, + // which is why the brief called the difference out as deliberate. Resolve + // both to the same direction and the three sleep stages land in the SAME + // vertical order: light highest, deep lowest. The only real difference is + // where awake goes - a lane above the others, or a bar below the zero line. + const stackTopToBottom = [...SLEEP_STACK_ORDER].reverse(); + const lanesTopToBottomWithoutWake = SLEEP_LANE_ORDER.filter((stage) => stage !== "wake"); + assert.deepEqual( + stackTopToBottom, + [...lanesTopToBottomWithoutWake], + "deep sits at the bottom in both views - do not 'fix' one to disagree with the other", + ); + + // Awake is in the lanes and NOT in the upward stack - it diverges downward. + assert.ok(!SLEEP_STACK_ORDER.includes("wake")); + assert.ok(SLEEP_LANE_ORDER.includes("wake")); +}); + +test("the nightly sleep series keeps gaps in position", () => { + const now = Date.now(); + const today = startOfLocalDay(now); + const startMs = today - 6 * DAY_MS; + const { sleep } = buildFixtures({ days: 7, nowMs: now }); + + const all = sleepNights(sleep, startMs, today + DAY_MS); + assert.equal(all.length, 7, "one entry per day in the window, filled or not"); + + // Drop the middle night and check the later ones do not slide left. + const middleDay = all[3].startMs; + const thinned = sleep.filter((session) => session.dayStartMs !== middleDay); + const withGap = sleepNights(thinned, startMs, today + DAY_MS); + assert.equal(withGap.length, 7); + assert.equal(withGap[3].hasData, false, "the removed night is a gap, not a shift"); + assert.equal(withGap[3].startMs, middleDay); + assert.deepEqual( + withGap.map((night) => night.startMs), + all.map((night) => night.startMs), + "every night keeps its own day on the axis", + ); +}); + +test("two sessions on one day are summed, not deduped to the longest", () => { + const today = startOfLocalDay(Date.now()); + const night = (totalSec, wakeSec) => ({ + dayStartMs: today, + startMs: today, + endMs: today, + totalSec, + wakeSec, + remSec: totalSec * 0.2, + lightSec: totalSec * 0.6, + deepSec: totalSec * 0.2, + segments: [], + timeResolved: true, + }); + const nights = sleepNights([night(3600, 300), night(1800, 60)], today, today + DAY_MS); + assert.equal(nights.length, 1); + assert.equal(nights[0].wakeSec, 360, "a nap's wake time counts too"); + assert.ok( + Math.abs(nights[0].lightSec - (3600 + 1800) * 0.6) < 1e-6, + "stage totals add across both sessions", + ); + const summary = dailySummary([], [night(3600, 300), night(1800, 60)], today).sleep; + assert.equal(summary.totalSec, 5400); + assert.equal(summary.wakeSec, 360); + assert.equal(summary.efficiencyPercent, 5400 / 5760 * 100); + assert.equal(dailySummary([], [], today).sleep, null); +}); + +test("split-night detail includes both blocks and leaves the gap unknown", () => { + const today = startOfLocalDay(Date.now()); + const block = (hour, stageId) => ({ + dayStartMs: today, startMs: today + hour * 3600000, + endMs: today + (hour + 1) * 3600000, + totalSec: 3600, wakeSec: 0, remSec: 0, lightSec: 3600, deepSec: 0, + segments: [{ stageId, halfMinutes: 120 }], timeResolved: true, + }); + const first = block(1, 1), second = block(3, 2); + const bands = dailyHypnogram([second, first, { ...block(1, 3), dayStartMs: today - DAY_MS }], today); + assert.equal(bands.length, 3); + assert.deepEqual(bands[1], { stage: null, seconds: 3600 }); + assert.equal(bands[0].seconds, 3600); + assert.equal(bands[2].seconds, 3600); + assert.notEqual(bands[0].stage, bands[2].stage); + assert.equal(dailySummary([], [first, second], today).sleep.totalSec, 7200, + "an unrecorded gap is not counted as sleep"); + assert.deepEqual(dailyHypnogram([{ ...first, segments: [] }], today), + [{ stage: null, seconds: 3600 }]); +}); + +test("a stage's lane duration comes from the named totals", () => { + const now = Date.now(); + const { sleep } = buildFixtures({ days: 2, nowMs: now }); + const summary = sleepSummary(sleep[0]); + // The four lanes must account for the whole time in bed, which is exactly + // the property that does NOT depend on the raw stage-id mapping. + const summed = SLEEP_LANE_ORDER.reduce( + (total, stage) => total + stageSeconds(stage, summary), + 0, + ); + assert.ok( + Math.abs(summed - (summary.totalSec + summary.wakeSec)) < 1, + `lanes should sum to time in bed, got ${summed}`, + ); + assert.equal(stageSeconds("wake", summary), summary.wakeSec); +}); + +test("the glance line reads as a range and an average", () => { + assert.equal( + rangeAverageText({ min: 60, max: 98, avg: 72.6, hasData: true }, "bpm"), + "60-98 bpm, avg 73", + ); + assert.equal( + rangeAverageText({ min: 0, max: 0, avg: 0, hasData: false }, "bpm"), + "--", + "no data shows a dash, never a zero", + ); + // ASCII hyphen only: Terminus has no en dash and would render the default + // char, putting a "?" in the middle of the number. + const text = rangeAverageText({ min: 40, max: 62, avg: 51, hasData: true }, "ms"); + for (const char of text) { + assert.ok(char.codePointAt(0) < 128, `"${char}" is outside ASCII`); + } +}); + +test("HRV reached the daily summary", () => { + const now = Date.now(); + const today = startOfLocalDay(now); + const { samples, sleep } = buildFixtures({ days: 2, nowMs: now }); + const summary = dailySummary(samples, sleep, today); + assert.ok(summary.hrv, "HRV is on the glance now - Chris revised the spec"); + assert.ok(summary.hrv.hasData); + assert.ok(summary.hrv.max >= summary.hrv.min); +}); + +test("the glasses cursor walks the summary, every parameter, then sleep", () => { + assert.equal(GLANCE_PAGES[0].kind, "overview", "the glance is where it opens"); + assert.equal(GLANCE_PAGES[GLANCE_PAGES.length - 1].kind, "sleep"); + const walked = GLANCE_PAGES.filter((page) => page.kind === "metric").map((page) => page.metric); + assert.deepEqual( + [...walked].sort(), + [...SAMPLE_METRICS].sort(), + "every measured parameter is reachable by scrolling", + ); +}); diff --git a/tests/health.test.cjs b/tests/health.test.cjs new file mode 100644 index 00000000..7a9fcac3 --- /dev/null +++ b/tests/health.test.cjs @@ -0,0 +1,490 @@ +// The health feature's logic, pinned where getting it wrong would be silent. +// +// The three things worth a test here are not the arithmetic - they are the +// places where a bug would quietly produce a plausible wrong answer: +// +// 1. The STORE's durability contract. A health record may be the only copy +// that will ever exist (the ring appears to discard backlog it thinks it +// delivered), so "an append never rewrites a file that already holds +// records" and "a re-sync of the same hour corrects rather than +// duplicates" are the properties the whole feature rests on. +// 2. The INGEST rules that decline to guess - an unanchored hourly page is +// dropped, and step buckets do not get invented timestamps. +// 3. SLEEP, where the percentages must come from the named totals (which +// need no stage-id mapping) while only the hypnogram depends on the ids. +// +// Everything runs on generated fixtures. No real health data is read. + +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { HealthStore } = require("../.test-build/app/health/health-store.js"); +const { buildFixtures } = require("../.test-build/app/health/health-fixtures.js"); +const { + dailySummary, + sleepSummary, + hypnogram, + rollupSeries, + bandIsMeaningful, + formatDuration, +} = require("../.test-build/app/health/health-derive.js"); +const { convertRecords, sleepIdentityHolds } = require("../.test-build/app/health/health-ingest.js"); +const { + STAGE_NAME_BY_ID, + STAGE_MAPPING_CONFIRMED, + stageNameForId, +} = require("../.test-build/app/health/sleep-stages.js"); +const { + startOfLocalDay, + DAY_MS, + HOUR_MS, + TEN_MINUTES_MS, +} = require("../.test-build/app/health/health-types.js"); + +/** An in-memory backend that also records how each file was touched. */ +function memoryBackend() { + const files = new Map(); + const ops = []; + return { + ops, + files, + exists: (name) => files.has(name), + read: (name) => files.get(name) ?? null, + append(name, text) { + ops.push({ op: "append", name }); + files.set(name, (files.get(name) ?? "") + text); + }, + write(name, text) { + ops.push({ op: "write", name }); + files.set(name, text); + }, + list: () => [...files.keys()], + }; +} + +const HOUR = 3600000; + +function sample(metric, startMs, min, max, avg, total) { + return { metric, startMs, spanMs: HOUR, min, max, avg, total: total ?? avg }; +} + +// --------------------------------------------------------------------------- +// Storage + +test("a stored sample survives a fresh store over the same files", () => { + const backend = memoryBackend(); + const first = new HealthStore(backend); + const start = startOfLocalDay(Date.now()); + first.ingestSamples([sample("heartRate", start, 55, 90, 70)]); + + const second = new HealthStore(backend); + const held = second.samplesInRange(start, start + DAY_MS); + assert.equal(held.length, 1); + assert.equal(held[0].avg, 70); +}); + +test("a sample file is only ever appended to, never rewritten", () => { + const backend = memoryBackend(); + const store = new HealthStore(backend); + const start = startOfLocalDay(Date.now()); + for (let hour = 0; hour < 6; hour += 1) { + store.ingestSamples([sample("heartRate", start + hour * HOUR, 50 + hour, 90, 70 + hour)]); + } + const sampleWrites = backend.ops.filter( + (entry) => entry.op === "write" && entry.name.startsWith("samples-"), + ); + // The rollup cache is rewritten freely - it is derived. The shards are not. + assert.equal(sampleWrites.length, 0); + assert.ok(backend.ops.some((entry) => entry.op === "append")); +}); + +test("re-storing an unchanged bucket writes nothing; a changed one corrects it", () => { + const backend = memoryBackend(); + const store = new HealthStore(backend); + const start = startOfLocalDay(Date.now()); + + assert.equal(store.ingestSamples([sample("heartRate", start, 55, 90, 70)]), 1); + // The live poller re-reads the same capped list every 30 minutes; a no-op + // here is what stops that appending a duplicate line forever. + assert.equal(store.ingestSamples([sample("heartRate", start, 55, 90, 70)]), 0); + // The current hour genuinely changes as it fills up. Later line wins. + assert.equal(store.ingestSamples([sample("heartRate", start, 55, 104, 74)]), 1); + + const reloaded = new HealthStore(backend); + const held = reloaded.samplesInRange(start, start + DAY_MS); + assert.equal(held.length, 1); + assert.equal(held[0].max, 104); +}); + +test("a corrupt rollup cache is rebuilt from the shards rather than trusted", () => { + const backend = memoryBackend(); + const store = new HealthStore(backend); + const start = startOfLocalDay(Date.now()); + store.ingestSamples([sample("heartRate", start, 55, 90, 70), sample("heartRate", start + HOUR, 60, 100, 80)]); + + backend.files.set("rollups.json", "{ not json"); + const recovered = new HealthStore(backend); + const rollups = recovered.dailyRollups("heartRate", start, start + DAY_MS); + const day = rollups.get(start); + assert.ok(day, "the day should be recovered from the raw shards"); + assert.equal(day.min, 55); + assert.equal(day.max, 100); + assert.equal(day.count, 2); +}); + +test("a single unreadable line does not cost the rest of the file", () => { + const backend = memoryBackend(); + const store = new HealthStore(backend); + const start = startOfLocalDay(Date.now()); + store.ingestSamples([sample("heartRate", start, 55, 90, 70)]); + const name = [...backend.files.keys()].find((key) => key.startsWith("samples-")); + backend.files.set(name, `${backend.files.get(name)}{ truncated\n`); + store.ingestSamples([sample("heartRate", start + HOUR, 60, 100, 80)]); + + const reloaded = new HealthStore(backend); + assert.equal(reloaded.samplesInRange(start, start + DAY_MS).length, 2); +}); + +// --------------------------------------------------------------------------- +// Ingest: the rules that decline to guess + +test("failed sample corrections stay retryable, including a partially stored batch", () => { + const backend = memoryBackend(); + const store = new HealthStore(backend); + const first = new Date(2026, 7, 31).getTime(); + const second = new Date(2026, 8, 1).getTime(); + const original = sample("heartRate", second, 50, 80, 60); + store.ingestSamples([original]); + const append = backend.append; + backend.append = (name, text) => { + if (name === "samples-2026-09.jsonl") throw new Error("disk full"); + append(name, text); + }; + const batch = [sample("heartRate", first, 50, 90, 70), sample("heartRate", second, 50, 100, 80)]; + assert.throws(() => store.ingestSamples(batch), /disk full/); + assert.equal(store.samplesInRange(second, second + DAY_MS)[0].avg, 60); + backend.append = append; + assert.equal(store.ingestSamples(batch), 1, "only the failed shard should need retry"); + const reloaded = new HealthStore(backend); + assert.equal(reloaded.samplesInRange(first, second + DAY_MS).length, 2); + assert.equal(reloaded.samplesInRange(second, second + DAY_MS)[0].avg, 80); +}); + +test("failed sleep appends and corrections do not poison deduplication", () => { + const backend = memoryBackend(); + const store = new HealthStore(backend); + const session = buildFixtures({ days: 1, nowMs: Date.now() }).sleep[0]; + assert.ok(session); + const append = backend.append; + backend.append = () => { throw new Error("disk full"); }; + assert.throws(() => store.ingestSleep([session]), /disk full/); + assert.equal(store.sleepSessions().length, 0); + backend.append = append; + assert.equal(store.ingestSleep([session]), 1); + const correction = { ...session, totalSec: session.totalSec + 60 }; + backend.append = () => { throw new Error("disk full"); }; + assert.throws(() => store.ingestSleep([correction]), /disk full/); + assert.equal(store.sleepSessions()[0].totalSec, session.totalSec); + backend.append = append; + assert.equal(store.ingestSleep([correction]), 1); + assert.equal(new HealthStore(backend).sleepSessions()[0].totalSec, correction.totalSec); +}); + +test("retry after a partial append preserves the first sample and sleep record", () => { + const backend = memoryBackend(); + const store = new HealthStore(backend); + const start = startOfLocalDay(Date.now()); + const row = sample("heartRate", start, 50, 90, 70); + const session = buildFixtures({ days: 1, nowMs: Date.now() }).sleep[0]; + const append = backend.append; + backend.append = (name, text) => { + append(name, text.slice(0, 12)); + throw new Error("partial append"); + }; + assert.throws(() => store.ingestSamples([row]), /partial append/); + assert.throws(() => store.ingestSleep([session]), /partial append/); + backend.append = append; + assert.equal(store.ingestSamples([row]), 1); + assert.equal(store.ingestSleep([session]), 1); + const recovered = new HealthStore(backend); + assert.equal(recovered.samplesInRange(start, start + DAY_MS)[0].avg, 70); + assert.equal(recovered.sleepSessions()[0].totalSec, session.totalSec); +}); + +test("an unanchored hourly page is dropped, not dated", () => { + const result = convertRecords([ + { + kind: "hourly", + metric: "heartRate", + anchorMs: null, + groups: [{ hourIndex: 0, avg: 70, max: 90, min: 55 }], + }, + ]); + assert.equal(result.samples.length, 0); + assert.equal(result.skipped.length, 1); + assert.match(result.skipped[0].why, /anchor/); +}); + +test("an anchored hourly page dates each group from the anchor", () => { + const anchor = startOfLocalDay(Date.now()); + const result = convertRecords([ + { + kind: "hourly", + metric: "hrv", + anchorMs: anchor, + groups: [ + { hourIndex: 0, avg: 40, max: 40, min: 40 }, + { hourIndex: 5, avg: 52, max: 55, min: 50 }, + ], + }, + ]); + assert.equal(result.samples.length, 2); + assert.equal(result.samples[0].startMs, anchor); + assert.equal(result.samples[1].startMs, anchor + 5 * HOUR_MS); +}); + +// The index is cracked (2026-09-12): bucket i starts at anchor + i * 10 minutes. +// This test previously asserted the opposite - one day-span total, buckets +// deliberately discarded - which was the honest call while the index was only +// trusted as an identity. It is now the placement contract. +test("steps place each bucket at anchor + index * ten minutes", () => { + const anchor = startOfLocalDay(Date.now()); + const result = convertRecords([ + { + kind: "steps", + anchorMs: anchor, + buckets: [ + { index: 0, steps: 100, activeCalories: 4, totalCalories: 15 }, + { index: 130, steps: 260, activeCalories: 9, totalCalories: 21 }, + ], + }, + ]); + const steps = result.samples.filter((entry) => entry.metric === "steps"); + assert.equal(steps.length, 2, "one sample per bucket, not one day total"); + assert.equal(steps[0].startMs, anchor); + assert.equal(steps[0].total, 100); + assert.equal(steps[0].spanMs, TEN_MINUTES_MS); + assert.equal(steps[1].startMs, anchor + 130 * TEN_MINUTES_MS); + assert.equal(steps[1].total, 260); + + // The day total is now `sum` and ONLY `sum` - `max`/`avg` are per-bucket. + // Every reader was checked against this on 2026-09-12. + assert.equal( + steps.reduce((acc, entry) => acc + entry.total, 0), + 360, + ); + + const calories = result.samples.filter((entry) => entry.metric === "calories"); + assert.equal(calories.length, 2); + assert.equal(calories[1].startMs, anchor + 130 * TEN_MINUTES_MS); + assert.equal(calories[1].total, 21); + + // Nothing is declined any more - the buckets are placed, not discarded. + assert.equal(result.skipped.length, 0); +}); + +test("a sleep session is stored with its time marked unresolved", () => { + const result = convertRecords([ + { + kind: "sleep", + startTs: 90000, + endTs: 90000 + 21600, + totalSec: 20400, + wakeSec: 1200, + remSec: 3600, + lightSec: 12000, + deepSec: 4800, + segments: [{ stageId: 2, halfMinutes: 720 }], + receivedAtMs: Date.now(), + }, + ]); + assert.equal(result.sleep.length, 1); + assert.equal(result.sleep[0].timeResolved, false); + assert.equal(result.sleep[0].dayStartMs, startOfLocalDay(Date.now())); +}); + +// The first real sleep record off the hardware, 2026-09-12, verbatim from +// `files/health/sleep.jsonl` under com.faceclaw.app. It is here as a FROZEN +// known-good: the -8h correction was derived from Chris confirming the window +// two independent ways, and a future change that quietly makes it -4h again +// (or 0h, which is what shipped first) should fail a test rather than wait to +// be noticed in a chart. +const REAL_SLEEP_RECORD = { + kind: "sleep", + startTs: 1789222861, + endTs: 1789233931, + totalSec: 10440, + wakeSec: 630, + remSec: 1620, + lightSec: 5880, + deepSec: 2940, + segments: [ + { stageId: 0, halfMinutes: 21 }, + { stageId: 2, halfMinutes: 42 }, + { stageId: 3, halfMinutes: 36 }, + { stageId: 2, halfMinutes: 40 }, + { stageId: 1, halfMinutes: 36 }, + { stageId: 2, halfMinutes: 42 }, + { stageId: 3, halfMinutes: 62 }, + { stageId: 2, halfMinutes: 46 }, + { stageId: 1, halfMinutes: 18 }, + { stageId: 2, halfMinutes: 26 }, + ], + receivedAtMs: 1789234000000, +}; + +test("a clock correction promotes a sleep session to a real placement", () => { + const rawStartMs = REAL_SLEEP_RECORD.startTs * 1000; + // Twice the hourly ring-clock offset, computed the way health-live.ts + // computes it - so this says what the RULE is rather than restating a + // constant that would rot at the November DST change. + const correction = 2 * new Date(rawStartMs).getTimezoneOffset() * 60 * 1000; + + const result = convertRecords([{ ...REAL_SLEEP_RECORD, clockCorrectionMs: correction }]); + assert.equal(result.sleep.length, 1); + const night = result.sleep[0]; + + assert.equal(night.timeResolved, true, "a corrected session is placed, not unresolved"); + assert.equal(night.startMs, rawStartMs - correction); + assert.equal(night.endMs, REAL_SLEEP_RECORD.endTs * 1000 - correction); + // The wake-up day, not the day it happened to be received on. + assert.equal(night.dayStartMs, startOfLocalDay(night.endMs)); + // The correction must move where the night sits, never how long it was. + assert.equal(night.endMs - night.startMs, 11070 * 1000); + assert.equal(night.totalSec, 10440); +}); + +test("the real 2026-09-12 record decodes to the window Chris confirmed", (t) => { + // EDT only: the known-good is a wall-clock reading and the assertion is + // meaningless in another zone. Skipped rather than weakened elsewhere. + if (new Date(REAL_SLEEP_RECORD.startTs * 1000).getTimezoneOffset() !== 240) { + t.skip("not EDT"); + return; + } + const result = convertRecords([{ ...REAL_SLEEP_RECORD, clockCorrectionMs: 8 * 3600 * 1000 }]); + const night = result.sleep[0]; + const local = (ms) => new Date(ms).toLocaleString("sv-SE", { timeZone: "America/New_York" }); + assert.equal(local(night.startMs), "2026-09-12 02:21:01"); + assert.equal(local(night.endMs), "2026-09-12 05:25:31"); +}); + +// --------------------------------------------------------------------------- +// Sleep + +test("stage percentages come from the named totals, not from the stage ids", () => { + const session = { + dayStartMs: startOfLocalDay(Date.now()), + startMs: 0, + endMs: 0, + totalSec: 20000, + wakeSec: 1000, + remSec: 4000, + lightSec: 12000, + deepSec: 4000, + // Deliberately unmappable ids: the percentages must not care. + segments: [{ stageId: 9, halfMinutes: 700 }], + timeResolved: true, + }; + const summary = sleepSummary(session); + assert.equal(Math.round(summary.remPercent), 20); + assert.equal(Math.round(summary.lightPercent), 60); + assert.equal(Math.round(summary.deepPercent), 20); + // total / (total + wake) = 20000 / 21000 + assert.equal(Math.round(summary.efficiencyPercent), 95); + // ...while the hypnogram, which does depend on the ids, says so. + assert.equal(hypnogram(session)[0].stage, null); +}); + +test("the stage-id mapping is the one named place, and it is the derived one", () => { + assert.equal(stageNameForId(0), "wake"); + assert.equal(stageNameForId(1), "rem"); + assert.equal(stageNameForId(2), "light"); + assert.equal(stageNameForId(3), "deep"); + assert.equal(stageNameForId(4), null); + assert.equal(Object.keys(STAGE_NAME_BY_ID).length, 4); + // Pinned deliberately: flipping this is the confirmation step, and it should + // be a decision someone makes, not something that drifts. + assert.equal(STAGE_MAPPING_CONFIRMED, false); +}); + +test("no sleep-quality composite is exposed", () => { + const summary = sleepSummary({ + dayStartMs: 0, startMs: 0, endMs: 0, + totalSec: 20000, wakeSec: 1000, remSec: 4000, lightSec: 12000, deepSec: 4000, + segments: [], timeResolved: true, + }); + const invented = Object.keys(summary).filter((key) => /quality|score/i.test(key)); + assert.deepEqual(invented, []); +}); + +// --------------------------------------------------------------------------- +// Series and fixtures + +test("a range with no data comes back as gaps at the right positions", () => { + const start = startOfLocalDay(Date.now()); + const points = rollupSeries([sample("heartRate", start + 3 * HOUR, 55, 90, 70)], { + metric: "heartRate", + granularity: "hour", + startMs: start, + endMs: start + DAY_MS, + }); + assert.equal(points.length, 24); + assert.equal(points[0].count, 0); + assert.equal(points[3].count, 1); + assert.equal(points[3].avg, 70); +}); + +test("the band is drawn for heart rate and dropped for a collapsed metric", () => { + const start = startOfLocalDay(Date.now()); + const spread = []; + const flat = []; + for (let hour = 0; hour < 12; hour += 1) { + spread.push({ startMs: start + hour * HOUR, spanMs: HOUR, min: 60, max: 92, avg: 74, sum: 74, count: 1 }); + flat.push({ startMs: start + hour * HOUR, spanMs: HOUR, min: 97, max: 97, avg: 97, sum: 97, count: 1 }); + } + assert.equal(bandIsMeaningful(spread), true); + assert.equal(bandIsMeaningful(flat), false); +}); + +test("the fixtures reproduce the shapes the real export has", () => { + const now = Date.now(); + const { samples, sleep } = buildFixtures({ days: 7, nowMs: now }); + + const hourly = samples.filter((entry) => entry.metric === "heartRate"); + assert.ok(hourly.every((entry) => entry.spanMs === HOUR_MS), "heart rate is hourly"); + const stepBuckets = samples.filter((entry) => entry.metric === "steps"); + assert.ok(stepBuckets.every((entry) => entry.spanMs === 600000), "steps are ten-minute"); + + // Heart rate has a real spread; SpO2 mostly does not. Both were measured off + // the export before the generator was written. + const hrSpread = hourly.filter((entry) => entry.max > entry.min).length / hourly.length; + const spo2 = samples.filter((entry) => entry.metric === "spo2"); + const spo2Spread = spo2.filter((entry) => entry.max > entry.min).length / spo2.length; + assert.ok(hrSpread > 0.9, `heart rate should nearly always have spread, got ${hrSpread}`); + assert.ok(spo2Spread < 0.15, `SpO2 should rarely have spread, got ${spo2Spread}`); + + // Every generated night satisfies the same identity real records satisfy. + for (const night of sleep) { + assert.ok( + sleepIdentityHolds(night), + "segment run must account for exactly the time in bed", + ); + } +}); + +test("the daily summary picks last night and today's own buckets", () => { + const now = Date.now(); + const today = startOfLocalDay(now); + const { samples, sleep } = buildFixtures({ days: 3, nowMs: now }); + const summary = dailySummary(samples, sleep, today); + assert.equal(summary.dayStartMs, today); + assert.ok(summary.heartRate.hasData); + assert.ok(summary.sleep, "there should be a night attributed to today"); + assert.ok(summary.steps >= 0); +}); + +test("durations format the way the glance prints them", () => { + assert.equal(formatDuration(0), "--"); + assert.equal(formatDuration(6 * 3600 + 12 * 60), "6h 12m"); + assert.equal(formatDuration(45 * 60), "45m"); +}); diff --git a/tests/kotlin/src/androidHostTest/java/com/faceclaw/app/RingProtocolSelfTest.java b/tests/kotlin/src/androidHostTest/java/com/faceclaw/app/RingProtocolSelfTest.java new file mode 100644 index 00000000..b1e27490 --- /dev/null +++ b/tests/kotlin/src/androidHostTest/java/com/faceclaw/app/RingProtocolSelfTest.java @@ -0,0 +1,620 @@ +package com.faceclaw.app; + +import java.util.Arrays; +import java.util.List; + +/** + * Standalone self-test for {@link RingProtocol}. No Android APIs and no + * hardware: every byte-manipulation path is exercised against either frames + * copied from the reference capture or synthetic bodies built from the spec's + * field layout. + * + *

Run through JavaCompatibilityTest ({@code npm run test:kotlin}), which + * also checks that the Kotlin port keeps the Java-facing API the TypeScript + * health ingest reads. + * + *

The captured frames reproduced below are requests and page-ACKs only. + * Those carry a nonce, a command id and a sequence number — no biometric + * values. No captured DATA page appears here, deliberately. + */ +public final class RingProtocolSelfTest { + private static int checks; + private static int failures; + + public static void main(String[] args) { + testCrcAndRequestRoundTrip(); + testFiveHealthRequests(); + testPageAckAgainstCapture(); + testParseRejectsGarbage(); + testFragmentReassembly(); + testHourlyDecode(); + testStepsDecode(); + testSleepDecodeAndIdentities(); + testDailyWireLayouts(); + testFirmware23Trailer(); + testFrameJournalReplay(); + testDeviceStatus(); + + System.out.println(); + System.out.println(failures == 0 + ? "PASS: all " + checks + " checks" + : "FAIL: " + failures + " of " + checks + " checks"); + if (failures != 0) { + throw new AssertionError(failures + " of " + checks + " ring protocol checks failed"); + } + } + + // ------------------------------------------------------------------ + + /** + * Rebuild captured request pkt 9166 from its decoded fields alone. If the + * CRC-32C parameters or the header layout are wrong by even one bit this + * cannot reproduce the captured bytes. + */ + private static void testCrcAndRequestRoundTrip() { + section("CRC + request round-trip (captured pkt 9166)"); + byte[] built = RingProtocol.buildRequest( + RingProtocol.CHAN_HEALTH, + RingProtocol.CMD_HI_HEART_RATE, + RingProtocol.CMD_LO_HEALTH, + 0x06, + 0x08ca); + expectHex("pkt 9166", "00db64265a64026406000001010c00ca08", built); + + RingProtocol.Frame frame = RingProtocol.parse(built); + expect("parses back", frame != null && frame.crcOk); + expect("chan", frame.chan == RingProtocol.CHAN_HEALTH); + expect("kind REQ", frame.kind == RingProtocol.KIND_REQ); + expect("seq", frame.seq == 0x06); + expect("cmd 01:01", frame.cmdHi == 0x01 && frame.cmdLo == 0x01); + expect("payload is the 2-byte nonce", frame.payload.length == 2); + + // A single flipped payload bit must invalidate the CRC. + byte[] tampered = built.clone(); + tampered[15] ^= 0x01; + RingProtocol.Frame bad = RingProtocol.parse(tampered); + expect("tampered frame fails CRC", bad != null && !bad.crcOk); + } + + /** The five ready-to-send health requests, seq=1, nonce=0. */ + private static void testFiveHealthRequests() { + section("five health requests (spec section 9)"); + String[][] expected = { + {"heart rate", "00450fe48f64026401000001010c000000"}, + {"SpO2", "000d3fd33364026401000002010c000000"}, + {"HRV", "00dc30615564026401000004010c000000"}, + {"steps", "00e4208c3e64026401000005010c000000"}, + {"sleep", "00ac10bb8264026401000006010c000000"}, + }; + int[] commands = { + RingProtocol.CMD_HI_HEART_RATE, + RingProtocol.CMD_HI_SPO2, + RingProtocol.CMD_HI_HRV, + RingProtocol.CMD_HI_STEPS, + RingProtocol.CMD_HI_SLEEP, + }; + for (int i = 0; i < commands.length; i++) { + byte[] built = RingProtocol.buildHealthRequest(commands[i], 0x01, 0x0000); + expectHex(expected[i][0], expected[i][1], built); + } + + // The convenience burst builder must produce the same first frame and + // then advance the shared sequence counter by one per frame. + List burst = RingProtocol.buildHealthRequestBurst(0x01, 0x0000); + expect("burst has five frames", burst.size() == 5); + expectHex("burst[0] == heart rate", expected[0][1], burst.get(0)); + boolean seqRuns = true; + for (int i = 0; i < burst.size(); i++) { + RingProtocol.Frame f = RingProtocol.parse(burst.get(i)); + if (f == null || !f.crcOk || f.seq != 0x01 + i) { + seqRuns = false; + } + } + expect("burst sequence numbers run 1..5 and all CRCs are valid", seqRuns); + } + + /** + * Rebuild real captured page-ACKs. This is what pins down the two things + * the prose spec got wrong: the payload begins with the usual nonce (so the + * echoed page seq is at offset 6, not 4), and the frame's own SEQ is the + * phone's shared counter rather than the echoed page seq. + */ + private static void testPageAckAgainstCapture() { + section("page ACK 00:7E rebuilt from captured frames"); + // seq, nonce, ackedCmdHi, ackedCmdLo, pageSeq, expected hex + Object[][] cases = { + {0x0d, 0x5f49, 0x01, 0x01, 0x03, "005e55d80b6401640d0001007e1600495f02010100030000000000"}, + {0x13, 0xdc10, 0x04, 0x01, 0x07, "00a2bae3c4640164130001007e160010dc02040100070000000000"}, + {0x17, 0x86e9, 0x02, 0x01, 0x09, "002c006c61640164170001007e1600e98602020100090000000000"}, + {0x23, 0x634c, 0x06, 0x01, 0x13, "00b96c8823640164230001007e16004c6302060100130000000000"}, + {0x25, 0x46f2, 0x05, 0x01, 0x14, "00474ee8b8640164250001007e1600f24602050100140000000000"}, + {0x14, 0x7bc3, 0x05, 0x01, 0x3b, "00f3a5a917640164140001007e1600c37b020501003b0000000000"}, + }; + for (Object[] c : cases) { + byte[] built = RingProtocol.buildPageAck( + (Integer) c[0], (Integer) c[1], (Integer) c[2], (Integer) c[3], (Integer) c[4]); + expectHex("ack for cmd " + hex2((Integer) c[2]) + ":" + hex2((Integer) c[3]) + + " page seq " + hex2((Integer) c[4]), (String) c[5], built); + } + + RingProtocol.Frame f = RingProtocol.parse(RingProtocol.buildPageAck(0x0d, 0x5f49, 0x01, 0x01, 0x03)); + expect("ack rides the DEVICE channel", f.chan == RingProtocol.CHAN_DEVICE); + expect("ack kind is ACK", f.kind == RingProtocol.KIND_ACK); + expect("ack command is 00:7e", f.cmdHi == 0x00 && f.cmdLo == 0x7e); + expect("ack header seq differs from echoed page seq", f.seq != (f.payload[6] & 0xff)); + expect("echoed page seq is at payload[6]", (f.payload[6] & 0xff) == 0x03); + } + + private static void testParseRejectsGarbage() { + section("parser rejects non-frames"); + expect("null", RingProtocol.parse(null) == null); + expect("too short", RingProtocol.parse(new byte[8]) == null); + expect("no magic", RingProtocol.parse(new byte[20]) == null); + // A 3-byte ring gesture frame must not look like a header. + expect("gesture frame is not a header", + !RingProtocol.looksLikeHeader(new byte[] {(byte) 0xff, 0x04, 0x01})); + // A frame whose PLEN disagrees with its actual length is rejected. + byte[] frame = RingProtocol.buildHealthRequest(RingProtocol.CMD_HI_HRV, 1, 0); + byte[] truncated = Arrays.copyOf(frame, frame.length - 1); + expect("length/PLEN mismatch rejected", RingProtocol.parse(truncated) == null); + } + + /** + * Fragmentation, reproducing the shape the capture actually shows: an + * oversized frame split into a 244-byte FLAG=0x01 head and a headerless + * continuation, with an unrelated complete frame arriving in between. + */ + private static void testFragmentReassembly() { + section("fragment reassembly"); + // Build a 252-byte steps-shaped frame: 15 header + 237 payload. + byte[] payload = new byte[237]; + for (int i = 0; i < payload.length; i++) { + payload[i] = (byte) (i * 7 + 3); + } + byte[] whole = RingProtocol.buildFrame( + RingProtocol.CHAN_HEALTH, RingProtocol.KIND_DATA, + RingProtocol.CMD_HI_STEPS, RingProtocol.CMD_LO_HEALTH, 0x15, payload); + expect("test frame is 252 bytes", whole.length == 252); + + byte[] head = Arrays.copyOf(whole, 244); + head[0] = (byte) RingProtocol.FLAG_FRAGMENTED; + byte[] continuation = new byte[RingProtocol.CONTINUATION_PREFIX_LEN + (whole.length - 244)]; + System.arraycopy(whole, 244, continuation, RingProtocol.CONTINUATION_PREFIX_LEN, whole.length - 244); + expect("continuation is 5 + remaining bytes", continuation.length == 13); + + byte[] interleaved = RingProtocol.buildFrame( + RingProtocol.CHAN_DEVICE, RingProtocol.KIND_DATA, 0x00, 0x01, 0x16, new byte[9]); + + RingProtocol.Reassembler reassembler = new RingProtocol.Reassembler(); + + RingProtocol.Intake first = reassembler.accept(head); + expect("head consumed", first.consumed && first.frame == null); + expect("fragment outstanding", reassembler.hasPending()); + + RingProtocol.Intake middle = reassembler.accept(interleaved); + expect("interleaved frame still parses while a fragment is pending", + middle.consumed && middle.frame != null && middle.frame.crcOk); + expect("fragment survives the interleaved frame", reassembler.hasPending()); + + RingProtocol.Intake done = reassembler.accept(continuation); + expect("continuation completes the frame", done.consumed && done.frame != null); + expect("reassembled frame passes CRC", done.frame.crcOk); + expect("reassembled bytes are exact", + Arrays.equals(done.frame.raw, headJoined(head, whole))); + expect("no fragment left outstanding", !reassembler.hasPending()); + expect("reassembled payload is intact", Arrays.equals(done.frame.payload, payload)); + + // Non-protocol traffic must pass straight through untouched. + RingProtocol.Intake gesture = reassembler.accept(new byte[] {(byte) 0xff, 0x04, 0x01}); + expect("gesture frame is not consumed", !gesture.consumed); + } + + private static byte[] headJoined(byte[] head, byte[] whole) { + byte[] expected = whole.clone(); + expected[0] = head[0]; + return expected; + } + + // ------------------------------------------------------------------ + // Synthetic record bodies, built directly from the spec's field layout. + // ------------------------------------------------------------------ + + private static void testHourlyDecode() { + section("hourly decode (heart rate W=1, HRV W=2, backlog page)"); + + // Anchored heart-rate page, W=1, three groups. + long anchor = 1788926400L; // 2026-09-09 00:00 local, the capture's anchor + int[][] groups = {{0, 61, 88, 55}, {1, 58, 71, 52}, {2, 63, 90, 57}}; + byte[] body = hourlyBody(3, anchor, 12345L, 64, 1, groups); + RingProtocol.Frame frame = dataFrame(RingProtocol.CMD_HI_HEART_RATE, body); + RingProtocol.HourlyRecord hr = RingProtocol.decodeHourly(frame, 0L); + expect("HR decodes", hr != null); + expect("HR width resolved to 1", hr.valueWidth == 1); + expect("HR group count", hr.groups.length == 3); + expect("HR anchor", hr.anchorUnixSeconds == anchor); + expect("HR not backlog", !hr.isBacklog()); + expect("HR current", hr.current == 64); + boolean values = true; + for (int i = 0; i < groups.length; i++) { + RingProtocol.HourlyGroup g = hr.groups[i]; + values &= g.hourIndex == groups[i][0] && g.avg == groups[i][1] + && g.max == groups[i][2] && g.min == groups[i][3] + && g.unixSeconds == anchor + groups[i][0] * 3600L; + } + expect("HR values and hour timestamps round-trip", values); + + // HRV uses two-byte values; the width must be resolved, not assumed. + int[][] hrvGroups = {{8, 300, 420, 210}, {9, 275, 380, 190}, {10, 512, 640, 400}}; + byte[] hrvBody = hourlyBody(3, anchor, 22222L, 333, 2, hrvGroups); + RingProtocol.HourlyRecord hrv = + RingProtocol.decodeHourly(dataFrame(RingProtocol.CMD_HI_HRV, hrvBody), 0L); + expect("HRV decodes", hrv != null); + expect("HRV width resolved to 2", hrv.valueWidth == 2); + expect("HRV current", hrv.current == 333); + expect("HRV holds values above 255", hrv.groups[2].max == 640); + + // Backlog page: anchor absent. The hour index must survive; the absolute + // time must NOT be invented. + byte[] backlogBody = hourlyBody(3, RingProtocol.UNKNOWN_TIME, 77777L, 60, 1, groups); + RingProtocol.HourlyRecord backlog = + RingProtocol.decodeHourly(dataFrame(RingProtocol.CMD_HI_HEART_RATE, backlogBody), 0L); + expect("backlog decodes", backlog != null); + expect("backlog flagged", backlog.isBacklog()); + expect("backlog anchor unknown", backlog.anchorUnixSeconds == RingProtocol.UNKNOWN_TIME); + boolean noInventedTime = true; + for (RingProtocol.HourlyGroup g : backlog.groups) { + noInventedTime &= g.unixSeconds == RingProtocol.UNKNOWN_TIME; + } + expect("backlog groups carry no invented absolute time", noInventedTime); + expect("backlog keeps raw hour indices", + backlog.groups[0].hourIndex == 0 && backlog.groups[2].hourIndex == 2); + expect("backlog still decodes values", backlog.groups[1].avg == 58); + } + + private static void testStepsDecode() { + section("steps decode"); + long anchor = 1788926400L; + int[][] buckets = {{0, 120, 4, 16}, {3, 0, 0, 12}, {130, 45, 2, 14}}; + byte[] body = stepsBody(anchor, buckets); + RingProtocol.StepsRecord steps = + RingProtocol.decodeSteps(dataFrame(RingProtocol.CMD_HI_STEPS, body), 0L); + expect("steps decode", steps != null); + expect("bucket count", steps.buckets.length == 3); + expect("total steps", steps.totalSteps() == 165); + expect("raw index preserved, including the 130+ jump", + steps.buckets[2].index == 130); + expect("v2/v3 kept as unconfirmed calorie-shaped fields", + steps.buckets[0].calorieLike2 == 4 && steps.buckets[0].calorieLike3 == 16); + expect("steps anchor", steps.anchorUnixSeconds == anchor); + // Length must be exact: a truncated body is a decode failure, not a guess. + byte[] shortBody = Arrays.copyOf(body, body.length - 1); + expect("truncated steps body rejected", + RingProtocol.decodeSteps(dataFrame(RingProtocol.CMD_HI_STEPS, shortBody), 0L) == null); + } + + private static void testSleepDecodeAndIdentities() { + section("sleep decode + the spec's arithmetic identities"); + // segments: (stage, halfMinutes). Stage sums: 0->10, 1->20, 2->70, 3->25. + int[][] segments = {{0, 4}, {1, 20}, {2, 40}, {0, 6}, {2, 30}, {3, 25}}; + int totalHalfMinutes = 125; + int seconds = totalHalfMinutes * 30; // 3750 + int wake = 10 * 30; // 300, stage 0 + int rem = 20 * 30; // 600, stage 1 + int light = 70 * 30; // 2100, stage 2 + int deep = 25 * 30; // 750, stage 3 + int total = seconds - wake; // 3450 + long start = 100000L; + long end = start + seconds; + + byte[] body = sleepBody(1, start, end, total, wake, rem, light, deep, segments); + RingProtocol.SleepRecord sleep = + RingProtocol.decodeSleep(dataFrame(RingProtocol.CMD_HI_SLEEP, body), 0L); + expect("sleep decodes", sleep != null); + expect("real record", sleep.isRealRecord()); + expect("segment count", sleep.segments.length == segments.length); + expect("segment stages and durations round-trip", + sleep.segments[2].stage == 2 && sleep.segments[2].halfMinutes == 40); + + expect("identity: sum(half_minutes) x 30 == total_time + wake_time", + sleep.totalHalfMinutes() * 30 == sleep.totalTime + sleep.wakeTime); + expect("identity: sum(half_minutes) x 30 == end_ts - start_ts", + sleep.totalHalfMinutes() * 30 == (int) (sleep.endTs - sleep.startTs)); + expect("identity: per-stage sums match the four stage totals", + sleep.halfMinutesForStage(0) * 30 == wake + && sleep.halfMinutesForStage(1) * 30 == rem + && sleep.halfMinutesForStage(2) * 30 == light + && sleep.halfMinutesForStage(3) * 30 == deep); + expect("identitiesHold() agrees", sleep.identitiesHold()); + + expect("uncracked 6-byte field stored raw, not interpreted", + sleep.unknownPrefix.length == 6); + expect("relative timestamps kept as sent", + sleep.startTs == start && sleep.endTs == end); + + // The empty end-of-list marker must decode without inventing a session. + byte[] marker = new byte[] {0x11, 0x22, 0x02}; + RingProtocol.SleepRecord empty = + RingProtocol.decodeSleep(dataFrame(RingProtocol.CMD_HI_SLEEP, marker), 0L); + expect("RECSTATE=2 marker decodes", empty != null && !empty.isRealRecord()); + expect("marker has no segments", empty.segments.length == 0); + + // A declared segment count that does not fill the body is a parse failure. + byte[] broken = body.clone(); + broken[32] = (byte) (segments.length + 1); + expect("segment-count mismatch rejected", + RingProtocol.decodeSleep(dataFrame(RingProtocol.CMD_HI_SLEEP, broken), 0L) == null); + } + + // ------------------------------------------------------------------ + private static void testDailyWireLayouts() { + section("footer-free daily layouts and timezone anchors"); + long anchor = 1789700400L; + byte[] hr = hourlyBody(2, anchor, anchor + 3600, 70, 1, + new int[][] {{0, 70, 80, 60}, {1, 72, 82, 62}}); + expect("two-hour HR frame is 37 bytes", dataFrame(1, hr).raw.length == 37); + for (int timezone : new int[] {-420, -240, 0, 330, 840}) { + putLe(hr, 3, timezone, 2); + RingProtocol.HourlyRecord decoded = RingProtocol.decodeHourly(dataFrame(1, hr), 0); + expect("anchor works at timezone " + timezone, + decoded != null && decoded.anchorUnixSeconds == anchor && decoded.groups.length == 2); + } + byte[] spo2 = hourlyBody(1, anchor, anchor, 98, 1, new int[][] {{0, 98, 99, 97}}); + expect("one-hour SpO2 frame is 33 bytes", dataFrame(2, spo2).raw.length == 33); + expect("SpO2 decodes without footer", RingProtocol.decodeHourly(dataFrame(2, spo2), 0).groups[0].avg == 98); + byte[] hrv = hourlyBody(1, anchor, anchor, 51, 2, new int[][] {{3, 51, 300, 40}}); + RingProtocol.HourlyRecord variability = RingProtocol.decodeHourly(dataFrame(4, hrv), 0); + expect("one-hour HRV retains two-byte values", variability.valueWidth == 2 + && variability.groups[0].hourIndex == 3 && variability.groups[0].max == 300); + + // Offline daily pages omit the five-byte latest-reading prefix. + byte[] offline = new byte[9 + 8]; + System.arraycopy(hr, 0, offline, 0, 9); + System.arraycopy(hr, 14, offline, 9, 8); + RingProtocol.HourlyRecord past = RingProtocol.decodeHourly(dataFrame(1, offline), 0); + expect("daily page without latest sample decodes", past != null + && past.current == -1 && past.groups[1].avg == 72); + putLe(offline, 5, 0, 4); + expect("zero day remains unresolved", RingProtocol.anchorUnixSeconds(offline) == RingProtocol.UNKNOWN_TIME); + + int[][] buckets = new int[8][4]; + for (int i = 0; i < buckets.length; i++) buckets[i] = new int[] {i, i * 10, 1, 2}; + byte[] activity = stepsBody(anchor, buckets); + expect("eight-bucket activity frame is 80 bytes", dataFrame(5, activity).raw.length == 80); + expect("activity decodes without footer", RingProtocol.decodeSteps(dataFrame(5, activity), 0).buckets.length == 8); + // Four extra bytes are firmware 2.3.x's trailer (testFirmware23Trailer); other lengths are garbage. + for (int extra : new int[] {1, 3, 5, 7}) { + expect("activity with " + extra + " trailing bytes rejected", RingProtocol.decodeSteps(dataFrame(5, + Arrays.copyOf(activity, activity.length + extra)), 0) == null); + } + } + + /** Firmware 2.3.x appends four bytes to every health page; 2.0.7 did not. */ + private static void testFirmware23Trailer() { + section("firmware 2.3.x four-byte page trailer"); + long anchor = 1793520000L; // 2026-11-01 00:00 PST, the anchor 2.3.2.0008 sent + byte[] trailer = {(byte) 0xad, 0x5e, 0x00, 0x00}; + + byte[] hr = withTrailer(hourlyBody(2, anchor, 24037L, 77, 1, + new int[][] {{13, 74, 80, 69}, {14, 74, 81, 68}}), trailer); + expect("two-hour HR page with trailer is 41 bytes", dataFrame(1, hr).raw.length == 41); + RingProtocol.HourlyRecord heart = RingProtocol.decodeHourly(dataFrame(1, hr), 0); + expect("HR with trailer decodes", heart != null && heart.groups.length == 2 + && heart.current == 77 && heart.anchorUnixSeconds == anchor + && heart.groups[1].hourIndex == 14 && heart.groups[1].max == 81 && heart.groups[1].min == 68); + + byte[] hrv = withTrailer(hourlyBody(2, anchor, 21676L, 54, 2, + new int[][] {{13, 65, 65, 65}, {14, 54, 300, 54}}), trailer); + expect("two-hour HRV page with trailer is 48 bytes", dataFrame(4, hrv).raw.length == 48); + RingProtocol.HourlyRecord variability = RingProtocol.decodeHourly(dataFrame(4, hrv), 0); + expect("HRV with trailer keeps two-byte values", variability != null && variability.valueWidth == 2 + && variability.current == 54 && variability.groups[1].max == 300); + + byte[] spo2 = withTrailer(hourlyBody(1, anchor, anchor + 70344L, 97, 1, + new int[][] {{19, 97, 97, 97}}), trailer); + expect("one-hour SpO2 page with trailer is 37 bytes", dataFrame(2, spo2).raw.length == 37); + RingProtocol.HourlyRecord oxygen = RingProtocol.decodeHourly(dataFrame(2, spo2), 0); + expect("SpO2 with trailer decodes", oxygen != null && oxygen.groups[0].hourIndex == 19 && oxygen.groups[0].avg == 97); + + // No latest-reading prefix, plus the trailer: 9 + 4 bytes around the groups. + byte[] offline = new byte[9 + 4 + 4]; + System.arraycopy(spo2, 0, offline, 0, 9); + System.arraycopy(spo2, 14, offline, 9, 4); + System.arraycopy(trailer, 0, offline, 13, 4); + RingProtocol.HourlyRecord past = RingProtocol.decodeHourly(dataFrame(2, offline), 0); + expect("page without latest reading, with trailer, decodes", past != null + && past.current == -1 && past.groups[0].hourIndex == 19); + expect("HR with one stray byte rejected", + RingProtocol.decodeHourly(dataFrame(1, Arrays.copyOf(hr, hr.length + 1)), 0) == null); + + int[][] buckets = new int[8][4]; + for (int i = 0; i < buckets.length; i++) buckets[i] = new int[] {80 + i, i * 11, i, 2 * i}; + byte[] activity = withTrailer(stepsBody(anchor, buckets), trailer); + expect("eight-bucket activity page with trailer is 84 bytes", dataFrame(5, activity).raw.length == 84); + RingProtocol.StepsRecord steps = RingProtocol.decodeSteps(dataFrame(5, activity), 0); + expect("activity with trailer decodes", steps != null && steps.buckets.length == 8 + && steps.buckets[7].index == 87 && steps.buckets[7].steps == 77); + + byte[] sleep = withTrailer(sleepBody(1, 1000L, 1000L + 120, 60, 60, 0, 60, 0, + new int[][] {{0, 2}, {2, 2}}), trailer); + RingProtocol.SleepRecord night = RingProtocol.decodeSleep(dataFrame(6, sleep), 0); + expect("sleep with trailer decodes", night != null && night.isRealRecord() && night.segments.length == 2); + } + + private static void testFrameJournalReplay() { + section("frame journal replay"); + long anchor = 1793520000L; + byte[] hr = withTrailer(hourlyBody(1, anchor, 1L, 70, 1, new int[][] {{13, 70, 75, 65}}), + new byte[] {0, 0, 0, 0}); + byte[] page = dataFrame(1, hr).raw; + byte[] rsp = RingProtocol.buildFrame(RingProtocol.CHAN_HEALTH, RingProtocol.KIND_RSP, 1, + RingProtocol.CMD_LO_HEALTH, 3, new byte[] {0, 0}); + byte[] battery = RingProtocol.buildFrame(RingProtocol.CHAN_DEVICE, RingProtocol.KIND_RSP, 0, 1, 4, + new byte[] {0x11, 0x22, 82, 2, 1, 0, 0, 0, 0}); + // The writer's own shape: a blank line, the record, a newline. + String journal = "\n{\"receivedAtMs\":100,\"raw\":\"" + RingProtocol.hex(page) + "\"}\n" + + "\n{\"receivedAtMs\":200,\"raw\":\"" + RingProtocol.hex(rsp) + "\"}\n" + + "\n{\"receivedAtMs\":300,\"raw\":\"" + RingProtocol.hex(battery) + "\"}\n" + + "{\"receivedAtMs\":350,\"raw\":\"zz\"}\n" + + "half a line from a failed app{\"receivedAtMs\":\n" + + "\n{\"receivedAtMs\":400,\"raw\":\"" + RingProtocol.hex(page) + "\"}\n"; + List all = RingProtocol.decodeFrameJournal(journal, 0L); + expect("only health DATA pages come back", all.size() == 2); + expect("each keeps its journaled receive time", + all.get(0).receivedAtMs == 100L && all.get(1).receivedAtMs == 400L); + expect("decoded as heart rate", all.get(0) instanceof RingProtocol.HourlyRecord + && ((RingProtocol.HourlyRecord) all.get(0)).groups[0].avg == 70); + List later = RingProtocol.decodeFrameJournal(journal, 100L); + expect("cursor skips what was already replayed", later.size() == 1 && later.get(0).receivedAtMs == 400L); + } + + private static byte[] withTrailer(byte[] body, byte[] trailer) { + byte[] out = Arrays.copyOf(body, body.length + trailer.length); + System.arraycopy(trailer, 0, out, body.length, trailer.length); + return out; + } + + private static void testDeviceStatus() { + section("direct device status battery"); + byte[] payload = {0x11, 0x22, 82, 2, 1, 0, 0, 0, 0}; + for (int charge = 0; charge <= 3; charge++) { + payload[3] = (byte) charge; + RingProtocol.Frame frame = RingProtocol.parse(RingProtocol.buildFrame( + RingProtocol.CHAN_DEVICE, RingProtocol.KIND_RSP, 0, 1, 1, payload)); + RingProtocol.DeviceStatus status = RingProtocol.decodeDeviceStatus(frame); + expect("battery and charge enum " + charge, status != null && status.battery == 82 + && status.charging == (charge == 0 ? -1 : charge == 2 ? 0 : 1)); + } + payload[2] = (byte) 255; + expect("invalid battery rejected", RingProtocol.decodeDeviceStatus(RingProtocol.parse( + RingProtocol.buildFrame(1, 3, 0, 1, 1, payload))) == null); + expect("wrong channel rejected", RingProtocol.decodeDeviceStatus(dataFrame(1, payload)) == null); + expect("short response rejected", RingProtocol.decodeDeviceStatus(RingProtocol.parse( + RingProtocol.buildFrame(1, 3, 0, 1, 1, new byte[2]))) == null); + } + + // Synthetic body builders matching the recovered R1 serializers. + // ------------------------------------------------------------------ + + private static byte[] hourlyBody(int count, long anchor, long tag, int current, + int width, int[][] groups) { + byte[] body = new byte[13 + width + count * (1 + 3 * width)]; + body[0] = 0x11; + body[1] = 0x22; + body[2] = (byte) count; + writeAnchor(body, anchor); + putLe(body, 9, tag, 4); + putLe(body, 13, current, width); + int offset = 13 + width; + for (int[] g : groups) { + body[offset++] = (byte) g[0]; + putLe(body, offset, g[1], width); + offset += width; + putLe(body, offset, g[2], width); + offset += width; + putLe(body, offset, g[3], width); + offset += width; + } + return body; + } + + private static byte[] stepsBody(long anchor, int[][] buckets) { + byte[] body = new byte[9 + buckets.length * 7]; + body[0] = 0x33; + body[1] = 0x44; + body[2] = (byte) buckets.length; + writeAnchor(body, anchor); + int offset = 9; + for (int[] b : buckets) { + body[offset] = (byte) b[0]; + putLe(body, offset + 1, b[1], 2); + putLe(body, offset + 3, b[2], 2); + putLe(body, offset + 5, b[3], 2); + offset += 7; + } + return body; + } + + private static byte[] sleepBody(int recordState, long start, long end, int total, int wake, + int rem, int light, int deep, int[][] segments) { + byte[] body = new byte[34 + segments.length * 3]; + body[0] = 0x55; + body[1] = 0x66; + body[2] = (byte) recordState; + for (int i = 3; i < 9; i++) { + body[i] = (byte) (0xA0 + i); // the uncracked 6-byte field + } + putLe(body, 9, 90210L, 4); // the uncracked u32 tag + body[13] = 0x00; + putLe(body, 14, start, 4); + putLe(body, 18, end, 4); + putLe(body, 22, total, 2); + putLe(body, 24, wake, 2); + putLe(body, 26, rem, 2); + putLe(body, 28, light, 2); + putLe(body, 30, deep, 2); + body[32] = (byte) segments.length; + body[33] = 0x00; + int offset = 34; + for (int[] s : segments) { + body[offset] = (byte) s[0]; + putLe(body, offset + 1, s[1], 2); + offset += 3; + } + return body; + } + + private static void writeAnchor(byte[] body, long anchor) { + if (anchor == RingProtocol.UNKNOWN_TIME) { + return; // six zero bytes = backlog page + } + body[3] = 0x10; + body[4] = (byte) 0xFF; + putLe(body, 5, anchor, 4); + } + + private static void putLe(byte[] out, int offset, long value, int width) { + for (int i = 0; i < width; i++) { + out[offset + i] = (byte) ((value >>> (8 * i)) & 0xff); + } + } + + private static RingProtocol.Frame dataFrame(int cmdHi, byte[] body) { + byte[] frame = RingProtocol.buildFrame( + RingProtocol.CHAN_HEALTH, RingProtocol.KIND_DATA, cmdHi, + RingProtocol.CMD_LO_HEALTH, 0x20, body); + return RingProtocol.parse(frame); + } + + // ------------------------------------------------------------------ + + private static void section(String name) { + System.out.println(); + System.out.println("-- " + name); + } + + private static void expect(String what, boolean ok) { + checks++; + if (!ok) { + failures++; + } + System.out.println(" " + (ok ? "ok " : "FAIL") + " " + what); + } + + private static void expectHex(String what, String expectedHex, byte[] actual) { + String actualHex = RingProtocol.hex(actual); + boolean ok = expectedHex.equals(actualHex); + checks++; + if (!ok) { + failures++; + System.out.println(" FAIL " + what); + System.out.println(" expected " + expectedHex); + System.out.println(" actual " + actualHex); + return; + } + System.out.println(" ok " + what + " " + actualHex); + } + + private static String hex2(int value) { + return String.format(java.util.Locale.US, "%02x", value & 0xff); + } +} diff --git a/tests/kotlin/src/androidHostTest/kotlin/com/faceclaw/app/JavaCompatibilityTest.kt b/tests/kotlin/src/androidHostTest/kotlin/com/faceclaw/app/JavaCompatibilityTest.kt index db32038b..7de31d04 100644 --- a/tests/kotlin/src/androidHostTest/kotlin/com/faceclaw/app/JavaCompatibilityTest.kt +++ b/tests/kotlin/src/androidHostTest/kotlin/com/faceclaw/app/JavaCompatibilityTest.kt @@ -11,6 +11,8 @@ class JavaCompatibilityTest { @Test fun gestures() = FaceclawGestureEventTest.main(emptyArray()) @Test fun resourceCache() = ResourceCacheProtocolTest.main(emptyArray()) + + @Test fun ringHealthProtocol() = RingProtocolSelfTest.main(emptyArray()) } class AndroidByteReaderTest { diff --git a/tests/kotlin/src/commonTest/kotlin/com/faceclaw/app/GlassesRingLinkTest.kt b/tests/kotlin/src/commonTest/kotlin/com/faceclaw/app/GlassesRingLinkTest.kt new file mode 100644 index 00000000..d6c91649 --- /dev/null +++ b/tests/kotlin/src/commonTest/kotlin/com/faceclaw/app/GlassesRingLinkTest.kt @@ -0,0 +1,125 @@ +package com.faceclaw.app + +import kotlin.test.* + +class GlassesRingLinkTest { + private fun hex(value: String) = value.chunked(2).map { it.toInt(16).toByte() }.toByteArray() + private fun toHex(bytes: ByteArray) = bytes.joinToString("") { (it.toInt() and 0xff).toString(16).padStart(2, '0') } + private val mac = hex("b16a9f2f43dc") + + @Test fun macWireBytesAreLeastSignificantFirst() { + assertEquals("b16a9f2f43dc", toHex(assertNotNull(macWireBytes("DC:43:2F:9F:6A:B1")))) + assertNull(macWireBytes("")) + assertNull(macWireBytes("DC:43:2F:9F:6A")) + assertNull(macWireBytes("DC:43:2F:9F:6A:ZZ")) + } + + @Test fun disconnectRequestWireShape() { + // commandId=8 magic=0x21 disconnectInfo(7){dev=0, ringMac} + assertEquals("080810213a0a08001206b16a9f2f43dc", toHex(BleProtocol.buildRingDisconnectRequest(0x21, mac))) + } + + @Test fun connectRequestWireShape() { + // commandId=6 magic=0x21 ringInfo(5){connectRing=[01], ringMac, ringName="R1"} + assertEquals("08061021" + "2a" + "0f" + "0a0101" + "1206b16a9f2f43dc" + "1a025231", + toHex(BleProtocol.buildRingConnectRequest(0x21, true, mac, "R1".encodeToByteArray()))) + } + + @Test fun parsesGlassesReportsThroughFraming() { + // A RING_CONNECT_INFO notification: ringInfo{connectRing, ringMac, ringName, connRet=0}. + val info = hex("0a0101") + hex("1206") + mac + hex("1a025231") + hex("2000") + val pb = hex("0806") + hex("1005") + byteArrayOf(0x2a, info.size.toByte()) + info + val frame = BleProtocol.parseFrame(BleProtocol.framePb(pb, BleProtocol.SID_SECURITY_AUTH, 1, 1).single()) + val report = assertNotNull(BleProtocol.parseRingConnectInfo(frame.pb)) + assertEquals("b16a9f2f43dc", toHex(assertNotNull(report.ringMac))) + assertEquals("R1", report.ringName) + assertEquals(0, report.code) + + // even-g2-protocol's captured sid-0x91 "Device Identity": {1:1, 2:19, 3:{1:mac, 2:1}} + val event = hex("08011013" + "1a0a" + "0a06b16a9f2f43dc" + "1001") + val eventFrame = BleProtocol.parseFrame(BleProtocol.framePb(event, BleProtocol.SID_RING_DATA, 1, 1).single()) + val ringEvent = assertNotNull(BleProtocol.parseRingDataEvent(eventFrame.pb)) + assertEquals("b16a9f2f43dc", toHex(assertNotNull(ringEvent.ringMac))) + assertEquals(1, ringEvent.code) + + assertNull(BleProtocol.parseRingConnectInfo(BleProtocol.buildAuthenticationRequest(3))) + } + + @Test fun unpairRequestWireShape() { + // commandId=9 magic=0x21 unpairInfo(8){dev=RING(0), ringMac} + assertEquals("0809" + "1021" + "420a" + "0800" + "1206b16a9f2f43dc", toHex(BleProtocol.buildRingUnpairRequest(0x21, mac))) + } + + @Test fun ringChecksumMatchesCapturedEvenFrames() { + // Frames from HCI snoops of Even's app (g2-kit-unofficial examples/ring-direct.ts). + assertEquals("00971953f964016401000000080d003f0101", toHex(RingProtocol.buildPairAuth(1))) + assertEquals("00f979f7b164016404000000020c001b64", + toHex(RingProtocol.buildCheckedFrame(RingProtocol.CHAN_DEVICE, RingProtocol.KIND_REQ, 0x00, 0x02, 4, ByteArray(0)))) + assertEquals("002d946c0164026405000001010c002ac6", + toHex(RingProtocol.buildCheckedFrame(RingProtocol.CHAN_HEALTH, RingProtocol.KIND_REQ, 0x01, 0x01, 5, ByteArray(0)))) + assertEquals("00d4c9ba7064016403000200051200807710ff3348bb69", + toHex(RingProtocol.buildCheckedFrame(RingProtocol.CHAN_DEVICE, RingProtocol.KIND_DATA, 0x00, 0x05, 3, hex("10ff3348bb69")))) + } + + @Test fun advStartCarriesBothTargetsLeastSignificantFirst() { + val right = assertNotNull(macWireBytes("EC:D7:82:69:3C:CB")) + val left = assertNotNull(macWireBytes("C4:5A:23:3D:F5:F8")) + val frame = RingProtocol.buildAdvStart(9, right, left) + assertValidRingFrame(frame) + assertEquals("00" + "000a", toHex(frame.copyOfRange(10, 13))) + assertEquals("cb3c6982d7ec" + "f8f53d235ac4", toHex(frame.copyOfRange(17, frame.size))) + assertEquals("ffffffffffff".repeat(2), + toHex(RingProtocol.buildAdvStart(9, ByteArray(6) { 0xff.toByte() }, ByteArray(6) { 0xff.toByte() }).copyOfRange(17, 29))) + } + + @Test fun touchSwitchAndRemoveRingAreSets() { + val on = RingProtocol.buildTouchSwitch(2, RingProtocol.TOUCH_SWITCH_SELECTOR_GLASSES, true) + assertValidRingFrame(on) + assertEquals("02" + "0007", toHex(on.copyOfRange(10, 13))) + assertEquals("0201", toHex(on.copyOfRange(17, on.size))) + assertEquals("0200", toHex(RingProtocol.buildTouchSwitch(2, 2, false).copyOfRange(17, 19))) + + val remove = RingProtocol.buildRemoveRingNotify(3) + assertValidRingFrame(remove) + assertEquals("02" + "0082" + "01", toHex(remove.copyOfRange(10, 13)) + toHex(remove.copyOfRange(17, remove.size))) + } + + @Test fun legacyGlassesChannelFrames() { + // Bytes from g2-firmware-emulator: the stock G2's pair-auth, the R1's battery + // report (67%, then charging) and its non-target rejection. + assertEquals("00358800", toHex(RingProtocol.LEGACY_GLASSES_PAIR_AUTH)) + val idle = assertNotNull(RingProtocol.parseLegacyBattery(hex("00098b004300"))) + assertEquals(67, idle.battery) + assertEquals(0, idle.charging) + assertEquals(1, assertNotNull(RingProtocol.parseLegacyBattery(hex("00098b004301"))).charging) + assertNull(RingProtocol.parseLegacyBattery(hex("00098b006500"))) // 101% + assertNull(RingProtocol.parseLegacyBattery(hex("00098b0043"))) + assertNull(RingProtocol.parseLegacyBattery(hex("000961000a000013cb0000"))) + assertTrue(RingProtocol.isLegacyTargetRejected(hex("00019600"))) + assertFalse(RingProtocol.isLegacyTargetRejected(hex("0001960000"))) + // Neither is mistaken for input. + assertNull(FaceclawRingEventDecoder.decode(hex("00098b004300"))) + assertNull(FaceclawRingEventDecoder.decode(hex("00019600"))) + } + + @Test fun ringResponseStatusDecodes() { + assertEquals("ok", RingProtocol.responseResult(0x03)) + assertEquals("error", RingProtocol.responseResult(0x07)) + assertEquals("refused", RingProtocol.responseResult(0x0b)) + assertEquals("unsupported", RingProtocol.responseResult(0x0f)) + assertNull(RingProtocol.responseResult(0x00)) + assertNull(RingProtocol.responseResult(0x02)) + } + + /** Outer CRC-32C and inner phone checksum both match the bytes. */ + private fun assertValidRingFrame(frame: ByteArray) { + val crc32 = (frame[1].toInt() and 0xff) or ((frame[2].toInt() and 0xff) shl 8) or + ((frame[3].toInt() and 0xff) shl 16) or ((frame[4].toInt() and 0xff) shl 24) + assertEquals(RingProtocol.crc32(frame, 5, frame.size), crc32) + val args = frame.copyOfRange(17, frame.size) + val checksum = RingProtocol.phoneChecksum(frame[6].toInt(), frame[8].toInt() and 0xff, + frame[10].toInt(), frame[11].toInt(), frame[12].toInt() and 0xff, args) + assertEquals(checksum, (frame[15].toInt() and 0xff) or ((frame[16].toInt() and 0xff) shl 8)) + assertEquals(frame.size - 5, (frame[13].toInt() and 0xff) or ((frame[14].toInt() and 0xff) shl 8)) + } +} diff --git a/tests/kotlin/src/commonTest/kotlin/com/faceclaw/app/RingHealthTransferTest.kt b/tests/kotlin/src/commonTest/kotlin/com/faceclaw/app/RingHealthTransferTest.kt new file mode 100644 index 00000000..d280e85f --- /dev/null +++ b/tests/kotlin/src/commonTest/kotlin/com/faceclaw/app/RingHealthTransferTest.kt @@ -0,0 +1,375 @@ +package com.faceclaw.app + +import kotlin.concurrent.Volatile +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +private const val RING = "CC:00:00:00:00:03" + +/** + * A ring that answers health requests through the session's real notification + * path: each REQ gets DATA page `cmd*10+1`, then its RSP; the ACK for a page + * ending in 1 triggers page `+1`, so the transfer is ACK-paced like the real + * ring's backlog. + */ +private class FakeRingLink(private val platform: ProtocolPlatform) : SessionLink { + lateinit var core: GlassesSessionCore + private val lock = platform.createLock() + private val writesList = ArrayList() + private val subscribedList = ArrayList() + @Volatile var failAck = false + @Volatile var answer = true + @Volatile var delayRsp = false + @Volatile var requestStarted = false + + val writes: List + get() = lock.withLock { writesList.toList() } + + /** Every CCCD enabled, in order, across connections. */ + val subscribed: List + get() = lock.withLock { subscribedList.toList() } + + @Volatile var disconnects = 0 + + private fun deliver(frame: ByteArray) = core.onNotification(RING, BleProtocol.R1_NOTIFY_CHAR_UUID, frame) + + private fun page(cmdHi: Int, pageSeq: Int) = + deliver(RingProtocol.buildFrame(RingProtocol.CHAN_HEALTH, RingProtocol.KIND_DATA, cmdHi, + RingProtocol.CMD_LO_HEALTH, pageSeq, byteArrayOf(0, 0))) + + private fun rsp(cmdHi: Int) = + deliver(RingProtocol.buildFrame(RingProtocol.CHAN_HEALTH, RingProtocol.KIND_RSP, cmdHi, + RingProtocol.CMD_LO_HEALTH, 0, byteArrayOf(0, 0))) + + override fun writeFrames(address: String, characteristicUuid: String, frames: List, mode: GattWriteMode, timeoutMs: Int): Boolean { + assertEquals(RING, address) + assertEquals(BleProtocol.R1_WRITE_CHAR_UUID, characteristicUuid) + val frame = RingProtocol.parse(frames.single())!! + if (frame.kind == RingProtocol.KIND_ACK) { + if (failAck) return false + val pageSeq = frame.payload[6].toInt() and 0xff + val cmdHi = frame.payload[3].toInt() and 0xff + lock.withLock { writesList.add("ack:$pageSeq") } + // A write longer than the idle timeout: page two arrives only + // after page one's ACK has actually completed. + sleepMs(130) + if (pageSeq % 10 == 1) { + startThread("ring-page", true) { + sleepMs(5) + page(cmdHi, pageSeq + 1) + } + } + } else if (frame.chan == RingProtocol.CHAN_HEALTH && frame.kind == RingProtocol.KIND_REQ) { + requestStarted = true + lock.withLock { writesList.add("req:" + frame.cmdHi) } + if (answer) { + page(frame.cmdHi, frame.cmdHi * 10 + 1) + if (delayRsp) { + startThread("ring-rsp", true) { + sleepMs(20) + rsp(frame.cmdHi) + } + } else { + rsp(frame.cmdHi) + } + } + } + // Device-channel pings between health types are not answered. + return true + } + + override fun connect(address: String, timeoutMs: Int): Boolean = true + + override fun requestHighPriority(address: String) {} + + override fun requestMtu(address: String, mtu: Int, timeoutMs: Int): Boolean = true + + override fun negotiatedMtu(address: String): Int = 247 + + override fun discoverServices(address: String, timeoutMs: Int): Boolean = true + + override fun enableNotifications(address: String, characteristicUuid: String, enable: Boolean, timeoutMs: Int): Boolean { + lock.withLock { subscribedList.add(characteristicUuid) } + return true + } + + override fun disconnect(address: String) { + disconnects++ + } + + override fun close() {} + + override fun isBonded(address: String): Boolean = true + + override fun prepareBenchmarkLink(address: String, mode: Int) {} + + override fun recordDisplayFrameSent() {} +} + +private class RingHost : SessionHost { + @Volatile var journalFails = false + val journal = ArrayList() + + override fun postToMain(action: () -> Unit) = action() + + override fun currentThreadDispatcher(): SessionDispatcher = SessionDispatcher { it() } + + override fun isPhoneLocked(): Boolean = false + + override fun setScreenWakeLock(on: Boolean) {} + + override fun isEvenAppActive(): Boolean = false + + override fun startWorker(body: () -> Unit) {} + + override fun joinWorker(timeoutMs: Long) {} + + override fun supportsRingHealth(): Boolean = true + + override fun appendRingFrameJournal(line: String) { + if (journalFails) throw IllegalStateException("disk full") + synchronizedAdd(line) + } + + private val lock = testPlatform().createLock() + + private fun synchronizedAdd(line: String) = lock.withLock { journal.add(line) } + + override fun log(level: SessionLogLevel, tag: String, message: String, error: Throwable?) {} +} + +/** A core whose ring link is up, without running the glasses worker. */ +private class RingSession { + val platform = testPlatform() + val link = FakeRingLink(platform) + val host = RingHost() + val core = GlassesSessionCore(link, host, FrameTimingsCore(platform), platform, + "AA:00:00:00:00:01", "AA:00:00:00:00:02", RING) + + init { + link.core = core + core.ringHealthRspTimeoutMs = 500 + core.ringHealthDataIdleMs = 100 + core.monitor.withLock { + core.running = true + core.ringConnected = true + core.ringNotificationsReady = true + } + } + + fun outboundSize(): Int = core.monitor.withLock { core.ringOutbound.size } +} + +class RingHealthTransferTest { + @Test fun shutdownCancelsAnRspWait() { + val s = RingSession() + s.link.answer = false + s.core.ringHealthRspTimeoutMs = 10_000 + val done = Latch(1, s.platform) + startThread("ring-pull", true) { + s.core.requestRingHealth() + done.countDown() + } + val deadline = s.platform.elapsedRealtimeMs() + 1000 + while (!s.link.requestStarted && s.platform.elapsedRealtimeMs() < deadline) sleepMs(5) + assertTrue(s.link.requestStarted, "no request") + val start = s.platform.elapsedRealtimeMs() + s.core.monitor.withLock { + s.core.running = false + s.core.monitor.signalAll() + } + assertTrue(done.await(300), "ring pull did not stop") + assertTrue(s.platform.elapsedRealtimeMs() - start < 300, "session lock blocked") + } + + @Test fun ackPacedPagesDrainBeforeTheNextType() { + val s = RingSession() + s.link.delayRsp = true + assertTrue(s.core.requestRingHealth(), "pull failed") + val expected = RingProtocol.HEALTH_COMMANDS.flatMap { command -> + listOf("req:$command", "ack:" + (command * 10 + 1), "ack:" + (command * 10 + 2)) + } + assertEquals(expected, s.link.writes, "premature next type") + // Every intact frame (each page and each RSP) was journaled. + assertEquals(expected.count { it.startsWith("ack:") } + RingProtocol.HEALTH_COMMANDS.size, s.host.journal.size) + } + + @Test fun failedAckAbortsAndStaysQueuedForRetry() { + val s = RingSession() + s.link.failAck = true + assertFalse(s.core.requestRingHealth(), "failed ACK completed pull") + assertEquals(1, s.link.writes.size, "advanced after failed ACK") + assertEquals(1, s.outboundSize(), "failed ACK was discarded") + s.link.failAck = false + // The failure paused ring writes; the retry must not touch the link yet. + assertEquals(-1, s.core.flushRingOutbound(), "retried inside the write backoff") + assertEquals(1, s.outboundSize(), "backoff dropped the queued ACK") + s.core.monitor.withLock { s.core.ringWriteBlockedUntilMs = 0L } + assertTrue(s.core.awaitRingHealthDataIdle(s.core.ringHealthDataIdleMs), "retry failed") + assertEquals(0, s.outboundSize(), "retry did not drain ACKs") + } + + @Test fun writeBackoffGrowsAndResetsOnSuccess() { + val s = RingSession() + s.link.failAck = true + s.core.queueRingPageAck(RingProtocol.parse(RingProtocol.buildFrame(RingProtocol.CHAN_HEALTH, + RingProtocol.KIND_DATA, RingProtocol.CMD_HI_HEART_RATE, RingProtocol.CMD_LO_HEALTH, 1, byteArrayOf(0, 0)))!!) + fun pausedForMs() = s.core.monitor.withLock { s.core.ringWriteBlockedUntilMs - s.core.now() } + assertEquals(-1, s.core.flushRingOutbound()) + val first = pausedForMs() + s.core.monitor.withLock { s.core.ringWriteBlockedUntilMs = 0L } + assertEquals(-1, s.core.flushRingOutbound()) + assertTrue(pausedForMs() > first, "backoff did not grow") + s.link.failAck = false + s.core.monitor.withLock { s.core.ringWriteBlockedUntilMs = 0L } + assertEquals(1, s.core.flushRingOutbound()) + assertEquals(0, s.core.monitor.withLock { s.core.ringWriteFailures }, "success did not reset the backoff") + } + + @Test fun missingRspAbortsWithoutAdvancing() { + val s = RingSession() + s.link.answer = false + assertFalse(s.core.requestRingHealth(), "missing RSP completed pull") + assertEquals(1, s.link.writes.size, "advanced without RSP") + } + + @Test fun disconnectFailsTheDataWait() { + val s = RingSession() + s.core.monitor.withLock { s.core.ringConnected = false } + assertFalse(s.core.awaitRingHealthDataIdle(100), "disconnect completed transfer") + } + + @Test fun unjournaledPageIsNotAcknowledged() { + val s = RingSession() + s.host.journalFails = true + s.core.onNotification(RING, BleProtocol.R1_NOTIFY_CHAR_UUID, + RingProtocol.buildFrame(RingProtocol.CHAN_HEALTH, RingProtocol.KIND_DATA, RingProtocol.CMD_HI_HEART_RATE, + RingProtocol.CMD_LO_HEALTH, 7, byteArrayOf(0, 0))) + assertEquals(0, s.outboundSize()) + } + + @Test fun batchWatermarkOnlyClearsWhatWasTaken() { + val s = RingSession() + // A decodable one-group heart-rate page: count 1, tz 0, anchor 1000, then [hour][avg][max][min]. + val payload = byteArrayOf(0, 0, 1, 0, 0, 0xe8.toByte(), 0x03, 0, 0, 2, 60, 70, 50) + fun deliver(seq: Int) = s.core.onNotification(RING, BleProtocol.R1_NOTIFY_CHAR_UUID, + RingProtocol.buildFrame(RingProtocol.CHAN_HEALTH, RingProtocol.KIND_DATA, RingProtocol.CMD_HI_HEART_RATE, + RingProtocol.CMD_LO_HEALTH, seq, payload)) + deliver(1) + deliver(2) + val batch = s.core.takeRingHealthBatch() + assertEquals(2, batch.records.size) + assertEquals(2L, batch.watermark) + deliver(3) + assertEquals(2, s.core.clearRingHealthRecordsBelow(batch.watermark)) + val rest = s.core.getRingHealthRecords() + assertEquals(1, rest.size) + val record = rest.single() as RingProtocol.HourlyRecord + assertEquals(60, record.groups.single().avg) + assertEquals(1000L + 2 * 3600L, record.groups.single().unixSeconds) + } + /** A Direct-mode (glasses-role) session whose direct link is up. */ + private fun directSession(): RingSession { + val s = RingSession() + s.core.monitor.withLock { + s.core.directRingRole = DIRECT_RING_ROLE_GLASSES + s.core.sessionReady = true + } + return s + } + + @Test fun directModePullBorrowsThePhoneRoleAndHandsItBack() { + val s = directSession() + // Not the first pull this session, so only the request opens the window. + s.core.monitor.withLock { s.core.ringHealthLastRequestedAtMs = s.core.now() - 10 * 60_000L } + s.core.runRequestedRingHealthPull() + assertFalse(s.core.monitor.withLock { s.core.ringHealthWindowActive }, "opened without a request") + + s.core.requestRingHealthNow() + s.core.runRequestedRingHealthPull() + s.core.monitor.withLock { + assertTrue(s.core.ringHealthWindowActive, "request did not open a health window") + assertTrue(s.core.ringRoleReconnectPending, "glasses-role link was not dropped") + assertEquals(DIRECT_RING_ROLE_PHONE, s.core.effectiveRingRoleLocked()) + } + s.core.restartRingLinkForRoleChange() + assertEquals(1, s.link.disconnects) + s.core.monitor.withLock { + assertFalse(s.core.ringNotificationsReady) + assertTrue(s.core.ringReconnectAfterMs > s.core.now(), "redialed before the old link could end") + } + + // Phone-role setup: data CCCD only, then the handshake and the pull. + s.core.connectRing() + assertEquals(listOf(BleProtocol.R1_NOTIFY_CHAR_UUID), s.link.subscribed, "phone role took the legacy CCCD") + val requests = RingProtocol.HEALTH_COMMANDS.map { "req:$it" } + assertEquals(requests, s.link.writes.filter { it.startsWith("req:") }, "pull did not run") + s.core.monitor.withLock { + assertFalse(s.core.ringHealthWindowActive, "window left open after the pull") + assertTrue(s.core.ringRoleReconnectPending, "link not handed back to the glasses role") + assertTrue(s.core.lastRingHealthPullResult.startsWith("completed"), s.core.lastRingHealthPullResult) + } + // Back in the glasses role: legacy CCCD again, and no further health traffic. + s.core.restartRingLinkForRoleChange() + s.core.connectRing() + assertEquals(listOf(BleProtocol.R1_LEGACY_NOTIFY_CHAR_UUID, BleProtocol.R1_NOTIFY_CHAR_UUID), + s.link.subscribed.drop(1), "glasses role not restored") + assertEquals(requests, s.link.writes.filter { it.startsWith("req:") }, "glasses-role link pulled") + } + + @Test fun directModeWindowWaitsForAnIdleRingAndRespectsItsFloor() { + val s = directSession() + s.core.monitor.withLock { + s.core.ringHealthLastRequestedAtMs = s.core.now() - 10 * 60_000L + s.core.lastDirectRingInputAtMs = s.core.now() + } + s.core.requestRingHealthNow() + s.core.runRequestedRingHealthPull() + s.core.monitor.withLock { + assertFalse(s.core.ringHealthWindowActive, "took the ring away mid-gesture") + assertTrue(s.core.ringHealthPullRequested, "deferred request was dropped") + s.core.lastDirectRingInputAtMs = s.core.now() - 60_000L + } + s.core.runRequestedRingHealthPull() + assertTrue(s.core.monitor.withLock { s.core.ringHealthWindowActive }, "idle ring did not open a window") + + // A second request inside the floor is dropped rather than bouncing the link again. + s.core.monitor.withLock { s.core.endRingHealthWindowLocked("test") } + s.core.requestRingHealthNow() + s.core.runRequestedRingHealthPull() + s.core.monitor.withLock { + assertFalse(s.core.ringHealthWindowActive, "window floor ignored") + assertFalse(s.core.ringHealthPullRequested, "request inside the floor stayed pending") + } + } + + @Test fun directModeFirstPullWaitsForTheGlassesAndGivesUpOnAnUnreachableRing() { + val s = directSession() + s.core.monitor.withLock { + s.core.ringConnected = false + s.core.ringNotificationsReady = false + s.core.sessionReady = false + } + s.core.runRequestedRingHealthPull() + assertFalse(s.core.monitor.withLock { s.core.ringHealthWindowActive }, "opened before the glasses session") + s.core.monitor.withLock { s.core.sessionReady = true } + s.core.runRequestedRingHealthPull() + s.core.monitor.withLock { + assertTrue(s.core.ringHealthWindowActive, "no first pull this session") + // Nothing set up to drop: the next connection sets up in the phone role. + assertFalse(s.core.ringRoleReconnectPending) + s.core.ringHealthWindowDeadlineMs = s.core.now() - 1 + } + s.core.expireRingHealthWindow() + s.core.monitor.withLock { + assertFalse(s.core.ringHealthWindowActive, "window outlived its deadline") + assertEquals(DIRECT_RING_ROLE_GLASSES, s.core.effectiveRingRoleLocked()) + assertTrue(s.core.lastRingHealthPullResult.startsWith("not run"), s.core.lastRingHealthPullResult) + } + // Not retried until something asks for it. + s.core.runRequestedRingHealthPull() + assertFalse(s.core.monitor.withLock { s.core.ringHealthWindowActive }, "retried without a request") + } +} diff --git a/tests/kotlin/src/commonTest/kotlin/com/faceclaw/app/RingInputTest.kt b/tests/kotlin/src/commonTest/kotlin/com/faceclaw/app/RingInputTest.kt index 866dc018..687fd151 100644 --- a/tests/kotlin/src/commonTest/kotlin/com/faceclaw/app/RingInputTest.kt +++ b/tests/kotlin/src/commonTest/kotlin/com/faceclaw/app/RingInputTest.kt @@ -22,6 +22,34 @@ class RingInputTest { assertEquals(decoded.ringTick, native.ringTick) } + @Test fun directReportsMapLikeTheGlassesRelay() { + // Frames captured on the direct link (bae80011), 2026-10-06. + val down = assertNotNull(FaceclawRingEventDecoder.decode(hex("000961000a000013cb0000"))).event + assertEquals(BleProtocol.EVENT_RING_PRESS, down.eventType) + assertEquals(BleProtocol.EVENT_SOURCE_RING, down.eventSource) + assertEquals(10, down.ringType) + assertEquals(0xcb13L, down.ringTick) + + val tapHold = assertNotNull(FaceclawRingEventDecoder.decode(hex("0009610009020055d60200"))).event + assertEquals(BleProtocol.EVENT_SHORT_THEN_LONG_PRESS, tapHold.eventType) + assertEquals(2, tapHold.ringAux) + assertEquals(0x02d655L, tapHold.ringTick) + + val swipe = assertNotNull(FaceclawRingEventDecoder.decode(hex("0009610004350009cc0000"))).event + assertEquals(BleProtocol.EVENT_SCROLL_TOP, swipe.eventType) + assertEquals(0x35, swipe.ringAux) + assertEquals(0x00, swipe.ringSpeed) + + // Same mapping as the CFW relay for every wire type (gesture_fwd.c). + val relayed = mapOf(0 to 9, 1 to 0, 2 to 3, 4 to 1, 5 to 2, 8 to 10, 9 to 11, 10 to 14, 3 to 127, 0xff to 127) + for ((wire, sysEvent) in relayed) { + val frame = hex("0009610000abcdefcdab89").also { it[4] = wire.toByte() } + val event = assertNotNull(FaceclawRingEventDecoder.decode(frame)).event + assertEquals(sysEvent, event.eventType, "wire type $wire") + assertEquals(0x89abcdefL, event.ringTick) + } + } + @Test fun legacyAndInvalidExtensionsNeverInventATimestamp() { assertEquals(-1L, assertNotNull(G2Event.decodePayload(224, hex("08026a041a02080e"))).ringTick) for (offset in listOf(9,13,14,15,16,20)) { diff --git a/tests/tsconfig.json b/tests/tsconfig.json index 374ebdf1..5c5fd912 100644 --- a/tests/tsconfig.json +++ b/tests/tsconfig.json @@ -58,6 +58,16 @@ "../app/apps/teleprompter/script-tracker.ts", "../app/apps/nightscout/nightscout-alerts.ts", "../app/apps/nightscout/missed-bolus-detector.ts", + "../app/health/health-types.ts", + "../app/health/health-derive.ts", + "../app/health/health-store.ts", + "../app/health/health-ingest.ts", + "../app/health/health-fixtures.ts", + "../app/health/sleep-stages.ts", + "../app/health/health-chart.ts", + "../app/health/health-glance.ts", + "../app/health/health-card.ts", + "../app/health/health-phone-chart.ts", "../app/g2/brightness-curve.ts", "../app/g2/events.ts", "../app/apps/t3code/t3-rpc.ts", diff --git a/tools/health-preview.cjs b/tools/health-preview.cjs new file mode 100644 index 00000000..37c9aad2 --- /dev/null +++ b/tools/health-preview.cjs @@ -0,0 +1,389 @@ +#!/usr/bin/env node +/** + * Render every health surface to a PNG, under plain node, with no emulator. + * + * ## Why this exists + * + * The first pass at this feature verified its layout by building an Android + * AVD, booting it headless, installing the app and screenshotting it. That + * works, and it cost most of a three-hour dispatch to set up for a question - + * "does this layout look right?" - that never needed a device in the loop. + * + * Everything the health screens draw goes into a `GrayImage` through code that + * imports nothing from NativeScript: `health/health-chart.ts` (the primitives), + * `health/health-glance.ts` (the glasses pages) and + * `health/health-phone-chart.ts` (the phone bitmap). So this script calls the + * REAL drawing functions with fixture data and writes what comes back. The + * previews cannot drift from the app, because they are not a second + * implementation of it - they are the same functions the device calls. + * + * ## The one platform shim, and why it is honest + * + * `graphics/bdffont.ts` reads the bundled .bdf through + * `knownFolders.currentApp()`. That is the only NativeScript call anywhere + * under the drawing code, so it gets one stub backed by node:fs, pointed at the + * same `app/fonts/` files the device loads. The glyphs are the real glyphs. + * + * ⚠ FONT CAVEAT, worth knowing before reading a preview as gospel. The device's + * DEFAULT UI font is Roboto-Light at 14px, a TTF - and TTF rasterization on + * this project happens in Java (`TtfFont.load` bails unless `global.isAndroid`), + * so it cannot run here. Off Android the shipping code falls back to the + * Terminus bitmap faces, which is what these previews use. That is a real, + * user-selectable configuration rather than a preview-only invention, but it is + * not the default, and text will not be pixel-identical to a device screenshot. + * + * The layouts are written against `font.lineHeight` / `measureText` rather than + * fixed offsets, so what actually matters is whether they survive the font + * metric range. `--big` re-renders everything one bitmap size up (small 12px -> + * 16px, large 24px -> 32px) to check exactly that; the guaranteed small-font + * line-height band is 12..21 (see ui-fonts.ts), and 12 and 16 sit inside it. + * + * ## Use + * + * npx tsc -p tests/tsconfig.json # or: npm test + * node tools/health-preview.cjs [--out DIR] [--big] [--real DIR] + * + * ## --real: the same surfaces, on data pulled off the phone + * + * `--real DIR` reads a `sleep.jsonl` (and, if present, a `samples-*.jsonl`) + * copied out of `files/health/` under `com.faceclaw.app` and renders the sleep + * surfaces from THAT instead of from fixtures. Nothing about the drawing + * changes - it is the same `drawGlancePage` and `renderPhoneChart` - so the + * question it answers is only ever "what does the real data look like in the + * layout we already have", never "should the layout be different". + * + * A stored session written by a pre-correction build carries + * `timeResolved: false` and RAW ring seconds. Those are run back through the + * shipping `convertRecords()` with the real clock correction, so the preview + * shows what the phone will store after the fix rather than a hand-placed + * guess. A session already marked resolved is used as-is and not corrected + * twice. + */ + +const fs = require("node:fs"); +const path = require("node:path"); +const Module = require("node:module"); + +const ROOT = path.resolve(__dirname, ".."); +const APP = path.join(ROOT, "app"); +const BUILD = path.join(ROOT, ".test-build", "app"); + +// --- the one platform shim ------------------------------------------------- +const nsCoreStub = { + knownFolders: { + currentApp: () => ({ + getFile: (relative) => ({ + readTextSync: () => fs.readFileSync(path.join(APP, relative), "utf8"), + }), + }), + }, +}; +const realLoad = Module._load; +Module._load = function (request) { + if (request === "@nativescript/core") return nsCoreStub; + return realLoad.apply(this, arguments); +}; + +if (!fs.existsSync(BUILD)) { + console.error(`No ${path.relative(ROOT, BUILD)} - run: npx tsc -p tests/tsconfig.json`); + process.exit(1); +} + +const { GrayImage } = require(path.join(BUILD, "graphics/image.js")); +const { getFont } = require(path.join(BUILD, "graphics/bdffont.js")); +const { buildFixtures } = require(path.join(BUILD, "health/health-fixtures.js")); +const { + dailySummary, + hypnogram, + rollupSeries, + shortWeekday, + sleepNights, + sleepSummary, + stageSeconds, + formatDuration, +} = require(path.join(BUILD, "health/health-derive.js")); +const { drawGlancePage, GLANCE_PAGES } = require(path.join(BUILD, "health/health-glance.js")); +const { drawHealthCard } = require(path.join(BUILD, "health/health-card.js")); +const { convertRecords } = require(path.join(BUILD, "health/health-ingest.js")); +const { HealthStore } = require(path.join(BUILD, "health/health-store.js")); +const { renderPhoneChart } = require(path.join(BUILD, "health/health-phone-chart.js")); +const { stageLabel } = require(path.join(BUILD, "health/sleep-stages.js")); +const { DAY_MS, SAMPLE_METRICS, startOfLocalDay } = require(path.join(BUILD, "health/health-types.js")); +const UPNG = require("upng-js"); + +// --- arguments ------------------------------------------------------------- +const args = process.argv.slice(2); +const big = args.includes("--big"); +const realIndex = args.indexOf("--real"); +const REAL_DIR = realIndex >= 0 && args[realIndex + 1] ? path.resolve(args[realIndex + 1]) : null; +const outIndex = args.indexOf("--out"); +const OUT = path.resolve( + outIndex >= 0 && args[outIndex + 1] ? args[outIndex + 1] : path.join(ROOT, "preview"), +); +fs.mkdirSync(OUT, { recursive: true }); + +const small = getFont(big ? "terminus16" : "terminus12"); +const large = getFont(big ? "terminus32" : "terminus24"); +const fonts = { small, large }; + +// --- real data, when asked for --------------------------------------------- +/** + * `HealthStorageBackend` over a plain directory. + * + * Reading the pulled files THROUGH the real store, rather than parsing them + * here, is the same rule the rest of this tool follows. The on-disk sample line + * is a compact seven-key shape (`{m,t,s,n,x,a,u}`) that only `health-store.ts` + * knows how to read; a hand-rolled parser for it in a preview script is exactly + * the kind of second implementation that drifts. Read-only - `append`/`write` + * throw rather than quietly doing nothing, so a preview can never mutate a + * pulled copy of real data. + */ +class DirBackend { + constructor(dir) { + this.dir = dir; + } + exists(name) { + return fs.existsSync(path.join(this.dir, name)); + } + read(name) { + return this.exists(name) ? fs.readFileSync(path.join(this.dir, name), "utf8") : null; + } + append() { + throw new Error("health-preview is read-only"); + } + write() { + throw new Error("health-preview is read-only"); + } + list() { + return fs.readdirSync(this.dir); + } +} + +/** + * Put a stored session in the frame the corrected build will store it in. + * + * The correction is NOT applied here by hand - the record is turned back into + * the wire shape and pushed through the real `convertRecords()`, so if that + * function is wrong the preview is wrong in exactly the same way the phone is, + * which is the only useful behaviour for a check like this. + */ +function resolveStoredSleep(stored) { + if (stored.timeResolved) return stored; + const startTs = Math.round(stored.startMs / 1000); + const endTs = Math.round(stored.endMs / 1000); + const correction = 2 * new Date(stored.startMs).getTimezoneOffset() * 60 * 1000; + const { sleep } = convertRecords([ + { + kind: "sleep", + startTs, + endTs, + totalSec: stored.totalSec, + wakeSec: stored.wakeSec, + remSec: stored.remSec, + lightSec: stored.lightSec, + deepSec: stored.deepSec, + segments: stored.segments, + receivedAtMs: stored.startMs, + clockCorrectionMs: correction, + }, + ]); + return sleep[0]; +} + +function loadReal(dir) { + const store = new HealthStore(new DirBackend(dir)); + const sleep = store.sleepSessions().map(resolveStoredSleep); + if (sleep.length === 0) { + console.error(`No sleep sessions in ${dir}/sleep.jsonl`); + process.exit(1); + } + // Pin the clock to mid-afternoon of the most recent night's WAKE-UP day, so + // "today" is the day that night belongs to and the glance reads like a real + // one rather than an empty day. + const latest = sleep.reduce((a, b) => (b.dayStartMs > a.dayStartMs ? b : a)); + const nowMs = latest.dayStartMs + 15 * 3600 * 1000 + 20 * 60 * 1000; + // A bounded window, not (0, MAX): samplesInRange walks a shard per MONTH, so + // an open range asks it to name a few million files and it returns nothing. + // A quarter back covers every view this tool renders. + const samples = store.samplesInRange(nowMs - 120 * DAY_MS, nowMs + DAY_MS); + console.log(`real data: ${sleep.length} sleep session(s), ${samples.length} samples`); + for (const night of sleep) { + console.log( + ` night ${new Date(night.startMs).toString()}\n` + + ` -> ${new Date(night.endMs).toString()}` + + ` total ${night.totalSec}s wake ${night.wakeSec}s` + + ` timeResolved=${night.timeResolved}`, + ); + } + return { samples, sleep, nowMs }; +} + +// --- data ------------------------------------------------------------------ +// A fixed clock so a preview is reproducible and its date caption is stable. +// Mid-afternoon, so "today so far" is a partial day like a real glance. +const real = REAL_DIR ? loadReal(REAL_DIR) : null; +const NOW = real ? real.nowMs : new Date(2026, 8, 10, 15, 20, 0).getTime(); +const TODAY = startOfLocalDay(NOW); +const fixtures = real + ? { samples: real.samples, sleep: real.sleep } + : buildFixtures({ days: 95, nowMs: NOW, seed: 0x5eed }); + +const todaySamples = fixtures.samples.filter( + (sample) => sample.startMs >= TODAY && sample.startMs < TODAY + DAY_MS, +); +const summary = dailySummary(todaySamples, fixtures.sleep, TODAY); +const lastNight = fixtures.sleep.find((session) => session.dayStartMs === TODAY); + +const hourly = {}; +for (const metric of SAMPLE_METRICS) { + hourly[metric] = rollupSeries(todaySamples, { + metric, + granularity: "hour", + startMs: TODAY, + endMs: TODAY + DAY_MS, + }); +} + +const glanceData = { + summary, + hourly, + stageBands: lastNight ? hypnogram(lastNight) : [], + nowMs: NOW, + // The badge the glasses footer draws. It must follow the DATA, or a real + // render comes out stamped "Sample data" and the preview lies about the one + // thing it exists to show. + fixture: !real, +}; + +// --- PNG out --------------------------------------------------------------- +const written = []; + +function writePng(name, image) { + const baked = image.withDrawsBaked(); + const rgba = new Uint8Array(baked.width * baked.height * 4); + for (let i = 0; i < baked.pixels.length; i += 1) { + const value = baked.pixels[i]; + rgba[i * 4] = value; + rgba[i * 4 + 1] = value; + rgba[i * 4 + 2] = value; + rgba[i * 4 + 3] = 255; + } + const file = path.join(OUT, `${REAL_DIR ? "real-" : ""}${name}${big ? "-big" : ""}.png`); + fs.writeFileSync(file, Buffer.from(UPNG.encode([rgba.buffer], baked.width, baked.height, 0))); + + // A blank canvas would otherwise be a silent pass, and a page that drew + // nothing is exactly the failure a preview is supposed to catch. + let lit = 0; + for (const value of baked.pixels) if (value > 0) lit += 1; + const inkPercent = ((lit / baked.pixels.length) * 100).toFixed(1); + written.push({ name: path.basename(file), size: `${baked.width}x${baked.height}`, ink: `${inkPercent}%` }); + if (lit === 0) console.error(` !! ${file} is entirely blank`); +} + +// --- the glasses: 640x480, the G2 lens ------------------------------------ +const LENS = { width: 640, height: 480 }; +GLANCE_PAGES.forEach((page, index) => { + const name = + page.kind === "overview" ? "overview" : page.kind === "sleep" ? "sleep" : page.metric; + const image = new GrayImage(LENS.width, LENS.height, 0); + drawGlancePage(image, LENS, fonts, page, glanceData); + writePng(`glasses-${String(index + 1).padStart(2, "0")}-${name}`, image); +}); + +// --- the phone ------------------------------------------------------------- +/** + * Two widths, both real: 411dp is the Fold 7's cover screen (the compact + * layout), 750dp its inner screen (expanded). Both are the numbers the first + * pass measured on screen in the emulator, so the previews line up with the + * readout in those screenshots. The chart renders at RENDER_SCALE 2 into a box + * of (width - 32)dp, matching health-view-model.ts. + */ +const RENDER_SCALE = 2; +const PHONE_LAYOUTS = [ + { name: "narrow", widthDp: 411, chartHeightDp: 190 }, + { name: "wide", widthDp: 750, chartHeightDp: 380 }, +]; + +function phoneChart(layout, name, content) { + const image = renderPhoneChart({ + width: Math.round((layout.widthDp - 32) * RENDER_SCALE), + height: Math.round(layout.chartHeightDp * RENDER_SCALE), + font: small, + content, + }); + writePng(`phone-${layout.name}-${name}`, image); +} + +function metricContent(metric, granularity, days) { + const startMs = TODAY - (days - 1) * DAY_MS; + const points = rollupSeries(fixtures.samples, { + metric, + granularity, + startMs, + endMs: TODAY + DAY_MS, + }); + return { + kind: "metric", + metric, + points, + mode: metric === "steps" || metric === "calories" ? "bars" : "band", + xLabel: (point) => + granularity === "hour" + ? `${new Date(point.startMs).getHours()}` + : days <= 7 + ? shortWeekday(point.startMs) + : `${new Date(point.startMs).getDate()}`, + }; +} + +function nightsContent(days) { + const startMs = TODAY - (days - 1) * DAY_MS; + return { + kind: "nights", + nights: sleepNights(fixtures.sleep, startMs, TODAY + DAY_MS), + xLabel: (night) => + days <= 7 ? shortWeekday(night.startMs) : `${new Date(night.startMs).getDate()}`, + }; +} + +function lanesContent() { + const summaryOfNight = lastNight ? sleepSummary(lastNight) : null; + return { + kind: "lanes", + bands: lastNight ? hypnogram(lastNight) : [], + laneText: (stage) => ({ + label: stageLabel(stage), + value: summaryOfNight ? formatDuration(stageSeconds(stage, summaryOfNight)) : "--", + }), + }; +} + +for (const layout of PHONE_LAYOUTS) { + phoneChart(layout, "hr-day", metricContent("heartRate", "hour", 1)); + phoneChart(layout, "hr-week", metricContent("heartRate", "day", 7)); + phoneChart(layout, "spo2-day", metricContent("spo2", "hour", 1)); + phoneChart(layout, "steps-week", metricContent("steps", "day", 7)); + phoneChart(layout, "sleep-day-lanes", lanesContent()); + phoneChart(layout, "sleep-week", nightsContent(7)); + phoneChart(layout, "sleep-month", nightsContent(30)); + phoneChart(layout, "sleep-quarter", nightsContent(90)); +} + +// --- report ---------------------------------------------------------------- +for (const [name, data] of [ + ["live", { kind: "live", summary: dailySummary(fixtures.samples, fixtures.sleep, TODAY), hasSteps: true, hasCalories: true }], + ["partial", { kind: "live", summary: dailySummary([], [], TODAY), hasSteps: true, hasCalories: false }], + ["sample", { kind: "fixture" }], + ["empty", { kind: "empty" }], + ["error", { kind: "error" }], +]) { + const card = new GrayImage(288, 144, 0); + drawHealthCard(card, data, small, getFont(big ? "terminus24" : "terminus16")); + writePng(`glanceboard-health-${name}`, card); +} + +console.log(`font: small lineHeight ${small.lineHeight}, large lineHeight ${large.lineHeight}`); +console.log(`wrote ${written.length} PNGs to ${OUT}\n`); +for (const entry of written) { + console.log(` ${entry.name.padEnd(34)} ${entry.size.padEnd(10)} ink ${entry.ink}`); +} diff --git a/tools/ring-clock-audit.py b/tools/ring-clock-audit.py new file mode 100644 index 00000000..dd7d8e3c --- /dev/null +++ b/tools/ring-clock-audit.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +"""Inspect timestamps in an app-private ring-frames.jsonl export (read-only). + +Prints clock metadata, never measurement values. A latest timestamp may be old; +its age is not by itself a clock measurement. Repeated *future* HR timestamps +tracking receipt time are stronger evidence. All output instants are UTC. +""" + +import argparse +import datetime +import json +import struct + + +def utc(seconds): + return datetime.datetime.fromtimestamp(seconds, datetime.timezone.utc).isoformat() + + +def audit(record): + raw = bytes.fromhex(record["raw"]) + if len(raw) < 24 or raw[5:8] != b"\x64\x02\x64" or raw[10] != 2 or raw[12] != 1: + return None + if int.from_bytes(raw[13:15], "little") != len(raw) - 5: + return None + command = raw[11] + metric = {1: "heart_rate", 2: "spo2", 4: "hrv", 5: "steps"}.get(command) + if metric is None: + return None + payload = raw[15:] + count, offset, anchor = struct.unpack_from("