forked from Blendman974/faceclaw
Porting onboarding/flashing flow io iOS
This commit is contained in:
1 parent
68b459751e
commit
64bf600ef9
46 files changed
+1419
-211
No files matched your search
@@ -0,0 +1,2 @@
|
||||
import { iosBluetooth } from './ios-bluetooth'
|
||||
export async function ensureBlePermissions(): Promise<void> { await iosBluetooth().ensureReady() }
|
||||
@@ -0,0 +1 @@
|
||||
export { ensureBlePermissions } from '../g2/android-permissions'
|
||||
@@ -0,0 +1,52 @@
|
||||
import { type RawAdvertisement } from "../g2/even-advertisement";
|
||||
import { DiscoveryAggregator } from "../g2/pairing-candidates";
|
||||
import type { DiscoveredAddressSet } from "./device-discovery";
|
||||
|
||||
/**
|
||||
* Pick one address per role from a batch of raw advertisements — the manual
|
||||
* address page's "load" helper and the flash flow's address resolution.
|
||||
*
|
||||
* Runs the batch through the same `DiscoveryAggregator` the pairing page
|
||||
* uses, so left/right come from ONE serial-joined pair (the closest complete
|
||||
* one) rather than from whichever arm of whatever pair advertised last —
|
||||
* "latest per role" silently welded together arms of two different pairs.
|
||||
* When no arm carries a serial at all (a bonded-device listing has no
|
||||
* manufacturer data), there is nothing to join on and the latest arm per side
|
||||
* is used as before.
|
||||
*/
|
||||
export function buildAddressSet(candidates: RawAdvertisement[]): DiscoveredAddressSet {
|
||||
const aggregator = new DiscoveryAggregator();
|
||||
for (const raw of candidates) aggregator.ingest(raw);
|
||||
const classified = aggregator.advertisements();
|
||||
const pairs = aggregator.pairs();
|
||||
|
||||
let left = "";
|
||||
let right = "";
|
||||
const completePair = pairs.find((pair) => pair.completeness === "complete");
|
||||
if (completePair) {
|
||||
left = completePair.left!.address;
|
||||
right = completePair.right!.address;
|
||||
} else if (classified.every((candidate) => !candidate.serial)) {
|
||||
for (const role of ["left", "right"] as const) {
|
||||
const latest = classified
|
||||
.filter((candidate) => candidate.role === role)
|
||||
.sort((a, b) => b.seenAtMs - a.seenAtMs)[0];
|
||||
if (role === "left") left = latest?.address ?? "";
|
||||
else right = latest?.address ?? "";
|
||||
}
|
||||
}
|
||||
// Arms with serials but no complete pair: leave the addresses empty. The
|
||||
// summary below names what was heard; guessing would defeat the serial join.
|
||||
|
||||
const lines = classified.map((candidate) => {
|
||||
const extras = [candidate.serial ? `serial ${candidate.serial}` : null, candidate.rssi != null ? `${candidate.rssi} dBm` : null].filter(Boolean);
|
||||
return `${candidate.role}: ${candidate.name} ${candidate.address}${extras.length ? ` (${extras.join(", ")})` : ""}`;
|
||||
});
|
||||
return {
|
||||
left,
|
||||
right,
|
||||
ring: aggregator.rings()[0]?.advertisement.address ?? "",
|
||||
summary: lines.length ? lines.join("\n") : "No matching devices found.",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { iosBluetooth } from './ios-bluetooth'
|
||||
import type { DiscoveryEvents } from './device-discovery'
|
||||
import type { RawAdvertisement } from '../g2/even-advertisement'
|
||||
export { buildAddressSet } from './device-discovery-common'
|
||||
|
||||
export class DeviceDiscoveryBridge {
|
||||
private ble = iosBluetooth()
|
||||
private off: (() => void) | null = null
|
||||
private generation = 0
|
||||
private cancelCollection: (() => void) | null = null
|
||||
get bluetoothEnabled(): boolean { return this.ble.state === 5 }
|
||||
get scanning(): boolean { return !!this.off && this.ble.scanning }
|
||||
startScan(events: DiscoveryEvents): boolean {
|
||||
this.stopScan()
|
||||
const generation = this.generation
|
||||
if (!this.bluetoothEnabled) return false
|
||||
this.off = this.ble.onEvent(event => {
|
||||
if (event.kind === 'device' && 'device' in event) events.onAdvertisement(event.device)
|
||||
if (event.kind === 'state' && event.state !== 5) events.onScanFailed?.(event.state ?? 0, 'Bluetooth is unavailable. Turn it on, then tap Scan.')
|
||||
})
|
||||
void this.ble.startScan(24 * 60 * 60 * 1000).catch(error => {
|
||||
if (generation === this.generation) events.onScanFailed?.(-1, String(error.message ?? error))
|
||||
})
|
||||
return true
|
||||
}
|
||||
stopScan(): void {
|
||||
++this.generation; this.cancelCollection?.()
|
||||
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.
|
||||
emitBondedDevices(): void {}
|
||||
async getBondedCandidates(): Promise<RawAdvertisement[]> { return [...this.ble.devices.values()] }
|
||||
async scanCandidates(timeoutMs = 6000): Promise<RawAdvertisement[]> {
|
||||
const generation = this.generation
|
||||
await this.ble.ensureReady()
|
||||
if (generation !== this.generation) throw new Error('Bluetooth scan cancelled.')
|
||||
return new Promise((resolve, reject) => {
|
||||
const samples: RawAdvertisement[] = []
|
||||
const finish = (error?: Error) => {
|
||||
clearTimeout(timer); this.cancelCollection = null; this.stopScan()
|
||||
if (error) reject(error); else resolve(samples)
|
||||
}
|
||||
const timer = setTimeout(() => finish(), timeoutMs)
|
||||
if (!this.startScan({ onAdvertisement: sample => samples.push(sample),
|
||||
onScanFailed: (_code, message) => finish(new Error(message)) })) {
|
||||
finish(new Error('Bluetooth is unavailable.')); return
|
||||
}
|
||||
this.cancelCollection = () => { this.cancelCollection = null; clearTimeout(timer); reject(new Error('Bluetooth scan cancelled.')) }
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Utils } from "@nativescript/core";
|
||||
|
||||
import { type RawAdvertisement } from "../g2/even-advertisement";
|
||||
import { DiscoveryAggregator } from "../g2/pairing-candidates";
|
||||
export { buildAddressSet } from "./device-discovery-common";
|
||||
|
||||
declare const com: any;
|
||||
|
||||
@@ -108,53 +108,6 @@ export class DeviceDiscoveryBridge {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick one address per role from a batch of raw advertisements — the manual
|
||||
* address page's "load" helper and the flash flow's address resolution.
|
||||
*
|
||||
* Runs the batch through the same `DiscoveryAggregator` the pairing page
|
||||
* uses, so left/right come from ONE serial-joined pair (the closest complete
|
||||
* one) rather than from whichever arm of whatever pair advertised last —
|
||||
* "latest per role" silently welded together arms of two different pairs.
|
||||
* When no arm carries a serial at all (a bonded-device listing has no
|
||||
* manufacturer data), there is nothing to join on and the latest arm per side
|
||||
* is used as before.
|
||||
*/
|
||||
export function buildAddressSet(candidates: RawAdvertisement[]): DiscoveredAddressSet {
|
||||
const aggregator = new DiscoveryAggregator();
|
||||
for (const raw of candidates) aggregator.ingest(raw);
|
||||
const classified = aggregator.advertisements();
|
||||
const pairs = aggregator.pairs();
|
||||
|
||||
let left = "";
|
||||
let right = "";
|
||||
const completePair = pairs.find((pair) => pair.completeness === "complete");
|
||||
if (completePair) {
|
||||
left = completePair.left!.address;
|
||||
right = completePair.right!.address;
|
||||
} else if (classified.every((candidate) => !candidate.serial)) {
|
||||
for (const role of ["left", "right"] as const) {
|
||||
const latest = classified
|
||||
.filter((candidate) => candidate.role === role)
|
||||
.sort((a, b) => b.seenAtMs - a.seenAtMs)[0];
|
||||
if (role === "left") left = latest?.address ?? "";
|
||||
else right = latest?.address ?? "";
|
||||
}
|
||||
}
|
||||
// Arms with serials but no complete pair: leave the addresses empty. The
|
||||
// summary below names what was heard; guessing would defeat the serial join.
|
||||
|
||||
const lines = classified.map((candidate) => {
|
||||
const extras = [candidate.serial ? `serial ${candidate.serial}` : null, candidate.rssi != null ? `${candidate.rssi} dBm` : null].filter(Boolean);
|
||||
return `${candidate.role}: ${candidate.name} ${candidate.address}${extras.length ? ` (${extras.join(", ")})` : ""}`;
|
||||
});
|
||||
return {
|
||||
left,
|
||||
right,
|
||||
ring: aggregator.rings()[0]?.advertisement.address ?? "",
|
||||
summary: lines.length ? lines.join("\n") : "No matching devices found.",
|
||||
};
|
||||
}
|
||||
|
||||
function parseRawArray(json: string): RawAdvertisement[] {
|
||||
const items = JSON.parse(json) as unknown[];
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { StockConnection, StockTimeout } from '../g2/stock-connection'
|
||||
import * as p from '../g2/ble-protocol'
|
||||
import { iosBluetooth } from './ios-bluetooth'
|
||||
import type { DeviceInfo, DeviceInfoState } from './device-info-probe'
|
||||
export type { DeviceInfo, DeviceInfoState } from './device-info-probe'
|
||||
|
||||
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) }
|
||||
})
|
||||
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()
|
||||
}
|
||||
}
|
||||
}
|
||||
cancel(): void { this.link.close() }
|
||||
close(): void { this.link.close() }
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { toData, fromData } from './kotlin-data'
|
||||
declare const FaceclawCrypto: any
|
||||
export function firmwareSha256(buffer: ArrayBuffer): string { return String(FaceclawCrypto.sha256(toData(new Uint8Array(buffer)))) }
|
||||
export function writeFirmwareFile(path: string, buffer: ArrayBuffer): void {
|
||||
if (!toData(new Uint8Array(buffer)).writeToFileAtomically(path, true)) throw new Error('Could not save the verified firmware image.')
|
||||
}
|
||||
export function readFirmwareFile(path: string): Uint8Array {
|
||||
const data = NSData.dataWithContentsOfFile(path)
|
||||
if (!data) throw new Error('Could not read the prepared firmware image.')
|
||||
return fromData(data)
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
declare const com: any
|
||||
export function firmwareSha256(buffer: ArrayBuffer): string { return String(com.faceclaw.app.FaceclawFirmwareUtil.sha256Hex(buffer)) }
|
||||
export function writeFirmwareFile(path: string, buffer: ArrayBuffer): void { com.faceclaw.app.FaceclawFirmwareUtil.writeFile(path, buffer) }
|
||||
@@ -0,0 +1,83 @@
|
||||
import { Application } from '@nativescript/core'
|
||||
import { StockConnection } from '../g2/stock-connection'
|
||||
import { flashLensImage, validateFirmware } from '../g2/firmware-ota'
|
||||
import { CFW_PATCH_SET } from '../g2/firmware/cfw-patches'
|
||||
import { firmwareSha256, readFirmwareFile } from './firmware-files.ios'
|
||||
import { iosBluetooth } from './ios-bluetooth'
|
||||
import type { FlashState, FlashProgress } from './firmware-flasher'
|
||||
export type { FlashState, FlashProgress } from './firmware-flasher'
|
||||
|
||||
export class FirmwareFlasher {
|
||||
private logs = new Set<(line: string) => void>()
|
||||
private states = new Set<(state: FlashState, detail: string) => void>()
|
||||
private progresses = new Set<(value: FlashProgress) => void>()
|
||||
private completes = new Set<(success: boolean, detail: string) => void>()
|
||||
private link = new StockConnection(iosBluetooth(), line => this.log(line))
|
||||
private started = false
|
||||
private cancelled = false
|
||||
private sleeps = new Set<() => void>()
|
||||
private foregroundError = ''
|
||||
constructor(private addresses: { right: string; left: string }, private path: string) {}
|
||||
onLog(fn: (line: string) => void): () => void { this.logs.add(fn); return () => this.logs.delete(fn) }
|
||||
onStateChange(fn: (state: FlashState, detail: string) => void): () => void { this.states.add(fn); return () => this.states.delete(fn) }
|
||||
onProgress(fn: (value: FlashProgress) => void): () => void { this.progresses.add(fn); return () => this.progresses.delete(fn) }
|
||||
onComplete(fn: (success: boolean, detail: string) => void): () => void { this.completes.add(fn); return () => this.completes.delete(fn) }
|
||||
private log(line: string): void { for (const fn of this.logs) fn(line) }
|
||||
private state(state: FlashState, detail = ''): void { for (const fn of this.states) fn(state, detail) }
|
||||
start(): void { if (!this.started) { this.started = true; void this.run() } }
|
||||
private readonly backgrounded = () => {
|
||||
this.foregroundError = 'Flashing was interrupted because Faceclaw left the foreground. Keep both lenses charged, return to Faceclaw, and retry both lenses.'
|
||||
this.cancel()
|
||||
}
|
||||
private async run(): Promise<void> {
|
||||
const previousIdle = UIApplication.sharedApplication.idleTimerDisabled
|
||||
UIApplication.sharedApplication.idleTimerDisabled = true
|
||||
Application.on(Application.suspendEvent, this.backgrounded)
|
||||
let success = false, detail = ''
|
||||
try {
|
||||
this.link.check()
|
||||
if (UIApplication.sharedApplication.applicationState !== UIApplicationState.Active) throw new Error('Keep Faceclaw open on the iPhone while flashing.')
|
||||
this.state('validating')
|
||||
const image = readFirmwareFile(this.path)
|
||||
const hash = firmwareSha256(image.buffer)
|
||||
if (![CFW_PATCH_SET.outputSha256, CFW_PATCH_SET.baseSha256].includes(hash)) throw new Error('Prepared firmware failed SHA-256 verification. Prepare the firmware again before flashing.')
|
||||
const segments = validateFirmware(image)
|
||||
await this.link.resolve({ ...this.addresses, ring: '' })
|
||||
for (const role of ['left', 'right']) {
|
||||
if (role === 'right') {
|
||||
this.state('rebooting', 'Left lens done. Both lenses reboot briefly; reconnecting for the right lens.')
|
||||
await this.delay(5000)
|
||||
}
|
||||
this.state('connecting', role)
|
||||
const deadline = Date.now() + (role === 'left' ? 30_000 : 120_000)
|
||||
for (;;) {
|
||||
try { await this.link.connect(role, true); await this.link.authenticate(role); break }
|
||||
catch (error) { this.link.check(); this.link.disconnect(role); if (Date.now() >= deadline) throw error; await this.delay(2500) }
|
||||
}
|
||||
await this.delay(2500)
|
||||
this.state('flashing', role)
|
||||
await flashLensImage(this.link, role, image, segments, value => { for (const fn of this.progresses) fn(value) }, line => this.log(line), ms => this.delay(ms))
|
||||
this.link.disconnect(role)
|
||||
}
|
||||
success = true; detail = 'Both lenses flashed. Your glasses are rebooting.'
|
||||
} catch (error) {
|
||||
detail = this.foregroundError || (this.cancelled ? 'Cancelled. Retry with both lenses powered on to complete installation.' : String((error as Error).message ?? error))
|
||||
} finally {
|
||||
Application.off(Application.suspendEvent, this.backgrounded)
|
||||
UIApplication.sharedApplication.idleTimerDisabled = previousIdle
|
||||
this.link.close()
|
||||
}
|
||||
this.state(success ? 'done' : 'error', detail)
|
||||
for (const fn of this.completes) fn(success, detail)
|
||||
}
|
||||
private delay(ms: number): Promise<void> {
|
||||
this.link.check()
|
||||
return new Promise((resolve, reject) => {
|
||||
const cancel = () => { clearTimeout(timer); this.sleeps.delete(cancel); reject(new Error('Cancelled.')) }
|
||||
const timer = setTimeout(() => { this.sleeps.delete(cancel); resolve() }, ms)
|
||||
this.sleeps.add(cancel)
|
||||
})
|
||||
}
|
||||
cancel(): void { this.cancelled = true; this.link.close(); for (const cancel of [...this.sleeps]) cancel() }
|
||||
close(): void { this.cancel() }
|
||||
}
|
||||
@@ -2,18 +2,8 @@ import { Utils } from "@nativescript/core";
|
||||
|
||||
declare const com: any;
|
||||
|
||||
export type FlashState = "validating" | "connecting" | "flashing" | "rebooting" | "done" | "error";
|
||||
|
||||
export type FlashProgress = {
|
||||
lens: string;
|
||||
componentIndex: number;
|
||||
componentCount: number;
|
||||
blockIndex: number;
|
||||
blockCount: number;
|
||||
/** Bytes flashed so far across the whole lens image — the size-weighted progress signal. */
|
||||
bytesSent: number;
|
||||
bytesTotal: number;
|
||||
};
|
||||
import type { FlashState, FlashProgress } from "../g2/firmware-types";
|
||||
export type { FlashState, FlashProgress } from "../g2/firmware-types";
|
||||
|
||||
/**
|
||||
* TS wrapper around the native FaceclawFirmwareFlasher — streams a verified
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import { StockConnection } from '../g2/stock-connection'
|
||||
import { createFlashPrompt, flashPromptSelection } from '../g2/flash-prompt-protocol'
|
||||
import * as p from '../g2/ble-protocol'
|
||||
import { iosBluetooth } from './ios-bluetooth'
|
||||
import type { FlashPromptBattery, FlashPromptState } from './flash-prompt-communicator'
|
||||
export type { FlashPromptBattery, FlashPromptState } from './flash-prompt-communicator'
|
||||
|
||||
export class FlashPromptCommunicator {
|
||||
private logs = new Set<(line: string) => void>()
|
||||
private states = new Set<(state: FlashPromptState, detail: string) => void>()
|
||||
private results = new Set<(approved: boolean) => void>()
|
||||
private batteries = new Set<(battery: FlashPromptBattery) => void>()
|
||||
private link = new StockConnection(iosBluetooth(), line => { for (const fn of this.logs) fn(line) })
|
||||
private closed = false
|
||||
private started = false
|
||||
private heartbeat: ReturnType<typeof setInterval> | null = null
|
||||
private stopSelection: (() => void) | null = null
|
||||
constructor(private addresses: { right: string; left: string }, private warning: string, private options?: { skipPrompt?: boolean }) {}
|
||||
onLog(fn: (line: string) => void): () => void { this.logs.add(fn); return () => this.logs.delete(fn) }
|
||||
onStateChange(fn: (state: FlashPromptState, detail: string) => void): () => void { this.states.add(fn); return () => this.states.delete(fn) }
|
||||
onResult(fn: (approved: boolean) => void): () => void { this.results.add(fn); return () => this.results.delete(fn) }
|
||||
onBattery(fn: (battery: FlashPromptBattery) => void): () => void { this.batteries.add(fn); return () => this.batteries.delete(fn) }
|
||||
private state(state: FlashPromptState, detail = ''): void { for (const fn of this.states) fn(state, detail) }
|
||||
start(): void { if (!this.started) { this.started = true; void this.run() } }
|
||||
private async run(): Promise<void> {
|
||||
try {
|
||||
this.state('connecting')
|
||||
await this.link.resolve({ ...this.addresses, ring: '' })
|
||||
// Complete pairing for one peripheral before starting the other.
|
||||
for (const role of ['right', 'left']) {
|
||||
await this.link.connect(role)
|
||||
if (role === 'right') this.state('connected')
|
||||
await this.link.authenticate(role)
|
||||
}
|
||||
await this.link.request('right', p.SID.launch, p.prelude, 3500, 156)
|
||||
if (!this.options?.skipPrompt) {
|
||||
// Listen before creating the page: an immediate tap may precede its ACK.
|
||||
const selection = this.selection()
|
||||
// Attach a rejection handler immediately, even while create-page is pending.
|
||||
void selection.catch(() => {})
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
try { await this.link.request('right', p.SID.hub, magic => createFlashPrompt(magic, this.warning)); break }
|
||||
catch (error) { this.link.check(); if (attempt) throw error }
|
||||
}
|
||||
this.state('prompting')
|
||||
this.heartbeat = setInterval(() => {
|
||||
void this.link.write('right', p.SID.hub, p.heartbeat(this.link.nextMagic())).catch(error => {
|
||||
if (!this.closed) this.state('error', String(error.message ?? error))
|
||||
this.close()
|
||||
})
|
||||
}, 4000)
|
||||
const approved = await selection
|
||||
this.stopHeartbeat()
|
||||
// Stock shutdown returns the glasses to their normal UI before OTA.
|
||||
await this.link.write('right', p.SID.hub, p.concat(p.integer(1, 9), p.integer(2, this.link.nextMagic()), p.bytes(11, p.integer(1, 0))))
|
||||
if (!approved) { for (const fn of this.results) fn(false); return }
|
||||
}
|
||||
this.state('battery')
|
||||
const battery: FlashPromptBattery = { right: null, left: null }
|
||||
for (const role of ['right', 'left'] as const) {
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
try {
|
||||
const message = await this.link.request(role, p.SID.settings, p.settingsQuery)
|
||||
const values = p.readBytes(message.payload, 4), value = values ? p.readInteger(values, 12, -1) : -1
|
||||
if (value >= 0 && value <= 100) { battery[role] = value; break }
|
||||
} catch (error) { this.link.check() }
|
||||
}
|
||||
}
|
||||
for (const fn of this.batteries) fn(battery)
|
||||
for (const fn of this.results) fn(true)
|
||||
} catch (error) { if (!this.closed) this.state('error', String((error as Error).message ?? error)) }
|
||||
finally { this.close() }
|
||||
}
|
||||
private selection(): Promise<boolean> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const cleanup = () => { clearTimeout(timer); off(); this.stopSelection = null }
|
||||
const off = this.link.onMessage((role, message) => {
|
||||
const result = role === 'right' ? flashPromptSelection(message) : null
|
||||
if (result !== null) { cleanup(); resolve(result) }
|
||||
})
|
||||
const timer = setTimeout(() => { cleanup(); reject(new Error('No response from the glasses.')) }, 120_000)
|
||||
this.stopSelection = () => { cleanup(); reject(new Error('Cancelled.')) }
|
||||
})
|
||||
}
|
||||
private stopHeartbeat(): void { if (this.heartbeat) clearInterval(this.heartbeat); this.heartbeat = null }
|
||||
cancel(): void { this.close() }
|
||||
close(): void { this.closed = true; this.stopHeartbeat(); this.stopSelection?.(); this.link.close() }
|
||||
}
|
||||
Reference in new issue
Block a user