Merge branch 'main' into rayneo-io-support

This commit is contained in:
James Babcock committed 2026-11-03 14:06:19 -08:00
commit b2b6c5c8d8
36 files changed
+822 -39

No files matched your search

+75
View File
@@ -0,0 +1,75 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { loader } = require('./helpers/load-typescript.cjs');
const GRANTED = 0;
const DENIED = -1;
const RECORD_AUDIO = 'android.permission.RECORD_AUDIO';
/**
* app/g2/android-permissions.ts against a stubbed Android: `granted` is the set
* of permissions already held, `activity` the foreground/start Activity. It is
* null once the app's Activity is destroyed (swiped away in Recents) while the
* foreground service keeps the process and the glasses session running:
* NativeScript then clears both foregroundActivity and startActivity.
*/
function permissions({ granted = [], activity = null } = {}) {
const held = new Set(granted);
const requests = [];
const Application = {
android: {
foregroundActivity: activity,
startActivity: activity,
activityRequestPermissionsEvent: 'activityRequestPermissions',
on() {},
off() {},
},
};
const globals = {
global: { isAndroid: true },
Array: { create: (_type, length) => new Array(length) },
android: {
content: { pm: { PackageManager: { PERMISSION_GRANTED: GRANTED } } },
os: { Build: { VERSION: { SDK_INT: 34 } } },
Manifest: { permission: { BLUETOOTH_SCAN: 'android.permission.BLUETOOTH_SCAN', BLUETOOTH_CONNECT: 'android.permission.BLUETOOTH_CONNECT' } },
},
androidx: {
core: {
content: { ContextCompat: { checkSelfPermission: (_context, permission) => (held.has(permission) ? GRANTED : DENIED) } },
app: { ActivityCompat: { requestPermissions: (requester, list, code) => requests.push({ requester, list: [...list], code }) } },
},
},
};
const load = loader(globals, {
'@nativescript/core': { Application, Utils: { android: { getApplicationContext: () => ({}) } } },
});
return { api: load('app/g2/android-permissions.ts'), requests };
}
test('a granted permission needs no Activity, so voice works after the app is swiped away', async () => {
const { api, requests } = permissions({ granted: [RECORD_AUDIO], activity: null });
await api.ensureVoicePermissions();
assert.equal(requests.length, 0);
});
test('BLE permissions that are all granted need no Activity either', async () => {
const { api } = permissions({
granted: ['android.permission.BLUETOOTH_SCAN', 'android.permission.BLUETOOTH_CONNECT', 'android.permission.POST_NOTIFICATIONS'],
activity: null,
});
await api.ensureBlePermissions();
});
test('a missing permission is requested through the Activity', async () => {
const activity = { name: 'main' };
const { api, requests } = permissions({ granted: [], activity });
void api.ensureVoicePermissions();
assert.equal(requests.length, 1);
assert.equal(requests[0].requester, activity);
assert.deepEqual(requests[0].list, [RECORD_AUDIO]);
});
test('a missing permission with no Activity still fails, since nothing can show the prompt', async () => {
const { api } = permissions({ granted: [], activity: null });
await assert.rejects(api.ensureVoicePermissions(), /No Android activity/);
});
+40 -1
View File
@@ -1,13 +1,22 @@
const test = require("node:test");
const assert = require("node:assert/strict");
const { chargingDisplayLabel, glassesDisplayAsleep, glassesDisplayLabel } = require("../.test-build/app/g2/glasses-display-state.js");
const {
chargingDisplayLabel,
chargingPreviewMessage,
formatBatteryLine,
glassesDisplayAsleep,
glassesDisplayDetail,
glassesDisplayLabel,
} = require("../.test-build/app/g2/glasses-display-state.js");
const connected = {
phase: "connected",
silentMode: false,
screenOn: true,
battery: 72,
caseBattery: null,
caseCharging: null,
foregroundTitle: "Music",
previewMode: false,
};
@@ -37,3 +46,33 @@ test("charging takes precedence and includes the last-known G2 battery", () => {
assert.equal(chargingDisplayLabel(-1), "Charging");
assert.equal(chargingDisplayLabel(101), "Charging");
});
test("while charging, the case level is the watch face's second line and joins the mirror's message", () => {
const charging = { ...connected, phase: "charging", caseBattery: 64, caseCharging: false };
assert.equal(glassesDisplayLabel(charging), "Charging · G2 72%");
assert.equal(glassesDisplayDetail(charging), "Case 64%");
assert.equal(glassesDisplayDetail({ ...charging, caseCharging: true }), "Case 64% ⚡");
assert.equal(chargingPreviewMessage(charging), "Charging · G2 72% · Case 64%");
// No case level yet: the label alone.
assert.equal(glassesDisplayDetail({ ...charging, caseBattery: null }), "");
assert.equal(chargingPreviewMessage({ ...charging, caseBattery: null, battery: null }), "Charging");
// Out of the case the level is stale, so it is not shown.
assert.equal(glassesDisplayDetail({ ...connected, caseBattery: 64 }), "");
});
const levels = {
headset: 87, headsetCharging: true, case: 64, caseCharging: true, ring: 72, ringCharging: false,
};
test("the Settings battery line lists each known level, with ⚡ only while the reading is live", () => {
assert.equal(formatBatteryLine(levels, true), "G2 87% ⚡ · Case 64% ⚡ · R1 72%");
// Without a link to the glasses their charging state and the case's are stale.
assert.equal(formatBatteryLine({ ...levels, ringCharging: true }, false), "G2 87% · Case 64% · R1 72% ⚡");
// caseCharging is null while the glasses are out of the case.
assert.equal(formatBatteryLine({ ...levels, caseCharging: null }, true), "G2 87% ⚡ · Case 64% · R1 72%");
assert.equal(formatBatteryLine({ ...levels, case: null, ring: null }, true), "G2 87% ⚡");
assert.equal(
formatBatteryLine({ headset: null, headsetCharging: null, case: null, caseCharging: null, ring: null, ringCharging: null }, true),
"",
);
});
+3
View File
@@ -218,6 +218,9 @@ test('iOS bandwidth footer toggles live, polls only in foreground and resets its
'../g2/ios-peripheral-identity': { deviceAddressError: () => 'no test devices' },
'./onboarding-state': { isPreviewOnlyMode: () => false },
'../g2/reconnect-policy': { isAutoReconnectSuppressed: () => false },
'../g2/glasses-display-state': require('../.test-build/app/g2/glasses-display-state.js'),
'../ui/shell/shell': { shell: { onBatteryLevelsChanged: () => () => {}, getBatteryLevels: () => ({
headset: null, headsetCharging: null, case: null, caseCharging: null, ring: null, ringCharging: null }) } },
};
modules['./keyboard-input-view-model'] = load('app/phone-ui/keyboard-input-view-model.ts', { require: id => modules[id] });
modules['./remote-controls-view-model'] = load('app/phone-ui/remote-controls-view-model.ts', { require: id => modules[id] });
+12 -1
View File
@@ -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();
@@ -70,6 +70,10 @@ private class FakeLink(private val platform: ProtocolPlatform) : SessionLink {
* arms ("" is stock firmware, which omits the field), or null for an ack without firmware info.
*/
@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
@@ -123,12 +127,16 @@ 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
BleProtocol.encodeVarintField(1, 1) + BleProtocol.encodeVarintField(2, magic)
return BleProtocol.framePb(body, sid, 0x00, seq++)[0]
@@ -152,6 +160,19 @@ private class FakeLink(private val platform: ProtocolPlatform) : SessionLink {
override fun recordDisplayFrameSent() {}
}
private fun hex(value: String): ByteArray = value.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
/** GlassesCaseDataPackage{commandId=CASE_INFO, magicRandom, caseInfo}; caseInfo omitted when null. */
private fun casePackage(magic: Int, caseInfo: ByteArray?): ByteArray =
BleProtocol.encodeVarintField(1, BleProtocol.GLASSES_CASE_CMD_CASE_INFO) + BleProtocol.encodeVarintField(2, magic) +
(if (caseInfo == null) ByteArray(0) else BleProtocol.encodeBytesField(3, caseInfo))
/** GlassesCaseInfo with proto3 zero-omission: soc=1, chargeStatus=2, lidStatus=3, inCaseStatus=4, errorCode=5. */
private fun caseInfoBody(soc: Int, charge: Int = 0, lid: Int = 0, inCase: Int = 0, error: Int = 0): ByteArray =
listOf(soc, charge, lid, inCase, error).withIndex()
.filter { it.value != 0 }
.fold(ByteArray(0)) { acc, field -> acc + BleProtocol.encodeVarintField(field.index + 1, field.value) }
private fun cfwAck(streamId: Int, lens: Int, size: Int, checksum: Int): ByteArray {
val packet = ByteArray(19)
packet[0] = 0xaa.toByte()
@@ -237,6 +258,12 @@ private class FakeListener : FaceclawBleCommunicatorListener {
batteries.add("$headsetBattery/$headsetCharging/$ringBattery/$ringCharging")
}
val cases = ArrayList<String>()
override fun onCaseState(caseBattery: Int, caseCharging: Int, caseDocked: Boolean) {
cases.add("$caseBattery/$caseCharging/" + (if (caseDocked) "docked" else "out"))
}
override fun onSilentMode(silent: Boolean) {}
override fun onWearState(wearing: Boolean) {}
@@ -691,4 +718,141 @@ class GlassesSessionCoreTest {
assertTrue(info("Faceclaw/1").isCompatible(0))
assertFalse(info("EVENCFW/22").isCompatible(0))
}
@Test
fun caseInfoQueryMatchesTheEvenAppAndRepliesParse() {
// commandId=CASE_INFO, magicRandom=42, empty caseInfo.
assertContentEquals(hex("0801102a1a00"), BleProtocol.buildCaseInfoQuery(42))
// 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)
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())
// 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(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(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 theCaseIsReadAfterTheLayoutAndOnDockingThenPushesCarryIt() {
val s = Session()
try {
// 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 })
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.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/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(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 dockingReadsTheBatteryEvenWithTheDisplaySuspended() {
val s = Session()
s.link.caseInfo = ByteArray(0)
try {
s.startAndAwaitLayout()
assertTrue(waitUntil(5_000) { s.listener.cases == listOf("-1/0/out") }, s.listener.cases.toString())
// Off the face the display is suspended, which stops the regular battery poll.
s.core.monitor.withLock { s.core.shutdownRequested = true }
fun batteryQueries() = s.link.writes.count { it.kind == "battery" }
val before = batteryQueries()
val wait = ConnectionOptions.DOCKED_BATTERY_CHECK_DELAY_MS + 1_000L
s.platform.offsetMs += wait
s.core.interruptibleSleep.interrupt()
sleepMs(300)
assertEquals(before, batteryQueries())
// Docking: the case push schedules a battery read a few seconds later.
s.core.onNotification(RIGHT, BleProtocol.NOTIFY_CHAR_UUID, BleProtocol.framePb(
casePackage(200, caseInfoBody(98, inCase = 1)), BleProtocol.SID_GLASSES_CASE, BleProtocol.FLAG_NOTIFY, 99)[0])
assertEquals("98/0/docked", s.listener.cases.last())
s.core.interruptibleSleep.interrupt()
sleepMs(300)
assertEquals(before, batteryQueries(), "not before the delay")
s.platform.offsetMs += wait
s.core.interruptibleSleep.interrupt()
assertTrue(waitUntil(5_000) { batteryQueries() == before + 1 }, s.host.logs().takeLast(10).toString())
// It reads once; the docking push is not repeated for later level changes.
s.core.onNotification(RIGHT, BleProtocol.NOTIFY_CHAR_UUID, BleProtocol.framePb(
casePackage(201, caseInfoBody(97, inCase = 1)), BleProtocol.SID_GLASSES_CASE, BleProtocol.FLAG_NOTIFY, 100)[0])
s.platform.offsetMs += wait
s.core.interruptibleSleep.interrupt()
sleepMs(300)
assertEquals(before + 1, batteryQueries())
} 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()
}
}
}
@@ -130,6 +130,10 @@ private class MainThreadListener : FaceclawBleCommunicatorListener {
if (!NSThread.isMainThread) offMainCallbacks++
}
override fun onCaseState(caseBattery: Int, caseCharging: Int, caseDocked: Boolean) {
if (!NSThread.isMainThread) offMainCallbacks++
}
override fun onSilentMode(silent: Boolean) {}
override fun onWearState(wearing: Boolean) {}