Skip to main content

BLE & sensors

How a physical Enode sensor becomes live reps in the app, across web / iOS / Android, including the SmartBar (VMP_SB) dual-sensor flow. This is the source of truth for the BLE subsystem and the handoff doc for anyone (human or agent) picking up sensor work. Code lives in packages/core/src/ble/, packages/core/src/calibration/, packages/ui/src/sensor-3d/, and the in-session hooks under apps/tracking/src/app/workouts/today/.

The pure byte-parsing, quaternion math, fusion, and pool logic all ship with co-located *.test.ts. npm run test covers them; the native transports and on-device timing are not unit-tested and need hardware (see Device-verify loop).

Layered architecture​

The whole point of the stack is that nothing above the transport touches navigator.bluetooth or a Capacitor plugin — platform code is sealed under two interfaces.

UI / hooks ConnectSensorSheet · use-sensor-connection · use-station-reps
use-sensor-reps · calibration hooks · SensorViewer (3D)
│ consumes SensorAdapter + the sensor pool
────────────────────────┼────────────────────────────────────────────────
domain sensor-pool.ts (stations, units, L/R) rep-recorder.ts
rep-fusion.ts (dual-sensor merge) throughput-monitor.ts
│
sensor object enode-sensor.ts → EnodeSensor implements SensorAdapter
commands (enode-sensor-commands.ts) + parsing
(enode-sensor-protocol.ts) + steady-state-tracker.ts
│ talks bytes through BleConnection
────────────────────────┼────────────────────────────────────────────────
transport BleService / BleConnection (ble/types.ts)
web-bluetooth.ts │ capacitor-ble.ts → native EnodeBle plugin
│ (iOS EnodeBlePlugin.swift /
│ Android EnodeBlePlugin.kt)

Two contracts define the seams:

  • BleService / BleConnection (ble/types.ts) — the raw transport: scan/pick a device, connect, subscribe/read/write GATT characteristics. Bytes are normalized to Uint8Array at this boundary; DataView / base64 quirks stay platform-internal.
  • SensorAdapter (ble/enode-sensor.ts) — a connected, initialized sensor: identity (id, deviceName), live readouts (battery/rssi/temperature/versions), a typed event surface (on("data" | "event" | "settings" | "connected" | "disconnected" | "apiIncompatible")), and commands (configure = settings+mode with retry, setMode, writeSettings, resetOrientation, shutDown, shouldDisconnect, plus the auto-reconnect lifecycle setReconnecting / reattach). Everything UI-side types its sensor as SensorAdapter and never cares which platform produced it.

Entry points​

ble/index.ts is the public surface:

  • getBleService() — singleton, picks WebBluetoothService on web or CapacitorBleService on a native platform.
  • searchAndConnect({ signal }) — the one "tap Connect → live sensor" flow for all platforms: pickDevice → connect → new EnodeSensor(connection) → initialize(). Honors an AbortSignal at every step (cancel = AbortError the sheet swallows).

searchAndConnect routes all three platforms through the unified BleService path (commit 7b02b99). The old CapacitorEnodeSensor package bridge (ble/capacitor-enode-sensor.ts) has been deleted — it was unreferenced (no import anywhere), so its top-level registerPlugin never ran.

Transports​

PlatformBleService implNative plugin
Web (Chrome)web-bluetooth.ts— (Web Bluetooth API)
iOScapacitor-ble.tsapps/tracking/ios/App/App/Plugins/EnodeBlePlugin.swift
Androidcapacitor-ble.tsapps/tracking/android/.../plugins/EnodeBlePlugin.kt
  • Live scan with streaming RSSI requires Chrome's experimental flag on web (supportsLiveScan()); without it, pickDevice falls back to the native chooser. Native transports support live scan.
  • Service and characteristic UUIDs for both GATT layouts live in ble/config.ts. Every scan uses SENSOR_SCAN_SERVICE_UUIDS (both generations) and SENSOR_GATT_SERVICE_UUIDS (Web Bluetooth optionalServices); see GATT layouts.

Android transport hardening (2026-07-16)​

Two Android-only failure modes were found on a budget tablet (SM-X230) with a streaming SmartBar pair — both invisible on iOS, whose CoreBluetooth queues notifications reliably no matter how slow the consumer is:

  • Connection starvation. With two sensors at the default BALANCED connection interval, one link delivered seconds-late, smeared buffers (583-sample "eccentrics", non-monotonic time). EnodeSensorDevice. requestHighPriority() now requests CONNECTION_PRIORITY_HIGH during connect (next to the MTU request, after service discovery — see below) — required for a two-sensor pair.
  • Notification loss under bridge load. Android's GATT silently drops notifications when the app's callback path is slow, and the plugin used to JSON-serialize + bridge-eval every notification (~100/s streaming) from inside that callback — observed as dropped repConcentricStarts, missing EndValids and byte-corrupted event packets. EnodeBlePlugin now batches: the GATT callback only enqueues (returns instantly); a single FIFO flushes every 50 ms as ONE notificationBatch bridge event (~10× fewer WebView evals). A rep-event notification (characteristic …1524) flushes the queue immediately, so rep latency stays at milliseconds and data-vs-event ordering — which the rep recorder depends on — is preserved by the single FIFO. The TS transport (capacitor-ble.ts) handles both notification (web/iOS, unchanged) and notificationBatch (Android).

Android connect hardening (2026-08-21)​

A customer on a Lenovo Idea Tab (TB336ZU, Android 16) reported every connect attempt ending in connect: service discovery failed, while the same sensor worked on older, weaker hardware. The transport had no way to say why, so the first goal was making the cause observable and the second was removing the ways a healthy link could still land in that message:

  • Unbounded GATT operations. Every deferred.await() could wait forever. Android delivers no callback for a request it refuses, so a refused operation held the per-device mutex indefinitely — a silent hang that looks like a slow connect, never an error. All operations are now bounded (CONNECT_TIMEOUT_MS / DISCOVER_TIMEOUT_MS / OP_TIMEOUT_MS).
  • Unchecked request results. On API 33+ requestMtu, discoverServices, writeCharacteristic and writeDescriptor all report whether the request was accepted; the 33+ branch ignored those values while the legacy branch checked them. Since Android 13 every device takes the unchecked path. Both branches now check and log.
  • Service discovery ran last. Connect issued requestMtu + requestConnectionPriority before discoverServices(). Any link loss in that widened window nulls the GATT client, so discovery finds nothing and reports service discovery failed — hiding a disconnect behind a discovery error. Discovery now runs first; MTU and priority follow once the link has proven itself.
  • Orphaned GATT clients. connect() overwrote connected[deviceId] without closing the previous BluetoothGatt. Android caps GATT clients per app; past the cap every connect fails with status 133 until the process restarts, which presents as hardware slowly going bad. The previous client is now closed, and pool removal only drops the entry if it is still the same device (forget).
  • The disconnect status was never logged. The STATE_DISCONNECTED branch — the path a link loss during connect actually takes — logged nothing. It now logs, and EnodeSensorDevice.lastStatus is appended to the connect rejection so a support screenshot carries the cause: 8 = supervision timeout (peer went away), 133 = generic/early failure, 19 = peer terminated, 22 = local.

Silent "connected but no reps" hardening (2026-09-25)​

Customer reports (iPads in feedback mode, and a single-sensor workout user) described a sensor that connects, shows its battery and moves the 3D model, yet records no reps. Three code paths could produce exactly that without any error:

  • Overlapping GATT operations orphaned a call on iOS. EnodeBlePlugin.swift keeps one pending call per deviceId|characteristic; a second write to the command characteristic before the first was acknowledged replaced the first call, which then never settled (e.g. configure hung before its setMode). CapacitorBleConnection now runs every read / write / notify toggle through a per-connection FIFO queue with a GATT_OP_TIMEOUT_MS (5 s) bound, so operations never overlap and a lost callback fails the operation (and configure's retry takes over) instead of stalling the queue.

  • A failed API-version read left the sensor silently idle. Without the Software Revision string apiVersionNumber stayed null, so setMode sent the idle none mode and every rep-end decoded to no payload. The read is now retried (API_VERSION_READ_ATTEMPTS, 3×) and otherwise initialize throws SensorIdentificationError: searchAndConnect drops the link and the connect sheet shows a localized "try connecting again"; the auto-reconnect drops the link and keeps retrying until its timeout.

  • The feedback flow configured the sensor while the connect sheet was open (see Device view ↔ tracking view mode ownership).

  • The feedback flow ran without its tracking setting. A feedback mode resolves its sensor mode from trackingSourceSettingID; when that setting was missing, configure never ran and useStationReps got sensorMode = null, which drops every rep-end. The tracking view now gates on the setting with RequireData (error + "Try again" instead of a silent sensor).

  • "Connect" took the first sensor heard, not the nearest. In a room with several powered-on sensors (the reporting customer runs nine) the first advertisement is often a sensor on another rack, so the device connected — battery and 3D model included — to a sensor nobody was lifting with. The native iOS package behaves the same (first device above -98 dBm, i.e. any). CapacitorBleService.pickDevice now keeps listening PICK_COLLECT_MS (1.5 s) after the first advertisement and connects to the strongest RSSI (strongestDevice). Web keeps the browser's own chooser.

  • A failed reconnect attempt was never retried on iOS. The pool's auto-reconnect only attempted a reattach on scan updates, and iOS reports each peripheral once per scan, so one failed attempt left the sensor in "reconnecting" until the 60 s timeout dropped it. The first sighting now starts the retry loop (found by the simulated-sensor suite below).

Every tracking view decides its sensor configuration through one pure function, planSensorConfiguration (ble/sensor-configuration.ts), so the exercise view and the feedback flow can no longer drift apart.

Not device-verified yet. Whether the firmware mis-handles settings writes in the middle of the calibration handshake is an assumption, not a measurement.

Simulated-sensor suite​

sensor-scenarios.test.ts runs the real stack — transport queue, EnodeSensor, sensor pool, auto-reconnect — against a simulated sensor, and checks that every lift reaches the app as a rep. It runs with npm run test; no hardware needed.

  • FakeEnodeBle (ble/testing/fake-enode-ble.ts) implements the native plugin surface with the iOS plugin's bookkeeping (one pending call per characteristic; a second call replaces the first). Its first test proves the model reproduces the orphaned call.
  • VirtualSensor speaks the protocol as the app parses it: device-info reads (with injectable Software Revision failures), the settings / mode / read-back commands, calibration, and rep events in the current hardware mode's byte layout. Its assumptions (idle none mode after connect, no reps while calibrating) are listed at the top of the file.
  • Injection: new CapacitorBleService(fake) + setBleService(...) (ble/index.ts) — the same seam a debug-build "virtual sensor" could use later.
  • Scenarios (customer reports 2026-09): nearest of nine sensors wins; API-version read retried / connect failed visibly; bar speed recorded after connecting from the picker; no writes while the sheet is open on a calibrating sensor; jump mode survives re-opening the sheet; overlapping SET_MODE / configure in both orders; no setting → no reps; reconnect mid-set with the view re-applying; reconnect retried after a failed attempt; SmartBar pair configured on both sides.
  • Mutation-checked (2026-09-25): reverting any single fix — transport queue, sheet gate, strongest-RSSI pick, version retry, reconnect retry loop — turns its scenario red.
  • Not covered: real radio behaviour, firmware rep rejection, and the React effect dependencies themselves (the suite models the views' effects; planSensorConfiguration is what they share). Those need the device check.

GATT layouts: legacy (API 2) and API 3 (firmware 7.0.6)​

Firmware 7.0.6 moved the sensor to a new GATT table ("API 3"). The app supports both layouts at once, because sensors in the field update over time. The normative byte spec is the firmware repo's GATT.md; the rollout is apps first, then firmware: an app without API 3 support does not find a 7.0.6 sensor at all.

Legacy (firmware ≤ 7.0.5)API 3 (firmware ≥ 7.0.6)
Advertised16-bit 0x1523128-bit F9CE0001-1C15-4D29-9907-B6C8F7067321
NameVMP / VMP_SB — encodes the typeenode for every variant
Device typefrom the namescan-response Service Data, then Device Info model
Event / Data / Command…1524 / …1525 / …1526F9CE0002 / 0003 / 0004, same payloads
BatteryBattery Service 0x2A19Device Status F9CE0005, byte 1 (0xFF = unknown)
Temperature0x2A1C, raw float32 LEDevice Status, i16 at 4 in 0.01 °C (0x7FFF = unknown)
IdentityDevice Information stringsDevice Info F9CE0006, 20-byte binary
Supported modeshardware-revision tableDevice Info capabilities bitmask
Command writesexact command lengthzero-padded to exactly 20 bytes

Layout detection​

EnodeSensor.initialize first reads Device Info (F9CE0006). A read that returns bytes means API 3, and a failed read means legacy. A missing characteristic fails at once on every transport (native: "characteristic not found", web: NotFoundError), so a legacy sensor costs one fast failed read. gattLayout records the result. SENSOR_CHANNELS in config.ts maps each layout to its Event / Data / Command UUIDs. A reattach re-detects the layout, so a sensor that reconnects after a DFU to 7.0.6 is picked up on the new table.

Device type (bar sensor or sensor)​

API 3 sensors all advertise the name enode, so the name says nothing about the type. sensor-kind.ts is the single place that decides it:

  • Before connecting: isBarSensorDevice(device) reads the 6-byte Service Data the sensor puts in its scan response under F9CE0001 (format, model, hw_rev, capabilities; parseScanInfo). The iOS and Android plugins forward Service Data in every scanResult, and capacitor-ble.ts keeps data seen earlier when a later iOS callback arrives without it. Legacy units fall back to the VMP_SB name. Web Bluetooth's chooser reports no advertisement data, so on web an API 3 bar sensor is only known after connecting.
  • After connecting: EnodeSensor.isBarSensor reads Device Info model == 2 on API 3 and the name on legacy. isBarSensor(sensor) wraps it with a name fallback for adapters that don't report it.

Everything that used to test the name now reads this flag: the pool's isSmartBar, the SmartBar pairing (use-sensor-connection.ts: left side first, reject a non-bar second sensor), the SmartBar quaternion rotation in the data stream (prepareQuaternion(raw, isBarSensor)), and the 3D body model (SensorViewer's barSensor, including the connecting phase via searchAndConnect's onConnecting({ isBarSensor })).

Field mapping on API 3​

Device Info fills the same SensorAdapter fields the legacy strings did, so nothing above the BLE layer changes:

  • hardwareNumber = String(hw_rev), e.g. "611".
  • firmwareNumber = String(fw_rev), e.g. "706".
  • serialNumber = %08X%08X of device_id0 / device_id1. The firmware guarantees it is byte-identical to the legacy Serial Number string.
  • modelNumber stays null; nothing reads it.

The binary decoders are parseDeviceInfo and parseDeviceStatus in enode-sensor-protocol.ts. Device Status notifications update battery, temperature and deviceStatus (charging, calibration flags, mode, cell voltage, uptime, reset reason). The firmware sends one snapshot when notifications are enabled and a heartbeat about every 30 s.

Sensor details dialog​

The connect sheet's "Show info" dialog (ConnectSensorSheet.tsx) lists what the sensor reports, built by the pure sensorDetailRows in sensor-details.ts: type, firmware, hardware, serial, protocol, battery and temperature for every sensor; for API 3 additionally cell voltage, charging, calibration state, factory calibration, uptime and last restart cause. Features (capabilities) and the bootloader app version are deliberately not shown. A row is left out when the sensor has no value. The open dialog re-reads the sensor every second, so the charging and calibration rows follow Device Status notifications. Behind the SENSOR_DETAILS_EXTENDED flag; false restores the plain version + serial lines.

API 3 decodes like v200​

API 3 changed the GATT table, not the Event / Data / Command payloads. Firmware 7.0.x reports API "2.0.0" on the legacy layout, so an API 3 sensor gets apiVersionNumber = "v200" (SENSOR_API3_PAYLOAD_VERSION in config.ts). Rep decoding, the settings clamp, steady state and rep feedback behave exactly as on a 7.0.5 sensor. If the firmware ever adds payload variants (announced through api_minor), this is the constant to revisit.

Unsupported API​

A Device Info format other than 1 or an api_major other than 3 throws SensorApiUnsupportedError. The connect sheet then asks the user to update the app, and the sensor pool stops an auto-reconnect instead of retrying until its timeout (the spec forbids disconnect loops). A truncated Device Info read is a bad read, not a protocol change: it throws the retryable SensorIdentificationError.

Stale GATT cache after a DFU​

A DFU does not change the sensor's BLE address, so a phone may still hold the pre-update GATT table. The firmware sends a Service Changed indication once per connection.

  • iOS: EnodeBlePlugin.swift handles peripheral(_:didModifyServices:). During a pending connect it rediscovers the services. Once connected, it drops the link so the auto-reconnect re-runs layout detection on the fresh table.
  • Android: the stack caches GATT tables only for bonded devices, and the sensors are not bonded, so no workaround is in place. Device-verify this.

EnodeBlePlugin.kt flushes its notification batch immediately for the rep event characteristic of both layouts (…1524 and F9CE0002).

Removing the legacy path​

Once Device Info shows the whole fleet on firmware ≥ 706, the legacy branch can go: the legacy entry in SENSOR_CHANNELS, the DIS / BAS / thermometer reads, 0x1523 in the scan filter, the legacy …1524 UUID in the Android plugin, and the VMP_SB name fallback in sensor-kind.ts.

Sensor access control (SAT v1)​

Firmware "FW-A" (not released yet) adds access control for RED Art. 3(3)(e) / EN 18031-2: who may use a sensor is decided by the backend, which signs a 116-byte token per (sensor, member, app install); the sensor verifies it, and both sides derive an encrypted channel for Event, Data and Command. The normative spec is SECURITY-protocol.md of the sensor revisions (outside this repo); the server contract is HANDOFF-security-server-response.md §4.

Versioning and strict mode (decisions 2026-10-26): the authenticating firmware ships as 7.0.7 with api_major 3, and no API-3 sensor without it reaches customers. So the legacy layout (API 2, firmware 7.0.4) keeps the plain path, and every API-3 sensor authenticates, in every state — also a sensor with no owner yet ("FREE but locked"). Device Info capabilities bit 6 is only checked (0 is logged). The v8 generation (hardware 800, API 3.1) goes by bit 6 (E2E finding app-7, 2026-10-27): image 0.2.0 on sets it and authenticates like every other API-3 sensor; the 0.1.x images without it keep the plain path, with a warning in the log.

Where it lives​

PieceFile
Token, ACL message, wire constants, serialble/auth/access-token.ts, acl-message.ts, sat-wire.ts
Handshake + channel (pure bytes)ble/auth/auth-session.ts
Connection flow, retry rules, ACL pushble/auth/auth-flow.ts
Security log (§9a), access noticesble/auth/sensor-log.ts, access-notices.ts
Install key + its storesble/auth/install-key.ts, install-key-store.ts
Status codes and user-facing situationsble/auth/auth-status.ts, copy in sensor-access-copy.ts
Token provider, cache, login/logout hookssensor-access/
Server callsapi/sensors.ts
Native: MTU, install-key seedEnodeBlePlugin.swift / EnodeBlePlugin.kt (getMtu, loadSensorKey, storeSensorKey, deleteSensorKey), SensorKeyStore.kt

Crypto is @noble/curves (Ed25519, X25519) and @noble/ciphers (ChaCha20-Poly1305) with @noble/hashes (SHA-256, HKDF) — see ADR 0015.

Connection flow​

EnodeSensor.initialize after Device Info, on an API-3 sensor (a v8 only with bit 6):

  1. Read Device Status; flag bit 5 owned = 0 means FREE (no owner).
  2. authenticateSensor: ATT MTU ≥ 185 (else status 6, no handshake), the provider's token (see "Token before connect" below), HELLO / CHALLENGE / PROVE / RESULT on the Auth characteristic f9ce000a, then the ACL message push (every authenticated connect).
  3. A FREE sensor without a token on this phone, or one that answers 7, ends as unclaimed: connected but locked — nothing is subscribed or written, the sensor emits unclaimed, and the connect sheet shows "Make this sensor yours" (SensorClaimDialog) before the station gets the sensor. claimConnectedSensor calls POST /sensors/claim, fetches the first token and runs authenticate() — on the same connection, or on a fresh one when the sensor dropped the link (it does so 20 s after connect without a channel). The dialog's first step names the physical action — "Plug in the charging cable", or "Press the button twice" when Device Info capabilities bit 7 says the window opens by button (v8); the bit decides, no hardware table. Status 11 (proof or first token outside the possession window, D1) keeps that title with a "Not in time" line. Every other failure replaces title and message in the dialog, which stays open; the copy is sensor-access-copy.ts.
  4. Status 1–5 → one token refresh and one more attempt; 10, a timeout or a broken answer → one more attempt as is; anything else, or the second failure → SensorAccessDeniedError. The connect sheet shows the access message (connectErrorCopy: its only button is the reconnect "Try again", so status 11 there — claimed on the server, the first HELLO missed the window — asks for the physical action and then Try again, no claim); the sensor pool does not reconnect (the user acts first). "As is" presents the token of the first attempt again: a rescue token is handed out once, so asking the provider a second time would lose it. The refresh after status 1–5 is waited for until TOKEN_WORK_BUDGET_MS (12 s) after the flow started; later the sensor would cut the link without a channel (about 20 s after connect) before a second HELLO, so the connect ends with the status the sensor gave.
  5. From RESULT on, Event and Data notifications are opened in the channel and Commands are sealed — frames of plaintext + 20 bytes (40 on 7.0.7; any plaintext of 1–240 bytes, so the v8's longer Data and raw tap need no special case). A frame that fails (replay, tag) drops the link; the pool's reconnect starts a fresh handshake. After such a failure the keys are gone but the disconnect is still on its way: Event and Data that arrive in between are dropped, never parsed as plaintext.

Token before connect (E2E finding app-10)​

The sensor accepts a held token until a phone of the owner pushes the new ACL, so a member the owner removed would still get a channel from the cache. SensorAccessProvider.access therefore asks GET /sensors/access?serial= before every online connect and uses its answer: the new token, or none when the list has no entry (or the server answers 403/404/410) — then the removed access ends in "Your access to this sensor was removed". The cached token carries the connect only when the server cannot answer: offline, a 429 pause, any other failure, or no answer within PRE_CONNECT_DEADLINE_MS (5 s; the late answer still lands in the cache). A refresh the serial got in the last 10 s (the flow's refetch after status 1–5) is not repeated.

Sensor identity (SCM-2)​

The assessor ruled that the app must authenticate the sensor too. Every 7.0.7 sensor has its own Ed25519 key (made at first boot, kept for life); Device Info announces it in bytes 23–54 (bytes 20–22 are the image version — one layout for every generation; v8 is told by hardware_rev ≥ 800 only).

  • Certificate (ble/auth/sensor-identity.ts): GET /sensors/access brings a 104-byte sensorCert per sensor (serial ‖ sensor key ‖ server signature), cached with the token. Before HELLO it must verify under the server key of the token's kid and name this serial; the server keys are compiled in (sensor-access/app-provider.ts: the dev keys for every non-production backend, the production keys for production). Otherwise — and when the CHALLENGE's signature over H does not verify — status 12: no PROVE, the link is dropped, "This is not your sensor". Fail closed, no transition mode.
  • Claim with possession proof (claimConnectedSensor): the app writes CLAIM_PROOF (its install key) on the Auth characteristic; the sensor in its possession window answers with its key and a signature over "enode-claim-v1" ‖ serial ‖ sensor key ‖ install key, FREE or OWNED alike (protocol §6a, revised 2026-10-27), checked against the Device Info key, then sent with POST /sensors/claim (proof). Outside the window: "Connect the charger" and the claim again. The server answers 409 while an account still owns the sensor.
  • OWNED sensor without access: when the provider's last online GET /sensors/access had no entry for the serial (serverHasNoAccess), an OWNED sensor without a token ends { kind: "unclaimed", owned: true } instead of noToken, and the claim dialog says it belongs to another account ("if it was handed over to you…"). After the claim the new token's epoch is above the sensor's, so there is no charger step after it.

My sensors: management by the owner only​

  • Where: Account › Devices › Sensors shows the My sensors page directly (DevicesSensorsSection, sensors-section.tsx; until 17.11.26 Settings › My sensors, the now deprecated MySensorsRow → MySensorsView), as in Enode One's Profile › My sensors. The manual with the safety notes and approvals is in Settings › Legal › Manual & safety (SensorManualLegalRow). It holds the account's own and shared sensors, the members, sharing, transfer (and its cancel), release, "Remove my access" (a member's own leave, with a confirmation, E2E finding app-19), the security log and staff's Service card. Each sensor is its own group; its one destructive action ("Unpair sensor" for the owner, the release of §6a; "Remove my access" for a member) is a full-width button below the group, as Delete account on the account page (E2E finding app-38). The training and connect flows offer no management: only connect, disconnect and the access message. Since 23.11.26 the sensors are listed like the devices next door (Recording): one row each (SensorListRow) with the name — "Enode Bar Sensor" for the server's model 2, "Enode Sensor" otherwise — and below it the serial number and the role. A tap opens the sensor's dialog (SensorDialog): the same two lines as its header, the members and the invitation (share, transfer), and at the bottom "Security log" beside "Unpair sensor" (a member gets "Remove my access"). The log opens only while the sensor is connected here as owner; otherwise the button answers with the hint "Connect the sensor to read it".
  • Owner only, in code: sharing, removing a member, transfer and release exist only on the object sensorOwnerActions(summary) returns (sensor-access/sensor-management.ts). It returns one only when GET /sensors lists this account's role as owner. A member's row gets sensorMemberActions instead, whose only action is leave(): the member's own DELETE …/members/<own id>, recorded as the own decision (recordOwnRelease, so no "access removed" notice follows). The confirmation dialog runs the action object it was opened with. The server refuses the rest anyway (403).
  • Release while connected stays owner-only and behind its confirmation; the RESET goes over the owner's channel as before.

Security log and notices (review E9)​

  • Log (readSecurityLog, owner or service only): 32 reads of f9ce000b, each one frame under K_s2c with nonce direction byte 0x02 and its own counter (read responses can overtake notifications, and a shared direction byte would reuse nonces), two 10-byte entries newest first, an all-zero frame ends it. Account › Devices › Sensors shows it for a connected, owned sensor (sensor-log-section.tsx): entries of the current boot get a wall time from Device Status uptime (about a minute accurate), earlier boots none. Export as CSV via the share sheet or the clipboard.
  • Notices: every prefetch (GET /sensors/access, after login and on foreground) is compared with the previous one — shared with you, yours now, access ended, transfer offered — and shown as in-app toasts (SensorAccessInit). The first result after login is the baseline.
  • Confirmations: release and transfer name the consequences (everyone loses access, phones are locked out at the next connect, the sensor stays locked until claimed again).
  • Release (releaseSensorAndReset): POST /sensors/:serial/release, then, when this phone holds the sensor's channel as owner, RESET (7F "RESET" on Auth): the sensor wipes its ACL and log and ends the link (the success; a refusal is ACL_RESULT 8 or 10), and the pool lets it go. Without the RESET the release still stands and the sensor stays OWNED until its next owner claims it in the possession window; the toast then names that action for the sensor's kind (releasePendingMessage: the connected sensor's hardware, else the server's hwRev, else no action). A transfer sends none. There is no separate factory reset in the app.
  • Removed access (lostAccess, E2E finding app-9, review L-6): a sensor this account held a token for and the server no longer lists ends the connect with "Ask the owner to share it — Your access to this sensor was removed" instead of the claim offer. The connect sheet says it once (clearLostAccess); the next connect offers the OWNED sensor for the claim and the server decides (409 while someone still owns it). The marks are kept per account (createAccessCache(storage, getCurrentUserID)) and end when a refresh lists the sensor again, a claim goes through, the own release, and at logout.
  • Firmware updates: Enode Pro has no in-app sensor DFU.

Server errors (/api/sensors)​

  • By code, never by text. Every error of /api/sensors carries {"reason": "<code>"} (server round 3); sensorApiReason (sensor-access/api-errors.ts) reads it, SENSOR_API_REASONS is the complete table. The error presenter shows userMessage ?? reason, so "My sensors" passes errors through withSensorApiMessage (sensor-access-copy.ts): the code's words, never the code. 401, 403 and 404 keep the API's translated body.
  • The claim dialog maps the code to its failure (claimFailureIssue): sensor_owned F2, sensor_key_mismatch F6, rate_limited "Try again later — Too many attempts", signing_unavailable "Try again later — unavailable"; both "later" failures close with OK. A refused claim counts toward the server's guard (50 failed claims per account and hour, sensor_owned included), so nothing repeats a claim: one request per tap.
  • Service token pick-up (F3): pickUpServiceTokens calls GET /sensors/service-tokens/pending at app start, login and every foreground. An empty list for everyone without one; a 404 (a server without the route) stays silent; 429 after 120 calls an hour, the tokens stay parked, and any failure waits for the next foreground. Only role 3 tokens for this sensor and this install key are kept, in memory, with the ACL and certificate from the same answer. access uses each once on the next connect to that serial, ahead of any cached token, until expiresAt. The cached token is left alone, so an owner's own token works again afterwards. The connect sheet says a rescue token is waiting.
  • 412 device_key_missing: the install key is registered again and the call repeated once, silently — /access inside the provider, the claim and the staff service token through withRegisteredDeviceKey.
  • 429 on /access (60 per session and hour): access-pacing.ts spaces the foreground prefetch (5 min) and does not repeat a serial's refresh within 10 s (the refresh before a connect, "Token before connect"); a 429 pauses every /access call, 10 minutes doubling to an hour, while the cached tokens carry the connects and the prefetch answers with its last result. A sensor without a cached token during the pause ends in "Go online" (F4).
  • 410 transfer_expired: the answer to a transfer shows the words and reloads, so the expired row leaves the list.

Sensor firmware update (app-55)​

The same flow as Enode One's, hw 6.x and native apps only: no offer in a browser (no such library for Web Bluetooth, and a page would have to ask the user again for the bootloader device) and none for v8 (MCUboot/SMP, no app path in either app yet).

  • Check (ble/firmware-update.ts, wired in firmware-update-app.ts): GET /enode_sensor_firmwares?hw&fw&api&beta on every connection once the sensor is ready and every 24 h while connected, for owner or service on an authenticated connection or a sensor without SAT. api is 300 (firmware-update.ts, app-80): the 7.0.7 rows carry app_sensor_api_version 300, so an app asking with 210 never gets them. The zip comes with the answer and is held in memory; a failed check is no offer.
  • Offer: a dot on the chip (the weak "!" takes that corner while it lasts) and a card above Disconnect in the connect sheet, one per sensor on a SmartBar, one update at a time. Below 20 % battery Update stays off (FIRMWARE_MIN_BATTERY, the same in Enode One); a level not read yet does not hold it back. The confirmation shows releaseNotesDe / releaseNotesEn in the app's language, else the other one, and no block without notes.
  • Install: EnodeBle.startFirmwareUpdate, Nordic's Secure DFU with Enode One's settings (PRN 1, buttonless). The sensor allows DFU entry only on the authenticated connection (SECURITY-protocol.md §8), so the sensor leaves the pool without a disconnect, and the library's own central manager (iOS) or GATT client (Android) shares the open link. Events: firmwareUpdate {deviceId, state, progress}.
  • End: done → the sheet searches again on its own, then calibration as after any connect. Failed before the upload → the link is dropped and Try again is a normal connect, which brings the offer back. Failed during the upload → the sensor sits in its updater and Try again restarts the library with the zip it has.
  • Not covered by tests: the native libraries and the two link-sharing paths need a device; Android's is the one to prove first. Android's retry during the upload may not find the sensor, because the updater advertises under another address.
  • Not implemented: the offer does not check whether a set is running; it takes a tap and a confirmation that says the sensor disconnects. /debug/sensor-update shows every state.

Device key registration with proof of possession (round 4, 4a)​

  • Body: PUT /sensors/device-key {publicKey, sig}, both base64. sig is the install key's Ed25519 signature over "enode-device-key-v1" ‖ publicKey ‖ userId ‖ deviceSessionId (ble/auth/device-key-proof.ts). userId is the JWT uid as its 16 UUID bytes; deviceSessionId is the device-id header as 16 UUID bytes, or SHA-256 of the bearer token when that id is not a UUID. Nobody can register another install's public key, which is readable over BLE during a claim.
  • Unconfirmed layout: the byte layout and the field name are the apps' assumption until the server team confirms them. DEVICE_KEY_PROOF_DOMAIN, DEVICE_KEY_PROOF_FIELD and deviceKeyProofMessage are the one place to change. The test vectors are shared with Enode One and the server team (device-key-proof.test.ts).
  • Refusal: 400 device_key_proof_required / device_key_proof_invalid sets deviceKeyRefusal to appUpdateRequired; 409 sets it to deviceKeyElsewhere. The provider keeps it until logout and sends nothing more in the meantime: no second registration, no /access that could only answer 412.
  • What the user sees: a connect without a token ends in "Update the app" or "Sign in again" instead of "Go online". A claim that needs the key throws DeviceKeyRefusedError (withRegisteredDeviceKey), and the dialog closes with OK.

Server state​

SENSOR_ACCESS_SERVER_ENABLED (sensor-access/app-provider.ts) is on in every production build unless the build says otherwise (E2E app-87, scripts/sensor-access-env.mjs), and off in next dev unless NEXT_PUBLIC_SENSOR_ACCESS_SERVER=on is set. Off: no request goes out, the token cache stays empty, a claimed sensor ends in "Go online, then try again" (no token), and Account › Devices › Sensors shows a placeholder.

A dev build for the end-to-end tests turns it on at web-build time with NEXT_PUBLIC_SENSOR_ACCESS_SERVER=on, together with a backend that has the routes (backdev: ENODE_API_SERVER=backdev, see api/servers.ts). Any backend other than production verifies sensor certificates under the dev keys of the server team's vector file (DEV_SERVER_KEYS) — such a build is dev keys — not for customers. A production build uses the production keys (PRODUCTION_SERVER_KEYS, the same two as the firmware's auth_keys_production.h); server-keys.test.ts checks them against the check signature in fixtures/sensor-token-kid*.pub.hex.

Build marker. Settings, Profile and the foot of the connect sheet show the server, the key variant (derived from the keys in use, with a fingerprint) and the build, from NEXT_PUBLIC_BUILD_STAMP. A store build, on production without a stamp, shows nothing (sensor-access/build-marker.ts). Internal builds also take -PenodeAppLabel (Android) and ENODE_NAME_SUFFIX (iOS) for their name.

The canonical serial is lower case %08x%08x (protocol §2): normalizeSerial produces it and every request, cache key and token comparison uses it — the backend answers 400 to an upper-case ?serial=. Upper case (displaySerial, as Device Info shows it) is for the screen only. The claim sends Device Info's model as a decimal string ("1", "2"); the backend decodes a String there.

Internal builds without SAT (satFreeHw6)​

NEXT_PUBLIC_SAT_FREE_HW6=on at web-build time lets a hw 6.x API-3 sensor whose image has no SAT (capabilities bit 6 = 0: 7.0.6, a 7.0.7 built with SAT=0) take the plain path (setSatFreeHw6, SensorAccessInit.tsx). A sensor with bit 6 still authenticates, and a serial with a cached certificate is still refused. Bench and demo units only — never in a store build. Such a build carries the literal enode-build:sat-free-hw6 in its bundle (satFreeHw6MarkerEnv, next.config.ts), and scripts/check-release-bundle.mjs fails a release that contains it; see deployment.

Tests​

  • ble/compat/*.compat.test.ts: one file per sensor generation and layer — 7.0.4 on the legacy layout, hw 6.x on API 3 (7.0.6 / 7.0.7 with SAT), v8, the transports (native plugin events, Web Bluetooth), and mixed fleets (pool, SmartBar pairs, firmware change between connections). Byte contracts come from the firmware sources and GATT.md. An it.fails there marks a known, still open defect.
  • ble/auth/auth-vectors.test.ts: both shared vector files (ble/auth/fixtures/, copies of SECURITY-vectors/), byte for byte — noble's Ed25519 is RFC 8032, so even signatures compare exactly.
  • ble/auth/sensor-auth.test.ts: the real stack against a simulated FW-A sensor (ble/testing/fake-sat-firmware.ts): legacy and a v8 without bit 6 unchanged, a v8 with SAT authenticated (double-press copy), an API-3 image without SAT refused, FREE locked + claim on the same connection, FREE with a token, status 11, claimed happy path, every status code, MTU 23, no token, broken frame, epoch bump delivered by another member, the security log as owner and refused for a member. API-3 VirtualSensors are FW-A units by default (TEST_SAT_SERVER, testSatProvider), so the other scenario suites run through the encrypted channel too.
  • sensor-access/provider.test.ts: the server before every online connect and the cache as the fallback (app-10), 412 → key registration, service token once, notices between two prefetches, wipe on logout.

Not covered: the native key stores and getMtu (need a device), and the firmware itself (FW-A does not exist yet).

Protocol & quaternion math (enode-sensor-protocol.ts)​

The pure byte layer: parses rep-event packets and the raw 50 Hz data-package frames into SensorDataPoints, and holds all quaternion/vector math. It mirrors iOS EnodeMath / EnodeSensorMath.

  • parseDataPoint builds per-mode samples (strength / jump / flywheel). prepareQuaternion(raw, isBarSensor) applies iOS prepare(quaternion:): a base raw × (1,0,0,0) 180°-about-X, plus — for bar sensors only (isBarSensor) — a 90°X then 90°Y display rotation (net 120° about the (1,1,1) diagonal). This is a display rotation for the 3D model; it is fed to .reference() exactly as iOS does (see below).
  • Quaternion convention map (this trips everyone up):
    iOSherenotes
    .multiply(with:)multiplyQuaternionw-scalar Hamilton product
    .multiply(by:)multiplyQuaternionByx-scalar product (rep-data only)
    .rotate(by:)rotateVectorq⊗v⊗q⁻¹; used only inside referenceQuaternion
    .rotateBy(_:)rotateVectorByMatrixrotation matrix = transpose of the above (rotates by q⁻¹)
    .reference()referenceQuaternionyaw-only reference frame
    .slerp(with:t:)slerpQuaternionshortest-path, for fusion

⚠️ The rotate(by:) vs rotateBy(_:) gotcha (fixed in 22c1899)​

iOS has two opposite-handed vector rotations. rotate(by:) is the quaternion product q⊗v⊗q⁻¹ (rotates by q). rotateBy(_:) builds a rotation matrix that is the transpose — it rotates by q⁻¹, i.e. it cancels the start heading instead of applying it.

makeRepData / rotateRepData rotate position+accel with .rotateBy(_:) (the matrix). We had originally ported them with rotateVector (the quaternion product), which rotated the trajectory the wrong way — rotating the sensor's start orientation about Z leaked sagittal motion into the frontal plane. Fix: rotateVectorByMatrix (verbatim port of the iOS matrix), used in correctedStrengthSamples (rep-data.ts) and rotateRepRows (rep-fusion.ts). referenceQuaternion still uses rotateVector internally — that one is correct, because iOS .reference() genuinely calls .rotate(by:). The fix is sensor-agnostic: clip-on and bar reps stay byte-identical.

The sensor object (enode-sensor.ts)​

EnodeSensor wires a BleConnection to the typed SensorAdapter:

  • Commands (enode-sensor-commands.ts) — the Mode enum, setMode/writeSettings byte builders (shared by web + the native bridges). Co-located test.
  • Events — parses the event characteristic into repConcentricEndValid, eccentric, jump variants, calibrationOnline, etc., and re-emits on "event".
  • Recording (rep-recorder.ts) — buffers the raw stream per rep. Mirrors iOS RecordingDevice: keeps buffering past EccentricEndValid until ConcentricStart so a rep's full continuation is captured (also extends WL concentric reps).
  • Steady-state (steady-state-tracker.ts) — detects the sensor sitting still (rack/re-rack) for the connect+rest UI.

Sensor pool & the station model (sensor-pool.ts)​

A module-level store (usePool / useStationSensors via useSyncExternalStore, the repo's prefetch-store pattern) of every connected sensor:

  • PooledSensor = { id, sensor: SensorAdapter, stationId, position, isSmartBar } where position: "left" | "right" | null.
  • A station owns ONE logical tracking source. A single sensor = its own source; a SmartBar = 1–2 VMP_SB sensors on one station, tagged L/R.
  • Key functions: addSensor, assignSensor, assignUnit (move both bar sensors as a unit), swapSmartBarSides, groupIntoUnits, orderStationSensors (always left-before-right — fusion depends on this ordering), removeSensor, releaseStation. Whether a sensor is a bar sensor comes from isBarSensor(sensor) in sensor-kind.ts, never from the name directly (see Device type).

SmartBar (VMP_SB) dual-sensor​

Connect / assignment / 3D​

  • use-sensor-connection.ts — stationSensors, isSmartBarStation, canAddSecond (only a second VMP_SB is allowed; NotASmartBarError otherwise), addSecond (assigns the opposite side), swapSides, removeSide.
  • ConnectSensorSheet.tsx — SmartBarConnectPanel: L/R chips, side-by-side MultiSensorViewer, per-sensor battery ring + Hz, shared note, "Switch side" (works on a lone sensor too), "Add second sensor".
  • 3D (SensorViewer.tsx) — MultiSensorViewer renders one independent <SensorViewer> per pane keyed by index (two <Canvas> or keying by sensor id loses the WebGL context on swap). Both bodies ship as quantized GLBs (/models/hw6-sensor.glb, /models/bar-sensor.glb) loaded via the extension-aware useSensorModel (FBX still supported for smartDevice.fbx). Both are the pair view's housings (the claim's STEP, hw6-sensor-claim.glb / bar-sensor-claim.glb) in the frame and with the cones of the old models they replaced (sensor-compressed.glb 2026-11-23, barSensor-compressed.glb 2026-11-01), so the framing and the orientation offsets apply unchanged. A v8 sensor (Device Info hardware revision ≥ 800, isV8Sensor) shows the puck /models/v8-sensor.glb (1.1 MB, loaded on demand). Every sensor keeps its file's PBR materials, brightened per model by PAIR_VIEW_LIGHT_GAIN (hw 6.x 3.9, bar 2.1, v8 1.75) so that under SceneLights its median on-screen brightness matches the pair view's (SensorClaimAnimation, which lights more brightly; measured side by side 2026-11-23, within 3 %). The lights stay, so the cones, the contact shadow and the searching scene's tablet look as before. While connecting, before an adapter exists, the scan's Service Data names the hardware (isV8SensorDevice, onConnecting), so the puck shows already on iOS and Android; Web Bluetooth's chooser has no Service Data, there it shows once connected. Bounding-box fit uses multiplyScalar (not setScalar, which clobbers the baked root scale).
  • Calibration (packages/core/src/calibration/) — six axis cones (FaceID). useCalibratedFaces seeds synchronously from a cached WeakMap; cone visibility is driven by a raw-pulse animationStartRef (not the live calibrated set), with an animationStart === null dedup guard so held-face re-emits don't flicker, plus a mount-init effect for cached faces. Bar model/view orientation offsets in model-orientation.ts are currently identity (0,0,0) / (-90,0,0); dev console helpers setBarSensorOffset / setBarViewOffset tune them live. The v8 pair is (90,90,0) / (-90,0,0), derived from the model's axis table (its quaternion has no VMP_SB rotation); the IMU x/y signs are unchecked on a unit — setV8SensorOffset(90, 90, 180) is the flip to try.

Fusion (strength + weightlifting only)​

  • Math (rep-fusion.ts, tested) — 1:1 port of iOS EnodeSensorMath: rotateRepRows (right sensor → shared frame via Q0=(0,0,1,0)), mergeRepRows (transpose → interpolate to 101 samples → average cols 0–7 → slerp relative-delta quaternions → bar-length validation 2.18 m ±0.25 → re-stamp time), and the PendingRep canonicalizers that each produce the single canonical rawData: fuseStrengthConcentric / fuseEccentric (fused bar-centre), rotateSingleRightRep (corrected + rotated), correctSingleRep (corrected, lone/left).

  • Coordinator (use-station-reps.ts) — the runtime fusion seam; reactive so a rep extended after its end (the WL-eccentric continuation) re-fuses with the extra samples. Runs a useSensorReps per slot (≤2):

    • 1 sensor: canonicalize each rep at finalization — lone right → rotateSingleRightRep, otherwise correctSingleRep.
    • 2 sensors: buffer each rep per phase, wait PAIR_WINDOW_MS (500 ms) for the partner, record a pair/single decision, then derive the fused stream from the current source reps (so a later append re-fuses). Partner → fuse (L/R by pool position, right rotated in the merge); timeout → single.
  • One canonical trajectory per rep (no fusedData). All trajectory manipulation happens once, at rep finalization (the coordinator), and the result is stored as the rep's single WorkoutRep.rawData:

    • dual sensors → fused bar-centre (fuseStrengthConcentric / fuseEccentric),
    • lone right → corrected + rotated into the shared frame (rotateSingleRightRep),
    • lone left / single → corrected (correctSingleRep).

    The makeRepData reference-frame correction is baked in here, once — every consumer reads rawData verbatim and never re-corrects: the chart maps it straight to samples, the upload mapper (api/mappers/sessions.ts) just encodeRepData(rawData), and rep-validation reads it as-is. The old rawData(raw) + fusedData(corrected blob) split (and decodeRepRows) was collapsed into this single field.

  • By design, a fused dual-sensor rep is indistinguishable from a single-sensor rep. Only the merged center-of-bar result is stored — both sensors' metrics, positions, accel and velocity are averaged and orientations slerped, so downstream consumers treat it like any normal rep. The two per-sensor raw streams are intentionally not stored separately; the merge is one-way and the originals are not recoverable. Intended contract, not a gap.

  • WL-eccentric is the one read-vs-write nuance. The weightlifting eccentric continuation is appended to the concentric rep's stream; the dual coordinator re-fuses reactively when that append lands (the jump eccentric→concentric merge, by contrast, stays a chart-read concern).

  • Merge acceptance gates (2026-07-16, all device-driven). chooseFusion only accepts the bar-centre merge when ALL hold; otherwise the pair falls back to ONE side — the left, unless only the right is healthy — using that side's corrected trajectory and its own event metrics (averaging with a drifted partner poisoned metrics: a −6.22 m displacement was observed):

    1. Spans match within SPAN_MISMATCH_TOLERANCE (20%) — the merge normalizes each side's time to [0,1], so differing recorded windows (asymmetric WL-continuation appends) would average mid-LIFT against mid-LOWERING.
    2. Both streams healthy (rowsHealthy): monotonic time, no sample-to-sample jump > 0.3 m, |s| ≤ 3 m — a starved link's smeared buffer stays "plausible" but fails these.
    3. iOS unfold() data check inside the interpolation: every time step ≥ 0 and ≤ 0.06 s (MAX_SAMPLE_GAP_S) — dropped packets reject the merge instead of interpolating across missing movement.
    4. Bar-rigidity validation passes (the two trajectories stay 2.18 m ± 0.25 apart). iOS computes-and-discards this flag; the web now consumes it.
  • Pairing hardening (2026-07-16, pairing-machine.ts). Pure reducer (PAIRING_REDUCER), scripted-timeline tested:

    • Late-partner upgrade. A slow bridge delivers the second sensor's rep after the 500 ms window; the flushed single stays upgrade-eligible for UPGRADE_WINDOW_MS (2 s) and the late partner converts it into a pair IN PLACE (decision replaced, order kept) — previously every late partner became a second single: one physical rep counted twice. (iOS instead waits 0.8 s silently and has a latent double-store when the partner exceeds it — the upgrade is deliberately better, and time-bounded because an idle sensor's garbage rep once claimed a single 19 s later.)
    • Duration compatibility gate. Pair/upgrade only when the two reps' firmware durations agree within PAIR_DURATION_TOLERANCE (30%) — the same physical rep measured from both bar ends always matches; two independent movements almost never do (alternating single-sided reps were being merged, silently eating the count). No iOS counterpart; on a real bar it never triggers.

⚠️ Architecture divergence. Fusion landed at the rep-coordinator layer (use-station-reps.ts), not as the SmartBarUnit adapter originally sketched. ble/smart-bar-unit.ts's selectTrackingSensor returns the left sensor on purpose: it remains the tracking source for settings / 3D / connection, while reps are fused downstream. (Its doc comment now says exactly this.)

Per-station configuration​

The per-station settings effect in ExerciseDetailView.tsx (and FeedbackTrainingFlow.tsx) calls sensor.configure(options) on every station sensor. configure applies the rep-detection settings + the data-layout setMode as one unit, with retry (3× / 300 ms) — a write can transiently fail right after connect/service-discovery, which used to leave a sensor unconfigured for the session. The effect is keyed on adapterKey = id:connectionTimestamp, so it also re-fires when a sensor (re)connects (the id is unchanged across an auto-reconnect, but the timestamp changes). options.isBarbell is the firmware's inclination-rejection flag (tighter lateral-accel ceiling — repAyMax 30 vs 100), set from trackingSetting.inclinationRejection (true for barbell equipment groups; iOS passes it as isBarbell).

The original "only the left sensor triggers reps" bug was the right sensor never getting setMode, so it never streamed — hence "every station sensor". The same bug re-surfaced in FeedbackTrainingFlow (fixed 2026-07-16): it configured only the primary sensor, leaving a pair partner in its previous mode. Both call sites now loop all station sensors, keyed on every adapter's id:connectionTimestamp. minDistance reaches both sensors identically: the device-wide override, else the exercise default (exercise view) or FEEDBACK_DEFAULT_DISTANCE_THRESHOLD_CM = 20 cm (feedback flow), always clamped to 5–100 cm (training/distance-threshold.ts).

Settings verification (observational, 2026-07-21)​

A WRITE_SETTINGS write is only acknowledged at the GATT layer — nothing confirms the firmware applied the values, so a silently-unapplied config was indistinguishable from a working one. configure now follows a successful write + setMode with a READ_SETTINGS round-trip and diffs the echo against the command it just sent (VERIFY_SETTINGS in enode-sensor.ts, 1.5 s timeout).

  • The response echoes the write payload at the same indices, so the diff is a plain byte compare — diffWrittenSettings in enode-sensor-commands.ts (pure, tested against a real device capture).
  • Only indices 1…15 are comparable. Index 0 differs by design (response opcode 0x01 vs command 0x02); index 16+ diverges — the command carries iirFilter / accRangeTh there while the response carries device state (handleSettings reads response byte 16 as the calibrating flag), and v100 firmware zero-fills the tail. 1…15 still covers every rep-detection parameter: the no-motion and rep-velocity thresholds, minDistance (11) and repAyMax (13).
  • Observational only. A mismatch, or no answer at all, is logged via console.warn and never changes control flow — configure still resolves and nothing retries or throws on it. This is deliberate: we want to learn how often it fires on real hardware before letting it drive the retry loop, since firmware layouts vary more than the code assumes. The call sits inside the existing retry try so that decision is a one-line change later.
  • Flip VERIFY_SETTINGS to false to drop the extra round-trip entirely.

Found while investigating a SmartBar pair on Android (2026-07-21). It did not explain that issue — both sensors verified byte-identical every run, and the cause turned out to be firmware-side. It closes a real blind spot regardless.

Device view ↔ tracking view mode ownership​

Only strength / weightlifting / science / isometric modes carry the quaternion stream that drives the 3D model (parseDataPoint). The connect-sensor sheet ("device view", ConnectSensorSheet.tsx) therefore setMode("strength")s every connected station sensor while it's open (skipped during active calibration so that handshake is untouched) — without this, a sensor left in an exercise mode (jump/flywheel carry no quaternion) would render a frozen model when the sheet is re-opened.

Because the device view and the per-station tracking effect both want to own the mode, the tracking effect defers while the sheet is open (connectSheetOpen is in its deps and short-circuits it) and re-applies the correct per-exercise configure(options) the moment the sheet closes. This holds for both call sites — ExerciseDetailView and FeedbackTrainingFlow. The feedback flow lacked the gate until 2026-09-25, so a coach who picked a mode first and then connected had the sensor configured mid-calibration, and re-opening the sheet left the sensor in strength mode for the rest of the session. Net: device view ⇒ strength for visualisation; active tracking view ⇒ the exercise's backend-resolved mode.

Disconnect & auto-reconnect​

  • Graceful disconnect (user-initiated). Tapping Disconnect / finishing training tears the station down via the pool (removeSensor / releaseStation with graceful: true), which sends shouldDisconnect (command 0xF1), waits GRACEFUL_DISCONNECT_DELAY_MS (200 ms; iOS uses 250 ms), then disconnects — mirroring iOS userDisconnect. Skipped for a dead link (state disconnected/reconnecting). Fire-and-forget so the UI updates immediately.
  • Auto-reconnect (involuntary drop). A user disconnect removes the pool's "disconnected" listener first, so reaching it means the device dropped on its own → the pool keeps the sensor as reconnecting and searches for the same id (live startScan rediscovery → connect; connect-retry fallback when live scan is unavailable), up to RECONNECT_TIMEOUT_MS (60 s; iOS uses 120 s), then gives up and drops it. On rediscovery, EnodeSensor.reattach(connection) re-wires the same sensor object onto the fresh link (keeps identity + emitter listeners + station/side) and re-initializes.
  • A reconnect the user has to act on ends, with a message. When the fresh link ends locked (SAT unclaimed: released, handed over, or updated to an authenticating firmware elsewhere), refused (SensorAccessDeniedError) or on an unsupported API, the pool removes the sensor and tells onSensorLost listeners why (SensorLossReason: locked / accessDenied / apiUnsupported). SensorAccessInit shows it as a sticky toast. A locked sensor is not kept: nothing is subscribed on it and its firmware cuts a link without a channel after about 20 s, so keeping it would reconnect without end. A reconnect that only times out is not reported.
  • Connect is bounded. CapacitorBleService.connect rejects after CONNECT_TIMEOUT_MS (35 s, above Android's own 20 s + 10 s) and cancels the pending native connect. CoreBluetooth never times a connect out, so without the bound a sensor that left range hung the reconnect, and the request could complete later into a link nobody drives. The iOS plugin's disconnect cancels a connect that is still pending.
  • Config restored on reconnect. A fresh connection resets the firmware to its default mode, so reattach calls reapplyConfig() (replays the last configure), and the per-station effect also re-fires (via connectionTimestamp) to apply the current desired config on top.
  • UI. While any station sensor is reconnecting, the Disconnect button reads "Stop reconnect" (station-wide — covers a dual SmartBar with one side dropped); tapping it cancels the search and removes the sensor.
  • Web caveat. Reliable on native; on web it needs Chrome's experimental scan flag, otherwise it falls back to gatt.connect() polling (flaky).

Adapter state (Bluetooth turned off)​

The stack reacts to the phone's Bluetooth adapter being toggled, not just to individual peripheral drops. Both are needed because turning the radio off does not reliably deliver a per-peripheral disconnect (notably iOS CoreBluetooth, which just invalidates the connections), so a connected sensor used to keep "looking connected" until the app was restarted.

  • BleService.isEnabled() reports whether the adapter is powered on. Native reads the real CoreBluetooth / BluetoothAdapter state; web reports isSupported() (Web Bluetooth can't read the radio's on/off state, and probing it would risk the requestDevice user-activation window). searchAndConnect gates on it before scanning and throws BluetoothDisabledError when off — the connect sheet surfaces a localized "Bluetooth is off" message immediately instead of spinning until the ~20 s scan timeout fails with "no sensor found".
  • adapterState plugin event ({ enabled }) fires whenever the adapter powers on/off — iOS centralManagerDidUpdateState, Android an ACTION_STATE_CHANGED BroadcastReceiver. On off, CapacitorBleService drives every live connection's handleDisconnect(), so each sensor enters the normal auto-reconnect path (§ Disconnect & auto-reconnect) rather than showing as connected; it reattaches automatically once the radio returns within RECONNECT_TIMEOUT_MS. iOS also clears its stale connected/charMaps on off (keeping discovered so the reconnect can re-establish the same peripheral).
  • Back on: live scans are asked for again. The pool starts its reconnect scan the moment the sensors drop, while the radio is still off. Android's plugin resolves that startScan without scanning (no LE scanner) and never starts it later, so on adapterState on CapacitorBleService re-issues every live scan a caller still holds; the Android plugin also clears its scanning flag when the radio goes off. iOS re-arms through wantsScan, and the second request is harmless there.

Rep recording resilience (rep-recorder.ts, 2026-07-16)​

The recorder is a faithful port of iOS RecordingDevice — which implicitly assumes a lossless, ordered transport. Android BLE is neither, so the port gained explicit defenses (each one traced to a device capture; all unit-tested):

  • WL continuation idle filter. The WL lowering window (concentric end → repEccentricWLEndValid) drops t === 0 firmware idle samples — matching iOS, whose WL capture runs through the isRecording path after its t==0 guard. The ecc→conc turnaround continuation stays unfiltered (jump eccentrics stream all-t=0 by design; the degenerate-span 62.5 Hz resample in makeRepData handles their time axis). Flag: WL_CONTINUATION_IDLE_FILTER.
  • WL continuation re-base on append (rep-data.ts appendContinuationData, WL window only): if the appended samples' time base restarted (first t not after the rep's last t), time is shifted to continue at the concentric's end and positions chain onto its last position — otherwise the bar path drew one straight teleport line back to the origin. v201 firmware continues its clock through the WL window, so this is normally a no-op safety.
  • WL window discarded at the next rep. A WL continuation still open when the next repConcentricStart arrives is dropped (iOS clears its buffer at concentric start) — it used to be APPENDED to the previous rep, gluing the whole inter-rep window (plus the next rep's lead-in) onto it.
  • Dropped-start defense. A rep-end arriving without its start event (dropped notification) seals an EMPTY trajectory instead of whatever accumulated since the last seal (observed: a 202-sample "concentric" spanning two reps). The rep keeps its firmware event metrics — reps are never rejected for data problems; only the trajectory / uploaded data package degrades (empty rawData → encodeRepData null → package omitted).
  • Backlog trim (trailingMonotonicRun). Rep events and data samples ride different characteristics; a starved link can drain the previous phase's queued samples AFTER the start event cleared the buffer. Every seal keeps only the trailing run whose time never steps backwards — stale backlog sits before a time restart and is dropped; clean buffers pass through unchanged; all-t=0 streams pass whole.

The only true rep rejection is the firmware's own repConcentricEndInvalid / repEccentricEndInvalid (inclination rejection via isBarbell, minDistance, detection profile) — currently silent in the UI (see follow-ups). It creates no rep at all, which is a different thing from a recorded rep whose valid flag is cleared later; invalid-reps.md is the source of truth for both.

Connection check ("Sensor doesn't connect?")​

The user-facing diagnostics flow of the connect sheet, in normal builds. Logic: ble/connection-check.ts; UI: sensor-check-sheet.tsx.

  • Entry points: the "Sensor doesn't connect?" link under the connect button (no sensor attached, no search running) and "Report a sensor problem" in the sheet's options menu (sensor attached — the "connects but does not record" case).
  • BleService.getAdapterStatus() is the detailed read behind isEnabled(): adapter state (on / off / unauthorized / unsupported / unknown), Bluetooth permission, and — Android up to 11 — location permission and the system location switch. Native: the plugin's getStatus (iOS CBCentralManager.state + .authorization; Android getPermissionState + LocationManagerCompat.isLocationEnabled). It never prompts. A native shell without getStatus falls back to isEnabled() with unknown permissions.
  • runConnectionCheck reads that status, listens for advertising sensors for CONNECTION_CHECK_SCAN_MS (name + RSSI, strongest first), and adds a summary of every sensor record of the app session (§ Debug Sensors page: identity, battery, connects / drops, failed subscriptions, findings, the newest timeline entries) plus the raw message of the connect attempt that failed. It never connects to or writes to a sensor.
  • The native scanner is shared. A stop ends every scan, so the sheet aborts its own in-flight search before the check, and passes scan: false while any pooled sensor is auto-reconnecting (the check then reports the scan as skipped, not-requested).
  • connectionChecklist turns the result into the lines the sheet shows (Bluetooth, permissions, scan, battery, firmware); lines that do not apply are left out. The battery and firmware lines come from a connected sensor; a sensor that does not connect only gets the "charge it" hint when nothing was heard.
  • Report: "Send to support" calls recordConnectionCheck (a ble breadcrumb, message sensor connection check, the whole result as data) and opens the regular support report sheet with openSupportReport(undefined, { includes }). A breadcrumb, not a snapshot field: the relay stores breadcrumb data as sent and drops snapshot fields it does not know.

Diagnostics (all off in normal builds)​

Flip together with loggingBehavior: 'debug' (capacitor.config.ts — on Android it gates WebView console → logcat, so adb logcat captures them; never ship it, the native per-notification logging costs real bridge throughput): REP_EVENT_DEBUG (enode-sensor.ts — every rep event with sensor serial, mode, api + raw bytes), REP_DATA_DEBUG (use-sensor-reps.ts — per-rep stream stats: n, t-range, monotonicity, max |s|, max sample jump, plus each continuation append), FUSION_DEBUG (rep-fusion.ts — spans/health/merge outcome per pair), PAIRING_DEBUG (use-station-reps.ts — every pairing decision). window.__stationPendingReps exposes the live pending reps for a raw-sample dump. Gradle CLI builds need JAVA_HOME="/Applications/Android Studio.app/Contents/jbr/Contents/Home".

Debug Sensors page (/debug/sensors)​

The in-app answer to "the sensor is connected but doesn't track — where are the reps lost?", readable on the device without a cable. Collected by ble/sensor-diagnostics.ts, which the sensor pool starts / stops next to the throughput monitor; the page is debug/sensors/SensorDiagnosticsView.tsx.

  • Per sensor: identity (serial, firmware, API version, battery), live data rate, connects / involuntary drops, the last SET_MODE with the mode that actually went over the wire (none when the API version is unknown), the last configure outcome and attempts, and the settings read-back result.
  • Rep counters: rep starts, valid rep-ends, rep-ends the firmware rejected (EndInvalid), undecodable rep-ends, and reps the app dropped (recordRepDropped from use-sensor-reps.ts: no tracking mode, or a mode mismatch).
  • Findings: diagnoseSensor turns the record into plain-language problems (unknown API version, idle wire mode, failed configure, read-back mismatch, rejected / dropped reps, starts without ends, weak link, drops).
  • Timeline of the last 80 events, and Copy report (JSON with findings and data rates) for a support ticket.
  • Records outlive the connection — the feedback flow disconnects when it closes, so its session stays inspectable afterwards. "Reset" clears counters and forgets removed sensors.
  • The data comes from a new diagnostic event on EnodeSensor (SensorDiagnostic: setMode / configure / settingsVerify); collecting only listens and never changes control flow.
  • On a device: the static export hides /debug unless it is built with NEXT_PUBLIC_ENABLE_DEBUG_VIEW=true npm run build tracking.

Throughput monitor (throughput-monitor.ts)​

Counts "data" events per sensor over a rolling 2 s window. Per-sensor rate is a direct measure of link health (EXPECTED_STREAM_HZ = 50, degraded < MIN_STABLE_HZ = 40). The pool starts/stops monitoring as sensors connect/disconnect; UI shows the Hz + the per-sensor "weak connection" badge. Two 2026-07-16 fixes make the weak signal honest: the rate divides by the observed span (first stamp in window → now), not the fixed window — a half-filled window used to read a healthy fresh connection at ~25 Hz and flash the badge on every connect — and "weak" requires the low rate to persist 3 consecutive ticks (WEAK_CONSECUTIVE_TICKS, ~3 s; recovery clears instantly), so single-tick jank dips can't flicker it. Tested (throughput-monitor.test.ts).

Status (committed on tracking-features-v2)​

  • 7b02b99 — unified BLE transport + multi-station pool (web/iOS/Android, device-verified) + throughput monitor + calibration persist.

  • 45167bf — SmartBar dual-sensor connect flow + side-by-side 3D.

  • 22c1899 — SmartBar dual-sensor fusion + coordinator + the reference-frame (rotateVectorByMatrix) fix.

  • Canonical-trajectory refactor — one rawData per rep, baked at rep finalization; fusedData / decodeRepRows removed; chart + upload read it verbatim (see Fusion).

  • Disconnect & reconnect — graceful disconnect (0xF1), auto-reconnect (rediscovery, 60 s, "Stop reconnect" + reattach/reapplyConfig), configure() retry, and inclination rejection (isBarbell).

  • 2026-07-16 — SmartBar-pair hardening (branch sensor-video-fixes): the full device-log-driven pass documented above — WL continuation fixes, merge gates + health-based fallback, pairing late-upgrade + duration gate, recorder transport defenses, Android connection priority + notification batching, weak-badge debounce, compressed GLB sensor models, feedback-flow pair configuration. Diagnosed live over adb against an SM-X230 with a real ELEIKO pair.

npm run typecheck / lint / test (1548) are clean.

Open follow-ups​

  • Firmware 7.0.6 device-verify (handover §8), against one 7.0.6 and one 7.0.5 unit:
    • both are listed, and each shows battery and temperature
    • the 7.0.6 serial equals the unit's old 0x2A25 serial
    • reps in every mode match 7.0.5
    • the charging flag follows the charger
    • a 7.0.6 bar sensor (advertising as enode) is treated as a bar sensor before connecting (3D model in the connecting phase) and after (pairing, fusion, rotation), and reports only strength + weightlifting + barometer
    • two bar sensors + one sensor, all 7.0.6: each gets the right type, and the second-bar-sensor rule behaves as it did with VMP_SB names
    • a DFU 7.0.5 → 7.0.6 followed by a reconnect without toggling Bluetooth picks up the new table (iOS didModifyServices, Android unbonded cache)
    • the 7.0.5 temperature reads plausibly after the float32 fix
  • v8 flywheel Data order. The v8 firmware packs a flywheel Data record as t, power, frequency, energy; enode-sensor-protocol.ts (like Enode One) reads t, energy, revolutions, power. Which is canonical is the firmware team's call (ble/compat/v8.compat.test.ts, it.fails).
  • v8 on an image before 0.1.22 (legacy layout, DIS sw "2.1.0") gets no payload API version, so it connects but cannot track. TODO: map "2.1.0" once it is known which payload layouts that image sends; no firmware update is offered to it (isV8Sensor reads the DIS hardware revision too).
  • Visible rep-rejection cue. Firmware EndInvalid rejections are silent — indistinguishable from "the app lost my rep" without a USB cable. iOS exposes repRejectedCallback for exactly this; wire it to a small UI signal (pulse / counter).
  • Un-adopted iOS knobs (from the 2026-07-16 full package comparison — everything else is 1:1 or deliberately better): the 0.8 s pair window (web: 0.5 s + bounded late-upgrade), repRejectionCountThreshold (skip the first N reps of a set), and mergeEccConData's quaternion-continuity stitch in the jump chart's ecc→con merge (web re-bases time only).
  • Single-sensor integration drift has no guard. The health gates only protect pairs; a lone sensor's runaway integration (impact / missed no-motion reset) flows through. Candidates: event-level plausibility bound, or tying rangeError to rep validity.
  • apiIncompatible has no consumer. iOS un-subscribes all notifies on a too-new sensor API; the web only emits the event.
  • v100 jump raw stream is misparsed (strength layout parsed as jump while V100_JUMP_STRENGTH_WIRE drives squat/CMJ through the strength engine) — reps/metrics are event-based and unaffected; per-rep charts for v100 jumps are empty/wrong.
  • Fusion is strength + weightlifting only (jump/flywheel fusion is commented out in iOS too).
  • enode-sensor.ts is large; a split is deferred (extract the pure event decoders + the type surface, keep the class a thin shell).

iOS reference sources​

The Swift originals live in a sibling checkout outside this repo (a local development/packages/ tree — not vendored here). Key files:

  • EnodeSensorPackage/.../EnodeSensor/Device/EnodeSensorMath.swift — makeRepData, rotateRepData, the merge.
  • EnodeSensorPackage/.../EnodeSensor/Device/EnodeSensorStream.swift — processUpdate (builds s/a RAW, only q gets prepare).
  • EnodeSensorPackage/.../EnodeSensor/Recording/RecordingDevice.swift — buffering.
  • EnodeGeneralExtensions/.../Math/MBQuaternion.swift + MBVector.swift — .reference(), .rotate(by:) vs .rotateBy(_:), the products.

When porting, read the Swift, match the convention exactly, add a boundary test. The exact local base path is recorded in agent memory.

Device-verify loop​

Web changes are live on the dev server (npm run dev tracking, :3000) — best debugged in a Chrome session (Web Bluetooth + experimental flag for live scan). Native is not live-reload; the app bundles the static export:

npm run build tracking
cd apps/tracking && npx cap sync ios # or: npx cap sync android
# then Run (⌘R) in Xcode / Android Studio

cap sync does not build the web bundle — run npm run build first, and run cap sync from apps/tracking, not the repo root.