Add bluetooth keyboard support

G2 only: You can pair the glasses with a bluetooth keyboard. It will
relay key events, and you can use it to type in some apps and to
navigate the UI.
This commit is contained in:
James Babcock committed 2026-11-15 01:54:54 -08:00
1 parent 9372b2742c
commit fd3c26333f
46 files changed
+3867 -41

No files matched your search

+559
View File
@@ -0,0 +1,559 @@
/**
* The phone side of the CFW keyboard bridge for one glasses session: the
* client, the remembered keyboard, reconnecting it, and what the UI shows.
* The session hands it field-131 records and a way to send controls; the
* rest stays in here. Modelled on the Glassly app's G2KeyboardBridge (MIT).
*
* The firmware keeps nothing across a reboot (it comes back with the bridge
* off), and holds the keyboard's connection only while told to. So the
* remembered keyboard is brought back whenever the glasses link comes up and
* whenever the keyboard drops, backing off while it stays away. The
* discovered handle mapping is good for one connection and is never stored.
* No platform imports: this runs under node in the tests.
*/
import { KeyboardClient, KeyboardClientError, type KeyboardStatus } from "./client";
import type { HidKeyEvent } from "./hid";
import {
KeyboardDm,
KeyboardError,
mergeKeyboardAdverts,
parseKeyboardAddress,
type KeyboardAdvert,
} from "./protocol";
export type SavedKeyboard = { address: string; addressType: number; name: string };
export type KeyboardBridgeState =
/** No glasses link that can host a keyboard. */
| "unavailable"
| "idle"
| "scanning"
| "connecting"
| "pairing"
| "configuring"
| "connected"
| "error";
/** A pairing step waiting on the user. */
export type KeyboardPairingPrompt =
/** Type this on the keyboard, then Enter. */
| { kind: "display"; pin: number }
/** Confirm both sides show this value (answerCompare). */
| { kind: "compare"; value: number }
/** The keyboard shows a code to enter here (answerPasskey). */
| { kind: "entry" };
export type KeyboardBridgeSnapshot = {
state: KeyboardBridgeState;
saved: SavedKeyboard | null;
/** Name of the keyboard being connected or in use. */
activeName: string;
error: string;
pairing: KeyboardPairingPrompt | null;
/** Advertisers from the last scan, HID devices first, strongest first. */
scanResults: KeyboardAdvert[];
/** A user-started scan or connect is running. */
busy: boolean;
/** The remembered keyboard is away and the bridge keeps trying to bring it back. */
waiting: boolean;
};
export type KeyboardBridgeHost = {
/** Queue a control record on the live session; false when there is none. */
send(record: Uint8Array): boolean;
loadSaved(): SavedKeyboard | null;
storeSaved(saved: SavedKeyboard | null): void;
/** Key transitions from the keyboard (including forced releases). */
onKeys(events: HidKeyEvent[]): void;
/** The keyboard stopped being usable; drop held-key state without releases. */
onKeyboardGone(): void;
/** Something in snapshot() changed. */
onChanged(): void;
/**
* A line for the log. `routine` marks the ones that repeat for as long as
* a remembered keyboard stays away, which only a verbose log wants.
*/
log(line: string, routine?: boolean): void;
/** A fresh six-digit pairing passkey from a good random source. */
randomPasskey?(): number;
/**
* Whether looking for an absent keyboard is worthwhile now. Each attempt
* has the glasses' radio listening for the keyboard for up to half a
* minute, so the owner limits it to when the glasses are in use, and calls
* retryNow() when that starts. Default: always.
*/
shouldReconnect?(): boolean;
};
/** Delay before each automatic attempt after a failure; the last one repeats. */
const RECONNECT_BACKOFF_MS = [2_000, 5_000, 10_000, 20_000, 30_000];
/** After the glasses link comes up, before the first attempt. */
const RESUME_DELAY_MS = 1_000;
/** After the keyboard drops (it may just be going to sleep). */
const DROP_RETRY_DELAY_MS = 2_000;
const RELEASE_POLLS = 20;
const RELEASE_POLL_MS = 150;
export class KeyboardBridge {
private client: KeyboardClient | null = null;
private available = false;
private state: KeyboardBridgeState = "unavailable";
private saved: SavedKeyboard | null;
private activeName = "";
private error = "";
private pairing: KeyboardPairingPrompt | null = null;
private scanResults: KeyboardAdvert[] = [];
/** A user-started scan/connect holds the bridge. */
private busy = false;
/** The keyboard is connected, encrypted and subscribed. */
private ready = false;
private userDisconnected = false;
/** The keyboard was let go while the glasses were out of reach; tell the firmware when they are back. */
private releaseOnLink = false;
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private reconnectAttempt = 0;
/** Bumped whenever the client is replaced; work started for an older one stops quietly. */
private generation = 0;
constructor(private readonly host: KeyboardBridgeHost) {
this.saved = host.loadSaved();
}
snapshot(): KeyboardBridgeSnapshot {
return {
state: this.state,
saved: this.saved,
activeName: this.activeName,
error: this.error,
pairing: this.pairing,
scanResults: sortAdverts(this.scanResults),
busy: this.busy,
waiting: this.available && !!this.saved && !this.ready && !this.userDisconnected && !this.busy,
};
}
/** True while key events can arrive. */
isConnected(): boolean {
return this.ready;
}
// ---------- Link lifecycle (driven by the session owner) ----------
/** The glasses link is up on firmware with the bridge: bring the remembered keyboard back. */
linkReady(): void {
if (this.available) return;
this.available = true;
this.userDisconnected = false;
this.reconnectAttempt = 0;
this.error = "";
const client = this.replaceClient();
this.setState("idle");
if (this.saved && !this.releaseOnLink) {
this.scheduleReconnect(RESUME_DELAY_MS);
} else if (this.releaseOnLink && client) {
this.userDisconnected = !!this.saved;
client.query().then((status) => {
if (status.enabled || status.conn) return client.disable();
}).catch(() => {});
}
this.releaseOnLink = false;
}
/** The glasses link is gone. Only the remembered keyboard survives. */
linkLost(): void {
if (!this.available && !this.client) return;
this.available = false;
this.cancelReconnect();
this.generation++;
this.client?.close();
this.client = null;
this.busy = false;
this.pairing = null;
this.error = "";
this.dropKeyboard();
this.setState("unavailable");
}
/**
* The app is about to close the glasses link on purpose: tell the firmware
* to let the keyboard go, so it isn't left attached to glasses nobody is
* listening to. Best effort; nothing waits for the answer.
*/
linkClosing(): void {
const client = this.client;
if (!client || !this.available || !client.status.enabled) return;
client.disable().catch(() => {});
}
/** One field-131 payload from the session. */
accept(payload: Uint8Array): void {
this.client?.accept(payload);
}
/**
* The keyboard may be reachable now, or is wanted now (the display woke):
* if it is away and the bridge is waiting out a backoff, try at once.
*/
retryNow(): void {
if (!this.available || !this.saved || this.ready || this.userDisconnected || this.busy) return;
// No timer means an attempt is already in flight.
if (this.reconnectTimer === null) return;
this.reconnectAttempt = 0;
this.scheduleReconnect(0);
}
// ---------- Commands (the settings UI) ----------
/** Scan for about five seconds; results accumulate in the snapshot as they arrive. */
async scan(): Promise<KeyboardAdvert[]> {
const client = this.beginUserOperation();
const generation = this.generation;
this.scanResults = [];
this.error = "";
this.setState("scanning");
try {
await this.releaseLink(client);
await client.enable();
await client.scan();
if (generation === this.generation) this.setState("idle");
} catch (e) {
if (generation === this.generation) this.fail(e);
throw friendly(e);
} finally {
if (generation === this.generation) this.endUserOperation();
}
return sortAdverts(this.scanResults);
}
/** Connect, pair and subscribe a keyboard, then remember it. */
async connect(keyboard: SavedKeyboard): Promise<void> {
if (!parseKeyboardAddress(keyboard.address) || keyboard.addressType < 0 || keyboard.addressType > 3) {
throw new KeyboardClientError("Invalid keyboard address");
}
const client = this.beginUserOperation();
const generation = this.generation;
this.userDisconnected = false;
try {
await this.connectWith(client, generation, keyboard, false);
} finally {
if (generation === this.generation) this.endUserOperation();
}
}
/** Try the remembered keyboard again now. */
async reconnect(): Promise<void> {
if (!this.saved) throw new KeyboardClientError("No remembered keyboard");
await this.connect(this.saved);
}
/** Drop the keyboard but keep it remembered. No automatic reconnect until the next explicit connect or glasses session. */
async disconnect(): Promise<void> {
this.userDisconnected = true;
this.cancelReconnect();
const client = this.replaceClient();
// A scan or connect this interrupts no longer owns the bridge.
this.busy = false;
this.dropKeyboard();
this.pairing = null;
this.error = "";
if (!client) {
this.releaseOnLink = true;
this.setState("unavailable");
return;
}
this.setState("idle");
try {
await client.query();
await client.disable();
} catch (e) {
this.host.log(`keyboard disconnect: ${messageOf(e)}`);
}
}
/** Forget the remembered keyboard. The glasses keep their bond with it. */
async forget(): Promise<void> {
this.saved = null;
this.host.storeSaved(null);
await this.disconnect();
this.scanResults = [];
this.activeName = "";
this.host.onChanged();
}
/** Answer a "compare" pairing prompt. */
async answerCompare(accept: boolean): Promise<void> {
if (!this.client || this.pairing?.kind !== "compare") throw new KeyboardClientError("No pairing comparison is pending");
this.pairing = null;
this.host.onChanged();
await this.client.confirm(accept);
}
/** Answer an "entry" pairing prompt with the code the keyboard shows. */
async answerPasskey(pin: number): Promise<void> {
if (!this.client || this.pairing?.kind !== "entry") throw new KeyboardClientError("No pairing code is pending");
this.pairing = null;
this.host.onChanged();
await this.client.authenticate(pin);
}
// ---------- Internals ----------
private beginUserOperation(): KeyboardClient {
if (!this.available) throw new KeyboardClientError("Connect to G2 glasses running Faceclaw firmware first");
if (this.busy) throw new KeyboardClientError("Another keyboard operation is in progress");
// An automatic attempt may be mid-flight (a sleeping keyboard holds one
// for up to 30 s): a fresh client fails it at once and takes over.
this.cancelReconnect();
const client = this.replaceClient()!;
this.dropKeyboard();
this.pairing = null;
this.busy = true;
return client;
}
private endUserOperation(): void {
this.busy = false;
this.host.onChanged();
}
/** Close the current client and, while the link is up, start a fresh one. */
private replaceClient(): KeyboardClient | null {
this.generation++;
this.client?.close();
this.client = null;
if (!this.available) return null;
const generation = this.generation;
const live = () => generation === this.generation;
const client = new KeyboardClient(
(record) => live() && this.host.send(record),
{
keys: (events) => { if (live() && this.ready) this.host.onKeys(events); },
advert: (advert) => { if (live()) this.addAdvert(advert); },
status: (status) => { if (live()) this.onStatus(status); },
dm: (event, status) => { if (live()) this.onDm(event, status); },
passkeyDisplay: (pin) => { if (live()) this.prompt({ kind: "display", pin }); },
passkeyRequest: () => { if (live()) this.prompt({ kind: "entry" }); },
compareRequest: (value) => { if (live()) this.prompt({ kind: "compare", value }); },
servicesChanged: () => { if (live()) this.onServicesChanged(); },
error: (message) => { if (live()) this.host.log(`keyboard: ${message}`); },
log: (line) => { if (live()) this.host.log(`keyboard setup: ${line}`); },
},
{ randomPasskey: this.host.randomPasskey ? () => this.host.randomPasskey!() : undefined },
);
this.client = client;
return client;
}
private async connectWith(
client: KeyboardClient,
generation: number,
keyboard: SavedKeyboard,
resume: boolean,
): Promise<void> {
const live = () => generation === this.generation;
this.error = "";
this.activeName = keyboard.name;
this.setState("connecting");
try {
const status = await client.query();
if (resume && status.enabled && status.connected && status.encrypted) {
// The glasses kept the keyboard through a phone-side drop (or an app
// restart): only the handle mapping is missing.
this.host.log("keyboard still connected to the glasses; rediscovering");
} else {
await this.releaseLink(client);
await client.enable();
await client.connect(keyboard.addressType, parseKeyboardAddress(keyboard.address)!);
}
if (!live()) return;
this.pairing = null;
this.setState("configuring");
const config = await client.configure();
if (!live()) return;
this.ready = true;
this.reconnectAttempt = 0;
// The list was for choosing; it is stale from here on.
this.scanResults = [];
if (!sameKeyboard(this.saved, keyboard)) {
this.saved = { ...keyboard };
this.host.storeSaved(this.saved);
}
this.host.log(
`keyboard ready: ${keyboard.name || keyboard.address}, ${config.watched.length} of ` +
`${config.reports.filter((r) => r.type === 1).length} input reports subscribed, epoch ${config.epoch}`);
this.setState("connected");
} catch (e) {
if (!live()) return;
this.ready = false;
this.pairing = null;
if (resume) {
// An automatic attempt: a keyboard that is asleep or out of range is
// the ordinary case, not an error to put in front of the user.
this.host.log(`keyboard reconnect: ${messageOf(friendly(e))}`, true);
this.setState("idle");
} else {
this.fail(e);
}
throw friendly(e);
}
}
/**
* The firmware refuses SCAN and CONNECT while it still owns a keyboard
* slot, and an interrupted connect keeps initiating until the close lands.
* DISABLE is epoch-checked and a fresh client hasn't seen the epoch yet,
* so QUERY first (it isn't, and its answer carries the epoch), then wait
* for the slot to clear.
*/
private async releaseLink(client: KeyboardClient): Promise<void> {
const status = await client.query();
if (!status.enabled && status.conn === 0) return;
await client.disable();
for (let i = 0; i < RELEASE_POLLS; i++) {
if ((await client.query()).conn === 0) return;
await delay(RELEASE_POLL_MS);
}
throw new KeyboardClientError("The glasses are still closing the previous keyboard link; try again in a moment");
}
private cancelReconnect(): void {
if (this.reconnectTimer !== null) clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
private scheduleReconnect(delayMs: number): void {
this.cancelReconnect();
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = null;
void this.attemptReconnect();
}, delayMs);
}
private async attemptReconnect(): Promise<void> {
const saved = this.saved;
const client = this.client;
if (!this.available || !client || !saved || this.userDisconnected || this.ready || this.busy) return;
if (this.host.shouldReconnect && !this.host.shouldReconnect()) {
this.parkFirmware(client);
this.scheduleReconnect(RECONNECT_BACKOFF_MS[RECONNECT_BACKOFF_MS.length - 1]!);
return;
}
const generation = this.generation;
try {
await this.connectWith(client, generation, saved, true);
} catch {
if (generation !== this.generation || !this.available || this.userDisconnected) return;
// Keyboards sleep, and the ring's own scan can hold the controller
// (BUSY): keep trying, less often, while the glasses stay up.
const backoff = RECONNECT_BACKOFF_MS[Math.min(this.reconnectAttempt, RECONNECT_BACKOFF_MS.length - 1)]!;
this.reconnectAttempt++;
this.scheduleReconnect(backoff);
}
}
/**
* While it is enabled the firmware bridge runs a 20 ms timer and reports
* its status every second, keyboard or no keyboard. When nothing will be
* tried for a while, switch it off; the next attempt enables it again.
*/
private parkFirmware(client: KeyboardClient): void {
if (!client.status.enabled) return;
client.disable().catch(() => {});
}
private onStatus(status: KeyboardStatus): void {
if (this.ready && (!status.connected || !status.encrypted)) this.keyboardDropped("status");
else if (this.state === "connecting" && status.connected && !status.encrypted) this.setState("pairing");
}
private onDm(event: number, status: number): void {
if (event === KeyboardDm.connClose || event === KeyboardDm.pairFailed || event === KeyboardDm.encryptFailed) {
this.host.log(`keyboard DM event 0x${event.toString(16)} status ${status}`);
if (this.ready) this.keyboardDropped("dm");
}
}
private onServicesChanged(): void {
this.host.log("keyboard services changed; rediscovering");
this.dropKeyboard();
this.setState("idle");
if (this.saved && !this.userDisconnected && !this.busy) this.scheduleReconnect(0);
}
private keyboardDropped(reason: string): void {
this.host.log(`keyboard disconnected (${reason})`);
this.dropKeyboard();
this.setState("idle");
if (this.saved && !this.userDisconnected && !this.busy) this.scheduleReconnect(DROP_RETRY_DELAY_MS);
}
/** The keyboard is no longer usable: tell the host once. */
private dropKeyboard(): void {
if (!this.ready) return;
this.ready = false;
this.host.onKeyboardGone();
}
private addAdvert(advert: KeyboardAdvert): void {
const index = this.scanResults.findIndex(
(a) => a.address === advert.address && a.addressType === advert.addressType);
if (index < 0) {
this.scanResults.push(advert);
} else {
const merged = mergeKeyboardAdverts(this.scanResults[index]!, advert);
const old = this.scanResults[index]!;
if (merged.name === old.name && merged.hid === old.hid && merged.rssi === old.rssi) return;
this.scanResults[index] = merged;
}
this.host.onChanged();
}
private prompt(pairing: KeyboardPairingPrompt): void {
this.pairing = pairing;
this.setState("pairing");
}
private setState(next: KeyboardBridgeState): void {
this.state = next;
if (next !== "pairing" && next !== "connecting") this.pairing = null;
this.host.onChanged();
}
private fail(error: unknown): void {
this.error = messageOf(friendly(error));
this.host.log(`keyboard error: ${this.error}`);
this.setState("error");
}
}
function sameKeyboard(a: SavedKeyboard | null, b: SavedKeyboard): boolean {
return !!a && a.address === b.address && a.addressType === b.addressType && a.name === b.name;
}
function sortAdverts(adverts: readonly KeyboardAdvert[]): KeyboardAdvert[] {
return [...adverts].sort((a, b) => Number(b.hid) - Number(a.hid) || b.rssi - a.rssi);
}
/**
* Firmware BUSY nearly always means the ring's own scan or reconnect holds
* the radio; say that rather than the raw control error.
*/
function friendly(error: unknown): Error {
if (error instanceof KeyboardClientError && error.code === KeyboardError.busy) {
return new KeyboardClientError(
"The glasses' radio is busy (usually the ring reconnecting). Wait a few seconds and try again.", error.code);
}
if (error instanceof KeyboardClientError && error.code === KeyboardError.noSpace) {
return new KeyboardClientError(
"The glasses have no room for another connection or pairing.", error.code);
}
return error instanceof Error ? error : new Error(String(error));
}
function messageOf(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function delay(ms: number): Promise<void> {
return new Promise<void>((resolve) => setTimeout(resolve, ms));
}
+709
View File
@@ -0,0 +1,709 @@
/**
* Transport-independent client for the CFW keyboard bridge: enable, scan,
* connect and pair a keyboard through the glasses, discover its HID service
* over the relayed ATT operations, subscribe its input reports, and decode
* them into key transitions. From the reference client in g2flash demos/
* (keyboard-client.ts), with the fixes its use in the Glassly app turned up.
*
* The firmware keeps almost no policy: it owns the connection and the bond,
* and forwards one ATT request at a time. Everything HID lives here. Handle
* numbers found by configure() are only good for one connection epoch.
* No platform imports: this runs under node in the tests.
*/
import { HidKeys, parseReportMap, reportHasKeys, type HidKeyEvent, type HidReport } from "./hid";
import {
KeyboardDm,
KeyboardError,
KeyboardKind,
KeyboardOp,
KeyboardRecords,
keyboardControl,
keyboardErrorName,
le16,
parseKeyboardAdvert,
u16,
u32,
type KeyboardAdvert,
type KeyboardRecord,
} from "./protocol";
/** Queue one field-130 control record; false when the glasses link can't take it now. */
export type KeyboardTransport = (record: Uint8Array) => boolean;
export type KeyboardStatus = {
enabled: boolean;
/** The firmware's connection id for the keyboard, 0 when it owns none. */
conn: number;
connected: boolean;
encrypted: boolean;
scanning: boolean;
};
export type KeyboardClientEvents = {
/** Key transitions from one input report (or the releases a gap forces). */
keys?(events: HidKeyEvent[]): void;
advert?(advert: KeyboardAdvert): void;
status?(status: KeyboardStatus): void;
/** The stream may have lost records; held keys were released. */
gap?(): void;
/** Device-manager event from the glasses' BLE host (KeyboardDm). */
dm?(event: number, status: number): void;
/** The keyboard shows a six-digit passkey; answer with authenticate(). */
passkeyRequest?(): void;
/** We chose a passkey and answered with it; the user types it on the keyboard, then Enter. */
passkeyDisplay?(pin: number): void;
/** Numeric comparison: answer with confirm() once the user has compared. */
compareRequest?(value: number): void;
/** The keyboard's GATT table changed; the mapping is void until configure() runs again. */
servicesChanged?(): void;
error?(message: string): void;
/** Setup diagnostics: the keyboard's attribute table and what was made of it. Never key contents. */
log?(line: string): void;
};
export type KeyboardReport = {
/** Handle of the HID service declaration the report belongs to. */
service: number;
handle: number;
id: number;
/** 1 input, 2 output, 3 feature. */
type: number;
ccc?: number;
/** From the characteristic's declaration; undefined when the keyboard wouldn't say (see declaredProperties). */
properties?: number;
map: Uint8Array;
};
export type KeyboardConfiguration = {
epoch: number;
/** Every report found, input or not. */
reports: KeyboardReport[];
/** Handles of the input reports subscribed for keys. */
watched: number[];
serviceChanged?: number;
};
export type KeyboardClientOptions = {
/** A fresh six-digit passkey for display pairing. Default: Math.random (pass a stronger source). */
randomPasskey?: () => number;
};
export class KeyboardClientError extends Error {
/** The firmware's control error code (KeyboardError), when that is what failed. */
readonly code: number | undefined;
/** The keyboard's ATT error code, when it refused a read or write. */
readonly attStatus: number | undefined;
constructor(message: string, code?: number, attStatus?: number) {
super(message);
this.name = "KeyboardClientError";
this.code = code;
this.attStatus = attStatus;
}
}
type Attribute = { handle: number; uuid: number | string };
type Pending = {
op: number;
resolve: (r: KeyboardRecord) => void;
reject: (e: Error) => void;
timer: ReturnType<typeof setTimeout>;
};
type Waiter = { test: () => boolean; resolve: () => void; reject: (e: Error) => void; timer: ReturnType<typeof setTimeout> };
type Input = { report: HidReport; id: number; service: number };
const COMMAND_TIMEOUT_MS = 32_000;
const MAX_PENDING = 8;
const MAX_ATTRIBUTES = 512;
const MAX_VALUE = 512;
const MAX_WATCHES = 16;
const UUID_PRIMARY_SERVICE = 0x2800;
const UUID_SECONDARY_SERVICE = 0x2801;
const UUID_CHARACTERISTIC = 0x2803;
const UUID_CCC = 0x2902;
const UUID_EXTERNAL_REPORT_REFERENCE = 0x2907;
const UUID_REPORT_REFERENCE = 0x2908;
const UUID_HID_SERVICE = 0x1812;
const UUID_SERVICE_CHANGED = 0x2a05;
const UUID_REPORT_MAP = 0x2a4b;
const UUID_REPORT = 0x2a4d;
const UUID_PROTOCOL_MODE = 0x2a4e;
/** ATT error codes that end a paged read rather than failing it. */
const ATT_INVALID_OFFSET = 7;
const ATT_NOT_LONG = 11;
const ATT_NOT_FOUND = 10;
/**
* ATT UUIDs are little endian. A 128-bit UUID on the Bluetooth base collapses
* to its 16-bit form; vendor UUIDs stay as hex strings.
*/
export function attributeUuid(bytes: Uint8Array): number | string {
if (bytes.length === 2) return u16(bytes);
if (bytes.length !== 16) throw new KeyboardClientError("Invalid ATT UUID length");
const base = [0xfb, 0x34, 0x9b, 0x5f, 0x80, 0, 0, 0x80, 0, 0x10, 0, 0];
if (base.every((v, i) => bytes[i] === v) && bytes[14] === 0 && bytes[15] === 0) return u16(bytes, 12);
return Array.from(bytes, (x) => x.toString(16).padStart(2, "0")).join("");
}
export class KeyboardClient {
/** The firmware's connection generation; every control but QUERY/ENABLE must carry the live one. */
epoch = 0;
status: KeyboardStatus = { enabled: false, conn: 0, connected: false, encrypted: false, scanning: false };
configuration: KeyboardConfiguration | undefined;
private serial = 0;
private closed = false;
/** The link under connect() went away (close, failed open, failed pairing). */
private linkLost = false;
private readonly pending = new Map<number, Pending>();
private readonly waiters = new Set<Waiter>();
private readonly keys = new HidKeys();
private inputs = new Map<number, Input>();
private readonly records = new KeyboardRecords(() => this.gap());
private readonly randomPasskey: () => number;
constructor(
private readonly transport: KeyboardTransport,
private readonly events: KeyboardClientEvents = {},
options: KeyboardClientOptions = {},
) {
this.randomPasskey = options.randomPasskey ?? (() => Math.floor(Math.random() * 1_000_000));
}
// ---------- Inbound ----------
/** Feed one field-131 payload, in arrival order. */
accept(data: Uint8Array): void {
if (this.closed) return;
const r = this.records.push(data);
if (!r) return;
this.epoch = r.epoch;
if (r.kind === KeyboardKind.status && r.data.length === 10) {
this.status = {
enabled: !!r.data[0], conn: r.data[1]!, connected: !!r.data[2], encrypted: !!r.data[3], scanning: !!r.data[4],
};
if (!this.status.enabled || !this.status.connected || !this.status.encrypted) this.release();
this.events.status?.(this.status);
}
const pending = this.pending.get(r.request);
if (pending && (r.kind === KeyboardKind.status || r.kind === KeyboardKind.att)) {
this.pending.delete(r.request);
clearTimeout(pending.timer);
if (r.kind === KeyboardKind.status && r.code) {
pending.reject(new KeyboardClientError(
`Keyboard command ${opName(pending.op)}: firmware ${keyboardErrorName(r.code)}`, r.code));
} else {
pending.resolve(r);
}
}
if (r.kind === KeyboardKind.dm) this.acceptDm(r);
else if (r.kind === KeyboardKind.input) this.acceptInput(r);
else if (r.kind === KeyboardKind.advert) {
const advert = parseKeyboardAdvert(r.data);
if (advert) this.events.advert?.(advert);
}
this.checkWaiters();
}
private acceptDm(r: KeyboardRecord): void {
const event = r.code & 255;
const status = r.code >>> 8;
if (event === KeyboardDm.connClose || event === KeyboardDm.pairFailed || event === KeyboardDm.encryptFailed ||
(event === KeyboardDm.connOpen && status !== 0)) {
this.linkLost = true;
this.gap();
this.inputs.clear();
this.configuration = undefined;
}
if (event === KeyboardDm.authRequest && r.data.length === 2) {
if (r.data[0]) {
this.command(KeyboardOp.disconnect).catch(() => {});
this.events.error?.("This keyboard only pairs out of band, which isn't supported.");
} else if (r.data[1]) {
// KeyboardDisplay on our side: choose the passkey, show it, and
// answer at once; the user types it on the keyboard.
const pin = Math.min(999_999, Math.max(0, Math.floor(this.randomPasskey())));
this.events.passkeyDisplay?.(pin);
this.authenticate(pin).catch((e) => this.events.error?.(messageOf(e)));
} else {
this.events.passkeyRequest?.();
}
}
if (event === KeyboardDm.compare && r.data.length === 4) this.events.compareRequest?.(u32(r.data));
this.events.dm?.(event, status);
}
private acceptInput(r: KeyboardRecord): void {
const changed = this.configuration?.serviceChanged;
if (changed !== undefined && r.handle === changed) {
this.gap();
this.inputs.clear();
this.configuration = undefined;
this.events.servicesChanged?.();
return;
}
const input = this.inputs.get(r.handle);
if (!input || this.configuration?.epoch !== r.epoch) {
this.gap();
return;
}
try {
const events = this.keys.update(r.handle, input.report, r.data);
if (events.length) this.events.keys?.(events);
} catch (e) {
this.release();
this.events.error?.(messageOf(e));
}
}
private release(): void {
const events = this.keys.reset();
if (events.length) this.events.keys?.(events);
}
private gap(): void {
this.release();
this.events.gap?.();
for (const [id, p] of this.pending) {
if (p.op < KeyboardOp.find) continue;
clearTimeout(p.timer);
this.pending.delete(id);
p.reject(new KeyboardClientError("Keyboard stream gap during ATT transaction"));
}
}
/** The phone's link to the glasses dropped: release held keys and fail everything in flight. */
lostPhoneLink(): void {
this.records.reset();
this.cancel("Glasses link lost");
}
/** Stop for good; later accept() calls are ignored. */
close(): void {
if (this.closed) return;
this.lostPhoneLink();
this.closed = true;
}
private cancel(reason: string): void {
for (const p of this.pending.values()) {
clearTimeout(p.timer);
p.reject(new KeyboardClientError(reason));
}
this.pending.clear();
for (const w of this.waiters) {
clearTimeout(w.timer);
w.reject(new KeyboardClientError(reason));
}
this.waiters.clear();
}
private checkWaiters(): void {
for (const w of [...this.waiters]) {
let done = false;
try {
done = w.test();
} catch (e) {
this.waiters.delete(w);
clearTimeout(w.timer);
w.reject(e instanceof Error ? e : new KeyboardClientError(String(e)));
continue;
}
if (!done) continue;
this.waiters.delete(w);
clearTimeout(w.timer);
w.resolve();
}
}
/** Resolve once `test` holds; it is re-evaluated after every accepted record. */
private waitFor(test: () => boolean, timeoutMs: number, what: string): Promise<void> {
if (this.closed) return Promise.reject(new KeyboardClientError("Keyboard client closed"));
if (test()) return Promise.resolve();
return new Promise<void>((resolve, reject) => {
const waiter: Waiter = {
test, resolve, reject,
timer: setTimeout(() => {
this.waiters.delete(waiter);
reject(new KeyboardClientError(`Timed out waiting for ${what}`));
}, timeoutMs),
};
this.waiters.add(waiter);
});
}
// ---------- Commands ----------
/** Send one control and await the STATUS or ATT record that answers it. */
command(op: number, body: readonly number[] = []): Promise<KeyboardRecord> {
if (this.closed) return Promise.reject(new KeyboardClientError("Keyboard client closed"));
if (this.pending.size >= MAX_PENDING) return Promise.reject(new KeyboardClientError("Too many keyboard commands"));
const request = this.serial = this.serial % 65535 + 1;
return new Promise<KeyboardRecord>((resolve, reject) => {
const timer = setTimeout(() => {
this.pending.delete(request);
reject(new KeyboardClientError(`Keyboard command ${opName(op)} timed out`));
}, COMMAND_TIMEOUT_MS);
this.pending.set(request, { op, resolve, reject, timer });
let queued = false;
try {
queued = this.transport(keyboardControl(op, request, this.epoch, body));
} catch {
queued = false;
}
if (!queued) {
clearTimeout(timer);
this.pending.delete(request);
reject(new KeyboardClientError("The glasses aren't ready for keyboard commands"));
}
});
}
async enable(): Promise<void> {
await this.command(KeyboardOp.enable);
}
/** Disconnect the keyboard and stop the bridge; the bond stays. */
async disable(): Promise<void> {
await this.command(KeyboardOp.disable);
this.release();
}
/** Ask for the firmware's state. Also the way to learn the live epoch: QUERY isn't epoch-checked. */
async query(): Promise<KeyboardStatus> {
await this.command(KeyboardOp.query);
return this.status;
}
/**
* Active scan for about five seconds; adverts arrive through events.advert.
* The firmware only clears `scanning` once the stock scanner is idle again,
* and a ring looking for its lens can hold that well past the window, so a
* lingering flag is not an error: the adverts already delivered stand.
*/
async scan(): Promise<void> {
await this.command(KeyboardOp.scan);
try {
await this.waitFor(() => !this.status.scanning, 8000, "the scan to finish");
} catch (e) {
if (this.closed) throw e;
}
}
/** Connect, then pair unless the link comes up encrypted. `address` is LSB first. */
async connect(addressType: number, address: Uint8Array): Promise<void> {
if (address.length !== 6 || !Number.isInteger(addressType) || addressType < 0 || addressType > 3) {
throw new KeyboardClientError("Invalid BLE address");
}
this.release();
this.inputs.clear();
this.configuration = undefined;
this.linkLost = false;
await this.command(KeyboardOp.connect, [addressType, ...address]);
await this.waitFor(() => this.status.connected || this.linkLost, 32_000, "the keyboard to connect");
if (!this.status.connected) throw new KeyboardClientError("The keyboard didn't answer");
if (!this.status.encrypted) {
// The keyboard's own security request may have started pairing already.
// BUSY is not success: the encrypted status below still decides.
try {
await this.command(KeyboardOp.pair);
} catch (e) {
if (!(e instanceof KeyboardClientError) || e.code !== KeyboardError.busy) throw e;
}
await this.waitFor(() => this.status.encrypted || this.linkLost, 65_000, "pairing to finish");
if (!this.status.encrypted) throw new KeyboardClientError("Pairing with the keyboard failed");
}
}
async disconnect(): Promise<void> {
await this.command(KeyboardOp.disconnect);
this.release();
}
/** Answer a pending passkey prompt. */
async authenticate(pin: number): Promise<void> {
if (!Number.isInteger(pin) || pin < 0 || pin > 999_999) throw new KeyboardClientError("Invalid pairing passkey");
await this.command(KeyboardOp.auth, [pin & 255, (pin >>> 8) & 255, pin >>> 16]);
}
/** Answer a pending numeric comparison. */
async confirm(accept: boolean): Promise<void> {
await this.command(KeyboardOp.compare, [accept ? 1 : 0]);
}
private async att(op: number, body: readonly number[]): Promise<KeyboardRecord> {
const r = await this.command(op, body);
if (r.kind !== KeyboardKind.att) throw new KeyboardClientError("Expected keyboard ATT response");
return r;
}
/** Read a whole attribute: Read, then Read Blob until a short or empty reply. Never assumes the MTU. */
async read(handle: number): Promise<Uint8Array> {
const parts: number[] = [];
for (;;) {
const r = await this.att(KeyboardOp.read, [...le16(handle), ...le16(parts.length)]);
const status = r.code >>> 8;
if (parts.length && (status === ATT_INVALID_OFFSET || status === ATT_NOT_LONG)) break;
if (status) throw new KeyboardClientError(`ATT read ${handle}: ${status}`, undefined, status);
if (!r.data.length) break;
for (const b of r.data) parts.push(b);
if (parts.length > MAX_VALUE) throw new KeyboardClientError("Attribute exceeds 512 bytes");
if (parts.length === MAX_VALUE) break;
}
return Uint8Array.from(parts);
}
/** Read a short attribute once (a Report Reference, a declaration, a service UUID). */
private async shortRead(handle: number): Promise<Uint8Array> {
const r = await this.att(KeyboardOp.read, [...le16(handle), 0, 0]);
if (r.code >>> 8) throw new KeyboardClientError(`ATT read ${handle}: ${r.code >>> 8}`, undefined, r.code >>> 8);
return r.data;
}
/** Write 1..18 bytes (an output report such as the LEDs, a CCC, the protocol mode). */
async write(handle: number, value: Uint8Array, withoutResponse = false): Promise<void> {
if (!value.length || value.length > 18) throw new KeyboardClientError("Keyboard write supports 1..18 bytes");
const r = await this.att(KeyboardOp.write, [...le16(handle), withoutResponse ? 1 : 0, value.length, ...value]);
if (r.code >>> 8) throw new KeyboardClientError(`ATT write ${handle}: ${r.code >>> 8}`, undefined, r.code >>> 8);
}
private async attributes(): Promise<Attribute[]> {
const attrs: Attribute[] = [];
let start = 1;
while (start <= 65535) {
const r = await this.att(KeyboardOp.find, [...le16(start), 255, 255]);
const status = r.code >>> 8;
if (status === ATT_NOT_FOUND) break; // the normal end of the table
if (status) throw new KeyboardClientError(`ATT Find Information: ${status}`);
const width = r.data[0] === 1 ? 4 : r.data[0] === 2 ? 18 : 0;
if (!width || r.data.length <= 1 || (r.data.length - 1) % width) {
throw new KeyboardClientError("Malformed Find Information response");
}
for (let i = 1; i < r.data.length; i += width) {
const handle = u16(r.data, i);
if (handle < start || attrs.length >= MAX_ATTRIBUTES) throw new KeyboardClientError("Invalid or excessive GATT handles");
attrs.push({ handle, uuid: attributeUuid(r.data.subarray(i + 2, i + width)) });
start = handle + 1;
}
}
return attrs;
}
/**
* The properties byte of a characteristic, from its declaration, or
* undefined when the keyboard won't say. A GATT client normally learns
* declarations through Read By Type, which the bridge doesn't relay, so
* this reads the declaration attribute itself. Most stacks answer that
* with the full declaration. Some keep only the properties byte there and
* build the rest for Read By Type alone (older Telink SDKs, common in
* small keyboards), and some refuse the read. None of that is a reason to
* turn a keyboard away: the report's handle and UUID are already known.
*/
private async declaredProperties(attrs: readonly Attribute[], a: Attribute): Promise<number | undefined> {
const decl = attrs.filter((d) => d.handle < a.handle && d.uuid === UUID_CHARACTERISTIC).pop();
if (!decl) return undefined;
let declaration: Uint8Array;
try {
declaration = await this.shortRead(decl.handle);
} catch (e) {
const status = attRefusal(e);
this.events.log?.(`declaration ${decl.handle} of ${a.handle}: read refused (ATT ${status})`);
return undefined;
}
if (declaration.length === 5 || declaration.length === 19) {
if (u16(declaration, 1) === a.handle && attributeUuid(declaration.subarray(3)) === a.uuid) return declaration[0]!;
this.events.log?.(`declaration ${decl.handle} of ${a.handle}: describes something else (${hex(declaration)})`);
return undefined;
}
if (declaration.length === 1) return declaration[0]!;
this.events.log?.(`declaration ${decl.handle} of ${a.handle}: unexpected value (${hex(declaration)})`);
return undefined;
}
/**
* Discover every HID service, its Report Map and each report's Report
* Reference; select Report Protocol and subscribe the input reports that
* can carry keys. Needs an encrypted link. No handle is assumed.
*
* Only what typing needs is required of the keyboard: a Report Map that
* parses, and at least one key-bearing input report with a Report
* Reference and a CCC. A report that can't be placed is skipped and
* logged, as is anything wrong with an external report (the battery
* level, usually).
*/
async configure(): Promise<KeyboardConfiguration> {
const epoch = this.epoch;
const log = (line: string): void => this.events.log?.(line);
// A new discovery replaces any earlier mapping, whether or not it succeeds.
this.release();
this.inputs.clear();
this.configuration = undefined;
const attrs = await this.attributes();
log(`gatt ${attrs.map((a) => `${a.handle}=${typeof a.uuid === "number" ? a.uuid.toString(16) : a.uuid}`).join(" ")}`);
const reports: KeyboardReport[] = [];
const watched: KeyboardReport[] = [];
const skipped: string[] = [];
const descriptorsFor = (handle: number): Attribute[] => {
const end = attrs.find((a) => a.handle > handle &&
(a.uuid === UUID_PRIMARY_SERVICE || a.uuid === UUID_SECONDARY_SERVICE || a.uuid === UUID_CHARACTERISTIC))?.handle ?? 65536;
return attrs.filter((a) => a.handle > handle && a.handle < end);
};
/** Why a report was left out; the link going away is not a reason to carry on. */
const skip = (a: Attribute, reason: string): void => {
skipped.push(`${a.handle}: ${reason}`);
log(`report ${a.handle} skipped: ${reason}`);
};
const addReport = async (service: number, a: Attribute, map: Uint8Array, parsed: Map<number, HidReport>) => {
if (reports.some((r) => r.handle === a.handle)) return skip(a, "already listed by another HID service");
const descriptors = descriptorsFor(a.handle);
const ref = descriptors.find((d) => d.uuid === UUID_REPORT_REFERENCE);
if (!ref) return skip(a, "no Report Reference descriptor");
let reference: Uint8Array;
try {
reference = await this.shortRead(ref.handle);
} catch (e) {
return skip(a, `Report Reference ${ref.handle} unreadable (ATT ${attRefusal(e)})`);
}
if (reference.length !== 2) return skip(a, `Report Reference ${ref.handle} is ${hex(reference) || "empty"}`);
const id = reference[0]!;
const type = reference[1]!;
if (type < 1 || type > 3) return skip(a, `Report Reference type ${type}`);
const ccc = descriptors.find((d) => d.uuid === UUID_CCC)?.handle;
const properties = await this.declaredProperties(attrs, a);
const report: KeyboardReport = { service, handle: a.handle, id, type, ccc, properties, map };
if (type === 1) {
const layout = parsed.get(id);
if (!layout) return skip(a, `input report id ${id} is not in the Report Map`);
if (ccc === undefined || (properties !== undefined && !(properties & 0x10))) return skip(a, "input report can't notify");
if (reportHasKeys(layout)) watched.push(report);
else log(`report ${a.handle} (id ${id}) carries no keys; not subscribed`);
}
reports.push(report);
log(`report ${a.handle}: id ${id} type ${type} ccc ${ccc ?? "-"} properties ${properties ?? "?"}`);
};
for (let i = 0; i < attrs.length; i++) {
const service = attrs[i]!;
if (service.uuid !== UUID_PRIMARY_SERVICE) continue;
if (attributeUuid(await this.shortRead(service.handle)) !== UUID_HID_SERVICE) continue;
const end = attrs.slice(i + 1).find((a) => a.uuid === UUID_PRIMARY_SERVICE || a.uuid === UUID_SECONDARY_SERVICE)?.handle ?? 65536;
const members = attrs.filter((a) => a.handle > service.handle && a.handle < end);
const mapAttr = members.find((a) => a.uuid === UUID_REPORT_MAP);
if (!mapAttr) throw new KeyboardClientError(`HID service ${service.handle} has no Report Map`);
const map = await this.read(mapAttr.handle);
log(`report map ${mapAttr.handle}: ${hex(map)}`);
const parsed = parseReportMap(map);
for (const mode of members.filter((a) => a.uuid === UUID_PROTOCOL_MODE)) {
try {
await this.write(mode.handle, Uint8Array.of(1), true);
} catch (e) {
// Report Protocol is the default after a connection; a keyboard
// that won't take the write is almost certainly in it already.
log(`protocol mode ${mode.handle}: write refused (ATT ${attRefusal(e)})`);
}
}
for (const a of members.filter((m) => m.uuid === UUID_REPORT)) await addReport(service.handle, a, map, parsed);
// HOGP lets a Report Map refer to reports in other services (commonly Battery).
for (const ext of descriptorsFor(mapAttr.handle).filter((a) => a.uuid === UUID_EXTERNAL_REPORT_REFERENCE)) {
let value: Uint8Array;
try {
value = await this.shortRead(ext.handle);
} catch (e) {
log(`external report reference ${ext.handle} skipped: unreadable (ATT ${attRefusal(e)})`);
continue;
}
if (value.length !== 2 && value.length !== 16) {
log(`external report reference ${ext.handle} skipped: value ${hex(value) || "empty"}`);
continue;
}
const uuid = attributeUuid(value);
for (const a of attrs.filter((m) => m.uuid === uuid && (m.handle < service.handle || m.handle >= end))) {
await addReport(service.handle, a, map, parsed);
}
}
}
if (this.closed || this.epoch !== epoch) throw new KeyboardClientError("The keyboard link changed during setup");
if (!watched.length) {
throw new KeyboardClientError(reports.length || skipped.length
? `No usable keyboard input report (${skipped.join("; ") || "none carries keys"})`
: "This device has no HID service");
}
if (watched.length > MAX_WATCHES) throw new KeyboardClientError("Keyboard has more than 16 input reports");
const changed = attrs.find((a) => a.uuid === UUID_SERVICE_CHANGED);
const changedCcc = changed && descriptorsFor(changed.handle).find((a) => a.uuid === UUID_CCC);
const watches = watched.map((r) => r.handle);
if (changed && changedCcc && watches.length < MAX_WATCHES) watches.push(changed.handle);
const serviceChanged = changed && changedCcc && watches.includes(changed.handle) ? changed.handle : undefined;
const config: KeyboardConfiguration = { epoch: this.epoch, reports, watched: watched.map((r) => r.handle), serviceChanged };
this.restore(config);
try {
await this.command(KeyboardOp.watch, [watches.length, ...watches.flatMap(le16)]);
if (serviceChanged !== undefined) {
try {
await this.write(changedCcc!.handle, Uint8Array.of(2, 0));
} catch (e) {
log(`service changed ${changedCcc!.handle}: subscription refused (ATT ${attRefusal(e)})`);
}
}
for (const r of watched) await this.write(r.ccc!, Uint8Array.of(1, 0));
} catch (e) {
this.inputs.clear();
this.configuration = undefined;
this.release();
throw e;
}
return config;
}
/**
* Install a mapping found by configure(). It is only good while the glasses
* keep the same connection (the same epoch): after a keyboard reconnect or
* a firmware boot, discover again.
*/
restore(config: KeyboardConfiguration): void {
if (!config.reports.length || config.reports.length > 64) throw new KeyboardClientError("Invalid keyboard configuration");
const inputs = new Map<number, Input>();
for (const r of config.reports) {
if (r.type !== 1 || !config.watched.includes(r.handle)) continue;
if (!Number.isInteger(r.handle) || r.handle < 1 || r.handle > 65535 || inputs.has(r.handle)) {
throw new KeyboardClientError("Invalid restored Report handle");
}
if (!r.map.length || r.map.length > MAX_VALUE) throw new KeyboardClientError("Invalid restored Report Map");
const report = parseReportMap(r.map).get(r.id);
if (!report) throw new KeyboardClientError("Restored Report ID missing");
inputs.set(r.handle, { report, id: r.id, service: r.service });
}
if (!inputs.size || inputs.size > MAX_WATCHES) throw new KeyboardClientError("Invalid restored input count");
this.release();
this.inputs = inputs;
this.configuration = config;
}
/** Output reports of the configured keyboard (the LED report is the usual one). */
outputReports(): KeyboardReport[] {
return this.configuration?.reports.filter((r) => r.type === 2) ?? [];
}
}
/**
* The ATT error code when `error` is the keyboard refusing a read or write.
* Anything else (the link dropping, a timeout, a stream gap) is rethrown:
* those end the setup, where a refusal only costs the one attribute.
*/
function attRefusal(error: unknown): number {
if (error instanceof KeyboardClientError && error.attStatus !== undefined) return error.attStatus;
throw error;
}
function hex(bytes: Uint8Array): string {
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
}
function opName(op: number): string {
for (const [name, value] of Object.entries(KeyboardOp)) if (value === op) return name;
return String(op);
}
function messageOf(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
+188
View File
@@ -0,0 +1,188 @@
/**
* Bounded HID report-descriptor decoder for the keyboard bridge: turns a
* keyboard's Report Map into the layout of each input report, and input
* reports into the set of keys held. From the reference client in g2flash
* demos/ (keyboard-hid.ts).
*
* HID over GATT carries the Report ID out of band (in each characteristic's
* Report Reference descriptor), so byte zero of a report value is data: it is
* never stripped as USB HID would. Only the keyboard/keypad page (7) and the
* consumer page (12) produce keys; pointer axes and padding are ignored.
* No platform imports: this runs under node in the tests.
*/
export type HidUsage = { page: number; usage: number };
export type HidKeyEvent = HidUsage & { down: boolean };
type Global = { page: number; min: number; max: number; size: number; count: number; id: number };
type Field = {
bit: number;
size: number;
count: number;
variable: boolean;
min: number;
max: number;
usages: HidUsage[];
range?: [HidUsage, HidUsage];
};
export type HidReport = { id: number; bits: number; fields: Field[] };
const HID_PAGE_KEYBOARD = 7;
const HID_PAGE_CONSUMER = 12;
const REPORT_MAP_MAX = 512;
function fail(reason: string): never {
throw new Error(`Unsupported or malformed HID descriptor: ${reason}`);
}
const usageKey = (u: HidUsage): string => `${u.page}:${u.usage}`;
/** Input reports by Report ID (0 when the descriptor uses none). Throws on anything out of bounds. */
export function parseReportMap(bytes: Uint8Array): Map<number, HidReport> {
if (!bytes.length || bytes.length > REPORT_MAP_MAX) fail("report map must contain 1..512 bytes");
const reports = new Map<number, HidReport>();
let g: Global = { page: 0, min: 0, max: 0, size: 0, count: 0, id: 0 };
const stack: Global[] = [];
let usages: HidUsage[] = [];
let lo: HidUsage | undefined;
let hi: HidUsage | undefined;
let depth = 0;
const usage = (v: number, n: number): HidUsage =>
n === 4 ? { page: v >>> 16, usage: v & 65535 } : { page: g.page, usage: v };
for (let p = 0; p < bytes.length;) {
const prefix = bytes[p++]!;
if (prefix === 0xfe) fail("long items");
const n = [0, 1, 2, 4][prefix & 3]!;
if (p + n > bytes.length) fail("truncated item");
let v = 0;
for (let j = 0; j < n; j++) v += bytes[p++]! * 2 ** (8 * j);
const signed = n && v >= 2 ** (n * 8 - 1) ? v - 2 ** (n * 8) : v;
const type = (prefix >> 2) & 3;
const tag = prefix >> 4;
if (type === 1) {
switch (tag) {
case 0: g.page = v; break;
case 1: g.min = signed; break;
case 2: g.max = g.min < 0 ? signed : v; break;
case 7: g.size = v; break;
case 8: if (!v || v > 255) fail("Report ID"); g.id = v; break;
case 9: g.count = v; break;
case 10: if (stack.length >= 8) fail("global stack overflow"); stack.push({ ...g }); break;
case 11: if (!stack.length) fail("global stack underflow"); g = stack.pop()!; break;
case 3: case 4: case 5: case 6: break; // physical range, unit and exponent
default: fail("unknown global item");
}
} else if (type === 2) {
if (tag === 0) { if (usages.length >= 512) fail("too many usages"); usages.push(usage(v, n)); }
else if (tag === 1) lo = usage(v, n);
else if (tag === 2) hi = usage(v, n);
else if (tag === 10) fail("usage delimiters");
else if (tag > 9) fail("unknown local item");
} else if (type === 0) {
if (tag === 10) { if (++depth > 32) fail("collection depth"); }
else if (tag === 12) { if (--depth < 0) fail("collection underflow"); }
else if (tag === 8) {
if (!g.size || g.size > 32 || !g.count || g.count > 512) fail("field dimensions");
let r = reports.get(g.id);
if (!r) {
if (reports.size >= 16) fail("too many input reports");
r = { id: g.id, bits: 0, fields: [] };
reports.set(g.id, r);
}
const field: Field = {
bit: r.bits, size: g.size, count: g.count, variable: !!(v & 2), min: g.min, max: g.max, usages: [...usages],
};
if (lo || hi) {
if (!lo || !hi || lo.page !== hi.page || hi.usage < lo.usage) fail("usage range");
field.range = [lo!, hi!];
}
r.bits += g.size * g.count;
if (r.bits > 4096) fail("report exceeds 512 bytes");
// Constant padding and relative pointer axes are not keys.
if (!(v & 1) && !(v & 4)) r.fields.push(field);
} else if (tag !== 9 && tag !== 11) fail("unknown main item");
usages = [];
lo = hi = undefined;
} else fail("reserved item type");
}
if (depth || stack.length) fail("unbalanced collection/global stack");
if (reports.has(0) && reports.size > 1) fail("mixed numbered and unnumbered input reports");
if (!reports.size) fail("no input reports");
return reports;
}
function usageAt(f: Field, index: number): HidUsage | undefined {
if (index < 0) return undefined;
if (index < f.usages.length) return f.usages[index];
const rangeIndex = index - f.usages.length;
if (f.range && rangeIndex <= f.range[1].usage - f.range[0].usage) {
return { page: f.range[0].page, usage: f.range[0].usage + rangeIndex };
}
// Variable items reuse their last usage when Report Count exceeds the usages.
if (f.variable) return f.range?.[1] ?? f.usages[f.usages.length - 1];
return undefined;
}
/**
* Whether an input report can ever say a key is held. False for a pointer's
* report (a trackpad or mouse on a combined device), whose movement would
* otherwise be relayed, and thrown away, a hundred times a second.
*/
export function reportHasKeys(report: HidReport): boolean {
const isKeyPage = (u: HidUsage): boolean => u.page === HID_PAGE_KEYBOARD || u.page === HID_PAGE_CONSUMER;
return report.fields.some((f) => f.usages.some(isKeyPage) || (f.range !== undefined && isKeyPage(f.range[0])));
}
/** The keys one input report says are held. Throws on a length mismatch or a rollover report. */
export function reportKeys(report: HidReport, data: Uint8Array): HidUsage[] {
if (data.length !== Math.ceil(report.bits / 8)) throw new Error("HID input length does not match Report Map");
const keys = new Map<string, HidUsage>();
for (const f of report.fields) {
for (let i = 0; i < f.count; i++) {
let value = 0;
for (let j = 0; j < f.size; j++) {
const bit = f.bit + i * f.size + j;
if (data[bit >>> 3]! & (1 << (bit & 7))) value += 2 ** j;
}
if (f.min < 0 && value >= 2 ** (f.size - 1)) value -= 2 ** f.size;
if (value < f.min || value > f.max) continue; // null state
const u = usageAt(f, f.variable ? i : value - f.min);
if (!u || (f.variable && value === 0) || !u.usage) continue;
if (u.page === HID_PAGE_KEYBOARD && u.usage <= 3) throw new Error("HID keyboard rollover/error report");
if (u.page === HID_PAGE_KEYBOARD || u.page === HID_PAGE_CONSUMER) keys.set(usageKey(u), u);
}
}
return [...keys.values()];
}
/**
* Held keys across a keyboard's input reports. Ownership is per report
* characteristic, then unioned: releasing a key in one report cannot release
* a modifier another report still holds.
*/
export class HidKeys {
private reports = new Map<number, HidUsage[]>();
private held = new Map<string, HidUsage>();
/** Apply one report from characteristic `handle`; returns the transitions it caused. */
update(handle: number, report: HidReport, data: Uint8Array): HidKeyEvent[] {
this.reports.set(handle, reportKeys(report, data));
return this.diff();
}
/** Release everything (a stream gap, a dropped link). */
reset(): HidKeyEvent[] {
this.reports.clear();
return this.diff();
}
private diff(): HidKeyEvent[] {
const next = new Map<string, HidUsage>();
for (const values of this.reports.values()) for (const u of values) next.set(usageKey(u), u);
const events: HidKeyEvent[] = [];
for (const [k, u] of this.held) if (!next.has(k)) events.push({ ...u, down: false });
for (const [k, u] of next) if (!this.held.has(k)) events.push({ ...u, down: true });
this.held = next;
return events;
}
}
+315
View File
@@ -0,0 +1,315 @@
/**
* Key events as the rest of Faceclaw sees them, and the translation from the
* keyboard bridge's raw HID transitions: layout (US only for now), modifier
* and Caps Lock state, and typematic repeat, which a BLE keyboard never sends
* (its report just stays asserted). The translation tables follow the Glassly
* app's (GlassesKeyboardInput.ts, MIT).
* No platform imports: this runs under node in the tests, and in app workers.
*/
import type { HidKeyEvent } from "./hid";
export type KeyModifiers = { shift: boolean; ctrl: boolean; alt: boolean; meta: boolean };
/**
* One key transition, shaped like a DOM KeyboardEvent: `key` is the logical
* key with the layout applied ("a", "A", "Enter", "ArrowUp"), `code` the
* physical key ("KeyA"), `text` what a press types (absent for releases, for
* keys that type nothing, and for Ctrl/Alt/Meta chords, which are commands).
*/
export type KeyEvent = {
phase: "down" | "up";
key: string;
code: string;
text?: string;
modifiers: KeyModifiers;
/** A synthesized auto-repeat of a held key. */
repeat: boolean;
/** Date.now() when the phone saw the transition. */
timestampMs: number;
};
const HID_PAGE_KEYBOARD = 7;
const HID_PAGE_CONSUMER = 12;
const USAGE_CAPS_LOCK = 57;
/** [unshifted, shifted, code] for US-layout punctuation on the keyboard page. */
const PUNCTUATION: Record<number, [string, string, string]> = {
45: ["-", "_", "Minus"],
46: ["=", "+", "Equal"],
47: ["[", "{", "BracketLeft"],
48: ["]", "}", "BracketRight"],
49: ["\\", "|", "Backslash"],
50: ["#", "~", "IntlHash"],
51: [";", ":", "Semicolon"],
52: ["'", '"', "Quote"],
53: ["`", "~", "Backquote"],
54: [",", "<", "Comma"],
55: [".", ">", "Period"],
56: ["/", "?", "Slash"],
100: ["\\", "|", "IntlBackslash"],
};
const DIGITS = "1234567890";
const SHIFTED_DIGITS = "!@#$%^&*()";
/** [key, code] for keys that type nothing. */
const NAMED: Record<number, [string, string]> = {
40: ["Enter", "Enter"],
41: ["Escape", "Escape"],
42: ["Backspace", "Backspace"],
43: ["Tab", "Tab"],
57: ["CapsLock", "CapsLock"],
70: ["PrintScreen", "PrintScreen"],
71: ["ScrollLock", "ScrollLock"],
72: ["Pause", "Pause"],
73: ["Insert", "Insert"],
74: ["Home", "Home"],
75: ["PageUp", "PageUp"],
76: ["Delete", "Delete"],
77: ["End", "End"],
78: ["PageDown", "PageDown"],
79: ["ArrowRight", "ArrowRight"],
80: ["ArrowLeft", "ArrowLeft"],
81: ["ArrowDown", "ArrowDown"],
82: ["ArrowUp", "ArrowUp"],
83: ["NumLock", "NumLock"],
88: ["Enter", "NumpadEnter"],
101: ["ContextMenu", "ContextMenu"],
102: ["Power", "Power"],
224: ["Control", "ControlLeft"],
225: ["Shift", "ShiftLeft"],
226: ["Alt", "AltLeft"],
227: ["Meta", "MetaLeft"],
228: ["Control", "ControlRight"],
229: ["Shift", "ShiftRight"],
230: ["Alt", "AltRight"],
231: ["Meta", "MetaRight"],
};
/** [key and text, code] for the numeric keypad's operators. */
const NUMPAD: Record<number, [string, string]> = {
84: ["/", "NumpadDivide"],
85: ["*", "NumpadMultiply"],
86: ["-", "NumpadSubtract"],
87: ["+", "NumpadAdd"],
99: [".", "NumpadDecimal"],
103: ["=", "NumpadEqual"],
};
const CONSUMER: Record<number, string> = {
0xe9: "AudioVolumeUp",
0xea: "AudioVolumeDown",
0xe2: "AudioVolumeMute",
0xcd: "MediaPlayPause",
0xb0: "MediaPlay",
0xb1: "MediaPause",
0xb5: "MediaTrackNext",
0xb6: "MediaTrackPrevious",
0xb7: "MediaStop",
0x6f: "BrightnessUp",
0x70: "BrightnessDown",
0x221: "BrowserSearch",
0x223: "BrowserHome",
0x224: "BrowserBack",
0x225: "BrowserForward",
0x18a: "LaunchMail",
0x192: "LaunchApplication2",
0x194: "LaunchApplication1",
};
const MODIFIER_USAGES: Record<number, keyof KeyModifiers> = {
224: "ctrl", 228: "ctrl", 225: "shift", 229: "shift", 226: "alt", 230: "alt", 227: "meta", 231: "meta",
};
type Translated = { key: string; code: string; text?: string };
/** One HID usage under the US layout. Caps Lock only affects letters. */
export function translateUsage(page: number, usage: number, shift: boolean, capsLock: boolean): Translated {
if (page === HID_PAGE_KEYBOARD) {
if (usage >= 4 && usage <= 29) {
const lower = String.fromCharCode(97 + usage - 4);
const key = shift !== capsLock ? lower.toUpperCase() : lower;
return { key, code: `Key${lower.toUpperCase()}`, text: key };
}
if (usage >= 30 && usage <= 39) {
const index = usage - 30;
const key = shift ? SHIFTED_DIGITS[index]! : DIGITS[index]!;
return { key, code: `Digit${DIGITS[index]}`, text: key };
}
if (usage === 44) return { key: " ", code: "Space", text: " " };
const punctuation = PUNCTUATION[usage];
if (punctuation) {
const key = shift ? punctuation[1] : punctuation[0];
return { key, code: punctuation[2], text: key };
}
if (usage >= 58 && usage <= 69) return { key: `F${usage - 57}`, code: `F${usage - 57}` };
if (usage >= 104 && usage <= 115) return { key: `F${usage - 91}`, code: `F${usage - 91}` };
if (usage >= 89 && usage <= 97) {
const digit = String(usage - 88);
return { key: digit, code: `Numpad${digit}`, text: digit };
}
if (usage === 98) return { key: "0", code: "Numpad0", text: "0" };
const numpad = NUMPAD[usage];
if (numpad) return { key: numpad[0], code: numpad[1], text: numpad[0] };
const named = NAMED[usage];
if (named) return { key: named[0], code: named[1] };
return { key: "Unidentified", code: `Usage${usage.toString(16).padStart(2, "0")}` };
}
if (page === HID_PAGE_CONSUMER) {
const name = CONSUMER[usage];
return name ? { key: name, code: name } : { key: "Unidentified", code: `Consumer${usage.toString(16)}` };
}
return { key: "Unidentified", code: `Page${page.toString(16)}Usage${usage.toString(16)}` };
}
export type KeyTranslatorOptions = {
emit: (event: KeyEvent) => void;
now?: () => number;
setTimer?: (callback: () => void, delayMs: number) => unknown;
clearTimer?: (handle: unknown) => void;
/** Hold time before the first repeat, and the gap between repeats. */
repeatDelayMs?: number;
repeatIntervalMs?: number;
};
const REPEAT_DELAY_MS = 400;
const REPEAT_INTERVAL_MS = 50;
/**
* Raw HID transitions in, KeyEvents out. Modifier state comes from the same
* stream, and the bridge reports a release for every key when the stream may
* have lost something, so a missed key-up cannot leave a modifier stuck or a
* key repeating forever.
*/
export class KeyTranslator {
private readonly emitEvent: (event: KeyEvent) => void;
private readonly now: () => number;
private readonly setTimer: (callback: () => void, delayMs: number) => unknown;
private readonly clearTimer: (handle: unknown) => void;
private readonly repeatDelayMs: number;
private readonly repeatIntervalMs: number;
private readonly held = new Set<string>();
private modifiers: KeyModifiers = { shift: false, ctrl: false, alt: false, meta: false };
private capsLock = false;
private repeatTimer: unknown = null;
private repeating: { page: number; usage: number } | null = null;
constructor(options: KeyTranslatorOptions) {
this.emitEvent = options.emit;
this.now = options.now ?? (() => Date.now());
this.setTimer = options.setTimer ?? ((callback, delayMs) => setTimeout(callback, delayMs));
this.clearTimer = options.clearTimer ?? ((handle) => clearTimeout(handle as ReturnType<typeof setTimeout>));
this.repeatDelayMs = options.repeatDelayMs ?? REPEAT_DELAY_MS;
this.repeatIntervalMs = options.repeatIntervalMs ?? REPEAT_INTERVAL_MS;
}
/** Apply the transitions one input report produced, in order. */
handle(events: readonly HidKeyEvent[]): void {
for (const event of events) this.handleOne(event);
}
private handleOne(event: HidKeyEvent): void {
const id = `${event.page}:${event.usage}`;
const modifier = event.page === HID_PAGE_KEYBOARD ? MODIFIER_USAGES[event.usage] : undefined;
if (event.down) {
if (this.held.has(id)) return;
this.held.add(id);
if (modifier) this.modifiers[modifier] = true;
if (event.page === HID_PAGE_KEYBOARD && event.usage === USAGE_CAPS_LOCK) this.capsLock = !this.capsLock;
this.emit("down", event.page, event.usage, false);
// The newest non-modifier key is the one that repeats, as on a PC.
if (!modifier) this.startRepeat(event.page, event.usage);
} else {
if (!this.held.delete(id)) return;
if (modifier) this.modifiers[modifier] = this.otherHeld(event.usage, modifier);
if (this.repeating?.page === event.page && this.repeating.usage === event.usage) this.stopRepeat();
this.emit("up", event.page, event.usage, false);
}
}
/** The keyboard went away: forget everything without emitting releases. */
reset(): void {
this.stopRepeat();
this.held.clear();
this.modifiers = { shift: false, ctrl: false, alt: false, meta: false };
this.capsLock = false;
}
/** Whether the same modifier's key on the other side is still down. */
private otherHeld(released: number, modifier: keyof KeyModifiers): boolean {
for (const [usage, name] of Object.entries(MODIFIER_USAGES)) {
if (name === modifier && Number(usage) !== released && this.held.has(`${HID_PAGE_KEYBOARD}:${usage}`)) return true;
}
return false;
}
private emit(phase: "down" | "up", page: number, usage: number, repeat: boolean): void {
const translated = translateUsage(page, usage, this.modifiers.shift, this.capsLock);
const event: KeyEvent = {
phase,
key: translated.key,
code: translated.code,
modifiers: { ...this.modifiers },
repeat,
timestampMs: this.now(),
};
if (phase === "down" && translated.text !== undefined &&
!this.modifiers.ctrl && !this.modifiers.alt && !this.modifiers.meta) {
event.text = translated.text;
}
this.emitEvent(event);
}
private startRepeat(page: number, usage: number): void {
this.stopRepeat();
this.repeating = { page, usage };
this.repeatTimer = this.setTimer(() => this.repeatTick(), this.repeatDelayMs);
}
private repeatTick(): void {
const key = this.repeating;
this.repeatTimer = null;
if (!key || !this.held.has(`${key.page}:${key.usage}`)) {
this.repeating = null;
return;
}
this.emit("down", key.page, key.usage, true);
this.repeatTimer = this.setTimer(() => this.repeatTick(), this.repeatIntervalMs);
}
private stopRepeat(): void {
if (this.repeatTimer !== null) this.clearTimer(this.repeatTimer);
this.repeatTimer = null;
this.repeating = null;
}
}
/** The ring gestures a keyboard can stand in for. */
export type KeyNavigationGesture = "scroll-up" | "scroll-down" | "click" | "double-click";
/**
* What a key does where nothing takes keys as keys: the ring's vocabulary,
* with the same reading of left and right as a watch swipe (right selects,
* left backs out). Held arrows keep scrolling; Enter and Escape act once per
* press. Chords and every other key do nothing. This is a deliberately small
* default, not a button-mapping scheme.
*/
export function navigationGestureForKey(event: KeyEvent): KeyNavigationGesture | null {
if (event.phase !== "down") return null;
const { ctrl, alt, meta } = event.modifiers;
if (ctrl || alt || meta) return null;
switch (event.key) {
case "ArrowUp":
return "scroll-up";
case "ArrowDown":
return "scroll-down";
case "Enter":
case "ArrowRight":
return event.repeat ? null : "click";
case "Escape":
case "ArrowLeft":
return event.repeat ? null : "double-click";
default:
return null;
}
}
+297
View File
@@ -0,0 +1,297 @@
/**
* Wire format of the CFW keyboard bridge (Faceclaw/39). The master temple acts
* as a BLE central for one HID-over-GATT keyboard; the phone drives that link
* over private settings fields and gets the keyboard's raw input reports back.
* The firmware side is g2flash patches/keyboard_core.h, documented in its
* docs/keyboard.md. This follows the reference client in g2flash demos/
* (keyboard-protocol.ts), which came with the firmware from tetramo-labs.
*
* Phone -> glasses, settings field 130 (wrapped by the native session):
* ['K','B',1,op, request LE16, epoch LE16, body...] at most 80 bytes
* Glasses -> phone, settings field 131:
* ['K','B',1,kind, sequence LE32, epoch LE16, request LE16, code LE16,
* handle LE16, total LE16, offset LE16, timestamp LE32, fragment...]
*
* All integers are little endian. No platform imports: this runs under node
* in the tests.
*/
export const KEYBOARD_PROTOCOL_VERSION = 1;
/** Fixed part of a field-131 record, before its fragment. */
export const KEYBOARD_RECORD_HEADER = 24;
/** Most body bytes one record carries; longer bodies are fragmented. */
export const KEYBOARD_RECORD_CHUNK = 96;
/** Largest reassembled body (an ATT value or a HID report). */
export const KEYBOARD_BODY_MAX = 512;
/** Largest control body after the 8-byte prefix. */
export const KEYBOARD_CONTROL_BODY_MAX = 72;
export const KeyboardOp = {
query: 0,
enable: 1,
disable: 2,
scan: 3,
connect: 4,
disconnect: 5,
pair: 6,
auth: 7,
compare: 8,
find: 9,
read: 10,
write: 11,
watch: 12,
} as const;
export type KeyboardOpCode = (typeof KeyboardOp)[keyof typeof KeyboardOp];
export const KeyboardKind = {
status: 1,
att: 2,
input: 3,
dm: 4,
advert: 5,
} as const;
/** Control error codes, carried in a STATUS record's `code`. */
export const KeyboardError = {
ok: 0,
badRequest: 1,
disabled: 2,
busy: 3,
staleEpoch: 4,
noSpace: 5,
notConnected: 6,
notEncrypted: 7,
timeout: 8,
noMemory: 9,
} as const;
export function keyboardErrorName(code: number): string {
switch (code) {
case KeyboardError.ok: return "ok";
case KeyboardError.badRequest: return "bad request";
case KeyboardError.disabled: return "keyboard bridge disabled";
case KeyboardError.busy: return "busy";
case KeyboardError.staleEpoch: return "stale epoch";
case KeyboardError.noSpace: return "no connection or bond space";
case KeyboardError.notConnected: return "not connected";
case KeyboardError.notEncrypted: return "not encrypted";
case KeyboardError.timeout: return "timeout";
case KeyboardError.noMemory: return "allocation failure";
default: return `error ${code}`;
}
}
/** Cordio device-manager events the bridge relays (a DM record's `code & 0xff`). */
export const KeyboardDm = {
connOpen: 0x27,
connClose: 0x28,
pairComplete: 0x2a,
pairFailed: 0x2b,
encrypted: 0x2c,
encryptFailed: 0x2d,
authRequest: 0x2e,
compare: 0x35,
} as const;
/** ATT client events (an ATT record's `code & 0xff`; the status is `code >> 8`). */
export const KeyboardAtt = {
notification: 13,
indication: 14,
} as const;
export type KeyboardRecord = {
kind: number;
sequence: number;
epoch: number;
request: number;
code: number;
handle: number;
/** Glasses uptime in ms when the record was queued. */
timestamp: number;
data: Uint8Array;
};
export const u16 = (p: Uint8Array, off = 0): number => p[off]! | (p[off + 1]! << 8);
export const u32 = (p: Uint8Array, off = 0): number =>
(p[off]! | (p[off + 1]! << 8) | (p[off + 2]! << 16) | (p[off + 3]! << 24)) >>> 0;
export const le16 = (v: number): number[] => [v & 255, (v >>> 8) & 255];
/** A field-130 control record. The session wraps it in the settings package. */
export function keyboardControl(op: number, request: number, epoch: number, body: readonly number[] = []): Uint8Array {
if (!Number.isInteger(op) || op < 0 || op > KeyboardOp.watch || body.length > KEYBOARD_CONTROL_BODY_MAX) {
throw new Error("Keyboard control bounds");
}
return Uint8Array.from([75, 66, KEYBOARD_PROTOCOL_VERSION, op, ...le16(request), ...le16(epoch), ...body]);
}
/**
* Bounded, ordered reassembly of field-131 records. `onGap` fires whenever
* the stream may have lost something (a skipped sequence, an epoch change, a
* malformed or orphaned fragment): the caller then releases every held key
* and fails any setup transaction in flight. The firmware's once-a-second
* status record makes a lost final release visible even when no further keys
* arrive.
*/
export class KeyboardRecords {
private epoch: number | undefined;
private last: number | undefined;
private fragment: { record: KeyboardRecord; total: number; used: number } | undefined;
constructor(private readonly onGap: () => void) {}
/** Forget the stream position (the phone link dropped); counts as a gap. */
reset(): void {
this.epoch = undefined;
this.last = undefined;
this.fragment = undefined;
this.onGap();
}
/** Feed one field-131 payload; returns a complete record, or undefined. */
push(p: Uint8Array): KeyboardRecord | undefined {
const invalid = (): undefined => {
this.fragment = undefined;
this.onGap();
return undefined;
};
if (
p.length < KEYBOARD_RECORD_HEADER || p.length > KEYBOARD_RECORD_HEADER + KEYBOARD_RECORD_CHUNK ||
p[0] !== 75 || p[1] !== 66 || p[2] !== KEYBOARD_PROTOCOL_VERSION
) {
return invalid();
}
const r: KeyboardRecord = {
kind: p[3]!,
sequence: u32(p, 4),
epoch: u16(p, 8),
request: u16(p, 10),
code: u16(p, 12),
handle: u16(p, 14),
timestamp: u32(p, 20),
data: new Uint8Array(0),
};
const total = u16(p, 16);
const offset = u16(p, 18);
const n = p.length - KEYBOARD_RECORD_HEADER;
if (r.kind < KeyboardKind.status || r.kind > KeyboardKind.advert || total > KEYBOARD_BODY_MAX ||
offset + n > total || (total > 0 && n === 0)) {
return invalid();
}
if (this.epoch !== r.epoch) {
this.onGap();
this.fragment = undefined;
this.last = undefined;
this.epoch = r.epoch;
}
if (offset === 0) {
if (this.last !== undefined) {
const distance = (r.sequence - this.last) >>> 0;
if (distance === 0 || distance >= 0x80000000) return undefined; // duplicate or old delivery
}
if (this.fragment || (this.last !== undefined && r.sequence !== ((this.last + 1) >>> 0))) this.onGap();
this.last = r.sequence;
this.fragment = { record: { ...r, data: new Uint8Array(total) }, total, used: 0 };
}
const f = this.fragment;
if (!f || f.used !== offset || f.total !== total || f.record.sequence !== r.sequence ||
f.record.kind !== r.kind || f.record.request !== r.request || f.record.code !== r.code ||
f.record.handle !== r.handle || f.record.timestamp !== r.timestamp) {
return invalid();
}
f.record.data.set(p.subarray(KEYBOARD_RECORD_HEADER), offset);
f.used += n;
if (f.used !== total) return undefined;
this.fragment = undefined;
return f.record;
}
}
/** BLE address types as the controller reports them. */
export const KEYBOARD_ADDRESS_TYPES = ["public", "random", "public-identity", "random-identity"] as const;
/** One advertiser seen during a scan (an ADVERT record's body, parsed). */
export type KeyboardAdvert = {
addressType: number;
/** "aa:bb:cc:dd:ee:ff", most significant byte first. */
address: string;
rssi: number;
name: string;
/** Advertises the HID service, or a HID appearance. */
hid: boolean;
};
/** ADVERT body: addrType, addr[6] (LSB first), RSSI, event type, AD length, AD structures. */
export function parseKeyboardAdvert(body: Uint8Array): KeyboardAdvert | null {
if (body.length < 10 || body[0]! > 3) return null;
let name = "";
let hid = false;
for (let i = 10; i < body.length;) {
const n = body[i++]!;
if (n === 0 || i + n > body.length) break;
const type = body[i]!;
if (type === 8 || type === 9) name = decodeUtf8(body.subarray(i + 1, i + n));
// 16-bit service lists (incomplete / complete): 0x1812 is HID.
if (type === 2 || type === 3) {
for (let j = i + 1; j + 1 < i + n; j += 2) if (body[j] === 0x12 && body[j + 1] === 0x18) hid = true;
}
// Appearance 0x03C0..0x03FF is the HID category (0x03C1 keyboard); some
// keyboards advertise that without the service list.
if (type === 0x19 && n >= 3 && body[i + 2] === 0x03 && body[i + 1]! >= 0xc0) hid = true;
i += n;
}
return {
addressType: body[0]!,
address: formatKeyboardAddress(body.subarray(1, 7)),
rssi: (body[7]! << 24) >> 24,
name,
hid,
};
}
/**
* Fold a later record for the same advertiser into an earlier one. An active
* scan reports the advertisement and its scan response separately and the
* name usually only rides in the latter: keep a name once seen, HID once
* seen, and the best signal.
*/
export function mergeKeyboardAdverts(a: KeyboardAdvert, b: KeyboardAdvert): KeyboardAdvert {
return { ...a, rssi: Math.max(a.rssi, b.rssi), name: a.name || b.name, hid: a.hid || b.hid };
}
/** Controller byte order (LSB first) to the usual "aa:bb:cc:dd:ee:ff". */
export function formatKeyboardAddress(lsbFirst: Uint8Array): string {
return Array.from(lsbFirst).reverse().map((b) => b.toString(16).padStart(2, "0")).join(":");
}
/** "aa:bb:cc:dd:ee:ff" to the controller's LSB-first bytes, or null if malformed. */
export function parseKeyboardAddress(text: string): Uint8Array | null {
if (!/^(?:[0-9a-f]{2}:){5}[0-9a-f]{2}$/i.test(text)) return null;
return Uint8Array.from(text.split(":").reverse().map((part) => parseInt(part, 16)));
}
/** Lenient UTF-8 decode (advertised names); no TextDecoder in every runtime this loads in. */
function decodeUtf8(bytes: Uint8Array): string {
let out = "";
for (let i = 0; i < bytes.length;) {
const b = bytes[i++]!;
let code = b;
let extra = 0;
if (b >= 0xf0 && b < 0xf8) { code = b & 0x07; extra = 3; }
else if (b >= 0xe0) { code = b & 0x0f; extra = 2; }
else if (b >= 0xc0) { code = b & 0x1f; extra = 1; }
else if (b >= 0x80) { out += "�"; continue; }
if (i + extra > bytes.length) { out += "�"; break; }
let valid = true;
for (let k = 0; k < extra; k++) {
const c = bytes[i + k]!;
if ((c & 0xc0) !== 0x80) { valid = false; break; }
code = (code << 6) | (c & 0x3f);
}
if (!valid || code > 0x10ffff) { out += "�"; continue; }
i += extra;
if (code === 0) continue;
out += String.fromCodePoint(code);
}
return out;
}
+131
View File
@@ -0,0 +1,131 @@
/**
* The keyboard bridge as the app uses it: one KeyboardBridge for the life of
* the app, fed by whichever glasses session is live, its remembered keyboard
* kept in the settings store, and its key transitions turned into KeyEvents.
* The dashboard controller reports the link coming and going and takes the
* keys; the Settings app drives pairing through `bridge`.
*/
import { addKeyboardEventListener, keyboardLinkSession, sendKeyboardControlRecord } from "../../native/keyboard-link";
import { getStringSetting, setStringSetting } from "../../native/settings-store";
import { KeyboardBridge, type KeyboardBridgeSnapshot, type SavedKeyboard } from "./bridge";
import { KeyTranslator, type KeyEvent } from "./keys";
declare const java: any;
declare const arc4random_uniform: ((bound: number) => number) | undefined;
/** JSON of the remembered keyboard ({ address, addressType, name }), or "" for none. */
const SAVED_KEYBOARD_KEY = "keyboard.saved";
export type KeyboardServiceHost = {
onKey(event: KeyEvent): void;
/** Routine lines only (failed background reconnects); the rest go to the device log directly. */
log(line: string): void;
/** Whether an absent keyboard is worth looking for now (see KeyboardBridgeHost). */
shouldReconnect(): boolean;
};
function loadSavedKeyboard(): SavedKeyboard | null {
try {
const raw = getStringSetting(SAVED_KEYBOARD_KEY, "");
if (!raw) return null;
const value = JSON.parse(raw);
if (typeof value?.address !== "string" || typeof value?.addressType !== "number") return null;
return { address: value.address, addressType: value.addressType, name: typeof value.name === "string" ? value.name : "" };
} catch {
return null;
}
}
/** Passkey entry only protects the pairing if the passkey can't be guessed. */
function randomPasskey(): number {
try {
if (global.isAndroid) return new java.security.SecureRandom().nextInt(1_000_000);
if (typeof arc4random_uniform === "function") return arc4random_uniform(1_000_000);
} catch {
// Fall through to the weaker source rather than failing the pairing.
}
return Math.floor(Math.random() * 1_000_000);
}
class KeyboardService {
private host: KeyboardServiceHost | null = null;
private session: unknown = null;
private offEvents: (() => void) | null = null;
private readonly listeners = new Set<() => void>();
private readonly translator = new KeyTranslator({ emit: (event) => this.host?.onKey(event) });
readonly bridge = new KeyboardBridge({
send: (record) => {
const session = this.session;
if (!session) return false;
try {
return sendKeyboardControlRecord(session, record, `op=${record[3]}`);
} catch {
return false;
}
},
loadSaved: loadSavedKeyboard,
storeSaved: (saved) => setStringSetting(SAVED_KEYBOARD_KEY, saved ? JSON.stringify(saved) : ""),
onKeys: (events) => this.translator.handle(events),
onKeyboardGone: () => this.translator.reset(),
onChanged: () => {
for (const listener of [...this.listeners]) listener();
},
// Pairing and setup are rare and are what a failure report needs, so
// they always reach the device log. Nothing here ever includes a key.
log: (line, routine) => {
if (routine) this.host?.log(line);
else console.log(`[keyboard] ${line}`);
},
randomPasskey,
shouldReconnect: () => this.host?.shouldReconnect() ?? true,
});
setHost(host: KeyboardServiceHost): void {
this.host = host;
}
snapshot(): KeyboardBridgeSnapshot {
return this.bridge.snapshot();
}
/** Called on every bridge state change. Returns an unsubscribe function. */
subscribe(listener: () => void): () => void {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
}
/** The glasses came into use (the display woke): look for an absent keyboard now. */
retryNow(): void {
this.bridge.retryNow();
}
/** A G2 session on firmware with the bridge is up. Idempotent. */
linkReady(): void {
const session = keyboardLinkSession();
if (!session) return;
if (session !== this.session) {
// The native session object is rebuilt across reconnects.
this.offEvents?.();
this.session = session;
this.offEvents = addKeyboardEventListener(session, (body) => this.bridge.accept(body));
}
this.bridge.linkReady();
}
/**
* The session can't host the keyboard any more. `release` asks the firmware
* to let the keyboard go first, for when the link itself stays up (the
* glasses went into their case, or the app is disconnecting on purpose).
* Idempotent.
*/
linkLost(release = false): void {
if (release) this.bridge.linkClosing();
this.bridge.linkLost();
this.offEvents?.();
this.offEvents = null;
this.session = null;
}
}
export const keyboardService = new KeyboardService();