Case battery: stop showing stale charging; read after the layout

Review fixes for the charging-case battery:

- The case reports whether the glasses are docked. An empty caseInfo
  (the reply out of the case) now parses as "not docked, no level"
  instead of nothing, and undocking is reported even when the level and
  charge state are unchanged. TS keeps the last level but clears
  caseCharging while the glasses are out of the case.
- The phone line shows the charging mark only while it is live: G2 and
  Case only with a link to the glasses (connected or charging), and Case
  only while docked. Levels stay as the last known ones.
- The session-start case read waits until the layout is up, so a
  firmware that ignored it could no longer hold up the first frame. When
  the glasses are already charging at connect, the charging-mode read is
  the only one; the old duplicate read and its "late ACK" log are gone.
- Case dedup state resets on every connect, as wearState does, so each
  session's read reaches TS.
- caseCharging uses > 0 like the headset, and is normalized to 0/1.
- iOS now feeds the reading into the shell battery state, and the
  assistant's describeState includes the case level.
- The batteryLine accessors move above connectionStatusLabel's doc
  comment.
This commit is contained in:
Om Alve committed 2026-11-02 12:01:12 +05:30
1 parent 9c0535014a
commit fa7f33bfe8
15 files changed
+199 -61

No files matched your search

+6
View File
@@ -221,6 +221,12 @@ function describeState(): string {
const charging = battery.headsetCharging ? ", charging" : ""; const charging = battery.headsetCharging ? ", charging" : "";
parts.push(`Headset battery: ${battery.headset}%${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())}.`); parts.push(`Local time: ${formatDateTime(new Date())}.`);
return parts.join(" "); return parts.join(" ");
} }
+7 -2
View File
@@ -1589,9 +1589,14 @@ class DashboardController {
this.emit(); this.emit();
}); });
this.offCaseBattery = communicator.onCaseState((state) => { 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. // 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.emit();
}); });
this.offEvenAppConflict = communicator.onEvenAppConflict((message) => { this.offEvenAppConflict = communicator.onEvenAppConflict((message) => {
+7
View File
@@ -883,6 +883,13 @@ export class IosPreviewController {
if (this.active) this.onConnectionState({ ...this.state }) if (this.active) this.onConnectionState({ ...this.state })
this.requestShellRender() 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 => { communicator.onFirmwareInfo(info => {
if (this.communicator !== communicator) return if (this.communicator !== communicator) return
this.logBluetooth(`Firmware: L=${info.leftVersion || '?'} R=${info.rightVersion || '?'}` + this.logBluetooth(`Firmware: L=${info.leftVersion || '?'} R=${info.rightVersion || '?'}` +
+9 -5
View File
@@ -43,7 +43,7 @@ export type HeadsetBatteryState = {
}; };
/** See the Android communicator's CaseBatteryState. */ /** 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 = { export type FrameMetrics = {
paintMs: number; paintMs: number;
@@ -123,8 +123,8 @@ class SessionListener extends NSObject {
onBatteryStateHeadsetBatteryHeadsetChargingRingBatteryRingCharging(headsetBattery: number, headsetCharging: number, ringBattery: number, ringCharging: number): void { onBatteryStateHeadsetBatteryHeadsetChargingRingBatteryRingCharging(headsetBattery: number, headsetCharging: number, ringBattery: number, ringCharging: number): void {
this.bridge.handleBatteryState(Number(headsetBattery), Number(headsetCharging), Number(ringBattery), Number(ringCharging)); this.bridge.handleBatteryState(Number(headsetBattery), Number(headsetCharging), Number(ringBattery), Number(ringCharging));
} }
onCaseStateCaseBatteryCaseCharging(caseBattery: number, caseCharging: number): void { onCaseStateCaseBatteryCaseChargingCaseDocked(caseBattery: number, caseCharging: number, caseDocked: boolean): void {
this.bridge.handleCaseState(Number(caseBattery), Number(caseCharging) === 1); this.bridge.handleCaseState(Number(caseBattery), Number(caseCharging), Boolean(caseDocked));
} }
onSilentModeSilent(silent: boolean): void { this.bridge.handleSilentMode(Boolean(silent)); } onSilentModeSilent(silent: boolean): void { this.bridge.handleSilentMode(Boolean(silent)); }
onWearStateWearing(wearing: boolean): void { this.bridge.handleWearState(Boolean(wearing)); } onWearStateWearing(wearing: boolean): void { this.bridge.handleWearState(Boolean(wearing)); }
@@ -288,8 +288,12 @@ export class FaceclawCommunicatorBridge {
} }
/** @internal */ /** @internal */
handleCaseState(battery: number, charging: boolean): void { handleCaseState(battery: number, charging: number, docked: boolean): void {
this.emitAsync(this.caseListeners, { battery, charging }); this.emitAsync(this.caseListeners, {
battery: Number.isInteger(battery) && battery >= 0 && battery <= 100 ? battery : null,
charging: charging > 0,
docked,
});
} }
/** @internal */ /** @internal */
+17 -5
View File
@@ -29,8 +29,12 @@ export type HeadsetBatteryState = {
ringChargingStatus?: number; 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 = { export type FrameMetrics = {
paintMs: number; paintMs: number;
@@ -216,8 +220,13 @@ export class FaceclawCommunicatorBridge {
}; };
this.emitAsync(this.batteryListeners, state); this.emitAsync(this.batteryListeners, state);
}, },
onCaseState: (caseBattery: number, caseCharging: number) => { onCaseState: (caseBattery: number, caseCharging: number, caseDocked: boolean) => {
this.emitAsync(this.caseListeners, { battery: Number(caseBattery), charging: Number(caseCharging) === 1 }); 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) => { onSilentMode: (silent: boolean) => {
this.emitAsync(this.silentModeListeners, Boolean(silent)); this.emitAsync(this.silentModeListeners, Boolean(silent));
@@ -339,7 +348,10 @@ export class FaceclawCommunicatorBridge {
return () => this.batteryListeners.delete(listener); 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 { onCaseState(listener: (state: CaseBatteryState) => void): () => void {
this.caseListeners.add(listener); this.caseListeners.add(listener);
return () => this.caseListeners.delete(listener); return () => this.caseListeners.delete(listener);
+15 -11
View File
@@ -34,13 +34,17 @@ type LayoutOrientation = "portrait" | "landscape";
/** /**
* The line under the mirror: each device whose level is known, e.g. * 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 * "G2 100% · Case 98% ⚡ · R1 72%" (⚡ = charging). Levels are the last known
* one the glasses relayed; it only reports while they are docked. * 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<DashboardSnapshot, "batteries" | "phase">): string {
const levels = snapshot.batteries;
const live = snapshot.phase === "connected" || snapshot.phase === "charging";
const devices: Array<[string, number | null, boolean | null]> = [ const devices: Array<[string, number | null, boolean | null]> = [
["G2", levels.headset, levels.headsetCharging], ["G2", levels.headset, live && levels.headsetCharging],
["Case", levels.case, levels.caseCharging], ["Case", levels.case, live && levels.caseCharging],
["R1", levels.ring, levels.ringCharging], ["R1", levels.ring, levels.ringCharging],
]; ];
return devices return devices
@@ -108,7 +112,7 @@ export class MainViewModel extends RemoteControlsViewModel {
this.displayPreview = snapshot.displayPreview; this.displayPreview = snapshot.displayPreview;
this.displayPreviewMessage = snapshot.displayPreviewMessage; this.displayPreviewMessage = snapshot.displayPreviewMessage;
this.phase = snapshot.phase; this.phase = snapshot.phase;
this.batteryLine = formatBatteryLine(snapshot.batteries); this.batteryLine = formatBatteryLine(snapshot);
this.activeTextSettingId = snapshot.activeTextSettingId; this.activeTextSettingId = snapshot.activeTextSettingId;
this.activeTextEditorTitle = snapshot.activeTextEditorTitle; this.activeTextEditorTitle = snapshot.activeTextEditorTitle;
this.activeTextSettingTitle = snapshot.activeTextSettingTitle; 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 { get batteryLine(): string {
return this._batteryLine; return this._batteryLine;
} }
@@ -183,6 +182,11 @@ export class MainViewModel extends RemoteControlsViewModel {
return this._batteryLine ? "visible" : "collapse"; 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 { get connectionStatusLabel(): string {
switch (this._phase) { switch (this._phase) {
case "connected": case "connected":
+3 -1
View File
@@ -488,7 +488,9 @@ export type ShellChromeState = {
watchCharging: boolean | null; watchCharging: boolean | null;
/** /**
* The glasses' charging case, last known (it only reports while the * 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; case: number | null;
caseCharging: boolean | null; caseCharging: boolean | null;
@@ -23,8 +23,12 @@ interface FaceclawBleCommunicatorListener {
ringCharging: Int, ringCharging: Int,
): Unit ): 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 fun onSilentMode(silent: Boolean): Unit
@@ -782,7 +782,8 @@ class BleProtocol {
/** /**
* The GlassesCaseInfo (field 3) of a sid-0x81 CASE_INFO reply or push, or null when there * 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 @JvmStatic
fun parseCaseInfo(pb: ByteArray?): CaseInfoSnapshot? { fun parseCaseInfo(pb: ByteArray?): CaseInfoSnapshot? {
@@ -794,9 +795,6 @@ class BleProtocol {
return null return null
} }
val info: ByteArray = readFieldBytes(root, 3) ?: return null val info: ByteArray = readFieldBytes(root, 3) ?: return null
if (info.isEmpty()) {
return null
}
return CaseInfoSnapshot( return CaseInfoSnapshot(
readVarintFieldValue(info, 1, -1), readVarintFieldValue(info, 1, -1),
readVarintFieldValue(info, 2, 0), readVarintFieldValue(info, 2, 0),
@@ -1508,7 +1506,7 @@ class BleProtocol {
data class CaseInfoSnapshot( data class CaseInfoSnapshot(
/** State of charge, 1..100; -1 when the message left it out. */ /** State of charge, 1..100; -1 when the message left it out. */
@JvmField val soc: Int, @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, @JvmField val chargeStatus: Int,
/** 1 = lid closed, 0 = open. */ /** 1 = lid closed, 0 = open. */
@JvmField val lidStatus: Int, @JvmField val lidStatus: Int,
@@ -1518,6 +1516,10 @@ class BleProtocol {
@JvmField val errorCode: Int, @JvmField val errorCode: Int,
) { ) {
fun hasLevel(): Boolean = errorCode == 0 && soc in 0..100 fun hasLevel(): Boolean = errorCode == 0 && soc in 0..100
fun isDocked(): Boolean = inCaseStatus > 0
fun isCaseCharging(): Boolean = chargeStatus > 0
} }
class FirmwareInfo { class FirmwareInfo {
@@ -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) { internal fun GlassesSessionCore.updateCaseInfoLocked(info: BleProtocol.CaseInfoSnapshot) {
if (!info.hasLevel() || (info.soc == caseBattery && info.chargeStatus == caseCharging)) { if (info.errorCode != 0) {
return return
} }
caseBattery = info.soc val docked = info.isDocked()
caseCharging = info.chargeStatus 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") logLine("charging case: $info")
val current = listener ?: return val current = listener ?: return
host.postToMain { host.postToMain {
try { try {
current.onCaseState(info.soc, info.chargeStatus) current.onCaseState(level, charging, docked)
} catch (t: Throwable) { } catch (t: Throwable) {
logWarn("listener onCaseState failed", t) logWarn("listener onCaseState failed", t)
} }
@@ -230,9 +230,14 @@ class GlassesSessionCore(
internal var headsetCharging = -1 internal var headsetCharging = -1
internal var ringBattery = -1 internal var ringBattery = -1
internal var ringCharging = -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 caseBattery = -1
internal var caseCharging = -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. // Silent mode: 1 = on, 0 = off, -1 = not yet known. See updateSilentModeLocked.
internal var silentMode = -1 internal var silentMode = -1
internal var wearState = -1 internal var wearState = -1
@@ -1773,6 +1778,11 @@ class GlassesSessionCore(
// reconnect; forget ours too, or the new session's first report // reconnect; forget ours too, or the new session's first report
// (the CFW query reply) is deduped away and TS never relearns it. // (the CFW query reply) is deduped away and TS never relearns it.
wearState = -1 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...") setStateDisplay("connecting", "Connecting to the glasses...")
ConnectionCounters.increment("g2.connect-attempt") ConnectionCounters.increment("g2.connect-attempt")
@@ -1844,8 +1854,9 @@ class GlassesSessionCore(
logLine("queue settings query for firmware info") logLine("queue settings query for firmware info")
// The case reports only while the glasses are docked, possibly // The case reports only while the glasses are docked, possibly
// fully charged and so not in charging mode; out of the case // fully charged and so not in charging mode; out of the case
// this read comes back empty. Later changes are pushed. // this read comes back empty. Later changes are pushed. The
pendingMessages.addLast(messageBuilder.caseInfoQuery()) // drive loop sends it once the layout is up.
caseInfoReadPending = true
} }
tryConnectRing("initial") tryConnectRing("initial")
} catch (t: Throwable) { } catch (t: Throwable) {
@@ -165,6 +165,14 @@ internal fun GlassesSessionCore.driveSession(): Long {
enqueueFirmwareDebugFlagsLocked() 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 (messageToPrewrite == null && !shutdownRequested && fixedLayoutCreated
&& (if (compassOwners.isEmpty()) 0 else 1) != compassControlLastSent && (if (compassOwners.isEmpty()) 0 else 1) != compassControlLastSent
&& pendingMessages.isEmpty() && inFlightMessages.isEmpty()) { && pendingMessages.isEmpty() && inFlightMessages.isEmpty()) {
@@ -1099,8 +1107,9 @@ internal fun GlassesSessionCore.updateChargingModeLocked(charging: Boolean, batt
if (charging) { if (charging) {
chargingMode = true chargingMode = true
clearAllMessagesLocked("glasses charging") clearAllMessagesLocked("glasses charging")
// Clearing may have dropped the session-start case read; docked is // Docked is when the case reports. No layout is created while
// when the case reports, so read it again. // charging, so this read stands in for the session-start one.
caseInfoReadPending = false
pendingMessages.addLast(messageBuilder.caseInfoQuery()) pendingMessages.addLast(messageBuilder.caseInfoQuery())
fixedLayoutCreated = false fixedLayoutCreated = false
startupProbePending = false startupProbePending = false
+12 -1
View File
@@ -107,7 +107,7 @@ function fixture() {
constructor() { super(); bridge = this; } constructor() { super(); bridge = this; }
on(kind, fn) { this.listeners[kind] = fn; return () => { if (this.listeners[kind] === fn) delete this.listeners[kind]; }; } 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); } 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(); } onFrameMetrics() { return noop(); } onPreviewAnimationFrame() { return noop(); } addCompassListener() { return noop(); } onAncsRelayFrame() { return noop(); }
onAncsAuthorization() { return noop(); } setRequiresAncs() {} rightWriteLimit() { return 20; } onPhoneLockSignal() {} onAncsAuthorization() { return noop(); } setRequiresAncs() {} rightWriteLimit() { return 20; } onPhoneLockSignal() {}
async writeRawToRight() {} async configureBrightness() {} async setBrightness() {} async enableWearDetectionAndRequestState() {} async playBuzzerSequence() {} async close() {} async writeRawToRight() {} async configureBrightness() {} async setBrightness() {} async enableWearDetectionAndRequestState() {} async playBuzzerSequence() {} async close() {}
@@ -115,6 +115,7 @@ function fixture() {
emitRing(input) { this.listeners.ring?.(input); } emitRing(input) { this.listeners.ring?.(input); }
emitWear(wearing) { this.listeners.wear?.(wearing); } emitWear(wearing) { this.listeners.wear?.(wearing); }
emitBattery(state) { this.listeners.battery?.(state); } emitBattery(state) { this.listeners.battery?.(state); }
emitCase(state) { this.listeners.case?.(state); }
async start() { this.emitState('connected', 'Connected.'); } async start() { this.emitState('connected', 'Connected.'); }
async disconnect() { this.emitState('disconnected', 'Disconnected.'); } async disconnect() { this.emitState('disconnected', 'Disconnected.'); }
waitForFrameFinished() { return Promise.resolve('sent'); } 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]); 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 () => { test('the switcher can open the Notifications window in the background, once, with a live surface', async () => {
const f = fixture(); const f = fixture();
await f.render(); await f.render();
@@ -72,6 +72,8 @@ private class FakeLink(private val platform: ProtocolPlatform) : SessionLink {
@Volatile var firmwareExtension: String? = null @Volatile var firmwareExtension: String? = null
/** The GlassesCaseInfo body case-info queries are answered with; null answers without one. */ /** The GlassesCaseInfo body case-info queries are answered with; null answers without one. */
@Volatile var caseInfo: ByteArray? = null @Volatile var caseInfo: ByteArray? = null
/** Settings READ acks report the glasses charging in their case (80%). */
@Volatile var headsetCharging = false
@Volatile var connects = 0 @Volatile var connects = 0
var seq = 0 var seq = 0
@@ -125,12 +127,14 @@ private class FakeLink(private val platform: ProtocolPlatform) : SessionLink {
val extension = firmwareExtension val extension = firmwareExtension
val body = if (sid == BleProtocol.SID_SECURITY_AUTH) val body = if (sid == BleProtocol.SID_SECURITY_AUTH)
BleProtocol.encodeVarintField(1, 4) + BleProtocol.encodeVarintField(2, magic) + byteArrayOf(0x1a, 0x00) 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.encodeVarintField(1, 1) + BleProtocol.encodeVarintField(2, magic) +
BleProtocol.encodeBytesField(4, BleProtocol.encodeBytesField(4,
BleProtocol.encodeBytesField(5, STOCK_VERSION.encodeToByteArray()) + (if (extension == null) ByteArray(0) else
BleProtocol.encodeBytesField(6, STOCK_VERSION.encodeToByteArray())) + BleProtocol.encodeBytesField(5, STOCK_VERSION.encodeToByteArray()) +
(if (extension.isEmpty()) ByteArray(0) else BleProtocol.encodeBytesField(100, extension.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") else if (kind == "case-info")
casePackage(magic, caseInfo) casePackage(magic, caseInfo)
else else
@@ -256,8 +260,8 @@ private class FakeListener : FaceclawBleCommunicatorListener {
val cases = ArrayList<String>() val cases = ArrayList<String>()
override fun onCaseState(caseBattery: Int, caseCharging: Int) { override fun onCaseState(caseBattery: Int, caseCharging: Int, caseDocked: Boolean) {
cases.add("$caseBattery/$caseCharging") cases.add("$caseBattery/$caseCharging/" + (if (caseDocked) "docked" else "out"))
} }
override fun onSilentMode(silent: Boolean) {} 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. // Through a real frame, so the trailing CRC is present as it is on the wire.
fun parse(pb: ByteArray) = BleProtocol.parseCaseInfo( fun parse(pb: ByteArray) = BleProtocol.parseCaseInfo(
BleProtocol.parseFrame(BleProtocol.framePb(pb, BleProtocol.SID_GLASSES_CASE, 0x00, 3)[0]).pb) 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()) 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, null)))
assertEquals(null, parse(casePackage(7, ByteArray(0))))
assertEquals(null, parse(BleProtocol.encodeVarintField(2, 7) + BleProtocol.encodeBytesField(3, caseInfoBody(50)))) assertEquals(null, parse(BleProtocol.encodeVarintField(2, 7) + BleProtocol.encodeBytesField(3, caseInfoBody(50))))
assertEquals(null, BleProtocol.parseCaseInfo(null)) assertEquals(null, BleProtocol.parseCaseInfo(null))
// Captured from G2 2.3.0.24 / Faceclaw/38 (CRC stripped). Out of the case the reply is empty; // 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. // 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"))!! val docked = parse(hex("08011a022001"))!!
assertEquals(BleProtocol.CaseInfoSnapshot(-1, 0, 0, 1, 0), docked) assertEquals(BleProtocol.CaseInfoSnapshot(-1, 0, 0, 1, 0), docked)
assertTrue(docked.isDocked())
assertFalse(docked.hasLevel()) assertFalse(docked.hasLevel())
assertEquals(BleProtocol.CaseInfoSnapshot(88, 0, 0, 1, 0), parse(hex("080110011a0408582001"))) assertEquals(BleProtocol.CaseInfoSnapshot(88, 0, 0, 1, 0), parse(hex("080110011a0408582001")))
} }
@Test @Test
fun theCaseIsReadAtSessionStartAndOnDockingThenPushesCarryIt() { fun theCaseIsReadAfterTheLayoutAndOnDockingThenPushesCarryIt() {
val s = Session() val s = Session()
try { 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() s.startAndAwaitLayout()
fun queries() = s.link.writes.filter { it.kind == "case-info" } fun queries() = s.link.writes.filter { it.kind == "case-info" }
assertTrue(waitUntil(5_000) { queries().size == 1 }) assertTrue(waitUntil(5_000) { queries().size == 1 })
assertEquals(listOf<String>(), 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.link.caseInfo = caseInfoBody(64, charge = 1, inCase = 1)
s.core.monitor.withLock { s.core.updateChargingModeLocked(true, 80) } s.core.monitor.withLock { s.core.updateChargingModeLocked(true, 80) }
s.core.interruptibleSleep.interrupt() s.core.interruptibleSleep.interrupt()
assertTrue(waitUntil(5_000) { s.listener.cases.isNotEmpty() }, s.host.logs().takeLast(10).toString()) assertTrue(waitUntil(5_000) { s.listener.cases.size == 2 }, s.host.logs().takeLast(10).toString())
assertEquals(listOf("64/1"), s.listener.cases) assertEquals("64/1/docked", s.listener.cases.last())
assertEquals(listOf(RIGHT, RIGHT), queries().map { it.address }) assertEquals(listOf(RIGHT, RIGHT), queries().map { it.address })
// Pushes (flag 0x01, the glasses' own magic) update it without being taken for acks. // 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, 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]) BleProtocol.framePb(casePackage(200, info), BleProtocol.SID_GLASSES_CASE, BleProtocol.FLAG_NOTIFY, 99)[0])
push(caseInfoBody(63, lid = 1, inCase = 1)) push(caseInfoBody(63, lid = 1, inCase = 1))
assertEquals("63/0", s.listener.cases.last()) assertEquals("63/0/docked", s.listener.cases.last())
// Unchanged level and charge, no level yet, or a failed read: nothing to report. // Unchanged level and charge, docked with no level yet, or a failed read: nothing to report.
push(caseInfoBody(63, inCase = 1)) push(caseInfoBody(63, inCase = 1))
push(caseInfoBody(0, inCase = 1)) push(caseInfoBody(0, inCase = 1))
push(caseInfoBody(70, inCase = 1, error = 3)) 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()) assertFalse(s.host.hasLog("unexpected"), s.host.logs().filter { it.contains("unexpected") }.toString())
// Later charging-mode battery polls do not read the case again. // Later charging-mode battery polls do not read the case again.
s.platform.offsetMs += 2L * ConnectionOptions.CHARGING_BATTERY_POLL_MS s.platform.offsetMs += 2L * ConnectionOptions.CHARGING_BATTERY_POLL_MS
s.core.interruptibleSleep.interrupt() s.core.interruptibleSleep.interrupt()
sleepMs(300) sleepMs(300)
assertEquals(2, queries().size) 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 { } finally {
s.core.close() s.core.close()
} }
@@ -130,7 +130,7 @@ private class MainThreadListener : FaceclawBleCommunicatorListener {
if (!NSThread.isMainThread) offMainCallbacks++ if (!NSThread.isMainThread) offMainCallbacks++
} }
override fun onCaseState(caseBattery: Int, caseCharging: Int) { override fun onCaseState(caseBattery: Int, caseCharging: Int, caseDocked: Boolean) {
if (!NSThread.isMainThread) offMainCallbacks++ if (!NSThread.isMainThread) offMainCallbacks++
} }