Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion lib/ble/adapters/whoop_gen4.dart
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ const Map<InputSignal, Duration> kWhoopGen4Signals = <InputSignal, Duration>{
InputSignal.rrIntervals: Duration(seconds: 1), // rrCount@18 + i16LE pairs@19
InputSignal.accel1Hz: Duration(seconds: 1), // f32 @36/40/44
InputSignal.ppgRedIr: Duration(seconds: 1), // u16 @64/66
InputSignal.skinTempRaw: Duration(seconds: 1), // u16 @68
// u16 @72: a temperature CANDIDATE, relative (not degrees, not a body
// temperature). @68 is not a temperature and is no longer declared as one.
InputSignal.skinTempRaw: Duration(seconds: 1),
};

class WhoopFramedAdapter extends BandAdapter {
Expand Down
3 changes: 3 additions & 0 deletions lib/ble/ble_engine.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6067,6 +6067,9 @@ class BleEngine {
// : 0` for unconfirmed versions) and is mapped to NULL at the write
// in `_queueDecodedOneHz` — do not "fix" it by zero-filling here.
ambientRaw: r.ambientRaw,
// v24 u16 @72, the temperature candidate (relative). Null for any
// record without the v24 tail; never filled from skinTempRaw.
skinTempCand: parseV24Status(decodeTarget)?.temperatureCandidateRaw,
// Same field, same offset, same omission on this side: the record's
// sub-second was decoded and thrown away here too.
tsSubsec: r.tsSubsec,
Expand Down
57 changes: 49 additions & 8 deletions lib/compute/derivation_engine.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2006,7 +2006,17 @@ import 'vendor_sleep.dart';
// shrank every minute of an ordinary day against it and strain read 0.0; the
// day after a hard session is the usual case. Strain, trimp_net, quiet_hrr and
// the strain curve move; stored history re-scores on the recompute.
const int kAlgoVersion = 142;
// 142 → 143: WHOOP 4 skin temperature comes from the record's u16@72 (a
// relative temperature candidate) instead of u16@68, which is not a
// temperature (protocol parseV24Status). `skin_temp_adc`, `skin_temp_z` and
// readiness's temperature driver move on gen4. Records that carry no @72
// degrade to no reading, never to @68. Nights stored under an older version
// hold @68 counts, so they are left out of the baseline rather than
// compared against @72. The ambient check now measures @72 against ambient.
// gen4's 40-count settle band was measured on @68, so there is no settled
// fraction or settled mean for @72 until one is measured: the nightly mean is
// the raw one and readiness's temperature driver is refused for gen4.
const int kAlgoVersion = 143;
/// The sibling SHAs this version was derived against, asserted against
/// pubspec.yaml in test/db_serve_version_and_reads_test.dart.
///
Expand Down Expand Up @@ -2264,7 +2274,9 @@ const String kAnalyticsPin = 'f29472e64719670fe74e31521f4975c34dc113cd';
// pubspec and lock moved to it in 304d306d; this constant did not.
// REPIN @ c0341bc: protocol main, #92 merge (small wire reads moved in from
// edge), no kAlgoVersion bump: WHOOP output is the same.
const String kProtocolPin = 'c0341bc3444388b3c0a489c54cc50e617ebd467c';
// REPIN @ f38adc4: protocol main, #90 merge (parseV24Status, the v24 tail).
// Gen4 skin temperature moves to its u16@72 in this bump: see kAlgoVersion 143.
const String kProtocolPin = 'f38adc456917b2feab0c6427ea4d1f4c90fdaca7';

// Fold idempotency, the minimum-nights warm-up, and legacy-payload handling
// all live in SleepProfilePolicy (pure, unit-tested) — see
Expand Down Expand Up @@ -2553,7 +2565,7 @@ List<Map<String, dynamic>> composeOneHzFrames(
const ['spo2_red_raw', 'spo2_ir_raw'],
),
skinTempSpans,
const ['skin_temp_raw', 'skin_temp_c'],
const ['skin_temp_raw', 'skin_temp_cand', 'skin_temp_c'],
),
];
}
Expand Down Expand Up @@ -2619,6 +2631,12 @@ Future<List<List<double>>> debugSweepBaselineWindows(
];
}

/// Test seam: one day_result row + payload as the cross-day record.
@visibleForTesting
Map<String, dynamic>? debugCrossDayRecord(
Map<String, dynamic> row, Map<String, dynamic> payload) =>
DerivationEngine._crossDayRecord(row, payload);

/// Test seam: the baseline signature [DerivationEngine.rescanRecent] gates on,
/// rebuilt from the current `metric_series`.
@visibleForTesting
Expand Down Expand Up @@ -2906,23 +2924,40 @@ class _BaselineHistoryCache {
final imported = await LocalDb.importedDates();
final foreignFamily =
await LocalDb.foreignFamilyDates(ignore: kWearableFamilies);
final versions = await LocalDb.metricSeriesVersions();
// Gen4 nights written before the temperature channel moved to u16@72 hold
// u16@68 counts (not a temperature), a different quantity from today's.
// They stay as stored but never enter the baseline (see kAlgoVersion 143).
final stamped = <String>{
for (final r in versions)
if (r['date'] case final String d) d,
};
final oldGen4Temp = <String>{
for (final r in versions)
if (r['date'] case final String d)
if ((r['algo_version'] as num?) case final num v when v < 143)
if (r['device_family'] == null || r['device_family'] == 'gen4') d,
Comment thread
abdulsaheel marked this conversation as resolved.
Resolved
};
Future<List<_DatedValue>> hist(String key) async {
final rows = await LocalDb.metricSeries(key);
final seam =
LocalDb.familySeamKeys.contains(key) ? foreignFamily : const <String>{};
final seam = {
if (LocalDb.familySeamKeys.contains(key)) ...foreignFamily,
if (key == 'skin_temp_adc') ...oldGen4Temp,
};
final out = <_DatedValue>[];
for (final row in rows) {
final date = row['date'];
final value = row['value'];
if (date is! String || date.isEmpty || value is! num) continue;
if (imported.contains(date) || seam.contains(date)) continue;
// No version stamp, so nothing says it is not a u16@68 night.
if (key == 'skin_temp_adc' && !stamped.contains(date)) continue;
out.add((date: date, value: value.toDouble()));
}
return out;
}

final loaded = await Future.wait([for (final k in keys) hist(k)]);
final versions = await LocalDb.metricSeriesVersions();
// Each value's method family (see [_families]).
final dayFamily = <String, String>{
for (final r in versions)
Expand Down Expand Up @@ -9304,6 +9339,9 @@ class DerivationEngine {
final acct = asMap(sleep?['accounting']);
final acctVal = asMap(acct?['value']);
final series = asMap(payload['series']);
final oldGen4Temp = (row['algo_version'] as num? ?? kAlgoVersion) < 143 &&
(payload['device_family'] == null ||
payload['device_family'] == 'gen4');

final onsetMs = (winVal?['onset_ms'] as num?)?.toDouble();
final offsetMs = (winVal?['offset_ms'] as num?)?.toDouble();
Expand All @@ -9324,13 +9362,16 @@ class DerivationEngine {
if (sc('ln_rmssd_dev') case final ln?) 'rmssd_dev': math.exp(ln),
'readiness': col('readiness') ?? sc('readiness'),
'resp_rate': sc('resp_rate'),
'skin_temp_z': sc('skin_temp_z'),
// The RAW nightly mean and the family whose unit it is in, for the
// temperature illness flag: it standardises its input itself, and a
// z-score handed to it is standardised twice against a baseline that
// already holds the earlier fever nights, so a multi-night rise fades
// below its threshold before the persistence rule can fire.
'skin_temp_adc': sc('skin_temp_adc'),
// A gen4 night stored before the channel moved to u16@72 holds u16@68
// counts (and a z against them), a different quantity, so both are left
// out of the cross-day series.
'skin_temp_z': oldGen4Temp ? null : sc('skin_temp_z'),
'skin_temp_adc': oldGen4Temp ? null : sc('skin_temp_adc'),
'skin_temp_family': payload['device_family'] as String?,
// Only the refusal is written: an eligible night reads as before.
if (!skinTempIllnessEligible(
Expand Down
9 changes: 6 additions & 3 deletions lib/compute/derive_prepare.dart
Original file line number Diff line number Diff line change
Expand Up @@ -822,7 +822,7 @@ class _PrepareAccumulator {
_buckets.putIfAbsent(recTs ~/ 900, _BucketAcc.new).note(row);
final family = row?['device_family'];
final id = row?['device_id'];
final unit = row?['skin_temp_raw'] is num ? 'raw' :
final unit = row?['skin_temp_cand'] is num ? 'raw' :
(row?['skin_temp_c'] is num ? 'c' : null);
final f = family is String && family.isNotEmpty ? family : null;
final d = id is String ? id : null;
Expand Down Expand Up @@ -860,7 +860,10 @@ class _PrepareAccumulator {
// gen4 → gen5 mid-history steps the baseline once; the z re-settles.
// See [_skinTempFor]/[_skinTempUnit] for the ONE-UNIT-PER-DAY guard
// that stops a second device's other unit from mixing into this array.
final tempRaw = _num(row?['skin_temp_raw'])?.toInt();
// gen4's channel is `skin_temp_cand` (u16@72). `skin_temp_raw` (u16@68)
// is not a temperature and is never a fallback: a row that predates the
// column reads absent.
final tempRaw = _num(row?['skin_temp_cand'])?.toInt();
final tempC = _num(row?['skin_temp_c'])?.toDouble();
skinTemp.add(_skinTempFor(tempRaw, tempC));
// NO skin contact on the decoded path, and no column to read: the byte the
Expand Down Expand Up @@ -966,7 +969,7 @@ class _BucketAcc {
if (family is String && family.isNotEmpty) families.add(family);
final id = row['device_id'];
if (id is String) deviceIds.add(id);
skinUnit ??= row['skin_temp_raw'] is num
skinUnit ??= row['skin_temp_cand'] is num
? 'raw' : (row['skin_temp_c'] is num ? 'c' : null);
}
}
9 changes: 6 additions & 3 deletions lib/compute/onehz_pipeline.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1089,9 +1089,12 @@ Map<String, dynamic> _deriveDayBundle(Map<String, dynamic> inputJson,
// Ts is not read by `nightlySkinTemp` (it is a median + a mean over the
// night's samples), and `tempValid` has no parallel timestamp series, so 0
// is passed rather than a fabricated clock.
// gen4's 40-count band was measured on u16@68, not on the u16@72 candidate
// this array holds now, so gen4 is handed over under a family with no band:
// no settled fraction or mean until one is measured on @72 nights.
final settledTemp = nightlySkinTemp(
[for (final v in tempValid) AdcSample(0, v)],
deviceFamily: d.deviceFamily,
deviceFamily: d.deviceFamily == 'gen4' ? 'gen4_u16_72' : d.deviceFamily,
minSettledFraction: 0.0,
minSamples: minTempSamples,
);
Expand Down Expand Up @@ -1726,11 +1729,11 @@ Map<String, dynamic> _deriveDayBundle(Map<String, dynamic> inputJson,
'confidence': skinTempZ == null ? 0 : (tempProvisional ? 0.25 : 0.5),
if (skinTempZ != null && tempProvisional) 'provisional': true,
'tier': Tier.relative,
// Both columns: gen4 stores a raw ADC count, gen5 centi-°C. Either way
// Both columns: gen4's u16@72 temperature candidate, gen5 centi-°C. Either way
// this is only ever a deviation from the user's OWN baseline. The two
// never mix within one day's array — see derive_prepare.dart's
// _skinTempFor / _skinTempUnit for the read-side gate.
'inputs_used': const ['skin_temp_raw', 'skin_temp_c'],
'inputs_used': const ['skin_temp_cand', 'skin_temp_c'],
'note':
'relative deviation (z) vs your baseline; raw sensor units, '
'never an absolute °C',
Expand Down
20 changes: 11 additions & 9 deletions lib/compute/substrate.dart
Original file line number Diff line number Diff line change
Expand Up @@ -717,8 +717,11 @@ Substrate decodeSubstrate(List<String> hexes) {
final decoder = proto.FirmwareAwareR24Decoder();
for (final hex in hexes) {
proto.R24? r;
int? cand;
try {
r = decoder.decode(proto.hexToBytes(hex));
final bytes = proto.hexToBytes(hex);
r = decoder.decode(bytes);
cand = proto.parseV24Status(bytes)?.temperatureCandidateRaw;
} catch (_) {
r = null;
}
Expand All @@ -733,7 +736,7 @@ Substrate decodeSubstrate(List<String> hexes) {
// nothing this path can use. Same refusal as `LocalDb._decodeOneHzSample`.
if (r != null && r.histVersion == 25) continue;
if (r != null && r.tsEpoch > 0) {
recs.add(_Rec(r));
recs.add(_Rec(r, cand));
continue;
}
final live = proto.realtimeRr(hex);
Expand Down Expand Up @@ -769,12 +772,9 @@ Substrate decodeSubstrate(List<String> hexes) {
}
spo2Red[i] = r.spo2RedRaw;
spo2Ir[i] = r.spo2IrRaw;
// both deprecated: neither field is what its name says. still filled here so
// the substrate keeps round-tripping, but _daySkinTempCurve and the
// fit_quality diagnostic both derive from them and shouldn't — separate fix,
// it moves user-facing output and needs an algo version bump.
// ignore: deprecated_member_use
skinTemp[i] = r.skinTempRaw;
// The temperature channel is the v24 u16@72 candidate (relative), 0 =
// absent. R24.skinTempRaw (u16@68) is not a temperature and is not read.
skinTemp[i] = recs[i].cand ?? 0;
Comment thread
abdulsaheel marked this conversation as resolved.
Resolved
// ignore: deprecated_member_use
skinContact[i] = r.skinContact;
// RR beats: placed at their MEASURED instant (`beatTimesMs` — the record's
Expand Down Expand Up @@ -1113,7 +1113,9 @@ int _localHourStart(int ts) {
class _Rec {
final proto.R24 r;
final int ts;
_Rec(this.r) : ts = r.tsEpoch;
// v24 u16 @72 (relative temperature candidate), null without the v24 tail.
final int? cand;
_Rec(this.r, [this.cand]) : ts = r.tsEpoch;
}

class _Beat {
Expand Down
25 changes: 19 additions & 6 deletions lib/data/db.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1958,6 +1958,11 @@ class LocalDb {
// bright, dark means nothing (a sleeve or a duvet reads dark in a lit
// room). 0 is the absent sentinel, not a reading — see _queueDecodedOneHz.
'ambient_raw': 'INTEGER',
// Gen4 v24 u16 @inner[72], a relative temperature CANDIDATE (see
// Sample.skinTempCand). The channel gen4's `skin_temp_adc` is built from;
// `skin_temp_raw` (u16 @68) stays as stored and is no longer read as one.
// Rows written before this column read NULL, which is the truth for them.
'skin_temp_cand': 'INTEGER',
// v43 (MT-12): the gen5 record's SECOND and THIRD temperature channels
// (i16 ÷10 °C), decoded by protocol and dropped by the mapper until now.
//
Expand Down Expand Up @@ -4351,7 +4356,7 @@ class LocalDb {
'hr1Hz': 'hr IS NOT NULL AND hr > 0',
'accel1Hz': 'ax IS NOT NULL AND ay IS NOT NULL AND az IS NOT NULL',
'ppgRedIr': 'spo2_red_raw IS NOT NULL OR spo2_ir_raw IS NOT NULL',
'skinTempRaw': 'skin_temp_raw IS NOT NULL',
'skinTempRaw': 'skin_temp_cand IS NOT NULL',
};

final batch = db.batch();
Expand Down Expand Up @@ -4389,6 +4394,8 @@ class LocalDb {
}

for (final e in specs.entries) {
// A pre-column table has no temperature candidate to claim.
if (e.key == 'skinTempRaw' && !cols.contains('skin_temp_cand')) continue;
// ORDER BY device THEN bucket: the coalescer is a single pass and must
// see one device's buckets contiguously.
final rows = await db.rawQuery(
Expand Down Expand Up @@ -4469,7 +4476,7 @@ class LocalDb {
if (s.spo2RedRaw != null || s.spo2IrRaw != null) {
observe('ppgRedIr', sec);
}
if (s.skinTempRaw != null) observe('skinTempRaw', sec);
if (s.skinTempCand != null) observe('skinTempRaw', sec);
if (s.rrIntervalsMs.isNotEmpty) observe('rrIntervals', sec);
}
// A wearable storing HR a minute or more apart covers `hrSparse`, never
Expand Down Expand Up @@ -6949,6 +6956,7 @@ class LocalDb {
hr_valid INTEGER,
hr_alt INTEGER,
ambient_raw INTEGER,
skin_temp_cand INTEGER,
device_family TEXT,
source TEXT,
temp_ch2_c REAL,
Expand Down Expand Up @@ -7795,6 +7803,7 @@ class LocalDb {
// gen4 ambient-light ADC. 0 (unconfirmed optical block) is turned
// into NULL at the write, not here — see _queueDecodedOneHz.
ambientRaw: r.ambientRaw,
skinTempCand: proto.parseV24Status(bytes)?.temperatureCandidateRaw,
tsSubsec: r.tsSubsec,
);
}
Expand Down Expand Up @@ -7925,6 +7934,10 @@ class LocalDb {
// as device_family) so the mid-ladder backfill can't name a column a
// pre-v42 rebuild has not handed back yet.
'ambient_raw': ?ambient,
// NULL stays absent: a record without the v24 tail writes no value. Not
// named on the mid-ladder replay: the column does not exist yet there,
// and the later rebuilds copy an explicit column list that omits it.
if (!preDeviceKey) 'skin_temp_cand': ?decoded.skinTempCand,
// Which strap measured this second. Stamped from the live link; unknown
// provenance is NULL, never a guess. See _ensureDeviceFamilyColumns.
//
Expand Down Expand Up @@ -10015,7 +10028,7 @@ class LocalDb {
}) async {
final db = await instance;
const cols = 'SELECT counter, rec_ts, hr, ax, ay, az, '
'spo2_red_raw, spo2_ir_raw, skin_temp_raw, '
'spo2_red_raw, spo2_ir_raw, skin_temp_raw, skin_temp_cand, '
'step_count, step_cadence, activity_class, skin_temp_c, '
'on_wrist, hr_valid, hr_alt, device_family, device_id, ts_ms, '
'band_sleep_state '
Expand Down Expand Up @@ -10464,7 +10477,7 @@ class LocalDb {
/// The result row for one day_id at the highest version this build serves
/// (see [_servedAlgoCeiling]), with a normalized `date` alias for callers.
/// Null if absent.
/// Minute means of `skin_temp_raw` and `ambient_raw` over the band's own
/// Minute means of `skin_temp_cand` and `ambient_raw` over the band's own
/// rows in [fromSec, toSec), oldest first, minutes holding both only. Feeds
/// the WHOOP 4 ambient check ([skinTempAmbientR]).
static Future<List<(int, double, double)>> skinTempAmbientMinutes(
Expand All @@ -10473,9 +10486,9 @@ class LocalDb {
) async {
final db = await instance;
final rows = await db.rawQuery(
'SELECT rec_ts / 60 AS m, AVG(skin_temp_raw) AS t, AVG(ambient_raw) AS a '
'SELECT rec_ts / 60 AS m, AVG(skin_temp_cand) AS t, AVG(ambient_raw) AS a '
'FROM decoded_onehz WHERE rec_ts >= ? AND rec_ts < ? '
'AND skin_temp_raw > 0 AND ambient_raw > 0 '
'AND skin_temp_cand > 0 AND ambient_raw > 0 '
// The primary band's own rows only: the same sensor the night's
// skin_temp_z comes from, never a second band or a wearable's mix.
'AND $kPrimaryBandSourceSql AND device_id = ? GROUP BY m ORDER BY m',
Expand Down
2 changes: 1 addition & 1 deletion lib/data/local_repository_impl.dart
Original file line number Diff line number Diff line change
Expand Up @@ -945,7 +945,7 @@ class LocalRepositoryImpl extends LocalRepository {
'value': z,
'confidence': (env?['confidence'] as num?) ?? 0.5,
'tier': (env?['tier'] as String?) ?? ana.Tier.relative,
'inputs_used': env?['inputs_used'] ?? const ['skin_temp_raw'],
'inputs_used': env?['inputs_used'] ?? const ['skin_temp_cand'],
'note': ?env?['note'],
// A ring's deviation rests on a settle band not yet measured on one:
// the row says so rather than read as a settled figure.
Expand Down
10 changes: 10 additions & 0 deletions lib/data/models.dart
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,13 @@ class Sample {
/// unconfirmed record never lands as a real reading of total darkness.
final int? ambientRaw;

/// Gen4 v24 u16 @inner[72], a temperature CANDIDATE, relative: probably
/// tenths of a degree C, not proven and not a body temperature. It is the
/// channel gen4's `skin_temp_adc` is built from. NULL on any row written
/// before this column existed and on any record without the v24 tail; it is
/// never filled from [skinTempRaw] (u16 @68, which is not a temperature).
final int? skinTempCand;

/// The gen5 record's SECOND and THIRD temperature channels, °C — GEN5 ONLY.
///
/// NOT NAMED AFTER A BODY PART, on purpose and permanently. protocol calls
Expand Down Expand Up @@ -182,6 +189,7 @@ class Sample {
this.hrValid,
this.hrAlt,
this.ambientRaw,
this.skinTempCand,
this.tempCh2C,
this.tempCh3C,
this.signalQualityLogVar,
Expand Down Expand Up @@ -214,6 +222,7 @@ class Sample {
hrValid: hrValid,
hrAlt: hrAlt,
ambientRaw: ambientRaw,
skinTempCand: skinTempCand,
tempCh2C: tempCh2C,
tempCh3C: tempCh3C,
signalQualityLogVar: signalQualityLogVar,
Expand Down Expand Up @@ -260,6 +269,7 @@ class Sample {
hrAlt: (m['hr_alt'] as num?)?.toInt(),
// Already 0-mapped-to-NULL on the way in, so a stored value is a reading.
ambientRaw: (m['ambient_raw'] as num?)?.toInt(),
skinTempCand: (m['skin_temp_cand'] as num?)?.toInt(),
tempCh2C: (m['temp_ch2_c'] as num?)?.toDouble(),
tempCh3C: (m['temp_ch3_c'] as num?)?.toDouble(),
signalQualityLogVar: (m['signal_quality_logvar'] as num?)?.toDouble(),
Expand Down
Loading
Loading