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