diff --git a/app/assistant/system-tools.ts b/app/assistant/system-tools.ts index 4e3f17f3..ccff0c25 100644 --- a/app/assistant/system-tools.ts +++ b/app/assistant/system-tools.ts @@ -221,6 +221,12 @@ function describeState(): string { const charging = battery.headsetCharging ? ", charging" : ""; parts.push(`Headset battery: ${battery.headset}%${charging}.`); } + if (battery.case !== null) { + // caseCharging is null while the glasses are out of the case: the level is the last one seen. + const detail = battery.caseCharging === null ? " (last reading, glasses not in the case)" + : battery.caseCharging ? ", charging" : ""; + parts.push(`Charging case battery: ${battery.case}%${detail}.`); + } parts.push(`Local time: ${formatDateTime(new Date())}.`); return parts.join(" "); } diff --git a/app/g2/dashboard-controller.ts b/app/g2/dashboard-controller.ts index f6d92f3a..d61e7b58 100644 --- a/app/g2/dashboard-controller.ts +++ b/app/g2/dashboard-controller.ts @@ -1589,9 +1589,14 @@ class DashboardController { this.emit(); }); this.offCaseBattery = communicator.onCaseState((state) => { - // Kept across disconnects: the case only reports while the glasses are + // The level is kept when a reading has none (the glasses left the case) + // and across disconnects: the case only reports while the glasses are // docked and only drains while charging them, so the last level holds. - shell.setBatteryLevels({ case: state.battery, caseCharging: state.charging }); + // Whether the case is on USB is only known while they are docked. + shell.setBatteryLevels({ + ...(state.battery !== null ? { case: state.battery } : {}), + caseCharging: state.docked ? state.charging : null, + }); this.emit(); }); this.offEvenAppConflict = communicator.onEvenAppConflict((message) => { diff --git a/app/g2/ios-preview-controller.ts b/app/g2/ios-preview-controller.ts index c10f984e..2442b87c 100644 --- a/app/g2/ios-preview-controller.ts +++ b/app/g2/ios-preview-controller.ts @@ -883,6 +883,13 @@ export class IosPreviewController { if (this.active) this.onConnectionState({ ...this.state }) this.requestShellRender() }), + communicator.onCaseState(state => { + if (this.communicator !== communicator) return + // As on Android: keep the last level when a reading has none (out of the case); + // the case's own charging is only known while the glasses are docked. + shell.setBatteryLevels({ ...(state.battery !== null ? { case: state.battery } : {}), + caseCharging: state.docked ? state.charging : null }) + }), communicator.onFirmwareInfo(info => { if (this.communicator !== communicator) return this.logBluetooth(`Firmware: L=${info.leftVersion || '?'} R=${info.rightVersion || '?'}` + diff --git a/app/native/faceclaw-communicator.ios.ts b/app/native/faceclaw-communicator.ios.ts index 638109af..edd8cd4b 100644 --- a/app/native/faceclaw-communicator.ios.ts +++ b/app/native/faceclaw-communicator.ios.ts @@ -43,7 +43,7 @@ export type HeadsetBatteryState = { }; /** See the Android communicator's CaseBatteryState. */ -export type CaseBatteryState = { battery: number; charging: boolean }; +export type CaseBatteryState = { battery: number | null; charging: boolean; docked: boolean }; export type FrameMetrics = { paintMs: number; @@ -123,8 +123,8 @@ class SessionListener extends NSObject { onBatteryStateHeadsetBatteryHeadsetChargingRingBatteryRingCharging(headsetBattery: number, headsetCharging: number, ringBattery: number, ringCharging: number): void { this.bridge.handleBatteryState(Number(headsetBattery), Number(headsetCharging), Number(ringBattery), Number(ringCharging)); } - onCaseStateCaseBatteryCaseCharging(caseBattery: number, caseCharging: number): void { - this.bridge.handleCaseState(Number(caseBattery), Number(caseCharging) === 1); + onCaseStateCaseBatteryCaseChargingCaseDocked(caseBattery: number, caseCharging: number, caseDocked: boolean): void { + this.bridge.handleCaseState(Number(caseBattery), Number(caseCharging), Boolean(caseDocked)); } onSilentModeSilent(silent: boolean): void { this.bridge.handleSilentMode(Boolean(silent)); } onWearStateWearing(wearing: boolean): void { this.bridge.handleWearState(Boolean(wearing)); } @@ -288,8 +288,12 @@ export class FaceclawCommunicatorBridge { } /** @internal */ - handleCaseState(battery: number, charging: boolean): void { - this.emitAsync(this.caseListeners, { battery, charging }); + handleCaseState(battery: number, charging: number, docked: boolean): void { + this.emitAsync(this.caseListeners, { + battery: Number.isInteger(battery) && battery >= 0 && battery <= 100 ? battery : null, + charging: charging > 0, + docked, + }); } /** @internal */ diff --git a/app/native/faceclaw-communicator.ts b/app/native/faceclaw-communicator.ts index dc94c50d..6b58f7fb 100644 --- a/app/native/faceclaw-communicator.ts +++ b/app/native/faceclaw-communicator.ts @@ -29,8 +29,12 @@ export type HeadsetBatteryState = { ringChargingStatus?: number; }; -/** The charging case's level (0..100) and whether it is itself charging, as the glasses relay it. */ -export type CaseBatteryState = { battery: number; charging: boolean }; +/** + * A charging-case reading, as the glasses relay it. battery is 0..100, or null when the reading + * has none (the glasses are out of the case). charging (the case is on USB) is only known while + * docked. + */ +export type CaseBatteryState = { battery: number | null; charging: boolean; docked: boolean }; export type FrameMetrics = { paintMs: number; @@ -216,8 +220,13 @@ export class FaceclawCommunicatorBridge { }; this.emitAsync(this.batteryListeners, state); }, - onCaseState: (caseBattery: number, caseCharging: number) => { - this.emitAsync(this.caseListeners, { battery: Number(caseBattery), charging: Number(caseCharging) === 1 }); + onCaseState: (caseBattery: number, caseCharging: number, caseDocked: boolean) => { + const battery = Number(caseBattery); + this.emitAsync(this.caseListeners, { + battery: Number.isInteger(battery) && battery >= 0 && battery <= 100 ? battery : null, + charging: Number(caseCharging) > 0, + docked: Boolean(caseDocked), + }); }, onSilentMode: (silent: boolean) => { this.emitAsync(this.silentModeListeners, Boolean(silent)); @@ -339,7 +348,10 @@ export class FaceclawCommunicatorBridge { return () => this.batteryListeners.delete(listener); } - /** Charging-case readings: read on docking, then pushed by the glasses on every change. */ + /** + * Charging-case readings: read at session start and on docking, then pushed by the glasses + * on every change, including leaving the case. + */ onCaseState(listener: (state: CaseBatteryState) => void): () => void { this.caseListeners.add(listener); return () => this.caseListeners.delete(listener); diff --git a/app/phone-ui/main-view-model.ts b/app/phone-ui/main-view-model.ts index de6dc703..57303e28 100644 --- a/app/phone-ui/main-view-model.ts +++ b/app/phone-ui/main-view-model.ts @@ -34,13 +34,17 @@ type LayoutOrientation = "portrait" | "landscape"; /** * The line under the mirror: each device whose level is known, e.g. - * "G2 100% · Case 98% ⚡ · R1 72%" (⚡ = charging). The case level is the last - * one the glasses relayed; it only reports while they are docked. + * "G2 100% · Case 98% ⚡ · R1 72%" (⚡ = charging). Levels are the last known + * ones (the case only reports while the glasses are docked), so ⚡ appears only + * while it is live: with a link to the glasses, and for the case only while + * they are docked (caseCharging is null otherwise). */ -function formatBatteryLine(levels: DashboardSnapshot["batteries"]): string { +function formatBatteryLine(snapshot: Pick): string { + const levels = snapshot.batteries; + const live = snapshot.phase === "connected" || snapshot.phase === "charging"; const devices: Array<[string, number | null, boolean | null]> = [ - ["G2", levels.headset, levels.headsetCharging], - ["Case", levels.case, levels.caseCharging], + ["G2", levels.headset, live && levels.headsetCharging], + ["Case", levels.case, live && levels.caseCharging], ["R1", levels.ring, levels.ringCharging], ]; return devices @@ -108,7 +112,7 @@ export class MainViewModel extends RemoteControlsViewModel { this.displayPreview = snapshot.displayPreview; this.displayPreviewMessage = snapshot.displayPreviewMessage; this.phase = snapshot.phase; - this.batteryLine = formatBatteryLine(snapshot.batteries); + this.batteryLine = formatBatteryLine(snapshot); this.activeTextSettingId = snapshot.activeTextSettingId; this.activeTextEditorTitle = snapshot.activeTextEditorTitle; this.activeTextSettingTitle = snapshot.activeTextSettingTitle; @@ -163,11 +167,6 @@ export class MainViewModel extends RemoteControlsViewModel { } } - /** - * Short connection indicator for the action bar. The full status string - * (which can be a sentence, e.g. a failure reason) stays available by - * tapping the indicator. - */ get batteryLine(): string { return this._batteryLine; } @@ -183,6 +182,11 @@ export class MainViewModel extends RemoteControlsViewModel { return this._batteryLine ? "visible" : "collapse"; } + /** + * Short connection indicator for the action bar. The full status string + * (which can be a sentence, e.g. a failure reason) stays available by + * tapping the indicator. + */ get connectionStatusLabel(): string { switch (this._phase) { case "connected": diff --git a/app/ui/shell/chrome-layer.ts b/app/ui/shell/chrome-layer.ts index bd8b72ef..3361a651 100644 --- a/app/ui/shell/chrome-layer.ts +++ b/app/ui/shell/chrome-layer.ts @@ -488,7 +488,9 @@ export type ShellChromeState = { watchCharging: boolean | null; /** * The glasses' charging case, last known (it only reports while the - * glasses are docked); null until it does. Shown on the phone, not here. + * glasses are docked); null until it does. caseCharging is null while the + * glasses are out of the case, where they can't see whether it is on USB. + * Shown on the phone, not here. */ case: number | null; caseCharging: boolean | null; diff --git a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/callbacks/FaceclawBleCommunicatorListener.kt b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/callbacks/FaceclawBleCommunicatorListener.kt index 54a9cd71..64185c2e 100644 --- a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/callbacks/FaceclawBleCommunicatorListener.kt +++ b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/callbacks/FaceclawBleCommunicatorListener.kt @@ -23,8 +23,12 @@ interface FaceclawBleCommunicatorListener { ringCharging: Int, ): Unit - /** A new charging-case level (0..100) or charge state; caseCharging 1 = the case is on USB. */ - fun onCaseState(caseBattery: Int, caseCharging: Int): Unit + /** + * A new charging-case reading. caseBattery is 0..100, or -1 when the reading has no level + * (the glasses are out of the case; keep the last one). caseCharging 1 = the case is on + * USB, known only while caseDocked (0 otherwise). + */ + fun onCaseState(caseBattery: Int, caseCharging: Int, caseDocked: Boolean): Unit fun onSilentMode(silent: Boolean): Unit 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 89928144..e52379ff 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 @@ -782,7 +782,8 @@ class BleProtocol { /** * The GlassesCaseInfo (field 3) of a sid-0x81 CASE_INFO reply or push, or null when there - * is none or it is empty. + * is none. Out of the case the glasses answer with an empty one, which parses as + * not docked and without a level. */ @JvmStatic fun parseCaseInfo(pb: ByteArray?): CaseInfoSnapshot? { @@ -794,9 +795,6 @@ class BleProtocol { return null } val info: ByteArray = readFieldBytes(root, 3) ?: return null - if (info.isEmpty()) { - return null - } return CaseInfoSnapshot( readVarintFieldValue(info, 1, -1), readVarintFieldValue(info, 2, 0), @@ -1508,7 +1506,7 @@ class BleProtocol { data class CaseInfoSnapshot( /** State of charge, 1..100; -1 when the message left it out. */ @JvmField val soc: Int, - /** 1 = the case itself is charging (on USB). */ + /** 1 = the case itself is charging (on USB); only 0 and 1 have been seen. */ @JvmField val chargeStatus: Int, /** 1 = lid closed, 0 = open. */ @JvmField val lidStatus: Int, @@ -1518,6 +1516,10 @@ class BleProtocol { @JvmField val errorCode: Int, ) { fun hasLevel(): Boolean = errorCode == 0 && soc in 0..100 + + fun isDocked(): Boolean = inCaseStatus > 0 + + fun isCaseCharging(): Boolean = chargeStatus > 0 } class FirmwareInfo { 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 23674fa1..91747738 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 @@ -721,18 +721,35 @@ internal fun GlassesSessionCore.emitBatteryState(headsetBattery: Int, headsetCha } } -/** Report a charging-case reading when it carries a level that differs from the last one. */ +/** + * Report a charging-case reading when it differs from the last one. Docked, a reading counts + * only once it carries a level (docking pushes {inCaseStatus=1} first and the level about 0.7 s + * later). Undocked -- the empty reply to a read, or an undock push -- it is reported even without + * a level, so the listener learns the case's charge state is no longer known. + */ internal fun GlassesSessionCore.updateCaseInfoLocked(info: BleProtocol.CaseInfoSnapshot) { - if (!info.hasLevel() || (info.soc == caseBattery && info.chargeStatus == caseCharging)) { + if (info.errorCode != 0) { return } - caseBattery = info.soc - caseCharging = info.chargeStatus + val docked = info.isDocked() + if (docked && !info.hasLevel()) { + return + } + val level = if (info.hasLevel()) info.soc else -1 + // Out of the case the glasses can't see the case's USB state. + val charging = if (docked && info.isCaseCharging()) 1 else 0 + val dockedState = if (docked) 1 else 0 + if (level == caseBattery && charging == caseCharging && dockedState == caseDocked) { + return + } + caseBattery = level + caseCharging = charging + caseDocked = dockedState logLine("charging case: $info") val current = listener ?: return host.postToMain { try { - current.onCaseState(info.soc, info.chargeStatus) + current.onCaseState(level, charging, docked) } catch (t: Throwable) { logWarn("listener onCaseState failed", t) } 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 42756b7d..2985306e 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 @@ -230,9 +230,14 @@ class GlassesSessionCore( internal var headsetCharging = -1 internal var ringBattery = -1 internal var ringCharging = -1 - // Last charging-case level and charge state reported to the listener. + // Last charging-case reading reported to the listener (-1 = none yet this + // connection). See updateCaseInfoLocked. internal var caseBattery = -1 internal var caseCharging = -1 + internal var caseDocked = -1 + // The session-start case read is still to be sent. It waits for the layout + // (see the drive loop), so a firmware that ignores it can't delay the first frame. + internal var caseInfoReadPending = false // Silent mode: 1 = on, 0 = off, -1 = not yet known. See updateSilentModeLocked. internal var silentMode = -1 internal var wearState = -1 @@ -1773,6 +1778,11 @@ class GlassesSessionCore( // reconnect; forget ours too, or the new session's first report // (the CFW query reply) is deduped away and TS never relearns it. wearState = -1 + // Same for the case: the glasses may have left it while the link + // was down, and the new session's read should reach TS either way. + caseBattery = -1 + caseCharging = -1 + caseDocked = -1 } setStateDisplay("connecting", "Connecting to the glasses...") ConnectionCounters.increment("g2.connect-attempt") @@ -1844,8 +1854,9 @@ class GlassesSessionCore( logLine("queue settings query for firmware info") // The case reports only while the glasses are docked, possibly // fully charged and so not in charging mode; out of the case - // this read comes back empty. Later changes are pushed. - pendingMessages.addLast(messageBuilder.caseInfoQuery()) + // this read comes back empty. Later changes are pushed. The + // drive loop sends it once the layout is up. + caseInfoReadPending = true } tryConnectRing("initial") } catch (t: Throwable) { 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 c3afbc12..997c911f 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 @@ -165,6 +165,14 @@ internal fun GlassesSessionCore.driveSession(): Long { enqueueFirmwareDebugFlagsLocked() } + if (messageToPrewrite == null && !shutdownRequested && fixedLayoutCreated + && caseInfoReadPending + && pendingMessages.isEmpty() && inFlightMessages.isEmpty()) { + caseInfoReadPending = false + logLine("enqueueing case info read") + pendingMessages.addLast(messageBuilder.caseInfoQuery()) + } + if (messageToPrewrite == null && !shutdownRequested && fixedLayoutCreated && (if (compassOwners.isEmpty()) 0 else 1) != compassControlLastSent && pendingMessages.isEmpty() && inFlightMessages.isEmpty()) { @@ -1099,8 +1107,9 @@ internal fun GlassesSessionCore.updateChargingModeLocked(charging: Boolean, batt if (charging) { chargingMode = true clearAllMessagesLocked("glasses charging") - // Clearing may have dropped the session-start case read; docked is - // when the case reports, so read it again. + // Docked is when the case reports. No layout is created while + // charging, so this read stands in for the session-start one. + caseInfoReadPending = false pendingMessages.addLast(messageBuilder.caseInfoQuery()) fixedLayoutCreated = false startupProbePending = false diff --git a/tests/ios-glanceboard.test.cjs b/tests/ios-glanceboard.test.cjs index d7fa25e1..ae2ab387 100644 --- a/tests/ios-glanceboard.test.cjs +++ b/tests/ios-glanceboard.test.cjs @@ -107,7 +107,7 @@ function fixture() { constructor() { super(); bridge = this; } on(kind, fn) { this.listeners[kind] = fn; return () => { if (this.listeners[kind] === fn) delete this.listeners[kind]; }; } onStateChange(fn) { return this.on('state', fn); } onRingEvent(fn) { return this.on('ring', fn); } - onWearState(fn) { return this.on('wear', fn); } onBatteryState(fn) { return this.on('battery', fn); } onFirmwareInfo() { return noop(); } + onWearState(fn) { return this.on('wear', fn); } onBatteryState(fn) { return this.on('battery', fn); } onCaseState(fn) { return this.on('case', fn); } onFirmwareInfo() { return noop(); } onFrameMetrics() { return noop(); } onPreviewAnimationFrame() { return noop(); } addCompassListener() { return noop(); } onAncsRelayFrame() { return noop(); } onAncsAuthorization() { return noop(); } setRequiresAncs() {} rightWriteLimit() { return 20; } onPhoneLockSignal() {} async writeRawToRight() {} async configureBrightness() {} async setBrightness() {} async enableWearDetectionAndRequestState() {} async playBuzzerSequence() {} async close() {} @@ -115,6 +115,7 @@ function fixture() { emitRing(input) { this.listeners.ring?.(input); } emitWear(wearing) { this.listeners.wear?.(wearing); } emitBattery(state) { this.listeners.battery?.(state); } + emitCase(state) { this.listeners.case?.(state); } async start() { this.emitState('connected', 'Connected.'); } async disconnect() { this.emitState('disconnected', 'Disconnected.'); } waitForFrameFinished() { return Promise.resolve('sent'); } @@ -268,6 +269,16 @@ test('ring battery reported through the glasses reaches the shell while connecte assert.deepEqual([f.battery.ring, f.battery.ringCharging], [null, null]); }); +test('the charging case reading reaches the shell and keeps its level once the glasses leave the case', async () => { + const f = fixture(); + await f.connect(); + f.bridge.emitCase({ battery: 64, charging: true, docked: true }); + assert.deepEqual([f.battery.case, f.battery.caseCharging], [64, true]); + // Out of the case there is no level, and whether the case is on USB is unknown. + f.bridge.emitCase({ battery: null, charging: false, docked: false }); + assert.deepEqual([f.battery.case, f.battery.caseCharging], [64, null]); +}); + test('the switcher can open the Notifications window in the background, once, with a live surface', async () => { const f = fixture(); await f.render(); diff --git a/tests/kotlin/src/commonTest/kotlin/com/faceclaw/app/GlassesSessionCoreTest.kt b/tests/kotlin/src/commonTest/kotlin/com/faceclaw/app/GlassesSessionCoreTest.kt index 46ff968d..fc236fa1 100644 --- a/tests/kotlin/src/commonTest/kotlin/com/faceclaw/app/GlassesSessionCoreTest.kt +++ b/tests/kotlin/src/commonTest/kotlin/com/faceclaw/app/GlassesSessionCoreTest.kt @@ -72,6 +72,8 @@ private class FakeLink(private val platform: ProtocolPlatform) : SessionLink { @Volatile var firmwareExtension: String? = null /** The GlassesCaseInfo body case-info queries are answered with; null answers without one. */ @Volatile var caseInfo: ByteArray? = null + /** Settings READ acks report the glasses charging in their case (80%). */ + @Volatile var headsetCharging = false @Volatile var connects = 0 var seq = 0 @@ -125,12 +127,14 @@ private class FakeLink(private val platform: ProtocolPlatform) : SessionLink { val extension = firmwareExtension val body = if (sid == BleProtocol.SID_SECURITY_AUTH) BleProtocol.encodeVarintField(1, 4) + BleProtocol.encodeVarintField(2, magic) + byteArrayOf(0x1a, 0x00) - else if (kind == "battery" && extension != null) + else if (kind == "battery" && (extension != null || headsetCharging)) BleProtocol.encodeVarintField(1, 1) + BleProtocol.encodeVarintField(2, magic) + BleProtocol.encodeBytesField(4, - BleProtocol.encodeBytesField(5, STOCK_VERSION.encodeToByteArray()) + - BleProtocol.encodeBytesField(6, STOCK_VERSION.encodeToByteArray())) + - (if (extension.isEmpty()) ByteArray(0) else BleProtocol.encodeBytesField(100, extension.encodeToByteArray())) + (if (extension == null) ByteArray(0) else + BleProtocol.encodeBytesField(5, STOCK_VERSION.encodeToByteArray()) + + BleProtocol.encodeBytesField(6, STOCK_VERSION.encodeToByteArray())) + + (if (headsetCharging) BleProtocol.encodeVarintField(12, 80) + BleProtocol.encodeVarintField(13, 1) else ByteArray(0))) + + (if (extension.isNullOrEmpty()) ByteArray(0) else BleProtocol.encodeBytesField(100, extension.encodeToByteArray())) else if (kind == "case-info") casePackage(magic, caseInfo) else @@ -256,8 +260,8 @@ private class FakeListener : FaceclawBleCommunicatorListener { val cases = ArrayList() - override fun onCaseState(caseBattery: Int, caseCharging: Int) { - cases.add("$caseBattery/$caseCharging") + override fun onCaseState(caseBattery: Int, caseCharging: Int, caseDocked: Boolean) { + cases.add("$caseBattery/$caseCharging/" + (if (caseDocked) "docked" else "out")) } override fun onSilentMode(silent: Boolean) {} @@ -722,53 +726,93 @@ class GlassesSessionCoreTest { // Through a real frame, so the trailing CRC is present as it is on the wire. fun parse(pb: ByteArray) = BleProtocol.parseCaseInfo( BleProtocol.parseFrame(BleProtocol.framePb(pb, BleProtocol.SID_GLASSES_CASE, 0x00, 3)[0]).pb) - assertEquals(BleProtocol.CaseInfoSnapshot(64, 1, 1, 1, 0), parse(casePackage(7, caseInfoBody(64, charge = 1, lid = 1, inCase = 1)))) + val full = parse(casePackage(7, caseInfoBody(64, charge = 1, lid = 1, inCase = 1)))!! + assertEquals(BleProtocol.CaseInfoSnapshot(64, 1, 1, 1, 0), full) + assertTrue(full.hasLevel() && full.isDocked() && full.isCaseCharging()) assertFalse(parse(casePackage(7, caseInfoBody(80, error = 7)))!!.hasLevel()) - // No data, an all-default body, or another command is not a reading. + // An empty caseInfo is a reading: not docked, no level. + val out = parse(casePackage(7, ByteArray(0)))!! + assertEquals(BleProtocol.CaseInfoSnapshot(-1, 0, 0, 0, 0), out) + assertFalse(out.isDocked() || out.hasLevel()) + // No caseInfo at all, or another command, is not. assertEquals(null, parse(casePackage(7, null))) - assertEquals(null, parse(casePackage(7, ByteArray(0)))) assertEquals(null, parse(BleProtocol.encodeVarintField(2, 7) + BleProtocol.encodeBytesField(3, caseInfoBody(50)))) assertEquals(null, BleProtocol.parseCaseInfo(null)) // Captured from G2 2.3.0.24 / Faceclaw/38 (CRC stripped). Out of the case the reply is empty; // docking pushes inCase alone (proto3 dropped soc: no level, not 0%), then the level. - assertEquals(null, parse(hex("08011086011a00"))) + assertEquals(out, parse(hex("08011086011a00"))) val docked = parse(hex("08011a022001"))!! assertEquals(BleProtocol.CaseInfoSnapshot(-1, 0, 0, 1, 0), docked) + assertTrue(docked.isDocked()) assertFalse(docked.hasLevel()) assertEquals(BleProtocol.CaseInfoSnapshot(88, 0, 0, 1, 0), parse(hex("080110011a0408582001"))) } @Test - fun theCaseIsReadAtSessionStartAndOnDockingThenPushesCarryIt() { + fun theCaseIsReadAfterTheLayoutAndOnDockingThenPushesCarryIt() { val s = Session() try { - // Out of the case the session-start read answers without a caseInfo. + // Out of the case the session-start read answers with an empty caseInfo, + // which reports "not docked" once. + s.link.caseInfo = ByteArray(0) s.startAndAwaitLayout() fun queries() = s.link.writes.filter { it.kind == "case-info" } assertTrue(waitUntil(5_000) { queries().size == 1 }) - assertEquals(listOf(), s.listener.cases) + assertTrue(waitUntil(5_000) { s.listener.cases.isNotEmpty() }) + assertEquals(listOf("-1/0/out"), s.listener.cases) + // It waits for the layout, so a firmware that ignores it can't delay the first frame. + assertTrue(s.link.writes.indexOf(queries()[0]) > s.link.writes.indexOfFirst { it.kind == "create-layout" }) s.link.caseInfo = caseInfoBody(64, charge = 1, inCase = 1) s.core.monitor.withLock { s.core.updateChargingModeLocked(true, 80) } s.core.interruptibleSleep.interrupt() - assertTrue(waitUntil(5_000) { s.listener.cases.isNotEmpty() }, s.host.logs().takeLast(10).toString()) - assertEquals(listOf("64/1"), s.listener.cases) + assertTrue(waitUntil(5_000) { s.listener.cases.size == 2 }, s.host.logs().takeLast(10).toString()) + assertEquals("64/1/docked", s.listener.cases.last()) assertEquals(listOf(RIGHT, RIGHT), queries().map { it.address }) // Pushes (flag 0x01, the glasses' own magic) update it without being taken for acks. fun push(info: ByteArray) = s.core.onNotification(RIGHT, BleProtocol.NOTIFY_CHAR_UUID, BleProtocol.framePb(casePackage(200, info), BleProtocol.SID_GLASSES_CASE, BleProtocol.FLAG_NOTIFY, 99)[0]) push(caseInfoBody(63, lid = 1, inCase = 1)) - assertEquals("63/0", s.listener.cases.last()) - // Unchanged level and charge, no level yet, or a failed read: nothing to report. + assertEquals("63/0/docked", s.listener.cases.last()) + // Unchanged level and charge, docked with no level yet, or a failed read: nothing to report. push(caseInfoBody(63, inCase = 1)) push(caseInfoBody(0, inCase = 1)) push(caseInfoBody(70, inCase = 1, error = 3)) - assertEquals(2, s.listener.cases.size) + assertEquals(3, s.listener.cases.size) assertFalse(s.host.hasLog("unexpected"), s.host.logs().filter { it.contains("unexpected") }.toString()) // Later charging-mode battery polls do not read the case again. s.platform.offsetMs += 2L * ConnectionOptions.CHARGING_BATTERY_POLL_MS s.core.interruptibleSleep.interrupt() sleepMs(300) assertEquals(2, queries().size) + // Leaving the case is reported even with the same level, and without one. + push(caseInfoBody(63)) + assertEquals("63/0/out", s.listener.cases.last()) + push(ByteArray(0)) + assertEquals("-1/0/out", s.listener.cases.last()) + push(ByteArray(0)) + assertEquals(5, s.listener.cases.size) + } finally { + s.core.close() + } + } + + @Test + fun glassesChargingAtConnectReadTheCaseOnce() { + val s = Session() + s.link.headsetCharging = true + s.link.caseInfo = caseInfoBody(90, charge = 1, lid = 1, inCase = 1) + try { + assertTrue(s.core.start()) + assertTrue(waitUntil(5_000) { s.listener.cases.isNotEmpty() }, s.host.logs().takeLast(10).toString()) + assertEquals(listOf("90/1/docked"), s.listener.cases) + // Charging mode skips the layout, and with it the session-start read; + // the charging-mode read is the only one. + s.platform.offsetMs += 2L * ConnectionOptions.CHARGING_BATTERY_POLL_MS + s.core.interruptibleSleep.interrupt() + sleepMs(300) + assertEquals(1, s.link.writes.count { it.kind == "case-info" }) + assertEquals(0, s.link.writes.count { it.kind == "create-layout" }) + assertFalse(s.host.hasLog("late ACK"), s.host.logs().filter { it.contains("late ACK") }.toString()) } finally { s.core.close() } diff --git a/tests/kotlin/src/iosTest/kotlin/com/faceclaw/app/IosSessionFacadeTest.kt b/tests/kotlin/src/iosTest/kotlin/com/faceclaw/app/IosSessionFacadeTest.kt index 4c9cbfe9..ad5e6867 100644 --- a/tests/kotlin/src/iosTest/kotlin/com/faceclaw/app/IosSessionFacadeTest.kt +++ b/tests/kotlin/src/iosTest/kotlin/com/faceclaw/app/IosSessionFacadeTest.kt @@ -130,7 +130,7 @@ private class MainThreadListener : FaceclawBleCommunicatorListener { if (!NSThread.isMainThread) offMainCallbacks++ } - override fun onCaseState(caseBattery: Int, caseCharging: Int) { + override fun onCaseState(caseBattery: Int, caseCharging: Int, caseDocked: Boolean) { if (!NSThread.isMainThread) offMainCallbacks++ }