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
@@ -1,4 +1,5 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
@interface FaceclawCrypto : NSObject
|
||||
+ (NSString *)hmacSha256:(NSString *)secret message:(NSString *)message;
|
||||
+ (NSString *)sha256:(NSData *)data;
|
||||
@end
|
||||
@@ -9,4 +9,11 @@
|
||||
CCHmac(kCCHmacAlgSHA256, key.bytes, key.length, data.bytes, data.length, digest);
|
||||
return [[NSData dataWithBytes:digest length:sizeof(digest)] base64EncodedStringWithOptions:0];
|
||||
}
|
||||
+ (NSString *)sha256:(NSData *)data {
|
||||
unsigned char digest[CC_SHA256_DIGEST_LENGTH];
|
||||
CC_SHA256(data.bytes, (CC_LONG)data.length, digest);
|
||||
NSMutableString *hex = [NSMutableString stringWithCapacity:64];
|
||||
for (NSUInteger i = 0; i < sizeof(digest); i++) [hex appendFormat:@"%02x", digest[i]];
|
||||
return hex;
|
||||
}
|
||||
@end
|
||||
+151
-2
@@ -1,3 +1,150 @@
|
||||
@import '@nativescript/theme/css/core.css';
|
||||
|
||||
.pairing-instructions {
|
||||
color: #555555;
|
||||
font-size: 14;
|
||||
}
|
||||
|
||||
.pairing-status {
|
||||
font-size: 14;
|
||||
margin-left: 8;
|
||||
}
|
||||
|
||||
.pairing-section {
|
||||
font-size: 16;
|
||||
font-weight: bold;
|
||||
margin-bottom: 4;
|
||||
}
|
||||
|
||||
.pairing-empty {
|
||||
color: #777777;
|
||||
font-size: 14;
|
||||
padding: 8 0;
|
||||
}
|
||||
|
||||
.pairing-row {
|
||||
background-color: #f4f4f4;
|
||||
border-color: #dddddd;
|
||||
border-width: 1;
|
||||
border-radius: 10;
|
||||
padding: 10;
|
||||
margin-bottom: 8;
|
||||
}
|
||||
|
||||
.pairing-row-selected {
|
||||
background-color: #e6f0ff;
|
||||
border-color: #3b6fd6;
|
||||
}
|
||||
|
||||
.pairing-row-incomplete {
|
||||
background-color: #fafafa;
|
||||
border-color: #e6e6e6;
|
||||
}
|
||||
|
||||
.pairing-art {
|
||||
vertical-align: center;
|
||||
}
|
||||
|
||||
.pairing-title {
|
||||
font-size: 16;
|
||||
font-weight: bold;
|
||||
color: #222222;
|
||||
}
|
||||
|
||||
.pairing-badge {
|
||||
font-size: 11;
|
||||
font-weight: bold;
|
||||
color: #2a5bc4;
|
||||
background-color: #dbe6fb;
|
||||
border-radius: 9;
|
||||
padding: 1 7;
|
||||
}
|
||||
|
||||
.pairing-variant {
|
||||
font-size: 13;
|
||||
font-weight: bold;
|
||||
color: #333333;
|
||||
}
|
||||
|
||||
.pairing-proximity {
|
||||
font-size: 12;
|
||||
color: #666666;
|
||||
}
|
||||
|
||||
.pairing-proximity-immediate {
|
||||
color: #2a5bc4;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.pairing-serial {
|
||||
font-size: 12;
|
||||
color: #666666;
|
||||
font-family: monospace;
|
||||
}
|
||||
|
||||
.pairing-arms {
|
||||
font-size: 12;
|
||||
color: #444444;
|
||||
}
|
||||
|
||||
.pairing-warning {
|
||||
font-size: 12;
|
||||
color: #a33a1f;
|
||||
margin-top: 4;
|
||||
}
|
||||
|
||||
.pairing-swatch-label {
|
||||
font-size: 11;
|
||||
color: #555555;
|
||||
}
|
||||
|
||||
.pairing-chevron {
|
||||
font-size: 22;
|
||||
color: #444444;
|
||||
margin-left: 6;
|
||||
}
|
||||
|
||||
.pairing-selection {
|
||||
background-color: #eef4ff;
|
||||
border-radius: 10;
|
||||
padding: 10;
|
||||
}
|
||||
|
||||
Button.pairing-link {
|
||||
background-color: transparent;
|
||||
color: #2a5bc4;
|
||||
font-size: 14;
|
||||
border-width: 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Permissions screen (phone-ui/permissions-page). Cards reuse the pairing-row
|
||||
* / pairing-title / pairing-badge look above; these add the explanation body
|
||||
* and the already-granted checkmark.
|
||||
*/
|
||||
.permissions-description {
|
||||
font-size: 13;
|
||||
color: #555555;
|
||||
margin-top: 2;
|
||||
}
|
||||
|
||||
.permissions-check {
|
||||
font-size: 24;
|
||||
color: #2e7d32;
|
||||
margin-left: 10;
|
||||
}
|
||||
|
||||
/* Continue with required permissions still missing: looks disabled but stays
|
||||
* tappable (the tap raises an are-you-sure prompt instead of being ignored). */
|
||||
Button.permissions-primary-dimmed {
|
||||
opacity: 0.45;
|
||||
}
|
||||
|
||||
|
||||
.body-text { font-size: 18; }
|
||||
.h1 { font-size: 28; font-weight: bold; }
|
||||
.footer-link { color: #285c45; padding: 4 8; text-decoration: underline; }
|
||||
|
||||
Page {
|
||||
background-color: #f5f5f2;
|
||||
color: #202820;
|
||||
@@ -7,6 +154,8 @@ Button {
|
||||
background-color: #285c45;
|
||||
color: #ffffff;
|
||||
border-radius: 12;
|
||||
padding: 16;
|
||||
font-size: 17;
|
||||
padding: 12 8;
|
||||
margin-left: 4;
|
||||
margin-right: 4;
|
||||
font-size: 15;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Application } from '@nativescript/core'
|
||||
import { Application, Frame } from '@nativescript/core'
|
||||
import { runKotlinBridgeSmokeTest } from './native/kotlin-bridge'
|
||||
declare const FaceclawConfigPort: any
|
||||
declare const __DEV__: boolean;
|
||||
@@ -7,6 +7,10 @@ if (__DEV__) runKotlinBridgeSmokeTest()
|
||||
|
||||
// Apply transferred preferences before settings getters or app workers load.
|
||||
FaceclawConfigPort.processPendingRequest()
|
||||
const { createMainPage } = require('./phone-ui/main-page.ios') as typeof import('./phone-ui/main-page.ios')
|
||||
|
||||
Application.run({ create: createMainPage })
|
||||
require('./phone-ui/onboarding-register.ios')
|
||||
const { hasCompletedOnboarding } = require('./phone-ui/onboarding-state') as typeof import('./phone-ui/onboarding-state')
|
||||
Application.run({ create: () => {
|
||||
const frame = new Frame()
|
||||
frame.navigate({ moduleName: hasCompletedOnboarding() ? 'phone-ui/main-page' : 'phone-ui/onboarding-page' })
|
||||
return frame
|
||||
} })
|
||||
@@ -23,7 +23,7 @@ import { fetchWithUserAgent } from "../util/http";
|
||||
import { bytesToHex, hexToBytes as hexToBytesLenient } from "../util/hex-util";
|
||||
import { EvenHubFont } from "../graphics/evenhub-font";
|
||||
|
||||
declare const com: any;
|
||||
import { firmwareSha256, writeFirmwareFile } from "../native/firmware-files";
|
||||
|
||||
// The CDN names firmware files by MD5. This must be the image whose SHA-256 is
|
||||
// CFW_PATCH_SET.baseSha256 — keep it in sync with FW_URL in g2flash/build_cfw.sh
|
||||
@@ -281,12 +281,12 @@ function tightBuffer(bytes: Uint8Array): ArrayBuffer {
|
||||
return bytes.slice().buffer;
|
||||
}
|
||||
|
||||
/** SHA-256 hex digest of an ArrayBuffer, via Android's MessageDigest. */
|
||||
/** SHA-256 hex digest using the platform's native crypto implementation. */
|
||||
function sha256Hex(buffer: ArrayBuffer): string {
|
||||
return String(com.faceclaw.app.FaceclawFirmwareUtil.sha256Hex(buffer));
|
||||
return firmwareSha256(buffer);
|
||||
}
|
||||
|
||||
/** Write an ArrayBuffer's bytes to `path`, via a native FileChannel write. */
|
||||
/** Persist the verified image using the platform's native file API. */
|
||||
function writeFile(path: string, buffer: ArrayBuffer): void {
|
||||
com.faceclaw.app.FaceclawFirmwareUtil.writeFile(path, buffer);
|
||||
writeFirmwareFile(path, buffer);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
/** Stock EVENOTA validation and transfer, matching Android's flasher/g2flash.py. */
|
||||
import { StockConnection, OTA_WRITE, OTA_NOTIFY } from './stock-connection'
|
||||
import { concat } from './ble-protocol'
|
||||
import type { FlashProgress } from './firmware-types'
|
||||
|
||||
export type FirmwareSegment = { offset: number; size: number; name: string }
|
||||
const CRC_TABLE = Array.from({ length: 256 }, (_, b) => {
|
||||
let c = b << 24
|
||||
for (let i = 0; i < 8; i++) c = c & 0x80000000 ? (c << 1) ^ 0x1edc6f41 : c << 1
|
||||
return c >>> 0
|
||||
})
|
||||
export function firmwareCrc(data: Uint8Array): number {
|
||||
let crc = 0
|
||||
for (const byte of data) crc = (crc << 8) ^ CRC_TABLE[((crc >>> 24) ^ byte) & 255]
|
||||
return crc >>> 0
|
||||
}
|
||||
export function validateFirmware(image: Uint8Array): FirmwareSegment[] {
|
||||
const u32 = (offset: number) => {
|
||||
if (offset < 0 || offset + 4 > image.length) throw new Error('Firmware header is truncated.')
|
||||
return new DataView(image.buffer, image.byteOffset, image.byteLength).getUint32(offset, true)
|
||||
}
|
||||
if (image.length < 0x40) throw new Error('File is too small to be a firmware image.')
|
||||
const count = u32(8)
|
||||
if (count < 5 || count > 6 || 0x40 + count * 16 > image.length) throw new Error('Expected 5–6 firmware components.')
|
||||
const segments: FirmwareSegment[] = []
|
||||
for (let i = 0; i < count; i++) {
|
||||
const toc = 0x40 + i * 16, offset = u32(toc + 4)
|
||||
if (offset < 0x40 + count * 16 || offset + 128 > image.length) throw new Error('Firmware component header is out of bounds.')
|
||||
const size = u32(offset + 8), end = offset + 128 + size
|
||||
if (!size || end > image.length) throw new Error('Firmware component payload is truncated.')
|
||||
if (segments.some(s => offset < s.offset + 128 + s.size && s.offset < end)) throw new Error('Firmware components overlap.')
|
||||
const nameBytes = image.subarray(offset + 48, offset + 128)
|
||||
const name = String.fromCharCode(...nameBytes.subarray(0, nameBytes.indexOf(0) < 0 ? 80 : nameBytes.indexOf(0)))
|
||||
const crc = firmwareCrc(image.subarray(offset + 128, end))
|
||||
if (crc !== u32(toc + 12) || crc !== u32(offset + 12)) throw new Error(`Component ${name} CRC32C is stale (image not checksum-fixed).`)
|
||||
segments.push({ offset, size, name })
|
||||
}
|
||||
const mains = segments.filter(s => s.name === 'ota/s200_firmware_ota.bin')
|
||||
if (mains.length !== 1) throw new Error('Required main firmware component is missing or duplicated.')
|
||||
const main = mains[0], payload = main.offset + 128
|
||||
if (main.size < 32 || u32(payload + 0x14) !== 0x00438000 || (u32(payload) & 0xffffff) !== main.size)
|
||||
throw new Error('Main-app preamble load address or length is invalid.')
|
||||
if (0x00438000 + main.size - 32 > 0x007f0000) throw new Error('Main-app exceeds the safe MRAM ceiling — refusing to flash.')
|
||||
return segments
|
||||
}
|
||||
|
||||
export async function flashLensImage(link: StockConnection, role: string, image: Uint8Array, segments: FirmwareSegment[],
|
||||
progress: (value: FlashProgress) => void, log: (line: string) => void,
|
||||
delay: (ms: number) => Promise<void>): Promise<void> {
|
||||
let sequence = 0
|
||||
const ctrl = async (op: number, payload = new Uint8Array(), data?: Uint8Array): Promise<number> => {
|
||||
sequence = (sequence + 1) & 255
|
||||
const message = await link.exchange(role, 0xc0, concat(new Uint8Array([op]), payload),
|
||||
message => message.command === op, data ? 4000 : 8000, OTA_WRITE, OTA_NOTIFY, 0, sequence, data)
|
||||
return message.payload[1]
|
||||
}
|
||||
const accepted = (status: number) => [0, 8, 9].includes(status)
|
||||
const begin = await ctrl(0)
|
||||
if (!accepted(begin)) throw new Error(`OTA BEGIN rejected (status ${begin}).`)
|
||||
const total = segments.reduce((sum, segment) => sum + segment.size, 0)
|
||||
let before = 0
|
||||
for (const [index, segment] of segments.entries()) {
|
||||
let verified = false, failure: unknown
|
||||
for (let attempt = 0; attempt < 3; attempt++) {
|
||||
link.check()
|
||||
if (attempt) { log(`${segment.name}: re-flash attempt ${attempt + 1}/3`); await delay(1500) }
|
||||
try {
|
||||
const status = await ctrl(1, image.slice(segment.offset, segment.offset + 128))
|
||||
if (status !== 0) throw new Error(`FILE_CHECK rejected (status ${status}).`)
|
||||
const blocks = Math.ceil(segment.size / 4096)
|
||||
for (let block = 0; block < blocks; block++) {
|
||||
const start = segment.offset + 128 + block * 4096
|
||||
const data = image.slice(start, Math.min(start + 4096, segment.offset + 128 + segment.size))
|
||||
let ok = false
|
||||
for (let retry = 0; retry < 3; retry++) {
|
||||
if (await ctrl(2, new Uint8Array(), data) === 0) { ok = true; break }
|
||||
}
|
||||
if (!ok) throw new Error(`Block ${block + 1} rejected three times.`)
|
||||
if (block % 20 === 0 || block === blocks - 1)
|
||||
progress({ lens: role, componentIndex: index + 1, componentCount: segments.length, blockIndex: block + 1,
|
||||
blockCount: blocks, bytesSent: before + Math.min((block + 1) * 4096, segment.size), bytesTotal: total })
|
||||
}
|
||||
const end = await ctrl(3)
|
||||
if (!accepted(end)) throw new Error(`END verification failed (status ${end}).`)
|
||||
log(`${role} ${segment.name}: END verify OK (status ${end})`); verified = true; break
|
||||
} catch (error) { link.check(); failure = error }
|
||||
}
|
||||
if (!verified) throw new Error(`Component ${segment.name} failed after 3 attempts: ${failure}`)
|
||||
before += segment.size
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
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;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { bytes, concat, integer, readBytes, readInteger, readString, type ProtocolMessage } from './ble-protocol'
|
||||
const text = (field: number, value: string) => bytes(field, new Uint8Array(Array.from(value, ch => ch.charCodeAt(0))))
|
||||
export function createFlashPrompt(magic: number, warning: string): Uint8Array {
|
||||
const geometry = (y: number, height: number, id: number, name: string) => concat(
|
||||
integer(1, 0), integer(2, y), integer(3, 280), integer(4, height), integer(9, id), text(10, name))
|
||||
const list = concat(geometry(150, 120, 2, 'flashmenu'), bytes(11, concat(integer(1, 2), integer(3, 1), text(4, 'No, cancel'), text(4, 'Yes, flash'))), integer(12, 1))
|
||||
const label = concat(geometry(0, 130, 1, 'flashwarn'), text(12, warning))
|
||||
return concat(integer(1, 0), integer(2, magic), bytes(3, concat(integer(1, 2), bytes(2, list), bytes(3, label), integer(5, 10000))))
|
||||
}
|
||||
export function flashPromptSelection(message: ProtocolMessage): boolean | null {
|
||||
if (message.sid !== 0xe0 || ![1, 6].includes(message.flag)) return null
|
||||
const event = readBytes(message.payload, 13), list = event && readBytes(event, 1)
|
||||
if (!list || readString(list, 2) !== 'flashmenu' || readInteger(list, 5, 0) !== 0) return null
|
||||
const index = readInteger(list, 4, -1), name = readString(list, 3).toLowerCase()
|
||||
if (index === 1 || name.startsWith('yes')) return true
|
||||
if (index === 0 || name.startsWith('no')) return false
|
||||
return null
|
||||
}
|
||||
@@ -130,7 +130,7 @@ export class GlassesSession {
|
||||
this.applySettings(settings)
|
||||
const firmware = { leftVersion: this.state.leftVersion, rightVersion: this.state.rightVersion, extension: this.state.capabilities }
|
||||
if (!hasCompatibleFirmware(firmware))
|
||||
throw new Error((firmwareIncompatibilityMessage(firmware) || `The glasses must report Faceclaw firmware revision ${REQUIRED_FACECLAW_FIRMWARE_VERSION} or newer.`) + ' Flashing remains available on Android.')
|
||||
throw new Error((firmwareIncompatibilityMessage(firmware) || `The glasses must report Faceclaw firmware revision ${REQUIRED_FACECLAW_FIRMWARE_VERSION} or newer.`) + ' Use Devices → Check firmware to install it.')
|
||||
this.update('connecting', 'Starting glasses display…')
|
||||
await this.request('right', protocol.SID.launch, () => protocol.prelude(), 'App launch', 3500, 0x20, 156)
|
||||
await this.lease(true)
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
import * as p from './ble-protocol'
|
||||
import type { SessionTransport, SessionAddresses, TransportEvent } from './glasses-session'
|
||||
import { hexToBytes } from '../util/hex-util'
|
||||
|
||||
declare function setTimeout(callback: () => void, ms: number): number
|
||||
declare function clearTimeout(id: number): void
|
||||
|
||||
export const OTA_WRITE = '00002760-08c2-11e1-9073-0e8ac72e0001'
|
||||
export const OTA_NOTIFY = '00002760-08c2-11e1-9073-0e8ac72e0002'
|
||||
export class StockTimeout extends Error {}
|
||||
type Waiter = { role: string; characteristic: string; match: (message: p.ProtocolMessage) => boolean;
|
||||
resolve: (message: p.ProtocolMessage) => void; reject: (error: Error) => void; timer: ReturnType<typeof setTimeout> | null }
|
||||
|
||||
/** Exclusive, short-lived stock-protocol connection for onboarding/OTA. No display pump. */
|
||||
export class StockConnection {
|
||||
ids: Record<string, string> = {}
|
||||
private limits: Record<string, number> = {}
|
||||
private receiver = new p.MessageReceiver()
|
||||
private waiters = new Set<Waiter>()
|
||||
private listeners = new Set<(role: string, message: p.ProtocolMessage) => void>()
|
||||
private lost = new Set<string>()
|
||||
private writes = new Map<string, Promise<void>>()
|
||||
private closed = false
|
||||
private magic = 0x60
|
||||
private sequence = 0
|
||||
private off: () => void
|
||||
constructor(private transport: SessionTransport, private log: (line: string) => void = () => {}) {
|
||||
this.off = transport.onEvent(event => this.receive(event))
|
||||
}
|
||||
check(): void { if (this.closed) throw new Error('Cancelled.') }
|
||||
isConnected(role: string): boolean { return !this.closed && !!this.limits[role] && !this.lost.has(role) }
|
||||
async resolve(addresses: SessionAddresses): Promise<void> {
|
||||
this.ids = await this.transport.resolveDevices(addresses); this.check()
|
||||
}
|
||||
async connect(role: string, ota = false): Promise<void> {
|
||||
this.check(); this.lost.delete(role)
|
||||
const id = this.ids[role]
|
||||
if (!id) throw new Error(`No ${role} lens configured.`)
|
||||
const details = await this.transport.connect(id)
|
||||
if (this.closed) { this.transport.disconnect(id); this.check() }
|
||||
this.limits[role] = details.maxWrite
|
||||
for (const characteristic of [p.G2_WRITE, p.G2_NOTIFY, ...(ota ? [OTA_WRITE, OTA_NOTIFY] : [])])
|
||||
if (!details.characteristics.includes(characteristic)) throw new Error(`${role} lens is missing ${ota ? 'firmware update' : 'G2'} characteristics.`)
|
||||
await this.transport.subscribe(id, p.G2_NOTIFY); this.check()
|
||||
if (ota) { await this.transport.subscribe(id, OTA_NOTIFY); this.check() }
|
||||
}
|
||||
nextMagic(): number { this.magic = this.magic >= 0x7f ? 0x60 : this.magic + 1; return this.magic }
|
||||
async authenticate(role: string): Promise<void> {
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
const magic = this.nextMagic()
|
||||
try {
|
||||
await this.exchange(role, p.SID.auth, p.authentication(magic),
|
||||
message => p.authenticationSucceeded(message, magic), 30_000, p.G2_WRITE, p.G2_NOTIFY, 0)
|
||||
this.log(`Security authentication complete: ${role} lens`); return
|
||||
} catch (error) { this.check(); if (!(error instanceof StockTimeout) || attempt === 1) throw error }
|
||||
}
|
||||
}
|
||||
request(role: string, sid: number, build: (magic: number) => Uint8Array, timeout = 3500, fixedMagic?: number): Promise<p.ProtocolMessage> {
|
||||
const magic = fixedMagic ?? this.nextMagic()
|
||||
return this.exchange(role, sid, build(magic), message => message.sid === sid && message.magic === magic && ![1, 6].includes(message.flag), timeout)
|
||||
}
|
||||
write(role: string, sid: number, payload: Uint8Array, characteristic = p.G2_WRITE, flag = 0x20, sequence = ++this.sequence): Promise<void> {
|
||||
// Keep a fragmented control message together when the prompt heartbeat
|
||||
// overlaps a settings request or shutdown.
|
||||
const pending = (this.writes.get(role) ?? Promise.resolve()).catch(() => {}).then(async () => {
|
||||
this.check()
|
||||
for (const frame of p.frameMessage(payload, sid, flag, sequence, this.limits[role])) {
|
||||
this.check()
|
||||
if (this.lost.has(role)) throw new Error(`Lost connection to the ${role} lens.`)
|
||||
await this.transport.write(this.ids[role], characteristic, frame)
|
||||
}
|
||||
this.check()
|
||||
if (this.lost.has(role)) throw new Error(`Lost connection to the ${role} lens.`)
|
||||
})
|
||||
this.writes.set(role, pending)
|
||||
return pending
|
||||
}
|
||||
exchange(role: string, sid: number, payload: Uint8Array, match: Waiter['match'], timeout: number,
|
||||
write = p.G2_WRITE, notify = p.G2_NOTIFY, flag = 0x20, sequence?: number, data?: Uint8Array): Promise<p.ProtocolMessage> {
|
||||
this.check()
|
||||
return new Promise((resolve, reject) => {
|
||||
let written = false, reply: p.ProtocolMessage | null = null
|
||||
const waiter: Waiter = { role, characteristic: notify, match,
|
||||
resolve: message => { reply = message; if (written) resolve(message) }, reject,
|
||||
timer: null }
|
||||
this.waiters.add(waiter)
|
||||
void (async () => {
|
||||
await this.write(role, sid, payload, write, flag, sequence)
|
||||
if (data) await this.write(role, 0xc1, data, write, flag, sequence)
|
||||
this.check()
|
||||
if (!reply && !this.waiters.has(waiter)) return
|
||||
written = true
|
||||
if (reply) resolve(reply)
|
||||
else waiter.timer = setTimeout(() => {
|
||||
this.waiters.delete(waiter)
|
||||
reject(new StockTimeout(`No response from the ${role} lens (0x${sid.toString(16)}).`))
|
||||
}, timeout)
|
||||
})().catch(error => { this.waiters.delete(waiter); if (waiter.timer !== null) clearTimeout(waiter.timer); reject(error) })
|
||||
})
|
||||
}
|
||||
|
||||
onMessage(listener: (role: string, message: p.ProtocolMessage) => void): () => void {
|
||||
this.listeners.add(listener); return () => this.listeners.delete(listener)
|
||||
}
|
||||
private receive(event: TransportEvent): void {
|
||||
if (this.closed) return
|
||||
const role = Object.keys(this.ids).find(role => this.ids[role] === event.identifier)
|
||||
if (!role) return
|
||||
if (event.kind === 'disconnected') {
|
||||
this.lost.add(role)
|
||||
for (const waiter of [...this.waiters]) if (waiter.role === role) {
|
||||
this.waiters.delete(waiter); if (waiter.timer !== null) clearTimeout(waiter.timer); waiter.reject(new Error(`Lost connection to the ${role} lens.`))
|
||||
}
|
||||
return
|
||||
}
|
||||
if (event.kind !== 'notification' || !event.data || ![p.G2_NOTIFY, OTA_NOTIFY].includes(event.characteristic!)) return
|
||||
try {
|
||||
const data = hexToBytes(event.data)
|
||||
const messages = event.characteristic === OTA_NOTIFY ? decodeOtaAcks(data) : this.receiver.receive(event.identifier!, data)
|
||||
for (const message of messages) {
|
||||
for (const waiter of [...this.waiters]) if (waiter.role === role && waiter.characteristic === event.characteristic && waiter.match(message)) {
|
||||
this.waiters.delete(waiter); if (waiter.timer !== null) clearTimeout(waiter.timer); waiter.resolve(message)
|
||||
}
|
||||
if (event.characteristic === p.G2_NOTIFY) for (const listener of this.listeners) listener(role, message)
|
||||
}
|
||||
} catch (error) { this.log(`Ignored malformed onboarding notification: ${error}`) }
|
||||
}
|
||||
disconnect(role: string): void { this.lost.add(role); if (this.ids[role]) this.transport.disconnect(this.ids[role]); this.receiver.clear() }
|
||||
close(): void {
|
||||
if (this.closed) return
|
||||
this.closed = true; this.off(); this.transport.stopScan()
|
||||
for (const waiter of this.waiters) { if (waiter.timer !== null) clearTimeout(waiter.timer); waiter.reject(new Error('Cancelled.')) }
|
||||
this.waiters.clear(); this.listeners.clear()
|
||||
for (const role of Object.keys(this.ids)) this.disconnect(role)
|
||||
}
|
||||
}
|
||||
|
||||
/** OTA ACKs are raw opcode/status bytes, not protobuf; validate the aa21 CRC envelope. */
|
||||
export function decodeOtaAcks(data: Uint8Array): p.ProtocolMessage[] {
|
||||
const messages: p.ProtocolMessage[] = []
|
||||
for (let offset = 0; offset + 8 <= data.length;) {
|
||||
const n = data[offset + 3], end = offset + 8 + n
|
||||
if (end > data.length) break
|
||||
if (data[offset] === 0xaa && [0x12, 0x21].includes(data[offset + 1]) && data[offset + 4] === 1 && data[offset + 5] === 1 && n >= 4) {
|
||||
const payload = data.slice(offset + 8, end - 2)
|
||||
if (p.crc16(payload) === (data[end - 2] | data[end - 1] << 8))
|
||||
messages.push({ sid: data[offset + 6], flag: data[offset + 7], payload, command: payload[0], magic: -1 })
|
||||
}
|
||||
offset = end
|
||||
}
|
||||
return messages
|
||||
}
|
||||
@@ -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() }
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { NavigatedData, Page } from "@nativescript/core";
|
||||
|
||||
import { ConfigViewModel } from "./config-view-model";
|
||||
|
||||
export function navigatingTo(args: NavigatedData): void {
|
||||
const page = args.object as Page;
|
||||
// Preserve the model across back-navigation (returning from the firmware
|
||||
// check page) so the onboarding "Continue" flow isn't lost.
|
||||
if (!page.bindingContext) {
|
||||
const context = (args.context as { onboarding?: boolean } | undefined) ?? undefined;
|
||||
page.bindingContext = new ConfigViewModel({ onboarding: context?.onboarding ?? false });
|
||||
}
|
||||
}
|
||||
@@ -1,68 +1 @@
|
||||
import { Button, Color, GridLayout, Label, Page, ScrollView, StackLayout, TextField } from '@nativescript/core'
|
||||
import { loadDeviceAddresses, normalizeMacAddress, saveDeviceAddresses } from '../g2/device-addresses'
|
||||
import { deviceAddressError, type IosDevice } from '../g2/ios-peripheral-identity'
|
||||
import { iosBluetooth } from '../native/ios-bluetooth'
|
||||
|
||||
export function createConfigureDevicesPage(): Page {
|
||||
const page = new Page(); page.actionBarHidden = true
|
||||
const root = new GridLayout(); root.rows = 'auto,*,auto'; root.padding = 16; page.content = root
|
||||
const title = new Label(); title.text = 'Configure devices'; title.fontSize = 24; title.fontWeight = 'bold'; root.addChild(title)
|
||||
const scroll = new ScrollView(); GridLayout.setRow(scroll, 1); root.addChild(scroll)
|
||||
const form = new StackLayout(); scroll.content = form
|
||||
const text = (value: string, size = 15) => {
|
||||
const label = new Label(); label.text = value; label.fontSize = size; label.textWrap = true; label.marginTop = 12; form.addChild(label); return label
|
||||
}
|
||||
text('Enter the G2 arm MAC addresses and optional R1 ring address. Scan once so this iPhone can find the matching devices. Saving does not connect.')
|
||||
const stored = loadDeviceAddresses()
|
||||
const fields = {} as Record<'left' | 'right' | 'ring', TextField>
|
||||
for (const role of ['right', 'left', 'ring'] as const) {
|
||||
text(role === 'ring' ? 'R1 ring MAC (optional)' : `${role === 'left' ? 'Left' : 'Right'} arm MAC`)
|
||||
const field = new TextField(); field.text = stored[role]; field.hint = 'AA:BB:CC:DD:EE:FF'
|
||||
field.autocorrect = false; field.autocapitalizationType = 'allcharacters'; field.fontSize = 18
|
||||
field.padding = 10; field.backgroundColor = new Color('#ffffff'); field.accessibilityLabel = `${role} MAC address`
|
||||
field.accessibilityIdentifier = `device-address-${role}`; form.addChild(field); fields[role] = field
|
||||
}
|
||||
const status = text('Addresses are saved only when you tap Save.'); status.color = new Color('#285c45')
|
||||
const button = (label: string, action: () => void) => {
|
||||
const view = new Button(); view.text = label; view.fontSize = 15; view.marginTop = 12; view.on('tap', action); return view
|
||||
}
|
||||
let off: (() => void) | null = null
|
||||
let closed = false
|
||||
const found = new StackLayout()
|
||||
const rows = new Map<string, Button>()
|
||||
const showDevice = (device: IosDevice) => {
|
||||
if (device.connectable === false) return
|
||||
let row = rows.get(device.address)
|
||||
if (!row) {
|
||||
row = button('', () => { fields[device.role].text = device.address; status.text = `${device.role} address selected. Tap Save to keep it.` })
|
||||
row.textWrap = true; row.fontSize = 13; rows.set(device.address, row); found.addChild(row)
|
||||
}
|
||||
row.text = `${device.role === 'ring' ? 'Ring' : device.role === 'left' ? 'Left arm' : 'Right arm'} · ${device.address}\n${device.serial || device.name} · ${device.rssi ?? '?'} dBm`
|
||||
}
|
||||
const scan = button('Scan for devices', () => {
|
||||
for (const field of Object.values(fields)) field.dismissSoftInput()
|
||||
const ble = iosBluetooth()
|
||||
off?.(); off = ble.onEvent(event => {
|
||||
if (closed) return
|
||||
if (event.kind === 'device' && 'device' in event) showDevice(event.device)
|
||||
if (event.kind === 'scan-stopped') { scan.isEnabled = true; status.text = rows.size ? 'Tap a device to fill its address, then Save.' : 'No matching devices found. Wake the glasses and disconnect other apps, then scan again.' }
|
||||
})
|
||||
rows.clear(); found.removeChildren(); scan.isEnabled = false; status.text = 'Scanning… Allow Bluetooth if iOS asks.'
|
||||
void ble.startScan().catch(error => { if (!closed) { status.text = String(error.message ?? error); scan.isEnabled = true } })
|
||||
})
|
||||
form.addChild(scan); form.addChild(found)
|
||||
const footer = new GridLayout(); footer.columns = '*,*'; GridLayout.setRow(footer, 2); root.addChild(footer)
|
||||
const close = () => { closed = true; off?.(); off = null; iosBluetooth().stopScan(); page.closeModal() }
|
||||
const back = button('Back', close); footer.addChild(back)
|
||||
const save = button('Save', () => {
|
||||
const addresses = { right: normalizeMacAddress(fields.right.text), left: normalizeMacAddress(fields.left.text), ring: normalizeMacAddress(fields.ring.text) }
|
||||
const error = deviceAddressError(addresses)
|
||||
if (error) { status.text = error; return }
|
||||
saveDeviceAddresses(addresses)
|
||||
for (const role of ['left', 'right', 'ring'] as const) { fields[role].text = addresses[role]; fields[role].dismissSoftInput() }
|
||||
status.text = 'Saved device addresses. Return to the main screen and choose Connect.'
|
||||
})
|
||||
GridLayout.setColumn(save, 1); footer.addChild(save)
|
||||
page.on('unloaded', () => { closed = true; off?.(); off = null; iosBluetooth().stopScan() })
|
||||
return page
|
||||
}
|
||||
export { navigatingTo } from "./config-page-shared";
|
||||
@@ -1,13 +1 @@
|
||||
import { NavigatedData, Page } from "@nativescript/core";
|
||||
|
||||
import { ConfigViewModel } from "./config-view-model";
|
||||
|
||||
export function navigatingTo(args: NavigatedData): void {
|
||||
const page = args.object as Page;
|
||||
// Preserve the model across back-navigation (returning from the firmware
|
||||
// check page) so the onboarding "Continue" flow isn't lost.
|
||||
if (!page.bindingContext) {
|
||||
const context = (args.context as { onboarding?: boolean } | undefined) ?? undefined;
|
||||
page.bindingContext = new ConfigViewModel({ onboarding: context?.onboarding ?? false });
|
||||
}
|
||||
}
|
||||
export { navigatingTo } from "./config-page-shared";
|
||||
@@ -16,21 +16,21 @@
|
||||
|
||||
<StackLayout row="2" class="m-t-16">
|
||||
<Label text="Right arm MAC" />
|
||||
<TextField text="{{ rightAddress }}" textChange="{{ onRightAddressTextChange }}" autocorrect="false" autocapitalizationType="none" />
|
||||
<TextField accessibilityLabel="Right arm MAC" text="{{ rightAddress }}" textChange="{{ onRightAddressTextChange }}" autocorrect="false" autocapitalizationType="none" />
|
||||
</StackLayout>
|
||||
|
||||
<StackLayout row="3" class="m-t-12">
|
||||
<Label text="Left arm MAC" />
|
||||
<TextField text="{{ leftAddress }}" textChange="{{ onLeftAddressTextChange }}" autocorrect="false" autocapitalizationType="none" />
|
||||
<TextField accessibilityLabel="Left arm MAC" text="{{ leftAddress }}" textChange="{{ onLeftAddressTextChange }}" autocorrect="false" autocapitalizationType="none" />
|
||||
</StackLayout>
|
||||
|
||||
<StackLayout row="4" class="m-t-12">
|
||||
<Label text="R1 ring MAC (optional)" />
|
||||
<TextField text="{{ ringAddress }}" textChange="{{ onRingAddressTextChange }}" autocorrect="false" autocapitalizationType="none" />
|
||||
<TextField accessibilityLabel="R1 ring MAC" text="{{ ringAddress }}" textChange="{{ onRingAddressTextChange }}" autocorrect="false" autocapitalizationType="none" />
|
||||
</StackLayout>
|
||||
|
||||
<GridLayout row="5" columns="*,*" class="m-t-16">
|
||||
<Button col="0" text="Load paired devices" tap="{{ onLoadPairedTap }}" class="-primary" isEnabled="{{ canDiscover }}" />
|
||||
<Button col="0" text="Load paired devices" visibility="{{ pairedDevicesVisibility }}" tap="{{ onLoadPairedTap }}" class="-primary" isEnabled="{{ canDiscover }}" />
|
||||
<Button col="1" text="Scan for glasses" tap="{{ onScanTap }}" class="-primary" isEnabled="{{ canDiscover }}" />
|
||||
</GridLayout>
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { finishOnboardingNavigation } from "./onboarding-navigation";
|
||||
import { Frame, Observable } from "@nativescript/core";
|
||||
|
||||
import { ensureBlePermissions } from "../g2/android-permissions";
|
||||
import { ensureBlePermissions } from "../native/ble-permissions";
|
||||
import {
|
||||
isValidMacAddress,
|
||||
loadDeviceAddresses,
|
||||
@@ -38,6 +39,9 @@ export class ConfigViewModel extends Observable {
|
||||
this.status = this.onboarding
|
||||
? "Scan for glasses to pick yours by model and serial, load the addresses of devices paired with this phone, or enter them by hand, then Continue."
|
||||
: "Edit addresses manually, scan for glasses, or load them from paired devices.";
|
||||
if (global.isIOS) this.status = this.onboarding
|
||||
? "Scan for glasses to pick yours by model and serial, or enter the addresses by hand, then Continue."
|
||||
: "Edit addresses manually or scan for glasses.";
|
||||
}
|
||||
|
||||
// --- paired identity card --------------------------------------------------
|
||||
@@ -183,13 +187,15 @@ export class ConfigViewModel extends Observable {
|
||||
this.ringAddress = args.object?.text ?? args.value ?? "";
|
||||
}
|
||||
|
||||
get pairedDevicesVisibility(): "visible" | "collapse" { return global.isIOS ? "collapse" : "visible"; }
|
||||
|
||||
async onLoadPairedTap(): Promise<void> {
|
||||
await this.populateFromDiscovery(async () => this.discovery.getBondedCandidates(), "Loaded paired devices.");
|
||||
}
|
||||
|
||||
/** The live scan page identifies pairs by serial, model, and distance; hand off to it. */
|
||||
async onScanTap(): Promise<void> {
|
||||
if (!this.onboarding) {
|
||||
if (!this.onboarding && global.isAndroid) {
|
||||
// A connected arm stops advertising, so drop the link before scanning.
|
||||
// Required lazily: a module-scope import would instantiate the dashboard
|
||||
// controller singleton during onboarding, which this page is part of.
|
||||
@@ -221,10 +227,7 @@ export class ConfigViewModel extends Observable {
|
||||
frame?.navigate({ moduleName: "phone-ui/onboarding-page", clearHistory: true });
|
||||
return;
|
||||
}
|
||||
Frame.topmost()?.navigate({
|
||||
moduleName: "phone-ui/main-page",
|
||||
clearHistory: true,
|
||||
});
|
||||
finishOnboardingNavigation();
|
||||
}
|
||||
|
||||
onSaveTap(): void {
|
||||
@@ -254,6 +257,10 @@ export class ConfigViewModel extends Observable {
|
||||
this.status = "Ring MAC address is invalid.";
|
||||
return false;
|
||||
}
|
||||
if (right === left || ring === right || ring === left) {
|
||||
this.status = "Each device must have a different MAC address.";
|
||||
return false;
|
||||
}
|
||||
|
||||
saveDeviceAddresses({ right, left, ring });
|
||||
this.rightAddress = right;
|
||||
@@ -267,7 +274,7 @@ export class ConfigViewModel extends Observable {
|
||||
load: () => Promise<Parameters<typeof buildAddressSet>[0]>,
|
||||
successMessage: string,
|
||||
): Promise<void> {
|
||||
if (!global.isAndroid) {
|
||||
if (!global.isAndroid && !global.isIOS) {
|
||||
this.status = "Discovery is only available on Android.";
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Application, Button, Color, Dialogs, GridLayout, Image, Label, Page, StackLayout, type TouchGestureEventData } from '@nativescript/core'
|
||||
import { createConfigureDevicesPage } from './config-page.ios'
|
||||
import { Application, Button, Color, Dialogs, Frame, GridLayout, Image, Label, Page, StackLayout, type TouchGestureEventData } from '@nativescript/core'
|
||||
import { isPreviewOnlyMode } from './onboarding-state'
|
||||
import { isAutoReconnectSuppressed, resumeAutoReconnect, suppressAutoReconnect } from '../g2/reconnect-policy'
|
||||
import { launcherEntries } from '../apps/launcher'
|
||||
import { ALL_APPS } from '../apps/all-apps'
|
||||
import { IosPreviewController } from '../g2/ios-preview-controller'
|
||||
@@ -69,12 +70,21 @@ export function createMainPage(): Page {
|
||||
async function openDevices(): Promise<void> {
|
||||
const connected = ['connected', 'connecting', 'retrying'].includes(controller.connectionState?.phase ?? '')
|
||||
const choice = await Dialogs.action({ title: 'Devices', message: controller.connectionState?.status ?? 'Preview only', cancelButtonText: 'Cancel',
|
||||
actions: ['Configure devices', connected ? 'Disconnect' : 'Connect', 'Connection details'] })
|
||||
if (choice === 'Configure devices') {
|
||||
actions: ['Pair glasses', 'Configure devices', connected ? 'Disconnect' : 'Connect', 'Check firmware', 'Install custom firmware', 'Uninstall custom firmware', 'Connection details'] })
|
||||
if (['Pair glasses', 'Configure devices', 'Check firmware', 'Install custom firmware', 'Uninstall custom firmware'].includes(choice)) {
|
||||
suppressAutoReconnect()
|
||||
await controller.disconnect()
|
||||
page.showModal(createConfigureDevicesPage(), { fullscreen: true, closeCallback: () => {} })
|
||||
} else if (choice === 'Connect') await controller.connect()
|
||||
else if (choice === 'Disconnect') await controller.disconnect()
|
||||
if (choice === 'Pair glasses') {
|
||||
Frame.topmost()?.navigate({ moduleName: 'phone-ui/onboarding-unpair-page' })
|
||||
} else if (choice === 'Configure devices') {
|
||||
Frame.topmost()?.navigate({ moduleName: 'phone-ui/config-page', context: { onboarding: isPreviewOnlyMode() } })
|
||||
} else if (choice === 'Check firmware') {
|
||||
Frame.topmost()?.navigate({ moduleName: 'phone-ui/onboarding-firmware-check-page' })
|
||||
} else {
|
||||
Frame.topmost()?.navigate({ moduleName: 'phone-ui/onboarding-flash-page', context: { mode: choice === 'Uninstall custom firmware' ? 'uninstall' : 'install', fromOnboarding: false } })
|
||||
}
|
||||
} else if (choice === 'Connect') { resumeAutoReconnect(); await controller.connect() }
|
||||
else if (choice === 'Disconnect') { suppressAutoReconnect(); await controller.disconnect() }
|
||||
else if (choice === 'Connection details') await Dialogs.alert({ title: 'Connection details', message: controller.connectionDetails, okButtonText: 'OK' })
|
||||
}
|
||||
const padInput = new PhoneGestureRecognizer(gesture => controller.gesture(gesture, selectedTab === 'ring' ? 'ring' : 'watch'))
|
||||
@@ -184,16 +194,11 @@ export function createMainPage(): Page {
|
||||
}
|
||||
const resume = () => { foreground = true; controller.resume(); syncBandwidth() }
|
||||
let offSettings: (() => void) | null = null
|
||||
let firstLoad = true
|
||||
page.on('loaded', () => {
|
||||
Application.on(Application.suspendEvent, pause); Application.on(Application.resumeEvent, resume)
|
||||
offSettings?.(); offSettings = onAnySettingChanged(() => { sizeButton.text = controller.displayModeLabel; syncBandwidth() })
|
||||
selectTab(selectedTab); resume()
|
||||
if (firstLoad) {
|
||||
firstLoad = false
|
||||
// Match Android's reconnect-on-launch behavior once addresses are saved.
|
||||
if (!deviceAddressError(loadDeviceAddresses())) void controller.connect()
|
||||
}
|
||||
if (!isPreviewOnlyMode() && !isAutoReconnectSuppressed() && !deviceAddressError(loadDeviceAddresses())) void controller.connect()
|
||||
})
|
||||
page.on('unloaded', () => {
|
||||
pause(); offSettings?.(); offSettings = null
|
||||
@@ -201,3 +206,5 @@ export function createMainPage(): Page {
|
||||
})
|
||||
return page
|
||||
}
|
||||
|
||||
export const createPage = createMainPage
|
||||
@@ -8,3 +8,9 @@ export function navigatingTo(args: EventData): void {
|
||||
page.bindingContext = new OnboardingFirmwareCheckViewModel();
|
||||
}
|
||||
}
|
||||
|
||||
export function navigatingFrom(args: EventData): void {
|
||||
const page = args.object as Page;
|
||||
(page.bindingContext as OnboardingFirmwareCheckViewModel | undefined)?.dispose();
|
||||
page.bindingContext = null;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo" actionBarHidden="true">
|
||||
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo" navigatingFrom="navigatingFrom" actionBarHidden="true">
|
||||
<GridLayout rows="*,auto" class="p-20">
|
||||
<ScrollView row="0">
|
||||
<StackLayout>
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { resumeAutoReconnect } from "../g2/reconnect-policy";
|
||||
import { finishOnboardingNavigation } from "./onboarding-navigation";
|
||||
import { Frame, Observable } from "@nativescript/core";
|
||||
|
||||
import { ensureBlePermissions } from "../g2/android-permissions";
|
||||
import { ensureBlePermissions } from "../native/ble-permissions";
|
||||
import { isValidMacAddress, loadDeviceAddresses } from "../g2/device-addresses";
|
||||
import {
|
||||
downloadAndExtractEvenHubFonts,
|
||||
@@ -27,6 +29,8 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
|
||||
private _status = "";
|
||||
private _busy = true;
|
||||
|
||||
private generation = 0;
|
||||
|
||||
private probeInstance: DeviceInfoProbe | null = null;
|
||||
|
||||
constructor() {
|
||||
@@ -158,7 +162,8 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
|
||||
// --- probe flow ------------------------------------------------------------
|
||||
|
||||
private async check(): Promise<void> {
|
||||
if (!global.isAndroid) {
|
||||
const generation = ++this.generation;
|
||||
if (!global.isAndroid && !global.isIOS) {
|
||||
this.toError("Firmware checking is only available on Android.");
|
||||
return;
|
||||
}
|
||||
@@ -169,6 +174,7 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
|
||||
|
||||
try {
|
||||
await ensureBlePermissions();
|
||||
if (generation !== this.generation) return;
|
||||
const stored = loadDeviceAddresses();
|
||||
if (!isValidMacAddress(stored.right)) {
|
||||
this.toError("No glasses address is configured. Go back and set the device addresses.");
|
||||
@@ -181,11 +187,13 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
|
||||
probe.onStateChange((state, detail) => this.reportProbeState(state, detail));
|
||||
|
||||
const info = await probe.run();
|
||||
if (generation !== this.generation) return;
|
||||
this.probeInstance = null;
|
||||
|
||||
const { kind, version, extension } = classifyOnboardingFirmware(info);
|
||||
this.applyClassification(kind, version, extension);
|
||||
} catch (error) {
|
||||
if (generation !== this.generation) return;
|
||||
this.probeInstance = null;
|
||||
this.toError(this.formatError(error));
|
||||
}
|
||||
@@ -199,7 +207,7 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
|
||||
this.status = `Connecting to ${lens}...`;
|
||||
} else if (state === "authenticating") {
|
||||
// First-time connections pair here; the OS may show a Bluetooth dialog.
|
||||
this.status = `Pairing with ${lens}... Each lens pairs separately; if Android asks to pair, tap Pair.`;
|
||||
this.status = `Pairing with ${lens}... Each lens pairs separately; if your phone asks to pair, tap Pair.`;
|
||||
} else if (state === "querying") {
|
||||
this.status = "Reading the firmware version...";
|
||||
}
|
||||
@@ -276,6 +284,7 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
|
||||
}
|
||||
|
||||
private async extractFontsForCustomFirmware(version: string, extension: FirmwareExtension): Promise<void> {
|
||||
const generation = this.generation;
|
||||
this.setPhase("fonts");
|
||||
this.headline = "Preparing G2 Fonts";
|
||||
this.busy = true;
|
||||
@@ -283,9 +292,13 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
|
||||
"Custom firmware is already installed, but its phone-side fonts are missing. " +
|
||||
"Downloading the official firmware to extract them; your glasses will not be reflashed.";
|
||||
try {
|
||||
await downloadAndExtractEvenHubFonts((progress) => this.reportFontProgress(progress));
|
||||
await downloadAndExtractEvenHubFonts((progress) => {
|
||||
if (generation === this.generation) this.reportFontProgress(progress);
|
||||
});
|
||||
if (generation !== this.generation) return;
|
||||
this.showCustomReady(version, extension, true);
|
||||
} catch (error) {
|
||||
if (generation !== this.generation) return;
|
||||
this.toError(
|
||||
`Custom firmware is installed, but the G2 fonts could not be prepared: ${this.formatError(error)}`,
|
||||
"Couldn't Prepare Fonts",
|
||||
@@ -337,13 +350,11 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
|
||||
}
|
||||
|
||||
private finish(): void {
|
||||
resumeAutoReconnect();
|
||||
setPreviewOnlyMode(false);
|
||||
setOnboardingCompleted(true);
|
||||
this.disposeProbe();
|
||||
Frame.topmost()?.navigate({
|
||||
moduleName: "phone-ui/main-page",
|
||||
clearHistory: true,
|
||||
});
|
||||
finishOnboardingNavigation();
|
||||
}
|
||||
|
||||
private toError(message: string, headline = "Couldn't Check Firmware"): void {
|
||||
@@ -366,6 +377,8 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
|
||||
this.notifyPropertyChange("errorActionsVisibility", this.errorActionsVisibility);
|
||||
}
|
||||
|
||||
dispose(): void { ++this.generation; this.disposeProbe(); }
|
||||
|
||||
private disposeProbe(): void {
|
||||
if (this.probeInstance) {
|
||||
try {
|
||||
|
||||
@@ -14,3 +14,9 @@ export function navigatingTo(args: NavigatedData): void {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function navigatingFrom(args: NavigatedData): void {
|
||||
const page = args.object as Page;
|
||||
(page.bindingContext as OnboardingFlashViewModel | undefined)?.dispose();
|
||||
page.bindingContext = null;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo" actionBarHidden="true">
|
||||
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo" navigatingFrom="navigatingFrom" enableSwipeBackNavigation="false" actionBarHidden="true">
|
||||
<GridLayout rows="*,auto" class="p-20">
|
||||
<ScrollView row="0">
|
||||
<StackLayout>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { finishOnboardingNavigation } from "./onboarding-navigation";
|
||||
import { Frame, Observable } from "@nativescript/core";
|
||||
|
||||
import { ensureBlePermissions } from "../g2/android-permissions";
|
||||
import { ensureBlePermissions } from "../native/ble-permissions";
|
||||
import {
|
||||
isValidMacAddress,
|
||||
loadDeviceAddresses,
|
||||
@@ -46,6 +47,9 @@ export class OnboardingFlashViewModel extends Observable {
|
||||
private addresses: { right: string; left: string } | null = null;
|
||||
private firmwarePath = "";
|
||||
|
||||
private disposed = false;
|
||||
private promptGeneration = 0;
|
||||
|
||||
private prompt: FlashPromptCommunicator | null = null;
|
||||
private promptUnsubscribers: Array<() => void> = [];
|
||||
private promptBattery: FlashPromptBattery | null = null;
|
||||
@@ -228,15 +232,17 @@ export class OnboardingFlashViewModel extends Observable {
|
||||
// --- prompt flow -----------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Connect to both arms, authenticate (this is where any Android pairing
|
||||
* Connect to both arms, authenticate (this is where any system pairing
|
||||
* prompts appear), show the Yes/No confirmation on the lens, then read the
|
||||
* battery. With `skipPrompt` (retrying after a low-battery refusal, when
|
||||
* the user has already confirmed) the on-glasses confirmation is skipped
|
||||
* and only the battery is re-checked.
|
||||
*/
|
||||
private async beginPrompt(options?: { skipPrompt?: boolean }): Promise<void> {
|
||||
if (this.disposed) return;
|
||||
const generation = ++this.promptGeneration;
|
||||
const skipPrompt = Boolean(options?.skipPrompt);
|
||||
if (!global.isAndroid) {
|
||||
if (!global.isAndroid && !global.isIOS) {
|
||||
this.toError("Flashing is only available on Android.", () => this.beginPrompt(options));
|
||||
return;
|
||||
}
|
||||
@@ -249,7 +255,9 @@ export class OnboardingFlashViewModel extends Observable {
|
||||
|
||||
try {
|
||||
await ensureBlePermissions();
|
||||
if (this.disposed || generation !== this.promptGeneration) return;
|
||||
const addresses = await this.resolveAddresses();
|
||||
if (this.disposed || generation !== this.promptGeneration) return;
|
||||
if (!addresses) {
|
||||
this.busy = false;
|
||||
this.toError(
|
||||
@@ -265,6 +273,7 @@ export class OnboardingFlashViewModel extends Observable {
|
||||
: "Connecting to your glasses. Watch the lens for a Yes/No prompt.";
|
||||
this.startCommunicator(addresses, skipPrompt);
|
||||
} catch (error) {
|
||||
if (this.disposed || generation !== this.promptGeneration) return;
|
||||
this.busy = false;
|
||||
this.toError(this.formatError(error), () => this.beginPrompt(options));
|
||||
}
|
||||
@@ -293,7 +302,7 @@ export class OnboardingFlashViewModel extends Observable {
|
||||
break;
|
||||
case "connected":
|
||||
this.status =
|
||||
"Connected. Pairing with both lenses — if Android asks to pair, accept it (once per lens)." +
|
||||
"Connected. Pairing with both lenses — if your phone asks to pair, accept it (once per lens)." +
|
||||
(skipPrompt ? "" : " Then watch the lens for the confirmation.");
|
||||
break;
|
||||
case "battery":
|
||||
@@ -368,6 +377,7 @@ export class OnboardingFlashViewModel extends Observable {
|
||||
}
|
||||
|
||||
private cancelPrompt(): void {
|
||||
++this.promptGeneration;
|
||||
this.status = "Cancelling...";
|
||||
try {
|
||||
this.prompt?.cancel();
|
||||
@@ -390,11 +400,13 @@ export class OnboardingFlashViewModel extends Observable {
|
||||
try {
|
||||
const build = this.mode === "uninstall" ? buildStockFirmware : buildCustomFirmware;
|
||||
const result = await build((progress) => this.reportBuildProgress(progress));
|
||||
if (this.disposed) return;
|
||||
this.firmwarePath = result.path;
|
||||
this.appendLog(`${this.noun} prepared and verified (${result.bytes.toLocaleString()} bytes), saved to ${result.path}`);
|
||||
// The user already said Yes on the lens; no second confirmation here.
|
||||
this.startFlashing();
|
||||
} catch (error) {
|
||||
if (this.disposed) return;
|
||||
this.busy = false;
|
||||
const message =
|
||||
error instanceof FirmwareBuildError ? error.message : this.formatError(error);
|
||||
@@ -403,6 +415,7 @@ export class OnboardingFlashViewModel extends Observable {
|
||||
}
|
||||
|
||||
private reportBuildProgress(progress: FirmwareProgress): void {
|
||||
if (this.disposed) return;
|
||||
switch (progress.phase) {
|
||||
case "downloading":
|
||||
this.status = "Downloading the stock firmware from Even's CDN...";
|
||||
@@ -430,6 +443,7 @@ export class OnboardingFlashViewModel extends Observable {
|
||||
// --- flashing flow ---------------------------------------------------------
|
||||
|
||||
private startFlashing(): void {
|
||||
if (this.disposed) return;
|
||||
if (!this.addresses || !this.firmwarePath) {
|
||||
this.toError("Missing glasses addresses or firmware; start over.", () => this.beginPrompt());
|
||||
return;
|
||||
@@ -537,10 +551,7 @@ export class OnboardingFlashViewModel extends Observable {
|
||||
}
|
||||
this.disposePrompt();
|
||||
this.disposeFlasher();
|
||||
Frame.topmost()?.navigate({
|
||||
moduleName: "phone-ui/main-page",
|
||||
clearHistory: true,
|
||||
});
|
||||
finishOnboardingNavigation();
|
||||
}
|
||||
|
||||
private leave(): void {
|
||||
@@ -551,6 +562,7 @@ export class OnboardingFlashViewModel extends Observable {
|
||||
frame.goBack();
|
||||
return;
|
||||
}
|
||||
if (!this.fromOnboarding) { finishOnboardingNavigation(); return; }
|
||||
frame?.navigate({
|
||||
moduleName: this.fromOnboarding ? "phone-ui/onboarding-page" : "phone-ui/main-page",
|
||||
clearHistory: true,
|
||||
@@ -581,6 +593,11 @@ export class OnboardingFlashViewModel extends Observable {
|
||||
this.log = this._log ? `${this._log}\n[${stamp}] ${line}` : `[${stamp}] ${line}`;
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.disposed = true; ++this.promptGeneration;
|
||||
this.discovery.stopScan(); this.disposePrompt(); this.disposeFlasher();
|
||||
}
|
||||
|
||||
private disposePrompt(): void {
|
||||
for (const unsubscribe of this.promptUnsubscribers) {
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Frame } from '@nativescript/core'
|
||||
|
||||
/** Return to the existing iOS controller after a devices/firmware detour. */
|
||||
export function finishOnboardingNavigation(): void {
|
||||
const frame = Frame.topmost()
|
||||
const main = global.isIOS && frame?.backStack.find(entry => entry.entry.moduleName === 'phone-ui/main-page')
|
||||
if (main) frame.goBack(main)
|
||||
else frame?.navigate({ moduleName: 'phone-ui/main-page', clearHistory: true })
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
require('@nativescript/core/bundle-entry-points');
|
||||
// iOS reuses Android's NativeScript XML forms and view models.
|
||||
global.registerModule('phone-ui/onboarding-page', () => require('./onboarding-page'));
|
||||
global.registerModule('phone-ui/onboarding-page.xml', () => require('./onboarding-page.xml'));
|
||||
global.registerModule('phone-ui/onboarding-unpair-page', () => require('./onboarding-unpair-page'));
|
||||
global.registerModule('phone-ui/onboarding-unpair-page.xml', () => require('./onboarding-unpair-page.xml'));
|
||||
global.registerModule('phone-ui/pairing-page', () => require('./pairing-page'));
|
||||
global.registerModule('phone-ui/pairing-page.xml', () => require('./pairing-page.xml'));
|
||||
global.registerModule('phone-ui/config-page', () => require('./config-page'));
|
||||
global.registerModule('phone-ui/config-page.xml', () => require('./config-page.xml'));
|
||||
global.registerModule('phone-ui/permissions-page', () => require('./permissions-page'));
|
||||
global.registerModule('phone-ui/permissions-page.xml', () => require('./permissions-page.xml'));
|
||||
global.registerModule('phone-ui/onboarding-firmware-check-page', () => require('./onboarding-firmware-check-page'));
|
||||
global.registerModule('phone-ui/onboarding-firmware-check-page.xml', () => require('./onboarding-firmware-check-page.xml'));
|
||||
global.registerModule('phone-ui/onboarding-flash-page', () => require('./onboarding-flash-page'));
|
||||
global.registerModule('phone-ui/onboarding-flash-page.xml', () => require('./onboarding-flash-page.xml'));
|
||||
global.registerModule('phone-ui/document-page', () => require('./document-page'));
|
||||
global.registerModule('phone-ui/document-page.xml', () => require('./document-page.xml'));
|
||||
global.registerModule('phone-ui/main-page', () => require('./main-page.ios'));
|
||||
@@ -7,7 +7,7 @@
|
||||
text="Your glasses can only be connected to one app or phone at a time. If they're connected to another app (such as Even Realities or MentraOS) or another phone, disconnect them there before continuing. If nothing else is connected, you can continue."
|
||||
class="body-text m-t-24" textWrap="true" />
|
||||
<Label
|
||||
text="If you use the Even Realities app, go to Home, select your glasses, open the Connection submenu, and press Disconnect (or disable the Even app's "nearby devices" permission)."
|
||||
text="{{ evenAppInstructions }}"
|
||||
class="body-text m-t-16" textWrap="true" />
|
||||
<Button text="Open Even App Settings" tap="{{ onOpenEvenAppSettingsTap }}" visibility="{{ settingsButtonVisibility }}" width="{{ settingsButtonWidth }}" horizontalAlignment="center" class="-primary m-t-24" />
|
||||
</StackLayout>
|
||||
|
||||
@@ -3,8 +3,13 @@ import { Frame, Observable, Screen } from "@nativescript/core";
|
||||
import { openEvenAppSettings } from "../native/even-app-conflict";
|
||||
|
||||
export class OnboardingUnpairViewModel extends Observable {
|
||||
get settingsButtonVisibility(): "visible" | "collapsed" {
|
||||
return global.isAndroid ? "visible" : "collapsed";
|
||||
get settingsButtonVisibility(): "visible" | "collapse" {
|
||||
return global.isAndroid ? "visible" : "collapse";
|
||||
}
|
||||
|
||||
get evenAppInstructions(): string {
|
||||
return "If you use the Even Realities app, go to Home, select your glasses, open the Connection submenu, and press Disconnect" +
|
||||
(global.isIOS ? "." : " (or disable the Even app's \"nearby devices\" permission).");
|
||||
}
|
||||
|
||||
onOpenEvenAppSettingsTap(): void {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { finishOnboardingNavigation } from "./onboarding-navigation";
|
||||
import { Frame, Observable, Screen } from "@nativescript/core";
|
||||
|
||||
import { setOnboardingCompleted, setPreviewOnlyMode } from "./onboarding-state";
|
||||
@@ -99,10 +100,7 @@ export class OnboardingViewModel extends Observable {
|
||||
// Step 3 secondary: skip flashing, use the on-phone preview only.
|
||||
setPreviewOnlyMode(true);
|
||||
setOnboardingCompleted(true);
|
||||
Frame.topmost()?.navigate({
|
||||
moduleName: "phone-ui/main-page",
|
||||
clearHistory: true,
|
||||
});
|
||||
finishOnboardingNavigation();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { finishOnboardingNavigation } from "./onboarding-navigation";
|
||||
import { Application, EventData, Frame, Observable, View } from "@nativescript/core";
|
||||
|
||||
import { ensureBlePermissions } from "../g2/android-permissions";
|
||||
import { ensureBlePermissions } from "../native/ble-permissions";
|
||||
import { loadDeviceAddresses, loadPairedGlassesIdentity, saveDeviceAddresses, savePairedGlassesIdentity } from "../g2/device-addresses";
|
||||
import { formatErrorMessage } from "../util/format-error";
|
||||
import {
|
||||
@@ -82,6 +83,7 @@ export class PairingViewModel extends Observable {
|
||||
// --- lifecycle -------------------------------------------------------------
|
||||
|
||||
private resumeScanAfterSuspend = false;
|
||||
private scanGeneration = 0;
|
||||
|
||||
private readonly onAppSuspend = (): void => {
|
||||
if (this._scanning) {
|
||||
@@ -106,12 +108,19 @@ export class PairingViewModel extends Observable {
|
||||
|
||||
async start(): Promise<void> {
|
||||
if (this._scanning) return;
|
||||
if (!global.isAndroid) {
|
||||
// A saved selection can be revisited from the firmware check page.
|
||||
Application.off(Application.suspendEvent, this.onAppSuspend);
|
||||
Application.off(Application.resumeEvent, this.onAppResume);
|
||||
Application.on(Application.suspendEvent, this.onAppSuspend);
|
||||
Application.on(Application.resumeEvent, this.onAppResume);
|
||||
const generation = ++this.scanGeneration;
|
||||
if (!global.isAndroid && !global.isIOS) {
|
||||
this.status = "Pairing is only available on Android.";
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await ensureBlePermissions();
|
||||
if (generation !== this.scanGeneration) return;
|
||||
} catch (error) {
|
||||
this.status = this.formatError(error);
|
||||
return;
|
||||
@@ -150,6 +159,7 @@ export class PairingViewModel extends Observable {
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
++this.scanGeneration;
|
||||
if (this.refreshTimer) {
|
||||
clearInterval(this.refreshTimer);
|
||||
this.refreshTimer = null;
|
||||
@@ -337,7 +347,7 @@ export class PairingViewModel extends Observable {
|
||||
Frame.topmost()?.navigate({ moduleName: "phone-ui/onboarding-firmware-check-page" });
|
||||
return;
|
||||
}
|
||||
Frame.topmost()?.navigate({ moduleName: "phone-ui/main-page", clearHistory: true });
|
||||
finishOnboardingNavigation();
|
||||
}
|
||||
|
||||
onSecondaryTap(): void {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { iosBluetooth } from "../native/ios-bluetooth";
|
||||
import { Application, Dialogs, EventData, Frame, Observable, View } from "@nativescript/core";
|
||||
|
||||
import {
|
||||
@@ -30,7 +31,7 @@ type PermissionDefinition = {
|
||||
* their request() opens a system screen, so the granted state can only be
|
||||
* re-checked when the app resumes (the page refreshes on Application.resume).
|
||||
*/
|
||||
const PERMISSIONS: PermissionDefinition[] = [
|
||||
const ANDROID_PERMISSIONS: PermissionDefinition[] = [
|
||||
{
|
||||
id: "nearby-devices",
|
||||
title: "Nearby Devices",
|
||||
@@ -91,6 +92,13 @@ const PERMISSIONS: PermissionDefinition[] = [
|
||||
},
|
||||
];
|
||||
|
||||
const PERMISSIONS: PermissionDefinition[] = global.isIOS ? [{
|
||||
id: "nearby-devices", title: "Nearby Devices",
|
||||
description: "Needed to communicate with your smart glasses over Bluetooth.", optional: false,
|
||||
isGranted: () => iosBluetooth().state === 5,
|
||||
request: () => iosBluetooth().ensureReady(),
|
||||
}] : ANDROID_PERMISSIONS;
|
||||
|
||||
/** One Repeater card: the permission's copy plus the display-only fields the XML binds. */
|
||||
export type PermissionCardItem = {
|
||||
id: string;
|
||||
@@ -144,8 +152,9 @@ export class PermissionsViewModel extends Observable {
|
||||
}
|
||||
|
||||
get instructions(): string {
|
||||
if (global.isIOS) return "Faceclaw uses Bluetooth to communicate with your smart glasses. Tap the card to allow access; a checkmark means Bluetooth is ready.";
|
||||
return this.onboarding
|
||||
? "Faceclaw uses these Android permissions. Tap a card to grant one; a checkmark means it is already granted. " +
|
||||
? `Faceclaw uses these ${global.isIOS ? "iOS" : "Android"} permissions. Tap a card to grant one; a checkmark means it is already granted. ` +
|
||||
"Optional permissions can also be granted later, from the Permissions item in the main-screen menu."
|
||||
: "Tap a card to grant a permission; a checkmark means it is already granted.";
|
||||
}
|
||||
@@ -216,7 +225,8 @@ export class PermissionsViewModel extends Observable {
|
||||
this.requesting = true;
|
||||
try {
|
||||
await definition.request();
|
||||
} catch {
|
||||
} catch (error) {
|
||||
if (global.isIOS) await Dialogs.alert({ title: "Bluetooth Unavailable", message: String((error as Error).message ?? error), okButtonText: "OK" });
|
||||
// A denial simply leaves the card unchecked; the user can tap again.
|
||||
} finally {
|
||||
this.requesting = false;
|
||||
|
||||
@@ -281,6 +281,8 @@ test('iOS bandwidth footer toggles live, polls only in foreground and resets its
|
||||
onAnySettingChanged: fn => { settingListeners.add(fn); return () => settingListeners.delete(fn); } },
|
||||
'../g2/device-addresses': { loadDeviceAddresses: () => ({}) },
|
||||
'../g2/ios-peripheral-identity': { deviceAddressError: () => 'no test devices' },
|
||||
'./onboarding-state': { isPreviewOnlyMode: () => false },
|
||||
'../g2/reconnect-policy': { isAutoReconnectSuppressed: () => false },
|
||||
};
|
||||
const { createMainPage } = load('app/phone-ui/main-page.ios.ts', {
|
||||
require: id => modules[id] ?? {}, Date: { now: () => atMs },
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const p = require('../.test-build/app/g2/ble-protocol.js');
|
||||
const { StockConnection, OTA_WRITE, OTA_NOTIFY, decodeOtaAcks } = require('../.test-build/app/g2/stock-connection.js');
|
||||
const { firmwareCrc, validateFirmware, flashLensImage } = require('../.test-build/app/g2/firmware-ota.js');
|
||||
const { createFlashPrompt, flashPromptSelection } = require('../.test-build/app/g2/flash-prompt-protocol.js');
|
||||
const hex = bytes => Buffer.from(bytes).toString('hex');
|
||||
function fixture() {
|
||||
const sizes = [9000, 20, 20, 20, 20], image = new Uint8Array(0x40 + 5 * 16 + sizes.reduce((n, size) => n + size + 128, 0));
|
||||
const view = new DataView(image.buffer), u32 = (off, value) => view.setUint32(off, value, true);
|
||||
u32(8, 5); let offset = 0x40 + 5 * 16;
|
||||
sizes.forEach((size, index) => {
|
||||
u32(0x40 + index * 16 + 4, offset); u32(offset + 8, size);
|
||||
image.set(Buffer.from(index ? `ota/part${index}.bin` : 'ota/s200_firmware_ota.bin'), offset + 48);
|
||||
image.fill(index + 1, offset + 128, offset + 128 + size);
|
||||
if (!index) { u32(offset + 128, size); u32(offset + 128 + 0x14, 0x00438000); }
|
||||
const crc = firmwareCrc(image.subarray(offset + 128, offset + 128 + size));
|
||||
u32(offset + 12, crc); u32(0x40 + index * 16 + 12, crc); offset += size + 128;
|
||||
});
|
||||
return image;
|
||||
}
|
||||
class Transport {
|
||||
listeners = new Set(); writes = []; messages = []; chunks = []; seq = 0; held = false; respond = null; closed = [];
|
||||
onEvent(fn) { this.listeners.add(fn); return () => this.listeners.delete(fn); }
|
||||
emit(event) { for (const fn of this.listeners) fn(event); }
|
||||
async resolveDevices() { return { left: 'L', right: 'R' }; }
|
||||
async connect() { return { characteristics: [p.G2_WRITE, p.G2_NOTIFY, OTA_WRITE, OTA_NOTIFY], maxWrite: 60 }; }
|
||||
async subscribe() {}
|
||||
stopScan() {}
|
||||
disconnect(id) { this.closed.push(id); this.emit({ kind: 'disconnected', identifier: id }); }
|
||||
notify(id, sid, payload, characteristic = p.G2_NOTIFY, flag = 0) {
|
||||
this.emit({ kind: 'notification', identifier: id, characteristic, data: hex(p.concat(...p.frameMessage(payload, sid, flag, 10))) });
|
||||
}
|
||||
async write(id, characteristic, bytes) {
|
||||
this.writes.push({ id, characteristic, bytes });
|
||||
if (bytes[5] === 1) this.chunks = [];
|
||||
this.chunks.push(bytes.subarray(8));
|
||||
if (bytes[5] !== bytes[4]) return;
|
||||
const all = p.concat(...this.chunks), payload = all.slice(0, -2);
|
||||
assert.equal(p.crc16(payload), all.at(-2) | all.at(-1) << 8);
|
||||
const message = { id, characteristic, sid: bytes[6], seq: bytes[2], payload };
|
||||
this.messages.push(message);
|
||||
if (this.respond) return this.respond(message);
|
||||
if (this.held) return;
|
||||
if (characteristic === OTA_WRITE) {
|
||||
if (message.sid === 0xc0 && payload[0] === 2) { this.seq = message.seq; return; }
|
||||
if (message.sid === 0xc1) assert.equal(message.seq, this.seq, 'marker/data sequence must match');
|
||||
this.notify(id, 0xc0, new Uint8Array([message.sid === 0xc1 ? 2 : payload[0], 0]), OTA_NOTIFY);
|
||||
} else {
|
||||
this.notify(id, message.sid, p.concat(p.integer(1, p.readInteger(payload, 1)), p.integer(2, p.readInteger(payload, 2)), p.bytes(3, new Uint8Array())));
|
||||
}
|
||||
}
|
||||
}
|
||||
async function connection(t, transport = new Transport()) {
|
||||
const link = new StockConnection(transport); t.after(() => link.close());
|
||||
await link.resolve({ left: 'a', right: 'b', ring: '' }); await link.connect('left', true);
|
||||
return { link, transport };
|
||||
}
|
||||
|
||||
test('OTA validator checks CRCs, bounds, overlap and the main-app preamble before transfer', () => {
|
||||
const image = fixture(), segments = validateFirmware(image);
|
||||
assert.equal(segments.length, 5);
|
||||
const corrupt = image.slice(); corrupt[segments[0].offset + 200] ^= 1;
|
||||
assert.throws(() => validateFirmware(corrupt), /CRC32C/);
|
||||
assert.throws(() => validateFirmware(image.slice(0, -1)), /truncated/);
|
||||
const bad = image.slice(), view = new DataView(bad.buffer);
|
||||
view.setUint32(0x44, 0xfffffff0, true); assert.throws(() => validateFirmware(bad), /bounds/);
|
||||
const overlap = image.slice(); new DataView(overlap.buffer).setUint32(0x54, segments[0].offset, true);
|
||||
assert.throws(() => validateFirmware(overlap), /overlap/);
|
||||
const wrongLoad = image.slice(), w = new DataView(wrongLoad.buffer), main = segments[0];
|
||||
w.setUint32(main.offset + 128 + 0x14, 0, true);
|
||||
const crc = firmwareCrc(wrongLoad.subarray(main.offset + 128, main.offset + 128 + main.size));
|
||||
w.setUint32(main.offset + 12, crc, true); w.setUint32(0x4c, crc, true);
|
||||
assert.throws(() => validateFirmware(wrongLoad), /preamble/);
|
||||
});
|
||||
|
||||
test('OTA framing streams every verified byte in 4KB blocks with shared marker/data sequences', async t => {
|
||||
const { link, transport } = await connection(t); await link.authenticate('left');
|
||||
const image = fixture(), segments = validateFirmware(image), progress = [];
|
||||
await flashLensImage(link, 'left', image, segments, value => progress.push(value), () => {}, async () => {});
|
||||
const controls = transport.messages.filter(m => m.sid === 0xc0);
|
||||
assert.equal(controls[0].payload[0], 0);
|
||||
assert.equal(controls.filter(m => m.payload[0] === 1).length, 5);
|
||||
assert.equal(controls.filter(m => m.payload[0] === 3).length, 5);
|
||||
const streamed = p.concat(...transport.messages.filter(m => m.sid === 0xc1).map(m => m.payload));
|
||||
assert.deepEqual(streamed, p.concat(...segments.map(s => image.slice(s.offset + 128, s.offset + 128 + s.size))));
|
||||
assert.equal(progress.at(-1).bytesSent, progress.at(-1).bytesTotal);
|
||||
assert.ok(transport.writes.every(w => w.bytes.length <= 60));
|
||||
});
|
||||
|
||||
test('OTA retries NAKed blocks and failed END verification, but never accepts a rejected FILE_CHECK', async () => {
|
||||
const image = fixture(), segments = validateFirmware(image); let blockAttempts = 0, endAttempts = 0, checks = 0;
|
||||
const fake = { check() {}, async exchange(_role, _sid, payload, _match, _timeout, _write, _notify, _flag, _seq, data) {
|
||||
const op = payload[0]; let status = 0;
|
||||
if (op === 1) checks++;
|
||||
if (op === 2 && ++blockAttempts === 1) status = 1;
|
||||
if (op === 3 && ++endAttempts === 1) status = 2;
|
||||
return { payload: new Uint8Array([op, status]) };
|
||||
} };
|
||||
await flashLensImage(fake, 'left', image, segments, () => {}, () => {}, async () => {});
|
||||
assert.equal(checks, 6); assert.equal(blockAttempts, 11);
|
||||
let dataWrites = 0;
|
||||
fake.exchange = async (_role, _sid, payload, ...args) => { if (args.at(-1)) dataWrites++; return { payload: new Uint8Array([payload[0], payload[0] === 1 ? 4 : 0]) }; };
|
||||
await assert.rejects(flashLensImage(fake, 'left', image, segments, () => {}, () => {}, async () => {}), /failed after 3 attempts/);
|
||||
assert.equal(dataWrites, 0);
|
||||
});
|
||||
|
||||
test('onboarding requests ignore wrong peers, magic and pre-encryption authentication failures', async t => {
|
||||
const { link, transport } = await connection(t); let resolved = false;
|
||||
transport.respond = message => {
|
||||
const magic = p.readInteger(message.payload, 2);
|
||||
const good = p.concat(p.integer(1, 4), p.integer(2, magic), p.bytes(3, new Uint8Array()));
|
||||
transport.notify('stranger', p.SID.auth, good);
|
||||
transport.notify('R', p.SID.auth, good);
|
||||
transport.notify('L', p.SID.auth, p.concat(p.integer(1, 4), p.integer(2, magic), p.bytes(3, p.integer(1, 1))));
|
||||
transport.notify('L', p.SID.auth, p.concat(p.integer(1, 4), p.integer(2, magic + 1), p.bytes(3, new Uint8Array())));
|
||||
setImmediate(() => { assert.equal(resolved, false); transport.notify('L', p.SID.auth, good); });
|
||||
};
|
||||
await link.authenticate('left'); resolved = true;
|
||||
});
|
||||
|
||||
test('OTA ACK parsing rejects bad CRC and truncation; cancellation rejects an outstanding transaction', async t => {
|
||||
const { link, transport } = await connection(t); transport.held = true;
|
||||
const payload = new Uint8Array([2, 0]), packet = p.frameMessage(payload, 0xc0, 0, 1)[0];
|
||||
assert.equal(decodeOtaAcks(packet)[0].payload[1], 0);
|
||||
assert.deepEqual(decodeOtaAcks(packet.slice(0, -1)), []);
|
||||
packet[8] ^= 1; assert.deepEqual(decodeOtaAcks(packet), []);
|
||||
const pending = link.exchange('left', 0xc0, new Uint8Array([0]), m => m.command === 0, 8000, OTA_WRITE, OTA_NOTIFY, 0);
|
||||
link.close(); await assert.rejects(pending, /Cancelled/);
|
||||
assert.equal(transport.listeners.size, 0);
|
||||
});
|
||||
|
||||
test('stock confirmation keeps No first and accepts only a confirmed flashmenu selection', () => {
|
||||
const page = createFlashPrompt(42, 'Warning'); const body = p.readBytes(page, 3);
|
||||
const list = p.readBytes(body, 2), label = p.readBytes(body, 3);
|
||||
assert.equal(p.readInteger(list, 3), 280); assert.equal(p.readInteger(label, 4), 130);
|
||||
assert.equal(p.readString(list, 10), 'flashmenu'); assert.equal(p.readString(label, 12), 'Warning');
|
||||
const event = (index, type = 0, name = 'flashmenu') => ({ sid: 0xe0, flag: 1,
|
||||
payload: p.bytes(13, p.bytes(1, p.concat(p.bytes(2, new Uint8Array(Buffer.from(name))), p.integer(4, index), p.integer(5, type)))) });
|
||||
assert.equal(flashPromptSelection(event(0)), false); assert.equal(flashPromptSelection(event(1)), true);
|
||||
assert.equal(flashPromptSelection(event(1, 1)), null); assert.equal(flashPromptSelection(event(1, 0, 'other')), null);
|
||||
});
|
||||
@@ -0,0 +1,164 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs'), vm = require('node:vm'), ts = require('typescript');
|
||||
const crypto = require('node:crypto'), os = require('node:os'), path = require('node:path');
|
||||
function load(file, modules = {}, globals = {}) {
|
||||
const context = { exports: {}, require: name => {
|
||||
if (!(name in modules)) throw new Error(`Missing mock: ${name} in ${file}`);
|
||||
return modules[name];
|
||||
}, Uint8Array, ArrayBuffer, DataView, setTimeout, clearTimeout, setInterval, clearInterval, ...globals };
|
||||
vm.runInNewContext(ts.transpileModule(fs.readFileSync(file, 'utf8'), {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
|
||||
}).outputText, context);
|
||||
return context.exports;
|
||||
}
|
||||
const flush = () => new Promise(resolve => setImmediate(resolve));
|
||||
function flasherFixture({ hash = 'custom', failRole = '', backgroundRole = '' } = {}) {
|
||||
const calls = [], events = new Map(), native = { idleTimerDisabled: false, applicationState: 0 };
|
||||
const app = { suspendEvent: 'suspend', on: (e, cb) => events.set(e, cb), off: e => events.delete(e) };
|
||||
class Link {
|
||||
closed = false;
|
||||
check() { if (this.closed) throw new Error('Cancelled'); }
|
||||
async resolve() { calls.push('resolve'); }
|
||||
async connect(role, ota) { this.check(); calls.push(`connect:${role}:${ota}`); }
|
||||
async authenticate(role) { this.check(); calls.push(`auth:${role}`); }
|
||||
disconnect(role) { calls.push(`disconnect:${role}`); }
|
||||
close() { this.closed = true; calls.push('close'); }
|
||||
}
|
||||
const { FirmwareFlasher } = load('app/native/firmware-flasher.ios.ts', {
|
||||
'@nativescript/core': { Application: app }, '../g2/stock-connection': { StockConnection: Link },
|
||||
'../g2/firmware/cfw-patches': { CFW_PATCH_SET: { outputSha256: 'custom', baseSha256: 'stock' } },
|
||||
'./firmware-files.ios': { readFirmwareFile: () => new Uint8Array(16), firmwareSha256: () => hash },
|
||||
'./ios-bluetooth': { iosBluetooth: () => ({}) },
|
||||
'../g2/firmware-ota': { validateFirmware: () => { calls.push('validate'); return []; },
|
||||
flashLensImage: async (link, role) => {
|
||||
calls.push(`flash:${role}`);
|
||||
if (role === backgroundRole) events.get('suspend')();
|
||||
link.check();
|
||||
if (role === failRole) throw new Error('END rejected');
|
||||
} },
|
||||
}, { UIApplication: { sharedApplication: native }, UIApplicationState: { Active: 0 },
|
||||
setTimeout: fn => setTimeout(fn, 0) });
|
||||
const flasher = new FirmwareFlasher({ right: 'r', left: 'l' }, 'prepared.bin');
|
||||
const result = new Promise(resolve => flasher.onComplete((success, detail) => resolve({ success, detail })));
|
||||
return { calls, events, native, flasher, result };
|
||||
}
|
||||
|
||||
test('iOS flashing authenticates and verifies both lenses in order before reporting success', async () => {
|
||||
for (const hash of ['custom', 'stock']) {
|
||||
const f = flasherFixture({ hash }); f.flasher.start(); f.flasher.start();
|
||||
assert.equal((await f.result).success, true);
|
||||
assert.deepEqual(f.calls, ['validate', 'resolve', 'connect:left:true', 'auth:left', 'flash:left', 'disconnect:left',
|
||||
'connect:right:true', 'auth:right', 'flash:right', 'disconnect:right', 'close']);
|
||||
assert.equal(f.native.idleTimerDisabled, false); assert.equal(f.events.size, 0);
|
||||
}
|
||||
});
|
||||
|
||||
test('iOS flashing refuses a changed image before Bluetooth and never reports partial success', async () => {
|
||||
const invalid = flasherFixture({ hash: 'changed' }); invalid.flasher.start();
|
||||
assert.match((await invalid.result).detail, /SHA-256/); assert.deepEqual(invalid.calls, ['close']);
|
||||
const failure = flasherFixture({ failRole: 'right' }); failure.flasher.start();
|
||||
const result = await failure.result; assert.equal(result.success, false); assert.match(result.detail, /END rejected/);
|
||||
assert.equal(failure.native.idleTimerDisabled, false); assert.equal(failure.events.size, 0);
|
||||
});
|
||||
|
||||
test('backgrounding during iOS OTA stops the transfer and directs retry of both lenses', async () => {
|
||||
const f = flasherFixture({ backgroundRole: 'left' }); f.flasher.start();
|
||||
const result = await f.result;
|
||||
assert.equal(result.success, false); assert.match(result.detail, /left the foreground.*retry both lenses/);
|
||||
assert.equal(f.calls.includes('flash:right'), false); assert.equal(f.native.idleTimerDisabled, false);
|
||||
});
|
||||
|
||||
test('iOS firmware prompt surfaces heartbeat disconnection instead of leaving confirmation stuck', async () => {
|
||||
let heartbeat;
|
||||
const p = require('../.test-build/app/g2/ble-protocol.js');
|
||||
class Link {
|
||||
async resolve() {} async connect() {} async authenticate() {} async request() {}
|
||||
onMessage() { return () => {}; } nextMagic() { return 1; } close() {}
|
||||
async write() { throw new Error('Lost connection to the right lens.'); }
|
||||
}
|
||||
const { FlashPromptCommunicator } = load('app/native/flash-prompt-communicator.ios.ts', {
|
||||
'../g2/stock-connection': { StockConnection: Link }, '../g2/flash-prompt-protocol': {}, '../g2/ble-protocol': p,
|
||||
'./ios-bluetooth': { iosBluetooth: () => ({}) },
|
||||
}, { setInterval: fn => { heartbeat = fn; return 1; }, clearInterval() {} });
|
||||
const prompt = new FlashPromptCommunicator({ right: 'r', left: 'l' }, 'warning'), errors = [];
|
||||
prompt.onStateChange((state, detail) => { if (state === 'error') errors.push(detail); });
|
||||
prompt.start(); await flush(); heartbeat(); await flush();
|
||||
assert.deepEqual(errors, ['Lost connection to the right lens.']); prompt.close();
|
||||
});
|
||||
|
||||
test('iOS onboarding returns to the existing main controller, or creates it after first setup', () => {
|
||||
const calls = [], main = { entry: { moduleName: 'phone-ui/main-page' } }, stack = [main];
|
||||
const { finishOnboardingNavigation } = load('app/phone-ui/onboarding-navigation.ts', {
|
||||
'@nativescript/core': { Frame: { topmost: () => ({ backStack: stack, goBack: entry => calls.push(entry), navigate: entry => calls.push(entry) }) } },
|
||||
}, { global: { isIOS: true } });
|
||||
finishOnboardingNavigation(); assert.equal(calls[0], main);
|
||||
stack.length = 0; finishOnboardingNavigation();
|
||||
assert.equal(calls[1].moduleName, 'phone-ui/main-page'); assert.equal(calls[1].clearHistory, true);
|
||||
});
|
||||
|
||||
test('pinned stock firmware reproduces the custom image, extracts fonts, and passes OTA validation', {
|
||||
skip: !process.env.FACECLAW_TEST_STOCK_FIRMWARE && 'Set FACECLAW_TEST_STOCK_FIRMWARE to the pinned stock .bin',
|
||||
}, async t => {
|
||||
const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'faceclaw-firmware-test-'));
|
||||
t.after(() => fs.rmSync(temp, { recursive: true, force: true }));
|
||||
const base = fs.readFileSync(process.env.FACECLAW_TEST_STOCK_FIRMWARE);
|
||||
const hash = buffer => crypto.createHash('sha256').update(new Uint8Array(buffer)).digest('hex');
|
||||
const patches = load('app/g2/firmware/cfw-patches.ts'), fonts = load('app/g2/firmware-fonts.ts');
|
||||
const builder = load('app/g2/firmware-builder.ts', {
|
||||
'@nativescript/core': { File: { exists: fs.existsSync, fromPath: file => ({ readTextSync: () => fs.readFileSync(file, 'utf8') }) },
|
||||
knownFolders: { documents: () => ({ path: temp, getFile: name => ({ writeTextSync: text => fs.writeFileSync(path.join(temp, name), text) }) }) } },
|
||||
'./firmware/cfw-patches': patches, './firmware-fonts': fonts,
|
||||
'../util/http': { fetchWithUserAgent: async () => ({ ok: true, arrayBuffer: async () => Uint8Array.from(base).buffer }) },
|
||||
'../util/hex-util': require('../.test-build/app/util/hex-util.js'), '../graphics/evenhub-font': { EvenHubFont: { invalidate() {} } },
|
||||
'../native/firmware-files': { firmwareSha256: hash, writeFirmwareFile: (file, buffer) => fs.writeFileSync(file, new Uint8Array(buffer)) },
|
||||
});
|
||||
const { validateFirmware } = require('../.test-build/app/g2/firmware-ota.js');
|
||||
const stock = await builder.buildStockFirmware(); assert.equal(stock.sha256, patches.CFW_PATCH_SET.baseSha256);
|
||||
assert.equal(validateFirmware(fs.readFileSync(stock.path)).length, 6);
|
||||
const custom = await builder.buildCustomFirmware(); assert.equal(hash(fs.readFileSync(custom.path)), patches.CFW_PATCH_SET.outputSha256);
|
||||
assert.equal(validateFirmware(fs.readFileSync(custom.path)).length, 6);
|
||||
assert.equal(builder.hasExtractedEvenHubFonts(), true);
|
||||
});
|
||||
|
||||
for (const unsolicited of [false, true]) test(`iOS firmware probe ${unsolicited ? 'accepts a version push with device-owned magic' : 'falls back to the left lens after a silent right lens'}`, async () => {
|
||||
const p = require('../.test-build/app/g2/ble-protocol.js'), calls = [];
|
||||
let listener;
|
||||
const str = (field, text) => p.bytes(field, new Uint8Array(Buffer.from(text)));
|
||||
const version = { sid: p.SID.settings, payload: p.concat(p.bytes(4, p.concat(str(5, '2.2.9.22'), str(6, '2.2.9.22'))), str(100, 'faceclaw/13')) };
|
||||
class Link {
|
||||
onMessage(fn) { listener = fn; } async resolve() {} check() {} isConnected() { return true; }
|
||||
async connect(role) { calls.push(`connect:${role}`); }
|
||||
async authenticate(role) { calls.push(`auth:${role}`); }
|
||||
async request(role, sid) {
|
||||
if (sid === p.SID.launch) return {};
|
||||
if (role === 'right') { if (unsolicited) listener(role, version); throw new Error('Timeout'); }
|
||||
return version;
|
||||
}
|
||||
close() { calls.push('close'); }
|
||||
}
|
||||
const { DeviceInfoProbe } = load('app/native/device-info-probe.ios.ts', {
|
||||
'../g2/stock-connection': { StockConnection: Link, StockTimeout: class extends Error {} },
|
||||
'../g2/ble-protocol': p, './ios-bluetooth': { iosBluetooth: () => ({}) },
|
||||
});
|
||||
const info = await new DeviceInfoProbe('r', 'l').run();
|
||||
assert.equal(info.rightVersion, '2.2.9.22'); assert.equal(info.leftVersion, '2.2.9.22'); assert.equal(info.extension, 'faceclaw/13');
|
||||
assert.deepEqual(calls, ['connect:right', 'auth:right', 'connect:left', 'auth:left', 'close']);
|
||||
});
|
||||
|
||||
test('iOS discovery stops pending scans on cancellation and ignores a late permission result', async () => {
|
||||
const listeners = new Set(); let ready = async () => {}, starts = 0, stops = 0;
|
||||
const ble = { state: 5, scanning: false, devices: new Map(),
|
||||
ensureReady: () => ready(), onEvent: fn => { listeners.add(fn); return () => listeners.delete(fn); },
|
||||
startScan: async () => { starts++; }, stopScan: () => { stops++; },
|
||||
};
|
||||
const { DeviceDiscoveryBridge } = load('app/native/device-discovery.ios.ts', {
|
||||
'./ios-bluetooth': { iosBluetooth: () => ble }, './device-discovery-common': {},
|
||||
});
|
||||
const discovery = new DeviceDiscoveryBridge();
|
||||
const pending = discovery.scanCandidates(60_000); await flush(); discovery.stopScan();
|
||||
await assert.rejects(pending, /cancelled/); assert.equal(listeners.size, 0); assert.equal(starts, 1);
|
||||
let release; ready = () => new Promise(resolve => { release = resolve; });
|
||||
const waiting = discovery.scanCandidates(); discovery.stopScan(); release();
|
||||
await assert.rejects(waiting, /cancelled/); assert.equal(starts, 1); assert.equal(stops, 1);
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs'), vm = require('node:vm'), ts = require('typescript');
|
||||
function load(file, modules = {}, globals = {}) {
|
||||
const context = { exports: {}, require: name => modules[name] ?? {}, ...globals };
|
||||
vm.runInNewContext(ts.transpileModule(fs.readFileSync(file, 'utf8'), {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
|
||||
}).outputText, context);
|
||||
return context.exports;
|
||||
}
|
||||
function scanner() {
|
||||
const instances = [];
|
||||
const api = load('app/native/qr-scan.ios.ts', {}, { FaceclawQrScanner: {
|
||||
isAvailable: () => true,
|
||||
new: () => {
|
||||
const native = { startWithCompletion(done) { this.done = done; }, cancel() { this.cancelled = true; this.done(null, null); } };
|
||||
instances.push(native); return native;
|
||||
},
|
||||
} });
|
||||
return { api, instances };
|
||||
}
|
||||
const flush = () => new Promise(resolve => setImmediate(resolve));
|
||||
function layerFixture() {
|
||||
const { api, instances } = scanner();
|
||||
let available = true, pops = 0, renders = 0, launch = async () => {};
|
||||
const saved = [], launched = [], logs = [];
|
||||
const manager = load('app/apps/evenhub/manager.ts');
|
||||
const { LoadAppFromQrLayer } = load('app/apps/developer/load-app.ts', {
|
||||
'../../native/qr-scan': { ...api, isQrScannerAvailable: () => available },
|
||||
'../../ui/dashboard-settings': { developerAppUrlSetting: { set: url => saved.push(url) } },
|
||||
'../evenhub': { isLoadableAppUrl: url => manager.normalizeAppUrl(url) !== null,
|
||||
openEvenHubUrl: async (_ctx, url) => { launched.push(url); await launch(); } },
|
||||
}, { global: { isIOS: true } });
|
||||
const layer = new LoadAppFromQrLayer({ appendLog: text => logs.push(text) });
|
||||
const ctx = { actions: { requestRender: () => renders++ }, stack: { pop: () => { pops++; layer.onRemoved(); } } };
|
||||
return { layer, ctx, instances, saved, launched, logs, get pops() { return pops; }, get renders() { return renders; },
|
||||
available: value => { available = value; }, launch: fn => { launch = fn; } };
|
||||
}
|
||||
|
||||
test('iOS scanner delivers one result, prevents overlapping cameras, and allows a later scan', async () => {
|
||||
const { api, instances } = scanner();
|
||||
assert.equal(api.isQrScannerAvailable(), true);
|
||||
const first = api.scanQrCode();
|
||||
await assert.rejects(api.scanQrCode(), /already open/);
|
||||
instances[0].done('https://example.com/app', null);
|
||||
instances[0].done('https://late.example/app', null);
|
||||
assert.equal(await first, 'https://example.com/app');
|
||||
const second = api.scanQrCode(); api.cancelQrScan();
|
||||
assert.equal(await second, null); assert.equal(instances[1].cancelled, true);
|
||||
});
|
||||
|
||||
test('iOS scanner reports permission/native errors and releases its active scan', async () => {
|
||||
const { api, instances } = scanner();
|
||||
const first = api.scanQrCode(); instances[0].done(null, 'Allow Camera in Settings');
|
||||
await assert.rejects(first, /Allow Camera/);
|
||||
const retry = api.scanQrCode(); instances[1].done('http://dev.local:5173/?key=a%2Fb#app', null);
|
||||
assert.equal(await retry, 'http://dev.local:5173/?key=a%2Fb#app');
|
||||
});
|
||||
|
||||
test('Developer QR saves and launches an app URL exactly once, preserving port/query/fragment', async () => {
|
||||
const f = layerFixture(); f.layer.open(f.ctx); f.layer.open(f.ctx);
|
||||
const url = 'http://dev.local:5173/?key=a%2Fb#app';
|
||||
f.instances[0].done(url, null); await flush();
|
||||
assert.deepEqual(f.saved, [url]); assert.deepEqual(f.launched, [url]);
|
||||
assert.equal(f.pops, 1); assert.equal(f.instances.length, 1);
|
||||
});
|
||||
|
||||
test('Developer QR cancellation, invalid content and permission failure can all be retried', async () => {
|
||||
const f = layerFixture(); f.layer.open(f.ctx); f.instances[0].done(null, null); await flush();
|
||||
assert.match(f.layer.status, /cancelled/);
|
||||
f.layer.handleInput({ type: 'click' }, f.ctx); f.instances[1].done('file:///private/test', null); await flush();
|
||||
assert.match(f.layer.status, /Not a URL/);
|
||||
f.layer.handleInput({ type: 'click' }, f.ctx); f.instances[2].done(null, 'Camera denied'); await flush();
|
||||
assert.match(f.layer.status, /Camera denied/);
|
||||
assert.deepEqual(f.saved, []); assert.deepEqual(f.launched, []); assert.equal(f.pops, 0);
|
||||
f.layer.handleInput({ type: 'click' }, f.ctx); f.instances[3].done('https://example.com/', null); await flush();
|
||||
assert.equal(f.pops, 1);
|
||||
});
|
||||
|
||||
test('leaving Developer QR cancels the camera and suppresses late results', async () => {
|
||||
const f = layerFixture(); f.layer.open(f.ctx);
|
||||
f.layer.handleInput({ type: 'double-click' }, f.ctx);
|
||||
const renders = f.renders;
|
||||
f.instances[0].done('https://example.com/', null); await flush();
|
||||
assert.equal(f.instances[0].cancelled, true);
|
||||
assert.deepEqual(f.saved, []); assert.deepEqual(f.launched, []);
|
||||
assert.equal(f.renders, renders); assert.equal(f.pops, 1);
|
||||
});
|
||||
|
||||
test('leaving while an app launches cannot pop a replacement page or repaint the removed layer', async () => {
|
||||
const f = layerFixture(); let finish;
|
||||
f.launch(() => new Promise(resolve => { finish = resolve; }));
|
||||
f.layer.open(f.ctx); f.instances[0].done('https://example.com/', null); await flush();
|
||||
f.ctx.stack.pop(); const renders = f.renders;
|
||||
finish(); await flush();
|
||||
assert.equal(f.pops, 1); assert.equal(f.renders, renders);
|
||||
});
|
||||
|
||||
test('iOS without a camera explains availability and can retry when available', async () => {
|
||||
const f = layerFixture(); f.available(false); f.layer.open(f.ctx);
|
||||
assert.match(f.layer.status, /physical iPhone/); assert.equal(f.instances.length, 0);
|
||||
f.available(true); f.layer.handleInput({ type: 'click' }, f.ctx);
|
||||
assert.equal(f.instances.length, 1); f.layer.onRemoved(); await flush();
|
||||
});
|
||||
|
||||
test('Developer QR menu is enabled on iOS and pushes then opens its layer', () => {
|
||||
let menu, options; const calls = [];
|
||||
const { createDeveloperAppWindow } = load('app/apps/developer/developer-app.ts', {
|
||||
'../../ui/menu': { MenuLayer: class { constructor(_title, items) { menu = items; } } },
|
||||
'../../ui/shell/geometry': { appViewportSize: () => ({ height: 480 }) },
|
||||
'../../ui/shell/in-process-window': { YieldAtRootLayer: class {}, createInProcessWindow: value => { options = value; return {}; } },
|
||||
'./load-app': { LoadAppFromQrLayer: class { open() { calls.push('open'); } } },
|
||||
}, { global: { isIOS: true } });
|
||||
createDeveloperAppWindow({}, {});
|
||||
const qr = menu.find(item => item.label === 'Load app from QR code');
|
||||
assert.ok(!qr.disabled); qr.onSelect({ stack: { push: () => calls.push('push') } });
|
||||
assert.deepEqual(calls, ['push', 'open']);
|
||||
});
|
||||
@@ -17,6 +17,9 @@
|
||||
"../app/apps/terminal/hub-header.ts",
|
||||
"../app/g2/ios-peripheral-identity.ts",
|
||||
"../app/g2/glasses-session.ts",
|
||||
"../app/g2/stock-connection.ts",
|
||||
"../app/g2/firmware-ota.ts",
|
||||
"../app/g2/flash-prompt-protocol.ts",
|
||||
"../app/graphics/surface-compositor.ts",
|
||||
"../app/graphics/image.ts",
|
||||
"../app/phone-ui/phone-gestures.ts",
|
||||
|
||||
+3
-3
@@ -5,9 +5,9 @@ module.exports = (env) => {
|
||||
webpack.init(env);
|
||||
|
||||
if (env.ios) {
|
||||
// The initial iOS UI is constructed in code. Skip automatic registration
|
||||
// of every XML page (and its Android-only service/worker dependencies).
|
||||
// Explicit imports can still share any platform-independent app code.
|
||||
// iOS explicitly registers its shared onboarding XML pages in
|
||||
// onboarding-register.ios.ts. Skip Android's remaining pages and
|
||||
// their Android-only service/worker dependencies.
|
||||
webpack.chainWebpack((config) => {
|
||||
const entry = config.entry('bundle');
|
||||
entry.values().forEach((value) => {
|
||||
|
||||
Reference in new issue
Block a user