forked from Blendman974/faceclaw
Merge branch 'bluetooth-pairing-improvements'
This commit is contained in:
commit
ca183e5aed
54 files changed
+1115
-474
No files matched your search
+101
-6
@@ -20,6 +20,15 @@ TextField {
|
||||
color: #222222;
|
||||
}
|
||||
|
||||
/* Without this, the theme's .ns-dark rules recolour the text white while the
|
||||
* white background above sticks, rendering white-on-white fields.
|
||||
* Order matters: .system-name-modal TextField must stay after this rule so the
|
||||
* deliberately light modal wins the equal-specificity tie in dark mode. */
|
||||
.ns-dark TextField {
|
||||
background-color: #2e2e2e;
|
||||
color: #f0f0f0;
|
||||
}
|
||||
|
||||
.system-name-modal TextField {
|
||||
background-color: #ffffff;
|
||||
color: #222222;
|
||||
@@ -29,6 +38,18 @@ Button.-primary {
|
||||
font-size: 18;
|
||||
}
|
||||
|
||||
/* Body/explanatory text in the onboarding flow; the theme default is too
|
||||
* small to comfortably read paragraphs of legalese, especially on tablets. */
|
||||
.body-text {
|
||||
font-size: 18;
|
||||
}
|
||||
|
||||
/* The logo art is black-on-transparent; tint it light in dark mode so it
|
||||
* doesn't vanish into the dark page background. */
|
||||
.ns-dark .onboarding-logo {
|
||||
tint-color: #e6e6e6;
|
||||
}
|
||||
|
||||
/*
|
||||
* Stands in for the lens preview when showing it would be misleading (silent
|
||||
* mode, or a disconnect explained by a flat battery). Sized by the view model
|
||||
@@ -109,6 +130,7 @@ Button.-primary {
|
||||
.pairing-title {
|
||||
font-size: 16;
|
||||
font-weight: bold;
|
||||
color: #222222;
|
||||
}
|
||||
|
||||
.pairing-badge {
|
||||
@@ -170,15 +192,88 @@ Button.-primary {
|
||||
padding: 10;
|
||||
}
|
||||
|
||||
.pairing-diagnostics {
|
||||
font-size: 11;
|
||||
color: #888888;
|
||||
font-family: monospace;
|
||||
}
|
||||
|
||||
Button.pairing-link {
|
||||
background-color: transparent;
|
||||
color: #2a5bc4;
|
||||
font-size: 14;
|
||||
border-width: 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Dark-mode pairing page. The cards keep their light-mode look above; here
|
||||
* they go dark-gray, and every text colour set above gets a light counterpart
|
||||
* so nothing renders dark-on-dark (the instructions) or dark-on-a-dark-card.
|
||||
* Order matters: the -selected/-incomplete rules must follow .pairing-row so
|
||||
* they win at equal specificity.
|
||||
*/
|
||||
.ns-dark .pairing-instructions {
|
||||
color: #b0b0b0;
|
||||
}
|
||||
|
||||
.ns-dark .pairing-empty {
|
||||
color: #999999;
|
||||
}
|
||||
|
||||
.ns-dark .pairing-row {
|
||||
background-color: #2e2e2e;
|
||||
border-color: #4a4a4a;
|
||||
}
|
||||
|
||||
.ns-dark .pairing-row-selected {
|
||||
background-color: #333c4c;
|
||||
border-color: #5b8def;
|
||||
}
|
||||
|
||||
.ns-dark .pairing-row-incomplete {
|
||||
background-color: #282828;
|
||||
border-color: #3c3c3c;
|
||||
}
|
||||
|
||||
.ns-dark .pairing-title {
|
||||
color: #f0f0f0;
|
||||
}
|
||||
|
||||
.ns-dark .pairing-badge {
|
||||
color: #a8c4f5;
|
||||
background-color: #2a3b5e;
|
||||
}
|
||||
|
||||
.ns-dark .pairing-variant {
|
||||
color: #cccccc;
|
||||
}
|
||||
|
||||
.ns-dark .pairing-proximity {
|
||||
color: #a0a0a0;
|
||||
}
|
||||
|
||||
.ns-dark .pairing-proximity-immediate {
|
||||
color: #7da7f5;
|
||||
}
|
||||
|
||||
.ns-dark .pairing-serial {
|
||||
color: #a0a0a0;
|
||||
}
|
||||
|
||||
.ns-dark .pairing-arms {
|
||||
color: #c0c0c0;
|
||||
}
|
||||
|
||||
.ns-dark .pairing-warning {
|
||||
color: #e08a66;
|
||||
}
|
||||
|
||||
.ns-dark .pairing-swatch-label {
|
||||
color: #aaaaaa;
|
||||
}
|
||||
|
||||
.ns-dark .pairing-chevron {
|
||||
color: #bbbbbb;
|
||||
}
|
||||
|
||||
.ns-dark .pairing-selection {
|
||||
background-color: #2e2e2e;
|
||||
}
|
||||
|
||||
.ns-dark Button.pairing-link {
|
||||
color: #7da7f5;
|
||||
}
|
||||
+20
-49
@@ -13,8 +13,11 @@
|
||||
*
|
||||
* `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.
|
||||
* A device that advertises its own TX power gets used as measured; everything
|
||||
* else falls back to a per-product calibration.
|
||||
* 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
|
||||
*
|
||||
@@ -25,14 +28,15 @@
|
||||
* 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. Every user-facing
|
||||
* number is therefore rounded hard, prefixed with "~" when confidence is low,
|
||||
* and paired with a coarse zone rather than being presented as a distance the
|
||||
* wearer could act on precisely.
|
||||
* 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;
|
||||
@@ -66,8 +70,6 @@ export const MAXIMUM_METERS = 100;
|
||||
*/
|
||||
export type ProximityZone = "immediate" | "near" | "far" | "distant";
|
||||
|
||||
const ZONE_ORDER: Record<ProximityZone, number> = { immediate: 0, near: 1, far: 2, distant: 3 };
|
||||
|
||||
export function zoneFromMeters(meters: number): ProximityZone {
|
||||
if (meters < 0.5) return "immediate";
|
||||
if (meters < 3) return "near";
|
||||
@@ -75,10 +77,6 @@ export function zoneFromMeters(meters: number): ProximityZone {
|
||||
return "distant";
|
||||
}
|
||||
|
||||
export function zoneRank(zone: ProximityZone): number {
|
||||
return ZONE_ORDER[zone];
|
||||
}
|
||||
|
||||
export function zoneLabel(zone: ProximityZone): string {
|
||||
switch (zone) {
|
||||
case "immediate":
|
||||
@@ -109,64 +107,37 @@ export function zoneGlyph(zone: ProximityZone): string {
|
||||
/** A distance estimate and how much to trust it. */
|
||||
export type ProximityEstimate = {
|
||||
readonly meters: number;
|
||||
/** 0…1. Drops with weak signal and with having to guess the TX power. */
|
||||
/** 0…1. Drops with weak signal. */
|
||||
readonly confidence: number;
|
||||
readonly zone: ProximityZone;
|
||||
};
|
||||
|
||||
/** "0.4 m", "~3 m". The tilde marks an estimate the reader should not lean on. */
|
||||
export function formatDistance(estimate: ProximityEstimate): string {
|
||||
const prefix = estimate.confidence < 0.6 ? "~" : "";
|
||||
const meters = estimate.meters;
|
||||
if (meters < 1) {
|
||||
return `${prefix}${Math.round(meters * 100)} cm`;
|
||||
}
|
||||
if (meters < 10) {
|
||||
return `${prefix}${meters.toFixed(1)} m`;
|
||||
}
|
||||
if (meters < MAXIMUM_METERS) {
|
||||
return `${prefix}${Math.round(meters)} m`;
|
||||
}
|
||||
return `${prefix}>${MAXIMUM_METERS} m`;
|
||||
}
|
||||
|
||||
/** "In your hand · 0.3 m" — zone first, because the zone is the trustworthy half. */
|
||||
export function proximitySummary(estimate: ProximityEstimate): string {
|
||||
return `${zoneLabel(estimate.zone)} · ${formatDistance(estimate)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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,
|
||||
txPower: number | null | undefined,
|
||||
calibration: ProximityCalibration,
|
||||
): ProximityEstimate | null {
|
||||
export function estimateProximity(rssi: number | null | undefined, calibration: ProximityCalibration): ProximityEstimate | null {
|
||||
if (rssi == null || !Number.isFinite(rssi) || rssi === 127) return null;
|
||||
const hasTxPower = txPower != null && Number.isFinite(txPower);
|
||||
const referencePower = hasTxPower ? txPower! : calibration.txPowerAtOneMeter;
|
||||
const ratio = (referencePower - rssi) / (10 * calibration.pathLossExponent);
|
||||
const meters = Math.min(Math.max(Math.pow(10, ratio), MINIMUM_METERS), MAXIMUM_METERS);
|
||||
const ratio = (calibration.txPowerAtOneMeter - rssi) / (10 * calibration.pathLossExponent);
|
||||
const meters = clamp(Math.pow(10, ratio), MINIMUM_METERS, MAXIMUM_METERS);
|
||||
return {
|
||||
meters,
|
||||
confidence: proximityConfidence(rssi, hasTxPower),
|
||||
confidence: proximityConfidence(rssi),
|
||||
zone: zoneFromMeters(meters),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Confidence falls with signal strength, because a weak sample is a noisy one,
|
||||
* and with having to assume the TX power instead of being told it.
|
||||
* 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, hasAdvertisedTxPower: boolean): number {
|
||||
let confidence = 1.0;
|
||||
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;
|
||||
confidence *= hasAdvertisedTxPower ? 1.0 : 0.85;
|
||||
return confidence;
|
||||
}
|
||||
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -27,28 +27,15 @@
|
||||
* 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";
|
||||
|
||||
export function hexToBytes(hex: string | null | undefined): Uint8Array {
|
||||
const clean = (hex ?? "").replace(/[^0-9a-fA-F]/g, "");
|
||||
const out = new Uint8Array(Math.floor(clean.length / 2));
|
||||
for (let i = 0; i < out.length; i++) {
|
||||
out[i] = parseInt(clean.substr(i * 2, 2), 16);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function bytesToHex(bytes: ArrayLike<number>): string {
|
||||
let out = "";
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
out += (bytes[i]! & 0xff).toString(16).padStart(2, "0").toUpperCase();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 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;
|
||||
@@ -136,7 +123,7 @@ export function ringNameAddressOctets(name: string | null | undefined): number[]
|
||||
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.substr(i, 2), 16));
|
||||
return [0, 2, 4].map((i) => parseInt(suffix.slice(i, i + 2), 16));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -233,20 +220,25 @@ export type EvenAdvertisement = {
|
||||
* 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.
|
||||
* 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 = /\bR1\b|EVEN R1|R1_/.test(upper);
|
||||
const looksLikeRing = /^EVEN R1([_ ]|$)/.test(upper);
|
||||
const looksLikeG2 = upper.includes("G2");
|
||||
|
||||
if (!looksLikeRing && !looksLikeG2 && !hasSignature) return null;
|
||||
|
||||
const base = {
|
||||
address: normalizeAddress(raw.address),
|
||||
address: normalizeMacAddress(raw.address),
|
||||
name,
|
||||
rssi: raw.rssi,
|
||||
txPower: raw.txPower,
|
||||
@@ -295,8 +287,19 @@ export function classifyAdvertisement(raw: RawAdvertisement): EvenAdvertisement
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeAddress(value: string | null | undefined): string {
|
||||
const compact = (value ?? "").replace(/[^0-9a-fA-F]/g, "").toUpperCase();
|
||||
/**
|
||||
* 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(":");
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -280,16 +280,32 @@ export type GlassesPairSerialVerdict =
|
||||
| { 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" };
|
||||
// Compare on the decoded serial when both decode, so an arm suffix or casing
|
||||
// difference in the reported string is not read as different hardware.
|
||||
const leftKey = GlassesHardwareIdentity.decode(l)?.serial ?? l.toUpperCase();
|
||||
const rightKey = GlassesHardwareIdentity.decode(r)?.serial ?? r.toUpperCase();
|
||||
if (leftKey !== rightKey) return { kind: "mismatched", left: l, right: r };
|
||||
return { kind: "matched", serial: leftKey };
|
||||
if (!serialsMatch(l, r)) return { kind: "mismatched", left: l, right: r };
|
||||
return { kind: "matched", serial: serialKey(l)! };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+104
-64
@@ -14,14 +14,14 @@
|
||||
import {
|
||||
estimateProximity,
|
||||
GLASSES_CALIBRATION,
|
||||
proximitySummary,
|
||||
RING_CALIBRATION,
|
||||
sortedByProximity,
|
||||
zoneGlyph,
|
||||
zoneLabel,
|
||||
type ProximityEstimate,
|
||||
type ProximityZone,
|
||||
} from "./ble-proximity";
|
||||
import { classifyAdvertisement, type EvenAdvertisement, type RawAdvertisement } from "./even-advertisement";
|
||||
import { classifyAdvertisement, normalizeMacAddress, type EvenAdvertisement, type RawAdvertisement } from "./even-advertisement";
|
||||
import { glassesImagePath, R1_IMAGE_PATH } from "./glasses-artwork";
|
||||
import {
|
||||
colorwayDisplayName,
|
||||
@@ -29,6 +29,8 @@ import {
|
||||
evaluatePairSerials,
|
||||
GlassesHardwareIdentity,
|
||||
pairSerialWarning,
|
||||
serialKey,
|
||||
serialsMatch,
|
||||
type GlassesColorway,
|
||||
} from "./glasses-hardware-identity";
|
||||
|
||||
@@ -45,9 +47,14 @@ export type GlassesPairCandidate = {
|
||||
completeness: PairCompleteness;
|
||||
/** Strongest smoothed signal across the arms that have one. */
|
||||
rssi: number | null;
|
||||
txPower: 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 = {
|
||||
@@ -84,10 +91,24 @@ export class DiscoveryAggregator {
|
||||
|
||||
/** Feed one raw advertisement. Returns the classified record, or null when ignored. */
|
||||
ingest(raw: RawAdvertisement): EvenAdvertisement | null {
|
||||
const classified = classifyAdvertisement(raw);
|
||||
let classified = classifyAdvertisement(raw);
|
||||
if (!classified) {
|
||||
if (raw.name) this.rejectedNames.add(raw.name);
|
||||
return null;
|
||||
// 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;
|
||||
@@ -109,6 +130,19 @@ export class DiscoveryAggregator {
|
||||
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;
|
||||
}
|
||||
@@ -144,7 +178,8 @@ export class DiscoveryAggregator {
|
||||
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 key = record.serial ? `serial:${record.serial}` : `arm:${record.address}`;
|
||||
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];
|
||||
@@ -162,20 +197,31 @@ export class DiscoveryAggregator {
|
||||
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;
|
||||
const txPower = strongest?.txPower ?? left?.txPower ?? right?.txPower ?? null;
|
||||
pairs.push({
|
||||
id: serial ?? `arm:${any.address}`,
|
||||
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,
|
||||
txPower,
|
||||
proximity: estimateProximity(rssi, txPower, GLASSES_CALIBRATION),
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -189,7 +235,7 @@ export class DiscoveryAggregator {
|
||||
id: record.address,
|
||||
advertisement: stripSmoothing(record),
|
||||
rssi,
|
||||
proximity: estimateProximity(rssi, record.txPower, RING_CALIBRATION),
|
||||
proximity: estimateProximity(rssi, RING_CALIBRATION),
|
||||
lastSeenMs: record.seenAtMs,
|
||||
});
|
||||
}
|
||||
@@ -205,9 +251,11 @@ function stripSmoothing(record: EvenAdvertisement & { smoothedRssi: number | nul
|
||||
/**
|
||||
* 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.
|
||||
* 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()
|
||||
@@ -221,19 +269,11 @@ export function nearestCandidateId(candidates: ReadonlyArray<{ id: string; rssi:
|
||||
|
||||
/**
|
||||
* The saved pair identity is stored as the serial, but historical values may
|
||||
* carry the `_L_1` arm suffix, so compare on the decoded serial when both
|
||||
* sides decode and fall back to a containment check when they do not.
|
||||
* 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 {
|
||||
if (!name || !pairedSerial) return false;
|
||||
const saved = pairedSerial.trim();
|
||||
if (!saved) return false;
|
||||
const left = GlassesHardwareIdentity.decode(name);
|
||||
const right = GlassesHardwareIdentity.decode(saved);
|
||||
if (left && right) return left.serial === right.serial;
|
||||
const a = name.toLowerCase();
|
||||
const b = saved.toLowerCase();
|
||||
return a.includes(b) || b.includes(a);
|
||||
return serialsMatch(name, pairedSerial);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -263,15 +303,12 @@ export type PairingRowPresentation = {
|
||||
proximitySummary: string;
|
||||
proximityGlyph: string;
|
||||
zone: ProximityZone | null;
|
||||
/** "Left + right arms found", "Only the left arm has been seen", … */
|
||||
/** "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;
|
||||
leftAddress: string;
|
||||
rightAddress: string;
|
||||
ringAddress: string;
|
||||
};
|
||||
|
||||
export type RowContext = {
|
||||
@@ -283,6 +320,29 @@ export type RowContext = {
|
||||
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);
|
||||
@@ -294,20 +354,17 @@ export function glassesRow(pair: GlassesPairCandidate, context: RowContext = {})
|
||||
const rightNote = pair.right?.note;
|
||||
if (leftNote) warnings.push(`Left arm: ${leftNote}.`);
|
||||
if (rightNote) warnings.push(`Right arm: ${rightNote}.`);
|
||||
if (pair.left?.embeddedMacMismatch) {
|
||||
warnings.push(`Left arm's advertised address ${pair.left.embeddedMac} differs from its radio address ${pair.left.address}.`);
|
||||
}
|
||||
if (pair.right?.embeddedMacMismatch) {
|
||||
warnings.push(`Right arm's advertised address ${pair.right.embeddedMac} differs from its radio address ${pair.right.address}.`);
|
||||
}
|
||||
const verdict = evaluatePairSerials(pair.left?.serial, pair.right?.serial);
|
||||
const mismatch = pairSerialWarning(verdict);
|
||||
if (mismatch) warnings.push(mismatch);
|
||||
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":
|
||||
armsSummary = verdict.kind === "matched" ? "Left + right arms found · serials match" : "Left + right arms found";
|
||||
// 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";
|
||||
@@ -328,30 +385,20 @@ export function glassesRow(pair: GlassesPairCandidate, context: RowContext = {})
|
||||
swatchHex: identity?.colorway ? colorwaySwatchHex(identity.colorway) : null,
|
||||
imagePath,
|
||||
hasVariantImage: !!identity?.imageAssetName,
|
||||
isNearest,
|
||||
isPreviouslyPaired: isPreviouslyPairedRow,
|
||||
badge: isPreviouslyPairedRow ? "Yours" : isNearest ? "Closest" : "",
|
||||
proximitySummary: pair.proximity ? proximitySummary(pair.proximity) : "Signal unknown",
|
||||
proximityGlyph: pair.proximity ? zoneGlyph(pair.proximity.zone) : "○○○○",
|
||||
zone: pair.proximity?.zone ?? null,
|
||||
...presentationBase(pair.proximity, isNearest, isPreviouslyPairedRow, warnings),
|
||||
armsSummary,
|
||||
warning: warnings.join(" "),
|
||||
canSelect: pair.completeness === "complete" && verdict.kind !== "mismatched",
|
||||
leftAddress: pair.left?.address ?? "",
|
||||
rightAddress: pair.right?.address ?? "",
|
||||
ringAddress: "",
|
||||
canSelect: pair.completeness === "complete",
|
||||
};
|
||||
}
|
||||
|
||||
export function ringRow(ring: RingCandidate, context: RowContext = {}): PairingRowPresentation {
|
||||
const ad = ring.advertisement;
|
||||
const isPaired = !!context.pairedRingAddress && context.pairedRingAddress.toUpperCase() === ad.address;
|
||||
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}.`);
|
||||
if (ad.embeddedMacMismatch) {
|
||||
warnings.push(`The ring's advertised address ${ad.embeddedMac} differs from its radio address ${ad.address}.`);
|
||||
}
|
||||
const macWarning = embeddedMacMismatchWarning("The ring's", ad);
|
||||
if (macWarning) warnings.push(macWarning);
|
||||
return {
|
||||
id: ring.id,
|
||||
kind: "ring",
|
||||
@@ -362,18 +409,11 @@ export function ringRow(ring: RingCandidate, context: RowContext = {}): PairingR
|
||||
swatchHex: null,
|
||||
imagePath: R1_IMAGE_PATH,
|
||||
hasVariantImage: true,
|
||||
isNearest,
|
||||
isPreviouslyPaired: isPaired,
|
||||
badge: isPaired ? "Yours" : isNearest ? "Closest" : "",
|
||||
proximitySummary: ring.proximity ? proximitySummary(ring.proximity) : "Signal unknown",
|
||||
proximityGlyph: ring.proximity ? zoneGlyph(ring.proximity.zone) : "○○○○",
|
||||
zone: ring.proximity?.zone ?? null,
|
||||
armsSummary: ad.bonded ? "Paired with this phone" : "Advertising",
|
||||
warning: warnings.join(" "),
|
||||
...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,
|
||||
leftAddress: "",
|
||||
rightAddress: "",
|
||||
ringAddress: ad.address,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 20 KiB |
@@ -1,6 +1,7 @@
|
||||
import { Utils } from "@nativescript/core";
|
||||
|
||||
import { classifyAdvertisement, type RawAdvertisement } from "../g2/even-advertisement";
|
||||
import { type RawAdvertisement } from "../g2/even-advertisement";
|
||||
import { DiscoveryAggregator } from "../g2/pairing-candidates";
|
||||
|
||||
declare const com: any;
|
||||
|
||||
@@ -80,13 +81,16 @@ export class DeviceDiscoveryBridge {
|
||||
/**
|
||||
* Collect advertisements for `timeoutMs` without blocking the UI thread
|
||||
* (scan callbacks are delivered on the main looper, so a blocking sleep
|
||||
* there would starve them). Latest sample per address wins.
|
||||
* there would starve them). Every sample is kept: Android can split one
|
||||
* advertisement across reports (name in one, manufacturer data in another),
|
||||
* so "latest per address" would drop the informative half — the aggregator
|
||||
* in `buildAddressSet` merges them instead.
|
||||
*/
|
||||
scanCandidates(timeoutMs = 6000): Promise<RawAdvertisement[]> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const latest = new Map<string, RawAdvertisement>();
|
||||
const samples: RawAdvertisement[] = [];
|
||||
const started = this.startScan({
|
||||
onAdvertisement: (raw) => latest.set(raw.address, raw),
|
||||
onAdvertisement: (raw) => samples.push(raw),
|
||||
onScanFailed: (code, message) => {
|
||||
this.stopScan();
|
||||
reject(new Error(`Bluetooth scan failed: ${message} (${code})`));
|
||||
@@ -98,7 +102,7 @@ export class DeviceDiscoveryBridge {
|
||||
}
|
||||
setTimeout(() => {
|
||||
this.stopScan();
|
||||
resolve(Array.from(latest.values()));
|
||||
resolve(samples);
|
||||
}, Math.max(500, timeoutMs));
|
||||
});
|
||||
}
|
||||
@@ -106,24 +110,48 @@ export class DeviceDiscoveryBridge {
|
||||
|
||||
/**
|
||||
* Pick one address per role from a batch of raw advertisements — the manual
|
||||
* address page's "load" helper. The latest-seen device of each role wins;
|
||||
* the summary names the serial where one was advertised.
|
||||
* address page's "load" helper and the flash flow's address resolution.
|
||||
*
|
||||
* Runs the batch through the same `DiscoveryAggregator` the pairing page
|
||||
* uses, so left/right come from ONE serial-joined pair (the closest complete
|
||||
* one) rather than from whichever arm of whatever pair advertised last —
|
||||
* "latest per role" silently welded together arms of two different pairs.
|
||||
* When no arm carries a serial at all (a bonded-device listing has no
|
||||
* manufacturer data), there is nothing to join on and the latest arm per side
|
||||
* is used as before.
|
||||
*/
|
||||
export function buildAddressSet(candidates: RawAdvertisement[]): DiscoveredAddressSet {
|
||||
const classified = candidates.map(classifyAdvertisement).filter((item): item is NonNullable<typeof item> => !!item);
|
||||
const latestForRole = new Map<"left" | "right" | "ring", (typeof classified)[number]>();
|
||||
for (const candidate of classified) {
|
||||
const incumbent = latestForRole.get(candidate.role);
|
||||
if (!incumbent || incumbent.seenAtMs <= candidate.seenAtMs) latestForRole.set(candidate.role, candidate);
|
||||
const aggregator = new DiscoveryAggregator();
|
||||
for (const raw of candidates) aggregator.ingest(raw);
|
||||
const classified = aggregator.advertisements();
|
||||
const pairs = aggregator.pairs();
|
||||
|
||||
let left = "";
|
||||
let right = "";
|
||||
const completePair = pairs.find((pair) => pair.completeness === "complete");
|
||||
if (completePair) {
|
||||
left = completePair.left!.address;
|
||||
right = completePair.right!.address;
|
||||
} else if (classified.every((candidate) => !candidate.serial)) {
|
||||
for (const role of ["left", "right"] as const) {
|
||||
const latest = classified
|
||||
.filter((candidate) => candidate.role === role)
|
||||
.sort((a, b) => b.seenAtMs - a.seenAtMs)[0];
|
||||
if (role === "left") left = latest?.address ?? "";
|
||||
else right = latest?.address ?? "";
|
||||
}
|
||||
}
|
||||
// Arms with serials but no complete pair: leave the addresses empty. The
|
||||
// summary below names what was heard; guessing would defeat the serial join.
|
||||
|
||||
const lines = classified.map((candidate) => {
|
||||
const extras = [candidate.serial ? `serial ${candidate.serial}` : null, candidate.rssi != null ? `${candidate.rssi} dBm` : null].filter(Boolean);
|
||||
return `${candidate.role}: ${candidate.name} ${candidate.address}${extras.length ? ` (${extras.join(", ")})` : ""}`;
|
||||
});
|
||||
return {
|
||||
left: latestForRole.get("left")?.address ?? "",
|
||||
right: latestForRole.get("right")?.address ?? "",
|
||||
ring: latestForRole.get("ring")?.address ?? "",
|
||||
left,
|
||||
right,
|
||||
ring: aggregator.rings()[0]?.advertisement.address ?? "",
|
||||
summary: lines.length ? lines.join("\n") : "No matching devices found.",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ export type DeviceInfo = {
|
||||
capabilities: string;
|
||||
};
|
||||
|
||||
export type DeviceInfoState = "connecting" | "querying";
|
||||
export type DeviceInfoState = "connecting" | "authenticating" | "querying";
|
||||
|
||||
/**
|
||||
* TS wrapper around the native FaceclawDeviceInfoProbe — a one-shot,
|
||||
@@ -25,11 +25,11 @@ export class DeviceInfoProbe {
|
||||
private resolveFn: ((info: DeviceInfo) => void) | null = null;
|
||||
private rejectFn: ((error: Error) => void) | null = null;
|
||||
|
||||
constructor(rightAddress: string) {
|
||||
constructor(rightAddress: string, leftAddress = "") {
|
||||
const context = Utils.android.getApplicationContext();
|
||||
if (!context) throw new Error("Android application context unavailable");
|
||||
|
||||
this.probe = new com.faceclaw.app.FaceclawDeviceInfoProbe(context, rightAddress);
|
||||
this.probe = new com.faceclaw.app.FaceclawDeviceInfoProbe(context, rightAddress, leftAddress);
|
||||
this.listenerProxy = new com.faceclaw.app.FaceclawDeviceInfoProbeListener({
|
||||
onLog: (line: string) => this.emit(this.logListeners, String(line)),
|
||||
onState: (state: string, detail: string) =>
|
||||
|
||||
@@ -10,6 +10,9 @@ export type FlashProgress = {
|
||||
componentCount: number;
|
||||
blockIndex: number;
|
||||
blockCount: number;
|
||||
/** Bytes flashed so far across the whole lens image — the size-weighted progress signal. */
|
||||
bytesSent: number;
|
||||
bytesTotal: number;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -42,6 +45,8 @@ export class FirmwareFlasher {
|
||||
componentCount: number,
|
||||
blockIndex: number,
|
||||
blockCount: number,
|
||||
bytesSent: number,
|
||||
bytesTotal: number,
|
||||
) =>
|
||||
this.emit(this.progressListeners, {
|
||||
lens: String(lens),
|
||||
@@ -49,6 +54,8 @@ export class FirmwareFlasher {
|
||||
componentCount: Number(componentCount),
|
||||
blockIndex: Number(blockIndex),
|
||||
blockCount: Number(blockCount),
|
||||
bytesSent: Number(bytesSent),
|
||||
bytesTotal: Number(bytesTotal),
|
||||
}),
|
||||
onState: (state: string, detail: string) =>
|
||||
this.emit(this.stateListeners, String(state) as FlashState, String(detail ?? "")),
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<ActionBar title="Configure Devices" />
|
||||
|
||||
<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" />
|
||||
<Label row="0" text="Configure the MAC addresses for the G2 headset arms and optional R1 ring. This page does not test a connection." class="body-text" textWrap="true" />
|
||||
|
||||
<GridLayout row="1" columns="96,*" class="pairing-row m-t-12" visibility="{{ identityVisibility }}">
|
||||
<Image col="0" src="{{ identityImagePath }}" stretch="aspectFit" width="90" height="34" />
|
||||
@@ -34,11 +34,11 @@
|
||||
<Button col="1" text="Scan for glasses" tap="{{ onScanTap }}" class="-primary" isEnabled="{{ canDiscover }}" />
|
||||
</GridLayout>
|
||||
|
||||
<Label row="6" text="{{ status }}" class="m-t-16" textWrap="true" />
|
||||
<Label row="6" text="{{ status }}" class="body-text m-t-16" textWrap="true" />
|
||||
|
||||
<GridLayout row="7" columns="*,*" class="m-t-16">
|
||||
<Button col="0" text="{{ saveLabel }}" tap="{{ onSaveTap }}" class="-primary" />
|
||||
<Button col="1" text="Back" tap="{{ onBackTap }}" />
|
||||
<Button col="0" text="Back" tap="{{ onBackTap }}" />
|
||||
<Button col="1" text="{{ saveLabel }}" tap="{{ onSaveTap }}" class="-primary" />
|
||||
</GridLayout>
|
||||
|
||||
<ScrollView row="8" class="m-t-16">
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
import { glassesImagePath } from "../g2/glasses-artwork";
|
||||
import { GlassesHardwareIdentity } from "../g2/glasses-hardware-identity";
|
||||
import { buildAddressSet, DeviceDiscoveryBridge } from "../native/device-discovery";
|
||||
import { formatErrorMessage } from "../util/format-error";
|
||||
|
||||
type TextChangeArgs = { value?: string; object?: { text?: string } };
|
||||
|
||||
@@ -187,7 +188,23 @@ export class ConfigViewModel extends Observable {
|
||||
}
|
||||
|
||||
/** The live scan page identifies pairs by serial, model, and distance; hand off to it. */
|
||||
onScanTap(): void {
|
||||
async onScanTap(): Promise<void> {
|
||||
if (!this.onboarding) {
|
||||
// A connected arm stops advertising, so drop the link before scanning.
|
||||
// Required lazily: a module-scope import would instantiate the dashboard
|
||||
// controller singleton during onboarding, which this page is part of.
|
||||
// Outside onboarding the main page has already loaded it.
|
||||
const { dashboardController } = require("../g2/dashboard-controller") as typeof import("../g2/dashboard-controller");
|
||||
const { resumeAutoReconnect } = require("../g2/reconnect-policy") as typeof import("../g2/reconnect-policy");
|
||||
try {
|
||||
await dashboardController.disconnect();
|
||||
} catch {
|
||||
// proceed anyway; the pairing page reports what it hears
|
||||
}
|
||||
// disconnect() enters the manual-disconnected state; pairing is a
|
||||
// detour, so let the main page reconnect afterwards.
|
||||
resumeAutoReconnect();
|
||||
}
|
||||
Frame.topmost()?.navigate({
|
||||
moduleName: "phone-ui/pairing-page",
|
||||
context: { onboarding: this.onboarding },
|
||||
@@ -273,7 +290,6 @@ export class ConfigViewModel extends Observable {
|
||||
}
|
||||
|
||||
private formatError(error: unknown): string {
|
||||
const raw = (error as Error)?.message ?? String(error);
|
||||
return raw.replace(/[\x00-\x1f]+/g, " ").replace(/\s+/g, " ").trim();
|
||||
return formatErrorMessage(error);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import { Application, Frame, ImageSource, Observable, Screen } from "@nativescript/core";
|
||||
import { dashboardController } from "../g2/dashboard-controller";
|
||||
import { isValidMacAddress, loadDeviceAddresses } from "../g2/device-addresses";
|
||||
import { isAutoReconnectSuppressed } from "../g2/reconnect-policy";
|
||||
import { isAutoReconnectSuppressed, resumeAutoReconnect } from "../g2/reconnect-policy";
|
||||
import { formatErrorMessage } from "../util/format-error";
|
||||
import { G2_LENS_HEIGHT, G2_LENS_WIDTH } from "../graphics/image";
|
||||
|
||||
const LENS_ASPECT_RATIO = G2_LENS_WIDTH / G2_LENS_HEIGHT;
|
||||
@@ -486,7 +487,10 @@ export class MainViewModel extends Observable {
|
||||
/**
|
||||
* 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.
|
||||
* drop the current link first. disconnect() enters the manual-disconnected
|
||||
* state; pairing is a detour, not a Disconnect, so lift the suppression
|
||||
* right away — nothing dials the glasses until the main page's autoConnect
|
||||
* runs again on the way back.
|
||||
*/
|
||||
async onPairGlassesTap(): Promise<void> {
|
||||
if (!this.canRun) return;
|
||||
@@ -496,6 +500,7 @@ export class MainViewModel extends Observable {
|
||||
} catch {
|
||||
// proceed anyway; the pairing page reports what it hears
|
||||
}
|
||||
resumeAutoReconnect();
|
||||
}
|
||||
Frame.topmost()?.navigate({ moduleName: "phone-ui/pairing-page", context: { onboarding: false } });
|
||||
}
|
||||
@@ -596,9 +601,6 @@ export class MainViewModel extends Observable {
|
||||
}
|
||||
|
||||
private formatError(error: unknown): string {
|
||||
const raw = (error as Error)?.message ?? String(error);
|
||||
const sanitized = raw.replace(/[\x00-\x1f]+/g, " ").replace(/\s+/g, " ").trim();
|
||||
if (sanitized.length <= 240) return sanitized;
|
||||
return `${sanitized.slice(0, 237)}...`;
|
||||
return formatErrorMessage(error, 240);
|
||||
}
|
||||
}
|
||||
@@ -4,13 +4,20 @@
|
||||
<StackLayout>
|
||||
<Label text="{{ headline }}" class="h1 text-center m-t-24" textWrap="true" />
|
||||
<ActivityIndicator busy="{{ busy }}" visibility="{{ busyVisibility }}" class="m-t-16" />
|
||||
<Label text="{{ status }}" class="m-t-16 text-center" textWrap="true" />
|
||||
<Label text="{{ status }}" class="body-text m-t-16 text-center" textWrap="true" />
|
||||
</StackLayout>
|
||||
</ScrollView>
|
||||
|
||||
<GridLayout row="1" columns="*,*" class="m-t-20">
|
||||
<Button col="0" text="{{ secondaryLabel }}" tap="{{ onSecondaryTap }}" visibility="{{ secondaryVisibility }}" />
|
||||
<Button col="1" text="{{ primaryLabel }}" tap="{{ onPrimaryTap }}" visibility="{{ primaryVisibility }}" class="-primary" />
|
||||
</GridLayout>
|
||||
<StackLayout row="1" class="m-t-20">
|
||||
<!-- Error-only escape hatches: flash anyway, or trust that the custom firmware is present. -->
|
||||
<GridLayout columns="*,*" visibility="{{ errorActionsVisibility }}">
|
||||
<Button col="0" text="Install" tap="{{ onInstallTap }}" />
|
||||
<Button col="1" text="Skip" tap="{{ onSkipTap }}" />
|
||||
</GridLayout>
|
||||
<GridLayout columns="*,*">
|
||||
<Button col="0" text="{{ secondaryLabel }}" tap="{{ onSecondaryTap }}" visibility="{{ secondaryVisibility }}" />
|
||||
<Button col="1" text="{{ primaryLabel }}" tap="{{ onPrimaryTap }}" visibility="{{ primaryVisibility }}" class="-primary" />
|
||||
</GridLayout>
|
||||
</StackLayout>
|
||||
</GridLayout>
|
||||
</Page>
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
import { classifyOnboardingFirmware, FLASHABLE_STOCK_VERSION_TEXT } from "../g2/firmware-compat";
|
||||
import { DeviceInfoProbe, DeviceInfoState } from "../native/device-info-probe";
|
||||
import { setOnboardingCompleted, setPreviewOnlyMode } from "./onboarding-state";
|
||||
import { formatErrorMessage } from "../util/format-error";
|
||||
|
||||
type CheckPhase = "checking" | "fonts" | "custom" | "flashable" | "newer" | "error";
|
||||
|
||||
@@ -94,6 +95,10 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
|
||||
return this._phase === "custom" || this._phase === "fonts" ? "collapse" : "visible";
|
||||
}
|
||||
|
||||
get errorActionsVisibility(): "visible" | "collapse" {
|
||||
return this._phase === "error" ? "visible" : "collapse";
|
||||
}
|
||||
|
||||
// --- button handlers -------------------------------------------------------
|
||||
|
||||
onPrimaryTap(): void {
|
||||
@@ -123,6 +128,20 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
|
||||
frame?.navigate({ moduleName: "phone-ui/onboarding-unpair-page", clearHistory: true });
|
||||
}
|
||||
|
||||
/** Escape hatch when the check itself fails: flash as if stock firmware had been detected. */
|
||||
onInstallTap(): void {
|
||||
if (this._phase !== "error") return;
|
||||
this.goToFlashing();
|
||||
}
|
||||
|
||||
/** Escape hatch when the check itself fails: continue as if compatible custom firmware had been detected. */
|
||||
onSkipTap(): void {
|
||||
if (this._phase !== "error") return;
|
||||
// Same path as a real "custom" classification, so the phone-side G2 fonts
|
||||
// still get extracted when they're missing.
|
||||
this.applyClassification("custom", "", "");
|
||||
}
|
||||
|
||||
// --- probe flow ------------------------------------------------------------
|
||||
|
||||
private async check(): Promise<void> {
|
||||
@@ -144,7 +163,7 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
|
||||
}
|
||||
|
||||
this.disposeProbe();
|
||||
const probe = new DeviceInfoProbe(stored.right);
|
||||
const probe = new DeviceInfoProbe(stored.right, stored.left);
|
||||
this.probeInstance = probe;
|
||||
probe.onStateChange((state) => this.reportProbeState(state));
|
||||
|
||||
@@ -162,6 +181,9 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
|
||||
private reportProbeState(state: DeviceInfoState): void {
|
||||
if (state === "connecting") {
|
||||
this.status = "Connecting to your glasses...";
|
||||
} else if (state === "authenticating") {
|
||||
// First-time connections pair here; the OS may show a Bluetooth dialog.
|
||||
this.status = "Authenticating with your glasses... If Android asks to pair, tap Pair.";
|
||||
} else if (state === "querying") {
|
||||
this.status = "Reading the firmware version...";
|
||||
}
|
||||
@@ -285,6 +307,7 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
|
||||
this.notifyPropertyChange("secondaryLabel", this.secondaryLabel);
|
||||
this.notifyPropertyChange("primaryVisibility", this.primaryVisibility);
|
||||
this.notifyPropertyChange("secondaryVisibility", this.secondaryVisibility);
|
||||
this.notifyPropertyChange("errorActionsVisibility", this.errorActionsVisibility);
|
||||
}
|
||||
|
||||
private disposeProbe(): void {
|
||||
@@ -299,7 +322,6 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
|
||||
}
|
||||
|
||||
private formatError(error: unknown): string {
|
||||
const raw = (error as Error)?.message ?? String(error);
|
||||
return raw.replace(/[\x00-\x1f]+/g, " ").replace(/\s+/g, " ").trim();
|
||||
return formatErrorMessage(error);
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
<Label text="{{ headline }}" class="h1 text-center m-t-24" textWrap="true" />
|
||||
<ActivityIndicator busy="{{ busy }}" visibility="{{ busyVisibility }}" class="m-t-16" />
|
||||
<Progress value="{{ progress }}" maxValue="100" visibility="{{ progressVisibility }}" class="m-t-16" />
|
||||
<Label text="{{ status }}" class="m-t-16 text-center" textWrap="true" />
|
||||
<Label text="{{ status }}" class="body-text m-t-16 text-center" textWrap="true" />
|
||||
<Label text="{{ log }}" class="m-t-24" textWrap="true" fontSize="12" visibility="{{ logVisibility }}" />
|
||||
</StackLayout>
|
||||
</ScrollView>
|
||||
|
||||
@@ -17,6 +17,7 @@ import { FirmwareFlasher, FlashProgress, FlashState } from "../native/firmware-f
|
||||
import { FlashPromptCommunicator, FlashPromptState } from "../native/flash-prompt-communicator";
|
||||
import { resumeAutoReconnect, suppressAutoReconnect } from "../g2/reconnect-policy";
|
||||
import { setOnboardingCompleted, setPreviewOnlyMode } from "./onboarding-state";
|
||||
import { formatErrorMessage } from "../util/format-error";
|
||||
|
||||
type FlashPhase = "intro" | "prompt" | "building" | "ready" | "flashing" | "flashed" | "error";
|
||||
|
||||
@@ -421,11 +422,9 @@ export class OnboardingFlashViewModel extends Observable {
|
||||
|
||||
private handleFlashProgress(progress: FlashProgress): void {
|
||||
const lensIndex = progress.lens === "right" ? 1 : 0;
|
||||
const withinLens =
|
||||
progress.componentCount > 0
|
||||
? (progress.componentIndex - 1 + (progress.blockCount > 0 ? progress.blockIndex / progress.blockCount : 0)) /
|
||||
progress.componentCount
|
||||
: 0;
|
||||
// Weight by bytes, not by component index: the image is one large segment
|
||||
// plus several small ones, so per-component steps move wildly unevenly.
|
||||
const withinLens = progress.bytesTotal > 0 ? Math.min(1, progress.bytesSent / progress.bytesTotal) : 0;
|
||||
this.progress = ((lensIndex + withinLens) / 2) * 100;
|
||||
this.status =
|
||||
`Flashing ${progress.lens} lens — part ${progress.componentIndex}/${progress.componentCount}, ` +
|
||||
@@ -566,7 +565,6 @@ export class OnboardingFlashViewModel extends Observable {
|
||||
}
|
||||
|
||||
private formatError(error: unknown): string {
|
||||
const raw = (error as Error)?.message ?? String(error);
|
||||
return raw.replace(/[\x00-\x1f]+/g, " ").replace(/\s+/g, " ").trim();
|
||||
return formatErrorMessage(error);
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,15 @@
|
||||
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo" actionBarHidden="true">
|
||||
<GridLayout rows="*,auto" class="p-20">
|
||||
<ScrollView row="0">
|
||||
<StackLayout row="0" verticalAlignment="middle" visibility="{{ splashVisibility }}">
|
||||
<Label text="{{ headline }}" class="h1 text-center" textWrap="true" />
|
||||
<Label text="{{ tagline }}" class="body-text text-center m-t-8" textWrap="true" />
|
||||
<Image src="~/images/faceclaw-logo.png" stretch="aspectFit" height="{{ logoHeight }}" horizontalAlignment="center" class="onboarding-logo m-t-24" />
|
||||
</StackLayout>
|
||||
|
||||
<ScrollView row="0" visibility="{{ contentVisibility }}">
|
||||
<StackLayout>
|
||||
<Image src="res://logo" stretch="aspectFit" height="140" horizontalAlignment="center" visibility="{{ logoVisibility }}" class="m-t-24" />
|
||||
<Label text="{{ headline }}" class="h1 text-center m-t-24" textWrap="true" />
|
||||
<Label text="{{ tagline }}" class="text-center m-t-8" textWrap="true" visibility="{{ taglineVisibility }}" />
|
||||
<Label text="{{ body }}" class="m-t-24" textWrap="true" />
|
||||
<Label text="{{ body }}" class="body-text m-t-24" textWrap="true" />
|
||||
</StackLayout>
|
||||
</ScrollView>
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<Label text="Disconnect the Even App" class="h1 text-center m-t-24" textWrap="true" />
|
||||
<Label
|
||||
text="Faceclaw and the official Even Realities app can't both be connected to the glasses at once. Before continuing, open the Even app, go to Home, select your glasses, open the Connection submenu, and press Disconnect (or turn off the Even app's Bluetooth)."
|
||||
class="m-t-24" textWrap="true" />
|
||||
class="body-text m-t-24" textWrap="true" />
|
||||
<Button text="Open Even App Settings" tap="{{ onOpenEvenAppSettingsTap }}" class="-primary m-t-24" />
|
||||
</StackLayout>
|
||||
</ScrollView>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Frame, Observable } from "@nativescript/core";
|
||||
import { Frame, Observable, Screen } from "@nativescript/core";
|
||||
|
||||
import { setOnboardingCompleted, setPreviewOnlyMode } from "./onboarding-state";
|
||||
|
||||
@@ -10,8 +10,8 @@ type StepContent = {
|
||||
body: string;
|
||||
primaryLabel: string;
|
||||
secondaryLabel: string;
|
||||
showLogo: boolean;
|
||||
showTagline: boolean;
|
||||
/** Step 1 renders as the vertically-centered splash (headline + tagline + logo) instead of the scrolling body. */
|
||||
splash: boolean;
|
||||
showSecondary: boolean;
|
||||
};
|
||||
|
||||
@@ -22,8 +22,7 @@ const STEP_CONTENT: Record<OnboardingStep, StepContent> = {
|
||||
body: "",
|
||||
primaryLabel: "Next",
|
||||
secondaryLabel: "",
|
||||
showLogo: true,
|
||||
showTagline: true,
|
||||
splash: true,
|
||||
showSecondary: false,
|
||||
},
|
||||
2: {
|
||||
@@ -33,8 +32,7 @@ const STEP_CONTENT: Record<OnboardingStep, StepContent> = {
|
||||
"This unofficial software provides a custom user interface and functionality for the Even Realities G2 smart glasses. It is not created or supported by Even Realities. If this software somehow breaks my headset, this is not Even's fault and is not covered by the hardware's warranty. If this software doesn't break my headset, using this software may void the hardware's warranty anyways, at the sole discretion of Even Realities. This software is a development prototype and may not be relied on for anything important. This software may be broken at any time by software or firmware updates created by Even, and this will not be Even's fault.",
|
||||
primaryLabel: "Agree",
|
||||
secondaryLabel: "Back",
|
||||
showLogo: false,
|
||||
showTagline: false,
|
||||
splash: false,
|
||||
showSecondary: true,
|
||||
},
|
||||
3: {
|
||||
@@ -44,8 +42,7 @@ const STEP_CONTENT: Record<OnboardingStep, StepContent> = {
|
||||
"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,
|
||||
showTagline: false,
|
||||
splash: false,
|
||||
showSecondary: true,
|
||||
},
|
||||
};
|
||||
@@ -112,24 +109,25 @@ export class OnboardingViewModel extends Observable {
|
||||
return STEP_CONTENT[this._step].secondaryLabel;
|
||||
}
|
||||
|
||||
get showLogo(): boolean {
|
||||
return STEP_CONTENT[this._step].showLogo;
|
||||
}
|
||||
|
||||
get showTagline(): boolean {
|
||||
return STEP_CONTENT[this._step].showTagline;
|
||||
}
|
||||
|
||||
get showSecondary(): boolean {
|
||||
return STEP_CONTENT[this._step].showSecondary;
|
||||
}
|
||||
|
||||
get logoVisibility(): "visible" | "collapse" {
|
||||
return this.showLogo ? "visible" : "collapse";
|
||||
get splashVisibility(): "visible" | "collapse" {
|
||||
return STEP_CONTENT[this._step].splash ? "visible" : "collapse";
|
||||
}
|
||||
|
||||
get taglineVisibility(): "visible" | "collapse" {
|
||||
return this.showTagline ? "visible" : "collapse";
|
||||
get contentVisibility(): "visible" | "collapse" {
|
||||
return STEP_CONTENT[this._step].splash ? "collapse" : "visible";
|
||||
}
|
||||
|
||||
/**
|
||||
* The logo scales with the screen (~40% of its height) so it reads as a
|
||||
* splash on tablets too, capped near the source PNG's height so it doesn't
|
||||
* upscale into mush.
|
||||
*/
|
||||
get logoHeight(): number {
|
||||
return Math.min(480, Math.round(Screen.mainScreen.heightDIPs * 0.4));
|
||||
}
|
||||
|
||||
get secondaryVisibility(): "visible" | "collapse" {
|
||||
@@ -148,11 +146,9 @@ export class OnboardingViewModel extends Observable {
|
||||
this.notifyPropertyChange("body", this.body);
|
||||
this.notifyPropertyChange("primaryLabel", this.primaryLabel);
|
||||
this.notifyPropertyChange("secondaryLabel", this.secondaryLabel);
|
||||
this.notifyPropertyChange("showLogo", this.showLogo);
|
||||
this.notifyPropertyChange("showTagline", this.showTagline);
|
||||
this.notifyPropertyChange("showSecondary", this.showSecondary);
|
||||
this.notifyPropertyChange("logoVisibility", this.logoVisibility);
|
||||
this.notifyPropertyChange("taglineVisibility", this.taglineVisibility);
|
||||
this.notifyPropertyChange("splashVisibility", this.splashVisibility);
|
||||
this.notifyPropertyChange("contentVisibility", this.contentVisibility);
|
||||
this.notifyPropertyChange("secondaryVisibility", this.secondaryVisibility);
|
||||
}
|
||||
}
|
||||
@@ -21,5 +21,12 @@ export function navigatingTo(args: NavigatedData): void {
|
||||
export function navigatingFrom(args: NavigatedData): void {
|
||||
const page = args.object as Page;
|
||||
const model = page.bindingContext as PairingViewModel | undefined;
|
||||
model?.stop();
|
||||
// Backing out destroys the page; a forward navigation (manual entry) keeps
|
||||
// it on the stack, so only pause the scan and keep the model's app-lifecycle
|
||||
// hooks for the return trip.
|
||||
if (args.isBackNavigation) {
|
||||
model?.dispose();
|
||||
} else {
|
||||
model?.stop();
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@
|
||||
|
||||
<ScrollView row="2" class="m-t-12">
|
||||
<StackLayout>
|
||||
<Label text="Glasses" class="h2 pairing-section" visibility="{{ glassesSectionVisibility }}" />
|
||||
<Label text="Glasses" class="h2 pairing-section" />
|
||||
<Label text="{{ emptyGlassesMessage }}" class="pairing-empty" textWrap="true" visibility="{{ emptyGlassesVisibility }}" />
|
||||
<Repeater items="{{ glassesRows }}">
|
||||
<Repeater.itemsLayout>
|
||||
@@ -37,7 +37,7 @@
|
||||
<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="{{ armsSummary }}" class="pairing-arms" textWrap="true" visibility="{{ armsVisibility }}" />
|
||||
<Label text="{{ warning }}" class="pairing-warning" textWrap="true" visibility="{{ warningVisibility }}" />
|
||||
</StackLayout>
|
||||
<Label col="2" text="{{ chevron }}" class="pairing-chevron" verticalAlignment="center" />
|
||||
@@ -61,7 +61,7 @@
|
||||
</GridLayout>
|
||||
<Label text="{{ proximityLine }}" class="{{ proximityClass }}" />
|
||||
<Label text="{{ deviceName }}" class="pairing-serial" />
|
||||
<Label text="{{ armsSummary }}" class="pairing-arms" textWrap="true" />
|
||||
<Label text="{{ armsSummary }}" class="pairing-arms" textWrap="true" visibility="{{ armsVisibility }}" />
|
||||
<Label text="{{ warning }}" class="pairing-warning" textWrap="true" visibility="{{ warningVisibility }}" />
|
||||
</StackLayout>
|
||||
<Label col="2" text="{{ chevron }}" class="pairing-chevron" verticalAlignment="center" />
|
||||
@@ -73,8 +73,6 @@
|
||||
<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>
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { EventData, Frame, Observable, View } from "@nativescript/core";
|
||||
import { Application, EventData, Frame, Observable, View } from "@nativescript/core";
|
||||
|
||||
import { ensureBlePermissions } from "../g2/android-permissions";
|
||||
import { loadDeviceAddresses, loadPairedGlassesIdentity, saveDeviceAddresses, savePairedGlassesIdentity } from "../g2/device-addresses";
|
||||
import { formatErrorMessage } from "../util/format-error";
|
||||
import {
|
||||
colorwayLabel,
|
||||
DEFAULT_STALE_AFTER_MS,
|
||||
@@ -25,6 +26,7 @@ export type PairingRowItem = PairingRowPresentation & {
|
||||
variantVisibility: "visible" | "collapse";
|
||||
proximityLine: string;
|
||||
proximityClass: string;
|
||||
armsVisibility: "visible" | "collapse";
|
||||
warningVisibility: "visible" | "collapse";
|
||||
chevron: string;
|
||||
/**
|
||||
@@ -55,7 +57,6 @@ export class PairingViewModel extends Observable {
|
||||
private startedAtMs = 0;
|
||||
private advertisementCount = 0;
|
||||
private scanFailure = "";
|
||||
private readonly logLines: string[] = [];
|
||||
|
||||
private _scanning = false;
|
||||
private _status = "";
|
||||
@@ -71,10 +72,38 @@ export class PairingViewModel extends Observable {
|
||||
this.onboarding = options?.onboarding ?? false;
|
||||
this.previouslyPairedSerial = loadPairedGlassesIdentity()?.serial ?? null;
|
||||
this.previouslyPairedRing = loadDeviceAddresses().ring;
|
||||
// A backgrounded phone (Home, screen lock, a call) must not keep the
|
||||
// low-latency scan and the refresh timer burning; pick both back up when
|
||||
// the app returns.
|
||||
Application.on(Application.suspendEvent, this.onAppSuspend);
|
||||
Application.on(Application.resumeEvent, this.onAppResume);
|
||||
}
|
||||
|
||||
// --- lifecycle -------------------------------------------------------------
|
||||
|
||||
private resumeScanAfterSuspend = false;
|
||||
|
||||
private readonly onAppSuspend = (): void => {
|
||||
if (this._scanning) {
|
||||
this.resumeScanAfterSuspend = true;
|
||||
this.stop();
|
||||
}
|
||||
};
|
||||
|
||||
private readonly onAppResume = (): void => {
|
||||
if (this.resumeScanAfterSuspend) {
|
||||
this.resumeScanAfterSuspend = false;
|
||||
void this.start();
|
||||
}
|
||||
};
|
||||
|
||||
/** Final teardown when the page is left for good (not a detour to manual entry). */
|
||||
dispose(): void {
|
||||
this.stop();
|
||||
Application.off(Application.suspendEvent, this.onAppSuspend);
|
||||
Application.off(Application.resumeEvent, this.onAppResume);
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
if (this._scanning) return;
|
||||
if (!global.isAndroid) {
|
||||
@@ -108,7 +137,6 @@ export class PairingViewModel extends Observable {
|
||||
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.";
|
||||
@@ -187,10 +215,6 @@ export class PairingViewModel extends Observable {
|
||||
return this._ringRows;
|
||||
}
|
||||
|
||||
get glassesSectionVisibility(): "visible" | "collapse" {
|
||||
return "visible";
|
||||
}
|
||||
|
||||
get emptyGlassesVisibility(): "visible" | "collapse" {
|
||||
return this._glassesRows.length ? "collapse" : "visible";
|
||||
}
|
||||
@@ -246,14 +270,6 @@ export class PairingViewModel extends Observable {
|
||||
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
|
||||
@@ -280,26 +296,41 @@ export class PairingViewModel extends Observable {
|
||||
const pair = this.selectedPair;
|
||||
const ring = this.selectedRing;
|
||||
if (!pair && !ring) return;
|
||||
// refresh() drops a selection whose pair regressed below complete, but the
|
||||
// tap can race a prune: never fall back to previously stored addresses for
|
||||
// a missing arm — that silently welds together arms of two different pairs.
|
||||
if (pair && (!pair.left || !pair.right)) return;
|
||||
const existing = loadDeviceAddresses();
|
||||
const addresses = {
|
||||
right: pair?.right?.address ?? existing.right,
|
||||
left: pair?.left?.address ?? existing.left,
|
||||
right: pair ? pair.right!.address : existing.right,
|
||||
left: pair ? pair.left!.address : existing.left,
|
||||
ring: ring?.advertisement.address ?? existing.ring,
|
||||
};
|
||||
saveDeviceAddresses(addresses);
|
||||
if (pair?.left && pair.right) {
|
||||
if (pair) {
|
||||
savePairedGlassesIdentity({
|
||||
serial: pair.serial ?? "",
|
||||
leftName: pair.left.name,
|
||||
rightName: pair.right.name,
|
||||
leftAddress: pair.left.address,
|
||||
rightAddress: pair.right.address,
|
||||
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(),
|
||||
});
|
||||
} else if (ring) {
|
||||
// Replacing just the ring: keep the stored glasses identity current so
|
||||
// the config page doesn't keep naming the old ring.
|
||||
const identity = loadPairedGlassesIdentity();
|
||||
if (identity) {
|
||||
savePairedGlassesIdentity({
|
||||
...identity,
|
||||
ringName: ring.advertisement.name,
|
||||
ringAddress: ring.advertisement.address,
|
||||
});
|
||||
}
|
||||
}
|
||||
this.stop();
|
||||
this.dispose();
|
||||
if (this.onboarding) {
|
||||
setPreviewOnlyMode(false);
|
||||
// Continue the onboarding chain: unpair the official app next.
|
||||
@@ -310,7 +341,7 @@ export class PairingViewModel extends Observable {
|
||||
}
|
||||
|
||||
onSecondaryTap(): void {
|
||||
this.stop();
|
||||
this.dispose();
|
||||
const frame = Frame.topmost();
|
||||
if (frame?.canGoBack()) {
|
||||
frame.goBack();
|
||||
@@ -348,9 +379,12 @@ export class PairingViewModel extends Observable {
|
||||
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.
|
||||
// side was replaced); drop it if the pair disappeared — or if it degraded
|
||||
// below complete (an arm went back in the case), so Save can never write a
|
||||
// one-armed selection padded with stale addresses.
|
||||
if (this.selectedPair) {
|
||||
this.selectedPair = pairs.find((pair) => pair.id === this.selectedPair!.id) ?? null;
|
||||
const live = pairs.find((pair) => pair.id === this.selectedPair!.id) ?? null;
|
||||
this.selectedPair = live?.completeness === "complete" ? live : null;
|
||||
}
|
||||
if (this.selectedRing) {
|
||||
this.selectedRing = rings.find((ring) => ring.id === this.selectedRing!.id) ?? null;
|
||||
@@ -378,7 +412,7 @@ export class PairingViewModel extends Observable {
|
||||
if (this.scanFailure) {
|
||||
this.status = `Scan failed: ${this.scanFailure}`;
|
||||
} else if (!this._scanning) {
|
||||
this.status = pairs.length ? "Scan paused." : "Scan paused.";
|
||||
this.status = "Scan paused.";
|
||||
} else if (!pairs.length && !rings.length) {
|
||||
this.status = "Scanning…";
|
||||
} else {
|
||||
@@ -400,21 +434,13 @@ export class PairingViewModel extends Observable {
|
||||
"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();
|
||||
return formatErrorMessage(error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -432,6 +458,7 @@ function toRowItem(row: PairingRowPresentation, selected: boolean, onRowTap: (ar
|
||||
variantVisibility: row.variantSummary ? "visible" : "collapse",
|
||||
proximityLine: `${row.proximityGlyph} ${row.proximitySummary}`,
|
||||
proximityClass: row.zone === "immediate" ? "pairing-proximity pairing-proximity-immediate" : "pairing-proximity",
|
||||
armsVisibility: row.armsSummary ? "visible" : "collapse",
|
||||
warningVisibility: row.warning ? "visible" : "collapse",
|
||||
chevron: selected ? "✓" : row.canSelect ? "›" : "…",
|
||||
onRowTap,
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* One-line error text safe for a status label: control characters stripped,
|
||||
* whitespace collapsed, optionally truncated. Shared by the view models so a
|
||||
* fix to error rendering lands everywhere at once.
|
||||
*/
|
||||
export function formatErrorMessage(error: unknown, maxLength?: number): string {
|
||||
const raw = (error as Error)?.message ?? String(error);
|
||||
const sanitized = raw.replace(/[\x00-\x1f]+/g, " ").replace(/\s+/g, " ").trim();
|
||||
if (maxLength != null && sanitized.length > maxLength) {
|
||||
return `${sanitized.slice(0, Math.max(0, maxLength - 3))}...`;
|
||||
}
|
||||
return sanitized;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Hex ⇄ byte helpers shared by the advertisement parsers and the firmware
|
||||
* builder. Pure (no NativeScript imports) so it can run under node tests.
|
||||
*/
|
||||
|
||||
/** Lenient decode: non-hex characters (separators, whitespace) are stripped first. */
|
||||
export function hexToBytes(hex: string | null | undefined): Uint8Array {
|
||||
const clean = (hex ?? "").replace(/[^0-9a-fA-F]/g, "");
|
||||
const out = new Uint8Array(Math.floor(clean.length / 2));
|
||||
for (let i = 0; i < out.length; i++) {
|
||||
out[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function bytesToHex(bytes: ArrayLike<number>): string {
|
||||
let out = "";
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
out += (bytes[i]! & 0xff).toString(16).padStart(2, "0").toUpperCase();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
Reference in new issue
Block a user