Files
faceclaw/app/native/ios-bluetooth.ts
T

222 lines
12 KiB
TypeScript

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'
declare const FaceclawKitIosBleCentral: any, FaceclawKitIosProtocolPlatform: any, FaceclawKitIosBleScanListener: any
/** CBManagerState raw values reported by the Kotlin central. */
export const BLE_STATE_UNSUPPORTED = 2, BLE_STATE_UNAUTHORIZED = 3, BLE_STATE_POWERED_OFF = 4, BLE_STATE_POWERED_ON = 5
/** 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 }
| { kind: 'device'; device: IosDevice }
| { kind: 'scan-started' }
| { kind: 'scan-stopped' }
/**
* Scanning and MAC-address-to-identifier resolution over the shared Kotlin CoreBluetooth
* central (FaceclawKitIosBleCentral). GATT sessions no longer pass through here: the
* session and stock-firmware flows own their own Kotlin centrals. What stays in TypeScript
* is the Even classification of advertisements and the persisted identifier map, which the
* Android address model (MACs) needs on iOS.
*/
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
state = 0
authorization = 0
scanning = false
constructor() {
this.scanListener = kotlinListener(FaceclawKitIosBleScanListener, {
onBluetoothStateStateAuthorization: (state: number, authorization: number) => {
this.state = Number(state); this.authorization = Number(authorization)
this.emit({ kind: 'state', state: this.state, authorization: this.authorization })
},
onAdvertisementIdentifierNameManufacturerDataHexRssiConnectable: (identifier: string, name: string, manufacturerData: string, rssi: number, connectable: boolean | undefined) => {
// The Kotlin central already merges split advertisements and bounds its cache.
const raw: IosAdvertisement = { identifier: String(identifier), name: String(name ?? ''), manufacturerData: String(manufacturerData ?? ''), rssi: Number(rssi), connectable: connectable !== false }
this.emit({ kind: 'advertisement', ...raw })
const device = identifyIosPeripheral(raw)
if (device) {
this.devices.set(device.address, device)
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) }
}
private emit(event: BluetoothEvent): void { for (const listener of [...this.listeners]) listener(event) }
/**
* Whether the user has allowed Bluetooth. Unlike `state` this is accurate before the
* central exists, and reading it never shows the permission prompt.
*/
isAuthorized(): boolean { return Number(this.native.authorization()) === BLE_AUTHORIZATION_ALLOWED }
/** Creates the central (first use shows the Bluetooth permission prompt) without blocking the JS thread. */
private ensureCentral(): void {
// Registering the listener creates the central, or has an existing one re-report its
// state; the state arrives through the listener on the main queue.
this.native.setScanListenerListener(this.scanListener)
}
ensureReady(): Promise<void> {
if (this.state === BLE_STATE_POWERED_ON) return Promise.resolve()
return new Promise((resolve, reject) => {
const finish = (error?: Error) => { clearTimeout(timer); off(); if (error) reject(error); else resolve() }
const off = this.onEvent(event => {
if (event.kind !== 'state') return
if (event.state === BLE_STATE_POWERED_ON) finish()
else if (event.state === BLE_STATE_UNSUPPORTED) finish(new Error('Bluetooth is unavailable on this device. Use the physical iPhone.'))
else if (event.state === BLE_STATE_UNAUTHORIZED) finish(new Error('Allow Faceclaw to use Bluetooth in iPhone Settings.'))
else if (event.state === BLE_STATE_POWERED_OFF) finish(new Error('Turn on Bluetooth, then try again.'))
})
const timer = setTimeout(() => finish(new Error('Waiting for Bluetooth permission timed out. Try again after allowing Bluetooth.')), 30_000)
this.ensureCentral()
})
}
async startScan(durationMs = 12_000): Promise<void> {
this.stopScan()
const generation = this.scanGeneration
await this.ensureReady()
if (generation !== this.scanGeneration) throw new Error('Bluetooth scan cancelled')
this.scanning = true; this.native.startScan()
this.scanTimer = setTimeout(() => this.stopScan(), durationMs)
this.emit({ kind: 'scan-started' })
}
stopScan(): void {
++this.scanGeneration
if (this.scanTimer) clearTimeout(this.scanTimer)
this.scanTimer = null
const wasScanning = this.scanning; this.scanning = false
if (wasScanning) { this.native.stopScan(); this.emit({ kind: 'scan-stopped' }) }
}
/** Peripheral identifiers for the stored MAC addresses, scanning for any that are not remembered. */
async resolveDevices(addresses: { left: string; right: string; ring: string }): Promise<Record<string, string>> {
const generation = this.scanGeneration
await this.ensureReady()
if (generation !== this.scanGeneration) throw new Error('Bluetooth connection cancelled')
const result: Record<string, string> = {}
for (const role of ['left', 'right', 'ring'] as const) {
const address = addresses[role]
if (!address) continue
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(`${PERIPHERAL_KEY_PREFIX}${address}`, '{}'))
if (saved.role === role && typeof saved.identifier === 'string') result[role] = saved.identifier
} catch { /* A fresh scan can recover malformed settings. */ }
}
const missing = () => (['left', 'right'] as const).filter(role => !result[role])
if (!missing().length && (!addresses.ring || result.ring)) return result
await this.startScan(15_000)
await new Promise<void>((resolve, reject) => {
const off = this.onEvent(event => {
if (event.kind === 'device') {
const device = event.device
for (const role of ['left', 'right', 'ring'] as const) {
if (addresses[role] === device.address && device.role === role) result[role] = device.identifier
}
if (!missing().length && (!addresses.ring || result.ring)) { off(); this.stopScan(); resolve() }
} else if (event.kind === 'scan-stopped') {
off()
if (missing().length) reject(new Error(`Could not find the ${missing().join(' and ')} arm. Wake the glasses, disconnect other apps, and scan again.`))
else resolve() // An optional missing ring must not block the glasses.
}
})
})
return result
}
/** 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(`${PERIPHERAL_KEY_PREFIX}${address}`, '{}'))
return saved.role === role && typeof saved.identifier === 'string' ? saved.identifier : null
} catch {
return null
}
}
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() }
export { hexToBytes }