diff --git a/AGENTS.md b/AGENTS.md index 41bc63636..02cb3a17f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -96,7 +96,10 @@ a hotspot. permanent data loss or an infinite re-flood. Never ACK a partial chunk. 2. **`decoded_onehz` stays INSERT-OR-REPLACE on its key `(device_id, ts_ms)`.** Newest wins: with INSERT-OR-IGNORE a stale or failed decode would - permanently shadow a fresh re-offload of the same second. A write that + permanently shadow a fresh re-offload of the same second. The neutral + path (`_queueNeutralOneHz`) is newest-wins PER FIELD (INSERT OR IGNORE + + UPDATE COALESCE): a `NeutralSample` carries only what it measured, and a + whole-row REPLACE let a same-second temperature sample null the HR. A write that replaces a second must replace that `(device_id, ts_ms)`'s `decoded_rr` beats in the same batch, never another device's (`_queueRrBeats` via `_queueDecodedOneHz`, and `_queueNeutralOneHz`). Known gap: the restore diff --git a/ios/Runner/AccessorySetup.swift b/ios/Runner/AccessorySetup.swift index 90f2234c4..ad723eecf 100644 --- a/ios/Runner/AccessorySetup.swift +++ b/ios/Runner/AccessorySetup.swift @@ -103,7 +103,12 @@ enum AccessorySetup { // or no argument is the band picker, byte-identical to before. if let args = call.arguments as? [String: Any], let services = args["services"] as? [String] { - Impl.shared.showSensorPicker(services: services, reply) + // `name`/`label`: a sensor that SHARES its service with another + // (FEE1: the Mi Bands and the Helio Strap) is told apart by the + // name it advertises and the label its approval was made under. + Impl.shared.showSensorPicker(services: services, + name: args["name"] as? String, + label: args["label"] as? String, reply) return } let addAnother = (call.arguments as? Bool) ?? false @@ -424,16 +429,21 @@ private final class Impl { /// return. Every service must be declared under `OSAskSensorServices`; anything else /// is refused here rather than handed to ASK, whose descriptor validation traps. func showSensorPicker(services: [String], + name: String? = nil, + label: String? = nil, _ completion: @escaping (Result) -> Void) { // Same as showPicker: the already-approved check needs the activated accessory list. whenActivated({ [weak self] in - self?.showSensorPickerActivated(services: services, completion) + self?.showSensorPickerActivated(services: services, name: name, label: label, + completion) }, timedOut: { completion(.failure(PickerError(message: "Accessory setup is not ready yet. Try again."))) }) } private func showSensorPickerActivated(services: [String], + name: String?, + label: String?, _ completion: @escaping (Result) -> Void) { let wanted = Set(services.map { $0.uppercased() }) guard !wanted.isEmpty, wanted.isSubset(of: sensorServices) else { @@ -441,9 +451,12 @@ private final class Impl { message: "That sensor is not declared for the iOS pairing sheet."))) return } + // A shared service is reused only when the approval is THIS device's (its + // label); another sensor's approval on the same service would hand back + // that sensor's id on every attempt. if let existing = session.accessories.first(where: { a in - guard let svc = service(of: a) else { return false } - return wanted.contains(svc) + guard let svc = service(of: a), wanted.contains(svc) else { return false } + return label == nil || a.displayName == label }), let id = existing.bluetoothIdentifier?.uuidString.uppercased() { completion(.success(id)) return @@ -459,8 +472,12 @@ private final class Impl { let sensorItems = wanted.sorted().map { svc -> ASPickerDisplayItem in let descriptor = ASDiscoveryDescriptor() descriptor.bluetoothServiceUUID = CBUUID(string: svc) - return ASPickerDisplayItem(name: labels[svc] ?? "Sensor", productImage: image, - descriptor: descriptor) + // Always WITH the service UUID (a name-only descriptor traps; see the + // note on whoopMemberUUID16), and the name must be declared under + // NSAccessorySetupBluetoothNames or iOS ignores it. + if let name = name { descriptor.bluetoothNameSubstring = name } + return ASPickerDisplayItem(name: label ?? labels[svc] ?? "Sensor", + productImage: image, descriptor: descriptor) } pickerResult = completion present(sensorItems, known: allIdList, fallback: { nil }, allowGen4Retry: false) diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist index 28ab6bcd6..b9be88cfa 100644 --- a/ios/Runner/Info.plist +++ b/ios/Runner/Info.plist @@ -65,6 +65,7 @@ 6E40FFF0-B5A3-F393-E0A9-E50E24DCCA9E 86F65000-F706-58A0-95B2-1FB9261E4DC7 FEE1 + FEE1 FED9 6A4E2800-667B-11E3-949A-0800200C9A66 1809 @@ -82,6 +83,7 @@ NSAccessorySetupBluetoothNames WHOOP + Helio Strap NSAccessorySetupKitSupports @@ -107,6 +109,8 @@ Ultrahuman Ring Air FEE1 Mi Band 2/3 + FEE1 + Amazfit Helio Strap FED9 Pebble 6A4E2800-667B-11E3-949A-0800200C9A66 @@ -137,6 +141,7 @@ 6E40FFF0-B5A3-F393-E0A9-E50E24DCCA9E 86F65000-F706-58A0-95B2-1FB9261E4DC7 FEE1 + FEE1 FED9 6A4E2800-667B-11E3-949A-0800200C9A66 1809 diff --git a/lib/ble/accessory_setup.dart b/lib/ble/accessory_setup.dart index 2f9833bd8..a0dfcf5b6 100644 --- a/lib/ble/accessory_setup.dart +++ b/lib/ble/accessory_setup.dart @@ -82,9 +82,18 @@ class AccessorySetup { /// service must be declared under `OSAskSensorServices`; the native side /// refuses anything else. Sent in [plistUuid] form (`180D`, not the 128-bit /// expansion), the form the plist declares. An already-approved sensor comes back with no sheet. - static Future showSensorPicker(List services) async { + /// + /// [name] (an advertised-name substring, declared under + /// `NSAccessorySetupBluetoothNames`) and [label] tell apart a sensor that + /// shares its service with another: the sheet lists only devices with that + /// name, and an earlier approval is reused only if it was made under + /// [label]. + static Future showSensorPicker(List services, + {String? name, String? label}) async { final id = await _ch.invokeMethod('showPicker', { 'services': [for (final s in services) plistUuid(s)], + 'name': ?name, + 'label': ?label, }); if (id == null || id.isEmpty) { throw Exception('Pairing cancelled.'); diff --git a/lib/ble/adapters/_registry.dart b/lib/ble/adapters/_registry.dart index a79da89c0..40a3dd95d 100644 --- a/lib/ble/adapters/_registry.dart +++ b/lib/ble/adapters/_registry.dart @@ -1028,6 +1028,57 @@ bool _looksLikeMiBand23(String lowercaseName) => const { 'xiaomi band 3', }.contains(lowercaseName); +/// Chunked transport write/notify (auth + small commands) and the plaintext +/// activity-fetch control/data pair (bulk history) — see +/// `huami2021_chunks.dart` and `huami2021_fetch.dart` in protocol. All four +/// are required: without the chunk pair there is no handshake, without the +/// fetch pair there is nothing to decode. +const String kHuami2021FetchControlChar = kHuamiActivityControlChar; +const String kHuami2021FetchDataChar = kHuamiActivityDataChar; + +/// Amazfit Helio Strap (Huami2021/ZeppOS protocol family). The auth key is a +/// precondition this adapter assumes already exists in secure storage — see +/// `helio_strap.dart`'s header; acquiring one is a separate, unbuilt flow. +/// +/// EXPERIMENTAL, and it stays that way: nobody on this project owns one, so +/// not a byte of this path has met hardware (ASSUMPTIONS R6). The service +/// UUID is the same `0000fee1-…` the whole Huami/Zepp family shares +/// (confirmed for Mi Band 2/3 above; assumed, not separately confirmed, for +/// this specific device) — a wrong guess here only means the scan filter +/// never matches, not a silent wrong decode. +const BandEntry kHelioStrap = BandEntry.notify( + id: 'helio_strap', + role: DeviceRole.band, + kind: DeviceKind.strap, + resetSteps: ResetSteps.unverified( + officialUrl: 'https://support.amazfit.com/en/amazfit_helio_strap/', + ), + category: DeviceCategory.wearable, + label: 'Amazfit Helio Strap', + service: kHuami234Service, + characteristics: [ + kHuami2021ChunkWriteChar, + kHuami2021ChunkNotifyChar, + kHuami2021FetchControlChar, + kHuami2021FetchDataChar, + ], + // The strap stamps its own records (session/round/absolute `sec` fields); + // none of this protocol's timestamps are arrival-anchored. + timeAnchor: TimeAnchor.measured, + nameMatcher: _looksLikeHelioStrap, + // Its own service as a HINT too: FEE1 is shared with the Mi Bands, so an + // advertisement named "Amazfit Helio Strap" carrying FEE1 must match this + // entry by name before the first FEE1 entry claims it by service. A + // nameless FEE1 advertisement still falls back to the service match. + scanHints: [kHuami234Service], + scanByName: true, +); + +/// The name the strap advertises, confirmed from the real Zepp app's own +/// BLE advertised-name match table. +bool _looksLikeHelioStrap(String lowercaseName) => + lowercaseName.contains('helio strap'); + /// Pebble 2 / Pebble 2 SE. Pure client, no envelope, no command channel — /// PPoGATT carries the inner protocol, whose health data logging the adapter /// decodes (HR, steps, the watch's sleep periods). `pebble_link.dart`'s @@ -1238,6 +1289,7 @@ const List kBandRegistry = [ kCoros, kUltrahuman, kMiBand234, + kHelioStrap, kPebble, kColmi, kGarmin, @@ -1281,6 +1333,19 @@ final List kFramedBands = /// a picker filtered on them would hand back another sensor's approval. On /// iOS 18+ they cannot be paired yet; `PairSensorScreen` says so. /// +/// [kHelioStrap] IS listed, with a known, owner-accepted risk: it shares +/// [kMiBand234]'s FEE1 service, and nothing here tells the two apart — +/// no company identifier, no manufacturer-data blob, because nobody has a +/// real strap to read one off. A developer forum report describes exactly +/// this shape (several products sharing one service UUID, no company +/// identifier set) as "random which device is found"; Apple's own WWDC24 +/// session says the picker shows the device's OWN advertised name as well +/// as ours, so a user may well see and tap the right one, but which +/// physical device the approval actually resolves to is unconfirmed when +/// more than one FEE1 device is nearby. Fix it properly once a real strap's +/// advertisement can be read for a `bluetoothCompanyIdentifier` or +/// manufacturer-data blob that differs from Mi Band's. +/// /// [kMiBand234], [kColmi], [kUltrahuman], [kMiScaleComposition] and /// [kMiScale2] are listed although they break the rule above: the band is /// not known to advertise FEE1, the Colmi ring is not known to advertise its @@ -1298,6 +1363,7 @@ const List kAskPickerSensors = [ kColmi, kUltrahuman, kMiBand234, + kHelioStrap, kPebble, kGarmin, kThermometer, @@ -1339,6 +1405,17 @@ const Map kAskSensorCompanyIds = { // Unverified on a band (R6): declared because a Mi Band 2/3 advertisement // is expected to carry this manufacturer data, the Oura case above. 'miband234': 0x0157, // Anhui Huami Information Technology + // The same company (Zepp Health, formerly Huami) makes every Amazfit + // device, so the same id; already declared above, listed so the plist + // test keeps it declared for this entry too. Unverified on a strap (R6). + 'helio_strap': 0x0157, +}; + +/// iOS picker names for sensors whose service another sensor shares (FEE1): +/// the advertised-name substring the sheet filters on. Each must also be +/// declared under `NSAccessorySetupBluetoothNames` in Info.plist. +const Map kAskSharedServiceNames = { + 'helio_strap': 'Helio Strap', }; /// The entry speaking [wire]. Used by the engine's test seam, which is handed @@ -1430,6 +1507,19 @@ const Map> kAdapterSignals = InputSignal.deviceSpo2: Duration(days: 1), InputSignal.deviceStress: Duration(days: 1), }, + // Mirrors `kHelioStrapSignals` in `helio_strap.dart` exactly — keep the + // two in sync by hand, same as every other entry here. + 'helio_strap': { + InputSignal.hrSparse: Duration(minutes: 1), + InputSignal.steps: Duration(minutes: 1), + InputSignal.skinTempC: Duration(minutes: 1), + InputSignal.deviceStress: Duration(minutes: 1), + InputSignal.deviceHrv: Duration(minutes: 2), + InputSignal.deviceResp: Duration(minutes: 30), + InputSignal.deviceSpo2: Duration(minutes: 5), + InputSignal.deviceStages: Duration.zero, + InputSignal.vendorScalars: Duration.zero, + }, 'thermometer': {}, 'miscale_bc': {}, 'miscale2': {}, @@ -1444,6 +1534,15 @@ const Map> kAdapterSignals = }, }; +/// POLICY EXCEPTION PE-1 (docs/internal/sparse_device_analytics_architecture.md +/// §1, owner decision 2026-11-22): the families whose OWN RMSSD readings +/// (`decoded_onehz.dev_rmssd_ms`, raw timestamped samples in ms) our readiness +/// may take as its HRV input, on a night no strap's beats gave our own. +/// Raw samples only: a device's stress score, readiness, PAI, ODI or any +/// aggregate it made stays in `observation`, display-only, forever. A family +/// not listed here contributes nothing even with samples on disk. +const Set kDeviceRmssdFamilies = {'helio_strap'}; + /// [adapterId]'s [DeviceCategory], or null for an id this build has no /// entry for. DeviceCategory? categoryOf(String? adapterId) { diff --git a/lib/ble/adapters/adapter.dart b/lib/ble/adapters/adapter.dart index a4fbf3a51..f943b4ed5 100644 --- a/lib/ble/adapters/adapter.dart +++ b/lib/ble/adapters/adapter.dart @@ -156,6 +156,17 @@ class NeutralSample { /// metric is claimed on its behalf. final double? skinTempC; + /// The device's OWN RMSSD reading for this second, in ms, or null; and its + /// own breathing-rate reading, breaths/min. Raw single-quantity samples in + /// a physical unit, never a composite and never an aggregate the device + /// made (its night mean is an observation). They land in + /// `decoded_onehz.dev_rmssd_ms` / `dev_resp_brpm`, and the ONLY reader is + /// `compute/inputs/device_night_samples.dart`, for a family listed in + /// `kAdmittedDeviceSamples` (policy exception PE-1, + /// docs/internal/sparse_device_analytics_architecture.md §1). + final double? deviceRmssdMs; + final double? deviceRespBrpm; + /// Anything the band emitted that we do not have a column for, under the /// band's OWN name for it (owner rulings R1-R3: capture everything, decide /// what to do with it later). Never an input to a derivation, never in a @@ -181,6 +192,8 @@ class NeutralSample { this.hr, this.rrMs = const [], this.skinTempC, + this.deviceRmssdMs, + this.deviceRespBrpm, this.vendor = const {}, this.beatTsMs, this.gapMs = 0, diff --git a/lib/ble/adapters/helio_strap.dart b/lib/ble/adapters/helio_strap.dart new file mode 100644 index 000000000..d9486d7c0 --- /dev/null +++ b/lib/ble/adapters/helio_strap.dart @@ -0,0 +1,897 @@ +// Amazfit Helio Strap (Huami2021/ZeppOS protocol family) as a [BandAdapter]: +// authenticate over the chunked transport, then walk the plaintext +// activity-fetch channel for every record type the strap stores. +// +// THE WIRE lives in `protocol` (`huami2021_chunks.dart`, `huami2021_auth.dart`, +// `huami2021_fetch.dart`, `huami2021_records.dart`): a B-163 ECDH handshake on +// chars 0016/0017, then a plaintext "give me everything since T" exchange on +// chars 0004/0005, one record type at a time. +// +// THE AUTH KEY IS A PRECONDITION THIS ADAPTER DOES NOT BUILD. The strap's +// first pairing has to go through the real Zepp app and its cloud — nothing +// here attempts that. [authKeyReader] reads a key that already exists in +// secure storage; a session with no key yields [kHelioNoKeyNote] and ends. +// How the key GETS into storage (a typed/scanned key, same shape as this +// project's Oura and Mi Band flows) is a separate, unbuilt piece. +// +// THE STRAP COMPUTES EVERYTHING ITSELF. Unlike WHOOP, there is no raw +// beat-level or accelerometer stream anywhere in this protocol — every +// record is already a finished, device-computed result (its own stress +// score, its own HRV figure, its own sleep stages). Only `hr`, `steps` and +// `temperature_c` are measured quantities comparable to our own; everything +// else is shown attributed to the strap and never feeds a derivation or a +// baseline (ADDING_A_DEVICE.md's honesty contract). +// +// WHAT BECOMES WHAT: +// * `hr` -> [NeutralSample.hr], signal `hrSparse` (the strap reports once a +// minute, not continuously). +// * `temperature_c` -> [NeutralSample.skinTempC] (already absolute Celsius, +// not a raw ADC count — the protocol layer does that conversion). +// * `hrv` (0x49) and `respiratory_rate` (0x38) readings -> also +// [NeutralSample.deviceRmssdMs] / [NeutralSample.deviceRespBrpm] at their +// own seconds: raw samples our readiness may take under policy exception +// PE-1 (`kAdmittedDeviceSamples`), never the strap's own aggregate. +// * `steps` -> a daily `steps` observation (comparable quantity, like +// Colmi's). +// * `stress`, `hrv_sdnn`, `pai`, `odi summary` -> daily VENDOR +// observations, attributed and never fed back into our own analytics. +// * `hrv`, `respiratory_rate`, `spo2`/`spo2_sleep` -> the strap's mean over +// each night it staged, on the night's wake date ([nightMeans]); the +// device slots they fill name the night's value, so a calendar-day mean +// there would pass waking hours off as the night. +// * Sleep sessions -> [VendorHypnogram] (the strap's own hypnogram, already +// mapped to our stage words) plus per-night stage-minute vendor +// observations and a `nap_min` row per nap — the same shape Colmi uses. +// * Workout summaries -> vendor observations keyed to the workout's own +// start time (sport type, duration, calories, HR range). NOTE: this does +// NOT yet write into the `sessions` table the way a full workout-tracking +// adapter would — that is a known, deliberate gap, not something this file +// pretends to have solved. +// +// SCOPE OF THE FETCH ITSELF: one round per type, covering roughly the last +// two days, every session. The real protocol supports persistent per-type +// cursors, stale-feed recovery and DST-robust paging (protocol's +// `huami2021_fetch.dart` header) — none of that multi-session sophistication +// is built here yet. Building it against a protocol nobody has run on real +// hardware has no way to be validated, so it is deliberately deferred rather +// than built speculatively. +// +// EXPERIMENTAL (ASSUMPTIONS R6): nobody on this project has run this against +// a physical strap. Every reply is archived verbatim so a corrected decoder +// can be re-run over what was already banked. + +import 'dart:async'; +import 'dart:typed_data'; + +import 'package:flutter/foundation.dart' show visibleForTesting; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import 'package:openstrap_protocol/openstrap_protocol.dart'; +import 'package:pointycastle/export.dart' show AESEngine, ECBBlockCipher, KeyParameter; + +import '../../compute/vendor_sleep.dart' show VendorEpoch; +import '../../data/observation.dart'; +import '_registry.dart'; +import 'adapter.dart'; +import 'signals.dart'; + +/// Shown next to every value the strap computed itself. +const String kHelioStrapAttribution = 'Amazfit'; + +/// The [BandNote] a session carries when no auth key is in secure storage — +/// the session ends immediately, nothing else is attempted. +const String kHelioNoKeyNote = 'helio_no_key'; + +/// The [BandNote] a session carries when the handshake was rejected or +/// timed out, with a short machine-readable reason as its value. +const String kHelioAuthFailedNote = 'helio_auth_failed'; + +/// The [BandNote] a session carries when a fetch round FAILED (a refused +/// write, no reply, or a round that never added up after its retries), as +/// opposed to the strap confirming it had nothing. What the other rounds +/// fetched is kept; the sync just must not read as complete. +const String kHelioIncompleteNote = 'helio_fetch_incomplete'; + +/// How far back one session's single fetch round reaches, for every type, +/// counted in whole local days: the fetch starts at the local midnight this +/// many days before today. +const Duration kHelioFetchWindow = Duration(days: 2); + +/// The secure-storage key the adapter reads from and the pairing screen +/// writes to — shared so the two can never drift onto different items. +const String kHelioStrapSecureStorageKey = 'helio_strap_auth_key'; + +/// FIRST-UNLOCK, not the plugin's default WHEN-UNLOCKED — same choice as +/// `oura_link.dart`'s `_kApple`, for the identical reason: this app is +/// relaunched in the background while the phone is LOCKED (BGProcessingTask, +/// the BLE restore central waking on a link drop), exactly when a +/// `whenUnlocked` item cannot be read. A background sync that read nothing +/// would conclude the strap has no key at all. Exported so the pairing +/// function (`helio_strap_link.dart`) writes under the identical +/// accessibility level this reads under. +const IOSOptions kHelioStrapIosKeyOptions = IOSOptions( + accessibility: KeychainAccessibility.first_unlock, +); +const MacOsOptions kHelioStrapMacosKeyOptions = MacOsOptions( + accessibility: KeychainAccessibility.first_unlock, +); + +const FlutterSecureStorage _secure = FlutterSecureStorage(); + +/// Reads this device's 16-byte auth key, or null if none is stored yet, the +/// keychain is unavailable, or the stored value is malformed. Never throws — +/// a session with no readable key is `kHelioNoKeyNote`, the same as a +/// session with no key at all, not an uncaught crash. +Future _defaultAuthKeyReader() async { + String? hex; + try { + hex = await _secure.read( + key: kHelioStrapSecureStorageKey, + iOptions: kHelioStrapIosKeyOptions, + mOptions: kHelioStrapMacosKeyOptions, + ); + } catch (_) { + return null; + } + // All 32 characters checked BEFORE parsing: a stored value of the right + // length with a non-hex pair would throw out of `int.parse` instead of + // taking the no-key path. + if (hex == null || !RegExp(r'^[0-9a-fA-F]{32}$').hasMatch(hex)) return null; + return Uint8List.fromList( + [for (var i = 0; i < 32; i += 2) int.parse(hex.substring(i, i + 2), radix: 16)]); +} + +Uint8List _aesEcb(Uint8List key, Uint8List data, bool encrypt) { + final c = ECBBlockCipher(AESEngine())..init(encrypt, KeyParameter(key)); + final out = Uint8List(data.length); + for (var i = 0; i < data.length; i += 16) { + c.processBlock(data, i, out, i); + } + return out; +} + +Uint8List _aesEncrypt(Uint8List k, Uint8List d) => _aesEcb(k, d, true); +Uint8List _aesDecrypt(Uint8List k, Uint8List d) => _aesEcb(k, d, false); + +/// The outcome of [runHelioHandshake]: either the strap authenticated, or it +/// didn't — with a short machine-readable reason either a session's +/// [BandNote] or a pairing screen's error sentence can be built from. +sealed class HelioHandshakeResult { + const HelioHandshakeResult(this.rawFrames); + + /// Every raw chunk the strap sent during the handshake, win or lose — + /// banked the same "capture everything, decide what to do with it later" + /// way every fetch-channel frame already is, so a session that fails + /// partway through authentication still leaves something to re-decode. + final List rawFrames; +} + +class HelioHandshakeOk extends HelioHandshakeResult { + const HelioHandshakeOk(this.event, List rawFrames) : super(rawFrames); + final Huami2021Authenticated event; +} + +class HelioHandshakeFailed extends HelioHandshakeResult { + const HelioHandshakeFailed(this.reason, List rawFrames) : super(rawFrames); + final String reason; +} + +/// Runs the Huami2021 auth handshake over [link]'s chunked transport +/// (chars 0016/0017) with [authKey]. Shared by [HelioStrapAdapter.run] (a +/// full session) and the pairing screen (which only needs to prove the key +/// works, never touches the fetch channel) — kept in one place so the two +/// callers cannot silently drift apart on how the handshake is actually +/// driven. +Future runHelioHandshake( + BandLink link, + Uint8List authKey, { + required Duration timeout, +}) async { + final chunkInbox = _Inbox(); + final rawFrames = []; + final sub = link.notify(kHuami2021ChunkNotifyChar).listen( + (r) => chunkInbox.add(Uint8List.fromList(r.$2)), + onDone: chunkInbox.close, + onError: (Object _) => chunkInbox.close()); + try { + final encoder = Huami2021Encoder(encrypt: _aesEncrypt); + final decoder = Huami2021Decoder(decrypt: _aesDecrypt); + final auth = Huami2021Auth(authKey, aesEcb: _aesEncrypt); + + Future sendAuthPayload(List body) async { + for (final chunk in encoder.encode(kHuami2021AuthEndpoint, body)) { + if (!await link.write(kHuami2021ChunkWriteChar, chunk)) return false; + } + return true; + } + + if (!await sendAuthPayload(auth.start())) { + return HelioHandshakeFailed('link_write_failed', rawFrames); + } + + // ONE deadline for the whole handshake: a strap chattering other + // notifications more often than [timeout] would otherwise restart the + // wait forever and hold the shared BLE slot. + final deadline = DateTime.now().add(timeout); + while (true) { + final left = deadline.difference(DateTime.now()); + if (left <= Duration.zero) { + return HelioHandshakeFailed('timeout', rawFrames); + } + final chunk = await chunkInbox.next(left); + if (chunk == null) return HelioHandshakeFailed('timeout', rawFrames); + rawFrames.add(chunk); + final frame = decoder.feed(chunk, sessionKey: null); + if (frame == null) continue; + if (frame.needsAck) { + // Per the chunked-transport spec: any reassembled frame flagged + // needs-ack gets this written back on the same characteristic, + // regardless of which endpoint it was for — the spec's own rule is + // "a failed ack write is logged, not fatal", so a failure here + // doesn't end the handshake; it's logged and the loop continues. + final acked = await link.write( + kHuami2021ChunkWriteChar, huami2021Ack(frame.handle, frame.count)); + if (!acked) link.log('helio_strap: chunk ack write failed.'); + } + if (frame.endpoint != kHuami2021AuthEndpoint) continue; + final event = auth.onPayload(frame.payload); + if (event is Huami2021AuthSendProof) { + if (!await sendAuthPayload(event.payload)) { + return HelioHandshakeFailed('link_write_failed', rawFrames); + } + continue; + } + if (event is Huami2021Authenticated) { + return HelioHandshakeOk(event, rawFrames); + } + if (event is Huami2021AuthFailed) { + final failure = event.failure; + return HelioHandshakeFailed( + switch (failure) { + WrongAuthKey() => 'wrong_key', + AuthRejected(:final step, :final status) => + 'rejected_step${step}_status$status', + AuthMalformed(:final reason) => 'malformed_$reason', + }, + rawFrames); + } + // Huami2021AuthIgnored: keep waiting. + } + } finally { + await sub.cancel(); + } +} + +class HelioStrapAdapter extends BandAdapter { + /// Wall-clock now, in Unix seconds. Injected so a replay is deterministic. + final int Function() nowSeconds; + + /// Reads the auth key from secure storage. Injected for testability. + final Future Function() authKeyReader; + + /// How long to wait for the handshake's first reply before giving up. + final Duration authTimeout; + + /// How long to wait for a fetch round's first reply, and between later + /// packets of the same round. + final Duration firstReplyTimeout; + final Duration quietTimeout; + + HelioStrapAdapter({ + int Function()? nowSeconds, + Future Function()? authKeyReader, + this.authTimeout = const Duration(seconds: 8), + this.firstReplyTimeout = const Duration(seconds: 10), + this.quietTimeout = const Duration(milliseconds: 800), + }) : nowSeconds = nowSeconds ?? + (() => DateTime.now().millisecondsSinceEpoch ~/ 1000), + authKeyReader = authKeyReader ?? _defaultAuthKeyReader; + + @override + BandEntry get entry => kHelioStrap; + + @override + Map get signals => kHelioStrapSignals; + + @override + Stream run(BandLink link) async* { + final key = await authKeyReader(); + if (key == null) { + yield const BandNote(kHelioNoKeyNote); + return; + } + + final dataInbox = _Inbox(); + final subData = link.notify(kHuami2021FetchDataChar).listen( + (r) => dataInbox.add(Uint8List.fromList(r.$2)), + onDone: dataInbox.close, + onError: (Object _) => dataInbox.close()); + final controlInbox = _Inbox(); + final subControl = link.notify(kHuami2021FetchControlChar).listen( + (r) => controlInbox.add(Uint8List.fromList(r.$2)), + onDone: controlInbox.close, + onError: (Object _) => controlInbox.close()); + + try { + final handshake = await runHelioHandshake(link, key, timeout: authTimeout); + if (handshake.rawFrames.isNotEmpty) { + yield SampleBatch(const [], raw: handshake.rawFrames); + } + if (handshake is HelioHandshakeFailed) { + yield BandNote(kHelioAuthFailedNote, handshake.reason); + return; + } + + // ── authenticated: the fetch channel itself is plaintext ── + final now = DateTime.fromMillisecondsSinceEpoch(nowSeconds() * 1000); + // From a local midnight, never mid-day: each day's step total and + // daily means replace the stored ones (one row per day), so a day the + // window cut into would overwrite the whole day an earlier sync read. + final since = DateTime( + now.year, now.month, now.day - kHelioFetchWindow.inDays); + // The offset AT `since`, not now's: across a DST change the two + // differ, and `since`'s wall time sent with now's offset names an + // instant an hour off the midnight it means. + final utcOffsetMinutes = since.timeZoneOffset.inMinutes; + // Replies that belong to no published round (a refused or retried + // attempt, a stale frame): archived anyway, never decoded. + final strayRaw = []; + var incomplete = false; + + Future<_FetchRound?> fetch(int type) => _fetchOneRound( + link, controlInbox, dataInbox, type, since, utcOffsetMinutes, + firstReplyTimeout: firstReplyTimeout, + quietTimeout: quietTimeout, + strayRaw: strayRaw, + onFailed: () => incomplete = true); + + final raw = []; + final samples = []; + final steps = {}; + final stress = >{}; + final hrvSdnn = >{}; + // The strap's own night readings, kept with their times: they are + // averaged over the night it staged ([nightMeans]), never over a + // calendar day, which would fold waking hours into a "night" figure. + final night = >{ + 'hrv_avg': [], + 'respiration_avg': [], + 'spo2_avg': [], + }; + DateTime dayOf(int ms) { + final t = DateTime.fromMillisecondsSinceEpoch(ms); + return DateTime(t.year, t.month, t.day); + } + + final activity = await fetch(kHuami2021TypeActivity); + if (activity != null) { + raw.addAll(activity.raw); + for (final s in parseHuami2021Activity(activity.bytes, activity.roundStartMs, + expectedRecordCount: activity.expectedCount)) { + if (s.metric == 'hr') { + samples.add(NeutralSample( + anchor: TimeAnchor.measured, tsEpoch: s.ms ~/ 1000, hr: s.value.round())); + } else if (s.metric == 'steps') { + final d = dayOf(s.ms); + steps[d] = (steps[d] ?? 0) + s.value.round(); + } + } + } + + final temperature = await fetch(kHuami2021TypeTemperature); + if (temperature != null) { + raw.addAll(temperature.raw); + for (final s in parseHuami2021Temperature(temperature.bytes, temperature.roundStartMs)) { + samples.add(NeutralSample( + anchor: TimeAnchor.measured, tsEpoch: s.ms ~/ 1000, skinTempC: s.value)); + } + } + + final stressFetch = await fetch(kHuami2021TypeStress); + if (stressFetch != null) { + raw.addAll(stressFetch.raw); + for (final s in parseHuami2021Stress(stressFetch.bytes, stressFetch.roundStartMs)) { + (stress[dayOf(s.ms)] ??= []).add(s.value); + } + } + + final hrvFetch = await fetch(kHuami2021TypeHrv); + if (hrvFetch != null) { + raw.addAll(hrvFetch.raw); + for (final s in parseHuami2021Hrv(hrvFetch.bytes)) { + night['hrv_avg']!.add((s.ms, s.value)); + // The raw reading too, at its own second (PE-1): our readiness + // takes the night's samples, not the strap's mean of them. + samples.add(NeutralSample( + anchor: TimeAnchor.measured, + tsEpoch: s.ms ~/ 1000, + deviceRmssdMs: s.value.toDouble())); + } + } + + final sdnnFetch = await fetch(kHuami2021TypeHrvSdnn); + if (sdnnFetch != null) { + raw.addAll(sdnnFetch.raw); + for (final s in parseHuami2021HrvSdnn(sdnnFetch.bytes)) { + (hrvSdnn[dayOf(s.ms)] ??= []).add(s.value); + } + } + + final respFetch = await fetch(kHuami2021TypeRespiratoryRate); + if (respFetch != null) { + raw.addAll(respFetch.raw); + for (final s in parseHuami2021RespiratoryRate(respFetch.bytes)) { + night['respiration_avg']!.add((s.ms, s.value)); + samples.add(NeutralSample( + anchor: TimeAnchor.measured, + tsEpoch: s.ms ~/ 1000, + deviceRespBrpm: s.value.toDouble())); + } + } + + final spo2Fetch = await fetch(kHuami2021TypeSpo2Spot); + if (spo2Fetch != null) { + raw.addAll(spo2Fetch.raw); + for (final s in parseHuami2021Spo2Spot(spo2Fetch.bytes)) { + night['spo2_avg']!.add((s.ms, s.value)); + } + } + final spo2SleepFetch = await fetch(kHuami2021TypeSpo2Sleep); + if (spo2SleepFetch != null) { + raw.addAll(spo2SleepFetch.raw); + for (final s in parseHuami2021Spo2Sleep(spo2SleepFetch.bytes)) { + night['spo2_avg']!.add((s.ms, s.value)); + } + } + + if (samples.isNotEmpty || raw.isNotEmpty) { + yield SampleBatch(samples, raw: raw); + } + + // Each section below is fetched, decoded and YIELDED on its own, + // deliberately not batched into one list collected across the whole + // session: a `yield` yields what the host already has, so a problem + // decoding a LATER section (a firmware shape this decoder doesn't + // expect, say) can never retroactively lose an EARLIER section's + // already-emitted data. A workout-record crash used to wipe out + // every scalar fetched before it, and stop sleep from being fetched + // at all — this structure is what prevents that class of bug, not + // just the one instance of it that's already been hardened. + final earlyRows = [ + for (final MapEntry(:key, :value) in steps.entries) + _obs(key, value, unit: 'steps', key: 'steps'), + for (final MapEntry(:key, :value) in stress.entries) + _obs(key, _mean(value), vendorKey: 'stress_avg'), + for (final MapEntry(:key, :value) in hrvSdnn.entries) + _obs(key, _mean(value), unit: 'ms', vendorKey: 'hrv_sdnn_avg'), + ]; + if (earlyRows.isNotEmpty) yield VendorScalars(earlyRows); + + // ── PAI ── + final paiFetch = await fetch(kHuami2021TypePai); + if (paiFetch != null) { + final paiRows = []; + for (final p in parseHuami2021Pai(paiFetch.bytes)) { + final d = dayOf(p.ms); + paiRows.add(_obs(d, p.daily, vendorKey: 'pai_daily')); + paiRows.add(_obs(d, p.total, vendorKey: 'pai_total')); + } + if (paiRows.isNotEmpty) yield VendorScalars(paiRows); + if (paiFetch.raw.isNotEmpty) yield SampleBatch(const [], raw: paiFetch.raw); + } + + // ── ODI (sleep-apnea) summary ── + final odiFetch = await fetch(kHuami2021TypeOdiSummary); + if (odiFetch != null) { + final odiRows = []; + for (final o in parseHuami2021OdiSummary(odiFetch.bytes)) { + final d = dayOf(o.belongTimeMs); + odiRows.add(_obs(d, o.validTimeSec, unit: 's', vendorKey: 'odi_valid_time')); + if (o.odiRefined != null) { + odiRows.add(_obs(d, o.odiRefined!, vendorKey: 'odi_refined')); + } + if (o.score != null) { + odiRows.add(_obs(d, o.score!, vendorKey: 'odi_score')); + } + } + if (odiRows.isNotEmpty) yield VendorScalars(odiRows); + if (odiFetch.raw.isNotEmpty) yield SampleBatch(const [], raw: odiFetch.raw); + } + + // ── workouts: vendor-attributed summary fields, not yet a `sessions` + // row (see the file header's known-gap note) ── + final workoutFetch = await fetch(kHuami2021TypeWorkout); + if (workoutFetch != null) { + final workoutRows = []; + for (final w in parseHuami2021Workouts(workoutFetch.bytes)) { + final start = DateTime.fromMillisecondsSinceEpoch(w.startMs); + workoutRows.add(Observation( + at: start, + sourceKind: ObservationSource.vendor, + vendorKey: 'workout_sport_type', + value: w.sportType, + attribution: kHelioStrapAttribution, + )); + workoutRows.add(Observation( + at: start, + sourceKind: ObservationSource.vendor, + vendorKey: 'workout_duration_sec', + value: w.durationSec, + unit: 's', + attribution: kHelioStrapAttribution, + )); + workoutRows.add(Observation( + at: start, + sourceKind: ObservationSource.vendor, + vendorKey: 'workout_calories', + value: w.calories, + unit: 'kcal', + attribution: kHelioStrapAttribution, + )); + workoutRows.add(Observation( + at: start, + sourceKind: ObservationSource.vendor, + vendorKey: 'workout_avg_hr', + value: w.avgHr, + unit: 'bpm', + attribution: kHelioStrapAttribution, + )); + workoutRows.add(Observation( + at: start, + sourceKind: ObservationSource.vendor, + vendorKey: 'workout_max_hr', + value: w.maxHr, + unit: 'bpm', + attribution: kHelioStrapAttribution, + )); + workoutRows.add(Observation( + at: start, + sourceKind: ObservationSource.vendor, + vendorKey: 'workout_min_hr', + value: w.minHr, + unit: 'bpm', + attribution: kHelioStrapAttribution, + )); + } + if (workoutRows.isNotEmpty) yield VendorScalars(workoutRows); + if (workoutFetch.raw.isNotEmpty) { + yield SampleBatch(const [], raw: workoutFetch.raw); + } + } + + // ── sleep: the strap's own hypnogram ── + final sleepFetch = await fetch(kHuami2021TypeSleep); + if (sleepFetch != null) { + final epochs = []; + final stageRows = []; + // Only sessions the window holds whole: one begun before `since` + // is read from `since` on, and its stage minutes and night means + // would replace the whole night an earlier sync stored. + final sessions = wholeSessions(parseHuami2021Sleep(sleepFetch.bytes), + since.millisecondsSinceEpoch); + for (final session in sessions) { + _emitSleepSession(session, epochs, stageRows); + } + stageRows.addAll(nightMeans(sessions, night)); + if (epochs.isNotEmpty) { + yield VendorHypnogram('helio_strap', epochs, wholeNights: true); + } + if (stageRows.isNotEmpty) yield VendorScalars(stageRows); + if (sleepFetch.raw.isNotEmpty) { + yield SampleBatch(const [], raw: sleepFetch.raw); + } + } + if (strayRaw.isNotEmpty) yield SampleBatch(const [], raw: strayRaw); + if (incomplete) yield const BandNote(kHelioIncompleteNote); + } finally { + await subData.cancel(); + await subControl.cancel(); + } + } + + static void _emitSleepSession( + Huami2021SleepSession session, + List epochs, + List rows, + ) { + if (session.isNap) { + final asleep = session.stages + .where((s) => s.type != kHuami2021StageAwake) + .fold(0, (sum, s) => sum + ((s.endMs - s.startMs) ~/ 60000)); + if (asleep > 0) { + rows.add(Observation( + at: DateTime.fromMillisecondsSinceEpoch(session.sessionStartMs), + sourceKind: ObservationSource.vendor, + vendorKey: 'nap_min', + value: asleep, + unit: 'min', + attribution: kHelioStrapAttribution, + )); + } + return; + } + // The night's wake date: a night begun at 23:00 is the next day's. + final dayStamp = + _wakeDate(_nightSpan(session)?.$2 ?? session.sessionStartMs); + for (final stage in session.stages) { + final name = _stageName(stage.type); + if (name != null && stage.endMs > stage.startMs) { + epochs.add(VendorEpoch(stage.startMs ~/ 1000, stage.endMs ~/ 1000, name)); + } + } + for (final entry in { + 'rem': session.remMin, + 'light': session.lightMin, + 'deep': session.deepMin, + 'wake': session.wakeMin, + }.entries) { + rows.add(Observation( + at: dayStamp, + sourceKind: ObservationSource.vendor, + vendorKey: 'sleep_${entry.key}_min', + value: entry.value, + unit: 'min', + attribution: kHelioStrapAttribution, + )); + } + } + + /// [sessions] that start at or after [sinceMs] (first stage, else the + /// session start): the ones a fetch from [sinceMs] holds whole. + @visibleForTesting + static List wholeSessions( + List sessions, int sinceMs) => + [ + for (final s in sessions) + if ((_nightSpan(s)?.$1 ?? s.sessionStartMs) >= sinceMs) s, + ]; + + /// The strap's own mean of each reading in [samples] (vendor key -> + /// (epoch ms, value)) over each night it staged, stamped on the night's + /// wake date, the day our day model files that night under. A reading + /// outside every staged night is dropped, and a night with none gets no + /// row: absent, never a calendar-day mean standing in for the night's. + @visibleForTesting + static List nightMeans( + List sessions, + Map> samples, + ) { + final rows = []; + for (final session in sessions) { + if (session.isNap) continue; + final span = _nightSpan(session); + if (span == null) continue; + final (start, end) = span; + for (final MapEntry(:key, :value) in samples.entries) { + final inNight = [ + for (final (ms, v) in value) + if (ms >= start && ms < end) v, + ]; + if (inNight.isEmpty) continue; + rows.add(_obs(_wakeDate(end), _mean(inNight), + unit: _nightUnit[key], vendorKey: key)); + } + } + return rows; + } + + static const Map _nightUnit = { + 'hrv_avg': 'ms', + 'respiration_avg': 'breaths/min', + 'spo2_avg': '%', + }; + + /// First stage start to last stage end, epoch ms; null with no stages. + static (int, int)? _nightSpan(Huami2021SleepSession session) { + if (session.stages.isEmpty) return null; + var start = session.stages.first.startMs, end = session.stages.first.endMs; + for (final st in session.stages) { + if (st.startMs < start) start = st.startMs; + if (st.endMs > end) end = st.endMs; + } + return end > start ? (start, end) : null; + } + + static DateTime _wakeDate(int endMs) { + final t = DateTime.fromMillisecondsSinceEpoch(endMs); + return DateTime(t.year, t.month, t.day); + } + + static String? _stageName(int type) => switch (type) { + kHuami2021StageAwake => 'wake', + kHuami2021StageLight => 'light', + kHuami2021StageDeep => 'deep', + kHuami2021StageRem => 'rem', + _ => null, + }; + + static double _mean(List v) => + v.fold(0, (s, x) => s + x) / v.length; + + static Observation _obs(DateTime day, num value, + {String? unit, String? key, String? vendorKey}) => + Observation( + at: day, + sourceKind: ObservationSource.vendor, + key: key, + vendorKey: vendorKey, + value: value, + unit: unit, + attribution: kHelioStrapAttribution, + ); +} + +/// One completed fetch round's accumulated bytes, raw frames (for +/// `raw_archive`), and the round's own `roundStart` (for the record types +/// that need it — activity, stress, temperature). +class _FetchRound { + const _FetchRound(this.bytes, this.raw, this.roundStart, this.expectedCount); + final Uint8List bytes; + final List raw; + final DateTime roundStart; + /// The start reply's own announced record/byte count — for type 0x01, + /// passed to [parseHuami2021Activity] so it never has to guess at the + /// 4-byte-vs-8-byte record size (see that function's own doc for why the + /// guess is unsafe). + final int expectedCount; + int get roundStartMs => roundStart.millisecondsSinceEpoch; +} + +/// One start -> send -> data -> end -> ack round for [type], with up to 2 +/// retries on a counter gap or a byte-count mismatch (per the spec's +/// documented retry policy). Returns null on "nothing to send", a refused +/// start, or exhausted retries. +Future<_FetchRound?> _fetchOneRound( + BandLink link, + _Inbox controlInbox, + _Inbox dataInbox, + int type, + DateTime since, + int utcOffsetMinutes, { + required Duration firstReplyTimeout, + required Duration quietTimeout, + required List strayRaw, + required void Function() onFailed, +}) async { + for (var attempt = 0; attempt <= 2; attempt++) { + // A frame that arrived late for an EARLIER round (a previous type, or + // a previous attempt at this same type) must never be read as part of + // THIS round — drain both channels before this round's first write. + controlInbox.drain(); + dataInbox.drain(); + if (!await link.write(kHuami2021FetchControlChar, + huami2021FetchStartRequest(type, since, utcOffsetMinutes))) { + onFailed(); + return null; + } + // The start reply, skipping stale control frames (a late end reply of + // the previous round can still land after the drain) until one parses + // or the reply window closes. + final deadline = DateTime.now().add(firstReplyTimeout); + Uint8List? startFrame; + Huami2021FetchStart? start; + while (start == null) { + final left = deadline.difference(DateTime.now()); + if (left <= Duration.zero) break; + startFrame = await controlInbox.next(left); + if (startFrame == null) break; + start = parseHuami2021FetchStart(startFrame); + if (start == null) strayRaw.add(startFrame); + } + if (start == null || startFrame == null) { + onFailed(); + return null; + } + if (!start.ok) { + strayRaw.add(startFrame); + onFailed(); + return null; + } + if (!start.hasData) { + // Confirmed empty: the strap has nothing for this type. Not a failure. + strayRaw.add(startFrame); + await link.write(kHuami2021FetchControlChar, kHuami2021FetchAckKeep); + return null; + } + + if (!await link.write(kHuami2021FetchControlChar, kHuami2021FetchSendData)) { + strayRaw.add(startFrame); + onFailed(); + return null; + } + + final buffer = Huami2021FetchBuffer(); + final rawFrames = [startFrame]; + var timeout = firstReplyTimeout; + while (true) { + final packet = await dataInbox.next(timeout); + if (packet == null) break; // quiet: assume the round-end reply follows + rawFrames.add(packet); + buffer.add(packet); + timeout = quietTimeout; + if (!buffer.ok) break; + } + + final endFrame = await controlInbox.next(firstReplyTimeout); + if (endFrame != null) rawFrames.add(endFrame); + final endStatus = endFrame == null ? null : parseHuami2021FetchRoundEnd(endFrame); + + final countOk = buffer.ok && + endStatus != null && + huami2021FetchCountMatches(type, start.expected, buffer.bytes.length); + if (!countOk) { + // ack(keep), discard, retry same cursor. The replies are archived, + // not decoded. + strayRaw.addAll(rawFrames); + await link.write(kHuami2021FetchControlChar, kHuami2021FetchAckKeep); + continue; + } + + await link.write(kHuami2021FetchControlChar, kHuami2021FetchAckKeep); + return _FetchRound(buffer.bytes, rawFrames, start.roundStart, start.expected); + } + onFailed(); + return null; +} + +/// The signals this strap supplies. Mirrored in `kAdapterSignals`. +const Map kHelioStrapSignals = { + InputSignal.hrSparse: Duration(minutes: 1), + InputSignal.steps: Duration(minutes: 1), + InputSignal.skinTempC: Duration(minutes: 1), + InputSignal.deviceStress: Duration(minutes: 1), + InputSignal.deviceHrv: Duration(minutes: 2), + InputSignal.deviceResp: Duration(minutes: 30), + InputSignal.deviceSpo2: Duration(minutes: 5), + InputSignal.deviceStages: Duration.zero, + InputSignal.vendorScalars: Duration.zero, +}; + +/// The single instance. Holds no per-strap state. +final HelioStrapAdapter kHelioStrapAdapter = HelioStrapAdapter(); + +/// Notifications buffered so a reply landing before anyone waits is kept. +/// Identical shape to Colmi's `_Inbox` — duplicated rather than shared, +/// since promoting it to a shared utility is a separate decision this file +/// should not make unilaterally. +class _Inbox { + final List _buf = []; + Completer? _waiter; + bool _closed = false; + + void add(Uint8List frame) { + final w = _waiter; + if (w != null && !w.isCompleted) { + _waiter = null; + w.complete(frame); + return; + } + _buf.add(frame); + } + + void close() { + _closed = true; + final w = _waiter; + _waiter = null; + if (w != null && !w.isCompleted) w.complete(null); + } + + /// Discards anything currently buffered. Called before every fetch round + /// starts (a fresh type, or a retry of the same one): without this, a + /// frame that arrived late for the PREVIOUS round — after this function + /// had already given up waiting for it — sits here and gets consumed by + /// the NEXT round's own first read instead, misreading a stale end-of- + /// round reply as the new round's start reply, or a trailing data packet + /// as something else entirely. + void drain() => _buf.clear(); + + Future next(Duration timeout) { + if (_buf.isNotEmpty) return Future.value(_buf.removeAt(0)); + if (_closed) return Future.value(null); + final w = Completer(); + _waiter = w; + return w.future.timeout(timeout, onTimeout: () { + if (identical(_waiter, w)) _waiter = null; + return null; + }); + } +} diff --git a/lib/ble/adapters/host.dart b/lib/ble/adapters/host.dart index 5212b7556..74012e8ba 100644 --- a/lib/ble/adapters/host.dart +++ b/lib/ble/adapters/host.dart @@ -59,6 +59,8 @@ class HrsReading { class _Second { int? hr; double? skinTempC; + double? deviceRmssdMs; + double? deviceRespBrpm; final List rr = []; /// Parallel to [rr] when the beats were timed ([beatEndTimesMs]). @@ -517,6 +519,8 @@ class BandHost { final slot = _pending.putIfAbsent(s.tsEpoch, _Second.new); if (s.hr != null) slot.hr = s.hr; if (s.skinTempC != null) slot.skinTempC = s.skinTempC; + if (s.deviceRmssdMs != null) slot.deviceRmssdMs = s.deviceRmssdMs; + if (s.deviceRespBrpm != null) slot.deviceRespBrpm = s.deviceRespBrpm; // An arrival-stamped strap's beats keep their own times, off the chain. // A second's beats are timed together, however many samples carry them // (a sensor sending one beat per record): timed one at a time, each @@ -606,6 +610,8 @@ class BandHost { if (fresh != null) { if (fresh.hr != null) slot.hr = fresh.hr; if (fresh.skinTempC != null) slot.skinTempC = fresh.skinTempC; + slot.deviceRmssdMs = fresh.deviceRmssdMs ?? slot.deviceRmssdMs; + slot.deviceRespBrpm = fresh.deviceRespBrpm ?? slot.deviceRespBrpm; if (slot.beatTs.length == slot.rr.length && fresh.beatTs.length == fresh.rr.length) { slot.beatTs.addAll(fresh.beatTs); @@ -674,6 +680,8 @@ class BandHost { hr: slot.hr, rrMs: slot.rr, skinTempC: slot.skinTempC, + deviceRmssdMs: slot.deviceRmssdMs, + deviceRespBrpm: slot.deviceRespBrpm, beatTsMs: slot.beatTs.length == slot.rr.length && slot.rr.isNotEmpty ? slot.beatTs : null, diff --git a/lib/ble/helio_strap_link.dart b/lib/ble/helio_strap_link.dart new file mode 100644 index 000000000..24e03226b --- /dev/null +++ b/lib/ble/helio_strap_link.dart @@ -0,0 +1,674 @@ +// The HOST for a paired Amazfit Helio Strap: hold the `device` row, connect, +// drive [HelioStrapAdapter] over the link, commit what it decodes and bank +// every reply verbatim, disconnect. +// +// THE SHAPE IS `ColmiLink`'s: no drain cursor (the adapter re-walks a rolling +// window every connect), no pairing key built here (the auth key is read +// from secure storage by the adapter itself — see `helio_strap.dart`'s file +// header). One-shot [HelioStrapLink.sync]: read the `device` row, connect by +// `remote_id`, discover, check [GattBandLink.missingCharacteristics], drive +// `run()`, commit, disconnect. +// +// EXPERIMENTAL (ASSUMPTIONS R6): nobody on this project has run this against +// a physical strap. + +import 'dart:async'; +import 'dart:math'; +import 'dart:typed_data'; + +import 'package:flutter/foundation.dart' show debugPrint, visibleForTesting; +import 'package:flutter_blue_plus/flutter_blue_plus.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; + +import '../compute/inputs/canonical.dart' show pairedRowOf; +import '../data/db.dart'; +import '../data/models.dart' show ArchiveRecord; +import 'adapters/_registry.dart'; +import 'adapters/adapter.dart' show ReplayBandLink; +import 'adapters/gatt_link.dart'; +import 'adapters/helio_strap.dart'; +import 'adapters/host.dart' show BandHost; +import '../sync/reset_gate.dart'; +import 'ble_state.dart' show withSecondaryLinkSlot; + +String _hex(List b) => + b.map((x) => x.toRadixString(16).padLeft(2, '0')).join(); + +const FlutterSecureStorage _pairSecure = FlutterSecureStorage(); + +/// Bounded wait for Bluetooth to actually be reported ON before a connect +/// is attempted. Same reasoning and same shape as `oura_link.dart`'s own +/// `_awaitAdapterOn` (duplicated, not shared, for the same reason as +/// `_Inbox` above): a connect issued while the adapter state is still +/// settling can throw a generic, confusing error on a phone whose +/// Bluetooth is genuinely on; this lets pairing say "Bluetooth is off" +/// instead. Returns false when the adapter never reported ON within the +/// bound. +Future _awaitAdapterOn() async { + final s = await FlutterBluePlus.adapterState + .firstWhere((s) => s == BluetoothAdapterState.on) + .timeout(const Duration(seconds: 10), + onTimeout: () => BluetoothAdapterState.unknown); + return s == BluetoothAdapterState.on; +} + +/// Pair [device] with a 16-byte auth key the user already has, from +/// wherever they obtained it — this function only VERIFIES and STORES one, +/// it never attempts to acquire one (that is a separate, unbuilt flow; see +/// `helio_strap.dart`'s file header). Null on success, or a sentence the +/// user can act on. +/// +/// READ-ONLY ON THE STRAP: only the auth handshake runs ([runHelioHandshake], +/// shared with [HelioStrapAdapter.run] so the two can never drift on how the +/// handshake is actually driven) — nothing is written to the strap's own +/// flash, so a wrong key costs a refusal and nothing else. +/// +/// THE KEY IS STORED ONLY AFTER THE STRAP HAS PROVEN IT ACCEPTS IT. A +/// failed attempt leaves whatever was in secure storage before completely +/// untouched — there is no install step here that could leave an unproven +/// secret behind the way Oura's fresh-key path has to guard against. +/// +/// THE DEVICE ID IS REUSED on a re-pair, same reasoning as every other +/// link's pairing function: `device_id` is the storage key for +/// `decoded_onehz`/`observation`, so minting a fresh one on every pairing +/// would fork one physical strap into N identities with the earlier one's +/// history orphaned under an id nothing reads. +Future pairHelioStrapWithTypedKey( + BluetoothDevice device, String raw) async { + final hex = raw.trim().replaceFirst(RegExp('^0x', caseSensitive: false), ''); + if (hex.length != 32 || !RegExp(r'^[0-9a-fA-F]{32}$').hasMatch(hex)) { + return 'That is not a strap key: it must be exactly 32 hex characters.'; + } + final key = Uint8List.fromList( + [for (var i = 0; i < 32; i += 2) int.parse(hex.substring(i, i + 2), radix: 16)]); + + // A pairing begun DURING a reset would capture the already-raised + // generation and pass every check once that reset ends. + if (ResetGate.active) return kHelioPairResetText; + // The reset generation and forget counter as this pairing BEGINS, read + // before waiting on the lock: a reset or forget queued ahead of it moves + // them, and [persistHelioPairing] then refuses. Read after the wait they + // would already include that reset or forget and miss it. + final resetGen = ResetGate.generation; + final forgets = HelioStrapLink.instance._forgets; + // ADMISSION, under [_pairingLock]: a second strap is turned away before + // any Bluetooth is spent on it. The handshake below runs OUTSIDE the + // lock; [persistHelioPairing] takes it again and re-checks everything + // before anything is written, so a reset or forget in between (or a + // second pairing that persisted first) is seen there. + final refused = await _pairingLock.run(() async { + final priorRow = await HelioStrapLink.pairedHelioStrapRow(); + return _anotherStrap(priorRow, device.remoteId.str); + }); + if (refused != null) return refused; + + return withSecondaryLinkSlot( + timeout: const Duration(seconds: 30), + onTimeout: () => 'Another sensor is using this phone’s Bluetooth right ' + 'now. Try pairing again in a moment.', + () async { + GattBandLink? link; + try { + // NOT a key verdict: Bluetooth being off says nothing about the key + // typed — it ends the attempt and is reported as itself, matching + // `oura_link.dart`'s own pairing function. + if (!await _awaitAdapterOn()) { + return 'Bluetooth is off. Turn it on and try again.'; + } + await device.connect(timeout: const Duration(seconds: 20)); + final services = await device.discoverServices(); + link = GattBandLink( + entry: kHelioStrap, + services: services, + onLog: (m) => debugPrint('[helio_strap pair] $m'), + ); + final missing = + link.missingCharacteristics(kHelioStrap.requiredCharacteristics); + if (missing.isNotEmpty) { + return 'This strap is missing something this app needs — it may ' + 'not be a Helio Strap, or its firmware answered differently ' + 'than expected.'; + } + + final result = await runHelioHandshake(link, key, + timeout: const Duration(seconds: 10)); + if (result is HelioHandshakeFailed) { + return switch (result.reason) { + 'wrong_key' => 'The strap rejected this key. Double-check it ' + 'and try again.', + 'timeout' => 'The strap didn’t answer. Make sure it’s close by ' + 'and try again.', + _ => 'Pairing failed (${result.reason}).', + }; + } + + return await persistHelioPairing( + remoteId: device.remoteId.str, + hex: hex, + resetGen: resetGen, + forgets: forgets, + ); + } catch (e) { + return 'Could not connect: $e'; + } finally { + // Drop the link and DISCONNECT before the slot is released — same + // ordering `HelioStrapLink._sync` and `ColmiLink._sync` both use, + // and for the same reason: held in an OUTER finally (after this + // closure returns) this would run after the slot had already been + // released, letting the next queued link connect while this one + // was still disconnecting. + await link?.close(); + try { + await device.disconnect(); + } catch (_) {/* already gone */} + } + }, + ); +} + +/// The text a pairing interrupted by "delete everything" ends with. +const String kHelioPairResetText = + 'Pairing was interrupted by a reset. Pair the strap again.'; + +/// The text a pairing ends with when its strap was forgotten meanwhile. +const String kHelioPairForgottenText = + 'The strap was forgotten while it was pairing. Pair it again.'; + +/// The reset ended the pairing but its own undo failed: say what may be +/// left, so the user can run "delete everything" again. +const String kHelioPairResetLeftoverText = + 'Pairing was interrupted by a reset, and the strap\'s key or device ' + 'entry may remain on this phone. Run "Delete everything" again, then ' + 'pair the strap again.'; + +/// The one lock Helio pairing, forget and "delete everything" share. Each +/// holds it only around its own short critical section — pairing's admission +/// read and its key-and-row persistence, forget's row-and-key deletion, the +/// reset's raising of [ResetGate] — never across a Bluetooth connection, a +/// handshake or the secondary-link slot, so it cannot hold up a radio. And +/// nothing that holds it waits on another lock (each section only reads or +/// writes the store and the keychain), so it cannot deadlock. +final _pairingLock = _AsyncMutex(); + +/// A FIFO async lock: [run]s take turns, in call order. +class _AsyncMutex { + Future _tail = Future.value(); + + Future run(Future Function() op) { + final previous = _tail; + final done = Completer(); + _tail = done.future; + return previous.then((_) => op()).whenComplete(done.complete); + } +} + +/// A strap other than [remoteId] already paired: refuse, never fold the new +/// strap into its history id. Null when there is none or it is the same one. +String? _anotherStrap(Map? priorRow, String remoteId) => + priorRow != null && priorRow['remote_id'] != remoteId + ? 'Another Helio Strap is already paired. Forget it on its device ' + 'page first, then pair this one.' + : null; + +/// Store a key the strap has just ACCEPTED, then its device row, all under +/// [_pairingLock]: a forget or reset either finished before this +/// started (and is seen below: [resetGen] / [forgets] moved) or starts after +/// it finished (and removes what it wrote), never in between. Under the +/// lock it re-reads the paired row: a different strap that another pairing +/// persisted meanwhile is refused; the same strap keeps its id; a new one +/// gets [deviceId] (tests) or a fresh random id. The keychain's prior value +/// is read here too, so a failed row write restores exactly what was there. +Future persistHelioPairing({ + String? deviceId, + required String remoteId, + required String hex, + required int resetGen, + int? forgets, +}) => + _pairingLock.run(() => _persistHeld( + deviceId: deviceId, + remoteId: remoteId, + hex: hex, + resetGen: resetGen, + forgets: forgets)); + +Future _persistHeld({ + required String? deviceId, + required String remoteId, + required String hex, + required int resetGen, + required int? forgets, +}) async { + // Interrupted: a reset ran ([ResetGate]), or the strap was forgotten from + // its device page ([HelioStrapLink.forgetStrap] bumps the counter first). + // Either must stay in effect over a pairing that finishes after it. + bool stopped() => + ResetGate.changedSince(resetGen) || + (forgets != null && HelioStrapLink.instance._forgets != forgets); + String stopText() => ResetGate.changedSince(resetGen) + ? kHelioPairResetText + : kHelioPairForgottenText; + + Future dropKey() async { + try { + await _pairSecure.delete( + key: kHelioStrapSecureStorageKey, + iOptions: kHelioStrapIosKeyOptions, + mOptions: kHelioStrapMacosKeyOptions, + ); + return true; + } catch (_) { + return false; // keychain unavailable: the caller says a key may remain + } + } + + if (stopped()) return stopText(); + final priorRow = await HelioStrapLink.pairedHelioStrapRow(); + final another = _anotherStrap(priorRow, remoteId); + if (another != null) return another; + final rnd = Random.secure(); + final id = (priorRow?['id'] as String?) ?? + deviceId ?? + 'helio-${_hex(List.generate(4, (_) => rnd.nextInt(256)))}'; + // What the keychain held before this write, so a failed row write can put + // it back rather than leave an unproven key where a working one was. + String? priorHex; + try { + priorHex = await _pairSecure.read( + key: kHelioStrapSecureStorageKey, + iOptions: kHelioStrapIosKeyOptions, + mOptions: kHelioStrapMacosKeyOptions, + ); + } catch (e) { + return 'The phone’s keychain is locked. Unlock the phone and try again.'; + } + try { + await _pairSecure.write( + key: kHelioStrapSecureStorageKey, + value: hex, + iOptions: kHelioStrapIosKeyOptions, + mOptions: kHelioStrapMacosKeyOptions, + ); + } catch (e) { + return 'The phone’s keychain is locked. Unlock the phone and try again.'; + } + if (stopped()) { + return await dropKey() ? stopText() : kHelioPairResetLeftoverText; + } + try { + await LocalDb.upsertDevice( + id: id, + adapterId: kHelioStrap.id, + remoteId: remoteId, + label: kHelioStrap.label, + ); + } catch (e) { + // The row never landed. Restore what the keychain held before this + // attempt, unless a reset wiped it meanwhile: then it stays wiped. + if (priorHex == null || stopped()) { + if (!await dropKey() && stopped()) { + return kHelioPairResetLeftoverText; + } + } else { + try { + await _pairSecure.write( + key: kHelioStrapSecureStorageKey, + value: priorHex, + iOptions: kHelioStrapIosKeyOptions, + mOptions: kHelioStrapMacosKeyOptions, + ); + } catch (_) {} + // A reset or forget that landed during that restore wiped the key it + // put back: take it out again. + if (stopped() && !await dropKey()) return kHelioPairResetLeftoverText; + } + return 'Could not save the pairing: $e'; + } + if (stopped()) { + // The wipe (or forget) ran while the row was written: take both back out, row + // first. If the row stays, keep its key with it (a row with no key is + // a strap that silently never syncs) and say both may remain. + try { + await LocalDb.deleteDevice(id); + } catch (_) { + return kHelioPairResetLeftoverText; + } + return await dropKey() ? stopText() : kHelioPairResetLeftoverText; + } + return null; +} + +/// The live link to a paired Helio Strap. One instance; a second concurrent +/// strap is not a thing anyone asked for (same call as `ColmiLink`). +class HelioStrapLink { + HelioStrapLink._(); + static final HelioStrapLink instance = HelioStrapLink._(); + + /// The `device` row for the paired strap, or null. + static Future?> pairedHelioStrapRow() => + pairedRowOf(kHelioStrap.id); + + /// Forget a paired strap: stop any live session, drop its `device` row. + /// No stored pairing-key row to drop here — the auth key lives in secure + /// storage, keyed by device id-independent constant, same as the adapter + /// reads it (`_kSecureStorageKey` in `helio_strap.dart`); dropping the + /// `device` row is the whole story for this link, same as `ColmiLink`. + static Future forgetStrap(String id) async { + if (id == LocalDb.kPrimaryDeviceId) { + debugPrint('[helio_strap] refusing to forget the primary band from here.'); + return false; + } + // Before the first await: a sync still reading the row has no + // `_deviceId` yet for the check below to match. + instance._forgets++; + if (instance._deviceId == id) await instance.stop(); + // Row and key go together under the pairing lock: a pairing persisting + // right now finishes first (and this then removes what it wrote), or + // starts after and sees the counter above moved. + await _pairingLock.run(() => _forgetHeld(id)); + return true; + } + + static Future _forgetHeld(String id) async { + await LocalDb.deleteDevice(id); + // The key outlives nothing once its device row is gone — a re-pair + // mints a fresh key anyway (first bind always goes through the real + // Zepp app), so leaving the old one in the keychain only means a + // factory-reset-and-forgotten strap's secret sits around unused + // forever. Same cleanup `OuraLink.forgetRing` does for its own key. + try { + await _pairSecure.delete( + key: kHelioStrapSecureStorageKey, + iOptions: kHelioStrapIosKeyOptions, + mOptions: kHelioStrapMacosKeyOptions, + ); + } catch (_) {/* keychain unavailable; the device row is gone regardless */} + } + + /// Runs [op] holding the lock Helio pairing and forget take around their + /// writes. "Delete everything" raises [ResetGate] inside it, so a pairing + /// mid-persist finishes first (and the wipe then removes what it wrote) + /// and any later one sees the generation moved. [op] must not await + /// anything that could itself wait on a pairing. + static Future exclusive(Future Function() op) => _pairingLock.run(op); + + /// "Delete everything": drop the strap's pairing key, whatever device it + /// was for. False when the keychain refused, so the reset can say a key + /// was left behind. + static Future dropStoredKey() async { + try { + await _pairSecure.delete( + key: kHelioStrapSecureStorageKey, + iOptions: kHelioStrapIosKeyOptions, + mOptions: kHelioStrapMacosKeyOptions, + ); + return true; + } catch (e) { + debugPrint('[helio_strap] could not drop the stored key: $e'); + return false; + } + } + + BluetoothDevice? _device; + GattBandLink? _link; + BandHost? _host; + String? _deviceId; + + /// Bumped by every forget. A sync that saw it move since it started + /// does not connect, whatever its `_deviceId` says. + int _forgets = 0; + bool _busy = false; + + /// How many syncs got past the slot wait to a connect attempt. Under a test + /// `connect()` has no plugin and fails, so the return value alone cannot + /// tell a cancelled sync from one that tried the radio. + @visibleForTesting + int get connectAttemptsForTest => _connectAttempts; + int _connectAttempts = 0; + + @visibleForTesting + String? get deviceIdForTest => _deviceId; + + @visibleForTesting + int get forgetsForTest => _forgets; + + /// The session's clock, read once (Unix seconds): what the adapter's + /// `kHelioFetchWindow` lookback is counted from, and the anchor stamped on + /// every raw reply's `rec_ts`. + int? _anchorSec; + + /// Connect to the paired strap, walk its rolling fetch window, disconnect. + /// + /// Returns false when nothing is paired, the connect failed, there was no + /// auth key, the handshake failed, or no required characteristic was + /// found. SERIALISED: a second call while one is in flight is a no-op + /// rather than a second radio session over the same peripheral. + Future sync() { + if (_busy) return Future.value(false); + _busy = true; + return _sync().whenComplete(() => _busy = false); + } + + Future _sync() async { + // Read before the first await: a "delete everything" that lands while + // this sync is parked on the link slot or still connecting must find it + // here. The host refuses every write once a reset has run since. + final resetGen = ResetGate.generation; + final forgets = _forgets; + lastSyncFailed = false; + final row = await pairedHelioStrapRow(); + if (row == null) return false; + final deviceId = row['id'] as String?; + final remoteId = row['remote_id'] as String?; + if (deviceId == null || remoteId == null || remoteId.isEmpty) return false; + if (deviceId == LocalDb.kPrimaryDeviceId) { + debugPrint('[helio_strap] refusing to sync: the strap row claims the ' + 'primary device id — re-pair it with a minted id.'); + return false; + } + _deviceId = deviceId; + try { + return await withSecondaryLinkSlot(() async { + // A forget that landed while this sync was parked on the slot has + // already stopped it (nulling `_deviceId`) and deleted the row. The + // ids captured above would otherwise still connect to the forgotten + // device and bank its history under a row that no longer exists. + if (_deviceId != deviceId || ResetGate.changedSince(resetGen)) { + return false; + } + // A forget during the row lookup above found no `_deviceId` to stop. + if (_forgets != forgets) return false; + _connectAttempts++; + BandHost? host; + try { + final device = BluetoothDevice.fromId(remoteId); + _device = device; + // Best-effort only here (unlike pairing, which treats the result + // as a reportable verdict) — same as `OuraLink._sync`'s own use + // of this wait: a connect issued while the adapter state is + // still settling can throw a confusing error on a phone whose + // Bluetooth is genuinely on. + await _awaitAdapterOn(); + // The same checks as on entering the slot: a forget during the + // wait above found no host to stop, so nothing else would keep + // this sync off the forgotten strap. + if (_deviceId != deviceId || + _forgets != forgets || + ResetGate.changedSince(resetGen)) { + return false; + } + await device.connect(timeout: const Duration(seconds: 20)); + final services = await device.discoverServices(); + // Again after discovery: a forget during it found no link or host + // to stop, so this is the last point the session can still back + // off before running against a deleted row. + if (_deviceId != deviceId || + _forgets != forgets || + ResetGate.changedSince(resetGen)) { + return false; + } + final link = GattBandLink( + entry: kHelioStrap, + services: services, + onLog: (m) => debugPrint('[helio_strap] $m'), + ); + _link = link; + final missing = link + .missingCharacteristics(kHelioStrap.requiredCharacteristics); + if (missing.isNotEmpty) { + debugPrint('[helio_strap] ${kHelioStrap.label}: missing required ' + 'characteristic(s) ' + '${missing.map((u) => u.substring(0, 8)).join(", ")}.'); + return false; + } + final anchor = DateTime.now().millisecondsSinceEpoch ~/ 1000; + _anchorSec = anchor; + final h = host = BandHost( + resetGeneration: resetGen, + adapter: HelioStrapAdapter(nowSeconds: () => anchor), + deviceId: deviceId, + onLog: (m) => debugPrint('[helio_strap] $m'), + onNote: _handleNote, + buildArchive: _buildArchiveRow, + ); + _host = h; + await h.run(link); + } finally { + // Drop the link and DISCONNECT before the slot is released — same + // ordering `ColmiLink._sync` uses and for the same reason: held in + // an outer `finally` this would run after the slot had already + // been released, letting the next queued link connect while this + // one was still disconnecting. + await stop(); + } + // A connect alone is not a sync: a strap with no key, a rejected + // handshake, or a session the host flagged failed, all end the + // session as quietly as one that answered nothing. + // Read only after [stop], which makes the session's final flush. + return !lastSyncFailed && !host.sessionFailed; + }); + } catch (e) { + debugPrint('[helio_strap] sync failed: $e'); + return false; + } + } + + /// Drop the link, flush what the session banked, disconnect. Safe to call + /// when nothing is connected. + Future stop() async { + _link?.close(); + _link = null; + try { + await _host?.stop(); + } finally { + // A host whose final flush throws still leaves the link torn down and + // the strap disconnected; the error then reaches the caller. + _host = null; + _deviceId = null; + final d = _device; + _device = null; + if (d != null) { + try { + await d.disconnect(); + } catch (_) {/* already gone */} + } + } + } + + /// The last session ended via [kHelioNoKeyNote] (no auth key stored yet) + /// or [kHelioAuthFailedNote] (handshake rejected/timed out). Cleared at the + /// start of every session. + bool lastSyncFailed = false; + + void _handleNote(String key, Object? value) { + if (key == kHelioNoKeyNote || + key == kHelioAuthFailedNote || + key == kHelioIncompleteNote) { + lastSyncFailed = true; + } + } + + /// Bank one reply verbatim (owner rulings R1-R3): a chunked-transport + /// handshake frame or a plaintext fetch-channel frame. `counter` stays + /// NULL — this protocol has no flash-record counter comparable to WHOOP's. + /// The time a round belongs to is derived from the round's own + /// `roundStart`, not carried per frame, so every raw frame from this + /// session is stamped with the session's [_anchorSec] (the clock its fetch + /// window counts back from). + ArchiveRecord? _buildArchiveRow(List bytes, int capturedAtMs) { + if (bytes.isEmpty) return null; + return ArchiveRecord( + counter: null, + hex: _hex(bytes), + packetType: bytes[0], + recTs: _anchorSec, + capturedAt: capturedAtMs, + // ONE REASON PER PACKET TYPE, so a re-decode finds its frames by name. + // Deliberately not in `LocalDb.redrivableArchiveReasons` — that list + // replays a row's `hex` through the WHOOP R24 chain, which would run + // the wrong decoder over a Helio frame. + reason: 'helio_strap_0x${bytes[0].toRadixString(16).padLeft(2, '0')}', + ); + } + + /// Replay a scripted strap through the REAL [HelioStrapAdapter] and the + /// real write path. The only way in: the entry point is a BLE notification + /// and `flutter_blue_plus` has no simulator path. Same shape as + /// `ColmiLink.ingestForTest`, except [reply] names the notify channel for + /// each frame it returns — unlike Colmi's single command/notify pair, this + /// protocol answers one write (the fetch "send data" trigger) with frames + /// pushed across two different channels (control end-status, then data). + @visibleForTesting + Future ingestForTest( + String deviceId, + List<(String char, List bytes)> Function( + int writeIndex, String writeChar, List value) + reply, { + int Function()? nowSeconds, + Future Function()? authKeyReader, + Duration firstReplyTimeout = const Duration(milliseconds: 100), + Duration quietTimeout = const Duration(milliseconds: 20), + }) async { + _deviceId = deviceId; + lastSyncFailed = false; + final link = ReplayBandLink(); + final now = nowSeconds ?? (() => DateTime.now().millisecondsSinceEpoch ~/ 1000); + _anchorSec = now(); + final host = BandHost( + adapter: HelioStrapAdapter( + nowSeconds: now, + authKeyReader: authKeyReader, + firstReplyTimeout: firstReplyTimeout, + quietTimeout: quietTimeout, + ), + deviceId: deviceId, + onLog: (m) => debugPrint('[helio_strap] $m'), + onNote: _handleNote, + buildArchive: _buildArchiveRow, + nowSeconds: now, + ); + _host = host; + var finished = false; + final done = host.run(link).whenComplete(() => finished = true); + var served = 0; + // A walk with no reply genuinely waits out its timeout in REAL wall-clock + // time, so this spin has to let that time pass rather than just yield + // microtasks. + for (var spin = 0; spin < 4000 && !finished; spin++) { + await Future.delayed(const Duration(milliseconds: 5)); + while (served < link.writes.length) { + final (char, value) = link.writes[served]; + for (final (notifyChar, bytes) in reply(served, char, value)) { + link.feed(notifyChar, bytes, atSec: now()); + } + served++; + } + } + await link.close(); + await done.timeout(const Duration(seconds: 5), onTimeout: () {}); + await host.stop(); + _host = null; + _deviceId = null; + return link; + } +} diff --git a/lib/ble/hrs_link.dart b/lib/ble/hrs_link.dart index c88b84871..28a006c3b 100644 --- a/lib/ble/hrs_link.dart +++ b/lib/ble/hrs_link.dart @@ -78,6 +78,7 @@ import 'ble_state.dart' acquireSecondaryLinkSlot, releaseSecondaryLinkSlot; import 'colmi_link.dart' show ColmiLink; +import 'helio_strap_link.dart' show HelioStrapLink; import 'session_link.dart' show SessionLink; import 'coros_link.dart' show CorosLink; import 'adapters/garmin.dart' show garminMlPair; @@ -984,6 +985,10 @@ class HrsLink { await ColmiLink.forgetRing(id); return; } + if (row?['adapter_id'] == kHelioStrap.id) { + await HelioStrapLink.forgetStrap(id); + return; + } final session = SessionLink.forId(row?['adapter_id'] as String?); if (session != null) { await session.forget(id); diff --git a/lib/compute/crossday_pipeline.dart b/lib/compute/crossday_pipeline.dart index 7025e84e9..98dee49e6 100644 --- a/lib/compute/crossday_pipeline.dart +++ b/lib/compute/crossday_pipeline.dart @@ -282,8 +282,20 @@ Map buildCrossDayBundle( // rmssd higher-better; rhr/resp lower-better; skin_temp_z lower-ABS better // (so we orient temp by its absolute deviation, lower=better). final gbInputs = []; + // PE-1: a night with no beat RMSSD but the device's own readings (the + // readiness headline's HRV input then) ranks that night value against the + // same DEVICE family's earlier nights only: two wearables can share a + // method family, and their RMSSD figures are not one quantity. + final family = n == 0 ? null : days[n - 1]['skin_temp_family']; + final rmssdDevOwn = [ + for (final d in days) + d['skin_temp_family'] == family ? _numOrNull(d['rmssd_dev']) : null, + ]; final gbRmssd = _glassInput('hrv', rmssdOwn, ana.wHrv, lowerIsBetter: false); - if (gbRmssd != null) gbInputs.add(gbRmssd); + final gbRmssdDev = gbRmssd == null + ? _glassInput('hrv', rmssdDevOwn, ana.wHrv, lowerIsBetter: false) + : null; + if (gbRmssd ?? gbRmssdDev case final hrv?) gbInputs.add(hrv); final gbRhr = _glassInput('rhr', rhrOwn, ana.wRhr, lowerIsBetter: true, quantum: 1); if (gbRhr != null) gbInputs.add(gbRhr); @@ -676,7 +688,8 @@ Map buildCrossDayBundle( // nights" without re-deriving it from the note. 'circadian_coverage': circadian.coverage, 'sleep_debt': sleepDebt.toJson((v) => v.toJson()), - 'readiness_glassbox': glassBox.toJson((v) => v.toJson()), + 'readiness_glassbox': _tagDeviceHrv( + glassBox.toJson((v) => v.toJson()), gbRmssdDev != null), 'brv': brv.toJson((v) => v.toJson()), // ── Coaching + fitness (forward-looking, today) ── 'sleep_coach': { @@ -1032,6 +1045,18 @@ Map _pctOfYou(List series, ana.Better better) { /// Build a GlassBoxInput for the LAST value vs the all-but-last history. Returns /// null when there is no value tonight (so the input is simply absent — the /// package reweights over the inputs that ARE present, never zero-filling). +/// Marks the breakdown's HRV row `source: device_rmssd` when it was the +/// device's own readings, so the row can say whose number it ranked. +Map _tagDeviceHrv(Map gb, bool device) { + final rows = (gb['value'] is Map) ? (gb['value'] as Map)['breakdown'] : null; + if (device && rows is List) { + for (final r in rows) { + if (r is Map && r['label'] == 'hrv') r['source'] = 'device_rmssd'; + } + } + return gb; +} + ana.GlassBoxInput? _glassInput( String label, List series, diff --git a/lib/compute/derivation_engine.dart b/lib/compute/derivation_engine.dart index f151c7f5e..872bf5b82 100644 --- a/lib/compute/derivation_engine.dart +++ b/lib/compute/derivation_engine.dart @@ -59,7 +59,9 @@ import '../telemetry/firebase_bridge.dart'; import '../telemetry/telemetry_service.dart'; import 'crossday_pipeline.dart'; import 'derive_pacing.dart'; +import '../ble/adapters/_registry.dart' show kDeviceRmssdFamilies; import 'inputs/canonical.dart'; +import 'inputs/device_night_samples.dart' show deviceNightRmssd; import 'inputs/garmin_inputs.dart' show isWearableFamily, @@ -1913,7 +1915,39 @@ import 'vendor_sleep.dart'; // counts covered TIME not rows, so sparse substrates are not called unclaimed; // ring naps no longer bridge ring-off holes; the quiet-level repass counts // wearable-only days as substrate; calories absence names resting_hr. -const int kAlgoVersion = 127; +// 127 → 128 (no analytics change): the Helio strap joins the sparse-HR +// wearables (kHrCadenceSec 60 s, method family hr_1min), so its days derive +// resting HR, nadir, strain, calories and an rhr-only readiness off its +// minute HR, served by the declaration-built column (sparseColumn). Its skin +// temperature rides on its HR rows (skin_temp_z). No band or other wearable +// output moves. +// 128 → 129 (no analytics change): policy exception PE-1 (owner decision +// 2026-11-22). On a night with no beat-derived HRV of ours, an admitted +// wearable's (kDeviceRmssdFamilies: helio_strap) own RMSSD readings, gated +// (>= 6 plausible in our night) and taken as ln(mean), are readiness's HRV +// input against that device family's own nights (`ln_rmssd_dev`; readiness_z +// is per device family there too). Served as ours, method +// composite_device_hrv. Band days and every other wearable unchanged. +// 129 → 130 (no analytics change): a wearable's own daily step count +// (owner decision 2026-11-22) joins the steps ladder as a whole-day answer +// beside the gen5 chip counter: the day's steps are the larger of it and the +// windowed band/phone sum, never their total. Wearable days only; a band day +// has no active-wearable count. +// 130 → 131 (no analytics change): the readiness breakdown (glass-box) ranks +// a PE-1 night's HRV too. A night with no beat RMSSD but the device's own +// readings (`ln_rmssd_dev`) feeds exp(ln_rmssd_dev) as the HRV row, against +// the same device family's earlier nights only, tagged source device_rmssd. +// Cross-day only; a band night has no `ln_rmssd_dev`, so nothing else moves. +// 131 → 132 (no analytics change): a day whose steps the active wearable's +// own count won names it: `inputs_used` ['wearable_pedometer'] and its own +// note, where it still named the phone pedometer it outcounted (the Home card +// read "Phone"). Wearable days only; every other day's envelope unchanged. +// 132 → 133 (no analytics change): a wearable that stores skin temperature as +// its own records (the Helio's temperature rounds start on their own second) +// had every reading dropped, because the sparse substrate reads only rows +// with HR. Each reading now joins the HR row of its minute. Wearables whose +// temperature already rode on the HR rows, and every band day, unchanged. +const int kAlgoVersion = 133; /// The sibling SHAs this version was derived against, asserted against /// pubspec.yaml in test/db_serve_version_and_reads_test.dart. /// @@ -2154,7 +2188,16 @@ const String kAnalyticsPin = 'a438df40b38a4586a52a68ab7e1c100fca111ccd'; // REPIN: protocol main @ fbadb5b (#84 realtime packet decoder, #85 image // update payload builders). NO kAlgoVersion bump: neither is read by any // derivation; WHOOP output unchanged (freeze goldens). -const String kProtocolPin = 'fbadb5bd055965d9400e266d6cf42748992ba950'; +// REPIN: protocol feat/zepp-family @ d74cbc8 (Huami2021 transport for the +// Helio Strap, additions only on top of fbadb5b). Its decoders feed the +// Helio adapter at ingest; WHOOP output unchanged (freeze goldens). +// REPIN: protocol feat/zepp-family @ f2398ab (#86 head: review fixes to the +// Huami2021 transport and decoders). Ingest only; WHOOP output unchanged. +// REPIN: protocol feat/zepp-family @ e4ccba2 (an activity round whose count +// doesn't fit 4- or 8-byte records decodes to nothing). NO kAlgoVersion bump: +// ingest only, and the Helio adapter already passes the checked count; WHOOP +// output unchanged. +const String kProtocolPin = 'e4ccba263dc94d772af122546fc93396243151fd'; // Fold idempotency, the minimum-nights warm-up, and legacy-payload handling // all live in SleepProfilePolicy (pure, unit-tested) — see @@ -2295,6 +2338,7 @@ bool pinnableNight({required int wakeSec, int? onsetSec}) { const _crossDayVendorScoreKeys = [ 'rhr', 'rmssd', + 'rmssd_dev', 'readiness', 'resp_rate', 'skin_temp_z', @@ -2705,6 +2749,8 @@ class _BaselineHistoryCache { // The readiness composite z — later days' scores are calibrated against // its spread (`calibratedReadinessScore`). 'readiness_z', + // PE-1: an admitted wearable's own night RMSSD (ln), its own baseline. + 'ln_rmssd_dev', // Per-day high quantile of the calibration-invariant dynamic accel // amplitude. The 1 Hz activity estimator's floor is anchored on the MEDIAN // of this series across trailing days, never on a same-day value: a @@ -2964,13 +3010,18 @@ class _BaselineHistoryCache { /// whole rescan window on every heavy pass for nothing. Once ANY baseline /// series has a later day (one too short to write its own level, say, which /// may already be finalized), that day was priced on it, so it is hashed. - String _quietFingerprint() { - final series = _series['quiet_hrr'] ?? const <_DatedValue>[]; + String _quietFingerprint() => _datedFingerprint('quiet_hrr'); + + /// [_quietFingerprint]'s rule for any trailing-window series: every dated + /// value an earlier day's window can see, newest excluded until a later day + /// exists. + String _datedFingerprint(String key) { + final series = _series[key] ?? const <_DatedValue>[]; const span = _rescanWindowDays + _baselineWindowDays; final newest = series.isEmpty ? null : series.last.date; final laterDay = newest != null && _series.entries.any((e) => - e.key != 'quiet_hrr' && + e.key != key && e.value.isNotEmpty && e.value.last.date.compareTo(newest) > 0); final end = series.isEmpty ? 0 : series.length - (laterDay ? 0 : 1); @@ -2994,9 +3045,15 @@ class _BaselineHistoryCache { final temp = values('skin_temp_adc'); final resp = values('resp_rate'); final readiness = values('readiness'); + // PE-1's device night RMSSD feeds readiness too, dated like the quiet + // levels (a reshuffle that keeps the median still moves a day's window). + // Only when the series has values: a band-only install's signature reads + // exactly as before. + final hasDev = (_series['ln_rmssd_dev'] ?? const []).isNotEmpty; final signature = 'v$kAlgoVersion|n${rhr.length}|rhr${fmt(_median(rhr))}|rmssd${fmt(_median(rmssd))}' '|temp${fmt(_median(temp))}|resp${fmt(_median(resp))}' + '${hasDev ? '|dev${_datedFingerprint('ln_rmssd_dev')}' : ''}' '|q${_quietFingerprint()}'; return { 'algo_version': kAlgoVersion, @@ -6958,6 +7015,14 @@ class DerivationEngine { ? null : await LocalDb.stepCalibrationProfile( daySub.deviceFamily!, counterWearing); + // PE-1: an admitted wearable's own RMSSD readings over the night the + // prepare step chose (null for every other family and every band day). + final deviceRmssd = await deviceNightRmssd( + family: daySub.deviceFamily, + deviceIds: daySub.deviceIds, + onsetSec: day.sleepOnsetSec, + offsetSec: day.sleepOffsetSec, + ); final input = DayBundleInput( date: day.date, dayTsSec: daySub.tsSec, @@ -7004,6 +7069,8 @@ class DerivationEngine { // forced window. sleepSource: day.sleepSource, useHmmStages: day.useHmmStages, + deviceLnRmssd: deviceRmssd?.lnRmssd, + deviceRmssdRefusal: deviceRmssd?.refusal, ); final withHistory = _attachHistory(input, history); @@ -7465,6 +7532,7 @@ class DerivationEngine { maxHrUsed: (bundle['max_hr_used'] as num?)?.round(), liveStepsReal: liveSteps.total, liveStepsFromStrap: liveSteps.strap, + wearableSteps: await wearableDaySteps(daySub, day.date), counterProfile: counterProfile, counterWearing: counterWearing, // The same resolution's credited spans, so the walking-cadence term @@ -7846,7 +7914,11 @@ class DerivationEngine { strapNight: strapNight, provisionalReadiness: ((bundle['clinical'] as Map?)?[ 'readiness_composite'] as Map?)?['provisional'] == - true), + true, + deviceHrvNight: deviceHrvNight(bundle)), + // Absent tonight means gone: an earlier pass's device night RMSSD + // must not outlive the readings that made it. + clearIfAbsent: const {'ln_rmssd_dev'}, series: { 'rhr': sc('rhr'), 'rmssd': sc('rmssd'), @@ -7854,6 +7926,9 @@ class DerivationEngine { 'readiness': sc('readiness'), 'readiness_z': sc('readiness_z'), 'ln_rmssd': sc('ln_rmssd'), + // Only when the device's readings produced it; a day without it + // has any earlier row removed by putDayResult. + 'ln_rmssd_dev': ?sc('ln_rmssd_dev'), 'resp_rate': sc('resp_rate'), 'skin_temp_z': sc('skin_temp_z'), // RAW nightly ADC mean — the baseline series for skin_temp_z. Written @@ -8228,6 +8303,10 @@ class DerivationEngine { Map? merged; for (final e in p.entries) { if (!carrySleep && sub == 'scalars' && e.key == 'nap_min') continue; + // PE-1's device night RMSSD is a FIRST-half scalar whose absence + // means the readings failed the gate tonight: carrying the previous + // value back in would bank a refused night into the baseline. + if (sub == 'scalars' && e.key == 'ln_rmssd_dev') continue; if (n.containsKey(e.key) || e.value == null) continue; (merged ??= Map.from(n))[e.key] = e.value; carried = true; @@ -8452,7 +8531,9 @@ class DerivationEngine { /// its method family, except a wearable's skin temperature, which is that /// device family's own nights (see [_BaselineHistoryCache.load]). static String? _baselineFamily(String key, String? deviceFamily) => - key == 'skin_temp_adc' && isWearableFamily(deviceFamily) + (key == 'skin_temp_adc' && isWearableFamily(deviceFamily)) || + (kDeviceSeriesFamilyKeys.contains(key) && + kDeviceRmssdFamilies.contains(deviceFamily)) ? deviceFamily : methodFamily(deviceFamily); @@ -8498,6 +8579,7 @@ class DerivationEngine { // two cannot score the day on different levels. m['quiet_hrr_history'] = before('quiet_hrr'); m['readiness_z_history'] = before('readiness_z'); + m['device_ln_rmssd_history'] = before('ln_rmssd_dev'); return m; } @@ -8988,6 +9070,9 @@ class DerivationEngine { 'date': date, 'rhr': col('rhr') ?? sc('rhr'), 'rmssd': col('rmssd') ?? sc('rmssd'), + // PE-1: the device's own night RMSSD (ms), for the breakdown's HRV row + // on a night with no beats. Only admitted families ever bank it. + if (sc('ln_rmssd_dev') case final ln?) 'rmssd_dev': math.exp(ln), 'readiness': col('readiness') ?? sc('readiness'), 'resp_rate': sc('resp_rate'), 'skin_temp_z': sc('skin_temp_z'), @@ -9519,6 +9604,7 @@ class DerivationEngine { double? dynFloorG, int liveStepsReal = 0, int liveStepsFromStrap = 0, + int? wearableSteps, int dynHistoryDays = 0, List> stepSpans = const [], /// This day's `sessions` rows (`LocalDb.sessionsInRange`), for the @@ -9616,6 +9702,7 @@ class DerivationEngine { dynHistoryDays, counterProfile: counterProfile, counterWearing: counterWearing, + wearableSteps: wearableSteps, ); // `_stepsAndEnergy` just wrote `steps` — REAL pedometer counts from // `live_coverage`, band 100 Hz or phone, never an estimate. `wake` was @@ -9936,6 +10023,7 @@ class DerivationEngine { Map? scMap, int liveStepsReal, { int liveStepsFromStrap = 0, + int? wearableSteps, CounterDeltas? counter, StepCalibrationProfile? profile, int wearing = Wearing.wrist, @@ -9972,8 +10060,23 @@ class DerivationEngine { final useBand = calibratedBand != null && calibratedBand > 0 && calibratedBand > liveStepsReal; - final steps = useBand ? calibratedBand : liveStepsReal; - final calibrated = useBand && profile != null && profile.isCalibrated; + // Rung 2b, the active wearable's OWN pedometer total for the day (a + // count it measured, served as the day's steps by owner decision + // 2026-11-22): a whole-day answer like the chip counter, so it joins the + // same max rather than the windowed sum (adding it would count every walk + // the phone also counted twice). + final wearable = wearableSteps != null && wearableSteps > 0 + ? wearableSteps + : null; + final useWearable = wearable != null && + wearable > (useBand ? calibratedBand : liveStepsReal); + final steps = useWearable + ? wearable + : useBand + ? calibratedBand + : liveStepsReal; + final calibrated = + useBand && !useWearable && profile != null && profile.isCalibrated; final haveRealSteps = steps > 0; if (haveRealSteps) { scMap?['steps'] = steps.toDouble(); @@ -9987,6 +10090,8 @@ class DerivationEngine { // won. Null (never 0) when this generation has no counter at all. Raw // ticks; `counter_calibration` carries the factor applied to `value`. 'band_measured': rawBand, + // The active wearable's own daily count, and whether it won. + 'wearable_measured': ?wearable, if (counter != null && wearing != 0) 'counter_wearing': wearingName(wearing), if (calibrated) @@ -10003,7 +10108,7 @@ class DerivationEngine { // When the on-chip counter is the day's answer, WHEN it counted: hourly // spans off the counter's own per-record times, scaled by the same // factor as `value` and summing to it exactly. - if (useBand && bandSpans != null) + if (useBand && !useWearable && bandSpans != null) 'spans': _scaleSpans(bandSpans, rawBand!, calibratedBand), // WHICH SENSOR COUNTED WHAT, so a screen can say so instead of implying // the phone's count came off the wrist or the other way round. Only the @@ -10013,7 +10118,9 @@ class DerivationEngine { ? { // What the chip counted, not the scaled value: the factor is // in `counter_calibration`. - if (useBand) + if (useWearable) + 'wearable': wearable + else if (useBand) 'strap_counter': rawBand! else ...{ if (strap > 0) 'strap': strap, @@ -10023,13 +10130,15 @@ class DerivationEngine { : const {}, 'source': !haveRealSteps ? null - : useBand + : useWearable + ? 'wearable' + : useBand ? 'strap_counter' : (strap > 0 && phone > 0) ? 'mixed' : (strap > 0 ? 'strap' : 'phone'), 'confidence': haveRealSteps - ? (useBand ? stepCounterConfidence(profile) : 0.9) + ? (useBand && !useWearable ? stepCounterConfidence(profile) : 0.9) : 0.0, // NO TIER ON AN ABSENT METRIC. `ESTIMATE` here was actively wrong in two // ways: this code path never estimates anything (that is the whole point @@ -10047,6 +10156,8 @@ class DerivationEngine { // reads these to label the card. 'inputs_used': !haveRealSteps ? const [] + : useWearable + ? const ['wearable_pedometer'] : useBand ? const ['band_step_counter'] : [ @@ -10054,7 +10165,11 @@ class DerivationEngine { if (phone > 0) 'phone_pedometer', ], 'note': haveRealSteps - ? (useBand + ? (useWearable + ? 'the wearable\'s own daily step count, as it counted it; used ' + 'whole when it counted more than the other sensors, never ' + 'added to them' + : useBand ? 'the strap\'s own on-chip pedometer, summed from its cumulative ' 'counter; wrapped and reset boundaries contribute nothing ' 'rather than a guess' @@ -10118,6 +10233,7 @@ class DerivationEngine { int dynHistoryDays, { StepCalibrationProfile? counterProfile, int counterWearing = Wearing.wrist, + int? wearableSteps, }) { try { // STEPS FIRST — they depend on NOTHING from the band substrate. @@ -10142,6 +10258,7 @@ class DerivationEngine { scMap, liveStepsReal, liveStepsFromStrap: liveStepsFromStrap, + wearableSteps: wearableSteps, counter: counter, profile: counterProfile, wearing: counterWearing, @@ -11853,6 +11970,7 @@ class DerivationEngine { dynFloorG: inp.dynFloorG, liveStepsReal: inp.liveStepsReal, liveStepsFromStrap: inp.liveStepsFromStrap, + wearableSteps: inp.wearableSteps, counterProfile: inp.counterProfile, counterWearing: inp.counterWearing, dynHistoryDays: inp.dynHistoryDays, @@ -12642,6 +12760,11 @@ class _DayBlocksInput { /// isolate, which has no handle. final int liveStepsFromStrap; + /// The active wearable's own step count for the day (its pedometer), or + /// null: a whole-day alternative to the windowed sum, like the gen5 chip + /// counter (`_writeSteps`). Read before the isolate, which has no handle. + final int? wearableSteps; + /// The SAME resolution's credited spans, as `[startSec, endSec, steps]` — /// the walking-cadence energy term prices wake minutes off these (see /// `cadenceSpmForMinutes`). Credited, never raw rows, so a step the ladder @@ -12716,6 +12839,7 @@ class _DayBlocksInput { this.counterProfile, this.counterWearing = Wearing.wrist, this.liveStepsFromStrap = 0, + this.wearableSteps, this.stepSpans = const [], required this.dynFloorG, required this.dynHistoryDays, diff --git a/lib/compute/hr_max.dart b/lib/compute/hr_max.dart index 649c29d58..fc38a88d0 100644 --- a/lib/compute/hr_max.dart +++ b/lib/compute/hr_max.dart @@ -325,6 +325,33 @@ int hrCeilingForAge(int? age) { {int? age, int window = kHrSmoothWindow}) => _smoothedExtremeHrAt(hr, wantMax: false, age: age, window: window); +/// [smoothedMaxHrAt] with each sample smoothed at its OWN source's cadence: +/// [capsSec] (parallel to [hr]) is the seconds each sample stands for. A +/// window of [kHrSmoothWindow] samples is 5 s of a 1 Hz strap but 5 minutes +/// of a wearable's minute HR (already one averaged value a minute), so the +/// sparse samples take no further smoothing and the dense ones keep theirs, +/// even when one session holds both. Null [capsSec]: [smoothedMaxHrAt]. +(int, int)? cadenceAwareMaxHrAt(List hr, List? capsSec, + {int? age}) { + if (capsSec == null || capsSec.length != hr.length) { + return smoothedMaxHrAt(hr, age: age); + } + (int, int)? best; + for (final sparse in const [false, true]) { + final idx = [ + for (var i = 0; i < hr.length; i++) + if ((capsSec[i] >= kHrSmoothWindow) == sparse) i, + ]; + if (idx.isEmpty) continue; + final at = smoothedMaxHrAt([for (final i in idx) hr[i]], + age: age, window: sparse ? 1 : kHrSmoothWindow); + if (at != null && (best == null || at.$1 > best.$1)) { + best = (at.$1, idx[at.$2]); + } + } + return best; +} + /// Spike-suppressed peak HR (value only) — see [smoothedMaxHrAt]. int? smoothedMaxHr(List hr, {int? age, int window = kHrSmoothWindow}) => smoothedMaxHrAt(hr, age: age, window: window)?.$1; diff --git a/lib/compute/inputs/canonical.dart b/lib/compute/inputs/canonical.dart index 2901fff9b..b2bc606cf 100644 --- a/lib/compute/inputs/canonical.dart +++ b/lib/compute/inputs/canonical.dart @@ -14,11 +14,20 @@ import 'dart:math' as math; import 'package:openstrap_analytics/onehz.dart' as ana; import '../../ble/adapters/_registry.dart' - show DeviceCategory, categoryOf, kBleHrs, kCoros, kPolarPmd; + show + DeviceCategory, + categoryOf, + declaredSignals, + kBleHrs, + kCoros, + kDeviceRmssdFamilies, + kPolarPmd; +import '../../ble/adapters/signals.dart' show InputSignal; import '../../data/day_label.dart'; import '../../data/db.dart'; import '../crossday_pipeline.dart' show buildCrossDayBundle; import '../derivation_engine.dart' show DerivationEngine, kAlgoVersion, runCancellableIsolate; +import '../onehz_pipeline.dart' show kDeviceRmssdHrvSource; import '../substrate.dart'; import '../vendor_sleep.dart'; import 'colmi_inputs.dart'; @@ -26,6 +35,7 @@ import 'garmin_inputs.dart'; import 'miband_inputs.dart'; import 'oura_inputs.dart'; import 'pebble_inputs.dart'; +import 'sparse_inputs.dart'; import 'ultrahuman_inputs.dart'; import 'validation_bands.dart'; @@ -39,6 +49,27 @@ const String kPartialReadinessMethod = 'composite_rhr_temp_partial'; /// strap's night beats (resting HR alone is below its weight floor). const String kStrapReadinessMethod = 'composite_rhr_strap'; +/// The method tag of our readiness on a night whose HRV input was the +/// wearable's own RMSSD readings (policy exception PE-1): resting HR from its +/// minute HR, HRV from its readings, both baselined on its own nights. Kept +/// on every such stored day so they stay findable if the readings turn out +/// not to be RMSSD (sparse_device_analytics_architecture.md §8.0). +const String kDeviceHrvReadinessMethod = 'composite_device_hrv'; + +/// The method tag of our night HRV off the wearable's own RMSSD readings. +const String kDeviceRmssdMethod = 'device_rmssd_samples'; + +/// `metric_series` keys a PE-1 night touches, whose baseline (and method +/// family) is the admitted DEVICE family's own nights, never the resolution's: +/// two vendors' RMSSD are two methods even at the same HR cadence. +const Set kDeviceSeriesFamilyKeys = {'ln_rmssd_dev', 'readiness_z'}; + +/// Whether a derived [bundle]'s composite took the wearable's own RMSSD. +bool deviceHrvNight(Map bundle) => + ((bundle['clinical'] as Map?)?['readiness_composite'] as Map?)?[ + 'hrv_source'] == + kDeviceRmssdHrvSource; + /// What a served number is. Ours collapses A and B (the method says which /// resolution it came from); device is the wearable's own value, labelled; /// estimated only where the device gives nothing; unavailable says why. @@ -403,7 +434,9 @@ Future refreshSessionSensorSources() async { for (final id in kWorkoutArmedSensors) if (await wearableEnabled(id)) id, }; - LocalDb.sessionWearableSource = (await activeWearable())?.$2; + final w = await activeWearable(); + LocalDb.sessionWearableSource = w?.$2; + LocalDb.sessionWearableDeviceId = w?.$1; } bool debugDisableWearableWorker = false; @@ -447,13 +480,13 @@ Future wearableSubstrate( int to, ) async { final own = await switch (wearable.$2) { - kGarminFamily || - kPebbleFamily || - kMiBandFamily => sparseHrSubstrate(wearable.$2, wearable.$1, from, to), kUltrahumanFamily => ultrahumanSubstrate(wearable.$1, from, to), kColmiFamily => colmiSubstrate(wearable.$1, from, to), kOuraFamily => ouraSubstrate(wearable.$1, from, to), - _ => Future.value(Substrate.empty), + // Every other family with an HR cadence: its HR rows, and the skin + // temperature on them when it declares one. + final f => sparseHrSubstrate(f, wearable.$1, from, to, + withSkinTemp: declaredSignals(f).contains(InputSignal.skinTempC)), }; if (!own.isEmpty || columnFor(wearable.$2) == null) { return withStrapSessions(own, from, to); @@ -638,6 +671,25 @@ Future enabledVendorSleepEndTs() async { return last; } +/// The active wearable's own step count for [date] when [daySub] is that +/// wearable's day and it declares a step counter ([InputSignal.steps]); null +/// on a band's day, with no active wearable (none chosen, flag off: rule R6) +/// or no count stored. The day's steps take it as a whole-day answer +/// (`DerivationEngine._writeSteps`). +/// ponytail: the newest stored row of the day; a device that banks several +/// partial counts a day would need them summed. +Future wearableDaySteps(Substrate daySub, String date) async { + final family = daySub.deviceFamily; + if (!isWearableFamily(family) || + daySub.deviceIds.length != 1 || + !declaredSignals(family).contains(InputSignal.steps)) { + return null; + } + final active = await activeWearable(); + if (active == null || active.$1 != daySub.deviceIds.single) return null; + return LocalDb.deviceDaySteps(active.$1, date); +} + /// Whether paired device [deviceId]'s adapter has its flag on (rule R6). Future deviceFlagOn(String? deviceId) async { if (deviceId == null) return false; @@ -697,12 +749,9 @@ Future> _scanWearableRecTsMaxByDay( (String, String) wearable) async { final out = { ...await switch (wearable.$2) { - kGarminFamily || - kPebbleFamily || - kMiBandFamily || - kUltrahumanFamily || - kColmiFamily => sparseHrRecTsMaxByDay(wearable.$2, wearable.$1), kOuraFamily => ouraRecTsMaxByDay(wearable.$1), + final f when kHrCadenceSec.containsKey(f) => + sparseHrRecTsMaxByDay(f, wearable.$1), _ => Future.value(const {}), }, }; @@ -873,9 +922,15 @@ class Cell { /// on that envelope): a ring's skin temperature, and the readiness that /// takes it in, rest on a settle band set on synthetic nights. final List? provisionalAt; + + /// Ours' method on the given stored day, where it depends on what that + /// night's inputs were (a PE-1 night's readiness); null falls back to + /// [ourMethod]. + final String? Function(Map day)? ourMethodOf; const Cell({ this.ours, this.ourMethod, + this.ourMethodOf, this.device, this.estimated, this.estimatedMethod, @@ -931,6 +986,18 @@ Cell strapBeatCell(String key, {String? device, required Why reason}) => Cell( reason: reason, ); +/// Steps on a wearable that counts them: the day's steps (`scalars.steps`, +/// the larger of the phone's count and the wearable's own whole-day total, +/// `DerivationEngine._writeSteps`), with the wearable's own count beside it. +/// Owner decision 2026-11-22: a step count is a measurement, served as the +/// day's steps, not only as the device's display value. +final Cell wearableStepsCell = Cell( + ours: (d, _) => scalar(d, 'steps'), + ourMethod: 'steps', + device: 'steps', + reason: Why.noDeviceSteps, +); + /// HRV: ours off a strap's beats on a night it was worn at rest. Cell strapHrvCell({String? device, required Why reason}) => strapBeatCell('rmssd', device: device, reason: reason); @@ -955,11 +1022,11 @@ Map> resolveCells( final est = dev == null ? c.estimated?.call(day, crossDay) : null; // Ours off the device's stages only on a night the device staged; on a // night our HR-led window found, ours off its HR ([seriesMethodFor]). - final ourHow = - c.ourMethod == 'device_stages' && - day['sleep_source'] != 'vendor_staged' - ? method - : c.ourMethod ?? method; + final ourHow = c.ourMethodOf?.call(day) ?? + (c.ourMethod == 'device_stages' && + day['sleep_source'] != 'vendor_staged' + ? method + : c.ourMethod ?? method); final (cls, value, how) = ours != null ? (MetricClass.ours, ours, ourHow) : dev != null @@ -1055,13 +1122,30 @@ SeriesMethod Function(String key)? seriesMethodFor( bool vendorNight = false, bool strapNight = false, bool provisionalReadiness = false, + bool deviceHrvNight = false, }) { final fam = methodFamily(family); if (fam == null) return null; + final admitted = kDeviceRmssdFamilies.contains(family); // A ring night a strap's beats own ([ouraStrapOwnsNight]). final strapBeats = strapNight && family == kOuraFamily; final column = strapBeats ? kOuraStrapNightColumn : columnFor(family); return (key) => switch (column?[kSeriesKeyRow[key]]) { + // PE-1: an admitted wearable's own night RMSSD, and the readiness and + // composite z of a night that took it, are ours under the device-HRV + // method, on that device family's own baseline. + _ when admitted && key == 'ln_rmssd_dev' => + (method: kDeviceRmssdMethod, family: family!, cls: MetricClass.ours.name), + _ when admitted && deviceHrvNight && key == 'readiness' => ( + method: kDeviceHrvReadinessMethod, + family: family!, + cls: MetricClass.ours.name, + ), + _ when admitted && key == 'readiness_z' => ( + method: deviceHrvNight ? kDeviceHrvReadinessMethod : fam, + family: family!, + cls: MetricClass.ours.name, + ), // A wearable's provisional readiness is not drawn as a measured point // either ([withoutWearableEstimates]); a band's day is left as it is. _ when column != null && provisionalReadiness && key == 'readiness' => ( @@ -1203,7 +1287,8 @@ const Map kEnvelopeSeriesKey = { /// exactly as it is: no stamp there means ours at `hr_1hz`, which its /// `metric_method` rows also say per key, so no band payload moves. void tagEnvelopes(Map? clinical, String? family) { - final of = seriesMethodFor(family); + final of = seriesMethodFor(family, + deviceHrvNight: clinical != null && deviceHrvNight({'clinical': clinical})); if (clinical == null || of == null || columnFor(family) == null) return; for (final MapEntry(:key, :value) in clinical.entries) { if (value is! Map) continue; @@ -1224,7 +1309,9 @@ Map? columnFor(String? adapterId) => switch (adapterId) { kUltrahumanFamily => kUltrahumanColumn, kColmiFamily => kColmiColumn, kOuraFamily => kOuraColumn, - _ => null, + // Any other wearable with an HR cadence: the column its declarations build. + final String f => sparseColumn(f), + null => null, }; /// What a column can serve at best, row by row, read off its cells rather diff --git a/lib/compute/inputs/colmi_inputs.dart b/lib/compute/inputs/colmi_inputs.dart index cc7ebb2a7..369607d14 100644 --- a/lib/compute/inputs/colmi_inputs.dart +++ b/lib/compute/inputs/colmi_inputs.dart @@ -270,7 +270,7 @@ final Map kColmiColumn = { 'irregular_rhythm_flag', reason: Why.needsBeats, ), - 'steps': Cell(device: 'steps', reason: Why.noDeviceSteps), + 'steps': wearableStepsCell, 'strain': Cell( estimated: (d, _) => scalar(d, 'strain'), estimatedMethod: 'hr_5min', diff --git a/lib/compute/inputs/device_night_samples.dart b/lib/compute/inputs/device_night_samples.dart new file mode 100644 index 000000000..09a6a03c4 --- /dev/null +++ b/lib/compute/inputs/device_night_samples.dart @@ -0,0 +1,98 @@ +// POLICY EXCEPTION PE-1, in one file: the only reader of a wearable's OWN +// RMSSD readings (`decoded_onehz.dev_rmssd_ms`), for a family admitted in +// `kDeviceRmssdFamilies`. It turns the night's raw samples into the one +// number our readiness takes as its HRV input when no strap's beats gave our +// own: ln(mean) over the night our pipeline already chose, or nothing. +// +// What stays OURS: the night window, the plausibility and count gates, the +// aggregate, the log, the personal baseline (per device family, never mixed +// with beat-derived HRV), the z, the weights and the calibration. What is the +// device's: each reading. Its composites (stress, readiness, PAI, ODI) never +// come through here. See docs/internal/sparse_device_analytics_architecture.md. + +import 'dart:math' as math; + +import '../../ble/adapters/_registry.dart' show kDeviceRmssdFamilies; +import '../../data/db.dart'; + +/// A reading outside this range is not a resting RMSSD (a dropout, a sensor +/// glitch, or a u8 field pinned near its ceiling). +const double kDeviceRmssdMinMs = 5; +const double kDeviceRmssdMaxMs = 200; + +/// The fewest plausible readings a night needs. A count, not a share of the +/// readings the declared cadence implies: that cadence has no capture behind +/// it, and a gate tied to it would abstain every night if the strap samples +/// less often than declared. +/// ponytail: set with no real Helio night behind it (§7 known unknowns); +/// refit on the first ~30 real nights. +const int kDeviceRmssdMinSamples = 6; + +/// The night's device RMSSD as ln(mean ms) over `[onsetSec, offsetSec)`, or +/// null with [refusal] saying why. +({double? lnRmssd, int n, String? refusal}) deviceNightLnRmssd( + List<(int, double)> samples, { + required int onsetSec, + required int offsetSec, +}) { + final inNight = [ + for (final (t, v) in samples) + if (t >= onsetSec && + t < offsetSec && + v >= kDeviceRmssdMinMs && + v <= kDeviceRmssdMaxMs) + v, + ]; + if (inNight.length < kDeviceRmssdMinSamples) { + return ( + lnRmssd: null, + n: inNight.length, + refusal: 'device_rmssd:n=${inNight.length},need=$kDeviceRmssdMinSamples', + ); + } + final mean = inNight.reduce((a, b) => a + b) / inNight.length; + return (lnRmssd: math.log(mean), n: inNight.length, refusal: null); +} + +/// [deviceId]'s own RMSSD readings over `[from, to)` as (epoch sec, ms), for +/// an admitted [family] only; empty for every other family. +Future> deviceRmssdSamples( + String? family, + String deviceId, + int from, + int to, +) async { + if (!kDeviceRmssdFamilies.contains(family)) return const []; + final db = await LocalDb.instance; + return [ + for (final r in await db.rawQuery( + 'SELECT rec_ts, dev_rmssd_ms FROM decoded_onehz ' + 'WHERE device_id = ? AND device_family = ? AND rec_ts >= ? ' + 'AND rec_ts < ? AND dev_rmssd_ms IS NOT NULL ORDER BY rec_ts', + [deviceId, family, from, to], + )) + ((r['rec_ts'] as num).toInt(), (r['dev_rmssd_ms'] as num).toDouble()), + ]; +} + +/// The night's value for a derive: admitted family, one device, a night. +/// Null when any of those is missing (the composite then has no HRV input, +/// exactly as before PE-1). +Future<({double? lnRmssd, String? refusal})?> deviceNightRmssd({ + required String? family, + required Set deviceIds, + required int onsetSec, + required int offsetSec, +}) async { + if (!kDeviceRmssdFamilies.contains(family) || + deviceIds.length != 1 || + onsetSec <= 0 || + offsetSec <= onsetSec) { + return null; + } + final samples = + await deviceRmssdSamples(family, deviceIds.single, onsetSec, offsetSec); + final r = + deviceNightLnRmssd(samples, onsetSec: onsetSec, offsetSec: offsetSec); + return (lnRmssd: r.lnRmssd, refusal: r.refusal); +} diff --git a/lib/compute/inputs/garmin_inputs.dart b/lib/compute/inputs/garmin_inputs.dart index ebe695dce..e7629af1f 100644 --- a/lib/compute/inputs/garmin_inputs.dart +++ b/lib/compute/inputs/garmin_inputs.dart @@ -29,6 +29,10 @@ import 'ultrahuman_inputs.dart'; const String kGarminFamily = 'garmin'; +/// The Amazfit Helio Strap (`helio_strap.dart`). No column of its own: it is +/// served by the declaration-built [sparseColumn]. +const String kHelioFamily = 'helio_strap'; + /// The widest gap, in seconds, between two readings still taken as one 1 Hz /// run (a strap's seconds laid over a wearable's day): a dropped second or /// two. A reading further off is a wearable's own and stands for its minutes. @@ -43,6 +47,7 @@ const int kOneHzRunGapSec = 3; /// A family missing here gets no substrate at all (calibrationFor refuses). const Map kHrCadenceSec = { kGarminFamily: 60, + kHelioFamily: 60, kPebbleFamily: 60, kMiBandFamily: 60, kUltrahumanFamily: 300, @@ -59,6 +64,7 @@ const Map kMethodFamily = { 'gen4': 'hr_1hz', 'gen5': 'hr_1hz', kGarminFamily: 'hr_1min', + kHelioFamily: 'hr_1min', kPebbleFamily: 'hr_1min', kMiBandFamily: 'hr_1min', kUltrahumanFamily: 'hr_5min', @@ -89,29 +95,56 @@ String? hrMethod(String? family) => /// A [family] watch's HR rows for [deviceId] over `[from, to]` as a /// substrate: HR only, absent gravity (0,0,0), no beats. Empty when there are /// none, or when the rows are not this family's. Shared by every family in -/// [kHrCadenceSec]. +/// [kHrCadenceSec]. [withSkinTemp]: each HR row's own `skin_temp_c` rides +/// beside it in centi-°C (0 = none), for a family that declares +/// [InputSignal.skinTempC] and stores it on its HR rows. Future sparseHrSubstrate( String family, String deviceId, int from, - int to, -) async { + int to, { + bool withSkinTemp = false, +}) async { if (ana.calibrationFor(kHrCadenceSec, family) == null) { return Substrate.empty; } final db = await LocalDb.instance; final rows = await db.rawQuery( - 'SELECT rec_ts, hr FROM decoded_onehz ' + 'SELECT rec_ts, hr, skin_temp_c FROM decoded_onehz ' 'WHERE device_id = ? AND device_family = ? AND rec_ts >= ? ' 'AND rec_ts <= ? AND hr > 0 ORDER BY rec_ts', [deviceId, family, from, to], ); if (rows.isEmpty) return Substrate.empty; - return constructWearable(() => _sparseHrSubstrate(family, deviceId, rows)); + // A device that stores temperature as its own records (the Helio's rounds + // start on their own seconds) has readings on rows with no HR, which the + // query above drops. Each such reading joins the HR row of the same + // minute, so it is kept without adding rows that would change the HR + // cadence the column is measured at. + var withTemp = rows; + if (withSkinTemp) { + final byMinute = { + for (final r in await db.rawQuery( + 'SELECT rec_ts, skin_temp_c FROM decoded_onehz ' + 'WHERE device_id = ? AND device_family = ? AND rec_ts >= ? ' + 'AND rec_ts <= ? AND skin_temp_c IS NOT NULL ORDER BY rec_ts', + [deviceId, family, from, to], + )) + (r['rec_ts'] as num).toInt() ~/ 60: r['skin_temp_c'], + }; + withTemp = [ + for (final r in rows) + r['skin_temp_c'] != null + ? r + : {...r, 'skin_temp_c': byMinute[(r['rec_ts'] as num).toInt() ~/ 60]}, + ]; + } + return constructWearable( + () => _sparseHrSubstrate(family, deviceId, withTemp, withSkinTemp)); } Substrate _sparseHrSubstrate(String family, String deviceId, - List> rows) { + List> rows, bool withSkinTemp) { final n = rows.length; final zeros = List.filled(n, 0); final none = List.filled(n, -1); @@ -125,7 +158,17 @@ Substrate _sparseHrSubstrate(String family, String deviceId, az: zeros, spo2Red: List.filled(n, 0), spo2Ir: List.filled(n, 0), - skinTemp: List.filled(n, 0), + skinTemp: withSkinTemp + ? [ + for (final r in rows) + switch (r['skin_temp_c']) { + // Skin on a wrist, arm or chest; anything else is the sensor + // off the body or its sentinel, read as no reading. + final num c when c >= 20 && c <= 45 => (c * 100).round(), + _ => 0, + }, + ] + : List.filled(n, 0), skinContact: List.filled(n, 0), stepCount: none, hrValid: none, @@ -228,7 +271,7 @@ final Map kGarminColumn = { 'irregular_rhythm_flag', reason: Why.needsBeats, ), - 'steps': Cell(device: 'steps', reason: Why.noDeviceSteps), + 'steps': wearableStepsCell, 'strain': Cell( ours: (d, _) => scalar(d, 'strain'), reason: Why.noWakeHr, diff --git a/lib/compute/inputs/miband_inputs.dart b/lib/compute/inputs/miband_inputs.dart index 4e636af46..2aa7f2fbc 100644 --- a/lib/compute/inputs/miband_inputs.dart +++ b/lib/compute/inputs/miband_inputs.dart @@ -76,7 +76,7 @@ final Map kMiBandColumn = { 'irregular_rhythm_flag', reason: Why.needsBeats, ), - 'steps': Cell(device: 'steps', reason: Why.noDeviceSteps), + 'steps': wearableStepsCell, 'strain': Cell( ours: (d, _) => scalar(d, 'strain'), reason: Why.noWakeHr, diff --git a/lib/compute/inputs/pebble_inputs.dart b/lib/compute/inputs/pebble_inputs.dart index 64c458d4b..cc28b2052 100644 --- a/lib/compute/inputs/pebble_inputs.dart +++ b/lib/compute/inputs/pebble_inputs.dart @@ -101,7 +101,7 @@ final Map kPebbleColumn = { 'irregular_rhythm_flag', reason: Why.needsBeats, ), - 'steps': Cell(device: 'steps', reason: Why.noDeviceSteps), + 'steps': wearableStepsCell, 'strain': Cell( ours: (d, _) => scalar(d, 'strain'), reason: Why.noWakeHr, diff --git a/lib/compute/inputs/sparse_inputs.dart b/lib/compute/inputs/sparse_inputs.dart new file mode 100644 index 000000000..3a0db4e30 --- /dev/null +++ b/lib/compute/inputs/sparse_inputs.dart @@ -0,0 +1,189 @@ +// A sparse-HR wearable's column of the metric x device table, BUILT FROM ITS +// DECLARATIONS rather than written per device: what it emits +// (`kAdapterSignals`) and the HR cadence it stores (`kHrCadenceSec`). A new +// wearable of this kind adds those rows and gets this column; nothing in +// compute names it. The hand-written columns (Garmin, Pebble, Mi Band, the +// rings) stay for the devices whose quirks a declaration cannot say (a watch +// that reports no wake, a ring that gives its own beats). +// +// Each row follows the hand-written columns' rules: ours where our method +// reads the HR it stores, the device's value where it declares one, and the +// reason otherwise. See docs/internal/sparse_device_analytics_architecture.md. + +import 'dart:math' as math; + +import '../../ble/adapters/_registry.dart' + show kAdapterSignals, kDeviceRmssdFamilies; +import '../../ble/adapters/signals.dart'; +import 'canonical.dart'; +import 'garmin_inputs.dart'; +import 'pebble_inputs.dart' show rhrOnlyReadiness; + +final Map> _built = {}; + +/// [family]'s declaration-built column, or null for a family with no HR +/// cadence ([kHrCadenceSec]): one with no validated method serves nothing. +Map? sparseColumn(String family) { + final cadence = kHrCadenceSec[family]; + if (cadence == null) return null; + return _built[family] ??= _sparseColumn( + kAdapterSignals[family]?.keys.toSet() ?? const {}, + cadence, + hrMethod(family), + admitted: kDeviceRmssdFamilies.contains(family), + ); +} + +/// exp of a stored ln value, or null. +num? _exp(num? ln) => ln == null ? null : math.exp(ln); + +Map _sparseColumn( + Set has, int cadence, String? method, + {required bool admitted}) { + final staged = has.contains(InputSignal.deviceStages); + // One HR a minute carries a workout's shape and a waking day's load; one + // every five minutes only an estimate of them (the rings' columns). + final minute = cadence <= 60; + Cell load(String key, Why reason) => minute + ? Cell(ours: (d, _) => scalar(d, key), reason: reason) + : Cell( + estimated: (d, _) => scalar(d, key), + estimatedMethod: method, + reason: reason, + ); + return { + // Ours is the HR-led window off its HR (in bed); the device's, the + // night it staged. + 'sleep_window': Cell( + ours: (d, _) => at(d, ['hr_sleep_window', 'in_bed_min']), + device: staged ? 'in_bed_min' : null, + reason: Why.noNight, + ), + 'efficiency_awakenings': staged + ? Cell( + ours: (d, _) => scalar(d, 'efficiency'), + ourMethod: 'device_stages', + reason: Why.noNight, + ) + : const Cell(reason: Why.noStagedNight), + 'sleep_stages': Cell( + device: staged ? 'deep_min' : null, + reason: Why.noStagedNight, + ), + 'naps': const Cell(device: 'nap_min', reason: Why.noDeviceNap), + 'sleep_debt_need_sri': Cell( + ours: (_, x) => at(x, ['sleep_debt', 'value', 'debt_hours']), + ourMethod: staged ? 'device_stages' : null, + reason: Why.needsThreeNights, + ), + 'resting_hr': Cell( + ours: (d, _) => scalar(d, 'rhr'), + device: 'rhr', + reason: Why.noNightHr, + ), + 'nadir_dip': Cell( + ours: (d, _) => scalar(d, 'sleeping_hr_nadir'), + reason: Why.noNightHr, + ), + // PE-1 (admitted family): ours is a strap's beats when it was worn, + // else our night mean of the device's own RMSSD readings; the device's + // own night figure rides beside it. + 'hrv': admitted + ? Cell( + ours: (d, _) => + scalar(d, 'rmssd') ?? _exp(scalar(d, 'ln_rmssd_dev')), + ourMethodOf: (d) => scalar(d, 'rmssd') != null + ? kRrStrapMethod + : scalar(d, 'ln_rmssd_dev') != null + ? kDeviceRmssdMethod + : null, + device: 'rmssd', + reason: Why.noDeviceHrv, + ) + : strapHrvCell( + device: has.contains(InputSignal.deviceHrv) ? 'rmssd' : null, + reason: has.contains(InputSignal.deviceHrv) + ? Why.noDeviceHrv + : Why.neverBeats, + ), + 'respiratory_rate': strapBeatCell( + 'resp_rate', + device: has.contains(InputSignal.deviceResp) ? 'resp_rate' : null, + reason: has.contains(InputSignal.deviceResp) + ? Why.noDeviceResp + : Why.neverResp, + ), + 'spo2': has.contains(InputSignal.deviceSpo2) + ? const Cell(device: 'spo2', reason: Why.noDeviceSpo2) + : const Cell(reason: Why.neverSpo2), + 'stress': strapBeatCell( + 'stress', + device: has.contains(InputSignal.deviceStress) ? 'stress' : null, + reason: has.contains(InputSignal.deviceStress) + ? Why.noDeviceStress + : Why.neverStress, + ), + // Ours off the Celsius it stores on its HR rows: the night's mean + // against its own earlier nights. + 'skin_temp': has.contains(InputSignal.skinTempC) + ? Cell( + ours: (d, _) => scalar(d, 'skin_temp_z'), + ourMethod: 'skin_temp_c', + reason: Why.needsThreeNightsTemp, + ) + : const Cell(reason: Why.neverSkinTemp), + // The composite needs two inputs we measured; resting HR alone is + // estimated until a strap's beats (or the device's own RMSSD samples, + // once admitted) make it two. + // On an admitted family the device's own RMSSD readings are the second + // input (PE-1, owner decision: served as ours, the Today headline). + 'readiness': Cell( + ours: (d, _) => scalar(d, 'readiness'), + ourMethod: kStrapReadinessMethod, + ourMethodOf: admitted + ? (d) => deviceHrvNight(d) ? kDeviceHrvReadinessMethod : null + : null, + best: admitted ? MetricClass.ours : MetricClass.estimated, + estimated: (d, _) => rhrOnlyReadiness(d), + estimatedMethod: 'rhr_only_partial', + reason: Why.needsRhrBaseline, + ), + 'irregular_rhythm': strapBeatCell( + 'irregular_rhythm_flag', + reason: Why.needsBeats, + ), + 'steps': has.contains(InputSignal.steps) + ? wearableStepsCell + : const Cell(reason: Why.noDeviceSteps), + 'strain': load('strain', Why.noWakeHr), + 'calories': load('calories', Why.noWakeHrOrProfile), + // Minutes in an HR zone stand in for movement (no accelerometer): a + // measure of effort, labelled estimated, as on a Garmin. + 'movement': Cell( + estimated: (d, _) => d['zones'] is Map + ? (d['zones'] as Map) + .values + .whereType() + .fold(0, (a, b) => a + b) + : null, + estimatedMethod: '${method}_zone_minutes', + reason: Why.noWakeHr, + ), + 'auto_workouts': minute + ? Cell( + ours: (d, _) => (d['workout_suggestions'] as List?)?.length, + reason: Why.noWakeHr, + ) + : const Cell(reason: Why.tooSparseForWorkouts), + 'workouts_with_strap': strapWorkoutsCell, + 'hrr': strapHrrCell, + 'baselines_load_illness': Cell( + ours: (d, _) => at(d, ['baselines', 'resting_hr', 'baseline']), + reason: Why.needsHistory, + ), + 'circadian': Cell( + ours: (_, x) => at(x, ['circadian_cosinor', 'value', 'acrophase_hours']), + reason: Why.needsThreeDaysHr, + ), + }; +} diff --git a/lib/compute/inputs/ultrahuman_inputs.dart b/lib/compute/inputs/ultrahuman_inputs.dart index eca5acfc6..f43f48db8 100644 --- a/lib/compute/inputs/ultrahuman_inputs.dart +++ b/lib/compute/inputs/ultrahuman_inputs.dart @@ -363,7 +363,7 @@ final Map kUltrahumanColumn = { 'irregular_rhythm_flag', reason: Why.needsBeats, ), - 'steps': Cell(device: 'steps', reason: Why.noDeviceSteps), + 'steps': wearableStepsCell, 'strain': Cell( estimated: (d, _) => scalar(d, 'strain'), estimatedMethod: 'hr_5min', diff --git a/lib/compute/manual_session.dart b/lib/compute/manual_session.dart index 794dec927..dc86ecab4 100644 --- a/lib/compute/manual_session.dart +++ b/lib/compute/manual_session.dart @@ -32,7 +32,7 @@ import 'dart:convert'; import 'package:openstrap_analytics/onehz.dart' as ana; -import 'hr_max.dart' show smoothedMaxHr; +import 'hr_max.dart' show cadenceAwareMaxHrAt, kHrSmoothWindow, smoothedMaxHr; import 'profile.dart'; /// Shortest window we accept. Below a minute the 1 Hz substrate cannot say @@ -167,6 +167,11 @@ class ManualSessionStats { /// cannot be scored. final int hrSampleCount; + /// Seconds of the window those samples stand for: [hrSampleCount] for a + /// 1 Hz stream, a minute a sample for a wearable's minute HR. Completeness + /// and trace replacement compare THIS, never the row count. + final int coveredSec; + const ManualSessionStats({ this.avgHr, this.maxHr, @@ -174,6 +179,7 @@ class ManualSessionStats { this.calories, this.zoneMinutes = const [], this.hrSampleCount = 0, + this.coveredSec = 0, }); /// True when the window had no 1 Hz HR at all — pruned, or band not worn. @@ -220,19 +226,41 @@ List hrPerMinute(List hrTs, List hrBpm) { /// resolves to the SAME %HRmax bands (`zonesFromMaxHr`) the inline loop here /// used to hard-code. 0 means "no ceiling": no age, or a strap we have no /// calibrated ceiling for, so no split. +/// +/// [hrTs] (parallel to [hrBpm]) weights each sample by the seconds it stands +/// for: the gap to the next, capped at the stream's median gap (the last +/// sample takes the median). A 1 Hz stream's median gap is 1 s, so every +/// sample is one second exactly as without it; a wearable storing one HR a +/// minute gets 60 s a sample instead of 1 (counted as seconds, its zone +/// minutes read 60x short). A gap longer than the median is unobserved time, +/// never zone time. Null: one second a sample. [cadenceSec], when given, +/// replaces the median as the cap: the caller's stream cadence measured +/// BEFORE off-skin samples were dropped, so a contact gap cannot widen it. +/// [capsSec] (parallel to [hrTs]) replaces both with each sample's OWN +/// source cadence, for a window that mixes a minute-HR wearable with a 1 Hz +/// sensor. [endSec] clips the last sample's span at the window's end (never +/// under 1 s, so a 1 Hz stream counts as before). List zoneMinutesFor( List hrBpm, double zoneMaxHr, { ana.HeartRateZoneSet? zoneSet, + List? hrTs, + int? cadenceSec, + List? capsSec, + int? endSec, }) { final set = zoneSet ?? (zoneMaxHr > 0 ? ana.HeartRateZones.zonesFromMaxHr(zoneMaxHr) : null); if (hrBpm.isEmpty || set == null) return const []; + final span = hrTs != null && hrTs.length == hrBpm.length + ? sampleSpansSec(hrTs, capSec: cadenceSec, capsSec: capsSec, endSec: endSec) + : null; final secs = List.filled(5, 0); - for (final v in hrBpm) { + for (var i = 0; i < hrBpm.length; i++) { + final v = hrBpm[i]; if (v <= 0) continue; final z = set.zoneNumber(v.toDouble()); - if (z >= 1) secs[z - 1]++; + if (z >= 1) secs[z - 1] += span?[i] ?? 1; } return [ for (var z = 0; z < 5; z++) @@ -240,6 +268,67 @@ List zoneMinutesFor( ]; } +/// Seconds each sample of ascending [ts] stands for: the gap to the next, +/// capped at the median gap (or [capSec]); the last takes the cap. 1 +/// everywhere on a gapless 1 Hz stream. +List sampleSpansSec(List ts, + {int? capSec, List? capsSec, int? endSec}) { + if (capsSec != null && capsSec.length == ts.length) { + return [ + for (var i = 0; i < ts.length; i++) + i + 1 < ts.length + ? (ts[i + 1] - ts[i]).clamp(1, capsSec[i] < 1 ? 1 : capsSec[i]) + : endSec == null + ? (capsSec[i] < 1 ? 1 : capsSec[i]) + : (endSec - ts[i]).clamp(1, capsSec[i] < 1 ? 1 : capsSec[i]), + ]; + } + if (ts.length < 2) return List.filled(ts.length, capSec ?? 1); + final median = capSec ?? medianGapSec(ts); + return [ + for (var i = 0; i < ts.length; i++) + i + 1 < ts.length + ? (ts[i + 1] - ts[i]).clamp(1, median) + : median, + ]; +} + +/// Per-minute HR for the samples whose cadence is a minute or coarser: each +/// stands for its span's seconds, accumulated across samples so a clipped +/// span adds a fraction of a minute rather than a whole one. A minute is +/// emitted per whole 60 s, at the mean HR of the seconds it holds (a minute +/// made of 30 s at 180 and 30 s at 80 is 130, not the HR of whichever +/// sample completed it); a sample spanning whole minutes emits its own HR. +List sparseMinutes(List hr, List caps, List spans) { + final out = []; + var openSec = 0; // seconds in the minute being filled + var openHrSec = 0; // their HR-seconds + for (var i = 0; i < hr.length; i++) { + if (caps[i] < 60) continue; + var left = spans[i]; + while (left > 0) { + final take = left < 60 - openSec ? left : 60 - openSec; + openSec += take; + openHrSec += hr[i] * take; + left -= take; + if (openSec == 60) { + out.add(openHrSec / 60); + openSec = 0; + openHrSec = 0; + } + } + } + return out; +} + +/// The median gap of ascending [ts], at least 1 s; 1 with under two samples. +int medianGapSec(List ts) { + if (ts.length < 2) return 1; + final gaps = [for (var i = 1; i < ts.length; i++) ts[i] - ts[i - 1]]..sort(); + final m = gaps[gaps.length ~/ 2]; + return m < 1 ? 1 : m; +} + /// Headline 0–21 strain from per-minute mean HR, or null when an anchor the /// Banister formula actually needs is missing. /// @@ -326,6 +415,8 @@ ManualSessionStats computeManualSessionStats({ ana.HeartRateZoneSet? zoneSet, double? quietHrr, bool quietSettled = true, + List? hrCadenceSec, + int? endSec, }) { if (hrTs.isEmpty || hrTs.length != hrBpm.length) { return const ManualSessionStats(); @@ -338,16 +429,51 @@ ManualSessionStats computeManualSessionStats({ // avgHr, strain and the zone bands had all correctly ignored. final wornTs = []; final worn = []; + final caps = hrCadenceSec != null && hrCadenceSec.length == hrTs.length + ? [] + : null; for (var i = 0; i < hrBpm.length; i++) { if (hrBpm[i] > 0) { wornTs.add(hrTs[i]); worn.add(hrBpm[i]); + caps?.add(hrCadenceSec![i]); } } if (worn.isEmpty) return const ManualSessionStats(); - - final avg = worn.reduce((a, b) => a + b) / worn.length; - final perMin = hrPerMinute(wornTs, worn); + // The stream's own cadence, off EVERY sample: dropping off-skin seconds + // leaves gaps that would otherwise read as a coarser stream and bill the + // lost contact as zone time. + final cadence = medianGapSec(hrTs); + + // Each sample's seconds when the rows say their source: a window mixing a + // wearable's minute HR with a 1 Hz strap would otherwise let the dense rows + // dominate the mean. + final spans = caps == null + ? null + : sampleSpansSec(wornTs, capsSec: caps, endSec: endSec); + final coveredSec = spans == null + ? worn.length + : spans.fold(0, (a, b) => a + b); + final avg = spans == null + ? worn.reduce((a, b) => a + b) / worn.length + : [for (var i = 0; i < worn.length; i++) worn[i] * spans[i]] + .fold(0, (a, b) => a + b) / + coveredSec; + // Strain is priced per minute. A sample sparser than a minute (a ring's + // 5-minute HR) stands for every minute its span covers, not just the one + // minute bucket it falls in, or a fully covered hour of 5-minute HR scores + // as 12 minutes. Their seconds are carried across samples and a minute is + // emitted per whole 60 s, so a span the window's end clipped to 90 s is + // 1.5 minutes of the run, not 2. Dense samples keep their minute means. + final perMin = spans == null + ? hrPerMinute(wornTs, worn) + : [ + ...hrPerMinute( + [for (var i = 0; i < worn.length; i++) if (caps![i] < 60) wornTs[i]], + [for (var i = 0; i < worn.length; i++) if (caps![i] < 60) worn[i]], + ), + ...sparseMinutes(worn, caps!, spans), + ]; final age = profile.ageYears?.toDouble(); // THE peak, spike-suppressed, at the point every save goes through (#127). @@ -356,7 +482,19 @@ ManualSessionStats computeManualSessionStats({ // window is pruned there is nothing left to correct it from. Smoothing here // means the stored value is the same quantity the re-score and the Heart page // report, rather than three producers agreeing by convention. - final peak = smoothedMaxHr(worn, age: age?.round()) ?? + // The smoothing window is SAMPLES: 5 of them is 5 s at 1 Hz but 5 minutes + // on a wearable storing one (already averaged) HR a minute, which would + // report a five-minute median as the peak. A stream sampled at least as + // coarsely as the window takes no further smoothing. + // Per source when the rows say which source each is (a window can mix a + // minute-HR wearable with a 1 Hz strap); otherwise the stream's own step. + final step = sampleSpansSec(wornTs, capSec: cadence, capsSec: caps) + .fold(0, (a, b) => b > a ? b : a); + final peak = (caps != null + ? cadenceAwareMaxHrAt(worn, caps, age: age?.round())?.$1 + : smoothedMaxHr(worn, + age: age?.round(), + window: step >= kHrSmoothWindow ? 1 : kHrSmoothWindow)) ?? worn.reduce((a, b) => a > b ? a : b); final weightKg = profile.weightKg; final heightCm = profile.heightCm; @@ -400,8 +538,14 @@ ManualSessionStats computeManualSessionStats({ strain: strain, calories: calories, // 0 is `zoneMinutesFor`'s own "no ceiling" input → an empty split. - zoneMinutes: zoneMinutesFor(worn, hrMax ?? 0, zoneSet: zoneSet), + zoneMinutes: zoneMinutesFor(worn, hrMax ?? 0, + zoneSet: zoneSet, + hrTs: wornTs, + cadenceSec: cadence, + capsSec: caps, + endSec: endSec), hrSampleCount: worn.length, + coveredSec: coveredSec, ); } diff --git a/lib/compute/onehz_pipeline.dart b/lib/compute/onehz_pipeline.dart index 6ab5733d0..6bfed8f45 100644 --- a/lib/compute/onehz_pipeline.dart +++ b/lib/compute/onehz_pipeline.dart @@ -171,6 +171,10 @@ const double kReadinessZCap = 5.0; /// [readinessCompositeMinWeight]. const double kPartialReadinessMinWeight = 0.4; +/// `readiness_composite.hrv_source` on a night whose HRV input was the +/// wearable's own RMSSD readings (policy exception PE-1). +const String kDeviceRmssdHrvSource = 'device_rmssd'; + /// The headline readiness scalar for a computed [composite], or null when it must /// abstain: absent composite, or one whose |z| exceeds [kReadinessZCap] (a /// saturated, degenerate-baseline artefact — see [kReadinessZCap]). Pure so the @@ -390,6 +394,16 @@ class DayBundleInput { /// calibrated against (`calibratedReadinessScore`). final List readinessZHistory; + /// POLICY EXCEPTION PE-1: ln(mean) of the wearable's OWN RMSSD readings + /// over this night (`device_night_samples.dart`), for an admitted family; + /// null otherwise, or when the night's readings failed the gate + /// ([deviceRmssdRefusal] says how). Readiness's HRV input only on a night + /// with no beat-derived HRV of ours, scored against + /// [deviceLnRmssdHistory] (this device family's own nights, never ours). + final double? deviceLnRmssd; + final String? deviceRmssdRefusal; + final List deviceLnRmssdHistory; + /// TS-03 — the highest heart rate the band has OBSERVED (held >=15 s with /// corroborating motion, `observed_max_hr.dart`) on any day STRICTLY BEFORE /// this one, or null when there is none. Not a physiological HRmax: if the @@ -459,6 +473,9 @@ class DayBundleInput { this.skinTempAdcHistory = const [], this.quietHrrHistory = const [], this.readinessZHistory = const [], + this.deviceLnRmssd, + this.deviceRmssdRefusal, + this.deviceLnRmssdHistory = const [], this.observedHrCeilingBpm, this.dayConfidence = 0, this.dayFlags = const [], @@ -496,6 +513,9 @@ class DayBundleInput { 'skin_temp_adc_history': skinTempAdcHistory, 'quiet_hrr_history': quietHrrHistory, 'readiness_z_history': readinessZHistory, + 'device_ln_rmssd': deviceLnRmssd, + 'device_rmssd_refusal': deviceRmssdRefusal, + 'device_ln_rmssd_history': deviceLnRmssdHistory, 'observed_hr_ceiling_bpm': observedHrCeilingBpm, 'day_confidence': dayConfidence, 'day_flags': dayFlags, @@ -552,6 +572,9 @@ class DayBundleInput { skinTempAdcHistory: dbls('skin_temp_adc_history'), quietHrrHistory: dbls('quiet_hrr_history'), readinessZHistory: dbls('readiness_z_history'), + deviceLnRmssd: (m['device_ln_rmssd'] as num?)?.toDouble(), + deviceRmssdRefusal: m['device_rmssd_refusal'] as String?, + deviceLnRmssdHistory: dbls('device_ln_rmssd_history'), observedHrCeilingBpm: (m['observed_hr_ceiling_bpm'] as num?)?.toDouble(), dayConfidence: (m['day_confidence'] as num?)?.toDouble() ?? 0, dayFlags: strs('day_flags'), @@ -658,6 +681,9 @@ class DayBundleInput { skinTempAdcHistory: skinTempAdcHistory, quietHrrHistory: quietHrrHistory, readinessZHistory: readinessZHistory, + deviceLnRmssd: deviceLnRmssd, + deviceRmssdRefusal: deviceRmssdRefusal, + deviceLnRmssdHistory: deviceLnRmssdHistory, observedHrCeilingBpm: observedHrCeilingBpm, dayConfidence: dayConfidence, dayFlags: dayFlags, @@ -1136,8 +1162,15 @@ Map _deriveDayBundle(Map inputJson, // lives in `rhr` itself, so this is the same number the card shows. final rhrToday = rhr.present ? rhr.value!.low30Mean : null; final respToday = resp.present ? resp.value!.brpm : null; + // POLICY EXCEPTION PE-1: a night with no beat-derived HRV of ours takes the + // admitted wearable's own RMSSD readings (their night mean, gated, ln) as + // the HRV input, scored against that device family's own nights only. + // Never both: beats win. `hrv_source` on the envelope says which it was. + final hrvFromDevice = lnToday == null && d.deviceLnRmssd != null; final composite = readinessComposite([ - hrvInput(lnToday, d.lnRmssdHistory), + hrvFromDevice + ? hrvInput(d.deviceLnRmssd, d.deviceLnRmssdHistory) + : hrvInput(lnToday, d.lnRmssdHistory), rhrInput(rhrToday, d.rhrHistory), respInput(respToday, d.respHistory), // Feed the RAW ADC mean + the RAW-ADC baseline so the composite computes its @@ -1185,8 +1218,10 @@ Map _deriveDayBundle(Map inputJson, if (!composite.present) { readinessAbsentDiag = { 'hrv': { - 'value': lnToday != null, - 'baseline_n': d.lnRmssdHistory.length, + 'value': lnToday != null || hrvFromDevice, + 'baseline_n': hrvFromDevice + ? d.deviceLnRmssdHistory.length + : d.lnRmssdHistory.length, }, 'rhr': { 'value': rhrToday != null, @@ -1552,6 +1587,12 @@ Map _deriveDayBundle(Map inputJson, 'readiness_lnrmssd': lnReadiness.toJson((v) => v.toJson()), 'readiness_composite': { ...composite.toJson((v) => v.toJson()), + // PE-1: which HRV this night's composite took, so every reader (the + // served cell's method, metric_method, the detail screen) can say so. + if (hrvFromDevice && composite.inputs_used.contains('HRV')) + 'hrv_source': kDeviceRmssdHrvSource, + if (d.deviceRmssdRefusal != null) + 'device_rmssd_refusal': d.deviceRmssdRefusal, if (tempProvisional && composite.inputs_used.contains('temp')) ...{ 'confidence': _round(composite.confidence * 0.5, 6), 'provisional': true, @@ -1720,7 +1761,12 @@ Map _deriveDayBundle(Map inputJson, final zCapNote = zCapAbsentNote(composite); if (readinessAbsentDiag == null && zCapNote != null) { readinessAbsentDiag = { - 'hrv': {'value': lnToday != null, 'baseline_n': d.lnRmssdHistory.length}, + 'hrv': { + 'value': lnToday != null || hrvFromDevice, + 'baseline_n': hrvFromDevice + ? d.deviceLnRmssdHistory.length + : d.lnRmssdHistory.length, + }, 'rhr': {'value': rhrToday != null, 'baseline_n': d.rhrHistory.length}, 'resp': {'value': respToday != null, 'baseline_n': d.respHistory.length}, 'temp': { @@ -2035,6 +2081,10 @@ Map _deriveDayBundle(Map inputJson, 'strain': strainScalar, 'max_hr_used': hrMax, 'ln_rmssd': lnToday, + // PE-1: the admitted wearable's own night RMSSD, ln, banked as its own + // series (never `ln_rmssd`) for its own baseline, whether or not beats + // won tonight. Absent (no key) when there is none. + 'ln_rmssd_dev': ?d.deviceLnRmssd, 'resp_rate': respToday, 'skin_temp_z': skinTempZ, // Nightly skin-temp ADC mean (of the settled samples, where the family diff --git a/lib/data/backup_extras.dart b/lib/data/backup_extras.dart index aea8bec5f..68de1ef58 100644 --- a/lib/data/backup_extras.dart +++ b/lib/data/backup_extras.dart @@ -68,6 +68,10 @@ const Map kSecretsNotBackedUp = { 'pair the band again on this phone', 'lib/ble/oura_link.dart': 'Oura pairing key is a credential; ' 'pair the ring again on this phone', + 'lib/ble/adapters/helio_strap.dart': 'Helio strap auth key is a credential ' + 'read from secure storage; enter the key again on this phone', + 'lib/ble/helio_strap_link.dart': 'Helio strap auth key is a credential; ' + 'pair the strap again on this phone', }; /// The app root reloads presentation controllers after AppState adopts prefs. diff --git a/lib/data/db.dart b/lib/data/db.dart index 2f6a6acba..464c6639e 100644 --- a/lib/data/db.dart +++ b/lib/data/db.dart @@ -53,6 +53,8 @@ import 'backup_extras.dart'; import '../models/activity_suggestion.dart'; import '../compute/accepted_naps.dart'; import '../compute/nap_edits.dart' show NapEditKind; +import '../compute/inputs/garmin_inputs.dart' show kHrCadenceSec; +import '../compute/manual_session.dart' show sampleSpansSec; import '../compute/vendor_sleep.dart' show VendorEpoch, VendorNight; import 'journal_fields.dart'; import 'live_coverage_policy.dart'; @@ -82,6 +84,10 @@ typedef DbRebuild = ({ typedef SessionHrReads = ({ Map> stats, Map> samples, + // Parallel to [samples]: the seconds each sample stands for, by its source + // (a wearable's minute HR vs a 1 Hz strap). Absent for a session whose + // samples are all 1 Hz. + Map> caps, }); // ── SUBSTRATE ADMISSION — the one predicate that decides what may become a @@ -160,8 +166,9 @@ String derivableSourceSql([String col = 'source']) => kDerivableSources.isEmpty /// The rows a read INSIDE one session window keeps, out of [rows]: every row /// of the window (`source`, `rec_ts`, `hr`), in any order. With no flagged-on -/// workout sensor ([LocalDb.sessionSensorSources]) in the window, exactly the -/// [derivableSourceSql] rows. With one, the session override as the derive +/// workout sensor ([LocalDb.sessionSensorSources]) in the window, the +/// [derivableSourceSql] rows, or (no band row either) the active wearable's +/// ([LocalDb.sessionWearableSource]). With one, the session override as the derive /// lays it over a wearable's day (`withStrapSessions`): the sensor that /// recorded most of the window (one, never two blended) from its first worn /// row to its last, and outside that span the active wearable's rows @@ -180,12 +187,26 @@ String derivableSourceSql([String col = 'source']) => kDerivableSources.isEmpty /// owner decides whether a strap may fill a band gap. List sessionWindowRows>(List rows) => _sessionWindowRowsFor(rows, sensors: LocalDb.sessionSensorSources, - wearable: LocalDb.sessionWearableSource); + wearable: LocalDb.sessionWearableSource, + wearableId: LocalDb.sessionWearableDeviceId); // Workers receive the flags explicitly; isolate-local statics start empty. List _sessionWindowRowsFor>( - List rows, {required Set sensors, required String? wearable}) { + List rows, + {required Set sensors, + required String? wearable, + String? wearableId}) { bool derivable(Object? s) => s == null || kDerivableSources.contains(s); + // The ACTIVE wearable's rows, by device: a forgotten device of the same + // adapter keeps its rows (`deleteDevice` leaves measurements), and its + // family alone would blend them in. A read that carries no device id + // (older callers) matches on the family as before. + bool isWearable(T r) => + wearable != null && + r['source'] == wearable && + (wearableId == null || + r['device_id'] == null || + r['device_id'] == wearableId); List plain() => [ for (final r in rows) if (derivable(r['source'])) r, @@ -199,7 +220,15 @@ List _sessionWindowRowsFor>( n[s] = (n[s] ?? 0) + 1; } } - if (n.isEmpty) return plain(); + // No band row and no workout sensor in the window: the active wearable's + // own rows score it, as they score the day it sits in (the wearable's + // substrate). Before this a wearable-only session read nothing at all. + if (n.isEmpty) { + return [ + for (final r in rows) + if (derivable(r['source']) || isWearable(r)) r, + ]; + } final owner = n.entries .reduce((a, b) => b.value > a.value || (b.value == a.value && '${b.key}'.compareTo('${a.key}') < 0) @@ -216,8 +245,7 @@ List _sessionWindowRowsFor>( return [ for (final r in rows) if (r['source'] == owner || - ((derivable(r['source']) || - (wearable != null && r['source'] == wearable)) && + ((derivable(r['source']) || isWearable(r)) && ((r['rec_ts'] as num) < lo! || (r['rec_ts'] as num) > hi!))) r, ]; @@ -255,6 +283,10 @@ class LocalDb { /// strap's span ([sessionWindowRows]). Null with none. static String? sessionWearableSource; + /// The active wearable's DEVICE id beside its adapter + /// ([sessionWearableSource]): a session reads that device's rows only. + static String? sessionWearableDeviceId; + static Future get instance async { final db = _db; // `_db != null` is NOT enough: Android can close the underlying @@ -1938,6 +1970,13 @@ class LocalDb { // See Sample.bandSleepState for the evidence that it varies and means // what it says. 'band_sleep_state': 'INTEGER', + // A wearable's OWN RMSSD (ms) and breathing-rate (breaths/min) + // readings, as raw timestamped samples ([NeutralSample.deviceRmssdMs]). + // Policy exception PE-1: read ONLY by device_night_samples.dart, for an + // admitted family. Nullable, no default: a row without one did not + // report it. + 'dev_rmssd_ms': 'REAL', + 'dev_resp_brpm': 'REAL', }; final have = await _columnsOf(db, 'decoded_onehz'); if (have.isEmpty) return; // table not created yet — the DDL carries them @@ -3763,6 +3802,23 @@ class LocalDb { /// /// Ordered by `attribution, name` so the same day renders in the same order /// on every build. + /// [deviceId]'s own step count for [date] (`observation` key 'steps'), or + /// null. The one observation a derive reads: a wearable's pedometer total, + /// served as the day's steps by owner decision 2026-11-22 + /// (ADDING_A_DEVICE.md §4.2). Never a baseline input. + static Future deviceDaySteps(String deviceId, String date) async { + final rows = await (await instance).query( + 'observation', + columns: ['value'], + where: "device_id = ? AND date = ? AND key = 'steps' AND value > 0", + whereArgs: [deviceId, date], + orderBy: 'ts_ms DESC', + limit: 1, + ); + final v = rows.isEmpty ? null : rows.first['value']; + return v is num ? v.round() : null; + } + static Future>> observationsForDay( String date, ) async { @@ -7843,9 +7899,15 @@ class LocalDb { /// [_queueDecodedOneHz]. The union of `hrs_link._flush` and /// `oura_link._commit`'s bodies, not new logic — see M1 spec §9.3. /// - /// REPLACE, not IGNORE, for the same reason [_queueDecodedOneHz] uses it: a - /// re-read of the same range is idempotent by design on a fetch-by-cursor - /// band. + /// Newest wins, PER FIELD: a sample carries only what it measured (null = + /// "this sample has no heart rate", not "the second had none"), so two + /// samples for the same second (a strap's HR record and its temperature + /// record, both stamped on the same minute) MERGE instead of the later one + /// replacing the row and nulling the earlier one's column. A field the new + /// sample does carry overwrites, so a re-read of the same range is still + /// idempotent and a fresh value still beats a stale one. INSERT OR IGNORE + + /// UPDATE COALESCE rather than an upsert: `ON CONFLICT DO UPDATE` needs + /// SQLite 3.24 and Android 8 ships 3.18. /// /// `beat_ts_ms` is [NeutralSample.beatTsMs] when the host timed the beats /// (an arrival-stamped strap, off its own beat chain), NULL otherwise. @@ -7874,12 +7936,26 @@ class LocalDb { // follows for hr/accel/optical. 'hr': n.hr, 'skin_temp_c': n.skinTempC, + 'dev_rmssd_ms': n.deviceRmssdMs, + 'dev_resp_brpm': n.deviceRespBrpm, 'device_family': deviceFamily, 'source': deviceFamily, }, - conflictAlgorithm: ConflictAlgorithm.replace, + conflictAlgorithm: ConflictAlgorithm.ignore, ); - var ops = 1; + batch.rawUpdate( + 'UPDATE decoded_onehz SET hr = COALESCE(?, hr), ' + 'skin_temp_c = COALESCE(?, skin_temp_c), ' + 'dev_rmssd_ms = COALESCE(?, dev_rmssd_ms), ' + 'dev_resp_brpm = COALESCE(?, dev_resp_brpm), rec_ts = ?, counter = 0, ' + 'device_family = ?, source = ? WHERE device_id = ? AND ts_ms = ?', + [n.hr, n.skinTempC, n.deviceRmssdMs, n.deviceRespBrpm, recTs, + deviceFamily, deviceFamily, deviceId, recTs * 1000], + ); + var ops = 2; + // A sample with no heart side (a temperature record) leaves the second's + // beats alone: they belong to the HR sample it merged with. + if (n.hr == null && n.rrMs.isEmpty) return ops; // SCOPED TO THE WRITING DEVICE. Clear the second before reinserting so a // shrinking beat count can't strand stale high-index beats — same // reasoning as _queueRrBeats, and it must run even when this sample @@ -10038,6 +10114,7 @@ class LocalDb { double? rmssd, double? readiness, Map series = const {}, + Set clearIfAbsent = const {}, // WHO produced these scalars — 'band' for a day this app derived from 1 Hz // records, a vendor tag for an importer. NULL is the default and means // UNKNOWN; it is never filled in with a guess, because the whole point of @@ -10107,6 +10184,21 @@ class LocalDb { // baseline reads via metric_series. The next successful (non-partial) // pass writes the real value once it lands. if (!partial) { + // [clearIfAbsent]: keys this write OWNS, so absence means "no + // longer". PE-1's device night RMSSD exists only on a day an admitted + // device's readings produced it; a re-derive that no longer does (the + // day now belongs to another wearable, or its readings stopped + // passing the gate) takes the old row and its method label with it, + // or that device's baseline keeps reading a night it no longer owns. + // Only the full derive passes it: a backfill writing one key must not + // clear the rest. + for (final key in clearIfAbsent) { + if (reviewedSeries.containsKey(key)) continue; + await txn.delete('metric_series', + where: 'date = ? AND key = ?', whereArgs: [dayId, key]); + await txn.delete('metric_method', + where: 'date = ? AND key = ?', whereArgs: [dayId, key]); + } for (final e in reviewedSeries.entries) { await txn.insert('metric_series', { 'date': dayId, @@ -10736,6 +10828,17 @@ class LocalDb { 'FROM decoded_onehz WHERE rec_ts BETWEEN ? AND ?', [fromSec, toSec], ); + // The neutral path updates a second IN PLACE (per-field merge), which + // can keep the count, the rowids and every column total ([60,180] -> + // [120,120]); the triggers' per-bucket revision counters cannot. + if (await has('input_rev')) { + await add( + 'input_rev', + 'SELECT bucket, rev FROM input_rev WHERE bucket BETWEEN ? AND ? ' + 'ORDER BY bucket', + [fromSec ~/ 900, toSec ~/ 900], + ); + } await add( 'rr', 'SELECT COUNT(*), TOTAL(rowid), MAX(rowid), TOTAL(rr_ms), ' @@ -10854,6 +10957,14 @@ class LocalDb { 'FROM $_rawArchiveLegacy WHERE device_id = ?' : ''})', [wearableDeviceId, if (legacyArchive) wearableDeviceId], ); + // Its own daily step count is the day's steps when it counted more + // ([deviceDaySteps]), and a sync can bring a new count with no new HR. + await add( + 'wearable_steps', + "SELECT ts_ms, value FROM observation WHERE device_id = ? " + "AND date = ? AND key = 'steps' ORDER BY ts_ms", + [wearableDeviceId, dayId], + ); } await add( 'baselines', @@ -11545,6 +11656,13 @@ class LocalDb { whereArgs: [dayId], ); await copyRows('metric_method', where: 'date = ?', whereArgs: [dayId]); + // A wearable's own daily step count is a derive input + // ([deviceDaySteps]); without it the exported day re-derives with + // a different total. Only that row, not the rest of the device's + // observations. + await copyRows('observation', + where: "date = ? AND key = 'steps' AND device_id IS NOT NULL", + whereArgs: [dayId]); await copyRows('journal', where: 'date = ?', whereArgs: [dayId]); await copyRows('journal_metric', where: 'date = ?', whereArgs: [dayId]); await copyRows('cycle_log', where: 'date = ?', whereArgs: [dayId]); @@ -11690,6 +11808,13 @@ class LocalDb { where: 'ts >= ? AND ts < ?', whereArgs: [startSec, endSec], ); + // A wearable's own daily step count is a derive input now + // ([deviceDaySteps]): deleting the day deletes it. + deleted += await txn.delete( + 'observation', + where: "date = ? AND key = 'steps' AND device_id IS NOT NULL", + whereArgs: [dayId], + ); // CASCADE the GPS route and the typed sets BEFORE their session row // disappears — otherwise the join key is gone and every lat/lng point // of a deleted run (and every logged set) stays on disk forever. Must @@ -16113,7 +16238,7 @@ class LocalDb { int toTs, ) async { final db = await instance; - if (sessionSensorSources.isEmpty) { + if (sessionSensorSources.isEmpty && sessionWearableSource == null) { return db.query( 'decoded_onehz', columns: ['rec_ts', 'hr'], @@ -16125,7 +16250,7 @@ class LocalDb { } final rows = await db.query( 'decoded_onehz', - columns: ['rec_ts', 'hr', 'source'], + columns: ['rec_ts', 'hr', 'source', 'device_id'], where: 'rec_ts >= ? AND rec_ts <= ?', whereArgs: [fromTs, toTs], orderBy: 'rec_ts ASC', @@ -16153,9 +16278,12 @@ class LocalDb { /// window once and construct its stats and samples together in a worker. static Future sessionHrReads(int from, int to, {int maxHrCeiling = 0, int minHrFloor = 0}) async { - if (sessionSensorSources.isEmpty) { + // The band-only SQL joins, unless a sensor or the active wearable may + // own a window ([sessionWindowRows]). + if (sessionSensorSources.isEmpty && sessionWearableSource == null) { return (stats: await _sessionHrStatsSql(from, to, maxHrCeiling, minHrFloor), - samples: await _sessionHrSamplesSql(from, to)); + samples: await _sessionHrSamplesSql(from, to), + caps: const >{}); } return _sessionWindows(from, to, maxHrCeiling, minHrFloor); } @@ -16172,7 +16300,9 @@ class LocalDb { ) async { final db = await instance; final rows = await db.rawQuery( - 'SELECT s.id AS id, d.source AS source, d.rec_ts AS rec_ts, d.hr AS hr ' + 'SELECT s.id AS id, d.source AS source, d.device_id AS device_id, ' + 'd.rec_ts AS rec_ts, d.hr AS hr, ' + 'COALESCE(s.end_ts, s.start_ts) AS end_ts ' 'FROM sessions s ' 'JOIN decoded_onehz d ON d.rec_ts >= s.start_ts ' ' AND d.rec_ts <= COALESCE(s.end_ts, s.start_ts) ' @@ -16182,8 +16312,10 @@ class LocalDb { ); final sensors = {...sessionSensorSources}; final wearable = sessionWearableSource; + final wearableId = sessionWearableDeviceId; (SessionHrReads, String) construct() => _prepareSessionWindows( - rows, sensors, wearable, maxHrCeiling, minHrFloor); + rows, sensors, wearable, maxHrCeiling, minHrFloor, + wearableId: wearableId); final result = debugDisableSessionWindowsWorker ? construct() : await runCancellableIsolate(construct, const Duration(seconds: 30), @@ -16194,7 +16326,7 @@ class LocalDb { static (SessionHrReads, String) _prepareSessionWindows( List> rows, Set sensors, String? wearable, - int maxHrCeiling, int minHrFloor) { + int maxHrCeiling, int minHrFloor, {String? wearableId}) { final by = >>{}; for (final r in rows) { final id = r['id'] as String?; @@ -16202,14 +16334,27 @@ class LocalDb { } final stats = >{}; final samples = >{}; + final caps = >{}; for (final MapEntry(key: id, value: rs) in by.entries) { - final hr = [ + final kept = [ for (final r in _sessionWindowRowsFor(rs, - sensors: sensors, wearable: wearable)) - if (((r['hr'] as num?) ?? 0) > 0) (r['hr'] as num).toInt(), + sensors: sensors, wearable: wearable, wearableId: wearableId)) + if (((r['hr'] as num?) ?? 0) > 0) r, ]; + final hr = [for (final r in kept) (r['hr'] as num).toInt()]; if (hr.isEmpty) continue; samples[id] = hr; + final c = [for (final r in kept) kHrCadenceSec[r['source']] ?? 1]; + if (c.any((v) => v > 1)) caps[id] = c; + // The seconds each row stands for: its cadence, clipped at the next + // kept row (a strap taking over mid-minute) and the session's end. + final spans = c.any((v) => v > 1) + ? sampleSpansSec([for (final r in kept) (r['rec_ts'] as num).toInt()], + capsSec: c, endSec: (rs.first['end_ts'] as num?)?.toInt()) + : null; + final covered = spans == null + ? hr.length + : spans.fold(0, (a, b) => a + b); final low = [ for (final h in hr) if (minHrFloor <= 0 || h >= minHrFloor) h, @@ -16220,12 +16365,20 @@ class LocalDb { ]; stats[id] = { 'n': hr.length, - 'avg_hr': hr.fold(0, (a, b) => a + b) / hr.length, + // Weighted by each row's cadence when the window mixes a minute-HR + // wearable with a 1 Hz strap; all 1 s reads exactly as before. + 'avg_hr': spans != null + ? [for (var i = 0; i < hr.length; i++) hr[i] * spans[i]] + .fold(0, (a, b) => a + b) / + covered + : hr.fold(0, (a, b) => a + b) / hr.length, + // Seconds covered, for the read-side guard against a banked trace. + 'covered': covered, 'min_hr': low.isEmpty ? 0 : low.reduce((a, b) => a < b ? a : b), 'max_hr': high.isEmpty ? 0 : high.reduce((a, b) => a > b ? a : b), }; } - return ((stats: stats, samples: samples), + return ((stats: stats, samples: samples, caps: caps), Isolate.current.debugName ?? 'unnamed'); } @@ -16245,7 +16398,7 @@ class LocalDb { int maxHrCeiling = 0, int minHrFloor = 0, }) async { - if (sessionSensorSources.isNotEmpty) { + if (sessionSensorSources.isNotEmpty || sessionWearableSource != null) { return (await sessionHrReads(fromTs, toTs, maxHrCeiling: maxHrCeiling, minHrFloor: minHrFloor)).stats; } @@ -16294,7 +16447,7 @@ class LocalDb { int fromTs, int toTs, ) async { - if (sessionSensorSources.isNotEmpty) { + if (sessionSensorSources.isNotEmpty || sessionWearableSource != null) { return (await sessionHrReads(fromTs, toTs)).samples; } return _sessionHrSamplesSql(fromTs, toTs); diff --git a/lib/data/local_repository_impl.dart b/lib/data/local_repository_impl.dart index e147b4aab..40bda58bf 100644 --- a/lib/data/local_repository_impl.dart +++ b/lib/data/local_repository_impl.dart @@ -26,6 +26,7 @@ import '../compute/findings.dart' show servedReadiness; import '../compute/hr_max.dart'; import '../compute/inputs/canonical.dart' show deviceFlagOn, withoutWearableEstimates; +import '../compute/inputs/garmin_inputs.dart' show kHrCadenceSec; import '../compute/manual_session.dart'; import '../compute/onehz_pipeline.dart' show kUnknownAbsenceNote, needInputNote; import '../compute/profile.dart'; @@ -2495,8 +2496,7 @@ class LocalRepositoryImpl extends LocalRepository { // session, so it must not replace the banked full-window avg/peak. final banked = { for (final r in rows) - if (r['trace_samples'] is num) - r['id']: (r['trace_samples'] as num).toInt(), + r['id']: ?_bankedSeconds(r), }; // Per-session HR aggregates from the 1 Hz substrate (one indexed join). @@ -2504,7 +2504,7 @@ class LocalRepositoryImpl extends LocalRepository { // "no data" (avg_hr == 0) even when the window is full of worn HR. try { final age = _profileAge(); - final (:stats, samples: rawBySession) = await LocalDb.sessionHrReads( + final (:stats, samples: rawBySession, :caps) = await LocalDb.sessionHrReads( fromTs, nowSec, maxHrCeiling: hrCeilingForAge(age), @@ -2517,13 +2517,15 @@ class LocalRepositoryImpl extends LocalRepository { final s = stats[w['id']]; final raw = rawBySession[w['id']]; final b = banked[w['id']]; - if (b != null && (s?['n'] ?? 0) < b) continue; + if (b != null && (s?['covered'] ?? s?['n'] ?? 0) < b) continue; if (s != null && (s['n'] ?? 0) != 0) { w['avg_hr'] = (s['avg_hr'] as num).round(); } // Peak: smoothed-from-raw (authoritative, matches the detail screen); // else stored column, else the ceiling-bounded SQL max. - final smax = raw == null ? null : smoothedMaxHr(raw, age: age); + // Each source at its own cadence, as the scorer and detail read. + final smax = + raw == null ? null : cadenceAwareMaxHrAt(raw, caps[w['id']], age: age)?.$1; if (smax != null) { w['max_hr'] = smax; } else if (s != null && (s['n'] ?? 0) != 0) { @@ -2627,13 +2629,26 @@ class LocalRepositoryImpl extends LocalRepository { // has cut into this window and only its tail is left. Redrawing from that // would swap the full session for its cooldown, so serve the banked trace // until the substrate is at least as complete as it. - final banked = (row['trace_samples'] as num?)?.toInt(); - if (hrRows.isNotEmpty && (banked == null || hrRows.length >= banked)) { - final ts = [for (final e in hrRows) (e['rec_ts'] as num).toInt()]; - final hr = [for (final e in hrRows) (e['hr'] as num).toInt()]; + final banked = _bankedSeconds(row); + final ts = [for (final e in hrRows) (e['rec_ts'] as num).toInt()]; + final hr = [for (final e in hrRows) (e['hr'] as num).toInt()]; + final c = _cadencesOf(hrRows); + // The seconds each row stands for, clipped as the scorer clips them. + final spans = c.any((v) => v > 1) + ? sampleSpansSec(ts, capsSec: c, endSec: endTs) + : null; + final covered = + spans == null ? hrRows.length : spans.fold(0, (a, b) => a + b); + if (hrRows.isNotEmpty && (banked == null || covered >= banked)) { w.addAll(_sessionTrace(ts, hr, startTs, endTs, - row['device_family'] as String?, await _zoneAnchors())); - final avg = hr.reduce((a, b) => a + b) / hr.length; + row['device_family'] as String?, await _zoneAnchors(), + caps: _cadencesOf(hrRows))); + // Weighted the same way the scorer and the list weight it. + final avg = spans != null + ? [for (var i = 0; i < hr.length; i++) hr[i] * spans[i]] + .fold(0, (a, b) => a + b) / + covered + : hr.reduce((a, b) => a + b) / hr.length; w['avg_hr'] = avg.round(); if (w['status'] == 'done') { final curve = await _recoveryCurve(endTs); @@ -2670,8 +2685,9 @@ class LocalRepositoryImpl extends LocalRepository { int startTs, int endTs, String? deviceFamily, - _ZoneAnchors anchors, - ) { + _ZoneAnchors anchors, { + List? caps, + }) { final w = {}; w['hr'] = _minuteHrCurve(ts, hr); // Spike-suppressed trough (issue #127): a lone low PPG dropout must not @@ -2680,20 +2696,32 @@ class LocalRepositoryImpl extends LocalRepository { // Spike-suppressed peak (issue #127). RECOMPUTE from the smoothed raw — // do NOT floor against the stored column: the live path may already have // written a spiked max there, and math.max() would preserve it. - final peakAt = smoothedMaxHrAt(hr, age: _profileAge()); + // Each source smoothed at its own cadence, as the scorer did. + final peakAt = cadenceAwareMaxHrAt(hr, caps, age: _profileAge()); if (peakAt != null) { w['max_hr'] = peakAt.$1; w['time_to_peak_min'] = ((ts[peakAt.$2] - startTs) / 60).round(); } - w['zone_bands'] = _zoneBands(hr, deviceFamily, anchors); + // Weighted by the seconds each sample stands for, as the stored split + // is: a wearable's minute HR is a minute a sample, not a second. + w['zone_bands'] = _zoneBands(hr, deviceFamily, anchors, + spans: caps == null + ? null + : sampleSpansSec(ts, capsSec: caps, endSec: endTs)); final drift = _hrDriftPct(ts, hr, startTs, endTs); if (drift != null) w['hr_drift_pct'] = drift; w['trace_samples'] = hr.length; + // Seconds covered, not samples: a minute-HR sample covers a minute. + final covered = caps == null + ? hr.length + : sampleSpansSec(ts, capsSec: caps, endSec: endTs) + .fold(0, (a, b) => a + b); + w['trace_seconds'] = covered; final windowSec = endTs - startTs; if (windowSec > 0) { w['trace_coverage_pct'] = math.min( 100, - (hr.length / windowSec * 100).round(), + (covered / windowSec * 100).round(), ); } return w; @@ -2765,17 +2793,20 @@ class LocalRepositoryImpl extends LocalRepository { List> _zoneBands( List hr, String? deviceFamily, - _ZoneAnchors anchors, - ) { + _ZoneAnchors anchors, { + List? spans, + }) { final set = _zoneSetFor(deviceFamily, anchors); // No age, or a strap with no calibrated ceiling ⇒ no bands. if (set == null) return const []; final secs = List.filled(5, 0); - for (final v in hr) { - final z = set.zoneNumber(v.toDouble()); - if (z >= 1) secs[z - 1]++; + for (var i = 0; i < hr.length; i++) { + final z = set.zoneNumber(hr[i].toDouble()); + if (z >= 1) secs[z - 1] += spans?[i] ?? 1; } - final total = hr.length; + final total = spans == null + ? hr.length + : spans.fold(0, (a, b) => a + b); return [ for (var z = 0; z < 5; z++) { @@ -3158,6 +3189,26 @@ class LocalRepositoryImpl extends LocalRepository { /// calories come from the whole-day substrate independently. So there is no /// analytics output to invalidate here and no `kAlgoVersion` bump to make; /// the next ordinary derive picks up the exclusion on its own. + /// Each HR row's own sampling interval, by the source that stored it: a + /// wearable's minute (or 5-minute) HR, 1 s for the band and a strap. A + /// window can hold both, so one interval for the whole window is wrong. + /// The seconds a session's banked trace covered: `trace_seconds` from the + /// trace itself, else `trace_samples` (a trace from before that field was + /// 1 Hz, so its sample count is its seconds). Null with no trace. + static int? _bankedSeconds(Map row) { + try { + final j = row['trace_json']; + final t = j is String && j.isNotEmpty ? jsonDecode(j) : null; + final sec = t is Map ? t['trace_seconds'] : null; + if (sec is num) return sec.toInt(); + } catch (_) {} + return (row['trace_samples'] as num?)?.toInt(); + } + + static List _cadencesOf(List> rows) => [ + for (final r in rows) kHrCadenceSec[r['source']] ?? 1, + ]; + Future> _writeManualSession({ required int startTs, required int endTs, @@ -3204,6 +3255,8 @@ class LocalRepositoryImpl extends LocalRepository { final stats = computeManualSessionStats( hrTs: hrTs, hrBpm: hrBpm, + hrCadenceSec: _cadencesOf(hrRows), + endSec: endTs, profile: profile, hrMax: _profileMaxHr(deviceFamily)?.toDouble(), restingHr: restingHr, @@ -3340,6 +3393,8 @@ class LocalRepositoryImpl extends LocalRepository { final stats = computeManualSessionStats( hrTs: [for (final e in hrRows) (e['rec_ts'] as num).toInt()], hrBpm: hrBpm, + hrCadenceSec: _cadencesOf(hrRows), + endSec: endTs, profile: profile, hrMax: hrMaxForSession, restingHr: restingHrForSession, @@ -3353,12 +3408,12 @@ class LocalRepositoryImpl extends LocalRepository { // (#127), instead of the raw peak being re-smoothed here and banked raw // everywhere else. Nothing to re-wrap. - // "Complete" = the band has handed over essentially the whole window. - // 1 Hz means one sample per second, so sample count vs window seconds is - // the coverage ratio; 90% absorbs the usual handful of dropped seconds. + // "Complete" = the whole window was handed over: the seconds the samples + // stand for (one each at 1 Hz, a minute each for a wearable's minute + // HR) against the window; 90% absorbs the usual handful of drops. final windowSec = endTs - startTs; final complete = - windowSec > 0 && stats.hrSampleCount >= (windowSec * 0.9).floor(); + windowSec > 0 && stats.coveredSec >= (windowSec * 0.9).floor(); final merged = reconcileSessionScore( substrateIsComplete: complete, @@ -3382,9 +3437,19 @@ class LocalRepositoryImpl extends LocalRepository { // when coverage IMPROVED. Rewrite only when this pass saw MORE seconds // than the stored trace was built from — a later pass with a thinner // window (a partial re-drain) must never overwrite a fuller trace. - final storedSamples = (row['trace_samples'] as num?)?.toInt(); - final needsTrace = - storedSamples == null || stats.hrSampleCount > storedSamples; + // In SECONDS covered, not samples: 60 minute-HR samples are an hour, + // 600 dense ones ten minutes. A trace stored before `trace_seconds` + // existed was 1 Hz, so its sample count is its seconds. + Object? storedTrace; + try { + final j = row['trace_json']; + storedTrace = j is String && j.isNotEmpty ? jsonDecode(j) : null; + } catch (_) {} + final storedSec = (storedTrace is Map + ? (storedTrace['trace_seconds'] as num?)?.toInt() + : null) ?? + (row['trace_samples'] as num?)?.toInt(); + final needsTrace = storedSec == null || stats.coveredSec > storedSec; // `identical`, not `==`: `reconcileSessionScore` returns one of the two // vectors it was handed, so identity IS the answer to which side won — // the same test its own `changed` flag is built on. @@ -3430,6 +3495,7 @@ class LocalRepositoryImpl extends LocalRepository { endTs, row['device_family'] as String?, await _zoneAnchors(), + caps: _cadencesOf(hrRows), ); // The post-end recovery window is outside the session and outside the // rows read above, so it costs one more bounded (~205 s) read — only on @@ -3579,9 +3645,16 @@ class LocalRepositoryImpl extends LocalRepository { // next drain — the one carrying the REST of that window — skipped it. // The partial score then stood on the list until someone opened the // detail screen, which is exactly the case the sweep exists for. + // Only a window the BAND fully scored is settled: the frontier is + // the band's, so an empty read (nothing arrived yet) or one carrying + // a sensor's or a wearable's rows (they arrive on their own syncs, + // behind no frontier) is read again next sweep. + final rows = after.hrRows; if (key != null && endTs! <= frontier && - after.hrRows != null && + rows != null && + rows.isNotEmpty && + rows.every((e) => e['source'] == null) && (r['status']?.toString() ?? '') == 'done') { _rescoredSessions.add(key); } diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index f2c9b0915..6aafdce9f 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -303,6 +303,9 @@ "pairSensorKeyTitle": "Schon anderswo eingerichtet?", "pairSensorKeyBody": "Wenn du den Schlüssel kennst, den dieses Gerät bereits verwendet, füge ihn hier ein. So lässt sich das Gerät ohne Zurücksetzen auf Werkseinstellungen koppeln; auf das Gerät werden dabei keine Daten geschrieben. Du kannst mehrere Schlüssel eingeben, jeweils einen pro Zeile. Sie werden nacheinander ausprobiert, bis einer akzeptiert wird. Lass das Feld leer, um die normale Kopplung zu verwenden.", "pairSensorKeyHint": "32 Hex-Zeichen oder Base64 — ein Schlüssel pro Zeile", + "pairSensorKeyRequiredTitle": "Geräteschlüssel", + "pairSensorKeyRequiredBody": "Dieses Gerät lässt sich nur mit dem Schlüssel koppeln, den seine eigene App eingerichtet hat. Füge diesen einen Schlüssel ein: 32 Hex-Ziffern.", + "pairSensorKeyRequiredHint": "32 Hex-Ziffern", "pairSensorSearchAnyway": "Trotzdem suchen", "devicePickerTitle": "Geräte verbinden", "devicePickerSubtitle": "Verbinde, was du nutzt. Weitere kannst du jederzeit hinzufügen.", @@ -521,7 +524,7 @@ "readinessDetailLastNDays": "{n, plural, one{Letzter {n} Tag} other{Letzte {n} Tage}}", "readinessDetailNoHistoryTitle": "Noch kein Verlauf der Erholung", "readinessDetailNoHistoryBody": "Bisher wurde kein Tag ausgewertet.", - "readinessDetailWearOvernight": "Trage das Band über Nacht", + "readinessDetailWearOvernight": "Trage dein Gerät über Nacht", "readinessDetailUnit": "/100", "readinessDetailDaysAgo": "{n, plural, one{vor {n} Tag} other{vor {n} Tagen}}", "readinessDetailToday": "Heute", @@ -534,6 +537,7 @@ "readinessDetailNotAvailable": "nicht verfügbar", "readinessDetailContributionNotReported": "Beitrag nicht angegeben", "readinessDetailRelativeUncalibrated": "relativ, unkalibriert", + "readinessDetailFromDeviceReadings": "aus den eigenen Messwerten deines Geräts", "readinessDetailWithinSpread": "innerhalb deiner üblichen Spanne", "readinessDetailOutsideRange": "nein, außerhalb deines üblichen Bereichs", "readinessDetailLiftingScore": "hebt deinen Score", @@ -603,7 +607,7 @@ "driverBreakdownAbsenceAlgoVersion": "Die Berechnung der Tagesform hat sich mit dem letzten Update geändert und wird gerade neu durchgeführt.", "driverBreakdownAbsenceStale": "Die letzte Auswertung ist zu alt, um sich darauf zu verlassen.", "driverBreakdownAbsenceNoVersion": "Deine Trends werden gerade aktualisiert. Das dauert nach einer Synchronisierung etwa eine Minute.", - "driverBreakdownSyncTheBand": "Band synchronisieren", + "driverBreakdownSyncTheBand": "Gerät synchronisieren", "driverBreakdownAbsenceNoReason": "Aus den gespeicherten Daten geht nicht hervor, warum es für die letzte Nacht keine Aufschlüsselung gibt.", "coachFiguresCouldNotBeDrawn": "Eine Abbildung konnte nicht gezeichnet werden", "coachFiguresNoType": "Der Coach hat eine Abbildung ohne Typ gesendet.", @@ -623,7 +627,7 @@ "circadianDetailTitle": "Innere Uhr", "circadianDetailNoNightsTitle": "Noch keine Nächte zum Darstellen", "circadianDetailNoNightsBody": "0 Nächte ausgewertet.", - "circadianDetailNoNightsFix": "Band über Nacht tragen", + "circadianDetailNoNightsFix": "Gerät über Nacht tragen", "circadianDetailSleepTitle": "Schlaf, Nacht für Nacht", "circadianDetailAsleep": "Schlaf", "circadianDetailSleepFootnote": "{count, plural, one{{count} Nacht, eine Spalte pro Nacht. Je dunkler, desto mehr wurde in dieser Stunde geschlafen.} other{{count} Nächte, eine Spalte pro Nacht. Je dunkler, desto mehr wurde in dieser Stunde geschlafen.}}", @@ -1219,7 +1223,8 @@ "metricDetailNoValueYet": "Für heute liegt noch kein Wert vor.", "metricDetailNoValueYetWiderRanges": "Für heute liegt noch kein Wert vor. In den längeren Zeiträumen oben findest du die Tage mit Werten.", "metricDetailNoValueInWindow": "Für keinen Tag in diesem Zeitraum gibt es einen Wert.", - "metricDetailWearBandFix": "Trag das Band über Nacht, damit die Aufzeichnung beginnt", + "metricDetailWearBandFix": "Trag dein Gerät über Nacht, damit die Aufzeichnung beginnt", + "metricDetailHrvNeedsBeatsFix": "Dieses Diagramm braucht nachts aufgezeichnete Schlag-zu-Schlag-Intervalle, die nur ein Gerät liefert, das Herzschläge aufzeichnet. Ein Brustgurt zeichnet nur beim Training auf, und viele Uhren, Ringe und Bänder melden stattdessen ihre eigene HRV: Sie steht auf ihrer Geräteseite", "metricDetailBreakdownLinkTitle": "Aufschlüsselung", "metricDetailBreakdownLinkSub": "Jeder Abschnitt des Tages und was ihn gezählt hat", "metricDetailNerdStatsTitle": "Detailwerte", @@ -1430,7 +1435,7 @@ "healthCoverageOf": "{pct} % von {day}", "healthNothingMeasuredDay": "Für diesen Tag wurde nichts gemessen", "healthNoBandRecordings": "Für diesen Tag sind keine Daten vom Band angekommen.", - "healthSyncTheBand": "Band synchronisieren", + "healthSyncTheBand": "Gerät synchronisieren", "healthDeepDivesTitle": "Detailanalysen", "healthHeartRateVariability": "Herzfrequenzvariabilität", "healthTimeFrequencyNonLinear": "Zeit, Frequenz und nichtlinear", @@ -1500,6 +1505,7 @@ "homeStepSensorStrapPhone": "Band + Smartphone", "homeStepSensorStrap": "Band", "homeStepSensorPhone": "Smartphone", + "homeStepSensorDevice": "Gerät", "homeOvernightBuilding": "Die letzte Nacht wird noch ausgewertet.", "homeOvernightNothingYet": "Von letzter Nacht ist noch nichts in der App angekommen.", "homeMonthJanuary": "Januar", @@ -1554,7 +1560,7 @@ "homeInsightsStaleOverWeek": "Die letzte Auswertung wurde vor über einer Woche erstellt – zu alt, um sich darauf zu verlassen.", "homeInsightsStaleOnDay": "Die letzte Auswertung wurde am {day} erstellt – zu alt, um sich darauf zu verlassen.", "homeInsightsNoVersionStamp": "Deine Trends werden gerade aktualisiert. Das dauert nach einer Synchronisierung etwa eine Minute.", - "homeSyncBand": "Band synchronisieren", + "homeSyncBand": "Gerät synchronisieren", "homeCalibrating": "Wird kalibriert", "homeCalibratingNights": "{have} von {need} Nächten", "homeCalibratingDays": "{have} von {need} Tagen", @@ -1648,7 +1654,7 @@ "wellnessLoadFailedBody": "Die gespeicherten Daten konnten nicht gelesen werden. Es wurde nichts gelöscht – das ist ein Ladefehler, es fehlen keine Daten.", "homeTryAgain": "Erneut versuchen", "homeNothingDerivedTitle": "Noch nichts ausgewertet", - "homeNothingDerivedBody": "Trag das Band heute Nacht und öffne die App am Morgen.", + "homeNothingDerivedBody": "Trag dein Gerät heute Nacht und öffne die App am Morgen.", "homeSyncedThrough": "Synchronisiert bis {when}", "homeSyncedNever": "Noch keine Daten vom Band", "homeSyncedTimeUnknown": "Banddaten, Uhr nicht gestellt", @@ -1840,7 +1846,7 @@ "sleepDetailNavTitle": "Schlaf", "sleepDetailNoNightTitle": "Keine Nacht vorhanden", "sleepDetailNoNightBody": "Keine Aufzeichnung des Bands ist lang genug für eine Auswertung.", - "sleepDetailNoNightFix": "Trage das Band über Nacht und synchronisiere es am Morgen", + "sleepDetailNoNightFix": "Trage dein Gerät über Nacht und synchronisiere es am Morgen", "sleepDetailStagesSection": "Phasen", "sleepDetailVersusUsualSection": "Im Vergleich zu sonst", "sleepDetailUnusualLastNight": "Auffällig letzte Nacht", @@ -2060,6 +2066,7 @@ "activitySetupHeartRateLabel": "Herzfrequenz", "activitySetupBandConnected": "Band verbunden", "activitySetupNoBandConnected": "Kein Band verbunden", + "activitySetupNoLiveHr": "Keine Live-Herzfrequenz", "activitySetupPrivateLabel": "Privates Training", "activitySetupWorkLabel": "Arbeit", "activitySetupRestLabel": "Pause", @@ -2095,7 +2102,7 @@ "dayStrainNoMinuteTraceTitle": "Kein minütlicher Verlauf für diesen Tag", "dayStrainNoReasonBody": "Aus den gespeicherten Daten geht nicht hervor, warum es für diesen Tag keinen Strain gibt.", "dayStrainScoredNoTraceBody": "Der Tages-Strain beträgt {strain}. Die Wachminuten, aus denen er berechnet wurde, sind für diesen Tag nicht gespeichert.", - "dayStrainWearBandFix": "Trag das Band den ganzen Tag", + "dayStrainWearBandFix": "Trag dein Gerät den ganzen Tag", "dayStrainChartTitle": "STRAIN IM TAGESVERLAUF", "dayStrainChartFootnote": "Belastung oberhalb deines üblichen Tempos im Wachzustand. Der Wert kann später wieder sinken, wenn du dich diesem Tempo wieder annäherst. Berechnet aus {drawn} aufgezeichneten Wachminuten.", "dayStrainPeakHr": "Max. Puls", @@ -2118,7 +2125,7 @@ "activityZonesNoCeilingTitle": "Noch kein gemessener Maximalpuls", "activityZonesNoCeilingTanakaTail": " Bis ein Maximalpuls gemessen wurde, werden die Zonen anhand deines Alters geschätzt.", "activityZonesNoCeilingDefaultBody": "Gezählt wird nur ein hoher Wert, den das Band während Bewegung 15 Sekunden lang gemessen hat. Eine Spitze von einer Sekunde ist keine Herzfrequenz.", - "activityZonesWearBandFix": "Trag das Band bei deinen üblichen harten Trainings", + "activityZonesWearBandFix": "Trag dein Gerät bei deinen üblichen harten Trainings", "activityZonesHighestSeenLabel": "HÖCHSTER GEMESSENER PULS", "activityZonesBpmUnit": "bpm", "activityZonesCeilingOnDate": "am {date}", @@ -2881,7 +2888,7 @@ "supplementCharging5f99fe": "Lädt", "supplementCoefficientOfVariationOfPerc71989": "Variationskoeffizient der Atemfrequenz je Zeitfenster über die Nacht.", "supplementColeKripkeWakeSpineHRVcd5f37": "Cole–Kripke-Wachgerüst + HRV-Einblendung", - "supplementCountedNeverModelledAStepc66896": "Gezählt, nie modelliert. Schritte stammen von einem Zähler, der den Gang erkennt: dem 100-Hz-Schrittzähler des Bands, während es streamt, oder dem deines Smartphones. Jeder Abschnitt des Tages wird von dem der beiden gezählt, der ihn tatsächlich aufgezeichnet hat, und ein Abschnitt, den beide abdecken, wird nur einmal gezählt – eine Einheit nimmt dem Sensor, der den Rest des Tages getragen hat, also nie den Tag weg. Es gibt keine Schätzung aus 1-Hz-Daten – die Schrittfrequenz beim Gehen liegt über dem, was ein Messwert pro Sekunde auflösen kann. Ein Tag ohne Zähler zeigt daher keine Schritte statt einer Schätzung.", + "supplementCountedNeverModelledAStepc66896": "Gezählt, nie modelliert. Schritte stammen von einem Zähler, der den Gang erkennt: dem 100-Hz-Schrittzähler des Bands, während es streamt, oder dem deines Smartphones. Jeder Abschnitt des Tages wird von dem der beiden gezählt, der ihn tatsächlich aufgezeichnet hat, und ein Abschnitt, den beide abdecken, wird nur einmal gezählt – eine Einheit nimmt dem Sensor, der den Rest des Tages getragen hat, also nie den Tag weg. Es gibt keine Schätzung aus 1-Hz-Daten – die Schrittfrequenz beim Gehen liegt über dem, was ein Messwert pro Sekunde auflösen kann. Ein Tag ohne Zähler zeigt daher keine Schritte statt einer Schätzung. Die eigene Tageszählung eines gekoppelten Wearables gilt als die Schritte des Tages, wenn sie mehr gezählt hat, und wird dann ganz übernommen, nie dazuaddiert.", "supplementCreatinined3029a": "Kreatinin", "supplementDailyRecoveryReadinessFromYourf995c0": "Dein täglicher Erholungsscore", "supplementDeepMin28f1fc": "Tiefschlaf (Min.)", @@ -3008,10 +3015,12 @@ "supplementTheHighestHeartRateHeldc1c878": "Deine bisher höchste Herzfrequenz liegt deutlich unter dem, was dein Alter erwarten lässt. Die Zonen bleiben daher bei der Altersschätzung, bis das Band eine härtere Belastung sieht.", "supplementTheLowestSustainedSleepingHeart72e5dd": "Die niedrigste anhaltende Herzfrequenz im Schlaf, ermittelt über ein gleitendes Fenster der nächtlichen Messreihe. Kein Einzelwert und kein Tagesminimum.", "supplementTheNightSMeanRaw25e383": "Der mittlere Sensor-Rohwert der Nacht, angegeben als Abstand zu deinen eigenen letzten Nächten. Nirgends wird in Grad umgerechnet.", + "supplementSkinTempMethodTrend": "Der mittlere Sensor-Rohwert der Nacht, angegeben als Abstand zu deinen eigenen letzten Nächten. Der gezeigte Verlauf ist dieser unkalibrierte ADC-Abstand, ohne Umrechnung in Grad. (Ein WHOOP 5 misst in echten Grad; seine nächtliche Abweichung wird stattdessen unter Vitalwerte in deiner Temperatureinheit angezeigt.)", "supplementTheRatioOfLowTo817781": "Das Verhältnis von nieder- zu hochfrequenter Leistung in der Variabilität der Schlagabstände, aus einem Lomb–Scargle-Periodogramm (die Reihe ist ungleichmäßig abgetastet, eine FFT wäre daher falsch).", "supplementThereIsNoRestingHeart36a9ca": "Es gibt keinen Ruhepuls aus einer bewerteten Nacht als Vergleich.", "supplementThereIsNoScoredNight5d353d": "Es gibt keine bewertete Nacht, aus der sich das ablesen lässt.", "supplementTheseRecordingsAreNotStamped66b52f": "Diese Aufzeichnungen sind nicht mit dem Band gekennzeichnet, von dem sie stammen, und dieser Wert muss je Band kalibriert werden. Er wird daher zurückgehalten statt geschätzt.", + "supplementNoCalibrationForThisDevice": "Dieser Wert muss je Gerät kalibriert werden, und für dieses gibt es noch keine Kalibrierung. Er wird daher zurückgehalten statt geschätzt.", "supplementThisDayCameFromAn2dc4b2": "Dieser Tag stammt aus einem Import, der nur die Nacht abdeckt. Für die Wachzeit ist daher nichts aufgezeichnet.", "supplementTimeAsleepAsAFraction516f7f": "Schlafzeit als Anteil der Zeit im Bett.", "supplementTimeToMove7afe98": "Zeit für Bewegung", @@ -3249,6 +3258,8 @@ "wearableMethodStrap": "einem Brustgurt, jede Sekunde", "wearableMethodStrapBeats": "den Schlag-zu-Schlag-Intervallen eines Brustgurts", "wearableMethodRhrStrapComposite": "Ruhepuls und den Schlag-zu-Schlag-Intervallen eines Brustgurts", + "wearableMethodDeviceHrvComposite": "Ruhepuls und den eigenen HRV-Messwerten des Geräts", + "wearableMethodDeviceRmssd": "den eigenen HRV-Messwerten des Geräts, über unsere Nacht", "wearableMethodRingBeats": "seinen eigenen Schlag-zu-Schlag-Intervallen", "wearableUnlocksTitle": "Was dieses Wearable freischaltet", "wearableUnlocksOurs": "Von uns gemessen", @@ -3423,7 +3434,7 @@ "homeBackToToday": "Zurück zu heute", "homeSomeDataMissingTitle": "Einige Daten von heute fehlen", "homeFirstWeekTitle": "Deine ersten Wochen", - "homeFirstWeekWear": "Trag das Band heute Nacht", + "homeFirstWeekWear": "Trag dein Gerät heute Nacht", "homeFirstWeekSleep": "Schlaf: am Morgen nach deiner ersten Nacht", "homeFirstWeekStrain": "Strain: ab Tag {day}", "homeFirstWeekRecovery": "Erholung: ab Nacht {night}, sobald dein Normalwert bekannt ist", diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index b0862a772..8aa7da6e0 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1328,6 +1328,18 @@ "@pairSensorKeyHint": { "description": "Hint text in the existing-key field." }, + "pairSensorKeyRequiredTitle": "Device key", + "@pairSensorKeyRequiredTitle": { + "description": "Key field title for a device that pairs only with a typed key." + }, + "pairSensorKeyRequiredBody": "This device pairs only with the key its own app set up. Paste that one key: 32 hex digits.", + "@pairSensorKeyRequiredBody": { + "description": "Key field body for a device that pairs only with one typed hex key." + }, + "pairSensorKeyRequiredHint": "32 hex digits", + "@pairSensorKeyRequiredHint": { + "description": "Key field hint for a device that pairs only with one typed hex key." + }, "pairSensorSearchAnyway": "Search anyway", "@pairSensorSearchAnyway": { "description": "iOS-gate status card fix." @@ -2456,7 +2468,7 @@ "@readinessDetailNoHistoryBody": { "description": "Status card body stating 0 days scored." }, - "readinessDetailWearOvernight": "Wear the band overnight", + "readinessDetailWearOvernight": "Wear your device overnight", "@readinessDetailWearOvernight": { "description": "Fix button label suggesting the user wear the band overnight." }, @@ -2531,6 +2543,10 @@ "@readinessDetailRelativeUncalibrated": { "description": "Breakdown row tag on the temperature input: it is a relative, uncalibrated sensor deviation." }, + "readinessDetailFromDeviceReadings": "from your device's own readings", + "@readinessDetailFromDeviceReadings": { + "description": "Breakdown row tag on the HRV input when it was the wearable's own RMSSD readings, not beat-derived." + }, "readinessDetailWithinSpread": "yes, within your usual range", "@readinessDetailWithinSpread": { "description": "Breakdown row tag: the input's change was within the user's usual spread (below the smallest-worthwhile-change threshold)." @@ -2889,7 +2905,7 @@ "@driverBreakdownAbsenceAlgoVersion": { "description": "Absence card body when the breakdown is missing because the algorithm version changed and is rebuilding." }, - "driverBreakdownAbsenceStale": "Your trends are out of date. Sync the band to update them.", + "driverBreakdownAbsenceStale": "Your trends are out of date. Sync your device to update them.", "@driverBreakdownAbsenceStale": { "description": "Absence card body when the last stored rollup is too old to show." }, @@ -2897,7 +2913,7 @@ "@driverBreakdownAbsenceNoVersion": { "description": "Absence card body when the stored rollup has no version stamp." }, - "driverBreakdownSyncTheBand": "Sync the band", + "driverBreakdownSyncTheBand": "Sync your device", "@driverBreakdownSyncTheBand": { "description": "Absence card action button: sync the band to refresh the rollup." }, @@ -2997,7 +3013,7 @@ "@circadianDetailNoNightsBody": { "description": "Empty-state body under circadianDetailNoNightsTitle" }, - "circadianDetailNoNightsFix": "Wear the band overnight", + "circadianDetailNoNightsFix": "Wear your device overnight", "@circadianDetailNoNightsFix": { "description": "Empty-state suggested fix action" }, @@ -5823,10 +5839,14 @@ "@metricDetailNoValueInWindow": { "description": "Empty-state body for a multi-day window with no value in it." }, - "metricDetailWearBandFix": "Wear the band overnight to start the series", + "metricDetailWearBandFix": "Wear your device overnight to start the series", "@metricDetailWearBandFix": { "description": "Empty-state fix suggestion telling the user to wear the band overnight." }, + "metricDetailHrvNeedsBeatsFix": "This chart needs beat-to-beat intervals recorded overnight, which only a device that records beats supplies. A chest strap records only during workouts, and many watches, rings and straps report their own HRV instead: it is on their device page", + "@metricDetailHrvNeedsBeatsFix": { + "description": "Empty HRV chart fix when no band is paired: the chart needs overnight beat intervals (only a device that records beats supplies them); a chest strap records only during workouts, and many wearables report their own HRV instead." + }, "metricDetailBreakdownLinkTitle": "Breakdown", "@metricDetailBreakdownLinkTitle": { "description": "Title of the doorway row from the Steps metric screen (Today only) into the day's step breakdown." @@ -7005,7 +7025,7 @@ "@healthNoBandRecordings": { "description": "Vitals empty-state body" }, - "healthSyncTheBand": "Sync the band", + "healthSyncTheBand": "Sync your device", "@healthSyncTheBand": { "description": "Vitals empty-state fix button: sync the band" }, @@ -7391,6 +7411,10 @@ "@homeStepSensorPhone": { "description": "Step count sensor label: the phone counted." }, + "homeStepSensorDevice": "Device", + "@homeStepSensorDevice": { + "description": "Step count sensor label: the paired wearable's own daily count was used." + }, "homeOvernightBuilding": "Last night is still being worked out.", "@homeOvernightBuilding": { "description": "Home ring gap reason: last night's data is still being derived." @@ -7613,11 +7637,11 @@ "@homeInsightsRebuildingAlgoVersion": { "description": "Reason the cross-day rollup is being rebuilt: the algorithm version changed." }, - "homeInsightsStaleOverWeek": "Your trends were last updated over a week ago. Sync the band to bring them up to date.", + "homeInsightsStaleOverWeek": "Your trends were last updated over a week ago. Sync your device to bring them up to date.", "@homeInsightsStaleOverWeek": { "description": "Reason the cross-day rollup is being rebuilt: the last rollup is more than a week old." }, - "homeInsightsStaleOnDay": "Your trends were last updated on {day}. Sync the band to bring them up to date.", + "homeInsightsStaleOnDay": "Your trends were last updated on {day}. Sync your device to bring them up to date.", "@homeInsightsStaleOnDay": { "description": "Reason the cross-day rollup is being rebuilt: names the day the last rollup was built.", "placeholders": { @@ -7631,7 +7655,7 @@ "@homeInsightsNoVersionStamp": { "description": "Reason the cross-day rollup is being rebuilt: the stored rollup has no version stamp." }, - "homeSyncBand": "Sync the band", + "homeSyncBand": "Sync your device", "@homeSyncBand": { "description": "Call-to-action button label: sync the band." }, @@ -7843,7 +7867,7 @@ "@homeNothingDerivedTitle": { "description": "Title shown on a first-run day with nothing derived yet." }, - "homeNothingDerivedBody": "Wear the band tonight and open the app in the morning.", + "homeNothingDerivedBody": "Wear your device tonight and open the app in the morning.", "@homeNothingDerivedBody": { "description": "Body shown on a first-run day with nothing derived yet." }, @@ -8838,7 +8862,7 @@ "@sleepDetailNoNightBody": { "description": "Status card body explaining why there is no night." }, - "sleepDetailNoNightFix": "Wear the band overnight and sync in the morning", + "sleepDetailNoNightFix": "Wear your device overnight and sync in the morning", "@sleepDetailNoNightFix": { "description": "Suggested fix line on the no-night status card." }, @@ -9967,6 +9991,10 @@ "@activitySetupNoBandConnected": { "description": "Detail text when no band is connected, shown under the heart rate row" }, + "activitySetupNoLiveHr": "No live heart rate", + "@activitySetupNoLiveHr": { + "description": "Workout setup heart-rate row when no band is paired and no device streams live heart rate." + }, "activitySetupPrivateLabel": "Private session", "@activitySetupPrivateLabel": { "description": "Label for the private-session toggle on the activity setup screen" @@ -10138,7 +10166,7 @@ } } }, - "dayStrainWearBandFix": "Wear the band through the day", + "dayStrainWearBandFix": "Wear your device through the day", "@dayStrainWearBandFix": { "description": "Suggested fix action on the no-strain-trace card, shown when the band never saw the day" }, @@ -10255,7 +10283,7 @@ "@activityZonesNoCeilingDefaultBody": { "description": "Default explanation of the 15-second hold rule for a measured ceiling, shown when no other reason was given" }, - "activityZonesWearBandFix": "Wear the band for your normal hard sessions", + "activityZonesWearBandFix": "Wear your device for your normal hard sessions", "@activityZonesWearBandFix": { "description": "Suggested fix action on the no-ceiling card" }, @@ -13954,7 +13982,7 @@ "@supplementColeKripkeWakeSpineHRVcd5f37": { "description": "Presentation-only text for existing interface, exports or notifications." }, - "supplementCountedNeverModelledAStepc66896": "Counted, never modelled. A step count comes from a gait-capable counter: the band's 100 Hz pedometer while it streams, or your phone's. Each stretch of the day is counted by whichever of the two was actually recording it, and a stretch both covered is counted once, so a session never takes the day from the sensor that carried the rest of it. There is no 1 Hz estimate — walking cadence sits above what one sample a second can resolve, so a day with no counter behind it reports no steps rather than a guess.", + "supplementCountedNeverModelledAStepc66896": "Counted, never modelled. A step count comes from a gait-capable counter: the band's 100 Hz pedometer while it streams, or your phone's. Each stretch of the day is counted by whichever of the two was actually recording it, and a stretch both covered is counted once, so a session never takes the day from the sensor that carried the rest of it. There is no 1 Hz estimate — walking cadence sits above what one sample a second can resolve, so a day with no counter behind it reports no steps rather than a guess. A paired wearable's own daily count is the day's steps when it counted more than these, used whole and never added to them.", "@supplementCountedNeverModelledAStepc66896": { "description": "Presentation-only text for existing interface, exports or notifications." }, @@ -14462,6 +14490,10 @@ "@supplementTheNightSMeanRaw25e383": { "description": "Presentation-only text for existing interface, exports or notifications." }, + "supplementSkinTempMethodTrend": "The night's mean raw sensor reading, expressed as distance from your own recent nights. The charted trend is that uncalibrated ADC distance, with no conversion to degrees. (A WHOOP 5 reads in real degrees; its nightly deviation is shown on Vitals in your temperature unit instead.)", + "@supplementSkinTempMethodTrend": { + "description": "Presentation-only text for existing interface, exports or notifications." + }, "supplementTheRatioOfLowTo817781": "The ratio of low- to high-frequency power in beat-interval variability, from a Lomb–Scargle periodogram (the series is unevenly sampled, so an FFT would be wrong).", "@supplementTheRatioOfLowTo817781": { "description": "Presentation-only text for existing interface, exports or notifications." @@ -14475,6 +14507,7 @@ "description": "Presentation-only text for existing interface, exports or notifications." }, "supplementTheseRecordingsAreNotStamped66b52f": "These recordings are not stamped with which strap made them, and this number has to be calibrated per strap, so it is withheld rather than guessed.", + "supplementNoCalibrationForThisDevice": "This number has to be calibrated per device, and there is no calibration for this one yet, so it is withheld rather than guessed.", "@supplementTheseRecordingsAreNotStamped66b52f": { "description": "Presentation-only text for existing interface, exports or notifications." }, @@ -15208,6 +15241,10 @@ "wearableMethodStrap": "a strap, every second", "wearableMethodStrapBeats": "a strap's beat-to-beat intervals", "wearableMethodRhrStrapComposite": "resting heart rate and a strap's beat-to-beat intervals", + "wearableMethodDeviceHrvComposite": "resting heart rate and the device's own HRV readings", + "wearableMethodDeviceRmssd": "the device's own HRV readings, over our night", + "@wearableMethodDeviceHrvComposite": {"description": "How readiness was computed on a night it took the wearable's own RMSSD readings (policy exception PE-1)."}, + "@wearableMethodDeviceRmssd": {"description": "How HRV was computed: our night's mean of the wearable's own RMSSD readings."}, "wearableMethodRingBeats": "its own beat-to-beat intervals", "wearableUnlocksTitle": "What this wearable unlocks", "wearableUnlocksOurs": "Measured by us", @@ -15970,7 +16007,7 @@ "@homeFirstWeekTitle": { "description": "Today tab: card saying when each score first appears." }, - "homeFirstWeekWear": "Wear the band tonight", + "homeFirstWeekWear": "Wear your device tonight", "@homeFirstWeekWear": { "description": "First weeks card step." }, diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 708e24d19..2f3bb8625 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -294,6 +294,9 @@ "pairSensorKeyTitle": "¿Ya configurado en otro sitio?", "pairSensorKeyBody": "¿Tienes la clave de este dispositivo? Pégala para emparejarlo sin restablecerlo de fábrica. Si pones varias claves, una por línea, se prueban por turno. Déjalo vacío para emparejar de la forma habitual.", "pairSensorKeyHint": "32 dígitos hexadecimales o base64 — una clave por línea", + "pairSensorKeyRequiredTitle": "Clave del dispositivo", + "pairSensorKeyRequiredBody": "Este dispositivo solo se vincula con la clave que configuró su propia app. Pega esa única clave: 32 dígitos hexadecimales.", + "pairSensorKeyRequiredHint": "32 dígitos hexadecimales", "pairSensorSearchAnyway": "Buscar de todos modos", "pairSensorSearching": "Buscando…", "pairSensorSearchForSensors": "Buscar sensores", @@ -490,7 +493,7 @@ "readinessDetailLastNDays": "{n, plural, one{Último {n} día} other{Últimos {n} días}}", "readinessDetailNoHistoryTitle": "Sin historial de recuperación", "readinessDetailNoHistoryBody": "0 días con puntuación.", - "readinessDetailWearOvernight": "Usa la banda durante la noche", + "readinessDetailWearOvernight": "Usa tu dispositivo durante la noche", "readinessDetailUnit": "/100", "readinessDetailDaysAgo": "{n, plural, one{hace {n} día} other{hace {n} días}}", "readinessDetailToday": "Hoy", @@ -502,6 +505,7 @@ "readinessDetailNotAvailable": "no disponible", "readinessDetailContributionNotReported": "contribución no notificada", "readinessDetailRelativeUncalibrated": "relativa, sin calibrar", + "readinessDetailFromDeviceReadings": "de las propias lecturas de tu dispositivo", "readinessDetailWithinSpread": "sí, dentro de tu rango habitual", "readinessDetailWeightPercent": "{pct}% de peso", "dayStepsTitle": "Pasos", @@ -562,9 +566,9 @@ "driverBreakdownToday": "Hoy", "driverBreakdownAbsenceTitle": "No hay desglose que mostrar", "driverBreakdownAbsenceAlgoVersion": "La forma de calcular la recuperación cambió en la última actualización. Tus días se están recalculando.", - "driverBreakdownAbsenceStale": "Tus tendencias no están al día. Sincroniza la banda para actualizarlas.", + "driverBreakdownAbsenceStale": "Tus tendencias no están al día. Sincroniza tu dispositivo para actualizarlas.", "driverBreakdownAbsenceNoVersion": "Tus tendencias se están actualizando. Tarda un minuto después de sincronizar.", - "driverBreakdownSyncTheBand": "Sincronizar la banda", + "driverBreakdownSyncTheBand": "Sincronizar el dispositivo", "driverBreakdownAbsenceNoReason": "No hay ningún registro que explique por qué anoche no tiene desglose.", "coachFiguresCouldNotBeDrawn": "No se pudo dibujar una figura", "coachFiguresNoType": "El entrenador envió una figura sin tipo.", @@ -584,7 +588,7 @@ "circadianDetailTitle": "Reloj corporal", "circadianDetailNoNightsTitle": "Aún no hay noches que representar", "circadianDetailNoNightsBody": "0 noches puntuadas.", - "circadianDetailNoNightsFix": "Usa la banda por la noche", + "circadianDetailNoNightsFix": "Usa tu dispositivo por la noche", "circadianDetailSleepTitle": "Sueño, noche a noche", "circadianDetailAsleep": "Dormido", "circadianDetailSleepFootnote": "{count, plural, one{{count} noche, una columna por noche, más oscura cuanto más tiempo de esa hora se durmió.} other{{count} noches, una columna por noche, más oscura cuanto más tiempo de esa hora se durmió.}}", @@ -1180,7 +1184,8 @@ "metricDetailNoValueYet": "Hoy aún no ha producido un valor.", "metricDetailNoValueYetWiderRanges": "Hoy aún no ha producido un valor. Los rangos más amplios de arriba tienen los días que sí lo hicieron.", "metricDetailNoValueInWindow": "Ningún día de este período produjo un valor.", - "metricDetailWearBandFix": "Usa la banda toda la noche para iniciar la serie", + "metricDetailWearBandFix": "Usa tu dispositivo toda la noche para iniciar la serie", + "metricDetailHrvNeedsBeatsFix": "Este gráfico necesita intervalos latido a latido registrados durante la noche, que solo aporta un dispositivo que registre los latidos. Una banda pectoral solo registra durante los entrenamientos, y muchos relojes, anillos y bandas informan de su propia VFC: está en su página de dispositivo", "metricDetailBreakdownLinkTitle": "Desglose", "metricDetailBreakdownLinkSub": "Cada tramo de hoy, y qué lo contó", "metricDetailNerdStatsTitle": "Estadísticas técnicas", @@ -1381,7 +1386,7 @@ "healthCoverageOf": "{pct}% de {day}", "healthNothingMeasuredDay": "No se midió nada este día", "healthNoBandRecordings": "No llegaron grabaciones de la banda para este día.", - "healthSyncTheBand": "Sincronizar la banda", + "healthSyncTheBand": "Sincronizar el dispositivo", "healthDeepDivesTitle": "Análisis en profundidad", "healthHeartRateVariability": "Variabilidad de la frecuencia cardíaca", "healthTimeFrequencyNonLinear": "Tiempo, frecuencia y no lineal", @@ -1451,6 +1456,7 @@ "homeStepSensorStrapPhone": "Correa + teléfono", "homeStepSensorStrap": "Correa", "homeStepSensorPhone": "Teléfono", + "homeStepSensorDevice": "Dispositivo", "homeOvernightBuilding": "Los datos de anoche aún se están procesando.", "homeOvernightNothingYet": "Todavía no ha llegado nada de anoche a la app.", "homeMonthJanuary": "enero", @@ -1503,10 +1509,10 @@ "homeWorkoutHoldBody": "Hoy se completa cuando termines el entrenamiento.", "homeInsightsRebuildingTitle": "Actualizando tus tendencias", "homeInsightsRebuildingAlgoVersion": "Actualizando tras la última actualización de la app.", - "homeInsightsStaleOverWeek": "Tus tendencias se actualizaron por última vez hace más de una semana. Sincroniza la banda para ponerlas al día.", - "homeInsightsStaleOnDay": "Tus tendencias se actualizaron por última vez el {day}. Sincroniza la banda para ponerlas al día.", + "homeInsightsStaleOverWeek": "Tus tendencias se actualizaron por última vez hace más de una semana. Sincroniza tu dispositivo para ponerlas al día.", + "homeInsightsStaleOnDay": "Tus tendencias se actualizaron por última vez el {day}. Sincroniza tu dispositivo para ponerlas al día.", "homeInsightsNoVersionStamp": "Tus tendencias se están actualizando. Tarda un minuto después de sincronizar.", - "homeSyncBand": "Sincronizar la correa", + "homeSyncBand": "Sincronizar el dispositivo", "homeCalibrating": "Aprendiendo lo habitual", "homeCalibratingNights": "{have} de {need} noches", "homeCalibratingDays": "{have} de {need} días", @@ -1600,7 +1606,7 @@ "wellnessLoadFailedBody": "No se pudieron leer los datos guardados. No se eliminó nada; fue un error de lectura, no datos perdidos.", "homeTryAgain": "Intentar de nuevo", "homeNothingDerivedTitle": "Aún no hay noches con puntuación", - "homeNothingDerivedBody": "Lleva la banda esta noche y abre la app por la mañana.", + "homeNothingDerivedBody": "Lleva tu dispositivo esta noche y abre la app por la mañana.", "homeSyncingTitle": "Sincronizando con tu banda", "homeSyncingBody": "Descargando datos — puede tardar unos minutos si hay mucho acumulado.", "homeAnalyzingTitle": "Calculando los números de anoche", @@ -1787,7 +1793,7 @@ "sleepDetailNavTitle": "Sueño", "sleepDetailNoNightTitle": "No hay noche que mostrar", "sleepDetailNoNightBody": "No hay un tramo de grabaciones de la banda lo bastante largo para puntuar.", - "sleepDetailNoNightFix": "Usa la banda toda la noche y sincroniza por la mañana", + "sleepDetailNoNightFix": "Usa tu dispositivo toda la noche y sincroniza por la mañana", "sleepDetailStagesSection": "Fases", "sleepDetailVersusUsualSection": "Frente a lo habitual", "sleepDetailUnusualLastNight": "Algo inusual anoche", @@ -2000,6 +2006,7 @@ "activitySetupHeartRateLabel": "Frecuencia cardíaca", "activitySetupBandConnected": "Banda conectada", "activitySetupNoBandConnected": "Ninguna banda conectada", + "activitySetupNoLiveHr": "Sin frecuencia cardiaca en directo", "activitySetupPrivateLabel": "Sesión privada", "activitySetupPrivateDetail": "Oculta en resúmenes y exportaciones", "activitySetupCaloriesNeedWeight": "Las calorías necesitan tu peso.", @@ -2032,7 +2039,7 @@ "dayStrainNoMinuteTraceTitle": "Sin registro minuto a minuto para este día", "dayStrainNoReasonBody": "No hay ningún registro que explique por qué este día no generó esfuerzo.", "dayStrainScoredNoTraceBody": "El esfuerzo diario es {strain}. Los minutos despierto con los que se calculó no están guardados para este día.", - "dayStrainWearBandFix": "Usa la banda durante todo el día", + "dayStrainWearBandFix": "Usa tu dispositivo durante todo el día", "dayStrainChartTitle": "Esfuerzo a lo largo del día", "dayStrainChartFootnote": "Esfuerzo por encima de tu ritmo habitual en vigilia. Puede bajar más tarde si vuelves a acercarte a ese ritmo. Calculado a partir de {drawn} minutos de vigilia registrados.", "dayStrainPeakHr": "FC máxima", @@ -2055,7 +2062,7 @@ "activityZonesNoCeilingTitle": "Aún sin límite medido", "activityZonesNoCeilingTanakaTail": " Hasta que se mida uno, las zonas de abajo se basan en tu edad.", "activityZonesNoCeilingDefaultBody": "Solo contamos una lectura alta que la banda mantuvo durante 15 segundos mientras te movías. Un pico de un segundo no es una frecuencia cardíaca.", - "activityZonesWearBandFix": "Usa la banda en tus sesiones intensas habituales", + "activityZonesWearBandFix": "Usa tu dispositivo en tus sesiones intensas habituales", "activityZonesHighestSeenLabel": "MÁXIMO REGISTRADO", "activityZonesBpmUnit": "lpm", "activityZonesCeilingOnDate": "el {date}", @@ -2714,6 +2721,8 @@ "wearableMethodStrap": "una banda, cada segundo", "wearableMethodStrapBeats": "los intervalos latido a latido de una banda", "wearableMethodRhrStrapComposite": "frecuencia cardíaca en reposo y los intervalos latido a latido de una banda", + "wearableMethodDeviceHrvComposite": "frecuencia cardíaca en reposo y las lecturas de VFC del propio dispositivo", + "wearableMethodDeviceRmssd": "las lecturas de VFC del propio dispositivo, a lo largo de nuestra noche", "wearableMethodRingBeats": "sus propios intervalos latido a latido", "wearableUnlocksTitle": "Lo que desbloquea este wearable", "wearableUnlocksOurs": "Medido por nosotros", @@ -3470,7 +3479,7 @@ "homeBackToToday": "Volver a hoy", "homeSomeDataMissingTitle": "Faltan algunos datos de hoy", "homeFirstWeekTitle": "Tus primeras semanas", - "homeFirstWeekWear": "Usa la banda esta noche", + "homeFirstWeekWear": "Usa tu dispositivo esta noche", "homeFirstWeekSleep": "Sueño: la mañana después de tu primera noche", "homeFirstWeekStrain": "Esfuerzo: a partir del día {day}", "homeFirstWeekRecovery": "Recuperación: a partir de la noche {night}, cuando conozca tu normalidad", @@ -3622,7 +3631,7 @@ "supplementCharging5f99fe": "Cargando", "supplementCoefficientOfVariationOfPerc71989": "Coeficiente de variación de la frecuencia respiratoria por ventana a lo largo de la noche.", "supplementColeKripkeWakeSpineHRVcd5f37": "Base de vigilia Cole–Kripke + capa de VFC", - "supplementCountedNeverModelledAStepc66896": "Contados, nunca modelados. Los pasos vienen de un contador capaz de detectar la marcha: el podómetro de 100 Hz de la banda mientras transmite, o el de tu teléfono. Cada tramo del día lo cuenta el que realmente lo estaba registrando, y un tramo que cubrieron los dos se cuenta una sola vez, así que una sesión nunca le quita el día al sensor que registró el resto. No hay estimación a 1 Hz: la cadencia al caminar está por encima de lo que una muestra por segundo puede resolver, así que un día sin contador no muestra pasos en lugar de una suposición.", + "supplementCountedNeverModelledAStepc66896": "Contados, nunca modelados. Los pasos vienen de un contador capaz de detectar la marcha: el podómetro de 100 Hz de la banda mientras transmite, o el de tu teléfono. Cada tramo del día lo cuenta el que realmente lo estaba registrando, y un tramo que cubrieron los dos se cuenta una sola vez, así que una sesión nunca le quita el día al sensor que registró el resto. No hay estimación a 1 Hz: la cadencia al caminar está por encima de lo que una muestra por segundo puede resolver, así que un día sin contador no muestra pasos en lugar de una suposición. Si el recuento diario propio de un dispositivo vinculado supera al de las otras fuentes ese mismo día, ese recuento son los pasos del día: se usa entero, nunca sumado a los otros.", "supplementCreatinined3029a": "Creatinina", "supplementDailyRecoveryReadinessFromYourf995c0": "Tu puntuación diaria de recuperación", "supplementDeepMin28f1fc": "Profundo (min)", @@ -3747,10 +3756,12 @@ "supplementTheHighestHeartRateHeldc1c878": "Tu frecuencia cardíaca más alta hasta ahora está muy por debajo de lo que predice tu edad, así que las zonas siguen basadas en la estimación por edad hasta que la banda vea un esfuerzo mayor.", "supplementTheLowestSustainedSleepingHeart72e5dd": "La frecuencia cardíaca más baja mantenida durante el sueño, tomada sobre una ventana móvil de la serie nocturna. No es una lectura puntual ni un mínimo diurno.", "supplementTheNightSMeanRaw25e383": "La lectura media en bruto del sensor durante la noche, expresada como distancia respecto a tus noches recientes. En ningún paso se convierte a grados.", + "supplementSkinTempMethodTrend": "La lectura media en bruto del sensor durante la noche, expresada como distancia respecto a tus propias noches recientes. La tendencia del gráfico es esa distancia ADC sin calibrar, sin conversión a grados. (Un WHOOP 5 mide en grados reales; su desviación nocturna se muestra en Vitales en tu unidad de temperatura.)", "supplementTheRatioOfLowTo817781": "La relación entre la potencia de baja y alta frecuencia de la variabilidad entre latidos, a partir de un periodograma de Lomb–Scargle (la serie no está muestreada de forma uniforme, así que una FFT sería incorrecta).", "supplementThereIsNoRestingHeart36a9ca": "No hay frecuencia cardíaca en reposo de una noche puntuada con la que comparar.", "supplementThereIsNoScoredNight5d353d": "No hay ninguna noche puntuada de la que leer esto.", "supplementTheseRecordingsAreNotStamped66b52f": "Estos registros no indican qué banda los hizo, y este valor hay que calibrarlo para cada banda, así que se omite en lugar de adivinarlo.", + "supplementNoCalibrationForThisDevice": "Este valor debe calibrarse para cada dispositivo y todavía no hay calibración para este, así que se omite en lugar de estimarlo.", "supplementThisDayCameFromAn2dc4b2": "Este día viene de una importación que solo cubre la noche, así que no hay nada registrado de las horas de vigilia.", "supplementTimeAsleepAsAFraction516f7f": "Tiempo dormido como fracción del tiempo en la cama.", "supplementTimeToMove7afe98": "Hora de moverse", diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 3c53087a8..610c4c1e6 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -292,6 +292,9 @@ "pairSensorKeyTitle": "Déjà configuré ailleurs ?", "pairSensorKeyBody": "Si vous avez la clé que cet appareil utilise déjà, collez-la ici : il se jumelle sans réinitialisation d'usine et rien n'est écrit sur l'appareil. Plusieurs clés, une par ligne, sont essayées à tour de rôle jusqu'à ce que l'une soit acceptée — pratique si vous en avez plusieurs sans savoir laquelle correspond à cet appareil. Laissez vide pour jumeler comme d'habitude.", "pairSensorKeyHint": "32 chiffres hexadécimaux ou base64 — une clé par ligne", + "pairSensorKeyRequiredTitle": "Clé de l’appareil", + "pairSensorKeyRequiredBody": "Cet appareil ne s’associe qu’avec la clé configurée par sa propre application. Collez cette clé unique : 32 chiffres hexadécimaux.", + "pairSensorKeyRequiredHint": "32 chiffres hexadécimaux", "pairSensorSearchAnyway": "Rechercher quand même", "pairSensorSearching": "Recherche…", "pairSensorSearchForSensors": "Rechercher des capteurs", @@ -488,7 +491,7 @@ "readinessDetailLastNDays": "{n, plural, one{Dernier {n} jour} other{Derniers {n} jours}}", "readinessDetailNoHistoryTitle": "Aucun historique de forme", "readinessDetailNoHistoryBody": "0 jour noté.", - "readinessDetailWearOvernight": "Portez le bracelet pendant la nuit", + "readinessDetailWearOvernight": "Portez votre appareil pendant la nuit", "readinessDetailUnit": "/100", "readinessDetailDaysAgo": "{n, plural, one{il y a {n} jour} other{il y a {n} jours}}", "readinessDetailToday": "Aujourd'hui", @@ -500,6 +503,7 @@ "readinessDetailNotAvailable": "non disponible", "readinessDetailContributionNotReported": "contribution non indiquée", "readinessDetailRelativeUncalibrated": "relative, non calibrée", + "readinessDetailFromDeviceReadings": "d’après les propres mesures de votre appareil", "readinessDetailWithinSpread": "dans votre écart habituel", "readinessDetailWeightPercent": "{pct} % de poids", "dayStepsTitle": "Pas", @@ -562,7 +566,7 @@ "driverBreakdownAbsenceAlgoVersion": "La façon de calculer la récupération a changé avec la dernière mise à jour, et elle est en cours de reconstruction.", "driverBreakdownAbsenceStale": "Le dernier récapitulatif est trop ancien pour être garanti.", "driverBreakdownAbsenceNoVersion": "Le récapitulatif enregistré ne porte aucune marque de version.", - "driverBreakdownSyncTheBand": "Synchroniser le bracelet", + "driverBreakdownSyncTheBand": "Synchroniser l'appareil", "driverBreakdownAbsenceNoReason": "Aucun enregistrement n’explique pourquoi la nuit dernière n’a pas de décomposition.", "coachFiguresCouldNotBeDrawn": "Impossible de tracer une figure", "coachFiguresNoType": "Le coach a envoyé une figure sans type.", @@ -582,7 +586,7 @@ "circadianDetailTitle": "Horloge biologique", "circadianDetailNoNightsTitle": "Aucune nuit à représenter pour l'instant", "circadianDetailNoNightsBody": "0 nuit notée.", - "circadianDetailNoNightsFix": "Portez le bracelet pendant la nuit", + "circadianDetailNoNightsFix": "Portez votre appareil pendant la nuit", "circadianDetailSleepTitle": "Sommeil, nuit après nuit", "circadianDetailAsleep": "Endormi", "circadianDetailSleepFootnote": "{count, plural, one{{count} nuit, une colonne chacune. Plus c'est foncé, plus vous étiez endormi cette heure-là.} other{{count} nuits, une colonne chacune. Plus c'est foncé, plus vous étiez endormi cette heure-là.}}", @@ -1178,7 +1182,8 @@ "metricDetailNoValueYet": "Aujourd’hui n’a pas encore produit de valeur.", "metricDetailNoValueYetWiderRanges": "Aujourd’hui n’a pas encore produit de valeur. Les plages plus larges ci-dessus contiennent les jours qui en ont produit une.", "metricDetailNoValueInWindow": "Aucun jour de cette plage n’a produit de valeur.", - "metricDetailWearBandFix": "Portez le bracelet toute la nuit pour démarrer la série", + "metricDetailWearBandFix": "Portez votre appareil toute la nuit pour démarrer la série", + "metricDetailHrvNeedsBeatsFix": "Ce graphique a besoin d’intervalles entre battements enregistrés la nuit, que seul un appareil qui enregistre les battements fournit. Une ceinture thoracique n’enregistre que pendant les séances, et beaucoup de montres, bagues et bracelets donnent plutôt leur propre VFC : elle figure sur leur page d’appareil", "metricDetailBreakdownLinkTitle": "Détail", "metricDetailBreakdownLinkSub": "Chaque plage de la journée, et ce qui l’a comptée", "metricDetailNerdStatsTitle": "Statistiques avancées", @@ -1379,7 +1384,7 @@ "healthCoverageOf": "{pct} % de {day}", "healthNothingMeasuredDay": "Rien n'a été mesuré ce jour-là", "healthNoBandRecordings": "Aucun enregistrement du bracelet n'a atteint ce jour-là.", - "healthSyncTheBand": "Synchroniser le bracelet", + "healthSyncTheBand": "Synchroniser l'appareil", "healthDeepDivesTitle": "Analyses approfondies", "healthHeartRateVariability": "Variabilité de la fréquence cardiaque", "healthTimeFrequencyNonLinear": "Temporel, fréquentiel et non linéaire", @@ -1449,6 +1454,7 @@ "homeStepSensorStrapPhone": "Bracelet + téléphone", "homeStepSensorStrap": "Bracelet", "homeStepSensorPhone": "Téléphone", + "homeStepSensorDevice": "Appareil", "homeOvernightBuilding": "Les données de cette nuit sont encore en cours de traitement.", "homeOvernightNothingYet": "Rien de cette nuit n'est encore arrivé dans l'application.", "homeMonthJanuary": "janvier", @@ -1504,7 +1510,7 @@ "homeInsightsStaleOverWeek": "Le dernier récapitulatif date de plus d'une semaine, ce qui est trop ancien pour s'y fier.", "homeInsightsStaleOnDay": "Le dernier récapitulatif a été généré le {day}, ce qui est trop ancien pour s'y fier.", "homeInsightsNoVersionStamp": "Le récapitulatif enregistré ne porte aucune marque de version.", - "homeSyncBand": "Synchroniser le bracelet", + "homeSyncBand": "Synchroniser l'appareil", "homeCalibrating": "Étalonnage", "homeCalibratingNights": "{have, plural, one{{have} nuit sur {need}} other{{have} nuits sur {need}}}", "homeCalibratingDays": "{have, plural, one{{have} jour sur {need}} other{{have} jours sur {need}}}", @@ -1598,7 +1604,7 @@ "wellnessLoadFailedBody": "Les données enregistrées n'ont pas pu être lues. Rien n'a été supprimé : c'est une erreur de lecture, pas une perte de données.", "homeTryAgain": "Réessayer", "homeNothingDerivedTitle": "Rien n'a encore été calculé", - "homeNothingDerivedBody": "Aucun enregistrement du bracelet n'a encore été traité.", + "homeNothingDerivedBody": "Aucun enregistrement de l'appareil n'a encore été traité.", "homeAskCoach": "Demander au coach", "homeProfileSettings": "Profil et réglages", "homeNothingTodayTitle": "Rien d'enregistré aujourd'hui", @@ -1779,7 +1785,7 @@ "sleepDetailNavTitle": "Sommeil", "sleepDetailNoNightTitle": "Aucune nuit à afficher", "sleepDetailNoNightBody": "Aucune plage d'enregistrements du bracelet assez longue pour être notée.", - "sleepDetailNoNightFix": "Portez le bracelet toute la nuit et synchronisez le matin", + "sleepDetailNoNightFix": "Portez votre appareil toute la nuit et synchronisez le matin", "sleepDetailStagesSection": "Phases", "sleepDetailVersusUsualSection": "Par rapport à d'habitude", "sleepDetailUnusualLastNight": "Chose inhabituelle cette nuit", @@ -1988,6 +1994,7 @@ "activitySetupHeartRateLabel": "Fréquence cardiaque", "activitySetupBandConnected": "Bracelet connecté", "activitySetupNoBandConnected": "Aucun bracelet connecté", + "activitySetupNoLiveHr": "Pas de fréquence cardiaque en direct", "activitySetupPrivateLabel": "Séance privée", "activitySetupPrivateDetail": "Masquée des résumés et des exports", "activitySetupCaloriesNeedWeight": "Les calories nécessitent votre poids.", @@ -2018,7 +2025,7 @@ "dayStrainNoMinuteTraceTitle": "Aucune courbe minute par minute pour ce jour", "dayStrainNoReasonBody": "Aucune donnée n’explique pourquoi ce jour n’a produit aucun effort.", "dayStrainScoredNoTraceBody": "L’effort du jour est {strain}. Les minutes d’éveil à partir desquelles il a été calculé ne sont pas conservées pour ce jour.", - "dayStrainWearBandFix": "Portez le bracelet toute la journée", + "dayStrainWearBandFix": "Portez votre appareil toute la journée", "dayStrainChartTitle": "EFFORT AU FIL DE LA JOURNÉE", "dayStrainChartFootnote": "Effort au-dessus de votre rythme d’éveil habituel. Il peut redescendre si vous revenez vers ce rythme. Calculé à partir de {drawn} minutes d’éveil enregistrées.", "dayStrainPeakHr": "FC max", @@ -2041,7 +2048,7 @@ "activityZonesNoCeilingTitle": "Pas encore de plafond mesuré", "activityZonesNoCeilingTanakaTail": " Tant qu’aucun n’est mesuré, les zones ci-dessous sont basées sur votre âge.", "activityZonesNoCeilingDefaultBody": "Nous ne comptons qu’une lecture élevée maintenue par le bracelet pendant 15 secondes pendant que vous bougiez. Un pic d’une seconde n’est pas une fréquence cardiaque.", - "activityZonesWearBandFix": "Portez le bracelet pendant vos séances intenses habituelles", + "activityZonesWearBandFix": "Portez votre appareil pendant vos séances intenses habituelles", "activityZonesHighestSeenLabel": "PLUS ÉLEVÉ OBSERVÉ", "activityZonesBpmUnit": "bpm", "activityZonesCeilingOnDate": "le {date}", @@ -2683,6 +2690,8 @@ "wearableMethodStrap": "une ceinture, chaque seconde", "wearableMethodStrapBeats": "les intervalles battement à battement d'une ceinture", "wearableMethodRhrStrapComposite": "fréquence cardiaque au repos et les intervalles battement à battement d'une ceinture", + "wearableMethodDeviceHrvComposite": "fréquence cardiaque au repos et les mesures de VFC de l'appareil lui-même", + "wearableMethodDeviceRmssd": "les mesures de VFC de l'appareil lui-même, sur notre nuit", "wearableMethodRingBeats": "ses propres intervalles battement à battement", "wearableUnlocksTitle": "Ce que ce wearable débloque", "wearableUnlocksOurs": "Mesuré par nous", @@ -3343,7 +3352,7 @@ "homeBackToToday": "Retour à aujourd’hui", "homeSomeDataMissingTitle": "Une partie des données du jour manque", "homeFirstWeekTitle": "Vos premières semaines", - "homeFirstWeekWear": "Portez le bracelet cette nuit", + "homeFirstWeekWear": "Portez votre appareil cette nuit", "homeFirstWeekSleep": "Sommeil : le matin après votre première nuit", "homeFirstWeekStrain": "Effort : à partir du jour {day}", "homeFirstWeekRecovery": "Récupération : à partir de la nuit {night}, une fois votre normale connue", @@ -3619,7 +3628,7 @@ "supplementCharging5f99fe": "En charge", "supplementCoefficientOfVariationOfPerc71989": "Coefficient de variation de la fréquence respiratoire par fenêtre au cours de la nuit.", "supplementColeKripkeWakeSpineHRVcd5f37": "Base d’éveil Cole–Kripke + couche VFC", - "supplementCountedNeverModelledAStepc66896": "Comptés, jamais modélisés. Les pas viennent d’un compteur capable de détecter la marche : le podomètre 100 Hz du bracelet pendant qu’il diffuse, ou celui de votre téléphone. Chaque partie de la journée est comptée par celui qui l’enregistrait réellement, et une partie couverte par les deux n’est comptée qu’une fois, donc une séance ne retire jamais la journée au capteur qui a enregistré le reste. Il n’y a pas d’estimation à 1 Hz : la cadence de marche dépasse ce qu’un échantillon par seconde peut résoudre, donc une journée sans compteur n’affiche aucun pas plutôt qu’une supposition.", + "supplementCountedNeverModelledAStepc66896": "Comptés, jamais modélisés. Les pas viennent d’un compteur capable de détecter la marche : le podomètre 100 Hz du bracelet pendant qu’il diffuse, ou celui de votre téléphone. Chaque partie de la journée est comptée par celui qui l’enregistrait réellement, et une partie couverte par les deux n’est comptée qu’une fois, donc une séance ne retire jamais la journée au capteur qui a enregistré le reste. Il n’y a pas d’estimation à 1 Hz : la cadence de marche dépasse ce qu’un échantillon par seconde peut résoudre, donc une journée sans compteur n’affiche aucun pas plutôt qu’une supposition. Le décompte quotidien propre d’un appareil associé devient les pas du jour lorsqu’il en a compté davantage ; il est alors repris tel quel, jamais additionné aux autres.", "supplementCreatinined3029a": "Créatinine", "supplementDailyRecoveryReadinessFromYourf995c0": "Votre score de récupération du jour", "supplementDeepMin28f1fc": "Profond (min)", @@ -3744,10 +3753,12 @@ "supplementTheHighestHeartRateHeldc1c878": "Votre fréquence cardiaque la plus élevée jusqu’ici est bien en dessous de ce que prédit votre âge, donc les zones restent basées sur l’estimation par l’âge jusqu’à ce que le bracelet voie un effort plus intense.", "supplementTheLowestSustainedSleepingHeart72e5dd": "La fréquence cardiaque la plus basse maintenue pendant le sommeil, prise sur une fenêtre glissante de la série nocturne. Ce n’est ni une mesure ponctuelle, ni un minimum de journée.", "supplementTheNightSMeanRaw25e383": "La mesure brute moyenne du capteur pendant la nuit, exprimée comme écart par rapport à vos nuits récentes. Aucune conversion en degrés n’a lieu à aucun moment.", + "supplementSkinTempMethodTrend": "La mesure brute moyenne du capteur pendant la nuit, exprimée comme écart par rapport à vos nuits récentes. La tendance tracée est cet écart ADC non étalonné, sans conversion en degrés. (Un WHOOP 5 mesure en vrais degrés ; son écart nocturne est affiché dans Vitaux, dans votre unité de température.)", "supplementTheRatioOfLowTo817781": "Le rapport entre la puissance basse et haute fréquence de la variabilité entre battements, à partir d’un périodogramme de Lomb–Scargle (la série n’est pas échantillonnée régulièrement, une FFT serait donc fausse).", "supplementThereIsNoRestingHeart36a9ca": "Il n’y a pas de fréquence cardiaque au repos issue d’une nuit notée pour comparer.", "supplementThereIsNoScoredNight5d353d": "Il n’y a aucune nuit notée d’où lire cette valeur.", "supplementTheseRecordingsAreNotStamped66b52f": "Ces enregistrements n’indiquent pas quel bracelet les a faits, et cette valeur doit être étalonnée pour chaque bracelet, elle est donc omise plutôt que devinée.", + "supplementNoCalibrationForThisDevice": "Cette valeur doit être étalonnée pour chaque appareil, et il n’existe pas encore d’étalonnage pour celui-ci : elle est donc omise plutôt que devinée.", "supplementThisDayCameFromAn2dc4b2": "Ce jour vient d’une importation qui ne couvre que la nuit, donc rien n’est enregistré pour les heures d’éveil.", "supplementTimeAsleepAsAFraction516f7f": "Temps de sommeil rapporté au temps passé au lit.", "supplementTimeToMove7afe98": "Il est temps de bouger", diff --git a/lib/l10n/app_hi.arb b/lib/l10n/app_hi.arb index bcaa27801..0ec6bdcd5 100644 --- a/lib/l10n/app_hi.arb +++ b/lib/l10n/app_hi.arb @@ -292,6 +292,9 @@ "pairSensorKeyTitle": "पहले से कहीं और सेट अप है?", "pairSensorKeyBody": "अगर आपके पास वह कुंजी है जो यह डिवाइस पहले से इस्तेमाल करता है, तो उसे यहाँ चिपकाएँ — फ़ैक्टरी रीसेट के बिना जोड़ी बन जाएगी और डिवाइस पर कुछ नहीं लिखा जाता। एक पंक्ति में एक कुंजी रखकर कई कुंजियाँ दी जा सकती हैं; उन्हें एक-एक करके आज़माया जाता है जब तक कोई स्वीकार न हो जाए, जो तब काम आता है जब आपके पास कई कुंजियाँ हों और पता न हो कि कौन सी इस डिवाइस की है। सामान्य तरीके से जोड़ने के लिए इसे खाली छोड़ दें।", "pairSensorKeyHint": "32 हेक्स अंक या base64 — हर पंक्ति में एक कुंजी", + "pairSensorKeyRequiredTitle": "डिवाइस कुंजी", + "pairSensorKeyRequiredBody": "यह डिवाइस केवल उसी कुंजी से जुड़ता है जो उसके अपने ऐप ने सेट की थी। वही एक कुंजी पेस्ट करें: 32 हेक्स अंक।", + "pairSensorKeyRequiredHint": "32 हेक्स अंक", "pairSensorSearchAnyway": "फिर भी खोजें", "pairSensorSearching": "खोज रहा है…", "pairSensorSearchForSensors": "सेंसर खोजें", @@ -488,7 +491,7 @@ "readinessDetailLastNDays": "{n, plural, one{पिछला {n} दिन} other{पिछले {n} दिन}}", "readinessDetailNoHistoryTitle": "तैयारी का कोई इतिहास नहीं", "readinessDetailNoHistoryBody": "0 दिनों का स्कोर मिला।", - "readinessDetailWearOvernight": "बैंड को रातभर पहनें", + "readinessDetailWearOvernight": "अपना डिवाइस रातभर पहनें", "readinessDetailUnit": "/100", "readinessDetailDaysAgo": "{n, plural, one{{n} दिन पहले} other{{n} दिन पहले}}", "readinessDetailToday": "आज", @@ -500,6 +503,7 @@ "readinessDetailNotAvailable": "उपलब्ध नहीं", "readinessDetailContributionNotReported": "योगदान की रिपोर्ट नहीं मिली", "readinessDetailRelativeUncalibrated": "सापेक्ष, अंशांकित नहीं", + "readinessDetailFromDeviceReadings": "आपके डिवाइस की अपनी रीडिंग से", "readinessDetailWithinSpread": "आपकी सामान्य सीमा के भीतर", "readinessDetailWeightPercent": "{pct}% भार", "dayStepsTitle": "कदम", @@ -562,7 +566,7 @@ "driverBreakdownAbsenceAlgoVersion": "पिछले अपडेट के साथ तैयारी की गणना करने का तरीका बदल गया है, और इसे फिर से बनाया जा रहा है।", "driverBreakdownAbsenceStale": "अंतिम रोलअप इतना पुराना है कि उस पर भरोसा नहीं किया जा सकता।", "driverBreakdownAbsenceNoVersion": "संग्रहीत रोलअप पर कोई संस्करण चिह्न नहीं है।", - "driverBreakdownSyncTheBand": "बैंड सिंक करें", + "driverBreakdownSyncTheBand": "डिवाइस सिंक करें", "driverBreakdownAbsenceNoReason": "कोई भी रिकॉर्ड यह नहीं बताता कि कल रात का विवरण क्यों उपलब्ध नहीं है।", "coachFiguresCouldNotBeDrawn": "एक आकृति नहीं बनाई जा सकी", "coachFiguresNoType": "कोच ने बिना प्रकार वाली आकृति भेजी।", @@ -582,7 +586,7 @@ "circadianDetailTitle": "बॉडी क्लॉक", "circadianDetailNoNightsTitle": "अभी तक दिखाने के लिए कोई रातें नहीं हैं", "circadianDetailNoNightsBody": "0 रातों का स्कोर बना।", - "circadianDetailNoNightsFix": "रातभर बैंड पहनें", + "circadianDetailNoNightsFix": "रातभर अपना डिवाइस पहनें", "circadianDetailSleepTitle": "नींद, रात दर रात", "circadianDetailAsleep": "सोया हुआ", "circadianDetailSleepFootnote": "{count, plural, one{{count} रात, हर एक का अलग कॉलम। जितना गहरा रंग, उस घंटे उतनी ही अधिक नींद।} other{{count} रातें, हर एक का अलग कॉलम। जितना गहरा रंग, उस घंटे उतनी ही अधिक नींद।}}", @@ -1178,7 +1182,8 @@ "metricDetailNoValueYet": "आज अभी तक कोई मान नहीं मिला है।", "metricDetailNoValueYetWiderRanges": "आज अभी तक कोई मान नहीं मिला है। ऊपर दी गई बड़ी समयसीमाओं में वे दिन शामिल हैं जिनमें मान मिला।", "metricDetailNoValueInWindow": "इस समयावधि में किसी भी दिन कोई मान नहीं मिला।", - "metricDetailWearBandFix": "सीरीज़ शुरू करने के लिए रातभर बैंड पहनें", + "metricDetailWearBandFix": "सीरीज़ शुरू करने के लिए रातभर अपना डिवाइस पहनें", + "metricDetailHrvNeedsBeatsFix": "इस चार्ट को रात में रिकॉर्ड किए गए धड़कन-दर-धड़कन अंतराल चाहिए, जो केवल धड़कनें रिकॉर्ड करने वाला डिवाइस देता है। चेस्ट स्ट्रैप केवल वर्कआउट के दौरान रिकॉर्ड करता है, और कई घड़ियाँ, रिंग और स्ट्रैप इसके बजाय अपनी HRV बताते हैं: वह उनके डिवाइस पेज पर है", "metricDetailBreakdownLinkTitle": "ब्यौरा", "metricDetailBreakdownLinkSub": "आज का हर हिस्सा, और उसे किसने गिना", "metricDetailNerdStatsTitle": "तकनीकी आँकड़े", @@ -1379,7 +1384,7 @@ "healthCoverageOf": "{day} का {pct}%", "healthNothingMeasuredDay": "इस दिन कुछ भी मापा नहीं गया", "healthNoBandRecordings": "इस दिन तक बैंड की कोई रिकॉर्डिंग नहीं पहुँची।", - "healthSyncTheBand": "बैंड सिंक करें", + "healthSyncTheBand": "डिवाइस सिंक करें", "healthDeepDivesTitle": "गहन विश्लेषण", "healthHeartRateVariability": "हृदय गति परिवर्तनशीलता", "healthTimeFrequencyNonLinear": "समय, आवृत्ति और नॉन-लीनियर", @@ -1449,6 +1454,7 @@ "homeStepSensorStrapPhone": "स्ट्रैप + फ़ोन", "homeStepSensorStrap": "स्ट्रैप", "homeStepSensorPhone": "फ़ोन", + "homeStepSensorDevice": "डिवाइस", "homeOvernightBuilding": "पिछली रात का डेटा अभी भी संसाधित हो रहा है।", "homeOvernightNothingYet": "पिछली रात का कोई डेटा अब तक ऐप तक नहीं पहुँचा है।", "homeMonthJanuary": "जनवरी", @@ -1504,7 +1510,7 @@ "homeInsightsStaleOverWeek": "आखिरी रोलअप एक हफ़्ते से भी पहले बना था, जो भरोसा करने के लिए बहुत पुराना है।", "homeInsightsStaleOnDay": "आखिरी रोलअप {day} को बना था, जो भरोसा करने के लिए बहुत पुराना है।", "homeInsightsNoVersionStamp": "सहेजे गए रोलअप पर कोई वर्शन स्टैंप नहीं है।", - "homeSyncBand": "स्ट्रैप सिंक करें", + "homeSyncBand": "डिवाइस सिंक करें", "homeCalibrating": "कैलिब्रेट हो रहा है", "homeCalibratingNights": "{need} में से {have} रातें", "homeCalibratingDays": "{need} में से {have} दिन", @@ -1598,7 +1604,7 @@ "wellnessLoadFailedBody": "आपका सहेजा गया डेटा पढ़ने में विफलता हुई। कुछ भी हटाया नहीं गया — यह पढ़ने में हुई गड़बड़ी है, डेटा गायब नहीं है।", "homeTryAgain": "फिर से कोशिश करें", "homeNothingDerivedTitle": "अभी तक कुछ भी नहीं निकाला गया", - "homeNothingDerivedBody": "आज रात बैंड पहनें और सुबह ऐप खोलें।", + "homeNothingDerivedBody": "आज रात अपना डिवाइस पहनें और सुबह ऐप खोलें।", "homeAskCoach": "कोच से पूछें", "homeProfileSettings": "प्रोफ़ाइल और सेटिंग्स", "homeNothingTodayTitle": "आज के लिए कुछ भी दर्ज नहीं", @@ -1779,7 +1785,7 @@ "sleepDetailNavTitle": "नींद", "sleepDetailNoNightTitle": "दिखाने के लिए कोई रात नहीं", "sleepDetailNoNightBody": "बैंड की रिकॉर्डिंग का कोई हिस्सा स्कोर करने लायक इतना लंबा नहीं है।", - "sleepDetailNoNightFix": "रातभर बैंड पहनें और सुबह सिंक करें", + "sleepDetailNoNightFix": "रातभर अपना डिवाइस पहनें और सुबह सिंक करें", "sleepDetailStagesSection": "चरण", "sleepDetailVersusUsualSection": "आपकी सामान्य नींद की तुलना में", "sleepDetailUnusualLastNight": "पिछली रात कुछ असामान्य", @@ -1988,6 +1994,7 @@ "activitySetupHeartRateLabel": "हृदय गति", "activitySetupBandConnected": "बैंड कनेक्टेड", "activitySetupNoBandConnected": "कोई बैंड कनेक्ट नहीं है", + "activitySetupNoLiveHr": "कोई लाइव हृदय गति नहीं", "activitySetupPrivateLabel": "प्राइवेट सेशन", "activitySetupPrivateDetail": "सारांश और एक्सपोर्ट से छिपा रहता है", "activitySetupCaloriesNeedWeight": "कैलोरी के लिए आपके वज़न की ज़रूरत है।", @@ -2018,7 +2025,7 @@ "dayStrainNoMinuteTraceTitle": "इस दिन के लिए मिनट-दर-मिनट ट्रेस नहीं है", "dayStrainNoReasonBody": "कोई रिकॉर्ड यह नहीं बताता कि इस दिन स्ट्रेन क्यों नहीं बना।", "dayStrainScoredNoTraceBody": "दिन का स्ट्रेन {strain} है। जिन जागने के मिनटों से यह बना था, वे इस दिन के लिए संग्रहीत नहीं हैं।", - "dayStrainWearBandFix": "पूरे दिन बैंड पहनें", + "dayStrainWearBandFix": "पूरे दिन अपना डिवाइस पहनें", "dayStrainChartTitle": "दिन भर का स्ट्रेन", "dayStrainChartFootnote": "यह संचयी है, इसलिए यह केवल बढ़ती है — जो हिस्से खड़ी ढलान जैसे हैं वहीं मेहनत हुई थी। {drawn} दर्ज किए गए जागने के मिनटों से बनाई गई।", "dayStrainPeakHr": "अधिकतम हृदय गति", @@ -2041,7 +2048,7 @@ "activityZonesNoCeilingTitle": "अभी तक कोई मापी गई ऊपरी सीमा नहीं", "activityZonesNoCeilingTanakaTail": " जब तक कोई मापा नहीं जाता, नीचे दिए गए ज़ोन आपकी उम्र पर आधारित हैं।", "activityZonesNoCeilingDefaultBody": "हम केवल वही उच्च रीडिंग गिनते हैं जिसे बैंड ने आपके चलते समय 15 सेकंड तक बनाए रखा हो। एक सेकंड की स्पाइक हृदय गति नहीं है।", - "activityZonesWearBandFix": "अपने सामान्य कठिन सत्रों के दौरान बैंड पहनें", + "activityZonesWearBandFix": "अपने सामान्य कठिन सत्रों के दौरान अपना डिवाइस पहनें", "activityZonesHighestSeenLabel": "अब तक देखा गया उच्चतम", "activityZonesBpmUnit": "bpm", "activityZonesCeilingOnDate": "{date} को", @@ -2683,6 +2690,8 @@ "wearableMethodStrap": "एक स्ट्रैप, हर सेकंड", "wearableMethodStrapBeats": "एक स्ट्रैप के धड़कन-दर-धड़कन अंतराल", "wearableMethodRhrStrapComposite": "आराम की हृदय गति और एक स्ट्रैप के धड़कन-दर-धड़कन अंतराल", + "wearableMethodDeviceHrvComposite": "आराम की हृदय गति और डिवाइस की अपनी HRV रीडिंग", + "wearableMethodDeviceRmssd": "डिवाइस की अपनी HRV रीडिंग, हमारी गिनी रात पर", "wearableMethodRingBeats": "इसके अपने धड़कन-दर-धड़कन अंतराल", "wearableUnlocksTitle": "यह वियरेबल क्या खोलता है", "wearableUnlocksOurs": "हमारे द्वारा मापा गया", @@ -3473,7 +3482,7 @@ "homeBackToToday": "आज पर वापस", "homeSomeDataMissingTitle": "आज का कुछ डेटा उपलब्ध नहीं है", "homeFirstWeekTitle": "आपके पहले कुछ सप्ताह", - "homeFirstWeekWear": "आज रात बैंड पहनें", + "homeFirstWeekWear": "आज रात अपना डिवाइस पहनें", "homeFirstWeekSleep": "नींद: आपकी पहली रात के बाद की सुबह", "homeFirstWeekStrain": "स्ट्रेन: दिन {day} से", "homeFirstWeekRecovery": "रिकवरी: रात {night} से, जब यह आपका सामान्य स्तर जान ले", @@ -3619,7 +3628,7 @@ "supplementCharging5f99fe": "चार्ज हो रहा है", "supplementCoefficientOfVariationOfPerc71989": "रात भर हर अवधि की साँस की दर का परिवर्तन गुणांक।", "supplementColeKripkeWakeSpineHRVcd5f37": "Cole–Kripke जागृति आधार + HRV परत", - "supplementCountedNeverModelledAStepc66896": "गिने जाते हैं, कभी अनुमान से नहीं बनाए जाते। कदम ऐसे काउंटर से आते हैं जो चाल पहचान सकता है: डेटा भेजते समय बैंड का 100 Hz पेडोमीटर, या आपके फ़ोन का। दिन का हर हिस्सा उसी से गिना जाता है जो उस समय सच में रिकॉर्ड कर रहा था, और जिस हिस्से को दोनों ने कवर किया उसे एक ही बार गिना जाता है, इसलिए कोई सत्र कभी पूरे दिन को उस सेंसर से नहीं छीनता जिसने बाकी दिन रिकॉर्ड किया। 1 Hz वाला कोई अनुमान नहीं है: चलने की गति उससे तेज़ है जिसे एक सेकंड में एक नमूना पकड़ सकता है, इसलिए जिस दिन कोई काउंटर नहीं था उस दिन अनुमान की जगह कोई कदम नहीं दिखाए जाते।", + "supplementCountedNeverModelledAStepc66896": "गिने जाते हैं, कभी अनुमान से नहीं बनाए जाते। कदम ऐसे काउंटर से आते हैं जो चाल पहचान सकता है: डेटा भेजते समय बैंड का 100 Hz पेडोमीटर, या आपके फ़ोन का। दिन का हर हिस्सा उसी से गिना जाता है जो उस समय सच में रिकॉर्ड कर रहा था, और जिस हिस्से को दोनों ने कवर किया उसे एक ही बार गिना जाता है, इसलिए कोई सत्र कभी पूरे दिन को उस सेंसर से नहीं छीनता जिसने बाकी दिन रिकॉर्ड किया। 1 Hz वाला कोई अनुमान नहीं है: चलने की गति उससे तेज़ है जिसे एक सेकंड में एक नमूना पकड़ सकता है, इसलिए जिस दिन कोई काउंटर नहीं था उस दिन अनुमान की जगह कोई कदम नहीं दिखाए जाते। जुड़े हुए वियरेबल की अपनी दैनिक गिनती तब दिन के कदम बनती है जब उसने ज़्यादा गिने हों, और तब वह पूरी ली जाती है, कभी दूसरों में जोड़ी नहीं जाती।", "supplementCreatinined3029a": "क्रिएटिनिन", "supplementDailyRecoveryReadinessFromYourf995c0": "आपका दैनिक रिकवरी स्कोर", "supplementDeepMin28f1fc": "गहरी नींद (मिनट)", @@ -3744,10 +3753,12 @@ "supplementTheHighestHeartRateHeldc1c878": "अब तक आपकी सबसे ऊँची हृदय गति आपकी उम्र के अनुमान से काफ़ी कम है, इसलिए जब तक बैंड कोई ज़्यादा कठिन प्रयास नहीं देखता, ज़ोन उम्र के अनुमान पर ही रहेंगे।", "supplementTheLowestSustainedSleepingHeart72e5dd": "रात में नींद के दौरान लगातार बनी रही सबसे कम हृदय गति, रात की श्रृंखला पर चलती विंडो से ली गई। यह एक बार की रीडिंग नहीं है, और न ही दिन का न्यूनतम।", "supplementTheNightSMeanRaw25e383": "रात भर सेंसर की औसत कच्ची रीडिंग, आपकी हाल की रातों से दूरी के रूप में। कहीं भी डिग्री में बदलाव नहीं किया जाता।", + "supplementSkinTempMethodTrend": "रात की औसत कच्ची सेंसर रीडिंग, जो आपकी हाल की रातों से दूरी के रूप में दिखाई जाती है। चार्ट का रुझान वही बिना कैलिब्रेट की गई ADC दूरी है, डिग्री में कोई रूपांतरण नहीं। (WHOOP 5 असली डिग्री में पढ़ता है; उसका रात का विचलन जीवन संकेत में आपकी तापमान इकाई में दिखाया जाता है।)", "supplementTheRatioOfLowTo817781": "धड़कनों के अंतराल की परिवर्तनशीलता में कम और उच्च आवृत्ति शक्ति का अनुपात, Lomb–Scargle पीरियडोग्राम से (श्रृंखला के नमूने समान अंतराल पर नहीं हैं, इसलिए FFT गलत होगा)।", "supplementThereIsNoRestingHeart36a9ca": "तुलना के लिए किसी स्कोर की गई रात की आराम हृदय गति नहीं है।", "supplementThereIsNoScoredNight5d353d": "इसे पढ़ने के लिए कोई स्कोर की गई रात नहीं है।", "supplementTheseRecordingsAreNotStamped66b52f": "इन रिकॉर्डिंग पर यह नहीं लिखा कि किस बैंड ने इन्हें बनाया, और इस मान को हर बैंड के लिए अलग कैलिब्रेट करना पड़ता है, इसलिए अनुमान लगाने की जगह इसे नहीं दिखाया जाता।", + "supplementNoCalibrationForThisDevice": "यह मान हर डिवाइस के लिए कैलिब्रेट करना होता है, और इस डिवाइस के लिए अभी कोई कैलिब्रेशन नहीं है, इसलिए इसका अनुमान लगाने के बजाय इसे रोका गया है।", "supplementThisDayCameFromAn2dc4b2": "यह दिन ऐसे आयात से आया है जिसमें केवल रात शामिल है, इसलिए जागने के समय का कुछ भी दर्ज नहीं है।", "supplementTimeAsleepAsAFraction516f7f": "बिस्तर पर बिताए समय में सोने के समय का हिस्सा।", "supplementTimeToMove7afe98": "थोड़ा चलने का समय", diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index f6f6f22eb..50f2efccf 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -460,6 +460,9 @@ "pairSensorKeyTitle": "Уже настроено в другом приложении?", "pairSensorKeyBody": "Есть ключ этого устройства? Вставьте его, чтобы обойтись без сброса. Несколько ключей, по одному в строке, пробуются по очереди. Оставьте пустым для обычного сопряжения.", "pairSensorKeyHint": "32 шестнадцатеричных символа или base64 — один ключ на строку", + "pairSensorKeyRequiredTitle": "Ключ устройства", + "pairSensorKeyRequiredBody": "Это устройство подключается только с ключом, который задало его собственное приложение. Вставьте этот один ключ: 32 шестнадцатеричные цифры.", + "pairSensorKeyRequiredHint": "32 шестнадцатеричные цифры", "pairSensorSearchAnyway": "Всё равно искать", "devicePickerTitle": "Подключите устройства", "devicePickerSubtitle": "Добавьте всё, чем пользуетесь. Другие устройства можно подключить позже.", @@ -1006,7 +1009,7 @@ }, "readinessDetailNoHistoryTitle": "Нет истории восстановления", "readinessDetailNoHistoryBody": "Оценённых дней: 0.", - "readinessDetailWearOvernight": "Носите браслет ночью", + "readinessDetailWearOvernight": "Носите устройство ночью", "readinessDetailUnit": "/100", "readinessDetailDaysAgo": "{n, plural, one{{n} день назад} few{{n} дня назад} many{{n} дней назад} other{{n} дня назад}}", "@readinessDetailDaysAgo": { @@ -1050,6 +1053,7 @@ "readinessDetailNotAvailable": "недоступно", "readinessDetailContributionNotReported": "вклад не указан", "readinessDetailRelativeUncalibrated": "относительное, без калибровки", + "readinessDetailFromDeviceReadings": "по собственным измерениям устройства", "readinessDetailWithinSpread": "да, в пределах обычного диапазона", "readinessDetailOutsideRange": "нет, вне обычного диапазона", "readinessDetailLiftingScore": "повышает оценку", @@ -1237,9 +1241,9 @@ "driverBreakdownToday": "Сегодня", "driverBreakdownAbsenceTitle": "Нет данных для разбивки", "driverBreakdownAbsenceAlgoVersion": "В последнем обновлении изменился расчёт восстановления. Ваши дни пересчитываются.", - "driverBreakdownAbsenceStale": "Тренды устарели. Синхронизируйте браслет, чтобы обновить их.", + "driverBreakdownAbsenceStale": "Тренды устарели. Синхронизируйте устройство, чтобы обновить их.", "driverBreakdownAbsenceNoVersion": "Тренды обновляются. После синхронизации это занимает около минуты.", - "driverBreakdownSyncTheBand": "Синхронизировать браслет", + "driverBreakdownSyncTheBand": "Синхронизировать устройство", "driverBreakdownAbsenceNoReason": "Причина отсутствия разбивки за прошлую ночь не записана.", "coachFiguresCouldNotBeDrawn": "Не удалось построить график", "coachFiguresNoType": "Тренер прислал график без указания типа.", @@ -1287,7 +1291,7 @@ "circadianDetailTitle": "Биологические часы", "circadianDetailNoNightsTitle": "Пока нет ночей для графика", "circadianDetailNoNightsBody": "Оценённых ночей: 0.", - "circadianDetailNoNightsFix": "Носите браслет ночью", + "circadianDetailNoNightsFix": "Носите устройство ночью", "circadianDetailSleepTitle": "Сон по ночам", "circadianDetailAsleep": "Сон", "circadianDetailSleepFootnote": "{count, plural, one{{count} ночь} few{{count} ночи} many{{count} ночей} other{{count} ночи}}, по столбцу на каждую; чем темнее, тем большая часть часа прошла во сне.", @@ -2475,7 +2479,8 @@ "metricDetailNoValueYet": "За сегодня значения пока нет.", "metricDetailNoValueYetWiderRanges": "За сегодня значения ещё нет. В более широких периодах выше есть дни с рассчитанными значениями.", "metricDetailNoValueInWindow": "За этот период значений нет.", - "metricDetailWearBandFix": "Носите браслет ночью для начала ряда", + "metricDetailWearBandFix": "Носите устройство ночью для начала ряда", + "metricDetailHrvNeedsBeatsFix": "Для этого графика нужны интервалы между ударами, записанные ночью; их даёт только устройство, которое записывает удары. Нагрудный датчик записывает только во время тренировок, а многие часы, кольца и браслеты вместо этого сообщают собственную ВСР: она на странице устройства", "metricDetailBreakdownLinkTitle": "Подробности", "metricDetailBreakdownLinkSub": "Каждый отрезок дня и источник его оценки", "metricDetailNerdStatsTitle": "Подробная статистика", @@ -3128,7 +3133,7 @@ }, "healthNothingMeasuredDay": "За этот день ничего не измерено", "healthNoBandRecordings": "Записи браслета за этот день не поступили.", - "healthSyncTheBand": "Синхронизировать браслет", + "healthSyncTheBand": "Синхронизировать устройство", "healthDeepDivesTitle": "Подробный разбор", "healthHeartRateVariability": "Вариабельность сердечного ритма", "healthTimeFrequencyNonLinear": "Временные, частотные и нелинейные показатели", @@ -3347,6 +3352,7 @@ "homeStepSensorStrapPhone": "Браслет + телефон", "homeStepSensorStrap": "Браслет", "homeStepSensorPhone": "Телефон", + "homeStepSensorDevice": "Устройство", "homeOvernightBuilding": "Данные прошлой ночи ещё обрабатываются.", "homeOvernightNothingYet": "Данные прошлой ночи ещё не поступили.", "homeMonthJanuary": "Январь", @@ -3422,8 +3428,8 @@ "homeWorkoutHoldBody": "Сегодняшний день заполнится, когда вы завершите тренировку.", "homeInsightsRebuildingTitle": "Обновляем ваши тренды", "homeInsightsRebuildingAlgoVersion": "Обновляется после последнего обновления приложения.", - "homeInsightsStaleOverWeek": "Тренды обновлялись больше недели назад. Синхронизируйте браслет, чтобы обновить их.", - "homeInsightsStaleOnDay": "Тренды обновлялись {day}. Синхронизируйте браслет, чтобы обновить их.", + "homeInsightsStaleOverWeek": "Тренды обновлялись больше недели назад. Синхронизируйте устройство, чтобы обновить их.", + "homeInsightsStaleOnDay": "Тренды обновлялись {day}. Синхронизируйте устройство, чтобы обновить их.", "@homeInsightsStaleOnDay": { "placeholders": { "day": { @@ -3433,7 +3439,7 @@ } }, "homeInsightsNoVersionStamp": "Тренды обновляются. После синхронизации это занимает около минуты.", - "homeSyncBand": "Синхронизировать браслет", + "homeSyncBand": "Синхронизировать устройство", "homeCalibrating": "Изучаем ваш обычный уровень", "homeCalibratingNights": "{have} из {need} ночей", "@homeCalibratingNights": { @@ -3577,7 +3583,7 @@ "wellnessLoadFailedBody": "Не удалось прочитать сохранённые данные. Ничего не удалено — это сбой чтения, а не отсутствие данных.", "homeTryAgain": "Повторить", "homeNothingDerivedTitle": "Ночей с оценкой пока нет", - "homeNothingDerivedBody": "Наденьте браслет на ночь и откройте приложение утром.", + "homeNothingDerivedBody": "Наденьте устройство на ночь и откройте приложение утром.", "homeSyncedThrough": "Данные по {when}", "@homeSyncedThrough": { "placeholders": { @@ -4059,7 +4065,7 @@ "sleepDetailNavTitle": "Сон", "sleepDetailNoNightTitle": "Нет ночи для просмотра", "sleepDetailNoNightBody": "Нет достаточно длинного отрезка записей браслета для расчёта.", - "sleepDetailNoNightFix": "Наденьте браслет на ночь и синхронизируйте утром", + "sleepDetailNoNightFix": "Наденьте устройство на ночь и синхронизируйте утром", "sleepDetailStagesSection": "Стадии", "sleepDetailVersusUsualSection": "В сравнении с обычным уровнем", "sleepDetailUnusualLastNight": "Необычные показатели прошлой ночи", @@ -4606,6 +4612,7 @@ "activitySetupHeartRateLabel": "Пульс", "activitySetupBandConnected": "Браслет подключён", "activitySetupNoBandConnected": "Браслет не подключён", + "activitySetupNoLiveHr": "Нет пульса в реальном времени", "activitySetupPrivateLabel": "Личная тренировка", "activitySetupWorkLabel": "Работа", "activitySetupRestLabel": "Отдых", @@ -4682,7 +4689,7 @@ } } }, - "dayStrainWearBandFix": "Носите браслет в течение дня", + "dayStrainWearBandFix": "Носите устройство в течение дня", "dayStrainChartTitle": "Нагрузка в течение дня", "dayStrainChartFootnote": "Усилие выше вашего обычного темпа бодрствования. Позже может снизиться, если вы вернётесь к этому темпу. По {drawn} записанным минутам бодрствования.", "@dayStrainChartFootnote": { @@ -4740,7 +4747,7 @@ "activityZonesNoCeilingTitle": "Максимальный пульс ещё не измерен", "activityZonesNoCeilingTanakaTail": " Пока максимум не измерен, зоны ниже определяются по возрасту.", "activityZonesNoCeilingDefaultBody": "Учитывается только высокий пульс, сохранявшийся 15 секунд во время движения. Односекундный скачок не считается пульсом.", - "activityZonesWearBandFix": "Носите браслет на обычных интенсивных тренировках", + "activityZonesWearBandFix": "Носите устройство на обычных интенсивных тренировках", "activityZonesHighestSeenLabel": "НАИБОЛЬШИЙ ИЗМЕРЕННЫЙ", "activityZonesBpmUnit": "уд/мин", "activityZonesCeilingOnDate": "за {date}", @@ -6588,7 +6595,7 @@ "supplementCharging5f99fe": "Зарядка", "supplementCoefficientOfVariationOfPerc71989": "Коэффициент вариации частоты дыхания по отрезкам ночи.", "supplementColeKripkeWakeSpineHRVcd5f37": "Определение бодрствования Cole–Kripke + оценка по ВСР", - "supplementCountedNeverModelledAStepc66896": "Шаги подсчитываются, а не моделируются. Источник — шагомер браслета с частотой 100 Гц при потоковой записи либо шагомер телефона. Каждый отрезок дня учитывается по реально записывавшему его устройству; перекрытия учитываются один раз. Тренировка не заменяет источник для остальной части дня. Оценки по данным 1 Гц нет: частота шагов слишком высока для одного отсчёта в секунду. Без записей шагомера значение отсутствует, а не угадывается.", + "supplementCountedNeverModelledAStepc66896": "Шаги подсчитываются, а не моделируются. Источник — шагомер браслета с частотой 100 Гц при потоковой записи либо шагомер телефона. Каждый отрезок дня учитывается по реально записывавшему его устройству; перекрытия учитываются один раз. Тренировка не заменяет источник для остальной части дня. Оценки по данным 1 Гц нет: частота шагов слишком высока для одного отсчёта в секунду. Без записей шагомера значение отсутствует, а не угадывается. Собственный дневной счёт подключённого носимого устройства становится шагами за день, если он больше; тогда он берётся целиком и никогда не складывается с остальными.", "supplementCreatinined3029a": "Креатинин", "supplementDailyRecoveryReadinessFromYourf995c0": "Ваша ежедневная оценка восстановления", "supplementDeepMin28f1fc": "Глубокий сон, мин", @@ -6715,10 +6722,12 @@ "supplementTheHighestHeartRateHeldc1c878": "Ваш максимальный пульс пока заметно ниже ожидаемого для возраста, поэтому зоны остаются по возрасту, пока браслет не увидит более тяжёлое усилие.", "supplementTheLowestSustainedSleepingHeart72e5dd": "Самый низкий устойчивый пульс во сне за ночь, определённый скользящим окном по ночной записи. Это не разовое измерение и не дневной минимум.", "supplementTheNightSMeanRaw25e383": "Среднее необработанное показание датчика за ночь, выраженное как отклонение от ваших недавних ночей. Преобразования в градусы нет ни на одном этапе.", + "supplementSkinTempMethodTrend": "Средний сырой показатель датчика за ночь, выраженный как отклонение от ваших недавних ночей. На графике — это некалиброванное отклонение АЦП, без перевода в градусы. (WHOOP 5 измеряет в настоящих градусах; его ночное отклонение показано в разделе «Показатели» в вашей единице температуры.)", "supplementTheRatioOfLowTo817781": "Отношение мощности низких и высоких частот вариабельности межударных интервалов по периодограмме Ломба — Скаргла. Отсчёты неравномерны, поэтому БПФ здесь не подходит.", "supplementThereIsNoRestingHeart36a9ca": "Нет пульса в покое из рассчитанной ночи для сравнения.", "supplementThereIsNoScoredNight5d353d": "Нет рассчитанной ночи для получения показателя.", "supplementTheseRecordingsAreNotStamped66b52f": "В записях не указано, какой браслет их сделал. Показатель требует калибровки для каждого браслета, поэтому значение не угадывается и не показывается.", + "supplementNoCalibrationForThisDevice": "Это значение нужно калибровать для каждого устройства, а для этого калибровки пока нет, поэтому оно не показывается, а не угадывается.", "supplementThisDayCameFromAn2dc4b2": "Этот день получен из импорта, где есть только ночь, поэтому за время бодрствования данных нет.", "supplementTimeAsleepAsAFraction516f7f": "Доля времени сна во времени, проведённом в постели.", "supplementTimeToMove7afe98": "Пора двигаться", @@ -7097,6 +7106,8 @@ "wearableMethodRest": "покой по пульсу за 5 минут", "wearableMethodRhrOnly": "только пульс в покое", "wearableMethodRhrStrapComposite": "пульс в покое и интервалы между ударами с нагрудного датчика", + "wearableMethodDeviceHrvComposite": "пульс в покое и собственные измерения ВСР устройства", + "wearableMethodDeviceRmssd": "собственные измерения ВСР устройства за нашу ночь", "wearableMethodRingBeats": "его собственные интервалы между ударами", "wearableMethodSkinTemp": "температура кожи", "wearableMethodStrap": "нагрудный датчик, каждую секунду", @@ -7628,7 +7639,7 @@ "homeBackToToday": "Вернуться к сегодняшнему дню", "homeSomeDataMissingTitle": "Часть сегодняшних данных отсутствует", "homeFirstWeekTitle": "Ваши первые недели", - "homeFirstWeekWear": "Наденьте браслет на ночь", + "homeFirstWeekWear": "Наденьте устройство на ночь", "homeFirstWeekSleep": "Сон: утром после первой ночи", "homeFirstWeekStrain": "Нагрузка: с {day}-го дня", "@homeFirstWeekStrain": { diff --git a/lib/l10n/app_th.arb b/lib/l10n/app_th.arb index 044576d30..dd5678a78 100644 --- a/lib/l10n/app_th.arb +++ b/lib/l10n/app_th.arb @@ -1067,6 +1067,9 @@ "description": "Explainer under the existing-key section title." }, "pairSensorKeyHint": "เลขฐานสิบหก 32 หลัก หรือ base64 — บรรทัดละหนึ่งคีย์", + "pairSensorKeyRequiredTitle": "คีย์ของอุปกรณ์", + "pairSensorKeyRequiredBody": "อุปกรณ์นี้จับคู่ได้เฉพาะกับคีย์ที่แอปของอุปกรณ์ตั้งไว้เท่านั้น วางคีย์นั้นหนึ่งคีย์: เลขฐานสิบหก 32 หลัก", + "pairSensorKeyRequiredHint": "เลขฐานสิบหก 32 หลัก", "@pairSensorKeyHint": { "description": "Hint text in the existing-key field." }, @@ -2192,7 +2195,7 @@ "@readinessDetailNoHistoryBody": { "description": "Status card body stating 0 days scored." }, - "readinessDetailWearOvernight": "สวมสายรัดขณะนอน", + "readinessDetailWearOvernight": "สวมอุปกรณ์ขณะนอน", "@readinessDetailWearOvernight": { "description": "Fix button label suggesting the user wear the band overnight." }, @@ -2264,6 +2267,7 @@ "description": "Breakdown row tag: input was used but its numeric contribution was not reported." }, "readinessDetailRelativeUncalibrated": "ค่าเชิงสัมพัทธ์ ยังไม่ปรับเทียบ", + "readinessDetailFromDeviceReadings": "จากค่าที่อุปกรณ์ของคุณวัดเอง", "@readinessDetailRelativeUncalibrated": { "description": "Breakdown row tag on the temperature input: it is a relative, uncalibrated sensor deviation." }, @@ -2625,7 +2629,7 @@ "@driverBreakdownAbsenceAlgoVersion": { "description": "Absence card body when the breakdown is missing because the algorithm version changed and is rebuilding." }, - "driverBreakdownAbsenceStale": "แนวโน้มของคุณยังไม่เป็นปัจจุบัน ซิงค์สายรัดเพื่ออัปเดต", + "driverBreakdownAbsenceStale": "แนวโน้มของคุณยังไม่เป็นปัจจุบัน ซิงค์อุปกรณ์เพื่ออัปเดต", "@driverBreakdownAbsenceStale": { "description": "Absence card body when the last stored rollup is too old to show." }, @@ -2633,7 +2637,7 @@ "@driverBreakdownAbsenceNoVersion": { "description": "Absence card body when the stored rollup has no version stamp." }, - "driverBreakdownSyncTheBand": "ซิงค์สายรัด", + "driverBreakdownSyncTheBand": "ซิงค์อุปกรณ์", "@driverBreakdownSyncTheBand": { "description": "Absence card action button: sync the band to refresh the rollup." }, @@ -2733,7 +2737,7 @@ "@circadianDetailNoNightsBody": { "description": "Empty-state body under circadianDetailNoNightsTitle" }, - "circadianDetailNoNightsFix": "สวมสายรัดขณะนอน", + "circadianDetailNoNightsFix": "สวมอุปกรณ์ขณะนอน", "@circadianDetailNoNightsFix": { "description": "Empty-state suggested fix action" }, @@ -5559,7 +5563,8 @@ "@metricDetailNoValueInWindow": { "description": "Empty-state body for a multi-day window with no value in it." }, - "metricDetailWearBandFix": "สวมสายรัดขณะนอนเพื่อเริ่มมีชุดข้อมูล", + "metricDetailWearBandFix": "สวมอุปกรณ์ขณะนอนเพื่อเริ่มมีชุดข้อมูล", + "metricDetailHrvNeedsBeatsFix": "กราฟนี้ต้องใช้ช่วงห่างระหว่างการเต้นแต่ละครั้งที่บันทึกขณะนอน ซึ่งได้จากอุปกรณ์ที่บันทึกการเต้นของหัวใจเท่านั้น สายรัดหน้าอกบันทึกเฉพาะระหว่างออกกำลังกาย และนาฬิกา แหวน และสายรัดหลายรุ่นรายงาน HRV ของตัวเองแทน ซึ่งอยู่ในหน้าอุปกรณ์", "@metricDetailWearBandFix": { "description": "Empty-state fix suggestion telling the user to wear the band overnight." }, @@ -6720,7 +6725,7 @@ "@healthNoBandRecordings": { "description": "Vitals empty-state body" }, - "healthSyncTheBand": "ซิงค์สายรัด", + "healthSyncTheBand": "ซิงค์อุปกรณ์", "@healthSyncTheBand": { "description": "Vitals empty-state fix button: sync the band" }, @@ -7103,6 +7108,7 @@ "description": "Step count sensor label: the strap counted." }, "homeStepSensorPhone": "โทรศัพท์", + "homeStepSensorDevice": "อุปกรณ์", "@homeStepSensorPhone": { "description": "Step count sensor label: the phone counted." }, @@ -7328,11 +7334,11 @@ "@homeInsightsRebuildingAlgoVersion": { "description": "Reason the cross-day rollup is being rebuilt: the algorithm version changed." }, - "homeInsightsStaleOverWeek": "อัปเดตแนวโน้มล่าสุดเกินหนึ่งสัปดาห์แล้ว ซิงค์สายรัดเพื่ออัปเดต", + "homeInsightsStaleOverWeek": "อัปเดตแนวโน้มล่าสุดเกินหนึ่งสัปดาห์แล้ว ซิงค์อุปกรณ์เพื่ออัปเดต", "@homeInsightsStaleOverWeek": { "description": "Reason the cross-day rollup is being rebuilt: the last rollup is more than a week old." }, - "homeInsightsStaleOnDay": "อัปเดตแนวโน้มล่าสุดเมื่อ {day} ซิงค์สายรัดเพื่ออัปเดต", + "homeInsightsStaleOnDay": "อัปเดตแนวโน้มล่าสุดเมื่อ {day} ซิงค์อุปกรณ์เพื่ออัปเดต", "@homeInsightsStaleOnDay": { "description": "Reason the cross-day rollup is being rebuilt: names the day the last rollup was built.", "placeholders": { @@ -7346,7 +7352,7 @@ "@homeInsightsNoVersionStamp": { "description": "Reason the cross-day rollup is being rebuilt: the stored rollup has no version stamp." }, - "homeSyncBand": "ซิงค์สายรัด", + "homeSyncBand": "ซิงค์อุปกรณ์", "@homeSyncBand": { "description": "Call-to-action button label: sync the band." }, @@ -7558,7 +7564,7 @@ "@homeNothingDerivedTitle": { "description": "Title shown on a first-run day with nothing derived yet." }, - "homeNothingDerivedBody": "สวมสายรัดคืนนี้ แล้วเปิดแอปตอนเช้า", + "homeNothingDerivedBody": "สวมอุปกรณ์คืนนี้ แล้วเปิดแอปตอนเช้า", "@homeNothingDerivedBody": { "description": "Body shown on a first-run day with nothing derived yet." }, @@ -8550,7 +8556,7 @@ "@sleepDetailNoNightBody": { "description": "Status card body explaining why there is no night." }, - "sleepDetailNoNightFix": "สวมสายรัดขณะนอนแล้วซิงค์ตอนเช้า", + "sleepDetailNoNightFix": "สวมอุปกรณ์ขณะนอนแล้วซิงค์ตอนเช้า", "@sleepDetailNoNightFix": { "description": "Suggested fix line on the no-night status card." }, @@ -9673,6 +9679,7 @@ "description": "Detail text when the band is connected, shown under the heart rate row" }, "activitySetupNoBandConnected": "ไม่มีสายรัดเชื่อมต่อ", + "activitySetupNoLiveHr": "ไม่มีอัตราการเต้นของหัวใจแบบสด", "@activitySetupNoBandConnected": { "description": "Detail text when no band is connected, shown under the heart rate row" }, @@ -9844,7 +9851,7 @@ } } }, - "dayStrainWearBandFix": "สวมสายรัดตลอดวัน", + "dayStrainWearBandFix": "สวมอุปกรณ์ตลอดวัน", "@dayStrainWearBandFix": { "description": "Suggested fix action on the no-strain-trace card, shown when the band never saw the day" }, @@ -9961,7 +9968,7 @@ "@activityZonesNoCeilingDefaultBody": { "description": "Default explanation of the 15-second hold rule for a measured ceiling, shown when no other reason was given" }, - "activityZonesWearBandFix": "สวมสายรัดระหว่างการออกกำลังกายหนักตามปกติ", + "activityZonesWearBandFix": "สวมอุปกรณ์ระหว่างการออกกำลังกายหนักตามปกติ", "@activityZonesWearBandFix": { "description": "Suggested fix action on the no-ceiling card" }, @@ -13657,7 +13664,7 @@ "@supplementColeKripkeWakeSpineHRVcd5f37": { "description": "Presentation-only text for existing interface, exports or notifications." }, - "supplementCountedNeverModelledAStepc66896": "นับจริง ไม่ใช้แบบจำลอง จำนวนก้าวมาจากตัวนับที่อ่านรูปแบบการเดินได้ ได้แก่ตัวนับ 100 Hz ของสายรัดขณะสตรีมหรือของโทรศัพท์ แต่ละช่วงใช้เซ็นเซอร์ที่บันทึกจริง ช่วงที่ทั้งสองบันทึกจะนับเพียงครั้งเดียว การออกกำลังกายจึงไม่เปลี่ยนแหล่งข้อมูลของทั้งวันแทนเซ็นเซอร์ที่บันทึกช่วงที่เหลือ ไม่มีค่าประมาณจาก 1 Hz เพราะจังหวะเดินสูงเกินกว่าหนึ่งตัวอย่างต่อวินาทีจะแยกได้ วันที่ไม่มีตัวนับจึงไม่รายงานก้าวแทนการเดา", + "supplementCountedNeverModelledAStepc66896": "นับจริง ไม่ใช้แบบจำลอง จำนวนก้าวมาจากตัวนับที่อ่านรูปแบบการเดินได้ ได้แก่ตัวนับ 100 Hz ของสายรัดขณะสตรีมหรือของโทรศัพท์ แต่ละช่วงใช้เซ็นเซอร์ที่บันทึกจริง ช่วงที่ทั้งสองบันทึกจะนับเพียงครั้งเดียว การออกกำลังกายจึงไม่เปลี่ยนแหล่งข้อมูลของทั้งวันแทนเซ็นเซอร์ที่บันทึกช่วงที่เหลือ ไม่มีค่าประมาณจาก 1 Hz เพราะจังหวะเดินสูงเกินกว่าหนึ่งตัวอย่างต่อวินาทีจะแยกได้ วันที่ไม่มีตัวนับจึงไม่รายงานก้าวแทนการเดา จำนวนก้าวรายวันของอุปกรณ์สวมใส่ที่จับคู่ไว้จะเป็นจำนวนก้าวของวันเมื่อมันนับได้มากกว่า โดยใช้ทั้งหมดและไม่บวกรวมกับตัวอื่น", "@supplementCountedNeverModelledAStepc66896": { "description": "Presentation-only text for existing interface, exports or notifications." }, @@ -14162,6 +14169,7 @@ "description": "Presentation-only text for existing interface, exports or notifications." }, "supplementTheNightSMeanRaw25e383": "ค่าเฉลี่ยเซ็นเซอร์ดิบของคืน แสดงเป็นความต่างจากคืนล่าสุด ๆ ของคุณ ไม่มีขั้นตอนใดแปลงเป็นองศา", + "supplementSkinTempMethodTrend": "ค่าเฉลี่ยดิบของเซ็นเซอร์ตลอดคืน แสดงเป็นระยะห่างจากคืนล่าสุดของคุณเอง แนวโน้มในกราฟคือระยะห่าง ADC ที่ยังไม่สอบเทียบนั้น โดยไม่แปลงเป็นองศา (WHOOP 5 วัดเป็นองศาจริง ค่าเบี่ยงเบนรายคืนของมันจะแสดงในหน้าสัญญาณชีพตามหน่วยอุณหภูมิของคุณแทน)", "@supplementTheNightSMeanRaw25e383": { "description": "Presentation-only text for existing interface, exports or notifications." }, @@ -14178,6 +14186,7 @@ "description": "Presentation-only text for existing interface, exports or notifications." }, "supplementTheseRecordingsAreNotStamped66b52f": "ข้อมูลนี้ไม่ได้ระบุว่าสายรัดใดบันทึก และค่านี้ต้องปรับเทียบรายสายรัด จึงไม่แสดงแทนการเดา", + "supplementNoCalibrationForThisDevice": "ค่านี้ต้องปรับเทียบแยกตามอุปกรณ์ และยังไม่มีการปรับเทียบสำหรับอุปกรณ์นี้ จึงงดแสดงแทนการคาดเดา", "@supplementTheseRecordingsAreNotStamped66b52f": { "description": "Presentation-only text for existing interface, exports or notifications." }, @@ -14911,6 +14920,8 @@ "wearableMethodStrap": "สายคาดวัดหัวใจ ทุกวินาที", "wearableMethodStrapBeats": "ช่วงเวลาระหว่างจังหวะหัวใจจากสายคาด", "wearableMethodRhrStrapComposite": "อัตราการเต้นหัวใจขณะพักและช่วงเวลาจังหวะหัวใจจากสายคาด", + "wearableMethodDeviceHrvComposite": "อัตราการเต้นหัวใจขณะพักและค่า HRV ที่อุปกรณ์วัดเอง", + "wearableMethodDeviceRmssd": "ค่า HRV ที่อุปกรณ์วัดเอง ตลอดคืนที่เรากำหนด", "wearableMethodRingBeats": "ช่วงเวลาระหว่างจังหวะหัวใจของอุปกรณ์เอง", "wearableUnlocksTitle": "สิ่งที่อุปกรณ์นี้ช่วยให้ใช้ได้", "wearableUnlocksOurs": "เราเป็นผู้วัด", @@ -15673,7 +15684,7 @@ "@homeFirstWeekTitle": { "description": "Today tab: card saying when each score first appears." }, - "homeFirstWeekWear": "สวมสายรัดคืนนี้", + "homeFirstWeekWear": "สวมอุปกรณ์คืนนี้", "@homeFirstWeekWear": { "description": "First weeks card step." }, diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 04fd576a9..6be0421b6 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -292,6 +292,9 @@ "pairSensorKeyTitle": "已在其他地方设置过?", "pairSensorKeyBody": "如果你有这台设备已在使用的密钥,粘贴到这里即可配对,无需恢复出厂设置,也不会向设备写入任何内容。可以每行一个地粘贴多个密钥,系统会逐个尝试直到其中一个被接受——当你有好几个密钥却不确定哪个属于这台设备时很方便。留空则按常规方式配对。", "pairSensorKeyHint": "32 位十六进制或 base64 —— 每行一个密钥", + "pairSensorKeyRequiredTitle": "设备密钥", + "pairSensorKeyRequiredBody": "此设备只能用其自带应用设置的密钥配对。粘贴这一个密钥:32 位十六进制数字。", + "pairSensorKeyRequiredHint": "32 位十六进制数字", "pairSensorSearchAnyway": "仍然搜索", "pairSensorSearching": "搜索中…", "pairSensorSearchForSensors": "搜索传感器", @@ -488,7 +491,7 @@ "readinessDetailLastNDays": "{n, plural, other{最近 {n} 天}}", "readinessDetailNoHistoryTitle": "没有身体准备度历史记录", "readinessDetailNoHistoryBody": "已评分天数:0 天。", - "readinessDetailWearOvernight": "整夜佩戴腕带", + "readinessDetailWearOvernight": "整夜佩戴设备", "readinessDetailUnit": "/100", "readinessDetailDaysAgo": "{n, plural, other{{n} 天前}}", "readinessDetailToday": "今天", @@ -500,6 +503,7 @@ "readinessDetailNotAvailable": "不可用", "readinessDetailContributionNotReported": "未报告贡献值", "readinessDetailRelativeUncalibrated": "相对值,未校准", + "readinessDetailFromDeviceReadings": "来自设备自身的读数", "readinessDetailWithinSpread": "在你的常规波动范围内", "readinessDetailWeightPercent": "权重 {pct}%", "dayStepsTitle": "步数", @@ -562,7 +566,7 @@ "driverBreakdownAbsenceAlgoVersion": "上次更新改变了恢复力的计算方式,目前正在重新生成。", "driverBreakdownAbsenceStale": "上一次汇总数据太旧,无法采信。", "driverBreakdownAbsenceNoVersion": "你的趋势正在更新,同步后大约需要一分钟。", - "driverBreakdownSyncTheBand": "同步腕带", + "driverBreakdownSyncTheBand": "同步设备", "driverBreakdownAbsenceNoReason": "没有任何记录说明昨晚为什么没有明细数据。", "coachFiguresCouldNotBeDrawn": "无法绘制图表", "coachFiguresNoType": "教练发送了一个没有指定类型的图表。", @@ -582,7 +586,7 @@ "circadianDetailTitle": "生理时钟", "circadianDetailNoNightsTitle": "暂无可绘制的夜晚", "circadianDetailNoNightsBody": "已评分 0 个夜晚。", - "circadianDetailNoNightsFix": "夜间佩戴腕带", + "circadianDetailNoNightsFix": "夜间佩戴设备", "circadianDetailSleepTitle": "睡眠,逐夜呈现", "circadianDetailAsleep": "睡眠中", "circadianDetailSleepFootnote": "{count, plural, other{共 {count} 晚,每晚一列。颜色越深,表示该小时睡眠时间越长。}}", @@ -1178,7 +1182,8 @@ "metricDetailNoValueYet": "今天还没有产生数值。", "metricDetailNoValueYetWiderRanges": "今天还没有产生数值。上方更宽的时间范围里有已产生数值的日子。", "metricDetailNoValueInWindow": "此时间范围内没有一天产生数值。", - "metricDetailWearBandFix": "整夜佩戴腕带以开始记录", + "metricDetailWearBandFix": "整夜佩戴设备以开始记录", + "metricDetailHrvNeedsBeatsFix": "此图表需要夜间记录的逐搏间期,只有记录心跳的设备才能提供。胸带只在锻炼时记录,许多手表、戒指和腕带则报告它们自己的 HRV:它显示在设备页面", "metricDetailBreakdownLinkTitle": "明细", "metricDetailBreakdownLinkSub": "今天的每一段,以及是什么统计了它", "metricDetailNerdStatsTitle": "极客统计", @@ -1379,7 +1384,7 @@ "healthCoverageOf": "{day}的{pct}%", "healthNothingMeasuredDay": "这一天没有测得任何数据", "healthNoBandRecordings": "这一天没有收到腕带的记录数据。", - "healthSyncTheBand": "同步腕带", + "healthSyncTheBand": "同步设备", "healthDeepDivesTitle": "深入分析", "healthHeartRateVariability": "心率变异性", "healthTimeFrequencyNonLinear": "时域、频域与非线性", @@ -1449,6 +1454,7 @@ "homeStepSensorStrapPhone": "腕带 + 手机", "homeStepSensorStrap": "腕带", "homeStepSensorPhone": "手机", + "homeStepSensorDevice": "设备", "homeOvernightBuilding": "昨晚的数据仍在处理中。", "homeOvernightNothingYet": "昨晚的数据还没有同步到应用。", "homeMonthJanuary": "1月", @@ -1504,7 +1510,7 @@ "homeInsightsStaleOverWeek": "上次汇总是一周多以前生成的,太旧了,不宜依赖。", "homeInsightsStaleOnDay": "上次汇总是在 {day} 生成的,太旧了,不宜依赖。", "homeInsightsNoVersionStamp": "你的趋势正在更新,同步后大约需要一分钟。", - "homeSyncBand": "同步腕带", + "homeSyncBand": "同步设备", "homeCalibrating": "校准中", "homeCalibratingNights": "已有 {have}/{need} 晚", "homeCalibratingDays": "已有 {have}/{need} 天", @@ -1598,7 +1604,7 @@ "wellnessLoadFailedBody": "读取已存储的数据失败。没有删除任何内容——这是一次读取出错,而不是数据缺失。", "homeTryAgain": "重试", "homeNothingDerivedTitle": "尚未计算出任何数据", - "homeNothingDerivedBody": "尚未处理任何腕带记录。", + "homeNothingDerivedBody": "尚未处理任何设备记录。", "homeAskCoach": "咨询教练", "homeProfileSettings": "个人资料与设置", "homeNothingTodayTitle": "今天没有记录到数据", @@ -1779,7 +1785,7 @@ "sleepDetailNavTitle": "睡眠", "sleepDetailNoNightTitle": "没有可显示的夜间数据", "sleepDetailNoNightBody": "手环记录的时长不足以进行评分。", - "sleepDetailNoNightFix": "整夜佩戴手环,早上同步数据", + "sleepDetailNoNightFix": "整夜佩戴设备,早上同步数据", "sleepDetailStagesSection": "睡眠阶段", "sleepDetailVersusUsualSection": "与你的日常对比", "sleepDetailUnusualLastNight": "昨晚的异常情况", @@ -1988,6 +1994,7 @@ "activitySetupHeartRateLabel": "心率", "activitySetupBandConnected": "已连接手环", "activitySetupNoBandConnected": "未连接手环", + "activitySetupNoLiveHr": "无实时心率", "activitySetupPrivateLabel": "隐私训练", "activitySetupPrivateDetail": "不会出现在摘要或导出内容中", "activitySetupCaloriesNeedWeight": "计算卡路里需要你的体重。", @@ -2683,6 +2690,8 @@ "wearableMethodStrap": "心率带,每秒", "wearableMethodStrapBeats": "心率带的逐搏间期", "wearableMethodRhrStrapComposite": "静息心率和心率带的逐搏间期", + "wearableMethodDeviceHrvComposite": "静息心率和设备自身的 HRV 读数", + "wearableMethodDeviceRmssd": "设备自身的 HRV 读数,按我们界定的夜间计算", "wearableMethodRingBeats": "其自身的逐搏间期", "wearableUnlocksTitle": "此可穿戴设备可解锁的内容", "wearableUnlocksOurs": "由我们测量", @@ -3471,7 +3480,7 @@ "homeBackToToday": "回到今天", "homeSomeDataMissingTitle": "今天的部分数据缺失", "homeFirstWeekTitle": "你的最初几周", - "homeFirstWeekWear": "今晚请佩戴腕带", + "homeFirstWeekWear": "今晚请佩戴设备", "homeFirstWeekSleep": "睡眠:第一晚之后的早上", "homeFirstWeekStrain": "消耗:从第 {day} 天起", "homeFirstWeekRecovery": "恢复:从第 {night} 晚起,了解你的正常水平之后", @@ -3619,7 +3628,7 @@ "supplementCharging5f99fe": "充电中", "supplementCoefficientOfVariationOfPerc71989": "整晚各窗口呼吸频率的变异系数。", "supplementColeKripkeWakeSpineHRVcd5f37": "Cole–Kripke 清醒基线 + 心率变异性叠加", - "supplementCountedNeverModelledAStepc66896": "只计数,从不建模。步数来自能识别步态的计数器:手环在传输数据时的 100 Hz 计步器,或你手机的计步器。一天中的每一段都由实际在记录的那一方计数,两者都覆盖的时段只计一次,因此一次训练绝不会让当天的步数改由另一个传感器决定。没有 1 Hz 的估算值:走路的步频超出了每秒一次采样能分辨的范围,所以没有计数器的日子会显示没有步数,而不是一个猜测值。", + "supplementCountedNeverModelledAStepc66896": "只计数,从不建模。步数来自能识别步态的计数器:手环在传输数据时的 100 Hz 计步器,或你手机的计步器。一天中的每一段都由实际在记录的那一方计数,两者都覆盖的时段只计一次,因此一次训练绝不会让当天的步数改由另一个传感器决定。没有 1 Hz 的估算值:走路的步频超出了每秒一次采样能分辨的范围,所以没有计数器的日子会显示没有步数,而不是一个猜测值。 已配对穿戴设备自身的每日计数若更多,就作为当天的步数,整体采用,绝不与其他来源相加。", "supplementCreatinined3029a": "肌酐", "supplementDailyRecoveryReadinessFromYourf995c0": "你的每日恢复评分", "supplementDeepMin28f1fc": "深睡(分钟)", @@ -3744,10 +3753,12 @@ "supplementTheHighestHeartRateHeldc1c878": "你目前的最高心率远低于你的年龄预测值,因此在手环记录到更高强度的运动之前,心率区间仍按年龄估算。", "supplementTheLowestSustainedSleepingHeart72e5dd": "夜间睡眠中持续保持的最低心率,在夜间序列上用滑动窗口取得。不是单次读数,也不是白天的最低值。", "supplementTheNightSMeanRaw25e383": "夜间传感器原始读数的平均值,以与你最近几晚的差距表示。整个过程中都没有换算成摄氏度。", + "supplementSkinTempMethodTrend": "夜间传感器原始读数的平均值,以与你自己近期夜晚的差距表示。图表中的趋势就是这个未校准的 ADC 差距,不换算成度数。(WHOOP 5 以真实度数读数;其夜间偏差会改为在“生命体征”中以你的温度单位显示。)", "supplementTheRatioOfLowTo817781": "心跳间期变异性中低频与高频功率之比,来自 Lomb–Scargle 周期图(该序列采样不均匀,因此用 FFT 会出错)。", "supplementThereIsNoRestingHeart36a9ca": "没有来自已评分夜晚的静息心率可供比较。", "supplementThereIsNoScoredNight5d353d": "没有可供读取的已评分夜晚。", "supplementTheseRecordingsAreNotStamped66b52f": "这些记录没有标明来自哪个手环,而这个数值需要针对每个手环校准,因此不予显示,而不是猜测。", + "supplementNoCalibrationForThisDevice": "这个数值需要按设备分别校准,而这台设备还没有校准,所以不显示,而不是猜测。", "supplementThisDayCameFromAn2dc4b2": "这一天来自只包含夜间数据的导入,因此清醒时段没有任何记录。", "supplementTimeAsleepAsAFraction516f7f": "睡眠时长占卧床时间的比例。", "supplementTimeToMove7afe98": "该活动一下了", diff --git a/lib/l10n/display_text.dart b/lib/l10n/display_text.dart index 2cc0f75d1..4e2881839 100644 --- a/lib/l10n/display_text.dart +++ b/lib/l10n/display_text.dart @@ -362,7 +362,7 @@ String localizedText(AppLocalizations? l, String text) { l.supplementCoefficientOfVariationOfPerc71989, "Cole–Kripke wake spine + HRV overlay" => l.supplementColeKripkeWakeSpineHRVcd5f37, - "Counted, never modelled. A step count comes from a gait-capable counter: the band's 100 Hz pedometer while it streams, or your phone's. Each stretch of the day is counted by whichever of the two was actually recording it, and a stretch both covered is counted once, so a session never takes the day from the sensor that carried the rest of it. There is no 1 Hz estimate — walking cadence sits above what one sample a second can resolve, so a day with no counter behind it reports no steps rather than a guess." => + "Counted, never modelled. A step count comes from a gait-capable counter: the band's 100 Hz pedometer while it streams, or your phone's. Each stretch of the day is counted by whichever of the two was actually recording it, and a stretch both covered is counted once, so a session never takes the day from the sensor that carried the rest of it. There is no 1 Hz estimate — walking cadence sits above what one sample a second can resolve, so a day with no counter behind it reports no steps rather than a guess. A paired wearable's own daily count is the day's steps when it counted more than these, used whole and never added to them." => l.supplementCountedNeverModelledAStepc66896, "Creatinine" => l.supplementCreatinined3029a, "Your daily recovery score" => @@ -555,6 +555,8 @@ String localizedText(AppLocalizations? l, String text) { l.supplementTheLowestSustainedSleepingHeart72e5dd, "The night's mean raw sensor reading, expressed as distance from your own recent nights. There is no conversion to degrees anywhere in the path." => l.supplementTheNightSMeanRaw25e383, + "The night's mean raw sensor reading, expressed as distance from your own recent nights. The charted trend is that uncalibrated ADC distance, with no conversion to degrees. (A WHOOP 5 reads in real degrees; its nightly deviation is shown on Vitals in your temperature unit instead.)" => + l.supplementSkinTempMethodTrend, "The ratio of low- to high-frequency power in beat-interval variability, from a Lomb–Scargle periodogram (the series is unevenly sampled, so an FFT would be wrong)." => l.supplementTheRatioOfLowTo817781, "There is no resting heart rate from a scored night to measure against." => @@ -563,6 +565,8 @@ String localizedText(AppLocalizations? l, String text) { l.supplementThereIsNoScoredNight5d353d, "These recordings are not stamped with which strap made them, and this number has to be calibrated per strap, so it is withheld rather than guessed." => l.supplementTheseRecordingsAreNotStamped66b52f, + "This number has to be calibrated per device, and there is no calibration for this one yet, so it is withheld rather than guessed." => + l.supplementNoCalibrationForThisDevice, "This day came from an import that only covers the night, so there is nothing recorded for the waking day." => l.supplementThisDayCameFromAn2dc4b2, "This phone" => l.settingsGroupThisPhone, diff --git a/lib/models/metric.dart b/lib/models/metric.dart index 5ec4914b3..9f8c20b9c 100644 --- a/lib/models/metric.dart +++ b/lib/models/metric.dart @@ -253,6 +253,14 @@ String? whyFromNote(String? note, {String unit = 'nights'}) { return c == null ? why : '$why There were ${c[1]}, and it needs ${c[2]}.'; } if (s.startsWith('unknown_device_family')) { + // `id=none` is an unstamped recording; any other id is a known device + // this number has no calibration for yet (a wearable with no motion + // channel, say), and "not stamped" would be false there. + if (!s.endsWith('id=none') && s.contains('id=')) { + return 'This number has to be calibrated per device, and there is no ' + 'calibration for this one yet, so it is withheld rather than ' + 'guessed.'; + } return 'These recordings are not stamped with which strap made them, and ' 'this number has to be calibrated per strap, so it is withheld rather ' 'than guessed.'; diff --git a/lib/state/app_state.dart b/lib/state/app_state.dart index 441cb61ad..a1f1b86cb 100644 --- a/lib/state/app_state.dart +++ b/lib/state/app_state.dart @@ -48,6 +48,7 @@ import '../ble/scale_presence.dart' show ScalePresenceWatcher; import '../ble/session_link.dart' show SessionLink; import '../ble/colmi_link.dart' show ColmiLink; import '../ble/coros_link.dart' show CorosLink; +import '../ble/helio_strap_link.dart' show HelioStrapLink; import '../ble/garmin_link.dart' show GarminLink; import '../ble/miband_link.dart' show MiBand234Link; import '../ble/oura_link.dart' show OuraLink; @@ -56,9 +57,12 @@ import '../ble/ultrahuman_link.dart' show UltrahumanLink; import '../cloud/companion_client.dart'; import '../compute/derivation_engine.dart'; import '../compute/derive_scheduler.dart'; +import '../compute/inputs/garmin_inputs.dart' show isWearableFamily; import '../compute/inputs/canonical.dart' show + activeWearable, flagOnOrPrimary, + wearableLastTs, onWearableDaysChanged, refreshSessionSensorSources, substrateDays; @@ -504,6 +508,33 @@ class AppState extends ChangeNotifier { bool get isPaired => paired != null; + /// A flag-on active wearable is chosen (`activeWearable`), cached for the + /// sync getters below; refreshed on boot, on device-row changes and on every + /// wearable flag or choice change ([refreshWearableSource]). + bool _wearableSource = false; + + /// Whether ANYTHING measures: the band, or the active wearable with its flag + /// on. The gates that mean "this install has data coming" (onboarding, the + /// cadence checks and reminders, Home's no-device card, pull-to-sync) read + /// this; the ones that mean "the band" (its session, alarm, battery, find) + /// keep [isPaired]. A flag-off wearable is not a source (rule R6). + bool get hasSource => isPaired || _wearableSource; + + /// Bumped by every [refreshWearableSource] and by a reset, so only the + /// newest read may write [_wearableSource]. + int _wearableSourceSeq = 0; + + /// Re-reads [hasSource]'s wearable half; notifies only on a change. A read + /// that a newer one (or a reset) overtook while it awaited writes nothing. + Future refreshWearableSource() async { + final seq = ++_wearableSourceSeq; + final on = await activeWearable() != null; + if (seq != _wearableSourceSeq) return; + if (on == _wearableSource) return; + _wearableSource = on; + if (!_disposed) notifyListeners(); + } + /// Sensors paired ALONGSIDE the primary band — a chest strap, a ring. /// /// Raw `device` rows, minus the primary. Not `PairedDevice`: that type is the @@ -547,6 +578,7 @@ class AppState extends ChangeNotifier { // only when the user changes it. _hrPriority = (await LocalDb.signalPriorities())[InputSignal.hr1Hz.name] ?? const []; + await refreshWearableSource(); notifyListeners(); } @@ -1635,8 +1667,14 @@ class AppState extends ChangeNotifier { 'deleted. Try again in a minute.'); } // 0 · nothing further ENTERS the database either. The band is still - // connected and still draining — see [_resetting]. - ResetGate.enter(); + // connected and still draining — see [_resetting]. Raised inside + // the Helio pairing lock: a pairing mid-persist finishes before the + // gate rises (and the wipe below removes what it wrote), and one + // that has not started persisting sees the generation moved. The + // section is only the raise, so it waits on nothing. + await HelioStrapLink.exclusive(() async { + ResetGate.enter(); + }); var primaryEnded = false; try { // Wait for a running backup and remove copies while the selected folder @@ -1716,7 +1754,7 @@ class AppState extends ChangeNotifier { } catch (e) { _log('[reset] coach chat delete failed: $e'); } - // The ring's and Mi Band's 16-byte pairing keys. iOS keeps keychain + // The ring's, Mi Band's and Helio Strap's pairing keys. iOS keeps keychain // items across an uninstall, and a ring still holding the old key needs // a factory reset before it pairs again. A delete of a key that was // never written is a no-op, so every non-primary id is tried for both, @@ -1724,6 +1762,8 @@ class AppState extends ChangeNotifier { final keysDropped = [ await OuraLink.dropStoredKeys(secondaryIds), await MiBand234Link.dropStoredKeys(secondaryIds), + // One fixed item, not keyed by device: the strap's key. + await HelioStrapLink.dropStoredKey(), ]; resetLeftPairingKeys = keysDropped.contains(false); @@ -1782,6 +1822,10 @@ class AppState extends ChangeNotifier { _lastRecTs = null; _bandUntimedArchive = false; lastSynced = null; + // The active wearable's cached source flag: left on, `hasSource` kept + // a wiped install out of the welcome screen until the next refresh. + _wearableSource = false; + _wearableSourceSeq++; // an in-flight refresh must not restore it // signOut() unpairs, so by the time it returns nothing is delivering. await signOut(); @@ -1840,6 +1884,7 @@ class AppState extends ChangeNotifier { await bounded('colmi', ColmiLink.instance.stop); await bounded('garmin', GarminLink.instance.stop); await bounded('miband234', MiBand234Link.instance.stop); + await bounded('helio_strap', HelioStrapLink.instance.stop); await bounded('pebble', PebbleLink.instance.stop); await bounded('coros', CorosLink.instance.stop); for (final link in SessionLink.all) { @@ -1870,8 +1915,8 @@ class AppState extends ChangeNotifier { // First run, fresh install: offer "existing v2 user vs new user" before we // ask anyone to pair. A returning (already-paired) user skips it even if the // choice flag predates this build. - if (_onboardChoice == null && !isPaired) return AppRoute.welcome; - if (!isPaired) return AppRoute.pairing; + if (_onboardChoice == null && !hasSource) return AppRoute.welcome; + if (!hasSource) return AppRoute.pairing; if (!profileComplete) return AppRoute.profile; return AppRoute.shell; } @@ -2541,7 +2586,14 @@ class AppState extends ChangeNotifier { if (!recoveryNightSettled( dayId: dayId, payload: payload, - dataEdgeSec: await LocalDb.lastDecodedRecTs() ?? 0, + // The edge of the device the night came off: the active wearable's + // for a wearable night (the band's is 0 there, so it settled only + // through the 12 h give-up), the band's otherwise. Never the larger + // of the two: a wearable synced to 08:00 would certify a band night + // whose own data stops at its 06:00 wake. + dataEdgeSec: isWearableFamily(payload?['device_family'] as String?) + ? await wearableLastTs() ?? 0 + : await LocalDb.lastDecodedRecTs() ?? 0, nowSec: DateTime.now().millisecondsSinceEpoch ~/ 1000, )) { return; @@ -2600,7 +2652,7 @@ class AppState extends ChangeNotifier { /// any prefs change), then run the data-driven foreground nudges. Future runCadenceChecks() async { try { - if (!isPaired) return; + if (!hasSource) return; await _ensureRemindersScheduled(); await _maybeNotifyStepGoal(); await _maybeNotifyInactivity(); @@ -2885,6 +2937,10 @@ class AppState extends ChangeNotifier { /// False when the pass threw or any day failed (logged), so a caller that /// owes the user more than a log line can tell. Future rederiveDays(Set days) async { + // A wearable's flag or the choice of wearable moved (the only caller of + // this through `onWearableDaysChanged`): whether anything measures may + // have too. + await refreshWearableSource(); if (days.isEmpty) return true; while (_derive.running) { await Future.delayed(const Duration(milliseconds: 250)); @@ -3424,7 +3480,7 @@ class AppState extends ChangeNotifier { unawaited(_loadAppStatus()); // Register the recurring wall-clock nudges as real OS-scheduled notifications // (wind-down, weekly recap) so they fire even when the app is closed. - if (isPaired) unawaited(_ensureRemindersScheduled()); + if (hasSource) unawaited(_ensureRemindersScheduled()); // SECOND FRAMED BAND (iOS 18+): the ASK picker must run with NO // CBCentralManager alive in the process. This is the only such moment — // `main()`'s two flutter_blue_plus calls (setOptions/setLogLevel) return diff --git a/lib/sync/background_sync.dart b/lib/sync/background_sync.dart index e5d6102f8..c2a9db8f0 100644 --- a/lib/sync/background_sync.dart +++ b/lib/sync/background_sync.dart @@ -24,6 +24,7 @@ import '../ble/adapters/whoop_gen4.dart' show WhoopFramedAdapter; import '../ble/ble_engine.dart'; import '../ble/ble_state.dart' show AlarmConfirmation; import '../ble/colmi_link.dart'; +import '../ble/helio_strap_link.dart'; import '../ble/session_link.dart'; import '../ble/coros_link.dart'; import '../ble/garmin_link.dart'; @@ -408,13 +409,16 @@ Future runHeadlessSync({BandLease? lease}) async { BandOwnership.release(ownedLease); // Not during "delete everything": a secondary sync started now would // bank a device the reset is removing into the store it just emptied. - if (!ResetGate.changedSince(runGen)) await _syncPairedSensors(); + if (!ResetGate.changedSince(runGen)) await syncPairedSensors(); } } /// The paired sensors' piggyback on a headless wake. Runs after the band work /// is fully done so it can never delay or interfere with WHOOP's own timing. -Future _syncPairedSensors() async { +/// Also Home's sync on an install whose only source is a wearable: every link +/// here no-ops when its device is not paired, so it is the one generic "sync +/// what is paired" there is. +Future syncPairedSensors() async { // Piggyback paired sensors on the same OS wake window, after the band // work is fully done so neither can ever delay or interfere with WHOOP's // own timing. Both `sync()` calls already no-op when nothing is paired @@ -475,6 +479,14 @@ Future _syncPairedSensors() async { } catch (e) { debugPrint('[bgsync] colmi sync skipped: $e'); } + // Same piggyback, same reasoning: no-ops when unpaired (and also when no + // auth key is stored yet — see `HelioStrapLink.sync`'s own doc), must + // never let a failure here mark the WHOOP cycle as errored. + try { + await HelioStrapLink.instance.sync(); + } catch (e) { + debugPrint('[bgsync] helio_strap sync skipped: $e'); + } // Thermometer and scales: same piggyback; each no-ops when unpaired and // only reaches a device that happens to be awake and nearby. for (final link in SessionLink.all) { diff --git a/lib/ui2/activity/day_strain.dart b/lib/ui2/activity/day_strain.dart index 40974598d..d6a8af912 100644 --- a/lib/ui2/activity/day_strain.dart +++ b/lib/ui2/activity/day_strain.dart @@ -363,7 +363,7 @@ class _DayStrainDetailState extends State { 'The day strain is ${displayFixed(s, 1)}. The waking minutes ' 'it was built from are not stored for this day.'), fix: (s == null && !saw) - ? (l?.dayStrainWearBandFix ?? 'Wear the band through the day') + ? (l?.dayStrainWearBandFix ?? 'Wear your device through the day') : '', icon: LucideIcons.trendingUp, ), diff --git a/lib/ui2/activity/live.dart b/lib/ui2/activity/live.dart index f67c6c0b3..31ee43b90 100644 --- a/lib/ui2/activity/live.dart +++ b/lib/ui2/activity/live.dart @@ -188,6 +188,10 @@ class ActivityHost { /// Whether the band is connected right now. final bool bandConnected; + /// Whether a band is paired at all: with one, "not connected" is the + /// answer; without one, there is no live heart rate to wait for. + final bool bandPaired; + const ActivityHost({ this.feed, this.onStart, @@ -195,6 +199,7 @@ class ActivityHost { this.onSets, this.history = const {}, this.bandConnected = false, + this.bandPaired = true, }); /// No app behind the screens: they still render, nothing is persisted. diff --git a/lib/ui2/activity/setup.dart b/lib/ui2/activity/setup.dart index a35e334f3..a0582f3d8 100644 --- a/lib/ui2/activity/setup.dart +++ b/lib/ui2/activity/setup.dart @@ -180,8 +180,11 @@ class _ActivitySetupState extends State { widget.host.bandConnected ? (l?.activitySetupBandConnected ?? 'Band connected') - : (l?.activitySetupNoBandConnected ?? - 'No band connected'), + : widget.host.bandPaired + ? (l?.activitySetupNoBandConnected ?? + 'No band connected') + : (l?.activitySetupNoLiveHr ?? + 'No live heart rate'), widget.host.bandConnected), Divider(color: p.line, height: 1), _toggle( diff --git a/lib/ui2/activity/zones.dart b/lib/ui2/activity/zones.dart index 2fd0415ae..039ca69fa 100644 --- a/lib/ui2/activity/zones.dart +++ b/lib/ui2/activity/zones.dart @@ -392,7 +392,7 @@ class _ZonesDetailState extends State { // The hard-session instruction belongs to the hold gate alone. fix: why == null ? (l?.activityZonesWearBandFix ?? - 'Wear the band for your normal hard sessions') + 'Wear your device for your normal hard sessions') : '', icon: LucideIcons.heartPulse, ); diff --git a/lib/ui2/pairing/device_picker.dart b/lib/ui2/pairing/device_picker.dart index 8a5005872..abc5fc775 100644 --- a/lib/ui2/pairing/device_picker.dart +++ b/lib/ui2/pairing/device_picker.dart @@ -47,6 +47,7 @@ import '../../ble/ble_state.dart' classifyBleBlocker, kMaxConcurrentSecondaryLinks; import '../../ble/hrs_link.dart'; +import '../../ble/helio_strap_link.dart' show pairHelioStrapWithTypedKey; import '../../ble/oura_link.dart' show pairOuraRingWithTypedKey; import '../../data/db.dart' show LocalDb; import '../../l10n/app_localizations.dart'; @@ -337,6 +338,17 @@ class _DevicePickerScreenState extends State 'sensors alongside your band. Remove one to add another.'); } if (!mounted) return const PairOutcome.failed(''); + // The strap pairs only with the key its vendor app issued, and a plain + // pair would save a row with none (every sync then ends at once). A + // nearby tap opens its key screen instead. + if (sensor.entry.id == kHelioStrap.id) { + await HrsLink.stopScanIfRunning(this); + final r = + await _openEntry(sensor.entry, returnOnPair: true, selected: cand); + return r == BandFlowResult.pairedWearable + ? const PairOutcome.saved() + : const PairOutcome.failed(''); + } setState(() => _busy = cand.device.remoteId.str); // OUR OWN SCAN, ENDED FIRST. It runs for a 15 s window and the user has // tapped a row several seconds into it, so without this the radio keeps @@ -362,7 +374,8 @@ class _DevicePickerScreenState extends State /// a scanned band handed over by [AddDeviceFlow] ([remoteId], [modelKnown] /// as [AddDeviceIo.openBandFlow]). Future _openEntry(BandEntry entry, - {String? remoteId, bool modelKnown = true, bool replacing = false, bool returnOnPair = false}) async { + {String? remoteId, bool modelKnown = true, bool replacing = false, bool returnOnPair = false, + BandCandidate? selected}) async { // A handoff from AddDeviceFlow awaits the scan shutdown first; the user may // have left meanwhile, and neither branch below may touch a disposed context. if (!mounted) return BandFlowResult.closed; @@ -409,11 +422,16 @@ class _DevicePickerScreenState extends State builder: (_) => PairSensorScreen( entry: sensor.entry, returnOnPair: returnOnPair, + selected: selected, onPicked: sensor.pick, - // The ring alone can be paired with the key its own app installed — - // see `pairOuraRingWithKey`. - onPickedWithKey: - sensor.entry.id == kOura.id ? pairOuraRingWithTypedKey : null, + // The ring can be paired with the key its own app installed — see + // `pairOuraRingWithKey`. The strap has no keyless path at all, so + // its typed-key function is the only way it pairs. + onPickedWithKey: switch (sensor.entry.id) { + final id when id == kOura.id => pairOuraRingWithTypedKey, + final id when id == kHelioStrap.id => pairHelioStrapWithTypedKey, + _ => null, + }, ), ), ); diff --git a/lib/ui2/profile/devices.dart b/lib/ui2/profile/devices.dart index bd376c8cc..356f02dce 100644 --- a/lib/ui2/profile/devices.dart +++ b/lib/ui2/profile/devices.dart @@ -51,6 +51,7 @@ import '../../ble/adapters/_registry.dart' kColmi, kCoros, kGarmin, + kHelioStrap, kMiBand234, kMiScale2, kMiScaleComposition, @@ -62,6 +63,7 @@ import '../../ble/adapters/_registry.dart' declaredSignals; import '../../ble/adapters/signals.dart' show InputSignal, kRankedSignals; import '../../ble/colmi_link.dart' show ColmiLink; +import '../../ble/helio_strap_link.dart' show HelioStrapLink; import '../../ble/coros_link.dart' show CorosLink; import '../../ble/garmin_link.dart' show GarminLink; import '../../ble/hrs_link.dart' show HrsLink, HrsReading; @@ -1287,6 +1289,19 @@ final List<({BandEntry entry, String blurb, Future Function(BluetoothDe 'not supported.)', pick: pairMiBand234, ), + ( + entry: kHelioStrap, + blurb: 'An Amazfit Helio Strap. First pairing still has to go through ' + 'the real Zepp app — that is where the strap\'s key comes from, and ' + 'nothing here can skip it. Paste that key below to pair it here ' + 'instead. Syncs heart rate, steps, skin temperature, sleep and ' + 'workouts; the strap\'s own stress, HRV, SpO2 and respiratory-rate ' + 'figures are labelled as Amazfit\'s. Experimental.', + // Null: this device has no keyless path at all — unlike Oura or Mi + // Band, there is no "mint our own key" option, so only the typed-key + // field (wired via `onPickedWithKey` in the pairing screens) applies. + pick: null, + ), ( entry: kPebble, blurb: 'Pebble 2 or Pebble 2 SE only — older Pebbles need Bluetooth ' @@ -2131,6 +2146,7 @@ class _DeviceDetailState extends State { 'miband234' => () => _syncMiband(c), 'pebble' => () => _syncPebble(c), 'colmi' => () => _syncColmiRing(c), + 'helio_strap' => () => _syncSensor(c, HelioStrapLink.instance.sync), 'thermometer' || 'miscale_bc' || 'miscale2' => () => _syncSensor(c, SessionLink.forId(s.family)!.sync), _ => null, diff --git a/lib/ui2/profile/pair_sensor.dart b/lib/ui2/profile/pair_sensor.dart index 1f4df6057..6ada972e3 100644 --- a/lib/ui2/profile/pair_sensor.dart +++ b/lib/ui2/profile/pair_sensor.dart @@ -63,6 +63,7 @@ import '../../ble/ble_state.dart' show BleUnavailableException, bandStatusFor, classifyBleBlocker; import '../../ble/hrs_link.dart'; import '../../ble/ios_ble_restore.dart'; +import '../../ble/helio_strap_link.dart' show pairHelioStrapWithTypedKey; import '../../ble/oura_link.dart' show pairOuraRingWithTypedKey; import '../../data/db.dart' show LocalDb; import '../../l10n/app_localizations.dart'; @@ -112,6 +113,11 @@ class PairSensorScreen extends StatefulWidget { /// A handoff needs a successful pair result, not just a closed route. final bool returnOnPair; + /// The device the user already chose (a nearby tap handed over for its + /// key): listed from the start, so the key is paired to THAT device rather + /// than to whichever one a fresh scan lists. + final BandCandidate? selected; + const PairSensorScreen({ super.key, required this.entry, @@ -120,6 +126,7 @@ class PairSensorScreen extends StatefulWidget { this.debugFound, this.debugPair, this.returnOnPair = false, + this.selected, }); @override @@ -159,7 +166,8 @@ class _PairSensorScreenState extends State @override void initState() { super.initState(); - _found = widget.debugFound ?? const []; + _found = widget.debugFound ?? + (widget.selected == null ? const [] : [widget.selected!]); unawaited(_load()); } @@ -261,7 +269,20 @@ class _PairSensorScreenState extends State /// The iOS 18+ path for a [kAskPickerSensors] entry: the ASK picker filtered /// to this sensor's service, then the same pairing step a scanned row gets. + /// A device that pairs ONLY with a typed key (no install path) and an + /// empty key field: nothing can pair it yet. + bool get _keyMissing => + widget.onPickedWithKey != null && + widget.onPicked == null && + _key.text.trim().isEmpty; + Future _pairViaPicker() async { + // Before the system sheet: approving an accessory there that this screen + // then refuses for want of a key leaves an OS approval behind. + if (_keyMissing) { + setState(() => _problem = 'Enter the device’s key to pair it.'); + return; + } setState(() { _scanning = true; _problem = null; @@ -276,7 +297,9 @@ class _PairSensorScreenState extends State // band (see `IosBleRestore.reacquireCentral`). await IosBleRestore.releaseCentralForPicker(); try { - id = await AccessorySetup.showSensorPicker([widget.entry.service]); + final askName = kAskSharedServiceNames[widget.entry.id]; + id = await AccessorySetup.showSensorPicker([widget.entry.service], + name: askName, label: askName == null ? null : widget.entry.label); } on PlatformException catch (e) { failure = l?.pairSensorCouldNotPair(e.message ?? e.code) ?? 'Could not pair that device: ${e.message ?? e.code}'; @@ -337,6 +360,20 @@ class _PairSensorScreenState extends State if (!mounted) return; String? failure; final typedKey = _key.text.trim(); + // An empty key is NOT the same thing as "no typed-key path exists". + // [kOura] has both a keyless install function AND a typed-key one, so + // leaving the field blank correctly means "use the install path" — + // but a device with ONLY a typed-key path (no [onPicked] at all, e.g. + // Helio) must refuse here, not silently fall through to the generic + // plain pairing below, which would create a device row with no + // handshake ever attempted and no key the adapter could ever use. + if (_keyMissing) { + setState(() { + _busy = null; + _problem = 'Enter the device’s key to pair it.'; + }); + return; + } try { failure = widget.onPickedWithKey != null && typedKey.isNotEmpty ? await widget.onPickedWithKey!(device, typedKey) @@ -441,8 +478,11 @@ class _PairSensorScreenState extends State entry: band, returnOnPair: true, onPicked: sensor.pick, - onPickedWithKey: - band.id == kOura.id ? pairOuraRingWithTypedKey : null, + onPickedWithKey: switch (band.id) { + final id when id == kOura.id => pairOuraRingWithTypedKey, + final id when id == kHelioStrap.id => pairHelioStrapWithTypedKey, + _ => null, + }, ), )); return result ?? BandFlowResult.closed; @@ -478,6 +518,7 @@ class _PairSensorScreenState extends State paired: _paired, busyRemoteId: _busy, keyController: widget.onPickedWithKey == null ? null : _key, + keyRequired: widget.onPickedWithKey != null && widget.onPicked == null, onScan: _scan, onPick: _pick, onForget: _forget, @@ -505,6 +546,10 @@ class PairSensorView extends StatelessWidget { /// The optional "pair with the key it already holds" field. Null hides it. final TextEditingController? keyController; + /// The device pairs ONLY with a typed key (no install path): the field says + /// one key is required, and the ring's key-replacement warning is not shown. + final bool keyRequired; + final VoidCallback? onScan; final void Function(BandCandidate)? onPick; final void Function(String id)? onForget; @@ -520,6 +565,7 @@ class PairSensorView extends StatelessWidget { this.paired, this.busyRemoteId, this.keyController, + this.keyRequired = false, this.onScan, this.onPick, this.onForget, @@ -579,6 +625,7 @@ class PairSensorView extends StatelessWidget { if (keyController != null) ...[ // Before the user commits: a new key evicts the ring's own // app, and there is no state in which both work. + if (!keyRequired) ...[ const SizedBox(height: S.x4), StatusCard( l?.pairSensorKeyReplacesTitle ?? @@ -587,8 +634,10 @@ class PairSensorView extends StatelessWidget { 'The ring holds one key. Pairing without the Oura app’s key gives it a new one, and the Oura app stops working with it until the ring is reset.', icon: LucideIcons.triangleAlert, ), + ], const SizedBox(height: S.x4), - _keySection(c, keyController!, busy || scanning), + _keySection(c, keyController!, busy || scanning, + required: keyRequired), ], if (heldBack != null) ...[ const SizedBox(height: S.x4), @@ -664,16 +713,22 @@ class PairSensorView extends StatelessWidget { /// The key the device already holds, if the user has it. Optional, and says /// so: an empty field is the ordinary pairing. - Widget _keySection(BuildContext c, TextEditingController ctl, bool locked) { + Widget _keySection(BuildContext c, TextEditingController ctl, bool locked, + {bool required = false}) { final p = P.of(c); final l = AppLocalizations.of(c); return Section( - l?.pairSensorKeyTitle ?? 'Already set up elsewhere?', + required + ? (l?.pairSensorKeyRequiredTitle ?? 'Device key') + : (l?.pairSensorKeyTitle ?? 'Already set up elsewhere?'), Surface( child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - l?.pairSensorKeyBody ?? - 'Have this device’s key? Paste it to pair without a factory reset. Several keys, one per line, are tried in turn. Leave it empty to pair normally.', + required + ? (l?.pairSensorKeyRequiredBody ?? + 'This device pairs only with the key its own app set up. Paste that one key: 32 hex digits.') + : (l?.pairSensorKeyBody ?? + 'Have this device’s key? Paste it to pair without a factory reset. Several keys, one per line, are tried in turn. Leave it empty to pair normally.'), style: F.cap.copyWith(color: p.ink3, height: 1.5), ), TextField( @@ -691,8 +746,10 @@ class PairSensorView extends StatelessWidget { textInputAction: TextInputAction.newline, style: F.head.copyWith(color: p.ink), decoration: InputDecoration( - hintText: l?.pairSensorKeyHint ?? - '32 hex digits or base64 — one key per line', + hintText: required + ? (l?.pairSensorKeyRequiredHint ?? '32 hex digits') + : (l?.pairSensorKeyHint ?? + '32 hex digits or base64 — one key per line'), hintStyle: F.head.copyWith(color: p.ink3), isDense: true, contentPadding: const EdgeInsets.symmetric(vertical: S.x3), diff --git a/lib/ui2/profile/settings.dart b/lib/ui2/profile/settings.dart index 0da093cc0..f0aa7466a 100644 --- a/lib/ui2/profile/settings.dart +++ b/lib/ui2/profile/settings.dart @@ -198,6 +198,10 @@ class _MoreSettingsState extends State final clock = c.watch(); final l = AppLocalizations.of(c); return MoreSettingsView( + // The band's own features (its alarm, buzz alerts, double-tap, step + // calibration) only where a band is paired; a wearable-only install + // would open screens that can only say "the band is not connected". + hasBand: app.isPaired, version: _version, devMode: _dev, onVersionTap: _tapVersion, @@ -639,6 +643,10 @@ class MoreSettingsView extends StatelessWidget { final VoidCallback? onVersionTap, onToggleDev, onGallery; + /// A band is paired: its own rows show (alarm, zone-alert buzz, + /// double-tap, step calibration). Default true (gallery, tests). + final bool hasBand; + final VoidCallback? onEditProfile, onAlarm, onNotifications, @@ -693,6 +701,7 @@ class MoreSettingsView extends StatelessWidget { this.onGallery, this.onEditProfile, this.onAlarm, + this.hasBand = true, this.onNotifications, this.onData, this.onAutomation, @@ -734,6 +743,7 @@ class MoreSettingsView extends StatelessWidget { // on the Profile screen — because two doors to one form is how // a user ends up unsure which one is the real setting. settingsGroup(c, l?.settingsGroupTheBand ?? 'The band', [ + if (hasBand) ...[ SetRow(LucideIcons.alarmClock, C.orange, l?.settingsAlarmRowTitle ?? 'Alarm', sub: l?.settingsAlarmRowSub ?? @@ -771,6 +781,7 @@ class MoreSettingsView extends StatelessWidget { ?.settingsDoubleTapRowSub ?? 'What a double-tap on the band does', onTap: () => goto(c, const BandGestures()))), + ], if (backgroundExempt != null) SetRow(LucideIcons.batteryCharging, C.green, l?.settingsKeepAliveRowTitle ?? @@ -873,6 +884,7 @@ class MoreSettingsView extends StatelessWidget { // 100 Hz pedometer — see step_calibration.dart for why it must be // measured rather than assumed, and for what makes it different // from the guided calibration app_state.dart records as removed. + if (hasBand) SetRow( LucideIcons.footprints, C.teal, @@ -1064,8 +1076,15 @@ class _NotificationSettingsState extends State /// Whether the strap-buzz relay exists on this platform. Android only — /// iOS gives no app access to another app's notifications — and the row is /// absent rather than disabled there, so there is nothing to explain. - bool get _relaySupported => - defaultTargetPlatform == TargetPlatform.android; + bool get _relaySupported { + if (defaultTargetPlatform != TargetPlatform.android) return false; + // It buzzes the band: no band, no row. + try { + return context.read().isPaired; + } catch (_) { + return true; // no AppState above (gallery): as before + } + } Future _apply(NotificationPrefs next) async { setState(() => _prefs = next); diff --git a/lib/ui2/profile/wearable_numbers.dart b/lib/ui2/profile/wearable_numbers.dart index 3c909badc..6c62667ef 100644 --- a/lib/ui2/profile/wearable_numbers.dart +++ b/lib/ui2/profile/wearable_numbers.dart @@ -188,6 +188,7 @@ String? methodText(AppLocalizations l, String? method) => switch (method) { 'rr_ring' => l.wearableMethodRingBeats, 'hr_5min' || 'hr_5min_stager' => l.wearableMethodHr5min, 'device_stages' => l.wearableMethodDeviceStages, + 'skin_temp_c' || 'skin_temp_c_5min' || 'skin_temp_c_slot' || 'skin_temp_c_event' => l.wearableMethodSkinTemp, @@ -195,6 +196,8 @@ String? methodText(AppLocalizations l, String? method) => switch (method) { 'rhr_only_partial' => l.wearableMethodRhrOnly, kPartialReadinessMethod => l.wearableMethodPartialComposite, kStrapReadinessMethod => l.wearableMethodRhrStrapComposite, + kDeviceHrvReadinessMethod => l.wearableMethodDeviceHrvComposite, + kDeviceRmssdMethod => l.wearableMethodDeviceRmssd, 'hr_1min_zone_minutes' => l.wearableMethodZoneMinutes, 'steps_5min' => l.wearableMethodActivity, _ => null, diff --git a/lib/ui2/screens/circadian_detail.dart b/lib/ui2/screens/circadian_detail.dart index 12fddcdfc..0d32ef0de 100644 --- a/lib/ui2/screens/circadian_detail.dart +++ b/lib/ui2/screens/circadian_detail.dart @@ -340,7 +340,7 @@ class _CircadianDetailState extends State { StatusCard( l?.circadianDetailNoNightsTitle ?? 'No nights to plot yet', l?.circadianDetailNoNightsBody ?? '0 nights scored.', - fix: l?.circadianDetailNoNightsFix ?? 'Wear the band overnight', + fix: l?.circadianDetailNoNightsFix ?? 'Wear your device overnight', icon: LucideIcons.calendarClock, ) else diff --git a/lib/ui2/screens/driver_breakdown.dart b/lib/ui2/screens/driver_breakdown.dart index 361a6f69f..12a43e713 100644 --- a/lib/ui2/screens/driver_breakdown.dart +++ b/lib/ui2/screens/driver_breakdown.dart @@ -522,11 +522,11 @@ StatusCard driverAbsenceCard( 'algo_version' => l?.driverBreakdownAbsenceAlgoVersion ?? 'The way recovery is worked out changed in the last update. Your days are being recalculated.', 'stale' => l?.driverBreakdownAbsenceStale ?? - 'Your trends are out of date. Sync the band to update them.', + 'Your trends are out of date. Sync your device to update them.', _ => l?.driverBreakdownAbsenceNoVersion ?? 'Your trends are being updated. This takes a minute after a sync.', }, - fix: onSync == null ? '' : (l?.driverBreakdownSyncTheBand ?? 'Sync the band'), + fix: onSync == null ? '' : (l?.driverBreakdownSyncTheBand ?? 'Sync your device'), onFix: onSync, icon: LucideIcons.refreshCw, ); diff --git a/lib/ui2/screens/health_screen.dart b/lib/ui2/screens/health_screen.dart index b8d5af270..ad2326050 100644 --- a/lib/ui2/screens/health_screen.dart +++ b/lib/ui2/screens/health_screen.dart @@ -1263,7 +1263,7 @@ class _HealthScreenState extends State with RevisionReload { StatusCard( l?.healthNothingMeasuredDay ?? 'Nothing measured for this day', l?.healthNoBandRecordings ?? 'No band recordings reached this day.', - fix: syncOf(c) == null ? '' : (l?.healthSyncTheBand ?? 'Sync the band'), + fix: syncOf(c) == null ? '' : (l?.healthSyncTheBand ?? 'Sync your device'), icon: LucideIcons.watch, onFix: syncOf(c), ) diff --git a/lib/ui2/screens/home_screen.dart b/lib/ui2/screens/home_screen.dart index 6d9eff0e0..52a6f33c3 100644 --- a/lib/ui2/screens/home_screen.dart +++ b/lib/ui2/screens/home_screen.dart @@ -64,6 +64,7 @@ import '../../notify/notification_prefs.dart' show NotificationPrefs; import '../../state/app_state.dart'; import '../../state/clock_format.dart' show formatClockOf; import '../../state/units_controller.dart'; +import '../../sync/background_sync.dart' show syncPairedSensors; import '../../theme/theme_switcher.dart' show themedRoute; import '../activity/day_strain.dart' show DayStrainDetail; import '../profile/alarm.dart' @@ -128,13 +129,14 @@ UnitsController? unitsOf(BuildContext c) { return i < 0 ? (s, '') : (s.substring(0, i), s.substring(i + 1)); } -/// The band-sync trigger, or null when there is no AppState above us. Every +/// The sync trigger, or null when there is no AppState above us. Every /// "Sync the band" CTA in this folder goes through here — a call to action -/// with no action behind it is worse than no call to action. +/// with no action behind it is worse than no call to action. With no band +/// paired it syncs the paired wearables instead ([syncPairedSensors]). VoidCallback? syncOf(BuildContext c) { try { final app = c.read(); - return app.syncNow; + return app.isPaired ? app.syncNow : () => unawaited(syncPairedSensors()); } catch (_) { return null; } @@ -147,7 +149,8 @@ VoidCallback? syncOf(BuildContext c) { /// nothing on Home pointed at pairing. Widget? noBandCard(BuildContext c, AppLocalizations? l) { try { - if (c.read().isPaired) return null; + // Any source, not only the band: a wearable-only install measures. + if (c.read().hasSource) return null; } catch (_) { return null; } @@ -362,6 +365,9 @@ String? stepSensorLabel(Metric m, [AppLocalizations? l]) { final strap = used.contains('band_pedometer_100hz') || used.contains('band_step_counter'); final phone = used.contains('phone_pedometer'); + if (used.contains('wearable_pedometer')) { + return l?.homeStepSensorDevice ?? 'Device'; + } if (strap && phone) return l?.homeStepSensorStrapPhone ?? 'Strap + phone'; if (strap) return l?.homeStepSensorStrap ?? 'Strap'; if (phone) return l?.homeStepSensorPhone ?? 'Phone'; @@ -629,12 +635,12 @@ StatusCard? staleInsightsCard( 'Updating after the latest app update.', 'stale' => built == null || built.isEmpty ? (l?.homeInsightsStaleOverWeek ?? - 'Your trends were last updated over a week ago. Sync the band to bring them up to date.') + 'Your trends were last updated over a week ago. Sync your device to bring them up to date.') : (l?.homeInsightsStaleOnDay(prettyDay(built, l)) ?? - 'Your trends were last updated on ${prettyDay(built, l)}. Sync the band to bring them up to date.'), + 'Your trends were last updated on ${prettyDay(built, l)}. Sync your device to bring them up to date.'), _ => l?.homeInsightsNoVersionStamp ?? 'Your trends are being updated. This takes a minute after a sync.', }, - fix: onSync == null ? '' : (l?.homeSyncBand ?? 'Sync the band'), + fix: onSync == null ? '' : (l?.homeSyncBand ?? 'Sync your device'), icon: LucideIcons.refreshCw, onFix: onSync, ); @@ -2350,10 +2356,10 @@ class _HomeScreenState extends State with RevisionReload { ? (l?.homeNothingDerivedTitle ?? 'No nights scored yet') : (l?.homeNothingTodayTitle ?? 'Nothing recorded for today'), d.heldOverNight == null - ? (l?.homeNothingDerivedBody ?? 'Wear the band tonight and open the app in the morning.') + ? (l?.homeNothingDerivedBody ?? 'Wear your device tonight and open the app in the morning.') : (l?.homeNothingTodayBody(prettyDay(d.heldOverNight, l)) ?? 'Last scored night: ${prettyDay(d.heldOverNight, l)}.'), - fix: sync == null ? '' : (l?.homeSyncBand ?? 'Sync the band'), + fix: sync == null ? '' : (l?.homeSyncBand ?? 'Sync your device'), icon: LucideIcons.watch, onFix: sync == null ? null : () => _tapSync(sync), ); @@ -2423,8 +2429,8 @@ class _HomeScreenState extends State with RevisionReload { final sync = syncOf(c); return StatusCard( l?.homeNothingDerivedTitle ?? 'No nights scored yet', - l?.homeNothingDerivedBody ?? 'Wear the band tonight and open the app in the morning.', - fix: sync == null ? '' : (l?.homeSyncBand ?? 'Sync the band'), + l?.homeNothingDerivedBody ?? 'Wear your device tonight and open the app in the morning.', + fix: sync == null ? '' : (l?.homeSyncBand ?? 'Sync your device'), icon: LucideIcons.watch, onFix: sync == null ? null : () => _tapSync(sync), ); @@ -2781,12 +2787,13 @@ class _HomeScreenState extends State with RevisionReload { // No AppState above us (goldens): nothing to sync. } final isToday = _day == null || _day == todayLabel(); - if (app != null && app.isPaired && isToday && widget.data == null) { + if (app != null && app.hasSource && isToday && widget.data == null) { _tapSync(() {}); // ponytail: the spinner lets go after 90 s; a long backlog keeps going // in the background and the syncing card stays up until it ends. try { - await app.syncNow().timeout(const Duration(seconds: 90)); + await (app.isPaired ? app.syncNow() : syncPairedSensors()) + .timeout(const Duration(seconds: 90)); } catch (_) { // A timeout or a failed sync still re-reads what did land. } @@ -3154,7 +3161,7 @@ Widget firstWeekCard(BuildContext c, Text(l?.homeFirstWeekTitle ?? 'Your first weeks', style: F.head.copyWith(color: p.ink)), const SizedBox(height: S.x2), - step(days > 0, l?.homeFirstWeekWear ?? 'Wear the band tonight'), + step(days > 0, l?.homeFirstWeekWear ?? 'Wear your device tonight'), step(days > 0, l?.homeFirstWeekSleep ?? 'Sleep: the morning after your first night'), step(strainScored, diff --git a/lib/ui2/screens/metric_detail.dart b/lib/ui2/screens/metric_detail.dart index aa6d45ef3..dbb495b85 100644 --- a/lib/ui2/screens/metric_detail.dart +++ b/lib/ui2/screens/metric_detail.dart @@ -247,7 +247,9 @@ const _specs = { 'once, so a session never takes the day from the sensor that carried ' 'the rest of it. There is no 1 Hz estimate — walking cadence sits above what ' 'one sample a second can resolve, so a day with no counter behind it ' - 'reports no steps rather than a guess.', + 'reports no steps rather than a guess. A paired wearable\'s own daily ' + 'count is the day\'s steps when it counted more than these, used ' + 'whole and never added to them.', citation: 'AN-2554 pedometer · phone pedometer (HealthKit / Health Connect)', // Deliberately EMPTY — see final-plan §4.6. Steps are resolved by // `live_coverage_policy.dart`, which ranks by SPAN not device and credits @@ -1012,9 +1014,16 @@ class _MetricDetailState extends State { fix: all.isEmpty ? (kDaytimeMetricKeys.contains(widget.metricKey) ? (l?.dayStrainWearBandFix ?? - 'Wear the band through the day') - : (l?.metricDetailWearBandFix ?? - 'Wear the band overnight to start the series')) + 'Wear your device through the day') + // This chart is beat-derived HRV. Only a device that + // records beats overnight fills it; many wearables report + // their own HRV (on their device page) instead, and a + // chest strap records only during workouts. + : widget.metricKey == 'hrv' && !_bandPaired(context) + ? (l?.metricDetailHrvNeedsBeatsFix ?? + 'This chart needs beat-to-beat intervals recorded overnight, which only a device that records beats supplies. A chest strap records only during workouts, and many watches, rings and straps report their own HRV instead: it is on their device page') + : (l?.metricDetailWearBandFix ?? + 'Wear your device overnight to start the series')) : '', icon: spec.icon, ), @@ -2288,3 +2297,13 @@ class MonoTable extends StatelessWidget { ); } } + +/// A band is paired, or there is no AppState above (gallery, tests: as +/// before). +bool _bandPaired(BuildContext c) { + try { + return c.read().isPaired; + } catch (_) { + return true; + } +} diff --git a/lib/ui2/screens/readiness_detail.dart b/lib/ui2/screens/readiness_detail.dart index 46cece992..273927207 100644 --- a/lib/ui2/screens/readiness_detail.dart +++ b/lib/ui2/screens/readiness_detail.dart @@ -381,7 +381,7 @@ class _ReadinessDetailState extends State { ? StatusCard( l?.readinessDetailNoHistoryTitle ?? 'No recovery history', l?.readinessDetailNoHistoryBody ?? '0 days scored.', - fix: l?.readinessDetailWearOvernight ?? 'Wear the band overnight', + fix: l?.readinessDetailWearOvernight ?? 'Wear your device overnight', icon: LucideIcons.chartLine, ) : Surface(child: _history(c, d)), @@ -659,6 +659,10 @@ class _ReadinessDetailState extends State { // temperature. It gets said, every time. if (key == 'temp') l?.readinessDetailRelativeUncalibrated ?? 'relative, uncalibrated', + // PE-1: the HRV ranked here was the wearable's own readings. + if (r['source'] == 'device_rmssd') + l?.readinessDetailFromDeviceReadings ?? + "from your device's own readings", ]; return Padding( diff --git a/lib/ui2/screens/sleep_detail.dart b/lib/ui2/screens/sleep_detail.dart index 3b85ceea6..adefc264d 100644 --- a/lib/ui2/screens/sleep_detail.dart +++ b/lib/ui2/screens/sleep_detail.dart @@ -772,7 +772,7 @@ class _SleepDetailState extends State with RevisionReload { l?.sleepDetailNoNightBody ?? 'No stretch of band recordings long enough to score.'), fix: rejected ? '' : (l?.sleepDetailNoNightFix ?? - 'Wear the band overnight and sync in the morning'), + 'Wear your device overnight and sync in the morning'), icon: rejected ? LucideIcons.undo2 : LucideIcons.moon, ), // Undo goes back to automatic, which needs the whole night window. diff --git a/lib/ui2/screens/sleep_tab.dart b/lib/ui2/screens/sleep_tab.dart index 061c2d221..ed0e78a47 100644 --- a/lib/ui2/screens/sleep_tab.dart +++ b/lib/ui2/screens/sleep_tab.dart @@ -8,8 +8,10 @@ import 'package:flutter/material.dart'; import 'package:lucide_icons_flutter/lucide_icons.dart'; +import 'package:provider/provider.dart'; import '../../l10n/app_localizations.dart'; +import '../../state/app_state.dart'; import '../profile/alarm.dart'; import '../ui2.dart'; import '../guides/help_entry.dart'; @@ -36,6 +38,8 @@ class SleepTab extends StatelessWidget { Section( l?.sleepTabMoreTitle ?? 'Alarm and body clock', Column(children: [ + // The alarm buzzes the band; without one it has nothing to arm. + if (_hasBand(c)) ...[ detailLinkRow( c, LucideIcons.alarmClock, @@ -45,6 +49,7 @@ class SleepTab extends StatelessWidget { () => Navigator.of(c).push(MaterialPageRoute( builder: (_) => const AlarmScreen()))), const SizedBox(height: S.x3), + ], detailLinkRow( c, LucideIcons.sunMoon, @@ -60,3 +65,13 @@ class SleepTab extends StatelessWidget { ); } } + +/// A band is paired, or there is no AppState above (gallery, goldens: as +/// before). Selected, so pairing or forgetting a band redraws the tab. +bool _hasBand(BuildContext c) { + try { + return c.select((a) => a.isPaired); + } catch (_) { + return true; + } +} diff --git a/lib/ui2/screens/workout_screen.dart b/lib/ui2/screens/workout_screen.dart index 5bcc1233d..57a481385 100644 --- a/lib/ui2/screens/workout_screen.dart +++ b/lib/ui2/screens/workout_screen.dart @@ -1359,6 +1359,7 @@ ActivityHost activityHost(AppState app, onSets: (sets) => _bankSets(app, sets), history: history, bandConnected: app.isConnected, + bandPaired: app.isPaired, ); } diff --git a/pubspec.lock b/pubspec.lock index 42c301a62..55af7ef35 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -946,8 +946,8 @@ packages: dependency: "direct main" description: path: "." - ref: fbadb5bd055965d9400e266d6cf42748992ba950 - resolved-ref: fbadb5bd055965d9400e266d6cf42748992ba950 + ref: dc699ce491c5eec4c924fafe8e29c637ea758b5a + resolved-ref: dc699ce491c5eec4c924fafe8e29c637ea758b5a url: "https://github.com/OpenStrap/protocol.git" source: git version: "1.0.0" diff --git a/pubspec.yaml b/pubspec.yaml index ccd06ab74..3eb043f41 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -269,7 +269,22 @@ dependencies: # truncation semantics, removal of deprecated gen5 APIs). #81 sits on top # of #82, so it cannot be pinned alone. # protocol main @ #85 merge (image update payload builders). - ref: fbadb5bd055965d9400e266d6cf42748992ba950 + # REPIN: protocol feat/zepp-family @ d74cbc8, one commit on top of + # fbadb5b: the Huami2021 transport the Helio Strap needs (chunked + # transport, auth, fetch, record decoders). Additions only; WHOOP decode + # untouched. Re-point at the merge commit once it lands on protocol main. + # REPIN: protocol feat/zepp-family @ f2398ab, PR #86's head: its review + # fixes to the same transport (chunk counter wrap, stale first chunk, + # short bodies, activity record stride/count, protobuf bounds, nap + # stage edge). Also carries #86's legacy-Huami and scale decoders, + # unread here. + # protocol main @ #86 merge (the huami2021 transport, 8-byte legacy + # records, the amazfit scale decoder, and the review fixes on top: + # chunk counter wrap, stale first chunk, short bodies, activity record + # stride/count, protobuf bounds, nap stage edge, and an activity round + # whose announced count doesn't fit 4- or 8-byte records decoding to + # nothing instead of a byte-length guess). + ref: dc699ce491c5eec4c924fafe8e29c637ea758b5a openstrap_analytics: git: url: https://github.com/OpenStrap/analytics.git diff --git a/test/absence_reason_test.dart b/test/absence_reason_test.dart index 78ece27f8..283507549 100644 --- a/test/absence_reason_test.dart +++ b/test/absence_reason_test.dart @@ -87,5 +87,13 @@ void main() { expect(s.toLowerCase(), isNot(contains('age'))); expect(s.toLowerCase(), isNot(contains('wrist'))); }); + + // A known device with no calibration (a wearable with no motion channel) + // IS stamped: "not stamped with which strap" would be false there. + test('a stamped but uncalibrated device is not called unstamped', () { + final s = whyFromNote('unknown_device_family:id=helio_strap')!; + expect(s, isNot(contains('not stamped'))); + expect(s, contains('no calibration for this one')); + }); }); } diff --git a/test/adapter_signals_registry_test.dart b/test/adapter_signals_registry_test.dart index 73928db1b..60e8a0a79 100644 --- a/test/adapter_signals_registry_test.dart +++ b/test/adapter_signals_registry_test.dart @@ -15,6 +15,7 @@ import 'package:openstrap_edge/ble/adapters/ble_hrs.dart'; import 'package:openstrap_edge/ble/adapters/colmi.dart'; import 'package:openstrap_edge/ble/adapters/coros.dart'; import 'package:openstrap_edge/ble/adapters/garmin.dart'; +import 'package:openstrap_edge/ble/adapters/helio_strap.dart'; import 'package:openstrap_edge/ble/adapters/miband234.dart'; import 'package:openstrap_edge/ble/adapters/oura.dart'; import 'package:openstrap_edge/ble/adapters/pebble.dart'; @@ -41,6 +42,7 @@ void main() { 'miband234': MiBand234Adapter(key: const [0]).signals, 'pebble': kPebbleAdapter.signals, 'colmi': kColmiAdapter.signals, + 'helio_strap': kHelioStrapAdapter.signals, 'thermometer': ThermometerAdapter().signals, 'miscale_bc': MiScaleAdapter(kMiScaleComposition).signals, 'miscale2': MiScaleAdapter(kMiScale2).signals, diff --git a/test/adapters/helio_strap_full_session_test.dart b/test/adapters/helio_strap_full_session_test.dart new file mode 100644 index 000000000..1505d3c3a --- /dev/null +++ b/test/adapters/helio_strap_full_session_test.dart @@ -0,0 +1,273 @@ +// Full end-to-end scripted session for [HelioStrapAdapter]: a FAKE STRAP +// that runs its own real B-163 ECDH + AES side of the Huami2021 handshake +// (not a stub — the same math the adapter runs, mirrored), then answers one +// fetch round (activity) with protocol-correct bytes, every other type with +// "no data". Asserts the adapter actually completes authentication and +// emits a SampleBatch with the expected HR/steps samples decoded from it. +// +// Unlike `colmi_test.dart` (single notify channel per write channel), this +// protocol pushes replies across three different channels — the chunk +// transport's notify (auth), and the fetch channel's control/data chars — +// so the driver loop below routes by the WRITTEN BYTES, not just the write +// channel. + +import 'dart:async'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:openstrap_edge/ble/adapters/_registry.dart'; +import 'package:openstrap_edge/ble/adapters/adapter.dart'; +import 'package:openstrap_edge/ble/adapters/helio_strap.dart'; +import 'package:openstrap_edge/ble/adapters/signals.dart'; +import 'package:openstrap_edge/data/observation.dart'; +import 'package:openstrap_protocol/openstrap_protocol.dart'; +import 'package:pointycastle/export.dart' show AESEngine, ECBBlockCipher, KeyParameter; + +Uint8List _aesEcb(Uint8List key, Uint8List data, bool encrypt) { + final c = ECBBlockCipher(AESEngine())..init(encrypt, KeyParameter(key)); + final out = Uint8List(data.length); + for (var i = 0; i < data.length; i += 16) { + c.processBlock(data, i, out, i); + } + return out; +} + +Uint8List _aesDecrypt(Uint8List k, Uint8List d) => _aesEcb(k, d, false); + +final DateTime _now = DateTime(2026, 10, 4, 12, 0); +final int _nowSec = _now.millisecondsSinceEpoch ~/ 1000; + +/// One completed run's events and the link it ran over, for assertions. +Future<({List events, ReplayBandLink link})> _run({ + Uint8List? authKey, + int? refuseType, + bool staleEndBeforeActivity = false, +}) async { + final key = authKey ?? Uint8List.fromList(List.generate(16, (i) => i + 1)); + final link = ReplayBandLink(); + final adapter = HelioStrapAdapter( + nowSeconds: () => _nowSec, + authKeyReader: () async => key, + firstReplyTimeout: const Duration(milliseconds: 200), + quietTimeout: const Duration(milliseconds: 30), + ); + + // ── the fake strap's own handshake state, computed for real ── + final deviceKeypair = keypairFrom( + Uint8List.fromList(List.generate(24, (i) => (i * 7 + 3) % 256))); + final remoteRandom = + Uint8List.fromList(List.generate(16, (i) => (i * 11 + 5) % 256)); + final strapDecoder = Huami2021Decoder(); + final strapEncoder = Huami2021Encoder(); + Uint8List? deviceSessionKey; + + // Activity round fixture: two 1-minute records starting at a fixed local + // time, steps + hr both present on the first, steps-only on the second + // (hr sentinel) — so the test proves both metrics decode independently. + final activityRoundStart = DateTime(_now.year, _now.month, _now.day, 6, 0); + const activitySteps1 = 20, activityHr1 = 65, activitySteps2 = 10; + List activityRecord(int steps, int hr) => + [0, 0, steps & 0xff, hr & 0xff, 0, 0, 0, 0]; + final activityBytes = [ + ...activityRecord(activitySteps1, activityHr1), + ...activityRecord(activitySteps2, 0xff), // hr sentinel: dropped + ]; + + /// Builds the strap's reply to one `[0x01, type, ...time8]` start request. + /// Every type other than activity answers "no data". + List fetchStartReply(int type) { + final hasData = type == kHuami2021TypeActivity; + final expected = hasData ? activityBytes.length ~/ 8 : 0; + final rs = hasData ? activityRoundStart : DateTime(1970); + return [ + 0x10, 0x01, 0x01, // status ok + expected & 0xff, (expected >> 8) & 0xff, (expected >> 16) & 0xff, + (expected >> 24) & 0xff, + rs.year & 0xff, (rs.year >> 8) & 0xff, rs.month, rs.day, rs.hour, + rs.minute, rs.second, + ]; + } + + final events = []; + final done = Completer(); + final sub = adapter.run(link).listen(events.add, onDone: done.complete); + + unawaited(() async { + var served = 0; + while (!done.isCompleted) { + await Future.delayed(const Duration(milliseconds: 2)); + while (served < link.writes.length) { + final (char, value) = link.writes[served++]; + if (char == kHuami2021ChunkWriteChar) { + final frame = strapDecoder.feed(value, sessionKey: null); + if (frame == null || frame.endpoint != kHuami2021AuthEndpoint) { + continue; + } + final p = frame.payload; + if (p.isNotEmpty && p[0] == 0x04) { + // Step 1: phone's public key. Reply step 2. + final phonePublicKey = p.sublist(4, 4 + 48); + final shared = sharedSecret(deviceKeypair.privateKey, phonePublicKey); + deviceSessionKey = Uint8List(16); + for (var i = 0; i < 16; i++) { + deviceSessionKey![i] = shared[i + 8] ^ key[i]; + } + final step2 = Uint8List.fromList( + [0x10, 0x04, 0x01, ...remoteRandom, ...deviceKeypair.publicKey]); + for (final chunk + in strapEncoder.encode(kHuami2021AuthEndpoint, step2)) { + link.feed(kHuami2021ChunkNotifyChar, chunk, atSec: _nowSec); + } + } else if (p.isNotEmpty && p[0] == 0x05) { + // Step 4: the phone's proof. Verify both blocks decrypt to the + // SAME remote-random this strap sent — real crypto, not a stub. + final authProof = _aesDecrypt(key, p.sublist(1, 17)); + final sessionProof = + _aesDecrypt(deviceSessionKey!, p.sublist(17, 33)); + expect(authProof, remoteRandom, + reason: 'proof block 1 must decrypt under the shared auth key'); + expect(sessionProof, remoteRandom, + reason: 'proof block 2 must decrypt under the derived ' + 'session key — proves the ECDH math matches on both ' + 'sides'); + final step5 = Uint8List.fromList([0x10, 0x05, 0x01]); + for (final chunk + in strapEncoder.encode(kHuami2021AuthEndpoint, step5)) { + link.feed(kHuami2021ChunkNotifyChar, chunk, atSec: _nowSec); + } + } + continue; + } + if (char == kHuami2021FetchControlChar) { + if (value.isNotEmpty && value[0] == 0x01) { + // Start request: [0x01, type, ...time8]. + final type = value[1]; + if (staleEndBeforeActivity && type == kHuami2021TypeActivity) { + // A late round-end reply from the previous round. + link.feed(kHuami2021FetchControlChar, const [0x10, 0x02, 0x01], + atSec: _nowSec); + } + final reply = fetchStartReply(type); + if (type == refuseType) reply[2] = 0x02; // status: refused + link.feed(kHuami2021FetchControlChar, reply, atSec: _nowSec); + } else if (value.length == 1 && value[0] == 0x02) { + // Send-data trigger for the round just started. Only the + // activity round (the last start reply with real data) ever + // reaches this — reply with its two packets, then the round end. + var counter = 0; + for (final r in [ + activityRecord(activitySteps1, activityHr1), + activityRecord(activitySteps2, 0xff), + ]) { + link.feed(kHuami2021FetchDataChar, [counter++, ...r], + atSec: _nowSec); + } + link.feed(kHuami2021FetchControlChar, const [0x10, 0x02, 0x01], + atSec: _nowSec); + } + // `[0x03, 0x09]` (ack-keep) needs no reply. + } + } + } + }()); + + await done.future.timeout(const Duration(seconds: 20)); + await sub.cancel(); + await link.close(); + return (events: events, link: link); +} + +List _samples(List e) => + [for (final b in e.whereType()) ...b.samples]; +List _rows(List e) => + [for (final v in e.whereType()) ...v.rows]; + +void main() { + test('declares the signals Helio actually supplies', () { + expect(kHelioStrapAdapter.signals.keys, [ + InputSignal.hrSparse, + InputSignal.steps, + InputSignal.skinTempC, + InputSignal.deviceStress, + InputSignal.deviceHrv, + InputSignal.deviceResp, + InputSignal.deviceSpo2, + InputSignal.deviceStages, + InputSignal.vendorScalars, + ]); + }); + + test('no auth key in secure storage ends the session with kHelioNoKeyNote', + () async { + final link = ReplayBandLink(); + final adapter = HelioStrapAdapter( + nowSeconds: () => _nowSec, authKeyReader: () async => null); + final events = await adapter.run(link).toList(); + expect(events, [const BandNote(kHelioNoKeyNote)]); + expect(link.writes, isEmpty, reason: 'no key ⇒ nothing sent at all'); + }); + + test('real B-163/AES handshake completes, then one fetch round decodes ' + 'into the expected HR/steps samples', () async { + final r = await _run(); + + expect(r.events.whereType(), isEmpty, + reason: 'a real handshake success emits no failure note'); + + final samples = _samples(r.events); + expect(samples, hasLength(1), reason: 'the hr-sentinel record yields no hr sample'); + expect(samples.single.anchor, TimeAnchor.measured); + expect(samples.single.tsEpoch, + activityRoundStartSec, reason: 'first minute of the round'); + expect(samples.single.hr, 65); + + final rows = _rows(r.events); + final steps = rows.singleWhere((o) => o.key == 'steps'); + expect(steps.value, 30, reason: '20 + 10 across the two one-minute slots'); + expect(steps.unit, 'steps'); + expect(steps.sourceKind, ObservationSource.vendor); + expect(steps.attribution, kHelioStrapAttribution); + + // Every reply (handshake chunks and fetch frames) is archived verbatim — + // asserted directly, not just "some raw bytes exist somewhere": at + // least one archived frame must contain the chunk-transport marker + // byte (0x03) that only a handshake chunk carries, since the fetch + // channel's own frames never do. + // The fetch starts at a local midnight (two days back), never mid-day: + // a day the window cut into would replace the whole day's stored total. + final start = r.link.writes.firstWhere((w) => + w.$1 == kHuami2021FetchControlChar && + w.$2.length > 1 && + w.$2[0] == 0x01 && + w.$2[1] == kHuami2021TypeActivity); + final since = DateTime(2026, 10, 2); + expect(start.$2, huami2021FetchStartRequest(kHuami2021TypeActivity, since, + since.timeZoneOffset.inMinutes)); + + final raw = [for (final b in r.events.whereType()) ...?b.raw]; + expect(raw, isNotEmpty); + expect(raw.any((f) => f.isNotEmpty && f[0] == 0x03), isTrue, + reason: 'at least one archived frame must be a handshake chunk, ' + 'not only fetch-channel frames'); + }); + + test('a refused round is an incomplete sync, not a clean empty one', + () async { + final r = await _run(refuseType: kHuami2021TypeStress); + expect(r.events.whereType().map((n) => n.key), + contains(kHelioIncompleteNote)); + // What the other rounds fetched is still banked. + expect(_rows(r.events).where((o) => o.key == 'steps'), isNotEmpty); + }); + + test("a stale end reply before the start reply doesn't end the round", + () async { + final r = await _run(staleEndBeforeActivity: true); + expect(r.events.whereType(), isEmpty); + expect(_rows(r.events).singleWhere((o) => o.key == 'steps').value, 30); + }); +} + +final int activityRoundStartSec = + DateTime(_now.year, _now.month, _now.day, 6, 0).millisecondsSinceEpoch ~/ + 1000; diff --git a/test/adapters/helio_strap_night_means_test.dart b/test/adapters/helio_strap_night_means_test.dart new file mode 100644 index 000000000..f2455f750 --- /dev/null +++ b/test/adapters/helio_strap_night_means_test.dart @@ -0,0 +1,86 @@ +// The strap's RMSSD, breathing-rate and SpO2 rows fill device slots that name +// the NIGHT's value (`kDeviceValueSlot`: hrv_avg -> rmssd, ...). They used to +// be calendar-day means, so waking-hours readings were shown as the night's. + +import 'package:flutter_test/flutter_test.dart'; +import 'package:openstrap_edge/ble/adapters/helio_strap.dart'; +import 'package:openstrap_protocol/openstrap_protocol.dart'; + +int _ms(int day, int h, [int m = 0]) => + DateTime(2026, 10, day, h, m).millisecondsSinceEpoch; + +Huami2021SleepSession _night(int startMs, int endMs, {bool nap = false}) => + Huami2021SleepSession( + sessionStartMs: startMs, + isNap: nap, + avgHr: 0, + score: 0, + sleepStartMin: 0, + sleepEndMin: 0, + remMin: 0, + lightMin: 0, + deepMin: 0, + wakeMin: 0, + stages: [Huami2021Stage(startMs, endMs, kHuami2021StageLight)], + ); + +void main() { + final night = _night(_ms(3, 23), _ms(4, 7)); + + test('the mean runs over the staged night only, on its wake date', () { + final rows = HelioStrapAdapter.nightMeans([ + night, + ], { + 'hrv_avg': [ + (_ms(3, 15), 20), // afternoon: not the night's + (_ms(4, 1), 60), + (_ms(4, 3), 70), + (_ms(4, 12), 15), // after wake + ], + }); + final hrv = rows.single; + expect(hrv.vendorKey, 'hrv_avg'); + expect(hrv.value, 65); + expect(hrv.unit, 'ms'); + expect(hrv.at, DateTime(2026, 10, 4), + reason: 'a night begun at 23:00 is filed under the day it ended'); + }); + + test('no reading inside a staged night: no row, never a day mean', () { + expect( + HelioStrapAdapter.nightMeans([night], { + 'respiration_avg': [(_ms(4, 14), 16)], + 'spo2_avg': [], + }), + isEmpty, + ); + expect( + HelioStrapAdapter.nightMeans(const [], { + 'hrv_avg': [(_ms(4, 2), 60)], + }), + isEmpty, + reason: 'no staged night at all', + ); + }); + + test('a nap is not a night', () { + expect( + HelioStrapAdapter.nightMeans([ + _night(_ms(4, 14), _ms(4, 15), nap: true), + ], { + 'hrv_avg': [(_ms(4, 14, 30), 50)], + }), + isEmpty, + ); + }); + + test('a night begun before the fetch window is not used, a whole one is', + () { + final cut = _night(_ms(1, 23), _ms(2, 7)); // window starts Oct 2 00:00 + final nap = _night(_ms(1, 23, 30), _ms(2, 0, 30), nap: true); + expect( + HelioStrapAdapter.wholeSessions( + [cut, nap, night], DateTime(2026, 10, 2).millisecondsSinceEpoch), + [night]); + }); +} diff --git a/test/adapters/helio_strap_test.dart b/test/adapters/helio_strap_test.dart new file mode 100644 index 000000000..626910672 --- /dev/null +++ b/test/adapters/helio_strap_test.dart @@ -0,0 +1,33 @@ +// HelioStrapAdapter: the one behaviour that matters most before any real +// handshake exists — a session with no auth key in storage does NOTHING +// (no-leak rule, ASSUMPTIONS R6). A full scripted end-to-end walk (a fake +// strap performing its own ECDH side of the handshake and answering fetch +// rounds) is a substantial follow-up, not yet written here — see the +// adapter's own header for what IS verified (the protocol layer, by +// known-value tests in the `protocol` package) versus what still needs a +// real session replay. + +import 'package:flutter_test/flutter_test.dart'; +import 'package:openstrap_edge/ble/adapters/adapter.dart'; +import 'package:openstrap_edge/ble/adapters/helio_strap.dart'; + +void main() { + test('no stored key: the session emits kHelioNoKeyNote and nothing else', () async { + final adapter = HelioStrapAdapter(authKeyReader: () async => null); + final link = ReplayBandLink(); + + final events = await adapter.run(link).toList(); + + expect(events, hasLength(1)); + expect(events.single, isA()); + expect((events.single as BandNote).key, kHelioNoKeyNote); + expect(link.writes, isEmpty, reason: 'no key means no write is ever attempted'); + }); + + test('entry/id/label/signals match the registry row', () { + final adapter = HelioStrapAdapter(); + expect(adapter.id, 'helio_strap'); + expect(adapter.label, 'Amazfit Helio Strap'); + expect(adapter.signals, kHelioStrapSignals); + }); +} diff --git a/test/band_identity_test.dart b/test/band_identity_test.dart index 4cc332f1e..c62f7bb96 100644 --- a/test/band_identity_test.dart +++ b/test/band_identity_test.dart @@ -160,6 +160,28 @@ void main() { expect(cand([kWhoopGen5.service], 'WHOOP 5A1B'), isNull); }); + test('a FEE1 advertisement named Amazfit Helio Strap is the strap, not a Mi Band', () { + final named = HrsLink.candidateFromAd( + entries: addDeviceScanEntries(), + device: BluetoothDevice.fromId('AA:BB:CC:DD:EE:32'), + serviceUuids: [Guid(kHelioStrap.service)], + advName: 'Amazfit Helio Strap', + platformName: '', + rssi: -50, + ); + expect(named!.entryId, 'helio_strap'); + // A nameless FEE1 advertisement still takes the service match. + final nameless = HrsLink.candidateFromAd( + entries: addDeviceScanEntries(), + device: BluetoothDevice.fromId('AA:BB:CC:DD:EE:33'), + serviceUuids: [Guid(kHelioStrap.service)], + advName: '', + platformName: '', + rssi: -50, + ); + expect(nameless!.entryId, 'miband234'); + }); + test('a WHOOP advertising 0x180D is a ble_hrs hit flagged alsoBand=gen4', () { // WHY: the picker needs both facts: it matched the HR scan AND is a band. final c = cand([kHeartRateServiceUuid, kWhoopGen4.service], 'WHOOP 4C01'); diff --git a/test/band_registry_test.dart b/test/band_registry_test.dart index d8f029dce..f874e072b 100644 --- a/test/band_registry_test.dart +++ b/test/band_registry_test.dart @@ -22,6 +22,7 @@ void main() { 'coros', 'ultrahuman', 'miband234', + 'helio_strap', 'pebble', 'colmi', 'garmin', diff --git a/test/carry_forward_detail_test.dart b/test/carry_forward_detail_test.dart index 88153adef..0b09b1380 100644 --- a/test/carry_forward_detail_test.dart +++ b/test/carry_forward_detail_test.dart @@ -230,4 +230,16 @@ void main() { isFalse); }); }); + + test("a device's night RMSSD the gate refused tonight is never carried back", + () { + final prev = { + 'scalars': {'ln_rmssd_dev': 3.7, 'steps': 4000.0}, + }; + final next = {'scalars': {'rhr': 52.0}}; + DerivationEngine.carryForwardDetail(prev, next); + final sc = next['scalars'] as Map; + expect(sc.containsKey('ln_rmssd_dev'), isFalse); + expect(sc['steps'], 4000.0, reason: 'other detail still carries'); + }); } diff --git a/test/crossday_input_record_test.dart b/test/crossday_input_record_test.dart index cbb921b96..ef9d9d400 100644 --- a/test/crossday_input_record_test.dart +++ b/test/crossday_input_record_test.dart @@ -75,4 +75,16 @@ void main() { edge: wake, imported: {'2026-09-01'})!; expect(own['rhr'], 62.0); }); + + test("PE-1: the device's night RMSSD rides along in ms, only when banked", () { + final p = payload(); + (p['scalars'] as Map)['ln_rmssd_dev'] = 3.5; + final r = rec(row('2026-09-02', finalized: 1), p, edge: wake)!; + expect(r['rmssd_dev'], closeTo(33.115, 0.001)); + expect(rec(row('2026-09-02', finalized: 1), payload(), edge: wake)! + .containsKey('rmssd_dev'), isFalse); + final imp = rec(row('2026-09-01', finalized: 1), p, + edge: wake, imported: {'2026-09-01'})!; + expect(imp['rmssd_dev'], isNull); + }); } diff --git a/test/crossday_pipeline_test.dart b/test/crossday_pipeline_test.dart index 78b215d13..081da03f3 100644 --- a/test/crossday_pipeline_test.dart +++ b/test/crossday_pipeline_test.dart @@ -1036,4 +1036,47 @@ void _wiredFamilies() { expect(pct(b, 'rmssd')['n'], 49); }); }); + + group('PE-1: a device-HRV night has an HRV row', () { + const methods = {'helio_strap': 'hr_1min', 'other': 'hr_1min'}; + + // 20 nights of another hr_1min wearable whose device RMSSD runs ~30 ms + // higher, then 20 helio nights. No night has beat RMSSD. + List> nights() { + final days = _synthDays(40); + for (var i = 0; i < days.length; i++) { + final helio = i >= 20; + days[i]['skin_temp_family'] = helio ? 'helio_strap' : 'other'; + days[i]['rmssd'] = null; + days[i]['rmssd_dev'] = (helio ? 40.0 : 70.0) + ((i % 5) - 2) * 2.0; + } + days.last['rmssd_dev'] = 40.0; + return days; + } + + Map hrvRow(Map b) => + ((((b['readiness_glassbox'] as Map)['value'] as Map)['breakdown'] + as List) + .cast()) + .firstWhere((m) => m['label'] == 'hrv'); + + test('ranked against the same device only, tagged as its readings', () { + final row = hrvRow( + buildCrossDayBundle(nights(), const {}, methodFamilies: methods)); + expect(row['source'], 'device_rmssd'); + // Tonight is helio's median. Against the other wearable's ~70 ms it + // would rank at the bottom. + expect(row['percentile_of_you'], greaterThan(40)); + }); + + test('beats win: a night with beat RMSSD is not tagged', () { + final days = nights(); + for (final d in days) { + d['rmssd'] = 45.0 + ((days.indexOf(d) % 5) - 2); + } + final row = hrvRow( + buildCrossDayBundle(days, const {}, methodFamilies: methods)); + expect(row.containsKey('source'), isFalse); + }); + }); } diff --git a/test/db_paged_import_export_test.dart b/test/db_paged_import_export_test.dart index e76c43c56..bf11aeb92 100644 --- a/test/db_paged_import_export_test.dart +++ b/test/db_paged_import_export_test.dart @@ -24,6 +24,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:path/path.dart' as p; import 'package:path_provider_platform_interface/path_provider_platform_interface.dart'; import 'package:sqflite_common_ffi/sqflite_ffi.dart'; +import 'package:openstrap_edge/data/observation.dart'; import 'package:openstrap_edge/data/db.dart'; /// The page size used by both paged readers in db.dart. The tests deliberately @@ -278,6 +279,50 @@ void main() { }); }); + test("exportDaysDb carries a wearable's daily step count, not its other rows", + () async { + await clearLocal(); + Observation obs(String key, num v) => Observation( + at: DateTime(2026, 5, 21), + sourceKind: ObservationSource.vendor, + key: key, + value: v, + unit: key == 'steps' ? 'steps' : 'kcal', + attribution: 'test', + ); + await LocalDb.putObservations([obs('steps', 8123), obs('calories', 400)], + deviceId: 'watch-1'); + final outPath = await LocalDb.exportDaysDb({'2026-05-21'}); + final out = await databaseFactory.openDatabase(outPath); + try { + final rows = await out.rawQuery('SELECT key, value FROM observation'); + expect(rows, [ + {'key': 'steps', 'value': 8123}, + ]); + } finally { + await out.close(); + await databaseFactory.deleteDatabase(outPath); + } + }); + + test("deleteDays takes the wearable's step count for that day, not others", + () async { + await clearLocal(); + Observation steps(int day, int n) => Observation( + at: DateTime(2026, 5, day), + sourceKind: ObservationSource.vendor, + key: 'steps', + value: n, + unit: 'steps', + attribution: 'test', + ); + await LocalDb.putObservations([steps(22, 5000), steps(23, 6000)], + deviceId: 'watch-1'); + await LocalDb.deleteDays({'2026-05-22'}); + expect(await LocalDb.deviceDaySteps('watch-1', '2026-05-22'), isNull); + expect(await LocalDb.deviceDaySteps('watch-1', '2026-05-23'), 6000); + }); + test('exportDaysDb copies a day that has a workout on it', () async { await clearLocal(); // Local noon, so the session sits inside the day in any timezone. diff --git a/test/ed2a_substrate_transfer_test.dart b/test/ed2a_substrate_transfer_test.dart index 52c773374..8aa5e4b7c 100644 --- a/test/ed2a_substrate_transfer_test.dart +++ b/test/ed2a_substrate_transfer_test.dart @@ -241,7 +241,7 @@ void main() { markTestSkipped('committed golden is UTC; run this test with TZ=UTC'); return; } - expect(kAlgoVersion, 127, reason: 'ED-2b repins analytics; transfer remains exact'); + expect(kAlgoVersion, 133, reason: 'ED-2b repins analytics; transfer remains exact'); final fixture = _fixture(); final baseline = substrateFromDecodedPage(fixture.frames, fixture.rr); final transferred = Substrate.fromTransfer(baseline.toJson()); diff --git a/test/ed2b_algo_version_114_test.dart b/test/ed2b_algo_version_114_test.dart index 437af1b9b..7d19847bc 100644 --- a/test/ed2b_algo_version_114_test.dart +++ b/test/ed2b_algo_version_114_test.dart @@ -6,7 +6,7 @@ import 'package:openstrap_edge/compute/derivation_engine.dart'; void main() { // WHY: finalized days need a new version when the analytics pin changes outputs. test('ED-2b adoption and workout rest repin name their output changes', () { - expect(kAlgoVersion, 127); + expect(kAlgoVersion, 133); expect(kAnalyticsPin, 'a438df40b38a4586a52a68ab7e1c100fca111ccd'); final src = File('lib/compute/derivation_engine.dart').readAsStringSync(); final at = src.indexOf('// 121 → 122'); diff --git a/test/fixtures/whoop_freeze/gen4_minus0400.json b/test/fixtures/whoop_freeze/gen4_minus0400.json index ac49ab02e..26a40d3e6 100644 --- a/test/fixtures/whoop_freeze/gen4_minus0400.json +++ b/test/fixtures/whoop_freeze/gen4_minus0400.json @@ -2,7 +2,7 @@ "day_result": [ { "day_id": "2026-07-13", - "algo_version": 127, + "algo_version": 133, "payload_json": { "date": "2026-07-13", "day_confidence": 0.6, @@ -25947,7 +25947,7 @@ }, { "day_id": "2026-07-14", - "algo_version": 127, + "algo_version": 133, "payload_json": { "date": "2026-07-14", "day_confidence": 0.6, @@ -51571,7 +51571,7 @@ }, { "day_id": "2026-07-15", - "algo_version": 127, + "algo_version": 133, "payload_json": { "date": "2026-07-15", "day_confidence": 0.6, @@ -76434,7 +76434,7 @@ "metric_series_version": [ { "date": "2026-07-13", - "algo_version": 127, + "algo_version": 133, "source": "band", "device_family": "gen4", "coverage_devices": "", @@ -76442,7 +76442,7 @@ }, { "date": "2026-07-14", - "algo_version": 127, + "algo_version": 133, "source": "band", "device_family": "gen4", "coverage_devices": "", @@ -76450,7 +76450,7 @@ }, { "date": "2026-07-15", - "algo_version": 127, + "algo_version": 133, "source": "band", "device_family": "gen4", "coverage_devices": "", @@ -76460,7 +76460,7 @@ "wake_day_features": [ { "day_id": "2026-07-13", - "algo_version": 127, + "algo_version": 133, "payload_json": { "day_id": "2026-07-13", "active_min": 90, @@ -77668,7 +77668,7 @@ }, { "day_id": "2026-07-14", - "algo_version": 127, + "algo_version": 133, "payload_json": { "day_id": "2026-07-14", "active_min": 240, @@ -78876,7 +78876,7 @@ }, { "day_id": "2026-07-15", - "algo_version": 127, + "algo_version": 133, "payload_json": { "day_id": "2026-07-15", "active_min": 40, diff --git a/test/fixtures/whoop_freeze/gen4_plus0530.json b/test/fixtures/whoop_freeze/gen4_plus0530.json index f4df44d7e..367b7efc8 100644 --- a/test/fixtures/whoop_freeze/gen4_plus0530.json +++ b/test/fixtures/whoop_freeze/gen4_plus0530.json @@ -2,7 +2,7 @@ "day_result": [ { "day_id": "2026-07-13", - "algo_version": 127, + "algo_version": 133, "payload_json": { "date": "2026-07-13", "day_confidence": 0.6, @@ -25947,7 +25947,7 @@ }, { "day_id": "2026-07-14", - "algo_version": 127, + "algo_version": 133, "payload_json": { "date": "2026-07-14", "day_confidence": 0.6, @@ -51571,7 +51571,7 @@ }, { "day_id": "2026-07-15", - "algo_version": 127, + "algo_version": 133, "payload_json": { "date": "2026-07-15", "day_confidence": 0.6, @@ -76434,7 +76434,7 @@ "metric_series_version": [ { "date": "2026-07-13", - "algo_version": 127, + "algo_version": 133, "source": "band", "device_family": "gen4", "coverage_devices": "", @@ -76442,7 +76442,7 @@ }, { "date": "2026-07-14", - "algo_version": 127, + "algo_version": 133, "source": "band", "device_family": "gen4", "coverage_devices": "", @@ -76450,7 +76450,7 @@ }, { "date": "2026-07-15", - "algo_version": 127, + "algo_version": 133, "source": "band", "device_family": "gen4", "coverage_devices": "", @@ -76460,7 +76460,7 @@ "wake_day_features": [ { "day_id": "2026-07-13", - "algo_version": 127, + "algo_version": 133, "payload_json": { "day_id": "2026-07-13", "active_min": 90, @@ -77668,7 +77668,7 @@ }, { "day_id": "2026-07-14", - "algo_version": 127, + "algo_version": 133, "payload_json": { "day_id": "2026-07-14", "active_min": 240, @@ -78876,7 +78876,7 @@ }, { "day_id": "2026-07-15", - "algo_version": 127, + "algo_version": 133, "payload_json": { "day_id": "2026-07-15", "active_min": 40, diff --git a/test/fixtures/whoop_freeze/gen4_utc.json b/test/fixtures/whoop_freeze/gen4_utc.json index c44039b55..ab9b8d911 100644 --- a/test/fixtures/whoop_freeze/gen4_utc.json +++ b/test/fixtures/whoop_freeze/gen4_utc.json @@ -2,7 +2,7 @@ "day_result": [ { "day_id": "2026-07-13", - "algo_version": 127, + "algo_version": 133, "payload_json": { "date": "2026-07-13", "day_confidence": 0.6, @@ -25947,7 +25947,7 @@ }, { "day_id": "2026-07-14", - "algo_version": 127, + "algo_version": 133, "payload_json": { "date": "2026-07-14", "day_confidence": 0.6, @@ -51571,7 +51571,7 @@ }, { "day_id": "2026-07-15", - "algo_version": 127, + "algo_version": 133, "payload_json": { "date": "2026-07-15", "day_confidence": 0.6, @@ -76434,7 +76434,7 @@ "metric_series_version": [ { "date": "2026-07-13", - "algo_version": 127, + "algo_version": 133, "source": "band", "device_family": "gen4", "coverage_devices": "", @@ -76442,7 +76442,7 @@ }, { "date": "2026-07-14", - "algo_version": 127, + "algo_version": 133, "source": "band", "device_family": "gen4", "coverage_devices": "", @@ -76450,7 +76450,7 @@ }, { "date": "2026-07-15", - "algo_version": 127, + "algo_version": 133, "source": "band", "device_family": "gen4", "coverage_devices": "", @@ -76460,7 +76460,7 @@ "wake_day_features": [ { "day_id": "2026-07-13", - "algo_version": 127, + "algo_version": 133, "payload_json": { "day_id": "2026-07-13", "active_min": 90, @@ -77668,7 +77668,7 @@ }, { "day_id": "2026-07-14", - "algo_version": 127, + "algo_version": 133, "payload_json": { "day_id": "2026-07-14", "active_min": 239, @@ -78876,7 +78876,7 @@ }, { "day_id": "2026-07-15", - "algo_version": 127, + "algo_version": 133, "payload_json": { "day_id": "2026-07-15", "active_min": 40, diff --git a/test/fixtures/whoop_freeze/gen5_minus0400.json b/test/fixtures/whoop_freeze/gen5_minus0400.json index def813975..6c6679df6 100644 --- a/test/fixtures/whoop_freeze/gen5_minus0400.json +++ b/test/fixtures/whoop_freeze/gen5_minus0400.json @@ -2,7 +2,7 @@ "day_result": [ { "day_id": "2026-07-13", - "algo_version": 127, + "algo_version": 133, "payload_json": { "date": "2026-07-13", "day_confidence": 0.6, @@ -26125,7 +26125,7 @@ }, { "day_id": "2026-07-14", - "algo_version": 127, + "algo_version": 133, "payload_json": { "date": "2026-07-14", "day_confidence": 0.6, @@ -51922,7 +51922,7 @@ }, { "day_id": "2026-07-15", - "algo_version": 127, + "algo_version": 133, "payload_json": { "date": "2026-07-15", "day_confidence": 0.6, @@ -76947,7 +76947,7 @@ "metric_series_version": [ { "date": "2026-07-13", - "algo_version": 127, + "algo_version": 133, "source": "band", "device_family": "gen5", "coverage_devices": "", @@ -76955,7 +76955,7 @@ }, { "date": "2026-07-14", - "algo_version": 127, + "algo_version": 133, "source": "band", "device_family": "gen5", "coverage_devices": "", @@ -76963,7 +76963,7 @@ }, { "date": "2026-07-15", - "algo_version": 127, + "algo_version": 133, "source": "band", "device_family": "gen5", "coverage_devices": "", @@ -76973,7 +76973,7 @@ "wake_day_features": [ { "day_id": "2026-07-13", - "algo_version": 127, + "algo_version": 133, "payload_json": { "day_id": "2026-07-13", "active_min": 90, @@ -78181,7 +78181,7 @@ }, { "day_id": "2026-07-14", - "algo_version": 127, + "algo_version": 133, "payload_json": { "day_id": "2026-07-14", "active_min": 240, @@ -79389,7 +79389,7 @@ }, { "day_id": "2026-07-15", - "algo_version": 127, + "algo_version": 133, "payload_json": { "day_id": "2026-07-15", "active_min": 40, diff --git a/test/fixtures/whoop_freeze/gen5_plus0530.json b/test/fixtures/whoop_freeze/gen5_plus0530.json index d6ebcf394..b0787eb2e 100644 --- a/test/fixtures/whoop_freeze/gen5_plus0530.json +++ b/test/fixtures/whoop_freeze/gen5_plus0530.json @@ -2,7 +2,7 @@ "day_result": [ { "day_id": "2026-07-13", - "algo_version": 127, + "algo_version": 133, "payload_json": { "date": "2026-07-13", "day_confidence": 0.6, @@ -26125,7 +26125,7 @@ }, { "day_id": "2026-07-14", - "algo_version": 127, + "algo_version": 133, "payload_json": { "date": "2026-07-14", "day_confidence": 0.6, @@ -51922,7 +51922,7 @@ }, { "day_id": "2026-07-15", - "algo_version": 127, + "algo_version": 133, "payload_json": { "date": "2026-07-15", "day_confidence": 0.6, @@ -76947,7 +76947,7 @@ "metric_series_version": [ { "date": "2026-07-13", - "algo_version": 127, + "algo_version": 133, "source": "band", "device_family": "gen5", "coverage_devices": "", @@ -76955,7 +76955,7 @@ }, { "date": "2026-07-14", - "algo_version": 127, + "algo_version": 133, "source": "band", "device_family": "gen5", "coverage_devices": "", @@ -76963,7 +76963,7 @@ }, { "date": "2026-07-15", - "algo_version": 127, + "algo_version": 133, "source": "band", "device_family": "gen5", "coverage_devices": "", @@ -76973,7 +76973,7 @@ "wake_day_features": [ { "day_id": "2026-07-13", - "algo_version": 127, + "algo_version": 133, "payload_json": { "day_id": "2026-07-13", "active_min": 90, @@ -78181,7 +78181,7 @@ }, { "day_id": "2026-07-14", - "algo_version": 127, + "algo_version": 133, "payload_json": { "day_id": "2026-07-14", "active_min": 240, @@ -79389,7 +79389,7 @@ }, { "day_id": "2026-07-15", - "algo_version": 127, + "algo_version": 133, "payload_json": { "day_id": "2026-07-15", "active_min": 40, diff --git a/test/fixtures/whoop_freeze/gen5_utc.json b/test/fixtures/whoop_freeze/gen5_utc.json index 07f46ea14..b6454f263 100644 --- a/test/fixtures/whoop_freeze/gen5_utc.json +++ b/test/fixtures/whoop_freeze/gen5_utc.json @@ -2,7 +2,7 @@ "day_result": [ { "day_id": "2026-07-13", - "algo_version": 127, + "algo_version": 133, "payload_json": { "date": "2026-07-13", "day_confidence": 0.6, @@ -26125,7 +26125,7 @@ }, { "day_id": "2026-07-14", - "algo_version": 127, + "algo_version": 133, "payload_json": { "date": "2026-07-14", "day_confidence": 0.6, @@ -51922,7 +51922,7 @@ }, { "day_id": "2026-07-15", - "algo_version": 127, + "algo_version": 133, "payload_json": { "date": "2026-07-15", "day_confidence": 0.6, @@ -76947,7 +76947,7 @@ "metric_series_version": [ { "date": "2026-07-13", - "algo_version": 127, + "algo_version": 133, "source": "band", "device_family": "gen5", "coverage_devices": "", @@ -76955,7 +76955,7 @@ }, { "date": "2026-07-14", - "algo_version": 127, + "algo_version": 133, "source": "band", "device_family": "gen5", "coverage_devices": "", @@ -76963,7 +76963,7 @@ }, { "date": "2026-07-15", - "algo_version": 127, + "algo_version": 133, "source": "band", "device_family": "gen5", "coverage_devices": "", @@ -76973,7 +76973,7 @@ "wake_day_features": [ { "day_id": "2026-07-13", - "algo_version": 127, + "algo_version": 133, "payload_json": { "day_id": "2026-07-13", "active_min": 90, @@ -78181,7 +78181,7 @@ }, { "day_id": "2026-07-14", - "algo_version": 127, + "algo_version": 133, "payload_json": { "day_id": "2026-07-14", "active_min": 239, @@ -79389,7 +79389,7 @@ }, { "day_id": "2026-07-15", - "algo_version": 127, + "algo_version": 133, "payload_json": { "day_id": "2026-07-15", "active_min": 40, diff --git a/test/guards/support/pairing_reset_fixtures.dart b/test/guards/support/pairing_reset_fixtures.dart index 4c7eedcbb..246522c04 100644 --- a/test/guards/support/pairing_reset_fixtures.dart +++ b/test/guards/support/pairing_reset_fixtures.dart @@ -14,6 +14,7 @@ const Map kPinnedOfficialHost = { 'ultrahuman': 'www.ultrahuman.com', 'coros': 'support.coros.com', 'miband234': 'www.mi.com', + 'helio_strap': 'support.amazfit.com', 'pebble': 'help.repebble.com', 'colmi': 'www.colmi.com', 'garmin': 'support.garmin.com', @@ -68,6 +69,7 @@ const Set kPairingFollowUp = { 'coros', 'ultrahuman', 'miband234', + 'helio_strap', 'pebble', 'colmi', 'garmin', diff --git a/test/helio_device_hrv_readiness_test.dart b/test/helio_device_hrv_readiness_test.dart new file mode 100644 index 000000000..7d5d000ff --- /dev/null +++ b/test/helio_device_hrv_readiness_test.dart @@ -0,0 +1,200 @@ +// Policy exception PE-1 end to end: a Helio strap alone, sixteen synthetic +// nights, its own RMSSD readings banked as raw samples. Once both readiness +// inputs have their fourteen nights, the composite scores off resting HR (our +// minute HR) and the strap's readings (our night mean of them), and every +// layer says the HRV was the device's: the envelope's `hrv_source`, the served +// cell's method, the series' own key and family. + +import 'dart:convert'; +import 'dart:math' as math; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:openstrap_edge/ble/adapters/_registry.dart' show TimeAnchor; +import 'package:openstrap_edge/ble/adapters/adapter.dart' show NeutralSample; +import 'package:openstrap_edge/compute/derivation_engine.dart'; +import 'package:openstrap_edge/compute/inputs/canonical.dart'; +import 'package:openstrap_edge/compute/inputs/device_night_samples.dart'; +import 'package:openstrap_edge/compute/profile.dart'; +import 'package:openstrap_edge/compute/vendor_sleep.dart'; +import 'package:openstrap_edge/data/db.dart'; +import 'package:path/path.dart' as p; +import 'package:sqflite_common_ffi/sqflite_ffi.dart'; + +import 'support/synthetic_day.dart'; + +const int _nights = 16; +final List _days = [ + // Resting HR wanders a couple of bpm night to night, as a real one does: a + // flat baseline has no spread, and the RHR input rightly refuses it. + for (var d = 1; d <= _nights; d++) + SyntheticDay(DateTime(2026, 9, d), + nightHrOffset: ((d * 37) % 5 - 2).toDouble()), +]; +String _label(DateTime d) => + '${d.year}-${d.month.toString().padLeft(2, '0')}-${d.day.toString().padLeft(2, '0')}'; +final Set _dayIds = {for (final d in _days) _label(d.day)}; +final String _today = _label(_days.last.day); +final String _thin = _label(_days[_nights - 2].day); +const String _id = 'helio-hrv'; +const Profile _profile = + Profile(ageYears: 32, weightKg: 72, heightCm: 176, sex: 'm'); + +Map _payload(Map row) => + (jsonDecode(row['payload_json'] as String) as Map).cast(); + +void main() { + group('the night value (pure)', () { + const on = 1000, off = 1000 + 8 * 3600; + test('ln of the mean of the plausible readings inside the night', () { + final r = deviceNightLnRmssd([ + for (var i = 0; i < 6; i++) (on + i * 120, 40.0 + i * 4), + (on - 60, 90), // before the night + (on + 600, 255), // a pinned u8, not a reading + ], onsetSec: on, offsetSec: off); + expect(r.lnRmssd, closeTo(math.log(50), 1e-9)); + expect(r.refusal, isNull); + }); + test('under six readings: no value, and the note says so', () { + final r = deviceNightLnRmssd( + [for (var i = 0; i < 5; i++) (on + i * 120, 50.0)], + onsetSec: on, offsetSec: off); + expect(r.lnRmssd, isNull); + expect(r.refusal, 'device_rmssd:n=5,need=6'); + expect(deviceNightLnRmssd(const [], onsetSec: on, offsetSec: off).lnRmssd, + isNull); + }); + }); + + group('derived', () { + setUpAll(() async { + sqfliteFfiInit(); + databaseFactory = databaseFactoryFfi; + await LocalDb.close(); + LocalDb.dbName = 'helio_device_hrv_readiness_test.db'; + final dir = await databaseFactory.getDatabasesPath(); + await databaseFactory.deleteDatabase(p.join(dir, LocalDb.dbName)); + await LocalDb.upsertDevice( + id: _id, adapterId: 'helio_strap', label: 'Helio'); + await LocalDb.upsertDevice( + id: 'garmin-x', adapterId: 'garmin', label: 'garmin'); + final minuteHr = {}; + for (final d in _days) { + for (final MapEntry(key: t, value: bpm) in d.hr.entries) { + if (t % 60 == 0) minuteHr[t] = bpm; + } + } + final samples = [ + for (final t in (minuteHr.keys.toList()..sort())) + NeutralSample( + anchor: TimeAnchor.measured, tsEpoch: t, hr: minuteHr[t]), + ]; + final rnd = math.Random(7); + for (var i = 0; i < _nights; i++) { + final d = _days[i]; + final on = SyntheticDay.sec(d.sleepOnset); + final off = SyntheticDay.sec(d.sleepOffset); + // A usual night between 50 and 62 ms; the last night under it. The night + // before it carries only five readings: under the gate. + final usual = 50 + rnd.nextDouble() * 12; + final step = i == _nights - 2 ? (off - on) ~/ 5 : 120; + var n = 0; + for (var t = on + 61; t < off && (i != _nights - 2 || n < 5); + t += step, n++) { + samples.add(NeutralSample( + anchor: TimeAnchor.measured, + tsEpoch: t, + deviceRmssdMs: i == _nights - 1 + ? 44 + rnd.nextDouble() * 4 + : usual + rnd.nextDouble() * 4 - 2)); + } + await LocalDb.putVendorSleepEpochs([ + for (final (a, b, st) in d.hypnogramBlocks()) + VendorEpoch(a, b, st.name), + ], deviceId: _id, source: 'helio_strap'); + } + await LocalDb.commitSyncBatch(const [], const [], + deviceId: _id, deviceFamily: 'helio_strap', neutrals: samples); + // A family not admitted under PE-1, with readings of its own on disk. + await LocalDb.commitSyncBatch(const [], const [], + deviceId: 'garmin-x', + deviceFamily: 'garmin', + neutrals: [ + NeutralSample( + anchor: TimeAnchor.measured, + tsEpoch: SyntheticDay.sec(_days.last.sleepOnset) + 600, + deviceRmssdMs: 40), + ]); + await LocalDb.setCursor(kActiveWearableCursor, _id); + await LocalDb.setCursor(wearableEnabledCursor('helio_strap'), '1'); + for (var i = 0; i < 2; i++) { + await DerivationEngine().runDays(_profile, _dayIds, force: true); + } + }); + + tearDownAll(() async => LocalDb.close()); + + test("readiness scores off resting HR and the strap's own readings, " + 'labelled as such everywhere', () async { + final stored = _payload((await LocalDb.dayResult(_today))!); + final rc = (stored['clinical'] as Map)['readiness_composite'] as Map; + expect(rc['hrv_source'], 'device_rmssd'); + expect(rc['inputs_used'], containsAll(['HRV', 'RHR'])); + final scalars = stored['scalars'] as Map; + expect(scalars['ln_rmssd'], isNull, reason: 'no beats: not ours at 1 Hz'); + expect(scalars['ln_rmssd_dev'], closeTo(math.log(46), 0.1)); + expect(rc['method'], kDeviceHrvReadinessMethod, + reason: 'the envelope itself carries the device-HRV method'); + expect(scalars['readiness'], isA()); + expect(scalars['readiness'] as num, lessThan(50), + reason: 'the night sat far under its usual HRV'); + + final cells = (await dayCells(_today))!; + expect(cells['readiness']!['class'], 'ours'); + expect(cells['readiness']!['method'], kDeviceHrvReadinessMethod); + expect(cells['readiness']!['value'], scalars['readiness']); + expect(cells['hrv']!['class'], 'ours'); + expect(cells['hrv']!['method'], kDeviceRmssdMethod); + expect(cells['hrv']!['value'] as num, closeTo(46, 3)); + + final db = await LocalDb.instance; + final m = await db.query('metric_method', + where: 'date = ? AND key IN (?, ?)', + whereArgs: [_today, 'ln_rmssd_dev', 'readiness']); + final byKey = {for (final r in m) r['key']: r}; + expect(byKey['ln_rmssd_dev']?['family'], 'helio_strap'); + expect(byKey['readiness']?['method'], kDeviceHrvReadinessMethod); + }, timeout: const Timeout(Duration(minutes: 5))); + + test('a night under the gate takes no device HRV, and says why', () async { + final stored = _payload((await LocalDb.dayResult(_thin))!); + final rc = (stored['clinical'] as Map)['readiness_composite'] as Map; + expect(rc['hrv_source'], isNull); + expect(rc['device_rmssd_refusal'], startsWith('device_rmssd:n=5')); + expect((stored['scalars'] as Map)['ln_rmssd_dev'], isNull); + }); + + test('an unadmitted family never reaches the readings', () async { + final on = SyntheticDay.sec(_days.last.sleepOnset); + expect( + await deviceRmssdSamples('garmin', 'garmin-x', on, on + 3600), isEmpty); + expect(await deviceRmssdSamples('helio_strap', _id, on, on + 3600), + isNotEmpty); + }); + + test('re-deriving moves no stored readiness or device HRV', () async { + Future> snap() async => { + for (final d in _dayIds) + d: { + for (final k in ['readiness', 'readiness_z', 'ln_rmssd_dev']) + k: (_payload((await LocalDb.dayResult(d))!)['scalars'] + as Map)[k], + }, + }; + final before = await snap(); + for (var i = 0; i < 2; i++) { + await DerivationEngine().runDays(_profile, _dayIds, force: true); + } + expect(await snap(), before); + }, timeout: const Timeout(Duration(minutes: 5))); + }); +} diff --git a/test/helio_strap_link_test.dart b/test/helio_strap_link_test.dart new file mode 100644 index 000000000..299956179 --- /dev/null +++ b/test/helio_strap_link_test.dart @@ -0,0 +1,187 @@ +// The Helio Strap HOST: scripted strap in, database rows out. Same shape as +// `colmi_link_test.dart` — this file pins where each decoded thing LANDS, +// `test/adapters/helio_strap_full_session_test.dart` pins what is decoded +// (and already proves the ECDH/AES handshake math agrees on both sides; this +// file reuses that same real-crypto script, through `HelioStrapLink`'s real +// `BandHost` and real sqlite instead of driving the adapter directly). + +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:openstrap_edge/ble/adapters/_registry.dart'; +import 'package:openstrap_edge/ble/helio_strap_link.dart'; +import 'package:openstrap_edge/data/db.dart'; +import 'package:openstrap_protocol/openstrap_protocol.dart'; +import 'package:path/path.dart' as p; +import 'package:pointycastle/export.dart' show AESEngine, ECBBlockCipher, KeyParameter; +import 'package:sqflite_common_ffi/sqflite_ffi.dart'; + +const String _deviceId = 'helio-0a1b2c3d'; +final DateTime _now = DateTime(2026, 10, 4, 12, 0); +int _nowSec() => _now.millisecondsSinceEpoch ~/ 1000; +final Uint8List _authKey = + Uint8List.fromList(List.generate(16, (i) => i + 1)); + +Uint8List _aesEcb(Uint8List key, Uint8List data, bool encrypt) { + final c = ECBBlockCipher(AESEngine())..init(encrypt, KeyParameter(key)); + final out = Uint8List(data.length); + for (var i = 0; i < data.length; i += 16) { + c.processBlock(data, i, out, i); + } + return out; +} + +Uint8List _aesDecrypt(Uint8List k, Uint8List d) => _aesEcb(k, d, false); + +final DateTime _activityRoundStart = + DateTime(_now.year, _now.month, _now.day, 6, 0); +const int _steps1 = 20, _hr1 = 65, _steps2 = 10; + +List _activityRecord(int steps, int hr) => + [0, 0, steps & 0xff, hr & 0xff, 0, 0, 0, 0]; + +/// Real B-163/AES handshake, one real activity fetch round, every other +/// type "no data" — the exact script `helio_strap_full_session_test.dart` +/// proves agrees on both sides, restructured for `ingestForTest`'s +/// per-write callback shape (one call per write, return the replies it +/// provokes) instead of a standing event loop. +List<(String, List)> Function(int, String, List) _strapScript() { + final deviceKeypair = keypairFrom( + Uint8List.fromList(List.generate(24, (i) => (i * 7 + 3) % 256))); + final remoteRandom = + Uint8List.fromList(List.generate(16, (i) => (i * 11 + 5) % 256)); + final strapDecoder = Huami2021Decoder(); + final strapEncoder = Huami2021Encoder(); + Uint8List? deviceSessionKey; + + List fetchStartReply(int type) { + final hasData = type == kHuami2021TypeActivity; + final expected = hasData + ? (_activityRecord(_steps1, _hr1).length + + _activityRecord(_steps2, 0xff).length) ~/ + 8 + : 0; + final rs = hasData ? _activityRoundStart : DateTime(1970); + return [ + 0x10, 0x01, 0x01, + expected & 0xff, (expected >> 8) & 0xff, (expected >> 16) & 0xff, + (expected >> 24) & 0xff, + rs.year & 0xff, (rs.year >> 8) & 0xff, rs.month, rs.day, rs.hour, + rs.minute, rs.second, + ]; + } + + return (index, char, value) { + final out = <(String, List)>[]; + if (char == kHuami2021ChunkWriteChar) { + final frame = strapDecoder.feed(value, sessionKey: null); + if (frame == null || frame.endpoint != kHuami2021AuthEndpoint) { + return out; + } + final payload = frame.payload; + if (payload.isNotEmpty && payload[0] == 0x04) { + final phonePublicKey = payload.sublist(4, 4 + 48); + final shared = sharedSecret(deviceKeypair.privateKey, phonePublicKey); + deviceSessionKey = Uint8List(16); + for (var i = 0; i < 16; i++) { + deviceSessionKey![i] = shared[i + 8] ^ _authKey[i]; + } + final step2 = Uint8List.fromList( + [0x10, 0x04, 0x01, ...remoteRandom, ...deviceKeypair.publicKey]); + for (final chunk in strapEncoder.encode(kHuami2021AuthEndpoint, step2)) { + out.add((kHuami2021ChunkNotifyChar, chunk)); + } + } else if (payload.isNotEmpty && payload[0] == 0x05) { + final authProof = _aesDecrypt(_authKey, payload.sublist(1, 17)); + final sessionProof = + _aesDecrypt(deviceSessionKey!, payload.sublist(17, 33)); + expect(authProof, remoteRandom, + reason: 'proof block 1 must decrypt under the shared auth key'); + expect(sessionProof, remoteRandom, + reason: 'proof block 2 must decrypt under the derived session ' + 'key — proves the ECDH math matches on both sides'); + final step5 = Uint8List.fromList([0x10, 0x05, 0x01]); + for (final chunk in strapEncoder.encode(kHuami2021AuthEndpoint, step5)) { + out.add((kHuami2021ChunkNotifyChar, chunk)); + } + } + return out; + } + if (char == kHuami2021FetchControlChar) { + if (value.isNotEmpty && value[0] == 0x01) { + out.add((kHuami2021FetchControlChar, fetchStartReply(value[1]))); + } else if (value.length == 1 && value[0] == 0x02) { + var counter = 0; + for (final r in [ + _activityRecord(_steps1, _hr1), + _activityRecord(_steps2, 0xff), + ]) { + out.add((kHuami2021FetchDataChar, [counter++, ...r])); + } + out.add((kHuami2021FetchControlChar, const [0x10, 0x02, 0x01])); + } + } + return out; + }; +} + +void main() { + setUpAll(() { + sqfliteFfiInit(); + databaseFactory = databaseFactoryFfi; + }); + + setUp(() async { + await LocalDb.close(); + LocalDb.dbName = 'helio_strap_link_test.db'; + final dir = await databaseFactory.getDatabasesPath(); + await databaseFactory.deleteDatabase(p.join(dir, LocalDb.dbName)); + }); + + tearDown(() async => LocalDb.close()); + + Future sync() => HelioStrapLink.instance.ingestForTest( + _deviceId, + _strapScript(), + nowSeconds: _nowSec, + authKeyReader: () async => _authKey, + ); + + test('HR lands in decoded_onehz under source helio_strap, outside derivation', + () async { + await sync(); + final db = await LocalDb.instance; + final rows = await db.query('decoded_onehz', orderBy: 'rec_ts'); + final roundStartSec = _activityRoundStart.millisecondsSinceEpoch ~/ 1000; + expect(rows.map((r) => (r['rec_ts'], r['hr'])), [ + (roundStartSec, _hr1), + ], reason: 'the second minute\'s hr=0xff sentinel yields no row'); + for (final r in rows) { + expect(r['device_id'], _deviceId); + } + }); + + test('steps lands as a vendor observation attributed to Amazfit', () async { + await sync(); + final db = await LocalDb.instance; + final rows = await db.query('observation', + where: 'key = ?', whereArgs: ['steps']); + expect(rows, hasLength(1)); + expect(rows.single['value'], _steps1 + _steps2); + expect(rows.single['attribution'], 'Amazfit'); + expect(rows.single['source_kind'], 'vendor'); + }); + + test('no auth key: nothing is written and sync reports failure', () async { + final ok = await HelioStrapLink.instance.ingestForTest( + _deviceId, + (i, c, v) => const [], + nowSeconds: _nowSec, + authKeyReader: () async => null, + ).then((link) => link.writes.isEmpty); + expect(ok, isTrue); + final db = await LocalDb.instance; + expect(await db.query('decoded_onehz'), isEmpty); + expect(HelioStrapLink.instance.lastSyncFailed, isTrue); + }); +} diff --git a/test/helio_strap_pair_test.dart b/test/helio_strap_pair_test.dart new file mode 100644 index 000000000..6589c31a0 --- /dev/null +++ b/test/helio_strap_pair_test.dart @@ -0,0 +1,219 @@ +// `pairHelioStrapWithTypedKey`'s key-validation path, which runs and +// returns BEFORE any BLE call — the only part of this function testable +// without a real strap. `flutter_blue_plus` has no simulator path, so the +// connect/discover/handshake body is untested here, same as every other +// link's typed-key pairing function in this repo (none of +// `pairOuraRing`/`pairOuraRingWithKey`/`pairOuraRingWithTypedKey` has a test +// either) — verified only by real hardware (ASSUMPTIONS R6). + +import 'package:flutter_blue_plus/flutter_blue_plus.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'dart:async'; +import 'dart:collection'; + +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import 'package:openstrap_edge/ble/adapters/helio_strap.dart' + show kHelioStrapSecureStorageKey; +import 'package:openstrap_edge/ble/helio_strap_link.dart'; +import 'package:openstrap_edge/sync/reset_gate.dart'; +import 'package:openstrap_edge/data/db.dart'; +import 'package:sqflite_common_ffi/sqflite_ffi.dart'; + +void main() { + // The pairing reads the device table before its BLE call. + setUpAll(() { + sqfliteFfiInit(); + databaseFactory = databaseFactoryFfi; + LocalDb.dbName = 'openstrap_helio_pair_test.db'; + }); + tearDownAll(LocalDb.close); + + final device = BluetoothDevice.fromId('00:00:00:00:00:00'); + + test('a key that is not 32 hex characters is rejected before any BLE call', + () async { + expect(await pairHelioStrapWithTypedKey(device, 'too short'), + contains('32 hex characters')); + expect(await pairHelioStrapWithTypedKey(device, 'x' * 32), + contains('32 hex characters')); + expect(await pairHelioStrapWithTypedKey(device, 'a' * 31), + contains('32 hex characters')); + }); + + test('a 0x-prefixed key of the right length passes validation (and then ' + 'fails on the real BLE call, which is expected without a strap)', + () async { + final result = + await pairHelioStrapWithTypedKey(device, '0x${'ab' * 16}'); + // Validation passed (no "32 hex characters" complaint); whatever comes + // back is from the real connect attempt, which has nothing to connect + // to here. + expect(result, isNot(contains('32 hex characters'))); + }); + + test('a pairing begun during a reset is refused before it reads anything', + () async { + ResetGate.enter(); + try { + expect(await pairHelioStrapWithTypedKey(device, 'ab' * 16), + kHelioPairResetText); + } finally { + ResetGate.leave(); + } + }); + + test('a second strap is refused while another is paired, never folded ' + 'into its history id', () async { + await LocalDb.upsertDevice( + id: 'helio-a', adapterId: 'helio_strap', remoteId: 'AA:AA:AA:AA:AA:AA'); + try { + expect(await pairHelioStrapWithTypedKey(device, 'ab' * 16), + contains('Another Helio Strap')); + } finally { + await LocalDb.deleteDevice('helio-a'); + } + }); + + group('persisting an accepted key', () { + Future?> row() => LocalDb.deviceRow('helio-test'); + Future persist({String remoteId = 'AA:BB'}) => persistHelioPairing( + deviceId: 'helio-test', + remoteId: remoteId, + hex: 'ab' * 16, + resetGen: ResetGate.generation, + ); + + setUp(() async => LocalDb.deleteDevice('helio-test')); + + test('no reset: the key and the row land', () async { + final store = {}; + FlutterSecureStorage.setMockInitialValues(store); + expect(await persist(), isNull); + expect(store[kHelioStrapSecureStorageKey], 'ab' * 16); + expect(await row(), isNotNull); + }); + + test('a reset since the pairing began: nothing is written', () async { + final store = {}; + FlutterSecureStorage.setMockInitialValues(store); + final gen = ResetGate.generation; + ResetGate.enter(); + ResetGate.leave(); + expect( + await persistHelioPairing( + deviceId: 'helio-test', + remoteId: 'AA:BB', + hex: 'ab' * 16, + resetGen: gen), + kHelioPairResetText); + expect(store, isEmpty); + expect(await row(), isNull); + }); + + test('a strap forgotten during the pairing stays forgotten', () async { + final store = {}; + FlutterSecureStorage.setMockInitialValues(store); + final forgets = HelioStrapLink.instance.forgetsForTest; + await HelioStrapLink.forgetStrap('helio-test'); // from its device page + expect( + await persistHelioPairing( + deviceId: 'helio-test', + remoteId: 'AA:BB', + hex: 'ab' * 16, + resetGen: ResetGate.generation, + forgets: forgets), + kHelioPairForgottenText); + expect(store, isEmpty); + expect(await row(), isNull); + }); + + test('forget and reset wait for the pairing lock; a persist after a forget is refused', + () async { + final store = {}; + FlutterSecureStorage.setMockInitialValues(store); + expect(await persist(), isNull); + // Something holds the lock (a persist mid-write, say). + final gate = Completer(); + final held = HelioStrapLink.exclusive(() => gate.future); + final forgets = HelioStrapLink.instance.forgetsForTest; + final forget = HelioStrapLink.forgetStrap('helio-test'); + var raised = false; + final reset = HelioStrapLink.exclusive(() async { + ResetGate.enter(); + raised = true; + }); + await Future.delayed(const Duration(milliseconds: 20)); + expect(await row(), isNotNull, reason: 'the forget waits its turn'); + expect(raised, isFalse, reason: 'so does the reset'); + gate.complete(); + await held; + expect(await forget, isTrue); + await reset; + expect(raised, isTrue); + ResetGate.leave(); + expect(await row(), isNull); + expect(store.containsKey(kHelioStrapSecureStorageKey), isFalse); + // A pairing that began before that forget (and after the reset) cannot + // bring the strap back. + expect( + await persistHelioPairing( + deviceId: 'helio-test', + remoteId: 'AA:BB', + hex: 'ab' * 16, + resetGen: ResetGate.generation, + forgets: forgets), + kHelioPairForgottenText); + expect(await row(), isNull); + }); + + test('two straps persisting: the second is refused, not folded in', + () async { + FlutterSecureStorage.setMockInitialValues({}); + expect(await persist(), isNull); + expect(await persist(remoteId: 'CC:DD'), contains('Another Helio Strap')); + expect((await row())!['remote_id'], 'AA:BB'); + }); + + test('a reset whose key undo fails says a key may remain', () async { + FlutterSecureStorage.setMockInitialValues(_ResetOnWriteUndeletable()); + expect(await persist(), kHelioPairResetLeftoverText); + expect(await row(), isNull); + }); + + test('a reset that lands during the key write takes the key back out', + () async { + final store = _ResetOnWrite(); + FlutterSecureStorage.setMockInitialValues(store); + expect(await persist(), kHelioPairResetText); + expect(store.containsKey(kHelioStrapSecureStorageKey), isFalse, + reason: 'neither the new key nor the pre-reset one survives'); + expect(await row(), isNull); + }); + }); +} + +/// A keychain whose writes coincide with a "delete everything". +class _ResetOnWrite extends MapBase { + final _m = {}; + @override + String? operator [](Object? key) => _m[key]; + @override + void operator []=(String key, String value) { + ResetGate.enter(); + ResetGate.leave(); + _m[key] = value; + } + + @override + void clear() => _m.clear(); + @override + Iterable get keys => _m.keys; + @override + String? remove(Object? key) => _m.remove(key); +} + +/// [_ResetOnWrite] whose deletes fail, as a locked keychain's would. +class _ResetOnWriteUndeletable extends _ResetOnWrite { + @override + String? remove(Object? key) => throw StateError('keychain locked'); +} diff --git a/test/ios_ask_plist_test.dart b/test/ios_ask_plist_test.dart index e543eb01d..565083334 100644 --- a/test/ios_ask_plist_test.dart +++ b/test/ios_ask_plist_test.dart @@ -78,6 +78,17 @@ void main() { expect(swift, isNot(contains('bluetoothCompanyIdentifier ='))); }); + test('every shared-service picker name is declared, or iOS ignores it', () { + final names = RegExp( + 'NSAccessorySetupBluetoothNames\\s*(.*?)', + dotAll: true, + ).firstMatch(plist)?.group(1); + expect(names, isNotNull); + for (final e in kAskSharedServiceNames.entries) { + expect(names, contains('${e.value}'), reason: e.key); + } + }); + test('ASK sensors are notify-class, never framed bands', () { for (final e in kAskPickerSensors) { expect(e.isFramed, isFalse, reason: e.id); diff --git a/test/manual_session_test.dart b/test/manual_session_test.dart index 8529b9790..601dd3ea8 100644 --- a/test/manual_session_test.dart +++ b/test/manual_session_test.dart @@ -683,4 +683,136 @@ void main() { expect(ids, ['s4']); }); }); + + // A wearable storing one HR a minute: each sample stands for 60 s. Counted + // as one second each, its zone minutes read 60x short, and a 5-sample peak + // median is a five-minute median. + group('minute-cadence HR', () { + final ts = [for (var i = 0; i < 20; i++) 1000 + i * 60]; + final bpm = [for (var i = 0; i < 20; i++) i == 10 ? 175 : 150]; + + test('zone minutes count each sample as its own minute', () { + final z = zoneMinutesFor(bpm, 190, hrTs: ts); + expect(z.fold(0, (a, b) => a + b), closeTo(20, 1e-9)); + }); + + test('a 1 Hz stream counts exactly as before', () { + final ts1 = [for (var i = 0; i < 300; i++) 5000 + i]; + final b1 = [for (var i = 0; i < 300; i++) 140 + i % 30]; + expect(zoneMinutesFor(b1, 190, hrTs: ts1), zoneMinutesFor(b1, 190)); + }); + + test('a gap longer than the cadence is not zone time', () { + final gapped = [...ts.sublist(0, 10), for (final t in ts.sublist(10)) t + 3600]; + final z = zoneMinutesFor(bpm, 190, hrTs: gapped); + expect(z.fold(0, (a, b) => a + b), closeTo(20, 1e-9)); + }); + + test("the peak is the hardest minute, not a five-minute median", () { + final s = computeManualSessionStats( + hrTs: ts, + hrBpm: bpm, + profile: const Profile(ageYears: 32, weightKg: 72, heightCm: 176, sex: 'm'), + hrMax: 190, + ); + expect(s.maxHr, 175); + }); + + test('lost contact on a 1 Hz stream is not read as a coarser stream', () { + // HR only at 0, 1 and 600 s of a 1 Hz stream: three worn seconds. + final t = [for (var i = 0; i <= 600; i++) 9000 + i]; + final b = [for (var i = 0; i <= 600; i++) i == 0 || i == 1 || i == 600 ? 150 : 0]; + final s = computeManualSessionStats( + hrTs: t, + hrBpm: b, + profile: const Profile(ageYears: 32, weightKg: 72, heightCm: 176, sex: 'm'), + hrMax: 190, + ); + expect(s.zoneMinutes.fold(0, (a, b) => a + b), closeTo(0.05, 1e-9)); + }); + + test('a window mixing minute HR and a 1 Hz strap weights each by its own source', () { + // 20 minutes of wearable minute HR, then 10 minutes of a 1 Hz strap. + final t = [for (var i = 0; i < 20; i++) i * 60, for (var i = 0; i < 600; i++) 1200 + i]; + final b = List.filled(t.length, 150); + final caps = [for (var i = 0; i < 20; i++) 60, for (var i = 0; i < 600; i++) 1]; + final z = zoneMinutesFor(b, 190, hrTs: t, capsSec: caps, endSec: 1800); + expect(z.fold(0, (a, b) => a + b), closeTo(30, 0.05)); + }); + + test('a minute-HR hour covers the hour, and a mixed window weights its mean by time', () { + const prof = Profile(ageYears: 32, weightKg: 72, heightCm: 176, sex: 'm'); + final hour = computeManualSessionStats( + hrTs: [for (var i = 0; i < 60; i++) i * 60], + hrBpm: List.filled(60, 120), + hrCadenceSec: List.filled(60, 60), + endSec: 3600, + profile: prof, + hrMax: 190, + ); + expect(hour.hrSampleCount, 60); + expect(hour.coveredSec, 3600, reason: 'complete, not 60 seconds of it'); + // Ten minutes of 60 bpm minute HR, then a minute of 180 bpm at 1 Hz. + final mixed = computeManualSessionStats( + hrTs: [for (var i = 0; i < 10; i++) i * 60, for (var i = 0; i < 60; i++) 600 + i], + hrBpm: [...List.filled(10, 60), ...List.filled(60, 180)], + hrCadenceSec: [...List.filled(10, 60), ...List.filled(60, 1)], + endSec: 660, + profile: prof, + hrMax: 190, + ); + expect(mixed.avgHr, closeTo(71, 1)); + }); + + test('an hour of 5-minute HR prices as an hour, like the same hour at 1 minute', () { + const prof = Profile(ageYears: 32, weightKg: 72, heightCm: 176, sex: 'm'); + ManualSessionStats at(int every) => computeManualSessionStats( + hrTs: [for (var t = 0; t < 3600; t += every) t], + hrBpm: [for (var t = 0; t < 3600; t += every) 150], + hrCadenceSec: [for (var t = 0; t < 3600; t += every) every], + endSec: 3600, + profile: prof, + hrMax: 190, + restingHr: 55, + quietHrr: 0.2, + ); + final five = at(300), one = at(60); + expect(one.strain, isNotNull); + expect(five.strain, closeTo(one.strain!, 1e-9)); + }); + + test('a clipped sparse span prices its seconds, not a rounded-up minute', () { + const prof = Profile(ageYears: 32, weightKg: 72, heightCm: 176, sex: 'm'); + ManualSessionStats run(List ts, int end) => computeManualSessionStats( + hrTs: ts, + hrBpm: List.filled(ts.length, 150), + hrCadenceSec: List.filled(ts.length, 300), + endSec: end, + profile: prof, + hrMax: 190, + restingHr: 55, + quietHrr: 0.2, + ); + // 0..300 then a sample at 300 clipped to 90 s: 6.5 minutes, so 6 + // whole minutes priced, the same as a 360 s window with one sample cut + // to 60 s. + final clipped = run([0, 300], 390); + final whole = run([0, 300], 360); + expect(clipped.strain, closeTo(whole.strain!, 1e-9)); + }); + + test('a sparse minute is the mean HR of the seconds it holds', () { + // 90 s at 180 then 30 s at 80: the second minute is half of each. + expect(sparseMinutes([180, 80], [300, 300], [90, 30]), [180, 130]); + // Whole-minute spans emit their own HR. + expect(sparseMinutes([150, 120], [300, 300], [120, 60]), [150, 150, 120]); + }); + + test("the window's end clips the last sample's span", () { + // A one-minute window read inclusively: samples at 0 and 60. + final z = zoneMinutesFor([150, 150], 190, + hrTs: [0, 60], capsSec: [60, 60], endSec: 60); + expect(z.fold(0, (a, b) => a + b), closeTo(61 / 60, 0.01)); + }); + }); } diff --git a/test/metric_detail_empty_hint_test.dart b/test/metric_detail_empty_hint_test.dart index 563447dc5..bfac6eec9 100644 --- a/test/metric_detail_empty_hint_test.dart +++ b/test/metric_detail_empty_hint_test.dart @@ -7,7 +7,9 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:openstrap_edge/ui2/screens/screens.dart'; +import 'package:openstrap_edge/state/app_state.dart'; import 'package:openstrap_edge/ui2/ui2.dart'; +import 'package:provider/provider.dart'; Future _pump(WidgetTester t, String key) async { t.view.physicalSize = const Size(390 * 3, 1600 * 3); @@ -20,8 +22,8 @@ Future _pump(WidgetTester t, String key) async { await t.pumpAndSettle(); } -const _overnight = 'Wear the band overnight to start the series'; -const _daytime = 'Wear the band through the day'; +const _overnight = 'Wear your device overnight to start the series'; +const _daytime = 'Wear your device through the day'; // Written out, not read from kDaytimeMetricKeys: a key dropped from the set // must fail here rather than quietly lose its test. @@ -56,4 +58,20 @@ void main() { expect(find.text(_daytime), findsNothing); }); } + + testWidgets('hrv with no band: the chart needs beats, not more nights', + (t) async { + final app = AppState.forTesting(); + addTearDown(app.dispose); + await t.pumpWidget(ChangeNotifierProvider.value( + value: app, + child: MaterialApp( + theme: buildTheme(Brightness.light), + home: const MetricDetail('hrv', data: MetricData()), + ), + )); + await t.pumpAndSettle(); + expect(find.textContaining('beat-to-beat intervals'), findsOneWidget); + expect(find.text(_overnight), findsNothing); + }); } diff --git a/test/neutral_commit_test.dart b/test/neutral_commit_test.dart index c895fb81d..7567364fe 100644 --- a/test/neutral_commit_test.dart +++ b/test/neutral_commit_test.dart @@ -127,6 +127,106 @@ void main() { expect(onehz.single['skin_temp_c'], 34.2); }); + // A strap's HR record and its temperature record both stamped on the same + // minute (the Helio strap's activity and temperature rounds do this) used to + // be two REPLACEs on one key: the second nulled the first's column. + for (final hrFirst in [true, false]) { + test('same-second HR and temperature in one batch keep both ' + '(${hrFirst ? 'HR' : 'temperature'} first)', () async { + const hr = NeutralSample( + anchor: TimeAnchor.measured, tsEpoch: 1750000060, hr: 58, rrMs: [1030]); + const temp = NeutralSample( + anchor: TimeAnchor.measured, tsEpoch: 1750000060, skinTempC: 33.6); + await LocalDb.commitSyncBatch( + const [], + const [], + deviceId: 'helio-1', + deviceFamily: 'helio_strap', + neutrals: hrFirst ? const [hr, temp] : const [temp, hr], + ); + final db = await LocalDb.instance; + final row = (await db.query('decoded_onehz', + where: 'device_id = ? AND ts_ms = ?', + whereArgs: ['helio-1', 1750000060000])) + .single; + expect(row['hr'], 58); + expect(row['skin_temp_c'], 33.6); + expect(row['device_family'], 'helio_strap'); + final rr = await db.query('decoded_rr', + where: 'device_id = ? AND ts_ms = ?', + whereArgs: ['helio-1', 1750000060000]); + expect(rr.single['rr_ms'], 1030, + reason: 'a temperature-only sample must not evict the beats'); + }); + } + + // The realistic shape: a later session re-fetches the strap's overlapping + // window but its activity round fails (retries exhausted) while the + // temperature round lands. Its temperature-only rows must not null the HR + // the earlier session banked. + test('a later temperature-only session keeps the banked HR', () async { + Future write(List n) => LocalDb.commitSyncBatch( + const [], const [], + deviceId: 'helio-1', deviceFamily: 'helio_strap', neutrals: n); + await write(const [ + NeutralSample(anchor: TimeAnchor.measured, tsEpoch: 1750000180, hr: 61), + ]); + await write(const [ + NeutralSample( + anchor: TimeAnchor.measured, tsEpoch: 1750000180, skinTempC: 33.9), + ]); + final db = await LocalDb.instance; + final row = (await db.query('decoded_onehz', + where: 'device_id = ? AND ts_ms = ?', + whereArgs: ['helio-1', 1750000180000])) + .single; + expect(row['hr'], 61); + expect(row['skin_temp_c'], 33.9); + }); + + test("the device's own RMSSD and breathing samples merge onto the HR row", + () async { + await LocalDb.commitSyncBatch(const [], const [], + deviceId: 'helio-1', + deviceFamily: 'helio_strap', + neutrals: const [ + NeutralSample(anchor: TimeAnchor.measured, tsEpoch: 1750000240, hr: 55), + NeutralSample( + anchor: TimeAnchor.measured, tsEpoch: 1750000240, deviceRmssdMs: 48), + NeutralSample( + anchor: TimeAnchor.measured, tsEpoch: 1750000240, deviceRespBrpm: 14), + ]); + final db = await LocalDb.instance; + final row = (await db.query('decoded_onehz', + where: 'device_id = ? AND ts_ms = ?', + whereArgs: ['helio-1', 1750000240000])) + .single; + expect(row['hr'], 55); + expect(row['dev_rmssd_ms'], 48); + expect(row['dev_resp_brpm'], 14); + }); + + test('a re-read still wins per field it carries', () async { + Future write(List n) => LocalDb.commitSyncBatch( + const [], const [], + deviceId: 'helio-1', deviceFamily: 'helio_strap', neutrals: n); + await write(const [ + NeutralSample( + anchor: TimeAnchor.measured, tsEpoch: 1750000120, hr: 70, skinTempC: 33.0), + ]); + await write(const [ + NeutralSample(anchor: TimeAnchor.measured, tsEpoch: 1750000120, hr: 64), + ]); + final db = await LocalDb.instance; + final row = (await db.query('decoded_onehz', + where: 'device_id = ? AND ts_ms = ?', + whereArgs: ['helio-1', 1750000120000])) + .single; + expect(row['hr'], 64, reason: 'the newer heart rate replaces the older'); + expect(row['skin_temp_c'], 33.0, + reason: 'a field the re-read does not carry is kept, not nulled'); + }); + test('deviceId defaults to the primary and neutrals is a no-op for gen4', () async { // Single-device equivalence: passing neutrals: null (the default) queues diff --git a/test/pair_sensor_test.dart b/test/pair_sensor_test.dart index 702144731..9c41b7e19 100644 --- a/test/pair_sensor_test.dart +++ b/test/pair_sensor_test.dart @@ -193,6 +193,21 @@ void main() { expect(find.textContaining('recovery'), findsNothing); }); + testWidgets('a key-only device asks for its one key, without the ring warning', + (t) async { + final key = TextEditingController(); + addTearDown(key.dispose); + await _pump(t, PairSensorView( + entryLabel: 'Amazfit Helio Strap', keyController: key, keyRequired: true)); + expect(find.text('Device key'), findsOneWidget); + expect(find.text('32 hex digits'), findsOneWidget); + expect(find.textContaining('Leave it empty'), findsNothing); + expect(find.textContaining('Oura'), findsNothing); + await _pump(t, PairSensorView(entryLabel: 'Oura Ring', keyController: key)); + expect(find.text('Already set up elsewhere?'), findsOneWidget); + expect(find.textContaining('Leave it empty'), findsOneWidget); + }); + testWidgets('the iOS gate replaces the button with the reason', (t) async { await _pump( t, diff --git a/test/pairing_device_role_test.dart b/test/pairing_device_role_test.dart index 97e6d4a6f..849b5e20d 100644 --- a/test/pairing_device_role_test.dart +++ b/test/pairing_device_role_test.dart @@ -27,8 +27,8 @@ void main() { if (e.role == DeviceRole.band) e.id, }; expect(bands, { - 'gen4', 'gen5', 'oura', 'coros', 'ultrahuman', 'miband234', 'pebble', - 'colmi', 'garmin', + 'gen4', 'gen5', 'oura', 'coros', 'ultrahuman', 'miband234', 'helio_strap', + 'pebble', 'colmi', 'garmin', }); }); diff --git a/test/pairing_stack_review_test.dart b/test/pairing_stack_review_test.dart index 9c9b3f212..48dfc95ce 100644 --- a/test/pairing_stack_review_test.dart +++ b/test/pairing_stack_review_test.dart @@ -369,6 +369,19 @@ void main() { expect(find.text('Candidate ring'), findsOneWidget); }); + // WHY: a nearby strap handed to its key screen must stay the one listed, + // or the key is paired to whichever strap a fresh scan finds. + testWidgets('a handed-over strap is listed on its key screen from the start', + (t) async { + final app = _App(); + addTearDown(app.dispose); + final strap = (device: BluetoothDevice.fromId('strap-a'), label: 'Strap A', + rssi: -40, entryId: 'helio_strap', alsoBand: null); + await _screen(t, app, PairSensorScreen(entry: kHelioStrap, selected: strap)); + await t.pumpAndSettle(); + expect(find.text('Strap A'), findsOneWidget); + }); + // WHY: requiring an explicit result must still accept a successful child pair. // CLAIM(unframed-pairing-result); catches: always returning cancellation after handoff. testWidgets('wearable child returns success only after its pairing succeeds', (t) async { diff --git a/test/raw_archive_frames_test.dart b/test/raw_archive_frames_test.dart index 8d25ceabe..dea9ed520 100644 --- a/test/raw_archive_frames_test.dart +++ b/test/raw_archive_frames_test.dart @@ -13,6 +13,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:path/path.dart' as p; import 'package:shared_preferences/shared_preferences.dart'; import 'package:sqflite_common_ffi/sqflite_ffi.dart'; +import 'package:openstrap_edge/data/observation.dart'; import 'package:openstrap_edge/data/db.dart'; import 'package:openstrap_edge/data/models.dart'; @@ -347,6 +348,55 @@ void main() { expect(sig, contains('wearable_archive=$expected;')); }); + test("a wearable's new step count alone moves the day's signature", () async { + Future sig() => LocalDb.dayInputSignature( + dayId: '2025-06-15', + prevDayId: '2025-06-14', + nextDayId: '2025-06-16', + fromSec: 1749900000, + toSec: 1750100000, + wearableDeviceId: 'ring-1', + ); + Observation steps(int n) => Observation( + at: DateTime(2025, 6, 15), + sourceKind: ObservationSource.vendor, + key: 'steps', + value: n, + unit: 'steps', + attribution: 'test', + ); + await LocalDb.putObservations([steps(4000)], deviceId: 'ring-1'); + final before = await sig(); + expect(await sig(), before); + await LocalDb.putObservations([steps(6500)], deviceId: 'ring-1'); + expect(await sig(), isNot(before)); + }); + + test('an in-place rewrite that keeps every total still moves the signature', + () async { + final db = await LocalDb.instance; + const t = 1750000000; + for (final (i, hr) in [(0, 60), (1, 180)]) { + await db.rawInsert( + 'INSERT OR REPLACE INTO decoded_onehz (device_id, ts_ms, rec_ts, counter, hr) ' + 'VALUES (?, ?, ?, ?, ?)', + ['w-1', (t + i) * 1000, t + i, t + i, hr]); + } + Future sig() => LocalDb.dayInputSignature( + dayId: '2025-06-15', + prevDayId: '2025-06-14', + nextDayId: '2025-06-16', + fromSec: 1749900000, + toSec: 1750100000, + wearableDeviceId: null, + ); + final before = await sig(); + // Same count, same rowids, same TOTAL(hr): only the revision moves. + await db.rawUpdate('UPDATE decoded_onehz SET hr = 120 WHERE rec_ts IN (?, ?)', + [t, t + 1]); + expect(await sig(), isNot(before)); + }); + test('a backup of the new layout restores every frame', () async { await _fresh('raw_frames_backup_src.db'); final frames = [_frameHex(1), 'Not-Hex', _frameHex(2)]; diff --git a/test/readiness_baseline_pollution_test.dart b/test/readiness_baseline_pollution_test.dart index 719c31f49..900d2259a 100644 --- a/test/readiness_baseline_pollution_test.dart +++ b/test/readiness_baseline_pollution_test.dart @@ -340,4 +340,47 @@ void main() { await LocalDb.putMetricSeriesValue('2027-01-07', 'quiet_hrr', 0.14); expect(await debugBaselineSignature(), isNot(withLater)); }); + + test("a device's night RMSSD history moves the rescan signature", () async { + final db = await LocalDb.instance; + await db.delete('metric_series', where: 'key = ?', whereArgs: ['ln_rmssd_dev']); + final none = await debugBaselineSignature(); + expect(none, isNot(contains('|dev')), reason: 'no series, no term'); + for (final (d, v) in [('2027-02-01', 3.6), ('2027-02-02', 3.8), ('2027-02-03', 3.7)]) { + await LocalDb.putMetricSeriesValue(d, 'ln_rmssd_dev', v); + } + await LocalDb.putMetricSeriesValue('2027-02-04', 'rhr', 52); + final before = await debugBaselineSignature(); + expect(await debugBaselineSignature(), before); + // Same median (3.7), but the 02-02 night is not what it was. + await LocalDb.putMetricSeriesValue('2027-02-02', 'ln_rmssd_dev', 3.9); + await LocalDb.putMetricSeriesValue('2027-02-01', 'ln_rmssd_dev', 3.5); + expect(await debugBaselineSignature(), isNot(before)); + }); + + test('a full derive that no longer makes device HRV removes the old row', () async { + final db = await LocalDb.instance; + Future>> rows(String table) => db.query(table, + where: "date = '2027-03-01' AND key = 'ln_rmssd_dev'"); + Future put(Map series, {Set clear = const {}}) => + LocalDb.putDayResult( + dayId: '2027-03-01', + algoVersion: 1, + payloadJson: '{}', + windowJson: '{}', + series: series, + clearIfAbsent: clear, + seriesMethod: (k) => (method: 'm', family: 'helio_strap', cls: 'ours'), + ); + await put({'ln_rmssd_dev': 3.6, 'rhr': 50}); + expect(await rows('metric_series'), hasLength(1)); + expect(await rows('metric_method'), hasLength(1)); + // A backfill writing one key leaves it alone. + await put({'strain': 9}); + expect(await rows('metric_series'), hasLength(1)); + // The full derive owns the key: absent now, gone now. + await put({'rhr': 51}, clear: const {'ln_rmssd_dev'}); + expect(await rows('metric_series'), isEmpty); + expect(await rows('metric_method'), isEmpty); + }); } diff --git a/test/reset_generation_rule_test.dart b/test/reset_generation_rule_test.dart index 9dc6c4931..a0db3601f 100644 --- a/test/reset_generation_rule_test.dart +++ b/test/reset_generation_rule_test.dart @@ -227,7 +227,10 @@ void main() { expect(tryAt, greaterThan(enter)); // Nothing between the start and the gate writes anything. final before = body.substring(0, enter); - expect('await '.allMatches(before).length, 2); + // The third await is the Helio pairing lock the gate is raised in: it + // only waits for a pairing's persist to finish, it writes nothing. + expect('await '.allMatches(before).length, 3); + expect(before.contains('await HelioStrapLink.exclusive('), isTrue); expect(before.contains('Prefs.'), isFalse); }); diff --git a/test/reset_quiesces_ingest_test.dart b/test/reset_quiesces_ingest_test.dart index 7a09074d2..c3cecf2fe 100644 --- a/test/reset_quiesces_ingest_test.dart +++ b/test/reset_quiesces_ingest_test.dart @@ -197,7 +197,7 @@ void main() { final fin = run.substring(run.indexOf('} finally {')); expect( fin.contains( - 'if (!ResetGate.changedSince(runGen)) await _syncPairedSensors();'), + 'if (!ResetGate.changedSince(runGen)) await syncPairedSensors();'), isTrue, reason: 'a reset that ran at any point during the drain ends it'); expect(fin.substring(0, fin.indexOf('\n}\n')).contains('.instance.sync()'), diff --git a/test/reset_sensor_leftovers_test.dart b/test/reset_sensor_leftovers_test.dart index 646127527..bc15255a9 100644 --- a/test/reset_sensor_leftovers_test.dart +++ b/test/reset_sensor_leftovers_test.dart @@ -9,6 +9,9 @@ import 'dart:io'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:openstrap_edge/ble/adapters/helio_strap.dart' + show kHelioStrapSecureStorageKey; +import 'package:openstrap_edge/ble/helio_strap_link.dart'; import 'package:openstrap_edge/ble/miband_link.dart'; import 'package:openstrap_edge/ble/oura_link.dart'; import 'package:openstrap_edge/ble/session_link.dart'; @@ -118,12 +121,26 @@ void main() { expect(store.keys, ['unrelated']); }); + test("the helio strap's one fixed key is dropped too", () async { + final store = { + kHelioStrapSecureStorageKey: 'ee', + 'unrelated': 'dd', + }; + FlutterSecureStorage.setMockInitialValues(store); + expect(await HelioStrapLink.dropStoredKey(), isTrue); + expect(store.keys, ['unrelated']); + }); + test('a delete that throws is reported, not swallowed', () async { FlutterSecureStorage.setMockInitialValues( _UndeletableMap({'oura_pairing_key:known': 'aa'}), ); expect(await OuraLink.dropStoredKeys(['known']), isFalse); expect(await MiBand234Link.dropStoredKeys(['known']), isFalse); + FlutterSecureStorage.setMockInitialValues( + _UndeletableMap({kHelioStrapSecureStorageKey: 'ee'}), + ); + expect(await HelioStrapLink.dropStoredKey(), isFalse); }); test('settings tells the user when a key may remain', () { diff --git a/test/slot_comparison_test.dart b/test/slot_comparison_test.dart index a4018aa1d..16742bf77 100644 --- a/test/slot_comparison_test.dart +++ b/test/slot_comparison_test.dart @@ -88,9 +88,11 @@ void main() { }); group('wearables fill every day (the active wearable)', () { - test('the six columned entries are found (control for the loops below)', () { - expect({for (final e in _columnEntries()) e.id}, - {'garmin', 'pebble', 'miband234', 'ultrahuman', 'colmi', 'oura'}); + test('the seven columned entries are found (control for the loops below)', + () { + // helio_strap's column is the declaration-built one (sparseColumn). + expect({for (final e in _columnEntries()) e.id}, {'garmin', 'pebble', + 'miband234', 'ultrahuman', 'colmi', 'oura', 'helio_strap'}); }); test('Oura: the rows read off kOuraColumn, with their captions', () { @@ -158,7 +160,9 @@ void main() { // Pebble 2 only caption must not drop that. expect(d[C.recovery]?.reasonKey, 'capReasonPebble2OnlyEstimated'); expect(d[C.sleep]?.reasonKey, kReasonOwnStages); - expect(d[C.steps]?.kind, K.vendorReported); + // The watch's own step count is the day's steps (owner decision + // 2026-11-22), so steps are served, not only reported. + expect(d[C.steps]?.kind, K.native); expect(cmp.workoutsOnly.sends, isEmpty); }); diff --git a/test/sparse_tier_every_family_test.dart b/test/sparse_tier_every_family_test.dart new file mode 100644 index 000000000..a4ea3dafa --- /dev/null +++ b/test/sparse_tier_every_family_test.dart @@ -0,0 +1,131 @@ +// Every minute-HR wearable family gets the sparse tier, not just the ones +// it was built and tested on. One table row per family in kHrCadenceSec at +// 60 s: four synthetic days banked as one-a-minute HR plus its own +// hypnogram, derived by the real engine. Flag off: nothing. Flag on: strain +// and resting HR ours, a readiness, a workout window scored off its minute +// HR, and (when it declares a step counter) its own count as the day's +// steps. A family added to the registry without the rest of the wiring +// fails here by name. + +import 'package:flutter_test/flutter_test.dart'; +import 'package:openstrap_edge/ble/adapters/_registry.dart' + show TimeAnchor, declaredSignals; +import 'package:openstrap_edge/ble/adapters/adapter.dart' show NeutralSample; +import 'package:openstrap_edge/ble/adapters/signals.dart' show InputSignal; +import 'package:openstrap_edge/compute/derivation_engine.dart'; +import 'package:openstrap_edge/compute/inputs/canonical.dart'; +import 'package:openstrap_edge/compute/inputs/garmin_inputs.dart'; +import 'package:openstrap_edge/compute/manual_session.dart' + show computeManualSessionStats; +import 'package:openstrap_edge/compute/profile.dart'; +import 'package:openstrap_edge/compute/vendor_sleep.dart'; +import 'package:openstrap_edge/data/db.dart'; +import 'package:openstrap_edge/data/observation.dart'; +import 'package:path/path.dart' as p; +import 'package:sqflite_common_ffi/sqflite_ffi.dart'; + +import 'support/synthetic_day.dart'; + +final List _days = [ + for (var d = 1; d <= 4; d++) + SyntheticDay(DateTime(2026, 10, d), nightHrOffset: d < 4 ? -6 : 0), +]; +const String _dayId = '2026-10-04'; +const Set _dayIds = {'2026-10-01', '2026-10-02', '2026-10-03', _dayId}; +const Profile _profile = + Profile(ageYears: 32, weightKg: 72, heightCm: 176, sex: 'm'); + +void main() { + sqfliteFfiInit(); + databaseFactory = databaseFactoryFfi; + + final families = [ + for (final e in kHrCadenceSec.entries) + if (e.value == 60) e.key, + ]; + + test('the table is not empty', () => expect(families, isNotEmpty)); + + for (final family in families) { + test('$family: the sparse tier, flag off then on', () async { + await LocalDb.close(); + LocalDb.dbName = 'sparse_tier_$family.db'; + final dir = await databaseFactory.getDatabasesPath(); + await databaseFactory.deleteDatabase(p.join(dir, LocalDb.dbName)); + final id = '$family-synthetic'; + await LocalDb.upsertDevice(id: id, adapterId: family, label: family); + final minuteHr = { + for (final d in _days) + for (final MapEntry(key: t, value: bpm) in d.hr.entries) + if (t % 60 == 0) t: bpm, + }; + await LocalDb.commitSyncBatch(const [], const [], + deviceId: id, + deviceFamily: family, + neutrals: [ + for (final t in minuteHr.keys.toList()..sort()) + NeutralSample( + anchor: TimeAnchor.measured, tsEpoch: t, hr: minuteHr[t]), + ]); + for (final d in _days) { + await LocalDb.putVendorSleepEpochs([ + for (final (a, b, st) in d.hypnogramBlocks()) + VendorEpoch(a, b, st.name), + ], deviceId: id, source: family); + } + await LocalDb.putObservations([ + Observation( + at: DateTime(2026, 10, 4), + sourceKind: ObservationSource.vendor, + key: 'steps', + value: 8123, + unit: 'steps', + attribution: family, + ), + ], deviceId: id); + await LocalDb.setCursor(kActiveWearableCursor, id); + + // Flag off (rule R6): nothing. + expect(await DerivationEngine().runDays(_profile, {_dayId}, force: true), + 0); + expect(await dayCells(_dayId), isNull); + + await LocalDb.setCursor(wearableEnabledCursor(family), '1'); + // Twice: strain is priced on the prior days' quiet-waking levels, + // which the first pass writes. + for (var i = 0; i < 2; i++) { + // The first pass also re-scores the day owed a quiet level (+1). + expect(await DerivationEngine().runDays(_profile, _dayIds, force: true), + i == 0 ? 5 : 4); + } + final cells = (await dayCells(_dayId))!; + String? cls(String row) => cells[row]?['class'] as String?; + expect(cls('strain'), 'ours', reason: '${cells['strain']}'); + expect(cells['strain']!['value'], isA()); + expect(cls('resting_hr'), 'ours'); + expect(cells['resting_hr']!['method'], 'hr_1min'); + expect(cls('readiness'), anyOf('ours', 'estimated')); + expect(cells['readiness']!['value'], isA()); + + // A workout window reads its minute HR, a minute per sample. + await refreshSessionSensorSources(); + final run0 = SyntheticDay.sec(_days.last.runStart); + final hr = await LocalDb.hrSamplesInRange(run0, run0 + 40 * 60); + expect(hr.length, inInclusiveRange(39, 41)); + final stats = computeManualSessionStats( + hrTs: [for (final r in hr) (r['rec_ts'] as num).toInt()], + hrBpm: [for (final r in hr) (r['hr'] as num).toInt()], + profile: _profile, + hrMax: 186, + ); + expect(stats.zoneMinutes.fold(0, (a, b) => a + b), + inInclusiveRange(38, 41)); + + if (declaredSignals(family).contains(InputSignal.steps)) { + expect(cls('steps'), 'ours'); + expect(cells['steps']!['value'], 8123); + } + await LocalDb.close(); + }, timeout: const Timeout(Duration(minutes: 3))); + } +} diff --git a/test/step_source_ladder_test.dart b/test/step_source_ladder_test.dart index 2ddc327d0..39d3c95ae 100644 --- a/test/step_source_ladder_test.dart +++ b/test/step_source_ladder_test.dart @@ -72,6 +72,7 @@ Substrate _sub(List counters, {int step = 600, String? family = 'gen5'}) { required int liveStepsReal, required int liveStepsFromStrap, StepCalibrationProfile? counterProfile, + int? wearableSteps, }) { final bundle = {}; final scalars = {}; @@ -90,6 +91,7 @@ Substrate _sub(List counters, {int step = 600, String? family = 'gen5'}) { liveStepsReal: liveStepsReal, liveStepsFromStrap: liveStepsFromStrap, counterProfile: counterProfile, + wearableSteps: wearableSteps, ); return ((bundle['steps'] as Map).cast(), scalars); } @@ -362,6 +364,13 @@ void main() { expect(label(4000, 4000), 'Strap'); expect(label(4000, 0), 'Phone'); expect(label(0, 0), 'Strap', reason: 'the on-chip counter is the strap'); + // A wearable's own count that beat the phone's: the card names the + // device, and the envelope never names the phone it outcounted. + final (wore, _) = _derive(gen5, + liveStepsReal: 1000, liveStepsFromStrap: 0, wearableSteps: 900000); + expect(wore['source'], 'wearable'); + expect(wore['inputs_used'], ['wearable_pedometer']); + expect(stepSensorLabel(Metric.parse(wore)), 'Device'); expect( stepSensorLabel(Metric.parse( _derive(_sub([-1, -1]), liveStepsReal: 0, liveStepsFromStrap: 0).$1)), diff --git a/test/strap_sensors_test.dart b/test/strap_sensors_test.dart index f3df60ca3..e7d0e4c49 100644 --- a/test/strap_sensors_test.dart +++ b/test/strap_sensors_test.dart @@ -39,8 +39,10 @@ class _Feed extends BandAdapter { } /// Banks [samples] as [entry]'s, through the real host. -Future _bank(BandEntry entry, List samples) async { - final host = BandHost(adapter: _Feed(entry, samples), deviceId: entry.id); +Future _bank(BandEntry entry, List samples, + {String? deviceId}) async { + final host = + BandHost(adapter: _Feed(entry, samples), deviceId: deviceId ?? entry.id); await host.run(ReplayBandLink()); await host.stop(); } @@ -217,6 +219,60 @@ void main() { expect(sub.length, 611); }); + // No band row and no workout sensor in the window: the active wearable's + // own minute HR scores it, as it scores the day. It used to read nothing, + // so every session on a wearable-only install was unscored. + test("a session with no band and no strap reads the active wearable's rows", + () async { + LocalDb.sessionWearableSource = kGarmin.id; + await _bank(kGarmin, [ + for (var t = _t0; t <= _t0 + 1200; t += 60) _s(t, hr: 120), + ]); + await LocalDb.putSession({ + 'id': 'wrist', + 'start_ts': _t0, + 'end_ts': _t0 + 1200, + 'type': 'run', + 'status': 'done', + 'created_at': _t0 + 1200, + }); + final rows = await LocalDb.hrSamplesInRange(_t0, _t0 + 1200); + expect(rows, hasLength(21)); + final stats = (await LocalDb.sessionHrStats(_t0 - 1, _t0 + 1))['wrist']!; + expect(stats['n'], 21); + // No active wearable (none chosen, or its flag off): nothing, as before. + LocalDb.sessionWearableSource = null; + expect(await LocalDb.hrSamplesInRange(_t0, _t0 + 1200), isEmpty); + }); + + // A forgotten watch keeps its rows; a new one of the same adapter must not + // blend them in. + test("only the ACTIVE wearable's device scores the session", () async { + LocalDb.sessionWearableSource = kGarmin.id; + LocalDb.sessionWearableDeviceId = 'watch-b'; + try { + await _bank(kGarmin, [for (var t = _t0; t <= _t0 + 600; t += 60) _s(t, hr: 60)], + deviceId: 'watch-b'); + await _bank(kGarmin, [_s(_t0 + 30, hr: 180)], deviceId: 'watch-a'); + await LocalDb.putSession({ + 'id': 'two-watches', + 'start_ts': _t0, + 'end_ts': _t0 + 600, + 'type': 'run', + 'status': 'done', + 'created_at': _t0 + 600, + }); + final rows = await LocalDb.hrSamplesInRange(_t0, _t0 + 600); + expect(rows.map((r) => r['hr']).toSet(), {60}); + final stats = + (await LocalDb.sessionHrStats(_t0 - 1, _t0 + 1))['two-watches']!; + expect(stats['max_hr'], 60); + } finally { + LocalDb.sessionWearableDeviceId = null; + LocalDb.sessionWearableSource = null; + } + }); + test("a strap's scored session serves no score once its flag is off", () async { LocalDb.sessionSensorSources = {kBleHrs.id}; diff --git a/test/support/guide_r2_scenes.dart b/test/support/guide_r2_scenes.dart index 5f4ea685c..eaa0286e5 100644 --- a/test/support/guide_r2_scenes.dart +++ b/test/support/guide_r2_scenes.dart @@ -1,4 +1,5 @@ // Real shell + real page fixtures for the cross-cutting r2 guard. The scene table is independent of the guide definitions; coverage is checked exactly. +import 'package:openstrap_edge/sync/paired_device.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:openstrap_edge/data/db.dart'; import 'package:openstrap_edge/l10n/app_localizations.dart'; import 'package:openstrap_edge/state/alarm_schedule.dart'; import 'package:openstrap_edge/ui2/activity/catalogue.dart'; import 'package:openstrap_edge/ui2/activity/day_strain.dart'; @@ -41,7 +42,9 @@ class R2Mounted { final LiveGuideApp app; final GuideRun run; final OverlayEntry Future pumpR2Scene(WidgetTester t, R2Scene scene, {Size size = r2Size, Brightness brightness = Brightness.light, bool singlePending = true, GuideFakeRepo? repo, GlobalKey? captureKey, double devicePixelRatio = 1}) async { final guide = r2Guide(scene.guide); repo ??= GuideFakeRepo(sleepSource: scene.manual ? 'manual' : 'auto', singlePending: singlePending); - final app = await pumpLiveGuideApp(t, size: size, repo: repo, brightness: brightness, captureKey: captureKey, devicePixelRatio: devicePixelRatio); if (scene.shell) { + // The alarm buzzes the band, so its door only shows with one paired. + final app = await pumpLiveGuideApp(t, size: size, repo: repo, brightness: brightness, captureKey: captureKey, devicePixelRatio: devicePixelRatio, + paired: scene.guide == 'alarm-schedule' ? PairedDevice('guide', 'guide-band', generation: 'gen4') : null); if (scene.shell) { // Use the shipped runner here: tab-navigation signals may be owned by GuideRunner. A separately inserted run would bypass that real seam. final started = await app.runner.start(guide, band: null); expect(started, isA()); final run = (started as GuideStarted).run; diff --git a/test/support/live_guide_harness.dart b/test/support/live_guide_harness.dart index cb4b60eb6..ad57ad490 100644 --- a/test/support/live_guide_harness.dart +++ b/test/support/live_guide_harness.dart @@ -11,7 +11,7 @@ import 'package:openstrap_edge/app.dart' show AppMainShell; import 'package:open import 'package:openstrap_edge/state/locale_controller.dart'; import 'package:openstrap_edge/ble/ble_engine.dart'; import 'package:openstrap_edge/data/db.dart'; import 'package:openstrap_edge/data/local_repository.dart'; import 'package:openstrap_edge/l10n/app_localizations.dart'; import 'package:openstrap_edge/models/activity_suggestion.dart'; -import 'package:openstrap_edge/state/app_state.dart'; import 'package:openstrap_edge/state/prefs.dart'; +import 'package:openstrap_edge/sync/paired_device.dart'; import 'package:openstrap_edge/state/app_state.dart'; import 'package:openstrap_edge/state/prefs.dart'; import 'package:openstrap_edge/state/units_controller.dart'; import 'package:openstrap_edge/theme/theme_controller.dart'; import 'package:openstrap_edge/ui2/guides/guide_dim.dart'; import 'package:openstrap_edge/ui2/guides/guide_runner.dart'; import 'package:openstrap_edge/ui2/theme.dart'; import 'package:openstrap_edge/ui2/skeleton/unit_paint.dart' show GuideScrollBehavior; @@ -82,6 +82,7 @@ bool isKnownNextOverflow(FlutterErrorDetails details) { final text = details.toS /// Shared-preferences storage is empty and loaded, so the shell opens on Today. Future pumpLiveGuideApp( WidgetTester t, { Widget? home, Locale locale = const Locale('en'), double textScale = 1, Size size = const Size(390, 844), GuideRunner? runner, LocalRepository? repo, BleEngine? engine, Brightness brightness = Brightness.light, + PairedDevice? paired, double devicePixelRatio = 1, GlobalKey? captureKey, CoachConfig? coachConfig, }) async { SharedPreferences.setMockInitialValues(const {}); await Prefs.ensureLoaded(); // Prefs caches its own instance across tests, while setMockInitialValues replaces the plugin singleton. Seed its synchronous tab read explicitly. Prefs.setInt(Prefs.shellTabV2, 0); t.view.physicalSize = size * devicePixelRatio; t.view.devicePixelRatio = devicePixelRatio; addTearDown(t.view.reset); @@ -89,7 +90,7 @@ Future pumpLiveGuideApp( WidgetTester t, { Widget? home, Locale lo if (repo is GuideFakeRepo || repo == null) { await t.runAsync(() async { final ts = GuideFakeRepo._at(12, 0); await (await LocalDb.instance).rawInsert( 'INSERT OR REPLACE INTO decoded_onehz (device_id, ts_ms, rec_ts, counter, hr) VALUES (?, ?, ?, ?, ?)', ['', ts * 1000, ts, ts % 100000, 60], ); }); } final key = GlobalKey(); final guideRunner = runner ?? GuideRunner(navigatorKey: key); - final state = AppState.forTesting(engine: engine); state.repo = repo ?? GuideFakeRepo(); + final state = AppState.forTesting(engine: engine); state.repo = repo ?? GuideFakeRepo(); if (paired != null) state.paired = paired; final app = LiveGuideApp(state, guideRunner, runner?.navigatorKey ?? key); addTearDown(app.dispose); await t.pumpWidget(MultiProvider( providers: [ if (coachConfig != null) ChangeNotifierProvider.value(value: coachConfig), ChangeNotifierProvider.value(value: state), ChangeNotifierProvider(create: (_) => LocaleController.seed(locale.languageCode)), diff --git a/test/synthetic_colmi_day_test.dart b/test/synthetic_colmi_day_test.dart index ac4bb117e..45fdd4f35 100644 --- a/test/synthetic_colmi_day_test.dart +++ b/test/synthetic_colmi_day_test.dart @@ -102,7 +102,7 @@ void main() { 'skin_temp': 'ours', 'readiness': 'estimated', 'irregular_rhythm': 'unavailable', - 'steps': 'device', + 'steps': 'ours', 'strain': 'estimated', 'calories': 'device', 'movement': 'unavailable', diff --git a/test/synthetic_garmin_day_test.dart b/test/synthetic_garmin_day_test.dart index 66a0941f7..f621b7529 100644 --- a/test/synthetic_garmin_day_test.dart +++ b/test/synthetic_garmin_day_test.dart @@ -105,7 +105,7 @@ void main() { 'skin_temp': 'unavailable', 'readiness': 'estimated', 'irregular_rhythm': 'unavailable', - 'steps': 'device', + 'steps': 'ours', 'strain': 'ours', 'calories': 'ours', 'movement': 'estimated', diff --git a/test/synthetic_helio_day_test.dart b/test/synthetic_helio_day_test.dart new file mode 100644 index 000000000..1871ace86 --- /dev/null +++ b/test/synthetic_helio_day_test.dart @@ -0,0 +1,222 @@ +// An Amazfit Helio strap as the ACTIVE WEARABLE, no primary band: four +// synthetic days (test/support/synthetic_day.dart) banked the way its link +// banks them (one-a-minute HR, skin temperature as its own record on the same +// minutes, its own hypnogram), derived by the real engine and served by the +// declaration-built column (lib/compute/inputs/sparse_inputs.dart). It must +// reach the same strain / resting-HR / readiness the Garmin watch gets off +// the same minute HR, with no Helio-specific code in compute. + +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:openstrap_edge/ble/adapters/_registry.dart' show TimeAnchor; +import 'package:openstrap_edge/ble/adapters/adapter.dart' show NeutralSample; +import 'package:openstrap_edge/compute/derivation_engine.dart'; +import 'package:openstrap_edge/compute/inputs/garmin_inputs.dart' + show sparseHrSubstrate; +import 'package:openstrap_edge/compute/inputs/canonical.dart'; +import 'package:openstrap_edge/compute/manual_session.dart' + show computeManualSessionStats; +import 'package:openstrap_edge/compute/profile.dart'; +import 'package:openstrap_edge/compute/vendor_sleep.dart'; +import 'package:openstrap_edge/data/db.dart'; +import 'package:openstrap_edge/data/observation.dart'; +import 'package:path/path.dart' as p; +import 'package:sqflite_common_ffi/sqflite_ffi.dart'; + +import 'support/synthetic_day.dart'; + +final List _days = [ + for (var d = 1; d <= 4; d++) + SyntheticDay(DateTime(2026, 10, d), nightHrOffset: d < 4 ? -6 : 0), +]; +final SyntheticDay _truth = _days.last; +const String _dayId = '2026-10-04'; +const Set _dayIds = {'2026-10-01', '2026-10-02', '2026-10-03', _dayId}; +const String _id = 'helio-synthetic'; +const Profile _profile = + Profile(ageYears: 32, weightKg: 72, heightCm: 176, sex: 'm'); + +Map _payload(Map row) => + (jsonDecode(row['payload_json'] as String) as Map).cast(); + +void main() { + setUpAll(() async { + sqfliteFfiInit(); + databaseFactory = databaseFactoryFfi; + await LocalDb.close(); + LocalDb.dbName = 'synthetic_helio_day_test.db'; + final dir = await databaseFactory.getDatabasesPath(); + await databaseFactory.deleteDatabase(p.join(dir, LocalDb.dbName)); + await LocalDb.upsertDevice( + id: _id, adapterId: 'helio_strap', label: 'Helio'); + final minuteHr = {}; + for (final d in _days) { + for (final MapEntry(key: t, value: bpm) in d.hr.entries) { + if (t % 60 == 0) minuteHr[t] = bpm; + } + } + final ts = minuteHr.keys.toList()..sort(); + // The strap's activity and temperature rounds are separate records on + // the same minutes: banked as two samples per minute, as its link does. + final samples = [ + for (final t in ts) ...[ + NeutralSample( + anchor: TimeAnchor.measured, tsEpoch: t, hr: minuteHr[t]), + // Each night a little warmer: a flat channel has no spread to + // score against, and the z abstains (rightly). + NeutralSample( + anchor: TimeAnchor.measured, + tsEpoch: t, + skinTempC: 33.0 + + 0.2 * DateTime.fromMillisecondsSinceEpoch(t * 1000).day), + ], + ]; + await LocalDb.commitSyncBatch(const [], const [], + deviceId: _id, deviceFamily: 'helio_strap', neutrals: samples); + for (final d in _days) { + await LocalDb.putVendorSleepEpochs([ + for (final (a, b, st) in d.hypnogramBlocks()) VendorEpoch(a, b, st.name), + ], deviceId: _id, source: 'helio_strap'); + } + }); + + tearDownAll(() async => LocalDb.close()); + + test('flag off: the strap moves no number and serves no column', () async { + await LocalDb.setCursor(kActiveWearableCursor, _id); + expect( + await DerivationEngine().runDays(_profile, {_dayId}, force: true), 0); + expect(await LocalDb.dayResult(_dayId), isNull); + expect(await dayCells(_dayId), isNull); + }); + + test('flag on: strain, resting HR and readiness derive off its minute HR', + () async { + await LocalDb.setCursor(wearableEnabledCursor('helio_strap'), '1'); + for (var i = 0; i < 2; i++) { + // The first pass also re-scores the day owed a quiet level (+1). + expect( + await DerivationEngine().runDays(_profile, _dayIds, force: true), + i == 0 ? 5 : 4); + } + final cells = (await dayCells(_dayId))!; + String cls(String row) => cells[row]!['class'] as String; + num v(String row) => cells[row]!['value'] as num; + + expect(cls('strain'), 'ours'); + expect(v('strain'), inInclusiveRange(4, 15), + reason: 'a 40-minute run at 150 bpm, as on the watch'); + expect(cls('resting_hr'), 'ours'); + expect(cells['resting_hr']!['method'], 'hr_1min'); + expect((v('resting_hr') - _truth.nightHrNadir).abs(), lessThanOrEqualTo(6)); + expect(cls('readiness'), 'estimated'); + expect(cells['readiness']!['method'], 'rhr_only_partial'); + expect(cls('sleep_window'), 'ours'); + expect(cls('calories'), 'ours'); + expect(cls('auto_workouts'), 'ours'); + expect(cls('skin_temp'), 'ours', + reason: 'its Celsius rode on the HR rows, three nights before today'); + for (final r in ['hrv', 'respiratory_rate', 'stress', 'irregular_rhythm']) { + expect(cls(r), 'unavailable', reason: '$r: no beats, no device value'); + expect(cells[r]!['reason'], isNotEmpty); + } + // A workout window on the strap's day reads its minute HR (no band, no + // chest strap), and scores off it with each sample a minute long. + await refreshSessionSensorSources(); + final run0 = SyntheticDay.sec(_truth.runStart); + final hr = await LocalDb.hrSamplesInRange(run0, run0 + 40 * 60); + expect(hr.length, inInclusiveRange(39, 41)); + expect(hr.first['source'], 'helio_strap', + reason: "each row says whose cadence it is (the session's per-row weights)"); + final stats = computeManualSessionStats( + hrTs: [for (final r in hr) (r['rec_ts'] as num).toInt()], + hrBpm: [for (final r in hr) (r['hr'] as num).toInt()], + profile: _profile, + hrMax: 186, + ); + expect(stats.zoneMinutes.fold(0, (a, b) => a + b), + inInclusiveRange(38, 41), reason: 'minutes, not seconds'); + + final stored = _payload((await LocalDb.dayResult(_dayId))!); + expect(stored['device_family'], 'helio_strap'); + expect(stored['sleep_source'], 'vendor_staged'); + }, timeout: const Timeout(Duration(minutes: 3))); + + // Owner decision 2026-11-22: the wearable's own daily count is the day's + // steps, served as ours (a whole-day answer, never added to the phone's). + test("the strap's own step count is the day's steps", () async { + await LocalDb.putObservations([ + Observation( + at: DateTime(2026, 10, 4), + sourceKind: ObservationSource.vendor, + key: 'steps', + value: 8123, + unit: 'steps', + attribution: 'Amazfit', + ), + ], deviceId: _id); + await DerivationEngine().runDays(_profile, {_dayId}, force: true); + final stored = _payload((await LocalDb.dayResult(_dayId))!); + expect((stored['scalars'] as Map)['steps'], 8123); + expect((stored['steps'] as Map)['source'], 'wearable'); + expect((stored['steps'] as Map)['inputs_used'], ['wearable_pedometer'], + reason: 'the sensor that won is the one named, not the phone'); + expect((stored['steps'] as Map)['note'], contains("wearable's own")); + final cells = (await dayCells(_dayId))!; + expect(cells['steps']!['class'], 'ours'); + expect(cells['steps']!['value'], 8123); + }, timeout: const Timeout(Duration(minutes: 3))); + + test("a temperature record on its own second joins that minute's HR row", + () async { + final t0 = DateTime(2026, 10, 9, 1).millisecondsSinceEpoch ~/ 1000; + await LocalDb.commitSyncBatch(const [], const [], + deviceId: _id, + deviceFamily: 'helio_strap', + neutrals: [ + NeutralSample(anchor: TimeAnchor.measured, tsEpoch: t0, hr: 55), + NeutralSample(anchor: TimeAnchor.measured, tsEpoch: t0 + 60, hr: 56), + // The temperature round starts 30 s into each minute. + NeutralSample( + anchor: TimeAnchor.measured, tsEpoch: t0 + 30, skinTempC: 34.1), + NeutralSample( + anchor: TimeAnchor.measured, tsEpoch: t0 + 90, skinTempC: 34.2), + ]); + final sub = await sparseHrSubstrate('helio_strap', _id, t0, t0 + 120, + withSkinTemp: true); + expect(sub.tsSec, [t0, t0 + 60], reason: 'no extra rows: HR cadence kept'); + expect(sub.skinTemp, [3410, 3420]); + }); + + test('re-deriving with nothing new moves no stored number', () async { + Future> snapshot() async => { + for (final d in _dayIds) + d: (_payload((await LocalDb.dayResult(d))!)['scalars'] as Map) + .cast(), + }; + final before = await snapshot(); + for (var i = 0; i < 3; i++) { + await DerivationEngine().runDays(_profile, _dayIds, force: true); + } + expect(await snapshot(), before); + final db = await LocalDb.instance; + final dupes = await db.rawQuery( + 'SELECT date, key, COUNT(*) c FROM metric_series ' + 'GROUP BY date, key HAVING c > 1'); + expect(dupes, isEmpty, reason: 'one value per day per key'); + }, timeout: const Timeout(Duration(minutes: 3))); + + test('turning the strap off leaves nothing of it', () async { + onWearableDaysChanged = (days) async => + DerivationEngine().runDays(_profile, days, force: true); + try { + await setWearableEnabled('helio_strap', false); + } finally { + onWearableDaysChanged = null; + } + for (final d in _dayIds) { + expect(await LocalDb.dayResult(d), isNull, reason: d); + } + }, timeout: const Timeout(Duration(minutes: 3))); +} diff --git a/test/synthetic_miband_day_test.dart b/test/synthetic_miband_day_test.dart index 37c883f85..a9a310579 100644 --- a/test/synthetic_miband_day_test.dart +++ b/test/synthetic_miband_day_test.dart @@ -164,7 +164,7 @@ void main() { 'skin_temp': 'unavailable', 'readiness': 'estimated', 'irregular_rhythm': 'unavailable', - 'steps': 'device', + 'steps': 'ours', 'strain': 'ours', 'calories': 'ours', 'movement': 'estimated', @@ -276,8 +276,10 @@ void main() { expect(find.text('Estimated'), findsOneWidget, reason: 'readiness'); expect(find.text('From your Mi Band 2/3 · 1-min heart rate'), findsWidgets); - expect(find.text("Your Mi Band 2/3's own value"), findsOneWidget, - reason: 'its own steps'); + // Its own step count is the day's steps now (owner decision + // 2026-11-22), served as ours, not labelled as the band's own value. + expect(find.text("Your Mi Band 2/3's own value"), findsNothing, + reason: 'its steps are the day\'s steps'); }); test("a daytime sleep block's minutes stay out of the night's stages", diff --git a/test/synthetic_pebble_day_test.dart b/test/synthetic_pebble_day_test.dart index cad19cc25..ddf04d097 100644 --- a/test/synthetic_pebble_day_test.dart +++ b/test/synthetic_pebble_day_test.dart @@ -102,7 +102,7 @@ void main() { 'skin_temp': 'unavailable', 'readiness': 'estimated', 'irregular_rhythm': 'unavailable', - 'steps': 'device', + 'steps': 'ours', 'strain': 'ours', 'calories': 'ours', 'movement': 'unavailable', diff --git a/test/synthetic_ultrahuman_day_test.dart b/test/synthetic_ultrahuman_day_test.dart index 47b9adf5d..5db0eafaf 100644 --- a/test/synthetic_ultrahuman_day_test.dart +++ b/test/synthetic_ultrahuman_day_test.dart @@ -118,7 +118,7 @@ void main() { 'skin_temp': 'ours', 'readiness': 'estimated', 'irregular_rhythm': 'unavailable', - 'steps': 'device', + 'steps': 'ours', 'strain': 'estimated', 'calories': 'estimated', 'movement': 'estimated', diff --git a/test/ui2/guide_conformance_test.dart b/test/ui2/guide_conformance_test.dart index 32039fa56..a96566f28 100644 --- a/test/ui2/guide_conformance_test.dart +++ b/test/ui2/guide_conformance_test.dart @@ -11,6 +11,7 @@ // * CLAIM(guide-quotes): the caption quotes that label verbatim. * CLAIM(guide-covered): the table covers exactly the catalogue's steps (a new // guide or step without a scene fails here). * CLAIM(guide-copy): every guide string exists in every locale, differs from // English where English is not a brand, and has balanced bold markup. +import 'package:openstrap_edge/sync/paired_device.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:openstrap_edge/data/db.dart'; import 'package:openstrap_edge/l10n/app_localizations.dart'; import 'package:openstrap_edge/state/alarm_schedule.dart'; import 'package:openstrap_edge/ui2/activity/catalogue.dart' show quickStart; import 'package:openstrap_edge/ui2/activity/day_strain.dart' show DayStrainDetail; @@ -72,7 +73,9 @@ void main() { setUpAll(() async { sqfliteFfiInit(); databaseFactory = databaseFa for (final locale in AppLocalizations.supportedLocales) { group(locale.languageCode, () { for (final scene in _scenes) { testWidgets('${scene.guideId} / ${scene.stepId}: anchor and target resolve on the real ${scene.screen}', (t) async { final l = lookupAppLocalizations(locale); await pumpLiveGuideApp(t, home: scene.home(), locale: locale, textScale: 1.3, - repo: GuideFakeRepo(sleepSource: scene.sleepSource)); await settleLiveGuide(t, frames: 30); await scene.prepare?.call(t, l); + repo: GuideFakeRepo(sleepSource: scene.sleepSource), + // The alarm's door only shows with a band paired. + paired: scene.guideId == 'alarm-schedule' ? PairedDevice('guide', 'guide-band', generation: 'gen4') : null); await settleLiveGuide(t, frames: 30); await scene.prepare?.call(t, l); await settleLiveGuide(t, frames: 30); final step = _stepOf(scene); final screens = find.byType(scene.screen).evaluate().toList(); expect(screens, hasLength(1), reason: 'exactly one ${scene.screen} on screen'); final root = screens.single; // Looked at BEFORE any scrolling: this is what the run sees after a frame. diff --git a/test/ui2/live_guide_integration_test.dart b/test/ui2/live_guide_integration_test.dart index 5f94636e7..05c165872 100644 --- a/test/ui2/live_guide_integration_test.dart +++ b/test/ui2/live_guide_integration_test.dart @@ -8,7 +8,8 @@ // 1 -> 3). Cross-cutting claims: skeletonizes the REAL screen, the real target tap advances the run, wrong navigation shows the off-path card, Exit leaves // the app where the user is. import '../support/live_guide_focus.dart'; -import '../support/guide_r7_scenes.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; +import '../support/guide_r7_scenes.dart'; import 'package:flutter/material.dart'; import 'package:openstrap_edge/sync/paired_device.dart'; +import 'package:flutter_test/flutter_test.dart'; import 'package:openstrap_edge/app.dart' show AppMainShell; import 'package:openstrap_edge/data/db.dart'; import 'package:openstrap_edge/state/prefs.dart'; import 'package:openstrap_edge/l10n/app_localizations.dart'; import 'package:openstrap_edge/ui2/activity/day_strain.dart' show DayStrainDetail; @@ -45,7 +46,8 @@ void main() { setUpAll(() async { sqfliteFfiInit(); databaseFactory = databaseFa await settleLiveGuide(t); expect(find.byType(HelpScreen), findsOneWidget); expect(find.byKey(HelpScreen.guideRowKey('heart-rate-zones')), findsOneWidget); }); testWidgets('alarm starts on the real Sleep content and stays matched after revealing its lazy target', (t) async { // why: a Sleep title must not be ambiguous with the shell's Sleep button, and revealing Alarm can dispose that title in the lazy list. - final app = await pumpLiveGuideApp(t); await app.runner.start(_guide('alarm-schedule'), band: null); await _reveal(t); await _reveal(t); + // The alarm buzzes the band, so its door only shows with one paired. + final app = await pumpLiveGuideApp(t, paired: PairedDevice('guide', 'guide-band', generation: 'gen4')); await app.runner.start(_guide('alarm-schedule'), band: null); await _reveal(t); await _reveal(t); expect(_step(app), 0); expect(_run(app).currentStep!.id, 'open-alarm'); expect(liveGuideFocus, findsOneWidget); final target = _overlay(t).targetRect!; expect(target.overlaps(t.getRect(_label(_l(t).settingsAlarmRowTitle))), isTrue); expect(target.top, greaterThanOrEqualTo(0)); expect(target.bottom, lessThanOrEqualTo(844)); expect(t.takeException(), isNull); }); diff --git a/test/ui2_activity_test.dart b/test/ui2_activity_test.dart index ccf01eefe..b3b93071e 100644 --- a/test/ui2_activity_test.dart +++ b/test/ui2_activity_test.dart @@ -941,7 +941,7 @@ void main() { await show(const DayStrainData(wornMin: 1274, coveragePct: 89)); expect(find.textContaining('scored night'), findsNothing, reason: 'the night WAS scored — a cause nobody gave this screen'); - expect(find.textContaining('Wear the band through the day'), findsNothing, + expect(find.textContaining('Wear your device through the day'), findsNothing, reason: 'an action that cannot change the outcome is worse than none'); expect(find.textContaining('Nothing recorded says why'), findsOneWidget); @@ -957,7 +957,7 @@ void main() { // A day the band genuinely never saw is the ONE state where "wear the // band" is an instruction rather than an insult, so it survives there. await show(const DayStrainData()); - expect(find.textContaining('Wear the band through the day'), + expect(find.textContaining('Wear your device through the day'), findsOneWidget); // MEASURED on whoop-4, 6 of 17 days: `backfillStrainScale` rescales the @@ -1007,7 +1007,7 @@ void main() { source: 'tanaka', ceilingNote: 'unknown_device_family:id=none')); expect(find.textContaining('HELD'), findsNothing); - expect(find.textContaining('Wear the band for your normal hard sessions'), + expect(find.textContaining('Wear your device for your normal hard sessions'), findsNothing); expect(find.textContaining('which strap'), findsWidgets); @@ -2588,4 +2588,29 @@ void main() { expect(strengthLoadInRange(-1, kgU), isFalse); }); }); + + testWidgets("setup's heart-rate row: a paired band is 'not connected', no band is no live heart rate", + (tester) async { + tester.view.physicalSize = const Size(390 * 3, 1400 * 3); + tester.view.devicePixelRatio = 3; + addTearDown(tester.view.reset); + addTearDown(LiveDraft.clear); + Future show(bool paired) async { + await tester.pumpWidget(_frame( + ActivitySetup(activityByName('running')!, + key: ValueKey(paired), + weightKg: 72.4, + host: ActivityHost(bandPaired: paired)), + Brightness.light, + 1.0)); + await tester.pumpAndSettle(); + } + + await show(true); + expect(find.text('No band connected'), findsOneWidget); + expect(find.text('No live heart rate'), findsNothing); + await show(false); + expect(find.text('No live heart rate'), findsOneWidget); + expect(find.text('No band connected'), findsNothing); + }); } diff --git a/test/ui2_home_day_switcher_test.dart b/test/ui2_home_day_switcher_test.dart index f1dd368dc..454e58c6f 100644 --- a/test/ui2_home_day_switcher_test.dart +++ b/test/ui2_home_day_switcher_test.dart @@ -491,7 +491,7 @@ void main() { await _settle(t); expect(find.text('No data for this day'), findsOneWidget); - expect(find.text('Sync the band'), findsNothing); + expect(find.text('Sync your device'), findsNothing); }); testWidgets('the past-day empty card follows the app language', (t) async { diff --git a/test/ui2_home_health_test.dart b/test/ui2_home_health_test.dart index 82050562a..26fba27fc 100644 --- a/test/ui2_home_health_test.dart +++ b/test/ui2_home_health_test.dart @@ -393,6 +393,40 @@ void main() { expect(find.textContaining('Provisional'), findsNothing); }); + testWidgets("a PE-1 breakdown's HRV row says it was the device's readings", + (tester) async { + Future show(bool device) async { + await tester.pumpWidget(_frame( + ReadinessDetail( + key: ValueKey(device), + data: ReadinessData( + readiness: + const Metric(value: 60, confidence: .8, tier: MetricTier.high), + breakdown: [ + { + 'label': 'hrv', + 'weight': .4, + 'used': true, + 'past_mdc': false, + 'weighted_contribution': 1.0, + if (device) 'source': 'device_rmssd', + }, + ], + inputsUsed: 1, + ), + ), + Brightness.light, + 1, + )); + await tester.pumpAndSettle(); + } + + await show(true); + expect(find.textContaining("your device's own readings"), findsOneWidget); + await show(false); + expect(find.textContaining("your device's own readings"), findsNothing); + }); + // ── MIND-01 / MIND-04 / MT-06 / MT-07 ──────────────────────────────────── testWidgets( 'journal findings say nothing when nothing survived, and phrase a dose and ' diff --git a/test/ui2_home_no_band_test.dart b/test/ui2_home_no_band_test.dart index a5b8a2623..b8ef866b4 100644 --- a/test/ui2_home_no_band_test.dart +++ b/test/ui2_home_no_band_test.dart @@ -7,7 +7,12 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:provider/provider.dart'; +import 'package:openstrap_edge/compute/inputs/canonical.dart' + show kActiveWearableCursor, wearableEnabledCursor; +import 'package:openstrap_edge/data/db.dart'; import 'package:openstrap_edge/state/app_state.dart'; +import 'package:path/path.dart' as p; +import 'package:sqflite_common_ffi/sqflite_ffi.dart'; import 'package:openstrap_edge/sync/paired_device.dart' show PairedDevice; import 'package:openstrap_edge/ui2/profile/devices.dart' show RePair; import 'package:openstrap_edge/ui2/screens/screens.dart'; @@ -33,7 +38,7 @@ void main() { expect(find.text('No band is paired'), findsOneWidget); expect(find.text('Pair a band'), findsOneWidget); - expect(find.text('Sync the band'), findsNothing); + expect(find.text('Sync your device'), findsNothing); await t.tap(find.text('Pair a band')); await t.pump(); @@ -52,6 +57,46 @@ void main() { expect(find.text('no card'), findsOneWidget); }); + // A wearable-only install measures: its flag-on active wearable is a + // source, so Home does not claim nothing is measured. Flag off, it is not + // (rule R6), and the card stays. + testWidgets('a flag-on wearable alone is a source; flag off it is not', + (t) async { + final app = AppState.forTesting(); + addTearDown(app.dispose); + await t.runAsync(() async { + sqfliteFfiInit(); + databaseFactory = databaseFactoryFfi; + await LocalDb.close(); + LocalDb.dbName = 'ui2_home_wearable_source_test.db'; + final dir = await databaseFactory.getDatabasesPath(); + await databaseFactory.deleteDatabase(p.join(dir, LocalDb.dbName)); + await LocalDb.upsertDevice( + id: 'helio-1', adapterId: 'helio_strap', label: 'Helio'); + await LocalDb.setCursor(kActiveWearableCursor, 'helio-1'); + await app.refreshWearableSource(); + }); + expect(app.hasSource, isFalse, reason: 'flag off: not a source'); + app.initialized = true; + expect(app.route, isIn([AppRoute.welcome, AppRoute.pairing]), + reason: 'nothing measures yet: onboarding still asks for a device'); + await t.pumpWidget(_host(app)); + expect(find.text('No band is paired'), findsOneWidget); + + await t.runAsync(() async { + await LocalDb.setCursor(wearableEnabledCursor('helio_strap'), '1'); + await app.refreshWearableSource(); + }); + expect(app.hasSource, isTrue); + expect(app.isPaired, isFalse, reason: 'still no band'); + expect(app.route, AppRoute.profile, + reason: 'past pairing on the wearable alone, on to profile setup'); + await t.pumpWidget(_host(app)); + await t.pump(); + expect(find.text('No band is paired'), findsNothing); + await t.runAsync(LocalDb.close); + }); + testWidgets('no AppState above (goldens) gets no pairing card', (t) async { await t.pumpWidget(_host(null)); expect(find.text('no card'), findsOneWidget); diff --git a/test/ui2_metric_detail_load_failure_test.dart b/test/ui2_metric_detail_load_failure_test.dart index adb24c98b..eb1bc8f51 100644 --- a/test/ui2_metric_detail_load_failure_test.dart +++ b/test/ui2_metric_detail_load_failure_test.dart @@ -106,7 +106,7 @@ void main() { expect(find.textContaining('could not be read'), findsOneWidget); expect(find.text('Try again'), findsOneWidget); expect(find.text('Nothing recorded today'), findsNothing); - expect(find.textContaining('Wear the band'), findsNothing); + expect(find.textContaining('Wear your device'), findsNothing); expect(repo.reads, 1); await t.tap(find.text('Try again')); diff --git a/test/ui2_pairing_review_test.dart b/test/ui2_pairing_review_test.dart index 5ffc5bfd4..938d6f28b 100644 --- a/test/ui2_pairing_review_test.dart +++ b/test/ui2_pairing_review_test.dart @@ -115,8 +115,10 @@ void main() { expect(find.descendant(of: sleep, matching: find.text( 'Every day: From the device’s own sleep stages')), findsOneWidget); final steps = find.byKey(const ValueKey('slot-row-steps')); + // The watch's own count is the day's steps now (owner decision + // 2026-11-22): served, so no "device's own reading" caption. expect(find.descendant(of: steps, matching: find.text( - 'Every day: The device’s own reading')), findsOneWidget); + 'Every day: The device’s own reading')), findsNothing); }); testWidgets('strap lead excludes daily strain precisely', (t) async { diff --git a/test/ui2_settings_band_rows_test.dart b/test/ui2_settings_band_rows_test.dart new file mode 100644 index 000000000..51ccf1bcc --- /dev/null +++ b/test/ui2_settings_band_rows_test.dart @@ -0,0 +1,33 @@ +// A wearable-only install has no band: the band's own rows (its alarm, the +// zone-alert buzz, double-tap, step calibration) would open screens that can +// only say "the band is not connected". With a band they show as before. + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:openstrap_edge/ui2/profile/settings.dart'; +import 'package:openstrap_edge/ui2/ui2.dart'; + +Future _pump(WidgetTester t, {required bool hasBand}) async { + await t.pumpWidget(MaterialApp( + theme: buildTheme(Brightness.light), + home: MoreSettingsView( + units: 'Metric', appearance: 'Dark', phoneSteps: true, hasBand: hasBand), + )); + await t.pump(); +} + +void main() { + testWidgets('no band: none of the band-only rows', (t) async { + await _pump(t, hasBand: false); + for (final row in ['Alarm', 'HR zone alert', 'Double-tap', 'Step calibration']) { + expect(find.text(row, skipOffstage: false), findsNothing, reason: row); + } + }); + + testWidgets('a band: the band rows are there', (t) async { + await _pump(t, hasBand: true); + for (final row in ['Alarm', 'HR zone alert', 'Double-tap', 'Step calibration']) { + expect(find.text(row, skipOffstage: false), findsOneWidget, reason: row); + } + }); +} diff --git a/test/ui2_wiring_r2_test.dart b/test/ui2_wiring_r2_test.dart index 0767fbea3..62fdf07dc 100644 --- a/test/ui2_wiring_r2_test.dart +++ b/test/ui2_wiring_r2_test.dart @@ -464,7 +464,7 @@ void main() { workoutLive: true)))); expect(find.text('A workout is still running'), findsOneWidget); expect(find.text('Nothing recorded for today'), findsNothing); - expect(find.text('Sync the band'), findsNothing); + expect(find.text('Sync your device'), findsNothing); }); }); diff --git a/test/wearable_numbers_test.dart b/test/wearable_numbers_test.dart index a24a7de17..6947272a2 100644 --- a/test/wearable_numbers_test.dart +++ b/test/wearable_numbers_test.dart @@ -505,7 +505,8 @@ void main() { final caps = capabilities(kMiBandColumn); expect(caps['resting_hr'], MetricClass.ours); expect(caps['sleep_stages'], MetricClass.device); - expect(caps['steps'], MetricClass.device); + // Its own count is the day's steps (owner decision 2026-11-22). + expect(caps['steps'], MetricClass.ours); expect(caps['readiness'], MetricClass.estimated, reason: 'C partial'); expect(caps['movement'], MetricClass.estimated); expect(caps['hrv'], MetricClass.unavailable); diff --git a/test/wearable_platform_test.dart b/test/wearable_platform_test.dart index 267edf7e2..be96d1515 100644 --- a/test/wearable_platform_test.dart +++ b/test/wearable_platform_test.dart @@ -54,6 +54,7 @@ void main() { 'miband234': DeviceCategory.wearable, 'pebble': DeviceCategory.wearable, 'colmi': DeviceCategory.wearable, + 'helio_strap': DeviceCategory.wearable, 'garmin': DeviceCategory.wearable, 'thermometer': DeviceCategory.healthMeasurement, 'miscale_bc': DeviceCategory.healthMeasurement, diff --git a/test/wearable_toggle_no_leak_test.dart b/test/wearable_toggle_no_leak_test.dart index d45d8e214..4ededd71a 100644 --- a/test/wearable_toggle_no_leak_test.dart +++ b/test/wearable_toggle_no_leak_test.dart @@ -28,6 +28,7 @@ const List _families = [ 'miband234', 'colmi', 'oura', + 'helio_strap', ]; void main() { diff --git a/test/workout_max_hr_spike_test.dart b/test/workout_max_hr_spike_test.dart index 8fa5c4bd8..5d2369c39 100644 --- a/test/workout_max_hr_spike_test.dart +++ b/test/workout_max_hr_spike_test.dart @@ -323,4 +323,19 @@ void main() { expect(DerivationEngine.recoveryTau(hr, ts, 0), isNull); }); }); + + group('cadence-aware peak', () { + test('a 1 Hz spike stays suppressed beside a minute-HR sample', () { + final hr = [100, 100, 100, 100, 160, 100, 100, 100]; + final caps = [60, 1, 1, 1, 1, 1, 1, 1]; + expect(cadenceAwareMaxHrAt(hr, caps)!.$1, 100); + }); + + test("a wearable's hardest minute is its peak, not a five-minute median", () { + final hr = [100, 100, 160, 100, 100]; + final at = cadenceAwareMaxHrAt(hr, [60, 60, 60, 60, 60])!; + expect(at.$1, 160); + expect(at.$2, 2, reason: 'the index is into the full stream'); + }); + }); } diff --git a/tool/gen_ios_ask_plist.dart b/tool/gen_ios_ask_plist.dart index 5804e8f88..d75685058 100644 --- a/tool/gen_ios_ask_plist.dart +++ b/tool/gen_ios_ask_plist.dart @@ -93,11 +93,13 @@ String _sensorServicesBody(List sensors) => sensors .map((e) => '\t\t${plistUuid(e.service)}\n') .join(); -String _companyIdsBody(List sensors) => [ +// A set: one company makes several listed devices, and each id is declared +// once. +String _companyIdsBody(List sensors) => { for (final e in sensors) if (kAskSensorCompanyIds[e.id] case final id?) '\t\t${companyIdString(id)}\n', - ].join(); + }.join(); String _labelsBody(List registry) => registry .map((e) => '\t\t${plistUuid(e.service)}\n'