From 734fba1b89393c38bec7df803d12bee30e91dcd7 Mon Sep 17 00:00:00 2001 From: Mohammad Abdul Sahil <127765312+abdulsaheel@users.noreply.github.com> Date: Sat, 5 Dec 2026 18:58:08 +0530 Subject: [PATCH 1/2] polar loop: file-transfer framing, proto reader, sleep/recovery/summary/activity/24-7 hr parsers --- lib/openstrap_protocol.dart | 3 + lib/src/pb_lite.dart | 138 +++++++++++ lib/src/polar_data.dart | 448 ++++++++++++++++++++++++++++++++++ lib/src/polar_pftp.dart | 465 ++++++++++++++++++++++++++++++++++++ test/polar_data_test.dart | 213 +++++++++++++++++ test/polar_pftp_test.dart | 222 +++++++++++++++++ 6 files changed, 1489 insertions(+) create mode 100644 lib/src/pb_lite.dart create mode 100644 lib/src/polar_data.dart create mode 100644 lib/src/polar_pftp.dart create mode 100644 test/polar_data_test.dart create mode 100644 test/polar_pftp_test.dart diff --git a/lib/openstrap_protocol.dart b/lib/openstrap_protocol.dart index 0df7aa8..dd2d12d 100644 --- a/lib/openstrap_protocol.dart +++ b/lib/openstrap_protocol.dart @@ -20,6 +20,9 @@ export 'src/oura.dart'; export 'src/hrs.dart'; export 'src/garmin.dart'; export 'src/ultrahuman.dart'; +export 'src/pb_lite.dart' show PbField, pbFields; +export 'src/polar_data.dart'; +export 'src/polar_pftp.dart'; export 'src/polar_pmd.dart'; export 'src/colmi.dart'; export 'src/health_thermometer.dart'; diff --git a/lib/src/pb_lite.dart b/lib/src/pb_lite.dart new file mode 100644 index 0000000..ab9ad37 --- /dev/null +++ b/lib/src/pb_lite.dart @@ -0,0 +1,138 @@ +// A tiny protobuf reader: just enough to walk the fields of a message whose +// layout the caller already knows. No schema, no generated code, no +// dependency. Every read that runs off the end or meets a wire type it does +// not know returns null: a damaged file is refused, never half-decoded. + +import 'dart:typed_data'; + +/// One decoded field. +class PbField { + final int field; + + /// 0 varint, 1 fixed64, 2 length-delimited, 5 fixed32. + final int wire; + + /// The value of a varint (wire 0), or the raw bits of a fixed field. + final int value; + + /// The payload of a length-delimited field (wire 2), else null. + final List? bytes; + const PbField(this.field, this.wire, this.value, this.bytes); + + /// The varint read as a signed 32-bit value (protobuf `int32`, which + /// sign-extends a negative number to ten bytes). + int get int32 => value.toSigned(32); + + /// The varint read as `sint32` (zigzag). + int get sint32 => (value >>> 1) ^ -(value & 1); + + /// The varint read as a bool. + bool get boolean => value != 0; + + /// A fixed32 field read as a float. + double get float32 => + (ByteData(4)..setUint32(0, value, Endian.little)) + .getFloat32(0, Endian.little); + + /// The payload as a UTF-8 string. + String get string => String.fromCharCodes(bytes ?? const []); +} + +/// Every field of [b] in order, or null if [b] is not well-formed. +List? pbFields(List b) { + final out = []; + var i = 0; + while (i < b.length) { + final tag = _varint(b, i); + if (tag == null) return null; + i = tag.$2; + final field = tag.$1 >> 3; + final wire = tag.$1 & 7; + if (field == 0) return null; + switch (wire) { + case 0: + final v = _varint(b, i); + if (v == null) return null; + out.add(PbField(field, 0, v.$1, null)); + i = v.$2; + case 1: + if (i + 8 > b.length) return null; + var v = 0; + for (var k = 7; k >= 0; k--) { + v = (v << 8) | b[i + k]; + } + out.add(PbField(field, 1, v, null)); + i += 8; + case 2: + final len = _varint(b, i); + if (len == null || len.$1 < 0 || len.$2 + len.$1 > b.length) { + return null; + } + out.add(PbField(field, 2, 0, b.sublist(len.$2, len.$2 + len.$1))); + i = len.$2 + len.$1; + case 5: + if (i + 4 > b.length) return null; + final v = b[i] | (b[i + 1] << 8) | (b[i + 2] << 16) | (b[i + 3] << 24); + out.add(PbField(field, 5, v, null)); + i += 4; + default: + return null; + } + } + return out; +} + +/// Repeated varints, whether packed into one field or sent one per field. +/// Null if a packed run is damaged. +List? pbVarints(Iterable fields) { + final out = []; + for (final f in fields) { + if (f.wire == 0) { + out.add(f.value); + } else if (f.wire == 2) { + final b = f.bytes!; + var i = 0; + while (i < b.length) { + final v = _varint(b, i); + if (v == null) return null; + out.add(v.$1); + i = v.$2; + } + } else { + return null; + } + } + return out; +} + +/// Repeated floats, packed or one per field. +List? pbFloats(Iterable fields) { + final out = []; + for (final f in fields) { + if (f.wire == 5) { + out.add(f.float32); + } else if (f.wire == 2) { + final b = f.bytes!; + if (b.length % 4 != 0) return null; + final d = ByteData.sublistView(Uint8List.fromList(b)); + for (var i = 0; i < b.length; i += 4) { + out.add(d.getFloat32(i, Endian.little)); + } + } else { + return null; + } + } + return out; +} + +/// (value, next index). Reads up to 64 bits: a negative int32 is ten bytes. +(int, int)? _varint(List b, int i) { + var v = 0; + for (var shift = 0; shift < 64; shift += 7) { + if (i >= b.length) return null; + final byte = b[i++]; + v |= (byte & 0x7F) << shift; + if (byte & 0x80 == 0) return (v, i); + } + return null; +} diff --git a/lib/src/polar_data.dart b/lib/src/polar_data.dart new file mode 100644 index 0000000..bf2d2d4 --- /dev/null +++ b/lib/src/polar_data.dart @@ -0,0 +1,448 @@ +// Decoders for the history files a Polar wellness wearable (Loop, 360) keeps +// on its file system: sleep, nightly recovery, the daily summary, activity +// samples and the 24/7 automatic samples. Each takes a whole file's bytes and +// returns null for a file that is damaged or is not that file: nothing is +// guessed and nothing is half-filled. +// +// NOTHING HERE HAS MET HARDWARE. Fixtures are built from the field layout. +// +// WALL-CLOCK TIMES. Polar stores a time as the wearer's wall clock plus, +// usually, an offset from UTC in minutes ([PolarWall]). The epoch is only +// known when the offset is. + +import 'pb_lite.dart'; + +/// File paths. Dates are `yyyyMMdd` in the device's local day. +const String kPolarUserRoot = '/U/0/'; +String polarDayDir(String yyyymmdd) => '$kPolarUserRoot$yyyymmdd/'; +String polarSleepPath(String d) => '${polarDayDir(d)}SLEEP/SLEEPRES.BPB'; +String polarRechargePath(String d) => '${polarDayDir(d)}NR/NR.BPB'; +String polarSummaryPath(String d) => '${polarDayDir(d)}DSUM/DSUM.BPB'; +String polarActivityDir(String d) => '${polarDayDir(d)}ACT/'; + +/// The directory of 24/7 automatic-sample files; each file is +/// `AUTOS` + three digits + `.BPB`. +const String kPolarAutosDir = '/U/0/AUTOS/'; +final RegExp kPolarAutosFile = RegExp(r'^AUTOS\d{3}\.BPB$'); + +/// An activity-sample file in a day's `ACT/` directory. +bool isPolarActivityFile(String name) => name.startsWith('ASAMPL'); + +/// A wall-clock time and, when the file carries it, the offset from UTC. +class PolarWall { + final int year, month, day, hour, minute, second; + + /// Minutes east of UTC, or null when the file did not say. + final int? tzMinutes; + const PolarWall(this.year, this.month, this.day, this.hour, this.minute, + this.second, this.tzMinutes); + + /// Seconds since the Unix epoch, or null when the offset is unknown. + int? get epochSec => tzMinutes == null + ? null + : DateTime.utc(year, month, day, hour, minute, second) + .millisecondsSinceEpoch ~/ + 1000 - + tzMinutes! * 60; + + /// `yyyyMMdd` of the wall-clock date. + String get dayKey => + '${year.toString().padLeft(4, '0')}${month.toString().padLeft(2, '0')}' + '${day.toString().padLeft(2, '0')}'; + + @override + String toString() => 'PolarWall($year-$month-$day $hour:$minute:$second' + '${tzMinutes == null ? '' : ' tz$tzMinutes'})'; +} + +// ── shared sub-messages ───────────────────────────────────────────────────── + +({int y, int m, int d})? _date(List? b) { + if (b == null) return null; + final f = pbFields(b); + if (f == null) return null; + int? y, m, d; + for (final x in f) { + if (x.wire != 0) continue; + switch (x.field) { + case 1: + y = x.value; + case 2: + m = x.value; + case 3: + d = x.value; + } + } + if (y == null || m == null || d == null) return null; + if (y < 2000 || y > 2200 || m < 1 || m > 12 || d < 1 || d > 31) return null; + return (y: y, m: m, d: d); +} + +({int h, int mi, int s})? _time(List? b) { + if (b == null) return null; + final f = pbFields(b); + if (f == null) return null; + int? h, mi, s; + for (final x in f) { + if (x.wire != 0) continue; + switch (x.field) { + case 1: + h = x.value; + case 2: + mi = x.value; + case 3: + s = x.value; + } + } + if (h == null || mi == null || s == null) return null; + if (h > 23 || mi > 59 || s > 59) return null; + return (h: h, mi: mi, s: s); +} + +/// PbLocalDateTime and PbSystemDateTime share fields 1 (date), 2 (time); the +/// local one adds the offset in field 4. +PolarWall? _wall(List? b) { + if (b == null) return null; + final f = pbFields(b); + if (f == null) return null; + List? dateB, timeB; + int? tz; + for (final x in f) { + if (x.field == 1 && x.wire == 2) dateB = x.bytes; + if (x.field == 2 && x.wire == 2) timeB = x.bytes; + if (x.field == 4 && x.wire == 0) tz = x.int32; + } + final d = _date(dateB), t = _time(timeB); + if (d == null || t == null) return null; + if (tz != null && (tz < -720 || tz > 840)) tz = null; + return PolarWall(d.y, d.m, d.d, t.h, t.mi, t.s, tz); +} + +int? _durationSeconds(List? b) { + if (b == null) return null; + final f = pbFields(b); + if (f == null) return null; + var s = 0; + for (final x in f) { + if (x.wire != 0) continue; + switch (x.field) { + case 1: + s += x.value * 3600; + case 2: + s += x.value * 60; + case 3: + s += x.value; + case 4: + s += x.value ~/ 1000; + } + } + return s; +} + +List? _sub(List f, int field) { + for (final x in f) { + if (x.field == field && x.wire == 2) return x.bytes; + } + return null; +} + +int? _int(List f, int field) { + for (final x in f) { + if (x.field == field && x.wire == 0) return x.int32; + } + return null; +} + +// ── sleep ─────────────────────────────────────────────────────────────────── + +/// A sleep/wake state as the device reports it. +enum PolarSleepState { unknown, wake, rem, nonRem12, nonRem3 } + +PolarSleepState _sleepState(int v) { + switch (v) { + case -2: + return PolarSleepState.wake; + case -3: + return PolarSleepState.rem; + case -5: + return PolarSleepState.nonRem12; + case -6: + return PolarSleepState.nonRem3; + default: + return PolarSleepState.unknown; + } +} + +/// One state change: from [secondsFromStart] the wearer is in [state], until +/// the next phase (or the end of the night). +class PolarSleepPhase { + final int secondsFromStart; + final PolarSleepState state; + const PolarSleepPhase(this.secondsFromStart, this.state); +} + +/// One night, `SLEEPRES.BPB`. +class PolarSleep { + final PolarWall start; + final PolarWall end; + final int goalMinutes; + final List phases; + const PolarSleep(this.start, this.end, this.goalMinutes, this.phases); +} + +PolarSleep? parsePolarSleep(List bytes) { + final f = pbFields(bytes); + if (f == null) return null; + final start = _wall(_sub(f, 1)); + final end = _wall(_sub(f, 2)); + if (start == null || end == null) return null; + final phases = []; + for (final x in f) { + if (x.field != 5 || x.wire != 2) continue; + final pf = pbFields(x.bytes!); + if (pf == null) return null; + final secs = _int(pf, 1); + final st = _int(pf, 2); + if (secs == null || st == null || secs < 0) return null; + phases.add(PolarSleepPhase(secs, _sleepState(st))); + } + // A night whose phases run backwards is damaged, not a night. + for (var i = 1; i < phases.length; i++) { + if (phases[i].secondsFromStart < phases[i - 1].secondsFromStart) { + return null; + } + } + return PolarSleep(start, end, _int(f, 4) ?? 0, phases); +} + +// ── nightly recovery ──────────────────────────────────────────────────────── + +/// `NR.BPB`: the device's own recovery numbers. Every value is the device's, +/// never ours, and any may be absent. +class PolarNightlyRecovery { + final double? ansStatus; + final int? recoveryIndicator; + final int? ansRate; + final int? meanRri; // ms + final int? meanRmssd; // ms + final int? meanRespirationInterval; // ms + final int? baselineRri; + final int? baselineRmssd; + final String? sleepResultDate; // yyyyMMdd + const PolarNightlyRecovery({ + this.ansStatus, + this.recoveryIndicator, + this.ansRate, + this.meanRri, + this.meanRmssd, + this.meanRespirationInterval, + this.baselineRri, + this.baselineRmssd, + this.sleepResultDate, + }); +} + +PolarNightlyRecovery? parsePolarNightlyRecovery(List bytes) { + final f = pbFields(bytes); + if (f == null) return null; + double? ans; + for (final x in f) { + if (x.field == 3 && x.wire == 5) ans = x.float32; + } + final d = _date(_sub(f, 20)); + return PolarNightlyRecovery( + ansStatus: ans, + recoveryIndicator: _int(f, 4), + ansRate: _int(f, 6), + meanRri: _int(f, 8), + meanRmssd: _int(f, 9), + meanRespirationInterval: _int(f, 10), + baselineRri: _int(f, 11), + baselineRmssd: _int(f, 13), + sleepResultDate: d == null + ? null + : '${d.y}${d.m.toString().padLeft(2, '0')}' + '${d.d.toString().padLeft(2, '0')}', + ); +} + +// ── daily summary ─────────────────────────────────────────────────────────── + +/// `DSUM.BPB`. +class PolarDailySummary { + final String date; // yyyyMMdd + final int? steps; + final int? activityKcal; + final int? trainingKcal; + final int? bmrKcal; + final double? distanceM; + + /// Seconds per activity class, null if the file had none. + final int? secondsNonWear; + final int? secondsSleep; + final int? secondsSedentary; + const PolarDailySummary({ + required this.date, + this.steps, + this.activityKcal, + this.trainingKcal, + this.bmrKcal, + this.distanceM, + this.secondsNonWear, + this.secondsSleep, + this.secondsSedentary, + }); +} + +PolarDailySummary? parsePolarDailySummary(List bytes) { + final f = pbFields(bytes); + if (f == null) return null; + final d = _date(_sub(f, 1)); + if (d == null) return null; + double? dist; + for (final x in f) { + if (x.field == 8 && x.wire == 5) dist = x.float32; + } + int? nonWear, sleep, sedentary; + final times = _sub(f, 7); + if (times != null) { + final tf = pbFields(times); + if (tf == null) return null; + nonWear = _durationSeconds(_sub(tf, 1)); + sleep = _durationSeconds(_sub(tf, 2)); + sedentary = _durationSeconds(_sub(tf, 3)); + } + return PolarDailySummary( + date: '${d.y}${d.m.toString().padLeft(2, '0')}' + '${d.d.toString().padLeft(2, '0')}', + steps: _int(f, 2), + activityKcal: _int(f, 3), + trainingKcal: _int(f, 4), + bmrKcal: _int(f, 5), + distanceM: dist, + secondsNonWear: nonWear, + secondsSleep: sleep, + secondsSedentary: sedentary, + ); +} + +// ── activity samples ──────────────────────────────────────────────────────── + +/// `ASAMPL*.BPB`: per-interval step counts and MET values from [start]. +class PolarActivitySamples { + final PolarWall start; + final int stepsIntervalSec; + final int metIntervalSec; + final List steps; + final List mets; + const PolarActivitySamples( + this.start, this.stepsIntervalSec, this.metIntervalSec, this.steps, + this.mets); +} + +PolarActivitySamples? parsePolarActivitySamples(List bytes) { + final f = pbFields(bytes); + if (f == null) return null; + final start = _wall(_sub(f, 1)); + final met = _durationSeconds(_sub(f, 2)); + final stp = _durationSeconds(_sub(f, 3)); + if (start == null || met == null || stp == null || met <= 0 || stp <= 0) { + return null; + } + final steps = pbVarints(f.where((x) => x.field == 5)); + final mets = pbFloats(f.where((x) => x.field == 4)); + if (steps == null || mets == null) return null; + return PolarActivitySamples(start, stp, met, steps, mets); +} + +// ── 24/7 automatic samples ────────────────────────────────────────────────── + +/// What made the device take a run of heart-rate samples. +enum PolarHrTrigger { highActivity, lowActivity, timed, manual, unknown } + +PolarHrTrigger _trigger(int v) { + switch (v) { + case 1: + return PolarHrTrigger.highActivity; + case 2: + return PolarHrTrigger.lowActivity; + case 3: + return PolarHrTrigger.timed; + case 4: + return PolarHrTrigger.manual; + default: + return PolarHrTrigger.unknown; + } +} + +/// A run of heart-rate values that begins at [secondsOfDay] on the file's day. +class PolarHrRun { + final PolarHrTrigger trigger; + final int secondsOfDay; + final List bpm; + const PolarHrRun(this.trigger, this.secondsOfDay, this.bpm); +} + +/// A run of pulse-to-pulse intervals, already summed out of the file's delta +/// coding: [intervalsMs] are consecutive durations, not timestamps. +class PolarPpiRun { + final int secondsOfDay; + final List intervalsMs; + final List errorMs; + final List status; + const PolarPpiRun( + this.secondsOfDay, this.intervalsMs, this.errorMs, this.status); +} + +/// One `AUTOSnnn.BPB`: a day of runs. +class PolarAutoSamples { + final String day; // yyyyMMdd + final List hr; + final List ppi; + const PolarAutoSamples(this.day, this.hr, this.ppi); +} + +PolarAutoSamples? parsePolarAutoSamples(List bytes) { + final f = pbFields(bytes); + if (f == null) return null; + final d = _date(_sub(f, 1)); + if (d == null) return null; + final hr = []; + final ppi = []; + for (final x in f) { + if (x.field == 2 && x.wire == 2) { + final rf = pbFields(x.bytes!); + if (rf == null) return null; + final t = _time(_sub(rf, 2)); + final trig = _int(rf, 1); + if (t == null || trig == null) return null; + final bpm = pbVarints(rf.where((y) => y.field == 3)); + if (bpm == null) return null; + hr.add(PolarHrRun(_trigger(trig), t.h * 3600 + t.mi * 60 + t.s, bpm)); + } else if (x.field == 3 && x.wire == 2) { + final rf = pbFields(x.bytes!); + if (rf == null) return null; + final t = _time(_sub(rf, 2)); + final p = _sub(rf, 3); + if (t == null || p == null) continue; // a recording with no beats + final pf = pbFields(p); + if (pf == null) return null; + final deltas = pbVarints(pf.where((y) => y.field == 1)); + final errs = pbVarints(pf.where((y) => y.field == 2)); + final status = pbVarints(pf.where((y) => y.field == 3)); + if (deltas == null || errs == null || status == null) return null; + // Delta coded: each value is the running sum of the deltas (zigzag). + int zz(int v) => (v >>> 1) ^ -(v & 1); + var acc = 0; + final iv = [for (final v in deltas) acc += zz(v)]; + var eacc = 0; + final er = [for (final v in errs) eacc += zz(v)]; + ppi.add(PolarPpiRun(t.h * 3600 + t.mi * 60 + t.s, iv, er, status)); + } + } + return PolarAutoSamples( + '${d.y}${d.m.toString().padLeft(2, '0')}${d.d.toString().padLeft(2, '0')}', + hr, + ppi, + ); +} diff --git a/lib/src/polar_pftp.dart b/lib/src/polar_pftp.dart new file mode 100644 index 0000000..caeb369 --- /dev/null +++ b/lib/src/polar_pftp.dart @@ -0,0 +1,465 @@ +// Polar's file-transfer protocol (PFTP) over BLE, as a pure codec: the request +// framing, the response reassembler and the three protobuf shapes a sync needs. +// +// NOTHING HERE HAS MET HARDWARE. It ships EXPERIMENTAL: the layout is pinned by +// the fixtures in `test/polar_pftp_test.dart`, which are built from the wire +// layout, not captured off a device. +// +// WHAT THIS IS. A Polar device that speaks it exposes a small file system +// (`/U/0/...`). A host reads a file or lists a directory with one request +// message and gets the bytes back in a stream of packets on the same +// characteristic. No network, no server: "file transfer" is just the layout. +// +// THE LAYERS, bottom up: +// packet one GATT write or notification: a 1-byte header + up to MTU-1 bytes. +// message the reassembled bytes. A request is `[u16 LE header length] +// [protobuf operation]`; a response to GET is the file itself. +// proto PbPFtpOperation {1: command, 2: path}; directory {1: entry*}, +// entry {1: name, 2: size, 3-5: dates}. +// +// PACKET HEADER (byte 0): +// bit 0 next: 0 on the first packet of a message, 1 on every later one +// bits 1-2 status: 1 last, 3 more, 0 error-or-empty-response +// bits 4-7 sequence: a 0..15 ring, restarting at 0 for each message +// Status 0 carries a u16 LE error code in bytes 1-2; code 0 means "done, no +// payload". +// +// WHAT IS NOT HERE: connecting, the MTU, bonding, timeouts. Those are the +// host's. This file never touches a radio. + +import 'dart:convert'; +import 'dart:typed_data'; + +/// The PFTP operation commands (`PbPFtpOperation.command`). +const int kPftpCmdGet = 0; +const int kPftpCmdPut = 1; +const int kPftpCmdMerge = 2; +const int kPftpCmdRemove = 3; + +/// Packet status values (bits 1-2 of the header byte). +const int kPftpStatusError = 0; +const int kPftpStatusLast = 1; +const int kPftpStatusMore = 3; + +/// The host's "stop sending this stream" packet, written when a response goes +/// out of sequence mid-stream. +const List kPftpCancelPacket = [0x00, 0x00, 0x00]; + +/// The largest header a request message can declare (15 bits). +const int kPftpMaxHeaderLength = 0x7FFF; + +/// A PFTP message could not be built or read. +class PftpException implements Exception { + final String message; + + /// The device's own error code when it sent one, else null. + final int? code; + const PftpException(this.message, {this.code}); + + @override + String toString() => 'PftpException($message${code == null ? '' : ', $code'})'; +} + +/// `PbPFtpOperation` for [command] on [path], as protobuf bytes. +Uint8List pftpOperation(int command, String path) { + final p = utf8.encode(path); + final out = BytesBuilder() + ..addByte(0x08) // field 1, varint + ..add(_varint(command)) + ..addByte(0x12) // field 2, length-delimited + ..add(_varint(p.length)) + ..add(p); + return out.toBytes(); +} + +/// A GET request for [path], ready to frame: `[u16 LE length][operation]`. +/// Reading a directory is the same request on a path ending in `/`. +Uint8List pftpGetRequest(String path) { + final op = pftpOperation(kPftpCmdGet, path); + if (op.length > kPftpMaxHeaderLength) { + throw const PftpException('request header too long'); + } + return Uint8List.fromList([op.length & 0xFF, op.length >> 8, ...op]); +} + +/// Splits [message] into packets no longer than [packetSize] bytes, each with +/// its header byte. [packetSize] is the ATT payload the link can carry (the +/// negotiated MTU minus 3), at least 2. +List pftpFrames(Uint8List message, int packetSize) { + if (packetSize < 2) throw const PftpException('packet size too small'); + final body = packetSize - 1; + final packets = []; + var seq = 0; + var off = 0; + do { + final left = message.length - off; + final more = left > body; + final take = more ? body : left; + final next = packets.isEmpty ? 0 : 1; + final status = more ? kPftpStatusMore : kPftpStatusLast; + final p = Uint8List(1 + take); + p[0] = next | (status << 1) | (seq << 4); + p.setRange(1, 1 + take, message, off); + packets.add(p); + off += take; + seq = (seq + 1) & 0x0F; + } while (off < message.length); + return packets; +} + +/// What one packet did to a [PftpReassembler]. +enum PftpFeed { + /// The message needs more packets. + more, + + /// The message is complete: read [PftpReassembler.message]. + done, + + /// The device refused: read [PftpReassembler.errorCode]. + error, + + /// The packet was malformed or out of sequence. The host should write + /// [kPftpCancelPacket] if the stream was mid-flight, and abandon the message. + broken, +} + +/// Reassembles ONE response message from its packets. One instance per +/// request; do not reuse it. +class PftpReassembler { + final BytesBuilder _buf = BytesBuilder(copy: false); + int _expectSeq = 0; + bool _first = true; + int? _error; + Uint8List? _message; + + /// The reassembled message, set once [feed] has returned [PftpFeed.done]. + Uint8List get message => _message ?? Uint8List(0); + + /// The device's error code, set once [feed] has returned [PftpFeed.error]. + int? get errorCode => _error; + + PftpFeed feed(List packet) { + if (packet.isEmpty) return PftpFeed.broken; + final h = packet[0]; + final next = h & 1; + final status = (h >> 1) & 3; + final seq = (h >> 4) & 0x0F; + if (seq != _expectSeq) return PftpFeed.broken; + if (next != (_first ? 0 : 1)) return PftpFeed.broken; + _expectSeq = (_expectSeq + 1) & 0x0F; + _first = false; + switch (status) { + case kPftpStatusMore: + case kPftpStatusLast: + _buf.add(packet.sublist(1)); + if (status == kPftpStatusMore) return PftpFeed.more; + _message = _buf.toBytes(); + return PftpFeed.done; + case kPftpStatusError: + if (packet.length < 3) return PftpFeed.broken; + final code = packet[1] | (packet[2] << 8); + if (code == 0) { + _message = Uint8List(0); + return PftpFeed.done; + } + _error = code; + return PftpFeed.error; + default: + return PftpFeed.broken; + } + } +} + +/// Query ids (`PbPFtpQuery`) a host sends with [pftpQueryMessage]. +const int kPftpQuerySetSystemTime = 1; +const int kPftpQuerySetLocalTime = 3; + +/// Device error code for a path that does not exist. A host treats it as +/// "absent", not as a failure of the session. +const int kPftpErrNoSuchFile = 103; + +/// Host-to-device notification ids (sent on the host-to-device characteristic +/// as `[id][params]`, framed like any message). +const int kPftpNotifStartSync = 0; +const int kPftpNotifStopSync = 1; +const int kPftpNotifInitializeSession = 8; +const int kPftpNotifTerminateSession = 9; + +/// Query that tells the device a host is about to synchronise. +const int kPftpQueryRequestSynchronization = 13; + +/// A notification message: one id byte, then [params]. +Uint8List pftpNotificationMessage(int id, + [List params = const []]) => + Uint8List.fromList([id & 0xFF, ...params]); + +/// `PbPFtpStopSyncParams {1: completed}`. +Uint8List pftpStopSyncParams({required bool completed}) => + Uint8List.fromList(_intField(1, completed ? 1 : 0)); + +/// The file whose master identifier says first-time-use has happened. +const String kPftpUserIdPath = '/U/0/USERID.BPB'; + +/// `PbUserIdentifier` for [kPftpUserIdPath]: the all-ones master identifier a +/// host with no account writes, and when it was written. +Uint8List pftpUserIdentifier(DateTime now) => Uint8List.fromList([ + ..._intField(1, -1), // 2^64 - 1, ten bytes + ..._msgField(100, _pbSystemDateTime(now.toUtc())), + ]); + +/// Whether [bytes] is a `PbUserIdentifier` that carries a master identifier, +/// which is how the device says first-time-use is done. False for a file with +/// none; null when [bytes] is not a message at all. +bool? pftpUserIdHasMaster(List bytes) { + return pftpTopLevelFields(bytes)?.contains(1); +} + +/// The field numbers present at the top level of [bytes], or null if damaged. +Set? pftpTopLevelFields(List bytes) { + final out = {}; + var i = 0; + while (i < bytes.length) { + final tag = _readVarint(bytes, i); + if (tag == null) return null; + i = tag.$2; + final skipped = _skip(bytes, i, tag.$1 & 7); + if (skipped == null) return null; + out.add(tag.$1 >> 3); + i = skipped; + } + return out; +} + +/// Where the device keeps the user's physical data. Written once at first-time +/// use; the device will not compute activity or sleep until it exists. +const String kPftpPhysDataPath = '/U/0/S/PHYSDATA.BPB'; + +/// A PUT of [data] to [path], ready to frame: the request header, then the +/// file bytes. +Uint8List pftpPutRequest(String path, List data) { + final op = pftpOperation(kPftpCmdPut, path); + if (op.length > kPftpMaxHeaderLength) { + throw const PftpException('request header too long'); + } + return Uint8List.fromList( + [op.length & 0xFF, op.length >> 8, ...op, ...data]); +} + +/// A query message: a 2-byte header with the top bit set and [id] in the other +/// 15, then [params]. The reply to a query comes back as an ordinary message. +Uint8List pftpQueryMessage(int id, [List params = const []]) { + if (id < 0 || id > 0x7FFF) throw const PftpException('query id out of range'); + return Uint8List.fromList( + [id & 0xFF, ((id >> 8) & 0x7F) | 0x80, ...params]); +} + +/// `PbPFtpSetLocalTimeParams`: the wall-clock time the wearer's day is counted +/// in, plus its offset from UTC in minutes. Fields are taken as given, with no +/// time zone logic here. +Uint8List pftpSetLocalTimeParams(DateTime local, int tzOffsetMinutes) => + Uint8List.fromList([ + ..._msgField(1, _pbDate(local)), + ..._msgField(2, _pbTime(local)), + ..._intField(3, tzOffsetMinutes), + ]); + +/// `PbPFtpSetSystemTimeParams`: the UTC instant. [trusted] says the time came +/// from a clock the host believes in (a phone synced to the network is one). +Uint8List pftpSetSystemTimeParams(DateTime utc, {bool trusted = true}) => + Uint8List.fromList([ + ..._msgField(1, _pbDate(utc)), + ..._msgField(2, _pbTime(utc)), + ..._intField(3, trusted ? 1 : 0), + ]); + +/// The user's sex as the device wants it. The device's own word for it is +/// "gender"; it is meant to be biological sex. +enum PftpSex { male, female } + +/// `PbUserPhysData` for the first-time-use PUT to [kPftpPhysDataPath]. +/// +/// [now] stamps every field's `last_modified` (UTC). Heights are centimetres, +/// weights kilograms, heart rates bpm, [sleepGoalMinutes] minutes. The three +/// numbers a host rarely knows ([hrMax], [hrRest], [vo2Max]) are optional and +/// omitted when null rather than guessed; the device then uses its own +/// defaults. +Uint8List pftpUserPhysData({ + required DateTime birthDate, + required PftpSex sex, + required DateTime now, + double? weightKg, + double? heightCm, + int? hrMax, + int? hrRest, + int? vo2Max, + int? sleepGoalMinutes, +}) { + final stamp = _pbSystemDateTime(now.toUtc()); + // Every physical value is `{1: value, 2: last_modified}`; [first] is field 1 + // already encoded in whatever shape that value takes. + List valued(List first) => + [...first, ..._msgField(2, stamp)]; + return Uint8List.fromList([ + ..._msgField(1, valued(_msgField(1, _pbDate(birthDate)))), + ..._msgField(2, valued(_intField(1, sex == PftpSex.male ? 1 : 2))), + if (weightKg != null) ..._msgField(3, valued(_floatField1(weightKg))), + if (heightCm != null) ..._msgField(4, valued(_floatField1(heightCm))), + if (hrMax != null) ..._msgField(5, valued(_intField(1, hrMax))), + if (hrRest != null) ..._msgField(6, valued(_intField(1, hrRest))), + if (vo2Max != null) ..._msgField(10, valued(_intField(1, vo2Max))), + if (sleepGoalMinutes != null) + ..._msgField(17, [ + ..._intField(1, sleepGoalMinutes), + ..._msgField(2, stamp), + ]), + ..._msgField(100, stamp), + ]); +} + +List _pbDate(DateTime d) => [ + ..._intField(1, d.year), + ..._intField(2, d.month), + ..._intField(3, d.day), + ]; + +List _pbTime(DateTime d) => [ + ..._intField(1, d.hour), + ..._intField(2, d.minute), + ..._intField(3, d.second), + ]; + +List _pbSystemDateTime(DateTime utc) => [ + ..._msgField(1, _pbDate(utc)), + ..._msgField(2, _pbTime(utc)), + ..._intField(3, 1), // trusted + ]; + +List _intField(int field, int v) => + [..._varint(field << 3), ..._varint(v)]; + +List _msgField(int field, List body) => + [..._varint((field << 3) | 2), ..._varint(body.length), ...body]; + +/// Field 1, wire type 5 (32-bit), little-endian float. +List _floatField1(double v) { + final b = ByteData(4)..setFloat32(0, v, Endian.little); + return [0x0D, ...b.buffer.asUint8List()]; +} + +/// One entry of a directory listing. +class PftpEntry { + final String name; + + /// Size in bytes; 0 for a directory. + final int size; + const PftpEntry(this.name, this.size); + + bool get isDirectory => name.endsWith('/'); + + @override + String toString() => 'PftpEntry($name, $size)'; +} + +/// Decodes a directory listing (`PbPFtpDirectory`). Returns null when [bytes] +/// is not one: a truncated field, a bad tag, or an entry without a name. +List? parsePftpDirectory(List bytes) { + final entries = []; + var i = 0; + while (i < bytes.length) { + final tag = _readVarint(bytes, i); + if (tag == null) return null; + i = tag.$2; + final field = tag.$1 >> 3; + final wire = tag.$1 & 7; + if (field == 1 && wire == 2) { + final len = _readVarint(bytes, i); + if (len == null) return null; + i = len.$2; + if (i + len.$1 > bytes.length) return null; + final e = _parseEntry(bytes.sublist(i, i + len.$1)); + if (e == null) return null; + entries.add(e); + i += len.$1; + } else { + final skipped = _skip(bytes, i, wire); + if (skipped == null) return null; + i = skipped; + } + } + return entries; +} + +PftpEntry? _parseEntry(List b) { + String? name; + var size = 0; + var i = 0; + while (i < b.length) { + final tag = _readVarint(b, i); + if (tag == null) return null; + i = tag.$2; + final field = tag.$1 >> 3; + final wire = tag.$1 & 7; + if (field == 1 && wire == 2) { + final len = _readVarint(b, i); + if (len == null || len.$2 + len.$1 > b.length) return null; + name = utf8.decode(b.sublist(len.$2, len.$2 + len.$1), + allowMalformed: true); + i = len.$2 + len.$1; + } else if (field == 2 && wire == 0) { + final v = _readVarint(b, i); + if (v == null) return null; + size = v.$1; + i = v.$2; + } else { + final skipped = _skip(b, i, wire); + if (skipped == null) return null; + i = skipped; + } + } + return name == null ? null : PftpEntry(name, size); +} + +/// Index after a field of wire type [wire] starting at [i], or null if it runs +/// off the end or is a type this decoder does not read. +int? _skip(List b, int i, int wire) { + switch (wire) { + case 0: + final v = _readVarint(b, i); + return v?.$2; + case 1: + return i + 8 <= b.length ? i + 8 : null; + case 2: + final len = _readVarint(b, i); + if (len == null || len.$2 + len.$1 > b.length) return null; + return len.$2 + len.$1; + case 5: + return i + 4 <= b.length ? i + 4 : null; + default: + return null; + } +} + +/// (value, next index), or null on a truncated or over-long varint. Reads up to +/// 64 bits (a ten-byte varint is how a negative or all-ones value is sent). +(int, int)? _readVarint(List b, int i) { + var v = 0; + for (var shift = 0; shift < 64; shift += 7) { + if (i >= b.length) return null; + final byte = b[i++]; + v |= (byte & 0x7F) << shift; + if (byte & 0x80 == 0) return (v, i); + } + return null; +} + +List _varint(int v) { + final out = []; + // `>>>` so a negative value (a time zone west of UTC) runs out after 10 + // bytes, the way protobuf sign-extends an int32. + while ((v & ~0x7F) != 0) { + out.add((v & 0x7F) | 0x80); + v >>>= 7; + } + out.add(v); + return out; +} diff --git a/test/polar_data_test.dart b/test/polar_data_test.dart new file mode 100644 index 0000000..5ff1534 --- /dev/null +++ b/test/polar_data_test.dart @@ -0,0 +1,213 @@ +// The Polar wellness-file decoders. +// +// NOTHING HERE HAS MET HARDWARE. Fixtures are built from the field layout with +// a small encoder below, not captured off a device. They pin the decode; they +// do not prove a real device writes these files this way. + +import 'dart:typed_data'; + +import 'package:openstrap_protocol/openstrap_protocol.dart'; +import 'package:test/test.dart'; + +List _varint(int v) { + final out = []; + while ((v & ~0x7F) != 0) { + out.add((v & 0x7F) | 0x80); + v >>>= 7; + } + out.add(v); + return out; +} + +List _v(int f, int v) => [..._varint(f << 3), ..._varint(v)]; +List _m(int f, List b) => + [..._varint((f << 3) | 2), ..._varint(b.length), ...b]; +List _f32(int f, double v) => [ + ..._varint((f << 3) | 5), + ...(ByteData(4)..setFloat32(0, v, Endian.little)).buffer.asUint8List(), + ]; +List _packed(int f, List vs) => + _m(f, [for (final v in vs) ..._varint(v)]); + +List _date(int y, int m, int d) => [..._v(1, y), ..._v(2, m), ..._v(3, d)]; +List _time(int h, int mi, int s) => + [..._v(1, h), ..._v(2, mi), ..._v(3, s)]; +List _local(int y, int mo, int d, int h, int mi, int s, int? tz) => [ + ..._m(1, _date(y, mo, d)), + ..._m(2, _time(h, mi, s)), + ..._v(3, 0), + if (tz != null) ..._v(4, tz), + ]; +List _dur(int h, int m, int s) => [..._v(1, h), ..._v(2, m), ..._v(3, s)]; +int _zz(int n) => (n << 1) ^ (n >> 63); + +void main() { + group('sleep', () { + test('decodes start, end, goal and phases incl. negative states', () { + final b = [ + ..._m(1, _local(2026, 12, 4, 23, 10, 0, 330)), + ..._m(2, _local(2026, 12, 5, 6, 40, 0, 330)), + ..._v(4, 480), + ..._m(5, [..._v(1, 0), ..._v(2, -5)]), + ..._m(5, [..._v(1, 1800), ..._v(2, -6)]), + ..._m(5, [..._v(1, 5400), ..._v(2, -3)]), + ..._m(5, [..._v(1, 6000), ..._v(2, -2)]), + ]; + final s = parsePolarSleep(b)!; + expect(s.goalMinutes, 480); + expect(s.phases.map((p) => p.state), [ + PolarSleepState.nonRem12, + PolarSleepState.nonRem3, + PolarSleepState.rem, + PolarSleepState.wake, + ]); + expect(s.phases.map((p) => p.secondsFromStart), [0, 1800, 5400, 6000]); + // 23:10 at +05:30 is 17:40 UTC + expect(s.start.epochSec, + DateTime.utc(2026, 12, 4, 17, 40).millisecondsSinceEpoch ~/ 1000); + expect(s.end.dayKey, '20261205'); + }); + + test('phases running backwards are refused', () { + final b = [ + ..._m(1, _local(2026, 12, 4, 23, 0, 0, 0)), + ..._m(2, _local(2026, 12, 5, 6, 0, 0, 0)), + ..._m(5, [..._v(1, 900), ..._v(2, -2)]), + ..._m(5, [..._v(1, 100), ..._v(2, -3)]), + ]; + expect(parsePolarSleep(b), isNull); + }); + + test('a missing offset leaves the epoch unknown, not zero', () { + final b = [ + ..._m(1, _local(2026, 12, 4, 23, 0, 0, null)), + ..._m(2, _local(2026, 12, 5, 6, 0, 0, null)), + ]; + expect(parsePolarSleep(b)!.start.epochSec, isNull); + }); + + test('garbage and an implausible date decode to null', () { + expect(parsePolarSleep([0xFF, 0xFF]), isNull); + expect(parsePolarSleep([]), isNull); + final b = [ + ..._m(1, _local(1970, 1, 1, 0, 0, 0, 0)), + ..._m(2, _local(1970, 1, 1, 8, 0, 0, 0)), + ]; + expect(parsePolarSleep(b), isNull); + }); + }); + + test('nightly recovery keeps what is present and nothing else', () { + final b = [ + ..._f32(3, 1.5), + ..._v(4, 4), + ..._v(8, 980), + ..._v(9, 55), + ..._v(13, 48), + ..._m(20, _date(2026, 12, 5)), + ]; + final r = parsePolarNightlyRecovery(b)!; + expect(r.ansStatus, 1.5); + expect(r.recoveryIndicator, 4); + expect(r.meanRmssd, 55); + expect(r.baselineRmssd, 48); + expect(r.ansRate, isNull); // not in the file, not 0 + expect(r.sleepResultDate, '20261205'); + }); + + test('daily summary decodes counts and class times', () { + final b = [ + ..._m(1, _date(2026, 12, 5)), + ..._v(2, 8421), + ..._v(3, 310), + ..._v(5, 1650), + ..._f32(8, 6123.5), + ..._m(7, [ + ..._m(1, _dur(1, 0, 0)), + ..._m(2, _dur(7, 30, 0)), + ..._m(3, _dur(9, 0, 30)), + ]), + ]; + final d = parsePolarDailySummary(b)!; + expect(d.date, '20261205'); + expect(d.steps, 8421); + expect(d.bmrKcal, 1650); + expect(d.trainingKcal, isNull); + expect(d.distanceM, 6123.5); + expect(d.secondsNonWear, 3600); + expect(d.secondsSleep, 27000); + expect(d.secondsSedentary, 32430); + expect(parsePolarDailySummary([..._v(2, 5)]), isNull); // no date + }); + + test('activity samples: packed steps, float mets, intervals', () { + final b = [ + ..._m(1, _local(2026, 12, 5, 0, 0, 0, 330)), + ..._m(2, [..._v(3, 30)]), + ..._m(3, [..._v(2, 1)]), + ..._f32(4, 1.0), + ..._f32(4, 2.5), + ..._packed(5, [0, 12, 40]), + ]; + final a = parsePolarActivitySamples(b)!; + expect(a.metIntervalSec, 30); + expect(a.stepsIntervalSec, 60); + expect(a.steps, [0, 12, 40]); + expect(a.mets, [1.0, 2.5]); + }); + + test('activity samples with a zero interval are refused', () { + final b = [ + ..._m(1, _local(2026, 12, 5, 0, 0, 0, 0)), + ..._m(2, []), + ..._m(3, [..._v(2, 1)]), + ]; + expect(parsePolarActivitySamples(b), isNull); + }); + + test('24/7 samples: hr runs and delta-coded intervals', () { + final hr = [ + ..._v(1, 3), + ..._m(2, _time(10, 5, 0)), + ..._packed(3, [61, 62, 64]), + ]; + final ppiBody = [ + ..._packed(1, [_zz(800), _zz(10), _zz(-20)]), + ..._packed(2, [_zz(20), _zz(0), _zz(5)]), + ..._packed(3, [0, 0, 1]), + ]; + final b = [ + ..._m(1, _date(2026, 12, 5)), + ..._m(2, hr), + ..._m(3, [..._v(1, 1), ..._m(2, _time(3, 0, 0)), ..._m(3, ppiBody)]), + ]; + final s = parsePolarAutoSamples(b)!; + expect(s.day, '20261205'); + expect(s.hr.single.trigger, PolarHrTrigger.timed); + expect(s.hr.single.secondsOfDay, 10 * 3600 + 5 * 60); + expect(s.hr.single.bpm, [61, 62, 64]); + // running sums: 800, 810, 790 + expect(s.ppi.single.intervalsMs, [800, 810, 790]); + expect(s.ppi.single.errorMs, [20, 20, 25]); + expect(s.ppi.single.status, [0, 0, 1]); + expect(s.ppi.single.secondsOfDay, 3 * 3600); + }); + + test('a damaged 24/7 file is null, not a partial day', () { + final good = [ + ..._m(1, _date(2026, 12, 5)), + ..._m(2, [..._v(1, 3), ..._m(2, _time(1, 0, 0)), ..._packed(3, [60])]), + ]; + expect(parsePolarAutoSamples(good), isNotNull); + expect(parsePolarAutoSamples(good.sublist(0, good.length - 2)), isNull); + }); + + test('file names and paths', () { + expect(polarSleepPath('20261205'), '/U/0/20261205/SLEEP/SLEEPRES.BPB'); + expect(polarRechargePath('20261205'), '/U/0/20261205/NR/NR.BPB'); + expect(polarSummaryPath('20261205'), '/U/0/20261205/DSUM/DSUM.BPB'); + expect(kPolarAutosFile.hasMatch('AUTOS007.BPB'), isTrue); + expect(kPolarAutosFile.hasMatch('AUTOS7.BPB'), isFalse); + expect(isPolarActivityFile('ASAMPL0.BPB'), isTrue); + }); +} diff --git a/test/polar_pftp_test.dart b/test/polar_pftp_test.dart new file mode 100644 index 0000000..4802838 --- /dev/null +++ b/test/polar_pftp_test.dart @@ -0,0 +1,222 @@ +// The Polar PFTP framing and directory decoders. +// +// NOTHING HERE HAS MET HARDWARE. Fixtures are built from the wire layout, not +// captured off a device. They pin the decode and the framing; they do not +// prove a real device behaves this way. + +import 'dart:typed_data'; + +import 'package:openstrap_protocol/openstrap_protocol.dart'; +import 'package:test/test.dart'; + +PftpFeed _feedAll(PftpReassembler r, List packets) { + var last = PftpFeed.more; + for (final p in packets) { + last = r.feed(p); + } + return last; +} + +/// Top-level length-delimited fields of a protobuf message, by field number. +Map> _fields(List b) { + final out = >{}; + var i = 0; + int varint() { + var v = 0, shift = 0; + while (true) { + final x = b[i++]; + v |= (x & 0x7F) << shift; + if (x & 0x80 == 0) return v; + shift += 7; + } + } + + while (i < b.length) { + final tag = varint(); + final field = tag >> 3; + switch (tag & 7) { + case 0: + out[field] = [varint()]; + case 2: + final n = varint(); + out[field] = b.sublist(i, i + n); + i += n; + case 5: + out[field] = b.sublist(i, i + 4); + i += 4; + default: + throw StateError('wire type'); + } + } + return out; +} + +void main() { + test('GET request is length-prefixed protobuf', () { + final req = pftpGetRequest('/U/0/'); + // op = 08 00 12 05 "/U/0/" -> 9 bytes + expect(req.sublist(0, 2), [9, 0]); + expect(req.sublist(2, 6), [0x08, 0x00, 0x12, 0x05]); + expect(String.fromCharCodes(req.sublist(6)), '/U/0/'); + }); + + test('a short request is one LAST packet, seq 0', () { + final frames = pftpFrames(pftpGetRequest('/U/0/'), 20); + expect(frames, hasLength(1)); + expect(frames[0][0], 0x02); // next 0, status last, seq 0 + }); + + test('a long message splits with a ring sequence and next bit', () { + final msg = Uint8List.fromList(List.generate(100, (i) => i)); + final frames = pftpFrames(msg, 10); // 9 payload bytes per packet + expect(frames, hasLength(12)); + expect(frames[0][0], 0x06); // first, more, seq 0 + expect(frames[1][0], 0x17); // next, more, seq 1 + expect(frames[11][0], (11 << 4) | 1 | 2); // next, last, seq 11 + expect(frames.every((p) => p.length <= 10), isTrue); + // the sequence ring wraps at 16 + final long = pftpFrames(Uint8List(200), 6); + expect((long[16][0] >> 4) & 0x0F, 0); + }); + + test('frames reassemble to the original message', () { + final msg = Uint8List.fromList(List.generate(250, (i) => i & 0xFF)); + final r = PftpReassembler(); + expect(_feedAll(r, pftpFrames(msg, 20)), PftpFeed.done); + expect(r.message, msg); + }); + + test('an out-of-sequence packet is broken, not guessed at', () { + final frames = pftpFrames(Uint8List(60), 20); + final r = PftpReassembler(); + expect(r.feed(frames[0]), PftpFeed.more); + expect(r.feed(frames[2]), PftpFeed.broken); // skipped frames[1] + }); + + test('a first packet claiming to be a continuation is broken', () { + expect(PftpReassembler().feed([0x13, 1]), PftpFeed.broken); + }); + + test('status 0 with code 0 is an empty success', () { + final r = PftpReassembler(); + expect(r.feed([0x00, 0x00, 0x00]), PftpFeed.done); + expect(r.message, isEmpty); + }); + + test('status 0 with a code is the device refusing', () { + final r = PftpReassembler(); + expect(r.feed([0x00, 0x67, 0x00]), PftpFeed.error); + expect(r.errorCode, 0x67); + }); + + test('empty and truncated packets are broken', () { + expect(PftpReassembler().feed([]), PftpFeed.broken); + expect(PftpReassembler().feed([0x00, 0x01]), PftpFeed.broken); + }); + + test('directory listing decodes names and sizes, skips dates', () { + // entry 1: name "SLEEP/" size 0 ; entry 2: name "X.BPB" size 300 + a + // length-delimited field 3 (a date) that must be skipped. + final e1 = [0x0A, 6, ...'SLEEP/'.codeUnits, 0x10, 0]; + final e2 = [ + 0x0A, 5, ...'X.BPB'.codeUnits, + 0x10, 0xAC, 0x02, // 300 + 0x1A, 2, 0x08, 0x01, // field 3, skipped + ]; + final dir = [0x0A, e1.length, ...e1, 0x0A, e2.length, ...e2]; + final list = parsePftpDirectory(dir)!; + expect(list.map((e) => e.name), ['SLEEP/', 'X.BPB']); + expect(list.map((e) => e.size), [0, 300]); + expect(list[0].isDirectory, isTrue); + expect(list[1].isDirectory, isFalse); + }); + + test('an empty directory is an empty list, garbage is null', () { + expect(parsePftpDirectory([]), isEmpty); + expect(parsePftpDirectory([0x0A, 9, 1, 2]), isNull); // runs off the end + expect(parsePftpDirectory([0x0A, 2, 0x10, 5]), isNull); // entry, no name + expect(parsePftpDirectory([0xFF]), isNull); // truncated tag + }); + + test('PUT request carries the file after the header', () { + final req = pftpPutRequest('/A', [9, 8, 7]); + // op = 08 01 12 02 '/' 'A' -> 6 bytes + expect(req, [6, 0, 0x08, 0x01, 0x12, 0x02, 0x2F, 0x41, 9, 8, 7]); + }); + + test('query message sets the top bit and keeps the id', () { + expect(pftpQueryMessage(3), [0x03, 0x80]); + expect(pftpQueryMessage(1, [5]), [0x01, 0x80, 5]); + expect(pftpQueryMessage(0x123), [0x23, 0x81]); + expect(() => pftpQueryMessage(0x8000), throwsA(isA())); + }); + + test('set-local-time params are date, time, offset', () { + final b = pftpSetLocalTimeParams(DateTime(2026, 12, 5, 10, 30, 15), 330); + expect(b, [ + 0x0A, 7, 0x08, 0xEA, 0x0F, 0x10, 0x0C, 0x18, 0x05, // 2026-12-05 + 0x12, 6, 0x08, 0x0A, 0x10, 0x1E, 0x18, 0x0F, // 10:30:15 + 0x18, 0xCA, 0x02, // +330 + ]); + }); + + test('a negative offset terminates and sign-extends to ten bytes', () { + final b = pftpSetLocalTimeParams(DateTime(2026, 1, 2, 3, 4, 5), -300); + final tz = b.sublist(b.length - 11); + expect(tz.first, 0x18); + expect(tz.last, 0x01); + expect(tz.sublist(1, 10).every((x) => x & 0x80 != 0), isTrue); + }); + + test('set-system-time params carry the trusted flag', () { + final b = pftpSetSystemTimeParams(DateTime.utc(2026, 12, 5, 4, 0, 0)); + expect(b.sublist(b.length - 2), [0x18, 0x01]); + final u = pftpSetSystemTimeParams(DateTime.utc(2026, 12, 5), + trusted: false); + expect(u.sublist(u.length - 2), [0x18, 0x00]); + }); + + test('physical data lays out each field and omits what it was not given', () { + final now = DateTime.utc(2026, 12, 5, 4, 0, 0); + final b = pftpUserPhysData( + birthDate: DateTime(1995, 6, 15), + sex: PftpSex.female, + now: now, + weightKg: 70.5, + heightCm: 175, + sleepGoalMinutes: 480, + ); + final f = _fields(b); + // birthday: {1: date{y,m,d}, 2: stamp} + final birthday = _fields(f[1]!); + expect(_fields(birthday[1]!), {1: [1995], 2: [6], 3: [15]}); + expect(_fields(f[2]!)[1], [2]); // female + final w = _fields(f[3]!)[1]!; + expect(ByteData.sublistView(Uint8List.fromList(w)) + .getFloat32(0, Endian.little), 70.5); + expect(_fields(f[4]!)[1], isNotNull); + expect(f.containsKey(5), isFalse); // hrMax not given, not guessed + expect(f.containsKey(6), isFalse); + expect(f.containsKey(10), isFalse); + expect(_fields(f[17]!)[1], [480]); // sleep goal minutes + expect(f.containsKey(100), isTrue); // last_modified + }); + + test('notification message is the id then the params', () { + expect(pftpNotificationMessage(kPftpNotifStartSync), [0]); + expect(pftpNotificationMessage(kPftpNotifStopSync, + pftpStopSyncParams(completed: true)), [1, 0x08, 0x01]); + }); + + test('user identifier carries a ten-byte master id; first-time-use read', () { + final id = pftpUserIdentifier(DateTime.utc(2026, 12, 5, 4)); + expect(id.sublist(0, 11), [ + 0x08, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, + ]); + expect(pftpUserIdHasMaster(id), isTrue); + // a file with only the timestamp has no master id + expect(pftpUserIdHasMaster(id.sublist(11)), isFalse); + expect(pftpUserIdHasMaster([]), isFalse); + expect(pftpUserIdHasMaster([0x08]), isNull); // truncated + }); +} From d05b4dfb2c23fae2574e31f380ce1aa256efc010 Mon Sep 17 00:00:00 2001 From: Mohammad Abdul Sahil <127765312+abdulsaheel@users.noreply.github.com> Date: Sat, 5 Dec 2026 19:37:01 +0530 Subject: [PATCH 2/2] polar loop: cap reassembled size, reject damaged optional fields and impossible dates --- lib/src/polar_data.dart | 13 ++++++++++++- lib/src/polar_pftp.dart | 14 +++++++++++++- test/polar_data_test.dart | 34 ++++++++++++++++++++++++++++++++++ test/polar_pftp_test.dart | 21 +++++++++++++++++++++ 4 files changed, 80 insertions(+), 2 deletions(-) diff --git a/lib/src/polar_data.dart b/lib/src/polar_data.dart index bf2d2d4..7e587ce 100644 --- a/lib/src/polar_data.dart +++ b/lib/src/polar_data.dart @@ -75,6 +75,9 @@ class PolarWall { } if (y == null || m == null || d == null) return null; if (y < 2000 || y > 2200 || m < 1 || m > 12 || d < 1 || d > 31) return null; + // A day that is not in its month (31 February) is damage, not a date. + final real = DateTime.utc(y, m, d); + if (real.month != m || real.day != d) return null; return (y: y, m: m, d: d); } @@ -250,6 +253,8 @@ PolarNightlyRecovery? parsePolarNightlyRecovery(List bytes) { if (x.field == 3 && x.wire == 5) ans = x.float32; } final d = _date(_sub(f, 20)); + // Present but undecodable is damage; only an absent field is absent. + if (_sub(f, 20) != null && d == null) return null; return PolarNightlyRecovery( ansStatus: ans, recoveryIndicator: _int(f, 4), @@ -311,6 +316,11 @@ PolarDailySummary? parsePolarDailySummary(List bytes) { nonWear = _durationSeconds(_sub(tf, 1)); sleep = _durationSeconds(_sub(tf, 2)); sedentary = _durationSeconds(_sub(tf, 3)); + if ((_sub(tf, 1) != null && nonWear == null) || + (_sub(tf, 2) != null && sleep == null) || + (_sub(tf, 3) != null && sedentary == null)) { + return null; + } } return PolarDailySummary( date: '${d.y}${d.m.toString().padLeft(2, '0')}' @@ -424,7 +434,8 @@ PolarAutoSamples? parsePolarAutoSamples(List bytes) { if (rf == null) return null; final t = _time(_sub(rf, 2)); final p = _sub(rf, 3); - if (t == null || p == null) continue; // a recording with no beats + if (p == null) continue; // a recording with no beats + if (t == null) return null; // beats with no usable time: damaged final pf = pbFields(p); if (pf == null) return null; final deltas = pbVarints(pf.where((y) => y.field == 1)); diff --git a/lib/src/polar_pftp.dart b/lib/src/polar_pftp.dart index caeb369..cb015e5 100644 --- a/lib/src/polar_pftp.dart +++ b/lib/src/polar_pftp.dart @@ -30,6 +30,8 @@ import 'dart:convert'; import 'dart:typed_data'; +import 'pb_lite.dart' show pbFields; + /// The PFTP operation commands (`PbPFtpOperation.command`). const int kPftpCmdGet = 0; const int kPftpCmdPut = 1; @@ -125,7 +127,12 @@ enum PftpFeed { /// Reassembles ONE response message from its packets. One instance per /// request; do not reuse it. +/// The most a reassembled response may grow to. A device that keeps saying +/// "more" never fills memory; the session is broken instead. +const int kPftpMaxMessageBytes = 4 * 1024 * 1024; + class PftpReassembler { + int _size = 0; final BytesBuilder _buf = BytesBuilder(copy: false); int _expectSeq = 0; bool _first = true; @@ -151,6 +158,8 @@ class PftpReassembler { switch (status) { case kPftpStatusMore: case kPftpStatusLast: + _size += packet.length - 1; + if (_size > kPftpMaxMessageBytes) return PftpFeed.broken; _buf.add(packet.sublist(1)); if (status == kPftpStatusMore) return PftpFeed.more; _message = _buf.toBytes(); @@ -211,7 +220,10 @@ Uint8List pftpUserIdentifier(DateTime now) => Uint8List.fromList([ /// which is how the device says first-time-use is done. False for a file with /// none; null when [bytes] is not a message at all. bool? pftpUserIdHasMaster(List bytes) { - return pftpTopLevelFields(bytes)?.contains(1); + final f = pbFields(bytes); + if (f == null) return null; + // Field 1 must be a varint: a length-delimited field 1 is not an identifier. + return f.any((x) => x.field == 1 && x.wire == 0); } /// The field numbers present at the top level of [bytes], or null if damaged. diff --git a/test/polar_data_test.dart b/test/polar_data_test.dart index 5ff1534..0bc5a1b 100644 --- a/test/polar_data_test.dart +++ b/test/polar_data_test.dart @@ -210,4 +210,38 @@ void main() { expect(kPolarAutosFile.hasMatch('AUTOS7.BPB'), isFalse); expect(isPolarActivityFile('ASAMPL0.BPB'), isTrue); }); + + group('damage is damage, not absence', () { + test('a day that is not in its month is rejected', () { + expect(parsePolarDailySummary([..._m(1, _date(2026, 2, 31)), ..._v(2, 100)]), + isNull); + expect(parsePolarDailySummary([..._m(1, _date(2026, 2, 28)), ..._v(2, 100)]), + isNotNull); + }); + + test('a recovery date that is present but impossible rejects the file', () { + expect(parsePolarNightlyRecovery([..._v(4, 3), ..._m(20, _date(2026, 4, 31))]), + isNull); + expect(parsePolarNightlyRecovery([..._v(4, 3)]), isNotNull); + }); + + test('a class time that is present but damaged rejects the summary', () { + final bad = [..._m(1, _date(2026, 12, 5)), ..._m(7, [..._m(2, [0x08])])]; + expect(parsePolarDailySummary(bad), isNull); + }); + + test('a PPI run with beats but no time rejects the file', () { + final ppiBody = [..._packed(1, [2]), ..._packed(2, [0]), ..._packed(3, [0])]; + final b = [ + ..._m(1, _date(2026, 12, 5)), + ..._m(3, [..._v(1, 1), ..._m(3, ppiBody)]), + ]; + expect(parsePolarAutoSamples(b), isNull); + // no beats at all is a recording with nothing in it, which is fine + expect( + parsePolarAutoSamples( + [..._m(1, _date(2026, 12, 5)), ..._m(3, _v(1, 1))]), + isNotNull); + }); + }); } diff --git a/test/polar_pftp_test.dart b/test/polar_pftp_test.dart index 4802838..2f5e13f 100644 --- a/test/polar_pftp_test.dart +++ b/test/polar_pftp_test.dart @@ -219,4 +219,25 @@ void main() { expect(pftpUserIdHasMaster([]), isFalse); expect(pftpUserIdHasMaster([0x08]), isNull); // truncated }); + + test('a device that never says last cannot grow the buffer without end', () { + final r = PftpReassembler(); + final chunk = List.filled(19, 7); + var seq = 0; + var first = true; + var res = PftpFeed.more; + for (var i = 0; i < kPftpMaxMessageBytes ~/ 19 + 2 && res == PftpFeed.more; i++) { + final h = (first ? 0 : 1) | (3 << 1) | (seq << 4); + res = r.feed([h, ...chunk]); + seq = (seq + 1) & 0x0F; + first = false; + } + expect(res, PftpFeed.broken); + }); + + test('a user id whose field 1 is not a varint has no master id', () { + expect(pftpUserIdHasMaster([0x0A, 0x01, 0x00]), isFalse); + expect(pftpUserIdHasMaster(pftpUserIdentifier(DateTime.utc(2026, 12, 5))), + isTrue); + }); }