Fix an issue where iOS couldn't reconnect to a G2 arm because it already had an ANCS connection open to it

This commit is contained in:
James Babcock committed 2026-11-17 17:38:11 -08:00
1 parent ab692741f7
commit d1e424b7e1
6 files changed
+164 -6

No files matched your search

+20 -2
View File
@@ -3,11 +3,18 @@ import type { DiscoveryEvents } from './device-discovery'
import type { RawAdvertisement } from '../g2/even-advertisement'
export { buildAddressSet } from './device-discovery-common'
/**
* How often a scan re-reads which arms the system is connected to. Each read refreshes
* their rows, which age out like advertisements once the link drops and they go quiet.
*/
const CONNECTED_ARMS_POLL_MS = 2000
export class DeviceDiscoveryBridge {
private ble = iosBluetooth()
private off: (() => void) | null = null
private generation = 0
private cancelCollection: (() => void) | null = null
private connectedArmsTimer: ReturnType<typeof setInterval> | null = null
get bluetoothEnabled(): boolean { return this.ble.state === 5 }
get scanning(): boolean { return !!this.off && this.ble.scanning }
startScan(events: DiscoveryEvents): boolean {
@@ -21,16 +28,27 @@ export class DeviceDiscoveryBridge {
void this.ble.startScan(24 * 60 * 60 * 1000).catch(error => {
if (generation === this.generation) events.onScanFailed?.(-1, String(error.message ?? error))
})
// A connected arm doesn't advertise (iOS holds the right arm's ANCS link open after a
// session ends), so the scan alone would show those glasses one-armed.
const reportConnectedArms = () => { for (const device of this.ble.systemConnectedDevices()) events.onAdvertisement(device) }
reportConnectedArms()
this.connectedArmsTimer = setInterval(reportConnectedArms, CONNECTED_ARMS_POLL_MS)
return true
}
stopScan(): void {
++this.generation; this.cancelCollection?.()
if (this.connectedArmsTimer) { clearInterval(this.connectedArmsTimer); this.connectedArmsTimer = null }
if (this.off) { this.off(); this.off = null; this.ble.stopScan() }
}
// CoreBluetooth does not expose the phone's bond list. Fresh advertisements
// supply both identity and the UUID mapping that iOS needs for connections.
// supply both identity and the UUID mapping that iOS needs for connections;
// startScan() reports the arms the system is connected to.
emitBondedDevices(): void {}
async getBondedCandidates(): Promise<RawAdvertisement[]> { return [...this.ble.devices.values()] }
async getBondedCandidates(): Promise<RawAdvertisement[]> {
const devices = new Map(this.ble.devices)
for (const device of this.ble.systemConnectedDevices()) if (!devices.has(device.address)) devices.set(device.address, device)
return [...devices.values()]
}
async scanCandidates(timeoutMs = 6000): Promise<RawAdvertisement[]> {
const generation = this.generation
await this.ble.ensureReady()
+74 -4
View File
@@ -1,4 +1,7 @@
import { ApplicationSettings } from '@nativescript/core'
import { loadPairedGlassesIdentity } from '../g2/device-addresses'
import { g2ManufacturerData } from '../g2/even-advertisement'
import { serialKey } from '../g2/glasses-hardware-identity'
import { identifyIosPeripheral, type IosAdvertisement, type IosDevice } from '../g2/ios-peripheral-identity'
import { hexToBytes } from '../util/hex-util'
import { kotlinListener } from './kotlin-listener.ios'
@@ -10,6 +13,13 @@ export const BLE_STATE_UNSUPPORTED = 2, BLE_STATE_UNAUTHORIZED = 3, BLE_STATE_PO
/** CBManagerAuthorization.allowedAlways. */
const BLE_AUTHORIZATION_ALLOWED = 3
/**
* Per address, the peripheral identifier and side last heard there and (since 2026-11-16)
* the advertisement itself, from which an arm that has stopped advertising is rebuilt.
*/
const PERIPHERAL_KEY_PREFIX = 'ios.ble.peripheral.'
type RememberedPeripheral = { identifier: string; role: string; name?: string; manufacturerData?: string }
export type BluetoothEvent =
| { kind: 'state'; state: number; authorization: number }
| { kind: 'advertisement'; identifier: string; name: string; manufacturerData: string; rssi: number; connectable: boolean }
@@ -28,6 +38,8 @@ export class IosBluetooth {
private readonly native = FaceclawKitIosBleCentral.alloc().initWithPlatform(FaceclawKitIosProtocolPlatform.shared)
private readonly listeners = new Set<(event: BluetoothEvent) => void>()
readonly devices = new Map<string, IosDevice>()
/** The record last written per settings key, so repeated advertisements don't rewrite it. */
private readonly rememberedValues = new Map<string, string>()
private scanTimer: ReturnType<typeof setTimeout> | null = null
private scanGeneration = 0
private readonly scanListener: object
@@ -47,12 +59,68 @@ export class IosBluetooth {
const device = identifyIosPeripheral(raw)
if (device) {
this.devices.set(device.address, device)
ApplicationSettings.setString(`ios.ble.peripheral.${device.address}`, JSON.stringify({ identifier: device.identifier, role: device.role }))
this.remember(device)
this.emit({ kind: 'device', device })
}
},
})
}
/** Persists what `device` advertised; skips the write when nothing changed (scans report duplicates). */
private remember(device: IosDevice): void {
const key = `${PERIPHERAL_KEY_PREFIX}${device.address}`
const record: RememberedPeripheral = { identifier: device.identifier, role: device.role, name: device.name, manufacturerData: device.manufacturerData }
const value = JSON.stringify(record)
if (this.rememberedValues.get(key) === value) return
this.rememberedValues.set(key, value)
ApplicationSettings.setString(key, value)
}
/**
* Even arms the system is connected to, rebuilt from what they last advertised here. A
* connected arm doesn't advertise, and iOS keeps the right arm's ANCS link open after a
* session ends (even after pairing other glasses), so a scan alone hears only the left
* arm. An arm this phone has never heard advertise can't be rebuilt: its MAC and the
* pair's serial come only from the advertisement. The device has no signal strength.
*/
systemConnectedDevices(): IosDevice[] {
if (this.state !== BLE_STATE_POWERED_ON) return []
let connected: any
try {
connected = this.native.systemConnectedG2Arms()
} catch (error) {
// Scanning still works without this; don't let it take the pairing page down.
console.log(`[IosBluetooth] systemConnectedG2Arms failed: ${error}`)
return []
}
if (!connected?.count) return []
const records = new Map<string, { address: string; record: RememberedPeripheral }>()
for (const key of ApplicationSettings.getAllKeys()) {
if (!key.startsWith(PERIPHERAL_KEY_PREFIX)) continue
try {
const record = JSON.parse(ApplicationSettings.getString(key, '{}')) as RememberedPeripheral
if (typeof record.identifier === 'string') records.set(record.identifier.toUpperCase(), { address: key.slice(PERIPHERAL_KEY_PREFIX.length), record })
} catch { /* Malformed: a fresh advertisement rewrites it. */ }
}
const identity = loadPairedGlassesIdentity()
const devices: IosDevice[] = []
for (let i = 0; i < connected.count; i++) {
const peripheral = connected.objectAtIndex(i)
const identifier = String(peripheral.identifier)
const remembered = records.get(identifier)
if (!remembered) continue
const { address, record } = remembered
let name = record.name ?? ''
let manufacturerData = record.manufacturerData ?? ''
if (!manufacturerData && identity && (address === identity.leftAddress || address === identity.rightAddress)) {
// Remembered before advertisements were: the saved pairing supplies the serial.
const side = address === identity.leftAddress ? 'left' : 'right'
name ||= side === 'left' ? identity.leftName : identity.rightName
manufacturerData = g2ManufacturerData(serialKey(identity.serial) ?? '', address) ?? ''
}
const device = identifyIosPeripheral({ identifier, name: name || String(peripheral.name ?? ''), manufacturerData, rssi: 0, connectable: true })
if (device?.address === address && device.role === record.role) devices.push({ ...device, rssi: null, source: 'paired' })
}
return devices
}
onEvent(listener: (event: BluetoothEvent) => void): () => void {
this.listeners.add(listener); return () => { this.listeners.delete(listener) }
}
@@ -111,7 +179,7 @@ export class IosBluetooth {
const live = this.devices.get(address)
if (live && live.role !== role) throw new Error(`${address} advertises as ${live.role}, not ${role}. Check Configure devices.`)
try {
const saved = JSON.parse(ApplicationSettings.getString(`ios.ble.peripheral.${address}`, '{}'))
const saved = JSON.parse(ApplicationSettings.getString(`${PERIPHERAL_KEY_PREFIX}${address}`, '{}'))
if (saved.role === role && typeof saved.identifier === 'string') result[role] = saved.identifier
} catch { /* A fresh scan can recover malformed settings. */ }
}
@@ -138,13 +206,15 @@ export class IosBluetooth {
/** The peripheral last heard at this address, if it was on this side. */
peripheralIdentifier(address: string, role: string): string | null {
try {
const saved = JSON.parse(ApplicationSettings.getString(`ios.ble.peripheral.${address}`, '{}'))
const saved = JSON.parse(ApplicationSettings.getString(`${PERIPHERAL_KEY_PREFIX}${address}`, '{}'))
return saved.role === role && typeof saved.identifier === 'string' ? saved.identifier : null
} catch {
return null
}
}
forget(address: string): void { ApplicationSettings.remove(`ios.ble.peripheral.${address}`); this.devices.delete(address) }
forget(address: string): void {
ApplicationSettings.remove(`${PERIPHERAL_KEY_PREFIX}${address}`); this.rememberedValues.delete(`${PERIPHERAL_KEY_PREFIX}${address}`); this.devices.delete(address)
}
}
let instance: IosBluetooth | null = null
export function iosBluetooth(): IosBluetooth { return instance ??= new IosBluetooth() }