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
@@ -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
|
||||
}
|
||||
Reference in new issue
Block a user