forked from Blendman974/faceclaw
Add proximity-based pairing for Even devices
Stream BLE advertisements into a dedicated pairing flow with arm, ring, serial, and hardware variant detection. Add proximity ranking, device artwork, pairing safeguards, and unit coverage for discovery and candidate grouping.
This commit is contained in:
35 files changed
+3309
-140
No files matched your search
@@ -1,37 +1,47 @@
|
||||
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo">
|
||||
<ActionBar title="Configure Devices" />
|
||||
|
||||
<GridLayout rows="auto,auto,auto,auto,auto,auto,auto,*" class="p-20">
|
||||
<GridLayout rows="auto,auto,auto,auto,auto,auto,auto,auto,*" class="p-20">
|
||||
<Label row="0" text="Configure the MAC addresses for the G2 headset arms and optional R1 ring. This page does not test a connection." textWrap="true" />
|
||||
|
||||
<StackLayout row="1" class="m-t-16">
|
||||
<GridLayout row="1" columns="96,*" class="pairing-row m-t-12" visibility="{{ identityVisibility }}">
|
||||
<Image col="0" src="{{ identityImagePath }}" stretch="aspectFit" width="90" height="34" />
|
||||
<StackLayout col="1" class="m-l-8">
|
||||
<Label text="{{ identityTitle }}" class="pairing-title" />
|
||||
<Label text="{{ identityVariant }}" class="pairing-variant" visibility="{{ identityVariantVisibility }}" />
|
||||
<Label text="{{ identitySerial }}" class="pairing-serial" />
|
||||
<Label text="{{ identityDetail }}" class="pairing-arms" textWrap="true" />
|
||||
</StackLayout>
|
||||
</GridLayout>
|
||||
|
||||
<StackLayout row="2" class="m-t-16">
|
||||
<Label text="Right arm MAC" />
|
||||
<TextField text="{{ rightAddress }}" textChange="{{ onRightAddressTextChange }}" autocorrect="false" autocapitalizationType="none" />
|
||||
</StackLayout>
|
||||
|
||||
<StackLayout row="2" class="m-t-12">
|
||||
<StackLayout row="3" class="m-t-12">
|
||||
<Label text="Left arm MAC" />
|
||||
<TextField text="{{ leftAddress }}" textChange="{{ onLeftAddressTextChange }}" autocorrect="false" autocapitalizationType="none" />
|
||||
</StackLayout>
|
||||
|
||||
<StackLayout row="3" class="m-t-12">
|
||||
<StackLayout row="4" class="m-t-12">
|
||||
<Label text="R1 ring MAC (optional)" />
|
||||
<TextField text="{{ ringAddress }}" textChange="{{ onRingAddressTextChange }}" autocorrect="false" autocapitalizationType="none" />
|
||||
</StackLayout>
|
||||
|
||||
<GridLayout row="4" columns="*,*" class="m-t-16">
|
||||
<GridLayout row="5" columns="*,*" class="m-t-16">
|
||||
<Button col="0" text="Load paired devices" tap="{{ onLoadPairedTap }}" class="-primary" isEnabled="{{ canDiscover }}" />
|
||||
<Button col="1" text="Scan nearby" tap="{{ onScanTap }}" class="-primary" isEnabled="{{ canDiscover }}" />
|
||||
<Button col="1" text="Scan for glasses" tap="{{ onScanTap }}" class="-primary" isEnabled="{{ canDiscover }}" />
|
||||
</GridLayout>
|
||||
|
||||
<Label row="5" text="{{ status }}" class="m-t-16" textWrap="true" />
|
||||
<Label row="6" text="{{ status }}" class="m-t-16" textWrap="true" />
|
||||
|
||||
<GridLayout row="6" columns="*,*" class="m-t-16">
|
||||
<GridLayout row="7" columns="*,*" class="m-t-16">
|
||||
<Button col="0" text="{{ saveLabel }}" tap="{{ onSaveTap }}" class="-primary" />
|
||||
<Button col="1" text="Back" tap="{{ onBackTap }}" />
|
||||
</GridLayout>
|
||||
|
||||
<ScrollView row="7" class="m-t-16">
|
||||
<ScrollView row="8" class="m-t-16">
|
||||
<Label text="{{ discoveryLog }}" textWrap="true" verticalAlignment="top" />
|
||||
</ScrollView>
|
||||
</GridLayout>
|
||||
|
||||
@@ -1,7 +1,16 @@
|
||||
import { Frame, Observable } from "@nativescript/core";
|
||||
|
||||
import { ensureBlePermissions } from "../g2/android-permissions";
|
||||
import { isValidMacAddress, loadDeviceAddresses, normalizeMacAddress, saveDeviceAddresses } from "../g2/device-addresses";
|
||||
import {
|
||||
isValidMacAddress,
|
||||
loadDeviceAddresses,
|
||||
loadPairedGlassesIdentityForAddresses,
|
||||
normalizeMacAddress,
|
||||
saveDeviceAddresses,
|
||||
type PairedGlassesIdentity,
|
||||
} from "../g2/device-addresses";
|
||||
import { glassesImagePath } from "../g2/glasses-artwork";
|
||||
import { GlassesHardwareIdentity } from "../g2/glasses-hardware-identity";
|
||||
import { buildAddressSet, DeviceDiscoveryBridge } from "../native/device-discovery";
|
||||
|
||||
type TextChangeArgs = { value?: string; object?: { text?: string } };
|
||||
@@ -15,6 +24,7 @@ export class ConfigViewModel extends Observable {
|
||||
private _status = "";
|
||||
private _discoveryLog = "";
|
||||
private _discovering = false;
|
||||
private pairedIdentity: PairedGlassesIdentity | null = null;
|
||||
|
||||
constructor(options?: { onboarding?: boolean }) {
|
||||
super();
|
||||
@@ -23,9 +33,69 @@ export class ConfigViewModel extends Observable {
|
||||
this.rightAddress = stored.right;
|
||||
this.leftAddress = stored.left;
|
||||
this.ringAddress = stored.ring;
|
||||
this.refreshIdentity();
|
||||
this.status = this.onboarding
|
||||
? "Load the addresses from the glasses you paired with the official Even app, or scan / enter them, then Continue."
|
||||
: "Edit addresses manually, or load them from paired devices or a scan.";
|
||||
? "Scan for glasses to pick yours by model and serial, load the addresses of devices paired with this phone, or enter them by hand, then Continue."
|
||||
: "Edit addresses manually, scan for glasses, or load them from paired devices.";
|
||||
}
|
||||
|
||||
// --- paired identity card --------------------------------------------------
|
||||
|
||||
/** The identity saved by the pairing scan, shown only while it still describes the entered addresses. */
|
||||
private refreshIdentity(): void {
|
||||
this.pairedIdentity = loadPairedGlassesIdentityForAddresses({
|
||||
right: this._rightAddress,
|
||||
left: this._leftAddress,
|
||||
ring: this._ringAddress,
|
||||
});
|
||||
for (const property of [
|
||||
"identityVisibility",
|
||||
"identityImagePath",
|
||||
"identityTitle",
|
||||
"identityVariant",
|
||||
"identityVariantVisibility",
|
||||
"identitySerial",
|
||||
"identityDetail",
|
||||
] as const) {
|
||||
this.notifyPropertyChange(property, this[property]);
|
||||
}
|
||||
}
|
||||
|
||||
private get decodedIdentity(): GlassesHardwareIdentity | null {
|
||||
return GlassesHardwareIdentity.decode(this.pairedIdentity?.serial);
|
||||
}
|
||||
|
||||
get identityVisibility(): "visible" | "collapse" {
|
||||
return this.pairedIdentity ? "visible" : "collapse";
|
||||
}
|
||||
|
||||
get identityImagePath(): string {
|
||||
return glassesImagePath(this.decodedIdentity);
|
||||
}
|
||||
|
||||
get identityTitle(): string {
|
||||
return this.decodedIdentity?.productName ?? "Even Realities G2";
|
||||
}
|
||||
|
||||
get identityVariant(): string {
|
||||
return this.decodedIdentity?.variantSummary ?? "";
|
||||
}
|
||||
|
||||
get identityVariantVisibility(): "visible" | "collapse" {
|
||||
return this.identityVariant ? "visible" : "collapse";
|
||||
}
|
||||
|
||||
get identitySerial(): string {
|
||||
return this.pairedIdentity ? `Serial ${this.pairedIdentity.serial}` : "";
|
||||
}
|
||||
|
||||
get identityDetail(): string {
|
||||
const identity = this.pairedIdentity;
|
||||
if (!identity) return "";
|
||||
const parts = [`Left ${identity.leftName || identity.leftAddress}`, `Right ${identity.rightName || identity.rightAddress}`];
|
||||
if (identity.ringName) parts.push(`Ring ${identity.ringName}`);
|
||||
if (identity.pairedAtMs) parts.push(`paired ${new Date(identity.pairedAtMs).toLocaleDateString()}`);
|
||||
return parts.join(" · ");
|
||||
}
|
||||
|
||||
get saveLabel(): string {
|
||||
@@ -100,10 +170,12 @@ export class ConfigViewModel extends Observable {
|
||||
|
||||
onRightAddressTextChange(args: TextChangeArgs): void {
|
||||
this.rightAddress = args.object?.text ?? args.value ?? "";
|
||||
this.refreshIdentity();
|
||||
}
|
||||
|
||||
onLeftAddressTextChange(args: TextChangeArgs): void {
|
||||
this.leftAddress = args.object?.text ?? args.value ?? "";
|
||||
this.refreshIdentity();
|
||||
}
|
||||
|
||||
onRingAddressTextChange(args: TextChangeArgs): void {
|
||||
@@ -114,8 +186,12 @@ export class ConfigViewModel extends Observable {
|
||||
await this.populateFromDiscovery(async () => this.discovery.getBondedCandidates(), "Loaded paired devices.");
|
||||
}
|
||||
|
||||
async onScanTap(): Promise<void> {
|
||||
await this.populateFromDiscovery(async () => this.discovery.scanCandidates(6000), "Scanned nearby devices.");
|
||||
/** The live scan page identifies pairs by serial, model, and distance; hand off to it. */
|
||||
onScanTap(): void {
|
||||
Frame.topmost()?.navigate({
|
||||
moduleName: "phone-ui/pairing-page",
|
||||
context: { onboarding: this.onboarding },
|
||||
});
|
||||
}
|
||||
|
||||
onBackTap(): void {
|
||||
@@ -186,6 +262,7 @@ export class ConfigViewModel extends Observable {
|
||||
if (selection.right) this.rightAddress = selection.right;
|
||||
if (selection.left) this.leftAddress = selection.left;
|
||||
if (selection.ring) this.ringAddress = selection.ring;
|
||||
this.refreshIdentity();
|
||||
this.discoveryLog = selection.summary;
|
||||
this.status = successMessage;
|
||||
} catch (error) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo" loaded="loaded" unloaded="unloaded">
|
||||
<ActionBar title="Faceclaw">
|
||||
<ActionItem text="{{ buttonLabel }}" tap="{{ onTap }}" isEnabled="{{ canRun }}" android.position="popup" />
|
||||
<ActionItem text="Pair glasses" tap="{{ onPairGlassesTap }}" isEnabled="{{ canRun }}" android.position="popup" />
|
||||
<ActionItem text="Configure devices" tap="{{ onConfigureTap }}" isEnabled="{{ canRun }}" android.position="popup" />
|
||||
<ActionItem text="Take screenshot" tap="{{ onTakeScreenshotTap }}" android.position="popup" />
|
||||
<ActionItem text="Record screen" tap="{{ onRecordScreenTap }}" android.position="popup" />
|
||||
|
||||
@@ -510,6 +510,23 @@ export class MainViewModel extends Observable {
|
||||
Frame.topmost()?.navigate("phone-ui/config-page");
|
||||
}
|
||||
|
||||
/**
|
||||
* Live scan that names each nearby pair by model, colour, and serial and
|
||||
* checks both arms belong together. A connected arm stops advertising, so
|
||||
* drop the current link first; autoConnect picks it back up afterwards.
|
||||
*/
|
||||
async onPairGlassesTap(): Promise<void> {
|
||||
if (!this.canRun) return;
|
||||
if (this.phase === "connected" || this.phase === "charging" || this.phase === "connecting") {
|
||||
try {
|
||||
await dashboardController.disconnect();
|
||||
} catch {
|
||||
// proceed anyway; the pairing page reports what it hears
|
||||
}
|
||||
}
|
||||
Frame.topmost()?.navigate({ moduleName: "phone-ui/pairing-page", context: { onboarding: false } });
|
||||
}
|
||||
|
||||
async onInstallFirmwareTap(): Promise<void> {
|
||||
await this.openFlashPage("install");
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ export class OnboardingUnpairViewModel extends Observable {
|
||||
return;
|
||||
}
|
||||
frame?.navigate({
|
||||
moduleName: "phone-ui/config-page",
|
||||
moduleName: "phone-ui/pairing-page",
|
||||
context: { onboarding: true },
|
||||
clearHistory: true,
|
||||
});
|
||||
|
||||
@@ -41,7 +41,7 @@ const STEP_CONTENT: Record<OnboardingStep, StepContent> = {
|
||||
headline: "Custom Firmware Required",
|
||||
tagline: "",
|
||||
body:
|
||||
"Faceclaw only runs on Even Realities G2 glasses that have Faceclaw's custom firmware installed. You have two choices:\n\n• Preview Only — explore Faceclaw's interface on your phone's screen without pairing any glasses. Nothing is written to a headset.\n\n• Flash Firmware — install the custom firmware on your glasses now, then use Faceclaw for real. This connects to your glasses, asks for confirmation on the lens, then downloads and prepares the firmware.\n\nFlashing replaces the official firmware. It may void your warranty and, like any firmware update, carries a risk of bricking the device. You can only be connected to one app at a time, so disconnect the official Even app before flashing (open it, go to Home, select your glasses, open Connection, and press Disconnect).",
|
||||
"Faceclaw only runs on Even Realities G2 glasses that have Faceclaw's custom firmware installed. You have two choices:\n\n• Preview Only — explore Faceclaw's interface on your phone's screen without pairing any glasses. Nothing is written to a headset.\n\n• Flash Firmware — install the custom firmware on your glasses now, then use Faceclaw for real. Faceclaw first scans for nearby glasses so you can pick yours by model, colour, and serial, then connects, asks for confirmation on the lens, and downloads and prepares the firmware.\n\nFlashing replaces the official firmware. It may void your warranty and, like any firmware update, carries a risk of bricking the device. You can only be connected to one app at a time, so disconnect the official Even app before flashing (open it, go to Home, select your glasses, open Connection, and press Disconnect).",
|
||||
primaryLabel: "Flash Firmware",
|
||||
secondaryLabel: "Preview Only",
|
||||
showLogo: false,
|
||||
@@ -67,10 +67,11 @@ export class OnboardingViewModel extends Observable {
|
||||
this.setStep(3);
|
||||
return;
|
||||
}
|
||||
// Step 3 primary: begin the flashing setup — configure device addresses,
|
||||
// then unpair the official app, then check firmware and flash.
|
||||
// Step 3 primary: begin the flashing setup — scan for and pick the glasses
|
||||
// (manual address entry is offered from that page), then unpair the
|
||||
// official app, then check firmware and flash.
|
||||
Frame.topmost()?.navigate({
|
||||
moduleName: "phone-ui/config-page",
|
||||
moduleName: "phone-ui/pairing-page",
|
||||
context: { onboarding: true },
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { NavigatedData, Page } from "@nativescript/core";
|
||||
|
||||
import { PairingViewModel } from "./pairing-view-model";
|
||||
|
||||
type PairingContext = { onboarding?: boolean } | undefined;
|
||||
|
||||
export function navigatingTo(args: NavigatedData): void {
|
||||
const page = args.object as Page;
|
||||
// Preserve the model across back-navigation (returning from the unpair or
|
||||
// manual-entry pages) so the selection isn't lost; the model restarts its
|
||||
// scan on re-entry.
|
||||
let model = page.bindingContext as PairingViewModel | undefined;
|
||||
if (!model) {
|
||||
const context = args.context as PairingContext;
|
||||
model = new PairingViewModel({ onboarding: context?.onboarding ?? false });
|
||||
page.bindingContext = model;
|
||||
}
|
||||
void model.start();
|
||||
}
|
||||
|
||||
export function navigatingFrom(args: NavigatedData): void {
|
||||
const page = args.object as Page;
|
||||
const model = page.bindingContext as PairingViewModel | undefined;
|
||||
model?.stop();
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo" navigatingFrom="navigatingFrom" actionBarHidden="{{ actionBarHidden }}">
|
||||
<ActionBar title="Pair Glasses" />
|
||||
|
||||
<GridLayout rows="auto,auto,*,auto" class="p-16">
|
||||
<StackLayout row="0">
|
||||
<Label text="{{ headline }}" class="h1 text-center" textWrap="true" />
|
||||
<Label text="{{ instructions }}" class="m-t-8 pairing-instructions" textWrap="true" />
|
||||
</StackLayout>
|
||||
|
||||
<GridLayout row="1" columns="auto,*" class="m-t-12 pairing-status-row">
|
||||
<ActivityIndicator col="0" busy="{{ scanning }}" visibility="{{ scanningVisibility }}" width="22" height="22" />
|
||||
<Label col="1" text="{{ status }}" textWrap="true" class="pairing-status" />
|
||||
</GridLayout>
|
||||
|
||||
<ScrollView row="2" class="m-t-12">
|
||||
<StackLayout>
|
||||
<Label text="Glasses" class="h2 pairing-section" visibility="{{ glassesSectionVisibility }}" />
|
||||
<Label text="{{ emptyGlassesMessage }}" class="pairing-empty" textWrap="true" visibility="{{ emptyGlassesVisibility }}" />
|
||||
<Repeater items="{{ glassesRows }}">
|
||||
<Repeater.itemsLayout>
|
||||
<StackLayout />
|
||||
</Repeater.itemsLayout>
|
||||
<Repeater.itemTemplate>
|
||||
<GridLayout columns="84,*,auto" rows="auto" class="{{ rowClass }}" tap="{{ onRowTap }}">
|
||||
<GridLayout col="0" rows="auto,auto" class="pairing-art">
|
||||
<Image row="0" src="{{ imagePath }}" stretch="aspectFit" width="80" height="30" />
|
||||
<GridLayout row="1" columns="auto,auto" horizontalAlignment="center" class="m-t-4" visibility="{{ swatchVisibility }}">
|
||||
<Label col="0" text="" width="12" height="12" borderRadius="6" backgroundColor="{{ swatchHex }}" />
|
||||
<Label col="1" text="{{ colorwayLabel }}" class="pairing-swatch-label m-l-4" />
|
||||
</GridLayout>
|
||||
</GridLayout>
|
||||
<StackLayout col="1" class="m-l-8">
|
||||
<GridLayout columns="auto,auto">
|
||||
<Label col="0" text="{{ modelTitle }}" class="pairing-title" />
|
||||
<Label col="1" text="{{ badge }}" class="pairing-badge m-l-6" visibility="{{ badgeVisibility }}" />
|
||||
</GridLayout>
|
||||
<Label text="{{ variantSummary }}" class="pairing-variant" visibility="{{ variantVisibility }}" />
|
||||
<Label text="{{ proximityLine }}" class="{{ proximityClass }}" />
|
||||
<Label text="{{ deviceName }}" class="pairing-serial" />
|
||||
<Label text="{{ armsSummary }}" class="pairing-arms" textWrap="true" />
|
||||
<Label text="{{ warning }}" class="pairing-warning" textWrap="true" visibility="{{ warningVisibility }}" />
|
||||
</StackLayout>
|
||||
<Label col="2" text="{{ chevron }}" class="pairing-chevron" verticalAlignment="center" />
|
||||
</GridLayout>
|
||||
</Repeater.itemTemplate>
|
||||
</Repeater>
|
||||
|
||||
<Label text="Ring (optional)" class="h2 pairing-section m-t-16" />
|
||||
<Label text="{{ emptyRingMessage }}" class="pairing-empty" textWrap="true" visibility="{{ emptyRingVisibility }}" />
|
||||
<Repeater items="{{ ringRows }}">
|
||||
<Repeater.itemsLayout>
|
||||
<StackLayout />
|
||||
</Repeater.itemsLayout>
|
||||
<Repeater.itemTemplate>
|
||||
<GridLayout columns="84,*,auto" rows="auto" class="{{ rowClass }}" tap="{{ onRowTap }}">
|
||||
<Image col="0" src="{{ imagePath }}" stretch="aspectFit" width="56" height="30" class="pairing-art" />
|
||||
<StackLayout col="1" class="m-l-8">
|
||||
<GridLayout columns="auto,auto">
|
||||
<Label col="0" text="{{ modelTitle }}" class="pairing-title" />
|
||||
<Label col="1" text="{{ badge }}" class="pairing-badge m-l-6" visibility="{{ badgeVisibility }}" />
|
||||
</GridLayout>
|
||||
<Label text="{{ proximityLine }}" class="{{ proximityClass }}" />
|
||||
<Label text="{{ deviceName }}" class="pairing-serial" />
|
||||
<Label text="{{ armsSummary }}" class="pairing-arms" textWrap="true" />
|
||||
<Label text="{{ warning }}" class="pairing-warning" textWrap="true" visibility="{{ warningVisibility }}" />
|
||||
</StackLayout>
|
||||
<Label col="2" text="{{ chevron }}" class="pairing-chevron" verticalAlignment="center" />
|
||||
</GridLayout>
|
||||
</Repeater.itemTemplate>
|
||||
</Repeater>
|
||||
|
||||
<StackLayout class="pairing-selection m-t-16" visibility="{{ selectionVisibility }}">
|
||||
<Label text="Selected" class="h2 pairing-section" />
|
||||
<Label text="{{ selectionSummary }}" textWrap="true" />
|
||||
</StackLayout>
|
||||
|
||||
<Label text="{{ diagnostics }}" class="pairing-diagnostics m-t-16" textWrap="true" visibility="{{ diagnosticsVisibility }}" />
|
||||
</StackLayout>
|
||||
</ScrollView>
|
||||
|
||||
<StackLayout row="3" class="m-t-12">
|
||||
<GridLayout columns="*,*">
|
||||
<Button col="0" text="{{ secondaryLabel }}" tap="{{ onSecondaryTap }}" />
|
||||
<Button col="1" text="{{ primaryLabel }}" tap="{{ onPrimaryTap }}" class="-primary" isEnabled="{{ primaryEnabled }}" />
|
||||
</GridLayout>
|
||||
<GridLayout columns="*,*" class="m-t-4">
|
||||
<Button col="0" text="{{ scanToggleLabel }}" tap="{{ onScanToggleTap }}" class="pairing-link" />
|
||||
<Button col="1" text="Enter addresses manually" tap="{{ onManualTap }}" class="pairing-link" />
|
||||
</GridLayout>
|
||||
</StackLayout>
|
||||
</GridLayout>
|
||||
</Page>
|
||||
@@ -0,0 +1,439 @@
|
||||
import { EventData, Frame, Observable, View } from "@nativescript/core";
|
||||
|
||||
import { ensureBlePermissions } from "../g2/android-permissions";
|
||||
import { loadDeviceAddresses, loadPairedGlassesIdentity, saveDeviceAddresses, savePairedGlassesIdentity } from "../g2/device-addresses";
|
||||
import {
|
||||
colorwayLabel,
|
||||
DEFAULT_STALE_AFTER_MS,
|
||||
DiscoveryAggregator,
|
||||
glassesRow,
|
||||
nearestCandidateId,
|
||||
ringRow,
|
||||
type GlassesPairCandidate,
|
||||
type PairingRowPresentation,
|
||||
type RingCandidate,
|
||||
} from "../g2/pairing-candidates";
|
||||
import { DeviceDiscoveryBridge } from "../native/device-discovery";
|
||||
import { setPreviewOnlyMode } from "./onboarding-state";
|
||||
|
||||
/** One Repeater row: the presentation plus the display-only fields the XML binds. */
|
||||
export type PairingRowItem = PairingRowPresentation & {
|
||||
rowClass: string;
|
||||
swatchVisibility: "visible" | "collapse";
|
||||
colorwayLabel: string;
|
||||
badgeVisibility: "visible" | "collapse";
|
||||
variantVisibility: "visible" | "collapse";
|
||||
proximityLine: string;
|
||||
proximityClass: string;
|
||||
warningVisibility: "visible" | "collapse";
|
||||
chevron: string;
|
||||
/**
|
||||
* Tap handler carried on the row itself. The Repeater assigns a row's
|
||||
* bindingContext before attaching it to the tree, so a `$parents['Page']`
|
||||
* binding cannot resolve on first bind and logs an error every refresh;
|
||||
* binding `tap="{{ onRowTap }}"` against the item avoids the walk entirely.
|
||||
*/
|
||||
onRowTap: (args: EventData) => void;
|
||||
};
|
||||
|
||||
const REFRESH_INTERVAL_MS = 500;
|
||||
const NO_RESULTS_HINT_AFTER_MS = 10_000;
|
||||
|
||||
/**
|
||||
* Live pairing scan. Streams advertisements into a `DiscoveryAggregator`,
|
||||
* re-renders the pair/ring lists at a calm cadence, and saves the chosen
|
||||
* addresses plus the decoded identity when the user continues.
|
||||
*
|
||||
* Selection is always a deliberate tap (no auto-select on a single result),
|
||||
* mirroring SybilSight's pairing flow: a strong signal is a hint, not consent.
|
||||
*/
|
||||
export class PairingViewModel extends Observable {
|
||||
private readonly onboarding: boolean;
|
||||
private readonly aggregator = new DiscoveryAggregator();
|
||||
private discovery: DeviceDiscoveryBridge | null = null;
|
||||
private refreshTimer: ReturnType<typeof setInterval> | null = null;
|
||||
private startedAtMs = 0;
|
||||
private advertisementCount = 0;
|
||||
private scanFailure = "";
|
||||
private readonly logLines: string[] = [];
|
||||
|
||||
private _scanning = false;
|
||||
private _status = "";
|
||||
private _glassesRows: PairingRowItem[] = [];
|
||||
private _ringRows: PairingRowItem[] = [];
|
||||
private selectedPair: GlassesPairCandidate | null = null;
|
||||
private selectedRing: RingCandidate | null = null;
|
||||
private readonly previouslyPairedSerial: string | null;
|
||||
private readonly previouslyPairedRing: string;
|
||||
|
||||
constructor(options?: { onboarding?: boolean }) {
|
||||
super();
|
||||
this.onboarding = options?.onboarding ?? false;
|
||||
this.previouslyPairedSerial = loadPairedGlassesIdentity()?.serial ?? null;
|
||||
this.previouslyPairedRing = loadDeviceAddresses().ring;
|
||||
}
|
||||
|
||||
// --- lifecycle -------------------------------------------------------------
|
||||
|
||||
async start(): Promise<void> {
|
||||
if (this._scanning) return;
|
||||
if (!global.isAndroid) {
|
||||
this.status = "Pairing is only available on Android.";
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await ensureBlePermissions();
|
||||
} catch (error) {
|
||||
this.status = this.formatError(error);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
this.discovery ??= new DeviceDiscoveryBridge();
|
||||
} catch (error) {
|
||||
this.status = this.formatError(error);
|
||||
return;
|
||||
}
|
||||
if (!this.discovery.bluetoothEnabled) {
|
||||
this.status = "Bluetooth is off. Turn it on, then tap Scan.";
|
||||
return;
|
||||
}
|
||||
this.scanFailure = "";
|
||||
this.startedAtMs = Date.now();
|
||||
const started = this.discovery.startScan({
|
||||
onAdvertisement: (raw) => {
|
||||
if (this.aggregator.ingest(raw)) this.advertisementCount += 1;
|
||||
},
|
||||
onScanFailed: (_code, message) => {
|
||||
this.scanFailure = message;
|
||||
this.scanning = false;
|
||||
this.refresh();
|
||||
},
|
||||
onLog: (line) => this.appendLog(line),
|
||||
});
|
||||
if (!started) {
|
||||
this.status = "Could not start the Bluetooth scan. Check that Bluetooth is on.";
|
||||
return;
|
||||
}
|
||||
// Bonded arms show up immediately (no signal) and gain a serial once heard.
|
||||
this.discovery.emitBondedDevices();
|
||||
this.scanning = true;
|
||||
this.refreshTimer ??= setInterval(() => this.refresh(), REFRESH_INTERVAL_MS);
|
||||
this.refresh();
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
if (this.refreshTimer) {
|
||||
clearInterval(this.refreshTimer);
|
||||
this.refreshTimer = null;
|
||||
}
|
||||
this.discovery?.stopScan();
|
||||
this.scanning = false;
|
||||
this.refresh();
|
||||
}
|
||||
|
||||
// --- observable properties -------------------------------------------------
|
||||
|
||||
get actionBarHidden(): boolean {
|
||||
return this.onboarding;
|
||||
}
|
||||
|
||||
get headline(): string {
|
||||
return this.onboarding ? "Pair Your Glasses" : "Pair Glasses";
|
||||
}
|
||||
|
||||
get instructions(): string {
|
||||
return (
|
||||
"Take the glasses out of their case (or open the lid) and keep them next to the phone. " +
|
||||
"Each arm advertises its serial; a pair is ready when both arms report the same one. " +
|
||||
"An arm connected to the official Even app stops advertising — disconnect it there first."
|
||||
);
|
||||
}
|
||||
|
||||
get scanning(): boolean {
|
||||
return this._scanning;
|
||||
}
|
||||
|
||||
set scanning(value: boolean) {
|
||||
if (this._scanning === value) return;
|
||||
this._scanning = value;
|
||||
this.notifyPropertyChange("scanning", value);
|
||||
this.notifyPropertyChange("scanningVisibility", this.scanningVisibility);
|
||||
this.notifyPropertyChange("scanToggleLabel", this.scanToggleLabel);
|
||||
}
|
||||
|
||||
get scanningVisibility(): "visible" | "collapse" {
|
||||
return this._scanning ? "visible" : "collapse";
|
||||
}
|
||||
|
||||
get scanToggleLabel(): string {
|
||||
return this._scanning ? "Pause scan" : "Scan again";
|
||||
}
|
||||
|
||||
get status(): string {
|
||||
return this._status;
|
||||
}
|
||||
|
||||
set status(value: string) {
|
||||
if (this._status === value) return;
|
||||
this._status = value;
|
||||
this.notifyPropertyChange("status", value);
|
||||
}
|
||||
|
||||
get glassesRows(): PairingRowItem[] {
|
||||
return this._glassesRows;
|
||||
}
|
||||
|
||||
get ringRows(): PairingRowItem[] {
|
||||
return this._ringRows;
|
||||
}
|
||||
|
||||
get glassesSectionVisibility(): "visible" | "collapse" {
|
||||
return "visible";
|
||||
}
|
||||
|
||||
get emptyGlassesVisibility(): "visible" | "collapse" {
|
||||
return this._glassesRows.length ? "collapse" : "visible";
|
||||
}
|
||||
|
||||
get emptyGlassesMessage(): string {
|
||||
if (this.scanFailure) return `Scan failed: ${this.scanFailure}`;
|
||||
if (!this._scanning) return "Scan paused. Tap Scan again to look for glasses.";
|
||||
const elapsed = Date.now() - this.startedAtMs;
|
||||
if (elapsed < NO_RESULTS_HINT_AFTER_MS) return "Listening for glasses…";
|
||||
return (
|
||||
"No glasses heard yet. Make sure they are out of the case and not connected to another app. " +
|
||||
"On Android 11 and older, Location must also be switched on for Bluetooth scanning to return results."
|
||||
);
|
||||
}
|
||||
|
||||
get emptyRingVisibility(): "visible" | "collapse" {
|
||||
return this._ringRows.length ? "collapse" : "visible";
|
||||
}
|
||||
|
||||
get emptyRingMessage(): string {
|
||||
return this._scanning ? "No ring heard yet. Tap the ring to wake it if you have one." : "";
|
||||
}
|
||||
|
||||
get selectionVisibility(): "visible" | "collapse" {
|
||||
return this.selectedPair || this.selectedRing ? "visible" : "collapse";
|
||||
}
|
||||
|
||||
get selectionSummary(): string {
|
||||
const parts: string[] = [];
|
||||
if (this.selectedPair) {
|
||||
const identity = this.selectedPair.identity;
|
||||
const label = identity ? identity.displayName : "Even Realities G2";
|
||||
parts.push(
|
||||
`${label} · serial ${this.selectedPair.serial ?? "unknown"}\n` +
|
||||
`Left ${this.selectedPair.left?.address ?? "?"} · Right ${this.selectedPair.right?.address ?? "?"}`,
|
||||
);
|
||||
}
|
||||
if (this.selectedRing) {
|
||||
parts.push(`Ring ${this.selectedRing.advertisement.name} · ${this.selectedRing.advertisement.address}`);
|
||||
}
|
||||
return parts.join("\n");
|
||||
}
|
||||
|
||||
get primaryLabel(): string {
|
||||
return this.onboarding ? "Continue" : "Save";
|
||||
}
|
||||
|
||||
get primaryEnabled(): boolean {
|
||||
return !!this.selectedPair || (!this.onboarding && !!this.selectedRing);
|
||||
}
|
||||
|
||||
get secondaryLabel(): string {
|
||||
return this.onboarding ? "Back" : "Cancel";
|
||||
}
|
||||
|
||||
get diagnostics(): string {
|
||||
return this.logLines.slice(-12).join("\n");
|
||||
}
|
||||
|
||||
get diagnosticsVisibility(): "visible" | "collapse" {
|
||||
return this.logLines.length ? "visible" : "collapse";
|
||||
}
|
||||
|
||||
// --- actions ---------------------------------------------------------------
|
||||
|
||||
// Arrow property: NativeScript fires XML event handlers with `this` bound to the
|
||||
// tapped view's bindingContext (the row item), not the view model.
|
||||
readonly onRowTap = (args: EventData): void => {
|
||||
const row = (args.object as View).bindingContext as PairingRowItem | undefined;
|
||||
if (!row) return;
|
||||
if (row.kind === "glasses") {
|
||||
const pair = this.aggregator.pairs().find((candidate) => candidate.id === row.id) ?? null;
|
||||
if (!pair) return;
|
||||
if (!row.canSelect) {
|
||||
this.status = row.warning || `${row.modelTitle}: ${row.armsSummary}. Both arms must be heard before pairing.`;
|
||||
return;
|
||||
}
|
||||
this.selectedPair = this.selectedPair?.id === pair.id ? null : pair;
|
||||
} else {
|
||||
const ring = this.aggregator.rings().find((candidate) => candidate.id === row.id) ?? null;
|
||||
this.selectedRing = this.selectedRing?.id === ring?.id ? null : ring;
|
||||
}
|
||||
this.refresh();
|
||||
};
|
||||
|
||||
onPrimaryTap(): void {
|
||||
const pair = this.selectedPair;
|
||||
const ring = this.selectedRing;
|
||||
if (!pair && !ring) return;
|
||||
const existing = loadDeviceAddresses();
|
||||
const addresses = {
|
||||
right: pair?.right?.address ?? existing.right,
|
||||
left: pair?.left?.address ?? existing.left,
|
||||
ring: ring?.advertisement.address ?? existing.ring,
|
||||
};
|
||||
saveDeviceAddresses(addresses);
|
||||
if (pair?.left && pair.right) {
|
||||
savePairedGlassesIdentity({
|
||||
serial: pair.serial ?? "",
|
||||
leftName: pair.left.name,
|
||||
rightName: pair.right.name,
|
||||
leftAddress: pair.left.address,
|
||||
rightAddress: pair.right.address,
|
||||
ringName: ring?.advertisement.name ?? (addresses.ring === existing.ring ? (loadPairedGlassesIdentity()?.ringName ?? "") : ""),
|
||||
ringAddress: addresses.ring,
|
||||
pairedAtMs: Date.now(),
|
||||
});
|
||||
}
|
||||
this.stop();
|
||||
if (this.onboarding) {
|
||||
setPreviewOnlyMode(false);
|
||||
// Continue the onboarding chain: unpair the official app next.
|
||||
Frame.topmost()?.navigate({ moduleName: "phone-ui/onboarding-unpair-page" });
|
||||
return;
|
||||
}
|
||||
Frame.topmost()?.navigate({ moduleName: "phone-ui/main-page", clearHistory: true });
|
||||
}
|
||||
|
||||
onSecondaryTap(): void {
|
||||
this.stop();
|
||||
const frame = Frame.topmost();
|
||||
if (frame?.canGoBack()) {
|
||||
frame.goBack();
|
||||
return;
|
||||
}
|
||||
frame?.navigate({
|
||||
moduleName: this.onboarding ? "phone-ui/onboarding-page" : "phone-ui/main-page",
|
||||
clearHistory: true,
|
||||
});
|
||||
}
|
||||
|
||||
onManualTap(): void {
|
||||
this.stop();
|
||||
Frame.topmost()?.navigate({
|
||||
moduleName: "phone-ui/config-page",
|
||||
context: { onboarding: this.onboarding },
|
||||
});
|
||||
}
|
||||
|
||||
onScanToggleTap(): void {
|
||||
if (this._scanning) {
|
||||
this.stop();
|
||||
return;
|
||||
}
|
||||
this.aggregator.clear();
|
||||
this.advertisementCount = 0;
|
||||
void this.start();
|
||||
}
|
||||
|
||||
// --- rendering -------------------------------------------------------------
|
||||
|
||||
private refresh(): void {
|
||||
this.aggregator.prune(Date.now(), DEFAULT_STALE_AFTER_MS);
|
||||
const pairs = this.aggregator.pairs();
|
||||
const rings = this.aggregator.rings();
|
||||
|
||||
// Keep the selection pointing at live data (addresses can only change if a
|
||||
// side was replaced); drop it if the pair disappeared.
|
||||
if (this.selectedPair) {
|
||||
this.selectedPair = pairs.find((pair) => pair.id === this.selectedPair!.id) ?? null;
|
||||
}
|
||||
if (this.selectedRing) {
|
||||
this.selectedRing = rings.find((ring) => ring.id === this.selectedRing!.id) ?? null;
|
||||
}
|
||||
|
||||
const nearestPair = nearestCandidateId(pairs);
|
||||
const nearestRing = nearestCandidateId(rings);
|
||||
this._glassesRows = pairs.map((pair) =>
|
||||
toRowItem(
|
||||
glassesRow(pair, { pairedSerial: this.previouslyPairedSerial, nearestId: nearestPair }),
|
||||
this.selectedPair?.id === pair.id,
|
||||
this.onRowTap,
|
||||
),
|
||||
);
|
||||
this._ringRows = rings.map((ring) =>
|
||||
toRowItem(
|
||||
ringRow(ring, { pairedRingAddress: this.previouslyPairedRing, nearestId: nearestRing }),
|
||||
this.selectedRing?.id === ring.id,
|
||||
this.onRowTap,
|
||||
),
|
||||
);
|
||||
|
||||
const complete = pairs.filter((pair) => pair.completeness === "complete").length;
|
||||
const partial = pairs.length - complete;
|
||||
if (this.scanFailure) {
|
||||
this.status = `Scan failed: ${this.scanFailure}`;
|
||||
} else if (!this._scanning) {
|
||||
this.status = pairs.length ? "Scan paused." : "Scan paused.";
|
||||
} else if (!pairs.length && !rings.length) {
|
||||
this.status = "Scanning…";
|
||||
} else {
|
||||
const bits = [
|
||||
complete ? `${complete} ${complete === 1 ? "pair" : "pairs"} ready` : null,
|
||||
partial ? `${partial} with one arm heard` : null,
|
||||
rings.length ? `${rings.length} ${rings.length === 1 ? "ring" : "rings"}` : null,
|
||||
].filter(Boolean);
|
||||
this.status = `Scanning… ${bits.join(" · ")}. Tap a pair to select it.`;
|
||||
}
|
||||
|
||||
for (const property of [
|
||||
"glassesRows",
|
||||
"ringRows",
|
||||
"emptyGlassesVisibility",
|
||||
"emptyGlassesMessage",
|
||||
"emptyRingVisibility",
|
||||
"emptyRingMessage",
|
||||
"selectionVisibility",
|
||||
"selectionSummary",
|
||||
"primaryEnabled",
|
||||
"diagnostics",
|
||||
"diagnosticsVisibility",
|
||||
] as const) {
|
||||
this.notifyPropertyChange(property, this[property]);
|
||||
}
|
||||
}
|
||||
|
||||
private appendLog(line: string): void {
|
||||
this.logLines.push(line);
|
||||
if (this.logLines.length > 50) this.logLines.splice(0, this.logLines.length - 50);
|
||||
}
|
||||
|
||||
private formatError(error: unknown): string {
|
||||
const raw = (error as Error)?.message ?? String(error);
|
||||
return raw.replace(/[\x00-\x1f]+/g, " ").replace(/\s+/g, " ").trim();
|
||||
}
|
||||
}
|
||||
|
||||
function toRowItem(row: PairingRowPresentation, selected: boolean, onRowTap: (args: EventData) => void): PairingRowItem {
|
||||
const classes = ["pairing-row"];
|
||||
if (selected) classes.push("pairing-row-selected");
|
||||
if (!row.canSelect) classes.push("pairing-row-incomplete");
|
||||
return {
|
||||
...row,
|
||||
rowClass: classes.join(" "),
|
||||
// The swatch is redundant when the variant photo already shows the finish.
|
||||
swatchVisibility: row.swatchHex && !row.hasVariantImage ? "visible" : "collapse",
|
||||
colorwayLabel: colorwayLabel(row.colorway),
|
||||
badgeVisibility: row.badge ? "visible" : "collapse",
|
||||
variantVisibility: row.variantSummary ? "visible" : "collapse",
|
||||
proximityLine: `${row.proximityGlyph} ${row.proximitySummary}`,
|
||||
proximityClass: row.zone === "immediate" ? "pairing-proximity pairing-proximity-immediate" : "pairing-proximity",
|
||||
warningVisibility: row.warning ? "visible" : "collapse",
|
||||
chevron: selected ? "✓" : row.canSelect ? "›" : "…",
|
||||
onRowTap,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user