forked from Blendman974/faceclaw
Refactor iOS version to use a bunch more shared code
This commit is contained in:
1 parent
c3a0ba9f56
commit
4a194e37bb
40 files changed
+1874
-2605
No files matched your search
@@ -1,68 +1,89 @@
|
||||
import { StockConnection, StockTimeout } from '../g2/stock-connection'
|
||||
import * as p from '../g2/ble-protocol'
|
||||
import { iosBluetooth } from './ios-bluetooth'
|
||||
import { kotlinListener } from './kotlin-listener.ios'
|
||||
import type { DeviceInfo, DeviceInfoState } from './device-info-probe'
|
||||
export type { DeviceInfo, DeviceInfoState } from './device-info-probe'
|
||||
|
||||
declare const FaceclawKitIosDeviceInfoProbe: any, FaceclawKitFaceclawDeviceInfoProbeListener: any
|
||||
|
||||
/**
|
||||
* iOS twin of the Android DeviceInfoProbe wrapper: the shared Kotlin DeviceInfoProbeFlow
|
||||
* runs over a CoreBluetooth central (FaceclawKitIosDeviceInfoProbe); TypeScript only maps
|
||||
* the stored MAC addresses to peripheral identifiers first. Callbacks arrive on the main
|
||||
* queue and are fanned out asynchronously like the Android wrapper does.
|
||||
*/
|
||||
export class DeviceInfoProbe {
|
||||
private logs = new Set<(line: string) => void>()
|
||||
private states = new Set<(state: DeviceInfoState, detail: string) => void>()
|
||||
private link = new StockConnection(iosBluetooth(), line => { for (const fn of this.logs) fn(line) })
|
||||
constructor(private right: string, private left = '') {}
|
||||
onLog(fn: (line: string) => void): () => void { this.logs.add(fn); return () => this.logs.delete(fn) }
|
||||
onStateChange(fn: (state: DeviceInfoState, detail: string) => void): () => void { this.states.add(fn); return () => this.states.delete(fn) }
|
||||
async run(): Promise<DeviceInfo> {
|
||||
const snapshots = new Map<string, DeviceInfo>()
|
||||
const parse = (message: p.ProtocolMessage): DeviceInfo => {
|
||||
const values = p.readBytes(message.payload, 4)
|
||||
return { leftVersion: values ? p.readString(values, 5) : '', rightVersion: values ? p.readString(values, 6) : '', extension: p.readString(message.payload, 100) }
|
||||
}
|
||||
const hasVersion = (info: DeviceInfo) => !!(info.leftVersion || info.rightVersion || info.extension)
|
||||
// Some stock builds push settings using their own magic instead of the
|
||||
// query's magic. Keep a valid snapshot as the Android probe does.
|
||||
this.link.onMessage((role, message) => {
|
||||
if (message.sid === p.SID.settings) { const info = parse(message); if (hasVersion(info)) snapshots.set(role, info) }
|
||||
private probe: any = null
|
||||
private listenerProxy: object | null = null
|
||||
private readonly logListeners = new Set<(line: string) => void>()
|
||||
private readonly stateListeners = new Set<(state: DeviceInfoState, detail: string) => void>()
|
||||
private settled = false
|
||||
private cancelled = false
|
||||
private resolveFn: ((info: DeviceInfo) => void) | null = null
|
||||
private rejectFn: ((error: Error) => void) | null = null
|
||||
|
||||
constructor(private readonly rightAddress: string, private readonly leftAddress = '') {}
|
||||
|
||||
onLog(listener: (line: string) => void): () => void {
|
||||
this.logListeners.add(listener)
|
||||
return () => this.logListeners.delete(listener)
|
||||
}
|
||||
|
||||
onStateChange(listener: (state: DeviceInfoState, detail: string) => void): () => void {
|
||||
this.stateListeners.add(listener)
|
||||
return () => this.stateListeners.delete(listener)
|
||||
}
|
||||
|
||||
run(): Promise<DeviceInfo> {
|
||||
return new Promise<DeviceInfo>((resolve, reject) => {
|
||||
this.resolveFn = resolve
|
||||
this.rejectFn = reject
|
||||
void this.start()
|
||||
})
|
||||
}
|
||||
|
||||
private async start(): Promise<void> {
|
||||
let identifiers: Record<string, string>
|
||||
try {
|
||||
await this.link.resolve({ right: this.right, left: this.left, ring: '' })
|
||||
for (const role of ['right', ...(this.left ? ['left'] : [])]) {
|
||||
await this.bringUp(role)
|
||||
}
|
||||
let lastError: unknown
|
||||
for (const role of ['right', ...(this.left ? ['left'] : [])]) {
|
||||
for (const fn of this.states) fn('querying', role)
|
||||
try {
|
||||
if (!this.link.isConnected(role)) await this.bringUp(role)
|
||||
await this.link.request(role, p.SID.launch, p.prelude, 3500, 156)
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
try {
|
||||
const message = await this.link.request(role, p.SID.settings, p.settingsQuery)
|
||||
const info = parse(message)
|
||||
if (hasVersion(info)) return info
|
||||
} catch (error) { this.link.check(); lastError = error }
|
||||
if (snapshots.has(role)) return snapshots.get(role)!
|
||||
}
|
||||
} catch (error) { this.link.check(); lastError = error }
|
||||
}
|
||||
throw lastError ?? new Error("Connected, but couldn't read a firmware version.")
|
||||
} finally { this.close() }
|
||||
}
|
||||
private async bringUp(role: string): Promise<void> {
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
try {
|
||||
for (const fn of this.states) fn('connecting', role)
|
||||
await this.link.connect(role)
|
||||
for (const fn of this.states) fn('authenticating', role)
|
||||
// Version reads remain available on older stock builds without an auth ACK.
|
||||
try { await this.link.authenticate(role) } catch (error) { if (!(error instanceof StockTimeout)) throw error }
|
||||
return
|
||||
} catch (error) {
|
||||
this.link.check(); this.link.disconnect(role)
|
||||
if (attempt === 2) throw error
|
||||
await new Promise(resolve => setTimeout(resolve, 1500)); this.link.check()
|
||||
}
|
||||
this.emit(this.stateListeners, 'connecting', 'right')
|
||||
identifiers = await iosBluetooth().resolveDevices({ right: this.rightAddress, left: this.leftAddress, ring: '' })
|
||||
} catch (error) {
|
||||
this.settle(error instanceof Error ? error : new Error(String(error)), null)
|
||||
return
|
||||
}
|
||||
if (this.cancelled) { this.settle(new Error('Cancelled.'), null); return }
|
||||
this.probe = FaceclawKitIosDeviceInfoProbe.alloc().initWithRightAddressLeftAddress(identifiers.right ?? '', identifiers.left ?? '')
|
||||
this.listenerProxy = kotlinListener(FaceclawKitFaceclawDeviceInfoProbeListener, {
|
||||
onLogLine: (line: string) => this.emit(this.logListeners, String(line ?? '')),
|
||||
onStateStateDetail: (state: string, detail: string) =>
|
||||
this.emit(this.stateListeners, String(state) as DeviceInfoState, String(detail ?? '')),
|
||||
onResultLeftVersionRightVersionExtension: (leftVersion: string, rightVersion: string, extension: string) =>
|
||||
this.settle(null, { leftVersion: String(leftVersion ?? ''), rightVersion: String(rightVersion ?? ''), extension: String(extension ?? '') }),
|
||||
onErrorMessage: (message: string) => this.settle(new Error(String(message ?? '')), null),
|
||||
})
|
||||
this.probe.setListenerListener(this.listenerProxy)
|
||||
this.probe.start()
|
||||
}
|
||||
|
||||
cancel(): void {
|
||||
this.cancelled = true
|
||||
try { this.probe?.cancel() } catch { /* ignore */ }
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.cancelled = true
|
||||
try { this.probe?.close() } catch { /* ignore */ }
|
||||
}
|
||||
|
||||
private settle(error: Error | null, info: DeviceInfo | null): void {
|
||||
if (this.settled) return
|
||||
this.settled = true
|
||||
this.close()
|
||||
if (error) this.rejectFn?.(error)
|
||||
else if (info) this.resolveFn?.(info)
|
||||
}
|
||||
|
||||
private emit<A extends unknown[]>(listeners: Set<(...args: A) => void>, ...args: A): void {
|
||||
const snapshot = Array.from(listeners)
|
||||
setTimeout(() => { for (const listener of snapshot) listener(...args) }, 0)
|
||||
}
|
||||
cancel(): void { this.link.close() }
|
||||
close(): void { this.link.close() }
|
||||
}
|
||||
Reference in new issue
Block a user