From d74cbc86d3b2cfb22444f638bdf5a76649f96878 Mon Sep 17 00:00:00 2001 From: Mohammad Abdul Sahil <127765312+abdulsaheel@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:52:57 +0530 Subject: [PATCH 1/5] huami2021: chunked transport, b163 auth, activity fetch and record decoders (helio strap) --- lib/openstrap_protocol.dart | 5 + lib/src/b163.dart | 285 ++++++++++++ lib/src/huami2021_auth.dart | 184 ++++++++ lib/src/huami2021_chunks.dart | 225 +++++++++ lib/src/huami2021_fetch.dart | 176 +++++++ lib/src/huami2021_records.dart | 665 +++++++++++++++++++++++++++ pubspec.yaml | 1 + test/b163_test.dart | 52 +++ test/fixtures/huami2021_vectors.json | 523 +++++++++++++++++++++ test/huami2021_auth_test.dart | 108 +++++ test/huami2021_chunks_test.dart | 154 +++++++ test/huami2021_fetch_test.dart | 156 +++++++ test/huami2021_records_test.dart | 307 +++++++++++++ 13 files changed, 2841 insertions(+) create mode 100644 lib/src/b163.dart create mode 100644 lib/src/huami2021_auth.dart create mode 100644 lib/src/huami2021_chunks.dart create mode 100644 lib/src/huami2021_fetch.dart create mode 100644 lib/src/huami2021_records.dart create mode 100644 test/b163_test.dart create mode 100644 test/fixtures/huami2021_vectors.json create mode 100644 test/huami2021_auth_test.dart create mode 100644 test/huami2021_chunks_test.dart create mode 100644 test/huami2021_fetch_test.dart create mode 100644 test/huami2021_records_test.dart diff --git a/lib/openstrap_protocol.dart b/lib/openstrap_protocol.dart index 226428c..825d789 100644 --- a/lib/openstrap_protocol.dart +++ b/lib/openstrap_protocol.dart @@ -25,6 +25,11 @@ export 'src/colmi.dart'; export 'src/health_thermometer.dart'; export 'src/miscale.dart'; export 'src/huami_legacy.dart'; +export 'src/huami2021_chunks.dart'; +export 'src/b163.dart'; +export 'src/huami2021_auth.dart'; +export 'src/huami2021_records.dart'; +export 'src/huami2021_fetch.dart'; export 'src/pebble.dart'; export 'src/garmin_fit.dart'; export 'src/garmin_transfer.dart'; diff --git a/lib/src/b163.dart b/lib/src/b163.dart new file mode 100644 index 0000000..ac5c8ce --- /dev/null +++ b/lib/src/b163.dart @@ -0,0 +1,285 @@ +// Elliptic-curve Diffie-Hellman over the binary field GF(2^163), using the +// standard curve sect163r2 (SEC 2 / ANSI X9.62; also called NIST B-163): +// y^2 + xy = x^3 + x^2 + b over GF(2^163), reduction polynomial +// x^163 + x^7 + x^6 + x^3 + 1. +// +// Field elements are 163-bit binary polynomials, represented as six 32-bit +// little-endian words (192 bits of storage, top 29 bits always zero). A +// private key is 24 random bytes with bit 163 and above cleared; a public +// key is the 48-byte concatenation of the affine X and Y coordinates, each +// 24 bytes little-endian. + +import 'dart:math'; +import 'dart:typed_data'; + +/// One point's affine coordinates, or the point at infinity when [isInfinity]. +class _Point { + const _Point(this.x, this.y, {this.isInfinity = false}); + final Uint32List x; + final Uint32List y; + final bool isInfinity; + + static final _Point infinity = + _Point(Uint32List(6), Uint32List(6), isInfinity: true); +} + +class B163Keypair { + const B163Keypair(this.privateKey, this.publicKey); + + /// 24 bytes, little-endian. + final Uint8List privateKey; + + /// 48 bytes: X (24 bytes LE) followed by Y (24 bytes LE). + final Uint8List publicKey; +} + +/// Thrown when a supplied public key is not a valid point on the curve. +class B163Error extends ArgumentError { + B163Error(super.message); +} + +const int _words = 6; + +// sect163r2 domain parameters, as 6 little-endian 32-bit words each. +final Uint32List _curveB = _fromWords( + [0x4a3205fd, 0x512f7874, 0x1481eb10, 0xb8c953ca, 0x0a601907, 0x00000002]); +final Uint32List _baseX = _fromWords( + [0xe8343e36, 0xd4994637, 0xa0991168, 0x86a2d57e, 0xf0eba162, 0x00000003]); +final Uint32List _baseY = _fromWords( + [0x797324f1, 0xb11c5c0c, 0xa2cdd545, 0x71a0094f, 0xd51fbc6c, 0x00000000]); + +Uint32List _fromWords(List w) => Uint32List.fromList(w); + +Uint32List _fromBytesLE(Uint8List b) { + final out = Uint32List(_words); + final bd = ByteData.sublistView(b); + for (var i = 0; i < 6; i++) { + final off = i * 4; + out[i] = off + 4 <= b.length ? bd.getUint32(off, Endian.little) : 0; + } + return out; +} + +Uint8List _toBytesLE(Uint32List w) { + final out = Uint8List(24); + final bd = ByteData.sublistView(out); + for (var i = 0; i < 6; i++) { + bd.setUint32(i * 4, w[i], Endian.little); + } + return out; +} + +// Returns the index of the highest set bit, or -1 for the zero element. +int _highestBit(Uint32List a) { + for (var w = _words - 1; w >= 0; w--) { + if (a[w] != 0) return w * 32 + (31 - _clz32(a[w])); + } + return -1; +} + +int _clz32(int v) { + var n = 0; + var x = v & 0xFFFFFFFF; + if (x == 0) return 32; + for (var bit = 31; bit >= 0; bit--) { + if ((x >> bit) & 1 != 0) return 31 - bit; + n++; + } + return n; +} + +bool _isZero(Uint32List a) => a.every((w) => w == 0); + +Uint32List _xor(Uint32List a, Uint32List b) { + final out = Uint32List(_words); + for (var i = 0; i < _words; i++) { + out[i] = a[i] ^ b[i]; + } + return out; +} + +/// Binary-polynomial multiplication (no reduction), result up to 326 bits, +/// returned as a wider word array (12 words) for the reducer to consume. +Uint32List _polyMul(Uint32List a, Uint32List b) { + final out = Uint32List(12); + for (var i = 0; i < _words; i++) { + if (a[i] == 0) continue; + for (var bit = 0; bit < 32; bit++) { + if ((a[i] >> bit) & 1 == 0) continue; + final shift = i * 32 + bit; + final wordShift = shift ~/ 32; + final bitShift = shift % 32; + for (var j = 0; j < _words; j++) { + if (b[j] == 0) continue; + final idx = wordShift + j; + if (idx >= 12) continue; + var v = b[j] << bitShift; + out[idx] ^= v & 0xFFFFFFFF; + if (bitShift != 0 && idx + 1 < 12) { + out[idx + 1] ^= (b[j] >>> (32 - bitShift)) & 0xFFFFFFFF; + } + } + } + } + return out; +} + +/// Reduces a wide (up to 326-bit) product modulo x^163 + x^7 + x^6 + x^3 + 1. +Uint32List _reduce(Uint32List wide) { + final w = Uint32List.fromList(wide); + // Fold bits at or above 163 back in using the reduction relation + // x^163 = x^7 + x^6 + x^3 + 1. + for (var bit = 11 * 32 + 31; bit >= 163; bit--) { + final word = bit ~/ 32; + final off = bit % 32; + if ((w[word] >> off) & 1 == 0) continue; + w[word] ^= 1 << off; + final reduceBy = bit - 163; + for (final termShift in [0, 3, 6, 7]) { + final target = reduceBy + termShift; + final tw = target ~/ 32; + final tb = target % 32; + if (tw < w.length) w[tw] ^= 1 << tb; + } + } + return Uint32List.fromList(w.sublist(0, _words)); +} + +Uint32List _mulMod(Uint32List a, Uint32List b) => _reduce(_polyMul(a, b)); + +Uint32List _sqrMod(Uint32List a) => _mulMod(a, a); + +/// Multiplicative inverse mod the field polynomial: `a^-1 = a^(2^163 - 2)`, +/// since the field's multiplicative group has order `2^163 - 1`. Plain +/// left-to-right square-and-multiply over the exponent's 163 bits (bit 0 is +/// 0, bits 1..162 are 1) — a fixed-length loop, so it always terminates, +/// unlike a degree-tracking extended-Euclidean variant. +Uint32List _invert(Uint32List a) { + if (_isZero(a)) throw B163Error('cannot invert zero'); + var result = Uint32List.fromList(_one); + for (var bit = 162; bit >= 0; bit--) { + result = _sqrMod(result); + if (bit != 0) { + result = _mulMod(result, a); + } + } + return result; +} + +_Point _pointAdd(_Point p, _Point q) { + if (p.isInfinity) return q; + if (q.isInfinity) return p; + if (_eq(p.x, q.x)) { + if (_isZero(p.x) || !_eq(p.y, q.y)) return _Point.infinity; + return _pointDouble(p); + } + final lambda = _mulMod(_xor(p.y, q.y), _invert(_xor(p.x, q.x))); + final lambdaSq = _sqrMod(lambda); + final x3 = _xor(_xor(_xor(_xor(lambdaSq, lambda), p.x), q.x), _one); + final y3 = _xor( + _xor(_mulMod(lambda, _xor(p.x, x3)), x3), p.y); + return _Point(x3, y3); +} + +final Uint32List _one = _fromWords([1, 0, 0, 0, 0, 0]); + +_Point _pointDouble(_Point p) { + if (p.isInfinity || _isZero(p.x)) return _Point.infinity; + // y^2 + xy = x^3 + x^2 + b (a2 = 1): x3 = lambda^2 + lambda + a2. + final lambda = _xor(p.x, _mulMod(p.y, _invert(p.x))); + final lambdaSq = _sqrMod(lambda); + final x3 = _xor(_xor(lambdaSq, lambda), _one); + final y3 = _xor(_xor(_sqrMod(p.x), _mulMod(lambda, x3)), x3); + return _Point(x3, y3); +} + +bool _eq(Uint32List a, Uint32List b) { + for (var i = 0; i < _words; i++) { + if (a[i] != b[i]) return false; + } + return true; +} + +_Point _scalarMul(Uint32List scalar, _Point base) { + var result = _Point.infinity; + var addend = base; + final bits = _highestBit(scalar); + for (var bit = 0; bit <= bits; bit++) { + final word = bit ~/ 32; + final off = bit % 32; + if ((scalar[word] >> off) & 1 != 0) { + result = _pointAdd(result, addend); + } + addend = _pointDouble(addend); + } + return result; +} + +/// Masks a raw 24-byte scalar to the private-key form this protocol uses: +/// clears bits 163 and above (byte 20's top 6 bits, bytes 21-23 zero). +Uint8List maskPrivateKey(Uint8List raw24) { + final out = Uint8List.fromList(raw24); + if (out.length != 24) throw ArgumentError('private key must be 24 bytes'); + out[20] &= 0x03; + out[21] = 0; + out[22] = 0; + out[23] = 0; + return out; +} + +/// Derives the 48-byte public key for a given (already-masked) 24-byte +/// private key. +Uint8List publicKeyFor(Uint8List privateKey24) { + final priv = _fromBytesLE(privateKey24); + final base = _Point(_baseX, _baseY); + final p = _scalarMul(priv, base); + if (p.isInfinity) throw B163Error('private key produced the point at infinity'); + return Uint8List.fromList([..._toBytesLE(p.x), ..._toBytesLE(p.y)]); +} + +/// Builds a keypair from 24 raw random bytes, masking them first. +B163Keypair keypairFrom(Uint8List raw24) { + final priv = maskPrivateKey(raw24); + return B163Keypair(priv, publicKeyFor(priv)); +} + +/// Generates a fresh keypair from a cryptographically secure random source. +/// Regenerates if the masked private key's bit length would fall below 81 +/// bits (vanishingly unlikely; guards against a degenerate near-zero key). +B163Keypair generateKeypair([Random? random]) { + final rng = random ?? Random.secure(); + while (true) { + final raw = Uint8List.fromList([for (var i = 0; i < 24; i++) rng.nextInt(256)]); + final priv = maskPrivateKey(raw); + if (_highestBit(_fromBytesLE(priv)) < 80) continue; // < 81 significant bits + try { + return B163Keypair(priv, publicKeyFor(priv)); + } on B163Error { + continue; // vanishingly unlikely: retry with a fresh private key + } + } +} + +/// The shared secret: the X coordinate (24 bytes LE) of `privateKey * peerPublicKey`. +Uint8List sharedSecret(Uint8List privateKey24, Uint8List peerPublicKey48) { + if (peerPublicKey48.length != 48) { + throw B163Error('public key must be 48 bytes'); + } + final peerX = _fromBytesLE(peerPublicKey48.sublist(0, 24)); + final peerY = _fromBytesLE(peerPublicKey48.sublist(24, 48)); + if (!_isOnCurve(peerX, peerY)) { + throw B163Error('peer public key is not on the curve'); + } + final priv = _fromBytesLE(privateKey24); + final s = _scalarMul(priv, _Point(peerX, peerY)); + if (s.isInfinity) throw B163Error('shared secret is the point at infinity'); + return _toBytesLE(s.x); +} + +bool _isOnCurve(Uint32List x, Uint32List y) { + if (_isZero(x) && _isZero(y)) return false; + // y^2 + xy = x^3 + x^2 + b + final lhs = _xor(_sqrMod(y), _mulMod(x, y)); + final rhs = _xor(_xor(_mulMod(_sqrMod(x), x), _sqrMod(x)), _curveB); + return _eq(lhs, rhs); +} diff --git a/lib/src/huami2021_auth.dart b/lib/src/huami2021_auth.dart new file mode 100644 index 0000000..5e0116e --- /dev/null +++ b/lib/src/huami2021_auth.dart @@ -0,0 +1,184 @@ +// The Huami2021/ZeppOS auth handshake, endpoint 0x0082: a pure state machine +// over five framed steps, using a pre-shared 16-byte auth key and B-163 ECDH +// to derive a fresh session key each time. +// +// 1 phone -> 04 02 00 02 | ourPublicKey[48] (52 bytes) +// 2 device -> 10 04 status | remoteRandom[16] | devicePublicKey[48] +// 3 -- shared = ECDH(ourPrivate, devicePublicKey) +// sequence = u32LE(shared[0:4]) +// sessionKey[i] = shared[i+8] XOR authKey[i], i = 0..15 +// 4 phone -> 05 | AES_ECB(authKey, remoteRandom) | AES_ECB(sessionKey, remoteRandom) +// 5 device -> 10 05 status (0x01 success, 0x25 wrong key) +// +// The caller frames step 1's and step 4's payloads on endpoint +// [kHuami2021AuthEndpoint] (unencrypted) with a chunk encoder, and feeds +// reassembled endpoint-0x0082 payloads to [Huami2021Auth.onPayload]. Secrets +// (auth key, session key) never appear in a failure's fields. + +import 'dart:typed_data'; + +import 'b163.dart'; +import 'huami2021_chunks.dart' show AesEcb; + +/// The auth endpoint every step above is framed on. +const int kHuami2021AuthEndpoint = 0x0082; + +const int _cmdPublicKey = 0x04; +const int _cmdSessionKey = 0x05; +const int _responsePrefix = 0x10; +const int _statusOk = 0x01; +const int _statusWrongKey = 0x25; + +enum _State { idle, sentPublicKey, sentProof, done } + +/// Why the device refused, or why a reply couldn't be used. +sealed class Huami2021AuthFailure { + const Huami2021AuthFailure(); +} + +/// Status `0x25` on step 5: the auth key does not match this device's pairing. +class WrongAuthKey extends Huami2021AuthFailure { + const WrongAuthKey(); +} + +/// Any other non-success status, at the step it arrived on. +class AuthRejected extends Huami2021AuthFailure { + const AuthRejected(this.step, this.status); + final int step; + final int status; +} + +/// A reply that doesn't have the shape this step requires. +class AuthMalformed extends Huami2021AuthFailure { + const AuthMalformed(this.reason); + final String reason; +} + +/// What [Huami2021Auth.onPayload] reports back to the caller. +sealed class Huami2021AuthEvent { + const Huami2021AuthEvent(); +} + +/// Not a reply this handshake is waiting for right now. +class Huami2021AuthIgnored extends Huami2021AuthEvent { + const Huami2021AuthIgnored(); +} + +/// Step 4: frame and send this payload on [kHuami2021AuthEndpoint]. +class Huami2021AuthSendProof extends Huami2021AuthEvent { + const Huami2021AuthSendProof(this.payload); + final Uint8List payload; +} + +/// Step 5 succeeded. [sessionKey] and [sequence] seed the chunk transport's +/// encryption from here on. +class Huami2021Authenticated extends Huami2021AuthEvent { + const Huami2021Authenticated(this.sessionKey, this.sequence); + final Uint8List sessionKey; + final int sequence; + + @override + String toString() => 'Huami2021Authenticated(sequence: )'; +} + +class Huami2021AuthFailed extends Huami2021AuthEvent { + const Huami2021AuthFailed(this.failure); + final Huami2021AuthFailure failure; +} + +/// Drives the five-step handshake above. One instance per connection +/// attempt; [start] may be called only once. +class Huami2021Auth { + Huami2021Auth(Uint8List authKey, {required AesEcb aesEcb, B163Keypair? keypair}) + : _authKey = Uint8List.fromList(authKey), + _aes = aesEcb, + _keypair = keypair ?? generateKeypair() { + if (_authKey.length != 16) { + throw ArgumentError('auth key must be 16 bytes'); + } + } + + final Uint8List _authKey; + final AesEcb _aes; + final B163Keypair _keypair; + _State _state = _State.idle; + Uint8List? _sessionKey; + int _sequence = 0; + + /// Step 1's payload: `04 02 00 02` followed by our 48-byte public key. + Uint8List start() { + if (_state != _State.idle) { + throw StateError('handshake already started'); + } + _state = _State.sentPublicKey; + return Uint8List.fromList( + [_cmdPublicKey, 0x02, 0x00, 0x02, ..._keypair.publicKey]); + } + + /// Feeds one reassembled payload from endpoint 0x0082. Steps 2 and 5 are + /// the only replies ever expected; anything else is [Huami2021AuthIgnored]. + Huami2021AuthEvent onPayload(Uint8List payload) { + if (payload.length < 3 || payload[0] != _responsePrefix) { + return const Huami2021AuthIgnored(); + } + final cmd = payload[1]; + final status = payload[2]; + if (cmd == _cmdPublicKey && _state == _State.sentPublicKey) { + return _onPublicKeyReply(status, payload); + } + if (cmd == _cmdSessionKey && _state == _State.sentProof) { + return _onSessionReply(status); + } + return const Huami2021AuthIgnored(); + } + + Huami2021AuthEvent _onPublicKeyReply(int status, Uint8List payload) { + if (status != _statusOk) { + return _fail(AuthRejected(2, status)); + } + if (payload.length < 3 + 16 + 48) { + return _fail(AuthMalformed( + 'step 2 reply is ${payload.length} bytes, need ${3 + 16 + 48}')); + } + final remoteRandom = payload.sublist(3, 19); + final devicePublicKey = payload.sublist(19, 19 + 48); + final Uint8List shared; + try { + shared = sharedSecret(_keypair.privateKey, devicePublicKey); + } on B163Error catch (e) { + return _fail(AuthMalformed(e.message?.toString() ?? 'bad device public key')); + } + _sequence = ByteData.sublistView(shared, 0, 4).getUint32(0, Endian.little); + final session = Uint8List(16); + for (var i = 0; i < 16; i++) { + session[i] = shared[i + 8] ^ _authKey[i]; + } + _sessionKey = session; + _state = _State.sentProof; + final proof = Uint8List.fromList([ + _cmdSessionKey, + ..._aes(_authKey, remoteRandom), + ..._aes(session, remoteRandom), + ]); + return Huami2021AuthSendProof(proof); + } + + Huami2021AuthEvent _onSessionReply(int status) { + if (status == _statusOk) { + _state = _State.done; + return Huami2021Authenticated(_sessionKey!, _sequence); + } + if (status == _statusWrongKey) { + return _fail(const WrongAuthKey()); + } + return _fail(AuthRejected(5, status)); + } + + Huami2021AuthEvent _fail(Huami2021AuthFailure failure) { + _state = _State.done; + return Huami2021AuthFailed(failure); + } + + @override + String toString() => 'Huami2021Auth(state: $_state)'; +} diff --git a/lib/src/huami2021_chunks.dart b/lib/src/huami2021_chunks.dart new file mode 100644 index 0000000..094ebcd --- /dev/null +++ b/lib/src/huami2021_chunks.dart @@ -0,0 +1,225 @@ +// Huami2021 chunked transport (chars 0016 write / 0017 notify): logical +// endpoint messages split into BLE writes, and reassembled (and decrypted) +// on the way back. +// +// Chunk header — marker 0x03 · flags · 0x00 · handle · count; the FIRST chunk +// then carries the ORIGINAL (plaintext) length u32 LE and the endpoint u16 LE. +// Flags: 0x01 first, 0x02 last, 0x04 needs-ACK (set with last), 0x08 encrypted. +// Handle is one per message, (prev + 1) & 0xFF, starting at 1. +// +// Encrypted message: key[i] = sessionKey[i] ^ handle, AES-128-ECB, plaintext = +// data | seq u32 LE | crc32(data | seq) u32 LE, zero-padded to 16. +// +// The cipher is passed in so this package stays dependency-free (the edge +// adapter owns AES, as it does for the other framed bands). + +import 'dart:typed_data'; + +import 'crc.dart' show crc32; + +/// AES-128-ECB, no padding. [data] is a multiple of 16 bytes. +typedef AesEcb = Uint8List Function(Uint8List key, Uint8List data); + +const int _marker = 0x03; +const int _flagFirst = 0x01; +const int _flagLast = 0x02; +const int _flagNeedsAck = 0x04; +const int _flagEncrypted = 0x08; +const int _firstHeader = 11; +const int _nextHeader = 5; + +/// The ATT MTU the strap grants; chunk sizes depend on it. +const int kHuami2021DefaultMtu = 247; + +/// Chunked WRITE (app -> strap). +const String kHuami2021ChunkWriteChar = '00000016-0000-3512-2118-0009af100700'; + +/// Chunked NOTIFY (strap -> app); ACKs are also written here. +const String kHuami2021ChunkNotifyChar = '00000017-0000-3512-2118-0009af100700'; + +/// `data | seq(4) | crc32(4)` rounded up to a 16-byte multiple. +int huami2021PaddedLength(int originalLength) { + final raw = originalLength + 8; + return raw % 16 == 0 ? raw : raw + 16 - raw % 16; +} + +Uint8List _messageKey(Uint8List sessionKey, int handle) => + Uint8List.fromList([for (final b in sessionKey) b ^ handle]); + +/// The ACK the strap expects on 0017 after a frame flagged needs-ACK. +Uint8List huami2021Ack(int handle, int count) => + Uint8List.fromList([0x04, 0x00, handle & 0xff, 0x01, count & 0xff]); + +/// Splits outgoing messages into chunks. One encoder per connection. +class Huami2021Encoder { + Huami2021Encoder({this.mtu = kHuami2021DefaultMtu, AesEcb? encrypt}) + : _aesEncrypt = encrypt; + + final int mtu; + final AesEcb? _aesEncrypt; + int _handle = 0; + Uint8List? _key; + int _seq = 0; + + /// Arms encryption for later `encrypt: true` messages. + void setEncryption(Uint8List sessionKey, int sequence) { + if (sessionKey.length != 16) { + throw ArgumentError('session key must be 16 bytes'); + } + _key = Uint8List.fromList(sessionKey); + _seq = sequence & 0xFFFFFFFF; + } + + List encode(int endpoint, List data, {bool encrypt = false}) { + _handle = (_handle + 1) & 0xFF; + final body = encrypt ? _encrypt(Uint8List.fromList(data)) : data; + final chunks = []; + var offset = 0; + var count = 0; + do { + final first = count == 0; + final header = first ? _firstHeader : _nextHeader; + final budget = (mtu - 3 - header).clamp(1, 1 << 30); + final remaining = body.length - offset; + final take = remaining < budget ? remaining : budget; + final last = remaining <= budget; + var flags = first ? _flagFirst : 0; + if (encrypt) flags |= _flagEncrypted; + if (last) flags |= _flagLast | _flagNeedsAck; + final chunk = Uint8List(header + take); + final bd = ByteData.sublistView(chunk); + chunk[0] = _marker; + chunk[1] = flags; + chunk[3] = _handle; + chunk[4] = count; + if (first) { + bd.setUint32(5, data.length, Endian.little); // ORIGINAL length + bd.setUint16(9, endpoint, Endian.little); + } + chunk.setRange(header, header + take, body, offset); + chunks.add(chunk); + offset += take; + count++; + } while (offset < body.length); + return chunks; + } + + Uint8List _encrypt(Uint8List data) { + final key = _key; + final aes = _aesEncrypt; + if (key == null || aes == null) { + throw StateError('encrypt requested without a session key or cipher'); + } + final plain = Uint8List(huami2021PaddedLength(data.length)); + plain.setRange(0, data.length, data); + final bd = ByteData.sublistView(plain); + bd.setUint32(data.length, _seq, Endian.little); + _seq = (_seq + 1) & 0xFFFFFFFF; + bd.setUint32(data.length + 4, crc32(plain.sublist(0, data.length + 4)), + Endian.little); + return aes(_messageKey(key, _handle), plain); + } +} + +/// One reassembled logical message. +class Huami2021Frame { + const Huami2021Frame(this.endpoint, this.payload, this.encrypted, + this.needsAck, this.handle, this.count); + final int endpoint; + final Uint8List payload; + final bool encrypted; + final bool needsAck; + final int handle; + final int count; +} + +/// Reassembles chunks arriving on 0017. One decoder per connection. +class Huami2021Decoder { + Huami2021Decoder({AesEcb? decrypt}) : _aesDecrypt = decrypt; + + final AesEcb? _aesDecrypt; + int? _handle; + int _endpoint = 0; + int _length = 0; + bool _encrypted = false; + int _nextCount = 0; + final BytesBuilder _buffer = BytesBuilder(copy: false); + + /// Feeds one notification. Returns the frame on its last chunk, else null. + /// Malformed, out-of-sequence, undecryptable or CRC-mismatched input + /// returns null and resets: the caller sees no frame, never garbage — + /// specifically: + /// * a chunk with no preceding first-chunk for this handle is an orphan + /// and is rejected, not treated as an empty message on endpoint 0; + /// * `count` must run 0, 1, 2, ... with no gap — a chunk that skips + /// ahead (a dropped middle chunk) or repeats is rejected rather than + /// silently reassembled into a truncated or duplicated payload; + /// * an encrypted message's trailing `seq | crc32(data|seq)` is checked + /// after decryption, so a wrong session key yields null, never the + /// garbage AES-ECB happens to produce under the wrong key. + Huami2021Frame? feed(List data, {Uint8List? sessionKey}) { + if (data.length < 5 || data[0] != _marker) return null; + final flags = data[1]; + final chunkHandle = data[3]; + final count = data[4]; + final isFirst = flags & _flagFirst != 0; + if (_handle == null && !isFirst) return null; // orphan: no first chunk seen + if (_handle != null && _handle != chunkHandle) return null; + var offset = 5; + if (isFirst) { + if (data.length < offset + 6) return null; + final bd = ByteData.sublistView(Uint8List.fromList(data)); + _length = bd.getUint32(offset, Endian.little); + _endpoint = bd.getUint16(offset + 4, Endian.little); + _encrypted = flags & _flagEncrypted != 0; + _buffer.clear(); + _handle = chunkHandle; + _nextCount = 0; + offset += 6; + } + if (count != _nextCount) { + _reset(); + return null; + } + _nextCount++; + _buffer.add(data.sublist(offset)); + if (flags & _flagLast == 0) return null; + final payload = _assemble(sessionKey, chunkHandle); + final frame = payload == null + ? null + : Huami2021Frame(_endpoint, payload, _encrypted, + flags & _flagNeedsAck != 0, chunkHandle, count); + _reset(); + return frame; + } + + Uint8List? _assemble(Uint8List? sessionKey, int chunkHandle) { + var all = _buffer.toBytes(); + if (_encrypted) { + final aes = _aesDecrypt; + if (sessionKey == null || aes == null) return null; + final cipherLength = huami2021PaddedLength(_length); + if (all.length < cipherLength) return null; + all = aes(_messageKey(sessionKey, chunkHandle), + Uint8List.sublistView(all, 0, cipherLength)); + // Verify the trailing seq|crc32 the encoder writes — a wrong session + // key decrypts to garbage with nothing else to catch it. + if (all.length < _length + 8) return null; + final bd = ByteData.sublistView(all); + final crc = bd.getUint32(_length + 4, Endian.little); + final want = crc32(all.sublist(0, _length + 4)); + if (crc != want) return null; + } + final n = _length < all.length ? _length : all.length; + return Uint8List.sublistView(all, 0, n); + } + + void _reset() { + _handle = null; + _endpoint = 0; + _length = 0; + _encrypted = false; + _nextCount = 0; + _buffer.clear(); + } +} diff --git a/lib/src/huami2021_fetch.dart b/lib/src/huami2021_fetch.dart new file mode 100644 index 0000000..f08b8cd --- /dev/null +++ b/lib/src/huami2021_fetch.dart @@ -0,0 +1,176 @@ +// Huami2021/ZeppOS history fetch (control char 0004, data char 0005): +// +// app -> 0004 [0x01, type] | time8(since) +// dev -> 0004 [0x10, 0x01, status, expected u32, year u16, mo, d, h, mi, s] +// app -> 0004 [0x02] (skip if expected == 0) +// dev -> 0005 [counter u8, payload...] x n +// dev -> 0004 [0x10, 0x02, status] +// app -> 0004 [0x03, 0x09] (0x09 = ack and KEEP data on the strap) +// +// Unlike the transport and handshake layers, there is no captured byte +// stream to check this against — only the documented shape. The logic here +// (counter contiguity, byte-count validation, paging) is pure state +// tracking and is tested by construction; the BYTE LAYOUT of the requests +// and replies is unverified against a real device. + +import 'dart:typed_data'; + +/// The `type` byte each fetch start request carries — the same numbering +/// as the record types in `huami2021_records.dart`. +const int kHuami2021TypeActivity = 0x01; +const int kHuami2021TypeManualHr = 0x02; +const int kHuami2021TypeStressManual = 0x12; +const int kHuami2021TypeStress = 0x13; +const int kHuami2021TypeSpo2Spot = 0x25; +const int kHuami2021TypeSpo2Sleep = 0x26; +const int kHuami2021TypeTemperature = 0x2E; +const int kHuami2021TypeRespiratoryRate = 0x38; +const int kHuami2021TypeRestingHr = 0x3A; +const int kHuami2021TypeMaxHr = 0x3D; +const int kHuami2021TypeHrv = 0x49; +const int kHuami2021TypeHrvSdnn = 0x4E; +const int kHuami2021TypePai = 0x0D; +const int kHuami2021TypeOdiSummary = 0x4A; +const int kHuami2021TypeSleep = 0x48; +const int kHuami2021TypeWorkout = 0x05; + +/// `[0x02]`: "send the data for the round just started." +const List kHuami2021FetchSendData = [0x02]; + +/// `[0x03, 0x09]`: ack the round and tell the strap to KEEP its copy. Never +/// send `0x03` with anything else — that would be the delete form, and this +/// protocol never trims (unlike WHOOP's offload, which this is not). +const List kHuami2021FetchAckKeep = [0x03, 0x09]; + +/// `time8`: local wall-clock `since`, as year u16 LE, month, day, hour, +/// minute, 0 (seconds), then `(utcOffsetMinutes / 15) & 0xFF`. +Uint8List huami2021Time8(DateTime localSince, int utcOffsetMinutes) { + final out = Uint8List(8); + final bd = ByteData.sublistView(out); + bd.setUint16(0, localSince.year, Endian.little); + out[2] = localSince.month; + out[3] = localSince.day; + out[4] = localSince.hour; + out[5] = localSince.minute; + out[6] = 0; + out[7] = (utcOffsetMinutes ~/ 15) & 0xFF; + return out; +} + +/// `[0x01, type] | time8(since)`: the fetch start request. +Uint8List huami2021FetchStartRequest(int type, DateTime localSince, int utcOffsetMinutes) => + Uint8List.fromList([0x01, type, ...huami2021Time8(localSince, utcOffsetMinutes)]); + +/// The device's reply to a start request: `[0x10, 0x01, status, expected +/// u32, year u16, mo, d, h, mi, s]`. `roundStartMs` is built from the +/// reply's own date fields, read as a plain local wall-clock value (no +/// timezone applied here — that is the caller's job, same as every other +/// local-time field in this protocol). +class Huami2021FetchStart { + const Huami2021FetchStart( + {required this.status, required this.expected, required this.roundStart}); + final int status; + final int expected; + final DateTime roundStart; + + bool get ok => status == 0x01; + bool get hasData => ok && expected > 0; +} + +/// Parses a start reply, or null if [b] isn't one (too short, or not this +/// shape). +Huami2021FetchStart? parseHuami2021FetchStart(Uint8List b) { + if (b.length < 13 || b[0] != 0x10 || b[1] != 0x01) return null; + final bd = ByteData.sublistView(b); + final status = b[2]; + final expected = bd.getUint32(3, Endian.little); + final year = bd.getUint16(7, Endian.little); + final month = b[9]; + final day = b[10]; + final hour = b[11]; + final minute = b[12]; + final second = b.length > 13 ? b[13] : 0; + // Dart's DateTime constructor NORMALISES an out-of-range field instead of + // throwing (month 0 becomes the previous December, for instance), so an + // all-zero or corrupted date silently becomes a real-looking date in the + // wrong year rather than failing loudly. Validate the fields explicitly + // before constructing, rather than relying on an exception that never + // comes. + final plausible = month >= 1 && + month <= 12 && + day >= 1 && + day <= 31 && + hour <= 23 && + minute <= 59 && + second <= 59 && + year >= 2000 && + year <= 2100; + final roundStart = + plausible ? DateTime(year, month, day, hour, minute, second) : DateTime(1970); + return Huami2021FetchStart(status: status, expected: expected, roundStart: roundStart); +} + +/// `[0x10, 0x02, status]`: the round is over. Returns null if [b] isn't +/// this shape. +int? parseHuami2021FetchRoundEnd(Uint8List b) { + if (b.length < 3 || b[0] != 0x10 || b[1] != 0x02) return null; + return b[2]; +} + +/// Reassembles the `[counter, payload...]` data packets of one round. +/// [ok] goes false the moment a counter isn't `(prev+1) & 0xFF` from 0 — +/// from then on the round is not trustworthy and must be discarded, never +/// decoded. A repeated final packet is not handled specially here (the +/// spec only documents the counter-gap and short-count failure modes); +/// decoders are tolerant of a harmless trailing partial record regardless. +class Huami2021FetchBuffer { + final BytesBuilder _bytes = BytesBuilder(copy: false); + int _next = 0; + bool ok = true; + + void add(List packet) { + if (!ok || packet.isEmpty) return; + if (packet[0] != (_next & 0xff)) { + ok = false; + return; + } + _next++; + _bytes.add(packet.sublist(1)); + } + + Uint8List get bytes => _bytes.toBytes(); +} + +/// Whether an accumulated round's byte count matches what the start reply +/// announced. Type `0x01`'s `expected` is a RECORD count (8 bytes normally, +/// 4 when the byte length isn't a multiple of 8); every other type's +/// `expected` is a plain byte count. +bool huami2021FetchCountMatches(int type, int expected, int actualBytes) { + if (type == kHuami2021TypeActivity) { + final recordSize = actualBytes % 8 == 0 ? 8 : 4; + return expected == actualBytes ~/ recordSize && actualBytes % recordSize == 0; + } + return expected == actualBytes; +} + +/// The paging advance when a round decoded to zero samples but did carry +/// raw bytes (types 0x01 and 0x13 only — a new strap answers every window +/// before its first real day with filler, and without this the pager never +/// gets past it). Minutes, clamped to 1-1440. +int huami2021FetchGapSkipMinutes(int type, int rawLen) { + final recordSize = switch (type) { + kHuami2021TypeActivity => rawLen % 8 == 0 ? 8 : 4, + kHuami2021TypeStress => 1, + _ => throw ArgumentError('gap-skip only applies to activity and stress'), + }; + if (recordSize == 0) return 1; + final minutes = rawLen ~/ recordSize; + return minutes.clamp(1, 1440); +} + +/// Workouts page by "latest decoded workout start + 1 min", but a round +/// that brings nothing newer should still advance — by 5 minutes, up to 40 +/// times — rather than stall forever on a strap whose wall clock drifted +/// across a DST change relative to when the workout was actually recorded. +const int kHuami2021WorkoutStallAdvanceMinutes = 5; +const int kHuami2021WorkoutStallMaxAdvances = 40; diff --git a/lib/src/huami2021_records.dart b/lib/src/huami2021_records.dart new file mode 100644 index 0000000..291de51 --- /dev/null +++ b/lib/src/huami2021_records.dart @@ -0,0 +1,665 @@ +// Huami2021/ZeppOS history record decoders (fetch endpoints, chars 0004 +// control / 0005 data). Two timestamp styles: round-relative (roundStart + +// 60 s per record) and absolute (a `sec` field inside the record). `0xFF` is +// a sentinel meaning "allocated, never written" — dropped everywhere, never +// treated as a real zero/low reading. +// +// All multi-byte integers are little-endian. + +import 'dart:typed_data'; + +int _u8(Uint8List b, int off) => b[off]; +int _u16(Uint8List b, int off) => ByteData.sublistView(b).getUint16(off, Endian.little); +int _i16(Uint8List b, int off) => ByteData.sublistView(b).getInt16(off, Endian.little); +int _u32(Uint8List b, int off) => ByteData.sublistView(b).getUint32(off, Endian.little); + +/// One decoded per-minute or per-event sample: a metric name, its Unix +/// milliseconds, and its value. +class Huami2021Sample { + const Huami2021Sample(this.metric, this.ms, this.value); + final String metric; + final int ms; + final double value; + + @override + String toString() => 'Huami2021Sample($metric @ $ms = $value)'; +} + +/// Type `0x01`: `hr` and `steps`, one record per minute, round-relative. +/// 8 bytes per record normally; some rounds arrive 4-byte packed (steps u8 @ +/// +2, hr u8 @ +3, no leading/trailing padding) instead. +/// +/// [expectedRecordCount] (the fetch start reply's own announced count, +/// per `huami2021_fetch.dart`) resolves which form this round used WITHOUT +/// guessing: `data.length / expectedRecordCount` is exact either way. Pass +/// it whenever it's available — it is always available from a real fetch +/// round, so a caller with a live connection should never fall through to +/// the heuristic below. +/// +/// The heuristic (`data.length % 8 == 0 ? 8 : 4`) is a fallback for when no +/// count is given (a unit test decoding a raw buffer with no round context, +/// say) and is WRONG whenever the true record count is even: an even +/// number of real 4-byte records is itself always a multiple of 8, so the +/// heuristic silently reads two real records as one 8-byte record, +/// collapsing N minutes into N/2 with corrupted values, not merely missing +/// ones. Never rely on it from a real fetch. +List parseHuami2021Activity(Uint8List data, int roundStartMs, + {int? expectedRecordCount}) { + final fromCount = (expectedRecordCount != null && expectedRecordCount > 0) + ? data.length ~/ expectedRecordCount + : 0; + // A count so large relative to the byte length that it would divide down + // to zero is not trustworthy either way — fall back to the heuristic + // rather than risk a zero record size (which would never advance the + // loop below). + final recordSize = + fromCount > 0 ? fromCount : (data.length % 8 == 0 ? 8 : 4); + final out = []; + for (var i = 0; i + recordSize <= data.length; i += recordSize) { + final ms = roundStartMs + (i ~/ recordSize) * 60000; + final steps = _u8(data, i + 2); + final hr = _u8(data, i + 3); + if (hr != 0xff && hr > 0) { + out.add(Huami2021Sample('hr', ms, hr.toDouble())); + } + if (steps != 0xff && steps > 0) { + out.add(Huami2021Sample('steps', ms, steps.toDouble())); + } + } + return out; +} + +/// Types `0x02` (`manual_hr`) and `0x12` (`stress_manual`): 6-byte absolute +/// records, `sec` u32 @ +0, value u8 @ +5. Kept when the value is neither +/// the sentinel nor zero. +List _parseAbsolute6(Uint8List data, String metric) { + final out = []; + for (var i = 0; i + 6 <= data.length; i += 6) { + final sec = _u32(data, i); + final value = _u8(data, i + 5); + if (value != 0xff && value > 0) { + out.add(Huami2021Sample(metric, sec * 1000, value.toDouble())); + } + } + return out; +} + +List parseHuami2021ManualHr(Uint8List data) => + _parseAbsolute6(data, 'manual_hr'); +List parseHuami2021StressManual(Uint8List data) => + _parseAbsolute6(data, 'stress_manual'); + +/// Types `0x3A` (`resting_hr`) and `0x3D` (`max_hr`, 1 byte/record since it +/// is one value per round) and `0x49` (`hrv`): same 6-byte absolute shape as +/// above, reused for clarity at the call site. +List parseHuami2021RestingHr(Uint8List data) => + _parseAbsolute6(data, 'resting_hr'); +List parseHuami2021MaxHr(Uint8List data) => + _parseAbsolute6(data, 'max_hr'); +List parseHuami2021Hrv(Uint8List data) => + _parseAbsolute6(data, 'hrv'); + +/// Type `0x13`: `stress`, 1 byte/record, round-relative, value 0-100. +/// `0xFF` means no reading; anything else is kept, including 0. +List parseHuami2021Stress(Uint8List data, int roundStartMs) { + final out = []; + for (var i = 0; i < data.length; i++) { + final v = data[i]; + if (v == 0xff) continue; + out.add(Huami2021Sample('stress', roundStartMs + i * 60000, v.toDouble())); + } + return out; +} + +/// Type `0x2E`: `temperature_c` (skin), 8 bytes/record, round-relative, +/// signed int16 at +2, hundredths of a degree. +/// +/// Kept only for a plausible skin temperature, 20-45 C — the same bound +/// this codebase's other device-temperature adapter (Ultrahuman) already +/// uses, since this record carries no separate quality flag to combine with +/// the way that one does. An earlier version of this function kept every +/// raw value unfiltered on the theory that a higher analytics layer would +/// reject an outlier; for this device that layer doesn't exist between +/// decode and storage, so an implausible value (a zeroed or corrupted +/// record, say) would otherwise reach `decoded_onehz` as a measured +/// reading with nothing downstream to catch it. +List parseHuami2021Temperature(Uint8List data, int roundStartMs) { + final out = []; + for (var i = 0; i + 8 <= data.length; i += 8) { + final raw = _i16(data, i + 2); + final celsius = raw / 100.0; + final ms = roundStartMs + (i ~/ 8) * 60000; + if (celsius < 20 || celsius > 45) continue; + out.add(Huami2021Sample('temperature_c', ms, celsius)); + } + return out; +} + +/// Type `0x38`: `respiratory_rate` (sleep), 8 bytes/record, absolute +/// `sec` u32 @ +0, breaths/min u8 @ +5. Dropped if sentinel or zero. +List parseHuami2021RespiratoryRate(Uint8List data) { + final out = []; + for (var i = 0; i + 8 <= data.length; i += 8) { + final sec = _u32(data, i); + final value = _u8(data, i + 5); + if (value != 0xff && value > 0) { + out.add(Huami2021Sample('respiratory_rate', sec * 1000, value.toDouble())); + } + } + return out; +} + +/// Type `0x25`: `spo2` (spot check), 65 bytes/record. The first byte of the +/// WHOLE payload is a version byte that must be `2`; each record inside is +/// then `sec u32 @ +0, value u8 @ +4` (`v >= 128 ? v - 128 : v`), one record +/// per `recordSize` chunk. Any other version yields no samples at all — +/// the layout for other versions isn't known, and guessing would be a +/// silent wrong answer. +/// +/// The documented table has no stated keep-rule for this type, but `0xFF` +/// (and, after the `>=128` fold, `0x7F`) is this protocol's sentinel +/// everywhere else, and no real SpO2 reading is 0% or above 100% — kept +/// only for 1-100, same bound as [parseHuami2021Spo2Sleep]. An earlier +/// version of this function kept every byte verbatim, including 0 and the +/// folded sentinel (127); that was wrong and is what this bound fixes. +const int _spo2SpotRecordSize = 65; +List parseHuami2021Spo2Spot(Uint8List data) { + if (data.isEmpty || data[0] != 2) return const []; + final out = []; + for (var i = 1; i + _spo2SpotRecordSize <= data.length; i += _spo2SpotRecordSize) { + final sec = _u32(data, i); + var value = _u8(data, i + 4); + if (value >= 128) value -= 128; + if (value < 1 || value > 100) continue; + out.add(Huami2021Sample('spo2', sec * 1000, value.toDouble())); + } + return out; +} + +/// Type `0x26`: `spo2_sleep`, 30 bytes/record after the version byte (must +/// be `2`), `sec u32 @ +0, percent u8 @ +4, durationSec u8 @ +5`. Kept for +/// 1-100%. +const int _spo2SleepRecordSize = 30; +List parseHuami2021Spo2Sleep(Uint8List data) { + if (data.isEmpty || data[0] != 2) return const []; + final out = []; + for (var i = 1; i + _spo2SleepRecordSize <= data.length; i += _spo2SleepRecordSize) { + final sec = _u32(data, i); + final pct = _u8(data, i + 4); + if (pct >= 1 && pct <= 100) { + out.add(Huami2021Sample('spo2_sleep', sec * 1000, pct.toDouble())); + } + } + return out; +} + +/// Type `0x4E`: `hrv_sdnn`, 9 bytes/record, absolute `sec` u32 @ +0, a +/// signed tz-in-quarter-hours byte @ +4 (unused here; the caller resolves +/// local time from `sec` directly), SDNN as u32 @ +5 in hundredths of a +/// millisecond. Kept when the value is non-zero and not the 0xFFFFFFFF +/// sentinel. +/// +/// NOTE: no known-value fixture covers this record; the layout is per the +/// documented spec only, unverified against a real capture. +List parseHuami2021HrvSdnn(Uint8List data) { + final out = []; + for (var i = 0; i + 9 <= data.length; i += 9) { + final sec = _u32(data, i); + final raw = _u32(data, i + 5); + if (raw != 0 && raw != 0xFFFFFFFF) { + out.add(Huami2021Sample('hrv_sdnn', sec * 1000, raw / 100.0)); + } + } + return out; +} + +// --- Type 0x05: workout summaries (protobuf, no .proto shipped) ---------- +// +// Each summary is a 2-byte prefix (not part of the message; `00 80` in +// every one of the 3 real records seen so far — too few samples to know if +// it ever varies, so it is treated as fixed rather than guessed at as a +// counter) followed by a protobuf message with fields (by number, as found +// by +// decoding real summaries byte-for-byte): 1 (string, a version tag, e.g. +// "2.1") · 2 (submessage: 1 varint start-time-seconds, 3 varint sport type) +// · 7 (submessage: 1 varint duration seconds) · 11 (submessage: 1 fixed32 +// float, always 1.0, unused) · 16 (submessage: 1 varint calories) · 19 +// (submessage: 1 varint avg HR, 2 varint max HR, 3 varint min HR). Field 7 +// also appears once more at the top level as a fixed32 (always the 4 bytes +// 01 02 03 04) — a constant, not data; it is simply skipped. + +class Huami2021Workout { + const Huami2021Workout({ + required this.startMs, + required this.durationSec, + required this.sportType, + required this.calories, + required this.avgHr, + required this.maxHr, + required this.minHr, + }); + + final int startMs; + final int durationSec; + final int sportType; + final int calories; + final int avgHr; + final int maxHr; + final int minHr; +} + +/// Thrown by the workout protobuf reader on truncated or malformed input — +/// caught by [parseHuami2021Workouts] itself, never left to surface as a +/// raw [RangeError] that could crash a caller that forgot to guard it. +class _HuamiProtobufTruncated implements Exception { + const _HuamiProtobufTruncated(); +} + +/// Reads one protobuf varint starting at [off]; returns its value and the +/// offset just past it. Throws [_HuamiProtobufTruncated] rather than a raw +/// index-out-of-range error if the buffer ends mid-varint (a continuation +/// bit set on the last byte) — this protocol has no schema to validate +/// against, so a corrupted or unexpectedly-shaped workout record is a real +/// possibility, not a theoretical one, and must be recoverable rather than +/// a crash. +({int value, int next}) _varint(Uint8List data, int off) { + var result = 0, shift = 0, i = off; + while (true) { + if (i >= data.length) throw const _HuamiProtobufTruncated(); + final b = data[i]; + i++; + result |= (b & 0x7f) << shift; + if (b & 0x80 == 0) break; + shift += 7; + } + return (value: result, next: i); +} + +/// Walks a flat protobuf message, calling [onField] with (fieldNumber, +/// wireType, valueBytesOrInt) for each field in wire order. Stops at [end]. +/// Unknown wire type 3/4 (start/end group) ends the walk early rather than +/// guessing at its length — callers get whatever fields were read so far. +void _walkProtobuf(Uint8List data, int start, int end, + void Function(int fieldNo, int wireType, int off, int len) onField) { + var i = start; + while (i < end) { + final tagRead = _varint(data, i); + final tag = tagRead.value; + i = tagRead.next; + final fieldNo = tag >> 3; + final wireType = tag & 7; + switch (wireType) { + case 0: // varint + final v = _varint(data, i); + onField(fieldNo, wireType, i, v.next - i); + i = v.next; + case 1: // fixed64 + onField(fieldNo, wireType, i, 8); + i += 8; + case 2: // length-delimited + final lenRead = _varint(data, i); + final contentStart = lenRead.next; + onField(fieldNo, wireType, contentStart, lenRead.value); + i = contentStart + lenRead.value; + case 5: // fixed32 + onField(fieldNo, wireType, i, 4); + i += 4; + default: + return; // group start/end: not used by this protocol, stop here + } + } +} + +int _varintFieldValue(Uint8List data, int off, int len) => _varint(data, off).value; + +/// Parses every workout summary in [data]: a 2-byte prefix, then one +/// protobuf message, repeated back to back. Messages aren't individually +/// length-prefixed in the stream, so each one is read as a flat top-level +/// field sequence and stops as soon as field 19 (avg/max/min HR) has been +/// read — every real summary seen so far ends there, with the next +/// record's own 2-byte prefix immediately following. +List parseHuami2021Workouts(Uint8List data) { + final out = []; + var cursor = 0; + while (cursor < data.length) { + cursor += 2; // the leading 2-byte prefix + if (cursor >= data.length) break; + + int? startSec, durationSec, sportType, calories, avgHr, maxHr, minHr; + var i = cursor; + try { + var sawField19 = false; + while (i < data.length && !sawField19) { + final tagRead = _varint(data, i); + final fieldNo = tagRead.value >> 3; + final wireType = tagRead.value & 7; + i = tagRead.next; + switch (wireType) { + case 0: + final v = _varint(data, i); + i = v.next; + case 1: + i += 8; + case 2: + final lenRead = _varint(data, i); + final contentStart = lenRead.next; + final contentEnd = contentStart + lenRead.value; + if (contentEnd > data.length) throw const _HuamiProtobufTruncated(); + if (fieldNo == 2) { + _walkProtobuf(data, contentStart, contentEnd, (f, w, o, l) { + if (f == 1 && w == 0) startSec = _varintFieldValue(data, o, l); + if (f == 3 && w == 0) sportType = _varintFieldValue(data, o, l); + }); + } else if (fieldNo == 7) { + _walkProtobuf(data, contentStart, contentEnd, (f, w, o, l) { + if (f == 1 && w == 0) durationSec = _varintFieldValue(data, o, l); + }); + } else if (fieldNo == 16) { + _walkProtobuf(data, contentStart, contentEnd, (f, w, o, l) { + if (f == 1 && w == 0) calories = _varintFieldValue(data, o, l); + }); + } else if (fieldNo == 19) { + _walkProtobuf(data, contentStart, contentEnd, (f, w, o, l) { + if (f == 1 && w == 0) avgHr = _varintFieldValue(data, o, l); + if (f == 2 && w == 0) maxHr = _varintFieldValue(data, o, l); + if (f == 3 && w == 0) minHr = _varintFieldValue(data, o, l); + }); + sawField19 = true; + } + i = contentEnd; + case 5: + if (i + 4 > data.length) throw const _HuamiProtobufTruncated(); + i += 4; + default: + i = data.length; // unknown wire type: stop, don't guess + } + } + } on _HuamiProtobufTruncated { + // This record (and anything after it in this buffer) can't be + // trusted — there is no length prefix to resync on, so guessing at + // where the next record starts would risk silently misparsing it. + // Every workout already decoded before this one stays valid; return + // them rather than crash the caller, which would otherwise lose + // everything else the session fetched alongside workouts. + return out; + } + + if (startSec != null && startSec! >= 1000000000) { + out.add(Huami2021Workout( + startMs: startSec! * 1000, + durationSec: durationSec ?? 0, + sportType: sportType ?? 0, + calories: calories ?? 0, + avgHr: avgHr ?? 0, + maxHr: maxHr ?? 0, + minHr: minHr ?? 0, + )); + } + cursor = i; + } + return out; +} + +/// Type `0x0D`: `pai_daily`/`pai_total` (the strap's own Personal Activity +/// Intelligence score). A version byte, then one record per round: +/// `sec u32 @ +1, daily f32 @ +55, 7-day total f32 @ +59`; record size is +/// 69 bytes for version < 2, 97 for 2-3, 99 for 4, 102 for version >= 5. +/// Kept only when the version matches a known size, `sec` is plausible, +/// and both values are finite and within 0-1000. +/// +/// NOTE: no known-value fixture covers this record; the layout is per the +/// documented spec only, unverified against a real capture. +class Huami2021Pai { + const Huami2021Pai(this.ms, this.daily, this.total); + final int ms; + final double daily; + final double total; +} + +int? _paiRecordSize(int version) => switch (version) { + < 2 => 69, + 2 || 3 => 97, + 4 => 99, + >= 5 => 102, + _ => null, + }; + +List parseHuami2021Pai(Uint8List data) { + if (data.isEmpty) return const []; + final version = data[0]; + final recordSize = _paiRecordSize(version); + if (recordSize == null) return const []; + final out = []; + for (var i = 1; i + recordSize <= data.length; i += recordSize) { + final sec = _u32(data, i); + if (sec < 1600000000 || sec > 2000000000) continue; + final daily = ByteData.sublistView(data).getFloat32(i + 54, Endian.little); + final total = ByteData.sublistView(data).getFloat32(i + 58, Endian.little); + if (!daily.isFinite || !total.isFinite) continue; + if (daily < 0 || daily > 1000 || total < 0 || total > 1000) continue; + out.add(Huami2021Pai(sec * 1000, daily, total)); + } + return out; +} + +/// Type `0x4A`: a nightly sleep-apnea summary, 2896 bytes. `belongTime` (the +/// local midnight starting the wake day) u32 @ +0, valid-time u32 @ +4, +/// `odiRefined` u32 @ +8, score u8 @ +12, 240 undecoded `{sec, value, +/// duration}` i32 triples from +16 on (not read here — their meaning past +/// the headline fields is not established). +/// +/// NOTE: no known-value fixture covers this record; the units of +/// `odiRefined` and the score are UNVERIFIED per the spec itself. Valid +/// time is kept whenever `belongTime` is plausible; the rest of the summary +/// is withheld unless its own value is greater than zero, since an +/// unmeasured night is not the same as a zero. +class Huami2021OdiSummary { + const Huami2021OdiSummary({ + required this.belongTimeMs, + required this.validTimeSec, + this.odiRefined, + this.score, + }); + final int belongTimeMs; + final int validTimeSec; + final int? odiRefined; + final int? score; +} + +const int _odiSummaryRecordSize = 2896; + +List parseHuami2021OdiSummary(Uint8List data) { + final out = []; + for (var i = 0; i + _odiSummaryRecordSize <= data.length; i += _odiSummaryRecordSize) { + final belongTime = _u32(data, i); + if (belongTime < 1600000000 || belongTime > 2000000000) continue; + final validTime = _u32(data, i + 4); + final odiRefined = _u32(data, i + 8); + final score = _u8(data, i + 12); + out.add(Huami2021OdiSummary( + belongTimeMs: belongTime * 1000, + validTimeSec: validTime, + odiRefined: odiRefined > 0 ? odiRefined : null, + score: score != 0xff ? score : null, + )); + } + return out; +} + +// --- Type 0x48: sleep sessions (594-byte slots) -------------------------- + +/// Stage type constants (the rest pass through as opaque small ints). +const int kHuami2021StageAwake = 7; +const int kHuami2021StageLight = 4; +const int kHuami2021StageDeep = 5; +const int kHuami2021StageRem = 8; +const int _gapMarkerType = 0x80; + +const int _sleepRecordSize = 594; + +/// One contiguous stage within a session: a wake, light, deep or REM span. +class Huami2021Stage { + const Huami2021Stage(this.startMs, this.endMs, this.type); + final int startMs; + final int endMs; + final int type; + + @override + String toString() => 'Huami2021Stage($startMs..$endMs type=$type)'; +} + +/// One sleep session: a full night, or a nap found within a night's own +/// slot. A nap's `avgHr`/`score` are always 0 (the device doesn't score +/// naps); its REM/light/deep/wake minutes are summed from its own [stages], +/// not read from the night's totals. +class Huami2021SleepSession { + const Huami2021SleepSession({ + required this.sessionStartMs, + required this.isNap, + required this.avgHr, + required this.score, + required this.sleepStartMin, + required this.sleepEndMin, + required this.remMin, + required this.lightMin, + required this.deepMin, + required this.wakeMin, + required this.stages, + }); + + final int sessionStartMs; + final bool isNap; + final int avgHr; + final int score; + final int sleepStartMin; + final int sleepEndMin; + final int remMin; + final int lightMin; + final int deepMin; + final int wakeMin; + final List stages; +} + +/// Reads one {start u16, end u16, type u8} stage slot at [off], or null for +/// a `{0,0}` entry (a terminator for the night timeline, a gap for the +/// shared nap timeline — the caller decides which). +({int start, int end, int type})? _readStageSlot(Uint8List data, int off) { + final start = _u16(data, off); + final end = _u16(data, off + 2); + if (start == 0 && end == 0) return null; + return (start: start, end: end, type: _u8(data, off + 4)); +} + +/// Parses every valid 594-byte sleep slot in [data] (an invalid slot is +/// skipped, not fatal — a later slot may still be a real session). Each +/// valid slot yields its main night session, plus one [Huami2021SleepSession] +/// per nap descriptor that actually has stages. +List parseHuami2021Sleep(Uint8List data) { + final out = []; + for (var base = 0; base + _sleepRecordSize <= data.length; base += _sleepRecordSize) { + final sessionSec = _u32(data, base + 0x000); + final midnightSec = _u32(data, base + 0x004); + final marker0 = _u8(data, base + 0x008); + final marker1 = _u8(data, base + 0x009); + const minSec = 1600000000, maxSec = 2000000000; + if (sessionSec < minSec || + sessionSec > maxSec || + midnightSec < minSec || + midnightSec > maxSec || + marker0 != 1 || + marker1 != 1) { + continue; // skip this slot, a later one may still be valid + } + // Stage minutes are offsets from (midnight - 24h) on the strap's own + // wall clock; this layer passes that arithmetic through verbatim and + // leaves timezone resolution to the caller. + final reference = midnightSec - 86400; + int msAt(int minutes) => (reference + minutes * 60) * 1000; + + final sleepStartMin = _u16(data, base + 0x00a); + final sleepEndMin = _u16(data, base + 0x00c); + final avgHr = _u8(data, base + 0x015); + final score = _u8(data, base + 0x016); + final remMin = _u16(data, base + 0x24a); + final lightMin = _u16(data, base + 0x24c); + final deepMin = _u16(data, base + 0x24e); + final wakeMin = _u16(data, base + 0x250); + + final nightStages = []; + final nightStagesStart = base + 0x056; + final nightStagesEnd = base + 0x155; + for (var off = nightStagesStart; off + 5 <= nightStagesEnd; off += 5) { + final slot = _readStageSlot(data, off); + if (slot == null) break; // {0,0} terminates the night timeline + if (slot.type == _gapMarkerType) continue; + nightStages.add(Huami2021Stage( + msAt(slot.start), msAt(slot.end), slot.type)); + } + + out.add(Huami2021SleepSession( + sessionStartMs: sessionSec * 1000, + isNap: false, + avgHr: avgHr, + score: score, + sleepStartMin: sleepStartMin, + sleepEndMin: sleepEndMin, + remMin: remMin, + lightMin: lightMin, + deepMin: deepMin, + wakeMin: wakeMin, + stages: nightStages, + )); + + // Nap descriptors share one stage timeline (0x155..0x24a) across every + // nap in this slot; a nap's own stages are those whose start falls + // within its descriptor's [start, end]. + final napDescStart = base + 0x018; + final napDescEnd = base + 0x054; + final napStagesStart = base + 0x155; + final napStagesEnd = base + 0x24a; + for (var dOff = napDescStart; dOff + 6 <= napDescEnd; dOff += 6) { + final napStart = _u16(data, dOff); + final napEnd = _u16(data, dOff + 2); + final napDur = _u16(data, dOff + 4); + if (napStart == 0 && napDur == 0) break; + if (!(napDur > 0 && napEnd > napStart)) continue; + + final napStages = []; + var rem = 0, light = 0, deep = 0, wake = 0; + for (var off = napStagesStart; off + 5 <= napStagesEnd; off += 5) { + final slot = _readStageSlot(data, off); + if (slot == null) continue; // a gap in the shared timeline, not this nap's end + if (slot.type == _gapMarkerType) continue; + if (slot.start < napStart || slot.start > napEnd) continue; + napStages.add(Huami2021Stage(msAt(slot.start), msAt(slot.end), slot.type)); + final minutes = slot.end - slot.start; + switch (slot.type) { + case kHuami2021StageRem: + rem += minutes; + case kHuami2021StageLight: + light += minutes; + case kHuami2021StageDeep: + deep += minutes; + case kHuami2021StageAwake: + wake += minutes; + } + } + if (napStages.isEmpty) continue; // a descriptor with no stages isn't a session + + out.add(Huami2021SleepSession( + sessionStartMs: msAt(napStart), + isNap: true, + avgHr: 0, + score: 0, + sleepStartMin: napStart, + sleepEndMin: napEnd, + remMin: rem, + lightMin: light, + deepMin: deep, + wakeMin: wake, + stages: napStages, + )); + } + } + return out; +} diff --git a/pubspec.yaml b/pubspec.yaml index 817b046..566fc62 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -9,3 +9,4 @@ environment: dev_dependencies: test: ^1.25.0 lints: ^4.0.0 + pointycastle: ^3.9.1 diff --git a/test/b163_test.dart b/test/b163_test.dart new file mode 100644 index 0000000..16b89a0 --- /dev/null +++ b/test/b163_test.dart @@ -0,0 +1,52 @@ +// sect163r2 (B-163) ECDH known-value tests. +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:openstrap_protocol/openstrap_protocol.dart'; +import 'package:test/test.dart'; + +Uint8List unhex(String s) => Uint8List.fromList( + [for (var i = 0; i < s.length; i += 2) int.parse(s.substring(i, i + 2), radix: 16)]); +String hex(List b) => b.map((e) => e.toRadixString(16).padLeft(2, '0')).join(); + +void main() { + final v = jsonDecode(File('test/fixtures/huami2021_vectors.json').readAsStringSync()) + as Map; + final ecdh = v['ecdh'] as Map; + + test('private key masking clears bits 163 and above', () { + final privAIn = unhex(ecdh['privA_in'] as String); + final kp = keypairFrom(privAIn); + expect(hex(kp.privateKey), ecdh['privA']); + }); + + test('public key derivation matches known value, both sides', () { + final kpA = keypairFrom(unhex(ecdh['privA_in'] as String)); + expect(hex(kpA.publicKey), ecdh['pubA']); + final kpB = keypairFrom(unhex(ecdh['privB_in'] as String)); + expect(hex(kpB.publicKey), ecdh['pubB']); + }); + + test('shared secret matches from both sides, and agrees', () { + final privA = unhex(ecdh['privA'] as String); + final privB = unhex(ecdh['privB'] as String); + final pubA = unhex(ecdh['pubA'] as String); + final pubB = unhex(ecdh['pubB'] as String); + // The fixture's 'shared' is the full 48-byte point (X||Y); the protocol + // uses only the X half (first 24 bytes). + final fullShared = ecdh['shared'] as String; + final expectedX = fullShared.substring(0, 48); + final sharedFromA = sharedSecret(privA, pubB); + final sharedFromB = sharedSecret(privB, pubA); + expect(hex(sharedFromA), expectedX); + expect(hex(sharedFromB), expectedX); + }); + + test('a corrupted peer public key is rejected, not silently accepted', () { + final priv = unhex(ecdh['privA'] as String); + final badPub = Uint8List.fromList(unhex(ecdh['pubB'] as String)); + badPub[0] ^= 0xff; + expect(() => sharedSecret(priv, badPub), throwsA(isA())); + }); +} diff --git a/test/fixtures/huami2021_vectors.json b/test/fixtures/huami2021_vectors.json new file mode 100644 index 0000000..a6b1b06 --- /dev/null +++ b/test/fixtures/huami2021_vectors.json @@ -0,0 +1,523 @@ +{ + "ecdh": { + "privA_in": "030a11181f262d343b424950575e656c737a81888f969da4", + "privA": "030a11181f262d343b424950575e656c737a818803000000", + "pubA": "62499465d5db3632d3e897d5674d479608ec1c6a01000000206cb342c029eb95881d04469f462358678ea0aa02000000", + "privB_in": "fffaf5f0ebe6e1dcd7d2cdc8c3beb9b4afaaa5a09b96918c", + "privB": "fffaf5f0ebe6e1dcd7d2cdc8c3beb9b4afaaa5a003000000", + "pubB": "13fff53cd2807fe1236f82eb25d3a7be341d331902000000a9fd33d2810414a6df1be8dd7f3922718ac8745f03000000", + "shared": "f1baa57b5b6009620cd47a8a1da2f6f62de0221e02000000a096913042fed836a34d4d956493589dffc123ff04000000" + }, + "auth": { + "authKey": "a0a1a2a3a4a5a6a7a8a9aaabacadaeaf", + "remoteRandom": "0112233445566778899aabbccddeef00", + "shared": "f1baa57b5b6009620cd47a8a1da2f6f62de0221e02000000a096913042fed836a34d4d956493589dffc123ff04000000", + "sequence": 2074458865, + "sessionKey": "ac75d829b9075051854988b5aeadaeaf", + "proof": "05c0d968d642d5cc3415b8b273dc49d930258cd4a1321d2a8bdd985428080c34a0" + }, + "crc32": { + "data": "000d1a2734414e5b6875828f9ca9b6c3d0ddeaf704111e2b3845525f6c798693a0adbac7d4", + "crc": 526198563 + }, + "aes": { + "key": "000102030405060708090a0b0c0d0e0f", + "plain": "000306090c0f1215181b1e2124272a2d303336393c3f4245484b4e5154575a5d", + "cipher": "551b13ba85ed16edfc1e337a28b37ab8ebef9002dd9ee1e7242d6af5e38458c5" + }, + "chunks": { + "plain_short": { + "mtu": 247, + "endpoint": 22, + "payload": "03", + "chunks": [ + "030700010001000000160003" + ] + }, + "plain_long": { + "mtu": 247, + "endpoint": 130, + "payload": "0524436281a0bfdefd1c3b5a7998b7d6f51433527190afceed0c2b4a6988a7c6e504234261809fbeddfc1b3a597897b6d5f4133251708faecdec0b2a496887a6c5e4032241607f9ebddcfb1a39587796b5d4f31231506f8eadcceb0a29486786a5c4e30221405f7e9dbcdbfa1938577695b4d3f211304f6e8daccbea0928476685a4c3e201203f5e7d9cbbdaf91837567594b3d2f1102f4e6d8cabcae90827466584a3c2e1001f3e5d7c9bbad9f81736557493b2d1f00f2e4d6c8baac9e80726456483a2c1e0ff1e3d5c7b9ab9d8f71635547392b1d0ef0e2d4c6b8aa9c8e70625446382a1c0dffe1d3c5b7a99b8d7f61534537291b0cfee0d2c4b6a89a8c7e60524436281a0bfdefd1c3b5a7998b7d6f51433527190afceed0c2b4a6988a7c6e504234261809fbeddfc1b3a597897b6d5f4133251708faecdec0b2a496887a6c5e4032241607f9ebddcfb1a39587796b5d4f31231506f8eadcceb0a29486786a5c4e30221405f7e9dbcdbfa1938577695b4d3f211304f6e8daccbea0928476685a4c3e201203f5e7d9cbbdaf91837567594b3d2f1102f4e6d8cabcae90827466584a3c2e1001f3e5d7c9bbad9f81736557493b2d1f00f2e4d6c8baac9e80726456483a2c1e0ff1e3d5c7b9ab9d8f71635547392b1d0ef0e2d4c6b8aa9c8e70625446382a1c0dffe1d3c5b7a99b8d7f61534537291b0cfee0d2c4b6a89a8c7e60524436281a0bfdefd1c3b5a7998b7d6f51433527190afceed0c2b4a6988a7c6e504234261809fbeddfc1b3a597897b6d5f4133251708faecdec0b2a496887a6c5e4032241607f9ebddcfb1a39587796b5d4f31231506f8e", + "chunks": [ + "03010002005802000082000524436281a0bfdefd1c3b5a7998b7d6f51433527190afceed0c2b4a6988a7c6e504234261809fbeddfc1b3a597897b6d5f4133251708faecdec0b2a496887a6c5e4032241607f9ebddcfb1a39587796b5d4f31231506f8eadcceb0a29486786a5c4e30221405f7e9dbcdbfa1938577695b4d3f211304f6e8daccbea0928476685a4c3e201203f5e7d9cbbdaf91837567594b3d2f1102f4e6d8cabcae90827466584a3c2e1001f3e5d7c9bbad9f81736557493b2d1f00f2e4d6c8baac9e80726456483a2c1e0ff1e3d5c7b9ab9d8f71635547392b1d0ef0e2d4c6b8aa9c8e70625446382a1c0dffe1d", + "03000002013c5b7a99b8d7f61534537291b0cfee0d2c4b6a89a8c7e60524436281a0bfdefd1c3b5a7998b7d6f51433527190afceed0c2b4a6988a7c6e504234261809fbeddfc1b3a597897b6d5f4133251708faecdec0b2a496887a6c5e4032241607f9ebddcfb1a39587796b5d4f31231506f8eadcceb0a29486786a5c4e30221405f7e9dbcdbfa1938577695b4d3f211304f6e8daccbea0928476685a4c3e201203f5e7d9cbbdaf91837567594b3d2f1102f4e6d8cabcae90827466584a3c2e1001f3e5d7c9bbad9f81736557493b2d1f00f2e4d6c8baac9e80726456483a2c1e0ff1e3d5c7b9ab9d8f71635547392b1d0ef0e", + "03060002022d4c6b8aa9c8e70625446382a1c0dffe1d3c5b7a99b8d7f61534537291b0cfee0d2c4b6a89a8c7e60524436281a0bfdefd1c3b5a7998b7d6f51433527190afceed0c2b4a6988a7c6e504234261809fbeddfc1b3a597897b6d5f4133251708faecdec0b2a496887a6c5e4032241607f9ebddcfb1a39587796b5d4f31231506f8e" + ] + }, + "plain_tiny": { + "mtu": 23, + "endpoint": 22, + "payload": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f2021222324252627", + "chunks": [ + "0301000100280000001600000102030405060708", + "0300000101090a0b0c0d0e0f1011121314151617", + "030000010218191a1b1c1d1e1f20212223242526", + "030600010327" + ] + }, + "encrypted": { + "mtu": 247, + "sessionKey": "101316191c1f2225282b2e3134373a3d", + "sequence": 16909060, + "messages": [ + { + "endpoint": 22, + "payload": "03", + "chunks": [ + "030f000100010000001600d7ffe0d3c479d8a5758dee95b95c1735" + ] + }, + { + "endpoint": 71, + "payload": "fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0efeeedecebeae9e8e7e6e5e4e3e2e1e0dfdedddcdbdad9d8d7d6d5d4d3d2d1d0cfcecdcccbcac9c8c7c6c5c4c3c2c1c0bfbebdbcbbbab9b8b7b6b5b4b3b2b1b0afaeadacabaaa9a8a7a6a5a4a3a2a1a09f9e9d9c9b9a999897969594939291908f8e8d8c8b8a898887868584838281807f7e7d7c7b7a797877767574737271706f6e6d6c6b6a696867666564636261605f5e5d5c5b5a595857565554535251504f4e4d4c4b4a494847464544434241403f3e3d3c3b3a393837363534333231302f2e2d2c2b2a292827262524232221201f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0efeeedecebeae9e8e7e6e5e4e3e2e1e0dfdedddcdbdad9d8d7d6d5d4", + "chunks": [ + "03090002002c0100004700e80e7e8a1aadd3002b378edbed6c7f2719000b3c4c39ef7df58af27a0ad9d518fe05696461dedb4318079fa21a4dd6d2e44987b1964e195ac8a0f39fc8467076598ccaa610f4bb63914a0c8351b761bfb7a049b6bfa0f32f2bd62c01153e3bcade2b9c9df6cf2b9e89cd3b4485c867120171bfbbffb5594a60903d9c9a2bceaa1b43cb2b40c2c85012fa236b9f5a29d27dbc4e7947397d0565c835d778a1c9fe0686a186e4bb7bba0978cfaba36338663625c88ce023b77056c4cd0453a5a0b6db6f647084e5d17ab0184a5957caaab5964928bf32caa47f0279bca9a3d64133d741cf383844143866", + "030e000201a59fbfd2dff4e8cd92323243bceab14cd2a4d1a516909ee80e7e8a1aadd3002b378edbed6c7f2719000b3c4c39ef7df58af27a0ad9d51818b26edbfb78ea5ce7f992d187d76fd85cb5856fb6e71e846d44c3ccd303be11" + ] + } + ] + } + }, + "parsers": { + "roundStartMs": 1780000020000, + "activity": { + "0x01": { + "code": 1, + "raw": "001100460000000001110c00000000000211ffff000000000311647800000000041105ff0000000005110037000000000611fab4000000000711ff3c000000000811010000000000091100ff000000000a113c63000000000b11091e00000000", + "samples": [ + { + "ms": 1780000020000, + "metric": "hr", + "value": 70.0 + }, + { + "ms": 1780000080000, + "metric": "steps", + "value": 12.0 + }, + { + "ms": 1780000200000, + "metric": "hr", + "value": 120.0 + }, + { + "ms": 1780000200000, + "metric": "steps", + "value": 100.0 + }, + { + "ms": 1780000260000, + "metric": "steps", + "value": 5.0 + }, + { + "ms": 1780000320000, + "metric": "hr", + "value": 55.0 + }, + { + "ms": 1780000380000, + "metric": "hr", + "value": 180.0 + }, + { + "ms": 1780000380000, + "metric": "steps", + "value": 250.0 + }, + { + "ms": 1780000440000, + "metric": "hr", + "value": 60.0 + }, + { + "ms": 1780000500000, + "metric": "steps", + "value": 1.0 + }, + { + "ms": 1780000620000, + "metric": "hr", + "value": 99.0 + }, + { + "ms": 1780000620000, + "metric": "steps", + "value": 60.0 + }, + { + "ms": 1780000680000, + "metric": "hr", + "value": 30.0 + }, + { + "ms": 1780000680000, + "metric": "steps", + "value": 9.0 + } + ] + }, + "0x01_4byte": { + "code": 1, + "raw": "000003500000ff51000000ff000007000000015a", + "samples": [ + { + "ms": 1780000020000, + "metric": "hr", + "value": 80.0 + }, + { + "ms": 1780000020000, + "metric": "steps", + "value": 3.0 + }, + { + "ms": 1780000080000, + "metric": "hr", + "value": 81.0 + }, + { + "ms": 1780000200000, + "metric": "steps", + "value": 7.0 + }, + { + "ms": 1780000260000, + "metric": "hr", + "value": 90.0 + }, + { + "ms": 1780000260000, + "metric": "steps", + "value": 1.0 + } + ] + }, + "0x13": { + "code": 19, + "raw": "0aff003764ff2a", + "samples": [ + { + "ms": 1780000020000, + "metric": "stress", + "value": 10.0 + }, + { + "ms": 1780000140000, + "metric": "stress", + "value": 0.0 + }, + { + "ms": 1780000200000, + "metric": "stress", + "value": 55.0 + }, + { + "ms": 1780000260000, + "metric": "stress", + "value": 100.0 + }, + { + "ms": 1780000380000, + "metric": "stress", + "value": 42.0 + } + ] + }, + "0x2E": { + "code": 46, + "raw": "0000800d00000000000088ff000000000000470d00000000", + "samples": [ + { + "ms": 1780000020000, + "metric": "temperature_c", + "value": 34.56 + }, + { + "ms": 1780000080000, + "metric": "temperature_c", + "value": -1.2 + }, + { + "ms": 1780000140000, + "metric": "temperature_c", + "value": 33.99 + } + ] + }, + "0x02": { + "code": 2, + "raw": "00a5186a33482ca6186a330058a7186a33ff84a8186a3340", + "samples": [ + { + "ms": 1780000000000, + "metric": "manual_hr", + "value": 72.0 + }, + { + "ms": 1780000900000, + "metric": "manual_hr", + "value": 64.0 + } + ] + }, + "0x12": { + "code": 18, + "raw": "00a5186a331e2ca6186a33ff", + "samples": [ + { + "ms": 1780000000000, + "metric": "stress_manual", + "value": 30.0 + } + ] + }, + "0x3A": { + "code": 58, + "raw": "00a5186a33342ca6186a3335", + "samples": [ + { + "ms": 1780000000000, + "metric": "resting_hr", + "value": 52.0 + }, + { + "ms": 1780000300000, + "metric": "resting_hr", + "value": 53.0 + } + ] + }, + "0x3D": { + "code": 61, + "raw": "00a5186a33ab", + "samples": [ + { + "ms": 1780000000000, + "metric": "max_hr", + "value": 171.0 + } + ] + }, + "0x49": { + "code": 73, + "raw": "00a5186a332d2ca6186a330058a7186a33ff84a8186a3358", + "samples": [ + { + "ms": 1780000000000, + "metric": "hrv", + "value": 45.0 + }, + { + "ms": 1780000900000, + "metric": "hrv", + "value": 88.0 + } + ] + }, + "0x38": { + "code": 56, + "raw": "00a5186a440e000058a7186a44ff0000b0a9186a4400000008ac186a44160000", + "samples": [ + { + "ms": 1780000000000, + "metric": "respiratory_rate", + "value": 14.0 + }, + { + "ms": 1780001800000, + "metric": "respiratory_rate", + "value": 22.0 + } + ] + }, + "0x25": { + "code": 37, + "raw": "0200a5186a6100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010b3186adf00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020c1186a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "samples": [ + { + "ms": 1780000000000, + "metric": "spo2", + "value": 97.0 + }, + { + "ms": 1780003600000, + "metric": "spo2", + "value": 95.0 + }, + { + "ms": 1780007200000, + "metric": "spo2", + "value": 0.0 + } + ] + }, + "0x25_bad_version": { + "code": 37, + "raw": "015a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a", + "samples": [] + }, + "0x26": { + "code": 38, + "raw": "0200a5186a601e0000000000000000000000000000000000000000000000003ca5186a001e00000000000000000000000000000000000000000000000078a5186a651e000000000000000000000000000000000000000000000000b4a5186a581e000000000000000000000000000000000000000000000000", + "samples": [ + { + "ms": 1780000000000, + "metric": "spo2_sleep", + "value": 96.0 + }, + { + "ms": 1780000180000, + "metric": "spo2_sleep", + "value": 88.0 + } + ] + } + }, + "sleep": { + "raw": "48cb186a00d7186a01016e05490700000000000000365100e8081009280000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007006e057805077805c80504c805c80580c80518060518067206087206770607770649070400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e808f20807f208060904060910090560096a09040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005a00220150000f00381b1a6a80281a6a01006e0549070000000000000036510000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007006e057805077805c80504c805c80580c8051806051806720608720677060777064907040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005a00220150000f00c81c1a6a80281a6a01016e0549070000000000000036510000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007006e057805077805c80504c805c80580c8051806051806720608720677060777064907040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005a00220150000f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "sessions": [ + { + "sessionStartMs": 1780009800000, + "sleepStartMin": 1390, + "sleepEndMin": 1865, + "avgHr": 54, + "score": 81, + "remMin": 90, + "lightMin": 290, + "deepMin": 80, + "wakeMin": 15, + "isNap": false, + "stages": [ + [ + 1780009800000, + 1780010400000, + 7 + ], + [ + 1780010400000, + 1780015200000, + 4 + ], + [ + 1780015200000, + 1780020000000, + 5 + ], + [ + 1780020000000, + 1780025400000, + 8 + ], + [ + 1780025400000, + 1780025700000, + 7 + ], + [ + 1780025700000, + 1780038300000, + 4 + ] + ] + }, + { + "sessionStartMs": 1780063200000, + "sleepStartMin": 2280, + "sleepEndMin": 2320, + "avgHr": 0, + "score": 0, + "remMin": 0, + "lightMin": 20, + "deepMin": 10, + "wakeMin": 10, + "isNap": true, + "stages": [ + [ + 1780063200000, + 1780063800000, + 7 + ], + [ + 1780063800000, + 1780065000000, + 4 + ], + [ + 1780065000000, + 1780065600000, + 5 + ] + ] + }, + { + "sessionStartMs": 1780096200000, + "sleepStartMin": 1390, + "sleepEndMin": 1865, + "avgHr": 54, + "score": 81, + "remMin": 90, + "lightMin": 290, + "deepMin": 80, + "wakeMin": 15, + "isNap": false, + "stages": [ + [ + 1780096200000, + 1780096800000, + 7 + ], + [ + 1780096800000, + 1780101600000, + 4 + ], + [ + 1780101600000, + 1780106400000, + 5 + ], + [ + 1780106400000, + 1780111800000, + 8 + ], + [ + 1780111800000, + 1780112100000, + 7 + ], + [ + 1780112100000, + 1780124700000, + 4 + ] + ] + } + ] + }, + "workout": { + "raw": "00800a03322e3112080880dacfcf06182c3d010203043a030899035a050d0000803f82010208359a0107087a108c01185800800a03322e3112080880fdd4cf06180a3d010203043a0308901c5a050d0000803f820103089a039a010808830110a801184600800a03322e31120508b96018013d010203043a0208015a050d0000803f82010208019a0106080110011801", + "workouts": [ + { + "startMs": 1777593600000, + "sportType": 44, + "durationSec": 409, + "calories": 53, + "avgHr": 122, + "maxHr": 140, + "minHr": 88 + }, + { + "startMs": 1777680000000, + "sportType": 10, + "durationSec": 3600, + "calories": 410, + "avgHr": 131, + "maxHr": 168, + "minHr": 70 + } + ] + } + } +} \ No newline at end of file diff --git a/test/huami2021_auth_test.dart b/test/huami2021_auth_test.dart new file mode 100644 index 0000000..0edf838 --- /dev/null +++ b/test/huami2021_auth_test.dart @@ -0,0 +1,108 @@ +// Huami2021/ZeppOS auth handshake (endpoint 0x0082) known-value tests. +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:openstrap_protocol/openstrap_protocol.dart'; +import 'package:pointycastle/export.dart' + show AESEngine, ECBBlockCipher, KeyParameter; +import 'package:test/test.dart'; + +Uint8List unhex(String s) => Uint8List.fromList( + [for (var i = 0; i < s.length; i += 2) int.parse(s.substring(i, i + 2), radix: 16)]); +String hex(List b) => b.map((e) => e.toRadixString(16).padLeft(2, '0')).join(); + +Uint8List _aesEcb(Uint8List key, Uint8List data) { + final c = ECBBlockCipher(AESEngine())..init(true, KeyParameter(key)); + final out = Uint8List(data.length); + for (var i = 0; i < data.length; i += 16) { + c.processBlock(data, i, out, i); + } + return out; +} + +void main() { + final v = jsonDecode(File('test/fixtures/huami2021_vectors.json').readAsStringSync()) + as Map; + final ecdh = v['ecdh'] as Map; + final auth = v['auth'] as Map; + + // Our side uses ecdh.privA/pubA; the device's reply carries ecdh.pubB as + // its public key, so the derived shared secret matches ecdh.shared. + B163Keypair ourKeypair() => B163Keypair( + unhex(ecdh['privA'] as String), unhex(ecdh['pubA'] as String)); + + Uint8List step2Reply() => Uint8List.fromList([ + 0x10, 0x04, 0x01, + ...unhex(auth['remoteRandom'] as String), + ...unhex(ecdh['pubB'] as String), + ]); + + test('step 1 payload is 04 02 00 02 followed by our public key', () { + final hs = Huami2021Auth(unhex(auth['authKey'] as String), + aesEcb: _aesEcb, keypair: ourKeypair()); + final payload = hs.start(); + expect(hex(payload.sublist(0, 4)), '04020002'); + expect(hex(payload.sublist(4)), ecdh['pubA']); + }); + + test('step 2 reply yields the known proof, sequence and session key', () { + final hs = Huami2021Auth(unhex(auth['authKey'] as String), + aesEcb: _aesEcb, keypair: ourKeypair()); + hs.start(); + final event = hs.onPayload(step2Reply()); + final proof = (event as Huami2021AuthSendProof).payload; + expect(hex(proof), auth['proof']); + }); + + test('step 5 success yields the known session key and sequence', () { + final hs = Huami2021Auth(unhex(auth['authKey'] as String), + aesEcb: _aesEcb, keypair: ourKeypair()); + hs.start(); + hs.onPayload(step2Reply()); + final event = hs.onPayload(Uint8List.fromList([0x10, 0x05, 0x01])); + final done = event as Huami2021Authenticated; + expect(hex(done.sessionKey), auth['sessionKey']); + expect(done.sequence, auth['sequence']); + }); + + test('status 0x25 on step 5 reports WrongAuthKey', () { + final hs = Huami2021Auth(unhex(auth['authKey'] as String), + aesEcb: _aesEcb, keypair: ourKeypair()); + hs.start(); + hs.onPayload(step2Reply()); + final event = hs.onPayload(Uint8List.fromList([0x10, 0x05, 0x25])); + final failed = (event as Huami2021AuthFailed).failure; + expect(failed, isA()); + }); + + test('a non-success status on step 2 is reported, not retried silently', () { + final hs = Huami2021Auth(unhex(auth['authKey'] as String), + aesEcb: _aesEcb, keypair: ourKeypair()); + hs.start(); + final event = hs.onPayload(Uint8List.fromList([0x10, 0x04, 0x02])); + final failed = (event as Huami2021AuthFailed).failure as AuthRejected; + expect(failed.step, 2); + expect(failed.status, 2); + }); + + test('an unrelated payload before the handshake starts is ignored', () { + final hs = Huami2021Auth(unhex(auth['authKey'] as String), + aesEcb: _aesEcb, keypair: ourKeypair()); + expect(hs.onPayload(Uint8List.fromList([0x01, 0x02])), + isA()); + }); + + test('starting twice throws', () { + final hs = Huami2021Auth(unhex(auth['authKey'] as String), + aesEcb: _aesEcb, keypair: ourKeypair()); + hs.start(); + expect(() => hs.start(), throwsStateError); + }); + + test('a 15-byte auth key is rejected at construction', () { + expect( + () => Huami2021Auth(Uint8List(15), aesEcb: _aesEcb), + throwsArgumentError); + }); +} diff --git a/test/huami2021_chunks_test.dart b/test/huami2021_chunks_test.dart new file mode 100644 index 0000000..8e71f39 --- /dev/null +++ b/test/huami2021_chunks_test.dart @@ -0,0 +1,154 @@ +// Huami2021 chunk transport known-value tests. +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:openstrap_protocol/openstrap_protocol.dart'; +import 'package:pointycastle/export.dart' + show AESEngine, ECBBlockCipher, KeyParameter; +import 'package:test/test.dart'; + +Uint8List unhex(String s) => Uint8List.fromList( + [for (var i = 0; i < s.length; i += 2) int.parse(s.substring(i, i + 2), radix: 16)]); +String hex(List b) => b.map((e) => e.toRadixString(16).padLeft(2, '0')).join(); + +Uint8List _aes(Uint8List key, Uint8List data, bool enc) { + final c = ECBBlockCipher(AESEngine())..init(enc, KeyParameter(key)); + final out = Uint8List(data.length); + for (var i = 0; i < data.length; i += 16) { + c.processBlock(data, i, out, i); + } + return out; +} + +Uint8List aesEnc(Uint8List k, Uint8List d) => _aes(k, d, true); +Uint8List aesDec(Uint8List k, Uint8List d) => _aes(k, d, false); + +void main() { + final v = jsonDecode(File('test/fixtures/huami2021_vectors.json').readAsStringSync()) + as Map; + final chunks = v['chunks'] as Map; + + void expectEncodes(Map m, Huami2021Encoder enc, + {bool encrypt = false}) { + final got = enc.encode(m['endpoint'] as int, unhex(m['payload'] as String), + encrypt: encrypt); + expect(got.map(hex).toList(), (m['chunks'] as List).cast()); + } + + test('first chunk header: marker, flags, handle, count, length, endpoint', () { + final c = Huami2021Encoder().encode(0x0016, [0x03]).single; + expect(hex(c), '030700010001000000160003'); + }); + + test('handle increments per message and wraps', () { + final enc = Huami2021Encoder(); + for (var i = 0; i < 254; i++) { + enc.encode(1, [1]); + } + expect(enc.encode(1, [1]).single[3], 0xFF); + expect(enc.encode(1, [1]).single[3], 0x00); + }); + + test('ack layout', () => expect(hex(huami2021Ack(5, 3)), '0400050103')); + + test('plain framing matches known-value vectors at MTU 247 and 23', () { + final shared = Huami2021Encoder(mtu: 247); // generator reused one encoder + Map m(String k) => chunks[k] as Map; + expectEncodes(m('plain_short'), shared); + expectEncodes(m('plain_long'), shared); + expectEncodes(m('plain_tiny'), Huami2021Encoder(mtu: 23)); + }); + + test('encrypted framing matches known-value vectors, and decodes', () { + final e = chunks['encrypted'] as Map; + final key = unhex(e['sessionKey'] as String); + final enc = Huami2021Encoder(encrypt: aesEnc) + ..setEncryption(key, e['sequence'] as int); + final msgs = (e['messages'] as List).cast>(); + for (final m in msgs) { + expectEncodes(m, enc, encrypt: true); + } + final dec = Huami2021Decoder(decrypt: aesDec); + Huami2021Frame? f; + for (final c in (msgs[1]['chunks'] as List).cast()) { + f = dec.feed(unhex(c), sessionKey: key); + } + expect(hex(f!.payload), msgs[1]['payload']); + expect(f.encrypted, isTrue); + }); + + test('encrypted frame without a session key yields no frame', () { + final key = Uint8List(16); + final enc = Huami2021Encoder(encrypt: aesEnc)..setEncryption(key, 0); + final c = enc.encode(1, [1, 2], encrypt: true).single; + expect(Huami2021Decoder(decrypt: aesDec).feed(c), isNull); + }); + + test('round trip, 100 bytes over several chunks', () { + final key = Uint8List.fromList([for (var i = 0; i < 16; i++) i * 9]); + final enc = Huami2021Encoder(mtu: 40, encrypt: aesEnc)..setEncryption(key, 7); + final payload = Uint8List.fromList([for (var i = 0; i < 100; i++) i]); + final cs = enc.encode(0x0047, payload, encrypt: true); + expect(cs.length, greaterThan(1)); + final dec = Huami2021Decoder(decrypt: aesDec); + Huami2021Frame? f; + for (final c in cs) { + f = dec.feed(c, sessionKey: key); + } + expect(f!.payload, payload); + expect(f.endpoint, 0x0047); + expect(f.needsAck, isTrue); + }); + + test('an orphan chunk with no preceding first chunk is rejected, not an ' + 'empty frame on endpoint 0', () { + final enc = Huami2021Encoder(mtu: 40); + final payload = Uint8List.fromList([for (var i = 0; i < 100; i++) i]); + final cs = enc.encode(7, payload); + expect(cs.length, greaterThan(1)); + // Feed only the LAST chunk — no first chunk was ever seen. + expect(Huami2021Decoder().feed(cs.last), isNull); + }); + + test('a dropped middle chunk is rejected, not a silently truncated ' + 'payload', () { + final enc = Huami2021Encoder(mtu: 40); + final payload = Uint8List.fromList([for (var i = 0; i < 100; i++) i]); + final cs = enc.encode(7, payload); + expect(cs.length, greaterThan(2), reason: 'need at least 3 chunks to drop a middle one'); + final dec = Huami2021Decoder(); + expect(dec.feed(cs[0]), isNull); // first chunk: no frame yet + // Skip cs[1] — simulate a dropped middle chunk — then feed the rest. + for (var i = 2; i < cs.length; i++) { + final f = dec.feed(cs[i]); + if (i < cs.length - 1) { + expect(f, isNull); + } else { + expect(f, isNull, reason: 'the gap must be rejected, not reassembled'); + } + } + }); + + test('a repeated chunk (duplicate count) is rejected', () { + final enc = Huami2021Encoder(mtu: 40); + final payload = Uint8List.fromList([for (var i = 0; i < 100; i++) i]); + final cs = enc.encode(7, payload); + expect(cs.length, greaterThan(2)); + final dec = Huami2021Decoder(); + expect(dec.feed(cs[0]), isNull); + expect(dec.feed(cs[1]), isNull); + expect(dec.feed(cs[1]), isNull); // repeated, not the real cs[2] + }); + + test('a wrong session key decrypts to garbage that the CRC check catches, ' + 'yielding null rather than a corrupted frame', () { + final rightKey = Uint8List.fromList([for (var i = 0; i < 16; i++) i * 9]); + final wrongKey = Uint8List.fromList([for (var i = 0; i < 16; i++) i * 7 + 1]); + final enc = Huami2021Encoder(encrypt: aesEnc)..setEncryption(rightKey, 1); + final payload = Uint8List.fromList([for (var i = 0; i < 20; i++) i]); + final chunk = enc.encode(9, payload, encrypt: true).single; + final dec = Huami2021Decoder(decrypt: aesDec); + expect(dec.feed(chunk, sessionKey: wrongKey), isNull); + }); +} diff --git a/test/huami2021_fetch_test.dart b/test/huami2021_fetch_test.dart new file mode 100644 index 0000000..f4f0cba --- /dev/null +++ b/test/huami2021_fetch_test.dart @@ -0,0 +1,156 @@ +// Huami2021/ZeppOS history-fetch protocol: synthetic tests (no captured +// device stream exists for this layer — see the file header in +// lib/src/huami2021_fetch.dart). These test the STATE/LOGIC, which is +// verifiable by construction, not a byte layout that needs real hardware. +import 'dart:typed_data'; + +import 'package:openstrap_protocol/openstrap_protocol.dart'; +import 'package:test/test.dart'; + +String hex(List b) => b.map((e) => e.toRadixString(16).padLeft(2, '0')).join(); + +void main() { + group('time8 and the start request', () { + test('encodes year LE, month, day, hour, minute, 0, tz in quarter-hours', () { + final since = DateTime(2026, 3, 4, 13, 7); + final t8 = huami2021Time8(since, 330); // UTC+5:30 → 22 quarters + expect(t8.length, 8); + expect(t8[0] | (t8[1] << 8), 2026); + expect(t8[2], 3); + expect(t8[3], 4); + expect(t8[4], 13); + expect(t8[5], 7); + expect(t8[6], 0); + expect(t8[7], 22); + }); + + test('a negative UTC offset still masks into one byte', () { + final t8 = huami2021Time8(DateTime(2026, 1, 1), -300); // UTC-5:00 + expect(t8[7], (-20) & 0xFF); + }); + + test('start request is 0x01, type, then time8', () { + final req = huami2021FetchStartRequest( + kHuami2021TypeActivity, DateTime(2026, 1, 1, 0, 0), 0); + expect(req[0], 0x01); + expect(req[1], kHuami2021TypeActivity); + expect(req.length, 10); + }); + }); + + group('start reply parsing', () { + test('a real reply is parsed with status, expected, and roundStart', () { + final b = Uint8List.fromList([ + 0x10, 0x01, 0x01, // status ok + 0x05, 0x00, 0x00, 0x00, // expected = 5 + 0xEA, 0x07, // year 2026 LE + 3, 4, 13, 7, 0, // month, day, hour, min, sec + ]); + final reply = parseHuami2021FetchStart(b)!; + expect(reply.ok, isTrue); + expect(reply.expected, 5); + expect(reply.hasData, isTrue); + expect(reply.roundStart, DateTime(2026, 3, 4, 13, 7, 0)); + }); + + test('expected == 0 means hasData is false even on success', () { + final b = Uint8List.fromList( + [0x10, 0x01, 0x01, 0, 0, 0, 0, 0xEA, 0x07, 1, 1, 0, 0, 0]); + expect(parseHuami2021FetchStart(b)!.hasData, isFalse); + }); + + test('an all-zero date falls back to 1970, never a silently-normalised ' + 'garbage date', () { + final b = Uint8List.fromList( + [0x10, 0x01, 0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + // Dart's DateTime(0, 0, 0, ...) would otherwise silently become + // -0001-11-30 instead of failing — this must never reach a caller. + expect(parseHuami2021FetchStart(b)!.roundStart, DateTime(1970)); + }); + + test('an implausible month/day/hour/minute/second falls back to 1970', + () { + final b = Uint8List.fromList( + [0x10, 0x01, 0x01, 1, 0, 0, 0, 0xEA, 0x07, 13, 32, 24, 60, 60]); + expect(parseHuami2021FetchStart(b)!.roundStart, DateTime(1970)); + }); + + test('a non-success status is not hasData', () { + final b = Uint8List.fromList( + [0x10, 0x01, 0x02, 5, 0, 0, 0, 0xEA, 0x07, 1, 1, 0, 0, 0]); + final reply = parseHuami2021FetchStart(b)!; + expect(reply.ok, isFalse); + expect(reply.hasData, isFalse); + }); + + test('an unrelated or too-short payload is not a start reply', () { + expect(parseHuami2021FetchStart(Uint8List.fromList([0x01, 0x02])), isNull); + expect(parseHuami2021FetchStart(Uint8List.fromList([0x10, 0x02, 1])), isNull); + }); + }); + + test('round-end reply', () { + expect(parseHuami2021FetchRoundEnd(Uint8List.fromList([0x10, 0x02, 0x01])), 0x01); + expect(parseHuami2021FetchRoundEnd(Uint8List.fromList([0x10, 0x01, 0x01])), isNull); + }); + + group('Huami2021FetchBuffer', () { + test('reassembles contiguous packets, stripping the counter byte', () { + final buf = Huami2021FetchBuffer(); + buf.add([0, 1, 2, 3]); + buf.add([1, 4, 5]); + buf.add([2, 6]); + expect(buf.ok, isTrue); + expect(buf.bytes, [1, 2, 3, 4, 5, 6]); + }); + + test('a counter gap flips ok false and further packets are ignored', () { + final buf = Huami2021FetchBuffer(); + buf.add([0, 1]); + buf.add([2, 9]); // should have been 1 + expect(buf.ok, isFalse); + buf.add([2, 9]); // ignored: round already discarded + expect(buf.bytes, [1]); + }); + + test('the counter wraps at 0xFF back to 0', () { + final buf = Huami2021FetchBuffer(); + var expectedCounter = 0; + for (var i = 0; i < 260; i++) { + buf.add([expectedCounter & 0xff, i]); + expectedCounter++; + } + expect(buf.ok, isTrue); + expect(buf.bytes.length, 260); + }); + }); + + group('count validation', () { + test('type 0x01 expected is a record count, 8 bytes per record', () { + expect(huami2021FetchCountMatches(kHuami2021TypeActivity, 3, 24), isTrue); + expect(huami2021FetchCountMatches(kHuami2021TypeActivity, 3, 20), isFalse); + }); + test('type 0x01 falls back to 4-byte records when length is not a multiple of 8', () { + expect(huami2021FetchCountMatches(kHuami2021TypeActivity, 3, 12), isTrue); + }); + test('every other type is a plain byte count', () { + expect(huami2021FetchCountMatches(kHuami2021TypeStress, 10, 10), isTrue); + expect(huami2021FetchCountMatches(kHuami2021TypeStress, 10, 9), isFalse); + }); + }); + + group('gap-skip paging', () { + test('activity: minutes = rawLen / recordSize, clamped 1-1440', () { + expect(huami2021FetchGapSkipMinutes(kHuami2021TypeActivity, 24), 3); + expect(huami2021FetchGapSkipMinutes(kHuami2021TypeActivity, 0), 1); // clamp up + expect(huami2021FetchGapSkipMinutes(kHuami2021TypeActivity, 100000), 1440); // clamp down + }); + test('stress: record size is 1 byte, so minutes == rawLen', () { + expect(huami2021FetchGapSkipMinutes(kHuami2021TypeStress, 7), 7); + }); + test('any other type is not a gap-skip type', () { + expect(() => huami2021FetchGapSkipMinutes(kHuami2021TypeSleep, 10), + throwsArgumentError); + }); + }); +} diff --git a/test/huami2021_records_test.dart b/test/huami2021_records_test.dart new file mode 100644 index 0000000..426ea58 --- /dev/null +++ b/test/huami2021_records_test.dart @@ -0,0 +1,307 @@ +// Huami2021/ZeppOS record decoders: known-value tests against real device +// output, plus guard tests for the sentinel/gap/invalid-slot rules. +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:openstrap_protocol/openstrap_protocol.dart'; +import 'package:test/test.dart'; + +Uint8List unhex(Object? raw) { + final s = raw! as String; + return Uint8List.fromList( + [for (var i = 0; i < s.length; i += 2) int.parse(s.substring(i, i + 2), radix: 16)]); +} + +void main() { + final v = jsonDecode(File('test/fixtures/huami2021_vectors.json').readAsStringSync()) + as Map; + final parsers = v['parsers'] as Map; + final roundStartMs = parsers['roundStartMs'] as int; + final activity = parsers['activity'] as Map; + + void expectSamples(List got, String key) { + final expected = (activity[key]['samples'] as List).cast>(); + expect(got.length, expected.length, reason: 'sample count for $key'); + for (var i = 0; i < expected.length; i++) { + expect(got[i].metric, expected[i]['metric'], reason: '$key[$i] metric'); + expect(got[i].ms, expected[i]['ms'], reason: '$key[$i] ms'); + expect(got[i].value, expected[i]['value'], reason: '$key[$i] value'); + } + } + + group('0x01 activity (hr + steps)', () { + test('8-byte records', () { + final got = parseHuami2021Activity(unhex(activity['0x01']['raw']), roundStartMs); + expectSamples(got, '0x01'); + }); + test('4-byte packed records', () { + final got = parseHuami2021Activity(unhex(activity['0x01_4byte']['raw']), roundStartMs); + expectSamples(got, '0x01_4byte'); + }); + + test('an EVEN count of 4-byte records is ambiguous with 8-byte records ' + 'by length alone, and the heuristic gets it wrong without a count', + () { + // 6 real 4-byte records: steps=10+m, hr=60+m per minute m. 6*4 = 24 + // bytes, which is ALSO a multiple of 8 — exactly the case the old + // length-only heuristic could not distinguish. + final bytes = []; + for (var m = 0; m < 6; m++) { + bytes.addAll([0, 0, 10 + m, 60 + m]); + } + final data = Uint8List.fromList(bytes); + expect(data.length % 8, 0, reason: 'the ambiguous case this test exists for'); + + // With the real count supplied (as a live fetch always has it), + // every minute decodes correctly. + final withCount = + parseHuami2021Activity(data, roundStartMs, expectedRecordCount: 6); + expect(withCount, hasLength(12)); // hr + steps, 6 minutes each + for (var m = 0; m < 6; m++) { + final hr = withCount.firstWhere( + (s) => s.metric == 'hr' && s.ms == roundStartMs + m * 60000); + final steps = withCount.firstWhere( + (s) => s.metric == 'steps' && s.ms == roundStartMs + m * 60000); + expect(hr.value, 60.0 + m); + expect(steps.value, 10.0 + m); + } + }); + }); + + test('0x02 manual_hr', () { + expectSamples(parseHuami2021ManualHr(unhex(activity['0x02']['raw'])), '0x02'); + }); + + test('0x12 stress_manual', () { + expectSamples(parseHuami2021StressManual(unhex(activity['0x12']['raw'])), '0x12'); + }); + + test('0x13 stress, round-relative, keeps 0 but not 0xFF', () { + final got = parseHuami2021Stress(unhex(activity['0x13']['raw']), roundStartMs); + expectSamples(got, '0x13'); + }); + + test('0x2E temperature_c, signed, divided by 100, implausible values dropped', + () { + final got = parseHuami2021Temperature(unhex(activity['0x2E']['raw']), roundStartMs); + // The fixture's second record (-1.2 C) is outside the 20-45 plausible + // range and correctly dropped, not kept as a measured reading. + final expected = (activity['0x2E']['samples'] as List) + .cast>() + .where((s) => (s['value'] as num) >= 20 && (s['value'] as num) <= 45) + .toList(); + expect(got.length, expected.length); + for (var i = 0; i < expected.length; i++) { + expect(got[i].ms, expected[i]['ms']); + expect(got[i].value, expected[i]['value']); + } + }); + + test('temperature outside the 20-45 C plausible range is never kept', () { + final b = Uint8List(24); // three 8-byte round-relative records + ByteData.sublistView(b).setInt16(2, (5.0 * 100).round(), Endian.little); // 5 C: too cold + ByteData.sublistView(b).setInt16(10, (30.0 * 100).round(), Endian.little); // 30 C: kept + ByteData.sublistView(b).setInt16(18, (60.0 * 100).round(), Endian.little); // 60 C: too hot + final got = parseHuami2021Temperature(b, roundStartMs); + expect(got, hasLength(1)); + expect(got.single.value, 30.0); + }); + + test('0x38 respiratory_rate', () { + expectSamples(parseHuami2021RespiratoryRate(unhex(activity['0x38']['raw'])), '0x38'); + }); + + test('0x3A resting_hr', () { + expectSamples(parseHuami2021RestingHr(unhex(activity['0x3A']['raw'])), '0x3A'); + }); + + test('0x3D max_hr', () { + expectSamples(parseHuami2021MaxHr(unhex(activity['0x3D']['raw'])), '0x3D'); + }); + + test('0x49 hrv', () { + expectSamples(parseHuami2021Hrv(unhex(activity['0x49']['raw'])), '0x49'); + }); + + group('0x25 spo2 spot', () { + test('version 2, subtracts 128 when the high bit is set, drops 0% as ' + 'implausible', () { + final got = parseHuami2021Spo2Spot(unhex(activity['0x25']['raw'])); + // The fixture's third record decodes to 0% before the plausibility + // bound — biologically impossible, and this protocol's own 0xFF + // sentinel convention folds to the same excluded range after the + // >=128 subtraction, so it is dropped rather than kept verbatim. + final expected = (activity['0x25']['samples'] as List) + .cast>() + .where((s) => (s['value'] as num) > 0) + .toList(); + expect(got.length, expected.length); + for (var i = 0; i < expected.length; i++) { + expect(got[i].ms, expected[i]['ms']); + expect(got[i].value, expected[i]['value']); + } + }); + test('an unknown version yields no samples, not a guess', () { + final got = parseHuami2021Spo2Spot(unhex(activity['0x25_bad_version']['raw'])); + expect(got, isEmpty); + }); + test('the folded sentinel (raw 0xFF -> 127) is dropped, not kept', () { + // version byte 2, one 65-byte record: sec=0, value=0xFF at +4. + final b = Uint8List(66); + b[0] = 2; + b[1 + 4] = 0xFF; + expect(parseHuami2021Spo2Spot(b), isEmpty); + }); + }); + + test('0x26 spo2_sleep', () { + expectSamples(parseHuami2021Spo2Sleep(unhex(activity['0x26']['raw'])), '0x26'); + }); + + group('0x48 sleep sessions', () { + final sleep = parsers['sleep'] as Map; + final expectedSessions = (sleep['sessions'] as List).cast>(); + late List got; + + setUpAll(() { + got = parseHuami2021Sleep(unhex(sleep['raw'] as String)); + }); + + test('yields exactly the expected sessions, in order', () { + expect(got.length, expectedSessions.length); + }); + + for (var i = 0; i < 3; i++) { + test('session $i matches field-for-field', () { + final e = expectedSessions[i]; + final g = got[i]; + expect(g.sessionStartMs, e['sessionStartMs'], reason: 'sessionStartMs'); + expect(g.isNap, e['isNap'], reason: 'isNap'); + expect(g.avgHr, e['avgHr'], reason: 'avgHr'); + expect(g.score, e['score'], reason: 'score'); + expect(g.sleepStartMin, e['sleepStartMin'], reason: 'sleepStartMin'); + expect(g.sleepEndMin, e['sleepEndMin'], reason: 'sleepEndMin'); + expect(g.remMin, e['remMin'], reason: 'remMin'); + expect(g.lightMin, e['lightMin'], reason: 'lightMin'); + expect(g.deepMin, e['deepMin'], reason: 'deepMin'); + expect(g.wakeMin, e['wakeMin'], reason: 'wakeMin'); + final eStages = (e['stages'] as List).cast(); + expect(g.stages.length, eStages.length, reason: 'stage count'); + for (var s = 0; s < eStages.length; s++) { + expect(g.stages[s].startMs, eStages[s][0], reason: 'stage $s start'); + expect(g.stages[s].endMs, eStages[s][1], reason: 'stage $s end'); + expect(g.stages[s].type, eStages[s][2], reason: 'stage $s type'); + } + }); + } + + test('a slot with a bad marker byte is skipped, not fatal', () { + // slot1 in the fixture has markers (1,0) and is correctly absent from + // the output above; re-assert it directly against a synthetic buffer + // with only an invalid slot, to isolate the skip behaviour. + final bad = Uint8List(594); // all zero: sec 0 is outside [1.6e9,2.0e9] + expect(parseHuami2021Sleep(bad), isEmpty); + }); + }); + + group('0x0D pai (no known-value fixture; shape/guard checks only)', () { + test('a plausible version-0 record with finite values in range is kept', () { + final b = Uint8List(70); // 1 version byte + one 69-byte record + b[0] = 0; // version + ByteData.sublistView(b).setUint32(1, 1780000000, Endian.little); + ByteData.sublistView(b).setFloat32(55, 120.5, Endian.little); + ByteData.sublistView(b).setFloat32(59, 700.0, Endian.little); + final got = parseHuami2021Pai(b); + expect(got, hasLength(1)); + expect(got.single.ms, 1780000000000); + expect(got.single.daily, closeTo(120.5, 0.001)); + expect(got.single.total, closeTo(700.0, 0.001)); + }); + + test('a value outside 0-1000 is dropped', () { + final b = Uint8List(70); + ByteData.sublistView(b).setUint32(1, 1780000000, Endian.little); + ByteData.sublistView(b).setFloat32(55, 5000.0, Endian.little); + ByteData.sublistView(b).setFloat32(59, 1.0, Endian.little); + expect(parseHuami2021Pai(b), isEmpty); + }); + }); + + group('0x4A odi summary (no known-value fixture; shape/guard checks only)', () { + test('a plausible belongTime with a measured night is kept', () { + final b = Uint8List(2896); + final bd = ByteData.sublistView(b); + bd.setUint32(0, 1780000000, Endian.little); + bd.setUint32(4, 25000, Endian.little); + bd.setUint32(8, 12, Endian.little); + b[12] = 42; + final got = parseHuami2021OdiSummary(b); + expect(got, hasLength(1)); + expect(got.single.belongTimeMs, 1780000000000); + expect(got.single.validTimeSec, 25000); + expect(got.single.odiRefined, 12); + expect(got.single.score, 42); + }); + + test('an unmeasured night (zero odi, 0xff score) withholds those fields', () { + final b = Uint8List(2896); + final bd = ByteData.sublistView(b); + bd.setUint32(0, 1780000000, Endian.little); + bd.setUint32(4, 100, Endian.little); + b[12] = 0xff; + final got = parseHuami2021OdiSummary(b).single; + expect(got.odiRefined, isNull); + expect(got.score, isNull); + expect(got.validTimeSec, 100); // valid time is always kept + }); + + test('an implausible belongTime is skipped', () { + expect(parseHuami2021OdiSummary(Uint8List(2896)), isEmpty); + }); + }); + + group('0x05 workout summaries', () { + final workout = parsers['workout'] as Map; + final expected = (workout['workouts'] as List).cast>(); + late List got; + + setUpAll(() { + got = parseHuami2021Workouts(unhex(workout['raw'] as String)); + }); + + test('decodes every summary in the buffer', () { + expect(got.length, expected.length); + }); + + for (var i = 0; i < 2; i++) { + test('workout $i matches field-for-field', () { + final e = expected[i]; + final g = got[i]; + expect(g.startMs, e['startMs'], reason: 'startMs'); + expect(g.durationSec, e['durationSec'], reason: 'durationSec'); + expect(g.sportType, e['sportType'], reason: 'sportType'); + expect(g.calories, e['calories'], reason: 'calories'); + expect(g.avgHr, e['avgHr'], reason: 'avgHr'); + expect(g.maxHr, e['maxHr'], reason: 'maxHr'); + expect(g.minHr, e['minHr'], reason: 'minHr'); + }); + } + + test('a truncated/malformed trailing record is dropped, not a crash, ' + 'and every record decoded before it is still returned', () { + final truncated = Uint8List.fromList([ + ...unhex(workout['raw'] as String), + // A 2-byte record prefix, then a tag byte whose continuation bit + // is set with nothing after it — a varint that never terminates + // within the buffer. Used to crash the whole function with a raw + // RangeError; now caught and treated as "nothing more to decode". + 0x00, 0x80, 0x80, + ]); + expect(() => parseHuami2021Workouts(truncated), returnsNormally); + final got = parseHuami2021Workouts(truncated); + expect(got.length, expected.length, + reason: 'every record before the truncation still decodes'); + }); + }); +} From e1410c7f344ce8ec57e28e3497e8b46ca9564a4b Mon Sep 17 00:00:00 2001 From: Mohammad Abdul Sahil <127765312+abdulsaheel@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:00:41 +0530 Subject: [PATCH 2/5] huami legacy: read 8-byte minute records too mi band 5 and 6 send 8 bytes a minute. the first four are the same kind, intensity, steps and hr; the other four aren't decoded. minutes() takes the record size, 4 by default, anything but 4 or 8 is an error. --- lib/src/huami_legacy.dart | 21 +++++++++++++++------ test/huami_legacy_test.dart | 12 ++++++++++++ 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/lib/src/huami_legacy.dart b/lib/src/huami_legacy.dart index 925ca0c..72b200a 100644 --- a/lib/src/huami_legacy.dart +++ b/lib/src/huami_legacy.dart @@ -21,8 +21,9 @@ // builds it. Without it the band keeps its history and the host tracks its // own resume point. // -// SAMPLE — 4 bytes per minute: kind, intensity, steps, heart rate (0 and 0xFF -// mean no reading). Kind is the low nibble; 0 (no change) and 10 (ignore) +// SAMPLE — 4 bytes per minute (8 on Mi Band 5/6, the same four first, the +// rest not decoded): kind, intensity, steps, heart rate (0 and 0xFF mean no +// reading). Kind is the low nibble; 0 (no change) and 10 (ignore) // inherit the previous minute's kind. Kinds: 1 activity, 2 running, // 3 not worn, 4 cycling, 6 charging, 9 light sleep, 11 deep sleep, 12 woke up. @@ -150,16 +151,24 @@ class HuamiActivityBuffer { /// bytes past it would land on the wrong minutes. A transfer cut short is /// still its contiguous prefix, so a caller resumes after the last minute /// it got, not after the count the header announced. - List minutes(int startSec, {int previousKind = 1}) { + /// + /// [recordSize] is 4 (Mi Band 2/3/4) or 8 (Mi Band 5/6). An 8-byte record + /// starts with the same four bytes; bytes 4-7 are not decoded here (their + /// meaning and units are not established). + List minutes(int startSec, + {int previousKind = 1, int recordSize = 4}) { + if (recordSize != 4 && recordSize != 8) { + throw ArgumentError.value(recordSize, 'recordSize', 'must be 4 or 8'); + } if (!ok) return const []; final out = []; var kind = previousKind; - for (var i = 0; i + 4 <= bytes.length; i += 4) { + for (var i = 0; i + recordSize <= bytes.length; i += recordSize) { final k = bytes[i] & 0x0f; if (k != 0 && k != 10) kind = k; final hr = bytes[i + 3]; - out.add(HuamiMinute(startSec + (i ~/ 4) * 60, kind, bytes[i + 1], - bytes[i + 2], hr == 0 || hr == 0xff ? null : hr)); + out.add(HuamiMinute(startSec + (i ~/ recordSize) * 60, kind, + bytes[i + 1], bytes[i + 2], hr == 0 || hr == 0xff ? null : hr)); } return out; } diff --git a/test/huami_legacy_test.dart b/test/huami_legacy_test.dart index 6bb342b..199a1d7 100644 --- a/test/huami_legacy_test.dart +++ b/test/huami_legacy_test.dart @@ -45,6 +45,18 @@ void main() { expect(m.every((x) => x.asleep), isTrue); }); + test('8-byte records: same first four bytes, one minute per eight', () { + final buf = HuamiActivityBuffer() + ..add([0, 0x01, 30, 12, 70, 9, 9, 9, 9]) + ..add([1, 0x09, 5, 0, 0xff, 9, 9, 9, 9]); + final m = buf.minutes(1000, recordSize: 8); + expect(m.map((x) => (x.tsSec, x.kind, x.steps, x.hr)), + [(1000, 1, 12, 70), (1060, 9, 0, null)]); + // Read as 4-byte records the same bytes would be four minutes of noise. + expect(buf.minutes(1000), hasLength(4)); + expect(() => buf.minutes(1000, recordSize: 6), throwsArgumentError); + }); + test('a counter gap marks the transfer untrustworthy', () { final buf = HuamiActivityBuffer()..add([0, 1, 0, 0, 0])..add([2, 1, 0, 0, 0]); expect(buf.ok, isFalse); From 5c66e3778e4fc35cfd6e1031112d1fd596ef95db Mon Sep 17 00:00:00 2001 From: Mohammad Abdul Sahil <127765312+abdulsaheel@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:00:40 +0530 Subject: [PATCH 3/5] amazfit scale: live weight records 20-byte records on fee0 char 0x0021: flags, packed utc time, weight; kept only when finished. impedance, hr and pressure aren't decoded (units not established). history and its delete-ack aren't built. --- lib/openstrap_protocol.dart | 1 + lib/src/amazfit_scale.dart | 92 ++++++++++++++++++++++++++++++++++++ test/amazfit_scale_test.dart | 63 ++++++++++++++++++++++++ 3 files changed, 156 insertions(+) create mode 100644 lib/src/amazfit_scale.dart create mode 100644 test/amazfit_scale_test.dart diff --git a/lib/openstrap_protocol.dart b/lib/openstrap_protocol.dart index 825d789..80922ec 100644 --- a/lib/openstrap_protocol.dart +++ b/lib/openstrap_protocol.dart @@ -23,6 +23,7 @@ export 'src/ultrahuman.dart'; export 'src/polar_pmd.dart'; export 'src/colmi.dart'; export 'src/health_thermometer.dart'; +export 'src/amazfit_scale.dart'; export 'src/miscale.dart'; export 'src/huami_legacy.dart'; export 'src/huami2021_chunks.dart'; diff --git a/lib/src/amazfit_scale.dart b/lib/src/amazfit_scale.dart new file mode 100644 index 0000000..58c5052 --- /dev/null +++ b/lib/src/amazfit_scale.dart @@ -0,0 +1,92 @@ +// Amazfit Scale ("Amazfit Scale"). Plain GATT on service FEE0, no auth. +// +// CLOCK — char 0x0019, write: the same 10 bytes as the Mi scales' Current +// Time ([miScaleClockValue]): year u16 LE, month, day, hour, minute, second, +// day of week (1 = Sunday), 0, 0. +// +// MEASUREMENT — char 0x0021, notify. 20-byte records, little-endian, several +// may share one notification; every field is always present (a flag only +// says whether it holds a value): +// 0-1 flags +// 2-6 time, packed (UTC): year bits 0-12, month 13-16, day 17-21, +// hour 22-27, minute 28-33, second 34-39 +// 7-8 weight raw (flag 0x0008); 0xFFFF = overload +// 9-11 impedance (flag 0x0010; unit not established, not decoded) +// 12 heart rate (flag 0x0020; not decoded) +// 13 pressure (flag 0x0040; not decoded) +// 14-19 family id (flag 0x0080) +// Flags: unit = bit 0 | bit 14 (0 kg, raw/200; otherwise raw/100: bit 0 lb, +// bit 14 jin, both = a stone display whose raw value is still pounds); +// bits 9-10 measurement state (0 measuring, 1 done, 2 failed). +// +// HISTORY lives on char 00000018-...-0009af100700 and is acknowledged with a +// `04` command that is presumed to delete it on the scale. Nothing here +// builds any of it. + +import 'health_thermometer.dart' show WallClock; + +/// The scale's service. +const String kAmazfitScaleService = '0000fee0-0000-1000-8000-00805f9b34fb'; + +/// Clock (write), see the header. +const String kAmazfitScaleClockChar = '00000019-0000-1000-8000-00805f9b34fb'; + +/// Live measurement records (notify), see the header. +const String kAmazfitScaleMeasureChar = '00000021-0000-1000-8000-00805f9b34fb'; + +/// One finished weighing. +class AmazfitScaleReading { + final double kg; + + /// UTC wall-clock components as the scale stamped them; null when they + /// are not a real date. + final WallClock? at; + const AmazfitScaleReading(this.kg, this.at); +} + +/// Every finished weighing in one measurement notification. A record that +/// is still measuring, failed, has no weight, or is overloaded is skipped, +/// not the ones after it. +List parseAmazfitScaleRecords(List b) { + final out = []; + for (var i = 0; i + 20 <= b.length; i += 20) { + final flags = b[i] | (b[i + 1] << 8); + final raw = b[i + 7] | (b[i + 8] << 8); + if (flags & 0x0008 == 0 || (flags >> 9) & 0x3 != 1 || raw == 0xFFFF) { + continue; + } + final unit = (flags & 0x0001) | ((flags & 0x4000) >> 10); + final kg = switch (unit) { + 0 => raw / 200, + 16 => raw / 100 * 0.5, + _ => raw / 100 * 0.45359237, + }; + final lo = b[i + 2] | (b[i + 3] << 8) | (b[i + 4] << 16) | (b[i + 5] << 24); + final hi = b[i + 6]; + final year = lo & 0x1FFF, month = (lo >> 13) & 0xF, day = (lo >> 17) & 0x1F; + final hour = (lo >> 22) & 0x3F; + final minute = ((lo >> 28) & 0xF) | ((hi & 0x3) << 4); + final second = hi >> 2; + final valid = year >= 2000 && + month >= 1 && + month <= 12 && + day >= 1 && + day <= DateTime.utc(year, month + 1, 0).day && + hour < 24 && + minute < 60 && + second < 60; + out.add(AmazfitScaleReading( + kg, + valid + ? ( + year: year, + month: month, + day: day, + hour: hour, + minute: minute, + second: second, + ) + : null)); + } + return out; +} diff --git a/test/amazfit_scale_test.dart b/test/amazfit_scale_test.dart new file mode 100644 index 0000000..c7a9316 --- /dev/null +++ b/test/amazfit_scale_test.dart @@ -0,0 +1,63 @@ +import 'package:openstrap_protocol/openstrap_protocol.dart'; +import 'package:test/test.dart'; + +/// One 20-byte record: flags, packed UTC time, weight raw, then zeros. +List _rec(int flags, int raw, DateTime t) { + final packed = t.year | + (t.month << 13) | + (t.day << 17) | + (t.hour << 22) | + (t.minute << 28) | + (t.second << 34); + return [ + flags & 0xff, flags >> 8, + for (var k = 0; k < 5; k++) (packed >> (8 * k)) & 0xff, + raw & 0xff, raw >> 8, + ...List.filled(11, 0), + ]; +} + +const _done = 0x0008 | (1 << 9); // weight present, state 1 + +void main() { + final t = DateTime.utc(2026, 11, 23, 21, 47, 59); + + test('a finished kg weighing, with its packed UTC stamp', () { + final r = parseAmazfitScaleRecords(_rec(_done, 14400, t)); + expect(r, hasLength(1)); + expect(r.single.kg, 72.0); + expect(r.single.at, + (year: 2026, month: 11, day: 23, hour: 21, minute: 47, second: 59)); + }); + + test('units: lb, jin, and stone (raw still pounds)', () { + double kg(int unitFlags) => + parseAmazfitScaleRecords(_rec(_done | unitFlags, 15873, t)).single.kg; + expect(kg(0x0001), closeTo(158.73 * 0.45359237, 1e-9)); + expect(kg(0x4000), closeTo(79.365, 1e-9)); + expect(kg(0x4001), closeTo(158.73 * 0.45359237, 1e-9)); + }); + + test('measuring, failed, no weight, overload: skipped, the rest kept', () { + final b = [ + ..._rec(0x0008, 14400, t), // still measuring + ..._rec(0x0008 | (2 << 9), 14400, t), // failed + ..._rec(1 << 9, 14400, t), // no weight flag + ..._rec(_done, 0xFFFF, t), // overload + ..._rec(_done, 16000, t), + 1, 2, 3, // a partial tail + ]; + expect([for (final r in parseAmazfitScaleRecords(b)) r.kg], [80.0]); + }); + + test('an impossible stamp reads as no stamp, the weight still counts', () { + final b = _rec(_done, 14400, t)..[2] = 0..[3] = 0; + final r = parseAmazfitScaleRecords(b).single; + expect(r.kg, 72.0); + expect(r.at, isNull); + }); + + test('the clock write is the Mi scales\' Current Time layout', () { + expect(miScaleClockValue(t), [0xEA, 0x07, 11, 23, 21, 47, 59, 2, 0, 0]); + }); +} From f2398ab77c2a4b5cf2f92b8ec6e111d40dd599ba Mon Sep 17 00:00:00 2001 From: Mohammad Abdul Sahil <127765312+abdulsaheel@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:13:04 +0530 Subject: [PATCH 4/5] huami2021: review fixes in chunking, fetch counts and record decoders - chunk counter wraps past 255 the same way on both ends - a new first chunk replaces a message whose last chunk never came - a body shorter than its declared length is no frame - activity rounds match their count in 4- or 8-byte records, filler skip can take the announced count - activity stride is 4 or 8 or it falls back - protobuf reads stay inside their submessage, fixed64 checks its bytes - a nap stage starting at the nap's end goes to the next nap --- lib/src/huami2021_chunks.dart | 12 ++-- lib/src/huami2021_fetch.dart | 17 +++-- lib/src/huami2021_records.dart | 28 +++++--- test/huami2021_edges_test.dart | 114 +++++++++++++++++++++++++++++++++ 4 files changed, 151 insertions(+), 20 deletions(-) create mode 100644 test/huami2021_edges_test.dart diff --git a/lib/src/huami2021_chunks.dart b/lib/src/huami2021_chunks.dart index 094ebcd..4f53c84 100644 --- a/lib/src/huami2021_chunks.dart +++ b/lib/src/huami2021_chunks.dart @@ -91,7 +91,7 @@ class Huami2021Encoder { chunk[0] = _marker; chunk[1] = flags; chunk[3] = _handle; - chunk[4] = count; + chunk[4] = count & 0xFF; // the counter wraps; the decoder wraps it too if (first) { bd.setUint32(5, data.length, Endian.little); // ORIGINAL length bd.setUint16(9, endpoint, Endian.little); @@ -164,7 +164,9 @@ class Huami2021Decoder { final count = data[4]; final isFirst = flags & _flagFirst != 0; if (_handle == null && !isFirst) return null; // orphan: no first chunk seen - if (_handle != null && _handle != chunkHandle) return null; + // A first chunk always starts over, even with a message still half + // assembled (its last chunk lost); only continuations must match. + if (!isFirst && _handle != chunkHandle) return null; var offset = 5; if (isFirst) { if (data.length < offset + 6) return null; @@ -177,7 +179,7 @@ class Huami2021Decoder { _nextCount = 0; offset += 6; } - if (count != _nextCount) { + if (count != (_nextCount & 0xFF)) { _reset(); return null; } @@ -210,8 +212,8 @@ class Huami2021Decoder { final want = crc32(all.sublist(0, _length + 4)); if (crc != want) return null; } - final n = _length < all.length ? _length : all.length; - return Uint8List.sublistView(all, 0, n); + if (all.length < _length) return null; // shorter than it said it was + return Uint8List.sublistView(all, 0, _length); } void _reset() { diff --git a/lib/src/huami2021_fetch.dart b/lib/src/huami2021_fetch.dart index f08b8cd..8859c08 100644 --- a/lib/src/huami2021_fetch.dart +++ b/lib/src/huami2021_fetch.dart @@ -142,13 +142,11 @@ class Huami2021FetchBuffer { } /// Whether an accumulated round's byte count matches what the start reply -/// announced. Type `0x01`'s `expected` is a RECORD count (8 bytes normally, -/// 4 when the byte length isn't a multiple of 8); every other type's -/// `expected` is a plain byte count. +/// announced. Type `0x01`'s `expected` is a RECORD count, of 8- or 4-byte +/// records; every other type's `expected` is a plain byte count. bool huami2021FetchCountMatches(int type, int expected, int actualBytes) { if (type == kHuami2021TypeActivity) { - final recordSize = actualBytes % 8 == 0 ? 8 : 4; - return expected == actualBytes ~/ recordSize && actualBytes % recordSize == 0; + return actualBytes == expected * 8 || actualBytes == expected * 4; } return expected == actualBytes; } @@ -156,8 +154,13 @@ bool huami2021FetchCountMatches(int type, int expected, int actualBytes) { /// The paging advance when a round decoded to zero samples but did carry /// raw bytes (types 0x01 and 0x13 only — a new strap answers every window /// before its first real day with filler, and without this the pager never -/// gets past it). Minutes, clamped to 1-1440. -int huami2021FetchGapSkipMinutes(int type, int rawLen) { +/// gets past it). Minutes, clamped to 1-1440. For activity, pass the +/// announced [recordCount] when there is one: the byte length alone can't +/// tell six 4-byte records from three 8-byte ones. +int huami2021FetchGapSkipMinutes(int type, int rawLen, {int? recordCount}) { + if (type == kHuami2021TypeActivity && recordCount != null && recordCount > 0) { + return recordCount.clamp(1, 1440); + } final recordSize = switch (type) { kHuami2021TypeActivity => rawLen % 8 == 0 ? 8 : 4, kHuami2021TypeStress => 1, diff --git a/lib/src/huami2021_records.dart b/lib/src/huami2021_records.dart index 291de51..b790772 100644 --- a/lib/src/huami2021_records.dart +++ b/lib/src/huami2021_records.dart @@ -52,8 +52,10 @@ List parseHuami2021Activity(Uint8List data, int roundStartMs, // to zero is not trustworthy either way — fall back to the heuristic // rather than risk a zero record size (which would never advance the // loop below). - final recordSize = - fromCount > 0 ? fromCount : (data.length % 8 == 0 ? 8 : 4); + // Only a 4- or 8-byte stride holds the fields read below. + final recordSize = fromCount == 4 || fromCount == 8 + ? fromCount + : (data.length % 8 == 0 ? 8 : 4); final out = []; for (var i = 0; i + recordSize <= data.length; i += recordSize) { final ms = roundStartMs + (i ~/ recordSize) * 60000; @@ -262,10 +264,11 @@ class _HuamiProtobufTruncated implements Exception { /// against, so a corrupted or unexpectedly-shaped workout record is a real /// possibility, not a theoretical one, and must be recoverable rather than /// a crash. -({int value, int next}) _varint(Uint8List data, int off) { +({int value, int next}) _varint(Uint8List data, int off, [int? end]) { var result = 0, shift = 0, i = off; + final limit = end ?? data.length; while (true) { - if (i >= data.length) throw const _HuamiProtobufTruncated(); + if (i >= limit) throw const _HuamiProtobufTruncated(); final b = data[i]; i++; result |= (b & 0x7f) << shift; @@ -281,27 +284,34 @@ class _HuamiProtobufTruncated implements Exception { /// guessing at its length — callers get whatever fields were read so far. void _walkProtobuf(Uint8List data, int start, int end, void Function(int fieldNo, int wireType, int off, int len) onField) { + // Every read is bounded by [end], the submessage, not the buffer: a + // field missing its value must not borrow the next outer field's bytes. var i = start; while (i < end) { - final tagRead = _varint(data, i); + final tagRead = _varint(data, i, end); final tag = tagRead.value; i = tagRead.next; final fieldNo = tag >> 3; final wireType = tag & 7; switch (wireType) { case 0: // varint - final v = _varint(data, i); + final v = _varint(data, i, end); onField(fieldNo, wireType, i, v.next - i); i = v.next; case 1: // fixed64 + if (i + 8 > end) throw const _HuamiProtobufTruncated(); onField(fieldNo, wireType, i, 8); i += 8; case 2: // length-delimited - final lenRead = _varint(data, i); + final lenRead = _varint(data, i, end); final contentStart = lenRead.next; + if (contentStart + lenRead.value > end) { + throw const _HuamiProtobufTruncated(); + } onField(fieldNo, wireType, contentStart, lenRead.value); i = contentStart + lenRead.value; case 5: // fixed32 + if (i + 4 > end) throw const _HuamiProtobufTruncated(); onField(fieldNo, wireType, i, 4); i += 4; default: @@ -339,6 +349,7 @@ List parseHuami2021Workouts(Uint8List data) { final v = _varint(data, i); i = v.next; case 1: + if (i + 8 > data.length) throw const _HuamiProtobufTruncated(); i += 8; case 2: final lenRead = _varint(data, i); @@ -630,7 +641,8 @@ List parseHuami2021Sleep(Uint8List data) { final slot = _readStageSlot(data, off); if (slot == null) continue; // a gap in the shared timeline, not this nap's end if (slot.type == _gapMarkerType) continue; - if (slot.start < napStart || slot.start > napEnd) continue; + // A stage starting at the nap's end belongs to the next nap. + if (slot.start < napStart || slot.start >= napEnd) continue; napStages.add(Huami2021Stage(msAt(slot.start), msAt(slot.end), slot.type)); final minutes = slot.end - slot.start; switch (slot.type) { diff --git a/test/huami2021_edges_test.dart b/test/huami2021_edges_test.dart new file mode 100644 index 0000000..93214a8 --- /dev/null +++ b/test/huami2021_edges_test.dart @@ -0,0 +1,114 @@ +// Edge cases in the huami2021 chunking, fetch bookkeeping and record +// decoders: counter wrap, a lost last chunk, short bodies, 4-byte activity +// rounds, short strides, protobuf bounds, adjacent naps. + +import 'dart:typed_data'; + +import 'package:openstrap_protocol/openstrap_protocol.dart'; +import 'package:test/test.dart'; + +void main() { + group('chunks', () { + test('a message past 256 chunks wraps the counter and still decodes', () { + final data = List.generate(4000, (i) => i & 0xff); + final chunks = Huami2021Encoder(mtu: 23).encode(0x0016, data); + expect(chunks.length, greaterThan(256)); + final dec = Huami2021Decoder(); + Huami2021Frame? frame; + for (final c in chunks) { + frame = dec.feed(c) ?? frame; + } + expect(frame?.payload, data); + }); + + test('a new first chunk replaces a message whose last chunk was lost', () { + final enc = Huami2021Encoder(mtu: 23); + final dec = Huami2021Decoder(); + final lost = enc.encode(0x0016, List.filled(40, 1)); + expect(lost.length, greaterThan(1)); + dec.feed(lost.first); // the rest never arrives + final next = enc.encode(0x0016, [7, 8, 9]).single; + expect(dec.feed(next)?.payload, [7, 8, 9]); + }); + + test('a body shorter than its declared length is no frame', () { + final c = Huami2021Encoder().encode(0x0016, [1, 2, 3, 4]).single; + final short = Uint8List.fromList(c.sublist(0, c.length - 3)); + expect(Huami2021Decoder().feed(short), isNull); + }); + }); + + group('fetch', () { + test('an even number of 4-byte activity records matches its count', () { + expect(huami2021FetchCountMatches(kHuami2021TypeActivity, 6, 24), isTrue); + expect(huami2021FetchCountMatches(kHuami2021TypeActivity, 3, 24), isTrue); + expect(huami2021FetchCountMatches(kHuami2021TypeActivity, 6, 20), isFalse); + }); + + test('filler skip follows the announced record count', () { + expect(huami2021FetchGapSkipMinutes(kHuami2021TypeActivity, 24, + recordCount: 6), 6); + expect(huami2021FetchGapSkipMinutes(kHuami2021TypeActivity, 24), 3); + }); + }); + + group('records', () { + test('a count that implies a stride under 4 falls back, never throws', () { + final data = Uint8List.fromList([1, 0, 5, 70, 1, 0]); + expect(() => parseHuami2021Activity(data, 0, expectedRecordCount: 2), + returnsNormally); + }); + + test('a duration field with no value does not borrow the next field', () { + // prefix, field 2 {1: start}, field 7 {1: }, then field 16. + final start = [0x80, 0xA4, 0xA7, 0xDA, 0x06]; // 1,800,000,000 + final data = Uint8List.fromList([ + 0, 0, + 0x12, start.length + 1, 0x08, ...start, + 0x3a, 0x01, 0x08, + 0x82, 0x01, 0x02, 0x08, 0x05, + ]); + final got = parseHuami2021Workouts(data); + expect(got.where((w) => w.durationSec == 130), isEmpty); + }); + + test('a trailing fixed64 with no value bytes drops that workout', () { + final start = [0x80, 0xA4, 0xA7, 0xDA, 0x06]; + final data = Uint8List.fromList([ + 0, 0, + 0x12, start.length + 1, 0x08, ...start, + 0x09, 1, 2, // fixed64 tag, 2 of its 8 bytes + ]); + expect(parseHuami2021Workouts(data), isEmpty); + }); + + test('a stage starting at one nap\'s end goes to the next nap only', () { + final b = Uint8List(594); + final bd = ByteData.sublistView(b); + bd.setUint32(0, 1800000000, Endian.little); + bd.setUint32(4, 1800000000, Endian.little); + b[8] = 1; + b[9] = 1; + void nap(int i, int s, int e) { + bd.setUint16(0x018 + i * 6, s, Endian.little); + bd.setUint16(0x018 + i * 6 + 2, e, Endian.little); + bd.setUint16(0x018 + i * 6 + 4, e - s, Endian.little); + } + + void stage(int i, int s, int e, int type) { + bd.setUint16(0x155 + i * 5, s, Endian.little); + bd.setUint16(0x155 + i * 5 + 2, e, Endian.little); + b[0x155 + i * 5 + 4] = type; + } + + nap(0, 600, 630); + nap(1, 630, 660); + stage(0, 600, 630, kHuami2021StageLight); + stage(1, 630, 660, kHuami2021StageDeep); + final naps = parseHuami2021Sleep(b).where((s) => s.isNap).toList(); + expect(naps, hasLength(2)); + expect((naps[0].lightMin, naps[0].deepMin), (30, 0)); + expect((naps[1].lightMin, naps[1].deepMin), (0, 30)); + }); + }); +} From e4ccba263dc94d772af122546fc93396243151fd Mon Sep 17 00:00:00 2001 From: Mohammad Abdul Sahil <127765312+abdulsaheel@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:18:47 +0530 Subject: [PATCH 5/5] huami2021 activity: a round whose count doesn't fit 4- or 8-byte records decodes to nothing it used to fall back to the byte-length guess, which the comment above it already says is wrong for even counts. --- lib/src/huami2021_records.dart | 25 ++++++++++++++----------- test/huami2021_edges_test.dart | 10 +++++++--- 2 files changed, 21 insertions(+), 14 deletions(-) diff --git a/lib/src/huami2021_records.dart b/lib/src/huami2021_records.dart index b790772..cad7516 100644 --- a/lib/src/huami2021_records.dart +++ b/lib/src/huami2021_records.dart @@ -45,17 +45,20 @@ class Huami2021Sample { /// ones. Never rely on it from a real fetch. List parseHuami2021Activity(Uint8List data, int roundStartMs, {int? expectedRecordCount}) { - final fromCount = (expectedRecordCount != null && expectedRecordCount > 0) - ? data.length ~/ expectedRecordCount - : 0; - // A count so large relative to the byte length that it would divide down - // to zero is not trustworthy either way — fall back to the heuristic - // rather than risk a zero record size (which would never advance the - // loop below). - // Only a 4- or 8-byte stride holds the fields read below. - final recordSize = fromCount == 4 || fromCount == 8 - ? fromCount - : (data.length % 8 == 0 ? 8 : 4); + final int recordSize; + if (expectedRecordCount != null && expectedRecordCount > 0) { + // The count settles it exactly, or the round doesn't add up: no samples + // rather than a guess the heuristic below is known to get wrong. + if (data.length == expectedRecordCount * 8) { + recordSize = 8; + } else if (data.length == expectedRecordCount * 4) { + recordSize = 4; + } else { + return const []; + } + } else { + recordSize = data.length % 8 == 0 ? 8 : 4; + } final out = []; for (var i = 0; i + recordSize <= data.length; i += recordSize) { final ms = roundStartMs + (i ~/ recordSize) * 60000; diff --git a/test/huami2021_edges_test.dart b/test/huami2021_edges_test.dart index 93214a8..c0bae01 100644 --- a/test/huami2021_edges_test.dart +++ b/test/huami2021_edges_test.dart @@ -53,10 +53,14 @@ void main() { }); group('records', () { - test('a count that implies a stride under 4 falls back, never throws', () { + test('a count that does not add up to 4- or 8-byte records gives nothing', + () { final data = Uint8List.fromList([1, 0, 5, 70, 1, 0]); - expect(() => parseHuami2021Activity(data, 0, expectedRecordCount: 2), - returnsNormally); + expect(parseHuami2021Activity(data, 0, expectedRecordCount: 2), isEmpty); + // The same bytes with a count that fits still decode. + final four = Uint8List.fromList([1, 0, 5, 70, 1, 0, 6, 71]); + expect(parseHuami2021Activity(four, 0, expectedRecordCount: 2), + isNotEmpty); }); test('a duration field with no value does not borrow the next field', () {