This commit is contained in:
James Babcock committed 2026-08-24 00:19:07 -07:00
commit fa241161e4
35 files changed
+3309 -140

No files matched your search

+203
View File
@@ -0,0 +1,203 @@
/**
* How far away an advertising device probably is, from its signal strength.
*
* Ported from SybilSight's `BLEProximity.swift` (itself from ProLink's
* `PeripheralInfo.basicEstimatedDistance`), with the calibration table
* narrowed to the two products this app pairs.
*
* ## The model
*
* The log-distance path loss model:
*
* RSSI = txPower - 10 · n · log₁₀(d) ⇒ d = 10 ^ ((txPower - RSSI) / (10 · n))
*
* `txPower` is the expected signal at one metre and `n` the path loss
* exponent — 2.0 in free space, higher indoors where walls and bodies absorb.
* A device that advertises its own TX power gets used as measured; everything
* else falls back to a per-product calibration.
*
* ## What this is for, and what it is not
*
* It exists so a pairing list can be ordered by "which of these is in my
* hand", and so a row can say roughly how far away its device is. That is a
* ranking problem, and RSSI ordering is far more trustworthy than RSSI
* magnitude — the ordering survives calibration error that would put the
* absolute numbers metres out.
*
* It is **not** a measurement. A hand over the temple, a pocket, or a body
* between phone and glasses moves the estimate by metres. 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.
*
* This module is pure (no NativeScript imports) so it can run under node tests.
*/
/** Expected RSSI at one metre, and the path loss exponent, per product. */
export type ProximityCalibration = {
readonly txPowerAtOneMeter: number;
readonly pathLossExponent: number;
};
/**
* Even Realities G2. Two temple radios on a head, usually held or worn
* indoors, so the exponent sits above free space. Verified only as a ranking
* input — see the module note.
*/
export const GLASSES_CALIBRATION: ProximityCalibration = { txPowerAtOneMeter: -62, pathLossExponent: 2.2 };
/**
* Even Realities R1. A ring antenna is smaller and more easily shadowed by a
* hand, so it reads weaker at the same distance than the glasses do.
*/
export const RING_CALIBRATION: ProximityCalibration = { txPowerAtOneMeter: -68, pathLossExponent: 2.3 };
/**
* Estimates below this are indistinguishable from "touching the phone", and
* above it from "somewhere else entirely". Clamping keeps a noisy sample from
* rendering as 0.001 m.
*/
export const MINIMUM_METERS = 0.1;
export const MAXIMUM_METERS = 100;
/**
* Coarse buckets. The wearer is being asked "is this the pair in your hand?",
* and a bucket answers that better than a number they might over-trust.
*/
export type ProximityZone = "immediate" | "near" | "far" | "distant";
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";
if (meters < 10) return "far";
return "distant";
}
export function zoneRank(zone: ProximityZone): number {
return ZONE_ORDER[zone];
}
export function zoneLabel(zone: ProximityZone): string {
switch (zone) {
case "immediate":
return "In your hand";
case "near":
return "Nearby";
case "far":
return "Across the room";
case "distant":
return "Far away";
}
}
/** A glyph for the zone; SF Symbols have no Android equivalent, so plain text. */
export function zoneGlyph(zone: ProximityZone): string {
switch (zone) {
case "immediate":
return "●●●●";
case "near":
return "●●●○";
case "far":
return "●●○○";
case "distant":
return "●○○○";
}
}
/** A distance estimate and how much to trust it. */
export type ProximityEstimate = {
readonly meters: number;
/** 0…1. Drops with weak signal and with having to guess the TX power. */
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 {
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);
return {
meters,
confidence: proximityConfidence(rssi, hasTxPower),
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.
*/
export function proximityConfidence(rssi: number, hasAdvertisedTxPower: boolean): number {
let confidence = 1.0;
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;
}
/**
* Order a list closest-first.
*
* Items whose signal never arrived sort last rather than being dropped: a pair
* that cannot be ranked is still a pair the wearer may need to choose, and
* hiding it would be worse than showing it at the bottom. Ties break on the
* stable id so the list does not reshuffle between scan passes — a list that
* reorders under the finger is how the wrong device gets tapped, which is the
* whole failure this ordering exists to prevent.
*/
export function sortedByProximity<T>(
items: readonly T[],
estimate: (item: T) => ProximityEstimate | null,
id: (item: T) => string,
): T[] {
return items.slice().sort((lhs, rhs) => {
const left = estimate(lhs);
const right = estimate(rhs);
if (left && right) {
if (left.meters !== right.meters) return left.meters < right.meters ? -1 : 1;
return compareIds(id(lhs), id(rhs));
}
if (left && !right) return -1;
if (!left && right) return 1;
return compareIds(id(lhs), id(rhs));
});
}
function compareIds(a: string, b: string): number {
return a < b ? -1 : a > b ? 1 : 0;
}
+78
View File
@@ -50,3 +50,81 @@ export function isValidMacAddress(value: string, allowEmpty = false): boolean {
}
return /^[0-9A-F]{2}(?::[0-9A-F]{2}){5}$/.test(normalizeMacAddress(trimmed));
}
// ---------------------------------------------------------------------------
// Paired-glasses identity
// ---------------------------------------------------------------------------
/**
* What the pairing scan learned about the pair whose addresses were saved, so
* later screens can name and picture the exact glasses without a connection.
* Kept separate from the addresses so hand-entered MACs keep working.
*/
export type PairedGlassesIdentity = {
/** The 14-character serial both arms advertised (pair identity). */
serial: string;
leftName: string;
rightName: string;
leftAddress: string;
rightAddress: string;
/** Ring local name ("EVEN R1_B56EE2"), when a ring was chosen from the scan. */
ringName: string;
ringAddress: string;
pairedAtMs: number;
};
const IDENTITY_KEYS = {
serial: "deviceIdentity.serial",
leftName: "deviceIdentity.leftName",
rightName: "deviceIdentity.rightName",
leftAddress: "deviceIdentity.leftAddress",
rightAddress: "deviceIdentity.rightAddress",
ringName: "deviceIdentity.ringName",
ringAddress: "deviceIdentity.ringAddress",
pairedAtMs: "deviceIdentity.pairedAtMs",
} as const;
export function loadPairedGlassesIdentity(): PairedGlassesIdentity | null {
const serial = ApplicationSettings.getString(IDENTITY_KEYS.serial, "").trim();
if (!serial) return null;
return {
serial,
leftName: ApplicationSettings.getString(IDENTITY_KEYS.leftName, ""),
rightName: ApplicationSettings.getString(IDENTITY_KEYS.rightName, ""),
leftAddress: normalizeMacAddress(ApplicationSettings.getString(IDENTITY_KEYS.leftAddress, "")),
rightAddress: normalizeMacAddress(ApplicationSettings.getString(IDENTITY_KEYS.rightAddress, "")),
ringName: ApplicationSettings.getString(IDENTITY_KEYS.ringName, ""),
ringAddress: normalizeMacAddress(ApplicationSettings.getString(IDENTITY_KEYS.ringAddress, "")),
pairedAtMs: ApplicationSettings.getNumber(IDENTITY_KEYS.pairedAtMs, 0),
};
}
export function savePairedGlassesIdentity(identity: PairedGlassesIdentity): void {
ApplicationSettings.setString(IDENTITY_KEYS.serial, identity.serial.trim().toUpperCase());
ApplicationSettings.setString(IDENTITY_KEYS.leftName, identity.leftName);
ApplicationSettings.setString(IDENTITY_KEYS.rightName, identity.rightName);
ApplicationSettings.setString(IDENTITY_KEYS.leftAddress, normalizeMacAddress(identity.leftAddress));
ApplicationSettings.setString(IDENTITY_KEYS.rightAddress, normalizeMacAddress(identity.rightAddress));
ApplicationSettings.setString(IDENTITY_KEYS.ringName, identity.ringName);
ApplicationSettings.setString(IDENTITY_KEYS.ringAddress, normalizeMacAddress(identity.ringAddress));
ApplicationSettings.setNumber(IDENTITY_KEYS.pairedAtMs, identity.pairedAtMs);
}
export function clearPairedGlassesIdentity(): void {
for (const key of Object.values(IDENTITY_KEYS)) {
ApplicationSettings.remove(key);
}
}
/**
* The saved identity only describes the saved addresses. If the user later
* hand-edits an arm's MAC to something else, the serial no longer applies —
* report null rather than a stale name for a different pair.
*/
export function loadPairedGlassesIdentityForAddresses(addresses: DeviceAddresses): PairedGlassesIdentity | null {
const identity = loadPairedGlassesIdentity();
if (!identity) return null;
if (identity.leftAddress !== normalizeMacAddress(addresses.left)) return null;
if (identity.rightAddress !== normalizeMacAddress(addresses.right)) return null;
return identity;
}
+302
View File
@@ -0,0 +1,302 @@
/**
* Parsers for what Even Realities hardware puts in a BLE advertisement.
*
* Ported from SybilSight's SDK (`extractSN` / `extractMac` /
* `extractG2AdvertisementFlag` in `G2.swift`, and `ringMacWireBytes` /
* `ringNameAddressOctets` in `R1.swift`).
*
* ## G2 temple (confirmed by HCI capture)
*
* Manufacturer-specific AD record: `45 52` + SN(14, ASCII) + MAC(6, little-endian) + flag(1).
* The `45 52` ("ER") bytes sit in the company-identifier field, which Android
* parses as little-endian uint16 `0x5245`. Both arms of a pair advertise the
* SAME serial; that is the pair identity. The local name is
* `Even G2_<token>_<L|R>_<hex6>` where the trailing hex is the last three
* bytes of THAT ARM's address — per-arm, NOT a pair id. One arm's name
* predicts nothing about the other's.
*
* ## R1 ring
*
* `45 52` + MAC(6, wire order) and, on ring firmware 2.2.7.x, further bytes
* after the MAC (observed live: the ASCII device-serial suffix, e.g. "140137").
* The local name is `EVEN R1_<hex6>` where the hex is the last three octets
* of the human-order MAC. Anchor on the marker and, when the name carries the
* conventional suffix, require the candidate MAC to reproduce it — a naive
* `suffix(6)` slice once captured serial digits as the ring identity.
*
* This module is pure (no NativeScript imports) so it can run under node tests.
*/
/** 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;
}
/**
* Extract the serial number from G2 manufacturer data.
* Layout: "ER"(2) + SN(14) + MAC(6, LE) + flag(1). Null when too short or when
* the 14 bytes are not printable ASCII (control bytes are stripped, as the
* SDK does, but a result that then fails to look like a serial is rejected).
*/
export function extractG2Serial(mfg: Uint8Array): string | null {
if (mfg.length < 16) return null;
let serial = "";
for (let i = 2; i < 16; i++) {
const byte = mfg[i]!;
if (byte <= 0x1f || byte === 0x7f) continue;
if (byte > 0x7e) return null;
serial += String.fromCharCode(byte);
}
return serial.length ? serial : null;
}
/**
* Extract the BLE MAC from G2 manufacturer data.
* Layout: "ER"(2) + SN(14) + MAC(6, little-endian) + flag(1).
* Returns "AA:BB:CC:DD:EE:FF" (big-endian, colon-separated).
*/
export function extractG2Mac(mfg: Uint8Array): string | null {
if (mfg.length < 22) return null;
return humanReadableAddressFromWireBytes(mfg.subarray(16, 22));
}
/** Preserve the final G2 manufacturer-data byte without guessing its meaning. */
export function extractG2AdvertisementFlag(mfg: Uint8Array): number | null {
if (mfg.length < 23 || !hasEvenManufacturerSignature(mfg)) return null;
return mfg[22]!;
}
/**
* Which side a G2 temple advertisement belongs to, from the local name.
* Null when the name carries neither or both markers.
*/
export function g2SideFromName(name: string | null | undefined): "left" | "right" | null {
if (!name) return null;
const upper = name.toUpperCase();
const isLeft = upper.includes("_L_");
const isRight = upper.includes("_R_");
if (isLeft === isRight) return null;
return isLeft ? "left" : "right";
}
/** "Even G2_32_L_ACD458" → "ACD458"; null when the name does not end in 6 hex digits. */
export function g2NameAddressTail(name: string | null | undefined): string | null {
if (!name) return null;
const match = /_([0-9A-F]{6})\s*$/i.exec(name);
return match ? match[1]!.toUpperCase() : null;
}
/**
* Even's wire order is reversed human order: "AA:BB:CC:DD:EE:FF" ⇄ [FF EE DD CC BB AA].
*/
export function wireBytesFromHumanReadableAddress(address: string): Uint8Array | null {
const cleaned = address.replace(/[:\-]/g, "").trim();
if (cleaned.length !== 12 || !/^[0-9a-fA-F]{12}$/.test(cleaned)) return null;
const human = hexToBytes(cleaned);
return new Uint8Array(Array.from(human).reverse());
}
export function humanReadableAddressFromWireBytes(bytes: Uint8Array): string | null {
if (bytes.length !== 6) return null;
return Array.from(bytes)
.reverse()
.map((b) => b.toString(16).padStart(2, "0").toUpperCase())
.join(":");
}
/**
* The conventional R1 local name ("EVEN R1_B56EE2") ends in the human-order
* MAC's last three octets. Returns those octets when the name carries a
* parseable 6-hex-digit suffix. A bare ring id ("B56EE2") is accepted too.
*/
export function ringNameAddressOctets(name: string | null | undefined): number[] | null {
if (!name) return null;
const marker = name.indexOf("R1_");
const suffix = (marker >= 0 ? name.slice(marker + 3) : name).trim();
if (suffix.length !== 6 || !/^[0-9a-fA-F]{6}$/.test(suffix)) return null;
return [0, 2, 4].map((i) => parseInt(suffix.substr(i, 2), 16));
}
/**
* A wire-order candidate is reversed(human), so its bytes [2],[1],[0] must
* equal the name suffix octets in order for the candidate to belong to the
* named ring.
*/
export function wireBytesMatchNameOctets(wire: ArrayLike<number>, nameOctets: number[]): boolean {
return wire.length === 6 && nameOctets.length === 3 && wire[2] === nameOctets[0] && wire[1] === nameOctets[1] && wire[0] === nameOctets[2];
}
/**
* Extract the ring's wire-order MAC from its manufacturer data, validated
* against the advertised name when the name is verifiable. Fails closed
* (null) when the name is verifiable and no 6-byte window reproduces it.
*/
export function ringMacWireBytes(mfg: Uint8Array, localName: string | null | undefined): Uint8Array | null {
if (mfg.length < 6) return null;
const markerAnchored = mfg.length >= 8 && hasEvenManufacturerSignature(mfg) ? mfg.subarray(2, 8) : null;
const nameOctets = ringNameAddressOctets(localName);
if (!nameOctets) {
// No verifiable name: prefer the documented marker layout, else legacy suffix.
return new Uint8Array(markerAnchored ?? mfg.subarray(mfg.length - 6));
}
if (markerAnchored && wireBytesMatchNameOctets(markerAnchored, nameOctets)) {
return new Uint8Array(markerAnchored);
}
for (let start = 0; start + 6 <= mfg.length; start++) {
const window = mfg.subarray(start, start + 6);
if (wireBytesMatchNameOctets(window, nameOctets)) return new Uint8Array(window);
}
return null;
}
/**
* Ring firmware 2.2.7.x appends the ASCII serial suffix after the MAC. Return
* it when present (digits/uppercase letters only) so the row can show it.
*/
export function extractRingSerialSuffix(mfg: Uint8Array): string | null {
if (!hasEvenManufacturerSignature(mfg) || mfg.length <= 8) return null;
let text = "";
for (let i = 8; i < mfg.length; i++) {
const byte = mfg[i]!;
if (byte < 0x30 || byte > 0x5a) return null;
text += String.fromCharCode(byte);
}
return text.length ? text : null;
}
// ---------------------------------------------------------------------------
// Classification of a raw advertisement
// ---------------------------------------------------------------------------
/** What the Java scanner hands up: one advertisement (or one bonded device). */
export type RawAdvertisement = {
address: string;
/** Live local name from the scan record, falling back to the cached device name. */
name: string;
/** Full manufacturer-specific data including the 2-byte company id, as hex. Empty when absent. */
manufacturerData: string;
rssi: number | null;
txPower: number | null;
connectable: boolean | null;
bonded: boolean;
source: "scan" | "paired";
seenAtMs: number;
};
/** One advertisement after the protocol knowledge has been applied. */
export type EvenAdvertisement = {
address: string;
name: string;
role: EvenDeviceRole;
/** G2: the 14-char pair serial. Ring: null (the ring's serial suffix is `ringSerialSuffix`). */
serial: string | null;
/** The address embedded in the manufacturer data, when present. Should equal `address`. */
embeddedMac: string | null;
/** True when the embedded MAC disagrees with the address the radio reported. */
embeddedMacMismatch: boolean;
flag: number | null;
ringSerialSuffix: string | null;
rssi: number | null;
txPower: number | null;
connectable: boolean | null;
bonded: boolean;
source: "scan" | "paired";
seenAtMs: number;
manufacturerData: string;
/** Why an otherwise Even-looking advertisement could not be fully parsed. */
note: string | null;
};
/**
* Classify a raw advertisement. Returns null for anything that is not an Even
* Realities G2 temple or R1 ring. Admission mirrors the SDK: stock names
* contain "G2"/"R1", but renamed firmware may not, so the "ER" manufacturer
* signature is an equally strong admission path.
*/
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 looksLikeG2 = upper.includes("G2");
if (!looksLikeRing && !looksLikeG2 && !hasSignature) return null;
const base = {
address: normalizeAddress(raw.address),
name,
rssi: raw.rssi,
txPower: raw.txPower,
connectable: raw.connectable,
bonded: raw.bonded,
source: raw.source,
seenAtMs: raw.seenAtMs,
manufacturerData: raw.manufacturerData ?? "",
};
if (looksLikeRing) {
const wire = mfg.length >= 6 ? ringMacWireBytes(mfg, name) : null;
const embeddedMac = wire ? humanReadableAddressFromWireBytes(wire) : null;
return {
...base,
role: "ring",
serial: null,
embeddedMac,
embeddedMacMismatch: !!embeddedMac && embeddedMac !== base.address,
flag: null,
ringSerialSuffix: extractRingSerialSuffix(mfg),
note: mfg.length >= 6 && !wire ? "advertisement carried no name-consistent MAC window" : null,
};
}
const side = g2SideFromName(name);
if (!side) {
// A G2-signature advertisement with no side marker cannot be placed in a pair.
return null;
}
const serial = mfg.length >= 16 ? extractG2Serial(mfg) : null;
const embeddedMac = extractG2Mac(mfg);
let note: string | null = null;
if (mfg.length === 0) note = "no manufacturer data (serial unknown)";
else if (mfg.length < 16) note = `manufacturer data too short (${mfg.length} bytes); cannot extract a serial`;
else if (!serial) note = "could not extract a serial from the manufacturer data";
return {
...base,
role: side,
serial,
embeddedMac,
embeddedMacMismatch: !!embeddedMac && embeddedMac !== base.address,
flag: extractG2AdvertisementFlag(mfg),
ringSerialSuffix: null,
note,
};
}
export function normalizeAddress(value: string | null | undefined): string {
const compact = (value ?? "").replace(/[^0-9a-fA-F]/g, "").toUpperCase();
if (compact.length !== 12) return (value ?? "").trim().toUpperCase();
return compact.match(/.{2}/g)!.join(":");
}
+42
View File
@@ -0,0 +1,42 @@
/**
* Product artwork for Even Realities hardware, keyed by the decoded serial.
*
* Ported from SybilSight's `SybilSightAssets.glassesAssetName(for:identity:)`.
* Prefer the photo of the exact SKU the serial decoded to, and fall back to
* the generic product shot. Every surface that draws "the user's glasses"
* should route through this — once the pair is known, showing brown Frame B
* for a grey Frame A pair is a small lie the wearer will notice immediately.
*
* The PNGs live under `app/images/glasses/` (copied from SybilSight's asset
* catalog; six SKU crops at 600×196 on a shared bounding box so they render at
* the same scale, plus the generic G2 and R1 product shots). NativeScript
* resolves `~/` to the app folder for `<Image src>`.
*
* This module is pure (no NativeScript imports) so it can run under node tests.
*/
import { BUNDLED_VARIANT_ASSET_NAMES, type GlassesHardwareIdentity } from "./glasses-hardware-identity";
export const GLASSES_IMAGE_DIR = "~/images/glasses";
/** Generic Even G2 product shot, used before the serial is known or for SKUs without art. */
export const GENERIC_G2_IMAGE_PATH = `${GLASSES_IMAGE_DIR}/even_realities_g2.png`;
/** Even R1 ring product shot. */
export const R1_IMAGE_PATH = `${GLASSES_IMAGE_DIR}/even_realities_r1.png`;
/** The SKU-specific photo, or null when none is bundled for this identity. */
export function variantImagePath(identity: GlassesHardwareIdentity | null | undefined): string | null {
const name = identity?.imageAssetName;
return name ? `${GLASSES_IMAGE_DIR}/${name}.png` : null;
}
/** The best available photo for these glasses: the SKU's own, else the generic shot. */
export function glassesImagePath(identity: GlassesHardwareIdentity | null | undefined): string {
return variantImagePath(identity) ?? GENERIC_G2_IMAGE_PATH;
}
/** Relative file names (under `app/images/glasses/`) that must exist for the resolver's claims to hold. */
export function requiredArtworkFileNames(): string[] {
return [...Array.from(BUNDLED_VARIANT_ASSET_NAMES).map((name) => `${name}.png`), "even_realities_g2.png", "even_realities_r1.png"].sort();
}
+317
View File
@@ -0,0 +1,317 @@
/**
* Decodes an Even Realities serial number into the product family, frame shape,
* and colourway the wearer can actually see.
*
* Ported from SybilSight's `GlassesHardwareIdentity.swift`.
*
* ## Why this exists
*
* A G2 arm advertises its 14-character serial inside the manufacturer data
* (`"ER"` + SN(14) + MAC(6) + flag(1), see `even-advertisement.ts`). Two people
* in the same room with glasses in pairing mode therefore produce two rows of
* near-identical alphanumerics, and the only way to tell which one you are
* holding is to guess. The serial already encodes the answer — the shape of
* the frame and its colour — so decoding it turns "S211GBBC180304" into
* "Even G2 B · Brown", which the wearer can check against the thing in their
* hand without connecting to a stranger's hardware first.
*
* ## Where the mapping comes from
*
* Recovered from the Even Realities app 2.2.0
* (`even/common/utils/device_image_resolver` `_parseGlassesSku`, and
* `even/common/extension/ble/ble_mtach_device_ext` `evenSNName` / `matchModel`).
* That app does exactly this decode to pick its product artwork:
*
* | Serial slice | Meaning |
* | --- | --- |
* | `[0..<2]` | Product family — `S1` = G1 glasses, `S2` = G2 glasses, `B2` = R1 ring |
* | `[0..<3]` | Frame shape — `S20`/`S28` → A, `S21`/`S29` → B, `S22` → C (G1: `S11` → B, else A) |
* | `[0..<4]` | Model code (`S211`, `S110`, `B210`, `B290`) |
* | `[5]` | Colourway — `A` grey, `B` brown, `C` green |
*
* Two deliberate departures from the Even app: it silently defaults an
* unrecognised prefix to frame A and an unrecognised colour byte to grey. For
* identification that is the wrong trade — mislabelling a future SKU as
* "Frame A · Grey" is worse than saying nothing — so unknown values decode to
* `null` here and the UI falls back to the serial.
*
* This module is pure (no NativeScript imports) so it can run under node tests.
*/
export type GlassesFamily = "g1" | "g2" | "r1";
/** Frame shape. Even ships these as bare letters — frame A is round, B is square. */
export type GlassesFrame = "a" | "b" | "c";
/** Frame finish. The three colourways Even sells across G1 and G2. */
export type GlassesColorway = "grey" | "brown" | "green";
const FAMILY_PRODUCT_NAME: Record<GlassesFamily, string> = {
g1: "Even G1",
g2: "Even G2",
r1: "Even R1",
};
const COLORWAY_DISPLAY_NAME: Record<GlassesColorway, string> = {
grey: "Grey",
brown: "Brown",
green: "Green",
};
/**
* sRGB hex for the swatch shown beside a scan row. Approximations of the
* shipping finishes, chosen to stay distinguishable at small sizes.
*/
const COLORWAY_SWATCH_HEX: Record<GlassesColorway, string> = {
grey: "#8A8D91",
brown: "#6B4F3A",
green: "#3E5B45",
};
export function familyProductName(family: GlassesFamily): string {
return FAMILY_PRODUCT_NAME[family];
}
export function familyIsGlasses(family: GlassesFamily): boolean {
return family === "g1" || family === "g2";
}
export function frameLetter(frame: GlassesFrame): string {
return frame.toUpperCase();
}
export function frameDisplayName(frame: GlassesFrame): string {
return `Frame ${frameLetter(frame)}`;
}
export function colorwayDisplayName(colorway: GlassesColorway): string {
return COLORWAY_DISPLAY_NAME[colorway];
}
export function colorwaySwatchHex(colorway: GlassesColorway): string {
return COLORWAY_SWATCH_HEX[colorway];
}
export class GlassesHardwareIdentity {
/** The normalised (uppercased, trimmed, suffix-stripped) serial this identity was decoded from. */
readonly serial: string;
readonly family: GlassesFamily;
/** Null when the prefix is a family we recognise but a shape we do not, and always null for the ring. */
readonly frame: GlassesFrame | null;
/** Null when the colour byte is not one of A/B/C, and always null for the ring. */
readonly colorway: GlassesColorway | null;
private constructor(serial: string, family: GlassesFamily, frame: GlassesFrame | null, colorway: GlassesColorway | null) {
this.serial = serial;
this.family = family;
this.frame = frame;
this.colorway = colorway;
}
/**
* Decode a serial, or null when the string is not an Even serial at all.
*
* Accepts the advertised name verbatim: the scan list carries the bare
* serial, but saved pair identities and log lines carry arm suffixes
* (`S211GBBC180304_L_1`), so the leading serial run is taken and the rest
* ignored.
*/
static decode(rawValue: string | null | undefined): GlassesHardwareIdentity | null {
if (!rawValue) return null;
const normalized = normalizeSerial(rawValue);
// Both the family prefix (3) and the colour byte (index 5) must be present
// for the string to carry any variant information at all.
if (normalized.length < 6) return null;
const prefix2 = normalized.slice(0, 2);
const prefix3 = normalized.slice(0, 3);
let family: GlassesFamily;
switch (prefix2) {
case "S1":
family = "g1";
break;
case "S2":
family = "g2";
break;
case "B2":
family = "r1";
break;
default:
return null;
}
const isGlasses = familyIsGlasses(family);
return new GlassesHardwareIdentity(
normalized,
family,
isGlasses ? decodeFrame(prefix3, family) : null,
isGlasses ? decodeColorway(normalized) : null,
);
}
/** The four-character model code (`S211`), matching the Even app's `matchModel`. */
get modelCode(): string | null {
return this.serial.length >= 4 ? this.serial.slice(0, 4) : null;
}
/**
* Last four characters of the serial. Two people with the same frame and
* finish are the case this exists for: it is the shortest string that still
* separates them.
*/
get shortSerial(): string {
return this.serial.slice(-4);
}
/** "Even G2 B" — product plus frame letter, the way Even names the SKU. */
get productName(): string {
const base = familyProductName(this.family);
return this.frame ? `${base} ${frameLetter(this.frame)}` : base;
}
/** "Frame B · Brown", or just the half that decoded. Null when neither did. */
get variantSummary(): string | null {
const parts: string[] = [];
if (this.frame) parts.push(frameDisplayName(this.frame));
if (this.colorway) parts.push(colorwayDisplayName(this.colorway));
return parts.length ? parts.join(" · ") : null;
}
/** "Even G2 B · Brown" — the one-line label for a device row or status line. */
get displayName(): string {
return this.colorway ? `${this.productName} · ${colorwayDisplayName(this.colorway)}` : this.productName;
}
/**
* Bundled artwork key for the product photo of this exact SKU, or null when
* the shape or finish did not decode — or when the SKU is real but no
* artwork is bundled for it. Membership is explicit so a missing image fails
* to a generic product shot rather than to a blank `<Image>`.
*/
get imageAssetName(): string | null {
if (!this.frame || !this.colorway) return null;
const candidate = `glasses_${this.family}_${this.frame}_${this.colorway}`;
return BUNDLED_VARIANT_ASSET_NAMES.has(candidate) ? candidate : null;
}
equals(other: GlassesHardwareIdentity | null | undefined): boolean {
return !!other && other.serial === this.serial && other.family === this.family && other.frame === this.frame && other.colorway === this.colorway;
}
}
/**
* Frame C artwork is not bundled yet; add the PNG under `app/images/glasses/`
* and the name here together (see `glasses-artwork.ts`).
*/
export const BUNDLED_VARIANT_ASSET_NAMES: ReadonlySet<string> = new Set([
"glasses_g2_a_grey",
"glasses_g2_a_brown",
"glasses_g2_a_green",
"glasses_g2_b_grey",
"glasses_g2_b_brown",
"glasses_g2_b_green",
]);
/**
* Uppercase, drop surrounding whitespace, and cut at the first character that
* cannot appear in a serial — which is how the `_L_1` / `_R_1` arm suffix gets
* removed.
*/
export function normalizeSerial(rawValue: string): string {
const trimmed = rawValue.trim().toUpperCase();
const match = /^[0-9A-Z]*/.exec(trimmed);
return match ? match[0] : "";
}
function decodeFrame(prefix3: string, family: GlassesFamily): GlassesFrame | null {
switch (family) {
case "g1":
// G1 ships two shapes; the Even app tests only for `S11` and treats every
// other `S1` prefix as A.
return prefix3 === "S11" ? "b" : "a";
case "g2":
switch (prefix3) {
case "S20":
case "S28":
return "a";
case "S21":
case "S29":
return "b";
case "S22":
return "c";
default:
return null;
}
case "r1":
return null;
}
}
function decodeColorway(serial: string): GlassesColorway | null {
switch (serial.charAt(5)) {
case "A":
return "grey";
case "B":
return "brown";
case "C":
return "green";
default:
return null;
}
}
// ---------------------------------------------------------------------------
// Left/right pair check
// ---------------------------------------------------------------------------
/**
* Do the two temples belong to the same pair?
*
* A G2 is two independent BLE peripherals, each advertising its own serial.
* They should read identically. They will not when two pairs share a case,
* when an arm from one pair is charged alongside another, or when a
* replacement temple is fitted — and the result is a link that starts,
* authenticates on one side, and then behaves inexplicably. This names that
* failure before a connection is attempted.
*/
export type GlassesPairSerialVerdict =
| { kind: "matched"; serial: string }
| { kind: "unknown" }
| { kind: "mismatched"; left: string; right: string };
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 };
}
/**
* One sentence naming what is wrong and what to do, or null when nothing is
* wrong. Deliberately concrete about the serials: the wearer has to physically
* sort two piles of near-identical temples, and the printed serial is what
* they can sort them by.
*/
export function pairSerialWarning(verdict: GlassesPairSerialVerdict): string | null {
if (verdict.kind !== "mismatched") return null;
const leftVariant = GlassesHardwareIdentity.decode(verdict.left)?.displayName;
const rightVariant = GlassesHardwareIdentity.decode(verdict.right)?.displayName;
let message = `The left and right temples report different serial numbers (left ${verdict.left}, right ${verdict.right}).`;
if (leftVariant && rightVariant && leftVariant !== rightVariant) {
message += ` They are not even the same model: ${leftVariant} and ${rightVariant}.`;
}
message += " These are arms from two different pairs — check the serial printed inside each temple and pair a matched set.";
return message;
}
function nonEmpty(value: string | null | undefined): string | null {
if (value == null) return null;
const trimmed = value.trim();
return trimmed ? trimmed : null;
}
+383
View File
@@ -0,0 +1,383 @@
/**
* Turns a stream of Even advertisements into the things a pairing list shows:
* G2 pairs (a left and a right temple that advertise the same serial) and R1
* rings, each ranked by how close it probably is.
*
* Ported from SybilSight's `PairingScanPresentation` / `PairingFlowState`
* (nearest-device margin, previously-paired match, closest-first ordering)
* and extended with the left↔right pair grouping that Faceclaw needs because
* it connects to each arm by address rather than through a vendor SDK.
*
* This module is pure (no NativeScript imports) so it can run under node tests.
*/
import {
estimateProximity,
GLASSES_CALIBRATION,
proximitySummary,
RING_CALIBRATION,
sortedByProximity,
zoneGlyph,
type ProximityEstimate,
type ProximityZone,
} from "./ble-proximity";
import { classifyAdvertisement, type EvenAdvertisement, type RawAdvertisement } from "./even-advertisement";
import { glassesImagePath, R1_IMAGE_PATH } from "./glasses-artwork";
import {
colorwayDisplayName,
colorwaySwatchHex,
evaluatePairSerials,
GlassesHardwareIdentity,
pairSerialWarning,
type GlassesColorway,
} from "./glasses-hardware-identity";
export type PairCompleteness = "complete" | "left-only" | "right-only";
/** A G2 pair as seen over the air: up to one advertisement per side, joined on serial. */
export type GlassesPairCandidate = {
/** Stable id: the serial when known, otherwise the lone arm's address. */
id: string;
serial: string | null;
identity: GlassesHardwareIdentity | null;
left: EvenAdvertisement | null;
right: EvenAdvertisement | null;
completeness: PairCompleteness;
/** Strongest smoothed signal across the arms that have one. */
rssi: number | null;
txPower: number | null;
proximity: ProximityEstimate | null;
lastSeenMs: number;
};
export type RingCandidate = {
id: string;
advertisement: EvenAdvertisement;
rssi: number | null;
proximity: ProximityEstimate | null;
lastSeenMs: number;
};
/**
* Android delivers a callback per advertisement (several per second per arm),
* far more often than CoreBluetooth's coalesced reports, so the raw RSSI
* jitters visibly. A light exponential average keeps the list calm without
* hiding a real move. Ordering still uses the smoothed value; the margin for
* the "Closest" badge is applied on top.
*/
const RSSI_SMOOTHING = 0.35;
/**
* The device whose signal is strong enough to call "the one you are holding"
* needs a clear margin over the runner-up: RSSI wanders by a few dB between
* advertisements, so a badge awarded on a 1 dB lead would hop between rows
* every scan pass and mean nothing.
*/
export const NEAREST_SIGNAL_MARGIN_DBM = 8;
/** Advertisements older than this are dropped — the pair went back in its case or walked off. */
export const DEFAULT_STALE_AFTER_MS = 12_000;
export class DiscoveryAggregator {
private readonly byAddress = new Map<string, EvenAdvertisement & { smoothedRssi: number | null }>();
private readonly rejectedNames = new Set<string>();
/** Feed one raw advertisement. Returns the classified record, or null when ignored. */
ingest(raw: RawAdvertisement): EvenAdvertisement | null {
const classified = classifyAdvertisement(raw);
if (!classified) {
if (raw.name) this.rejectedNames.add(raw.name);
return null;
}
const previous = this.byAddress.get(classified.address);
let smoothedRssi: number | null = classified.rssi;
if (classified.rssi != null && previous?.smoothedRssi != null) {
smoothedRssi = previous.smoothedRssi + RSSI_SMOOTHING * (classified.rssi - previous.smoothedRssi);
} else if (classified.rssi == null && previous) {
// A bonded-device entry carries no signal; keep what the scan told us.
smoothedRssi = previous.smoothedRssi;
}
const merged: EvenAdvertisement & { smoothedRssi: number | null } = {
...classified,
// A bonded listing never has a serial; do not let it erase a scanned one.
serial: classified.serial ?? previous?.serial ?? null,
embeddedMac: classified.embeddedMac ?? previous?.embeddedMac ?? null,
manufacturerData: classified.manufacturerData || previous?.manufacturerData || "",
bonded: classified.bonded || (previous?.bonded ?? false),
rssi: classified.rssi ?? previous?.rssi ?? null,
txPower: classified.txPower ?? previous?.txPower ?? null,
seenAtMs: Math.max(classified.seenAtMs, previous?.seenAtMs ?? 0),
smoothedRssi,
};
this.byAddress.set(merged.address, merged);
return merged;
}
/** Forget advertisements not refreshed within `maxAgeMs`. Bonded entries are kept. */
prune(nowMs: number, maxAgeMs: number = DEFAULT_STALE_AFTER_MS): void {
for (const [address, record] of this.byAddress) {
if (record.bonded) continue;
if (nowMs - record.seenAtMs > maxAgeMs) this.byAddress.delete(address);
}
}
clear(): void {
this.byAddress.clear();
this.rejectedNames.clear();
}
get size(): number {
return this.byAddress.size;
}
/** Names of advertisements that looked like nothing we pair with — for the diagnostics log. */
get rejectedNameList(): string[] {
return Array.from(this.rejectedNames).sort();
}
advertisements(): EvenAdvertisement[] {
return Array.from(this.byAddress.values());
}
/** Every G2 pair seen, joined on serial, closest first. */
pairs(): GlassesPairCandidate[] {
const groups = new Map<string, { left: (EvenAdvertisement & { smoothedRssi: number | null }) | null; right: (EvenAdvertisement & { smoothedRssi: number | null }) | null }>();
for (const record of this.byAddress.values()) {
if (record.role === "ring") continue;
const key = record.serial ? `serial:${record.serial}` : `arm:${record.address}`;
const group = groups.get(key) ?? { left: null, right: null };
const slot = record.role === "left" ? "left" : "right";
const incumbent = group[slot];
// Two arms of one side claiming the same serial is a replaced temple or a
// stale row; keep the one heard most recently.
if (!incumbent || incumbent.seenAtMs <= record.seenAtMs) group[slot] = record;
groups.set(key, group);
}
const pairs: GlassesPairCandidate[] = [];
for (const group of groups.values()) {
const left = group.left;
const right = group.right;
const any = (left ?? right)!;
const serial = any.serial;
const samples = [left, right].filter((arm): arm is NonNullable<typeof arm> => !!arm && arm.smoothedRssi != null);
const strongest = samples.length ? samples.reduce((a, b) => (a.smoothedRssi! >= b.smoothedRssi! ? a : b)) : null;
const rssi = strongest ? Math.round(strongest.smoothedRssi!) : null;
const txPower = strongest?.txPower ?? left?.txPower ?? right?.txPower ?? null;
pairs.push({
id: 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),
lastSeenMs: Math.max(left?.seenAtMs ?? 0, right?.seenAtMs ?? 0),
});
}
return sortedByProximity(pairs, (pair) => pair.proximity, (pair) => pair.id);
}
/** Every R1 ring seen, closest first. */
rings(): RingCandidate[] {
const rings: RingCandidate[] = [];
for (const record of this.byAddress.values()) {
if (record.role !== "ring") continue;
const rssi = record.smoothedRssi != null ? Math.round(record.smoothedRssi) : null;
rings.push({
id: record.address,
advertisement: stripSmoothing(record),
rssi,
proximity: estimateProximity(rssi, record.txPower, RING_CALIBRATION),
lastSeenMs: record.seenAtMs,
});
}
return sortedByProximity(rings, (ring) => ring.proximity, (ring) => ring.id);
}
}
function stripSmoothing(record: EvenAdvertisement & { smoothedRssi: number | null }): EvenAdvertisement {
const { smoothedRssi: _ignored, ...rest } = record;
return rest;
}
/**
* The candidate whose signal is strong enough to call "the one you are
* holding". `null` when nothing leads clearly, which is the honest answer for
* two pairs sitting on the same table.
*/
export function nearestCandidateId(candidates: ReadonlyArray<{ id: string; rssi: number | null }>): string | null {
const ranked = candidates
.filter((candidate): candidate is { id: string; rssi: number } => candidate.rssi != null)
.slice()
// Stable order for equal signal so repeated polls nominate the same row.
.sort((lhs, rhs) => (lhs.rssi === rhs.rssi ? (lhs.id < rhs.id ? -1 : 1) : rhs.rssi - lhs.rssi));
const best = ranked[0];
if (!best) return null;
if (ranked.length === 1) return best.id;
return best.rssi - ranked[1]!.rssi >= NEAREST_SIGNAL_MARGIN_DBM ? best.id : null;
}
/**
* The saved pair identity is stored as the serial, but historical values may
* carry the `_L_1` arm suffix, so compare on the decoded serial when both
* sides decode and fall back to a containment check when they do not.
*/
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);
}
// ---------------------------------------------------------------------------
// Row presentation
// ---------------------------------------------------------------------------
export type PairingRowPresentation = {
id: string;
kind: "glasses" | "ring";
/** "Even G2 B" / "Even R1" / fallback product name. */
modelTitle: string;
/** The serial (glasses) or local name (ring). */
deviceName: string;
/** "Frame B · Brown", or null when the serial does not carry a variant we recognise. */
variantSummary: string | null;
colorway: GlassesColorway | null;
/** Hex colour for the swatch. Null suppresses it rather than guessing a finish. */
swatchHex: string | null;
/** Product photo path for `<Image src>`. Variant art when bundled, else the generic shot. */
imagePath: string;
/** True only when the variant-specific photo is available (the swatch is redundant then). */
hasVariantImage: boolean;
isNearest: boolean;
isPreviouslyPaired: boolean;
/** "Yours" / "Closest" / "". */
badge: string;
proximitySummary: string;
proximityGlyph: string;
zone: ProximityZone | null;
/** "Left + right arms found", "Only the left arm has been seen", … */
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 = {
/** Serial of the pair this phone paired with before, if any. */
pairedSerial?: string | null;
/** From `nearestCandidateId` over the same list. */
nearestId?: string | null;
/** Ring address saved before, if any. */
pairedRingAddress?: string | null;
};
export function glassesRow(pair: GlassesPairCandidate, context: RowContext = {}): PairingRowPresentation {
const identity = pair.identity;
const imagePath = glassesImagePath(identity);
const isPreviouslyPairedRow = isPreviouslyPaired(pair.serial, context.pairedSerial);
const isNearest = !!context.nearestId && context.nearestId === pair.id;
const warnings: string[] = [];
const leftNote = pair.left?.note;
const rightNote = pair.right?.note;
if (leftNote) warnings.push(`Left arm: ${leftNote}.`);
if (rightNote) warnings.push(`Right arm: ${rightNote}.`);
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);
let armsSummary: string;
switch (pair.completeness) {
case "complete":
armsSummary = verdict.kind === "matched" ? "Left + right arms found · serials match" : "Left + right arms found";
break;
case "left-only":
armsSummary = "Only the left arm has been seen — waiting for the right";
break;
case "right-only":
armsSummary = "Only the right arm has been seen — waiting for the left";
break;
}
if (!pair.serial) armsSummary += " · serial unknown, cannot match arms";
return {
id: pair.id,
kind: "glasses",
modelTitle: identity?.productName ?? "Even Realities G2",
deviceName: pair.serial ?? (pair.left ?? pair.right)!.name,
variantSummary: identity?.variantSummary ?? null,
colorway: identity?.colorway ?? null,
swatchHex: identity?.colorway ? colorwaySwatchHex(identity.colorway) : null,
imagePath,
hasVariantImage: !!identity?.imageAssetName,
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,
armsSummary,
warning: warnings.join(" "),
canSelect: pair.completeness === "complete" && verdict.kind !== "mismatched",
leftAddress: pair.left?.address ?? "",
rightAddress: pair.right?.address ?? "",
ringAddress: "",
};
}
export function ringRow(ring: RingCandidate, context: RowContext = {}): PairingRowPresentation {
const ad = ring.advertisement;
const isPaired = !!context.pairedRingAddress && context.pairedRingAddress.toUpperCase() === 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}.`);
}
return {
id: ring.id,
kind: "ring",
modelTitle: "Even R1",
deviceName: ad.ringSerialSuffix ? `${ad.name} · serial …${ad.ringSerialSuffix}` : ad.name,
variantSummary: null,
colorway: null,
swatchHex: null,
imagePath: R1_IMAGE_PATH,
hasVariantImage: true,
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(" "),
canSelect: true,
leftAddress: "",
rightAddress: "",
ringAddress: ad.address,
};
}
/** Convenience: a colourway's display text, for rows that show the swatch alone. */
export function colorwayLabel(colorway: GlassesColorway | null): string {
return colorway ? colorwayDisplayName(colorway) : "";
}