Add proximity-based pairing for Even devices
Stream BLE advertisements into a dedicated pairing flow with arm, ring, serial, and hardware variant detection. Add proximity ranking, device artwork, pairing safeguards, and unit coverage for discovery and candidate grouping.
No files matched your search
@@ -6,151 +6,392 @@ import android.bluetooth.BluetoothDevice;
|
||||
import android.bluetooth.BluetoothManager;
|
||||
import android.bluetooth.le.BluetoothLeScanner;
|
||||
import android.bluetooth.le.ScanCallback;
|
||||
import android.bluetooth.le.ScanRecord;
|
||||
import android.bluetooth.le.ScanResult;
|
||||
import android.bluetooth.le.ScanSettings;
|
||||
import android.content.Context;
|
||||
import android.os.Build;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.util.SparseArray;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Finds Even Realities hardware over BLE and hands every advertisement up to
|
||||
* TypeScript with the raw fields the pairing screen needs: the LIVE local name
|
||||
* from the scan record (BluetoothDevice.getName() is a cache that can hold a
|
||||
* pre-reset value indefinitely), the full manufacturer-specific payload with
|
||||
* its company identifier restored so the "ER"+serial+MAC layout survives
|
||||
* intact, RSSI, advertised TX power, and connectability.
|
||||
*
|
||||
* Admission is deliberately loose — a name containing G2 or R1, or the Even
|
||||
* "ER" manufacturer signature — because renamed custom firmware may drop the
|
||||
* stock name. Side, serial, and pair matching are decided in TypeScript
|
||||
* (app/g2/even-advertisement.ts, app/g2/pairing-candidates.ts) where they can
|
||||
* be unit-tested.
|
||||
*
|
||||
* Ported from the discovery path of SybilSight's Bluetooth SDK (G2.didDiscover
|
||||
* and R1's advertisement snapshot), reduced to what Android exposes.
|
||||
*/
|
||||
@SuppressLint("MissingPermission")
|
||||
public class FaceclawDeviceDiscovery {
|
||||
private static final Pattern RING_NAME = Pattern.compile("^EVEN R1_[0-9A-F]{6}$");
|
||||
private static final Pattern RIGHT_NAME = Pattern.compile("^Even G2_32_R_[0-9A-F]{6}$");
|
||||
private static final Pattern LEFT_NAME = Pattern.compile("^Even G2_32_L_[0-9A-F]{6}$");
|
||||
/** Even Realities' company identifier: the ASCII bytes "ER" read little-endian. */
|
||||
public static final int EVEN_COMPANY_ID = 0x5245;
|
||||
|
||||
private final Context appContext;
|
||||
private final BluetoothAdapter bluetoothAdapter;
|
||||
private final Handler mainHandler = new Handler(Looper.getMainLooper());
|
||||
|
||||
private final Object lock = new Object();
|
||||
private ScanCallback activeCallback;
|
||||
private volatile FaceclawDeviceDiscoveryListener listener;
|
||||
|
||||
public FaceclawDeviceDiscovery(Context context) {
|
||||
this.appContext = context.getApplicationContext();
|
||||
Context appContext = context.getApplicationContext();
|
||||
BluetoothManager bluetoothManager =
|
||||
(BluetoothManager) this.appContext.getSystemService(Context.BLUETOOTH_SERVICE);
|
||||
(BluetoothManager) appContext.getSystemService(Context.BLUETOOTH_SERVICE);
|
||||
if (bluetoothManager == null || bluetoothManager.getAdapter() == null) {
|
||||
throw new IllegalStateException("Bluetooth adapter unavailable");
|
||||
}
|
||||
this.bluetoothAdapter = bluetoothManager.getAdapter();
|
||||
}
|
||||
|
||||
public String getBondedCandidatesJson() {
|
||||
LinkedHashMap<String, CandidateDevice> matches = new LinkedHashMap<>();
|
||||
Set<BluetoothDevice> bonded = bluetoothAdapter.getBondedDevices();
|
||||
if (bonded != null) {
|
||||
for (BluetoothDevice device : bonded) {
|
||||
maybeAddCandidate(matches, device, "paired");
|
||||
}
|
||||
}
|
||||
return encodeCandidates(matches);
|
||||
public boolean isBluetoothEnabled() {
|
||||
return bluetoothAdapter.isEnabled();
|
||||
}
|
||||
|
||||
public String scanCandidatesJson(int timeoutMs) throws InterruptedException {
|
||||
LinkedHashMap<String, CandidateDevice> matches = new LinkedHashMap<>();
|
||||
BluetoothLeScanner scanner = bluetoothAdapter.getBluetoothLeScanner();
|
||||
if (scanner == null) {
|
||||
return encodeCandidates(matches);
|
||||
}
|
||||
final ScanCallback callback = new ScanCallback() {
|
||||
@Override
|
||||
public void onScanResult(int callbackType, ScanResult result) {
|
||||
if (result == null) {
|
||||
return;
|
||||
}
|
||||
maybeAddCandidate(matches, result.getDevice(), "scan");
|
||||
}
|
||||
public void setListener(FaceclawDeviceDiscoveryListener newListener) {
|
||||
this.listener = newListener;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBatchScanResults(java.util.List<ScanResult> results) {
|
||||
if (results == null) {
|
||||
return;
|
||||
}
|
||||
for (ScanResult result : results) {
|
||||
// ------------------------------------------------------------------
|
||||
// Live scan
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Start streaming advertisements to the listener. Returns false when the
|
||||
* radio is off or the scanner is unavailable; a later platform refusal
|
||||
* arrives through onScanFailed. Calling while a scan is running is a no-op.
|
||||
*/
|
||||
public boolean startScan() {
|
||||
synchronized (lock) {
|
||||
if (activeCallback != null) {
|
||||
return true;
|
||||
}
|
||||
if (!bluetoothAdapter.isEnabled()) {
|
||||
emitLog("scan not started: Bluetooth is off");
|
||||
return false;
|
||||
}
|
||||
BluetoothLeScanner scanner = bluetoothAdapter.getBluetoothLeScanner();
|
||||
if (scanner == null) {
|
||||
emitLog("scan not started: no BLE scanner");
|
||||
return false;
|
||||
}
|
||||
final ScanCallback callback = new ScanCallback() {
|
||||
@Override
|
||||
public void onScanResult(int callbackType, ScanResult result) {
|
||||
if (result != null) {
|
||||
maybeAddCandidate(matches, result.getDevice(), "scan");
|
||||
emitAdvertisement(result);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBatchScanResults(List<ScanResult> results) {
|
||||
if (results == null) {
|
||||
return;
|
||||
}
|
||||
for (ScanResult result : results) {
|
||||
if (result != null) {
|
||||
emitAdvertisement(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onScanFailed(int errorCode) {
|
||||
synchronized (lock) {
|
||||
if (activeCallback == this) {
|
||||
activeCallback = null;
|
||||
}
|
||||
}
|
||||
final FaceclawDeviceDiscoveryListener l = listener;
|
||||
if (l != null) {
|
||||
final String message = describeScanError(errorCode);
|
||||
mainHandler.post(() -> l.onScanFailed(errorCode, message));
|
||||
}
|
||||
}
|
||||
};
|
||||
activeCallback = callback;
|
||||
try {
|
||||
scanner.startScan(null, buildScanSettings(), callback);
|
||||
} catch (Throwable t) {
|
||||
activeCallback = null;
|
||||
emitLog("scan not started: " + t);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
scanner.startScan(
|
||||
null,
|
||||
new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build(),
|
||||
callback
|
||||
);
|
||||
try {
|
||||
Thread.sleep(Math.max(500, timeoutMs));
|
||||
} finally {
|
||||
emitLog("scan started (unfiltered, low latency)");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public void stopScan() {
|
||||
ScanCallback callback;
|
||||
synchronized (lock) {
|
||||
callback = activeCallback;
|
||||
activeCallback = null;
|
||||
}
|
||||
if (callback == null) {
|
||||
return;
|
||||
}
|
||||
BluetoothLeScanner scanner = bluetoothAdapter.getBluetoothLeScanner();
|
||||
if (scanner != null) {
|
||||
try {
|
||||
scanner.stopScan(callback);
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
}
|
||||
return encodeCandidates(matches);
|
||||
emitLog("scan stopped");
|
||||
}
|
||||
|
||||
private void maybeAddCandidate(Map<String, CandidateDevice> matches, BluetoothDevice device, String source) {
|
||||
if (device == null) {
|
||||
return;
|
||||
public boolean isScanning() {
|
||||
synchronized (lock) {
|
||||
return activeCallback != null;
|
||||
}
|
||||
String name = device.getName();
|
||||
String role = classifyRole(name);
|
||||
if (role == null) {
|
||||
return;
|
||||
}
|
||||
String address = device.getAddress();
|
||||
if (address == null || address.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
matches.put(address, new CandidateDevice(address, name == null ? "" : name, role, source));
|
||||
}
|
||||
|
||||
private String classifyRole(String name) {
|
||||
if (name == null) {
|
||||
return null;
|
||||
/**
|
||||
* Replay bonded Even devices to the listener. A bonded listing has no
|
||||
* signal sample and no manufacturer data, so its serial stays unknown until
|
||||
* the device is also heard advertising.
|
||||
*/
|
||||
public void emitBondedDevices() {
|
||||
final FaceclawDeviceDiscoveryListener l = listener;
|
||||
if (l == null) {
|
||||
return;
|
||||
}
|
||||
if (RIGHT_NAME.matcher(name).matches()) {
|
||||
return "right";
|
||||
for (String json : bondedCandidateJsonList()) {
|
||||
l.onAdvertisement(json);
|
||||
}
|
||||
if (LEFT_NAME.matcher(name).matches()) {
|
||||
return "left";
|
||||
}
|
||||
if (RING_NAME.matcher(name).matches()) {
|
||||
return "ring";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String encodeCandidates(Map<String, CandidateDevice> matches) {
|
||||
/** Bonded Even devices as one JSON array, for callers without a listener. */
|
||||
public String getBondedCandidatesJson() {
|
||||
JSONArray array = new JSONArray();
|
||||
for (CandidateDevice candidate : matches.values()) {
|
||||
JSONObject object = new JSONObject();
|
||||
for (String json : bondedCandidateJsonList()) {
|
||||
try {
|
||||
object.put("address", candidate.address);
|
||||
object.put("name", candidate.name);
|
||||
object.put("role", candidate.role);
|
||||
object.put("source", candidate.source);
|
||||
array.put(object);
|
||||
array.put(new JSONObject(json));
|
||||
} catch (JSONException ignored) {
|
||||
}
|
||||
}
|
||||
return array.toString();
|
||||
}
|
||||
|
||||
private static final class CandidateDevice {
|
||||
final String address;
|
||||
final String name;
|
||||
final String role;
|
||||
final String source;
|
||||
// ------------------------------------------------------------------
|
||||
// Internals
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
CandidateDevice(String address, String name, String role, String source) {
|
||||
this.address = address;
|
||||
this.name = name;
|
||||
this.role = role;
|
||||
this.source = source;
|
||||
private static ScanSettings buildScanSettings() {
|
||||
ScanSettings.Builder builder = new ScanSettings.Builder()
|
||||
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
|
||||
.setReportDelay(0);
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
builder.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES);
|
||||
builder.setMatchMode(ScanSettings.MATCH_MODE_AGGRESSIVE);
|
||||
builder.setNumOfMatches(ScanSettings.MATCH_NUM_MAX_ADVERTISEMENT);
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
// Accept extended advertising too; setLegacy(true) would hide it.
|
||||
builder.setLegacy(false);
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
private void emitAdvertisement(ScanResult result) {
|
||||
final JSONObject object = toJson(result);
|
||||
if (object == null) {
|
||||
return;
|
||||
}
|
||||
final FaceclawDeviceDiscoveryListener l = listener;
|
||||
if (l == null) {
|
||||
return;
|
||||
}
|
||||
final String json = object.toString();
|
||||
if (Looper.myLooper() == Looper.getMainLooper()) {
|
||||
l.onAdvertisement(json);
|
||||
} else {
|
||||
mainHandler.post(() -> {
|
||||
FaceclawDeviceDiscoveryListener current = listener;
|
||||
if (current != null) {
|
||||
current.onAdvertisement(json);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private List<String> bondedCandidateJsonList() {
|
||||
List<String> out = new ArrayList<>();
|
||||
Set<BluetoothDevice> bonded = bluetoothAdapter.getBondedDevices();
|
||||
if (bonded == null) {
|
||||
return out;
|
||||
}
|
||||
long now = System.currentTimeMillis();
|
||||
for (BluetoothDevice device : bonded) {
|
||||
if (device == null) {
|
||||
continue;
|
||||
}
|
||||
String name = device.getName();
|
||||
if (!isAdmissible(name, null)) {
|
||||
continue;
|
||||
}
|
||||
JSONObject object = buildJson(
|
||||
device.getAddress(), name, "", null, null, null, true, "paired", now);
|
||||
if (object != null) {
|
||||
out.add(object.toString());
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Null when the result is not something we pair with. */
|
||||
private static JSONObject toJson(ScanResult result) {
|
||||
BluetoothDevice device = result.getDevice();
|
||||
if (device == null) {
|
||||
return null;
|
||||
}
|
||||
ScanRecord record = result.getScanRecord();
|
||||
String liveName = record == null ? null : record.getDeviceName();
|
||||
String name = liveName != null && !liveName.isEmpty() ? liveName : device.getName();
|
||||
byte[] manufacturerData = extractEvenManufacturerData(record);
|
||||
if (!isAdmissible(name, manufacturerData)) {
|
||||
return null;
|
||||
}
|
||||
Integer txPower = null;
|
||||
if (record != null && record.getTxPowerLevel() != Integer.MIN_VALUE) {
|
||||
txPower = record.getTxPowerLevel();
|
||||
}
|
||||
if (txPower == null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
|
||||
&& result.getTxPower() != ScanResult.TX_POWER_NOT_PRESENT) {
|
||||
txPower = result.getTxPower();
|
||||
}
|
||||
Boolean connectable = null;
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
connectable = result.isConnectable();
|
||||
}
|
||||
int rssi = result.getRssi();
|
||||
// 127 is the "unavailable" sentinel; 0 dBm never happens for a real sample.
|
||||
Integer rssiValue = (rssi == 127 || rssi == 0) ? null : rssi;
|
||||
boolean bonded = device.getBondState() == BluetoothDevice.BOND_BONDED;
|
||||
return buildJson(
|
||||
device.getAddress(), name, toHex(manufacturerData), rssiValue, txPower,
|
||||
connectable, bonded, "scan", System.currentTimeMillis());
|
||||
}
|
||||
|
||||
/**
|
||||
* Android strips the 2-byte company identifier from each manufacturer
|
||||
* record and keys the SparseArray by it. Put the bytes back (little-endian)
|
||||
* so TypeScript sees the same "ER"+… layout the iOS SDK and HCI captures
|
||||
* document. Prefers Even's own id; otherwise returns the first record so an
|
||||
* unexpected company id still reaches the diagnostics log.
|
||||
*/
|
||||
private static byte[] extractEvenManufacturerData(ScanRecord record) {
|
||||
if (record == null) {
|
||||
return new byte[0];
|
||||
}
|
||||
SparseArray<byte[]> all = record.getManufacturerSpecificData();
|
||||
if (all == null || all.size() == 0) {
|
||||
return new byte[0];
|
||||
}
|
||||
byte[] payload = all.get(EVEN_COMPANY_ID);
|
||||
int companyId = EVEN_COMPANY_ID;
|
||||
if (payload == null) {
|
||||
companyId = all.keyAt(0);
|
||||
payload = all.valueAt(0);
|
||||
}
|
||||
if (payload == null) {
|
||||
return new byte[0];
|
||||
}
|
||||
byte[] out = new byte[payload.length + 2];
|
||||
out[0] = (byte) (companyId & 0xff);
|
||||
out[1] = (byte) ((companyId >> 8) & 0xff);
|
||||
System.arraycopy(payload, 0, out, 2, payload.length);
|
||||
return out;
|
||||
}
|
||||
|
||||
private static boolean isAdmissible(String name, byte[] manufacturerData) {
|
||||
if (manufacturerData != null && manufacturerData.length >= 2
|
||||
&& manufacturerData[0] == 0x45 && manufacturerData[1] == 0x52) {
|
||||
return true;
|
||||
}
|
||||
if (name == null) {
|
||||
return false;
|
||||
}
|
||||
String upper = name.toUpperCase();
|
||||
return upper.contains("G2") || upper.contains("R1");
|
||||
}
|
||||
|
||||
private static JSONObject buildJson(
|
||||
String address, String name, String manufacturerHex, Integer rssi, Integer txPower,
|
||||
Boolean connectable, boolean bonded, String source, long seenAtMs) {
|
||||
if (address == null || address.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
JSONObject object = new JSONObject();
|
||||
object.put("address", address);
|
||||
object.put("name", name == null ? "" : name);
|
||||
object.put("manufacturerData", manufacturerHex == null ? "" : manufacturerHex);
|
||||
object.put("rssi", rssi == null ? JSONObject.NULL : rssi);
|
||||
object.put("txPower", txPower == null ? JSONObject.NULL : txPower);
|
||||
object.put("connectable", connectable == null ? JSONObject.NULL : connectable);
|
||||
object.put("bonded", bonded);
|
||||
object.put("source", source);
|
||||
object.put("seenAtMs", seenAtMs);
|
||||
return object;
|
||||
} catch (JSONException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static String toHex(byte[] bytes) {
|
||||
if (bytes == null || bytes.length == 0) {
|
||||
return "";
|
||||
}
|
||||
StringBuilder sb = new StringBuilder(bytes.length * 2);
|
||||
for (byte b : bytes) {
|
||||
sb.append(String.format("%02X", b & 0xff));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static String describeScanError(int errorCode) {
|
||||
switch (errorCode) {
|
||||
case ScanCallback.SCAN_FAILED_ALREADY_STARTED:
|
||||
return "a scan is already running";
|
||||
case ScanCallback.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED:
|
||||
return "the Bluetooth stack refused to register the scan (try toggling Bluetooth)";
|
||||
case ScanCallback.SCAN_FAILED_FEATURE_UNSUPPORTED:
|
||||
return "BLE scanning is not supported on this device";
|
||||
case ScanCallback.SCAN_FAILED_INTERNAL_ERROR:
|
||||
return "internal Bluetooth error";
|
||||
case 5: // SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES (API 31)
|
||||
return "out of Bluetooth hardware resources";
|
||||
case 6: // SCAN_FAILED_SCANNING_TOO_FREQUENTLY (API 31)
|
||||
return "scanning too frequently; wait a moment and try again";
|
||||
default:
|
||||
return "scan failed (code " + errorCode + ")";
|
||||
}
|
||||
}
|
||||
|
||||
private void emitLog(String line) {
|
||||
FaceclawDeviceDiscoveryListener l = listener;
|
||||
if (l != null) {
|
||||
l.onLog(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
/** Callbacks from FaceclawDeviceDiscovery's live scan to the TypeScript layer. */
|
||||
public interface FaceclawDeviceDiscoveryListener {
|
||||
/**
|
||||
* One advertisement (or one bonded device) as a JSON object:
|
||||
* {address, name, manufacturerData (hex, company id included), rssi|null,
|
||||
* txPower|null, connectable|null, bonded, source, seenAtMs}.
|
||||
* Protocol decoding happens in TypeScript (see app/g2/even-advertisement.ts).
|
||||
*/
|
||||
void onAdvertisement(String json);
|
||||
|
||||
/** The platform refused to start or continue the scan. */
|
||||
void onScanFailed(int errorCode, String message);
|
||||
|
||||
/** Diagnostic line for the pairing log. */
|
||||
void onLog(String line);
|
||||
}
|
||||
@@ -65,6 +65,11 @@ To install, run
|
||||
battery life similar to the stock Even app.
|
||||
* Connection management with auto-reconnect, and autodetection of conflict
|
||||
with the official Even Realities app
|
||||
* Bluetooth pairing that scans for nearby glasses and identifies each pair
|
||||
before connecting: model, frame shape, and colour decoded from the
|
||||
advertised serial (with product photos), left and right arms matched to
|
||||
each other by that serial, an estimated distance so the pair in your hand
|
||||
sorts first, and the optional R1 ring
|
||||
* On-phone screen mirroring and simulated ring input
|
||||
* Dual-language NativeScript architecture with Java for the multithreaded
|
||||
Android API and bluetooth stack bits, Typescript for the bits you want to
|
||||
|
||||
@@ -55,3 +55,130 @@ Button.-primary {
|
||||
border-width: 1;
|
||||
border-radius: 8;
|
||||
}
|
||||
|
||||
/*
|
||||
* Pairing scan list (phone-ui/pairing-page). Rows are Repeater items: product
|
||||
* art (or a colourway swatch) on the left, decoded SKU + proximity + serial in
|
||||
* the middle, a chevron/check on the right.
|
||||
*/
|
||||
.pairing-instructions {
|
||||
color: #555555;
|
||||
font-size: 14;
|
||||
}
|
||||
|
||||
.pairing-status {
|
||||
font-size: 14;
|
||||
margin-left: 8;
|
||||
}
|
||||
|
||||
.pairing-section {
|
||||
font-size: 16;
|
||||
font-weight: bold;
|
||||
margin-bottom: 4;
|
||||
}
|
||||
|
||||
.pairing-empty {
|
||||
color: #777777;
|
||||
font-size: 14;
|
||||
padding: 8 0;
|
||||
}
|
||||
|
||||
.pairing-row {
|
||||
background-color: #f4f4f4;
|
||||
border-color: #dddddd;
|
||||
border-width: 1;
|
||||
border-radius: 10;
|
||||
padding: 10;
|
||||
margin-bottom: 8;
|
||||
}
|
||||
|
||||
.pairing-row-selected {
|
||||
background-color: #e6f0ff;
|
||||
border-color: #3b6fd6;
|
||||
}
|
||||
|
||||
.pairing-row-incomplete {
|
||||
background-color: #fafafa;
|
||||
border-color: #e6e6e6;
|
||||
}
|
||||
|
||||
.pairing-art {
|
||||
vertical-align: center;
|
||||
}
|
||||
|
||||
.pairing-title {
|
||||
font-size: 16;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.pairing-badge {
|
||||
font-size: 11;
|
||||
font-weight: bold;
|
||||
color: #2a5bc4;
|
||||
background-color: #dbe6fb;
|
||||
border-radius: 9;
|
||||
padding: 1 7;
|
||||
}
|
||||
|
||||
.pairing-variant {
|
||||
font-size: 13;
|
||||
font-weight: bold;
|
||||
color: #333333;
|
||||
}
|
||||
|
||||
.pairing-proximity {
|
||||
font-size: 12;
|
||||
color: #666666;
|
||||
}
|
||||
|
||||
.pairing-proximity-immediate {
|
||||
color: #2a5bc4;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.pairing-serial {
|
||||
font-size: 12;
|
||||
color: #666666;
|
||||
font-family: monospace;
|
||||
}
|
||||
|
||||
.pairing-arms {
|
||||
font-size: 12;
|
||||
color: #444444;
|
||||
}
|
||||
|
||||
.pairing-warning {
|
||||
font-size: 12;
|
||||
color: #a33a1f;
|
||||
margin-top: 4;
|
||||
}
|
||||
|
||||
.pairing-swatch-label {
|
||||
font-size: 11;
|
||||
color: #555555;
|
||||
}
|
||||
|
||||
.pairing-chevron {
|
||||
font-size: 22;
|
||||
color: #444444;
|
||||
margin-left: 6;
|
||||
}
|
||||
|
||||
.pairing-selection {
|
||||
background-color: #eef4ff;
|
||||
border-radius: 10;
|
||||
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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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(":");
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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) : "";
|
||||
}
|
||||
|
After Width: | Height: | Size: 212 KiB |
|
After Width: | Height: | Size: 47 KiB |
|
After Width: | Height: | Size: 83 KiB |
|
After Width: | Height: | Size: 87 KiB |
|
After Width: | Height: | Size: 66 KiB |
|
After Width: | Height: | Size: 85 KiB |
|
After Width: | Height: | Size: 89 KiB |
|
After Width: | Height: | Size: 67 KiB |
@@ -1,12 +1,13 @@
|
||||
import { Utils } from "@nativescript/core";
|
||||
|
||||
import { classifyAdvertisement, type RawAdvertisement } from "../g2/even-advertisement";
|
||||
|
||||
declare const com: any;
|
||||
|
||||
export type DiscoveredDevice = {
|
||||
address: string;
|
||||
name: string;
|
||||
role: "left" | "right" | "ring";
|
||||
source: "paired" | "scan";
|
||||
export type DiscoveryEvents = {
|
||||
onAdvertisement: (raw: RawAdvertisement) => void;
|
||||
onScanFailed?: (code: number, message: string) => void;
|
||||
onLog?: (line: string) => void;
|
||||
};
|
||||
|
||||
export type DiscoveredAddressSet = {
|
||||
@@ -16,8 +17,16 @@ export type DiscoveredAddressSet = {
|
||||
summary: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* TS wrapper around the native FaceclawDeviceDiscovery. The live scan streams
|
||||
* raw advertisements (see `RawAdvertisement`); protocol decoding happens in
|
||||
* `app/g2/even-advertisement.ts` and pair grouping in
|
||||
* `app/g2/pairing-candidates.ts`.
|
||||
*/
|
||||
export class DeviceDiscoveryBridge {
|
||||
private readonly discovery: any;
|
||||
private listenerProxy: any = null;
|
||||
private events: DiscoveryEvents | null = null;
|
||||
|
||||
constructor() {
|
||||
const context = Utils.android.getApplicationContext();
|
||||
@@ -25,40 +34,133 @@ export class DeviceDiscoveryBridge {
|
||||
this.discovery = new com.faceclaw.app.FaceclawDeviceDiscovery(context);
|
||||
}
|
||||
|
||||
async getBondedCandidates(): Promise<DiscoveredDevice[]> {
|
||||
return parseCandidates(String(this.discovery.getBondedCandidatesJson()));
|
||||
get bluetoothEnabled(): boolean {
|
||||
return !!this.discovery.isBluetoothEnabled();
|
||||
}
|
||||
|
||||
async scanCandidates(timeoutMs = 6000): Promise<DiscoveredDevice[]> {
|
||||
return parseCandidates(String(this.discovery.scanCandidatesJson(timeoutMs)));
|
||||
get scanning(): boolean {
|
||||
return !!this.discovery.isScanning();
|
||||
}
|
||||
|
||||
/** Start (or re-target) the live scan. Returns false when the radio is off. */
|
||||
startScan(events: DiscoveryEvents): boolean {
|
||||
this.events = events;
|
||||
if (!this.listenerProxy) {
|
||||
this.listenerProxy = new com.faceclaw.app.FaceclawDeviceDiscoveryListener({
|
||||
onAdvertisement: (json: string) => {
|
||||
const raw = parseRaw(String(json));
|
||||
if (raw) this.events?.onAdvertisement(raw);
|
||||
},
|
||||
onScanFailed: (code: number, message: string) => this.events?.onScanFailed?.(Number(code), String(message)),
|
||||
onLog: (line: string) => this.events?.onLog?.(String(line)),
|
||||
});
|
||||
this.discovery.setListener(this.listenerProxy);
|
||||
}
|
||||
return !!this.discovery.startScan();
|
||||
}
|
||||
|
||||
stopScan(): void {
|
||||
try {
|
||||
this.discovery.stopScan();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
/** Push bonded Even devices through the listener as `source: "paired"` entries. */
|
||||
emitBondedDevices(): void {
|
||||
if (!this.listenerProxy) return;
|
||||
this.discovery.emitBondedDevices();
|
||||
}
|
||||
|
||||
async getBondedCandidates(): Promise<RawAdvertisement[]> {
|
||||
return parseRawArray(String(this.discovery.getBondedCandidatesJson()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
scanCandidates(timeoutMs = 6000): Promise<RawAdvertisement[]> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const latest = new Map<string, RawAdvertisement>();
|
||||
const started = this.startScan({
|
||||
onAdvertisement: (raw) => latest.set(raw.address, raw),
|
||||
onScanFailed: (code, message) => {
|
||||
this.stopScan();
|
||||
reject(new Error(`Bluetooth scan failed: ${message} (${code})`));
|
||||
},
|
||||
});
|
||||
if (!started) {
|
||||
reject(new Error("Bluetooth is off or BLE scanning is unavailable."));
|
||||
return;
|
||||
}
|
||||
setTimeout(() => {
|
||||
this.stopScan();
|
||||
resolve(Array.from(latest.values()));
|
||||
}, Math.max(500, timeoutMs));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function buildAddressSet(candidates: DiscoveredDevice[]): DiscoveredAddressSet {
|
||||
const latestForRole = new Map<DiscoveredDevice["role"], DiscoveredDevice>();
|
||||
for (const candidate of candidates) {
|
||||
latestForRole.set(candidate.role, candidate);
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
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 selected = {
|
||||
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 ?? "",
|
||||
};
|
||||
const lines = candidates.map((candidate) => `${candidate.role}: ${candidate.name} ${candidate.address}`);
|
||||
return {
|
||||
...selected,
|
||||
summary: lines.length ? lines.join("\n") : "No matching devices found.",
|
||||
};
|
||||
}
|
||||
|
||||
function parseCandidates(json: string): DiscoveredDevice[] {
|
||||
const raw = JSON.parse(json) as Array<Record<string, unknown>>;
|
||||
return raw
|
||||
.map((item) => ({
|
||||
address: String(item.address ?? ""),
|
||||
name: String(item.name ?? ""),
|
||||
role: String(item.role ?? "") as DiscoveredDevice["role"],
|
||||
source: String(item.source ?? "") as DiscoveredDevice["source"],
|
||||
}))
|
||||
.filter((item) => !!item.address && (item.role === "left" || item.role === "right" || item.role === "ring"));
|
||||
function parseRawArray(json: string): RawAdvertisement[] {
|
||||
const items = JSON.parse(json) as unknown[];
|
||||
return items.map((item) => parseRawObject(item)).filter((item): item is RawAdvertisement => !!item);
|
||||
}
|
||||
|
||||
function parseRaw(json: string): RawAdvertisement | null {
|
||||
try {
|
||||
return parseRawObject(JSON.parse(json));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function parseRawObject(item: unknown): RawAdvertisement | null {
|
||||
if (!item || typeof item !== "object") return null;
|
||||
const record = item as Record<string, unknown>;
|
||||
const address = String(record.address ?? "");
|
||||
if (!address) return null;
|
||||
return {
|
||||
address,
|
||||
name: String(record.name ?? ""),
|
||||
manufacturerData: String(record.manufacturerData ?? ""),
|
||||
rssi: numberOrNull(record.rssi),
|
||||
txPower: numberOrNull(record.txPower),
|
||||
connectable: typeof record.connectable === "boolean" ? record.connectable : null,
|
||||
bonded: record.bonded === true,
|
||||
source: record.source === "paired" ? "paired" : "scan",
|
||||
seenAtMs: numberOrNull(record.seenAtMs) ?? Date.now(),
|
||||
};
|
||||
}
|
||||
|
||||
function numberOrNull(value: unknown): number | null {
|
||||
if (value === null || value === undefined) return null;
|
||||
const n = Number(value);
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
@@ -1,37 +1,47 @@
|
||||
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo">
|
||||
<ActionBar title="Configure Devices" />
|
||||
|
||||
<GridLayout rows="auto,auto,auto,auto,auto,auto,auto,*" class="p-20">
|
||||
<GridLayout rows="auto,auto,auto,auto,auto,auto,auto,auto,*" class="p-20">
|
||||
<Label row="0" text="Configure the MAC addresses for the G2 headset arms and optional R1 ring. This page does not test a connection." textWrap="true" />
|
||||
|
||||
<StackLayout row="1" class="m-t-16">
|
||||
<GridLayout row="1" columns="96,*" class="pairing-row m-t-12" visibility="{{ identityVisibility }}">
|
||||
<Image col="0" src="{{ identityImagePath }}" stretch="aspectFit" width="90" height="34" />
|
||||
<StackLayout col="1" class="m-l-8">
|
||||
<Label text="{{ identityTitle }}" class="pairing-title" />
|
||||
<Label text="{{ identityVariant }}" class="pairing-variant" visibility="{{ identityVariantVisibility }}" />
|
||||
<Label text="{{ identitySerial }}" class="pairing-serial" />
|
||||
<Label text="{{ identityDetail }}" class="pairing-arms" textWrap="true" />
|
||||
</StackLayout>
|
||||
</GridLayout>
|
||||
|
||||
<StackLayout row="2" class="m-t-16">
|
||||
<Label text="Right arm MAC" />
|
||||
<TextField text="{{ rightAddress }}" textChange="{{ onRightAddressTextChange }}" autocorrect="false" autocapitalizationType="none" />
|
||||
</StackLayout>
|
||||
|
||||
<StackLayout row="2" class="m-t-12">
|
||||
<StackLayout row="3" class="m-t-12">
|
||||
<Label text="Left arm MAC" />
|
||||
<TextField text="{{ leftAddress }}" textChange="{{ onLeftAddressTextChange }}" autocorrect="false" autocapitalizationType="none" />
|
||||
</StackLayout>
|
||||
|
||||
<StackLayout row="3" class="m-t-12">
|
||||
<StackLayout row="4" class="m-t-12">
|
||||
<Label text="R1 ring MAC (optional)" />
|
||||
<TextField text="{{ ringAddress }}" textChange="{{ onRingAddressTextChange }}" autocorrect="false" autocapitalizationType="none" />
|
||||
</StackLayout>
|
||||
|
||||
<GridLayout row="4" columns="*,*" class="m-t-16">
|
||||
<GridLayout row="5" columns="*,*" class="m-t-16">
|
||||
<Button col="0" text="Load paired devices" tap="{{ onLoadPairedTap }}" class="-primary" isEnabled="{{ canDiscover }}" />
|
||||
<Button col="1" text="Scan nearby" tap="{{ onScanTap }}" class="-primary" isEnabled="{{ canDiscover }}" />
|
||||
<Button col="1" text="Scan for glasses" tap="{{ onScanTap }}" class="-primary" isEnabled="{{ canDiscover }}" />
|
||||
</GridLayout>
|
||||
|
||||
<Label row="5" text="{{ status }}" class="m-t-16" textWrap="true" />
|
||||
<Label row="6" text="{{ status }}" class="m-t-16" textWrap="true" />
|
||||
|
||||
<GridLayout row="6" columns="*,*" class="m-t-16">
|
||||
<GridLayout row="7" columns="*,*" class="m-t-16">
|
||||
<Button col="0" text="{{ saveLabel }}" tap="{{ onSaveTap }}" class="-primary" />
|
||||
<Button col="1" text="Back" tap="{{ onBackTap }}" />
|
||||
</GridLayout>
|
||||
|
||||
<ScrollView row="7" class="m-t-16">
|
||||
<ScrollView row="8" class="m-t-16">
|
||||
<Label text="{{ discoveryLog }}" textWrap="true" verticalAlignment="top" />
|
||||
</ScrollView>
|
||||
</GridLayout>
|
||||
|
||||
@@ -1,7 +1,16 @@
|
||||
import { Frame, Observable } from "@nativescript/core";
|
||||
|
||||
import { ensureBlePermissions } from "../g2/android-permissions";
|
||||
import { isValidMacAddress, loadDeviceAddresses, normalizeMacAddress, saveDeviceAddresses } from "../g2/device-addresses";
|
||||
import {
|
||||
isValidMacAddress,
|
||||
loadDeviceAddresses,
|
||||
loadPairedGlassesIdentityForAddresses,
|
||||
normalizeMacAddress,
|
||||
saveDeviceAddresses,
|
||||
type PairedGlassesIdentity,
|
||||
} from "../g2/device-addresses";
|
||||
import { glassesImagePath } from "../g2/glasses-artwork";
|
||||
import { GlassesHardwareIdentity } from "../g2/glasses-hardware-identity";
|
||||
import { buildAddressSet, DeviceDiscoveryBridge } from "../native/device-discovery";
|
||||
|
||||
type TextChangeArgs = { value?: string; object?: { text?: string } };
|
||||
@@ -15,6 +24,7 @@ export class ConfigViewModel extends Observable {
|
||||
private _status = "";
|
||||
private _discoveryLog = "";
|
||||
private _discovering = false;
|
||||
private pairedIdentity: PairedGlassesIdentity | null = null;
|
||||
|
||||
constructor(options?: { onboarding?: boolean }) {
|
||||
super();
|
||||
@@ -23,9 +33,69 @@ export class ConfigViewModel extends Observable {
|
||||
this.rightAddress = stored.right;
|
||||
this.leftAddress = stored.left;
|
||||
this.ringAddress = stored.ring;
|
||||
this.refreshIdentity();
|
||||
this.status = this.onboarding
|
||||
? "Load the addresses from the glasses you paired with the official Even app, or scan / enter them, then Continue."
|
||||
: "Edit addresses manually, or load them from paired devices or a scan.";
|
||||
? "Scan for glasses to pick yours by model and serial, load the addresses of devices paired with this phone, or enter them by hand, then Continue."
|
||||
: "Edit addresses manually, scan for glasses, or load them from paired devices.";
|
||||
}
|
||||
|
||||
// --- paired identity card --------------------------------------------------
|
||||
|
||||
/** The identity saved by the pairing scan, shown only while it still describes the entered addresses. */
|
||||
private refreshIdentity(): void {
|
||||
this.pairedIdentity = loadPairedGlassesIdentityForAddresses({
|
||||
right: this._rightAddress,
|
||||
left: this._leftAddress,
|
||||
ring: this._ringAddress,
|
||||
});
|
||||
for (const property of [
|
||||
"identityVisibility",
|
||||
"identityImagePath",
|
||||
"identityTitle",
|
||||
"identityVariant",
|
||||
"identityVariantVisibility",
|
||||
"identitySerial",
|
||||
"identityDetail",
|
||||
] as const) {
|
||||
this.notifyPropertyChange(property, this[property]);
|
||||
}
|
||||
}
|
||||
|
||||
private get decodedIdentity(): GlassesHardwareIdentity | null {
|
||||
return GlassesHardwareIdentity.decode(this.pairedIdentity?.serial);
|
||||
}
|
||||
|
||||
get identityVisibility(): "visible" | "collapse" {
|
||||
return this.pairedIdentity ? "visible" : "collapse";
|
||||
}
|
||||
|
||||
get identityImagePath(): string {
|
||||
return glassesImagePath(this.decodedIdentity);
|
||||
}
|
||||
|
||||
get identityTitle(): string {
|
||||
return this.decodedIdentity?.productName ?? "Even Realities G2";
|
||||
}
|
||||
|
||||
get identityVariant(): string {
|
||||
return this.decodedIdentity?.variantSummary ?? "";
|
||||
}
|
||||
|
||||
get identityVariantVisibility(): "visible" | "collapse" {
|
||||
return this.identityVariant ? "visible" : "collapse";
|
||||
}
|
||||
|
||||
get identitySerial(): string {
|
||||
return this.pairedIdentity ? `Serial ${this.pairedIdentity.serial}` : "";
|
||||
}
|
||||
|
||||
get identityDetail(): string {
|
||||
const identity = this.pairedIdentity;
|
||||
if (!identity) return "";
|
||||
const parts = [`Left ${identity.leftName || identity.leftAddress}`, `Right ${identity.rightName || identity.rightAddress}`];
|
||||
if (identity.ringName) parts.push(`Ring ${identity.ringName}`);
|
||||
if (identity.pairedAtMs) parts.push(`paired ${new Date(identity.pairedAtMs).toLocaleDateString()}`);
|
||||
return parts.join(" · ");
|
||||
}
|
||||
|
||||
get saveLabel(): string {
|
||||
@@ -100,10 +170,12 @@ export class ConfigViewModel extends Observable {
|
||||
|
||||
onRightAddressTextChange(args: TextChangeArgs): void {
|
||||
this.rightAddress = args.object?.text ?? args.value ?? "";
|
||||
this.refreshIdentity();
|
||||
}
|
||||
|
||||
onLeftAddressTextChange(args: TextChangeArgs): void {
|
||||
this.leftAddress = args.object?.text ?? args.value ?? "";
|
||||
this.refreshIdentity();
|
||||
}
|
||||
|
||||
onRingAddressTextChange(args: TextChangeArgs): void {
|
||||
@@ -114,8 +186,12 @@ export class ConfigViewModel extends Observable {
|
||||
await this.populateFromDiscovery(async () => this.discovery.getBondedCandidates(), "Loaded paired devices.");
|
||||
}
|
||||
|
||||
async onScanTap(): Promise<void> {
|
||||
await this.populateFromDiscovery(async () => this.discovery.scanCandidates(6000), "Scanned nearby devices.");
|
||||
/** The live scan page identifies pairs by serial, model, and distance; hand off to it. */
|
||||
onScanTap(): void {
|
||||
Frame.topmost()?.navigate({
|
||||
moduleName: "phone-ui/pairing-page",
|
||||
context: { onboarding: this.onboarding },
|
||||
});
|
||||
}
|
||||
|
||||
onBackTap(): void {
|
||||
@@ -186,6 +262,7 @@ export class ConfigViewModel extends Observable {
|
||||
if (selection.right) this.rightAddress = selection.right;
|
||||
if (selection.left) this.leftAddress = selection.left;
|
||||
if (selection.ring) this.ringAddress = selection.ring;
|
||||
this.refreshIdentity();
|
||||
this.discoveryLog = selection.summary;
|
||||
this.status = successMessage;
|
||||
} catch (error) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo" loaded="loaded" unloaded="unloaded">
|
||||
<ActionBar title="Faceclaw">
|
||||
<ActionItem text="{{ buttonLabel }}" tap="{{ onTap }}" isEnabled="{{ canRun }}" android.position="popup" />
|
||||
<ActionItem text="Pair glasses" tap="{{ onPairGlassesTap }}" isEnabled="{{ canRun }}" android.position="popup" />
|
||||
<ActionItem text="Configure devices" tap="{{ onConfigureTap }}" isEnabled="{{ canRun }}" android.position="popup" />
|
||||
<ActionItem text="Take screenshot" tap="{{ onTakeScreenshotTap }}" android.position="popup" />
|
||||
<ActionItem text="Record screen" tap="{{ onRecordScreenTap }}" android.position="popup" />
|
||||
|
||||
@@ -510,6 +510,23 @@ export class MainViewModel extends Observable {
|
||||
Frame.topmost()?.navigate("phone-ui/config-page");
|
||||
}
|
||||
|
||||
/**
|
||||
* Live scan that names each nearby pair by model, colour, and serial and
|
||||
* checks both arms belong together. A connected arm stops advertising, so
|
||||
* drop the current link first; autoConnect picks it back up afterwards.
|
||||
*/
|
||||
async onPairGlassesTap(): Promise<void> {
|
||||
if (!this.canRun) return;
|
||||
if (this.phase === "connected" || this.phase === "charging" || this.phase === "connecting") {
|
||||
try {
|
||||
await dashboardController.disconnect();
|
||||
} catch {
|
||||
// proceed anyway; the pairing page reports what it hears
|
||||
}
|
||||
}
|
||||
Frame.topmost()?.navigate({ moduleName: "phone-ui/pairing-page", context: { onboarding: false } });
|
||||
}
|
||||
|
||||
async onInstallFirmwareTap(): Promise<void> {
|
||||
await this.openFlashPage("install");
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ export class OnboardingUnpairViewModel extends Observable {
|
||||
return;
|
||||
}
|
||||
frame?.navigate({
|
||||
moduleName: "phone-ui/config-page",
|
||||
moduleName: "phone-ui/pairing-page",
|
||||
context: { onboarding: true },
|
||||
clearHistory: true,
|
||||
});
|
||||
|
||||
@@ -41,7 +41,7 @@ const STEP_CONTENT: Record<OnboardingStep, StepContent> = {
|
||||
headline: "Custom Firmware Required",
|
||||
tagline: "",
|
||||
body:
|
||||
"Faceclaw only runs on Even Realities G2 glasses that have Faceclaw's custom firmware installed. You have two choices:\n\n• Preview Only — explore Faceclaw's interface on your phone's screen without pairing any glasses. Nothing is written to a headset.\n\n• Flash Firmware — install the custom firmware on your glasses now, then use Faceclaw for real. This connects to your glasses, asks for confirmation on the lens, then downloads and prepares the firmware.\n\nFlashing replaces the official firmware. It may void your warranty and, like any firmware update, carries a risk of bricking the device. You can only be connected to one app at a time, so disconnect the official Even app before flashing (open it, go to Home, select your glasses, open Connection, and press Disconnect).",
|
||||
"Faceclaw only runs on Even Realities G2 glasses that have Faceclaw's custom firmware installed. You have two choices:\n\n• Preview Only — explore Faceclaw's interface on your phone's screen without pairing any glasses. Nothing is written to a headset.\n\n• Flash Firmware — install the custom firmware on your glasses now, then use Faceclaw for real. Faceclaw first scans for nearby glasses so you can pick yours by model, colour, and serial, then connects, asks for confirmation on the lens, and downloads and prepares the firmware.\n\nFlashing replaces the official firmware. It may void your warranty and, like any firmware update, carries a risk of bricking the device. You can only be connected to one app at a time, so disconnect the official Even app before flashing (open it, go to Home, select your glasses, open Connection, and press Disconnect).",
|
||||
primaryLabel: "Flash Firmware",
|
||||
secondaryLabel: "Preview Only",
|
||||
showLogo: false,
|
||||
@@ -67,10 +67,11 @@ export class OnboardingViewModel extends Observable {
|
||||
this.setStep(3);
|
||||
return;
|
||||
}
|
||||
// Step 3 primary: begin the flashing setup — configure device addresses,
|
||||
// then unpair the official app, then check firmware and flash.
|
||||
// Step 3 primary: begin the flashing setup — scan for and pick the glasses
|
||||
// (manual address entry is offered from that page), then unpair the
|
||||
// official app, then check firmware and flash.
|
||||
Frame.topmost()?.navigate({
|
||||
moduleName: "phone-ui/config-page",
|
||||
moduleName: "phone-ui/pairing-page",
|
||||
context: { onboarding: true },
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { NavigatedData, Page } from "@nativescript/core";
|
||||
|
||||
import { PairingViewModel } from "./pairing-view-model";
|
||||
|
||||
type PairingContext = { onboarding?: boolean } | undefined;
|
||||
|
||||
export function navigatingTo(args: NavigatedData): void {
|
||||
const page = args.object as Page;
|
||||
// Preserve the model across back-navigation (returning from the unpair or
|
||||
// manual-entry pages) so the selection isn't lost; the model restarts its
|
||||
// scan on re-entry.
|
||||
let model = page.bindingContext as PairingViewModel | undefined;
|
||||
if (!model) {
|
||||
const context = args.context as PairingContext;
|
||||
model = new PairingViewModel({ onboarding: context?.onboarding ?? false });
|
||||
page.bindingContext = model;
|
||||
}
|
||||
void model.start();
|
||||
}
|
||||
|
||||
export function navigatingFrom(args: NavigatedData): void {
|
||||
const page = args.object as Page;
|
||||
const model = page.bindingContext as PairingViewModel | undefined;
|
||||
model?.stop();
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo" navigatingFrom="navigatingFrom" actionBarHidden="{{ actionBarHidden }}">
|
||||
<ActionBar title="Pair Glasses" />
|
||||
|
||||
<GridLayout rows="auto,auto,*,auto" class="p-16">
|
||||
<StackLayout row="0">
|
||||
<Label text="{{ headline }}" class="h1 text-center" textWrap="true" />
|
||||
<Label text="{{ instructions }}" class="m-t-8 pairing-instructions" textWrap="true" />
|
||||
</StackLayout>
|
||||
|
||||
<GridLayout row="1" columns="auto,*" class="m-t-12 pairing-status-row">
|
||||
<ActivityIndicator col="0" busy="{{ scanning }}" visibility="{{ scanningVisibility }}" width="22" height="22" />
|
||||
<Label col="1" text="{{ status }}" textWrap="true" class="pairing-status" />
|
||||
</GridLayout>
|
||||
|
||||
<ScrollView row="2" class="m-t-12">
|
||||
<StackLayout>
|
||||
<Label text="Glasses" class="h2 pairing-section" visibility="{{ glassesSectionVisibility }}" />
|
||||
<Label text="{{ emptyGlassesMessage }}" class="pairing-empty" textWrap="true" visibility="{{ emptyGlassesVisibility }}" />
|
||||
<Repeater items="{{ glassesRows }}">
|
||||
<Repeater.itemsLayout>
|
||||
<StackLayout />
|
||||
</Repeater.itemsLayout>
|
||||
<Repeater.itemTemplate>
|
||||
<GridLayout columns="84,*,auto" rows="auto" class="{{ rowClass }}" tap="{{ onRowTap }}">
|
||||
<GridLayout col="0" rows="auto,auto" class="pairing-art">
|
||||
<Image row="0" src="{{ imagePath }}" stretch="aspectFit" width="80" height="30" />
|
||||
<GridLayout row="1" columns="auto,auto" horizontalAlignment="center" class="m-t-4" visibility="{{ swatchVisibility }}">
|
||||
<Label col="0" text="" width="12" height="12" borderRadius="6" backgroundColor="{{ swatchHex }}" />
|
||||
<Label col="1" text="{{ colorwayLabel }}" class="pairing-swatch-label m-l-4" />
|
||||
</GridLayout>
|
||||
</GridLayout>
|
||||
<StackLayout col="1" class="m-l-8">
|
||||
<GridLayout columns="auto,auto">
|
||||
<Label col="0" text="{{ modelTitle }}" class="pairing-title" />
|
||||
<Label col="1" text="{{ badge }}" class="pairing-badge m-l-6" visibility="{{ badgeVisibility }}" />
|
||||
</GridLayout>
|
||||
<Label text="{{ variantSummary }}" class="pairing-variant" visibility="{{ variantVisibility }}" />
|
||||
<Label text="{{ proximityLine }}" class="{{ proximityClass }}" />
|
||||
<Label text="{{ deviceName }}" class="pairing-serial" />
|
||||
<Label text="{{ armsSummary }}" class="pairing-arms" textWrap="true" />
|
||||
<Label text="{{ warning }}" class="pairing-warning" textWrap="true" visibility="{{ warningVisibility }}" />
|
||||
</StackLayout>
|
||||
<Label col="2" text="{{ chevron }}" class="pairing-chevron" verticalAlignment="center" />
|
||||
</GridLayout>
|
||||
</Repeater.itemTemplate>
|
||||
</Repeater>
|
||||
|
||||
<Label text="Ring (optional)" class="h2 pairing-section m-t-16" />
|
||||
<Label text="{{ emptyRingMessage }}" class="pairing-empty" textWrap="true" visibility="{{ emptyRingVisibility }}" />
|
||||
<Repeater items="{{ ringRows }}">
|
||||
<Repeater.itemsLayout>
|
||||
<StackLayout />
|
||||
</Repeater.itemsLayout>
|
||||
<Repeater.itemTemplate>
|
||||
<GridLayout columns="84,*,auto" rows="auto" class="{{ rowClass }}" tap="{{ onRowTap }}">
|
||||
<Image col="0" src="{{ imagePath }}" stretch="aspectFit" width="56" height="30" class="pairing-art" />
|
||||
<StackLayout col="1" class="m-l-8">
|
||||
<GridLayout columns="auto,auto">
|
||||
<Label col="0" text="{{ modelTitle }}" class="pairing-title" />
|
||||
<Label col="1" text="{{ badge }}" class="pairing-badge m-l-6" visibility="{{ badgeVisibility }}" />
|
||||
</GridLayout>
|
||||
<Label text="{{ proximityLine }}" class="{{ proximityClass }}" />
|
||||
<Label text="{{ deviceName }}" class="pairing-serial" />
|
||||
<Label text="{{ armsSummary }}" class="pairing-arms" textWrap="true" />
|
||||
<Label text="{{ warning }}" class="pairing-warning" textWrap="true" visibility="{{ warningVisibility }}" />
|
||||
</StackLayout>
|
||||
<Label col="2" text="{{ chevron }}" class="pairing-chevron" verticalAlignment="center" />
|
||||
</GridLayout>
|
||||
</Repeater.itemTemplate>
|
||||
</Repeater>
|
||||
|
||||
<StackLayout class="pairing-selection m-t-16" visibility="{{ selectionVisibility }}">
|
||||
<Label text="Selected" class="h2 pairing-section" />
|
||||
<Label text="{{ selectionSummary }}" textWrap="true" />
|
||||
</StackLayout>
|
||||
|
||||
<Label text="{{ diagnostics }}" class="pairing-diagnostics m-t-16" textWrap="true" visibility="{{ diagnosticsVisibility }}" />
|
||||
</StackLayout>
|
||||
</ScrollView>
|
||||
|
||||
<StackLayout row="3" class="m-t-12">
|
||||
<GridLayout columns="*,*">
|
||||
<Button col="0" text="{{ secondaryLabel }}" tap="{{ onSecondaryTap }}" />
|
||||
<Button col="1" text="{{ primaryLabel }}" tap="{{ onPrimaryTap }}" class="-primary" isEnabled="{{ primaryEnabled }}" />
|
||||
</GridLayout>
|
||||
<GridLayout columns="*,*" class="m-t-4">
|
||||
<Button col="0" text="{{ scanToggleLabel }}" tap="{{ onScanToggleTap }}" class="pairing-link" />
|
||||
<Button col="1" text="Enter addresses manually" tap="{{ onManualTap }}" class="pairing-link" />
|
||||
</GridLayout>
|
||||
</StackLayout>
|
||||
</GridLayout>
|
||||
</Page>
|
||||
@@ -0,0 +1,439 @@
|
||||
import { EventData, Frame, Observable, View } from "@nativescript/core";
|
||||
|
||||
import { ensureBlePermissions } from "../g2/android-permissions";
|
||||
import { loadDeviceAddresses, loadPairedGlassesIdentity, saveDeviceAddresses, savePairedGlassesIdentity } from "../g2/device-addresses";
|
||||
import {
|
||||
colorwayLabel,
|
||||
DEFAULT_STALE_AFTER_MS,
|
||||
DiscoveryAggregator,
|
||||
glassesRow,
|
||||
nearestCandidateId,
|
||||
ringRow,
|
||||
type GlassesPairCandidate,
|
||||
type PairingRowPresentation,
|
||||
type RingCandidate,
|
||||
} from "../g2/pairing-candidates";
|
||||
import { DeviceDiscoveryBridge } from "../native/device-discovery";
|
||||
import { setPreviewOnlyMode } from "./onboarding-state";
|
||||
|
||||
/** One Repeater row: the presentation plus the display-only fields the XML binds. */
|
||||
export type PairingRowItem = PairingRowPresentation & {
|
||||
rowClass: string;
|
||||
swatchVisibility: "visible" | "collapse";
|
||||
colorwayLabel: string;
|
||||
badgeVisibility: "visible" | "collapse";
|
||||
variantVisibility: "visible" | "collapse";
|
||||
proximityLine: string;
|
||||
proximityClass: string;
|
||||
warningVisibility: "visible" | "collapse";
|
||||
chevron: string;
|
||||
/**
|
||||
* Tap handler carried on the row itself. The Repeater assigns a row's
|
||||
* bindingContext before attaching it to the tree, so a `$parents['Page']`
|
||||
* binding cannot resolve on first bind and logs an error every refresh;
|
||||
* binding `tap="{{ onRowTap }}"` against the item avoids the walk entirely.
|
||||
*/
|
||||
onRowTap: (args: EventData) => void;
|
||||
};
|
||||
|
||||
const REFRESH_INTERVAL_MS = 500;
|
||||
const NO_RESULTS_HINT_AFTER_MS = 10_000;
|
||||
|
||||
/**
|
||||
* Live pairing scan. Streams advertisements into a `DiscoveryAggregator`,
|
||||
* re-renders the pair/ring lists at a calm cadence, and saves the chosen
|
||||
* addresses plus the decoded identity when the user continues.
|
||||
*
|
||||
* Selection is always a deliberate tap (no auto-select on a single result),
|
||||
* mirroring SybilSight's pairing flow: a strong signal is a hint, not consent.
|
||||
*/
|
||||
export class PairingViewModel extends Observable {
|
||||
private readonly onboarding: boolean;
|
||||
private readonly aggregator = new DiscoveryAggregator();
|
||||
private discovery: DeviceDiscoveryBridge | null = null;
|
||||
private refreshTimer: ReturnType<typeof setInterval> | null = null;
|
||||
private startedAtMs = 0;
|
||||
private advertisementCount = 0;
|
||||
private scanFailure = "";
|
||||
private readonly logLines: string[] = [];
|
||||
|
||||
private _scanning = false;
|
||||
private _status = "";
|
||||
private _glassesRows: PairingRowItem[] = [];
|
||||
private _ringRows: PairingRowItem[] = [];
|
||||
private selectedPair: GlassesPairCandidate | null = null;
|
||||
private selectedRing: RingCandidate | null = null;
|
||||
private readonly previouslyPairedSerial: string | null;
|
||||
private readonly previouslyPairedRing: string;
|
||||
|
||||
constructor(options?: { onboarding?: boolean }) {
|
||||
super();
|
||||
this.onboarding = options?.onboarding ?? false;
|
||||
this.previouslyPairedSerial = loadPairedGlassesIdentity()?.serial ?? null;
|
||||
this.previouslyPairedRing = loadDeviceAddresses().ring;
|
||||
}
|
||||
|
||||
// --- lifecycle -------------------------------------------------------------
|
||||
|
||||
async start(): Promise<void> {
|
||||
if (this._scanning) return;
|
||||
if (!global.isAndroid) {
|
||||
this.status = "Pairing is only available on Android.";
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await ensureBlePermissions();
|
||||
} catch (error) {
|
||||
this.status = this.formatError(error);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
this.discovery ??= new DeviceDiscoveryBridge();
|
||||
} catch (error) {
|
||||
this.status = this.formatError(error);
|
||||
return;
|
||||
}
|
||||
if (!this.discovery.bluetoothEnabled) {
|
||||
this.status = "Bluetooth is off. Turn it on, then tap Scan.";
|
||||
return;
|
||||
}
|
||||
this.scanFailure = "";
|
||||
this.startedAtMs = Date.now();
|
||||
const started = this.discovery.startScan({
|
||||
onAdvertisement: (raw) => {
|
||||
if (this.aggregator.ingest(raw)) this.advertisementCount += 1;
|
||||
},
|
||||
onScanFailed: (_code, message) => {
|
||||
this.scanFailure = message;
|
||||
this.scanning = false;
|
||||
this.refresh();
|
||||
},
|
||||
onLog: (line) => this.appendLog(line),
|
||||
});
|
||||
if (!started) {
|
||||
this.status = "Could not start the Bluetooth scan. Check that Bluetooth is on.";
|
||||
return;
|
||||
}
|
||||
// Bonded arms show up immediately (no signal) and gain a serial once heard.
|
||||
this.discovery.emitBondedDevices();
|
||||
this.scanning = true;
|
||||
this.refreshTimer ??= setInterval(() => this.refresh(), REFRESH_INTERVAL_MS);
|
||||
this.refresh();
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
if (this.refreshTimer) {
|
||||
clearInterval(this.refreshTimer);
|
||||
this.refreshTimer = null;
|
||||
}
|
||||
this.discovery?.stopScan();
|
||||
this.scanning = false;
|
||||
this.refresh();
|
||||
}
|
||||
|
||||
// --- observable properties -------------------------------------------------
|
||||
|
||||
get actionBarHidden(): boolean {
|
||||
return this.onboarding;
|
||||
}
|
||||
|
||||
get headline(): string {
|
||||
return this.onboarding ? "Pair Your Glasses" : "Pair Glasses";
|
||||
}
|
||||
|
||||
get instructions(): string {
|
||||
return (
|
||||
"Take the glasses out of their case (or open the lid) and keep them next to the phone. " +
|
||||
"Each arm advertises its serial; a pair is ready when both arms report the same one. " +
|
||||
"An arm connected to the official Even app stops advertising — disconnect it there first."
|
||||
);
|
||||
}
|
||||
|
||||
get scanning(): boolean {
|
||||
return this._scanning;
|
||||
}
|
||||
|
||||
set scanning(value: boolean) {
|
||||
if (this._scanning === value) return;
|
||||
this._scanning = value;
|
||||
this.notifyPropertyChange("scanning", value);
|
||||
this.notifyPropertyChange("scanningVisibility", this.scanningVisibility);
|
||||
this.notifyPropertyChange("scanToggleLabel", this.scanToggleLabel);
|
||||
}
|
||||
|
||||
get scanningVisibility(): "visible" | "collapse" {
|
||||
return this._scanning ? "visible" : "collapse";
|
||||
}
|
||||
|
||||
get scanToggleLabel(): string {
|
||||
return this._scanning ? "Pause scan" : "Scan again";
|
||||
}
|
||||
|
||||
get status(): string {
|
||||
return this._status;
|
||||
}
|
||||
|
||||
set status(value: string) {
|
||||
if (this._status === value) return;
|
||||
this._status = value;
|
||||
this.notifyPropertyChange("status", value);
|
||||
}
|
||||
|
||||
get glassesRows(): PairingRowItem[] {
|
||||
return this._glassesRows;
|
||||
}
|
||||
|
||||
get ringRows(): PairingRowItem[] {
|
||||
return this._ringRows;
|
||||
}
|
||||
|
||||
get glassesSectionVisibility(): "visible" | "collapse" {
|
||||
return "visible";
|
||||
}
|
||||
|
||||
get emptyGlassesVisibility(): "visible" | "collapse" {
|
||||
return this._glassesRows.length ? "collapse" : "visible";
|
||||
}
|
||||
|
||||
get emptyGlassesMessage(): string {
|
||||
if (this.scanFailure) return `Scan failed: ${this.scanFailure}`;
|
||||
if (!this._scanning) return "Scan paused. Tap Scan again to look for glasses.";
|
||||
const elapsed = Date.now() - this.startedAtMs;
|
||||
if (elapsed < NO_RESULTS_HINT_AFTER_MS) return "Listening for glasses…";
|
||||
return (
|
||||
"No glasses heard yet. Make sure they are out of the case and not connected to another app. " +
|
||||
"On Android 11 and older, Location must also be switched on for Bluetooth scanning to return results."
|
||||
);
|
||||
}
|
||||
|
||||
get emptyRingVisibility(): "visible" | "collapse" {
|
||||
return this._ringRows.length ? "collapse" : "visible";
|
||||
}
|
||||
|
||||
get emptyRingMessage(): string {
|
||||
return this._scanning ? "No ring heard yet. Tap the ring to wake it if you have one." : "";
|
||||
}
|
||||
|
||||
get selectionVisibility(): "visible" | "collapse" {
|
||||
return this.selectedPair || this.selectedRing ? "visible" : "collapse";
|
||||
}
|
||||
|
||||
get selectionSummary(): string {
|
||||
const parts: string[] = [];
|
||||
if (this.selectedPair) {
|
||||
const identity = this.selectedPair.identity;
|
||||
const label = identity ? identity.displayName : "Even Realities G2";
|
||||
parts.push(
|
||||
`${label} · serial ${this.selectedPair.serial ?? "unknown"}\n` +
|
||||
`Left ${this.selectedPair.left?.address ?? "?"} · Right ${this.selectedPair.right?.address ?? "?"}`,
|
||||
);
|
||||
}
|
||||
if (this.selectedRing) {
|
||||
parts.push(`Ring ${this.selectedRing.advertisement.name} · ${this.selectedRing.advertisement.address}`);
|
||||
}
|
||||
return parts.join("\n");
|
||||
}
|
||||
|
||||
get primaryLabel(): string {
|
||||
return this.onboarding ? "Continue" : "Save";
|
||||
}
|
||||
|
||||
get primaryEnabled(): boolean {
|
||||
return !!this.selectedPair || (!this.onboarding && !!this.selectedRing);
|
||||
}
|
||||
|
||||
get secondaryLabel(): string {
|
||||
return this.onboarding ? "Back" : "Cancel";
|
||||
}
|
||||
|
||||
get diagnostics(): string {
|
||||
return this.logLines.slice(-12).join("\n");
|
||||
}
|
||||
|
||||
get diagnosticsVisibility(): "visible" | "collapse" {
|
||||
return this.logLines.length ? "visible" : "collapse";
|
||||
}
|
||||
|
||||
// --- actions ---------------------------------------------------------------
|
||||
|
||||
// Arrow property: NativeScript fires XML event handlers with `this` bound to the
|
||||
// tapped view's bindingContext (the row item), not the view model.
|
||||
readonly onRowTap = (args: EventData): void => {
|
||||
const row = (args.object as View).bindingContext as PairingRowItem | undefined;
|
||||
if (!row) return;
|
||||
if (row.kind === "glasses") {
|
||||
const pair = this.aggregator.pairs().find((candidate) => candidate.id === row.id) ?? null;
|
||||
if (!pair) return;
|
||||
if (!row.canSelect) {
|
||||
this.status = row.warning || `${row.modelTitle}: ${row.armsSummary}. Both arms must be heard before pairing.`;
|
||||
return;
|
||||
}
|
||||
this.selectedPair = this.selectedPair?.id === pair.id ? null : pair;
|
||||
} else {
|
||||
const ring = this.aggregator.rings().find((candidate) => candidate.id === row.id) ?? null;
|
||||
this.selectedRing = this.selectedRing?.id === ring?.id ? null : ring;
|
||||
}
|
||||
this.refresh();
|
||||
};
|
||||
|
||||
onPrimaryTap(): void {
|
||||
const pair = this.selectedPair;
|
||||
const ring = this.selectedRing;
|
||||
if (!pair && !ring) return;
|
||||
const existing = loadDeviceAddresses();
|
||||
const addresses = {
|
||||
right: pair?.right?.address ?? existing.right,
|
||||
left: pair?.left?.address ?? existing.left,
|
||||
ring: ring?.advertisement.address ?? existing.ring,
|
||||
};
|
||||
saveDeviceAddresses(addresses);
|
||||
if (pair?.left && pair.right) {
|
||||
savePairedGlassesIdentity({
|
||||
serial: pair.serial ?? "",
|
||||
leftName: pair.left.name,
|
||||
rightName: pair.right.name,
|
||||
leftAddress: pair.left.address,
|
||||
rightAddress: pair.right.address,
|
||||
ringName: ring?.advertisement.name ?? (addresses.ring === existing.ring ? (loadPairedGlassesIdentity()?.ringName ?? "") : ""),
|
||||
ringAddress: addresses.ring,
|
||||
pairedAtMs: Date.now(),
|
||||
});
|
||||
}
|
||||
this.stop();
|
||||
if (this.onboarding) {
|
||||
setPreviewOnlyMode(false);
|
||||
// Continue the onboarding chain: unpair the official app next.
|
||||
Frame.topmost()?.navigate({ moduleName: "phone-ui/onboarding-unpair-page" });
|
||||
return;
|
||||
}
|
||||
Frame.topmost()?.navigate({ moduleName: "phone-ui/main-page", clearHistory: true });
|
||||
}
|
||||
|
||||
onSecondaryTap(): void {
|
||||
this.stop();
|
||||
const frame = Frame.topmost();
|
||||
if (frame?.canGoBack()) {
|
||||
frame.goBack();
|
||||
return;
|
||||
}
|
||||
frame?.navigate({
|
||||
moduleName: this.onboarding ? "phone-ui/onboarding-page" : "phone-ui/main-page",
|
||||
clearHistory: true,
|
||||
});
|
||||
}
|
||||
|
||||
onManualTap(): void {
|
||||
this.stop();
|
||||
Frame.topmost()?.navigate({
|
||||
moduleName: "phone-ui/config-page",
|
||||
context: { onboarding: this.onboarding },
|
||||
});
|
||||
}
|
||||
|
||||
onScanToggleTap(): void {
|
||||
if (this._scanning) {
|
||||
this.stop();
|
||||
return;
|
||||
}
|
||||
this.aggregator.clear();
|
||||
this.advertisementCount = 0;
|
||||
void this.start();
|
||||
}
|
||||
|
||||
// --- rendering -------------------------------------------------------------
|
||||
|
||||
private refresh(): void {
|
||||
this.aggregator.prune(Date.now(), DEFAULT_STALE_AFTER_MS);
|
||||
const pairs = this.aggregator.pairs();
|
||||
const rings = this.aggregator.rings();
|
||||
|
||||
// Keep the selection pointing at live data (addresses can only change if a
|
||||
// side was replaced); drop it if the pair disappeared.
|
||||
if (this.selectedPair) {
|
||||
this.selectedPair = pairs.find((pair) => pair.id === this.selectedPair!.id) ?? null;
|
||||
}
|
||||
if (this.selectedRing) {
|
||||
this.selectedRing = rings.find((ring) => ring.id === this.selectedRing!.id) ?? null;
|
||||
}
|
||||
|
||||
const nearestPair = nearestCandidateId(pairs);
|
||||
const nearestRing = nearestCandidateId(rings);
|
||||
this._glassesRows = pairs.map((pair) =>
|
||||
toRowItem(
|
||||
glassesRow(pair, { pairedSerial: this.previouslyPairedSerial, nearestId: nearestPair }),
|
||||
this.selectedPair?.id === pair.id,
|
||||
this.onRowTap,
|
||||
),
|
||||
);
|
||||
this._ringRows = rings.map((ring) =>
|
||||
toRowItem(
|
||||
ringRow(ring, { pairedRingAddress: this.previouslyPairedRing, nearestId: nearestRing }),
|
||||
this.selectedRing?.id === ring.id,
|
||||
this.onRowTap,
|
||||
),
|
||||
);
|
||||
|
||||
const complete = pairs.filter((pair) => pair.completeness === "complete").length;
|
||||
const partial = pairs.length - complete;
|
||||
if (this.scanFailure) {
|
||||
this.status = `Scan failed: ${this.scanFailure}`;
|
||||
} else if (!this._scanning) {
|
||||
this.status = pairs.length ? "Scan paused." : "Scan paused.";
|
||||
} else if (!pairs.length && !rings.length) {
|
||||
this.status = "Scanning…";
|
||||
} else {
|
||||
const bits = [
|
||||
complete ? `${complete} ${complete === 1 ? "pair" : "pairs"} ready` : null,
|
||||
partial ? `${partial} with one arm heard` : null,
|
||||
rings.length ? `${rings.length} ${rings.length === 1 ? "ring" : "rings"}` : null,
|
||||
].filter(Boolean);
|
||||
this.status = `Scanning… ${bits.join(" · ")}. Tap a pair to select it.`;
|
||||
}
|
||||
|
||||
for (const property of [
|
||||
"glassesRows",
|
||||
"ringRows",
|
||||
"emptyGlassesVisibility",
|
||||
"emptyGlassesMessage",
|
||||
"emptyRingVisibility",
|
||||
"emptyRingMessage",
|
||||
"selectionVisibility",
|
||||
"selectionSummary",
|
||||
"primaryEnabled",
|
||||
"diagnostics",
|
||||
"diagnosticsVisibility",
|
||||
] as const) {
|
||||
this.notifyPropertyChange(property, this[property]);
|
||||
}
|
||||
}
|
||||
|
||||
private appendLog(line: string): void {
|
||||
this.logLines.push(line);
|
||||
if (this.logLines.length > 50) this.logLines.splice(0, this.logLines.length - 50);
|
||||
}
|
||||
|
||||
private formatError(error: unknown): string {
|
||||
const raw = (error as Error)?.message ?? String(error);
|
||||
return raw.replace(/[\x00-\x1f]+/g, " ").replace(/\s+/g, " ").trim();
|
||||
}
|
||||
}
|
||||
|
||||
function toRowItem(row: PairingRowPresentation, selected: boolean, onRowTap: (args: EventData) => void): PairingRowItem {
|
||||
const classes = ["pairing-row"];
|
||||
if (selected) classes.push("pairing-row-selected");
|
||||
if (!row.canSelect) classes.push("pairing-row-incomplete");
|
||||
return {
|
||||
...row,
|
||||
rowClass: classes.join(" "),
|
||||
// The swatch is redundant when the variant photo already shows the finish.
|
||||
swatchVisibility: row.swatchHex && !row.hasVariantImage ? "visible" : "collapse",
|
||||
colorwayLabel: colorwayLabel(row.colorway),
|
||||
badgeVisibility: row.badge ? "visible" : "collapse",
|
||||
variantVisibility: row.variantSummary ? "visible" : "collapse",
|
||||
proximityLine: `${row.proximityGlyph} ${row.proximitySummary}`,
|
||||
proximityClass: row.zone === "immediate" ? "pairing-proximity pairing-proximity-immediate" : "pairing-proximity",
|
||||
warningVisibility: row.warning ? "visible" : "collapse",
|
||||
chevron: selected ? "✓" : row.canSelect ? "›" : "…",
|
||||
onRowTap,
|
||||
};
|
||||
}
|
||||
@@ -5,7 +5,8 @@
|
||||
"private": false,
|
||||
"scripts": {
|
||||
"build": "nativescript build android",
|
||||
"clean": "rm -rf platforms"
|
||||
"clean": "rm -rf platforms",
|
||||
"test": "tsc -p tests/tsconfig.json && node --test tests/*.test.cjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@evenrealities/pretext": "^0.1.4",
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
# Tests
|
||||
|
||||
Faceclaw's pairing logic (`app/g2/glasses-hardware-identity.ts`,
|
||||
`ble-proximity.ts`, `even-advertisement.ts`, `pairing-candidates.ts`,
|
||||
`glasses-artwork.ts`) is written without NativeScript imports so it can run
|
||||
under plain node. The tests here are ports of SybilSight's
|
||||
`GlassesHardwareIdentityTests` / `BLEProximityTests` plus coverage for the
|
||||
advertisement parsers and left↔right pair grouping.
|
||||
|
||||
Run with:
|
||||
|
||||
npm test
|
||||
|
||||
That compiles the pure modules with the project's TypeScript into
|
||||
`.test-build/` (git-ignored) and runs `node --test tests/`. No extra
|
||||
dependencies are needed — the tests are plain `.test.cjs` files that use
|
||||
`node:test` and `node:assert`.
|
||||
@@ -0,0 +1,112 @@
|
||||
// Ported from SybilSight's BLEProximityTests.
|
||||
//
|
||||
// These pin the parts the pairing screen depends on: that a stronger signal
|
||||
// always sorts first, that the absolute numbers stay inside a plausible band,
|
||||
// and that a missing signal degrades to "unknown" rather than to a fabricated
|
||||
// distance.
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
|
||||
const {
|
||||
estimateProximity,
|
||||
GLASSES_CALIBRATION,
|
||||
RING_CALIBRATION,
|
||||
MINIMUM_METERS,
|
||||
MAXIMUM_METERS,
|
||||
zoneFromMeters,
|
||||
zoneLabel,
|
||||
formatDistance,
|
||||
proximitySummary,
|
||||
sortedByProximity,
|
||||
} = require("../.test-build/app/g2/ble-proximity.js");
|
||||
|
||||
const near = (a, b, eps) => Math.abs(a - b) <= eps;
|
||||
|
||||
test("distance falls as signal weakens", () => {
|
||||
const close = estimateProximity(-40, null, GLASSES_CALIBRATION);
|
||||
const mid = estimateProximity(-70, null, GLASSES_CALIBRATION);
|
||||
const farAway = estimateProximity(-95, null, GLASSES_CALIBRATION);
|
||||
assert.ok(close.meters < mid.meters);
|
||||
assert.ok(mid.meters < farAway.meters);
|
||||
});
|
||||
|
||||
test("the reference power reads as one metre", () => {
|
||||
const estimate = estimateProximity(GLASSES_CALIBRATION.txPowerAtOneMeter, null, GLASSES_CALIBRATION);
|
||||
assert.ok(near(estimate.meters, 1.0, 0.001));
|
||||
assert.equal(estimate.zone, "near");
|
||||
});
|
||||
|
||||
test("estimates stay inside a plausible band", () => {
|
||||
assert.ok(near(estimateProximity(20, null, GLASSES_CALIBRATION).meters, MINIMUM_METERS, 0.0001));
|
||||
assert.ok(near(estimateProximity(-127, null, GLASSES_CALIBRATION).meters, MAXIMUM_METERS, 0.0001));
|
||||
});
|
||||
|
||||
test("an advertised TX power overrides the calibration", () => {
|
||||
const assumed = estimateProximity(-60, null, GLASSES_CALIBRATION);
|
||||
const measured = estimateProximity(-60, -50, GLASSES_CALIBRATION);
|
||||
// A device that says it transmits at -50 dBm at 1 m, heard at -60, is further
|
||||
// away than one assumed to transmit at -62 — and it is trusted more.
|
||||
assert.ok(measured.meters > assumed.meters);
|
||||
assert.ok(measured.confidence > assumed.confidence);
|
||||
});
|
||||
|
||||
test("no signal yields no estimate (127 is the unavailable sentinel)", () => {
|
||||
assert.equal(estimateProximity(null, null, GLASSES_CALIBRATION), null);
|
||||
assert.equal(estimateProximity(undefined, null, GLASSES_CALIBRATION), null);
|
||||
assert.equal(estimateProximity(127, null, GLASSES_CALIBRATION), null);
|
||||
});
|
||||
|
||||
test("zones and their boundaries", () => {
|
||||
assert.equal(zoneFromMeters(0.2), "immediate");
|
||||
assert.equal(zoneFromMeters(0.5), "near");
|
||||
assert.equal(zoneFromMeters(2.9), "near");
|
||||
assert.equal(zoneFromMeters(3), "far");
|
||||
assert.equal(zoneFromMeters(9.9), "far");
|
||||
assert.equal(zoneFromMeters(10), "distant");
|
||||
assert.equal(zoneLabel("immediate"), "In your hand");
|
||||
});
|
||||
|
||||
test("weak signals are marked as approximate", () => {
|
||||
const strong = estimateProximity(-45, -60, GLASSES_CALIBRATION);
|
||||
const weak = estimateProximity(-95, null, GLASSES_CALIBRATION);
|
||||
assert.ok(!formatDistance(strong).startsWith("~"));
|
||||
assert.ok(formatDistance(weak).startsWith("~"));
|
||||
assert.ok(weak.confidence < strong.confidence);
|
||||
});
|
||||
|
||||
test("distance formatting is rounded hard", () => {
|
||||
const centimetres = estimateProximity(-30, -60, GLASSES_CALIBRATION);
|
||||
assert.ok(formatDistance(centimetres).includes("cm"), formatDistance(centimetres));
|
||||
assert.equal(formatDistance({ meters: 2.34, confidence: 1, zone: "near" }), "2.3 m");
|
||||
assert.equal(formatDistance({ meters: 42.6, confidence: 1, zone: "distant" }), "43 m");
|
||||
assert.equal(proximitySummary({ meters: 0.3, confidence: 1, zone: "immediate" }), "In your hand · 30 cm");
|
||||
});
|
||||
|
||||
const device = (id, rssi) => ({ id, rssi });
|
||||
const estimate = (d) => estimateProximity(d.rssi, null, GLASSES_CALIBRATION);
|
||||
const byId = (d) => d.id;
|
||||
|
||||
test("glasses sort closest first", () => {
|
||||
const sorted = sortedByProximity([device("1", -80), device("2", -40), device("3", -60)], estimate, byId);
|
||||
assert.deepEqual(sorted.map(byId), ["2", "3", "1"]);
|
||||
});
|
||||
|
||||
test("devices without a signal sort last and are not dropped", () => {
|
||||
const sorted = sortedByProximity([device("silent", null), device("heard", -70)], estimate, byId);
|
||||
assert.deepEqual(sorted.map(byId), ["heard", "silent"]);
|
||||
});
|
||||
|
||||
test("equal signals keep a stable order", () => {
|
||||
const forward = sortedByProximity([device("b", -60), device("a", -60)], estimate, byId);
|
||||
const reversed = sortedByProximity([device("a", -60), device("b", -60)], estimate, byId);
|
||||
assert.deepEqual(forward.map(byId), ["a", "b"]);
|
||||
assert.deepEqual(reversed.map(byId), forward.map(byId));
|
||||
});
|
||||
|
||||
test("ring and glasses are calibrated separately", () => {
|
||||
// The ring's antenna reads weaker than the glasses at the same distance, so
|
||||
// the same RSSI must not be reported as the same distance for both.
|
||||
const ring = estimateProximity(-70, null, RING_CALIBRATION);
|
||||
const glasses = estimateProximity(-70, null, GLASSES_CALIBRATION);
|
||||
assert.ok(ring.meters < glasses.meters);
|
||||
});
|
||||
@@ -0,0 +1,157 @@
|
||||
// Advertisement parsers, checked against the layouts SybilSight confirmed by
|
||||
// HCI capture (G2: "ER"+SN(14)+MAC(6,LE)+flag) and on-disk forensics (R1:
|
||||
// "ER"+MAC(6,wire)+ASCII serial suffix on ring firmware 2.2.7.x).
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
|
||||
const {
|
||||
hexToBytes,
|
||||
bytesToHex,
|
||||
hasEvenManufacturerSignature,
|
||||
extractG2Serial,
|
||||
extractG2Mac,
|
||||
extractG2AdvertisementFlag,
|
||||
g2SideFromName,
|
||||
g2NameAddressTail,
|
||||
wireBytesFromHumanReadableAddress,
|
||||
humanReadableAddressFromWireBytes,
|
||||
ringNameAddressOctets,
|
||||
ringMacWireBytes,
|
||||
extractRingSerialSuffix,
|
||||
classifyAdvertisement,
|
||||
normalizeAddress,
|
||||
EVEN_COMPANY_IDENTIFIER,
|
||||
} = require("../.test-build/app/g2/even-advertisement.js");
|
||||
|
||||
const ascii = (s) => bytesToHex(Array.from(s).map((c) => c.charCodeAt(0)));
|
||||
|
||||
// Real pair serial S211GBBC180304 at E0:12:14:B6:EC:E0 (HCI capture 2026-04-12).
|
||||
const G2_MFG_HEX = "4552" + ascii("S211GBBC180304") + "E0ECB61412E0" + "01";
|
||||
|
||||
// Ring identity proven on disk: wire E2 6E B5 D2 7F DA ⇄ human DA:7F:D2:B5:6E:E2,
|
||||
// name suffix B56EE2 = human last three octets, followed by ASCII serial "140137".
|
||||
const RING_MFG_HEX = "4552" + "E26EB5D27FDA" + ascii("140137");
|
||||
|
||||
const raw = (overrides) => ({
|
||||
address: "E0:12:14:B6:EC:E0",
|
||||
name: "Even G2_32_L_B6ECE0",
|
||||
manufacturerData: G2_MFG_HEX,
|
||||
rssi: -55,
|
||||
txPower: null,
|
||||
connectable: true,
|
||||
bonded: false,
|
||||
source: "scan",
|
||||
seenAtMs: 1000,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
test("company identifier is the ASCII bytes ER read little-endian", () => {
|
||||
assert.equal(EVEN_COMPANY_IDENTIFIER, 0x5245);
|
||||
assert.ok(hasEvenManufacturerSignature(hexToBytes("4552")));
|
||||
assert.ok(!hasEvenManufacturerSignature(hexToBytes("5245")));
|
||||
});
|
||||
|
||||
test("G2 manufacturer data yields serial, MAC, and flag", () => {
|
||||
const mfg = hexToBytes(G2_MFG_HEX);
|
||||
assert.equal(mfg.length, 23);
|
||||
assert.equal(extractG2Serial(mfg), "S211GBBC180304");
|
||||
assert.equal(extractG2Mac(mfg), "E0:12:14:B6:EC:E0");
|
||||
assert.equal(extractG2AdvertisementFlag(mfg), 1);
|
||||
});
|
||||
|
||||
test("short or binary manufacturer data yields no serial", () => {
|
||||
assert.equal(extractG2Serial(hexToBytes("4552")), null);
|
||||
assert.equal(extractG2Serial(hexToBytes("4552" + "FF".repeat(14))), null);
|
||||
assert.equal(extractG2Mac(hexToBytes("4552" + ascii("S211GBBC180304"))), null);
|
||||
assert.equal(extractG2AdvertisementFlag(hexToBytes(G2_MFG_HEX.slice(0, -2))), null);
|
||||
});
|
||||
|
||||
test("side comes from the local name; the hex tail is per-arm", () => {
|
||||
assert.equal(g2SideFromName("Even G2_32_L_ACD458"), "left");
|
||||
assert.equal(g2SideFromName("Even G2_32_R_8D6E3C"), "right");
|
||||
assert.equal(g2SideFromName("Even G2_32"), null);
|
||||
assert.equal(g2SideFromName("X_L_R_"), null);
|
||||
assert.equal(g2NameAddressTail("Even G2_32_L_ACD458"), "ACD458");
|
||||
assert.equal(g2NameAddressTail("Even G2"), null);
|
||||
});
|
||||
|
||||
test("address codec crosses wire/human order exactly once", () => {
|
||||
const wire = wireBytesFromHumanReadableAddress("DA:7F:D2:B5:6E:E2");
|
||||
assert.equal(bytesToHex(wire), "E26EB5D27FDA");
|
||||
assert.equal(humanReadableAddressFromWireBytes(wire), "DA:7F:D2:B5:6E:E2");
|
||||
assert.equal(wireBytesFromHumanReadableAddress("nope"), null);
|
||||
assert.equal(normalizeAddress("e0ecb61412e0"), "E0:EC:B6:14:12:E0");
|
||||
});
|
||||
|
||||
test("ring name suffix octets parse from the full name and the bare id", () => {
|
||||
assert.deepEqual(ringNameAddressOctets("EVEN R1_B56EE2"), [0xb5, 0x6e, 0xe2]);
|
||||
assert.deepEqual(ringNameAddressOctets("B56EE2"), [0xb5, 0x6e, 0xe2]);
|
||||
assert.equal(ringNameAddressOctets("EVEN R1_B56E"), null);
|
||||
assert.equal(ringNameAddressOctets(null), null);
|
||||
});
|
||||
|
||||
test("ring MAC extraction anchors on the marker and rejects the serial suffix", () => {
|
||||
const mfg = hexToBytes(RING_MFG_HEX);
|
||||
// The historical suffix(6) slice would have returned "140137" as ASCII bytes.
|
||||
assert.equal(bytesToHex(mfg.subarray(mfg.length - 6)), "313430313337");
|
||||
const wire = ringMacWireBytes(mfg, "EVEN R1_B56EE2");
|
||||
assert.equal(bytesToHex(wire), "E26EB5D27FDA");
|
||||
assert.equal(humanReadableAddressFromWireBytes(wire), "DA:7F:D2:B5:6E:E2");
|
||||
assert.equal(extractRingSerialSuffix(mfg), "140137");
|
||||
});
|
||||
|
||||
test("ring MAC extraction fails closed when the name contradicts every window", () => {
|
||||
assert.equal(ringMacWireBytes(hexToBytes(RING_MFG_HEX), "EVEN R1_000000"), null);
|
||||
// Without a verifiable name, the documented marker layout wins.
|
||||
assert.equal(bytesToHex(ringMacWireBytes(hexToBytes(RING_MFG_HEX), null)), "E26EB5D27FDA");
|
||||
});
|
||||
|
||||
test("classifies a G2 left arm with its serial and embedded MAC", () => {
|
||||
const ad = classifyAdvertisement(raw({}));
|
||||
assert.equal(ad.role, "left");
|
||||
assert.equal(ad.serial, "S211GBBC180304");
|
||||
assert.equal(ad.embeddedMac, "E0:12:14:B6:EC:E0");
|
||||
assert.equal(ad.embeddedMacMismatch, false);
|
||||
assert.equal(ad.flag, 1);
|
||||
assert.equal(ad.note, null);
|
||||
});
|
||||
|
||||
test("flags an embedded MAC that disagrees with the radio address", () => {
|
||||
const ad = classifyAdvertisement(raw({ address: "AA:BB:CC:DD:EE:FF", name: "Even G2_32_R_DDEEFF" }));
|
||||
assert.equal(ad.role, "right");
|
||||
assert.equal(ad.embeddedMacMismatch, true);
|
||||
});
|
||||
|
||||
test("renamed firmware is admitted on the ER signature alone", () => {
|
||||
const ad = classifyAdvertisement(raw({ name: "Faceclaw_L_1" }));
|
||||
assert.ok(ad);
|
||||
assert.equal(ad.role, "left");
|
||||
assert.equal(ad.serial, "S211GBBC180304");
|
||||
});
|
||||
|
||||
test("a G2 name without manufacturer data is admitted but carries a note", () => {
|
||||
const ad = classifyAdvertisement(raw({ manufacturerData: "" }));
|
||||
assert.equal(ad.role, "left");
|
||||
assert.equal(ad.serial, null);
|
||||
assert.match(ad.note, /no manufacturer data/);
|
||||
const short = classifyAdvertisement(raw({ manufacturerData: "4552AABB" }));
|
||||
assert.match(short.note, /too short/);
|
||||
});
|
||||
|
||||
test("a G2 advertisement with no side marker cannot be placed in a pair", () => {
|
||||
assert.equal(classifyAdvertisement(raw({ name: "Even G2_32" })), null);
|
||||
});
|
||||
|
||||
test("classifies the ring from its name and validated MAC", () => {
|
||||
const ad = classifyAdvertisement(raw({ address: "DA:7F:D2:B5:6E:E2", name: "EVEN R1_B56EE2", manufacturerData: RING_MFG_HEX }));
|
||||
assert.equal(ad.role, "ring");
|
||||
assert.equal(ad.serial, null);
|
||||
assert.equal(ad.embeddedMac, "DA:7F:D2:B5:6E:E2");
|
||||
assert.equal(ad.embeddedMacMismatch, false);
|
||||
assert.equal(ad.ringSerialSuffix, "140137");
|
||||
});
|
||||
|
||||
test("ignores unrelated advertisers", () => {
|
||||
assert.equal(classifyAdvertisement(raw({ name: "Pixel Buds", manufacturerData: "E000010203" })), null);
|
||||
assert.equal(classifyAdvertisement(raw({ name: "", manufacturerData: "" })), null);
|
||||
});
|
||||
@@ -0,0 +1,132 @@
|
||||
// Ported from SybilSight's GlassesHardwareIdentityTests.
|
||||
//
|
||||
// The reference mapping is the Even Realities app 2.2.0 (`_parseGlassesSku`,
|
||||
// `evenSNName`, `matchModel`). `S211GBBC180304` and `S211GCBC300403` are
|
||||
// serials observed on real hardware, so they are the anchors here rather than
|
||||
// synthetic strings.
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
|
||||
const {
|
||||
GlassesHardwareIdentity,
|
||||
evaluatePairSerials,
|
||||
pairSerialWarning,
|
||||
BUNDLED_VARIANT_ASSET_NAMES,
|
||||
} = require("../.test-build/app/g2/glasses-hardware-identity.js");
|
||||
|
||||
test("decodes an observed G2 serial", () => {
|
||||
const identity = GlassesHardwareIdentity.decode("S211GBBC180304");
|
||||
assert.ok(identity);
|
||||
assert.equal(identity.family, "g2");
|
||||
assert.equal(identity.frame, "b");
|
||||
assert.equal(identity.colorway, "brown");
|
||||
assert.equal(identity.modelCode, "S211");
|
||||
assert.equal(identity.shortSerial, "0304");
|
||||
assert.equal(identity.productName, "Even G2 B");
|
||||
assert.equal(identity.variantSummary, "Frame B · Brown");
|
||||
assert.equal(identity.displayName, "Even G2 B · Brown");
|
||||
});
|
||||
|
||||
test("colour byte at index five selects the finish", () => {
|
||||
assert.equal(GlassesHardwareIdentity.decode("S211GAAA000001").colorway, "grey");
|
||||
assert.equal(GlassesHardwareIdentity.decode("S211GBBC180304").colorway, "brown");
|
||||
assert.equal(GlassesHardwareIdentity.decode("S211GCBC300403").colorway, "green");
|
||||
});
|
||||
|
||||
test("frame prefix table", () => {
|
||||
assert.equal(GlassesHardwareIdentity.decode("S201GAAA000001").frame, "a");
|
||||
assert.equal(GlassesHardwareIdentity.decode("S281GAAA000001").frame, "a");
|
||||
assert.equal(GlassesHardwareIdentity.decode("S211GAAA000001").frame, "b");
|
||||
assert.equal(GlassesHardwareIdentity.decode("S291GAAA000001").frame, "b");
|
||||
assert.equal(GlassesHardwareIdentity.decode("S221GAAA000001").frame, "c");
|
||||
});
|
||||
|
||||
test("unknown G2 prefix keeps the family but claims no shape", () => {
|
||||
// The Even app defaults an unknown prefix to frame A. Identification cannot
|
||||
// afford that: a future SKU must read as "Even G2" with no shape claim.
|
||||
const identity = GlassesHardwareIdentity.decode("S231GBAA000001");
|
||||
assert.equal(identity.family, "g2");
|
||||
assert.equal(identity.frame, null);
|
||||
assert.equal(identity.colorway, "brown");
|
||||
assert.equal(identity.productName, "Even G2");
|
||||
assert.equal(identity.variantSummary, "Brown");
|
||||
});
|
||||
|
||||
test("unknown colour byte claims no finish", () => {
|
||||
const identity = GlassesHardwareIdentity.decode("S211GZAA000001");
|
||||
assert.equal(identity.frame, "b");
|
||||
assert.equal(identity.colorway, null);
|
||||
assert.equal(identity.displayName, "Even G2 B");
|
||||
assert.equal(identity.variantSummary, "Frame B");
|
||||
});
|
||||
|
||||
test("bench-unit colour byte D (seen in HCI capture) decodes to no finish", () => {
|
||||
const identity = GlassesHardwareIdentity.decode("S200LDBE210001");
|
||||
assert.equal(identity.frame, "a");
|
||||
assert.equal(identity.colorway, null);
|
||||
});
|
||||
|
||||
test("G1 and ring families", () => {
|
||||
const g1 = GlassesHardwareIdentity.decode("S110GAAA000001");
|
||||
assert.equal(g1.family, "g1");
|
||||
assert.equal(g1.frame, "b");
|
||||
assert.equal(g1.productName, "Even G1 B");
|
||||
assert.equal(GlassesHardwareIdentity.decode("S100GAAA000001").frame, "a");
|
||||
|
||||
// The ring has neither a frame shape nor a colourway in the Even app's model.
|
||||
const ring = GlassesHardwareIdentity.decode("B210GAAA000001");
|
||||
assert.equal(ring.family, "r1");
|
||||
assert.equal(ring.frame, null);
|
||||
assert.equal(ring.colorway, null);
|
||||
assert.equal(ring.variantSummary, null);
|
||||
assert.equal(ring.displayName, "Even R1");
|
||||
});
|
||||
|
||||
test("arm suffix and case are normalized away", () => {
|
||||
const suffixed = GlassesHardwareIdentity.decode("S211GBBC180304_L_1");
|
||||
const lowercased = GlassesHardwareIdentity.decode(" s211gbbc180304 ");
|
||||
assert.equal(suffixed.serial, "S211GBBC180304");
|
||||
assert.ok(suffixed.equals(lowercased));
|
||||
});
|
||||
|
||||
test("rejects non-Even and truncated serials", () => {
|
||||
assert.equal(GlassesHardwareIdentity.decode("EVEN_G2_ALPHA"), null);
|
||||
assert.equal(GlassesHardwareIdentity.decode("Even G2_32_L_ACD458"), null);
|
||||
assert.equal(GlassesHardwareIdentity.decode("S211G"), null);
|
||||
assert.equal(GlassesHardwareIdentity.decode(""), null);
|
||||
assert.equal(GlassesHardwareIdentity.decode(null), null);
|
||||
assert.equal(GlassesHardwareIdentity.decode(undefined), null);
|
||||
});
|
||||
|
||||
test("known SKUs resolve to their own artwork; frame C and the ring fall back", () => {
|
||||
assert.equal(GlassesHardwareIdentity.decode("S211GBBC180304").imageAssetName, "glasses_g2_b_brown");
|
||||
assert.equal(GlassesHardwareIdentity.decode("S201GAAA000001").imageAssetName, "glasses_g2_a_grey");
|
||||
assert.equal(GlassesHardwareIdentity.decode("S221GAAA000001").imageAssetName, null);
|
||||
assert.equal(GlassesHardwareIdentity.decode("B210GAAA000001").imageAssetName, null);
|
||||
assert.equal(BUNDLED_VARIANT_ASSET_NAMES.size, 6);
|
||||
});
|
||||
|
||||
test("pair serial check verdicts", () => {
|
||||
assert.deepEqual(evaluatePairSerials("S211GBBC180304", "S211GBBC180304"), { kind: "matched", serial: "S211GBBC180304" });
|
||||
// The arm suffix and casing differ but the hardware does not.
|
||||
assert.deepEqual(evaluatePairSerials("S211GBBC180304_L_1", "s211gbbc180304"), { kind: "matched", serial: "S211GBBC180304" });
|
||||
assert.deepEqual(evaluatePairSerials("S211GBBC180304", "S211GCBC300403"), {
|
||||
kind: "mismatched",
|
||||
left: "S211GBBC180304",
|
||||
right: "S211GCBC300403",
|
||||
});
|
||||
assert.deepEqual(evaluatePairSerials("S211GBBC180304", null), { kind: "unknown" });
|
||||
assert.deepEqual(evaluatePairSerials(null, null), { kind: "unknown" });
|
||||
assert.deepEqual(evaluatePairSerials(" ", "S211GBBC180304"), { kind: "unknown" });
|
||||
});
|
||||
|
||||
test("pair serial warning names both serials and only fires on mismatch", () => {
|
||||
assert.equal(pairSerialWarning({ kind: "unknown" }), null);
|
||||
assert.equal(pairSerialWarning({ kind: "matched", serial: "S211GBBC180304" }), null);
|
||||
const warning = pairSerialWarning({ kind: "mismatched", left: "S211GBBC180304", right: "S201GCBC300403" });
|
||||
assert.ok(warning.includes("S211GBBC180304"));
|
||||
assert.ok(warning.includes("S201GCBC300403"));
|
||||
// Different frame AND finish — say so, because the wearer can see that difference.
|
||||
assert.ok(warning.includes("Even G2 B · Brown"));
|
||||
assert.ok(warning.includes("Even G2 A · Green"));
|
||||
});
|
||||
@@ -0,0 +1,250 @@
|
||||
// Left↔right pair grouping on the advertised serial, closest-first ordering,
|
||||
// the "Closest"/"Yours" disambiguators (ported from SybilSight's
|
||||
// PairingScanPresentation tests), and the row presentation.
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
|
||||
const { bytesToHex } = require("../.test-build/app/g2/even-advertisement.js");
|
||||
const {
|
||||
DiscoveryAggregator,
|
||||
nearestCandidateId,
|
||||
isPreviouslyPaired,
|
||||
glassesRow,
|
||||
ringRow,
|
||||
DEFAULT_STALE_AFTER_MS,
|
||||
} = require("../.test-build/app/g2/pairing-candidates.js");
|
||||
const { requiredArtworkFileNames, glassesImagePath, GENERIC_G2_IMAGE_PATH } = require("../.test-build/app/g2/glasses-artwork.js");
|
||||
const { GlassesHardwareIdentity } = require("../.test-build/app/g2/glasses-hardware-identity.js");
|
||||
|
||||
const ascii = (s) => bytesToHex(Array.from(s).map((c) => c.charCodeAt(0)));
|
||||
const wireOf = (human) => bytesToHex(human.split(":").map((h) => parseInt(h, 16)).reverse());
|
||||
|
||||
function arm(side, serial, address, rssi, extra = {}) {
|
||||
const tail = address.replace(/:/g, "").slice(-6);
|
||||
return {
|
||||
address,
|
||||
name: `Even G2_32_${side === "left" ? "L" : "R"}_${tail}`,
|
||||
manufacturerData: "4552" + ascii(serial) + wireOf(address) + "01",
|
||||
rssi,
|
||||
txPower: null,
|
||||
connectable: true,
|
||||
bonded: false,
|
||||
source: "scan",
|
||||
seenAtMs: 1000,
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
function ring(address, rssi, extra = {}) {
|
||||
const tail = address.replace(/:/g, "").slice(-6);
|
||||
return {
|
||||
address,
|
||||
name: `EVEN R1_${tail}`,
|
||||
manufacturerData: "4552" + wireOf(address) + ascii("140137"),
|
||||
rssi,
|
||||
txPower: null,
|
||||
connectable: true,
|
||||
bonded: false,
|
||||
source: "scan",
|
||||
seenAtMs: 1000,
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
// One real pair: the left and right arms carry DIFFERENT name tails (per-arm
|
||||
// address) but the SAME serial. That serial is the pair identity.
|
||||
const LEFT = arm("left", "S211GBBC180304", "E0:12:14:AC:D4:58", -50);
|
||||
const RIGHT = arm("right", "S211GBBC180304", "E0:12:14:8D:6E:3C", -54);
|
||||
const OTHER_RIGHT = arm("right", "S211GCBC300403", "E0:12:14:14:12:E0", -80);
|
||||
|
||||
test("left and right arms advertising the same serial group into one complete pair", () => {
|
||||
const aggregator = new DiscoveryAggregator();
|
||||
aggregator.ingest(LEFT);
|
||||
aggregator.ingest(RIGHT);
|
||||
const pairs = aggregator.pairs();
|
||||
assert.equal(pairs.length, 1);
|
||||
const pair = pairs[0];
|
||||
assert.equal(pair.id, "S211GBBC180304");
|
||||
assert.equal(pair.completeness, "complete");
|
||||
assert.equal(pair.left.address, "E0:12:14:AC:D4:58");
|
||||
assert.equal(pair.right.address, "E0:12:14:8D:6E:3C");
|
||||
assert.equal(pair.identity.displayName, "Even G2 B · Brown");
|
||||
// Strongest arm's signal represents the pair.
|
||||
assert.equal(pair.rssi, -50);
|
||||
assert.ok(pair.proximity);
|
||||
});
|
||||
|
||||
test("arms with different serials are different pairs, each incomplete", () => {
|
||||
const aggregator = new DiscoveryAggregator();
|
||||
aggregator.ingest(LEFT);
|
||||
aggregator.ingest(OTHER_RIGHT);
|
||||
const pairs = aggregator.pairs();
|
||||
assert.equal(pairs.length, 2);
|
||||
assert.deepEqual(
|
||||
pairs.map((p) => [p.id, p.completeness]),
|
||||
[
|
||||
["S211GBBC180304", "left-only"],
|
||||
["S211GCBC300403", "right-only"],
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
test("pairs sort closest first; a pair without a signal sorts last", () => {
|
||||
const aggregator = new DiscoveryAggregator();
|
||||
aggregator.ingest(arm("left", "S211GAAA000001", "00:00:00:00:00:01", -80));
|
||||
aggregator.ingest(arm("left", "S211GAAA000002", "00:00:00:00:00:02", -40));
|
||||
aggregator.ingest(arm("left", "S211GAAA000003", "00:00:00:00:00:03", null));
|
||||
assert.deepEqual(
|
||||
aggregator.pairs().map((p) => p.id),
|
||||
["S211GAAA000002", "S211GAAA000001", "S211GAAA000003"],
|
||||
);
|
||||
});
|
||||
|
||||
test("an arm without a serial stands alone keyed by its address", () => {
|
||||
const aggregator = new DiscoveryAggregator();
|
||||
aggregator.ingest({ ...LEFT, manufacturerData: "" });
|
||||
const pairs = aggregator.pairs();
|
||||
assert.equal(pairs.length, 1);
|
||||
assert.equal(pairs[0].id, "arm:E0:12:14:AC:D4:58");
|
||||
assert.equal(pairs[0].serial, null);
|
||||
const row = glassesRow(pairs[0]);
|
||||
assert.equal(row.canSelect, false);
|
||||
assert.match(row.armsSummary, /serial unknown/);
|
||||
});
|
||||
|
||||
test("a bonded listing never erases a scanned serial and gains one when heard", () => {
|
||||
const aggregator = new DiscoveryAggregator();
|
||||
aggregator.ingest({ ...LEFT, manufacturerData: "", rssi: null, bonded: true, source: "paired" });
|
||||
assert.equal(aggregator.pairs()[0].serial, null);
|
||||
aggregator.ingest({ ...LEFT, seenAtMs: 2000 });
|
||||
assert.equal(aggregator.pairs()[0].serial, "S211GBBC180304");
|
||||
assert.equal(aggregator.pairs()[0].left.bonded, true);
|
||||
aggregator.ingest({ ...LEFT, manufacturerData: "", rssi: null, bonded: true, source: "paired", seenAtMs: 3000 });
|
||||
assert.equal(aggregator.pairs()[0].serial, "S211GBBC180304");
|
||||
});
|
||||
|
||||
test("stale advertisements are pruned; bonded entries survive", () => {
|
||||
const aggregator = new DiscoveryAggregator();
|
||||
aggregator.ingest(LEFT);
|
||||
aggregator.ingest({ ...RIGHT, bonded: true });
|
||||
aggregator.prune(1000 + DEFAULT_STALE_AFTER_MS + 1);
|
||||
const pairs = aggregator.pairs();
|
||||
assert.equal(pairs.length, 1);
|
||||
assert.equal(pairs[0].completeness, "right-only");
|
||||
});
|
||||
|
||||
test("RSSI is smoothed across repeated advertisements", () => {
|
||||
const aggregator = new DiscoveryAggregator();
|
||||
aggregator.ingest({ ...LEFT, rssi: -40 });
|
||||
aggregator.ingest({ ...LEFT, rssi: -80, seenAtMs: 1100 });
|
||||
const rssi = aggregator.pairs()[0].rssi;
|
||||
assert.ok(rssi < -40 && rssi > -80, `expected a blend, got ${rssi}`);
|
||||
});
|
||||
|
||||
test("rings are grouped separately and sorted closest first", () => {
|
||||
const aggregator = new DiscoveryAggregator();
|
||||
aggregator.ingest(LEFT);
|
||||
aggregator.ingest(ring("DA:7F:D2:B5:6E:E2", -70));
|
||||
aggregator.ingest(ring("DA:7F:D2:00:00:01", -45));
|
||||
assert.equal(aggregator.pairs().length, 1);
|
||||
assert.deepEqual(
|
||||
aggregator.rings().map((r) => r.id),
|
||||
["DA:7F:D2:00:00:01", "DA:7F:D2:B5:6E:E2"],
|
||||
);
|
||||
const row = ringRow(aggregator.rings()[1]);
|
||||
assert.equal(row.modelTitle, "Even R1");
|
||||
assert.match(row.deviceName, /140137/);
|
||||
assert.equal(row.ringAddress, "DA:7F:D2:B5:6E:E2");
|
||||
});
|
||||
|
||||
test("nearest requires a clear signal lead", () => {
|
||||
const d = (id, rssi) => ({ id, rssi });
|
||||
assert.equal(nearestCandidateId([d("1", -40), d("2", -70)]), "1");
|
||||
assert.equal(nearestCandidateId([d("1", -60), d("2", -57)]), null);
|
||||
// A lone advertiser is trivially the nearest.
|
||||
assert.equal(nearestCandidateId([d("1", -80)]), "1");
|
||||
// Nothing to rank without RSSI.
|
||||
assert.equal(nearestCandidateId([d("1", null)]), null);
|
||||
assert.equal(nearestCandidateId([]), null);
|
||||
});
|
||||
|
||||
test("previously paired matches across the arm suffix", () => {
|
||||
assert.ok(isPreviouslyPaired("S211GBBC180304", "S211GBBC180304_L_1"));
|
||||
assert.ok(!isPreviouslyPaired("S211GBBC180304", "S211GCBC300403"));
|
||||
assert.ok(!isPreviouslyPaired("S211GBBC180304", ""));
|
||||
assert.ok(!isPreviouslyPaired("S211GBBC180304", null));
|
||||
assert.ok(!isPreviouslyPaired(null, "S211GBBC180304"));
|
||||
});
|
||||
|
||||
test("scan row carries the decoded variant, artwork, and proximity", () => {
|
||||
const aggregator = new DiscoveryAggregator();
|
||||
aggregator.ingest({ ...LEFT, rssi: -42 });
|
||||
aggregator.ingest({ ...RIGHT, rssi: -42 });
|
||||
const row = glassesRow(aggregator.pairs()[0]);
|
||||
assert.equal(row.modelTitle, "Even G2 B");
|
||||
assert.equal(row.deviceName, "S211GBBC180304");
|
||||
assert.equal(row.variantSummary, "Frame B · Brown");
|
||||
assert.equal(row.colorway, "brown");
|
||||
assert.equal(row.imagePath, "~/images/glasses/glasses_g2_b_brown.png");
|
||||
assert.equal(row.hasVariantImage, true);
|
||||
assert.match(row.proximitySummary, /In your hand|Nearby/);
|
||||
assert.match(row.armsSummary, /serials match/);
|
||||
assert.equal(row.canSelect, true);
|
||||
assert.equal(row.isNearest, false);
|
||||
assert.equal(row.badge, "");
|
||||
});
|
||||
|
||||
test("the Yours badge wins over Closest; Closest needs the nearest id", () => {
|
||||
const aggregator = new DiscoveryAggregator();
|
||||
aggregator.ingest(LEFT);
|
||||
aggregator.ingest(RIGHT);
|
||||
const pair = aggregator.pairs()[0];
|
||||
assert.equal(glassesRow(pair, { nearestId: pair.id }).badge, "Closest");
|
||||
assert.equal(glassesRow(pair, { nearestId: pair.id, pairedSerial: "S211GBBC180304_L_1" }).badge, "Yours");
|
||||
});
|
||||
|
||||
test("a pair whose serial does not decode falls back to the generic shot and swatch-less row", () => {
|
||||
const aggregator = new DiscoveryAggregator();
|
||||
aggregator.ingest(arm("left", "XX11GBBC180304", "00:00:00:00:00:01", -50));
|
||||
aggregator.ingest(arm("right", "XX11GBBC180304", "00:00:00:00:00:02", -50));
|
||||
const row = glassesRow(aggregator.pairs()[0]);
|
||||
assert.equal(row.modelTitle, "Even Realities G2");
|
||||
assert.equal(row.variantSummary, null);
|
||||
assert.equal(row.swatchHex, null);
|
||||
assert.equal(row.imagePath, GENERIC_G2_IMAGE_PATH);
|
||||
assert.equal(row.hasVariantImage, false);
|
||||
assert.equal(row.canSelect, true);
|
||||
});
|
||||
|
||||
test("frame C resolves to the generic shot with the swatch still available", () => {
|
||||
const identity = GlassesHardwareIdentity.decode("S221GCAA000001");
|
||||
assert.equal(glassesImagePath(identity), GENERIC_G2_IMAGE_PATH);
|
||||
assert.equal(identity.colorway, "green");
|
||||
});
|
||||
|
||||
test("an incomplete pair cannot be selected and says which arm is missing", () => {
|
||||
const aggregator = new DiscoveryAggregator();
|
||||
aggregator.ingest(RIGHT);
|
||||
const row = glassesRow(aggregator.pairs()[0]);
|
||||
assert.equal(row.canSelect, false);
|
||||
assert.match(row.armsSummary, /Only the right arm/);
|
||||
assert.equal(row.rightAddress, "E0:12:14:8D:6E:3C");
|
||||
assert.equal(row.leftAddress, "");
|
||||
});
|
||||
|
||||
test("an embedded-MAC mismatch is surfaced as a warning", () => {
|
||||
const aggregator = new DiscoveryAggregator();
|
||||
aggregator.ingest({ ...LEFT, address: "AA:BB:CC:DD:EE:FF" });
|
||||
aggregator.ingest(RIGHT);
|
||||
const row = glassesRow(aggregator.pairs()[0]);
|
||||
assert.match(row.warning, /Left arm's advertised address/);
|
||||
});
|
||||
|
||||
test("every artwork file the resolver claims is bundled exists on disk", () => {
|
||||
const dir = path.join(__dirname, "..", "app", "images", "glasses");
|
||||
for (const name of requiredArtworkFileNames()) {
|
||||
assert.ok(fs.existsSync(path.join(dir, name)), `missing app/images/glasses/${name}`);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"target": "ES2020",
|
||||
"lib": ["ES2020"],
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"types": [],
|
||||
"rootDir": "..",
|
||||
"outDir": "../.test-build"
|
||||
},
|
||||
"include": [
|
||||
"../app/g2/glasses-hardware-identity.ts",
|
||||
"../app/g2/ble-proximity.ts",
|
||||
"../app/g2/even-advertisement.ts",
|
||||
"../app/g2/glasses-artwork.ts",
|
||||
"../app/g2/pairing-candidates.ts"
|
||||
]
|
||||
}
|
||||