From 7799a028456d75d4997bde5daf22f2ce09d1d76a Mon Sep 17 00:00:00 2001 From: Mohammad Abdul Sahil <127765312+abdulsaheel@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:41:21 +0530 Subject: [PATCH 01/22] mi band 7 (l66): pair, sync, forget, on the helio engine same zepp os protocol as the helio strap, so the helio adapter and link now take an entry instead of hardcoding the strap. per device: key slot (helio keeps its old one), attribution (xiaomi for l66), hypnogram source, archive reason. hrv records stay raw for anything but helio. the band's 0x49/0x4e unit isn't confirmed without hardware, so no number labelled ms goes on disk and l66 is not in the device-rmssd set. declares hr, steps, stages and vendor scalars only. listed in the ios picker next to the other fee1 devices; ordered so the fee1 label stays helio's. beta, flag off by default. also pins helio_strap in the registry id tests the helio commit left out. --- ios/Runner/Info.plist | 4 + lib/ble/adapters/_registry.dart | 53 +++++ lib/ble/adapters/helio_strap.dart | 114 ++++++++--- lib/ble/helio_strap_link.dart | 159 +++++++++------ lib/ble/hrs_link.dart | 4 + lib/state/app_state.dart | 1 + lib/sync/background_sync.dart | 5 + lib/ui2/pairing/device_picker.dart | 4 +- lib/ui2/profile/devices.dart | 12 ++ lib/ui2/profile/pair_sensor.dart | 4 +- test/adapter_signals_registry_test.dart | 1 + test/adapters/miband7_test.dart | 254 ++++++++++++++++++++++++ test/band_registry_test.dart | 1 + test/miband7_link_test.dart | 149 ++++++++++++++ test/pairing_device_role_test.dart | 2 +- test/wearable_platform_test.dart | 1 + 16 files changed, 675 insertions(+), 93 deletions(-) create mode 100644 test/adapters/miband7_test.dart create mode 100644 test/miband7_link_test.dart diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist index b9be88cfa..f51567208 100644 --- a/ios/Runner/Info.plist +++ b/ios/Runner/Info.plist @@ -66,6 +66,7 @@ 86F65000-F706-58A0-95B2-1FB9261E4DC7 FEE1 FEE1 + FEE1 FED9 6A4E2800-667B-11E3-949A-0800200C9A66 1809 @@ -110,6 +111,8 @@ FEE1 Mi Band 2/3 FEE1 + Xiaomi Smart Band 7 + FEE1 Amazfit Helio Strap FED9 Pebble @@ -142,6 +145,7 @@ 86F65000-F706-58A0-95B2-1FB9261E4DC7 FEE1 FEE1 + FEE1 FED9 6A4E2800-667B-11E3-949A-0800200C9A66 1809 diff --git a/lib/ble/adapters/_registry.dart b/lib/ble/adapters/_registry.dart index 40a3dd95d..7420f8749 100644 --- a/lib/ble/adapters/_registry.dart +++ b/lib/ble/adapters/_registry.dart @@ -1079,6 +1079,44 @@ const BandEntry kHelioStrap = BandEntry.notify( bool _looksLikeHelioStrap(String lowercaseName) => lowercaseName.contains('helio strap'); +/// Xiaomi / Mi Smart Band 7 (codename L66). Same Huami2021/ZeppOS protocol as +/// [kHelioStrap] (same auth endpoint and handshake, same chunk and fetch +/// channels), so [HelioStrapAdapter] drives it with this entry. Keyed by +/// codename, not brand: one id covers every regional SKU sold under it. +/// +/// EXPERIMENTAL, and it stays that way: nobody on this project owns one, so +/// not a byte of this path has met hardware (ASSUMPTIONS R6). Its HRV +/// records are banked raw, never decoded into numbers, until a real band +/// shows their unit (see the adapter's HRV gate). +const BandEntry kMiBand7 = BandEntry.notify( + id: 'zeppos_l66', + role: DeviceRole.band, + kind: DeviceKind.band, + resetSteps: ResetSteps.unverified( + officialUrl: 'https://www.mi.com/global/support/', + ), + category: DeviceCategory.wearable, + label: 'Xiaomi Smart Band 7', + service: kHuami234Service, + characteristics: [ + kHuami2021ChunkWriteChar, + kHuami2021ChunkNotifyChar, + kHuami2021FetchControlChar, + kHuami2021FetchDataChar, + ], + timeAnchor: TimeAnchor.measured, + nameMatcher: _looksLikeMiBand7, + scanByName: true, +); + +/// The names the band advertises: the retail names, the bare codename, or +/// the retail name plus a 4-character suffix. "Xiaomi Smart Band 7 Pro" is a +/// different device and must not match (its suffix is 3 characters). +bool _looksLikeMiBand7(String lowercaseName) => + lowercaseName == 'l66' || + lowercaseName == 'mi smart band 7' || + RegExp(r'^xiaomi smart band 7( [0-9a-z]{4})?$').hasMatch(lowercaseName); + /// 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 @@ -1290,6 +1328,7 @@ const List kBandRegistry = [ kUltrahuman, kMiBand234, kHelioStrap, + kMiBand7, kPebble, kColmi, kGarmin, @@ -1346,6 +1385,10 @@ final List kFramedBands = /// advertisement can be read for a `bluetoothCompanyIdentifier` or /// manufacturer-data blob that differs from Mi Band's. /// +/// [kMiBand7] is listed under the same owner-accepted risk (owner decision +/// 2026-11-23): a third FEE1 device, told apart from the other two only by +/// the name it advertises. +/// /// [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 @@ -1363,6 +1406,7 @@ const List kAskPickerSensors = [ kColmi, kUltrahuman, kMiBand234, + kMiBand7, kHelioStrap, kPebble, kGarmin, @@ -1520,6 +1564,15 @@ const Map> kAdapterSignals = InputSignal.deviceStages: Duration.zero, InputSignal.vendorScalars: Duration.zero, }, + // Mirrors `kMiBand7Signals` in `helio_strap.dart`. Only what this band is + // known to carry: no skin-temperature sensor, and its HRV records are + // banked raw, not decoded (unit unconfirmed without hardware). + 'zeppos_l66': { + InputSignal.hrSparse: Duration(minutes: 1), + InputSignal.steps: Duration(minutes: 1), + InputSignal.deviceStages: Duration.zero, + InputSignal.vendorScalars: Duration.zero, + }, 'thermometer': {}, 'miscale_bc': {}, 'miscale2': {}, diff --git a/lib/ble/adapters/helio_strap.dart b/lib/ble/adapters/helio_strap.dart index d9486d7c0..7a2339340 100644 --- a/lib/ble/adapters/helio_strap.dart +++ b/lib/ble/adapters/helio_strap.dart @@ -100,6 +100,17 @@ const Duration kHelioFetchWindow = Duration(days: 2); /// writes to — shared so the two can never drift onto different items. const String kHelioStrapSecureStorageKey = 'helio_strap_auth_key'; +/// The secure-storage slot holding [entry]'s auth key. One slot per device +/// family, so pairing one never overwrites another's key. The Helio Strap +/// keeps its original slot name, so a key already stored there still reads. +String zeppOsKeySlot(BandEntry entry) => entry.id == kHelioStrap.id + ? kHelioStrapSecureStorageKey + : '${entry.id}_auth_key'; + +/// Who the device's own figures are attributed to: the brand on the box. +String zeppOsAttribution(BandEntry entry) => + entry.id == kMiBand7.id ? 'Xiaomi' : kHelioStrapAttribution; + /// 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, @@ -121,11 +132,11 @@ const FlutterSecureStorage _secure = FlutterSecureStorage(); /// 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 { +Future _defaultAuthKeyReader(BandEntry entry) async { String? hex; try { hex = await _secure.read( - key: kHelioStrapSecureStorageKey, + key: zeppOsKeySlot(entry), iOptions: kHelioStrapIosKeyOptions, mOptions: kHelioStrapMacosKeyOptions, ); @@ -277,6 +288,7 @@ class HelioStrapAdapter extends BandAdapter { final Duration quietTimeout; HelioStrapAdapter({ + this.entry = kHelioStrap, int Function()? nowSeconds, Future Function()? authKeyReader, this.authTimeout = const Duration(seconds: 8), @@ -284,13 +296,26 @@ class HelioStrapAdapter extends BandAdapter { this.quietTimeout = const Duration(milliseconds: 800), }) : nowSeconds = nowSeconds ?? (() => DateTime.now().millisecondsSinceEpoch ~/ 1000), - authKeyReader = authKeyReader ?? _defaultAuthKeyReader; + authKeyReader = + authKeyReader ?? (() => _defaultAuthKeyReader(entry)); + /// The device this session drives: [kHelioStrap] or [kMiBand7]. Same + /// protocol; the entry decides the key slot, attribution, signals and + /// which record types are decoded. @override - BandEntry get entry => kHelioStrap; + final BandEntry entry; @override - Map get signals => kHelioStrapSignals; + Map get signals => + entry.id == kMiBand7.id ? kMiBand7Signals : kHelioStrapSignals; + + String get _attribution => zeppOsAttribution(entry); + + /// HRV records (types 0x49, 0x4E) are decoded only for the Helio Strap. + /// For any other device their unit is unconfirmed without hardware, so + /// their bytes are banked raw for a later re-decode and never stored as a + /// number labelled "ms". + bool get _decodesHrv => entry.id == kHelioStrap.id; @override Stream run(BandLink link) async* { @@ -336,6 +361,11 @@ class HelioStrapAdapter extends BandAdapter { // attempt, a stale frame): archived anyway, never decoded. final strayRaw = []; var incomplete = false; + final attribution = _attribution; + Observation obs(DateTime day, num value, + {String? unit, String? key, String? vendorKey}) => + _obs(day, value, + unit: unit, key: key, vendorKey: vendorKey, attribution: attribution); Future<_FetchRound?> fetch(int type) => _fetchOneRound( link, controlInbox, dataInbox, type, since, utcOffsetMinutes, @@ -397,7 +427,9 @@ class HelioStrapAdapter extends BandAdapter { final hrvFetch = await fetch(kHuami2021TypeHrv); if (hrvFetch != null) { raw.addAll(hrvFetch.raw); - for (final s in parseHuami2021Hrv(hrvFetch.bytes)) { + for (final s in _decodesHrv + ? parseHuami2021Hrv(hrvFetch.bytes) + : const []) { 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. @@ -411,7 +443,9 @@ class HelioStrapAdapter extends BandAdapter { final sdnnFetch = await fetch(kHuami2021TypeHrvSdnn); if (sdnnFetch != null) { raw.addAll(sdnnFetch.raw); - for (final s in parseHuami2021HrvSdnn(sdnnFetch.bytes)) { + for (final s in _decodesHrv + ? parseHuami2021HrvSdnn(sdnnFetch.bytes) + : const []) { (hrvSdnn[dayOf(s.ms)] ??= []).add(s.value); } } @@ -458,11 +492,11 @@ class HelioStrapAdapter extends BandAdapter { // 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'), + obs(key, value, unit: 'steps', key: 'steps'), for (final MapEntry(:key, :value) in stress.entries) - _obs(key, _mean(value), vendorKey: 'stress_avg'), + 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'), + obs(key, _mean(value), unit: 'ms', vendorKey: 'hrv_sdnn_avg'), ]; if (earlyRows.isNotEmpty) yield VendorScalars(earlyRows); @@ -472,8 +506,8 @@ class HelioStrapAdapter extends BandAdapter { 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')); + 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); @@ -485,12 +519,12 @@ class HelioStrapAdapter extends BandAdapter { 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')); + 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')); + odiRows.add(obs(d, o.odiRefined!, vendorKey: 'odi_refined')); } if (o.score != null) { - odiRows.add(_obs(d, o.score!, vendorKey: 'odi_score')); + odiRows.add(obs(d, o.score!, vendorKey: 'odi_score')); } } if (odiRows.isNotEmpty) yield VendorScalars(odiRows); @@ -509,7 +543,7 @@ class HelioStrapAdapter extends BandAdapter { sourceKind: ObservationSource.vendor, vendorKey: 'workout_sport_type', value: w.sportType, - attribution: kHelioStrapAttribution, + attribution: attribution, )); workoutRows.add(Observation( at: start, @@ -517,7 +551,7 @@ class HelioStrapAdapter extends BandAdapter { vendorKey: 'workout_duration_sec', value: w.durationSec, unit: 's', - attribution: kHelioStrapAttribution, + attribution: attribution, )); workoutRows.add(Observation( at: start, @@ -525,7 +559,7 @@ class HelioStrapAdapter extends BandAdapter { vendorKey: 'workout_calories', value: w.calories, unit: 'kcal', - attribution: kHelioStrapAttribution, + attribution: attribution, )); workoutRows.add(Observation( at: start, @@ -533,7 +567,7 @@ class HelioStrapAdapter extends BandAdapter { vendorKey: 'workout_avg_hr', value: w.avgHr, unit: 'bpm', - attribution: kHelioStrapAttribution, + attribution: attribution, )); workoutRows.add(Observation( at: start, @@ -541,7 +575,7 @@ class HelioStrapAdapter extends BandAdapter { vendorKey: 'workout_max_hr', value: w.maxHr, unit: 'bpm', - attribution: kHelioStrapAttribution, + attribution: attribution, )); workoutRows.add(Observation( at: start, @@ -549,7 +583,7 @@ class HelioStrapAdapter extends BandAdapter { vendorKey: 'workout_min_hr', value: w.minHr, unit: 'bpm', - attribution: kHelioStrapAttribution, + attribution: attribution, )); } if (workoutRows.isNotEmpty) yield VendorScalars(workoutRows); @@ -569,11 +603,11 @@ class HelioStrapAdapter extends BandAdapter { final sessions = wholeSessions(parseHuami2021Sleep(sleepFetch.bytes), since.millisecondsSinceEpoch); for (final session in sessions) { - _emitSleepSession(session, epochs, stageRows); + _emitSleepSession(session, epochs, stageRows, attribution); } - stageRows.addAll(nightMeans(sessions, night)); + stageRows.addAll(nightMeans(sessions, night, attribution: attribution)); if (epochs.isNotEmpty) { - yield VendorHypnogram('helio_strap', epochs, wholeNights: true); + yield VendorHypnogram(entry.id, epochs, wholeNights: true); } if (stageRows.isNotEmpty) yield VendorScalars(stageRows); if (sleepFetch.raw.isNotEmpty) { @@ -592,6 +626,7 @@ class HelioStrapAdapter extends BandAdapter { Huami2021SleepSession session, List epochs, List rows, + String attribution, ) { if (session.isNap) { final asleep = session.stages @@ -604,7 +639,7 @@ class HelioStrapAdapter extends BandAdapter { vendorKey: 'nap_min', value: asleep, unit: 'min', - attribution: kHelioStrapAttribution, + attribution: attribution, )); } return; @@ -630,7 +665,7 @@ class HelioStrapAdapter extends BandAdapter { vendorKey: 'sleep_${entry.key}_min', value: entry.value, unit: 'min', - attribution: kHelioStrapAttribution, + attribution: attribution, )); } } @@ -653,8 +688,9 @@ class HelioStrapAdapter extends BandAdapter { @visibleForTesting static List nightMeans( List sessions, - Map> samples, - ) { + Map> samples, { + String attribution = kHelioStrapAttribution, + }) { final rows = []; for (final session in sessions) { if (session.isNap) continue; @@ -668,7 +704,7 @@ class HelioStrapAdapter extends BandAdapter { ]; if (inNight.isEmpty) continue; rows.add(_obs(_wakeDate(end), _mean(inNight), - unit: _nightUnit[key], vendorKey: key)); + unit: _nightUnit[key], vendorKey: key, attribution: attribution)); } } return rows; @@ -708,7 +744,10 @@ class HelioStrapAdapter extends BandAdapter { v.fold(0, (s, x) => s + x) / v.length; static Observation _obs(DateTime day, num value, - {String? unit, String? key, String? vendorKey}) => + {String? unit, + String? key, + String? vendorKey, + String attribution = kHelioStrapAttribution}) => Observation( at: day, sourceKind: ObservationSource.vendor, @@ -716,7 +755,7 @@ class HelioStrapAdapter extends BandAdapter { vendorKey: vendorKey, value: value, unit: unit, - attribution: kHelioStrapAttribution, + attribution: attribution, ); } @@ -846,9 +885,22 @@ const Map kHelioStrapSignals = { InputSignal.vendorScalars: Duration.zero, }; +/// The signals Mi Band 7 supplies. Mirrored in `kAdapterSignals`. No skin +/// temperature (no sensor), and no HRV: its HRV records are banked raw, +/// not decoded ([HelioStrapAdapter._decodesHrv]). +const Map kMiBand7Signals = { + InputSignal.hrSparse: Duration(minutes: 1), + InputSignal.steps: Duration(minutes: 1), + InputSignal.deviceStages: Duration.zero, + InputSignal.vendorScalars: Duration.zero, +}; + /// The single instance. Holds no per-strap state. final HelioStrapAdapter kHelioStrapAdapter = HelioStrapAdapter(); +/// The Mi Band 7 instance: the same adapter driving [kMiBand7]. +final HelioStrapAdapter kMiBand7Adapter = HelioStrapAdapter(entry: kMiBand7); + /// 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 diff --git a/lib/ble/helio_strap_link.dart b/lib/ble/helio_strap_link.dart index 24e03226b..4cdd10504 100644 --- a/lib/ble/helio_strap_link.dart +++ b/lib/ble/helio_strap_link.dart @@ -74,13 +74,25 @@ Future _awaitAdapterOn() async { /// 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 { + BluetoothDevice device, String raw) => + _pairZeppOsWithTypedKey(device, raw, kHelioStrap); + +/// [pairHelioStrapWithTypedKey] for a Xiaomi / Mi Smart Band 7: the same +/// handshake and the same verify-then-store rules, under its own key slot +/// and its own `device` row. +Future pairMiBand7WithTypedKey( + BluetoothDevice device, String raw) => + _pairZeppOsWithTypedKey(device, raw, kMiBand7); + +Future _pairZeppOsWithTypedKey( + BluetoothDevice device, String raw, BandEntry entry) 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.'; + return 'That is not a valid 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)]); + final tag = '[${entry.id} pair]'; // A pairing begun DURING a reset would capture the already-raised // generation and pass every check once that reset ends. @@ -90,15 +102,16 @@ Future pairHelioStrapWithTypedKey( // 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 link = HelioStrapLink._of(entry); + final forgets = link._forgets; + // ADMISSION, under [_pairingLock]: a second device of the family 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); + final priorRow = await link.pairedRow(); + return _anotherStrap(priorRow, device.remoteId.str, entry); }); if (refused != null) return refused; @@ -118,15 +131,15 @@ Future pairHelioStrapWithTypedKey( await device.connect(timeout: const Duration(seconds: 20)); final services = await device.discoverServices(); link = GattBandLink( - entry: kHelioStrap, + entry: entry, services: services, - onLog: (m) => debugPrint('[helio_strap pair] $m'), + onLog: (m) => debugPrint('$tag $m'), ); final missing = - link.missingCharacteristics(kHelioStrap.requiredCharacteristics); + link.missingCharacteristics(entry.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 ' + return 'This device is missing something this app needs — it may ' + 'not be a ${entry.label}, or its firmware answered differently ' 'than expected.'; } @@ -134,9 +147,9 @@ Future pairHelioStrapWithTypedKey( timeout: const Duration(seconds: 10)); if (result is HelioHandshakeFailed) { return switch (result.reason) { - 'wrong_key' => 'The strap rejected this key. Double-check it ' + 'wrong_key' => 'The device rejected this key. Double-check it ' 'and try again.', - 'timeout' => 'The strap didn’t answer. Make sure it’s close by ' + 'timeout' => 'The device didn’t answer. Make sure it’s close by ' 'and try again.', _ => 'Pairing failed (${result.reason}).', }; @@ -147,6 +160,7 @@ Future pairHelioStrapWithTypedKey( hex: hex, resetGen: resetGen, forgets: forgets, + entry: entry, ); } catch (e) { return 'Could not connect: $e'; @@ -204,10 +218,12 @@ class _AsyncMutex { /// 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) => +String? _anotherStrap(Map? priorRow, String remoteId, + [BandEntry entry = kHelioStrap]) => priorRow != null && priorRow['remote_id'] != remoteId - ? 'Another Helio Strap is already paired. Forget it on its device ' - 'page first, then pair this one.' + ? 'Another ${entry.id == kHelioStrap.id ? 'Helio Strap' : entry.label} ' + '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 @@ -224,13 +240,15 @@ Future persistHelioPairing({ required String hex, required int resetGen, int? forgets, + BandEntry entry = kHelioStrap, }) => _pairingLock.run(() => _persistHeld( deviceId: deviceId, remoteId: remoteId, hex: hex, resetGen: resetGen, - forgets: forgets)); + forgets: forgets, + entry: entry)); Future _persistHeld({ required String? deviceId, @@ -238,13 +256,16 @@ Future _persistHeld({ required String hex, required int resetGen, required int? forgets, + required BandEntry entry, }) async { - // Interrupted: a reset ran ([ResetGate]), or the strap was forgotten from - // its device page ([HelioStrapLink.forgetStrap] bumps the counter first). + final keySlot = zeppOsKeySlot(entry); + final link = HelioStrapLink._of(entry); + // Interrupted: a reset ran ([ResetGate]), or the device was forgotten from + // its device page ([HelioStrapLink.forget] 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); + (forgets != null && link._forgets != forgets); String stopText() => ResetGate.changedSince(resetGen) ? kHelioPairResetText : kHelioPairForgottenText; @@ -252,7 +273,7 @@ Future _persistHeld({ Future dropKey() async { try { await _pairSecure.delete( - key: kHelioStrapSecureStorageKey, + key: keySlot, iOptions: kHelioStrapIosKeyOptions, mOptions: kHelioStrapMacosKeyOptions, ); @@ -263,19 +284,20 @@ Future _persistHeld({ } if (stopped()) return stopText(); - final priorRow = await HelioStrapLink.pairedHelioStrapRow(); - final another = _anotherStrap(priorRow, remoteId); + final priorRow = await link.pairedRow(); + final another = _anotherStrap(priorRow, remoteId, entry); if (another != null) return another; final rnd = Random.secure(); + final idPrefix = entry.id == kHelioStrap.id ? 'helio' : entry.id; final id = (priorRow?['id'] as String?) ?? deviceId ?? - 'helio-${_hex(List.generate(4, (_) => rnd.nextInt(256)))}'; + '$idPrefix-${_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, + key: keySlot, iOptions: kHelioStrapIosKeyOptions, mOptions: kHelioStrapMacosKeyOptions, ); @@ -284,7 +306,7 @@ Future _persistHeld({ } try { await _pairSecure.write( - key: kHelioStrapSecureStorageKey, + key: keySlot, value: hex, iOptions: kHelioStrapIosKeyOptions, mOptions: kHelioStrapMacosKeyOptions, @@ -298,9 +320,9 @@ Future _persistHeld({ try { await LocalDb.upsertDevice( id: id, - adapterId: kHelioStrap.id, + adapterId: entry.id, remoteId: remoteId, - label: kHelioStrap.label, + label: entry.label, ); } catch (e) { // The row never landed. Restore what the keychain held before this @@ -312,7 +334,7 @@ Future _persistHeld({ } else { try { await _pairSecure.write( - key: kHelioStrapSecureStorageKey, + key: keySlot, value: priorHex, iOptions: kHelioStrapIosKeyOptions, mOptions: kHelioStrapMacosKeyOptions, @@ -338,30 +360,48 @@ Future _persistHeld({ 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`). +/// The live link to one paired device of this protocol family. One instance +/// per device family ([instance] for the Helio Strap, [miBand7] for the +/// Xiaomi / Mi Smart Band 7); a second concurrent device of the same family +/// is not a thing anyone asked for (same call as `ColmiLink`). class HelioStrapLink { - HelioStrapLink._(); - static final HelioStrapLink instance = HelioStrapLink._(); + HelioStrapLink._(this.entry); + static final HelioStrapLink instance = HelioStrapLink._(kHelioStrap); + static final HelioStrapLink miBand7 = HelioStrapLink._(kMiBand7); + + /// The family this link drives. + final BandEntry entry; + + /// The link driving [e]. + static HelioStrapLink _of(BandEntry e) => + e.id == kMiBand7.id ? miBand7 : instance; + + String get _tag => '[${entry.id}]'; /// The `device` row for the paired strap, or null. static Future?> pairedHelioStrapRow() => - pairedRowOf(kHelioStrap.id); + instance.pairedRow(); - /// Forget a paired strap: stop any live session, drop its `device` row. + /// The `device` row for this link's paired device, or null. + Future?> pairedRow() => pairedRowOf(entry.id); + + /// Forget a paired strap — [forget] on the Helio link. + static Future forgetStrap(String id) => instance.forget(id); + + /// Forget a paired device: 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 { + /// storage under this family's slot (`zeppOsKeySlot` in + /// `helio_strap.dart`); dropping the `device` row is the whole story for + /// this link, same as `ColmiLink`. + Future forget(String id) async { if (id == LocalDb.kPrimaryDeviceId) { - debugPrint('[helio_strap] refusing to forget the primary band from here.'); + debugPrint('$_tag 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(); + _forgets++; + if (_deviceId == id) await 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. @@ -369,7 +409,7 @@ class HelioStrapLink { return true; } - static Future _forgetHeld(String id) async { + 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 @@ -378,7 +418,7 @@ class HelioStrapLink { // forever. Same cleanup `OuraLink.forgetRing` does for its own key. try { await _pairSecure.delete( - key: kHelioStrapSecureStorageKey, + key: zeppOsKeySlot(entry), iOptions: kHelioStrapIosKeyOptions, mOptions: kHelioStrapMacosKeyOptions, ); @@ -456,13 +496,13 @@ class HelioStrapLink { final resetGen = ResetGate.generation; final forgets = _forgets; lastSyncFailed = false; - final row = await pairedHelioStrapRow(); + final row = await pairedRow(); 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 ' + debugPrint('$_tag refusing to sync: the strap row claims the ' 'primary device id — re-pair it with a minted id.'); return false; } @@ -508,15 +548,15 @@ class HelioStrapLink { return false; } final link = GattBandLink( - entry: kHelioStrap, + entry: entry, services: services, - onLog: (m) => debugPrint('[helio_strap] $m'), + onLog: (m) => debugPrint('$_tag $m'), ); _link = link; final missing = link - .missingCharacteristics(kHelioStrap.requiredCharacteristics); + .missingCharacteristics(entry.requiredCharacteristics); if (missing.isNotEmpty) { - debugPrint('[helio_strap] ${kHelioStrap.label}: missing required ' + debugPrint('$_tag ${entry.label}: missing required ' 'characteristic(s) ' '${missing.map((u) => u.substring(0, 8)).join(", ")}.'); return false; @@ -525,9 +565,9 @@ class HelioStrapLink { _anchorSec = anchor; final h = host = BandHost( resetGeneration: resetGen, - adapter: HelioStrapAdapter(nowSeconds: () => anchor), + adapter: HelioStrapAdapter(entry: entry, nowSeconds: () => anchor), deviceId: deviceId, - onLog: (m) => debugPrint('[helio_strap] $m'), + onLog: (m) => debugPrint('$_tag $m'), onNote: _handleNote, buildArchive: _buildArchiveRow, ); @@ -548,7 +588,7 @@ class HelioStrapLink { return !lastSyncFailed && !host.sessionFailed; }); } catch (e) { - debugPrint('[helio_strap] sync failed: $e'); + debugPrint('$_tag sync failed: $e'); return false; } } @@ -607,7 +647,7 @@ class HelioStrapLink { // 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')}', + reason: '${entry.id}_0x${bytes[0].toRadixString(16).padLeft(2, '0')}', ); } @@ -636,13 +676,14 @@ class HelioStrapLink { _anchorSec = now(); final host = BandHost( adapter: HelioStrapAdapter( + entry: entry, nowSeconds: now, authKeyReader: authKeyReader, firstReplyTimeout: firstReplyTimeout, quietTimeout: quietTimeout, ), deviceId: deviceId, - onLog: (m) => debugPrint('[helio_strap] $m'), + onLog: (m) => debugPrint('$_tag $m'), onNote: _handleNote, buildArchive: _buildArchiveRow, nowSeconds: now, diff --git a/lib/ble/hrs_link.dart b/lib/ble/hrs_link.dart index 28a006c3b..3af347edd 100644 --- a/lib/ble/hrs_link.dart +++ b/lib/ble/hrs_link.dart @@ -989,6 +989,10 @@ class HrsLink { await HelioStrapLink.forgetStrap(id); return; } + if (row?['adapter_id'] == kMiBand7.id) { + await HelioStrapLink.miBand7.forget(id); + return; + } final session = SessionLink.forId(row?['adapter_id'] as String?); if (session != null) { await session.forget(id); diff --git a/lib/state/app_state.dart b/lib/state/app_state.dart index a1f1b86cb..c53de5579 100644 --- a/lib/state/app_state.dart +++ b/lib/state/app_state.dart @@ -1885,6 +1885,7 @@ class AppState extends ChangeNotifier { await bounded('garmin', GarminLink.instance.stop); await bounded('miband234', MiBand234Link.instance.stop); await bounded('helio_strap', HelioStrapLink.instance.stop); + await bounded('zeppos_l66', HelioStrapLink.miBand7.stop); await bounded('pebble', PebbleLink.instance.stop); await bounded('coros', CorosLink.instance.stop); for (final link in SessionLink.all) { diff --git a/lib/sync/background_sync.dart b/lib/sync/background_sync.dart index c2a9db8f0..e9b7b5a6c 100644 --- a/lib/sync/background_sync.dart +++ b/lib/sync/background_sync.dart @@ -487,6 +487,11 @@ Future syncPairedSensors() async { } catch (e) { debugPrint('[bgsync] helio_strap sync skipped: $e'); } + try { + await HelioStrapLink.miBand7.sync(); + } catch (e) { + debugPrint('[bgsync] zeppos_l66 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/pairing/device_picker.dart b/lib/ui2/pairing/device_picker.dart index abc5fc775..d001f732b 100644 --- a/lib/ui2/pairing/device_picker.dart +++ b/lib/ui2/pairing/device_picker.dart @@ -47,7 +47,8 @@ import '../../ble/ble_state.dart' classifyBleBlocker, kMaxConcurrentSecondaryLinks; import '../../ble/hrs_link.dart'; -import '../../ble/helio_strap_link.dart' show pairHelioStrapWithTypedKey; +import '../../ble/helio_strap_link.dart' + show pairHelioStrapWithTypedKey, pairMiBand7WithTypedKey; import '../../ble/oura_link.dart' show pairOuraRingWithTypedKey; import '../../data/db.dart' show LocalDb; import '../../l10n/app_localizations.dart'; @@ -430,6 +431,7 @@ class _DevicePickerScreenState extends State onPickedWithKey: switch (sensor.entry.id) { final id when id == kOura.id => pairOuraRingWithTypedKey, final id when id == kHelioStrap.id => pairHelioStrapWithTypedKey, + final id when id == kMiBand7.id => pairMiBand7WithTypedKey, _ => null, }, ), diff --git a/lib/ui2/profile/devices.dart b/lib/ui2/profile/devices.dart index 356f02dce..3b1182a61 100644 --- a/lib/ui2/profile/devices.dart +++ b/lib/ui2/profile/devices.dart @@ -52,6 +52,7 @@ import '../../ble/adapters/_registry.dart' kCoros, kGarmin, kHelioStrap, + kMiBand7, kMiBand234, kMiScale2, kMiScaleComposition, @@ -1302,6 +1303,16 @@ final List<({BandEntry entry, String blurb, Future Function(BluetoothDe // field (wired via `onPickedWithKey` in the pairing screens) applies. pick: null, ), + ( + entry: kMiBand7, + blurb: 'A Xiaomi Smart Band 7 (Mi Smart Band 7). First pairing still has ' + 'to go through Zepp Life, which is where the band\'s key comes from. ' + 'Paste that key below to pair it here instead. Syncs heart rate, ' + 'steps, sleep and workouts; the band\'s own stress and SpO2 figures ' + 'are labelled as Xiaomi\'s. HRV is not read yet. Experimental.', + // Null for the same reason as the Helio Strap: typed key only. + pick: null, + ), ( entry: kPebble, blurb: 'Pebble 2 or Pebble 2 SE only — older Pebbles need Bluetooth ' @@ -2147,6 +2158,7 @@ class _DeviceDetailState extends State { 'pebble' => () => _syncPebble(c), 'colmi' => () => _syncColmiRing(c), 'helio_strap' => () => _syncSensor(c, HelioStrapLink.instance.sync), + 'zeppos_l66' => () => _syncSensor(c, HelioStrapLink.miBand7.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 6ada972e3..be944a0e7 100644 --- a/lib/ui2/profile/pair_sensor.dart +++ b/lib/ui2/profile/pair_sensor.dart @@ -63,7 +63,8 @@ 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/helio_strap_link.dart' + show pairHelioStrapWithTypedKey, pairMiBand7WithTypedKey; import '../../ble/oura_link.dart' show pairOuraRingWithTypedKey; import '../../data/db.dart' show LocalDb; import '../../l10n/app_localizations.dart'; @@ -481,6 +482,7 @@ class _PairSensorScreenState extends State onPickedWithKey: switch (band.id) { final id when id == kOura.id => pairOuraRingWithTypedKey, final id when id == kHelioStrap.id => pairHelioStrapWithTypedKey, + final id when id == kMiBand7.id => pairMiBand7WithTypedKey, _ => null, }, ), diff --git a/test/adapter_signals_registry_test.dart b/test/adapter_signals_registry_test.dart index 60e8a0a79..c75dd43b9 100644 --- a/test/adapter_signals_registry_test.dart +++ b/test/adapter_signals_registry_test.dart @@ -43,6 +43,7 @@ void main() { 'pebble': kPebbleAdapter.signals, 'colmi': kColmiAdapter.signals, 'helio_strap': kHelioStrapAdapter.signals, + 'zeppos_l66': kMiBand7Adapter.signals, 'thermometer': ThermometerAdapter().signals, 'miscale_bc': MiScaleAdapter(kMiScaleComposition).signals, 'miscale2': MiScaleAdapter(kMiScale2).signals, diff --git a/test/adapters/miband7_test.dart b/test/adapters/miband7_test.dart new file mode 100644 index 000000000..b14c66907 --- /dev/null +++ b/test/adapters/miband7_test.dart @@ -0,0 +1,254 @@ +// Xiaomi / Mi Smart Band 7 (`kMiBand7`, codename L66) through the SAME +// adapter as the Helio Strap. A fake band runs its own real B-163 ECDH + AES +// side of the handshake, then answers two fetch rounds with data (activity, +// HRV) and every other type with "no data". The same script runs against +// both entries, so each assertion that differs between them is a difference +// the entry makes, not the fixture. + +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 _aesDecrypt(Uint8List key, Uint8List data) { + final c = ECBBlockCipher(AESEngine())..init(false, KeyParameter(key)); + final out = Uint8List(data.length); + for (var i = 0; i < data.length; i += 16) { + c.processBlock(data, i, out, i); + } + return out; +} + +final DateTime _now = DateTime(2026, 10, 4, 12, 0); +final int _nowSec = _now.millisecondsSinceEpoch ~/ 1000; +final DateTime _roundStart = DateTime(_now.year, _now.month, _now.day, 6, 0); + +/// One 1-minute activity record: steps @ +2, hr @ +3. +List _activity(int steps, int hr) => [0, 0, steps & 0xff, hr & 0xff, 0, 0, 0, 0]; + +final List _activityBytes = [..._activity(20, 65), ..._activity(10, 0xff)]; + +/// One HRV record (type 0x49): absolute `sec` u32 LE @ +0, value u8 @ +5. +final int _hrvSec = _nowSec - 3600; +final List _hrvBytes = [ + _hrvSec & 0xff, (_hrvSec >> 8) & 0xff, (_hrvSec >> 16) & 0xff, + (_hrvSec >> 24) & 0xff, 0, 42, +]; + +Future> _run(BandEntry entry) async { + final key = Uint8List.fromList(List.generate(16, (i) => i + 1)); + final link = ReplayBandLink(); + final adapter = HelioStrapAdapter( + entry: entry, + nowSeconds: () => _nowSec, + authKeyReader: () async => key, + firstReplyTimeout: const Duration(milliseconds: 200), + quietTimeout: const Duration(milliseconds: 30), + ); + + 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 bandDecoder = Huami2021Decoder(); + final bandEncoder = Huami2021Encoder(); + Uint8List? sessionKey; + + // The data each round with data serves, by type, and the count its start + // reply announces: records for activity, BYTES for every other type + // (`huami2021FetchCountMatches`). + final rounds = , int)>{ + kHuami2021TypeActivity: (_activityBytes, _activityBytes.length ~/ 8), + kHuami2021TypeHrv: (_hrvBytes, _hrvBytes.length), + }; + int? currentType; + + void feedAuth(List body) { + for (final chunk in bandEncoder.encode(kHuami2021AuthEndpoint, body)) { + link.feed(kHuami2021ChunkNotifyChar, chunk, atSec: _nowSec); + } + } + + 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 = bandDecoder.feed(value, sessionKey: null); + if (frame == null || frame.endpoint != kHuami2021AuthEndpoint) continue; + final p = frame.payload; + if (p.isNotEmpty && p[0] == 0x04) { + final shared = + sharedSecret(deviceKeypair.privateKey, p.sublist(4, 4 + 48)); + sessionKey = Uint8List(16); + for (var i = 0; i < 16; i++) { + sessionKey![i] = shared[i + 8] ^ key[i]; + } + feedAuth([0x10, 0x04, 0x01, ...remoteRandom, ...deviceKeypair.publicKey]); + } else if (p.isNotEmpty && p[0] == 0x05) { + expect(_aesDecrypt(key, p.sublist(1, 17)), remoteRandom); + expect(_aesDecrypt(sessionKey!, p.sublist(17, 33)), remoteRandom); + feedAuth([0x10, 0x05, 0x01]); + } + continue; + } + if (char != kHuami2021FetchControlChar || value.isEmpty) continue; + if (value[0] == 0x01) { + currentType = value[1]; + final round = rounds[currentType]; + final n = round?.$2 ?? 0; + final rs = round == null ? DateTime(1970) : _roundStart; + link.feed( + kHuami2021FetchControlChar, + [ + 0x10, 0x01, 0x01, + n & 0xff, (n >> 8) & 0xff, (n >> 16) & 0xff, (n >> 24) & 0xff, + rs.year & 0xff, (rs.year >> 8) & 0xff, rs.month, rs.day, + rs.hour, rs.minute, rs.second, + ], + atSec: _nowSec); + } else if (value.length == 1 && value[0] == 0x02) { + final bytes = rounds[currentType]?.$1 ?? const []; + link.feed(kHuami2021FetchDataChar, [0, ...bytes], atSec: _nowSec); + link.feed(kHuami2021FetchControlChar, const [0x10, 0x02, 0x01], + atSec: _nowSec); + } + } + } + }()); + + await done.future.timeout(const Duration(seconds: 20)); + await sub.cancel(); + await link.close(); + return events; +} + +List _samples(List e) => + [for (final b in e.whereType()) ...b.samples]; +List _rows(List e) => + [for (final v in e.whereType()) ...v.rows]; +List _raw(List e) => + [for (final b in e.whereType()) ...?b.raw]; + +bool _containsSequence(List haystack, List needle) { + for (var i = 0; i + needle.length <= haystack.length; i++) { + var ok = true; + for (var j = 0; j < needle.length && ok; j++) { + ok = haystack[i + j] == needle[j]; + } + if (ok) return true; + } + return false; +} + +void main() { + group('registry', () { + test('Mi Band 7 is its own codename-keyed entry on the Zepp OS channels', () { + expect(kMiBand7.id, 'zeppos_l66'); + expect(kMiBand7.service, kHelioStrap.service); + expect(kMiBand7.requiredCharacteristics, + kHelioStrap.requiredCharacteristics); + expect(kBandRegistry, contains(kMiBand7)); + expect(kAskPickerSensors, contains(kMiBand7)); + }); + + test('matches every name the band advertises, and nothing else', () { + final m = kMiBand7.nameMatcher!; + for (final name in [ + 'xiaomi smart band 7', + 'mi smart band 7', + 'l66', + 'xiaomi smart band 7 a1b2', + 'xiaomi smart band 7 0f3c', + ]) { + expect(m(name), isTrue, reason: name); + } + for (final name in [ + 'xiaomi smart band 7 pro', + 'xiaomi smart band 8', + 'mi band 3', + 'amazfit helio strap', + 'xiaomi smart band 7 abcde', + ]) { + expect(m(name), isFalse, reason: name); + } + }); + + test('no earlier registry entry claims a Mi Band 7 name', () { + for (final name in ['xiaomi smart band 7', 'mi smart band 7', 'l66']) { + final first = kBandRegistry + .firstWhere((e) => e.nameMatcher?.call(name) ?? false); + expect(first, kMiBand7, reason: name); + } + }); + + test('declares only HR, steps, stages and vendor scalars, in sync with ' + 'kAdapterSignals', () { + expect(kMiBand7Adapter.signals.keys.toSet(), { + InputSignal.hrSparse, + InputSignal.steps, + InputSignal.deviceStages, + InputSignal.vendorScalars, + }); + expect(kAdapterSignals['zeppos_l66'], kMiBand7Adapter.signals); + expect(kMiBand7Adapter.signals.containsKey(InputSignal.deviceHrv), isFalse); + expect(kMiBand7Adapter.signals.containsKey(InputSignal.skinTempC), isFalse); + }); + + test('each family has its own key slot; Helio keeps its original one', () { + expect(zeppOsKeySlot(kHelioStrap), kHelioStrapSecureStorageKey); + expect(zeppOsKeySlot(kMiBand7), isNot(kHelioStrapSecureStorageKey)); + }); + }); + + group('session', () { + test('Mi Band 7: real handshake, HR and steps decoded, Xiaomi-attributed', + () async { + final events = await _run(kMiBand7); + expect(events.whereType(), isEmpty); + + final hr = _samples(events).where((s) => s.hr != null).toList(); + expect(hr, hasLength(1)); + expect(hr.single.hr, 65); + expect(hr.single.tsEpoch, _roundStart.millisecondsSinceEpoch ~/ 1000); + + final steps = _rows(events).singleWhere((o) => o.key == 'steps'); + expect(steps.value, 30); + expect(steps.attribution, 'Xiaomi'); + }); + + test('Mi Band 7: HRV bytes are banked raw and never decoded into a value', + () async { + final events = await _run(kMiBand7); + expect(_samples(events).where((s) => s.deviceRmssdMs != null), isEmpty, + reason: 'unit unconfirmed without hardware: no number labelled ms'); + expect(_rows(events).where((o) => (o.vendorKey ?? '').startsWith('hrv')), + isEmpty); + expect(_raw(events).any((f) => _containsSequence(f, _hrvBytes)), isTrue, + reason: 'the HRV round is kept for a later re-decode'); + }); + + test('Helio Strap: the same script still decodes HRV and stays ' + 'Amazfit-attributed', () async { + final events = await _run(kHelioStrap); + final rmssd = _samples(events).where((s) => s.deviceRmssdMs != null); + expect(rmssd, hasLength(1)); + expect(rmssd.single.deviceRmssdMs, 42); + expect(_rows(events).singleWhere((o) => o.key == 'steps').attribution, + kHelioStrapAttribution); + }); + }); +} diff --git a/test/band_registry_test.dart b/test/band_registry_test.dart index f874e072b..7f91fe147 100644 --- a/test/band_registry_test.dart +++ b/test/band_registry_test.dart @@ -23,6 +23,7 @@ void main() { 'ultrahuman', 'miband234', 'helio_strap', + 'zeppos_l66', 'pebble', 'colmi', 'garmin', diff --git a/test/miband7_link_test.dart b/test/miband7_link_test.dart new file mode 100644 index 000000000..680572716 --- /dev/null +++ b/test/miband7_link_test.dart @@ -0,0 +1,149 @@ +// The Mi Band 7 HOST (`HelioStrapLink.miBand7`): scripted band in, database +// rows out, through the real `BandHost` and real sqlite. Pins where its data +// LANDS and that it never touches a paired Helio Strap's rows. +// `test/adapters/miband7_test.dart` pins what is decoded. + +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:sqflite_common_ffi/sqflite_ffi.dart'; + +const String _bandId = 'zeppos_l66-0a1b2c3d'; +const String _helioId = 'helio-11223344'; +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)); +final DateTime _roundStart = DateTime(_now.year, _now.month, _now.day, 6, 0); +const int _steps1 = 20, _hr1 = 65, _steps2 = 10; + +List _record(int steps, int hr) => [0, 0, steps & 0xff, hr & 0xff, 0, 0, 0, 0]; + +/// Real handshake, one activity round with data, every other type "no data". +List<(String, List)> Function(int, String, List) _bandScript() { + final kp = keypairFrom( + Uint8List.fromList(List.generate(24, (i) => (i * 7 + 3) % 256))); + final remoteRandom = + Uint8List.fromList(List.generate(16, (i) => (i * 11 + 5) % 256)); + final decoder = Huami2021Decoder(); + final encoder = Huami2021Encoder(); + + List<(String, List)> auth(List body) => [ + for (final c in encoder.encode(kHuami2021AuthEndpoint, body)) + (kHuami2021ChunkNotifyChar, c), + ]; + + return (index, char, value) { + if (char == kHuami2021ChunkWriteChar) { + final frame = decoder.feed(value, sessionKey: null); + if (frame == null || frame.endpoint != kHuami2021AuthEndpoint) return []; + final payload = frame.payload; + if (payload.isNotEmpty && payload[0] == 0x04) { + return auth([0x10, 0x04, 0x01, ...remoteRandom, ...kp.publicKey]); + } + if (payload.isNotEmpty && payload[0] == 0x05) return auth([0x10, 0x05, 0x01]); + return []; + } + if (char != kHuami2021FetchControlChar || value.isEmpty) return []; + if (value[0] == 0x01) { + final hasData = value[1] == kHuami2021TypeActivity; + final n = hasData ? 2 : 0; + final rs = hasData ? _roundStart : DateTime(1970); + return [ + ( + kHuami2021FetchControlChar, + [ + 0x10, 0x01, 0x01, n, 0, 0, 0, + rs.year & 0xff, (rs.year >> 8) & 0xff, rs.month, rs.day, + rs.hour, rs.minute, rs.second, + ] + ), + ]; + } + if (value.length == 1 && value[0] == 0x02) { + return [ + (kHuami2021FetchDataChar, [0, ..._record(_steps1, _hr1)]), + (kHuami2021FetchDataChar, [1, ..._record(_steps2, 0xff)]), + (kHuami2021FetchControlChar, const [0x10, 0x02, 0x01]), + ]; + } + return []; + }; +} + +void main() { + setUpAll(() { + sqfliteFfiInit(); + databaseFactory = databaseFactoryFfi; + }); + + setUp(() async { + await LocalDb.close(); + LocalDb.dbName = 'miband7_link_test.db'; + final dir = await databaseFactory.getDatabasesPath(); + await databaseFactory.deleteDatabase(p.join(dir, LocalDb.dbName)); + }); + + tearDown(() async => LocalDb.close()); + + Future sync() => HelioStrapLink.miBand7.ingestForTest( + _bandId, + _bandScript(), + nowSeconds: _nowSec, + authKeyReader: () async => _authKey, + ); + + test('the Mi Band 7 link drives the Mi Band 7 entry', () { + expect(HelioStrapLink.miBand7.entry, kMiBand7); + expect(HelioStrapLink.instance.entry, kHelioStrap); + }); + + test('HR lands in decoded_onehz under the band\'s own device id', () async { + await sync(); + final db = await LocalDb.instance; + final rows = await db.query('decoded_onehz', orderBy: 'rec_ts'); + expect(rows.map((r) => (r['rec_ts'], r['hr'], r['device_id'])), [ + (_roundStart.millisecondsSinceEpoch ~/ 1000, _hr1, _bandId), + ]); + }); + + test('steps lands as a vendor observation attributed to Xiaomi', () 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'], 'Xiaomi'); + }); + + test('every raw reply is banked under the band\'s own archive reason', + () async { + await sync(); + final db = await LocalDb.instance; + final reasons = (await db.query(LocalDb.rawArchiveView, columns: ['reason'])) + .map((r) => r['reason'] as String) + .toSet(); + expect(reasons, isNotEmpty); + expect(reasons.every((r) => r.startsWith('zeppos_l66_0x')), isTrue, + reason: '$reasons'); + }); + + test('forgetting the band leaves a paired Helio Strap alone', () async { + await LocalDb.upsertDevice( + id: _bandId, adapterId: kMiBand7.id, remoteId: 'AA', label: kMiBand7.label); + await LocalDb.upsertDevice( + id: _helioId, adapterId: kHelioStrap.id, remoteId: 'BB', label: kHelioStrap.label); + expect((await HelioStrapLink.miBand7.pairedRow())?['id'], _bandId); + expect((await HelioStrapLink.pairedHelioStrapRow())?['id'], _helioId); + + expect(await HelioStrapLink.miBand7.forget(_bandId), isTrue); + + expect(await HelioStrapLink.miBand7.pairedRow(), isNull); + expect((await HelioStrapLink.pairedHelioStrapRow())?['id'], _helioId); + }); +} diff --git a/test/pairing_device_role_test.dart b/test/pairing_device_role_test.dart index 849b5e20d..a75812365 100644 --- a/test/pairing_device_role_test.dart +++ b/test/pairing_device_role_test.dart @@ -28,7 +28,7 @@ void main() { }; expect(bands, { 'gen4', 'gen5', 'oura', 'coros', 'ultrahuman', 'miband234', 'helio_strap', - 'pebble', 'colmi', 'garmin', + 'zeppos_l66', 'pebble', 'colmi', 'garmin', }); }); diff --git a/test/wearable_platform_test.dart b/test/wearable_platform_test.dart index be96d1515..21407488c 100644 --- a/test/wearable_platform_test.dart +++ b/test/wearable_platform_test.dart @@ -55,6 +55,7 @@ void main() { 'pebble': DeviceCategory.wearable, 'colmi': DeviceCategory.wearable, 'helio_strap': DeviceCategory.wearable, + 'zeppos_l66': DeviceCategory.wearable, 'garmin': DeviceCategory.wearable, 'thermometer': DeviceCategory.healthMeasurement, 'miscale_bc': DeviceCategory.healthMeasurement, From 22a00b59dd3b88dd442b23bb66f1f347a2dd5f79 Mon Sep 17 00:00:00 2001 From: Mohammad Abdul Sahil <127765312+abdulsaheel@users.noreply.github.com> Date: Mon, 23 Nov 2026 01:08:24 +0530 Subject: [PATCH 02/22] mi band 7: derived numbers off its minute hr hr cadence 60s and method family hr_1min, so the declaration-built column serves it like the helio: strain, resting hr, an rhr-only readiness estimate, its own sleep window and steps. hrv, respiration, stress, irregular rhythm and skin temp stay unavailable with a reason; it has no skin temp sensor and its hrv isn't decoded. synthetic 4-day test through the real engine, plus it joins the no-leak sweep (flag off leaves nothing), the columned-entries control and the reset-steps guard lists (www.mi.com, same reviewed host as the other xiaomi rows). --- lib/compute/inputs/garmin_inputs.dart | 7 + .../support/pairing_reset_fixtures.dart | 2 + test/slot_comparison_test.dart | 8 +- test/synthetic_miband7_day_test.dart | 146 ++++++++++++++++++ test/wearable_toggle_no_leak_test.dart | 1 + 5 files changed, 161 insertions(+), 3 deletions(-) create mode 100644 test/synthetic_miband7_day_test.dart diff --git a/lib/compute/inputs/garmin_inputs.dart b/lib/compute/inputs/garmin_inputs.dart index e7629af1f..917ceb29e 100644 --- a/lib/compute/inputs/garmin_inputs.dart +++ b/lib/compute/inputs/garmin_inputs.dart @@ -33,6 +33,11 @@ const String kGarminFamily = 'garmin'; /// served by the declaration-built [sparseColumn]. const String kHelioFamily = 'helio_strap'; +/// Xiaomi / Mi Smart Band 7 (codename L66), on the Helio engine. Served by +/// [sparseColumn] the same way; its HRV is never decoded, so it is not a +/// device-RMSSD family. +const String kMiBand7Family = 'zeppos_l66'; + /// 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. @@ -48,6 +53,7 @@ const int kOneHzRunGapSec = 3; const Map kHrCadenceSec = { kGarminFamily: 60, kHelioFamily: 60, + kMiBand7Family: 60, kPebbleFamily: 60, kMiBandFamily: 60, kUltrahumanFamily: 300, @@ -65,6 +71,7 @@ const Map kMethodFamily = { 'gen5': 'hr_1hz', kGarminFamily: 'hr_1min', kHelioFamily: 'hr_1min', + kMiBand7Family: 'hr_1min', kPebbleFamily: 'hr_1min', kMiBandFamily: 'hr_1min', kUltrahumanFamily: 'hr_5min', diff --git a/test/guards/support/pairing_reset_fixtures.dart b/test/guards/support/pairing_reset_fixtures.dart index 246522c04..05a71fa13 100644 --- a/test/guards/support/pairing_reset_fixtures.dart +++ b/test/guards/support/pairing_reset_fixtures.dart @@ -15,6 +15,7 @@ const Map kPinnedOfficialHost = { 'coros': 'support.coros.com', 'miband234': 'www.mi.com', 'helio_strap': 'support.amazfit.com', + 'zeppos_l66': 'www.mi.com', // Xiaomi / Mi Smart Band 7, same reviewed host as the other Xiaomi rows 'pebble': 'help.repebble.com', 'colmi': 'www.colmi.com', 'garmin': 'support.garmin.com', @@ -70,6 +71,7 @@ const Set kPairingFollowUp = { 'ultrahuman', 'miband234', 'helio_strap', + 'zeppos_l66', 'pebble', 'colmi', 'garmin', diff --git a/test/slot_comparison_test.dart b/test/slot_comparison_test.dart index 16742bf77..c3203d2b4 100644 --- a/test/slot_comparison_test.dart +++ b/test/slot_comparison_test.dart @@ -88,11 +88,13 @@ void main() { }); group('wearables fill every day (the active wearable)', () { - test('the seven columned entries are found (control for the loops below)', + test('the eight columned entries are found (control for the loops below)', () { - // helio_strap's column is the declaration-built one (sparseColumn). + // helio_strap's and zeppos_l66's columns are the declaration-built one + // (sparseColumn). expect({for (final e in _columnEntries()) e.id}, {'garmin', 'pebble', - 'miband234', 'ultrahuman', 'colmi', 'oura', 'helio_strap'}); + 'miband234', 'ultrahuman', 'colmi', 'oura', 'helio_strap', + 'zeppos_l66'}); }); test('Oura: the rows read off kOuraColumn, with their captions', () { diff --git a/test/synthetic_miband7_day_test.dart b/test/synthetic_miband7_day_test.dart new file mode 100644 index 000000000..408bcc73a --- /dev/null +++ b/test/synthetic_miband7_day_test.dart @@ -0,0 +1,146 @@ +// A Xiaomi / Mi Smart Band 7 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, its own hypnogram, no skin temperature: the +// band has no sensor for it), derived by the real engine and served by the +// declaration-built column. Same numbers as the Helio Strap off the same +// minute HR, with nothing Mi Band 7-specific in compute, and every row the +// band cannot feed unavailable with a reason, never filled in. + +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:openstrap_edge/ble/adapters/_registry.dart' + show TimeAnchor, kMiBand7; +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/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 = 'zeppos_l66-synthetic'; +final String _family = kMiBand7.id; +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_miband7_day_test.db'; + final dir = await databaseFactory.getDatabasesPath(); + await databaseFactory.deleteDatabase(p.join(dir, LocalDb.dbName)); + await LocalDb.upsertDevice(id: _id, adapterId: _family, label: kMiBand7.label); + 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(); + await LocalDb.commitSyncBatch(const [], const [], + deviceId: _id, + deviceFamily: _family, + neutrals: [ + for (final t in ts) + 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); + } + }); + + tearDownAll(() async => LocalDb.close()); + + test('flag off: the band 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(_family), '1'); + for (var i = 0; i < 2; i++) { + expect( + await DerivationEngine().runDays(_profile, _dayIds, force: true), 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)); + 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', + reason: 'resting HR only: no device RMSSD for this family'); + expect(cells['readiness']!['method'], 'rhr_only_partial'); + expect(cls('sleep_window'), 'ours'); + for (final r in [ + 'hrv', + 'respiratory_rate', + 'stress', + 'irregular_rhythm', + 'skin_temp', + ]) { + expect(cls(r), 'unavailable', reason: '$r: nothing this band feeds'); + expect(cells[r]!['reason'], isNotEmpty); + } + + final stored = _payload((await LocalDb.dayResult(_dayId))!); + expect(stored['device_family'], _family); + expect(stored['sleep_source'], 'vendor_staged'); + }, timeout: const Timeout(Duration(minutes: 3))); + + test("the band'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: 9001, + unit: 'steps', + attribution: 'Xiaomi', + ), + ], deviceId: _id); + await DerivationEngine().runDays(_profile, {_dayId}, force: true); + final stored = _payload((await LocalDb.dayResult(_dayId))!); + expect((stored['scalars'] as Map)['steps'], 9001); + expect((stored['steps'] as Map)['source'], 'wearable'); + }, timeout: const Timeout(Duration(minutes: 3))); + + test('turning the band off leaves nothing of it', () async { + onWearableDaysChanged = (days) async => + DerivationEngine().runDays(_profile, days, force: true); + try { + await setWearableEnabled(_family, 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/wearable_toggle_no_leak_test.dart b/test/wearable_toggle_no_leak_test.dart index 4ededd71a..78f444d22 100644 --- a/test/wearable_toggle_no_leak_test.dart +++ b/test/wearable_toggle_no_leak_test.dart @@ -29,6 +29,7 @@ const List _families = [ 'colmi', 'oura', 'helio_strap', + 'zeppos_l66', ]; void main() { From 5993dc1225813bda0b84e636aadd950693d256c5 Mon Sep 17 00:00:00 2001 From: Mohammad Abdul Sahil <127765312+abdulsaheel@users.noreply.github.com> Date: Mon, 23 Nov 2026 01:32:54 +0530 Subject: [PATCH 03/22] amazfit gtr 3, gtr 3 pro, gts 3 on the helio engine three more zepp os devices, keyed by codename (verona, madrid, zurich), same shape as mi band 7: typed-key pairing, sync, background sync, forget, devices rows, ios picker (before helio so the fee1 label stays the strap's), and derived numbers off minute hr. hr, steps, stages and vendor scalars only; hrv stays raw. with five devices on one engine the per-device arms go: HelioStrapLink.all and forId, one typed-key pairing lookup, and app_state / background sync / forget / the devices sync button loop or look up instead of naming each one. kMiBand7Signals becomes kZeppOsSignals. beta, flag off by default. names match exactly, so "amazfit gtr 3" never claims a gtr 3 pro. --- ios/Runner/Info.plist | 12 + lib/ble/adapters/_registry.dart | 98 +++++- lib/ble/adapters/helio_strap.dart | 14 +- lib/ble/helio_strap_link.dart | 31 +- lib/ble/hrs_link.dart | 9 +- lib/compute/inputs/garmin_inputs.dart | 12 + lib/state/app_state.dart | 5 +- lib/sync/background_sync.dart | 17 +- lib/ui2/pairing/device_picker.dart | 6 +- lib/ui2/profile/devices.dart | 30 +- lib/ui2/profile/pair_sensor.dart | 6 +- test/adapter_signals_registry_test.dart | 3 + test/band_registry_test.dart | 3 + .../support/pairing_reset_fixtures.dart | 6 + test/pairing_device_role_test.dart | 3 +- test/slot_comparison_test.dart | 6 +- test/wearable_platform_test.dart | 3 + test/wearable_toggle_no_leak_test.dart | 3 + test/zeppos_watches_test.dart | 281 ++++++++++++++++++ 19 files changed, 503 insertions(+), 45 deletions(-) create mode 100644 test/zeppos_watches_test.dart diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist index f51567208..63f128142 100644 --- a/ios/Runner/Info.plist +++ b/ios/Runner/Info.plist @@ -67,6 +67,9 @@ FEE1 FEE1 FEE1 + FEE1 + FEE1 + FEE1 FED9 6A4E2800-667B-11E3-949A-0800200C9A66 1809 @@ -113,6 +116,12 @@ FEE1 Xiaomi Smart Band 7 FEE1 + Amazfit GTR 3 + FEE1 + Amazfit GTR 3 Pro + FEE1 + Amazfit GTS 3 + FEE1 Amazfit Helio Strap FED9 Pebble @@ -146,6 +155,9 @@ FEE1 FEE1 FEE1 + FEE1 + FEE1 + FEE1 FED9 6A4E2800-667B-11E3-949A-0800200C9A66 1809 diff --git a/lib/ble/adapters/_registry.dart b/lib/ble/adapters/_registry.dart index 7420f8749..86590b088 100644 --- a/lib/ble/adapters/_registry.dart +++ b/lib/ble/adapters/_registry.dart @@ -1117,6 +1117,69 @@ bool _looksLikeMiBand7(String lowercaseName) => lowercaseName == 'mi smart band 7' || RegExp(r'^xiaomi smart band 7( [0-9a-z]{4})?$').hasMatch(lowercaseName); +/// One Zepp OS watch on the Helio engine, keyed by codename. Same protocol, +/// channels and caveats as [kMiBand7]: EXPERIMENTAL (ASSUMPTIONS R6), nobody +/// on this project owns one, HRV banked raw, not decoded. +const BandEntry kAmazfitGtr3 = BandEntry.notify( + id: 'zeppos_verona', + role: DeviceRole.band, + kind: DeviceKind.watch, + resetSteps: ResetSteps.unverified(officialUrl: 'https://support.amazfit.com/'), + category: DeviceCategory.wearable, + label: 'Amazfit GTR 3', + service: kHuami234Service, + characteristics: _kZeppOsChars, + timeAnchor: TimeAnchor.measured, + nameMatcher: _looksLikeGtr3, + scanByName: true, +); + +/// See [kAmazfitGtr3]. +const BandEntry kAmazfitGtr3Pro = BandEntry.notify( + id: 'zeppos_madrid', + role: DeviceRole.band, + kind: DeviceKind.watch, + resetSteps: ResetSteps.unverified(officialUrl: 'https://support.amazfit.com/'), + category: DeviceCategory.wearable, + label: 'Amazfit GTR 3 Pro', + service: kHuami234Service, + characteristics: _kZeppOsChars, + timeAnchor: TimeAnchor.measured, + nameMatcher: _looksLikeGtr3Pro, + scanByName: true, +); + +/// See [kAmazfitGtr3]. +const BandEntry kAmazfitGts3 = BandEntry.notify( + id: 'zeppos_zurich', + role: DeviceRole.band, + kind: DeviceKind.watch, + resetSteps: ResetSteps.unverified(officialUrl: 'https://support.amazfit.com/'), + category: DeviceCategory.wearable, + label: 'Amazfit GTS 3', + service: kHuami234Service, + characteristics: _kZeppOsChars, + timeAnchor: TimeAnchor.measured, + nameMatcher: _looksLikeGts3, + scanByName: true, +); + +const List _kZeppOsChars = [ + kHuami2021ChunkWriteChar, + kHuami2021ChunkNotifyChar, + kHuami2021FetchControlChar, + kHuami2021FetchDataChar, +]; + +/// Exact names only: each codename's retail names plus the codename itself. +/// "amazfit gtr 3" must never claim a GTR 3 Pro. +bool _looksLikeGtr3(String n) => + const {'verona', 'amazfit gtr 3', 'amazfit gtr 3e'}.contains(n); +bool _looksLikeGtr3Pro(String n) => + const {'madrid', 'madrid w', 'madridw', 'amazfit gtr 3 pro'}.contains(n); +bool _looksLikeGts3(String n) => + const {'zurich', 'amazfit gts 3', 'amazfit gts 3e'}.contains(n); + /// 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 @@ -1329,6 +1392,9 @@ const List kBandRegistry = [ kMiBand234, kHelioStrap, kMiBand7, + kAmazfitGtr3, + kAmazfitGtr3Pro, + kAmazfitGts3, kPebble, kColmi, kGarmin, @@ -1385,9 +1451,10 @@ final List kFramedBands = /// advertisement can be read for a `bluetoothCompanyIdentifier` or /// manufacturer-data blob that differs from Mi Band's. /// -/// [kMiBand7] is listed under the same owner-accepted risk (owner decision -/// 2026-11-23): a third FEE1 device, told apart from the other two only by -/// the name it advertises. +/// [kMiBand7], [kAmazfitGtr3], [kAmazfitGtr3Pro] and [kAmazfitGts3] are +/// listed under the same owner-accepted risk (owner decision 2026-11-23): +/// more FEE1 devices, told apart only by the names they advertise. They sit +/// before [kHelioStrap] so the FEE1 label the picker shows stays the strap's. /// /// [kMiBand234], [kColmi], [kUltrahuman], [kMiScaleComposition] and /// [kMiScale2] are listed although they break the rule above: the band is @@ -1407,6 +1474,9 @@ const List kAskPickerSensors = [ kUltrahuman, kMiBand234, kMiBand7, + kAmazfitGtr3, + kAmazfitGtr3Pro, + kAmazfitGts3, kHelioStrap, kPebble, kGarmin, @@ -1564,7 +1634,7 @@ const Map> kAdapterSignals = InputSignal.deviceStages: Duration.zero, InputSignal.vendorScalars: Duration.zero, }, - // Mirrors `kMiBand7Signals` in `helio_strap.dart`. Only what this band is + // Mirrors `kZeppOsSignals` in `helio_strap.dart`. Only what this band is // known to carry: no skin-temperature sensor, and its HRV records are // banked raw, not decoded (unit unconfirmed without hardware). 'zeppos_l66': { @@ -1573,6 +1643,26 @@ const Map> kAdapterSignals = InputSignal.deviceStages: Duration.zero, InputSignal.vendorScalars: Duration.zero, }, + // The Zepp OS watches: the same declaration as Mi Band 7, for the same + // reasons (no skin-temperature channel, HRV not decoded). + 'zeppos_verona': { + InputSignal.hrSparse: Duration(minutes: 1), + InputSignal.steps: Duration(minutes: 1), + InputSignal.deviceStages: Duration.zero, + InputSignal.vendorScalars: Duration.zero, + }, + 'zeppos_madrid': { + InputSignal.hrSparse: Duration(minutes: 1), + InputSignal.steps: Duration(minutes: 1), + InputSignal.deviceStages: Duration.zero, + InputSignal.vendorScalars: Duration.zero, + }, + 'zeppos_zurich': { + InputSignal.hrSparse: Duration(minutes: 1), + InputSignal.steps: Duration(minutes: 1), + InputSignal.deviceStages: Duration.zero, + InputSignal.vendorScalars: Duration.zero, + }, 'thermometer': {}, 'miscale_bc': {}, 'miscale2': {}, diff --git a/lib/ble/adapters/helio_strap.dart b/lib/ble/adapters/helio_strap.dart index 7a2339340..eb065c8d3 100644 --- a/lib/ble/adapters/helio_strap.dart +++ b/lib/ble/adapters/helio_strap.dart @@ -299,7 +299,8 @@ class HelioStrapAdapter extends BandAdapter { authKeyReader = authKeyReader ?? (() => _defaultAuthKeyReader(entry)); - /// The device this session drives: [kHelioStrap] or [kMiBand7]. Same + /// The device this session drives: [kHelioStrap], [kMiBand7] or one of the + /// Zepp OS watches. Same /// protocol; the entry decides the key slot, attribution, signals and /// which record types are decoded. @override @@ -307,7 +308,7 @@ class HelioStrapAdapter extends BandAdapter { @override Map get signals => - entry.id == kMiBand7.id ? kMiBand7Signals : kHelioStrapSignals; + entry.id == kHelioStrap.id ? kHelioStrapSignals : kZeppOsSignals; String get _attribution => zeppOsAttribution(entry); @@ -885,10 +886,11 @@ const Map kHelioStrapSignals = { InputSignal.vendorScalars: Duration.zero, }; -/// The signals Mi Band 7 supplies. Mirrored in `kAdapterSignals`. No skin -/// temperature (no sensor), and no HRV: its HRV records are banked raw, -/// not decoded ([HelioStrapAdapter._decodesHrv]). -const Map kMiBand7Signals = { +/// The signals every Zepp OS device other than the Helio Strap supplies +/// (Mi Band 7, the GTR 3 / GTR 3 Pro / GTS 3 watches). Mirrored in +/// `kAdapterSignals`. No skin temperature (no channel), and no HRV: their +/// HRV records are banked raw, not decoded ([HelioStrapAdapter._decodesHrv]). +const Map kZeppOsSignals = { InputSignal.hrSparse: Duration(minutes: 1), InputSignal.steps: Duration(minutes: 1), InputSignal.deviceStages: Duration.zero, diff --git a/lib/ble/helio_strap_link.dart b/lib/ble/helio_strap_link.dart index 4cdd10504..0b7fc63fd 100644 --- a/lib/ble/helio_strap_link.dart +++ b/lib/ble/helio_strap_link.dart @@ -77,12 +77,16 @@ Future pairHelioStrapWithTypedKey( BluetoothDevice device, String raw) => _pairZeppOsWithTypedKey(device, raw, kHelioStrap); -/// [pairHelioStrapWithTypedKey] for a Xiaomi / Mi Smart Band 7: the same -/// handshake and the same verify-then-store rules, under its own key slot -/// and its own `device` row. -Future pairMiBand7WithTypedKey( - BluetoothDevice device, String raw) => - _pairZeppOsWithTypedKey(device, raw, kMiBand7); +/// The typed-key pairing function for [adapterId] when it is one of this +/// family's devices (Helio Strap, Mi Band 7, the Zepp OS watches), else +/// null. Same handshake and verify-then-store rules for each, under the +/// device's own key slot and its own `device` row. +Future Function(BluetoothDevice, String)? zeppOsTypedKeyPairFor( + String adapterId) { + final link = HelioStrapLink.forId(adapterId); + if (link == null) return null; + return (device, raw) => _pairZeppOsWithTypedKey(device, raw, link.entry); +} Future _pairZeppOsWithTypedKey( BluetoothDevice device, String raw, BandEntry entry) async { @@ -368,6 +372,21 @@ class HelioStrapLink { HelioStrapLink._(this.entry); static final HelioStrapLink instance = HelioStrapLink._(kHelioStrap); static final HelioStrapLink miBand7 = HelioStrapLink._(kMiBand7); + static final HelioStrapLink gtr3 = HelioStrapLink._(kAmazfitGtr3); + static final HelioStrapLink gtr3Pro = HelioStrapLink._(kAmazfitGtr3Pro); + static final HelioStrapLink gts3 = HelioStrapLink._(kAmazfitGts3); + + /// Every link of this family, so app-wide stop / background sync loop over + /// them instead of naming each device. + static final List all = [instance, miBand7, gtr3, gtr3Pro, gts3]; + + /// The link driving [adapterId], or null when it is not this family. + static HelioStrapLink? forId(Object? adapterId) { + for (final l in all) { + if (l.entry.id == adapterId) return l; + } + return null; + } /// The family this link drives. final BandEntry entry; diff --git a/lib/ble/hrs_link.dart b/lib/ble/hrs_link.dart index 3af347edd..99126ec27 100644 --- a/lib/ble/hrs_link.dart +++ b/lib/ble/hrs_link.dart @@ -985,12 +985,9 @@ class HrsLink { await ColmiLink.forgetRing(id); return; } - if (row?['adapter_id'] == kHelioStrap.id) { - await HelioStrapLink.forgetStrap(id); - return; - } - if (row?['adapter_id'] == kMiBand7.id) { - await HelioStrapLink.miBand7.forget(id); + final zeppOs = HelioStrapLink.forId(row?['adapter_id']); + if (zeppOs != null) { + await zeppOs.forget(id); return; } final session = SessionLink.forId(row?['adapter_id'] as String?); diff --git a/lib/compute/inputs/garmin_inputs.dart b/lib/compute/inputs/garmin_inputs.dart index 917ceb29e..b952e7435 100644 --- a/lib/compute/inputs/garmin_inputs.dart +++ b/lib/compute/inputs/garmin_inputs.dart @@ -38,6 +38,12 @@ const String kHelioFamily = 'helio_strap'; /// device-RMSSD family. const String kMiBand7Family = 'zeppos_l66'; +/// The Zepp OS watches on the same engine (GTR 3, GTR 3 Pro, GTS 3), served +/// the same way and for the same reason not device-RMSSD families. +const String kGtr3Family = 'zeppos_verona'; +const String kGtr3ProFamily = 'zeppos_madrid'; +const String kGts3Family = 'zeppos_zurich'; + /// 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. @@ -54,6 +60,9 @@ const Map kHrCadenceSec = { kGarminFamily: 60, kHelioFamily: 60, kMiBand7Family: 60, + kGtr3Family: 60, + kGtr3ProFamily: 60, + kGts3Family: 60, kPebbleFamily: 60, kMiBandFamily: 60, kUltrahumanFamily: 300, @@ -72,6 +81,9 @@ const Map kMethodFamily = { kGarminFamily: 'hr_1min', kHelioFamily: 'hr_1min', kMiBand7Family: 'hr_1min', + kGtr3Family: 'hr_1min', + kGtr3ProFamily: 'hr_1min', + kGts3Family: 'hr_1min', kPebbleFamily: 'hr_1min', kMiBandFamily: 'hr_1min', kUltrahumanFamily: 'hr_5min', diff --git a/lib/state/app_state.dart b/lib/state/app_state.dart index c53de5579..2455bb90c 100644 --- a/lib/state/app_state.dart +++ b/lib/state/app_state.dart @@ -1884,8 +1884,9 @@ 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('zeppos_l66', HelioStrapLink.miBand7.stop); + for (final l in HelioStrapLink.all) { + await bounded(l.entry.id, l.stop); + } await bounded('pebble', PebbleLink.instance.stop); await bounded('coros', CorosLink.instance.stop); for (final link in SessionLink.all) { diff --git a/lib/sync/background_sync.dart b/lib/sync/background_sync.dart index e9b7b5a6c..dee0666b7 100644 --- a/lib/sync/background_sync.dart +++ b/lib/sync/background_sync.dart @@ -482,15 +482,14 @@ Future syncPairedSensors() async { // 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'); - } - try { - await HelioStrapLink.miBand7.sync(); - } catch (e) { - debugPrint('[bgsync] zeppos_l66 sync skipped: $e'); + // One at a time, each on its own: a failure on one device never skips the + // rest. Unpaired ones no-op. + for (final link in HelioStrapLink.all) { + try { + await link.sync(); + } catch (e) { + debugPrint('[bgsync] ${link.entry.id} 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. diff --git a/lib/ui2/pairing/device_picker.dart b/lib/ui2/pairing/device_picker.dart index d001f732b..cdb5a62c4 100644 --- a/lib/ui2/pairing/device_picker.dart +++ b/lib/ui2/pairing/device_picker.dart @@ -48,7 +48,7 @@ import '../../ble/ble_state.dart' kMaxConcurrentSecondaryLinks; import '../../ble/hrs_link.dart'; import '../../ble/helio_strap_link.dart' - show pairHelioStrapWithTypedKey, pairMiBand7WithTypedKey; + show zeppOsTypedKeyPairFor; import '../../ble/oura_link.dart' show pairOuraRingWithTypedKey; import '../../data/db.dart' show LocalDb; import '../../l10n/app_localizations.dart'; @@ -430,8 +430,8 @@ class _DevicePickerScreenState extends State // 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, - final id when id == kMiBand7.id => pairMiBand7WithTypedKey, + final id when zeppOsTypedKeyPairFor(id) != null => + zeppOsTypedKeyPairFor(id), _ => null, }, ), diff --git a/lib/ui2/profile/devices.dart b/lib/ui2/profile/devices.dart index 3b1182a61..e17955f31 100644 --- a/lib/ui2/profile/devices.dart +++ b/lib/ui2/profile/devices.dart @@ -53,6 +53,9 @@ import '../../ble/adapters/_registry.dart' kGarmin, kHelioStrap, kMiBand7, + kAmazfitGtr3, + kAmazfitGtr3Pro, + kAmazfitGts3, kMiBand234, kMiScale2, kMiScaleComposition, @@ -1194,6 +1197,14 @@ class MyDevices extends StatelessWidget { } } +/// The pairing blurb every Zepp OS watch shares; [what] names the model. +String _zeppOsWatchBlurb(String what) => + '$what. First pairing still has to go through the Zepp app, which is ' + 'where the watch\'s key comes from. Paste that key below to pair it here ' + 'instead. Syncs heart rate, steps, sleep and workouts; the watch\'s own ' + 'stress and SpO2 figures are labelled as Amazfit\'s. HRV is not read ' + 'yet. Experimental.'; + /// Every sensor that can be paired from this screen — a second device /// alongside the band, never a replacement for it. /// @@ -1313,6 +1324,21 @@ final List<({BandEntry entry, String blurb, Future Function(BluetoothDe // Null for the same reason as the Helio Strap: typed key only. pick: null, ), + ( + entry: kAmazfitGtr3, + blurb: _zeppOsWatchBlurb('An Amazfit GTR 3 or GTR 3e'), + pick: null, + ), + ( + entry: kAmazfitGtr3Pro, + blurb: _zeppOsWatchBlurb('An Amazfit GTR 3 Pro'), + pick: null, + ), + ( + entry: kAmazfitGts3, + blurb: _zeppOsWatchBlurb('An Amazfit GTS 3 or GTS 3e'), + pick: null, + ), ( entry: kPebble, blurb: 'Pebble 2 or Pebble 2 SE only — older Pebbles need Bluetooth ' @@ -2157,8 +2183,8 @@ class _DeviceDetailState extends State { 'miband234' => () => _syncMiband(c), 'pebble' => () => _syncPebble(c), 'colmi' => () => _syncColmiRing(c), - 'helio_strap' => () => _syncSensor(c, HelioStrapLink.instance.sync), - 'zeppos_l66' => () => _syncSensor(c, HelioStrapLink.miBand7.sync), + final f when HelioStrapLink.forId(f) != null => + () => _syncSensor(c, HelioStrapLink.forId(f)!.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 be944a0e7..96859fa30 100644 --- a/lib/ui2/profile/pair_sensor.dart +++ b/lib/ui2/profile/pair_sensor.dart @@ -64,7 +64,7 @@ import '../../ble/ble_state.dart' import '../../ble/hrs_link.dart'; import '../../ble/ios_ble_restore.dart'; import '../../ble/helio_strap_link.dart' - show pairHelioStrapWithTypedKey, pairMiBand7WithTypedKey; + show zeppOsTypedKeyPairFor; import '../../ble/oura_link.dart' show pairOuraRingWithTypedKey; import '../../data/db.dart' show LocalDb; import '../../l10n/app_localizations.dart'; @@ -481,8 +481,8 @@ class _PairSensorScreenState extends State onPicked: sensor.pick, onPickedWithKey: switch (band.id) { final id when id == kOura.id => pairOuraRingWithTypedKey, - final id when id == kHelioStrap.id => pairHelioStrapWithTypedKey, - final id when id == kMiBand7.id => pairMiBand7WithTypedKey, + final id when zeppOsTypedKeyPairFor(id) != null => + zeppOsTypedKeyPairFor(id), _ => null, }, ), diff --git a/test/adapter_signals_registry_test.dart b/test/adapter_signals_registry_test.dart index c75dd43b9..ea0aeccf4 100644 --- a/test/adapter_signals_registry_test.dart +++ b/test/adapter_signals_registry_test.dart @@ -44,6 +44,9 @@ void main() { 'colmi': kColmiAdapter.signals, 'helio_strap': kHelioStrapAdapter.signals, 'zeppos_l66': kMiBand7Adapter.signals, + 'zeppos_verona': HelioStrapAdapter(entry: kAmazfitGtr3).signals, + 'zeppos_madrid': HelioStrapAdapter(entry: kAmazfitGtr3Pro).signals, + 'zeppos_zurich': HelioStrapAdapter(entry: kAmazfitGts3).signals, 'thermometer': ThermometerAdapter().signals, 'miscale_bc': MiScaleAdapter(kMiScaleComposition).signals, 'miscale2': MiScaleAdapter(kMiScale2).signals, diff --git a/test/band_registry_test.dart b/test/band_registry_test.dart index 7f91fe147..0f736ee8a 100644 --- a/test/band_registry_test.dart +++ b/test/band_registry_test.dart @@ -24,6 +24,9 @@ void main() { 'miband234', 'helio_strap', 'zeppos_l66', + 'zeppos_verona', + 'zeppos_madrid', + 'zeppos_zurich', 'pebble', 'colmi', 'garmin', diff --git a/test/guards/support/pairing_reset_fixtures.dart b/test/guards/support/pairing_reset_fixtures.dart index 05a71fa13..924b69237 100644 --- a/test/guards/support/pairing_reset_fixtures.dart +++ b/test/guards/support/pairing_reset_fixtures.dart @@ -16,6 +16,9 @@ const Map kPinnedOfficialHost = { 'miband234': 'www.mi.com', 'helio_strap': 'support.amazfit.com', 'zeppos_l66': 'www.mi.com', // Xiaomi / Mi Smart Band 7, same reviewed host as the other Xiaomi rows + 'zeppos_verona': 'support.amazfit.com', // Amazfit GTR 3, same reviewed host as the Helio row + 'zeppos_madrid': 'support.amazfit.com', // Amazfit GTR 3 Pro + 'zeppos_zurich': 'support.amazfit.com', // Amazfit GTS 3 'pebble': 'help.repebble.com', 'colmi': 'www.colmi.com', 'garmin': 'support.garmin.com', @@ -72,6 +75,9 @@ const Set kPairingFollowUp = { 'miband234', 'helio_strap', 'zeppos_l66', + 'zeppos_verona', + 'zeppos_madrid', + 'zeppos_zurich', 'pebble', 'colmi', 'garmin', diff --git a/test/pairing_device_role_test.dart b/test/pairing_device_role_test.dart index a75812365..96c365ab5 100644 --- a/test/pairing_device_role_test.dart +++ b/test/pairing_device_role_test.dart @@ -28,7 +28,8 @@ void main() { }; expect(bands, { 'gen4', 'gen5', 'oura', 'coros', 'ultrahuman', 'miband234', 'helio_strap', - 'zeppos_l66', 'pebble', 'colmi', 'garmin', + 'zeppos_l66', 'zeppos_verona', 'zeppos_madrid', 'zeppos_zurich', + 'pebble', 'colmi', 'garmin', }); }); diff --git a/test/slot_comparison_test.dart b/test/slot_comparison_test.dart index c3203d2b4..759d32648 100644 --- a/test/slot_comparison_test.dart +++ b/test/slot_comparison_test.dart @@ -88,13 +88,13 @@ void main() { }); group('wearables fill every day (the active wearable)', () { - test('the eight columned entries are found (control for the loops below)', + test('the eleven columned entries are found (control for the loops below)', () { - // helio_strap's and zeppos_l66's columns are the declaration-built one + // the helio and zepp os columns are the declaration-built one // (sparseColumn). expect({for (final e in _columnEntries()) e.id}, {'garmin', 'pebble', 'miband234', 'ultrahuman', 'colmi', 'oura', 'helio_strap', - 'zeppos_l66'}); + 'zeppos_l66', 'zeppos_verona', 'zeppos_madrid', 'zeppos_zurich'}); }); test('Oura: the rows read off kOuraColumn, with their captions', () { diff --git a/test/wearable_platform_test.dart b/test/wearable_platform_test.dart index 21407488c..11e563639 100644 --- a/test/wearable_platform_test.dart +++ b/test/wearable_platform_test.dart @@ -56,6 +56,9 @@ void main() { 'colmi': DeviceCategory.wearable, 'helio_strap': DeviceCategory.wearable, 'zeppos_l66': DeviceCategory.wearable, + 'zeppos_verona': DeviceCategory.wearable, + 'zeppos_madrid': DeviceCategory.wearable, + 'zeppos_zurich': 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 78f444d22..44151d362 100644 --- a/test/wearable_toggle_no_leak_test.dart +++ b/test/wearable_toggle_no_leak_test.dart @@ -30,6 +30,9 @@ const List _families = [ 'oura', 'helio_strap', 'zeppos_l66', + 'zeppos_verona', + 'zeppos_madrid', + 'zeppos_zurich', ]; void main() { diff --git a/test/zeppos_watches_test.dart b/test/zeppos_watches_test.dart new file mode 100644 index 000000000..b50e894ac --- /dev/null +++ b/test/zeppos_watches_test.dart @@ -0,0 +1,281 @@ +// The Zepp OS watches on the Helio engine: Amazfit GTR 3 (`zeppos_verona`), +// GTR 3 Pro (`zeppos_madrid`) and GTS 3 (`zeppos_zurich`). Registry and +// lookups, a real-handshake session through the adapter, and one watch's +// synthetic days through the real derivation engine. The engine path is the +// same for all three, which the registry tests pin. + +import 'dart:async'; +import 'dart:convert'; +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/ble/helio_strap_link.dart'; +import 'package:openstrap_edge/compute/derivation_engine.dart'; +import 'package:openstrap_edge/compute/inputs/canonical.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:openstrap_edge/data/observation.dart'; +import 'package:openstrap_protocol/openstrap_protocol.dart'; +import 'package:path/path.dart' as p; +import 'package:sqflite_common_ffi/sqflite_ffi.dart'; + +import 'support/synthetic_day.dart'; + +const List _watches = [kAmazfitGtr3, kAmazfitGtr3Pro, kAmazfitGts3]; + +final DateTime _now = DateTime(2026, 10, 4, 12, 0); +final int _nowSec = _now.millisecondsSinceEpoch ~/ 1000; +final DateTime _roundStart = DateTime(_now.year, _now.month, _now.day, 6, 0); + +/// Real handshake, one activity round (two minutes: hr 65 + 20 steps, then +/// 10 steps with the hr sentinel), every other type "no data". +Future> _session(BandEntry entry) async { + final key = Uint8List.fromList(List.generate(16, (i) => i + 1)); + final link = ReplayBandLink(); + final adapter = HelioStrapAdapter( + entry: entry, + nowSeconds: () => _nowSec, + authKeyReader: () async => key, + firstReplyTimeout: const Duration(milliseconds: 200), + quietTimeout: const Duration(milliseconds: 30), + ); + final kp = keypairFrom( + Uint8List.fromList(List.generate(24, (i) => (i * 7 + 3) % 256))); + final remoteRandom = + Uint8List.fromList(List.generate(16, (i) => (i * 11 + 5) % 256)); + final decoder = Huami2021Decoder(); + final encoder = Huami2021Encoder(); + void auth(List body) { + for (final c in encoder.encode(kHuami2021AuthEndpoint, body)) { + link.feed(kHuami2021ChunkNotifyChar, c, atSec: _nowSec); + } + } + + 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 = decoder.feed(value, sessionKey: null); + if (frame == null || frame.endpoint != kHuami2021AuthEndpoint) continue; + final p = frame.payload; + if (p.isNotEmpty && p[0] == 0x04) { + auth([0x10, 0x04, 0x01, ...remoteRandom, ...kp.publicKey]); + } else if (p.isNotEmpty && p[0] == 0x05) { + auth([0x10, 0x05, 0x01]); + } + continue; + } + if (char != kHuami2021FetchControlChar || value.isEmpty) continue; + if (value[0] == 0x01) { + final hasData = value[1] == kHuami2021TypeActivity; + final n = hasData ? 2 : 0; + final rs = hasData ? _roundStart : DateTime(1970); + link.feed( + kHuami2021FetchControlChar, + [ + 0x10, 0x01, 0x01, n, 0, 0, 0, + rs.year & 0xff, (rs.year >> 8) & 0xff, rs.month, rs.day, + rs.hour, rs.minute, rs.second, + ], + atSec: _nowSec); + } else if (value.length == 1 && value[0] == 0x02) { + link.feed(kHuami2021FetchDataChar, + [0, 0, 0, 20, 65, 0, 0, 0, 0, 0, 0, 10, 0xff, 0, 0, 0, 0], + atSec: _nowSec); + link.feed(kHuami2021FetchControlChar, const [0x10, 0x02, 0x01], + atSec: _nowSec); + } + } + } + }()); + await done.future.timeout(const Duration(seconds: 20)); + await sub.cancel(); + await link.close(); + return events; +} + +Map _payload(Map row) => + (jsonDecode(row['payload_json'] as String) as Map).cast(); + +void main() { + group('registry', () { + test('each watch is its own codename-keyed entry on the Zepp OS channels', + () { + expect(_watches.map((e) => e.id), + ['zeppos_verona', 'zeppos_madrid', 'zeppos_zurich']); + for (final e in _watches) { + expect(e.service, kHelioStrap.service, reason: e.id); + expect(e.requiredCharacteristics, kHelioStrap.requiredCharacteristics, + reason: e.id); + expect(kBandRegistry, contains(e)); + expect(kAskPickerSensors, contains(e)); + } + }); + + test('names map to exactly one entry, the right one', () { + const names = { + 'amazfit gtr 3': 'zeppos_verona', + 'amazfit gtr 3e': 'zeppos_verona', + 'verona': 'zeppos_verona', + 'amazfit gtr 3 pro': 'zeppos_madrid', + 'madrid': 'zeppos_madrid', + 'madrid w': 'zeppos_madrid', + 'amazfit gts 3': 'zeppos_zurich', + 'amazfit gts 3e': 'zeppos_zurich', + 'zurich': 'zeppos_zurich', + }; + for (final MapEntry(key: name, value: id) in names.entries) { + final claims = [ + for (final e in kBandRegistry) + if (e.nameMatcher?.call(name) ?? false) e.id, + ]; + expect(claims, [id], reason: name); + } + for (final name in ['amazfit gtr 4', 'amazfit gts 3 pro', 'gtr 3']) { + expect(_watches.where((e) => e.nameMatcher!(name)), isEmpty, + reason: name); + } + }); + + test('signals are the basic Zepp OS set, in sync with kAdapterSignals', () { + for (final e in _watches) { + final s = HelioStrapAdapter(entry: e).signals; + expect(s, kZeppOsSignals, reason: e.id); + expect(kAdapterSignals[e.id], s, reason: e.id); + expect(s.containsKey(InputSignal.deviceHrv), isFalse); + } + }); + + test('links, pairing and key slots are per watch', () { + for (final e in _watches) { + expect(HelioStrapLink.forId(e.id)?.entry, e, reason: e.id); + expect(zeppOsTypedKeyPairFor(e.id), isNotNull, reason: e.id); + } + expect(HelioStrapLink.all.map((l) => l.entry.id).toSet(), hasLength(5)); + expect(HelioStrapLink.forId('oura'), isNull); + expect(zeppOsTypedKeyPairFor('oura'), isNull); + final slots = { + for (final l in HelioStrapLink.all) zeppOsKeySlot(l.entry), + }; + expect(slots, hasLength(5), reason: 'no two devices share a key slot'); + }); + + test('attribution is Amazfit for the watches', () { + for (final e in _watches) { + expect(zeppOsAttribution(e), 'Amazfit', reason: e.id); + } + }); + }); + + test('GTR 3 session: real handshake, HR and steps decoded', () async { + final events = await _session(kAmazfitGtr3); + expect(events.whereType(), isEmpty); + final hr = [ + for (final b in events.whereType()) + for (final s in b.samples) + if (s.hr != null) s, + ]; + expect(hr.map((s) => s.hr), [65]); + final steps = [ + for (final v in events.whereType()) ...v.rows, + ].singleWhere((o) => o.key == 'steps'); + expect(steps.value, 30); + expect(steps.attribution, 'Amazfit'); + }); + + group('GTS 3 through the engine', () { + final days = [ + for (var d = 1; d <= 4; d++) + SyntheticDay(DateTime(2026, 10, d), nightHrOffset: d < 4 ? -6 : 0), + ]; + const id = 'zeppos_zurich-synthetic'; + final family = kAmazfitGts3.id; + const dayId = '2026-10-04'; + const dayIds = {'2026-10-01', '2026-10-02', '2026-10-03', dayId}; + const profile = Profile(ageYears: 32, weightKg: 72, heightCm: 176, sex: 'm'); + + setUpAll(() async { + sqfliteFfiInit(); + databaseFactory = databaseFactoryFfi; + await LocalDb.close(); + LocalDb.dbName = 'zeppos_watches_test.db'; + final dir = await databaseFactory.getDatabasesPath(); + await databaseFactory.deleteDatabase(p.join(dir, LocalDb.dbName)); + await LocalDb.upsertDevice(id: id, adapterId: family, label: kAmazfitGts3.label); + 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; + } + } + 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); + } + }); + + tearDownAll(() async => LocalDb.close()); + + test('flag off: nothing; flag on: strain, resting HR, readiness estimate', + () async { + await LocalDb.setCursor(kActiveWearableCursor, id); + expect(await DerivationEngine().runDays(profile, {dayId}, force: true), 0); + expect(await LocalDb.dayResult(dayId), isNull); + + await LocalDb.setCursor(wearableEnabledCursor(family), '1'); + // Twice: strain abstains until three prior days have a level, which + // the first pass is what writes. + for (var i = 0; i < 2; i++) { + expect( + await DerivationEngine().runDays(profile, dayIds, force: true), 4); + } + final cells = (await dayCells(dayId))!; + String cls(String row) => cells[row]!['class'] as String; + expect(cls('strain'), 'ours'); + expect(cls('resting_hr'), 'ours'); + expect(cells['resting_hr']!['method'], 'hr_1min'); + expect(cls('readiness'), 'estimated'); + expect(cls('sleep_window'), 'ours'); + for (final r in ['hrv', 'respiratory_rate', 'stress', 'skin_temp']) { + expect(cls(r), 'unavailable', reason: r); + expect(cells[r]!['reason'], isNotEmpty); + } + expect(_payload((await LocalDb.dayResult(dayId))!)['device_family'], + family); + + await LocalDb.putObservations([ + Observation( + at: DateTime(2026, 10, 4), + sourceKind: ObservationSource.vendor, + key: 'steps', + value: 7000, + unit: 'steps', + attribution: 'Amazfit', + ), + ], deviceId: id); + await DerivationEngine().runDays(profile, {dayId}, force: true); + expect((_payload((await LocalDb.dayResult(dayId))!)['scalars'] as Map)['steps'], + 7000); + }, timeout: const Timeout(Duration(minutes: 3))); + }); +} From 6851986f5b7599e9e725ffd0cafed4e66df3b48c Mon Sep 17 00:00:00 2001 From: Mohammad Abdul Sahil <127765312+abdulsaheel@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:06:21 +0530 Subject: [PATCH 04/22] ios picker: mi band 7 and gtr 3 / gts 3 under the huami id same maker as the helio strap, so 0x0157, already declared; listed so the plist test keeps it declared for each of them. --- lib/ble/adapters/_registry.dart | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/lib/ble/adapters/_registry.dart b/lib/ble/adapters/_registry.dart index 86590b088..cace3f2aa 100644 --- a/lib/ble/adapters/_registry.dart +++ b/lib/ble/adapters/_registry.dart @@ -1523,6 +1523,12 @@ const Map kAskSensorCompanyIds = { // 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, + // Mi Band 7 and the GTR 3 / GTS 3 watches: the same maker, the same id. + // Unverified on any of them (R6). + 'zeppos_l66': 0x0157, + 'zeppos_verona': 0x0157, + 'zeppos_madrid': 0x0157, + 'zeppos_zurich': 0x0157, }; /// iOS picker names for sensors whose service another sensor shares (FEE1): From d63771615d973a8a18c9c471e627f91cd594ad95 Mon Sep 17 00:00:00 2001 From: Mohammad Abdul Sahil <127765312+abdulsaheel@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:05:25 +0530 Subject: [PATCH 05/22] mi band 4 (cinco): typed key, sync, numbers, on the mi band 2/3 engine same legacy huami protocol as mi band 2/3, two differences keyed off its own entry: the handshake runs with crypt flag 0x80 (82 00 02 01 00 for the challenge, 83 00 for the answer, replies matched on the low nibble), and it never takes a key from this app, so pairing is a typed vendor key, verified on the band before anything is stored. MiBand234Link gets a per-entry instance and forId like the helio link; forget, stop, background sync and the devices sync button cover both. same mi band column for derivation (isMiBandFamily), same three-stage sleep vocabulary. 4-byte minute records, so no protocol change. beta, flag off by default, not in the ios picker yet (owner call). drops the now-false "mi band 4 isn't supported" from the mi band 2/3 blurb in all eight languages. --- lib/ble/adapters/_registry.dart | 36 ++++ lib/ble/adapters/miband234.dart | 65 ++++-- lib/ble/hrs_link.dart | 5 +- lib/ble/miband_link.dart | 120 ++++++++++- lib/compute/inputs/canonical.dart | 6 +- lib/compute/inputs/garmin_inputs.dart | 2 + lib/compute/inputs/miband_inputs.dart | 11 + lib/compute/vendor_sleep.dart | 2 + lib/l10n/app_de.arb | 2 +- lib/l10n/app_en.arb | 2 +- lib/l10n/app_es.arb | 2 +- lib/l10n/app_fr.arb | 2 +- lib/l10n/app_hi.arb | 2 +- lib/l10n/app_ru.arb | 2 +- lib/l10n/app_th.arb | 2 +- lib/l10n/app_zh.arb | 2 +- lib/state/app_state.dart | 1 + lib/sync/background_sync.dart | 5 + lib/ui2/pairing/device_picker.dart | 5 +- lib/ui2/profile/devices.dart | 32 ++- lib/ui2/profile/pair_sensor.dart | 2 + test/adapter_signals_registry_test.dart | 2 + test/band_registry_test.dart | 1 + .../support/pairing_reset_fixtures.dart | 2 + test/miband4_test.dart | 204 ++++++++++++++++++ test/pairing_device_role_test.dart | 3 +- test/reset_generation_rule_test.dart | 27 ++- test/slot_comparison_test.dart | 5 +- test/wearable_platform_test.dart | 1 + test/wearable_toggle_no_leak_test.dart | 1 + 30 files changed, 495 insertions(+), 59 deletions(-) create mode 100644 test/miband4_test.dart diff --git a/lib/ble/adapters/_registry.dart b/lib/ble/adapters/_registry.dart index cace3f2aa..4f0822011 100644 --- a/lib/ble/adapters/_registry.dart +++ b/lib/ble/adapters/_registry.dart @@ -1020,6 +1020,35 @@ const BandEntry kMiBand234 = BandEntry.notify( scanByName: true, ); +/// Mi Smart Band 4 (codename Cinco). The same legacy Huami protocol as +/// [kMiBand234] (auth on its char `0009`, the same paged minute history), +/// with two differences the adapter keys off this entry: the auth runs with +/// crypt flag `0x80`, and the band never accepts a key from this app, so +/// the user types the one its vendor pairing issued (like the Helio Strap). +/// +/// EXPERIMENTAL, and it stays that way: nobody on this project owns one +/// (ASSUMPTIONS R6). Not in [kAskPickerSensors]: one more FEE1-sharing +/// device in the iOS picker is the owner's call, not made for this one yet. +const BandEntry kMiBand4 = BandEntry.notify( + id: 'huami_cinco', + role: DeviceRole.band, + kind: DeviceKind.band, + resetSteps: ResetSteps.unverified( + officialUrl: 'https://www.mi.com/global/support/', + ), + category: DeviceCategory.wearable, + label: 'Mi Smart Band 4', + service: kHuami234Service, + characteristics: [kHuami234AuthChar], + timeAnchor: TimeAnchor.measured, + nameMatcher: _looksLikeMiBand4, + scanByName: true, +); + +/// The names Mi Band 4 advertises: its retail name and its codename. +bool _looksLikeMiBand4(String lowercaseName) => + const {'mi smart band 4', 'cinco'}.contains(lowercaseName); + /// The names Mi Band 2 and Mi Band 3 advertise. bool _looksLikeMiBand23(String lowercaseName) => const { 'mi band 2', @@ -1390,6 +1419,7 @@ const List kBandRegistry = [ kCoros, kUltrahuman, kMiBand234, + kMiBand4, kHelioStrap, kMiBand7, kAmazfitGtr3, @@ -1613,6 +1643,12 @@ const Map> kAdapterSignals = InputSignal.steps: Duration(days: 1), InputSignal.deviceStages: Duration(minutes: 1), }, + // Mi Band 4: the same adapter and the same records as Mi Band 2/3. + 'huami_cinco': { + InputSignal.hrSparse: Duration(minutes: 1), + InputSignal.steps: Duration(days: 1), + InputSignal.deviceStages: Duration(minutes: 1), + }, 'pebble': { InputSignal.hrSparse: Duration(minutes: 1), InputSignal.steps: Duration(days: 1), diff --git a/lib/ble/adapters/miband234.dart b/lib/ble/adapters/miband234.dart index 2ad8a1d79..4a74d3e6c 100644 --- a/lib/ble/adapters/miband234.dart +++ b/lib/ble/adapters/miband234.dart @@ -73,9 +73,14 @@ const List> kMiBand234ChallengeRequests = >[ [0x02, 0x00], ]; -/// Answer the challenge with its encryption under the key. -List miBand234AuthAnswer(List encrypted) => - [0x03, 0x00, ...encrypted]; +/// Answer the challenge with its encryption under the key. [cryptFlags] is +/// OR-ed into the opcode: 0 for Mi Band 2/3, 0x80 for Mi Band 4. +List miBand234AuthAnswer(List encrypted, {int cryptFlags = 0}) => + [0x03 | cryptFlags, 0x00, ...encrypted]; + +/// Mi Band 4's challenge request: opcode 0x02 with crypt flag 0x80, auth +/// flags 0x00, then `02 01 00`. +const List miBand4ChallengeRequest = [0x82, 0x00, 0x02, 0x01, 0x00]; /// Status 0x02 in an auth reply: the band was in the wrong state for the /// command, which a retry can clear; 0x04 and others are a refusal. @@ -139,6 +144,7 @@ class MiBand234Adapter extends BandAdapter { MiBand234Adapter({ required this.key, + this.entry = kMiBand234, this.needsKeyWrite = false, this.replyTimeout = const Duration(seconds: 5), this.confirmTimeout = const Duration(seconds: 30), @@ -150,12 +156,36 @@ class MiBand234Adapter extends BandAdapter { static const int kMiBandFirstFetchDays = 7; + /// [kMiBand234] or [kMiBand4]: same protocol, but Mi Band 4 authenticates + /// with crypt flag 0x80 and never takes a key from this app. @override - BandEntry get entry => kMiBand234; + final BandEntry entry; + + /// The crypt flag OR-ed into the challenge and answer opcodes: 0x80 on + /// Mi Band 4, 0 on Mi Band 2/3. + int get _cryptFlags => entry.id == kMiBand4.id ? 0x80 : 0x00; @override Map get signals => kMiBand234Signals; + /// The handshake alone, for a pairing screen proving a typed key: null when + /// the band accepted [key], else the refusing status (null status: no + /// answer). Reads and writes the auth characteristic only; nothing on the + /// band changes. + Future<({int? status})?> authenticateOnly(BandLink link) async { + final inbox = _Inbox(); + final sub = link.notify(kHuami234AuthChar).listen( + (rec) => inbox.add(Uint8List.fromList(rec.$2)), + onDone: inbox.close, + onError: (Object _) => inbox.close(), + ); + try { + return await _authenticate(link, inbox); + } finally { + await sub.cancel(); + } + } + @override Stream run(BandLink link) async* { final inbox = _Inbox(); @@ -187,7 +217,10 @@ class MiBand234Adapter extends BandAdapter { Future<({int? status})?> _authenticate( BandLink link, _Inbox inbox) async { const unanswered = (status: null); - if (needsKeyWrite) { + final crypt = _cryptFlags; + // A crypt-flagged band (Mi Band 4) never takes a key from this app: its + // key comes from the vendor pairing, so there is nothing to install. + if (needsKeyWrite && crypt == 0) { if (!await link.write(kHuami234AuthChar, miBand234KeyInstall(key))) { return unanswered; } @@ -202,10 +235,14 @@ class MiBand234Adapter extends BandAdapter { } } Uint8List? challengeFrame; - for (final request in kMiBand234ChallengeRequests) { + // Replies echo the opcode with the crypt flag set, so they are matched + // on its low nibble. + for (final request in crypt == 0 + ? kMiBand234ChallengeRequests + : >[miBand4ChallengeRequest]) { if (!await link.write(kHuami234AuthChar, request)) return unanswered; challengeFrame = await inbox.firstWhere( - (f) => f.length >= 3 && f[0] == 0x10 && f[1] == 0x02, + (f) => f.length >= 3 && f[0] == 0x10 && (f[1] & 0x0f) == 0x02, replyTimeout, ); if (challengeFrame != null && @@ -221,11 +258,12 @@ class MiBand234Adapter extends BandAdapter { } final answer = miBand234AuthResponse(key, challengeFrame.sublist(3, 19)); - if (!await link.write(kHuami234AuthChar, miBand234AuthAnswer(answer))) { + if (!await link.write( + kHuami234AuthChar, miBand234AuthAnswer(answer, cryptFlags: crypt))) { return unanswered; } final result = await inbox.firstWhere( - (f) => f.length >= 3 && f[0] == 0x10 && f[1] == 0x03, + (f) => f.length >= 3 && f[0] == 0x10 && (f[1] & 0x0f) == 0x03, replyTimeout, ); if (result == null || result[2] != 0x01) { @@ -372,7 +410,7 @@ extension on MiBand234Adapter { final got = decoded(); minutes.addAll(got.skip(banked)); for (final e in _bank(got.skip(banked), raw, minutes, sessionSince, - nowSec)) { + nowSec, entry.id)) { yield e; } banked = got.length; @@ -394,7 +432,8 @@ extension on MiBand234Adapter { if (got.length > banked) { minutes.addAll(got.skip(banked)); for (final e - in _bank(got.skip(banked), raw, minutes, sessionSince, nowSec)) { + in _bank( + got.skip(banked), raw, minutes, sessionSince, nowSec, entry.id)) { yield e; } } else if (raw.isNotEmpty) { @@ -420,7 +459,7 @@ extension on MiBand234Adapter { /// session would move the cursor past days whose steps and sleep never /// landed. The link holds the cursor behind these vendor writes. Iterable _bank(Iterable got, List raw, - List all, int sessionSince, int nowSec) sync* { + List all, int sessionSince, int nowSec, String source) sync* { yield SampleBatch([ for (final m in got) if (m.hr != null && m.hr! >= 25 && m.hr! <= 230 && m.tsSec <= nowSec) @@ -429,7 +468,7 @@ Iterable _bank(Iterable got, List raw, final epochs = []; final (nights, openSec) = _nights(all, sessionSince, epochs); final rows = [..._dailySteps(all, sessionSince), ...nights]; - if (epochs.isNotEmpty) yield VendorHypnogram(kMiBand234.id, epochs); + if (epochs.isNotEmpty) yield VendorHypnogram(source, epochs); if (rows.isNotEmpty) yield VendorScalars(rows); // From the start of the first day not read whole (the next one when the // last minute seen is 23:59), or of the day holding the awake minute before diff --git a/lib/ble/hrs_link.dart b/lib/ble/hrs_link.dart index 99126ec27..c3507ebab 100644 --- a/lib/ble/hrs_link.dart +++ b/lib/ble/hrs_link.dart @@ -973,8 +973,9 @@ class HrsLink { await UltrahumanLink.forgetRing(id); return; } - if (row?['adapter_id'] == kMiBand234.id) { - await MiBand234Link.forgetBand(id); + final miBand = MiBand234Link.forId(row?['adapter_id']); + if (miBand != null) { + await miBand.forget(id); return; } if (row?['adapter_id'] == kPebble.id) { diff --git a/lib/ble/miband_link.dart b/lib/ble/miband_link.dart index f64f003a5..8fc00b761 100644 --- a/lib/ble/miband_link.dart +++ b/lib/ble/miband_link.dart @@ -118,8 +118,22 @@ enum MiBand234SyncFailure { /// fetches history from the cursor, collects the optional channels inside a /// bounded window, and disconnects. class MiBand234Link { - MiBand234Link._(); - static final MiBand234Link instance = MiBand234Link._(); + MiBand234Link._(this.entry); + static final MiBand234Link instance = MiBand234Link._(kMiBand234); + + /// Mi Band 4 on the same link: its own `device` row, key and cursor, and + /// the crypt-flagged handshake its adapter runs for [kMiBand4]. + static final MiBand234Link miBand4 = MiBand234Link._(kMiBand4); + + /// The family this link drives. + final BandEntry entry; + + /// The link for [adapterId], or null when it is not a Mi Band. + static MiBand234Link? forId(Object? adapterId) => adapterId == kMiBand234.id + ? instance + : adapterId == kMiBand4.id + ? miBand4 + : null; /// The `device` row for the paired band, or null. static Future?> pairedRow() => @@ -198,7 +212,10 @@ class MiBand234Link { /// crash between the two here would rather leave a `device` row whose key is /// already gone (which just fails the next connect visibly) than a key /// outliving the row that was its only reason to exist. - static Future forgetBand(String id) async { + static Future forgetBand(String id) => instance.forget(id); + + /// [forgetBand] for this link's own family. + Future forget(String id) async { if (id == LocalDb.kPrimaryDeviceId) { debugPrint('[miband234] refusing to forget the primary band from here.'); return false; @@ -206,8 +223,8 @@ class MiBand234Link { // Before the first await: a sync still reading this band's row or key // has no `_deviceId` yet for the check below to match, so it learns of // the forget from this instead. - instance._forgets++; - if (instance._deviceId == id) await instance.stop(); + _forgets++; + if (_deviceId == id) await stop(); await _dropKey(id); await LocalDb.deleteDevice(id); // Nothing resumes from a forgotten id's cursor: a re-pair of the same @@ -259,7 +276,7 @@ class MiBand234Link { final resetGen = ResetGate.generation; final forgets = _forgets; lastSyncFailure = null; - final row = await pairedRow(); + final row = await pairedRowOf(entry.id); if (row == null) return false; final deviceId = row['id'] as String?; final remoteId = row['remote_id'] as String?; @@ -295,15 +312,15 @@ class MiBand234Link { await device.connect(timeout: const Duration(seconds: 20)); final services = await device.discoverServices(); final link = GattBandLink( - entry: kMiBand234, + entry: entry, services: services, onLog: (m) => debugPrint('[miband234] $m'), ); _link = link; final missing = - link.missingCharacteristics(kMiBand234.requiredCharacteristics); + link.missingCharacteristics(entry.requiredCharacteristics); if (missing.isNotEmpty) { - debugPrint('[miband234] ${kMiBand234.label}: missing required ' + debugPrint('[miband234] ${entry.label}: missing required ' 'characteristic(s) ' '${missing.map((u) => u.substring(0, 8)).join(", ")}.'); return false; @@ -313,6 +330,7 @@ class MiBand234Link { deviceId, resetGeneration: resetGen, MiBand234Adapter( + entry: entry, key: key, sinceSec: await LocalDb.getCursorInt(_sinceItem(deviceId)), nowSeconds: _now, @@ -457,6 +475,7 @@ class MiBand234Link { final host = _makeHost( deviceId, MiBand234Adapter( + entry: entry, key: key, needsKeyWrite: needsKeyWrite, replyTimeout: const Duration(milliseconds: 50), @@ -514,10 +533,11 @@ class MiBand234Link { /// A different band gets a fresh id, and its pairing forgets the old row only /// once it succeeds. String? miBandReusableDeviceId( - Iterable> rows, String remoteId) { + Iterable> rows, String remoteId, {String? adapterId}) { + final family = adapterId ?? kMiBand234.id; for (final r in rows) { final id = r['id']; - if (r['adapter_id'] == kMiBand234.id && + if (r['adapter_id'] == family && id is String && id != LocalDb.kPrimaryDeviceId && r['remote_id'] == remoteId) { @@ -817,3 +837,81 @@ Future pairMiBand234(BluetoothDevice device) async { } } } + +/// Pair [device] as this phone's Mi Band 4 with a 16-byte key the user +/// already has (the band only answers to the key its vendor pairing issued; +/// it never takes one from this app). Null on success, or a sentence the +/// user can act on. +/// +/// READ-ONLY ON THE BAND: only the crypt-flagged handshake runs +/// ([MiBand234Adapter.authenticateOnly]), so a wrong key costs a refusal and +/// nothing else. The key is stored only after the band accepted it; a +/// failure leaves the keychain as it was. A re-pair of the same band keeps +/// its row ([miBandReusableDeviceId]). +/// +/// STILL HARDWARE-UNVERIFIED (R6). +Future pairMiBand4WithTypedKey(BluetoothDevice device, String raw) async { + final hex = raw.trim().replaceFirst(RegExp('^0x', caseSensitive: false), ''); + if (!RegExp(r'^[0-9a-fA-F]{32}$').hasMatch(hex)) { + return 'That is not a valid key: it must be exactly 32 hex characters.'; + } + final key = _unhex(hex); + if (key == null) { + return 'That is not a valid key: it must be exactly 32 hex characters.'; + } + final rnd = Random.secure(); + final deviceId = miBandReusableDeviceId( + await LocalDb.deviceRows(), device.remoteId.str, + adapterId: kMiBand4.id) ?? + '${kMiBand4.id}-${_hex(List.generate(4, (_) => rnd.nextInt(256)))}'; + 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 { + await device.connect(timeout: const Duration(seconds: 20)); + final services = await device.discoverServices(); + link = GattBandLink( + entry: kMiBand4, + services: services, + onLog: (m) => debugPrint('[${kMiBand4.id} pair] $m'), + ); + if (link.missingCharacteristics(kMiBand4.requiredCharacteristics) + .isNotEmpty) { + return 'That device does not expose the service this app speaks ' + 'for a Mi Band 4.'; + } + final refusal = + await MiBand234Adapter(entry: kMiBand4, key: key).authenticateOnly(link); + if (refusal != null) { + return refusal.status == null + ? 'The band didn’t answer. Make sure it’s close by and try again.' + : 'The band rejected this key. Double-check it and try again.'; + } + try { + await _secure.write( + key: _keyItem(deviceId), value: hex.toLowerCase(), + iOptions: _kApple, mOptions: _kMacos); + } catch (e) { + return 'The phone’s keychain is locked. Unlock the phone and try again.'; + } + await LocalDb.upsertDevice( + id: deviceId, + adapterId: kMiBand4.id, + remoteId: device.remoteId.str, + label: cleanDeviceLabel(device.platformName) ?? kMiBand4.label, + ); + return null; + } catch (e) { + return 'Could not connect: $e'; + } finally { + await link?.close(); + try { + await device.disconnect(); + } catch (_) {/* already gone */} + } + }, + ); +} diff --git a/lib/compute/inputs/canonical.dart b/lib/compute/inputs/canonical.dart index b2bc606cf..40809bdf0 100644 --- a/lib/compute/inputs/canonical.dart +++ b/lib/compute/inputs/canonical.dart @@ -1305,7 +1305,7 @@ void tagEnvelopes(Map? clinical, String? family) { Map? columnFor(String? adapterId) => switch (adapterId) { kGarminFamily => kGarminColumn, kPebbleFamily => kPebbleColumn, - kMiBandFamily => kMiBandColumn, + kMiBandFamily || kMiBand4Family => kMiBandColumn, kUltrahumanFamily => kUltrahumanColumn, kColmiFamily => kColmiColumn, kOuraFamily => kOuraColumn, @@ -1409,7 +1409,7 @@ Future>?> dayCells(String date) async { // banks rows for every sleep block it records, daytime ones included, so // the same holds for it. if (wearable.$2 == kOuraFamily || - ((wearable.$2 == kGarminFamily || wearable.$2 == kMiBandFamily) && + ((wearable.$2 == kGarminFamily || isMiBandFamily(wearable.$2)) && stored.isNotEmpty)) { for (final s in const ['deep', 'light', 'rem', 'wake']) { deviceValues.remove('${s}_min'); @@ -1781,7 +1781,7 @@ Future>> timelineObservations( Future _stagesPerFile(Object? id) async { if (id is! String) return null; final family = (await LocalDb.deviceRow(id))?['adapter_id']; - return family == kGarminFamily || family == kMiBandFamily + return family == kGarminFamily || isMiBandFamily(family) ? family as String : null; } diff --git a/lib/compute/inputs/garmin_inputs.dart b/lib/compute/inputs/garmin_inputs.dart index b952e7435..134a2c440 100644 --- a/lib/compute/inputs/garmin_inputs.dart +++ b/lib/compute/inputs/garmin_inputs.dart @@ -65,6 +65,7 @@ const Map kHrCadenceSec = { kGts3Family: 60, kPebbleFamily: 60, kMiBandFamily: 60, + kMiBand4Family: 60, kUltrahumanFamily: 300, kColmiFamily: 300, kOuraFamily: 300, @@ -86,6 +87,7 @@ const Map kMethodFamily = { kGts3Family: 'hr_1min', kPebbleFamily: 'hr_1min', kMiBandFamily: 'hr_1min', + kMiBand4Family: 'hr_1min', kUltrahumanFamily: 'hr_5min', kColmiFamily: 'hr_5min', kOuraFamily: 'hr_5min', diff --git a/lib/compute/inputs/miband_inputs.dart b/lib/compute/inputs/miband_inputs.dart index 2aa7f2fbc..db6b9240d 100644 --- a/lib/compute/inputs/miband_inputs.dart +++ b/lib/compute/inputs/miband_inputs.dart @@ -24,6 +24,17 @@ import 'pebble_inputs.dart' show rhrOnlyReadiness; /// The adapter id the host stamps on this band's `decoded_onehz` rows. const String kMiBandFamily = 'miband234'; +/// Mi Band 4: the same protocol and the same records as Mi Band 2/3 (HR in +/// its minute record, its own per-minute sleep kind, daily steps), so the +/// same column serves it. +const String kMiBand4Family = 'huami_cinco'; + +/// Every family [kMiBandColumn] serves. +const Set kMiBandFamilies = {kMiBandFamily, kMiBand4Family}; + +/// Whether [family] is one of [kMiBandFamilies]. +bool isMiBandFamily(Object? family) => kMiBandFamilies.contains(family); + /// Mi Band 2/3's column of the metric x device table (PLAN §3b), as served. final Map kMiBandColumn = { // Ours is the HR-led window off its one-a-minute HR (in bed); the band's diff --git a/lib/compute/vendor_sleep.dart b/lib/compute/vendor_sleep.dart index aad0f7ffb..c77c7c041 100644 --- a/lib/compute/vendor_sleep.dart +++ b/lib/compute/vendor_sleep.dart @@ -29,6 +29,8 @@ class VendorEpoch { /// report all four. const Map> kVendorStagesReported = { 'miband234': {'wake', 'light', 'deep'}, + // Mi Band 4: the same 4-byte minute record, so the same three stages. + 'huami_cinco': {'wake', 'light', 'deep'}, 'pebble': {'light', 'deep'}, kHrWindowNightSource: {}, }; diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 6aafdce9f..645e45c0f 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -322,7 +322,7 @@ "devicePickerBlurbPolarPmd": "Ein Polar Verity Sense oder OH1. Misst die Herzschlag-Abstände optisch und überträgt sie während eines Trainings, genau wie ein Brustgurt.", "devicePickerBlurbSensor": "Ein Brustgurt oder Armband für Herzschlag-Abstände während eines Trainings.", "devicePickerBlurbCoros": "Eine Sportuhr. Liest Akkustand und Live-Herzfrequenz – aufgezeichnete Aktivitäten bleiben auf der Uhr.", - "devicePickerBlurbMiband234": "Ein Mi Band 2 oder 3. Zuerst in Mi Fit oder Zepp entkoppeln (oder auf Werkseinstellungen zurücksetzen): Es nimmt nur einen neuen Schlüssel an, solange es keinen hat. Synchronisiert gespeicherte Herzfrequenz, Schritte und Schlaf. Wenn das Band beim Koppeln vibriert, tippe darauf, um zu bestätigen. Das Mi Band 4 braucht die Kopplung des Herstellers und wird nicht unterstützt.", + "devicePickerBlurbMiband234": "Ein Mi Band 2 oder 3. Zuerst in Mi Fit oder Zepp entkoppeln (oder auf Werkseinstellungen zurücksetzen): Es nimmt nur einen neuen Schlüssel an, solange es keinen hat. Synchronisiert gespeicherte Herzfrequenz, Schritte und Schlaf. Wenn das Band beim Koppeln vibriert, tippe darauf, um zu bestätigen.", "devicePickerBlurbGarmin": "Eine Garmin-Uhr. Synchronisiert Herzfrequenz, Schritte, Schlaf und HRV. Experimentell.", "devicePickerNoMatch": "Kein Gerät in der Nähe passt zu dieser Suche.", "devicePickerBlurbColmi": "Ein Colmi-Ring. Synchronisiert Herzfrequenz, Schlafphasen, Schritte, SpO2, HRV und Stress; Werte, die der Ring selbst berechnet, sind als Colmi-Werte gekennzeichnet. Experimentell.", diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 8aa7da6e0..cfcf3bc2c 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1404,7 +1404,7 @@ "@devicePickerBlurbCoros": { "description": "Category row subtitle for a Coros sports watch." }, - "devicePickerBlurbMiband234": "Mi Band 2 or 3: heart rate, steps and sleep. Unpair it from Mi Fit or Zepp first, or reset it. Tap the band if it buzzes. Mi Band 4 isn’t supported.", + "devicePickerBlurbMiband234": "Mi Band 2 or 3: heart rate, steps and sleep. Unpair it from Mi Fit or Zepp first, or reset it. Tap the band if it buzzes.", "@devicePickerBlurbMiband234": { "description": "Category row subtitle for a Mi Band 2/3." }, diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 2f3bb8625..84f011c82 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -2691,7 +2691,7 @@ "pairSensorStoredOnSync": "Los registros se guardan al sincronizar", "pairSensorStoredOnReading": "Las lecturas se guardan al tomarlas", "pairSensorPairingMiband234": "Emparejando… Si la pulsera vibra, tócala para confirmar.", - "devicePickerBlurbMiband234": "Mi Band 2 o 3: frecuencia cardíaca, pasos y sueño. Desvincúlala primero de Mi Fit o Zepp, o restablécela. Toca la pulsera si vibra. La Mi Band 4 no es compatible.", + "devicePickerBlurbMiband234": "Mi Band 2 o 3: frecuencia cardíaca, pasos y sueño. Desvincúlala primero de Mi Fit o Zepp, o restablécela. Toca la pulsera si vibra.", "devicePickerBlurbUltrahuman": "Lee el anillo directamente: sin cuenta ni intercambio de claves.", "devicePickerBlurbPebble": "Solo Pebble 2 o Pebble 2 SE. Sincroniza pasos y sueño, y la frecuencia cardiaca en un Pebble 2 (el SE no tiene sensor de frecuencia cardiaca).", "pairSensorKeyReplacesTitle": "Vincular sustituye la clave de la app de Oura", diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 610c4c1e6..2aeb6fb6a 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -2660,7 +2660,7 @@ "pairSensorStoredOnSync": "Données stockées à chaque synchronisation", "pairSensorStoredOnReading": "Mesures stockées au fil des relevés", "pairSensorPairingMiband234": "Jumelage… Si le bracelet vibre, touchez-le pour confirmer.", - "devicePickerBlurbMiband234": "Un Mi Band 2 ou 3. Dissociez-le d'abord de Mi Fit ou Zepp (ou réinitialisez-le) : il n'accepte une nouvelle clé que s'il n'en a aucune. Synchronise la fréquence cardiaque, les pas et le sommeil qu'il a enregistrés. Si le bracelet vibre pendant le jumelage, touchez-le pour confirmer. Le Mi Band 4 nécessite le jumelage du fabricant et n'est pas pris en charge.", + "devicePickerBlurbMiband234": "Un Mi Band 2 ou 3. Dissociez-le d'abord de Mi Fit ou Zepp (ou réinitialisez-le) : il n'accepte une nouvelle clé que s'il n'en a aucune. Synchronise la fréquence cardiaque, les pas et le sommeil qu'il a enregistrés. Si le bracelet vibre pendant le jumelage, touchez-le pour confirmer.", "devicePickerBlurbUltrahuman": "Lit la bague directement : ni compte, ni échange de clés.", "devicePickerBlurbPebble": "Pebble 2 ou Pebble 2 SE uniquement. Synchronise les pas et le sommeil, et la fréquence cardiaque sur une Pebble 2 (la SE n'a pas de capteur de fréquence cardiaque).", "pairSensorKeyReplacesTitle": "L'appairage remplace la clé de l'app Oura", diff --git a/lib/l10n/app_hi.arb b/lib/l10n/app_hi.arb index 0ec6bdcd5..48cd0dbae 100644 --- a/lib/l10n/app_hi.arb +++ b/lib/l10n/app_hi.arb @@ -2660,7 +2660,7 @@ "pairSensorStoredOnSync": "सिंक होने पर रिकॉर्ड संग्रहीत होते हैं", "pairSensorStoredOnReading": "माप लेते ही रीडिंग संग्रहीत होती हैं", "pairSensorPairingMiband234": "पेयर हो रहा है… अगर बैंड वाइब्रेट करे, तो पुष्टि के लिए उस पर टैप करें।", - "devicePickerBlurbMiband234": "Mi Band 2 या 3। पहले इसे Mi Fit या Zepp से अनपेयर करें (या फ़ैक्टरी रीसेट करें): यह नई कुंजी तभी लेता है जब इसमें कोई कुंजी न हो। इसमें सहेजी गई हृदय गति, कदम और नींद सिंक करता है। पेयर करते समय बैंड वाइब्रेट करे, तो पुष्टि के लिए उस पर टैप करें। Mi Band 4 को निर्माता की पेयरिंग चाहिए और यह समर्थित नहीं है।", + "devicePickerBlurbMiband234": "Mi Band 2 या 3। पहले इसे Mi Fit या Zepp से अनपेयर करें (या फ़ैक्टरी रीसेट करें): यह नई कुंजी तभी लेता है जब इसमें कोई कुंजी न हो। इसमें सहेजी गई हृदय गति, कदम और नींद सिंक करता है। पेयर करते समय बैंड वाइब्रेट करे, तो पुष्टि के लिए उस पर टैप करें।", "devicePickerBlurbUltrahuman": "रिंग को सीधे पढ़ता है — कोई खाता नहीं, कोई कुंजी विनिमय नहीं।", "devicePickerBlurbPebble": "केवल Pebble 2 या Pebble 2 SE। कदम और नींद सिंक करता है, और Pebble 2 पर हृदय गति भी (SE में हृदय गति सेंसर नहीं है)।", "pairSensorKeyReplacesTitle": "पेयर करने से Oura ऐप की कुंजी बदल जाती है", diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index 50f2efccf..cde927f98 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -479,7 +479,7 @@ "devicePickerBlurbPolarPmd": "Polar Verity Sense или OH1. Оптически измеренные интервалы между ударами передаются во время тренировки, как у нагрудного датчика.", "devicePickerBlurbSensor": "Нагрудный датчик или датчик на руку для измерения интервалов между ударами во время тренировки.", "devicePickerBlurbCoros": "Спортивные часы. Читает заряд и текущий пульс; записанные тренировки остаются на часах.", - "devicePickerBlurbMiband234": "Mi Band 2 или 3: пульс, шаги и сон. Сначала отвяжите его от Mi Fit или Zepp либо сбросьте. Если браслет завибрирует, коснитесь его. Mi Band 4 не поддерживается.", + "devicePickerBlurbMiband234": "Mi Band 2 или 3: пульс, шаги и сон. Сначала отвяжите его от Mi Fit или Zepp либо сбросьте. Если браслет завибрирует, коснитесь его.", "devicePickerBlurbGarmin": "Часы Garmin. Синхронизируют пульс, шаги, сон и ВСР. Экспериментально.", "devicePickerNoMatch": "Поблизости нет устройств, подходящих под этот поиск.", "devicePickerBlurbColmi": "Кольцо Colmi. Синхронизирует пульс, стадии сна, шаги, SpO2, ВСР и стресс; значения, которые кольцо рассчитывает само, помечены как значения Colmi. Экспериментально.", diff --git a/lib/l10n/app_th.arb b/lib/l10n/app_th.arb index dd5678a78..9fa4032c7 100644 --- a/lib/l10n/app_th.arb +++ b/lib/l10n/app_th.arb @@ -1137,7 +1137,7 @@ "@devicePickerBlurbCoros": { "description": "Category row subtitle for a Coros sports watch." }, - "devicePickerBlurbMiband234": "Mi Band 2 หรือ 3: อัตราการเต้นหัวใจ ก้าว และการนอน ยกเลิกการจับคู่จาก Mi Fit หรือ Zepp ก่อน หรือรีเซ็ตอุปกรณ์ แตะสายรัดหากสั่น ยังไม่รองรับ Mi Band 4", + "devicePickerBlurbMiband234": "Mi Band 2 หรือ 3: อัตราการเต้นหัวใจ ก้าว และการนอน ยกเลิกการจับคู่จาก Mi Fit หรือ Zepp ก่อน หรือรีเซ็ตอุปกรณ์ แตะสายรัดหากสั่น", "@devicePickerBlurbMiband234": { "description": "Category row subtitle for a Mi Band 2/3." }, diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 6be0421b6..63f6eae9f 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -2660,7 +2660,7 @@ "pairSensorStoredOnSync": "同步时存储记录", "pairSensorStoredOnReading": "测量时存储读数", "pairSensorPairingMiband234": "配对中…如果手环振动,请轻点手环确认。", - "devicePickerBlurbMiband234": "Mi Band 2 或 3。请先在 Mi Fit 或 Zepp 中解除配对(或恢复出厂设置):它只有在没有密钥时才接受新密钥。同步手环保存的心率、步数和睡眠。配对时如果手环振动,请轻点手环确认。Mi Band 4 需要厂商配对,不受支持。", + "devicePickerBlurbMiband234": "Mi Band 2 或 3。请先在 Mi Fit 或 Zepp 中解除配对(或恢复出厂设置):它只有在没有密钥时才接受新密钥。同步手环保存的心率、步数和睡眠。配对时如果手环振动,请轻点手环确认。", "devicePickerBlurbUltrahuman": "直接读取戒指——无需账户,无需交换密钥。", "devicePickerBlurbPebble": "仅限 Pebble 2 或 Pebble 2 SE。同步步数和睡眠,在 Pebble 2 上还同步心率(SE 没有心率传感器)。", "pairSensorKeyReplacesTitle": "配对会替换 Oura 应用的密钥", diff --git a/lib/state/app_state.dart b/lib/state/app_state.dart index 2455bb90c..1718dbd55 100644 --- a/lib/state/app_state.dart +++ b/lib/state/app_state.dart @@ -1884,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('huami_cinco', MiBand234Link.miBand4.stop); for (final l in HelioStrapLink.all) { await bounded(l.entry.id, l.stop); } diff --git a/lib/sync/background_sync.dart b/lib/sync/background_sync.dart index dee0666b7..a4a6f3177 100644 --- a/lib/sync/background_sync.dart +++ b/lib/sync/background_sync.dart @@ -464,6 +464,11 @@ Future syncPairedSensors() async { } catch (e) { debugPrint('[bgsync] miband234 sync skipped: $e'); } + try { + await MiBand234Link.miBand4.sync(); + } catch (e) { + debugPrint('[bgsync] huami_cinco sync skipped: $e'); + } // Same piggyback, same reasoning: a bounded connect-drain window that // no-ops when nothing is paired and must never mark the WHOOP cycle // errored on its own failure. diff --git a/lib/ui2/pairing/device_picker.dart b/lib/ui2/pairing/device_picker.dart index cdb5a62c4..5cd76cbdd 100644 --- a/lib/ui2/pairing/device_picker.dart +++ b/lib/ui2/pairing/device_picker.dart @@ -49,6 +49,7 @@ import '../../ble/ble_state.dart' import '../../ble/hrs_link.dart'; import '../../ble/helio_strap_link.dart' show zeppOsTypedKeyPairFor; +import '../../ble/miband_link.dart' show pairMiBand4WithTypedKey; import '../../ble/oura_link.dart' show pairOuraRingWithTypedKey; import '../../data/db.dart' show LocalDb; import '../../l10n/app_localizations.dart'; @@ -432,6 +433,7 @@ class _DevicePickerScreenState extends State final id when id == kOura.id => pairOuraRingWithTypedKey, final id when zeppOsTypedKeyPairFor(id) != null => zeppOsTypedKeyPairFor(id), + final id when id == kMiBand4.id => pairMiBand4WithTypedKey, _ => null, }, ), @@ -939,8 +941,7 @@ String deviceCategoryBlurb(AppLocalizations? l, BandEntry e) { 'Reads the ring directly — no account, no key exchange.', 'miband234' => l?.devicePickerBlurbMiband234 ?? 'Mi Band 2 or 3: heart rate, steps and sleep. Unpair it from Mi ' - 'Fit or Zepp first, or reset it. Tap the band if it buzzes. Mi ' - 'Band 4 isn’t supported.', + 'Fit or Zepp first, or reset it. Tap the band if it buzzes.', 'pebble' => l?.devicePickerBlurbPebble ?? 'Pebble 2 or Pebble 2 SE only. Syncs steps and sleep, and heart ' 'rate on a Pebble 2 (the SE has no heart-rate sensor).', diff --git a/lib/ui2/profile/devices.dart b/lib/ui2/profile/devices.dart index e17955f31..9d5fda8f7 100644 --- a/lib/ui2/profile/devices.dart +++ b/lib/ui2/profile/devices.dart @@ -57,6 +57,7 @@ import '../../ble/adapters/_registry.dart' kAmazfitGtr3Pro, kAmazfitGts3, kMiBand234, + kMiBand4, kMiScale2, kMiScaleComposition, kOura, @@ -950,7 +951,8 @@ IconData sensorIcon(String? adapterId) => switch (adapterId) { 'ultrahuman' => LucideIcons.circle, 'thermometer' => LucideIcons.thermometer, 'miscale_bc' || 'miscale2' => LucideIcons.scale, - 'garmin' || 'miband234' || 'pebble' => LucideIcons.watch, + 'garmin' || 'miband234' || 'huami_cinco' || 'pebble' => + LucideIcons.watch, _ => LucideIcons.heartPulse, }; @@ -1297,10 +1299,19 @@ final List<({BandEntry entry, String blurb, Future Function(BluetoothDe 'still bound to Mi Fit or Zepp will refuse to pair. Unpair it from ' 'that app first, or use a factory-reset unit. If the band buzzes ' 'while pairing, tap it to confirm. Syncs its stored heart ' - 'rate, steps and sleep. (Mi Band 4 needs the vendor pairing and is ' - 'not supported.)', + 'rate, steps and sleep. (Mi Band 4 has its own entry below.)', pick: pairMiBand234, ), + ( + entry: kMiBand4, + blurb: 'A Mi Smart Band 4. First pairing still has to go through Zepp ' + 'Life or Mi Fit, which is where the band\'s key comes from; this ' + 'app can\'t install one on it. Paste that key below to pair it here ' + 'instead. Syncs its stored heart rate, steps and sleep. ' + 'Experimental.', + // Null: typed key only, like the Helio Strap. + pick: null, + ), ( entry: kHelioStrap, blurb: 'An Amazfit Helio Strap. First pairing still has to go through ' @@ -1400,7 +1411,10 @@ bool sensorCapReached(Iterable> deviceRows, ((r['remote_id'] as String?) ?? '').isNotEmpty) .toList(); final sameAdapterRewrites = adapterId != null && - (anyOfAdapter || adapterId == kOura.id || adapterId == kMiBand234.id); + (anyOfAdapter || + adapterId == kOura.id || + adapterId == kMiBand234.id || + adapterId == kMiBand4.id); for (final r in secondary) { if (repairingId != null && r['id'] == repairingId) return false; if (sameAdapterRewrites && r['adapter_id'] == adapterId) return false; @@ -2181,6 +2195,7 @@ class _DeviceDetailState extends State { 'garmin' => () => _syncGarminWatch(c), 'ultrahuman' => () => _syncUltrahumanRing(c), 'miband234' => () => _syncMiband(c), + 'huami_cinco' => () => _syncMiband(c, MiBand234Link.miBand4), 'pebble' => () => _syncPebble(c), 'colmi' => () => _syncColmiRing(c), final f when HelioStrapLink.forId(f) != null => @@ -2319,17 +2334,18 @@ Future _syncUltrahumanRing(BuildContext c) async { /// [_syncRing]: a bounded-window snapshot (no cursor, see /// `MiBand234Link`'s own header), so "synced" here means "connected and /// collected what the window allowed", not "drained everything". -Future _syncMiband(BuildContext c) async { +Future _syncMiband(BuildContext c, + [MiBand234Link? band]) async { + final link = band ?? MiBand234Link.instance; final l = AppLocalizations.of(c); final messenger = ScaffoldMessenger.maybeOf(c); messenger?.showSnackBar( SnackBar(content: Text(l?.devicesSyncing ?? 'Syncing'))); - final ok = await MiBand234Link.instance.sync(); + final ok = await link.sync(); if (!c.mounted) return; // A rejected key needs a re-pair, which no amount of moving closer fixes. final keyRejected = !ok && - MiBand234Link.instance.lastSyncFailure == - MiBand234SyncFailure.keyRejected; + link.lastSyncFailure == MiBand234SyncFailure.keyRejected; messenger?.showSnackBar(SnackBar( content: Text(ok ? (l?.devicesSynced ?? 'Synced.') diff --git a/lib/ui2/profile/pair_sensor.dart b/lib/ui2/profile/pair_sensor.dart index 96859fa30..eee00c0fd 100644 --- a/lib/ui2/profile/pair_sensor.dart +++ b/lib/ui2/profile/pair_sensor.dart @@ -65,6 +65,7 @@ import '../../ble/hrs_link.dart'; import '../../ble/ios_ble_restore.dart'; import '../../ble/helio_strap_link.dart' show zeppOsTypedKeyPairFor; +import '../../ble/miband_link.dart' show pairMiBand4WithTypedKey; import '../../ble/oura_link.dart' show pairOuraRingWithTypedKey; import '../../data/db.dart' show LocalDb; import '../../l10n/app_localizations.dart'; @@ -483,6 +484,7 @@ class _PairSensorScreenState extends State final id when id == kOura.id => pairOuraRingWithTypedKey, final id when zeppOsTypedKeyPairFor(id) != null => zeppOsTypedKeyPairFor(id), + final id when id == kMiBand4.id => pairMiBand4WithTypedKey, _ => null, }, ), diff --git a/test/adapter_signals_registry_test.dart b/test/adapter_signals_registry_test.dart index ea0aeccf4..22109197e 100644 --- a/test/adapter_signals_registry_test.dart +++ b/test/adapter_signals_registry_test.dart @@ -40,6 +40,8 @@ void main() { 'garmin': const GarminAdapter().signals, 'ultrahuman': UltrahumanAdapter().signals, 'miband234': MiBand234Adapter(key: const [0]).signals, + 'huami_cinco': + MiBand234Adapter(key: const [0], entry: kMiBand4).signals, 'pebble': kPebbleAdapter.signals, 'colmi': kColmiAdapter.signals, 'helio_strap': kHelioStrapAdapter.signals, diff --git a/test/band_registry_test.dart b/test/band_registry_test.dart index 0f736ee8a..974279cb0 100644 --- a/test/band_registry_test.dart +++ b/test/band_registry_test.dart @@ -22,6 +22,7 @@ void main() { 'coros', 'ultrahuman', 'miband234', + 'huami_cinco', 'helio_strap', 'zeppos_l66', 'zeppos_verona', diff --git a/test/guards/support/pairing_reset_fixtures.dart b/test/guards/support/pairing_reset_fixtures.dart index 924b69237..b34c0dd00 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', + 'huami_cinco': 'www.mi.com', // Mi Smart Band 4, same reviewed host as the other Xiaomi rows 'helio_strap': 'support.amazfit.com', 'zeppos_l66': 'www.mi.com', // Xiaomi / Mi Smart Band 7, same reviewed host as the other Xiaomi rows 'zeppos_verona': 'support.amazfit.com', // Amazfit GTR 3, same reviewed host as the Helio row @@ -73,6 +74,7 @@ const Set kPairingFollowUp = { 'coros', 'ultrahuman', 'miband234', + 'huami_cinco', 'helio_strap', 'zeppos_l66', 'zeppos_verona', diff --git a/test/miband4_test.dart b/test/miband4_test.dart new file mode 100644 index 000000000..f0382eb47 --- /dev/null +++ b/test/miband4_test.dart @@ -0,0 +1,204 @@ +// Mi Smart Band 4 (`kMiBand4`, codename Cinco) on the Mi Band 2/3 engine: +// the crypt-flagged handshake (0x82 / 0x83, never a key install), then the +// same minute history through the real link, then the same column through +// the real derivation engine. + +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:openstrap_edge/ble/adapters/_registry.dart'; +import 'package:openstrap_edge/ble/adapters/adapter.dart' show ReplayBandLink; +import 'package:openstrap_edge/ble/adapters/miband234.dart'; +import 'package:openstrap_edge/ble/adapters/signals.dart'; +import 'package:openstrap_edge/ble/miband_link.dart'; +import 'package:openstrap_edge/compute/derivation_engine.dart'; +import 'package:openstrap_edge/compute/inputs/canonical.dart'; +import 'package:openstrap_edge/compute/profile.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'; + +final List _key = List.generate(16, (i) => i + 1); +final List _challenge = List.generate(16, (i) => 0xa0 + i); + +/// The band's side of the crypt-flagged handshake. [accept] false answers the +/// proof with status 0x04, as a band holding a different key would. +List> _band(List w, {bool accept = true}) => switch (w[0]) { + 0x82 => [ + [0x10, 0x82, 0x01, ..._challenge], + ], + 0x83 => accept && + w.sublist(2).toString() == + miBand234AuthResponse(_key, _challenge).toString() + ? [ + [0x10, 0x83, 0x01], + ] + : [ + [0x10, 0x83, 0x04], + ], + _ => const >[], + }; + +/// Runs [authenticateOnly] against [_band], returning the result and every +/// write the adapter made. +Future<(({int? status})?, List>)> _auth(MiBand234Adapter a, + {bool accept = true}) async { + final link = ReplayBandLink(); + final writes = >[]; + final pending = a.authenticateOnly(link); + var served = 0; + var result = pending.then((r) => r); + var done = false; + result = result.whenComplete(() => done = true); + while (!done) { + await Future.delayed(const Duration(milliseconds: 2)); + while (served < link.writes.length) { + final (_, v) = link.writes[served++]; + writes.add(v); + for (final f in _band(v, accept: accept)) { + link.feed(kHuami234AuthChar, f, atSec: 0); + } + } + } + await link.close(); + return (await result, writes); +} + +void main() { + group('registry', () { + test('its own codename-keyed entry, Android only for now', () { + expect(kMiBand4.id, 'huami_cinco'); + expect(kMiBand4.service, kMiBand234.service); + expect(kBandRegistry, contains(kMiBand4)); + expect(kAskPickerSensors, isNot(contains(kMiBand4)), + reason: 'the iOS picker is the owner\'s call for this one'); + }); + + test('names: its own, and no other entry claims them', () { + for (final n in ['mi smart band 4', 'cinco']) { + final claims = [ + for (final e in kBandRegistry) + if (e.nameMatcher?.call(n) ?? false) e.id, + ]; + expect(claims, ['huami_cinco'], reason: n); + } + for (final n in ['mi band 3', 'mi smart band 5', 'mi smart band 4 nfc']) { + expect(kMiBand4.nameMatcher!(n), isFalse, reason: n); + } + }); + + test('same signals as Mi Band 2/3, in sync with kAdapterSignals', () { + final s = MiBand234Adapter(key: _key, entry: kMiBand4).signals; + expect(s, kMiBand234Signals); + expect(kAdapterSignals['huami_cinco'], s); + expect(s.containsKey(InputSignal.deviceHrv), isFalse); + }); + + test('the link and its lookup', () { + expect(MiBand234Link.miBand4.entry, kMiBand4); + expect(MiBand234Link.forId('huami_cinco'), MiBand234Link.miBand4); + expect(MiBand234Link.forId('miband234'), MiBand234Link.instance); + expect(MiBand234Link.forId('oura'), isNull); + }); + }); + + group('handshake', () { + test('Mi Band 4: 82 00 02 01 00, then 83 00 , never a key install', + () async { + final (result, writes) = await _auth( + MiBand234Adapter(key: _key, entry: kMiBand4, needsKeyWrite: true)); + expect(result, isNull, reason: 'the band accepted the key'); + expect(writes.first, [0x82, 0x00, 0x02, 0x01, 0x00]); + expect(writes.last, + [0x83, 0x00, ...miBand234AuthResponse(_key, _challenge)]); + expect(writes.any((w) => w[0] == 0x01), isFalse, + reason: 'a crypt-flagged band never takes a key from this app'); + }); + + test('Mi Band 4: a wrong key is a refusal with its status', () async { + final (result, _) = await _auth( + MiBand234Adapter(key: _key, entry: kMiBand4), accept: false); + expect(result?.status, 0x04); + }); + + test('Mi Band 2/3 still asks the old way', () async { + final link = ReplayBandLink(); + final pending = MiBand234Adapter( + key: _key, replyTimeout: const Duration(milliseconds: 20)) + .authenticateOnly(link); + await Future.delayed(const Duration(milliseconds: 10)); + expect(link.writes.first.$2, [0x02, 0x00, 0x02]); + await link.close(); + await pending; + }); + }); + + group('through the link and the engine', () { + final days = [ + for (var d = 1; d <= 4; d++) + SyntheticDay(DateTime(2026, 10, d), nightHrOffset: d < 4 ? -6 : 0), + ]; + const id = 'huami_cinco-synthetic'; + const dayId = '2026-10-04'; + const dayIds = {'2026-10-01', '2026-10-02', '2026-10-03', dayId}; + const profile = Profile(ageYears: 32, weightKg: 72, heightCm: 176, sex: 'm'); + + setUpAll(() async { + sqfliteFfiInit(); + databaseFactory = databaseFactoryFfi; + await LocalDb.close(); + LocalDb.dbName = 'miband4_test.db'; + final dir = await databaseFactory.getDatabasesPath(); + await databaseFactory.deleteDatabase(p.join(dir, LocalDb.dbName)); + await LocalDb.upsertDevice( + id: id, + adapterId: kMiBand4.id, + remoteId: 'AA:BB:CC:00:00:44', + label: kMiBand4.label); + final now = DateTime(2026, 10, 4, 22, 30); + await MiBand234Link.miBand4.ingestForTest( + id, + _key, + (_, w) => _band(w), + history: SyntheticDay.miBandHistory(days, now), + nowSeconds: () => SyntheticDay.sec(now), + window: const Duration(seconds: 5), + ); + }); + + tearDownAll(() async => LocalDb.close()); + + test('its minute HR lands under its own device id', () async { + final db = await LocalDb.instance; + final rows = await db.query('decoded_onehz', + where: 'device_id = ?', whereArgs: [id], limit: 5); + expect(rows, isNotEmpty); + }); + + test('flag off: no number; flag on: the Mi Band column', () async { + await LocalDb.setCursor(kActiveWearableCursor, id); + expect(await DerivationEngine().runDays(profile, {dayId}, force: true), 0); + expect(await LocalDb.dayResult(dayId), isNull); + + await LocalDb.setCursor(wearableEnabledCursor(kMiBand4.id), '1'); + for (var i = 0; i < 2; i++) { + expect(await DerivationEngine().runDays(profile, dayIds, force: true), 4); + } + final cells = (await dayCells(dayId))!; + String cls(String row) => cells[row]!['class'] as String; + expect(cls('resting_hr'), 'ours'); + expect(cls('strain'), 'ours'); + expect(cls('readiness'), 'estimated'); + expect(cls('sleep_stages'), 'device'); + for (final r in ['hrv', 'respiratory_rate', 'spo2', 'stress', 'skin_temp']) { + expect(cls(r), 'unavailable', reason: r); + } + final payload = (jsonDecode( + (await LocalDb.dayResult(dayId))!['payload_json'] as String) + as Map); + expect(payload['device_family'], 'huami_cinco'); + }, timeout: const Timeout(Duration(minutes: 3))); + }); +} diff --git a/test/pairing_device_role_test.dart b/test/pairing_device_role_test.dart index 96c365ab5..568883c82 100644 --- a/test/pairing_device_role_test.dart +++ b/test/pairing_device_role_test.dart @@ -27,7 +27,8 @@ void main() { if (e.role == DeviceRole.band) e.id, }; expect(bands, { - 'gen4', 'gen5', 'oura', 'coros', 'ultrahuman', 'miband234', 'helio_strap', + 'gen4', 'gen5', 'oura', 'coros', 'ultrahuman', 'miband234', 'huami_cinco', + 'helio_strap', 'zeppos_l66', 'zeppos_verona', 'zeppos_madrid', 'zeppos_zurich', 'pebble', 'colmi', 'garmin', }); diff --git a/test/reset_generation_rule_test.dart b/test/reset_generation_rule_test.dart index a0db3601f..452747026 100644 --- a/test/reset_generation_rule_test.dart +++ b/test/reset_generation_rule_test.dart @@ -296,18 +296,27 @@ void main() { }); test('a forget during the key read stops a keyed sync from connecting', () { - for (final (f, forget) in [ - ('miband', 'static Future forgetBand(String id) async {'), - ('oura', 'static Future forgetRing(String id) async {'), - ('colmi', 'static Future forgetRing(String id) async {'), - ('coros', 'static Future forget(String id) async {'), - ('garmin', 'static Future forget(String id) async {'), - ('pebble', 'static Future forgetPebble(String id) async {'), - ('ultrahuman', 'static Future forgetRing(String id) async {'), + // Mi Band's forget is per link (Mi Band 2/3 and Mi Band 4 each have one), + // so it bumps its own count rather than the singleton's. + for (final (f, forget, bumpText) in [ + ('miband', ' Future forget(String id) async {', ' _forgets++;'), + ('oura', 'static Future forgetRing(String id) async {', + 'instance._forgets++;'), + ('colmi', 'static Future forgetRing(String id) async {', + 'instance._forgets++;'), + ('coros', 'static Future forget(String id) async {', + 'instance._forgets++;'), + ('garmin', 'static Future forget(String id) async {', + 'instance._forgets++;'), + ('pebble', 'static Future forgetPebble(String id) async {', + 'instance._forgets++;'), + ('ultrahuman', 'static Future forgetRing(String id) async {', + 'instance._forgets++;'), ]) { final src = _read('lib/ble/${f}_link.dart'); final fg = src.indexOf(forget); - final bump = src.indexOf('instance._forgets++;', fg); + expect(fg, greaterThanOrEqualTo(0), reason: '$f: no forget found'); + final bump = src.indexOf(bumpText, fg); expect(bump, greaterThan(fg), reason: f); expect(bump, lessThan(src.indexOf('await ', fg)), reason: '$f bumps the count after an await'); diff --git a/test/slot_comparison_test.dart b/test/slot_comparison_test.dart index 759d32648..39fa0dc8a 100644 --- a/test/slot_comparison_test.dart +++ b/test/slot_comparison_test.dart @@ -88,12 +88,13 @@ void main() { }); group('wearables fill every day (the active wearable)', () { - test('the eleven columned entries are found (control for the loops below)', + test('the twelve columned entries are found (control for the loops below)', () { // the helio and zepp os columns are the declaration-built one // (sparseColumn). expect({for (final e in _columnEntries()) e.id}, {'garmin', 'pebble', - 'miband234', 'ultrahuman', 'colmi', 'oura', 'helio_strap', + 'miband234', 'huami_cinco', 'ultrahuman', 'colmi', 'oura', + 'helio_strap', 'zeppos_l66', 'zeppos_verona', 'zeppos_madrid', 'zeppos_zurich'}); }); diff --git a/test/wearable_platform_test.dart b/test/wearable_platform_test.dart index 11e563639..956d9f9e2 100644 --- a/test/wearable_platform_test.dart +++ b/test/wearable_platform_test.dart @@ -52,6 +52,7 @@ void main() { 'coros': DeviceCategory.workoutSensor, 'ultrahuman': DeviceCategory.wearable, 'miband234': DeviceCategory.wearable, + 'huami_cinco': DeviceCategory.wearable, 'pebble': DeviceCategory.wearable, 'colmi': DeviceCategory.wearable, 'helio_strap': DeviceCategory.wearable, diff --git a/test/wearable_toggle_no_leak_test.dart b/test/wearable_toggle_no_leak_test.dart index 44151d362..254ed7de2 100644 --- a/test/wearable_toggle_no_leak_test.dart +++ b/test/wearable_toggle_no_leak_test.dart @@ -26,6 +26,7 @@ const List _families = [ 'garmin', 'pebble', 'miband234', + 'huami_cinco', 'colmi', 'oura', 'helio_strap', From acc1305e40b9870d95878cb5389e8e6493f302c8 Mon Sep 17 00:00:00 2001 From: Mohammad Abdul Sahil <127765312+abdulsaheel@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:30:16 +0530 Subject: [PATCH 06/22] mi band 4 in the ios picker same shared-fee1 risk as the helio strap and mi band 7, now accepted for this one too. sits before the strap so fee1 still reads as the strap. --- ios/Runner/Info.plist | 4 ++++ lib/ble/adapters/_registry.dart | 10 ++++++++-- test/miband4_test.dart | 7 +++++-- 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist index 63f128142..12661b584 100644 --- a/ios/Runner/Info.plist +++ b/ios/Runner/Info.plist @@ -70,6 +70,7 @@ FEE1 FEE1 FEE1 + FEE1 FED9 6A4E2800-667B-11E3-949A-0800200C9A66 1809 @@ -114,6 +115,8 @@ FEE1 Mi Band 2/3 FEE1 + Mi Smart Band 4 + FEE1 Xiaomi Smart Band 7 FEE1 Amazfit GTR 3 @@ -158,6 +161,7 @@ FEE1 FEE1 FEE1 + FEE1 FED9 6A4E2800-667B-11E3-949A-0800200C9A66 1809 diff --git a/lib/ble/adapters/_registry.dart b/lib/ble/adapters/_registry.dart index 4f0822011..3fdfd508c 100644 --- a/lib/ble/adapters/_registry.dart +++ b/lib/ble/adapters/_registry.dart @@ -1027,8 +1027,8 @@ const BandEntry kMiBand234 = BandEntry.notify( /// the user types the one its vendor pairing issued (like the Helio Strap). /// /// EXPERIMENTAL, and it stays that way: nobody on this project owns one -/// (ASSUMPTIONS R6). Not in [kAskPickerSensors]: one more FEE1-sharing -/// device in the iOS picker is the owner's call, not made for this one yet. +/// (ASSUMPTIONS R6). In [kAskPickerSensors] under the shared-FEE1 risk +/// written up there. const BandEntry kMiBand4 = BandEntry.notify( id: 'huami_cinco', role: DeviceRole.band, @@ -1486,6 +1486,11 @@ final List kFramedBands = /// more FEE1 devices, told apart only by the names they advertise. They sit /// before [kHelioStrap] so the FEE1 label the picker shows stays the strap's. /// +/// [kMiBand4] is listed under the same owner-accepted risk (owner decision +/// 2026-11-23): one more FEE1 device, told apart only by the name it +/// advertises. It sits before [kHelioStrap] so the FEE1 label the picker +/// shows stays the strap'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 @@ -1503,6 +1508,7 @@ const List kAskPickerSensors = [ kColmi, kUltrahuman, kMiBand234, + kMiBand4, kMiBand7, kAmazfitGtr3, kAmazfitGtr3Pro, diff --git a/test/miband4_test.dart b/test/miband4_test.dart index f0382eb47..250950223 100644 --- a/test/miband4_test.dart +++ b/test/miband4_test.dart @@ -72,8 +72,11 @@ void main() { expect(kMiBand4.id, 'huami_cinco'); expect(kMiBand4.service, kMiBand234.service); expect(kBandRegistry, contains(kMiBand4)); - expect(kAskPickerSensors, isNot(contains(kMiBand4)), - reason: 'the iOS picker is the owner\'s call for this one'); + expect(kAskPickerSensors, contains(kMiBand4)); + expect( + kAskPickerSensors.indexOf(kMiBand4), + lessThan(kAskPickerSensors.indexOf(kHelioStrap)), + reason: 'the FEE1 label the picker shows stays the strap\'s'); }); test('names: its own, and no other entry claims them', () { From 0de3b92e49b0a175eef47f9f60b48df23e2960c1 Mon Sep 17 00:00:00 2001 From: Mohammad Abdul Sahil <127765312+abdulsaheel@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:46:42 +0530 Subject: [PATCH 07/22] mi band 5 and 6 (kongming, pangu): typed key, 8-byte minutes, on the mi band 4 path same crypt-flagged handshake and vendor key as mi band 4; minute records are 8 bytes, the first four read the same. needs the protocol 8-byte minutes() (huami8). beta, flag off, not in pe-1. --- lib/ble/adapters/_registry.dart | 53 ++++++ lib/ble/adapters/miband234.dart | 22 ++- lib/ble/miband_link.dart | 54 +++--- lib/compute/inputs/canonical.dart | 2 +- lib/compute/inputs/garmin_inputs.dart | 4 + lib/compute/inputs/miband_inputs.dart | 12 +- lib/compute/vendor_sleep.dart | 4 + lib/state/app_state.dart | 5 +- lib/sync/background_sync.dart | 15 +- lib/ui2/pairing/device_picker.dart | 5 +- lib/ui2/profile/devices.dart | 30 +++- lib/ui2/profile/pair_sensor.dart | 5 +- test/adapter_signals_registry_test.dart | 4 + test/band_registry_test.dart | 2 + .../support/pairing_reset_fixtures.dart | 4 + test/miband56_test.dart | 160 ++++++++++++++++++ test/pairing_device_role_test.dart | 1 + test/reset_quiesces_ingest_test.dart | 2 +- test/slot_comparison_test.dart | 6 +- test/support/synthetic_day.dart | 7 +- test/wearable_platform_test.dart | 2 + test/wearable_toggle_no_leak_test.dart | 2 + 22 files changed, 348 insertions(+), 53 deletions(-) create mode 100644 test/miband56_test.dart diff --git a/lib/ble/adapters/_registry.dart b/lib/ble/adapters/_registry.dart index 3fdfd508c..f2b7c2b73 100644 --- a/lib/ble/adapters/_registry.dart +++ b/lib/ble/adapters/_registry.dart @@ -1049,6 +1049,47 @@ const BandEntry kMiBand4 = BandEntry.notify( bool _looksLikeMiBand4(String lowercaseName) => const {'mi smart band 4', 'cinco'}.contains(lowercaseName); +/// Mi Smart Band 5 (codename Kongming): [kMiBand4]'s protocol, auth and +/// typed vendor key, with 8-byte minute records instead of 4 (the first four +/// bytes are the same). EXPERIMENTAL (ASSUMPTIONS R6), not in the iOS picker. +const BandEntry kMiBand5 = BandEntry.notify( + id: 'huami_kongming', + role: DeviceRole.band, + kind: DeviceKind.band, + resetSteps: ResetSteps.unverified( + officialUrl: 'https://www.mi.com/global/support/', + ), + category: DeviceCategory.wearable, + label: 'Mi Smart Band 5', + service: kHuami234Service, + characteristics: [kHuami234AuthChar], + timeAnchor: TimeAnchor.measured, + nameMatcher: _looksLikeMiBand5, + scanByName: true, +); + +/// Mi Smart Band 6 (codename Pangu): see [kMiBand5]. +const BandEntry kMiBand6 = BandEntry.notify( + id: 'huami_pangu', + role: DeviceRole.band, + kind: DeviceKind.band, + resetSteps: ResetSteps.unverified( + officialUrl: 'https://www.mi.com/global/support/', + ), + category: DeviceCategory.wearable, + label: 'Mi Smart Band 6', + service: kHuami234Service, + characteristics: [kHuami234AuthChar], + timeAnchor: TimeAnchor.measured, + nameMatcher: _looksLikeMiBand6, + scanByName: true, +); + +bool _looksLikeMiBand5(String n) => + const {'mi smart band 5', 'kongming'}.contains(n); +bool _looksLikeMiBand6(String n) => + const {'mi smart band 6', 'pangu'}.contains(n); + /// The names Mi Band 2 and Mi Band 3 advertise. bool _looksLikeMiBand23(String lowercaseName) => const { 'mi band 2', @@ -1420,6 +1461,8 @@ const List kBandRegistry = [ kUltrahuman, kMiBand234, kMiBand4, + kMiBand5, + kMiBand6, kHelioStrap, kMiBand7, kAmazfitGtr3, @@ -1655,6 +1698,16 @@ const Map> kAdapterSignals = InputSignal.steps: Duration(days: 1), InputSignal.deviceStages: Duration(minutes: 1), }, + 'huami_kongming': { + InputSignal.hrSparse: Duration(minutes: 1), + InputSignal.steps: Duration(days: 1), + InputSignal.deviceStages: Duration(minutes: 1), + }, + 'huami_pangu': { + InputSignal.hrSparse: Duration(minutes: 1), + InputSignal.steps: Duration(days: 1), + InputSignal.deviceStages: Duration(minutes: 1), + }, 'pebble': { InputSignal.hrSparse: Duration(minutes: 1), InputSignal.steps: Duration(days: 1), diff --git a/lib/ble/adapters/miband234.dart b/lib/ble/adapters/miband234.dart index 4a74d3e6c..bcef2e289 100644 --- a/lib/ble/adapters/miband234.dart +++ b/lib/ble/adapters/miband234.dart @@ -162,8 +162,15 @@ class MiBand234Adapter extends BandAdapter { final BandEntry entry; /// The crypt flag OR-ed into the challenge and answer opcodes: 0x80 on - /// Mi Band 4, 0 on Mi Band 2/3. - int get _cryptFlags => entry.id == kMiBand4.id ? 0x80 : 0x00; + /// Mi Band 4, 5 and 6, 0 on Mi Band 2/3. + int get _cryptFlags => + {kMiBand4.id, kMiBand5.id, kMiBand6.id}.contains(entry.id) + ? 0x80 + : 0x00; + + /// Bytes per stored minute: 8 on Mi Band 5 and 6, 4 on the others. + int get _recordSize => + {kMiBand5.id, kMiBand6.id}.contains(entry.id) ? 8 : 4; @override Map get signals => kMiBand234Signals; @@ -375,15 +382,17 @@ extension on MiBand234Adapter { if (!await link.write(kHuamiActivityControlChar, kHuamiActivityFetchData)) { break; } - // The header counts 4-byte minute samples, not bytes. - final want = start.count * 4; + // The header counts minute samples, not bytes. + final recordSize = _recordSize; + final want = start.count * recordSize; final buf = HuamiActivityBuffer(); var raw = []; final previousKind = minutes.isEmpty ? 1 : minutes.last.kind; // How many of this round's minutes are already banked. var banked = 0; List decoded() => buf - .minutes(start.startSec, previousKind: previousKind) + .minutes(start.startSec, + previousKind: previousKind, recordSize: recordSize) .take(start.count) .toList(); // Ends with all the announced samples, or shortly after the band's @@ -406,7 +415,8 @@ extension on MiBand234Adapter { // A first sync answers one fetch with up to a week in one round: // bank it a day at a time, so a session the sync window (or a // drop) cuts mid-round still keeps, and resumes after, what came. - if (buf.ok && buf.bytes.length ~/ 4 - banked >= _kBankEveryMinutes) { + if (buf.ok && + buf.bytes.length ~/ recordSize - banked >= _kBankEveryMinutes) { final got = decoded(); minutes.addAll(got.skip(banked)); for (final e in _bank(got.skip(banked), raw, minutes, sessionSince, diff --git a/lib/ble/miband_link.dart b/lib/ble/miband_link.dart index 8fc00b761..38b769e8c 100644 --- a/lib/ble/miband_link.dart +++ b/lib/ble/miband_link.dart @@ -124,16 +124,22 @@ class MiBand234Link { /// Mi Band 4 on the same link: its own `device` row, key and cursor, and /// the crypt-flagged handshake its adapter runs for [kMiBand4]. static final MiBand234Link miBand4 = MiBand234Link._(kMiBand4); + static final MiBand234Link miBand5 = MiBand234Link._(kMiBand5); + static final MiBand234Link miBand6 = MiBand234Link._(kMiBand6); + + /// Every Mi Band link, so app-wide stop / background sync loop over them. + static final List all = [instance, miBand4, miBand5, miBand6]; /// The family this link drives. final BandEntry entry; /// The link for [adapterId], or null when it is not a Mi Band. - static MiBand234Link? forId(Object? adapterId) => adapterId == kMiBand234.id - ? instance - : adapterId == kMiBand4.id - ? miBand4 - : null; + static MiBand234Link? forId(Object? adapterId) { + for (final l in all) { + if (l.entry.id == adapterId) return l; + } + return null; + } /// The `device` row for the paired band, or null. static Future?> pairedRow() => @@ -838,10 +844,19 @@ Future pairMiBand234(BluetoothDevice device) async { } } -/// Pair [device] as this phone's Mi Band 4 with a 16-byte key the user -/// already has (the band only answers to the key its vendor pairing issued; -/// it never takes one from this app). Null on success, or a sentence the -/// user can act on. +/// The typed-key pairing function for [adapterId] when it is a Mi Band that +/// only answers to a vendor-issued key (Mi Band 4, 5, 6), else null. +Future Function(BluetoothDevice, String)? miBandTypedKeyPairFor( + String adapterId) { + final link = MiBand234Link.forId(adapterId); + if (link == null || link.entry.id == kMiBand234.id) return null; + return (device, raw) => _pairCryptMiBandWithTypedKey(device, raw, link.entry); +} + +/// Pair [device] as this phone's [entry] (Mi Band 4, 5 or 6) with a 16-byte +/// key the user already has (the band only answers to the key its vendor +/// pairing issued; it never takes one from this app). Null on success, or a +/// sentence the user can act on. /// /// READ-ONLY ON THE BAND: only the crypt-flagged handshake runs /// ([MiBand234Adapter.authenticateOnly]), so a wrong key costs a refusal and @@ -850,7 +865,8 @@ Future pairMiBand234(BluetoothDevice device) async { /// its row ([miBandReusableDeviceId]). /// /// STILL HARDWARE-UNVERIFIED (R6). -Future pairMiBand4WithTypedKey(BluetoothDevice device, String raw) async { +Future _pairCryptMiBandWithTypedKey( + BluetoothDevice device, String raw, BandEntry entry) async { final hex = raw.trim().replaceFirst(RegExp('^0x', caseSensitive: false), ''); if (!RegExp(r'^[0-9a-fA-F]{32}$').hasMatch(hex)) { return 'That is not a valid key: it must be exactly 32 hex characters.'; @@ -862,8 +878,8 @@ Future pairMiBand4WithTypedKey(BluetoothDevice device, String raw) asyn final rnd = Random.secure(); final deviceId = miBandReusableDeviceId( await LocalDb.deviceRows(), device.remoteId.str, - adapterId: kMiBand4.id) ?? - '${kMiBand4.id}-${_hex(List.generate(4, (_) => rnd.nextInt(256)))}'; + adapterId: entry.id) ?? + '${entry.id}-${_hex(List.generate(4, (_) => rnd.nextInt(256)))}'; return withSecondaryLinkSlot( timeout: const Duration(seconds: 30), onTimeout: () => 'Another sensor is using this phone’s Bluetooth right ' @@ -874,17 +890,17 @@ Future pairMiBand4WithTypedKey(BluetoothDevice device, String raw) asyn await device.connect(timeout: const Duration(seconds: 20)); final services = await device.discoverServices(); link = GattBandLink( - entry: kMiBand4, + entry: entry, services: services, - onLog: (m) => debugPrint('[${kMiBand4.id} pair] $m'), + onLog: (m) => debugPrint('[${entry.id} pair] $m'), ); - if (link.missingCharacteristics(kMiBand4.requiredCharacteristics) + if (link.missingCharacteristics(entry.requiredCharacteristics) .isNotEmpty) { return 'That device does not expose the service this app speaks ' - 'for a Mi Band 4.'; + 'for a ${entry.label}.'; } final refusal = - await MiBand234Adapter(entry: kMiBand4, key: key).authenticateOnly(link); + await MiBand234Adapter(entry: entry, key: key).authenticateOnly(link); if (refusal != null) { return refusal.status == null ? 'The band didn’t answer. Make sure it’s close by and try again.' @@ -899,9 +915,9 @@ Future pairMiBand4WithTypedKey(BluetoothDevice device, String raw) asyn } await LocalDb.upsertDevice( id: deviceId, - adapterId: kMiBand4.id, + adapterId: entry.id, remoteId: device.remoteId.str, - label: cleanDeviceLabel(device.platformName) ?? kMiBand4.label, + label: cleanDeviceLabel(device.platformName) ?? entry.label, ); return null; } catch (e) { diff --git a/lib/compute/inputs/canonical.dart b/lib/compute/inputs/canonical.dart index 40809bdf0..d75d53956 100644 --- a/lib/compute/inputs/canonical.dart +++ b/lib/compute/inputs/canonical.dart @@ -1305,7 +1305,7 @@ void tagEnvelopes(Map? clinical, String? family) { Map? columnFor(String? adapterId) => switch (adapterId) { kGarminFamily => kGarminColumn, kPebbleFamily => kPebbleColumn, - kMiBandFamily || kMiBand4Family => kMiBandColumn, + final String f when isMiBandFamily(f) => kMiBandColumn, kUltrahumanFamily => kUltrahumanColumn, kColmiFamily => kColmiColumn, kOuraFamily => kOuraColumn, diff --git a/lib/compute/inputs/garmin_inputs.dart b/lib/compute/inputs/garmin_inputs.dart index 134a2c440..0c1aa280d 100644 --- a/lib/compute/inputs/garmin_inputs.dart +++ b/lib/compute/inputs/garmin_inputs.dart @@ -66,6 +66,8 @@ const Map kHrCadenceSec = { kPebbleFamily: 60, kMiBandFamily: 60, kMiBand4Family: 60, + kMiBand5Family: 60, + kMiBand6Family: 60, kUltrahumanFamily: 300, kColmiFamily: 300, kOuraFamily: 300, @@ -88,6 +90,8 @@ const Map kMethodFamily = { kPebbleFamily: 'hr_1min', kMiBandFamily: 'hr_1min', kMiBand4Family: 'hr_1min', + kMiBand5Family: 'hr_1min', + kMiBand6Family: 'hr_1min', kUltrahumanFamily: 'hr_5min', kColmiFamily: 'hr_5min', kOuraFamily: 'hr_5min', diff --git a/lib/compute/inputs/miband_inputs.dart b/lib/compute/inputs/miband_inputs.dart index db6b9240d..35a985d0d 100644 --- a/lib/compute/inputs/miband_inputs.dart +++ b/lib/compute/inputs/miband_inputs.dart @@ -29,8 +29,18 @@ const String kMiBandFamily = 'miband234'; /// same column serves it. const String kMiBand4Family = 'huami_cinco'; +/// Mi Band 5 and 6: the same minute record in an 8-byte slot (the first +/// four bytes read the same), so the same column serves them too. +const String kMiBand5Family = 'huami_kongming'; +const String kMiBand6Family = 'huami_pangu'; + /// Every family [kMiBandColumn] serves. -const Set kMiBandFamilies = {kMiBandFamily, kMiBand4Family}; +const Set kMiBandFamilies = { + kMiBandFamily, + kMiBand4Family, + kMiBand5Family, + kMiBand6Family, +}; /// Whether [family] is one of [kMiBandFamilies]. bool isMiBandFamily(Object? family) => kMiBandFamilies.contains(family); diff --git a/lib/compute/vendor_sleep.dart b/lib/compute/vendor_sleep.dart index c77c7c041..430d21c3a 100644 --- a/lib/compute/vendor_sleep.dart +++ b/lib/compute/vendor_sleep.dart @@ -31,6 +31,10 @@ const Map> kVendorStagesReported = { 'miband234': {'wake', 'light', 'deep'}, // Mi Band 4: the same 4-byte minute record, so the same three stages. 'huami_cinco': {'wake', 'light', 'deep'}, + // Mi Band 5 and 6: the sleep kind is read off the same first four bytes, + // so the same three stages (the rest of their record is not decoded). + 'huami_kongming': {'wake', 'light', 'deep'}, + 'huami_pangu': {'wake', 'light', 'deep'}, 'pebble': {'light', 'deep'}, kHrWindowNightSource: {}, }; diff --git a/lib/state/app_state.dart b/lib/state/app_state.dart index 1718dbd55..0df5eb098 100644 --- a/lib/state/app_state.dart +++ b/lib/state/app_state.dart @@ -1883,8 +1883,9 @@ class AppState extends ChangeNotifier { await bounded('ultrahuman', UltrahumanLink.instance.stop); await bounded('colmi', ColmiLink.instance.stop); await bounded('garmin', GarminLink.instance.stop); - await bounded('miband234', MiBand234Link.instance.stop); - await bounded('huami_cinco', MiBand234Link.miBand4.stop); + for (final l in MiBand234Link.all) { + await bounded(l.entry.id, l.stop); + } for (final l in HelioStrapLink.all) { await bounded(l.entry.id, l.stop); } diff --git a/lib/sync/background_sync.dart b/lib/sync/background_sync.dart index a4a6f3177..f04bbcbb7 100644 --- a/lib/sync/background_sync.dart +++ b/lib/sync/background_sync.dart @@ -459,15 +459,12 @@ Future syncPairedSensors() async { // also no-ops when nothing is paired and never throws, but guard it // anyway so a surprise failure here still can't mark the WHOOP cycle // errored. - try { - await MiBand234Link.instance.sync(); - } catch (e) { - debugPrint('[bgsync] miband234 sync skipped: $e'); - } - try { - await MiBand234Link.miBand4.sync(); - } catch (e) { - debugPrint('[bgsync] huami_cinco sync skipped: $e'); + for (final link in MiBand234Link.all) { + try { + await link.sync(); + } catch (e) { + debugPrint('[bgsync] ${link.entry.id} sync skipped: $e'); + } } // Same piggyback, same reasoning: a bounded connect-drain window that // no-ops when nothing is paired and must never mark the WHOOP cycle diff --git a/lib/ui2/pairing/device_picker.dart b/lib/ui2/pairing/device_picker.dart index 5cd76cbdd..b174e05ac 100644 --- a/lib/ui2/pairing/device_picker.dart +++ b/lib/ui2/pairing/device_picker.dart @@ -49,7 +49,7 @@ import '../../ble/ble_state.dart' import '../../ble/hrs_link.dart'; import '../../ble/helio_strap_link.dart' show zeppOsTypedKeyPairFor; -import '../../ble/miband_link.dart' show pairMiBand4WithTypedKey; +import '../../ble/miband_link.dart' show miBandTypedKeyPairFor; import '../../ble/oura_link.dart' show pairOuraRingWithTypedKey; import '../../data/db.dart' show LocalDb; import '../../l10n/app_localizations.dart'; @@ -433,7 +433,8 @@ class _DevicePickerScreenState extends State final id when id == kOura.id => pairOuraRingWithTypedKey, final id when zeppOsTypedKeyPairFor(id) != null => zeppOsTypedKeyPairFor(id), - final id when id == kMiBand4.id => pairMiBand4WithTypedKey, + final id when miBandTypedKeyPairFor(id) != null => + miBandTypedKeyPairFor(id), _ => null, }, ), diff --git a/lib/ui2/profile/devices.dart b/lib/ui2/profile/devices.dart index 9d5fda8f7..7295dad58 100644 --- a/lib/ui2/profile/devices.dart +++ b/lib/ui2/profile/devices.dart @@ -58,6 +58,8 @@ import '../../ble/adapters/_registry.dart' kAmazfitGts3, kMiBand234, kMiBand4, + kMiBand5, + kMiBand6, kMiScale2, kMiScaleComposition, kOura, @@ -951,7 +953,8 @@ IconData sensorIcon(String? adapterId) => switch (adapterId) { 'ultrahuman' => LucideIcons.circle, 'thermometer' => LucideIcons.thermometer, 'miscale_bc' || 'miscale2' => LucideIcons.scale, - 'garmin' || 'miband234' || 'huami_cinco' || 'pebble' => + 'garmin' || 'miband234' || 'huami_cinco' || 'huami_kongming' || + 'huami_pangu' || 'pebble' => LucideIcons.watch, _ => LucideIcons.heartPulse, }; @@ -1312,6 +1315,24 @@ final List<({BandEntry entry, String blurb, Future Function(BluetoothDe // Null: typed key only, like the Helio Strap. pick: null, ), + ( + entry: kMiBand5, + blurb: 'A Mi Smart Band 5. First pairing still has to go through Zepp ' + 'Life or Mi Fit, which is where the band\'s key comes from; this ' + 'app can\'t install one on it. Paste that key below to pair it here ' + 'instead. Syncs its stored heart rate, steps and sleep. ' + 'Experimental.', + pick: null, + ), + ( + entry: kMiBand6, + blurb: 'A Mi Smart Band 6. First pairing still has to go through Zepp ' + 'Life or Mi Fit, which is where the band\'s key comes from; this ' + 'app can\'t install one on it. Paste that key below to pair it here ' + 'instead. Syncs its stored heart rate, steps and sleep. ' + 'Experimental.', + pick: null, + ), ( entry: kHelioStrap, blurb: 'An Amazfit Helio Strap. First pairing still has to go through ' @@ -1413,8 +1434,7 @@ bool sensorCapReached(Iterable> deviceRows, final sameAdapterRewrites = adapterId != null && (anyOfAdapter || adapterId == kOura.id || - adapterId == kMiBand234.id || - adapterId == kMiBand4.id); + MiBand234Link.forId(adapterId) != null); for (final r in secondary) { if (repairingId != null && r['id'] == repairingId) return false; if (sameAdapterRewrites && r['adapter_id'] == adapterId) return false; @@ -2194,8 +2214,8 @@ class _DeviceDetailState extends State { 'coros' => () => _syncCorosWatch(c), 'garmin' => () => _syncGarminWatch(c), 'ultrahuman' => () => _syncUltrahumanRing(c), - 'miband234' => () => _syncMiband(c), - 'huami_cinco' => () => _syncMiband(c, MiBand234Link.miBand4), + final f when MiBand234Link.forId(f) != null => + () => _syncMiband(c, MiBand234Link.forId(f)), 'pebble' => () => _syncPebble(c), 'colmi' => () => _syncColmiRing(c), final f when HelioStrapLink.forId(f) != null => diff --git a/lib/ui2/profile/pair_sensor.dart b/lib/ui2/profile/pair_sensor.dart index eee00c0fd..7d9b68405 100644 --- a/lib/ui2/profile/pair_sensor.dart +++ b/lib/ui2/profile/pair_sensor.dart @@ -65,7 +65,7 @@ import '../../ble/hrs_link.dart'; import '../../ble/ios_ble_restore.dart'; import '../../ble/helio_strap_link.dart' show zeppOsTypedKeyPairFor; -import '../../ble/miband_link.dart' show pairMiBand4WithTypedKey; +import '../../ble/miband_link.dart' show miBandTypedKeyPairFor; import '../../ble/oura_link.dart' show pairOuraRingWithTypedKey; import '../../data/db.dart' show LocalDb; import '../../l10n/app_localizations.dart'; @@ -484,7 +484,8 @@ class _PairSensorScreenState extends State final id when id == kOura.id => pairOuraRingWithTypedKey, final id when zeppOsTypedKeyPairFor(id) != null => zeppOsTypedKeyPairFor(id), - final id when id == kMiBand4.id => pairMiBand4WithTypedKey, + final id when miBandTypedKeyPairFor(id) != null => + miBandTypedKeyPairFor(id), _ => null, }, ), diff --git a/test/adapter_signals_registry_test.dart b/test/adapter_signals_registry_test.dart index 22109197e..f61aa0248 100644 --- a/test/adapter_signals_registry_test.dart +++ b/test/adapter_signals_registry_test.dart @@ -42,6 +42,10 @@ void main() { 'miband234': MiBand234Adapter(key: const [0]).signals, 'huami_cinco': MiBand234Adapter(key: const [0], entry: kMiBand4).signals, + 'huami_kongming': + MiBand234Adapter(key: const [0], entry: kMiBand5).signals, + 'huami_pangu': + MiBand234Adapter(key: const [0], entry: kMiBand6).signals, 'pebble': kPebbleAdapter.signals, 'colmi': kColmiAdapter.signals, 'helio_strap': kHelioStrapAdapter.signals, diff --git a/test/band_registry_test.dart b/test/band_registry_test.dart index 974279cb0..fbe1b6c4a 100644 --- a/test/band_registry_test.dart +++ b/test/band_registry_test.dart @@ -23,6 +23,8 @@ void main() { 'ultrahuman', 'miband234', 'huami_cinco', + 'huami_kongming', + 'huami_pangu', 'helio_strap', 'zeppos_l66', 'zeppos_verona', diff --git a/test/guards/support/pairing_reset_fixtures.dart b/test/guards/support/pairing_reset_fixtures.dart index b34c0dd00..d5c6be426 100644 --- a/test/guards/support/pairing_reset_fixtures.dart +++ b/test/guards/support/pairing_reset_fixtures.dart @@ -15,6 +15,8 @@ const Map kPinnedOfficialHost = { 'coros': 'support.coros.com', 'miband234': 'www.mi.com', 'huami_cinco': 'www.mi.com', // Mi Smart Band 4, same reviewed host as the other Xiaomi rows + 'huami_kongming': 'www.mi.com', // Mi Smart Band 5 + 'huami_pangu': 'www.mi.com', // Mi Smart Band 6 'helio_strap': 'support.amazfit.com', 'zeppos_l66': 'www.mi.com', // Xiaomi / Mi Smart Band 7, same reviewed host as the other Xiaomi rows 'zeppos_verona': 'support.amazfit.com', // Amazfit GTR 3, same reviewed host as the Helio row @@ -75,6 +77,8 @@ const Set kPairingFollowUp = { 'ultrahuman', 'miband234', 'huami_cinco', + 'huami_kongming', + 'huami_pangu', 'helio_strap', 'zeppos_l66', 'zeppos_verona', diff --git a/test/miband56_test.dart b/test/miband56_test.dart new file mode 100644 index 000000000..c02ad9dd2 --- /dev/null +++ b/test/miband56_test.dart @@ -0,0 +1,160 @@ +// Mi Smart Band 5 (`kMiBand5`, Kongming) and 6 (`kMiBand6`, Pangu): Mi Band +// 4's crypt-flagged handshake and typed vendor key, with 8-byte minute +// records. The 8-byte history runs through the real link into the real +// engine; its filler bytes (0x7e) must never surface as a reading. + +import 'package:flutter_test/flutter_test.dart'; +import 'package:openstrap_edge/ble/adapters/_registry.dart'; +import 'package:openstrap_edge/ble/adapters/adapter.dart' show ReplayBandLink; +import 'package:openstrap_edge/ble/adapters/miband234.dart'; +import 'package:openstrap_edge/ble/miband_link.dart'; +import 'package:openstrap_edge/compute/derivation_engine.dart'; +import 'package:openstrap_edge/compute/inputs/canonical.dart'; +import 'package:openstrap_edge/compute/profile.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'; + +final List _key = List.generate(16, (i) => i + 1); +final List _challenge = List.generate(16, (i) => 0xa0 + i); + +List> _band(List w) => switch (w[0]) { + 0x82 => [ + [0x10, 0x82, 0x01, ..._challenge], + ], + 0x83 => w.sublist(2).toString() == + miBand234AuthResponse(_key, _challenge).toString() + ? [ + [0x10, 0x83, 0x01], + ] + : [ + [0x10, 0x83, 0x04], + ], + _ => const >[], + }; + +void main() { + group('registry', () { + test('two codename-keyed entries; names claimed by exactly one entry', () { + const names = { + 'mi smart band 5': 'huami_kongming', + 'kongming': 'huami_kongming', + 'mi smart band 6': 'huami_pangu', + 'pangu': 'huami_pangu', + }; + for (final MapEntry(key: n, value: id) in names.entries) { + final claims = [ + for (final e in kBandRegistry) + if (e.nameMatcher?.call(n) ?? false) e.id, + ]; + expect(claims, [id], reason: n); + } + expect(kAskPickerSensors, isNot(contains(kMiBand5))); + expect(kAskPickerSensors, isNot(contains(kMiBand6))); + }); + + test('links, typed-key pairing, signals', () { + for (final e in [kMiBand5, kMiBand6]) { + expect(MiBand234Link.forId(e.id)?.entry, e); + expect(miBandTypedKeyPairFor(e.id), isNotNull); + expect(kAdapterSignals[e.id], + MiBand234Adapter(key: _key, entry: e).signals); + } + expect(miBandTypedKeyPairFor(kMiBand234.id), isNull, + reason: 'Mi Band 2/3 pairs on its own screen with a minted key'); + expect(MiBand234Link.all, hasLength(4)); + }); + }); + + test('Mi Band 5: the crypt-flagged challenge, no key install', () async { + final link = ReplayBandLink(); + final pending = MiBand234Adapter( + key: _key, entry: kMiBand5, needsKeyWrite: true) + .authenticateOnly(link); + var done = false; + final result = pending.whenComplete(() => done = true); + var served = 0; + while (!done) { + await Future.delayed(const Duration(milliseconds: 2)); + while (served < link.writes.length) { + for (final f in _band(link.writes[served++].$2)) { + link.feed(kHuami234AuthChar, f, atSec: 0); + } + } + } + expect(await result, isNull); + expect(link.writes.first.$2, [0x82, 0x00, 0x02, 0x01, 0x00]); + expect(link.writes.any((w) => w.$2.first == 0x01), isFalse); + await link.close(); + }); + + group('Mi Band 6: 8-byte history through the link and the engine', () { + final days = [ + for (var d = 1; d <= 4; d++) + SyntheticDay(DateTime(2026, 10, d), nightHrOffset: d < 4 ? -6 : 0), + ]; + const id = 'huami_pangu-synthetic'; + const dayId = '2026-10-04'; + const dayIds = {'2026-10-01', '2026-10-02', '2026-10-03', dayId}; + const profile = Profile(ageYears: 32, weightKg: 72, heightCm: 176, sex: 'm'); + + setUpAll(() async { + sqfliteFfiInit(); + databaseFactory = databaseFactoryFfi; + await LocalDb.close(); + LocalDb.dbName = 'miband56_test.db'; + final dir = await databaseFactory.getDatabasesPath(); + await databaseFactory.deleteDatabase(p.join(dir, LocalDb.dbName)); + await LocalDb.upsertDevice( + id: id, + adapterId: kMiBand6.id, + remoteId: 'AA:BB:CC:00:00:66', + label: kMiBand6.label); + final now = DateTime(2026, 10, 4, 22, 30); + await MiBand234Link.miBand6.ingestForTest( + id, + _key, + (_, w) => _band(w), + history: SyntheticDay.miBandHistory(days, now, recordSize: 8), + nowSeconds: () => SyntheticDay.sec(now), + window: const Duration(seconds: 5), + ); + }); + + tearDownAll(() async => LocalDb.close()); + + test('minutes land one per minute with real HR, never the filler', () async { + final db = await LocalDb.instance; + final rows = await db.query('decoded_onehz', + where: 'device_id = ?', whereArgs: [id], orderBy: 'rec_ts'); + expect(rows.length, greaterThan(60 * 24 * 3), + reason: 'about a minute each across the four days'); + final ts = [for (final r in rows) (r['rec_ts'] as num).toInt()]; + for (var i = 1; i < ts.length; i++) { + expect(ts[i] - ts[i - 1], greaterThanOrEqualTo(60)); + } + expect(rows.where((r) => r['hr'] == 0x7e), isEmpty, + reason: 'a filler byte read as HR means 4-byte decoding'); + }); + + test('flag off: nothing; flag on: the Mi Band column', () async { + await LocalDb.setCursor(kActiveWearableCursor, id); + expect(await DerivationEngine().runDays(profile, {dayId}, force: true), 0); + await LocalDb.setCursor(wearableEnabledCursor(kMiBand6.id), '1'); + for (var i = 0; i < 2; i++) { + expect(await DerivationEngine().runDays(profile, dayIds, force: true), 4); + } + final cells = (await dayCells(dayId))!; + String cls(String row) => cells[row]!['class'] as String; + expect(cls('resting_hr'), 'ours'); + expect(cls('strain'), 'ours'); + expect(cls('sleep_stages'), 'device'); + expect(cls('readiness'), 'estimated'); + for (final r in ['hrv', 'respiratory_rate', 'stress', 'skin_temp']) { + expect(cls(r), 'unavailable', reason: r); + } + }, timeout: const Timeout(Duration(minutes: 3))); + }); +} diff --git a/test/pairing_device_role_test.dart b/test/pairing_device_role_test.dart index 568883c82..032f00c97 100644 --- a/test/pairing_device_role_test.dart +++ b/test/pairing_device_role_test.dart @@ -28,6 +28,7 @@ void main() { }; expect(bands, { 'gen4', 'gen5', 'oura', 'coros', 'ultrahuman', 'miband234', 'huami_cinco', + 'huami_kongming', 'huami_pangu', 'helio_strap', 'zeppos_l66', 'zeppos_verona', 'zeppos_madrid', 'zeppos_zurich', 'pebble', 'colmi', 'garmin', diff --git a/test/reset_quiesces_ingest_test.dart b/test/reset_quiesces_ingest_test.dart index c3cecf2fe..8906038b8 100644 --- a/test/reset_quiesces_ingest_test.dart +++ b/test/reset_quiesces_ingest_test.dart @@ -154,7 +154,7 @@ void main() { 'UltrahumanLink.instance.stop', 'ColmiLink.instance.stop', 'GarminLink.instance.stop', - 'MiBand234Link.instance.stop', + 'MiBand234Link.all', 'PebbleLink.instance.stop', 'CorosLink.instance.stop', 'SessionLink.all', diff --git a/test/slot_comparison_test.dart b/test/slot_comparison_test.dart index 39fa0dc8a..be8f5c651 100644 --- a/test/slot_comparison_test.dart +++ b/test/slot_comparison_test.dart @@ -88,13 +88,13 @@ void main() { }); group('wearables fill every day (the active wearable)', () { - test('the twelve columned entries are found (control for the loops below)', + test('the fourteen columned entries are found (control for the loops below)', () { // the helio and zepp os columns are the declaration-built one // (sparseColumn). expect({for (final e in _columnEntries()) e.id}, {'garmin', 'pebble', - 'miband234', 'huami_cinco', 'ultrahuman', 'colmi', 'oura', - 'helio_strap', + 'miband234', 'huami_cinco', 'huami_kongming', 'huami_pangu', + 'ultrahuman', 'colmi', 'oura', 'helio_strap', 'zeppos_l66', 'zeppos_verona', 'zeppos_madrid', 'zeppos_zurich'}); }); diff --git a/test/support/synthetic_day.dart b/test/support/synthetic_day.dart index b8998c798..02d035b73 100644 --- a/test/support/synthetic_day.dart +++ b/test/support/synthetic_day.dart @@ -596,8 +596,10 @@ class SyntheticDay { /// characteristics) with one 4-byte record per minute: kind (deep 11, /// light/REM 9, awake-in-night 12, else 1), intensity, steps, HR. Returns /// (characteristic, bytes) notifications. [now] is the sync instant. + /// [recordSize] 8 renders Mi Band 5/6 records: the same four bytes, then + /// four filler bytes the decoder must skip. static List<(String, List)> Function(String, List) miBandHistory( - List days, DateTime now) { + List days, DateTime now, {int recordSize = 4}) { var pending = const []; return (char, w) { if (char != kHuamiActivityControlChar) return const []; @@ -620,12 +622,13 @@ class SyntheticDay { s += d.steps[k] ?? 0; } recs.addAll([kind, st == null ? 40 : 5, math.min(s, 255), d.hr[t]!]); + if (recordSize == 8) recs.addAll(const [0x7e, 0x7e, 0x7e, 0x7e]); } pending = recs; final first = DateTime.fromMillisecondsSinceEpoch( (from - from % 60) * 1000); final tz = (first.timeZoneOffset.inMinutes ~/ 15) & 0xff; - final n = recs.length ~/ 4; // the header counts minute samples + final n = recs.length ~/ recordSize; // the header counts minute samples return [ (kHuamiActivityControlChar, [ 0x10, 0x01, 0x01, n & 0xff, (n >> 8) & 0xff, (n >> 16) & 0xff, 0, diff --git a/test/wearable_platform_test.dart b/test/wearable_platform_test.dart index 956d9f9e2..a647ba353 100644 --- a/test/wearable_platform_test.dart +++ b/test/wearable_platform_test.dart @@ -53,6 +53,8 @@ void main() { 'ultrahuman': DeviceCategory.wearable, 'miband234': DeviceCategory.wearable, 'huami_cinco': DeviceCategory.wearable, + 'huami_kongming': DeviceCategory.wearable, + 'huami_pangu': DeviceCategory.wearable, 'pebble': DeviceCategory.wearable, 'colmi': DeviceCategory.wearable, 'helio_strap': DeviceCategory.wearable, diff --git a/test/wearable_toggle_no_leak_test.dart b/test/wearable_toggle_no_leak_test.dart index 254ed7de2..9489a682d 100644 --- a/test/wearable_toggle_no_leak_test.dart +++ b/test/wearable_toggle_no_leak_test.dart @@ -27,6 +27,8 @@ const List _families = [ 'pebble', 'miband234', 'huami_cinco', + 'huami_kongming', + 'huami_pangu', 'colmi', 'oura', 'helio_strap', From 53c7fa765fcefecc5e4d8601d7c3a1134e0b772f Mon Sep 17 00:00:00 2001 From: Mohammad Abdul Sahil <127765312+abdulsaheel@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:52:38 +0530 Subject: [PATCH 08/22] amazfit bip s, bip u, gts, gts 2, gtr on the mi band engine the first amazfit watches use mi band 4's crypt-flagged handshake and a typed vendor key; bip u and gts 2 send 8-byte minutes, the rest 4. exact names only, so gts doesn't claim gts 2 and gtr doesn't claim gtr 2/3. beta, flag off, not in pe-1. gtr 2 left out: it can need the newer protocol depending on firmware. --- lib/ble/adapters/_registry.dart | 118 ++++++++++++ lib/ble/adapters/miband234.dart | 26 +-- lib/ble/miband_link.dart | 18 +- lib/compute/inputs/garmin_inputs.dart | 10 + lib/compute/inputs/miband_inputs.dart | 11 ++ lib/compute/vendor_sleep.dart | 6 + lib/ui2/profile/devices.dart | 47 ++--- test/adapter_signals_registry_test.dart | 10 + test/amazfit_g1_test.dart | 172 ++++++++++++++++++ test/band_registry_test.dart | 5 + .../support/pairing_reset_fixtures.dart | 10 + test/miband56_test.dart | 2 +- test/pairing_device_role_test.dart | 2 + test/slot_comparison_test.dart | 4 +- test/wearable_platform_test.dart | 5 + test/wearable_toggle_no_leak_test.dart | 5 + 16 files changed, 415 insertions(+), 36 deletions(-) create mode 100644 test/amazfit_g1_test.dart diff --git a/lib/ble/adapters/_registry.dart b/lib/ble/adapters/_registry.dart index f2b7c2b73..f094cc291 100644 --- a/lib/ble/adapters/_registry.dart +++ b/lib/ble/adapters/_registry.dart @@ -1090,6 +1090,94 @@ bool _looksLikeMiBand5(String n) => bool _looksLikeMiBand6(String n) => const {'mi smart band 6', 'pangu'}.contains(n); +/// Amazfit Bip S (codename Tonlesap). A first-generation Amazfit watch on the +/// legacy Huami protocol: [kMiBand4]'s crypt-flagged handshake and typed +/// vendor key, 4-byte minute records. EXPERIMENTAL (ASSUMPTIONS R6), nobody +/// on this project owns one. Watches on newer firmware may answer only the +/// chunked protocol instead; that is untested. +const BandEntry kAmazfitBipS = BandEntry.notify( + id: 'huami_tonlesap', + role: DeviceRole.band, + kind: DeviceKind.watch, + resetSteps: ResetSteps.unverified(officialUrl: 'https://support.amazfit.com/'), + category: DeviceCategory.wearable, + label: 'Amazfit Bip S', + service: kHuami234Service, + characteristics: [kHuami234AuthChar], + timeAnchor: TimeAnchor.measured, + nameMatcher: _looksLikeBipS, + scanByName: true, +); + +/// Amazfit Bip U (codename Como): see [kAmazfitBipS], 8-byte records. +const BandEntry kAmazfitBipU = BandEntry.notify( + id: 'huami_como', + role: DeviceRole.band, + kind: DeviceKind.watch, + resetSteps: ResetSteps.unverified(officialUrl: 'https://support.amazfit.com/'), + category: DeviceCategory.wearable, + label: 'Amazfit Bip U', + service: kHuami234Service, + characteristics: [kHuami234AuthChar], + timeAnchor: TimeAnchor.measured, + nameMatcher: _looksLikeBipU, + scanByName: true, +); + +/// Amazfit GTS (codename Kestrel): see [kAmazfitBipS], 4-byte records. +const BandEntry kAmazfitGts = BandEntry.notify( + id: 'huami_kestrel', + role: DeviceRole.band, + kind: DeviceKind.watch, + resetSteps: ResetSteps.unverified(officialUrl: 'https://support.amazfit.com/'), + category: DeviceCategory.wearable, + label: 'Amazfit GTS', + service: kHuami234Service, + characteristics: [kHuami234AuthChar], + timeAnchor: TimeAnchor.measured, + nameMatcher: _looksLikeGts, + scanByName: true, +); + +/// Amazfit GTS 2 (codename Newton): see [kAmazfitBipS], 8-byte records. +const BandEntry kAmazfitGts2 = BandEntry.notify( + id: 'huami_newton', + role: DeviceRole.band, + kind: DeviceKind.watch, + resetSteps: ResetSteps.unverified(officialUrl: 'https://support.amazfit.com/'), + category: DeviceCategory.wearable, + label: 'Amazfit GTS 2', + service: kHuami234Service, + characteristics: [kHuami234AuthChar], + timeAnchor: TimeAnchor.measured, + nameMatcher: _looksLikeGts2, + scanByName: true, +); + +/// Amazfit GTR (codename Falcon): see [kAmazfitBipS], 4-byte records. +const BandEntry kAmazfitGtr = BandEntry.notify( + id: 'huami_falcon', + role: DeviceRole.band, + kind: DeviceKind.watch, + resetSteps: ResetSteps.unverified(officialUrl: 'https://support.amazfit.com/'), + category: DeviceCategory.wearable, + label: 'Amazfit GTR', + service: kHuami234Service, + characteristics: [kHuami234AuthChar], + timeAnchor: TimeAnchor.measured, + nameMatcher: _looksLikeGtr, + scanByName: true, +); + +// Exact names only: "amazfit gts" must not claim "amazfit gts 2", nor +// "amazfit gtr" a GTR 2 or 3. +bool _looksLikeBipS(String n) => n == 'amazfit bip s'; +bool _looksLikeBipU(String n) => n == 'amazfit bip u'; +bool _looksLikeGts(String n) => + const {'amazfit gts', 'amazfit kestrel'}.contains(n); +bool _looksLikeGts2(String n) => const {'amazfit gts 2', 'newton'}.contains(n); +bool _looksLikeGtr(String n) => n == 'amazfit gtr'; + /// The names Mi Band 2 and Mi Band 3 advertise. bool _looksLikeMiBand23(String lowercaseName) => const { 'mi band 2', @@ -1463,6 +1551,11 @@ const List kBandRegistry = [ kMiBand4, kMiBand5, kMiBand6, + kAmazfitBipS, + kAmazfitBipU, + kAmazfitGts, + kAmazfitGts2, + kAmazfitGtr, kHelioStrap, kMiBand7, kAmazfitGtr3, @@ -1708,6 +1801,31 @@ const Map> kAdapterSignals = InputSignal.steps: Duration(days: 1), InputSignal.deviceStages: Duration(minutes: 1), }, + 'huami_tonlesap': { + InputSignal.hrSparse: Duration(minutes: 1), + InputSignal.steps: Duration(days: 1), + InputSignal.deviceStages: Duration(minutes: 1), + }, + 'huami_como': { + InputSignal.hrSparse: Duration(minutes: 1), + InputSignal.steps: Duration(days: 1), + InputSignal.deviceStages: Duration(minutes: 1), + }, + 'huami_kestrel': { + InputSignal.hrSparse: Duration(minutes: 1), + InputSignal.steps: Duration(days: 1), + InputSignal.deviceStages: Duration(minutes: 1), + }, + 'huami_newton': { + InputSignal.hrSparse: Duration(minutes: 1), + InputSignal.steps: Duration(days: 1), + InputSignal.deviceStages: Duration(minutes: 1), + }, + 'huami_falcon': { + InputSignal.hrSparse: Duration(minutes: 1), + InputSignal.steps: Duration(days: 1), + InputSignal.deviceStages: Duration(minutes: 1), + }, 'pebble': { InputSignal.hrSparse: Duration(minutes: 1), InputSignal.steps: Duration(days: 1), diff --git a/lib/ble/adapters/miband234.dart b/lib/ble/adapters/miband234.dart index bcef2e289..3c130678c 100644 --- a/lib/ble/adapters/miband234.dart +++ b/lib/ble/adapters/miband234.dart @@ -156,21 +156,25 @@ class MiBand234Adapter extends BandAdapter { static const int kMiBandFirstFetchDays = 7; - /// [kMiBand234] or [kMiBand4]: same protocol, but Mi Band 4 authenticates - /// with crypt flag 0x80 and never takes a key from this app. + /// [kMiBand234] or one of the crypt-flagged entries on the same protocol + /// (Mi Band 4-6, the first Amazfit watches): those authenticate with crypt + /// flag 0x80 and never take a key from this app. @override final BandEntry entry; /// The crypt flag OR-ed into the challenge and answer opcodes: 0x80 on - /// Mi Band 4, 5 and 6, 0 on Mi Band 2/3. - int get _cryptFlags => - {kMiBand4.id, kMiBand5.id, kMiBand6.id}.contains(entry.id) - ? 0x80 - : 0x00; - - /// Bytes per stored minute: 8 on Mi Band 5 and 6, 4 on the others. - int get _recordSize => - {kMiBand5.id, kMiBand6.id}.contains(entry.id) ? 8 : 4; + /// everything but Mi Band 2/3 (Mi Band 4-6 and the first Amazfit watches). + int get _cryptFlags => entry.id == kMiBand234.id ? 0x00 : 0x80; + + /// Bytes per stored minute: 8 on Mi Band 5/6, Bip U and GTS 2, else 4. + int get _recordSize => { + kMiBand5.id, + kMiBand6.id, + kAmazfitBipU.id, + kAmazfitGts2.id, + }.contains(entry.id) + ? 8 + : 4; @override Map get signals => kMiBand234Signals; diff --git a/lib/ble/miband_link.dart b/lib/ble/miband_link.dart index 38b769e8c..60c751278 100644 --- a/lib/ble/miband_link.dart +++ b/lib/ble/miband_link.dart @@ -127,8 +127,22 @@ class MiBand234Link { static final MiBand234Link miBand5 = MiBand234Link._(kMiBand5); static final MiBand234Link miBand6 = MiBand234Link._(kMiBand6); - /// Every Mi Band link, so app-wide stop / background sync loop over them. - static final List all = [instance, miBand4, miBand5, miBand6]; + /// Every link on this engine, so app-wide stop / background sync loop over + /// them: the Mi Bands and the first Amazfit watches. + static final List all = [ + instance, + miBand4, + miBand5, + miBand6, + for (final e in [ + kAmazfitBipS, + kAmazfitBipU, + kAmazfitGts, + kAmazfitGts2, + kAmazfitGtr, + ]) + MiBand234Link._(e), + ]; /// The family this link drives. final BandEntry entry; diff --git a/lib/compute/inputs/garmin_inputs.dart b/lib/compute/inputs/garmin_inputs.dart index 0c1aa280d..790edd012 100644 --- a/lib/compute/inputs/garmin_inputs.dart +++ b/lib/compute/inputs/garmin_inputs.dart @@ -68,6 +68,11 @@ const Map kHrCadenceSec = { kMiBand4Family: 60, kMiBand5Family: 60, kMiBand6Family: 60, + 'huami_tonlesap': 60, + 'huami_como': 60, + 'huami_kestrel': 60, + 'huami_newton': 60, + 'huami_falcon': 60, kUltrahumanFamily: 300, kColmiFamily: 300, kOuraFamily: 300, @@ -92,6 +97,11 @@ const Map kMethodFamily = { kMiBand4Family: 'hr_1min', kMiBand5Family: 'hr_1min', kMiBand6Family: 'hr_1min', + 'huami_tonlesap': 'hr_1min', + 'huami_como': 'hr_1min', + 'huami_kestrel': 'hr_1min', + 'huami_newton': 'hr_1min', + 'huami_falcon': 'hr_1min', kUltrahumanFamily: 'hr_5min', kColmiFamily: 'hr_5min', kOuraFamily: 'hr_5min', diff --git a/lib/compute/inputs/miband_inputs.dart b/lib/compute/inputs/miband_inputs.dart index 35a985d0d..d3b6d4549 100644 --- a/lib/compute/inputs/miband_inputs.dart +++ b/lib/compute/inputs/miband_inputs.dart @@ -34,12 +34,23 @@ const String kMiBand4Family = 'huami_cinco'; const String kMiBand5Family = 'huami_kongming'; const String kMiBand6Family = 'huami_pangu'; +/// The first Amazfit watches on the same engine (Bip S, Bip U, GTS, GTS 2, +/// GTR): the same minute record, 4 or 8 bytes, so the same column. +const Set kAmazfitG1Families = { + 'huami_tonlesap', + 'huami_como', + 'huami_kestrel', + 'huami_newton', + 'huami_falcon', +}; + /// Every family [kMiBandColumn] serves. const Set kMiBandFamilies = { kMiBandFamily, kMiBand4Family, kMiBand5Family, kMiBand6Family, + ...kAmazfitG1Families, }; /// Whether [family] is one of [kMiBandFamilies]. diff --git a/lib/compute/vendor_sleep.dart b/lib/compute/vendor_sleep.dart index 430d21c3a..c1c0b34cb 100644 --- a/lib/compute/vendor_sleep.dart +++ b/lib/compute/vendor_sleep.dart @@ -35,6 +35,12 @@ const Map> kVendorStagesReported = { // so the same three stages (the rest of their record is not decoded). 'huami_kongming': {'wake', 'light', 'deep'}, 'huami_pangu': {'wake', 'light', 'deep'}, + // The first Amazfit watches: the same minute record, the same stages. + 'huami_tonlesap': {'wake', 'light', 'deep'}, + 'huami_como': {'wake', 'light', 'deep'}, + 'huami_kestrel': {'wake', 'light', 'deep'}, + 'huami_newton': {'wake', 'light', 'deep'}, + 'huami_falcon': {'wake', 'light', 'deep'}, 'pebble': {'light', 'deep'}, kHrWindowNightSource: {}, }; diff --git a/lib/ui2/profile/devices.dart b/lib/ui2/profile/devices.dart index 7295dad58..f1982147c 100644 --- a/lib/ui2/profile/devices.dart +++ b/lib/ui2/profile/devices.dart @@ -60,6 +60,12 @@ import '../../ble/adapters/_registry.dart' kMiBand4, kMiBand5, kMiBand6, + kAmazfitBipS, + kAmazfitBipU, + kAmazfitGts, + kAmazfitGts2, + kAmazfitGtr, + DeviceKind, kMiScale2, kMiScaleComposition, kOura, @@ -953,9 +959,8 @@ IconData sensorIcon(String? adapterId) => switch (adapterId) { 'ultrahuman' => LucideIcons.circle, 'thermometer' => LucideIcons.thermometer, 'miscale_bc' || 'miscale2' => LucideIcons.scale, - 'garmin' || 'miband234' || 'huami_cinco' || 'huami_kongming' || - 'huami_pangu' || 'pebble' => - LucideIcons.watch, + 'garmin' || 'pebble' => LucideIcons.watch, + final id when MiBand234Link.forId(id) != null => LucideIcons.watch, _ => LucideIcons.heartPulse, }; @@ -1315,24 +1320,24 @@ final List<({BandEntry entry, String blurb, Future Function(BluetoothDe // Null: typed key only, like the Helio Strap. pick: null, ), - ( - entry: kMiBand5, - blurb: 'A Mi Smart Band 5. First pairing still has to go through Zepp ' - 'Life or Mi Fit, which is where the band\'s key comes from; this ' - 'app can\'t install one on it. Paste that key below to pair it here ' - 'instead. Syncs its stored heart rate, steps and sleep. ' - 'Experimental.', - pick: null, - ), - ( - entry: kMiBand6, - blurb: 'A Mi Smart Band 6. First pairing still has to go through Zepp ' - 'Life or Mi Fit, which is where the band\'s key comes from; this ' - 'app can\'t install one on it. Paste that key below to pair it here ' - 'instead. Syncs its stored heart rate, steps and sleep. ' - 'Experimental.', - pick: null, - ), + for (final e in [ + kMiBand5, + kMiBand6, + kAmazfitBipS, + kAmazfitBipU, + kAmazfitGts, + kAmazfitGts2, + kAmazfitGtr, + ]) + ( + entry: e, + blurb: 'A ${e.label}. First pairing still has to go through ' + '${e.kind == DeviceKind.watch ? 'Zepp' : 'Zepp Life or Mi Fit'}, ' + 'which is where its key comes from; this app can\'t install one on ' + 'it. Paste that key below to pair it here instead. Syncs its stored ' + 'heart rate, steps and sleep. Experimental.', + pick: null, + ), ( entry: kHelioStrap, blurb: 'An Amazfit Helio Strap. First pairing still has to go through ' diff --git a/test/adapter_signals_registry_test.dart b/test/adapter_signals_registry_test.dart index f61aa0248..54830a042 100644 --- a/test/adapter_signals_registry_test.dart +++ b/test/adapter_signals_registry_test.dart @@ -46,6 +46,16 @@ void main() { MiBand234Adapter(key: const [0], entry: kMiBand5).signals, 'huami_pangu': MiBand234Adapter(key: const [0], entry: kMiBand6).signals, + 'huami_tonlesap': + MiBand234Adapter(key: const [0], entry: kAmazfitBipS).signals, + 'huami_como': + MiBand234Adapter(key: const [0], entry: kAmazfitBipU).signals, + 'huami_kestrel': + MiBand234Adapter(key: const [0], entry: kAmazfitGts).signals, + 'huami_newton': + MiBand234Adapter(key: const [0], entry: kAmazfitGts2).signals, + 'huami_falcon': + MiBand234Adapter(key: const [0], entry: kAmazfitGtr).signals, 'pebble': kPebbleAdapter.signals, 'colmi': kColmiAdapter.signals, 'helio_strap': kHelioStrapAdapter.signals, diff --git a/test/amazfit_g1_test.dart b/test/amazfit_g1_test.dart new file mode 100644 index 000000000..6d038b645 --- /dev/null +++ b/test/amazfit_g1_test.dart @@ -0,0 +1,172 @@ +// The first Amazfit watches (Bip S, Bip U, GTS, GTS 2, GTR) on the Mi Band +// 2/3 engine: Mi Band 4's crypt-flagged handshake and typed vendor key, with +// 4- or 8-byte minute records. Histories run through the real link into the +// real engine. + +import 'package:flutter_test/flutter_test.dart'; +import 'package:openstrap_edge/ble/adapters/_registry.dart'; +import 'package:openstrap_edge/ble/adapters/adapter.dart' show ReplayBandLink; +import 'package:openstrap_edge/ble/adapters/miband234.dart'; +import 'package:openstrap_edge/ble/miband_link.dart'; +import 'package:openstrap_edge/compute/derivation_engine.dart'; +import 'package:openstrap_edge/compute/inputs/canonical.dart'; +import 'package:openstrap_edge/compute/profile.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'; + +final List _key = List.generate(16, (i) => i + 1); +final List _challenge = List.generate(16, (i) => 0xa0 + i); + +List> _band(List w) => switch (w[0]) { + 0x82 => [ + [0x10, 0x82, 0x01, ..._challenge], + ], + 0x83 => w.sublist(2).toString() == + miBand234AuthResponse(_key, _challenge).toString() + ? [ + [0x10, 0x83, 0x01], + ] + : [ + [0x10, 0x83, 0x04], + ], + _ => const >[], + }; + +const _watches = [ + kAmazfitBipS, + kAmazfitBipU, + kAmazfitGts, + kAmazfitGts2, + kAmazfitGtr, +]; + +void main() { + test('exact names: each claimed by one entry, newer models by none', () { + const names = { + 'amazfit bip s': 'huami_tonlesap', + 'amazfit bip u': 'huami_como', + 'amazfit gts': 'huami_kestrel', + 'amazfit kestrel': 'huami_kestrel', + 'amazfit gts 2': 'huami_newton', + 'newton': 'huami_newton', + 'amazfit gtr': 'huami_falcon', + }; + List claims(String n) => [ + for (final e in kBandRegistry) + if (e.nameMatcher?.call(n) ?? false) e.id, + ]; + for (final MapEntry(key: n, value: id) in names.entries) { + expect(claims(n), [id], reason: n); + } + for (final n in ['amazfit gtr 2', 'amazfit gts 2 mini', 'amazfit bip u pro']) { + expect(claims(n).where((id) => id.startsWith('huami_')), isEmpty, + reason: n); + } + }); + + test('links, typed-key pairing, signals, watch kind', () { + for (final e in _watches) { + expect(e.kind, DeviceKind.watch); + expect(MiBand234Link.forId(e.id)?.entry, e); + expect(miBandTypedKeyPairFor(e.id), isNotNull); + expect(kAdapterSignals[e.id], + MiBand234Adapter(key: _key, entry: e).signals); + } + }); + + test('GTR: the crypt-flagged challenge, no key install', () async { + final link = ReplayBandLink(); + final pending = + MiBand234Adapter(key: _key, entry: kAmazfitGtr, needsKeyWrite: true) + .authenticateOnly(link); + var done = false; + final result = pending.whenComplete(() => done = true); + var served = 0; + while (!done) { + await Future.delayed(const Duration(milliseconds: 2)); + while (served < link.writes.length) { + for (final f in _band(link.writes[served++].$2)) { + link.feed(kHuami234AuthChar, f, atSec: 0); + } + } + } + expect(await result, isNull); + expect(link.writes.first.$2, [0x82, 0x00, 0x02, 0x01, 0x00]); + expect(link.writes.any((w) => w.$2.first == 0x01), isFalse); + await link.close(); + }); + + group('history through the link and the engine', () { + final days = [ + for (var d = 1; d <= 4; d++) + SyntheticDay(DateTime(2026, 10, d), nightHrOffset: d < 4 ? -6 : 0), + ]; + const dayId = '2026-10-04'; + const dayIds = {'2026-10-01', '2026-10-02', '2026-10-03', dayId}; + const profile = Profile(ageYears: 32, weightKg: 72, heightCm: 176, sex: 'm'); + // GTS 2 sends 8-byte minutes, GTR 4-byte ones. + const gts2 = 'huami_newton-synthetic'; + const gtr = 'huami_falcon-synthetic'; + + setUpAll(() async { + sqfliteFfiInit(); + databaseFactory = databaseFactoryFfi; + await LocalDb.close(); + LocalDb.dbName = 'amazfit_g1_test.db'; + final dir = await databaseFactory.getDatabasesPath(); + await databaseFactory.deleteDatabase(p.join(dir, LocalDb.dbName)); + final now = DateTime(2026, 10, 4, 22, 30); + for (final (id, entry, size) in [ + (gts2, kAmazfitGts2, 8), + (gtr, kAmazfitGtr, 4), + ]) { + await LocalDb.upsertDevice( + id: id, + adapterId: entry.id, + remoteId: 'AA:BB:CC:00:00:${size}0', + label: entry.label); + await MiBand234Link.forId(entry.id)!.ingestForTest( + id, + _key, + (_, w) => _band(w), + history: SyntheticDay.miBandHistory(days, now, recordSize: size), + nowSeconds: () => SyntheticDay.sec(now), + window: const Duration(seconds: 5), + ); + } + }); + + tearDownAll(() async => LocalDb.close()); + + test('both land a minute each, the 8-byte filler never as HR', () async { + final db = await LocalDb.instance; + for (final id in [gts2, gtr]) { + final rows = await db.query('decoded_onehz', + where: 'device_id = ?', whereArgs: [id], orderBy: 'rec_ts'); + expect(rows.length, greaterThan(60 * 24 * 3), reason: id); + expect(rows.where((r) => r['hr'] == 0x7e), isEmpty, reason: id); + } + }); + + test('flag off: nothing; flag on: the Mi Band column', () async { + await LocalDb.setCursor(kActiveWearableCursor, gts2); + expect(await DerivationEngine().runDays(profile, {dayId}, force: true), 0); + await LocalDb.setCursor(wearableEnabledCursor(kAmazfitGts2.id), '1'); + for (var i = 0; i < 2; i++) { + expect(await DerivationEngine().runDays(profile, dayIds, force: true), 4); + } + final cells = (await dayCells(dayId))!; + String cls(String row) => cells[row]!['class'] as String; + expect(cls('resting_hr'), 'ours'); + expect(cls('strain'), 'ours'); + expect(cls('sleep_stages'), 'device'); + expect(cls('readiness'), 'estimated'); + for (final r in ['hrv', 'respiratory_rate', 'stress', 'skin_temp']) { + expect(cls(r), 'unavailable', reason: r); + } + }, timeout: const Timeout(Duration(minutes: 3))); + }); +} diff --git a/test/band_registry_test.dart b/test/band_registry_test.dart index fbe1b6c4a..5ae8615a7 100644 --- a/test/band_registry_test.dart +++ b/test/band_registry_test.dart @@ -25,6 +25,11 @@ void main() { 'huami_cinco', 'huami_kongming', 'huami_pangu', + 'huami_tonlesap', + 'huami_como', + 'huami_kestrel', + 'huami_newton', + 'huami_falcon', 'helio_strap', 'zeppos_l66', 'zeppos_verona', diff --git a/test/guards/support/pairing_reset_fixtures.dart b/test/guards/support/pairing_reset_fixtures.dart index d5c6be426..52c33608d 100644 --- a/test/guards/support/pairing_reset_fixtures.dart +++ b/test/guards/support/pairing_reset_fixtures.dart @@ -17,6 +17,11 @@ const Map kPinnedOfficialHost = { 'huami_cinco': 'www.mi.com', // Mi Smart Band 4, same reviewed host as the other Xiaomi rows 'huami_kongming': 'www.mi.com', // Mi Smart Band 5 'huami_pangu': 'www.mi.com', // Mi Smart Band 6 + 'huami_tonlesap': 'support.amazfit.com', + 'huami_como': 'support.amazfit.com', + 'huami_kestrel': 'support.amazfit.com', + 'huami_newton': 'support.amazfit.com', + 'huami_falcon': 'support.amazfit.com', 'helio_strap': 'support.amazfit.com', 'zeppos_l66': 'www.mi.com', // Xiaomi / Mi Smart Band 7, same reviewed host as the other Xiaomi rows 'zeppos_verona': 'support.amazfit.com', // Amazfit GTR 3, same reviewed host as the Helio row @@ -79,6 +84,11 @@ const Set kPairingFollowUp = { 'huami_cinco', 'huami_kongming', 'huami_pangu', + 'huami_tonlesap', + 'huami_como', + 'huami_kestrel', + 'huami_newton', + 'huami_falcon', 'helio_strap', 'zeppos_l66', 'zeppos_verona', diff --git a/test/miband56_test.dart b/test/miband56_test.dart index c02ad9dd2..58ac3212e 100644 --- a/test/miband56_test.dart +++ b/test/miband56_test.dart @@ -64,7 +64,7 @@ void main() { } expect(miBandTypedKeyPairFor(kMiBand234.id), isNull, reason: 'Mi Band 2/3 pairs on its own screen with a minted key'); - expect(MiBand234Link.all, hasLength(4)); + expect(MiBand234Link.all, hasLength(9)); }); }); diff --git a/test/pairing_device_role_test.dart b/test/pairing_device_role_test.dart index 032f00c97..d37622f41 100644 --- a/test/pairing_device_role_test.dart +++ b/test/pairing_device_role_test.dart @@ -29,6 +29,8 @@ void main() { expect(bands, { 'gen4', 'gen5', 'oura', 'coros', 'ultrahuman', 'miband234', 'huami_cinco', 'huami_kongming', 'huami_pangu', + 'huami_tonlesap', 'huami_como', 'huami_kestrel', + 'huami_newton', 'huami_falcon', 'helio_strap', 'zeppos_l66', 'zeppos_verona', 'zeppos_madrid', 'zeppos_zurich', 'pebble', 'colmi', 'garmin', diff --git a/test/slot_comparison_test.dart b/test/slot_comparison_test.dart index be8f5c651..9ab64a5d6 100644 --- a/test/slot_comparison_test.dart +++ b/test/slot_comparison_test.dart @@ -88,12 +88,14 @@ void main() { }); group('wearables fill every day (the active wearable)', () { - test('the fourteen columned entries are found (control for the loops below)', + test('the nineteen columned entries are found (control for the loops below)', () { // the helio and zepp os columns are the declaration-built one // (sparseColumn). expect({for (final e in _columnEntries()) e.id}, {'garmin', 'pebble', 'miband234', 'huami_cinco', 'huami_kongming', 'huami_pangu', + 'huami_tonlesap', 'huami_como', 'huami_kestrel', + 'huami_newton', 'huami_falcon', 'ultrahuman', 'colmi', 'oura', 'helio_strap', 'zeppos_l66', 'zeppos_verona', 'zeppos_madrid', 'zeppos_zurich'}); }); diff --git a/test/wearable_platform_test.dart b/test/wearable_platform_test.dart index a647ba353..8a381b9fa 100644 --- a/test/wearable_platform_test.dart +++ b/test/wearable_platform_test.dart @@ -55,6 +55,11 @@ void main() { 'huami_cinco': DeviceCategory.wearable, 'huami_kongming': DeviceCategory.wearable, 'huami_pangu': DeviceCategory.wearable, + 'huami_tonlesap': DeviceCategory.wearable, + 'huami_como': DeviceCategory.wearable, + 'huami_kestrel': DeviceCategory.wearable, + 'huami_newton': DeviceCategory.wearable, + 'huami_falcon': DeviceCategory.wearable, 'pebble': DeviceCategory.wearable, 'colmi': DeviceCategory.wearable, 'helio_strap': DeviceCategory.wearable, diff --git a/test/wearable_toggle_no_leak_test.dart b/test/wearable_toggle_no_leak_test.dart index 9489a682d..f148d9130 100644 --- a/test/wearable_toggle_no_leak_test.dart +++ b/test/wearable_toggle_no_leak_test.dart @@ -29,6 +29,11 @@ const List _families = [ 'huami_cinco', 'huami_kongming', 'huami_pangu', + 'huami_tonlesap', + 'huami_como', + 'huami_kestrel', + 'huami_newton', + 'huami_falcon', 'colmi', 'oura', 'helio_strap', From e71299ea2d6d32771ddd067e0aa54ca3e28a0ed6 Mon Sep 17 00:00:00 2001 From: Mohammad Abdul Sahil <127765312+abdulsaheel@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:31:20 +0530 Subject: [PATCH 09/22] mi band 5/6 and the first amazfit watches in the ios picker same shared-fee1 risk already accepted for mi band 4 and 7; listed before the strap so fee1 still reads as the strap. separate commit so it can be dropped if the picker should stay smaller. --- ios/Runner/Info.plist | 28 ++++++++++++++++++++++++++++ lib/ble/adapters/_registry.dart | 11 ++++++++++- test/amazfit_g1_test.dart | 1 + test/miband56_test.dart | 7 +++++-- 4 files changed, 44 insertions(+), 3 deletions(-) diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist index 12661b584..93686dd1a 100644 --- a/ios/Runner/Info.plist +++ b/ios/Runner/Info.plist @@ -71,6 +71,13 @@ FEE1 FEE1 FEE1 + FEE1 + FEE1 + FEE1 + FEE1 + FEE1 + FEE1 + FEE1 FED9 6A4E2800-667B-11E3-949A-0800200C9A66 1809 @@ -117,6 +124,20 @@ FEE1 Mi Smart Band 4 FEE1 + Mi Smart Band 5 + FEE1 + Mi Smart Band 6 + FEE1 + Amazfit Bip S + FEE1 + Amazfit Bip U + FEE1 + Amazfit GTS + FEE1 + Amazfit GTS 2 + FEE1 + Amazfit GTR + FEE1 Xiaomi Smart Band 7 FEE1 Amazfit GTR 3 @@ -162,6 +183,13 @@ FEE1 FEE1 FEE1 + FEE1 + FEE1 + FEE1 + FEE1 + FEE1 + FEE1 + FEE1 FED9 6A4E2800-667B-11E3-949A-0800200C9A66 1809 diff --git a/lib/ble/adapters/_registry.dart b/lib/ble/adapters/_registry.dart index f094cc291..091bdef69 100644 --- a/lib/ble/adapters/_registry.dart +++ b/lib/ble/adapters/_registry.dart @@ -1624,7 +1624,9 @@ final List kFramedBands = /// /// [kMiBand4] is listed under the same owner-accepted risk (owner decision /// 2026-11-23): one more FEE1 device, told apart only by the name it -/// advertises. It sits before [kHelioStrap] so the FEE1 label the picker +/// advertises. [kMiBand5], [kMiBand6] and the first Amazfit watches +/// ([kAmazfitBipS] to [kAmazfitGtr]) follow it on the same reasoning. They +/// sit before [kHelioStrap] so the FEE1 label the picker /// shows stays the strap's. /// /// [kMiBand234], [kColmi], [kUltrahuman], [kMiScaleComposition] and @@ -1645,6 +1647,13 @@ const List kAskPickerSensors = [ kUltrahuman, kMiBand234, kMiBand4, + kMiBand5, + kMiBand6, + kAmazfitBipS, + kAmazfitBipU, + kAmazfitGts, + kAmazfitGts2, + kAmazfitGtr, kMiBand7, kAmazfitGtr3, kAmazfitGtr3Pro, diff --git a/test/amazfit_g1_test.dart b/test/amazfit_g1_test.dart index 6d038b645..066f91516 100644 --- a/test/amazfit_g1_test.dart +++ b/test/amazfit_g1_test.dart @@ -70,6 +70,7 @@ void main() { test('links, typed-key pairing, signals, watch kind', () { for (final e in _watches) { expect(e.kind, DeviceKind.watch); + expect(kAskPickerSensors, contains(e)); expect(MiBand234Link.forId(e.id)?.entry, e); expect(miBandTypedKeyPairFor(e.id), isNotNull); expect(kAdapterSignals[e.id], diff --git a/test/miband56_test.dart b/test/miband56_test.dart index 58ac3212e..19c74a509 100644 --- a/test/miband56_test.dart +++ b/test/miband56_test.dart @@ -51,8 +51,11 @@ void main() { ]; expect(claims, [id], reason: n); } - expect(kAskPickerSensors, isNot(contains(kMiBand5))); - expect(kAskPickerSensors, isNot(contains(kMiBand6))); + for (final e in [kMiBand5, kMiBand6]) { + expect(kAskPickerSensors.indexOf(e), + inInclusiveRange(0, kAskPickerSensors.indexOf(kHelioStrap) - 1), + reason: 'listed, before the strap so FEE1 still reads as it'); + } }); test('links, typed-key pairing, signals', () { From 559cd460951f1057d8f18f289c45abc0d8972d9b Mon Sep 17 00:00:00 2001 From: Mohammad Abdul Sahil <127765312+abdulsaheel@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:03:36 +0530 Subject: [PATCH 10/22] amazfit scale: live weighings, clock only plain gatt on fee0, no auth. sets its clock in utc, reads finished weighings off 0x0021 as weight rows. never reads or acks the stored history; the link refuses every write but the clock. no user is selected on the scale, so whether it sends a weighing without one is the thing a real scale has to answer. beta, flag off, in the ios picker like the mi scales, auto-synced like them. --- ios/Runner/Info.plist | 4 + lib/ble/adapters/_registry.dart | 28 ++++++ lib/ble/adapters/gatt_link.dart | 8 ++ lib/ble/adapters/miscale.dart | 74 ++++++++++++++++ lib/ble/scale_presence.dart | 11 ++- lib/ble/session_link.dart | 10 ++- lib/ui2/profile/devices.dart | 12 ++- test/adapter_signals_registry_test.dart | 1 + test/adapters/amazfit_scale_test.dart | 87 +++++++++++++++++++ test/adapters/gatt_link_write_test.dart | 21 +++++ test/band_registry_test.dart | 1 + .../support/pairing_reset_fixtures.dart | 2 + test/pairing_device_role_test.dart | 3 +- test/wearable_platform_test.dart | 1 + 14 files changed, 256 insertions(+), 7 deletions(-) create mode 100644 test/adapters/amazfit_scale_test.dart diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist index 93686dd1a..e73843a9d 100644 --- a/ios/Runner/Info.plist +++ b/ios/Runner/Info.plist @@ -83,6 +83,7 @@ 1809 181B 181D + FEE0