Refactor: g2flash protocol doesn't have so many magic numbers

This commit is contained in:
James Babcock committed 2026-09-22 16:27:04 -07:00
1 parent 306accf06d
commit ea9bfae6af
22 files changed
+231 -99

No files matched your search

+3 -2
View File
@@ -1,3 +1,4 @@
import { CFW_MSG_BOUNDING_BOX } from "./cfw-message-type";
import { concat, rle4 } from './ble-protocol'
/** Android BleImageOptimizer's mode-3 changed rectangle. Coordinates are in
@@ -29,7 +30,7 @@ export function buildBoundingBoxPayload(previous: Uint8Array | null, next: Uint8
const start = (top + y) * stride + left / 2
region.set(next.subarray(start, start + regionStride), y * regionStride)
}
return concat(new Uint8Array([3, left / 4, top / 2, boxWidth / 4, boxHeight / 2,
return concat(new Uint8Array([CFW_MSG_BOUNDING_BOX, left / 4, top / 2, boxWidth / 4, boxHeight / 2,
frameId & 255, (frameId >>> 8) & 255]), rle4(region))
}
@@ -41,7 +42,7 @@ export function buildFullFrameBands(packed: Uint8Array, width: number, height: n
let id = firstId
for (let top = 0; top < height; top += 64) {
const rows = Math.min(64, height - top)
bands.push(concat(new Uint8Array([3, 0, top / 2, width / 4, rows / 2, id & 255, id >>> 8]),
bands.push(concat(new Uint8Array([CFW_MSG_BOUNDING_BOX, 0, top / 2, width / 4, rows / 2, id & 255, id >>> 8]),
rle4(packed.subarray(top * width / 2, (top + rows) * width / 2))))
id = id >= 0xfffe ? 1 : id + 1
}
+36
View File
@@ -0,0 +1,36 @@
/** Message IDs and header flags mirror g2flash/patches/zlib_glue.c. */
/** Retired wire ID; used internally by the phone optimizer. */
export const CFW_MSG_BOUNDING_BOX = 3
export const CFW_MSG_BUZZER = 5
/** Retired wire ID; used internally by the phone optimizer. */
export const CFW_MSG_FULL_FRAME = 6
export const CFW_MSG_DIAGNOSTICS = 7
/** Retired wire ID; used internally by the phone optimizer. */
export const CFW_MSG_MULTI_SEGMENT = 8
/** Retired wire ID; used internally by the phone optimizer. */
export const CFW_MSG_RECT_COPY = 9
export const CFW_MSG_COMPASS = 10
export const CFW_MSG_CLEANUP = 11
export const CFW_MSG_RETIRED_12 = 12
export const CFW_MSG_RETIRED_13 = 13
export const CFW_MSG_RETIRED_14 = 14
/** Retired wire ID; used internally by the phone optimizer. */
export const CFW_MSG_STOCK_FONT_STRING = 15
export const CFW_MSG_AMBIENT_LIGHT = 16
export const CFW_MSG_RING_BATTERY = 17
export const CFW_MSG_RETIRED_CACHE_WRITE = 18
/** Retired wire ID; used internally by the phone optimizer. */
export const CFW_MSG_CACHED_IMAGE = 19
/** Retired wire ID; used internally by the phone optimizer. */
export const CFW_MSG_CACHED_TEXT = 20
export const CFW_MSG_UPLOAD_RESOURCE = 21
export const CFW_MSG_EVICT_RESOURCE = 22
export const CFW_MSG_PANEL_READ = 23
export const CFW_MSG_PANEL_WRITE = 24
export const CFW_MSG_PANEL_PATTERN = 25
export const CFW_MSG_DRAW_CALLS = 26
export const CFW_MSG_SET_ROOT_DISPLAY_LIST = 27
export const CFW_MSG_PRESENT = 28
export const CFW_MSG_CREATE_SURFACE = 29
export const CFW_MSG_TYPE_MASK = 127
export const CFW_MSG_FLAG_LENSES_DIFFER = 128
+1
View File
@@ -1,6 +1,7 @@
import { concat, crc16, SID } from './ble-protocol'
declare const require: (name: string) => any
/** Mirrors CFW_MESSAGE_MAX in g2flash/patches/message_transport.h. */
export const CFW_MAX_MESSAGE = 65535
export type CfwAck = { nack: boolean; streamId: number; messageId: number; lens: number; size: number; checksum: number }
const u16 = (data: Uint8Array, offset: number) => data[offset] | (data[offset + 1] << 8)
+6 -5
View File
@@ -1,14 +1,15 @@
import { CFW_MSG_BOUNDING_BOX, CFW_MSG_DRAW_CALLS, CFW_MSG_FULL_FRAME, CFW_MSG_MULTI_SEGMENT, CFW_MSG_TYPE_MASK } from "./cfw-message-type";
/** Adapter for raster-only senders; optimized legacy layouts remain internal to the phone. */
export function drawMessages(payload: Uint8Array, width = 640, height = 480): Uint8Array[] {
const word = (v: number) => [v & 255, (v >>> 8) & 255]
const mode = payload[0] & 127
const mode = payload[0] & CFW_MSG_TYPE_MASK
let calls: Uint8Array[]
if (mode === 8) {
if (mode === CFW_MSG_MULTI_SEGMENT) {
const output: Uint8Array[] = []; let p=2
for(let i=0;i<payload[1];i++) { const n=payload[p] | payload[p+1]<<8; p+=2; output.push(...drawMessages(payload.subarray(p,p+n),width,height));p+=n }
return output
} else if (mode === 3) calls=[new Uint8Array([1,0,0,...payload.subarray(1,5),...payload.subarray(7)])]
else if(mode === 6) calls=[new Uint8Array([1,0,1,0,0,0,0,...word(width),...word(height),...payload.subarray(1)])]
} else if (mode === CFW_MSG_BOUNDING_BOX) calls=[new Uint8Array([1,0,0,...payload.subarray(1,5),...payload.subarray(7)])]
else if(mode === CFW_MSG_FULL_FRAME) calls=[new Uint8Array([1,0,1,0,0,0,0,...word(width),...word(height),...payload.subarray(1)])]
else throw new Error(`Unsupported raster draw ${mode}`)
return calls.map(call => new Uint8Array([26,1,0,...word(call.length),...call]))
return calls.map(call => new Uint8Array([CFW_MSG_DRAW_CALLS,1,0,...word(call.length),...call]))
}
+7 -6
View File
@@ -1,3 +1,4 @@
import { CFW_MSG_CLEANUP, CFW_MSG_COMPASS, CFW_MSG_EVICT_RESOURCE, CFW_MSG_FULL_FRAME, CFW_MSG_PRESENT } from "./cfw-message-type";
import { drawMessages } from './draw-protocol'
import { setBrightness } from './brightness-protocol'
import { AncsClient, ANCS_FIRMWARE_VERSION } from './ancs-client'
@@ -481,7 +482,7 @@ export class GlassesSession {
const enabled = !this.compassStopping && this.compassWanted
if (this.compassSent === enabled) return
// Same CFW mode 10, 100 ms report interval and zero minimum change as Android.
await this.requestCfw('left', new Uint8Array(enabled ? [10, 2, 100, 0, 0, 0] : [10, 0]))
await this.requestCfw('left', new Uint8Array(enabled ? [CFW_MSG_COMPASS, 2, 100, 0, 0, 0] : [CFW_MSG_COMPASS, 0]))
if (generation === this.generation) this.compassSent = enabled
}).catch(error => { if (generation === this.generation) this.fail(error, true) })
this.compassWork = work
@@ -497,7 +498,7 @@ export class GlassesSession {
this.timer = setTimeout(() => { this.timer = null; void this.pump() }, delay)
}
private canSendDisplay(): boolean {
if (this.displaySending?.commands[this.displaySending.offset][0] === 22 && this.cfwPending.length) return false
if (this.displaySending?.commands[this.displaySending.offset][0] === CFW_MSG_EVICT_RESOURCE && this.cfwPending.length) return false
// Also bound completed frames retained behind a missing/out-of-order ACK.
return this.displayInFlight < DISPLAY_WINDOW_SIZE && !!(this.displaySending ||
(this.latest && !this.charging && this.displayFrames.length < DISPLAY_WINDOW_SIZE))
@@ -520,12 +521,12 @@ export class GlassesSession {
this.log(`Display textures (${texturePlan.resourceCommands.length} resource commands, cache=${texturePlan.usedBytes}B)`)
} else {
const delta = buildBoundingBoxPayload(this.lastEnqueued, packed, 640, 480, this.nextImageFrameId)
const payload = delta ?? protocol.concat(new Uint8Array([6]), protocol.rle4(packed))
const payload = delta ?? protocol.concat(new Uint8Array([CFW_MSG_FULL_FRAME]), protocol.rle4(packed))
if (delta) this.nextImageFrameId = this.nextImageFrameId >= 0xfffe ? 1 : this.nextImageFrameId + 1
commands = payload.length <= CFW_MAX_MESSAGE - 16 ? [payload] : buildFullFrameBands(packed, 640, 480, this.nextImageFrameId)
if (payload.length > CFW_MAX_MESSAGE - 16) for (const _ of commands)
this.nextImageFrameId = this.nextImageFrameId >= 0xfffe ? 1 : this.nextImageFrameId + 1
commands = [...commands.flatMap(command => drawMessages(command)), new Uint8Array([28])]
commands = [...commands.flatMap(command => drawMessages(command)), new Uint8Array([CFW_MSG_PRESENT])]
this.log(`Display ${delta ? 'bbox' : 'full'} (${commands.length} CFW commands)`)
}
this.displaySending = { packed, commands, offset: 0, pending: 0 }
@@ -533,7 +534,7 @@ export class GlassesSession {
}
const frame = this.displaySending
// Drain earlier commands before evicting: recovery may replay any unresolved draw/upload.
if (frame.commands[frame.offset][0] === 22 && this.cfwPending.length) return
if (frame.commands[frame.offset][0] === CFW_MSG_EVICT_RESOURCE && this.cfwPending.length) return
const payload = frame.commands[frame.offset++]
frame.pending++; this.displayInFlight++
if (frame.offset >= frame.commands.length) this.displaySending = null
@@ -634,7 +635,7 @@ export class GlassesSession {
this.update('disconnecting', 'Disconnecting…'); this.reset()
try {
if (cleanup) {
await this.requestCfw('left', new Uint8Array([11]))
await this.requestCfw('left', new Uint8Array([CFW_MSG_CLEANUP]))
}
} catch (error) { this.log(`Disconnect cleanup: ${this.message(error)}`) }
finally { this.reset(); this.closeLinks(); this.update('disconnected', 'Preview only') }
+4 -3
View File
@@ -1,3 +1,4 @@
import { CFW_MSG_BOUNDING_BOX, CFW_MSG_CREATE_SURFACE, CFW_MSG_PRESENT, CFW_MSG_UPLOAD_RESOURCE } from "../g2/cfw-message-type";
import { GrayImage } from "../graphics/image"
import { encodeShellScene } from "../graphics/shell-scene"
import { decodeImageBytes } from './image-bytes.ios'
@@ -44,7 +45,7 @@ export function runKotlinProtocolSmokeTest(): void {
textured.submitSurfaceFrame('icon', white, { x: 0, y: 0, width: 2, height: 2 }, draw.buffer)
const snapshot = textured.compositeFrame(), packed = protocol.packGray4(snapshot.pixels, 4, 2)
const cold = textures.plan(null, packed, snapshot.textures, 1)
assert(!!cold && cold.resourceCommands.some(command => command[0] === 21) && cold.payload[0] === 28, 'texture upload and draw')
assert(!!cold && cold.resourceCommands.some(command => command[0] === CFW_MSG_UPLOAD_RESOURCE) && cold.payload[0] === CFW_MSG_PRESENT, 'texture upload and draw')
assert(textures.plan(null, packed, snapshot.textures, 1)?.resourceCommands.length === 0, 'texture reuse')
textures.reset()
assert((textures.plan(null, packed, snapshot.textures, 1)?.resourceCommands.length ?? 0) > 0, 'texture reset')
@@ -55,9 +56,9 @@ export function runKotlinProtocolSmokeTest(): void {
const selectedSnapshot = selectedPreview.compositeFrame()
assert(selectedSnapshot.pixels[10] === 240 && selectedSnapshot.pixels[9] === 0, 'menu selection depth and bridge')
const selectedPlan = new IosTexturePlanner().plan(null, protocol.packGray4(selectedSnapshot.pixels, 8, 4), selectedSnapshot.textures, 1)
assert(!!selectedPlan && selectedPlan.payload[0] === 28 && selectedPlan.resourceCommands.some(c => c[0] === 29), 'menu resource planning')
assert(!!selectedPlan && selectedPlan.payload[0] === CFW_MSG_PRESENT && selectedPlan.resourceCommands.some(c => c[0] === CFW_MSG_CREATE_SURFACE), 'menu resource planning')
const changed = new Uint8Array(16); changed[0] = 255
assert(buildBoundingBoxPayload(new Uint8Array(16), changed, 8, 4, 1)?.[0] === 3, 'image update')
assert(buildBoundingBoxPayload(new Uint8Array(16), changed, 8, 4, 1)?.[0] === CFW_MSG_BOUNDING_BOX, 'image update')
assert(lvglMetrics('/nonexistent/faceclaw-font').length === 0, 'font bridge')
const compass = protocol.decodeCompassInput({ sid: 8, flag: 1, command: 15, magic: 0,
payload: new Uint8Array([8, 15, 16, 0, 82, 3, 8, 231, 2, 162, 6, 12, 67, 77, 1, 3, 2, 3, 140, 0, 152, 186, 220, 254]) })
+3 -2
View File
@@ -1,3 +1,4 @@
import { CFW_MSG_BUZZER } from "../g2/cfw-message-type";
/**
* Sound-effect catalog for the CFW buzzer tone sequencer (load_image_z mode 5
* kind 4). Ported from g2-kit-unofficial/examples/tunes.ts.
@@ -19,14 +20,14 @@ export type Step = { freq: number; duty?: number; ms: number };
/** One or more phrases; each phrase is one sequencer message. */
export type Effect = Step[] | Step[][];
/** Firmware cap: steps per mode-5 kind-4 message. */
/** Mirrors CFW_SEQ_MAX in g2flash/patches/cfw_context.h. */
export const CFW_SEQ_MAX = 48;
/** Build the wire buffer: [5][4][nSteps][ freqLo,freqHi,duty,msLo,msHi ]*n. */
export function buildSoundSequencePayload(steps: Step[]): Uint8Array {
const count = Math.min(steps.length, CFW_SEQ_MAX);
const out = new Uint8Array(3 + count * 5);
out[0] = 0x05;
out[0] = CFW_MSG_BUZZER;
out[1] = 0x04;
out[2] = count;
for (let index = 0; index < count; index++) {