This commit is contained in:
James Babcock committed 2026-08-30 00:42:27 -07:00
commit d542acb891
315 files changed
+35117 -2087

No files matched your search

+75 -11
View File
@@ -5,6 +5,8 @@ const VOICE_PERMISSION_REQUEST_CODE = 4243;
const CALENDAR_PERMISSION_REQUEST_CODE = 4244;
const LOCATION_PERMISSION_REQUEST_CODE = 4245;
const FINE_LOCATION_PERMISSION_REQUEST_CODE = 4246;
const BLE_ONLY_PERMISSION_REQUEST_CODE = 4247;
const POST_NOTIFICATIONS_PERMISSION_REQUEST_CODE = 4248;
const POST_NOTIFICATIONS_PERMISSION = "android.permission.POST_NOTIFICATIONS";
const RECORD_AUDIO_PERMISSION = "android.permission.RECORD_AUDIO";
const READ_CALENDAR_PERMISSION = "android.permission.READ_CALENDAR";
@@ -31,23 +33,22 @@ function toJavaStringArray(values: string[]): string[] {
return result;
}
function getRequiredPermissions(): string[] {
const sdk = android.os.Build.VERSION.SDK_INT;
const permissions: string[] = [];
if (sdk >= 31) {
permissions.push(
/** The runtime permissions this Android version needs for BLE scan + connect. */
function getBlePermissions(): string[] {
if (android.os.Build.VERSION.SDK_INT >= 31) {
return [
android.Manifest.permission.BLUETOOTH_SCAN,
android.Manifest.permission.BLUETOOTH_CONNECT,
);
} else {
permissions.push(android.Manifest.permission.ACCESS_FINE_LOCATION);
];
}
return [android.Manifest.permission.ACCESS_FINE_LOCATION];
}
if (sdk >= 33) {
function getRequiredPermissions(): string[] {
const permissions = getBlePermissions();
if (android.os.Build.VERSION.SDK_INT >= 33) {
permissions.push(POST_NOTIFICATIONS_PERMISSION);
}
return permissions;
}
@@ -107,6 +108,69 @@ export async function ensureVoicePermissions(): Promise<void> {
await ensurePermissions([RECORD_AUDIO_PERMISSION], VOICE_PERMISSION_REQUEST_CODE, "Voice control");
}
/** Whether the BLE scan/connect permissions have been granted (false off-Android). */
export function hasBlePermissions(): boolean {
if (!global.isAndroid) return false;
return getBlePermissions().every((permission) => isPermissionGranted(permission));
}
/**
* Prompt for just the BLE permissions (without POST_NOTIFICATIONS, which the
* Permissions screen presents as its own card). Resolves true when granted.
*/
export async function requestBlePermissions(): Promise<boolean> {
if (!global.isAndroid) return false;
try {
await ensurePermissions(getBlePermissions(), BLE_ONLY_PERMISSION_REQUEST_CODE, "Bluetooth");
return true;
} catch {
return false;
}
}
/**
* Whether posting notifications is allowed. Before Android 13 (sdk 33) there
* is no runtime permission for this, so it reports as granted.
*/
export function hasPostNotificationsPermission(): boolean {
if (!global.isAndroid) return false;
if (android.os.Build.VERSION.SDK_INT < 33) return true;
return isPermissionGranted(POST_NOTIFICATIONS_PERMISSION);
}
/** Prompt for POST_NOTIFICATIONS. Resolves true when the permission is held afterward. */
export async function requestPostNotificationsPermission(): Promise<boolean> {
if (!global.isAndroid) return false;
if (android.os.Build.VERSION.SDK_INT < 33) return true;
try {
await ensurePermissions(
[POST_NOTIFICATIONS_PERMISSION],
POST_NOTIFICATIONS_PERMISSION_REQUEST_CODE,
"Notification",
);
return true;
} catch {
return false;
}
}
/** Whether RECORD_AUDIO has been granted (false off-Android). */
export function hasMicrophonePermission(): boolean {
if (!global.isAndroid) return false;
return isPermissionGranted(RECORD_AUDIO_PERMISSION);
}
/** Prompt for RECORD_AUDIO. Resolves true when granted, false on denial. */
export async function requestMicrophonePermission(): Promise<boolean> {
if (!global.isAndroid) return false;
try {
await ensureVoicePermissions();
return true;
} catch {
return false;
}
}
/** Whether READ_CALENDAR has been granted (false off-Android). */
export function hasCalendarPermission(): boolean {
if (!global.isAndroid) return false;
+172
View File
@@ -0,0 +1,172 @@
/**
* How far away an advertising device probably is, from its signal strength.
*
* The calibration table is narrowed to the two products this app pairs.
*
* ## The model
*
* The log-distance path loss model:
*
* RSSI = txPower - 10 · n · log₁₀(d) ⇒ d = 10 ^ ((txPower - RSSI) / (10 · n))
*
* `txPower` is the expected signal at one metre and `n` the path loss
* exponent — 2.0 in free space, higher indoors where walls and bodies absorb.
* The reference power always comes from the per-product calibration table. An
* advertised BLE "TX Power Level" is deliberately NOT used: that field is the
* radiated power at the antenna (typically 0…+4 dBm), not an iBeacon-style
* measured power at one metre, and reading it as the latter inflates every
* distance by orders of magnitude.
*
* ## What this is for, and what it is not
*
* It exists so a pairing list can be ordered by "which of these is in my
* hand", and so a row can say roughly how far away its device is. That is a
* ranking problem, and RSSI ordering is far more trustworthy than RSSI
* magnitude — the ordering survives calibration error that would put the
* absolute numbers metres out.
*
* It is **not** a measurement. A hand over the temple, a pocket, or a body
* between phone and glasses moves the estimate by metres. The wearer therefore
* only ever sees a coarse zone (glyph + label), never a number in metres they
* might over-trust; the metres value exists purely to rank and bucket.
*
* This module is pure (no NativeScript imports) so it can run under node tests.
*/
import { clamp } from "../util/numeric-util";
/** Expected RSSI at one metre, and the path loss exponent, per product. */
export type ProximityCalibration = {
readonly txPowerAtOneMeter: number;
readonly pathLossExponent: number;
};
/**
* Even Realities G2. Two temple radios on a head, usually held or worn
* indoors, so the exponent sits above free space. Verified only as a ranking
* input — see the module note.
*/
export const GLASSES_CALIBRATION: ProximityCalibration = { txPowerAtOneMeter: -62, pathLossExponent: 2.2 };
/**
* Even Realities R1. A ring antenna is smaller and more easily shadowed by a
* hand, so it reads weaker at the same distance than the glasses do.
*/
export const RING_CALIBRATION: ProximityCalibration = { txPowerAtOneMeter: -68, pathLossExponent: 2.3 };
/**
* Estimates below this are indistinguishable from "touching the phone", and
* above it from "somewhere else entirely". Clamping keeps a noisy sample from
* rendering as 0.001 m.
*/
export const MINIMUM_METERS = 0.1;
export const MAXIMUM_METERS = 100;
/**
* Coarse buckets. The wearer is being asked "is this the pair in your hand?",
* and a bucket answers that better than a number they might over-trust.
*/
export type ProximityZone = "immediate" | "near" | "far" | "distant";
export function zoneFromMeters(meters: number): ProximityZone {
if (meters < 0.5) return "immediate";
if (meters < 3) return "near";
if (meters < 10) return "far";
return "distant";
}
export function zoneLabel(zone: ProximityZone): string {
switch (zone) {
case "immediate":
return "In your hand";
case "near":
return "Nearby";
case "far":
return "Across the room";
case "distant":
return "Far away";
}
}
/** A glyph for the zone; SF Symbols have no Android equivalent, so plain text. */
export function zoneGlyph(zone: ProximityZone): string {
switch (zone) {
case "immediate":
return "●●●●";
case "near":
return "●●●○";
case "far":
return "●●○○";
case "distant":
return "●○○○";
}
}
/** A distance estimate and how much to trust it. */
export type ProximityEstimate = {
readonly meters: number;
/** 0…1. Drops with weak signal. */
readonly confidence: number;
readonly zone: ProximityZone;
};
/**
* Estimate distance from a signal sample. Null when there is no RSSI to work
* from, so callers can say "signal unknown" rather than render a fabricated
* distance. 127 is the Bluetooth "RSSI unavailable" sentinel.
*/
export function estimateProximity(rssi: number | null | undefined, calibration: ProximityCalibration): ProximityEstimate | null {
if (rssi == null || !Number.isFinite(rssi) || rssi === 127) return null;
const ratio = (calibration.txPowerAtOneMeter - rssi) / (10 * calibration.pathLossExponent);
const meters = clamp(Math.pow(10, ratio), MINIMUM_METERS, MAXIMUM_METERS);
return {
meters,
confidence: proximityConfidence(rssi),
zone: zoneFromMeters(meters),
};
}
/**
* Confidence falls with signal strength, because a weak sample is a noisy one.
* The 0.85 ceiling reflects that the TX power is always an assumption from the
* calibration table, never a measurement.
*/
export function proximityConfidence(rssi: number): number {
let confidence = 0.85;
if (rssi < -85) confidence *= 0.4;
else if (rssi < -75) confidence *= 0.7;
else if (rssi < -65) confidence *= 0.85;
return confidence;
}
/**
* Order a list closest-first.
*
* Items whose signal never arrived sort last rather than being dropped: a pair
* that cannot be ranked is still a pair the wearer may need to choose, and
* hiding it would be worse than showing it at the bottom. Ties break on the
* stable id so the list does not reshuffle between scan passes — a list that
* reorders under the finger is how the wrong device gets tapped, which is the
* whole failure this ordering exists to prevent.
*/
export function sortedByProximity<T>(
items: readonly T[],
estimate: (item: T) => ProximityEstimate | null,
id: (item: T) => string,
): T[] {
return items.slice().sort((lhs, rhs) => {
const left = estimate(lhs);
const right = estimate(rhs);
if (left && right) {
if (left.meters !== right.meters) return left.meters < right.meters ? -1 : 1;
return compareIds(id(lhs), id(rhs));
}
if (left && !right) return -1;
if (!left && right) return 1;
return compareIds(id(lhs), id(rhs));
});
}
function compareIds(a: string, b: string): number {
return a < b ? -1 : a > b ? 1 : 0;
}
+417 -83
View File
@@ -1,5 +1,5 @@
import { Application, ImageSource } from "@nativescript/core";
import { EvenAIStatus, EvenAIStatusName, EventSourceType, EventSourceTypeName, OsEventTypeList, OsEventTypeName } from "./events";
import { EvenAIStatus, EvenAIStatusName, EventSourceType, EventSourceTypeName, OsEventTypeList, OsEventTypeName, WatchGestureType, WatchGestureTypeName } from "./events";
import { loadDeviceAddresses } from "./device-addresses";
import { ensureBlePermissions, ensureVoicePermissions } from "./android-permissions";
import { FaceclawCommunicatorBridge, type RawInputEvent } from "../native/faceclaw-communicator";
@@ -12,6 +12,29 @@ import { openEvenAppSettings, readEvenAppNotificationState } from "../native/eve
import { grayImageToPreviewSource } from "../native/gray-image-preview";
import { firmwareIncompatibilityMessage } from "./firmware-compat";
import { resumeAutoReconnect, suppressAutoReconnect } from "./reconnect-policy";
import { WearRemote, type WearRemoteInputKind } from "./wear-remote";
/** Who a synthetic (non-firmware) input stands for. */
type SyntheticInputOrigin = "ring" | "watch";
/** Gestures the phone's mirror view reports (see handleMirrorTouch). */
export type MirrorTouchKind =
| "tap"
| "double-tap"
| "long-press"
| "swipe-up"
| "swipe-down"
| "swipe-left"
| "swipe-right";
const MIRROR_TOUCH_GESTURES: Record<Exclude<MirrorTouchKind, "tap">, WearRemoteInputKind> = {
"double-tap": "double-click",
"long-press": "long-press",
"swipe-up": "swipe-up",
"swipe-down": "swipe-down",
"swipe-left": "swipe-left",
"swipe-right": "swipe-right",
};
import { findSoundEffect, playSoundEffect } from "../ui/sound-effects";
import { isWelcomeSoundPending, setWelcomeSoundPending } from "../phone-ui/onboarding-state";
import { beginRenderPass, endRenderPass } from "../util/render-freshness";
@@ -33,9 +56,9 @@ import { ALL_APPS } from "../apps/all-apps";
import { type AppContext, type AppDefinition, type AppLaunchParams, type TextEditorHost } from "../apps/app-definition";
import { type InProcessAppOptions, type InProcessWindow } from "../ui/shell/in-process-window";
import { loadPersistedOpenApps, savePersistedOpenApps } from "../ui/shell/open-apps-persistence";
import { appViewportRect, type WindowHeightMode } from "../ui/shell/geometry";
import { appViewportRect, SIDEBAR_WIDTH, sidebarStripVisible, type WindowHeightMode } from "../ui/shell/geometry";
import { type LayerActions, type TextSettingsEditToggle } from "../ui/layers";
import { assistantAllowProactiveSetting, assistantBackendSetting, assistantBridgeHostSetting, assistantBridgePortSetting, assistantBridgeTokenSetting, brightnessSetting, brightnessSettingToLevel, elevenLabsApiKeySetting, getStringSettingById, openAiApiKeySetting, nightscoutApiTokenSetting, firmwareDebugFlagsSetting, lockScreenEnabledSetting, nightscoutSiteUrlSetting, onAnySettingChanged, saveVoiceRecordingsSetting, sonioxApiKeySetting, screenTimeoutSetting, screenTimeoutSettingToMs, suspendEvenHubWhenScreenOffSetting, verticalPositionSetting, voiceProviderSetting, wakeWordActionSetting, type ConfigSettingString } from "../ui/dashboard-settings";
import { assistantAllowProactiveSetting, assistantBackendSetting, assistantBridgeHostSetting, assistantBridgePortSetting, assistantBridgeTokenSetting, brightnessSetting, brightnessSettingToLevel, displayModeSetting, elevenLabsApiKeySetting, getStringSettingById, openAiApiKeySetting, nightscoutApiTokenSetting, firmwareDebugFlagsSetting, lockScreenEnabledSetting, nightscoutSiteUrlSetting, onAnySettingChanged, previewColorSetting, ringConnectionModeSetting, saveVoiceRecordingsSetting, sonioxApiKeySetting, screenTimeoutSetting, screenTimeoutSettingToMs, suspendEvenHubWhenScreenOffSetting, verticalPositionSetting, voiceProviderSetting, wakeWordActionSetting, type ConfigSettingString } from "../ui/dashboard-settings";
import { isIgnoringBatteryOptimizations, requestIgnoreBatteryOptimizations } from "../native/battery-optimization";
import {
getInstalledEvenHubAppById,
@@ -43,13 +66,15 @@ import {
uninstallEvenHubPackage,
} from "../apps/evenhub/installed-apps";
import { closeRunningPackage, launchInstalledPackage } from "../apps/evenhub/manager";
import { wearerVerificationOptions } from "../apps/microphones/speakers";
import { micSession } from "../apps/microphones/mic-session";
import { glassesDisplayLabel } from "./glasses-display-state";
type ConnectionPhase = "disconnected" | "connecting" | "connected" | "charging" | "disconnecting";
export type DashboardSnapshot = {
phase: ConnectionPhase;
status: string;
log: string;
displayPreview: ImageSource | null;
/**
* When non-empty, the phone UI shows this instead of the display preview:
@@ -87,13 +112,20 @@ const LOCK_SCREEN_MESSAGE = "Glasses locked; unlock the phone to unlock the glas
// Top-bar clock refresh; the phone-side preview polls the Java composite so
// it reflects every app (including worker apps the TS side never renders).
const SHELL_REFRESH_INTERVAL_MS = 60_000;
// Safety-net poll only; the preview is event-driven (every composited frame
// schedules a refresh), so this just covers anything that slips through.
const PREVIEW_INTERVAL_MS = 1_000;
const SCREEN_TIMEOUT_CHECK_MS = 1_000;
const EVENHUB_SCREEN_OFF_SUSPEND_DELAY_MS = 5_000;
const EVENHUB_WAKE_READY_TIMEOUT_MS = 4_500;
const FOREGROUND_NOTIFICATION_MIN_UPDATE_MS = 30_000;
const FRAME_TRANSMIT_BACKPRESSURE_TIMEOUT_MS = 6_000;
const CONNECTED_PREVIEW_MIN_UPDATE_MS = 1_000;
// Preview refresh floor. Refreshes are scheduled per composited frame with a
// trailing update, so the mirror tracks the glasses within this bound instead
// of the old 1s poll (which lagged up to two polls behind).
const CONNECTED_PREVIEW_MIN_UPDATE_MS = 150;
// The GIF recorder keeps its old cadence; per-frame captures would balloon it.
const RECORDING_MIN_CAPTURE_MS = 1_000;
// Below this, a disconnect is more likely a flat battery than a BLE problem.
const LOW_BATTERY_PERCENT = 5;
const EVEN_APP_DETECTED_MESSAGE =
@@ -141,6 +173,9 @@ function eventLabel(kind: string, eventType: number): string {
if (kind === "even-ai") {
return EvenAIStatusName[eventType] ?? `EVEN_AI_UNKNOWN_${eventType}`;
}
if (kind === "watch-gesture") {
return WatchGestureTypeName[eventType] ?? `WATCH_UNKNOWN_${eventType}`;
}
return eventName(eventType);
}
@@ -151,7 +186,6 @@ function sourceName(eventSource: number): string {
class DashboardController {
private phase: ConnectionPhase = "disconnected";
private status = "Disconnected.";
private log = "";
private activeTextSettings: ConfigSettingString[] = [];
private activeTextEditorTitle = "";
private activeTextEditorOnFinish: (() => void) | null = null;
@@ -186,6 +220,8 @@ class DashboardController {
private glassesWorn: boolean | null = null;
private phoneLocked = false;
private glassesLocked = false;
// Wear OS watch remote; constructed last so it sees a fully wired shell.
private wearRemote: WearRemote | null = null;
private lockSurfaceConfigured = false;
private lastLockScreenEnabled = lockScreenEnabledSetting.get();
private offState: (() => void) | null = null;
@@ -199,7 +235,6 @@ class DashboardController {
private offFrameMetrics: (() => void) | null = null;
private offFirmwareInfo: (() => void) | null = null;
private offVoiceStatus: (() => void) | null = null;
private offVoiceWakeWord: (() => void) | null = null;
private offAndroidNotification: (() => void) | null = null;
private lastInput = "waiting...";
private lastSys = "none yet";
@@ -227,6 +262,7 @@ class DashboardController {
// underneath it, so it waits for this to clear.
private connectRunning = false;
private incompatibleDisconnectPending = false;
private unpairedDisconnectPending = false;
constructor() {
const sharedActions = {
@@ -270,10 +306,15 @@ class DashboardController {
},
getScreenTimeoutMs: () => screenTimeoutSettingToMs(screenTimeoutSetting.get()),
requestShellRender: () => this.requestShellRender(),
onWindowsChanged: () => this.persistOpenApps(),
onWindowsChanged: () => {
this.persistOpenApps();
// The foreground title is mirrored on both remote-control faces.
this.emit();
},
onScreenStateChanged: (on) => {
this.handleScreenStateChanged(on);
if (on) this.requestShellRender();
this.emit();
},
});
// Boot hooks register windows that exist from startup (the launcher,
@@ -295,13 +336,37 @@ class DashboardController {
this.pushBrightness();
this.syncEvenHubScreenOffSetting();
this.applyVerticalPositionIfChanged();
this.applyDisplayModeIfChanged();
this.syncAssistantBridgeIfChanged();
this.syncLockScreenSettingIfChanged();
// A Preview color change should show on the mirror at once, not at the
// next composited frame (cheap: floor-limited, dedup'd on the Java side).
this.schedulePreviewUpdate();
});
// Connect to the external agent bridge at boot if configured; the
// connection stays up (with re-dial) so proactive tool calls work
// outside voice turns.
this.syncAssistantBridge();
// The watch drives the same synthetic-input path as the phone UI's test
// buttons, plus app/window/lock commands; it mirrors the state below.
this.wearRemote = new WearRemote({
apps: LAUNCHABLE_APPS,
injectInput: (kind) => this.injectSyntheticRingInput(kind, "watch"),
launchApp: (appId) => this.launchApp(appId),
connect: () => this.connect(),
disconnect: () => this.disconnect(),
setGlassesLocked: (locked, reason) => this.setGlassesLocked(locked, reason),
requestShellRender: () => this.requestShellRender(),
getState: () => ({
phase: this.phase,
status: this.status,
glassesLocked: this.glassesLocked,
glassesWorn: this.glassesWorn,
silentMode: this.silentMode,
lastHeadsetBattery: this.lastHeadsetBattery,
}),
appendLog: (line) => this.appendLog(line),
});
}
// Bridge settings changes re-dial the connection; unrelated setting changes
@@ -344,6 +409,48 @@ class DashboardController {
// don't trigger a full reposition.
private lastVerticalPosition = verticalPositionSetting.get();
private lastDisplayMode = displayModeSetting.get();
/**
* Display mode changed (Settings > Display, or the phone page's picker):
* every window's viewport size changes. In-process windows re-measure in
* place; worker windows get their canvas once at open, so they are closed
* and launched again at the new size.
*/
private applyDisplayModeIfChanged(): void {
const mode = displayModeSetting.get();
if (mode === this.lastDisplayMode) return;
this.lastDisplayMode = mode;
this.appendLog(`display mode: ${mode}`);
const foregroundWindowId = shell.foregroundWindow()?.windowId;
void (async () => {
const relaunch: string[] = [];
for (const window of Array.from(shell.getWindows())) {
if (window.relayout) {
window.relayout();
await this.configureWindowSurface(
window.surfaceId,
window.windowId === foregroundWindowId,
window.heightMode,
);
} else if (window.closeable) {
relaunch.push(window.appId);
shell.closeWindow(window.windowId);
}
}
for (const appId of relaunch) {
await this.launchApp(appId);
}
if (foregroundWindowId && shell.getWindows().some((w) => w.windowId === foregroundWindowId)) {
shell.focusWindow(foregroundWindowId);
}
shell.foregroundWindow()?.requestRender();
this.requestShellRender();
})().catch((error) => {
this.appendLog(`display mode change failed: ${this.formatError(error)}`);
});
}
private applyVerticalPositionIfChanged(): void {
const position = verticalPositionSetting.get();
if (position === this.lastVerticalPosition) return;
@@ -405,6 +512,7 @@ class DashboardController {
private handleWearState(wearing: boolean): void {
this.glassesWorn = wearing;
this.appendLog(wearing ? "glasses wear state: ON_HEAD" : "glasses wear state: OFF_HEAD");
this.wearRemote?.schedulePublish();
if (!wearing && this.phoneLocked && lockScreenEnabledSetting.get()) {
this.setGlassesLocked(true, "glasses removed while phone locked");
}
@@ -425,6 +533,7 @@ class DashboardController {
if (locked === this.glassesLocked) return;
this.glassesLocked = locked;
this.appendLog(`glasses ${locked ? "locked" : "unlocked"}: ${reason}`);
this.wearRemote?.schedulePublish();
void this.syncLockSurface().catch((error) => {
this.appendLog(`lock screen update failed: ${this.formatError(error)}`);
});
@@ -600,6 +709,14 @@ class DashboardController {
return;
}
if (voiceControlBridge.isCaptureHeld()) {
// Ending the plugin task ends the mic with it, so a live capture (the
// Transcribe window, typically) outranks the screen-off power save.
// Check before the lease refresh below, which costs a BLE message.
this.scheduleEvenHubSuspend();
return;
}
void (async () => {
if (this.faceclawWakeLeaseSupported) {
// Refresh immediately before teardown so the first suspended wake
@@ -625,6 +742,9 @@ class DashboardController {
.then((suspended) => {
if (suspended === undefined) return;
if (suspended) {
// A capture that raced the suspend lost its mic with the plugin
// task; park it for the resume path.
voiceControlBridge.handleSessionEnded();
this.appendLog("EvenHub session suspended while screen is off");
return;
}
@@ -726,7 +846,6 @@ class DashboardController {
return {
phase: this.phase,
status: this.status,
log: this.log,
displayPreview: this.displayPreview,
displayPreviewMessage: this.displayPreviewMessage(),
activeTextSettingId: primaryTextSetting?.id ?? null,
@@ -753,12 +872,15 @@ class DashboardController {
/**
* Message to show in place of the display preview, or "" to show the preview.
*
* Both cases look identical to a dead pair of glasses from the phone side:
* silent mode blanks the display and swallows input while the BLE session
* stays up, and a battery that just ran out simply stops answering.
* These states look identical to a dead pair of glasses from the phone side:
* charging and silent mode both make the display unavailable while BLE stays
* up, and a battery that just ran out simply stops answering.
*/
private displayPreviewMessage(): string {
if (this.silentMode && (this.phase === "connected" || this.phase === "charging")) {
if (this.phase === "charging") {
return this.glassesDisplayLabel();
}
if (this.silentMode && this.phase === "connected") {
return "Connected (Silent mode enabled)";
}
const connectionFailing = this.phase === "disconnected" || this.phase === "connecting";
@@ -772,6 +894,17 @@ class DashboardController {
return "";
}
/** What occupies the foreground-title line on the watch-style controls. */
glassesDisplayLabel(): string {
return glassesDisplayLabel({
phase: this.phase,
silentMode: this.silentMode,
screenOn: shell.isScreenOn(),
battery: this.lastHeadsetBattery,
foregroundTitle: shell.getForegroundApp()?.title ?? null,
});
}
/**
* Re-check the Doze exemption (cheap system call, but cached so snapshot()
* stays trivial). Called on connect, page load, and after the user answers
@@ -854,7 +987,6 @@ class DashboardController {
this.appendLog(`error: ${message}`);
throw new Error(message);
}
this.log = "";
this.lastInput = "waiting...";
this.lastSys = "none yet";
this.welcomeSoundArmed = isWelcomeSoundPending();
@@ -865,8 +997,13 @@ class DashboardController {
this.refreshEvenAppStatus();
this.setPhase("connecting");
this.setStatus("Connecting to the glasses...");
// "Only via glasses" (the default) means the phone never opens its own
// link to the ring: the glasses relay its gestures to us anyway, and the
// direct link is currently unreliable. An empty address disables every
// direct-ring code path in the communicator.
const ringAddress = ringConnectionModeSetting.get() === "direct" ? addresses.ring : "";
this.appendLog(
`Using configured arms: R=${addresses.right} L=${addresses.left}${addresses.ring ? ` ring=${addresses.ring}` : ""}`,
`Using configured arms: R=${addresses.right} L=${addresses.left}${ringAddress ? ` ring=${ringAddress}` : ""}`,
);
let communicator: FaceclawCommunicatorBridge | null = null;
@@ -883,13 +1020,21 @@ class DashboardController {
communicator = new FaceclawCommunicatorBridge({
right: addresses.right,
left: addresses.left,
ring: addresses.ring,
ring: ringAddress,
});
this.communicator = communicator;
this.offLog = communicator.onLog((line) => {
this.appendLog(line);
});
this.offState = communicator.onStateChange((state) => {
if (state.phase === "unpaired") {
// Java parked its retry loop: an arm's Android bond is gone, so
// every redial would fail the same way until the user re-pairs.
// Tear down into the manual-disconnected state and keep the
// re-pair instruction as the visible status.
this.scheduleUnpairedDisconnect(state.status);
return;
}
const mappedPhase =
state.phase === "connected"
? "connected"
@@ -923,6 +1068,10 @@ class DashboardController {
// the transport comes back, so do not make lock decisions from a
// stale pre-disconnect value in the meantime.
this.glassesWorn = null;
// The mic enable was session-scoped too: park any live capture so
// the next session restarts it, instead of leaving a holder that
// makes every later request think the mic is already running.
voiceControlBridge.handleSessionEnded();
}
this.setPhase(mappedPhase);
this.setStatus(state.status);
@@ -952,15 +1101,21 @@ class DashboardController {
this.handlePhoneLockState(locked);
});
this.offBattery = communicator.onBatteryState((state) => {
this.lastHeadsetBattery = state.battery >= 0 ? state.battery : null;
// An unavailable reading must not erase the useful last-known value,
// especially while the glasses remain reachable in their case.
const hasBatteryLevel = Number.isInteger(state.battery) && state.battery >= 0 && state.battery <= 100;
if (hasBatteryLevel) this.lastHeadsetBattery = state.battery;
shell.setBatteryLevels({
headset: state.battery,
headset: hasBatteryLevel ? state.battery : this.lastHeadsetBattery,
headsetCharging: state.chargingStatus > 0,
});
if ((this.phase === "connected" || this.phase === "charging") && this.communicator) {
// Repaint the top bar (battery indicators live in the shell chrome).
this.requestShellRender();
}
// Battery belongs in the charging stand-in on the phone as well as in
// the watch state, so refresh both consumers on every report.
this.emit();
});
this.offEvenAppConflict = communicator.onEvenAppConflict((message) => {
this.refreshEvenAppStatus();
@@ -973,8 +1128,16 @@ class DashboardController {
this.emit();
});
this.offFrameMetrics = communicator.onFrameMetrics(() => {
// Every composited frame refreshes the phone-side mirror (bounded by
// CONNECTED_PREVIEW_MIN_UPDATE_MS) so it tracks the glasses instead
// of trailing the 1s safety-net poll.
this.schedulePreviewUpdate();
if (this.phase === "connected") {
this.setStatus("Connected.");
// A rendered frame also means the display path is warm enough for
// the glasses to accept a mic enable, so this is where a capture
// parked by the previous session (or by an EvenHub suspend) resumes.
this.resumeVoiceCapture();
// A rendered frame means the session is warmed up (fixedLayoutCreated),
// so the buzzer won't be dropped. Play the one-time welcome sound now.
if (this.welcomeSoundArmed) {
@@ -1025,11 +1188,6 @@ class DashboardController {
this.offVoiceStatus = voiceControlBridge.onStatus((state) => {
this.appendLog(state.status);
});
this.offVoiceWakeWord = voiceControlBridge.onWakeWord((keyword) => {
void this.handleWakeWord(keyword).catch((error) => {
this.appendLog(`wake-word handler failed: ${this.formatError(error)}`);
});
});
await mediaControllerBridge.start();
await nightscoutBridge.start();
@@ -1096,8 +1254,6 @@ class DashboardController {
this.offFirmwareInfo = null;
this.offVoiceStatus?.();
this.offVoiceStatus = null;
this.offVoiceWakeWord?.();
this.offVoiceWakeWord = null;
await mediaControllerBridge.stop().catch(() => {});
await nightscoutBridge.stop().catch(() => {});
voiceControlBridge.stop();
@@ -1158,6 +1314,40 @@ class DashboardController {
setTimeout(attempt, 0);
}
/**
* A connect attempt found an arm whose Android bond is missing, so the Java
* worker stopped retrying. Drop into the manual-disconnected state (no
* auto-reconnect: it would just fail again) and leave the re-pair
* instruction from Java as the status the user sees.
*/
private scheduleUnpairedDisconnect(message: string): void {
if (this.unpairedDisconnectPending) return;
this.unpairedDisconnectPending = true;
const attempt = () => {
// The unpaired report can arrive while connect() is still mid-flight;
// let it finish so the teardown doesn't race its surface setup.
if (this.connectRunning) {
setTimeout(attempt, 200);
return;
}
this.unpairedDisconnectPending = false;
if (this.phase === "disconnected" || this.phase === "disconnecting") {
// The session ended some other way; still stop auto-reconnect from
// re-dialing glasses that are no longer paired.
suppressAutoReconnect();
this.setStatus(message);
return;
}
this.appendLog(`Disconnecting: ${message} Auto-reconnect is disabled until you connect manually.`);
void this.disconnect({ skipFirmwareCleanup: true })
.then(() => this.setStatus(message))
.catch((error) => {
this.appendLog(`unpaired disconnect failed: ${this.formatError(error)}`);
});
};
setTimeout(attempt, 0);
}
/**
* Tear down the connection and enter the manual-disconnected state: every
* caller is deliberate (the phone/glasses Disconnect actions, entering the
@@ -1169,6 +1359,14 @@ class DashboardController {
*/
async disconnect(options?: { skipFirmwareCleanup?: boolean }): Promise<void> {
suppressAutoReconnect();
// The phone menu offers Disconnect during the connecting phase (it is the
// only way out of a reconnection-attempt loop), so a call can land while
// connect() is still mid-flight; let it finish so the teardown doesn't
// race its surface setup. connect() returns once the Java worker thread
// owns the retry loop, so this wait is short.
while (this.connectRunning) {
await new Promise((resolve) => setTimeout(resolve, 200));
}
if (this.phase === "disconnected" || this.phase === "disconnecting") return;
this.setPhase("disconnecting");
@@ -1196,8 +1394,6 @@ class DashboardController {
this.offFirmwareInfo = null;
this.offVoiceStatus?.();
this.offVoiceStatus = null;
this.offVoiceWakeWord?.();
this.offVoiceWakeWord = null;
const communicator = this.communicator;
this.communicator = null;
@@ -1234,7 +1430,7 @@ class DashboardController {
// Faceclaw's final BLE message before the transport closes.
await mediaControllerBridge.stop().catch(() => {});
await nightscoutBridge.stop().catch(() => {});
voiceControlBridge.stop();
voiceControlBridge.handleSessionEnded();
const cleanupAcked = skipFirmwareCleanup
? false
@@ -1269,20 +1465,89 @@ class DashboardController {
}
}
async injectSyntheticRingInput(
kind: "click" | "double-click" | "scroll-up" | "scroll-down" | "long-press" | "wakeword",
): Promise<void> {
/**
* Feed a ring gesture from somewhere other than the ring (the phone UI's
* test buttons, the watch). "long-press" is a complete short hold;
* "long-press-start" / "long-press-release" let a source with a real
* finger-down/finger-up (the watch) hold for as long as the user does.
*/
async injectSyntheticRingInput(kind: WearRemoteInputKind, origin: SyntheticInputOrigin = "ring"): Promise<void> {
// Match the ring while the display is dark: only a double-click wakes it,
// and that wake is handled by Shell.receiveInput. This check also protects
// against a watch acting on a stale state snapshot.
if (
origin === "watch" &&
!shell.isScreenOn() &&
kind !== "double-click" &&
kind !== "long-press-release"
) {
this.appendLog(`${kind} (watch scheme) ignored while display is off`);
return;
}
if (kind === "long-press") {
// Hardware delivers a press event and then a release when the finger
// lifts; emulate a short hold so the escape-menu countdown never fires.
await this.handleInputEvent(this.buildSyntheticRingInput("long-press"));
await this.handleInputEvent(this.buildSyntheticRingInput("long-press-release"));
await this.handleInputEvent(this.buildSyntheticRingInput("long-press", origin));
await this.handleInputEvent(this.buildSyntheticRingInput("long-press-release", origin));
return;
}
const event = this.buildSyntheticRingInput(kind);
const event = this.buildSyntheticRingInput(kind === "long-press-start" ? "long-press" : kind, origin);
await this.handleInputEvent(event);
}
/**
* A touch on the phone's mirror of the glasses display. Gestures other than
* a tap are the watch scheme (swipes navigate, double-tap is back, a hold
* is the menu). A tap lands on what the mirror shows: a sidebar icon
* switches to that window, a launcher cell opens, anything else selects.
* Coordinates are fractions of the mirror (0..1).
*/
async handleMirrorTouch(kind: MirrorTouchKind, nx: number, ny: number): Promise<void> {
if (this.phase !== "connected" && this.phase !== "charging") return;
if (this.glassesLocked) {
// Same as the ring: only a double-tap reaches a locked display.
if (kind === "double-tap") await this.injectSyntheticRingInput("double-click", "watch");
return;
}
if (!shell.isScreenOn()) {
if (kind === "double-tap") await this.injectSyntheticRingInput("double-click", "watch");
return;
}
if (kind !== "tap") {
await this.injectSyntheticRingInput(MIRROR_TOUCH_GESTURES[kind], "watch");
return;
}
const x = Math.round(Math.min(1, Math.max(0, nx)) * G2_LENS_WIDTH);
const y = Math.round(Math.min(1, Math.max(0, ny)) * G2_LENS_HEIGHT);
const stripShown = sidebarStripVisible(shell.getFocus());
this.appendLog(`mirror tap at ${x},${y}`);
if (!shell.hasOverlay() && stripShown && x < SIDEBAR_WIDTH) {
const target = shell.windowAtSidebarPoint(x, y);
if (target) {
this.appendLog(`mirror tap: sidebar -> ${target.title}`);
shell.focusWindow(target.windowId);
shell.foregroundWindow()?.requestRender();
this.requestShellRender();
}
return;
}
const window = shell.foregroundWindow();
if (window && !shell.hasOverlay()) {
const rect = appViewportRect(window.heightMode);
const inside = x >= rect.x && x < rect.x + rect.width && y >= rect.y && y < rect.y + rect.height;
if (shell.getFocus() !== "window") {
shell.focusWindow(window.windowId);
this.requestShellRender();
}
if (inside && window.hitTest && (await window.hitTest(x - rect.x, y - rect.y))) {
this.appendLog(`mirror tap: ${window.title} at ${x - rect.x},${y - rect.y}`);
this.requestShellRender();
return;
}
}
await this.injectSyntheticRingInput("click", "watch");
}
/** A document arrived via Android's Share intent: open it as a new window. */
async openSharedTextDocument(text: string): Promise<void> {
this.appendLog(`shared text document received (${text.length} chars)`);
@@ -1335,6 +1600,37 @@ class DashboardController {
voiceControlBridge.stopContinuousCapture();
}
/** Provider and key settings for a capture on the given connection. */
private voiceCaptureOptions(communicator: FaceclawCommunicatorBridge) {
return {
communicator: communicator.getNativeCommunicator(),
provider: voiceProviderSetting.get(),
elevenLabsApiKey: elevenLabsApiKeySetting.get(),
openAiApiKey: openAiApiKeySetting.get(),
sonioxApiKey: sonioxApiKeySetting.get(),
saveRecording: saveVoiceRecordingsSetting.get(),
// "My voice only" (Microphones app): verify command utterances
// against the enrolled wearer voice-print; non-matching speakers'
// finals are suppressed by the bridge.
speakerVerification: wearerVerificationOptions() ?? undefined,
// The Microphones app's processing config applies to every capture:
// spectral noise suppression and the Sonic Radar listening beam.
...micSession.captureProcessingOptions(),
};
}
/**
* Restart the mic for a capture that a previous session left holding. Cheap
* to call per frame: it does nothing unless one is actually parked.
*/
private resumeVoiceCapture(): void {
if (!voiceControlBridge.hasSuspendedCapture()) return;
const communicator = this.communicator;
if (!communicator || this.phase !== "connected") return;
this.appendLog("resuming voice capture on the new glasses session");
voiceControlBridge.resumeCapture(this.voiceCaptureOptions(communicator));
}
private beginVoiceCapture(kind: "ptt" | "continuous", endpointing = false): void {
if (this.phase !== "connected" || !this.communicator) {
return;
@@ -1343,15 +1639,7 @@ class DashboardController {
void ensureVoicePermissions()
.then(() => {
if (this.phase !== "connected" || this.communicator !== communicator) return;
const options = {
communicator: communicator.getNativeCommunicator(),
provider: voiceProviderSetting.get(),
elevenLabsApiKey: elevenLabsApiKeySetting.get(),
openAiApiKey: openAiApiKeySetting.get(),
sonioxApiKey: sonioxApiKeySetting.get(),
saveRecording: saveVoiceRecordingsSetting.get(),
endpointing,
};
const options = { ...this.voiceCaptureOptions(communicator), endpointing };
if (kind === "ptt") {
voiceControlBridge.startPushToTalk(options);
} else {
@@ -1427,7 +1715,8 @@ class DashboardController {
if (this.glassesLocked) {
const ringDoubleTap =
inputEvent.type === "double-click" &&
event.eventSource === EventSourceType.TOUCH_EVENT_FROM_RING;
(event.eventSource === EventSourceType.TOUCH_EVENT_FROM_RING ||
event.eventSource === EventSourceType.TOUCH_EVENT_FROM_WATCH);
const suspendedDisplayWake = inputEvent.type === "display-wake";
if (ringDoubleTap || suspendedDisplayWake) {
if (shell.isScreenOn()) {
@@ -1480,6 +1769,9 @@ class DashboardController {
outcome = { ...outcome, shell: true };
}
if (event.kind === "watch-gesture") {
this.appendLog(`watch-gesture ${eventLabel(event.kind, event.eventType)}`);
}
if (event.kind === "sys-event") {
this.lastSys = `${sourceName(event.eventSource)}/${eventName(event.eventType)}`;
this.appendLog(`sys-event ${this.lastSys}`);
@@ -1490,7 +1782,10 @@ class DashboardController {
) {
this.appendLog("display state invalidated by firmware exit event");
}
if (event.eventSource === EventSourceType.TOUCH_EVENT_FROM_RING) {
if (
event.eventSource === EventSourceType.TOUCH_EVENT_FROM_RING ||
event.eventSource === EventSourceType.TOUCH_EVENT_FROM_WATCH
) {
this.lastInput = eventName(event.eventType);
}
}
@@ -1830,21 +2125,7 @@ class DashboardController {
`still unsent after ${FRAME_TRANSMIT_BACKPRESSURE_TIMEOUT_MS}ms; shell render loop released`,
);
}
this.updateCompositePreview();
}
private async handleWakeWord(keyword: string): Promise<void> {
const normalized = keyword.trim();
if (normalized.length === 0) return;
this.appendLog(`wake-word detected: ${normalized}`);
const woke = shell.wake("sidebar");
if (woke) {
const ready = await this.ensureEvenHubSessionActive();
if (!ready) {
this.appendLog("EvenHub wake barrier timed out for phone wakeword");
}
this.requestShellRender();
}
this.schedulePreviewUpdate();
}
private async handleAndroidNotificationPosted(notificationKey: string): Promise<void> {
@@ -1895,6 +2176,10 @@ class DashboardController {
clearInterval(this.previewTimer);
this.previewTimer = null;
}
if (this.previewTrailingTimer) {
clearTimeout(this.previewTrailingTimer);
this.previewTrailingTimer = null;
}
if (this.screenTimeoutTimer) {
clearInterval(this.screenTimeoutTimer);
this.screenTimeoutTimer = null;
@@ -1927,10 +2212,7 @@ class DashboardController {
}
private appendLog(line: string): void {
const stamped = `[${formatTimestamp(new Date())}] ${line}`;
//this.log = this.log ? `${this.log}\n${stamped}` : stamped;
console.log(stamped);
//this.emit();
console.log(`[${formatTimestamp(new Date())}] ${line}`);
}
private setDisplayPreview(preview: ImageSource | null): void {
@@ -1945,8 +2227,41 @@ class DashboardController {
* foreground, including worker apps the TS side never renders). Throttled
* to avoid rebuilding the bitmap faster than the phone UI needs it.
*/
private previewTrailingTimer: ReturnType<typeof setTimeout> | null = null;
private lastRecordCaptureAtMs = 0;
/**
* Refresh the preview now if the floor allows, otherwise once the floor
* expires — so the last frame of a burst always reaches the mirror instead
* of waiting for the safety-net poll.
*/
private schedulePreviewUpdate(): void {
if (this.previewTrailingTimer) return;
const wait = this.lastConnectedPreviewUpdateAtMs + CONNECTED_PREVIEW_MIN_UPDATE_MS - Date.now();
if (wait <= 0) {
this.updateCompositePreview();
return;
}
this.previewTrailingTimer = setTimeout(() => {
this.previewTrailingTimer = null;
this.updateCompositePreview();
}, wait);
}
private updateCompositePreview(): void {
if (!this.communicator) return;
// The floor comes first (and stamps even when backgrounded below): with
// it after the background check, per-frame refresh requests from a
// backgrounded app never advance the timestamp and every one of them
// pays the foreground-activity lookup.
const now = Date.now();
if (
this.lastConnectedPreviewUpdateAtMs > 0 &&
now - this.lastConnectedPreviewUpdateAtMs < CONNECTED_PREVIEW_MIN_UPDATE_MS
) {
return;
}
this.lastConnectedPreviewUpdateAtMs = now;
// The connected foreground service intentionally keeps this controller
// alive after the phone UI is backgrounded. Do not keep constructing
// 640x480 Android Bitmaps for a window that cannot display them: besides
@@ -1956,20 +2271,11 @@ class DashboardController {
const activity = Application.android.foregroundActivity;
if (!activity || !activity.hasWindowFocus()) return;
}
const now = Date.now();
if (
this.lastConnectedPreviewUpdateAtMs > 0 &&
now - this.lastConnectedPreviewUpdateAtMs < CONNECTED_PREVIEW_MIN_UPDATE_MS
) {
return;
}
this.lastConnectedPreviewUpdateAtMs = now;
// The recorder captures at the same cadence the phone-side preview is
// refreshed, so the GIF matches what the phone display showed.
if (this.screenRecordingActive) {
if (this.screenRecordingActive && now - this.lastRecordCaptureAtMs >= RECORDING_MIN_CAPTURE_MS) {
this.lastRecordCaptureAtMs = now;
this.communicator.recordScreenFrame();
}
const preview = this.communicator.getCompositePreview();
const preview = this.communicator.getCompositePreview(previewColorSetting.get() === "green");
if (preview) {
this.setDisplayPreview(preview);
}
@@ -1990,10 +2296,37 @@ class DashboardController {
| "scroll-down"
| "long-press"
| "long-press-release"
| "wakeword",
| "wakeword"
| "swipe-left"
| "swipe-right"
| "swipe-up"
| "swipe-down",
origin: SyntheticInputOrigin = "ring",
): RawInputEvent {
const frameId = frameTimings.startFrame(`input:synthetic:${kind}`);
// The phone UI's test buttons stand in for the ring; the watch is its own
// source so the UI can give it a richer scheme (see InputSource).
const eventSource =
origin === "watch" ? EventSourceType.TOUCH_EVENT_FROM_WATCH : EventSourceType.TOUCH_EVENT_FROM_RING;
switch (kind) {
case "swipe-left":
case "swipe-right":
case "swipe-up":
case "swipe-down":
// Watch-only directional input; see WatchGestureType.
return {
kind: "watch-gesture",
containerName: "",
eventType: {
"swipe-left": WatchGestureType.SWIPE_LEFT,
"swipe-right": WatchGestureType.SWIPE_RIGHT,
"swipe-up": WatchGestureType.SWIPE_UP,
"swipe-down": WatchGestureType.SWIPE_DOWN,
}[kind],
eventSource: 0,
systemExitReasonCode: 0,
frameId,
};
case "wakeword":
// Same event the glasses report for the spoken wakeword (sid 0x07).
return {
@@ -2009,7 +2342,7 @@ class DashboardController {
kind: "sys-event",
containerName: "",
eventType: OsEventTypeList.RING_LONG_PRESS_EVENT,
eventSource: EventSourceType.TOUCH_EVENT_FROM_RING,
eventSource,
systemExitReasonCode: 0,
frameId,
};
@@ -2018,7 +2351,7 @@ class DashboardController {
kind: "sys-event",
containerName: "",
eventType: OsEventTypeList.RING_LONG_PRESS_RELEASE_EVENT,
eventSource: EventSourceType.TOUCH_EVENT_FROM_RING,
eventSource,
systemExitReasonCode: 0,
frameId,
};
@@ -2027,7 +2360,7 @@ class DashboardController {
kind: "sys-event",
containerName: "",
eventType: OsEventTypeList.CLICK_EVENT,
eventSource: EventSourceType.TOUCH_EVENT_FROM_RING,
eventSource,
systemExitReasonCode: 0,
frameId,
};
@@ -2036,7 +2369,7 @@ class DashboardController {
kind: "sys-event",
containerName: "",
eventType: OsEventTypeList.DOUBLE_CLICK_EVENT,
eventSource: EventSourceType.TOUCH_EVENT_FROM_RING,
eventSource,
systemExitReasonCode: 0,
frameId,
};
@@ -2045,7 +2378,7 @@ class DashboardController {
kind: "text-click",
containerName: "",
eventType: OsEventTypeList.SCROLL_TOP_EVENT,
eventSource: EventSourceType.TOUCH_EVENT_FROM_RING,
eventSource,
systemExitReasonCode: 0,
frameId,
};
@@ -2055,7 +2388,7 @@ class DashboardController {
kind: "text-click",
containerName: "",
eventType: OsEventTypeList.SCROLL_BOTTOM_EVENT,
eventSource: EventSourceType.TOUCH_EVENT_FROM_RING,
eventSource,
systemExitReasonCode: 0,
frameId,
};
@@ -2067,6 +2400,7 @@ class DashboardController {
for (const listener of this.listeners) {
listener(snapshot);
}
this.wearRemote?.schedulePublish();
}
}
+82 -11
View File
@@ -1,5 +1,9 @@
import { ApplicationSettings } from "@nativescript/core";
import { normalizeMacAddress } from "./even-advertisement";
export { normalizeMacAddress };
export type DeviceAddresses = {
right: string;
left: string;
@@ -32,17 +36,6 @@ export function saveDeviceAddresses(addresses: DeviceAddresses): void {
ApplicationSettings.setString(ADDRESS_KEYS.ring, normalizeMacAddress(addresses.ring));
}
export function normalizeMacAddress(value: string | null | undefined): string {
const compact = (value ?? "")
.trim()
.replace(/[^0-9a-fA-F]/g, "")
.toUpperCase();
if (compact.length !== 12) {
return (value ?? "").trim().toUpperCase();
}
return compact.match(/.{1,2}/g)?.join(":") ?? compact;
}
export function isValidMacAddress(value: string, allowEmpty = false): boolean {
const trimmed = value.trim();
if (!trimmed) {
@@ -50,3 +43,81 @@ export function isValidMacAddress(value: string, allowEmpty = false): boolean {
}
return /^[0-9A-F]{2}(?::[0-9A-F]{2}){5}$/.test(normalizeMacAddress(trimmed));
}
// ---------------------------------------------------------------------------
// Paired-glasses identity
// ---------------------------------------------------------------------------
/**
* What the pairing scan learned about the pair whose addresses were saved, so
* later screens can name and picture the exact glasses without a connection.
* Kept separate from the addresses so hand-entered MACs keep working.
*/
export type PairedGlassesIdentity = {
/** The 14-character serial both arms advertised (pair identity). */
serial: string;
leftName: string;
rightName: string;
leftAddress: string;
rightAddress: string;
/** Ring local name ("EVEN R1_B56EE2"), when a ring was chosen from the scan. */
ringName: string;
ringAddress: string;
pairedAtMs: number;
};
const IDENTITY_KEYS = {
serial: "deviceIdentity.serial",
leftName: "deviceIdentity.leftName",
rightName: "deviceIdentity.rightName",
leftAddress: "deviceIdentity.leftAddress",
rightAddress: "deviceIdentity.rightAddress",
ringName: "deviceIdentity.ringName",
ringAddress: "deviceIdentity.ringAddress",
pairedAtMs: "deviceIdentity.pairedAtMs",
} as const;
export function loadPairedGlassesIdentity(): PairedGlassesIdentity | null {
const serial = ApplicationSettings.getString(IDENTITY_KEYS.serial, "").trim();
if (!serial) return null;
return {
serial,
leftName: ApplicationSettings.getString(IDENTITY_KEYS.leftName, ""),
rightName: ApplicationSettings.getString(IDENTITY_KEYS.rightName, ""),
leftAddress: normalizeMacAddress(ApplicationSettings.getString(IDENTITY_KEYS.leftAddress, "")),
rightAddress: normalizeMacAddress(ApplicationSettings.getString(IDENTITY_KEYS.rightAddress, "")),
ringName: ApplicationSettings.getString(IDENTITY_KEYS.ringName, ""),
ringAddress: normalizeMacAddress(ApplicationSettings.getString(IDENTITY_KEYS.ringAddress, "")),
pairedAtMs: ApplicationSettings.getNumber(IDENTITY_KEYS.pairedAtMs, 0),
};
}
export function savePairedGlassesIdentity(identity: PairedGlassesIdentity): void {
ApplicationSettings.setString(IDENTITY_KEYS.serial, identity.serial.trim().toUpperCase());
ApplicationSettings.setString(IDENTITY_KEYS.leftName, identity.leftName);
ApplicationSettings.setString(IDENTITY_KEYS.rightName, identity.rightName);
ApplicationSettings.setString(IDENTITY_KEYS.leftAddress, normalizeMacAddress(identity.leftAddress));
ApplicationSettings.setString(IDENTITY_KEYS.rightAddress, normalizeMacAddress(identity.rightAddress));
ApplicationSettings.setString(IDENTITY_KEYS.ringName, identity.ringName);
ApplicationSettings.setString(IDENTITY_KEYS.ringAddress, normalizeMacAddress(identity.ringAddress));
ApplicationSettings.setNumber(IDENTITY_KEYS.pairedAtMs, identity.pairedAtMs);
}
export function clearPairedGlassesIdentity(): void {
for (const key of Object.values(IDENTITY_KEYS)) {
ApplicationSettings.remove(key);
}
}
/**
* The saved identity only describes the saved addresses. If the user later
* hand-edits an arm's MAC to something else, the serial no longer applies —
* report null rather than a stale name for a different pair.
*/
export function loadPairedGlassesIdentityForAddresses(addresses: DeviceAddresses): PairedGlassesIdentity | null {
const identity = loadPairedGlassesIdentity();
if (!identity) return null;
if (identity.leftAddress !== normalizeMacAddress(addresses.left)) return null;
if (identity.rightAddress !== normalizeMacAddress(addresses.right)) return null;
return identity;
}
+301
View File
@@ -0,0 +1,301 @@
/**
* Parsers for what Even Realities hardware puts in a BLE advertisement.
*
* ## G2 temple (confirmed by HCI capture)
*
* Manufacturer-specific AD record: `45 52` + SN(14, ASCII) + MAC(6, little-endian) + flag(1).
* The `45 52` ("ER") bytes sit in the company-identifier field, which Android
* parses as little-endian uint16 `0x5245`. Both arms of a pair advertise the
* SAME serial; that is the pair identity. The local name is
* `Even G2_<token>_<L|R>_<hex6>` where the trailing hex is the last three
* bytes of THAT ARM's address — per-arm, NOT a pair id. One arm's name
* predicts nothing about the other's.
*
* ## R1 ring
*
* `45 52` + MAC(6, wire order) and, on ring firmware 2.2.7.x, further bytes
* after the MAC (observed live: the ASCII device-serial suffix, e.g. "140137").
* The local name is `EVEN R1_<hex6>` where the hex is the last three octets
* of the human-order MAC. Anchor on the marker and, when the name carries the
* conventional suffix, require the candidate MAC to reproduce it — a naive
* `suffix(6)` slice once captured serial digits as the ring identity.
*
* This module is pure (no NativeScript imports) so it can run under node tests.
*/
import { bytesToHex, hexToBytes } from "../util/hex-util";
export { bytesToHex, hexToBytes };
/** Even Realities' manufacturer-data company identifier (`"ER"` read little-endian). */
export const EVEN_COMPANY_IDENTIFIER = 0x5245;
export type EvenDeviceRole = "left" | "right" | "ring";
/** True when the manufacturer data opens with Even's `"ER"` marker. */
export function hasEvenManufacturerSignature(mfg: Uint8Array): boolean {
return mfg.length >= 2 && mfg[0] === 0x45 && mfg[1] === 0x52;
}
/**
* Extract the serial number from G2 manufacturer data.
* Layout: "ER"(2) + SN(14) + MAC(6, LE) + flag(1). Null when too short or when
* the 14 bytes are not printable ASCII (control bytes are stripped, as the
* SDK does, but a result that then fails to look like a serial is rejected).
*/
export function extractG2Serial(mfg: Uint8Array): string | null {
if (mfg.length < 16) return null;
let serial = "";
for (let i = 2; i < 16; i++) {
const byte = mfg[i]!;
if (byte <= 0x1f || byte === 0x7f) continue;
if (byte > 0x7e) return null;
serial += String.fromCharCode(byte);
}
return serial.length ? serial : null;
}
/**
* Extract the BLE MAC from G2 manufacturer data.
* Layout: "ER"(2) + SN(14) + MAC(6, little-endian) + flag(1).
* Returns "AA:BB:CC:DD:EE:FF" (big-endian, colon-separated).
*/
export function extractG2Mac(mfg: Uint8Array): string | null {
if (mfg.length < 22) return null;
return humanReadableAddressFromWireBytes(mfg.subarray(16, 22));
}
/** Preserve the final G2 manufacturer-data byte without guessing its meaning. */
export function extractG2AdvertisementFlag(mfg: Uint8Array): number | null {
if (mfg.length < 23 || !hasEvenManufacturerSignature(mfg)) return null;
return mfg[22]!;
}
/**
* Which side a G2 temple advertisement belongs to, from the local name.
* Null when the name carries neither or both markers.
*/
export function g2SideFromName(name: string | null | undefined): "left" | "right" | null {
if (!name) return null;
const upper = name.toUpperCase();
const isLeft = upper.includes("_L_");
const isRight = upper.includes("_R_");
if (isLeft === isRight) return null;
return isLeft ? "left" : "right";
}
/** "Even G2_32_L_ACD458" → "ACD458"; null when the name does not end in 6 hex digits. */
export function g2NameAddressTail(name: string | null | undefined): string | null {
if (!name) return null;
const match = /_([0-9A-F]{6})\s*$/i.exec(name);
return match ? match[1]!.toUpperCase() : null;
}
/**
* Even's wire order is reversed human order: "AA:BB:CC:DD:EE:FF" ⇄ [FF EE DD CC BB AA].
*/
export function wireBytesFromHumanReadableAddress(address: string): Uint8Array | null {
const cleaned = address.replace(/[:\-]/g, "").trim();
if (cleaned.length !== 12 || !/^[0-9a-fA-F]{12}$/.test(cleaned)) return null;
const human = hexToBytes(cleaned);
return new Uint8Array(Array.from(human).reverse());
}
export function humanReadableAddressFromWireBytes(bytes: Uint8Array): string | null {
if (bytes.length !== 6) return null;
return Array.from(bytes)
.reverse()
.map((b) => b.toString(16).padStart(2, "0").toUpperCase())
.join(":");
}
/**
* The conventional R1 local name ("EVEN R1_B56EE2") ends in the human-order
* MAC's last three octets. Returns those octets when the name carries a
* parseable 6-hex-digit suffix. A bare ring id ("B56EE2") is accepted too.
*/
export function ringNameAddressOctets(name: string | null | undefined): number[] | null {
if (!name) return null;
const marker = name.indexOf("R1_");
const suffix = (marker >= 0 ? name.slice(marker + 3) : name).trim();
if (suffix.length !== 6 || !/^[0-9a-fA-F]{6}$/.test(suffix)) return null;
return [0, 2, 4].map((i) => parseInt(suffix.slice(i, i + 2), 16));
}
/**
* A wire-order candidate is reversed(human), so its bytes [2],[1],[0] must
* equal the name suffix octets in order for the candidate to belong to the
* named ring.
*/
export function wireBytesMatchNameOctets(wire: ArrayLike<number>, nameOctets: number[]): boolean {
return wire.length === 6 && nameOctets.length === 3 && wire[2] === nameOctets[0] && wire[1] === nameOctets[1] && wire[0] === nameOctets[2];
}
/**
* Extract the ring's wire-order MAC from its manufacturer data, validated
* against the advertised name when the name is verifiable. Fails closed
* (null) when the name is verifiable and no 6-byte window reproduces it.
*/
export function ringMacWireBytes(mfg: Uint8Array, localName: string | null | undefined): Uint8Array | null {
if (mfg.length < 6) return null;
const markerAnchored = mfg.length >= 8 && hasEvenManufacturerSignature(mfg) ? mfg.subarray(2, 8) : null;
const nameOctets = ringNameAddressOctets(localName);
if (!nameOctets) {
// No verifiable name: prefer the documented marker layout, else legacy suffix.
return new Uint8Array(markerAnchored ?? mfg.subarray(mfg.length - 6));
}
if (markerAnchored && wireBytesMatchNameOctets(markerAnchored, nameOctets)) {
return new Uint8Array(markerAnchored);
}
for (let start = 0; start + 6 <= mfg.length; start++) {
const window = mfg.subarray(start, start + 6);
if (wireBytesMatchNameOctets(window, nameOctets)) return new Uint8Array(window);
}
return null;
}
/**
* Ring firmware 2.2.7.x appends the ASCII serial suffix after the MAC. Return
* it when present (digits/uppercase letters only) so the row can show it.
*/
export function extractRingSerialSuffix(mfg: Uint8Array): string | null {
if (!hasEvenManufacturerSignature(mfg) || mfg.length <= 8) return null;
let text = "";
for (let i = 8; i < mfg.length; i++) {
const byte = mfg[i]!;
if (byte < 0x30 || byte > 0x5a) return null;
text += String.fromCharCode(byte);
}
return text.length ? text : null;
}
// ---------------------------------------------------------------------------
// Classification of a raw advertisement
// ---------------------------------------------------------------------------
/** What the Java scanner hands up: one advertisement (or one bonded device). */
export type RawAdvertisement = {
address: string;
/** Live local name from the scan record, falling back to the cached device name. */
name: string;
/** Full manufacturer-specific data including the 2-byte company id, as hex. Empty when absent. */
manufacturerData: string;
rssi: number | null;
txPower: number | null;
connectable: boolean | null;
bonded: boolean;
source: "scan" | "paired";
seenAtMs: number;
};
/** One advertisement after the protocol knowledge has been applied. */
export type EvenAdvertisement = {
address: string;
name: string;
role: EvenDeviceRole;
/** G2: the 14-char pair serial. Ring: null (the ring's serial suffix is `ringSerialSuffix`). */
serial: string | null;
/** The address embedded in the manufacturer data, when present. Should equal `address`. */
embeddedMac: string | null;
/** True when the embedded MAC disagrees with the address the radio reported. */
embeddedMacMismatch: boolean;
flag: number | null;
ringSerialSuffix: string | null;
rssi: number | null;
txPower: number | null;
connectable: boolean | null;
bonded: boolean;
source: "scan" | "paired";
seenAtMs: number;
manufacturerData: string;
/** Why an otherwise Even-looking advertisement could not be fully parsed. */
note: string | null;
};
/**
* Classify a raw advertisement. Returns null for anything that is not an Even
* Realities G2 temple or R1 ring. Admission mirrors the SDK: stock names
* contain "G2"/"R1", but renamed firmware may not, so the "ER" manufacturer
* signature is an equally strong admission path. The ring check is anchored to
* the stock "EVEN R1…" prefix — a bare `R1` substring also matches unrelated
* hardware ("Oppo Enco R1"), and every ring row is selectable, so a loose
* match here saves a stranger's earbuds as the ring. Keep this in sync with
* the Java pre-filter (FaceclawDeviceDiscovery.isAdmissible), which must stay
* a superset of it.
*/
export function classifyAdvertisement(raw: RawAdvertisement): EvenAdvertisement | null {
const mfg = hexToBytes(raw.manufacturerData);
const name = raw.name ?? "";
const upper = name.toUpperCase();
const hasSignature = hasEvenManufacturerSignature(mfg);
const looksLikeRing = /^EVEN R1([_ ]|$)/.test(upper);
const looksLikeG2 = upper.includes("G2");
if (!looksLikeRing && !looksLikeG2 && !hasSignature) return null;
const base = {
address: normalizeMacAddress(raw.address),
name,
rssi: raw.rssi,
txPower: raw.txPower,
connectable: raw.connectable,
bonded: raw.bonded,
source: raw.source,
seenAtMs: raw.seenAtMs,
manufacturerData: raw.manufacturerData ?? "",
};
if (looksLikeRing) {
const wire = mfg.length >= 6 ? ringMacWireBytes(mfg, name) : null;
const embeddedMac = wire ? humanReadableAddressFromWireBytes(wire) : null;
return {
...base,
role: "ring",
serial: null,
embeddedMac,
embeddedMacMismatch: !!embeddedMac && embeddedMac !== base.address,
flag: null,
ringSerialSuffix: extractRingSerialSuffix(mfg),
note: mfg.length >= 6 && !wire ? "advertisement carried no name-consistent MAC window" : null,
};
}
const side = g2SideFromName(name);
if (!side) {
// A G2-signature advertisement with no side marker cannot be placed in a pair.
return null;
}
const serial = mfg.length >= 16 ? extractG2Serial(mfg) : null;
const embeddedMac = extractG2Mac(mfg);
let note: string | null = null;
if (mfg.length === 0) note = "no manufacturer data (serial unknown)";
else if (mfg.length < 16) note = `manufacturer data too short (${mfg.length} bytes); cannot extract a serial`;
else if (!serial) note = "could not extract a serial from the manufacturer data";
return {
...base,
role: side,
serial,
embeddedMac,
embeddedMacMismatch: !!embeddedMac && embeddedMac !== base.address,
flag: extractG2AdvertisementFlag(mfg),
ringSerialSuffix: null,
note,
};
}
/**
* Canonical MAC form: uppercase, colon-separated. Anything that does not
* contain exactly 12 hex digits is passed through trimmed and uppercased so
* an obviously-wrong value stays visible instead of being silently mangled.
* The single normalizer for every address comparison in the app — the stored
* side (device-addresses.ts re-exports this) and the scanned side must agree
* byte for byte or "is this the previously-paired device" checks break.
*/
export function normalizeMacAddress(value: string | null | undefined): string {
const compact = (value ?? "")
.trim()
.replace(/[^0-9a-fA-F]/g, "")
.toUpperCase();
if (compact.length !== 12) return (value ?? "").trim().toUpperCase();
return compact.match(/.{2}/g)!.join(":");
}
+25
View File
@@ -3,6 +3,12 @@ export const EventSourceType = {
TOUCH_EVENT_FROM_GLASSES_R: 1,
TOUCH_EVENT_FROM_RING: 2,
TOUCH_EVENT_FROM_GLASSES_L: 3,
/**
* Synthetic: the Wear OS remote (app/g2/wear-remote.ts). Not a firmware
* value. Lets the UI give watch input its own, richer scheme (direct
* spatial selection) while ring input keeps the stock one.
*/
TOUCH_EVENT_FROM_WATCH: 4,
} as const;
export const EventSourceTypeName: Record<number, string> = {
@@ -10,6 +16,7 @@ export const EventSourceTypeName: Record<number, string> = {
1: "TOUCH_EVENT_FROM_GLASSES_R",
2: "TOUCH_EVENT_FROM_RING",
3: "TOUCH_EVENT_FROM_GLASSES_L",
4: "TOUCH_EVENT_FROM_WATCH",
};
/**
@@ -32,6 +39,24 @@ export const EvenAIStatusName: Record<number, string> = {
3: "EVEN_AI_EXIT",
};
/**
* Synthetic gestures from the Wear OS remote (RawInputEvent kind
* "watch-gesture"). Not a firmware enum: the glasses never send these.
*/
export const WatchGestureType = {
SWIPE_LEFT: 0,
SWIPE_RIGHT: 1,
SWIPE_UP: 2,
SWIPE_DOWN: 3,
} as const;
export const WatchGestureTypeName: Record<number, string> = {
0: "SWIPE_LEFT",
1: "SWIPE_RIGHT",
2: "SWIPE_UP",
3: "SWIPE_DOWN",
};
export const OsEventTypeList = {
CLICK_EVENT: 0,
SCROLL_TOP_EVENT: 1,
+5 -15
View File
@@ -19,6 +19,7 @@ import {
isEvenHubFontAsset,
} from "./firmware-fonts";
import { fetchWithUserAgent } from "../util/http";
import { bytesToHex, hexToBytes as hexToBytesLenient } from "../util/hex-util";
declare const com: any;
@@ -237,23 +238,12 @@ function applyPatches(
return buf;
}
/** Patch-op hex is data, not user input: reject malformed strings instead of the shared decoder's silent stripping. */
function hexToBytes(hex: string): Uint8Array {
if (hex.length % 2 !== 0) {
throw new FirmwareBuildError(`odd-length hex string: ${hex}`);
if (hex.length % 2 !== 0 || /[^0-9a-fA-F]/.test(hex)) {
throw new FirmwareBuildError(`invalid hex string: ${hex}`);
}
const out = new Uint8Array(hex.length / 2);
for (let i = 0; i < out.length; i++) {
out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
}
return out;
}
function bytesToHex(bytes: Uint8Array): string {
let hex = "";
for (let i = 0; i < bytes.length; i++) {
hex += bytes[i].toString(16).padStart(2, "0");
}
return hex;
return hexToBytesLenient(hex);
}
function bytesEqual(a: Uint8Array, b: Uint8Array): boolean {
+11
View File
@@ -78,6 +78,17 @@ export function hasCustomFirmware(info: FirmwareInfo): boolean {
return REQUIRED_FIRMWARE_EXTENSIONS.every((extension) => tokens.includes(extension));
}
/**
* True when the firmware advertises the optional mic-control extension: the
* private field-103/104 channel for per-temple multi-microphone capture that
* the Microphones app's 4-mic array mode and beamforming need. Absent on the
* stock single-mono-stream path, which still works (firmware-computed
* direction of arrival, one mixed channel).
*/
export function hasMicControl(info: FirmwareInfo): boolean {
return info.capabilities.trim().split(/\s+/).includes("micctl");
}
/** The higher of the two arms' reported versions, or "" if none reported. */
export function reportedFirmwareVersion(info: FirmwareInfo): string {
const versions = [info.leftVersion, info.rightVersion].map((v) => v.trim()).filter(Boolean);
+21 -21
View File
@@ -19,7 +19,7 @@ export type FirmwarePatchSet = {
export const CFW_PATCH_SET: FirmwarePatchSet = {
"base": "g2_2.2.6.10.bin",
"baseSha256": "f4dfb0b49ad3de3c2daf17f8a27a157c3dc98411d6a0d3ab2cfd0918f41b9afa",
"outputSha256": "82726bbe4d1d82f06a3d345ba3e5a4a39161077e5d26dcd7af24c4677df87fd1",
"outputSha256": "d4054ab1519c7184fcc4450104de18f9ff714180c80b3a579f91106536a274cd",
"patches": [
{
"offset": 1089903,
@@ -48,61 +48,61 @@ export const CFW_PATCH_SET: FirmwarePatchSet = {
{
"offset": 1447919,
"old": "7ef7fefd",
"new": "bcf24cfa",
"new": "bcf23afb",
"desc": "bl snapshot_side @ 0x4db968"
},
{
"offset": 1448931,
"old": "7ef704fc",
"new": "bcf252f8",
"new": "bcf240f9",
"desc": "bl snapshot_side @ 0x4dbd5c"
},
{
"offset": 1165461,
"old": "45f0cefd",
"new": "01f3fdf9",
"new": "01f3ebfa",
"desc": "bl image_deferred (deferred consumer -> FIFO restore + worker, both lenses)"
},
{
"offset": 1186287,
"old": "d9f7d4ff",
"new": "fdf258f8",
"new": "fdf21afa",
"desc": "bl settings_send_wrapper (append caps field 100)"
},
{
"offset": 1183983,
"old": "f4f75aff",
"new": "fdf21afa",
"new": "fdf2bafb",
"desc": "bl settings_decode_wrapper (Faceclaw lease field 101)"
},
{
"offset": 926945,
"old": "08f068fa",
"new": "3bf33dff",
"new": "3cf3ddf8",
"desc": "bl faceclaw_display_start @ 0x45c65a (fail-open double-tap takeover)"
},
{
"offset": 927137,
"old": "08f008fa",
"new": "3bf3ddfe",
"new": "3cf37df8",
"desc": "bl faceclaw_display_start @ 0x45c71a (fail-open double-tap takeover)"
},
{
"offset": 822553,
"old": "28f003f8",
"new": "55f34dff",
"new": "56f3e5fd",
"desc": "bl evenhub_longpress (Faceclaw lease gates custom event vs stock dialog)"
},
{
"offset": 823369,
"old": "1cf09bfb",
"new": "55f3dbfd",
"desc": "bl ring_release (forward ring release-long-press)"
"new": "56f371fc",
"desc": "bl ring_release (forward source-qualified release-long-press)"
},
{
"offset": 1474137,
"old": "7fb50600",
"new": "b6f211be",
"new": "b6f2d3bf",
"desc": "even_ai_display_ctrl entry -> conditional Faceclaw lease trampoline"
},
{
@@ -120,13 +120,13 @@ export const CFW_PATCH_SET: FirmwarePatchSet = {
{
"offset": 1198787,
"old": "dff770fb",
"new": "f9f28cfb",
"new": "f9f2f4fc",
"desc": "bl faceclaw_send_wear_event @ 0x49ec3c (outside onboarding)"
},
{
"offset": 1198881,
"old": "dff741fb",
"new": "f9f25dfb",
"new": "f9f2c5fc",
"desc": "bl faceclaw_send_wear_event @ 0x49ec9a (outside onboarding)"
},
{
@@ -138,43 +138,43 @@ export const CFW_PATCH_SET: FirmwarePatchSet = {
{
"offset": 4301227,
"old": "",
"new": "02fb01f000e000bfb0b546f27424c2f22a040146206846f23f52c5f28802b2eb500f40f2543044f281124cf67e25c2f20000c0f24802caf2101518bf25609047002804bf691c2160b0bd00bf0846ffe7014640f2543044f29f22c2f20000c0f24802104770b500284ed001684ef66762ccf2ff02914218bf70bd90f8081190f8095142f6c52c8d42c0f2500c2ad205eb8501014491f80d2191f80e4191f80ae191f80b3191f80c1142ea0424012c4ff0010298bf14466e1c054680f80961b9b164294eea032028bf6421012888bf024644f62060824228bf02460cf5e2731046984706e0002180f80811bde870406047e047d5f8040138b149f29942c0f244022146bde87040104770bd00bf70b54ff6fd03c0f2450314460d46984746f27021c2f22a010e6831466ff39601b1f1005f0ad131684ef66762ccf2ff02914218bf0026412d03d070bd0026412dfbd1002cf9d04af26951c0f2450105468847002e01462846efd00129edd196f807120029e9d02168002948bf70bd47f25d02c0f2580208469047284670bd00bf2de9f04f9db046f2702ac2f22a0adaf800b058466ff39600b0f1005f40f07d81dbf800004ef66767ccf2ff07b84240f074819bf82802002800f05d81dbf82442002c00f0588140f2b870c2f20000d0f8008004a802f08effb8f1000f00f0dd81032045f24075cff68070a4f1600108f160026ff0bf03c0f2020500bf0e6ed41826664e6ec03366668e6eab42a666ce6ee6660e6f26674e6f66678e6fa667ce6fe667d1f88060c4f88060d1f88460c4f88460d1f88860c4f88860d1f88c60c4f88c60d1f89060c4f89060d1f89460c4f89460d1f89860c4f89860d1f89c60c4f89c60d1f8a060c4f8a060d1f8a460c4f8a460d1f8a860c4f8a860d1f8ac60c4f8ac60d1f8b060c4f8b060d1f8b460c4f8b460d1f8b860c4f8b860d1f8bc60c4f8bc6051f8c06fc4f8c0604e68c4f8c4608e68c4f8c860ce68c4f8cc600e69c4f8d0604e69c4f8d4608e69c4f8d860ce69c4f8dc600e6ac4f8e0604e6ac4f8e4608e6ac4f8e860ce6ac4f8ec600e6bc4f8f0604e6bc4f8f4608e6bc4f8f860ce6bc4f8fc600e6cc4f800614e6cc4f804618e6cc4f80861ce6cc4f80c610e6dc4f810614e6dc4f814618e6dc4f81861ce6dc4f81c617ff462afdaf800603040b0f1005f40f0b2803068b84240f0ae8096f8ce00002840f0348196f8dc10002000298df8140000f0ac8105a90a5c002a00f07f810a185378002b00f03d819378002b00f03b81d378002b00f039811379002b00f037815379002b00f035819379002b00f03381d379002b00f03181137a002b00f02f81537a002b00f02d81937a002b00f02b81d37a002b00f02981137b002b00f02781537b002b00f02581937b002b00f02381d37b002b00f02181137c002b00f01f81537c002b00f01d81937c002b00f01b81d37c002b00f01981137d002b00f01781537d002b00f01581937d002b00f01381d37d002b00f01181137e002b00f00f81537e002b00f00d81937e002b00f00b81d37e002b00f00981137f002b00f00781537f002b00f00581937f002b00f00381d27f002a00f00181203060287ff47baf20e19bf82a0270b1dbf82c0240b144f63421c2f207010968401a002800f3ae8000208bf82a024cf61520c0f246001db0bde8f04f004704f005fb002800f0838000216ff017020023c518c1542f338618b3f50d7f02f12f026970a970e97029716971a971e97129726972a972e97229736973a973e97329746974a974e97429756975a97586f82f1086f830106976a976e97629776977a977e97785f8201085f8211085f8221085f8231085f8241085f8251085f8261085f8271085f8281085f8291085f82a1085f82b1085f82c1085f82d1085f82e10b7d1012180f8ce104ff0ff310760a0f8e010a0f8e210a0f8e410a0f8e610a0f8e810a0f8ea10a0f8ec10a0f8ee10a0f8f010a0f8f210a0f8f410a0f8f610a0f8f810a0f8fa10a0f8fc10a0f8fe1010e000208bf82802cbf824028bf82a0201208bf829024cf61520c0f24600804715e00020caf8000000208bf82802cbf824024ff4163045f20f11069005a8c0f24701cdf81480884701208bf82a0204a802f06efecbf8d4001db0bde8f08f01303ae0023038e0033036e0043034e0053032e0063030e007302ee008302ce009302ae00a3028e00b3026e00c3024e00d3022e00e3020e00f301ee010301ce011301ae0123018e0133016e0143014e0153012e0163010e017300ee018300ce019300ae01a3008e01b3006e01c3004e01d3002e01e3000e01f305f2821d84ff052020a541dd0014445225e284a7018d04f225d288a7014d052225c28ca7010d044225b280a710cd045225a284a7108d0522259288a7104d020225828ca7142f0168500208df87300012096f8dd10002900f0c280002105aa535c002b00f0a08057187b78002b5ed0bb78002b5dd0fb78002b5cd03b79002b5bd07b79002b5ad0bb79002b59d0fb79002b58d03b7a002b57d07b7a002b56d0bb7a002b55d0fb7a002b54d03b7b002b53d07b7b002b52d0bb7b002b51d0fb7b002b50d03b7c002b4fd07b7c002b4ed0bb7c002b4dd0fb7c002b4cd03b7d002b4bd07b7d002b4ad0bb7d002b49d0fb7d002b48d03b7e002b47d07b7e002b46d0bb7e002b45d0fb7e002b44d03b7f002b43d07b7f002b42d0bb7f002b41d0fb7f002b40d0203160297ff49aaf54e001313ae0023138e0033136e0043134e0053132e0063130e007312ee008312ce009312ae00a3128e00b3126e00c3124e00d3122e00e3120e00f311ee010311ce011311ae0123118e0133116e0143114e0153112e0163110e017310ee018310ce019310ae01a3108e01b3106e01c3104e01d3102e01e3100e01f315f2915d84ff05303535411d00a444b235e2953700cd049235d29937008d050235c29d37004d020235b29137140f0c28200218df87310013096f8de10002900f0be80002105aa535c002b00f0a08057187b78002b5ed0bb78002b5dd0fb78002b5cd03b79002b5bd07b79002b5ad0bb79002b59d0fb79002b58d03b7a002b57d07b7a002b56d0bb7a002b55d0fb7a002b54d03b7b002b53d07b7b002b52d0bb7b002b51d0fb7b002b50d03b7c002b4fd07b7c002b4ed0bb7c002b4dd0fb7c002b4cd03b7d002b4bd07b7d002b4ad0bb7d002b49d0fb7d002b48d03b7e002b47d07b7e002b46d0bb7e002b45d0fb7e002b44d03b7f002b43d07b7f002b42d0bb7f002b41d0fb7f002b40d0203160297ff49aaf50e001313ae0023138e0033136e0043134e0053132e0063130e007312ee008312ce009312ae00a3128e00b3126e00c3124e00d3122e00e3120e00f311ee010311ce011311ae0123118e0133116e0143114e0153112e0163110e017310ee018310ce019310ae01a3108e01b3106e01c3104e01d3102e01e3100e01f315f2911d84ff0440353540dd00Line truncated
"new": "02fb01f000e000bfb0b546f27424c2f22a040146206846f23f52c5f28802b2eb500f40f2543044f281124cf67e25c2f20000c0f24802caf2101518bf25609047002804bf691c2160b0bd00bf0846ffe7014640f2543044f29f22c2f20000c0f24802104770b500284ed001684ef66862ccf2ff02914218bf70bd90f8081190f8095142f6c52c8d42c0f2500c2ad205eb8501014491f80d2191f80e4191f80ae191f80b3191f80c1142ea0424012c4ff0010298bf14466e1c054680f80961b9b164294eea032028bf6421012888bf024644f62060824228bf02460cf5e2731046984706e0002180f80811bde870406047e047d5f8040138b149f29942c0f244022146bde87040104770bd00bf70b54ff6fd03c0f2450314460d46984746f27021c2f22a010e6831466ff39601b1f1005f0ad131684ef66862ccf2ff02914218bf0026412d03d070bd0026412dfbd1002cf9d04af26951c0f2450105468847002e01462846efd00129edd196f807120029e9d02168002948bf70bd47f25d02c0f2580208469047284670bd00bf2de9f04f9db046f2702ac2f22a0adaf800b058466ff39600b0f1005f40f07d81dbf800004ef66867ccf2ff07b84240f074819bf82802002800f05d81dbf82442002c00f0588140f2b870c2f20000d0f8008004a802f0caffb8f1000f00f01982032045f24075cff68070a4f1600108f160026ff0bf03c0f2020500bf0e6ed41826664e6ec03366668e6eab42a666ce6ee6660e6f26674e6f66678e6fa667ce6fe667d1f88060c4f88060d1f88460c4f88460d1f88860c4f88860d1f88c60c4f88c60d1f89060c4f89060d1f89460c4f89460d1f89860c4f89860d1f89c60c4f89c60d1f8a060c4f8a060d1f8a460c4f8a460d1f8a860c4f8a860d1f8ac60c4f8ac60d1f8b060c4f8b060d1f8b460c4f8b460d1f8b860c4f8b860d1f8bc60c4f8bc6051f8c06fc4f8c0604e68c4f8c4608e68c4f8c860ce68c4f8cc600e69c4f8d0604e69c4f8d4608e69c4f8d860ce69c4f8dc600e6ac4f8e0604e6ac4f8e4608e6ac4f8e860ce6ac4f8ec600e6bc4f8f0604e6bc4f8f4608e6bc4f8f860ce6bc4f8fc600e6cc4f800614e6cc4f804618e6cc4f80861ce6cc4f80c610e6dc4f810614e6dc4f814618e6dc4f81861ce6dc4f81c617ff462afdaf800603040b0f1005f40f0b2803068b84240f0ae8096f8ce00002840f0708196f8dc10002000298df8140000f0e88105a90a5c002a00f0bb810a185378002b00f079819378002b00f07781d378002b00f075811379002b00f073815379002b00f071819379002b00f06f81d379002b00f06d81137a002b00f06b81537a002b00f06981937a002b00f06781d37a002b00f06581137b002b00f06381537b002b00f06181937b002b00f05f81d37b002b00f05d81137c002b00f05b81537c002b00f05981937c002b00f05781d37c002b00f05581137d002b00f05381537d002b00f05181937d002b00f04f81d37d002b00f04d81137e002b00f04b81537e002b00f04981937e002b00f04781d37e002b00f04581137f002b00f04381537f002b00f04181937f002b00f03f81d27f002a00f03d81203060287ff47baf5ce19bf82a0270b1dbf82c0240b144f63421c2f207010968401a002800f3ea8000208bf82a024cf61520c0f246001db0bde8f04f00474ff41b7004f063fe002800f0bd804ff69451cff6ff71002200bf43183e3183f86c2283f86d2283f86e2283f86f2283f8702283f8712283f8722283f8732283f8742283f8752283f8762283f8772283f8782283f8792283f87a2283f87b2283f87c2283f87d2283f87e2283f87f2283f8802283f8812283f8822283f8832283f8842283f8852283f8862283f8872283f8882283f8892283f88a2283f88b2283f88c2283f88d2283f88e2283f88f2283f8902283f8912283f8922283f8932283f8942283f8952283f8962283f8972283f8982283f8992283f89a2283f89b2283f89c2283f89d2283f89e2283f89f2283f8a02283f8a12283f8a22283f8a32283f8a42283f8a52283f8a62283f8a72283f8a82283f8a9227ff480af012180f8ce104ff0ff310760a0f8e010a0f8e210a0f8e410a0f8e610a0f8e810a0f8ea10a0f8ec10a0f8ee10a0f8f010a0f8f210a0f8f410a0f8f610a0f8f810a0f8fa10a0f8fc10a0f8fe1010e000208bf82802cbf824028bf82a0201208bf829024cf61520c0f24600804715e00020caf8000000208bf82802cbf824024ff4163045f20f11069005a8c0f24701cdf81480884701208bf82a0204a802f0aafecbf8d4001db0bde8f08f01303ae0023038e0033036e0043034e0053032e0063030e007302ee008302ce009302ae00a3028e00b3026e00c3024e00d3022e00e3020e00f301ee010301ce011301ae0123018e0133016e0143014e0153012e0163010e017300ee018300ce019300ae01a3008e01b3006e01c3004e01d3002e01e3000e01f305f2821d84ff052020a541dd0014445225e284a7018d04f225d288a7014d052225c28ca7010d044225b280a710cd045225a284a7108d0522259288a7104d020225828ca7142f0168500208df87300012096f8dd10002900f0c280002105aa535c002b00f0a08057187b78002b5ed0bb78002b5dd0fb78002b5cd03b79002b5bd07b79002b5ad0bb79002b59d0fb79002b58d03b7a002b57d07b7a002b56d0bb7a002b55d0fb7a002b54d03b7b002b53d07b7b002b52d0bb7b002b51d0fb7b002b50d03b7c002b4fd07b7c002b4ed0bb7c002b4dd0fb7c002b4cd03b7d002b4bd07b7d002b4ad0bb7d002b49d0fb7d002b48d03b7e002b47d07b7e002b46d0bb7e002b45d0fb7e002b44d03b7f002b43d07b7f002b42d0bb7f002b41d0fb7f002b40d0203160297ff49aaf54e001313ae0023138e0033136e0043134e0053132e0063130e007312ee008312ce009312ae00a3128e00b3126e00c3124e00d3122e00e3120e00f311ee010311ce011311ae0123118e0133116e0143114e0153112e0163110e017310ee018310ce019310ae01a3108e01b3106e01c3104e01d3102e01e3100e01f315f2915d84ff05303535411d00a444b235e2953700cd049235d29937008d050235c29d37004d020235b29137140f0c28200218df87310013096f8de10002900f0be80002105aa535c002b00f0a08057187b78002b5ed0bb78002b5dd0fb78002b5cd03b79002b5bd07b79002b5ad0bb79002b59d0fb79002b58d03b7a002b57d07b7a002b56d0bb7a002b55d0fb7a002b54d03b7b002b53d07b7b002b52d0bb7b002b51d0fb7b002b50d03b7c002b4fd07b7c002b4ed0bb7c002b4dd0fb7c002b4cd03b7d002b4bd07b7d002b4ad0bb7d002b49d0fb7d002b48d03b7e002b47d07b7e002b46d0bb7e002b45d0fb7e002b44d03b7f002b43d07b7f002b42d0bb7f002b41d0fb7f002b40d0203160297ff49aaf50e001313ae0023138e0033136e004313Line truncated
"desc": "append injected blobs to main-app payload"
},
{
"offset": 777711,
"old": "44c33500",
"new": "604b3600",
"new": "4a5c3600",
"desc": "main-app subheader payload size (ps)"
},
{
"offset": 152,
"old": "c4c33500",
"new": "e04b3600",
"new": "ca5c3600",
"desc": "main-app TOC entry size (ps + 128)"
},
{
"offset": 777831,
"old": "44c33504",
"new": "604b3604",
"new": "4a5c3604",
"desc": "main-app preamble length (low 24 bits)"
},
{
"offset": 777835,
"old": "df8110c9",
"new": "562ec508",
"new": "0aa0bcf3",
"desc": "[5] ota/s200_firmware_ota.bin preamble crc32"
},
{
"offset": 156,
"old": "c1be0fb1",
"new": "ef84d21c",
"new": "01fcf86d",
"desc": "[5] ota/s200_firmware_ota.bin component crc32c (TOC)"
},
{
"offset": 777715,
"old": "c1be0fb1",
"new": "ef84d21c",
"new": "01fcf86d",
"desc": "[5] ota/s200_firmware_ota.bin component crc32c (subheader)"
}
]
+41
View File
@@ -0,0 +1,41 @@
/**
* Product artwork for Even Realities hardware, keyed by the decoded serial.
*
* Prefer the photo of the exact SKU the serial decoded to, and fall back to
* the generic product shot. Every surface that draws "the user's glasses"
* should route through this — once the pair is known, showing brown Frame B
* for a grey Frame A pair is a small lie the wearer will notice immediately.
*
* The PNGs live under `app/images/glasses/` (six SKU crops at 600×196 on a
* shared bounding box so they render at the same scale, plus the generic G2
* and R1 product shots). NativeScript
* resolves `~/` to the app folder for `<Image src>`.
*
* This module is pure (no NativeScript imports) so it can run under node tests.
*/
import { BUNDLED_VARIANT_ASSET_NAMES, type GlassesHardwareIdentity } from "./glasses-hardware-identity";
export const GLASSES_IMAGE_DIR = "~/images/glasses";
/** Generic Even G2 product shot, used before the serial is known or for SKUs without art. */
export const GENERIC_G2_IMAGE_PATH = `${GLASSES_IMAGE_DIR}/even_realities_g2.png`;
/** Even R1 ring product shot. */
export const R1_IMAGE_PATH = `${GLASSES_IMAGE_DIR}/even_realities_r1.png`;
/** The SKU-specific photo, or null when none is bundled for this identity. */
export function variantImagePath(identity: GlassesHardwareIdentity | null | undefined): string | null {
const name = identity?.imageAssetName;
return name ? `${GLASSES_IMAGE_DIR}/${name}.png` : null;
}
/** The best available photo for these glasses: the SKU's own, else the generic shot. */
export function glassesImagePath(identity: GlassesHardwareIdentity | null | undefined): string {
return variantImagePath(identity) ?? GENERIC_G2_IMAGE_PATH;
}
/** Relative file names (under `app/images/glasses/`) that must exist for the resolver's claims to hold. */
export function requiredArtworkFileNames(): string[] {
return [...Array.from(BUNDLED_VARIANT_ASSET_NAMES).map((name) => `${name}.png`), "even_realities_g2.png", "even_realities_r1.png"].sort();
}
+34
View File
@@ -0,0 +1,34 @@
export type GlassesDisplayState = {
phase: string;
silentMode: boolean;
screenOn: boolean;
battery: number | null;
foregroundTitle: string | null;
};
/** Compact status shown where the foreground-window title normally lives. */
export function glassesDisplayLabel(state: GlassesDisplayState): string {
// Charging wins over every session-local state: the glasses are in their
// case, so neither the lock screen nor the foreground window is visible.
if (state.phase === "charging") {
return chargingDisplayLabel(state.battery);
}
if (state.phase !== "connected") {
return "Glasses disconnected";
}
if (state.silentMode) {
return "Silent mode";
}
if (!state.screenOn) {
return "Display off";
}
return state.foregroundTitle || "Launcher";
}
export function chargingDisplayLabel(battery: number | null): string {
return validBatteryLevel(battery) ? `Charging · G2 ${battery}%` : "Charging";
}
function validBatteryLevel(battery: number | null): battery is number {
return battery !== null && Number.isInteger(battery) && battery >= 0 && battery <= 100;
}
+331
View File
@@ -0,0 +1,331 @@
/**
* Decodes an Even Realities serial number into the product family, frame shape,
* and colourway the wearer can actually see.
*
* ## Why this exists
*
* A G2 arm advertises its 14-character serial inside the manufacturer data
* (`"ER"` + SN(14) + MAC(6) + flag(1), see `even-advertisement.ts`). Two people
* in the same room with glasses in pairing mode therefore produce two rows of
* near-identical alphanumerics, and the only way to tell which one you are
* holding is to guess. The serial already encodes the answer — the shape of
* the frame and its colour — so decoding it turns "S211GBBC180304" into
* "Even G2 B · Brown", which the wearer can check against the thing in their
* hand without connecting to a stranger's hardware first.
*
* ## Where the mapping comes from
*
* Recovered from the Even Realities app 2.2.0
* (`even/common/utils/device_image_resolver` `_parseGlassesSku`, and
* `even/common/extension/ble/ble_mtach_device_ext` `evenSNName` / `matchModel`).
* That app does exactly this decode to pick its product artwork:
*
* | Serial slice | Meaning |
* | --- | --- |
* | `[0..<2]` | Product family — `S1` = G1 glasses, `S2` = G2 glasses, `B2` = R1 ring |
* | `[0..<3]` | Frame shape — `S20`/`S28` → A, `S21`/`S29` → B, `S22` → C (G1: `S11` → B, else A) |
* | `[0..<4]` | Model code (`S211`, `S110`, `B210`, `B290`) |
* | `[5]` | Colourway — `A` grey, `B` brown, `C` green |
*
* Two deliberate departures from the Even app: it silently defaults an
* unrecognised prefix to frame A and an unrecognised colour byte to grey. For
* identification that is the wrong trade — mislabelling a future SKU as
* "Frame A · Grey" is worse than saying nothing — so unknown values decode to
* `null` here and the UI falls back to the serial.
*
* This module is pure (no NativeScript imports) so it can run under node tests.
*/
export type GlassesFamily = "g1" | "g2" | "r1";
/** Frame shape. Even ships these as bare letters — frame A is round, B is square. */
export type GlassesFrame = "a" | "b" | "c";
/** Frame finish. The three colourways Even sells across G1 and G2. */
export type GlassesColorway = "grey" | "brown" | "green";
const FAMILY_PRODUCT_NAME: Record<GlassesFamily, string> = {
g1: "Even G1",
g2: "Even G2",
r1: "Even R1",
};
const COLORWAY_DISPLAY_NAME: Record<GlassesColorway, string> = {
grey: "Grey",
brown: "Brown",
green: "Green",
};
/**
* sRGB hex for the swatch shown beside a scan row. Approximations of the
* shipping finishes, chosen to stay distinguishable at small sizes.
*/
const COLORWAY_SWATCH_HEX: Record<GlassesColorway, string> = {
grey: "#8A8D91",
brown: "#6B4F3A",
green: "#3E5B45",
};
export function familyProductName(family: GlassesFamily): string {
return FAMILY_PRODUCT_NAME[family];
}
export function familyIsGlasses(family: GlassesFamily): boolean {
return family === "g1" || family === "g2";
}
export function frameLetter(frame: GlassesFrame): string {
return frame.toUpperCase();
}
export function frameDisplayName(frame: GlassesFrame): string {
return `Frame ${frameLetter(frame)}`;
}
export function colorwayDisplayName(colorway: GlassesColorway): string {
return COLORWAY_DISPLAY_NAME[colorway];
}
export function colorwaySwatchHex(colorway: GlassesColorway): string {
return COLORWAY_SWATCH_HEX[colorway];
}
export class GlassesHardwareIdentity {
/** The normalised (uppercased, trimmed, suffix-stripped) serial this identity was decoded from. */
readonly serial: string;
readonly family: GlassesFamily;
/** Null when the prefix is a family we recognise but a shape we do not, and always null for the ring. */
readonly frame: GlassesFrame | null;
/** Null when the colour byte is not one of A/B/C, and always null for the ring. */
readonly colorway: GlassesColorway | null;
private constructor(serial: string, family: GlassesFamily, frame: GlassesFrame | null, colorway: GlassesColorway | null) {
this.serial = serial;
this.family = family;
this.frame = frame;
this.colorway = colorway;
}
/**
* Decode a serial, or null when the string is not an Even serial at all.
*
* Accepts the advertised name verbatim: the scan list carries the bare
* serial, but saved pair identities and log lines carry arm suffixes
* (`S211GBBC180304_L_1`), so the leading serial run is taken and the rest
* ignored.
*/
static decode(rawValue: string | null | undefined): GlassesHardwareIdentity | null {
if (!rawValue) return null;
const normalized = normalizeSerial(rawValue);
// Both the family prefix (3) and the colour byte (index 5) must be present
// for the string to carry any variant information at all.
if (normalized.length < 6) return null;
const prefix2 = normalized.slice(0, 2);
const prefix3 = normalized.slice(0, 3);
let family: GlassesFamily;
switch (prefix2) {
case "S1":
family = "g1";
break;
case "S2":
family = "g2";
break;
case "B2":
family = "r1";
break;
default:
return null;
}
const isGlasses = familyIsGlasses(family);
return new GlassesHardwareIdentity(
normalized,
family,
isGlasses ? decodeFrame(prefix3, family) : null,
isGlasses ? decodeColorway(normalized) : null,
);
}
/** The four-character model code (`S211`), matching the Even app's `matchModel`. */
get modelCode(): string | null {
return this.serial.length >= 4 ? this.serial.slice(0, 4) : null;
}
/**
* Last four characters of the serial. Two people with the same frame and
* finish are the case this exists for: it is the shortest string that still
* separates them.
*/
get shortSerial(): string {
return this.serial.slice(-4);
}
/** "Even G2 B" — product plus frame letter, the way Even names the SKU. */
get productName(): string {
const base = familyProductName(this.family);
return this.frame ? `${base} ${frameLetter(this.frame)}` : base;
}
/** "Frame B · Brown", or just the half that decoded. Null when neither did. */
get variantSummary(): string | null {
const parts: string[] = [];
if (this.frame) parts.push(frameDisplayName(this.frame));
if (this.colorway) parts.push(colorwayDisplayName(this.colorway));
return parts.length ? parts.join(" · ") : null;
}
/** "Even G2 B · Brown" — the one-line label for a device row or status line. */
get displayName(): string {
return this.colorway ? `${this.productName} · ${colorwayDisplayName(this.colorway)}` : this.productName;
}
/**
* Bundled artwork key for the product photo of this exact SKU, or null when
* the shape or finish did not decode — or when the SKU is real but no
* artwork is bundled for it. Membership is explicit so a missing image fails
* to a generic product shot rather than to a blank `<Image>`.
*/
get imageAssetName(): string | null {
if (!this.frame || !this.colorway) return null;
const candidate = `glasses_${this.family}_${this.frame}_${this.colorway}`;
return BUNDLED_VARIANT_ASSET_NAMES.has(candidate) ? candidate : null;
}
equals(other: GlassesHardwareIdentity | null | undefined): boolean {
return !!other && other.serial === this.serial && other.family === this.family && other.frame === this.frame && other.colorway === this.colorway;
}
}
/**
* Frame C artwork is not bundled yet; add the PNG under `app/images/glasses/`
* and the name here together (see `glasses-artwork.ts`).
*/
export const BUNDLED_VARIANT_ASSET_NAMES: ReadonlySet<string> = new Set([
"glasses_g2_a_grey",
"glasses_g2_a_brown",
"glasses_g2_a_green",
"glasses_g2_b_grey",
"glasses_g2_b_brown",
"glasses_g2_b_green",
]);
/**
* Uppercase, drop surrounding whitespace, and cut at the first character that
* cannot appear in a serial — which is how the `_L_1` / `_R_1` arm suffix gets
* removed.
*/
export function normalizeSerial(rawValue: string): string {
const trimmed = rawValue.trim().toUpperCase();
const match = /^[0-9A-Z]*/.exec(trimmed);
return match ? match[0] : "";
}
function decodeFrame(prefix3: string, family: GlassesFamily): GlassesFrame | null {
switch (family) {
case "g1":
// G1 ships two shapes; the Even app tests only for `S11` and treats every
// other `S1` prefix as A.
return prefix3 === "S11" ? "b" : "a";
case "g2":
switch (prefix3) {
case "S20":
case "S28":
return "a";
case "S21":
case "S29":
return "b";
case "S22":
return "c";
default:
return null;
}
case "r1":
return null;
}
}
function decodeColorway(serial: string): GlassesColorway | null {
switch (serial.charAt(5)) {
case "A":
return "grey";
case "B":
return "brown";
case "C":
return "green";
default:
return null;
}
}
// ---------------------------------------------------------------------------
// Left/right pair check
// ---------------------------------------------------------------------------
/**
* Do the two temples belong to the same pair?
*
* A G2 is two independent BLE peripherals, each advertising its own serial.
* They should read identically. They will not when two pairs share a case,
* when an arm from one pair is charged alongside another, or when a
* replacement temple is fitted — and the result is a link that starts,
* authenticates on one side, and then behaves inexplicably. This names that
* failure before a connection is attempted.
*/
export type GlassesPairSerialVerdict =
| { kind: "matched"; serial: string }
| { kind: "unknown" }
| { kind: "mismatched"; left: string; right: string };
/**
* Canonical comparison key for a serial-ish string: the decoded serial when it
* decodes (so an `_L_1` arm suffix or casing difference is not read as
* different hardware), else the trimmed uppercase raw value. Null when empty.
* The single definition of serial equality — pair grouping, the pair check,
* and the "Yours" badge must all agree on it.
*/
export function serialKey(value: string | null | undefined): string | null {
const trimmed = nonEmpty(value);
if (!trimmed) return null;
return GlassesHardwareIdentity.decode(trimmed)?.serial ?? trimmed.toUpperCase();
}
/** True when both values carry a serial and the serials name the same hardware. */
export function serialsMatch(a: string | null | undefined, b: string | null | undefined): boolean {
const keyA = serialKey(a);
const keyB = serialKey(b);
return !!keyA && !!keyB && keyA === keyB;
}
export function evaluatePairSerials(left: string | null | undefined, right: string | null | undefined): GlassesPairSerialVerdict {
const l = nonEmpty(left);
const r = nonEmpty(right);
if (!l || !r) return { kind: "unknown" };
if (!serialsMatch(l, r)) return { kind: "mismatched", left: l, right: r };
return { kind: "matched", serial: serialKey(l)! };
}
/**
* One sentence naming what is wrong and what to do, or null when nothing is
* wrong. Deliberately concrete about the serials: the wearer has to physically
* sort two piles of near-identical temples, and the printed serial is what
* they can sort them by.
*/
export function pairSerialWarning(verdict: GlassesPairSerialVerdict): string | null {
if (verdict.kind !== "mismatched") return null;
const leftVariant = GlassesHardwareIdentity.decode(verdict.left)?.displayName;
const rightVariant = GlassesHardwareIdentity.decode(verdict.right)?.displayName;
let message = `The left and right temples report different serial numbers (left ${verdict.left}, right ${verdict.right}).`;
if (leftVariant && rightVariant && leftVariant !== rightVariant) {
message += ` They are not even the same model: ${leftVariant} and ${rightVariant}.`;
}
message += " These are arms from two different pairs — check the serial printed inside each temple and pair a matched set.";
return message;
}
function nonEmpty(value: string | null | undefined): string | null {
if (value == null) return null;
const trimmed = value.trim();
return trimmed ? trimmed : null;
}
+422
View File
@@ -0,0 +1,422 @@
/**
* Turns a stream of Even advertisements into the things a pairing list shows:
* G2 pairs (a left and a right temple that advertise the same serial) and R1
* rings, each ranked by how close it probably is.
*
* Ranks by nearest-device margin, previously-paired match, and closest-first
* ordering, with the left↔right pair grouping that Faceclaw needs because
* it connects to each arm by address rather than through a vendor SDK.
*
* This module is pure (no NativeScript imports) so it can run under node tests.
*/
import {
estimateProximity,
GLASSES_CALIBRATION,
RING_CALIBRATION,
sortedByProximity,
zoneGlyph,
zoneLabel,
type ProximityEstimate,
type ProximityZone,
} from "./ble-proximity";
import { classifyAdvertisement, normalizeMacAddress, type EvenAdvertisement, type RawAdvertisement } from "./even-advertisement";
import { glassesImagePath, R1_IMAGE_PATH } from "./glasses-artwork";
import {
colorwayDisplayName,
colorwaySwatchHex,
evaluatePairSerials,
GlassesHardwareIdentity,
pairSerialWarning,
serialKey,
serialsMatch,
type GlassesColorway,
} from "./glasses-hardware-identity";
export type PairCompleteness = "complete" | "left-only" | "right-only";
/** A G2 pair as seen over the air: up to one advertisement per side, joined on serial. */
export type GlassesPairCandidate = {
/** Stable id: the serial when known, otherwise the lone arm's address. */
id: string;
serial: string | null;
identity: GlassesHardwareIdentity | null;
left: EvenAdvertisement | null;
right: EvenAdvertisement | null;
completeness: PairCompleteness;
/** Strongest smoothed signal across the arms that have one. */
rssi: number | null;
proximity: ProximityEstimate | null;
lastSeenMs: number;
/**
* Set when this lone arm and a lone arm of the other side carry different
* serials — the mixed-pair situation the serial check exists to name.
* Grouping is by serial, so the mismatch can only show up across groups.
*/
mismatchWarning: string | null;
};
export type RingCandidate = {
id: string;
advertisement: EvenAdvertisement;
rssi: number | null;
proximity: ProximityEstimate | null;
lastSeenMs: number;
};
/**
* Android delivers a callback per advertisement (several per second per arm),
* far more often than CoreBluetooth's coalesced reports, so the raw RSSI
* jitters visibly. A light exponential average keeps the list calm without
* hiding a real move. Ordering still uses the smoothed value; the margin for
* the "Closest" badge is applied on top.
*/
const RSSI_SMOOTHING = 0.35;
/**
* The device whose signal is strong enough to call "the one you are holding"
* needs a clear margin over the runner-up: RSSI wanders by a few dB between
* advertisements, so a badge awarded on a 1 dB lead would hop between rows
* every scan pass and mean nothing.
*/
export const NEAREST_SIGNAL_MARGIN_DBM = 8;
/** Advertisements older than this are dropped — the pair went back in its case or walked off. */
export const DEFAULT_STALE_AFTER_MS = 12_000;
export class DiscoveryAggregator {
private readonly byAddress = new Map<string, EvenAdvertisement & { smoothedRssi: number | null }>();
private readonly rejectedNames = new Set<string>();
/** Feed one raw advertisement. Returns the classified record, or null when ignored. */
ingest(raw: RawAdvertisement): EvenAdvertisement | null {
let classified = classifyAdvertisement(raw);
if (!classified) {
// Android sometimes splits an advertisement across reports — an ADV
// report without the scan response's name, or the reverse. If earlier
// traffic from this address already supplied the missing half, retry
// with it filled in rather than dropping the arm.
const remembered = this.byAddress.get(normalizeMacAddress(raw.address));
if (remembered) {
classified = classifyAdvertisement({
...raw,
name: raw.name || remembered.name,
manufacturerData: raw.manufacturerData || remembered.manufacturerData,
});
}
if (!classified) {
if (raw.name) this.rejectedNames.add(raw.name);
return null;
}
}
const previous = this.byAddress.get(classified.address);
let smoothedRssi: number | null = classified.rssi;
if (classified.rssi != null && previous?.smoothedRssi != null) {
smoothedRssi = previous.smoothedRssi + RSSI_SMOOTHING * (classified.rssi - previous.smoothedRssi);
} else if (classified.rssi == null && previous) {
// A bonded-device entry carries no signal; keep what the scan told us.
smoothedRssi = previous.smoothedRssi;
}
const merged: EvenAdvertisement & { smoothedRssi: number | null } = {
...classified,
// A bonded listing never has a serial; do not let it erase a scanned one.
serial: classified.serial ?? previous?.serial ?? null,
embeddedMac: classified.embeddedMac ?? previous?.embeddedMac ?? null,
manufacturerData: classified.manufacturerData || previous?.manufacturerData || "",
bonded: classified.bonded || (previous?.bonded ?? false),
rssi: classified.rssi ?? previous?.rssi ?? null,
txPower: classified.txPower ?? previous?.txPower ?? null,
seenAtMs: Math.max(classified.seenAtMs, previous?.seenAtMs ?? 0),
smoothedRssi,
};
if (previous && !classified.manufacturerData && previous.manufacturerData) {
// A record without manufacturer data (a bonded listing, or a split
// report) parses to "serial unknown" notes and a possibly stale cached
// name; those must not overwrite what a fuller advertisement already
// established, or the row shows a serial and claims it is unknown.
merged.note = previous.note;
merged.flag = previous.flag;
merged.embeddedMacMismatch = previous.embeddedMacMismatch;
merged.ringSerialSuffix = previous.ringSerialSuffix;
if (previous.name && (!classified.name || classified.source === "paired")) {
merged.name = previous.name;
}
}
this.byAddress.set(merged.address, merged);
return merged;
}
/** Forget advertisements not refreshed within `maxAgeMs`. Bonded entries are kept. */
prune(nowMs: number, maxAgeMs: number = DEFAULT_STALE_AFTER_MS): void {
for (const [address, record] of this.byAddress) {
if (record.bonded) continue;
if (nowMs - record.seenAtMs > maxAgeMs) this.byAddress.delete(address);
}
}
clear(): void {
this.byAddress.clear();
this.rejectedNames.clear();
}
get size(): number {
return this.byAddress.size;
}
/** Names of advertisements that looked like nothing we pair with — for the diagnostics log. */
get rejectedNameList(): string[] {
return Array.from(this.rejectedNames).sort();
}
advertisements(): EvenAdvertisement[] {
return Array.from(this.byAddress.values());
}
/** Every G2 pair seen, joined on serial, closest first. */
pairs(): GlassesPairCandidate[] {
const groups = new Map<string, { left: (EvenAdvertisement & { smoothedRssi: number | null }) | null; right: (EvenAdvertisement & { smoothedRssi: number | null }) | null }>();
for (const record of this.byAddress.values()) {
if (record.role === "ring") continue;
const canonical = serialKey(record.serial);
const key = canonical ? `serial:${canonical}` : `arm:${record.address}`;
const group = groups.get(key) ?? { left: null, right: null };
const slot = record.role === "left" ? "left" : "right";
const incumbent = group[slot];
// Two arms of one side claiming the same serial is a replaced temple or a
// stale row; keep the one heard most recently.
if (!incumbent || incumbent.seenAtMs <= record.seenAtMs) group[slot] = record;
groups.set(key, group);
}
const pairs: GlassesPairCandidate[] = [];
for (const group of groups.values()) {
const left = group.left;
const right = group.right;
const any = (left ?? right)!;
const serial = any.serial;
const samples = [left, right].filter((arm): arm is NonNullable<typeof arm> => !!arm && arm.smoothedRssi != null);
const strongest = samples.length ? samples.reduce((a, b) => (a.smoothedRssi! >= b.smoothedRssi! ? a : b)) : null;
const rssi = strongest ? Math.round(strongest.smoothedRssi!) : null;
pairs.push({
id: serialKey(serial) ?? `arm:${any.address}`,
serial,
identity: GlassesHardwareIdentity.decode(serial),
left: left ? stripSmoothing(left) : null,
right: right ? stripSmoothing(right) : null,
completeness: left && right ? "complete" : left ? "left-only" : "right-only",
rssi,
proximity: estimateProximity(rssi, GLASSES_CALIBRATION),
lastSeenMs: Math.max(left?.seenAtMs ?? 0, right?.seenAtMs ?? 0),
mismatchWarning: null,
});
}
// Grouping on the serial means a group can never hold two different
// serials, so a mixed pair (left temple from A, right from B) surfaces as
// two lone arms, not as one mismatched row. With exactly one lone arm per
// side visible that IS the mixed-arms situation — name it on both rows so
// the wearer isn't left staring at two "waiting for the other" rows.
const loneLeft = pairs.filter((pair) => pair.completeness === "left-only" && pair.serial);
const loneRight = pairs.filter((pair) => pair.completeness === "right-only" && pair.serial);
if (loneLeft.length === 1 && loneRight.length === 1) {
const warning = pairSerialWarning(evaluatePairSerials(loneLeft[0]!.left!.serial, loneRight[0]!.right!.serial));
loneLeft[0]!.mismatchWarning = warning;
loneRight[0]!.mismatchWarning = warning;
}
return sortedByProximity(pairs, (pair) => pair.proximity, (pair) => pair.id);
}
/** Every R1 ring seen, closest first. */
rings(): RingCandidate[] {
const rings: RingCandidate[] = [];
for (const record of this.byAddress.values()) {
if (record.role !== "ring") continue;
const rssi = record.smoothedRssi != null ? Math.round(record.smoothedRssi) : null;
rings.push({
id: record.address,
advertisement: stripSmoothing(record),
rssi,
proximity: estimateProximity(rssi, RING_CALIBRATION),
lastSeenMs: record.seenAtMs,
});
}
return sortedByProximity(rings, (ring) => ring.proximity, (ring) => ring.id);
}
}
function stripSmoothing(record: EvenAdvertisement & { smoothedRssi: number | null }): EvenAdvertisement {
const { smoothedRssi: _ignored, ...rest } = record;
return rest;
}
/**
* The candidate whose signal is strong enough to call "the one you are
* holding". `null` when nothing leads clearly, which is the honest answer for
* two pairs sitting on the same table — and when the list has a single entry,
* where "closest" has nothing to be closer than.
*/
export function nearestCandidateId(candidates: ReadonlyArray<{ id: string; rssi: number | null }>): string | null {
if (candidates.length < 2) return null;
const ranked = candidates
.filter((candidate): candidate is { id: string; rssi: number } => candidate.rssi != null)
.slice()
// Stable order for equal signal so repeated polls nominate the same row.
.sort((lhs, rhs) => (lhs.rssi === rhs.rssi ? (lhs.id < rhs.id ? -1 : 1) : rhs.rssi - lhs.rssi));
const best = ranked[0];
if (!best) return null;
if (ranked.length === 1) return best.id;
return best.rssi - ranked[1]!.rssi >= NEAREST_SIGNAL_MARGIN_DBM ? best.id : null;
}
/**
* The saved pair identity is stored as the serial, but historical values may
* carry the `_L_1` arm suffix; `serialsMatch` compares on the decoded serial
* so the suffix or casing is not read as different hardware.
*/
export function isPreviouslyPaired(name: string | null | undefined, pairedSerial: string | null | undefined): boolean {
return serialsMatch(name, pairedSerial);
}
// ---------------------------------------------------------------------------
// Row presentation
// ---------------------------------------------------------------------------
export type PairingRowPresentation = {
id: string;
kind: "glasses" | "ring";
/** "Even G2 B" / "Even R1" / fallback product name. */
modelTitle: string;
/** The serial (glasses) or local name (ring). */
deviceName: string;
/** "Frame B · Brown", or null when the serial does not carry a variant we recognise. */
variantSummary: string | null;
colorway: GlassesColorway | null;
/** Hex colour for the swatch. Null suppresses it rather than guessing a finish. */
swatchHex: string | null;
/** Product photo path for `<Image src>`. Variant art when bundled, else the generic shot. */
imagePath: string;
/** True only when the variant-specific photo is available (the swatch is redundant then). */
hasVariantImage: boolean;
isNearest: boolean;
isPreviouslyPaired: boolean;
/** "Yours" / "Closest" / "". */
badge: string;
proximitySummary: string;
proximityGlyph: string;
zone: ProximityZone | null;
/** "Left + right arms found", "Only the left arm has been seen", …; "" when there is nothing worth a line (an unbonded ring). */
armsSummary: string;
/** A problem the wearer should read before tapping, or "" when none. */
warning: string;
/** Both arms present (or a ring), so tapping can save addresses. */
canSelect: boolean;
};
export type RowContext = {
/** Serial of the pair this phone paired with before, if any. */
pairedSerial?: string | null;
/** From `nearestCandidateId` over the same list. */
nearestId?: string | null;
/** Ring address saved before, if any. */
pairedRingAddress?: string | null;
};
/** The presentation fields glasses and ring rows share, so badge and fallback rules cannot drift apart. */
function presentationBase(
proximity: ProximityEstimate | null,
isNearest: boolean,
isPaired: boolean,
warnings: readonly string[],
): Pick<PairingRowPresentation, "isNearest" | "isPreviouslyPaired" | "badge" | "proximitySummary" | "proximityGlyph" | "zone" | "warning"> {
return {
isNearest,
isPreviouslyPaired: isPaired,
badge: isPaired ? "Yours" : isNearest ? "Closest" : "",
proximitySummary: proximity ? zoneLabel(proximity.zone) : "Signal unknown",
proximityGlyph: proximity ? zoneGlyph(proximity.zone) : "○○○○",
zone: proximity?.zone ?? null,
warning: warnings.join(" "),
};
}
function embeddedMacMismatchWarning(subject: string, ad: EvenAdvertisement | null): string | null {
if (!ad?.embeddedMacMismatch) return null;
return `${subject} advertised address ${ad.embeddedMac} differs from its radio address ${ad.address}.`;
}
export function glassesRow(pair: GlassesPairCandidate, context: RowContext = {}): PairingRowPresentation {
const identity = pair.identity;
const imagePath = glassesImagePath(identity);
const isPreviouslyPairedRow = isPreviouslyPaired(pair.serial, context.pairedSerial);
const isNearest = !!context.nearestId && context.nearestId === pair.id;
const warnings: string[] = [];
const leftNote = pair.left?.note;
const rightNote = pair.right?.note;
if (leftNote) warnings.push(`Left arm: ${leftNote}.`);
if (rightNote) warnings.push(`Right arm: ${rightNote}.`);
const leftMacWarning = embeddedMacMismatchWarning("Left arm's", pair.left);
if (leftMacWarning) warnings.push(leftMacWarning);
const rightMacWarning = embeddedMacMismatchWarning("Right arm's", pair.right);
if (rightMacWarning) warnings.push(rightMacWarning);
if (pair.mismatchWarning) warnings.push(pair.mismatchWarning);
let armsSummary: string;
switch (pair.completeness) {
case "complete":
// Arms are grouped by serial, so a complete pair's serials match by construction.
armsSummary = "Left + right arms found · serials match";
break;
case "left-only":
armsSummary = "Only the left arm has been seen — waiting for the right";
break;
case "right-only":
armsSummary = "Only the right arm has been seen — waiting for the left";
break;
}
if (!pair.serial) armsSummary += " · serial unknown, cannot match arms";
return {
id: pair.id,
kind: "glasses",
modelTitle: identity?.productName ?? "Even Realities G2",
deviceName: pair.serial ?? (pair.left ?? pair.right)!.name,
variantSummary: identity?.variantSummary ?? null,
colorway: identity?.colorway ?? null,
swatchHex: identity?.colorway ? colorwaySwatchHex(identity.colorway) : null,
imagePath,
hasVariantImage: !!identity?.imageAssetName,
...presentationBase(pair.proximity, isNearest, isPreviouslyPairedRow, warnings),
armsSummary,
canSelect: pair.completeness === "complete",
};
}
export function ringRow(ring: RingCandidate, context: RowContext = {}): PairingRowPresentation {
const ad = ring.advertisement;
const isPaired = !!context.pairedRingAddress && normalizeMacAddress(context.pairedRingAddress) === ad.address;
const isNearest = !!context.nearestId && context.nearestId === ring.id;
const warnings: string[] = [];
if (ad.note) warnings.push(`${ad.note}.`);
const macWarning = embeddedMacMismatchWarning("The ring's", ad);
if (macWarning) warnings.push(macWarning);
return {
id: ring.id,
kind: "ring",
modelTitle: "Even R1",
deviceName: ad.ringSerialSuffix ? `${ad.name} · serial …${ad.ringSerialSuffix}` : ad.name,
variantSummary: null,
colorway: null,
swatchHex: null,
imagePath: R1_IMAGE_PATH,
hasVariantImage: true,
...presentationBase(ring.proximity, isNearest, isPaired, warnings),
// "Advertising" told the wearer nothing (a listed ring is advertising by
// definition); only the bonded state is worth a line.
armsSummary: ad.bonded ? "Paired with this phone" : "",
canSelect: true,
};
}
/** Convenience: a colourway's display text, for rows that show the swatch alone. */
export function colorwayLabel(colorway: GlassesColorway | null): string {
return colorway ? colorwayDisplayName(colorway) : "";
}
+502
View File
@@ -0,0 +1,502 @@
/**
* The Wear OS watch as an input device and status mirror for the glasses.
*
* Inbound, the watch sends ring-style gestures (tap, double-tap, hold,
* swipe/crown scrolls, "Hey Even") which feed the exact synthetic-ring path
* the phone UI's test buttons use, plus higher-level commands the ring has no
* way to express: launch an app, switch or close a window, wake/sleep/lock
* the display, send a spoken or typed query straight to the assistant, or
* type text into the foreground app.
*
* Outbound, the dashboard state (connection, battery, screen, lock, open
* windows, launchable apps) is mirrored into a Data Layer item so the watch
* UI can show it and offer the right actions; assistant replies and alerts
* stream to the watch as events so a query made from the wrist can be read
* from the wrist.
*
* Transport is app/native/wear-bridge.ts (Java FaceclawWearBridge); the
* message shapes are documented in wear/PROTOCOL.md.
*/
import { type AppDefinition } from "../apps/app-definition";
import { getInstalledEvenHubApps, installedEvenHubAppId } from "../apps/evenhub/installed-apps";
import { WEAR_PATHS, wearBridge, type WearMessage } from "../native/wear-bridge";
import {
DISPLAY_MODE_VALUES,
displayModeSetting,
onAnySettingChanged,
watchCanUnlockSetting,
watchCrownClockwiseNextSetting,
watchMirrorAssistantSetting,
watchRemoteEnabledSetting,
} from "../ui/dashboard-settings";
import { shell, type AssistantActivityEvent } from "../ui/shell/shell";
import { voiceActivity } from "../ui/shell/voice-activity";
import { FACECLAW_VERSION } from "../version";
/** Protocol revision carried in the state item; bump on incompatible changes. */
export const WEAR_PROTOCOL_VERSION = 1;
export type WearRemoteInputKind =
| "click"
| "double-click"
| "scroll-up"
| "scroll-down"
| "long-press"
| "long-press-start"
| "long-press-release"
| "wakeword"
| "swipe-left"
| "swipe-right"
| "swipe-up"
| "swipe-down";
const INPUT_KINDS: readonly WearRemoteInputKind[] = [
"click",
"double-click",
"scroll-up",
"scroll-down",
"long-press",
"long-press-start",
"long-press-release",
"wakeword",
"swipe-left",
"swipe-right",
"swipe-up",
"swipe-down",
];
const COMMANDS = [
"launch-app",
"focus-window",
"close-window",
"sidebar",
"wake",
"sleep",
"lock",
"unlock",
"connect",
"disconnect",
"close-assistant",
"display-mode",
] as const;
type WearCommand = (typeof COMMANDS)[number];
const MAX_SCROLL_STEPS = 12;
const MAX_TEXT_LENGTH = 2000;
const STATE_PUBLISH_DEBOUNCE_MS = 150;
const STATE_REFRESH_INTERVAL_MS = 30_000;
const ASSISTANT_STREAM_MIN_INTERVAL_MS = 250;
/** What the dashboard controller lends the watch remote. */
export type WearRemoteHost = {
/** The launcher-grid apps; installed EvenHub packages are added dynamically. */
apps: readonly AppDefinition[];
injectInput: (kind: WearRemoteInputKind) => Promise<void>;
launchApp: (appId: string) => Promise<void>;
connect: () => Promise<void>;
disconnect: () => Promise<void>;
setGlassesLocked: (locked: boolean, reason: string) => void;
requestShellRender: () => void;
getState: () => {
phase: string;
status: string;
glassesLocked: boolean;
glassesWorn: boolean | null;
silentMode: boolean;
lastHeadsetBattery: number | null;
};
appendLog: (line: string) => void;
};
export class WearRemote {
private readonly active: boolean;
private publishTimer: ReturnType<typeof setTimeout> | null = null;
private watchReachable = false;
private watchName = "";
// Assistant text streams as deltas many times a second; the watch gets a
// snapshot every ASSISTANT_STREAM_MIN_INTERVAL_MS plus every phase change.
private assistantStreamTimer: ReturnType<typeof setTimeout> | null = null;
private assistantPendingText: string | null = null;
private lastAssistantSentAtMs = 0;
constructor(private readonly host: WearRemoteHost) {
this.active = wearBridge.isAvailable();
if (!this.active) {
host.appendLog("watch: Google Play services unavailable; watch remote disabled");
return;
}
wearBridge.onMessage((message) => {
void this.handleMessage(message).catch((error) => {
host.appendLog(`watch: ${message.path} failed: ${formatError(error)}`);
});
});
wearBridge.onWatchConnection((connection) => {
const changed = connection.reachable !== this.watchReachable || connection.watchName !== this.watchName;
this.watchReachable = connection.reachable;
this.watchName = connection.watchName;
if (changed) {
host.appendLog(
connection.reachable ? `watch: ${connection.watchName || "watch"} reachable` : "watch: no watch reachable",
);
}
// A watch that just came into range gets the current state at once.
if (connection.reachable) this.publishNow(true);
});
shell.onAssistantActivity((event) => this.forwardAssistantActivity(event));
shell.onAlertShown((text) => {
if (this.watchReachable && watchMirrorAssistantSetting.get()) {
wearBridge.sendEvent({ type: "alert", text });
}
});
voiceActivity.subscribe(() => this.schedulePublish());
onAnySettingChanged(() => this.schedulePublish());
// Catch-all refresh for state the controller does not announce (cheap:
// identical states are dropped on the Java side).
setInterval(() => this.schedulePublish(), STATE_REFRESH_INTERVAL_MS);
this.schedulePublish();
}
/** Whether a watch running the Faceclaw watch app is reachable right now. */
isWatchReachable(): boolean {
return this.watchReachable;
}
getWatchName(): string {
return this.watchName;
}
/** Mirror the dashboard state to the watch soon; coalesces bursts. */
schedulePublish(): void {
if (!this.active || this.publishTimer) return;
this.publishTimer = setTimeout(() => {
this.publishTimer = null;
this.publishNow(false);
}, STATE_PUBLISH_DEBOUNCE_MS);
}
private publishNow(force: boolean): void {
if (!this.active) return;
try {
wearBridge.publishState(this.buildState(), force);
} catch (error) {
this.host.appendLog(`watch: state publish failed: ${formatError(error)}`);
}
}
private buildState(): Record<string, unknown> {
const state = this.host.getState();
const battery = shell.getBatteryLevels();
const foregroundId = shell.foregroundWindow()?.windowId ?? null;
const foreground = shell.getForegroundApp();
return {
protocol: WEAR_PROTOCOL_VERSION,
version: FACECLAW_VERSION,
phase: state.phase,
status: state.status,
connected: state.phase === "connected" || state.phase === "charging",
screenOn: shell.isScreenOn(),
locked: state.glassesLocked,
worn: state.glassesWorn,
listening: voiceActivity.isActive(),
battery: state.lastHeadsetBattery,
charging: state.phase === "charging" || battery.headsetCharging === true,
silentMode: state.silentMode,
foreground: foreground ? { appId: foreground.appId, title: foreground.title } : null,
windows: shell.getWindows().map((window) => ({
windowId: window.windowId,
title: window.title,
appId: window.appId,
focused: window.windowId === foregroundId,
closeable: window.closeable,
acceptsText: typeof window.receiveTextInput === "function",
})),
apps: this.listApps(),
displayMode: displayModeSetting.get(),
remoteEnabled: watchRemoteEnabledSetting.get(),
crownClockwiseNext: watchCrownClockwiseNextSetting.get(),
canUnlock: watchCanUnlockSetting.get(),
mirrorAssistant: watchMirrorAssistantSetting.get(),
assistantAvailable: shell.isAssistantAvailable(),
};
}
/** Launchable apps, matching the launcher grid and the apps.launch tool. */
private listApps(): Array<{ appId: string; title: string }> {
const apps = this.host.apps.map((app) => ({ appId: app.appId, title: app.title }));
for (const installed of getInstalledEvenHubApps()) {
apps.push({ appId: installedEvenHubAppId(installed.packageId), title: installed.name });
}
return apps;
}
private async handleMessage(message: WearMessage): Promise<void> {
const seq = readNumber(message.payload.seq, 0);
const ack = (ok: boolean, text = "") => wearBridge.sendAck(message.nodeId, seq, ok, text);
if (message.path === WEAR_PATHS.stateRequest) {
this.publishNow(true);
ack(true);
return;
}
if (!watchRemoteEnabledSetting.get()) {
ack(false, "Watch control is turned off in Faceclaw's Settings > Watch.");
return;
}
switch (message.path) {
case WEAR_PATHS.input:
await this.handleInput(message.payload, ack);
return;
case WEAR_PATHS.command:
await this.handleCommand(message.payload, ack);
return;
case WEAR_PATHS.assistant: {
const text = readText(message.payload.text);
if (!text) {
ack(false, "Nothing to send.");
return;
}
if (!shell.isAssistantAvailable()) {
ack(false, "Set up the assistant in Faceclaw's Settings first.");
return;
}
this.host.appendLog(`watch: assistant query (${text.length} chars)`);
shell.sendToAssistant(text);
ack(true);
return;
}
case WEAR_PATHS.text: {
const text = readText(message.payload.text);
if (!text) {
ack(false, "Nothing to type.");
return;
}
const window = shell.foregroundWindow();
if (!window?.receiveTextInput) {
ack(false, `${window ? window.title : "The current app"} does not accept typed text.`);
return;
}
if (!shell.isScreenOn()) shell.wake("window");
this.host.appendLog(`watch: typed ${text.length} chars into ${window.title}`);
shell.sendTextToForegroundWindow(text);
ack(true);
return;
}
default:
ack(false, `Unknown message: ${message.path}`);
}
}
private async handleInput(payload: Record<string, unknown>, ack: (ok: boolean, text?: string) => void): Promise<void> {
const gesture = String(payload.gesture ?? "");
if (!(INPUT_KINDS as readonly string[]).includes(gesture)) {
ack(false, `Unknown gesture: ${gesture}`);
return;
}
const kind = gesture as WearRemoteInputKind;
const state = this.host.getState();
if (state.phase !== "connected" && state.phase !== "charging") {
ack(false, "The glasses are not connected.");
return;
}
// The lock and a dark display only yield to a double-click, exactly as
// the ring does (handled inside the controller).
const repeatable = kind === "scroll-up" || kind === "scroll-down" || kind === "swipe-up" || kind === "swipe-down";
const steps = repeatable ? Math.min(MAX_SCROLL_STEPS, Math.max(1, Math.round(readNumber(payload.steps, 1)))) : 1;
for (let i = 0; i < steps; i++) {
await this.host.injectInput(kind);
}
ack(true);
}
private async handleCommand(payload: Record<string, unknown>, ack: (ok: boolean, text?: string) => void): Promise<void> {
const command = String(payload.command ?? "");
if (!(COMMANDS as readonly string[]).includes(command)) {
ack(false, `Unknown command: ${command}`);
return;
}
const state = this.host.getState();
const connected = state.phase === "connected" || state.phase === "charging";
this.host.appendLog(`watch: ${command}`);
switch (command as WearCommand) {
case "connect":
if (connected) {
ack(true, "Already connected.");
return;
}
ack(true, "Connecting...");
await this.host.connect();
return;
case "disconnect":
if (!connected && state.phase === "disconnected") {
ack(true, "Already disconnected.");
return;
}
ack(true, "Disconnecting...");
await this.host.disconnect();
return;
default:
break;
}
if (!connected) {
ack(false, "The glasses are not connected.");
return;
}
if (payload.source === "gesture" && !shell.isScreenOn()) {
ack(true);
return;
}
if (state.glassesLocked && command !== "unlock" && command !== "lock") {
ack(false, "The glasses are locked.");
return;
}
switch (command as WearCommand) {
case "launch-app": {
const appId = String(payload.appId ?? "").trim();
const app = this.listApps().find((entry) => entry.appId === appId);
if (!app) {
ack(false, `Unknown app: ${appId}`);
return;
}
shell.wake("window");
await this.host.launchApp(appId);
this.schedulePublish();
ack(true, `Opened ${app.title}.`);
return;
}
case "focus-window": {
const windowId = String(payload.windowId ?? "").trim();
const window = shell.getWindows().find((entry) => entry.windowId === windowId);
if (!window) {
ack(false, "That window is no longer open.");
return;
}
shell.wake("window");
shell.focusWindow(windowId);
this.host.requestShellRender();
this.schedulePublish();
ack(true);
return;
}
case "close-window": {
const windowId = String(payload.windowId ?? "").trim();
const window = shell.getWindows().find((entry) => entry.windowId === windowId);
if (!window) {
ack(false, "That window is no longer open.");
return;
}
if (!window.closeable) {
ack(false, `${window.title} cannot be closed.`);
return;
}
shell.closeWindow(windowId);
this.host.requestShellRender();
this.schedulePublish();
ack(true, `Closed ${window.title}.`);
return;
}
case "sidebar":
shell.wake("sidebar");
shell.yieldFocusToSidebar();
this.host.requestShellRender();
ack(true);
return;
case "wake":
if (!shell.wake("sidebar")) {
ack(true, "The display is already on.");
return;
}
this.host.requestShellRender();
ack(true);
return;
case "sleep":
if (!shell.isScreenOn()) {
ack(true, "The display is already off.");
return;
}
shell.sleep();
ack(true);
return;
case "lock":
this.host.setGlassesLocked(true, "locked from the watch");
this.schedulePublish();
ack(true);
return;
case "unlock":
if (!watchCanUnlockSetting.get()) {
ack(false, "Unlocking from the watch is turned off in Settings > Watch.");
return;
}
this.host.setGlassesLocked(false, "unlocked from the watch");
this.schedulePublish();
ack(true);
return;
case "close-assistant":
// Idempotent: closing an assistant that isn't open still succeeds,
// but tell the watch which of the two happened.
ack(true, shell.closeAssistant() ? "" : "The assistant was not open.");
return;
case "display-mode": {
const value = String(payload.value ?? "");
if (!(DISPLAY_MODE_VALUES as readonly string[]).includes(value)) {
ack(false, `Unknown display mode: ${value}`);
return;
}
displayModeSetting.set(value as (typeof DISPLAY_MODE_VALUES)[number]);
this.schedulePublish();
ack(true, `Display mode: ${value}`);
return;
}
default:
ack(false, `Unhandled command: ${command}`);
}
}
private forwardAssistantActivity(event: AssistantActivityEvent): void {
if (!watchMirrorAssistantSetting.get()) return;
// No watch to mirror to: sending anyway is not free — with no known
// watch nodes the Java side runs a capability lookup per event, which a
// streaming reply would repeat several times a second.
if (!this.watchReachable) return;
if (event.phase === "streaming") {
// Coalesce: the newest text wins, sent no more often than the interval.
this.assistantPendingText = event.text;
if (this.assistantStreamTimer) return;
const wait = Math.max(0, ASSISTANT_STREAM_MIN_INTERVAL_MS - (Date.now() - this.lastAssistantSentAtMs));
this.assistantStreamTimer = setTimeout(() => {
this.assistantStreamTimer = null;
if (this.assistantPendingText === null) return;
this.sendAssistantEvent("streaming", this.assistantPendingText);
this.assistantPendingText = null;
}, wait);
return;
}
// A phase change supersedes any queued stream snapshot.
if (this.assistantStreamTimer) {
clearTimeout(this.assistantStreamTimer);
this.assistantStreamTimer = null;
}
this.assistantPendingText = null;
this.sendAssistantEvent(event.phase, event.text);
this.schedulePublish();
}
private sendAssistantEvent(phase: AssistantActivityEvent["phase"], text: string): void {
this.lastAssistantSentAtMs = Date.now();
wearBridge.sendEvent({ type: "assistant", phase, text });
}
}
function readNumber(value: unknown, fallback: number): number {
const numeric = typeof value === "number" ? value : Number(value);
return Number.isFinite(numeric) ? numeric : fallback;
}
function readText(value: unknown): string {
const text = typeof value === "string" ? value : "";
return text.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f]/g, "").trim().slice(0, MAX_TEXT_LENGTH);
}
function formatError(error: unknown): string {
return (error as Error)?.message ?? String(error);
}