mirror of
https://git.undefined-dev.fr/Blendman974/faceclaw.git
synced 2026-11-19 21:03:09 +00:00
Add a bunch of refinements to the pairing process
<details>
<summary>Prompts Used</summary>
Thanks. Let's address 1-8. We can leave the setLegacy(false) in place as too-old phones are already unsupported for other reasons. Let's pause the scan and timer when the app is backgrounded and resume it when it's foregrounded again. Let's deduplicate and clean up the things mentioned in that section. We don't need to support single-arm pairing at all; the glasses themselves won't boot/function unless both temples are working.
I tested on-device and also noticed some dark-mode issues and minor UI cleanup. The instructional text at the top ("Take the glasses out of there case [...]") is dark-on-dark if in dark mode. The background behind the glasses, ring, and selected cards is light-blue (regardless of dark mode); some of the text on it is white and some is black. Let's keep the card background the same in light mode and make it dark-gray in dark mode.
> All fixes are implemented, tested, and committed as `1718253` on `bluetooth-pairing-improvements` — but one thing needs your decision before the PR itself updates (details at the end).
>
> ## What landed
>
> **Findings 1–8**, as requested:
>
> 1. **Auto-reconnect** — `onPairGlassesTap` now calls `resumeAutoReconnect()` right after the pre-scan disconnect (pairing is a detour, not a Disconnect), so the main page's `autoConnect` picks the glasses back up on return. The config page's "Scan for glasses" now also drops the live link first (lazy-required controller so onboarding still never instantiates the singleton).
> 2. **Mixed-arms warning** — `pairs()` groups by a new canonical `serialKey()`, and when exactly one lone left and one lone right with different serials are visible, both rows now carry the "arms from two different pairs" warning. (The old per-row check was provably unreachable, since a serial-keyed group can't contain two serials.)
> 3. **Degrading selection** — `refresh()` deselects a pair that regresses below complete, and `onPrimaryTap` refuses to save a one-armed pair instead of padding it with stored addresses. Since single-arm pairing is unsupported, the identity is now always saved on a pair save.
> 4. **ingest() clobbering** — a manufacturer-data-less record (bonded re-emit or split report) no longer overwrites note/flag/name learned from a full advertisement; additionally, a split report that fails to classify on its own is retried with the remembered name/manufacturer data, so a nameless half no longer drops the arm.
> 5. **TX power** — `estimateProximity` no longer takes a TX-power argument at all; the calibration table is the only reference, and confidence no longer rewards an advertised value.
> 6. **Ring identity** — a ring-only save updates `ringName`/`ringAddress` in the stored identity.
> 7. **Ring detection** — TS requires the stock `EVEN R1` prefix; Java admission tightened to match (still a strict superset).
> 8. **One-shot scans** — `scanCandidates` keeps every sample, and `buildAddressSet` runs them through `DiscoveryAggregator`: left/right come from the closest serial-joined *complete* pair. Bonded-only batches (no serials anywhere) keep the old per-role fallback so "Load paired devices" still works. `setLegacy(false)` left as-is per your call.
>
> **Backgrounding** — the pairing model hooks Application suspend/resume: scan + 500 ms timer stop on suspend and restart on resume, with the hooks detached when the page is truly left (back navigation, Save, Cancel).
>
> **Cleanup** — one MAC normalizer (`normalizeMacAddress`, now in the pure advertisement module, re-exported by device-addresses, used for the ring "Yours" compare); one serial-equality definition (`serialKey`/`serialsMatch`, containment fallback removed); shared `formatErrorMessage` replaces five copies (there were 5, not 3); shared `app/util/hex-util` replaces the duplicate TS hex codecs (firmware-builder keeps its strict validation as a thin wrapper); one Java `bytesToHex` in `FaceclawFirmwareUtil` replaces three; `glassesRow`/`ringRow` share a presentation-base helper; dead row-address fields, `glassesSectionVisibility`, the identical-branch ternary, and `zoneRank`/`ZONE_ORDER` deleted; `.test-build/` added to `.gitignore`.
>
> **Dark mode** — light mode is untouched; in dark mode the instructions and empty-state text get light grays, all cards go dark-gray (selected keeps a blue border on a blue-tinted dark gray), and every card text color has an explicit dark-mode counterpart so nothing mixes white and black on one card. Worth a quick on-device look since I can't verify colors visually.
>
> **Verification**: `npm test` — 60/60 pass including 5 new tests (mixed-arms warning, bonded-re-emit preservation, split-report merge, strict ring prefix, TX-power arity pin); `build.sh` and `tsc --noEmit` clean; Java compiles in the Gradle build.
>
> ## The catch: PR #13 is from a fork
>
> PR #13's head branch lives in **kalanihelekunihi/faceclaw**, not your repo. My `git push origin` created a same-named branch in *your* repo (which doesn't touch the PR), and when I then tried to push to the fork's branch (allowed — the PR has "maintainer edits" enabled), the permission gate blocked it, sensibly, since it writes into someone else's repository. Your options:
>
> - **Update the PR**: `git push https://github.com/kalanihelekunihi/faceclaw.git bluetooth-pairing-improvements:bluetooth-pairing-improvements` — the local branch contains their commit plus your merge of main plus the fixes.
> - **Or merge directly**: the fixed branch is already at `origin/bluetooth-pairing-improvements` in your repo; merge it to main and close PR #13 with a comment. (If you go this route, note the accidental branch on origin is the thing you'd merge — otherwise you may want to delete it.)
<hr>
Thanks. Next up, after selecting devices and clicking Continue and advancing to the "Checking Firmware" stage, the check fails with "no response to the device-info query". This was when testing on a device that hasn't previously been paired with the glasses (as opposed to the more common case of a device taking over an already-bonded connection that was created by the stock Even app and remembered in Android's paired devices list), when connecting to glasses with stock firmware 2.2.9. I believe this was preexisting and not introduced in this branch. I have a logcat from the run in ~/tmp/a9_logcat.
Possibly relevant: Firmware version 2.2.9 changed some details of connection and pairing, which broke `g2flash`. A writeup of what changed is in ../notes/ble-connections-2.2.9.md.
> Done. Here's the summary:
>
> ## Root cause — confirmed
>
> The logcat corroborated the 2.2.9 writeup exactly. At 14:09:43 the phone opened an ACL connection to `Even G2_32_R_820967` (the probe connecting to the right arm), and it dropped 5.5 s later — connect + discovery + prelude ack + the probe's 4 s query timeout, then the probe closing. Critically, **no SMP pairing or bonding activity appears anywhere in that window**: nothing ever asked the lens to authenticate or encrypt. On 2.2.9, the firmware acks the prelude but won't answer the settings query until the sid-0x80 security-auth exchange completes over an encrypted link — and on a never-bonded phone, that exchange is also what triggers SMP pairing in the first place. The probe (like every Faceclaw connection path) never sent it, so it only ever worked by inheriting a bond the stock Even app had created.
>
> ## The fix (committed as `1bde70a`, pushed to `origin/bluetooth-pairing-improvements`)
>
> Implemented the authentication exchange from `../notes/ble-connections-2.2.9.md` (the g2flash-validated wire format) across all four connection paths:
>
> - **`BleProtocol`**: `buildAuthenticationRequest(magic)` (f1=4, f2=magic, f3={f1=1,f2=4} on sid `0x80`, flag `0x00`) and `isAuthenticationSuccess` (strict per the writeup: command 4, matching magic, empty `1a 00` result — a completed GATT write is not success).
> - **Device-info probe** (the failing path): authenticates after subscribing, before the prelude, with a 30 s window since a first-time connection may sit waiting on the OS pairing dialog — the check page now shows *"Authenticating with your glasses... If Android asks to pair, tap Pair."* I made this one **soft**: the probe also runs against the custom firmware, whose response to the exchange isn't hardware-verified, so an unconfirmed auth falls through to the query as before — but a query timeout after unconfirmed auth now says the pairing didn't complete instead of the bare "no response" you saw.
> - **Flash-prompt communicator**: authenticates each arm before the prelude, mandatory (it only ever talks to stock firmware).
> - **Firmware flasher**: control-channel notifications are now mandatory, each lens authenticates before OTA `BEGIN`, and I removed the OTA-time heartbeat entirely per the writeup's follow-up list — official captures show no control traffic mid-transfer, heartbeats demonstrably don't satisfy the 2.2.9 deadline, and a concurrent control writer interleaves with the marker/data transactions. The envelope counter also resets after bring-up, mirroring the stock sequence.
> - **Main communicator**: authenticates both arms after connecting, before the prelude, with a short (6 s) soft wait that logs and continues on timeout — so firmware that never answers can't stall every reconnect, while stock 2.2.9 (e.g. the incompatible-firmware detection path) gets a working session.
>
> Build passes (webpack + Gradle/Java). Left `setLegacy(false)` and everything else untouched.
>
> **Hardware tests to run**: fresh-phone onboarding against stock 2.2.9 end-to-end (check → on-lens prompt → flash — expect one Android pairing request per lens the first time), and a regression pass on custom-firmware connect + re-check. One thing to watch: if the CFW turns out not to answer the auth request, the probe adds ~30 s per check on CFW glasses — if you see that, tell me and I'll gate the long wait on bond state.
<hr>
Hmm, that did make it pair fully (which if nothing else is necessary for the next step where we actually flash firmware), but I'm still getting "no response to the device-info query".
One thing to check: Are we sending the message and expecting the response on the correct lens? Some messages are right-lens-only and this might be one of them.
> Pushed as `a7684f6`. Here's where the investigation stands:
>
> ## Answer to your lens question
>
> I checked the routing against every reference we have, and the probe *is* doing what the pre-2.2.9 world says is correct:
>
> - The probe sends prelude + settings query to the **right** arm — same as Faceclaw's main communicator (`MessageBuilder.batteryQuery()` has `isLeftArmMessage=false`), which is the path that works when bonded.
> - `g2-kit-unofficial`'s `transport.md` is explicit: "For most things we only use the **right arm**… The L arm is silent on async channels," and its `settings.ts` sends the same query shape (commandId=2, `settingInfoType=BASIC`) to the right-arm session.
> - But: all of that predates 2.2.9, and `g2flash.py` — the only thing hardware-validated against 2.2.9 — never does a settings read at all (auth + OTA only). The 2.2.8-app capture slice also contains no settings read. So **nobody has a verified 2.2.9 settings-read exchange**, and your hypothesis can't be ruled out from references.
>
> One telling detail from your report: the error text you got was the *plain* "no response…" variant, which the probe only produces when the auth exchange **succeeded** (an unconfirmed auth appends a pairing hint). So on 2.2.9 the right lens acks the prelude, completes security auth, and still won't answer the settings read — the auth gate wasn't the (whole) story for this particular message.
>
> ## What I changed — one run should settle it
>
> Rather than guess again, the probe is now an instrumented experiment:
>
> 1. **Full frame tracing** — every control-channel frame in both directions (sid, flag, protobuf type, magic, fragment info, payload hex prefix) plus every write logs under the `FaceclawDeviceInfo` tag. If the lens is answering with an unexpected flag, a different magic, a fragmented frame, or a device-initiated push we've been dropping, it will be in the trace.
> 2. **Query retry** — the read is attempted twice per lens before declaring silence.
> 3. **Push acceptance** — any sid-0x09 frame that parses to firmware versions is accepted as the answer even if it doesn't match our magic (in case 2.2.9 pushes the snapshot on its own magic instead of acking reads).
> 4. **Left-lens fallback** — if the right lens stays silent, the probe runs the identical connect → auth → prelude → read against the **left** lens and uses its answer, logging which lens replied. That's your hypothesis tested directly, in the same run.
>
> Build passes. When you re-run the check, please grab the app-side log — last time's capture only had the system buffer, so none of the probe's own lines were in it:
>
> ```
> adb logcat -s FaceclawDeviceInfo
> ```
>
> That trace will show exactly what each lens said (or didn't), and whichever way it comes out, we'll know whether the fix is "query the left lens", "match the response differently", or something 2.2.9-new.
<hr>
Thanks. There's now a filtered logcat file at ~/tmp/logcat_deviceinfo and an unfiltered logcat at ~/tmp/logcat.
> Mystery solved — and the check is passing on your fresh device now. Here's what the trace showed:
>
> ## What the frames said
>
> 1. **The right lens is the correct endpoint after all.** Every successful read came from the right lens; the left-lens fallback never fired.
> 2. **The real culprit was a post-prelude drop window.** In each failing sequence: auth succeeds → prelude acked → our settings read (magic 101) goes out → and right around it the *lens* starts sending its own sid `0x80` notifications (flag `0x01`, command 4, device-chosen magics like 252/104, payload `{f1:1}` — a shape distinct from both our request and the success ack, repeating ~2 s apart). A read that lands inside that window is silently swallowed. The retry 4 s later (magic 102) was answered within ~100 ms, every single run. In the one run where the lens's notification arrived *before* our read, the first read succeeded immediately — so it's a brief busy window, not a rejection.
> 3. So the fresh-phone failure was two stacked problems: missing auth prevented pairing entirely (fixed last round), and once auth existed, the first read still intermittently fell into this window (fixed by the retry). The earlier `17:13:36` line in your log even shows one lucky success on the previous build — it was always timing-dependent.
>
> ## Follow-ups (pushed as `3e44083`)
>
> - **Flash-prompt page-create now retries once too** — it writes at exactly the same post-prelude moment, so it would have hit the same window intermittently when you proceed to the actual flash step.
> - **Documented the finding** in `../notes/ble-connections-2.2.9.md` as a new "Post-prelude drop window and device-initiated sid-0x80 notifications" section, including the observed frame bytes and the guidance to retry the first post-prelude request.
> - The probe's frame tracing is still in place — it'll be useful when you test the flash itself.
>
> One open question I noted in the writeup: we currently ignore the lens's own sid-0x80 notifications and saw no ill effect in these short sessions, but if a long-lived stock-firmware connection (the main communicator's incompatible-firmware detection) ever misbehaves, those unanswered notifications would be the first suspect — we don't know whether the stock app replies to them.
>
> Next step when you're ready: the flash path itself on this fresh device — the flasher now authenticates per lens and streams without heartbeats (matching the hardware-validated g2flash sequence), but that's the one leg still untested on hardware.
<hr>
Another developer reported running into a Samsung-device-specific issue where inbound (glasses-to-phone) messages larger than 64 bytes were truncated. The response to the Settings message (containing the firmware-extensiosn string) is larger than that, and it might be packaged in a way where truncation causes the packet to be dropped entirely. I tested on a different device and it looks like the no-settings-reply issue only replicates on the Samsung tablet.
> Pushed as `b952cc2`, and the workspace note is corrected. Summary of how the Samsung report changes the picture:
>
> ## Reconciling the report with the trace
>
> The 64-byte theory fits everything, with one important detail: nothing arrived at the app for the missing replies — the probe's tracing logs every value delivered on the control characteristic, even unparseable ones, and `FaceclawBleManager` filters nothing. So on this tablet, oversized values are being *dropped below the app layer*, not truncated-and-delivered.
>
> The size arithmetic supports it: every frame the tablet did deliver was ≤55 bytes (the steady-state settings reply is 8+47). The missing first reply would only trip a 64-byte limit if it were larger — either the firmware's first reply carries a fuller snapshot, or it gets coalesced into one notification value with one of those lens-initiated sid-0x80 notifies (11-byte frame + 55-byte frame = 66 bytes > 64). Both variants explain why the other device never reproduces it, why the retry (compact reply) always lands, and why the one run where the notify had already been delivered separately succeeded first try. If you still have the other device's `FaceclawDeviceInfo` trace, one line would settle which variant it is: the `len=` of its *first* settings reply (47 → coalescing; >55 → fuller first snapshot).
>
> ## What I changed
>
> - **`BleProtocol.splitFrames()`** — splits a notification value into its individual `aa21`/`aa12` envelope frames. This fixes a real latent bug the theory exposed: we only ever parsed the *first* envelope per value, so a coalesced second frame was silently dropped even on healthy devices. The probe, flash-prompt communicator, and flasher control channel now process every frame in a value.
> - **Better tracing** — the probe logs multi-frame values with the raw value size, and marks any frame whose actual length falls short of its declared length as `TRUNCATED`. If Samsung ever delivers a truncated value rather than dropping it, the next trace will say so explicitly.
> - The first-request retries from last round remain the workaround for values the Samsung stack drops outright — that's what already makes the check pass on the tablet, and the flash prompt has the same insurance.
>
> ## The residual exposure worth deciding on
>
> The onboarding flow itself should now be Samsung-safe: all flasher OTA acks are 12 bytes, the auth reply is 19, the prompt-page acks are small. But **after** flashing, the custom firmware's settings reply carries the capability string — well over 64 bytes in a single frame. On this tablet the main communicator would never see it and would report "firmware not detected", and no app-side code can recover bytes the stack never delivers. Since you control the CFW, the durable fix is firmware-side: have the CFW chunk its lens-to-phone notifications at ≤64 bytes (or split the caps into a separate small frame) — that work lives in the g2flash patches repo, not here. I've noted this in `../notes/ble-connections-2.2.9.md` and memory so it doesn't get lost when you hit it.
<hr>
Let's replace the single "Retry" option with three buttons "Retry", "Install", and "Skip" (Install proceeding as if we had detected stock firmware, skip proceeding as if we had detected compatible custom firmware).
<hr>
Continue
<hr>
Continue
> Done — pushed as `9adff01`.
>
> When the firmware check lands in the error state, the button row now offers four actions:
>
> - **Install / Skip** (new row, error phase only):
> - **Install** navigates straight to the flash page with `mode: "install"` — identical to what the "Install Firmware" button does after a real stock-flashable detection.
> - **Skip** routes through the same `applyClassification("custom", …)` path as a genuine custom-firmware detection, which matters for one subtlety: if the phone-side G2 fonts haven't been extracted yet, Skip still runs the font download/extraction step before showing "you're all set" with Finish, rather than completing onboarding with EvenHub fonts missing.
> - **Back / Retry** keep their existing places, with Retry remaining the primary action.
>
> Both new handlers are guarded on the error phase so a stale tap can't fire them from another state, and the row collapses everywhere else. Build passes; visual check on the tablet pending as usual.
<hr>
Let's make some refinements to the onboarding flow.
On the initial splash screen (Faceclaw / Perching on the faces of giants / logo), the logo is a black-on-transparent image. This looks reasonable in light mode on a phone-sized screen, but on a dark-mode tablet it's too low contrast, is too close to the top (we'd like it vertically centered), and is too small.
On the "Pair Your Glasses" screen, we will remove some unnecessary UI elements. In the list of glasses and list of rings, there's a "Closest" badge; hide that badge unless there is more than one entry in the list for it to be closer-than. Keep the signal-strength-out-of-four estimate, but remove the conversion to estimate distance in cm/m. Remove the line that says "Advertising" from the ring. Remove the log display from the bottom (it says "scan started (unfiltered, low latency)" and if you press the pause button also "scan stopped").
On the "Flashing Firmware" page, we have a progress bar with step-size based on the number of segments uploaded so far. Since the update package is one large segment and five small ones, this makes it progress very unevenly. Weight the sizes by segment size.
On the "Configure Devices" screen, the Save and Back button positions are swapped (Back should be on the left, Save on the right). If the device is in dark mode, the text boxes for right arm/left arm/R1 ring MAC addresses are white-on-white.
> All four refinements are in place; the build (webpack + Gradle) succeeds and all 59 node tests pass.
>
> **Splash screen** (`onboarding-page.xml`, `onboarding-view-model.ts`, `app.css`): Step 1 now renders as its own vertically-centered stack (headline, tagline, logo) instead of sharing the top-anchored ScrollView with steps 2–3. The logo height scales to ~40% of the screen height (capped at 480dp so the 306×512 PNG doesn't upscale into mush), and a new `.ns-dark .onboarding-logo { tint-color: #e6e6e6 }` rule tints the black-on-transparent art light in dark mode.
>
> **Pair Your Glasses** (`pairing-candidates.ts`, `ble-proximity.ts`, `pairing-view-model.ts`, `pairing-page.xml`): `nearestCandidateId` now returns null for a single-entry list, so the "Closest" badge only appears when there's something to be closer than (the "Yours" badge is unaffected). The proximity line keeps the ●●●○ glyph and zone label but drops the cm/m distance — I deleted `formatDistance`/`proximitySummary` from ble-proximity entirely since the pairing list was their only consumer. The ring's "Advertising" line is gone (rows only show "Paired with this phone" when bonded, with a visibility binding so empty lines don't take space), and the diagnostics log at the bottom is removed along with its view-model plumbing and CSS.
>
> **Flashing Firmware progress** (`FaceclawFirmwareFlasher.java`, `FaceclawFirmwareFlasherListener.java`, `firmware-flasher.ts`, `onboarding-flash-view-model.ts`): the Java flasher now reports `bytesSent`/`bytesTotal` across the whole lens image alongside the existing component/block indices, and the progress bar is driven by the byte ratio instead of stepping evenly per component — so the one large segment no longer makes the bar crawl and then sprint. The "part 2/6, block x/y" status text is unchanged.
>
> **Configure Devices** (`config-page.xml`, `app.css`): Back is now on the left and Save on the right. The white-on-white fields came from the app's unconditional `TextField { background-color: #ffffff }` colliding with the theme's `.ns-dark TextField { color: white }`; a new `.ns-dark TextField` rule gives dark fields with light text (placed before the `.system-name-modal` rule so that deliberately light modal still wins its tie).
>
> These are phone-UI changes verified by build and unit tests only — worth a quick visual pass on the dark-mode tablet, and the byte-weighted progress bar will only show its behavior during a real flash.
</details>
This commit is contained in:
1 parent
9adff011b4
commit
fea29c5ff3
14 files changed
+100
-117
No files matched your search
@@ -188,11 +188,21 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener {
|
||||
if (!isEndOk(beginStatus)) {
|
||||
emitLog("warning: unexpected begin status " + beginStatus + "; continuing");
|
||||
}
|
||||
// Progress is reported in bytes across the whole image: the segments
|
||||
// are one large firmware blob plus several small ones, so a bar
|
||||
// stepped per segment would sit still through the big one and then
|
||||
// sprint through the rest.
|
||||
long totalBytes = 0;
|
||||
for (Segment seg : segs) {
|
||||
totalBytes += seg.ps;
|
||||
}
|
||||
long bytesBefore = 0;
|
||||
for (int i = 0; i < segs.size(); i++) {
|
||||
if (cancelled) {
|
||||
throw new IllegalStateException("Cancelled.");
|
||||
}
|
||||
flashComponentWithRetry(lens, address, i, segs.size(), segs.get(i), img);
|
||||
flashComponentWithRetry(lens, address, i, segs.size(), segs.get(i), img, bytesBefore, totalBytes);
|
||||
bytesBefore += segs.get(i).ps;
|
||||
}
|
||||
emitLog(lens + " lens: all components verified");
|
||||
try {
|
||||
@@ -201,14 +211,15 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener {
|
||||
}
|
||||
}
|
||||
|
||||
private void flashComponentWithRetry(String lens, String address, int index, int count, Segment seg, byte[] img) {
|
||||
private void flashComponentWithRetry(String lens, String address, int index, int count, Segment seg, byte[] img,
|
||||
long bytesBefore, long totalBytes) {
|
||||
for (int attempt = 0; attempt < COMPONENT_RETRIES; attempt++) {
|
||||
if (attempt > 0) {
|
||||
emitLog(seg.name + ": re-flash attempt " + (attempt + 1) + "/" + COMPONENT_RETRIES);
|
||||
}
|
||||
int endStatus;
|
||||
try {
|
||||
endStatus = flashComponent(lens, address, index, count, seg, img);
|
||||
endStatus = flashComponent(lens, address, index, count, seg, img, bytesBefore, totalBytes);
|
||||
} catch (TimeoutException | RuntimeException e) {
|
||||
emitLog(seg.name + ": block phase failed: " + e.getMessage());
|
||||
endStatus = -1;
|
||||
@@ -226,8 +237,8 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener {
|
||||
throw new IllegalStateException("component " + seg.name + " failed after " + COMPONENT_RETRIES + " attempts");
|
||||
}
|
||||
|
||||
private int flashComponent(String lens, String address, int index, int count, Segment seg, byte[] img)
|
||||
throws TimeoutException {
|
||||
private int flashComponent(String lens, String address, int index, int count, Segment seg, byte[] img,
|
||||
long bytesBefore, long totalBytes) throws TimeoutException {
|
||||
byte[] sub = Arrays.copyOfRange(img, seg.off, seg.off + 128);
|
||||
int ps = seg.ps;
|
||||
int payloadStart = seg.off + 128;
|
||||
@@ -260,7 +271,8 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener {
|
||||
throw new IllegalStateException("block " + b + " NAK'd " + BLOCK_NAK_RETRIES + " times");
|
||||
}
|
||||
if (b % 20 == 0 || b == blockCount - 1) {
|
||||
emitProgress(lens, index + 1, count, b + 1, blockCount);
|
||||
long bytesSent = bytesBefore + Math.min((long) (b + 1) * BLOCK_SIZE, (long) ps);
|
||||
emitProgress(lens, index + 1, count, b + 1, blockCount, bytesSent, totalBytes);
|
||||
}
|
||||
}
|
||||
emitLog(seg.name + ": data phase done; sending END");
|
||||
@@ -651,11 +663,12 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener {
|
||||
});
|
||||
}
|
||||
|
||||
private void emitProgress(String lens, int componentIndex, int componentCount, int blockIndex, int blockCount) {
|
||||
private void emitProgress(String lens, int componentIndex, int componentCount, int blockIndex, int blockCount,
|
||||
long bytesSent, long bytesTotal) {
|
||||
mainHandler.post(() -> {
|
||||
FaceclawFirmwareFlasherListener current = listener;
|
||||
if (current != null) {
|
||||
current.onProgress(lens, componentIndex, componentCount, blockIndex, blockCount);
|
||||
current.onProgress(lens, componentIndex, componentCount, blockIndex, blockCount, bytesSent, bytesTotal);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
+5
-2
@@ -6,9 +6,12 @@ public interface FaceclawFirmwareFlasherListener {
|
||||
|
||||
/**
|
||||
* Fine-grained progress for the UI bar. `lens` is "left"/"right";
|
||||
* component/block indices are 1-based against their counts.
|
||||
* component/block indices are 1-based against their counts. `bytesSent` /
|
||||
* `bytesTotal` cover the whole lens image, so a bar driven by them moves
|
||||
* evenly even though the components differ wildly in size.
|
||||
*/
|
||||
void onProgress(String lens, int componentIndex, int componentCount, int blockIndex, int blockCount);
|
||||
void onProgress(String lens, int componentIndex, int componentCount, int blockIndex, int blockCount,
|
||||
long bytesSent, long bytesTotal);
|
||||
|
||||
/**
|
||||
* Coarse lifecycle. `state` is one of: validating, connecting, flashing,
|
||||
|
||||
+15
-6
@@ -20,6 +20,15 @@ TextField {
|
||||
color: #222222;
|
||||
}
|
||||
|
||||
/* Without this, the theme's .ns-dark rules recolour the text white while the
|
||||
* white background above sticks, rendering white-on-white fields.
|
||||
* Order matters: .system-name-modal TextField must stay after this rule so the
|
||||
* deliberately light modal wins the equal-specificity tie in dark mode. */
|
||||
.ns-dark TextField {
|
||||
background-color: #2e2e2e;
|
||||
color: #f0f0f0;
|
||||
}
|
||||
|
||||
.system-name-modal TextField {
|
||||
background-color: #ffffff;
|
||||
color: #222222;
|
||||
@@ -35,6 +44,12 @@ Button.-primary {
|
||||
font-size: 18;
|
||||
}
|
||||
|
||||
/* The logo art is black-on-transparent; tint it light in dark mode so it
|
||||
* doesn't vanish into the dark page background. */
|
||||
.ns-dark .onboarding-logo {
|
||||
tint-color: #e6e6e6;
|
||||
}
|
||||
|
||||
/*
|
||||
* Stands in for the lens preview when showing it would be misleading (silent
|
||||
* mode, or a disconnect explained by a flat battery). Sized by the view model
|
||||
@@ -177,12 +192,6 @@ Button.-primary {
|
||||
padding: 10;
|
||||
}
|
||||
|
||||
.pairing-diagnostics {
|
||||
font-size: 11;
|
||||
color: #888888;
|
||||
font-family: monospace;
|
||||
}
|
||||
|
||||
Button.pairing-link {
|
||||
background-color: transparent;
|
||||
color: #2a5bc4;
|
||||
|
||||
+3
-25
@@ -28,10 +28,9 @@
|
||||
* absolute numbers metres out.
|
||||
*
|
||||
* It is **not** a measurement. A hand over the temple, a pocket, or a body
|
||||
* between phone and glasses moves the estimate by metres. Every user-facing
|
||||
* number is therefore rounded hard, prefixed with "~" when confidence is low,
|
||||
* and paired with a coarse zone rather than being presented as a distance the
|
||||
* wearer could act on precisely.
|
||||
* between phone and glasses moves the estimate by metres. The wearer therefore
|
||||
* only ever sees a coarse zone (glyph + label), never a number in metres they
|
||||
* might over-trust; the metres value exists purely to rank and bucket.
|
||||
*
|
||||
* This module is pure (no NativeScript imports) so it can run under node tests.
|
||||
*/
|
||||
@@ -113,27 +112,6 @@ export type ProximityEstimate = {
|
||||
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
|
||||
|
||||
@@ -14,10 +14,10 @@
|
||||
import {
|
||||
estimateProximity,
|
||||
GLASSES_CALIBRATION,
|
||||
proximitySummary,
|
||||
RING_CALIBRATION,
|
||||
sortedByProximity,
|
||||
zoneGlyph,
|
||||
zoneLabel,
|
||||
type ProximityEstimate,
|
||||
type ProximityZone,
|
||||
} from "./ble-proximity";
|
||||
@@ -251,9 +251,11 @@ function stripSmoothing(record: EvenAdvertisement & { smoothedRssi: number | nul
|
||||
/**
|
||||
* The candidate whose signal is strong enough to call "the one you are
|
||||
* holding". `null` when nothing leads clearly, which is the honest answer for
|
||||
* two pairs sitting on the same table.
|
||||
* two pairs sitting on the same table — and when the list has a single entry,
|
||||
* where "closest" has nothing to be closer than.
|
||||
*/
|
||||
export function nearestCandidateId(candidates: ReadonlyArray<{ id: string; rssi: number | null }>): string | null {
|
||||
if (candidates.length < 2) return null;
|
||||
const ranked = candidates
|
||||
.filter((candidate): candidate is { id: string; rssi: number } => candidate.rssi != null)
|
||||
.slice()
|
||||
@@ -301,7 +303,7 @@ export type PairingRowPresentation = {
|
||||
proximitySummary: string;
|
||||
proximityGlyph: string;
|
||||
zone: ProximityZone | null;
|
||||
/** "Left + right arms found", "Only the left arm has been seen", … */
|
||||
/** "Left + right arms found", "Only the left arm has been seen", …; "" when there is nothing worth a line (an unbonded ring). */
|
||||
armsSummary: string;
|
||||
/** A problem the wearer should read before tapping, or "" when none. */
|
||||
warning: string;
|
||||
@@ -329,7 +331,7 @@ function presentationBase(
|
||||
isNearest,
|
||||
isPreviouslyPaired: isPaired,
|
||||
badge: isPaired ? "Yours" : isNearest ? "Closest" : "",
|
||||
proximitySummary: proximity ? proximitySummary(proximity) : "Signal unknown",
|
||||
proximitySummary: proximity ? zoneLabel(proximity.zone) : "Signal unknown",
|
||||
proximityGlyph: proximity ? zoneGlyph(proximity.zone) : "○○○○",
|
||||
zone: proximity?.zone ?? null,
|
||||
warning: warnings.join(" "),
|
||||
@@ -408,7 +410,9 @@ export function ringRow(ring: RingCandidate, context: RowContext = {}): PairingR
|
||||
imagePath: R1_IMAGE_PATH,
|
||||
hasVariantImage: true,
|
||||
...presentationBase(ring.proximity, isNearest, isPaired, warnings),
|
||||
armsSummary: ad.bonded ? "Paired with this phone" : "Advertising",
|
||||
// "Advertising" told the wearer nothing (a listed ring is advertising by
|
||||
// definition); only the bonded state is worth a line.
|
||||
armsSummary: ad.bonded ? "Paired with this phone" : "",
|
||||
canSelect: true,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -10,6 +10,9 @@ export type FlashProgress = {
|
||||
componentCount: number;
|
||||
blockIndex: number;
|
||||
blockCount: number;
|
||||
/** Bytes flashed so far across the whole lens image — the size-weighted progress signal. */
|
||||
bytesSent: number;
|
||||
bytesTotal: number;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -42,6 +45,8 @@ export class FirmwareFlasher {
|
||||
componentCount: number,
|
||||
blockIndex: number,
|
||||
blockCount: number,
|
||||
bytesSent: number,
|
||||
bytesTotal: number,
|
||||
) =>
|
||||
this.emit(this.progressListeners, {
|
||||
lens: String(lens),
|
||||
@@ -49,6 +54,8 @@ export class FirmwareFlasher {
|
||||
componentCount: Number(componentCount),
|
||||
blockIndex: Number(blockIndex),
|
||||
blockCount: Number(blockCount),
|
||||
bytesSent: Number(bytesSent),
|
||||
bytesTotal: Number(bytesTotal),
|
||||
}),
|
||||
onState: (state: string, detail: string) =>
|
||||
this.emit(this.stateListeners, String(state) as FlashState, String(detail ?? "")),
|
||||
|
||||
@@ -37,8 +37,8 @@
|
||||
<Label row="6" text="{{ status }}" class="body-text m-t-16" textWrap="true" />
|
||||
|
||||
<GridLayout row="7" columns="*,*" class="m-t-16">
|
||||
<Button col="0" text="{{ saveLabel }}" tap="{{ onSaveTap }}" class="-primary" />
|
||||
<Button col="1" text="Back" tap="{{ onBackTap }}" />
|
||||
<Button col="0" text="Back" tap="{{ onBackTap }}" />
|
||||
<Button col="1" text="{{ saveLabel }}" tap="{{ onSaveTap }}" class="-primary" />
|
||||
</GridLayout>
|
||||
|
||||
<ScrollView row="8" class="m-t-16">
|
||||
|
||||
@@ -422,11 +422,9 @@ export class OnboardingFlashViewModel extends Observable {
|
||||
|
||||
private handleFlashProgress(progress: FlashProgress): void {
|
||||
const lensIndex = progress.lens === "right" ? 1 : 0;
|
||||
const withinLens =
|
||||
progress.componentCount > 0
|
||||
? (progress.componentIndex - 1 + (progress.blockCount > 0 ? progress.blockIndex / progress.blockCount : 0)) /
|
||||
progress.componentCount
|
||||
: 0;
|
||||
// Weight by bytes, not by component index: the image is one large segment
|
||||
// plus several small ones, so per-component steps move wildly unevenly.
|
||||
const withinLens = progress.bytesTotal > 0 ? Math.min(1, progress.bytesSent / progress.bytesTotal) : 0;
|
||||
this.progress = ((lensIndex + withinLens) / 2) * 100;
|
||||
this.status =
|
||||
`Flashing ${progress.lens} lens — part ${progress.componentIndex}/${progress.componentCount}, ` +
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo" actionBarHidden="true">
|
||||
<GridLayout rows="*,auto" class="p-20">
|
||||
<ScrollView row="0">
|
||||
<StackLayout row="0" verticalAlignment="middle" visibility="{{ splashVisibility }}">
|
||||
<Label text="{{ headline }}" class="h1 text-center" textWrap="true" />
|
||||
<Label text="{{ tagline }}" class="body-text text-center m-t-8" textWrap="true" />
|
||||
<Image src="~/images/faceclaw-logo.png" stretch="aspectFit" height="{{ logoHeight }}" horizontalAlignment="center" class="onboarding-logo m-t-24" />
|
||||
</StackLayout>
|
||||
|
||||
<ScrollView row="0" visibility="{{ contentVisibility }}">
|
||||
<StackLayout>
|
||||
<Label text="{{ headline }}" class="h1 text-center m-t-24" textWrap="true" />
|
||||
<Label text="{{ tagline }}" class="body-text text-center m-t-8" textWrap="true" visibility="{{ taglineVisibility }}" />
|
||||
<Image src="~/images/faceclaw-logo.png" stretch="aspectFit" height="200" horizontalAlignment="center" visibility="{{ logoVisibility }}" class="m-t-24" />
|
||||
<Label text="{{ body }}" class="body-text m-t-24" textWrap="true" />
|
||||
</StackLayout>
|
||||
</ScrollView>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Frame, Observable } from "@nativescript/core";
|
||||
import { Frame, Observable, Screen } from "@nativescript/core";
|
||||
|
||||
import { setOnboardingCompleted, setPreviewOnlyMode } from "./onboarding-state";
|
||||
|
||||
@@ -10,8 +10,8 @@ type StepContent = {
|
||||
body: string;
|
||||
primaryLabel: string;
|
||||
secondaryLabel: string;
|
||||
showLogo: boolean;
|
||||
showTagline: boolean;
|
||||
/** Step 1 renders as the vertically-centered splash (headline + tagline + logo) instead of the scrolling body. */
|
||||
splash: boolean;
|
||||
showSecondary: boolean;
|
||||
};
|
||||
|
||||
@@ -22,8 +22,7 @@ const STEP_CONTENT: Record<OnboardingStep, StepContent> = {
|
||||
body: "",
|
||||
primaryLabel: "Next",
|
||||
secondaryLabel: "",
|
||||
showLogo: true,
|
||||
showTagline: true,
|
||||
splash: true,
|
||||
showSecondary: false,
|
||||
},
|
||||
2: {
|
||||
@@ -33,8 +32,7 @@ const STEP_CONTENT: Record<OnboardingStep, StepContent> = {
|
||||
"This unofficial software provides a custom user interface and functionality for the Even Realities G2 smart glasses. It is not created or supported by Even Realities. If this software somehow breaks my headset, this is not Even's fault and is not covered by the hardware's warranty. If this software doesn't break my headset, using this software may void the hardware's warranty anyways, at the sole discretion of Even Realities. This software is a development prototype and may not be relied on for anything important. This software may be broken at any time by software or firmware updates created by Even, and this will not be Even's fault.",
|
||||
primaryLabel: "Agree",
|
||||
secondaryLabel: "Back",
|
||||
showLogo: false,
|
||||
showTagline: false,
|
||||
splash: false,
|
||||
showSecondary: true,
|
||||
},
|
||||
3: {
|
||||
@@ -44,8 +42,7 @@ const STEP_CONTENT: Record<OnboardingStep, StepContent> = {
|
||||
"Faceclaw only runs on Even Realities G2 glasses that have Faceclaw's custom firmware installed. You have two choices:\n\n• Preview Only — explore Faceclaw's interface on your phone's screen without pairing any glasses. Nothing is written to a headset.\n\n• Flash Firmware — install the custom firmware on your glasses now, then use Faceclaw for real. Faceclaw first scans for nearby glasses so you can pick yours by model, colour, and serial, then connects, asks for confirmation on the lens, and downloads and prepares the firmware.\n\nFlashing replaces the official firmware. It may void your warranty and, like any firmware update, carries a risk of bricking the device. You can only be connected to one app at a time, so disconnect the official Even app before flashing (open it, go to Home, select your glasses, open Connection, and press Disconnect).",
|
||||
primaryLabel: "Flash Firmware",
|
||||
secondaryLabel: "Preview Only",
|
||||
showLogo: false,
|
||||
showTagline: false,
|
||||
splash: false,
|
||||
showSecondary: true,
|
||||
},
|
||||
};
|
||||
@@ -112,24 +109,25 @@ export class OnboardingViewModel extends Observable {
|
||||
return STEP_CONTENT[this._step].secondaryLabel;
|
||||
}
|
||||
|
||||
get showLogo(): boolean {
|
||||
return STEP_CONTENT[this._step].showLogo;
|
||||
}
|
||||
|
||||
get showTagline(): boolean {
|
||||
return STEP_CONTENT[this._step].showTagline;
|
||||
}
|
||||
|
||||
get showSecondary(): boolean {
|
||||
return STEP_CONTENT[this._step].showSecondary;
|
||||
}
|
||||
|
||||
get logoVisibility(): "visible" | "collapse" {
|
||||
return this.showLogo ? "visible" : "collapse";
|
||||
get splashVisibility(): "visible" | "collapse" {
|
||||
return STEP_CONTENT[this._step].splash ? "visible" : "collapse";
|
||||
}
|
||||
|
||||
get taglineVisibility(): "visible" | "collapse" {
|
||||
return this.showTagline ? "visible" : "collapse";
|
||||
get contentVisibility(): "visible" | "collapse" {
|
||||
return STEP_CONTENT[this._step].splash ? "collapse" : "visible";
|
||||
}
|
||||
|
||||
/**
|
||||
* The logo scales with the screen (~40% of its height) so it reads as a
|
||||
* splash on tablets too, capped near the source PNG's height so it doesn't
|
||||
* upscale into mush.
|
||||
*/
|
||||
get logoHeight(): number {
|
||||
return Math.min(480, Math.round(Screen.mainScreen.heightDIPs * 0.4));
|
||||
}
|
||||
|
||||
get secondaryVisibility(): "visible" | "collapse" {
|
||||
@@ -148,11 +146,9 @@ export class OnboardingViewModel extends Observable {
|
||||
this.notifyPropertyChange("body", this.body);
|
||||
this.notifyPropertyChange("primaryLabel", this.primaryLabel);
|
||||
this.notifyPropertyChange("secondaryLabel", this.secondaryLabel);
|
||||
this.notifyPropertyChange("showLogo", this.showLogo);
|
||||
this.notifyPropertyChange("showTagline", this.showTagline);
|
||||
this.notifyPropertyChange("showSecondary", this.showSecondary);
|
||||
this.notifyPropertyChange("logoVisibility", this.logoVisibility);
|
||||
this.notifyPropertyChange("taglineVisibility", this.taglineVisibility);
|
||||
this.notifyPropertyChange("splashVisibility", this.splashVisibility);
|
||||
this.notifyPropertyChange("contentVisibility", this.contentVisibility);
|
||||
this.notifyPropertyChange("secondaryVisibility", this.secondaryVisibility);
|
||||
}
|
||||
}
|
||||
@@ -37,7 +37,7 @@
|
||||
<Label text="{{ variantSummary }}" class="pairing-variant" visibility="{{ variantVisibility }}" />
|
||||
<Label text="{{ proximityLine }}" class="{{ proximityClass }}" />
|
||||
<Label text="{{ deviceName }}" class="pairing-serial" />
|
||||
<Label text="{{ armsSummary }}" class="pairing-arms" textWrap="true" />
|
||||
<Label text="{{ armsSummary }}" class="pairing-arms" textWrap="true" visibility="{{ armsVisibility }}" />
|
||||
<Label text="{{ warning }}" class="pairing-warning" textWrap="true" visibility="{{ warningVisibility }}" />
|
||||
</StackLayout>
|
||||
<Label col="2" text="{{ chevron }}" class="pairing-chevron" verticalAlignment="center" />
|
||||
@@ -61,7 +61,7 @@
|
||||
</GridLayout>
|
||||
<Label text="{{ proximityLine }}" class="{{ proximityClass }}" />
|
||||
<Label text="{{ deviceName }}" class="pairing-serial" />
|
||||
<Label text="{{ armsSummary }}" class="pairing-arms" textWrap="true" />
|
||||
<Label text="{{ armsSummary }}" class="pairing-arms" textWrap="true" visibility="{{ armsVisibility }}" />
|
||||
<Label text="{{ warning }}" class="pairing-warning" textWrap="true" visibility="{{ warningVisibility }}" />
|
||||
</StackLayout>
|
||||
<Label col="2" text="{{ chevron }}" class="pairing-chevron" verticalAlignment="center" />
|
||||
@@ -73,8 +73,6 @@
|
||||
<Label text="Selected" class="h2 pairing-section" />
|
||||
<Label text="{{ selectionSummary }}" textWrap="true" />
|
||||
</StackLayout>
|
||||
|
||||
<Label text="{{ diagnostics }}" class="pairing-diagnostics m-t-16" textWrap="true" visibility="{{ diagnosticsVisibility }}" />
|
||||
</StackLayout>
|
||||
</ScrollView>
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@ export type PairingRowItem = PairingRowPresentation & {
|
||||
variantVisibility: "visible" | "collapse";
|
||||
proximityLine: string;
|
||||
proximityClass: string;
|
||||
armsVisibility: "visible" | "collapse";
|
||||
warningVisibility: "visible" | "collapse";
|
||||
chevron: string;
|
||||
/**
|
||||
@@ -56,7 +57,6 @@ export class PairingViewModel extends Observable {
|
||||
private startedAtMs = 0;
|
||||
private advertisementCount = 0;
|
||||
private scanFailure = "";
|
||||
private readonly logLines: string[] = [];
|
||||
|
||||
private _scanning = false;
|
||||
private _status = "";
|
||||
@@ -137,7 +137,6 @@ export class PairingViewModel extends Observable {
|
||||
this.scanning = false;
|
||||
this.refresh();
|
||||
},
|
||||
onLog: (line) => this.appendLog(line),
|
||||
});
|
||||
if (!started) {
|
||||
this.status = "Could not start the Bluetooth scan. Check that Bluetooth is on.";
|
||||
@@ -271,14 +270,6 @@ export class PairingViewModel extends Observable {
|
||||
return this.onboarding ? "Back" : "Cancel";
|
||||
}
|
||||
|
||||
get diagnostics(): string {
|
||||
return this.logLines.slice(-12).join("\n");
|
||||
}
|
||||
|
||||
get diagnosticsVisibility(): "visible" | "collapse" {
|
||||
return this.logLines.length ? "visible" : "collapse";
|
||||
}
|
||||
|
||||
// --- actions ---------------------------------------------------------------
|
||||
|
||||
// Arrow property: NativeScript fires XML event handlers with `this` bound to the
|
||||
@@ -443,18 +434,11 @@ export class PairingViewModel extends Observable {
|
||||
"selectionVisibility",
|
||||
"selectionSummary",
|
||||
"primaryEnabled",
|
||||
"diagnostics",
|
||||
"diagnosticsVisibility",
|
||||
] as const) {
|
||||
this.notifyPropertyChange(property, this[property]);
|
||||
}
|
||||
}
|
||||
|
||||
private appendLog(line: string): void {
|
||||
this.logLines.push(line);
|
||||
if (this.logLines.length > 50) this.logLines.splice(0, this.logLines.length - 50);
|
||||
}
|
||||
|
||||
private formatError(error: unknown): string {
|
||||
return formatErrorMessage(error);
|
||||
}
|
||||
@@ -474,6 +458,7 @@ function toRowItem(row: PairingRowPresentation, selected: boolean, onRowTap: (ar
|
||||
variantVisibility: row.variantSummary ? "visible" : "collapse",
|
||||
proximityLine: `${row.proximityGlyph} ${row.proximitySummary}`,
|
||||
proximityClass: row.zone === "immediate" ? "pairing-proximity pairing-proximity-immediate" : "pairing-proximity",
|
||||
armsVisibility: row.armsSummary ? "visible" : "collapse",
|
||||
warningVisibility: row.warning ? "visible" : "collapse",
|
||||
chevron: selected ? "✓" : row.canSelect ? "›" : "…",
|
||||
onRowTap,
|
||||
|
||||
@@ -15,8 +15,6 @@ const {
|
||||
MAXIMUM_METERS,
|
||||
zoneFromMeters,
|
||||
zoneLabel,
|
||||
formatDistance,
|
||||
proximitySummary,
|
||||
sortedByProximity,
|
||||
} = require("../.test-build/app/g2/ble-proximity.js");
|
||||
|
||||
@@ -66,22 +64,12 @@ test("zones and their boundaries", () => {
|
||||
assert.equal(zoneLabel("immediate"), "In your hand");
|
||||
});
|
||||
|
||||
test("weak signals are marked as approximate", () => {
|
||||
test("weak signals carry lower confidence", () => {
|
||||
const strong = estimateProximity(-45, GLASSES_CALIBRATION);
|
||||
const weak = estimateProximity(-95, 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, 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, GLASSES_CALIBRATION);
|
||||
const byId = (d) => d.id;
|
||||
|
||||
@@ -163,8 +163,8 @@ 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");
|
||||
// A lone advertiser has nothing to be closer than, so no Closest badge.
|
||||
assert.equal(nearestCandidateId([d("1", -80)]), null);
|
||||
// Nothing to rank without RSSI.
|
||||
assert.equal(nearestCandidateId([d("1", null)]), null);
|
||||
assert.equal(nearestCandidateId([]), null);
|
||||
|
||||
Reference in new issue
Block a user