diff --git a/app/g2/glasses-session.ts b/app/g2/glasses-session.ts index 8f7a67ae..26c9418d 100644 --- a/app/g2/glasses-session.ts +++ b/app/g2/glasses-session.ts @@ -35,6 +35,9 @@ export class GlassesSession { private sequence = 0x40 private timer: number | null = null private retryTimer: number | null = null + private ringRetryTimer: number | null = null + private ringRetryCount = 0 + private ringConnecting = false private retryCount = 0 private wanted = false private addresses: SessionAddresses | null = null @@ -47,6 +50,7 @@ export class GlassesSession { private charging = false private layoutCreated = false private off: () => void + private stopping: Promise | null = null constructor(private readonly transport: SessionTransport, private readonly deflate: (data: Uint8Array) => Uint8Array, private readonly onState: (state: SessionState) => void, @@ -105,24 +109,52 @@ export class GlassesSession { this.displayed = null; this.retryCount = 0 this.update('connected', 'Glasses connected') this.schedule() - if (addresses.ring && ids.ring) { - try { - const ring = await this.transport.connect(ids.ring); this.check(generation) - const notifications = protocol.RING_NOTIFY.filter(uuid => ring.characteristics.includes(uuid)) - if (!notifications.length) throw new Error('No R1 gesture notifications found') - for (const uuid of notifications) await this.transport.subscribe(ids.ring, uuid) - this.check(generation); this.state.ring = true; this.update('connected', 'Glasses and ring connected') - } catch (error) { - if (generation !== this.generation) return - this.transport.disconnect(ids.ring) - this.update('connected', `Glasses connected; ring unavailable: ${this.message(error)}`) - } - } else if (addresses.ring) this.update('connected', 'Glasses connected; configured ring was not found') + if (addresses.ring && ids.ring) await this.connectRing(generation) + else if (addresses.ring) this.update('connected', 'Glasses connected; configured ring was not found') } catch (error) { if (generation !== this.generation) return - this.fail(error, retry) + this.fail(error, retry || error instanceof AckTimeout) } } + private async connectRing(generation: number): Promise { + if (this.ringConnecting || generation !== this.generation || this.state.phase !== 'connected' || !this.ids.ring) return + this.ringConnecting = true + const identifier = this.ids.ring + try { + const ring = await this.transport.connect(identifier); this.check(generation) + this.log(`R1 services discovered: ${ring.characteristics.join(', ')}`) + const notifications = protocol.RING_NOTIFY.filter(uuid => ring.characteristics.includes(uuid)) + if (!notifications.length) throw new Error('No R1 gesture notifications found') + let subscribed = 0 + for (const uuid of notifications) { + this.log(`Subscribing R1 ${uuid}`) + try { await this.transport.subscribe(identifier, uuid); this.check(generation); subscribed++; this.log(`R1 subscribed ${uuid}`) } + catch (error) { this.check(generation); this.log(`R1 channel unavailable ${uuid}: ${this.message(error)}`) } + } + if (!subscribed) throw new Error('Neither R1 notification channel could be subscribed') + this.check(generation); this.state.ring = true; this.ringRetryCount = 0 + this.update('connected', 'Glasses and ring connected') + } catch (error) { + if (generation !== this.generation) return + this.state.ring = false + this.transport.disconnect(identifier) + this.update('connected', `Glasses connected; ring unavailable: ${this.message(error)}`) + } finally { + if (generation === this.generation) { + this.ringConnecting = false + if (!this.state.ring) this.scheduleRingRetry() + } + } + } + private scheduleRingRetry(): void { + if (!this.wanted || this.state.phase !== 'connected' || !this.ids.ring || this.ringConnecting || this.ringRetryTimer !== null || this.ringRetryCount >= 5) return + const generation = this.generation, delay = Math.min(30_000, 2000 * 2 ** this.ringRetryCount++) + this.log(`Retrying ring in ${delay / 1000}s`) + this.ringRetryTimer = setTimeout(() => { + this.ringRetryTimer = null + if (generation === this.generation) void this.connectRing(generation) + }, delay) + } private check(generation: number): void { if (generation !== this.generation) throw new Error('Connection cancelled') } private nextMagic(): number { for (let i = 0; i < 156; i++) { @@ -134,6 +166,7 @@ export class GlassesSession { private request(role: string, sid: number, build: (magic: number) => Uint8Array, label: string, timeout = 3500, flag = 0x20, fixedMagic?: number): Promise { const magic = fixedMagic ?? this.nextMagic(), payload = build(magic), key = `${sid}:${magic}` + this.log(`TX ${label} ${role} sid=${sid.toString(16)} magic=${magic}`) const generation = this.generation return new Promise((resolve, reject) => { const pending: PendingAck = { resolve, reject, timer: null, command: protocol.readInteger(payload, 1, -1), label } @@ -169,7 +202,10 @@ export class GlassesSession { if (event.kind === 'disconnected') { if (event.identifier === this.ids.ring) { this.state.ring = false - if (this.state.phase === 'connected') this.update('connected', 'Glasses connected; ring disconnected') + if (this.state.phase === 'connected') { + this.update('connected', `Glasses connected; ring disconnected${event.message ? ': ' + event.message : ''}`) + this.scheduleRingRetry() + } } else if (['connected', 'connecting'].includes(this.state.phase)) this.fail(new Error(event.message || 'Glasses disconnected'), true) return } @@ -178,10 +214,13 @@ export class GlassesSession { const data = hexToBytes(event.data) if (event.identifier === this.ids.ring) { if (!protocol.RING_NOTIFY.includes(event.characteristic ?? '')) return - const input = protocol.decodeRingInput(data); if (input) this.onInput(input); return + const input = protocol.decodeRingInput(data) + if (input) { this.log(`Direct R1 gesture ${input.eventType}`); this.onInput(input) } + return } if (event.characteristic !== protocol.G2_NOTIFY) return for (const message of this.receiver.receive(event.identifier!, data)) { + this.log(`RX ${event.identifier === this.ids.left ? 'L' : 'R'} sid=${message.sid.toString(16)} flag=${message.flag.toString(16)} cmd=${message.command} magic=${message.magic}`) if (![1, 6].includes(message.flag)) { // A master arm can relay the other arm's ACK; magic is allocated // across BOTH links, matching Android's communicator. @@ -259,6 +298,8 @@ export class GlassesSession { ++this.generation if (this.timer !== null) clearTimeout(this.timer) if (this.retryTimer !== null) clearTimeout(this.retryTimer) + if (this.ringRetryTimer !== null) clearTimeout(this.ringRetryTimer) + this.ringRetryTimer = null; this.ringConnecting = false; this.ringRetryCount = 0 this.timer = this.retryTimer = null; this.pumping = false const pending = [...this.pending.values()]; this.pending.clear() for (const request of pending) { if (request.timer) clearTimeout(request.timer); request.reject(new Error('Connection ended')) } @@ -277,7 +318,12 @@ export class GlassesSession { this.retryTimer = setTimeout(() => { this.retryTimer = null; if (this.wanted && this.addresses) void this.start(this.addresses, true) }, delay) } else { this.wanted = false; this.update('error', message) } } - async stop(): Promise { + stop(): Promise { + if (this.stopping) return this.stopping + this.stopping = this.stopInternal().finally(() => { this.stopping = null }) + return this.stopping + } + private async stopInternal(): Promise { this.wanted = false const cleanup = this.layoutCreated && this.state.phase === 'connected' this.update('disconnecting', 'Disconnecting…'); this.reset() diff --git a/app/native/ios-bluetooth.ts b/app/native/ios-bluetooth.ts index fab13d6b..38d6686f 100644 --- a/app/native/ios-bluetooth.ts +++ b/app/native/ios-bluetooth.ts @@ -18,6 +18,7 @@ export class IosBluetooth { readonly devices = new Map() private requestId = 0 private scanTimer: ReturnType | null = null + private scanGeneration = 0 state = 0 scanning = false constructor() { @@ -72,19 +73,25 @@ export class IosBluetooth { }) } async startScan(durationMs = 12_000): Promise { + this.stopScan() + const generation = this.scanGeneration await this.ensureReady() - this.stopScan(); this.scanning = true; this.native.scan(true) + if (generation !== this.scanGeneration) throw new Error('Bluetooth scan cancelled') + this.scanning = true; this.native.scan(true) this.scanTimer = setTimeout(() => this.stopScan(), durationMs) this.emit({ kind: 'scan-started' }) } stopScan(): void { + ++this.scanGeneration if (this.scanTimer) clearTimeout(this.scanTimer) this.scanTimer = null; this.native.scan(false) const wasScanning = this.scanning; this.scanning = false if (wasScanning) this.emit({ kind: 'scan-stopped' }) } async resolveDevices(addresses: { left: string; right: string; ring: string }): Promise> { + const generation = this.scanGeneration await this.ensureReady() + if (generation !== this.scanGeneration) throw new Error('Bluetooth connection cancelled') const result: Record = {} for (const role of ['left', 'right', 'ring'] as const) { const address = addresses[role] @@ -116,11 +123,11 @@ export class IosBluetooth { }) return result } - private operation(identifier: string, call: (id: number) => void, timeoutMs = 10_000): Promise { + private operation(identifier: string, call: (id: number) => void, timeoutMs = 10_000, disconnectOnTimeout = true): Promise { const id = ++this.requestId return new Promise((resolve, reject) => { const timer = setTimeout(() => { - this.pending.delete(id); this.native.disconnect(identifier) + this.pending.delete(id); if (disconnectOnTimeout) this.native.disconnect(identifier) reject(new Error('Bluetooth operation timed out. Wake the device and try connecting again.')) }, timeoutMs) this.pending.set(id, { resolve, reject, timer }) @@ -129,7 +136,9 @@ export class IosBluetooth { } connect(identifier: string): Promise { return this.operation(identifier, id => this.native.connectRequestId(identifier, id), 20_000) } async subscribe(identifier: string, characteristic: string): Promise { - await this.operation(identifier, id => this.native.subscribeCharacteristicRequestId(identifier, characteristic, id)) + // R1 exposes two notification channels; one may never complete its CCCD + // request. Keep the link alive so the other channel can still be tried. + await this.operation(identifier, id => this.native.subscribeCharacteristicRequestId(identifier, characteristic, id), 30_000, false) } async write(identifier: string, characteristic: string, bytes: Uint8Array): Promise { const copy = new Uint8Array(bytes) diff --git a/tests/ios-ble.test.cjs b/tests/ios-ble.test.cjs index 07c186d6..22645eb0 100644 --- a/tests/ios-ble.test.cjs +++ b/tests/ios-ble.test.cjs @@ -102,7 +102,8 @@ class FakeTransport { let body = new Uint8Array(); if (message.sid === p.SID.auth) body = p.bytes(3, new Uint8Array()); if (message.sid === p.SID.settings) body = p.concat(p.bytes(4, p.concat(string(5, '2.2.9.22'), string(6, '2.2.9.22'), p.integer(12, 90), p.integer(13, 0))), string(100, this.stock ? '' : 'EVENCFW/18 img640 fbguard wearnotify cleanup11')); - const payload = p.concat(p.integer(1, message.command), p.integer(2, overrides.magic ?? message.magic), body); + const responseCommand = message.sid === p.SID.launch ? 1 : message.sid === p.SID.hub && message.command === 0 ? 1 : message.sid === p.SID.hub && message.command === 3 ? 4 : message.command; + const payload = p.concat(p.integer(1, responseCommand), p.integer(2, overrides.magic ?? message.magic), body); const data = hex(p.concat(...p.frameMessage(payload, overrides.sid ?? message.sid, 0, 12))); // The right/master link also carries ACKs for image writes to L. this.emit({ kind: 'notification', identifier: overrides.identifier ?? 'R', characteristic: p.G2_NOTIFY, data }); @@ -148,6 +149,18 @@ test('stock firmware is rejected before framebuffer/layout/image commands', asyn assert.equal(h.session.state.phase, 'error'); assert.match(h.session.state.status, /modified firmware/); assert.ok(!transport.sent.some(s => s.message.sid === p.SID.hub)); }); +test('one unavailable R1 notification channel does not discard the usable channel', async t => { + const transport = new FakeTransport(); + const subscribe = transport.subscribe.bind(transport); + transport.subscribe = async (id, uuid) => { + if (uuid === p.RING_NOTIFY[0]) throw new Error('CCCD timed out'); + return subscribe(id, uuid); + }; + const h = harness(t, transport); await h.session.start({ ...addresses, ring: 'AA:BB:CC:DD:EE:03' }); + assert.equal(h.session.state.ring, true); + assert.ok(transport.subscriptions.some(([id, uuid]) => id === 'ring' && uuid === p.RING_NOTIFY[1])); + assert.ok(!transport.closed.includes('ring')); +}); test('disconnect cancels in-flight authentication and ignores late acknowledgements', async t => { const h = harness(t); h.transport.hold = true; const start = h.session.start(addresses); await until(() => h.transport.held.length === 2); @@ -169,3 +182,18 @@ test('wrong peer, service or magic cannot satisfy a pending request; timeout rej h.transport.ack(held.id, held.message, { magic: held.message.magic + 1 }); await rejected; }); + +test('ring disconnect retries independently and stop cancels further retries', async t => { + const h = harness(t); await h.session.start({ ...addresses, ring: 'AA:BB:CC:DD:EE:03' }); + const armMessages = h.transport.sent.length; + h.transport.emit({ kind: 'disconnected', identifier: 'ring', message: 'Link lost' }); + assert.equal(h.session.state.phase, 'connected'); assert.equal(h.session.state.ring, false); + assert.notEqual(h.session.ringRetryTimer, null); + await new Promise(resolve => setTimeout(resolve, 2100)); + assert.equal(h.session.state.ring, true); + assert.equal(h.transport.sent.length, armMessages); + assert.equal(h.transport.subscriptions.filter(([id]) => id === 'ring').length, 4); + h.transport.emit({ kind: 'disconnected', identifier: 'ring' }); + await h.session.stop(); + assert.equal(h.session.ringRetryTimer, null); +});