Port Compass to iOS

This commit is contained in:
James Babcock committed 2026-09-18 23:30:07 -07:00
1 parent 5ae2c245c6
commit 2b3e068a23
32 files changed
+490 -56

No files matched your search

+1 -1
View File
@@ -59,7 +59,7 @@ function compass(width = 576, height = 260) {
createInProcessWindow: (options) => { window = options; return { requestRender: () => ++renders }; },
},
'../../ui/shell/shell': { shell: { isWindowVisible: () => true } },
'../../g2/android-permissions': { hasLocationPermission: () => false },
'../../native/location-permissions': { hasLocationPermission: () => false },
'./calibration': calibration,
'./calibration-layer': {}, './declination': { onDeclinationChanged: () => () => {} },
'./heading': { getNorthReference: () => 'magnetic', resolveHeading: (v) => ({ displayDegrees: v }) },
+1 -1
View File
@@ -58,7 +58,7 @@ function compass({ style, width = 576, height = 260 } = {}) {
createInProcessWindow: (options) => { window = options; return { requestRender: () => renders++ }; },
},
'../../ui/shell/shell': { shell: { isWindowVisible: () => true } },
'../../g2/android-permissions': { hasLocationPermission: () => false },
'../../native/location-permissions': { hasLocationPermission: () => false },
'./calibration': { isCompassCalibrated: () => true, normalizeHeading: (n) => ((n % 360) + 360) % 360 },
'./calibration-layer': {},
'./compass-rose': load('app/apps/compass/compass-rose.ts', {
+1 -1
View File
@@ -43,7 +43,7 @@ const compass = load('app/apps/compass/compass-app.ts', {
'../../ui/shell/geometry': { screenCenterInViewportX: () => viewportWidth - 320 },
'../../ui/shell/in-process-window': {},
'../../ui/shell/shell': {},
'../../g2/android-permissions': {},
'../../native/location-permissions': {},
'./calibration': calibration,
'./calibration-layer': {},
'./compass-rose': rose,
+2
View File
@@ -89,6 +89,7 @@ test('background glasses input still composites frames; phone resume preserves t
}
const settings = { onAnySettingChanged: () => () => {}, previewColorSetting: { get: () => 'white' } };
const modules = {
'../native/compass.ios': { bindCompassSession() {}, receiveCompassEvent() {} },
'@nativescript/core': { File: { fromPath: () => ({ writeTextSync() {} }) }, knownFolders: { documents: () => ({ path: '/tmp' }) }, path },
'../native/ios-voice-input': { iosVoiceInput: { handleSessionEnded() {} } },
'../native/ios-bluetooth': { iosBluetooth: () => ({}) }, './glasses-session': { GlassesSession: Session },
@@ -156,6 +157,7 @@ test('iOS bandwidth footer toggles live, polls only in foreground and resets its
on: (key, fn) => appEvents.set(key, fn), off: key => appEvents.delete(key) },
Button: View, Color: class {}, Dialogs: {}, GridLayout: View, Image: View, Label: View, Page: View, StackLayout: View };
const modules = {
'../native/compass.ios': { bindCompassSession() {}, receiveCompassEvent() {} },
'@nativescript/core': core,
'../apps/all-apps': { ALL_APPS: [] },
'../g2/ios-preview-controller': { IosPreviewController: class { resume() {} pause() {} } },
+49 -5
View File
@@ -159,10 +159,10 @@ async function until(predicate) {
assert.fail('Timed out waiting for test state');
}
function harness(t, transport = new FakeTransport()) {
const states = [], input = [];
const session = new GlassesSession(transport, state => states.push(state), event => input.push(event));
const states = [], input = [], compass = [];
const session = new GlassesSession(transport, state => states.push(state), event => input.push(event), undefined, undefined, event => compass.push(event));
t.after(async () => { transport.hold = false; await session.stop(); });
return { transport, session, states, input };
return { transport, session, states, input, compass };
}
test('session authenticates both arms, checks firmware and sends acknowledged display data to L', async t => {
const h = harness(t); await h.session.start({ ...addresses, ring: 'AA:BB:CC:DD:EE:03' });
@@ -171,7 +171,7 @@ test('session authenticates both arms, checks firmware and sends acknowledged di
assert.equal(h.session.state.charging, false);
assert.deepEqual(h.transport.sent.filter(s => s.message.sid === 128).map(s => s.id).sort(), ['L', 'R']);
h.session.setFrame(new Uint8Array(640 * 480)); await until(() => h.session.state.frames === 1);
const image = h.transport.sent.find(s => s.message.sid === p.SID.cfw);
const image = h.transport.sent.find(s => s.message.sid === p.SID.cfw && s.message.payload[0] === 6);
assert.equal(image.id, 'L');
assert.equal(image.message.payload[0], 6);
const layout = h.transport.sent.find(s => s.message.sid === p.SID.hub && s.message.command === 0);
@@ -293,7 +293,7 @@ test('release while microphone enable awaits ACK sends disable last and rejects
assert.equal(p.readInteger(p.readBytes(mic.at(-1).message.payload, 18), 1), 0);
});
const imageMessages = transport => transport.sent.filter(s => s.message.sid === p.SID.cfw && s.message.payload[0] !== 11);
const imageMessages = transport => transport.sent.filter(s => s.message.sid === p.SID.cfw && ![10, 11].includes(s.message.payload[0]));
const imageBody = sent => sent.message.payload;
const ack = (transport, sent, overrides) => transport.ack(sent.id, sent.message, overrides);
const tick = () => new Promise(resolve => setImmediate(resolve));
@@ -467,3 +467,47 @@ test('delta ids skip reserved values and advance only on emitted deltas; reconne
await h.session.stop(); await h.session.start(addresses);
assert.equal((await submit(base))[0], 6); // Even the same pixels need a trusted full base.
});
const compassMessages = transport => transport.sent.filter(s => s.message.sid === p.SID.cfw && s.message.payload[0] === 10);
test('compass desired state survives connecting and reconnecting; explicit stop disables it first', async t => {
const h = harness(t);
h.session.setCompassEnabled(true);
await h.session.start(addresses);
assert.equal(compassMessages(h.transport).length, 1);
assert.equal(compassMessages(h.transport)[0].id, 'L');
assert.deepEqual([...compassMessages(h.transport)[0].message.payload], [10, 2, 100, 0, 0, 0]);
await h.session.stop();
assert.deepEqual([...compassMessages(h.transport).at(-1).message.payload], [10, 0]);
assert.equal(h.transport.sent.at(-1).message.payload[0], 11);
await h.session.start(addresses);
assert.equal(compassMessages(h.transport).at(-1).message.payload[1], 2);
h.transport.emit({ kind: 'disconnected', identifier: 'R' });
assert.equal(h.session.state.phase, 'retrying');
await h.session.start(addresses, true);
assert.equal(compassMessages(h.transport).at(-1).message.payload[1], 2);
});
test('release during pending compass enable sends disable after the enable ACK', async t => {
const h = harness(t); await h.session.start(addresses);
assert.deepEqual([...compassMessages(h.transport)[0].message.payload], [10, 0]);
h.transport.hold = true;
h.session.setCompassEnabled(true);
await until(() => h.transport.held.length === 1);
h.session.setCompassEnabled(false);
const enabling = h.transport.held.shift();
h.transport.hold = false; h.transport.ack(enabling.id, enabling.message);
await until(() => compassMessages(h.transport).length === 3);
assert.deepEqual(compassMessages(h.transport).map(s => s.message.payload[1]), [0, 2, 0]);
});
test('compass notifications only come from the right arm and preserve diagnostics and calibration', async t => {
const h = harness(t); await h.session.start(addresses);
const payload = new Uint8Array(Buffer.from('080f1000520308e702a2060c434d010302038c0098badcfe', 'hex'));
const emit = (id, sid = 8, flag = 1, body = payload) => h.transport.emit({ kind: 'notification', identifier: id,
characteristic: p.G2_NOTIFY, data: hex(p.concat(...p.frameMessage(body, sid, flag, 20))) });
emit('L'); emit('other'); emit('R', 9); emit('R', 8, 0x20);
assert.equal(h.compass.length, 0);
emit('R'); emit('R', 8, 6, new Uint8Array([8, 16, 16, 0]));
emit('R', 8, 1, new Uint8Array([8, 17, 16, 0]));
assert.deepEqual(h.compass, [{ command: 15, headingDegrees: 359, diagnostics: {
magneticAccuracy: 3, magneticAnomalies: 2, orientationSource: 3, flags: 140, sampleTimeMs: 0xfedcba98,
} }, { command: 16, headingDegrees: -1 }, { command: 17, headingDegrees: -1 }]);
});
+86
View File
@@ -0,0 +1,86 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const ts = require('typescript');
const path = require('node:path');
function load(file, context = {}) {
const sandbox = { exports: {}, console, ...context };
vm.runInNewContext(ts.transpileModule(fs.readFileSync(path.join(__dirname, '..', file), 'utf8'), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText, sandbox);
return sandbox.exports;
}
test('iOS compass owners and listeners work before connection and across session replacement', () => {
const api = load('app/native/compass.ios.ts', { require: () => ({}) });
const states = [], nextStates = [], events = [];
const off = api.addCompassListener(event => events.push(event));
api.setCompassEnabled(true, 'compass');
api.setCompassEnabled(true, 'glanceboard');
api.bindCompassSession({ setCompassEnabled: enabled => states.push(enabled) });
api.setCompassEnabled(false, 'compass');
assert.deepEqual(states, [true, true]);
api.bindCompassSession({ setCompassEnabled: enabled => nextStates.push(enabled) });
assert.equal(states.at(-1), false);
api.setCompassEnabled(false, 'glanceboard');
assert.deepEqual(nextStates, [true, false]);
api.receiveCompassEvent({ command: 15, headingDegrees: 271 });
off(); api.receiveCompassEvent({ command: 15, headingDegrees: 90 });
assert.deepEqual(events, [{ command: 15, headingDegrees: 271 }]);
});
test('shared declination cache handles iOS fixes, persisted corrections and unavailable sensors', async () => {
const store = new Map(), listeners = [];
let permission = false, lookups = 0, fail = false;
let now = 1_800_000_000_000;
const ios = load('app/native/declination.ios.ts');
const context = {
Date: { now: () => now }, console: { warn() {} },
require: id => ({
'../../native/location-permissions': { hasLocationPermission: () => permission },
'../../native/declination': { restoreDeclination: ios.restoreDeclination, getCurrentDeclination: async () => {
lookups++; if (fail) throw new Error('No heading sensor');
return { latitude: 37.7, longitude: -122.4, degrees: 12.5 };
} },
'../../native/settings-store': { getStringSetting: (key, fallback) => store.get(key) ?? fallback,
setStringSetting: (key, value) => store.set(key, value) },
})[id],
};
const api = load('app/apps/compass/declination.ts', context);
api.onDeclinationChanged(() => listeners.push(api.getDeclinationDegrees()));
assert.equal(api.getDeclinationAvailability(), 'no-permission');
api.refreshDeclination(); assert.equal(lookups, 0);
permission = true;
assert.equal(api.getDeclinationAvailability(), 'no-fix');
api.refreshDeclination(); api.refreshDeclination();
await new Promise(resolve => setImmediate(resolve));
assert.equal(lookups, 1); assert.deepEqual(listeners, [12.5]);
assert.equal(api.getDeclinationAvailability(), 'available');
const restarted = load('app/apps/compass/declination.ts', context);
assert.equal(restarted.getDeclinationDegrees(), 12.5);
restarted.refreshDeclination(); assert.equal(lookups, 1);
now += 25 * 60 * 60 * 1000; fail = true;
restarted.refreshDeclination(); await new Promise(resolve => setImmediate(resolve));
assert.equal(restarted.getDeclinationDegrees(), 12.5);
restarted.refreshDeclination(); assert.equal(lookups, 2);
// Existing Android preferences have coordinates but no cached correction.
store.delete('compass.declination.degrees'); fail = false;
store.set('compass.declination.locatedAtMs', String(now));
const migrated = load('app/apps/compass/declination.ts', context);
assert.equal(migrated.getDeclinationDegrees(), null);
migrated.refreshDeclination(); await new Promise(resolve => setImmediate(resolve));
assert.equal(migrated.getDeclinationDegrees(), 12.5);
});
test('iOS native correction callbacks resolve values or propagate unavailable errors', async () => {
let unavailable = false;
const api = load('app/native/declination.ios.ts', { FaceclawLocation: { shared: () => ({
requestDeclination: callback => callback(-8.25, 51, 0, unavailable ? 'Heading unavailable' : ''),
}) } });
assert.deepEqual({ ...await api.getCurrentDeclination() }, { latitude: 51, longitude: 0, degrees: -8.25 });
unavailable = true;
await assert.rejects(api.getCurrentDeclination(), /Heading unavailable/);
assert.equal(api.restoreDeclination(0, 0, NaN), null);
assert.equal(api.restoreDeclination(0, 0, 360), null);
});
+1
View File
@@ -68,6 +68,7 @@ function fixture() {
paint: () => { boardStats.paints++; return new images.GrayImage(100, 80, 200); } }),
};
const modules = {
"../native/compass.ios": { bindCompassSession() {}, receiveCompassEvent() {} },
'@nativescript/core': { File: { fromPath: () => ({ writeTextSync() {} }) },
knownFolders: { documents: () => ({ path: '/tmp' }) }, path },
'../native/ios-bluetooth': { iosBluetooth: () => ({}) },
@@ -0,0 +1,40 @@
package com.faceclaw.app
import kotlin.test.*
class CompassTest {
private fun hex(text: String) = text.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
@Test
fun receiverPayloadAndAndroidFrameDecodeTheSameCompassSample() {
val payload = hex("080f1000520308e702a2060c434d010302038c0098badcfe")
for (flag in listOf(1, 6)) {
val frame = BleProtocol.framePb(payload, 8, flag, 15).single()
val received = MessageReceiver().receive("R", frame, 0).single()
val shared = assertNotNull(BleProtocol.parseCompassPayload(received.sid, received.flag, received.payload))
val android = assertNotNull(BleProtocol.parseCompassEvent(BleProtocol.parseFrame(frame)))
assertEquals(359, shared.headingDegrees)
assertEquals(15, shared.command)
assertEquals(3, shared.magneticAccuracy)
assertEquals(2, shared.magneticAnomalies)
assertEquals(3, shared.orientationSource)
assertEquals(0x8c, shared.diagnosticFlags)
assertEquals(0xfedcba98L, shared.sampleTimeMs)
assertEquals(android.sampleTimeMs, shared.sampleTimeMs)
}
assertNull(BleProtocol.parseCompassPayload(9, 1, payload))
assertNull(BleProtocol.parseCompassPayload(8, 0x20, payload))
assertNull(BleProtocol.parseCompassPayload(8, 1, hex("080f1000520308e802")))
assertNull(BleProtocol.parseCompassPayload(8, 1, byteArrayOf()))
for (size in 9 until payload.size) {
val legacy = assertNotNull(BleProtocol.parseCompassPayload(8, 1, payload.copyOf(size)))
assertEquals(359, legacy.headingDegrees)
assertEquals(-1, legacy.diagnosticFlags)
}
for (command in listOf(16, 17)) {
val calibration = assertNotNull(BleProtocol.parseCompassPayload(8, 1, byteArrayOf(8, command.toByte(), 16, 0)))
assertEquals(command, calibration.command)
assertEquals(-1, calibration.headingDegrees)
}
}
}
@@ -22,6 +22,14 @@ class IosNativeApiTest {
assertContentEquals(auth.byteArray(), result.payload.byteArray())
}
@Test
fun compassFacadePreservesTheEndOfTheCrcFreePayload() {
val protocol = IosProtocol()
val payload = byteArrayOf(8, 15, 16, 0, 82, 3, 8, -25, 2).data()
assertEquals(359, protocol.compassInput(payload, 8, 1)?.headingDegrees)
assertNull(protocol.compassInput(payload, 8, 0))
}
@Test
fun nativeCompositorClipsPartialUpdatesBeforeCoalescing() {
val compositor = IosSurfaceCompositor(3, 2)