Skip to content

Glucose algorithm robustness - #66

Merged
dabear merged 22 commits into
next-devfrom
glucose-algorithm-robustness
Nov 27, 2026
Merged

dabear merged 22 commits into
next-devfrom
glucose-algorithm-robustness

Conversation

@dabear

@dabear dabear commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Makes the factory-calibration glucose algorithm (Libre 1 / Libre 2 EU and Libre 2 Plus over BLE and NFC) safer around bad input: wrong values are dropped or flagged instead of passed on. Readings are dated by their sensor minute. A new setting picks how much smoothing is applied. 21 commits on next-dev, no Gen2 code.

Needs review before merge. Several changes alter which glucose values reach Loop. The decisions under Needs a clinical decision below should be confirmed by someone qualified. Nothing here has been checked against reference blood glucose. Not medical advice.

What changes for the user

What reaches Loop

Situation Before After
First hour after sensor start (warmup) Readings sent No readings until 60 minutes (when the sensor start is known)
Glucose that rounds above 500 mg/dL Trend: reading dropped (a gap). History: passed on unbounded 500, marked HI
Glucose that rounds below 40 mg/dL, above 0 Passed on as calculated 40, marked LO
Values right at the edges, e.g. 39.6 or 500.3 — Shown as 40 / 500, in range, as the official reader does (it rounds first)
Falling into LO or rising into HI, with glucose smoothing on (the default) Passed on as averaged, no mark LO/HI decided on the averaged value that is sent: a fall averaging 42 is sent as 42, unmarked; a steady low stays 40 LO, a steady high 500 HI
Faulty sensor temperature (outside 10–45 °C) Used, giving a plausible but wrong glucose Reading dropped
Broken calibration (would divide by zero), NaN or infinite results Could crash or produce NaN Reading dropped
Libre 2 over BLE, sensor past its wear limit Expiry notification, readings kept going to Loop Readings stop after the limit minute, as the official reader
Libre 2 BLE reading times Some off by up to ~10 minutes Correct, so trend arrows and smoothing are too
Libre 2 over BLE, gap in delivery (out of range, app suspended) Gap stays empty: only the newest reading of a packet is sent Backfilled from the packet's history and older trend readings (up to ~45 min back, ≥ 4.5 min apart), marked as backfill, when "Backfill from history" is on

The above/below-range mark uses LoopKit's GlucoseCondition (.aboveRange / .belowRange), not isDisplayOnly. Loop still uses the value, so a real low is never ignored.

In the app

  • Smoothing setting: one picker, Off / Temperature / Glucose (previous), replaces the switch. Existing users keep their current behaviour (Glucose, or Off if it was off).

  • Settings "current glucose" projection:

    • Falls are shown as urgently as rises. Before, a fall was barely projected, so it could read up to ~14 mg/dL higher than the official reader shows; now 8 minutes ahead either way, a fall capped at 15 mg/dL.
    • Matches the official reader for established rises and never shows an established fall smaller.
    • Works from the first BLE packet, and is a little steadier than before.
    • Still Settings-only, never sent to Loop.
  • Sensor-age adjustment (optional, off by default): a new setting, "Match the official reader's sensor-age adjustment (experimental)", raises readings the way the official reader does early and late in wear. Turning it on goes through a warning. Readings that round below 22 mg/dL are never raised: they stay LO (or are dropped at or below 0), as with the setting off.

By default (setting off)

  • No sensor-age adjustment. The official reader raises readings on a new sensor (about +18 mg/dL at 5–6 h, more for lows) and slightly near end of wear, so by default LibreTransmitter can read lower than it in the first day and the last few days. Matching it raises lows on a new sensor, the risky direction for dosing, so it is opt-in; see Needs a clinical decision.

Changes

  • Algorithm hardening (GlucoseFromRaw.swift, GlucoseAlgorithm): returns nil instead of NaN, infinity or a crash outside the model's domain. Calibration isn't rounded before the user's extra slope and offset any more; syncId still rounds, so uploads aren't duplicated.

  • Temperature smoothing (optional, off by default): when chosen, sensor temperature is low-pass filtered (5-minute time constant) before temperature compensation. Each °C of thermistor jitter otherwise shows up as about 4.5 % glucose noise (the compensation is 1.045^(32.5 − T)). That the thermistor leads the sensor's chemistry is assumed, not measured; see Smoothing modes compared below.

  • Operating temperature gate: a temperature outside 10–45 °C (the sensor's rated range) drops the reading.

  • Warmup gate: readings less than 60 minutes after sensor start are dropped when the start time is known (BLE: from the packet's sensor age; NFC/transmitters: from minutesSinceStart).

  • Out-of-range handling: clamped to 40–500 mg/dL and marked with GlucoseCondition, passed through to NewGlucoseSample.condition. LO/HI is decided on the value rounded to whole mg/dL, as the official reader does (39.5 shows as 40, 500.4 as 500). Trend readings out of range are held at the official reader's own LO/HI values (39 / 501) before glucose smoothing; the mark is then decided on the smoothed value, which is clamped to 40–500, so the value sent and its mark always agree. syncId still uses 40–500, so identifiers don't change.

  • BLE gap backfill (Libre 2): when the newest reading is more than 7 minutes after the last one sent to Loop, the packet's three history readings (15-minute grid, ~2–16, 17–31 and 32–46 minutes old) and older trend readings inside the gap are sent too, at least 4.5 minutes apart and from both ends of the gap, as isBackfill samples without a trend arrow. Uses the existing "Backfill from history" setting (on by default). Nothing changes while readings arrive on time, and a reading is never backfilled twice. History readings are skipped from packets at age ≡ 2 (mod 15), where the BLE and FRAM dating rules differ by one slot.

  • Wear limit (Libre 2 BLE): readings stop once the sensor age is past the FRAM footer's maxMinutesWearTime; the reader reports at the limit minute and nothing after. The NFC/transmitter path already stopped on the sensor's state byte.

  • Reading timestamps (Libre 2 BLE): each reading is dated from its sensor minute relative to the packet's sensor age. This builds on 8282db9, now dated from when the packet arrived. Buffered readings from earlier packets fill the minutes between a packet's trend slots, matched on sensor minute so none is counted twice.

  • Blood sugar prediction fixes: fit on minutes relative to the newest reading (absolute timestamps lost precision), independent of input order, skips invalid readings, needs at least 10.

  • Display projection (Settings only): the "current glucose" shown in Settings is the newest reading projected 8 minutes along its trend, rising and falling alike, rate from the last 16 minutes, with a fall limited to 15 mg/dL below the newest reading. This matches the official reader for established trends (measured; see Testing). A single Libre 2 BLE packet (readings 0, 2, 4, 6, 7, 12, 15 minutes old) is enough; buffered readings fill the gaps. It is never sent to Loop, because Loop does its own momentum prediction.

  • Sensor age correction: the neutral placeholder was removed, and replaced by an optional offset that matches the official reader (setting off by default). Measured black-box on flat frames of three real sensors (287 scans, all reproduced within ±1 mg/dL by the fitted curve, not the reader's code); additive, the same at 100–300 mg/dL:

    • early: +7.6 at 60 minutes, peaking at +18.2 at ~5.4 h, gone by ~38 h (a difference of two exponentials from sensor start);
    • low: from 63 to 556 minutes, readings below 90 mg/dL get (0.306 − 0.0135·t)·(90 − G) more (+30 instead of +17 at 40 mg/dL and 4 h);
    • late: from day 10, +4/3 mg/dL per day;
    • none below 22 mg/dL (rounded; 21.40 gets nothing, 21.57 is raised, measured at 1.5, 4 and 8 h). The reader returns no reading for those during the first 12 hours and LO later. LibreTransmitter doesn't raise them either, so a value at or below 0 (a sensor pulled off) is still dropped rather than lifted into range, and one up to 21 is LO. In the first 12 hours that is LO where the reader has a gap, on purpose.

    Applied to trend and history readings and the Settings projection, before the 40–500 clamp (early in wear the reader turns 30 into ~60, not LO). Validated for Libre 2 EU (and Libre 1 calibrations); the reader's separate early correction referenced to the warmup readings is not included.

  • Smoothing setting: one picker under Glucose processing replaces the switch. Only one kind of smoothing applies at a time, so their lags never add up.

    • Off: nothing smoothed.
    • Temperature: temperature filtered, readings not averaged.
    • Glucose (previous): trend readings averaged over about 5 minutes, about 2 minutes of lag, as before. This is the default.
  • Test target: adds the LibreTransmitterTests unit test bundle the shared scheme already pointed to.

  • Regression vectors: synthetic frames from Libre2.Example2 with the official reader's output (LibreLink 2.3.0's library, unmodified, on an emulator) for temperature compensation, levels, the LO/HI edges, the wear limit, the warmup edge and the low edge with the sensor-age offset on.

Smoothing modes compared

The branch's own GlucoseAlgorithm, run on synthetic data: one reading per minute, the newest calibrated from the last 20 minutes as the Libre 2 BLE path does, 20 runs each. Error against the synthetic true glucose, mg/dL (rms / worst; bias where it matters):

Scenario Off Temperature Glucose (previous)
Steady, thermistor jitter 0.03 °C (as in real dumps) 0.2 / 0.8 0.1 / 0.3 0.1 / 0.4
Steady, thermistor jitter 0.3 °C (10× real) 1.8 / 6.1 0.6 / 2.1 0.8 / 3.1
Steady, sensor noise 2 % 2.4 / 11.1 2.4 / 11.1 1.1 / 4.5
Falling 2 mg/dL/min, no noise 0.1 0.1 4.0, +3.9 high (≈ 2 min lag)
Skin temperature step 34 → 30 °C, glucose steady 0.1 3.2 / 17.8 0.1
Falling 1 mg/dL/min + both noises 2.9 / 9.9 2.4 / 9.3 2.4 / 6.4, +2.0 high
  • Thermistor jitter in real data is small: 0.01–0.03 °C minute to minute in the four FRAM dumps in libre2sim's traces/. At that level the temperature filter changes readings by about 0.1 mg/dL.
  • Glucose (previous) halves sensor noise, at about 2 minutes of lag: while glucose falls, readings run a few mg/dL high.
  • Temperature helps only if the thermistor is noisy. After a sudden real temperature change it can be wrong by up to about 18 mg/dL for a few minutes, if the sensor's chemistry follows the skin temperature at once (the model used here). If the chemistry lags the thermistor, as the code comment assumes, the filter helps instead. Which is true is unknown.
  • Limits: synthetic glucose, four short 2018 dumps for the jitter, nothing checked against blood glucose.

Hence the default stays Glucose (previous), and Temperature stays an option rather than a recommendation.

Needs a clinical decision

  1. HI clamp: any value above 500, including a corrupt one, becomes 500 marked above range, and Loop doses against 500. The official reader has no upper cut-off either (measured: a steady 600–3000 reads HI). What it has instead is a jump check on the newest three one-minute raw readings: it gives no reading when their average step is above the sensor footer's average-delta limit (208 raw on the sensors measured, about 34–43 mg/dL a minute depending on the calibration), or when one step is above the peak-delta limit (608 raw). So a newest reading 35 mg/dL off the one before, or a 20 mg/dL one-minute blip a minute earlier, gives no reading; real glucose changes far more slowly. Measured on the official reader's algorithm, which follows those two footer bytes when they're changed. LibreTransmitter doesn't have that check, as on next-dev: a one-minute glitch from 150 to 300 reaches Loop as about 200 with the default smoothing, and as 300 without. Proposed as a follow-up. Is that the right protection, rather than a cut-off?
  2. LO clamp: near-zero values (for example a sensor pulled off the skin) become 40 LO and can raise a low alert. That errs on the side of caution, but it's a change in behaviour.
  3. Warmup is 60 minutes for every sensor type. That's right for Libre 2 and Libre 2 Plus; other types handled by this code may need their own.
  4. Display projection: measured against the official reader on synthetic ramps, it agrees within +1 mg/dL for established rises and never shows an established fall smaller than the reader (up to 11 mg/dL more, mostly near lows and above 200, where the reader limits falls more). Trends younger than ~15 minutes are projected further than the reader in both directions (up to ±17 mg/dL at ±3 mg/dL/min), because the reader projects only 2–3 minutes until its history covers the trend. Settings only, but a number a user may read.
  5. Sensor-age adjustment: optional and off by default. When on, it raises low readings on a new sensor (up to ~+30 mg/dL at 40 mg/dL in the first hours), which can delay low alerts and raise dosing, and nothing shows the raised value is more accurate; it only matches the official reader. Is offering it at all acceptable, and is the warning sufficient? It currently applies to any sensor using this algorithm when on; should it be limited to Libre 2 EU? Below 22 mg/dL nothing is raised; in the first 12 hours the reader gives no reading there and LibreTransmitter reports LO instead.

Known minor issues (not addressed here)

  • Libre 2 BLE: the reading at exactly minute 60 can be dropped by the warmup gate (the sensor start is computed a few milliseconds after the reading's date), so the first reading arrives at minute 61.
  • Settings projection: takes the temperature from the newest reading even when that reading is unusable, and on the NFC/transmitter path is shown during warmup while the readings themselves are dropped. Settings only.
  • Libre 2 BLE past the wear limit: the expiry error is sent to Loop on every packet (the update throttle is skipped), and Settings keeps showing the last status and time left.

Testing

  • 58 unit tests pass on the iOS Simulator (Shared scheme, built in LoopWorkspace). They cover:
    • the algorithm against the previous implementation;
    • invalid input, and the temperature and warmup gates;
    • the range clamp, the low-pass filter and the prediction;
    • BLE reading dates and buffer merging;
    • the three smoothing modes, including carrying over the old setting;
    • the symmetric projection, its 16-minute window (pinned exactly), a single BLE packet and the fall limit;
    • the wear-limit cut-off;
    • the official reader's output (above);
    • BLE backfill selection (only after a gap, spacing, both ends) and the ambiguous-minute guard;
    • the sensor-age adjustment: 19 measured outputs reproduced exactly, the age-dependent regression vectors with it on (128 at minute 60, 126 at the wear limit), the order before the clamp, and the default off;
    • the sensor-age cut-off: 10 official-reader vectors at the low edge (4 h to day 3), and no offset at or below 0;
    • LO/HI decided after smoothing: falls into LO and rises into HI with and without smoothing, steady out-of-range readings, and unchanged syncId.
  • The tests catch regressions: six deliberate breakages (window 15 or 6 minutes, falling horizon 0.5, window edge >, wear limit >=, unrounded LO/HI) each fail the intended test.
  • Projection against the official reader: 98 ramp frames (±1 to ±4 mg/dL/min, 5–60 minutes, ending at 70–300 mg/dL, days 5 and 13) through both; LibreTransmitter's side runs its real code on the NFC trend and on BLE-shaped inputs (packet only, 5 and 10 minutes buffered), which agree with each other.
  • BLE history and backfill, end to end:
    • History dating vs the official algorithm on a real FRAM dump: a single spiked history record shows up at exactly the minute LibreTransmitter assigns (2 of 2 positions); with flat history the official value equals LibreTransmitter's plus the age offset.
    • Live in the iOS Simulator (Loop + LibreTransmitter + libre2sim over ImpossiBLE): a 15-minute gap backfilled 1 reading; a 40-minute gap with sine-wave glucose backfilled 3 readings (sensor minutes 405, 418, 424) inside the gap. Loop's glucose store shows them with isBackfill = 1 and no trend; the history reading equals libre2sim's truth + age offset exactly, and the trend readings carry the same smoothing lag as regular readings. The deliveries after each backfill sent one normal reading.
    • Not verified: the BLE packet's history slot layout itself against the official algorithm (it only takes FRAM; libre2sim mirrors LibreTransmitter's reading of the packet). After an app relaunch, backfill needs Loop's last glucose date and was not seen in the Simulator (conservative: no backfill, no wrong data).
  • Not tested: a real sensor, Loop end to end, or that GlucoseCondition shows as LO/HI in Loop and Nightscout. The new picker has been built but not checked on screen.

Bjørn Inge Berg added 12 commits November 24, 2026 22:35
Restructure GlucoseFromRaw into a GlucoseAlgorithm type with separate
temperature, glucose and range functions, and fix the numerical edge
cases of the factory calibrated algorithm:

- Return nil instead of crashing or producing NaN/infinity when i2 is
  outside 1...1023 (t1[i2 - 1] crashed for i2 == 0), when i4 == i3, or
  when the thermistor divisor or resistance is not positive.
- Apply one reportable range to trend and history readings: invalid or
  non positive values are dropped, values above 500 mg/dL are dropped
  (history had no upper bound), and values between 0 and 40 mg/dL are
  reported as 40 ("LO"), since the linear model is unreliable below the
  sensor's specified range.
- Stop rounding before the user's extra slope and offset are applied.
  Values keep full precision through calibration and smoothing and are
  rounded only when displayed or reported. syncId rounds internally so
  its format is unchanged.

Low pass filter the sensor temperature (time based exponential moving
average, 5 minute time constant) across each batch of readings before
temperature compensation. The compensation is about 5-7 % per degree C,
and the skin side thermistor reacts faster than interstitial fluid, so
unfiltered temperature changes showed up as glucose noise. Enabled by
default, with a "Smooth sensor temperature" toggle in glucose settings.

Add GlucoseAlgorithmTests pinning the output of the previous
implementation for fixed inputs, plus tests for the guards, the range,
the filter and the temperature spike response.
Sensor sensitivity changes with age: readings tend to be low during the
first day after warmup, and sensitivity drifts over the sensor's life.
Model this as a multiplier on the t2 sensitivity:

  f(age) = 1 - earlyDeficit * e^(-age / earlyTimeConstant)
             + drift * min(age / maxAge, 1)

The active parameters are neutral (earlyDeficit = 0, drift = 0), so
output is unchanged. Real values must be fitted against reference blood
glucose measurements first: a wrong age correction biases every reading
in one direction for days, which is worse than none. An unknown or
negative age is not corrected, and the factor never drops below 0.5.

The sensor start date is passed from both data paths:
minutesSinceStart for MiaoMiao/Bubble, and the BLE age for Libre 2
direct.
The prediction (shown in settings only) extrapolates the raw glucose
10 minutes ahead with a linear fit and stamps it at the newest reading.

- Take the date and temperature from the newest reading by date instead
  of the first element, which only worked because the caller sorted
  newest first.
- Return nil instead of an unpredicted reading when there is too little
  data; the caller would have stamped that reading 10 minutes early.
- Leave readings without a raw value or with sensor error flags out of
  the fit, so a single dropout no longer tilts the line. At least 10
  usable readings are required.
- Fit on minutes relative to the newest reading. average(x * x) -
  average(x)^2 on absolute Unix timestamps lost precision and was off
  by one raw unit for about 1.4 % of timestamps.
- Convert the prediction with the newest reading's filtered temperature,
  the sensor age correction and the reportable glucose range, like the
  trend readings.
A Libre 2 BLE packet holds trend readings that are 0, 2, 4, 6, 7, 12 and
15 minutes old and history readings on the sensor's 15 minute grid. The
parser computed each reading's sensor minute (idValue) correctly, but
dated it by slot index, so the readings were stamped 0-6 minutes old
and the history 7-9 minutes old.

This broke everything that uses the dates:
- The trend arrow compares against a reading 4-6 minutes old and picked
  the one stamped 5 minutes ago, which was really 12 minutes old, so
  rates were about 2.4 times too low.
- Smoothing averaged readings spanning 7 minutes instead of 4.
- Buffered readings from earlier packets (correctly one minute apart)
  were merged with the misdated ones, so the 7, 12 and 15 minute
  readings appeared twice with different dates.

Date each reading from its sensor minute relative to the sensor age and
the time the packet was received. Merge buffered readings on idValue
instead of dates: every minute within 20 minutes of the newest reading
is included exactly once, preferring the packet's own reading, so the
gaps between the packet's slots are filled once a few packets have been
received. Only readings newer than everything buffered are added to the
buffer.

Add Libre2TrendTests for the parsed dates, the history grid and the
buffering and merging over consecutive packets.
The test sources and the shared scheme's test action referenced a
LibreTransmitterTests target that no longer existed, so no tests were
compiled or run. Add a unit test bundle target depending on the
LibreTransmitter framework, reusing the target id the shared scheme
already points to, with LibreTransmitterTests,
GlucoseAlgorithmTests and Libre2TrendTests as sources.

Qualify Measurement in the new tests, since Foundation also declares a
Measurement type.

Run with the "Shared" scheme from LoopWorkspace:
  xcodebuild test -workspace LoopWorkspace.xcworkspace \
    -scheme 'Shared (LibreTransmitter project)' \
    -destination 'platform=iOS Simulator,name=iPhone 18 Pro'
The thermistor-derived temperature feeds g2 = 1.045^(32.5 - t), so a corrupt
thermistor read outside the sensor's operating band produces a plausible-looking
but wrong glucose instead of an obvious failure. Drop readings whose temperature
falls outside 10-45 C, mirroring the official algorithm's TEMP_HIGH / TEMP_LOW
data-quality gating. Normal on-body readings sit around 30-37 C, so real data is
unaffected (verified against captured sensor FRAMs, 32.8-35.4 C).
The sensor is not equilibrated during the warmup period, so its raw output is
unreliable; the official algorithm reports no value (SensorInWarmupException)
until warmup completes. Suppress calibrated glucose for measurements whose age
is below warmupInterval (60 min for Libre 2) when the sensor start time is known.
Readings pass through unchanged when the start time is unknown.
The official reader shows a short forward extrapolation of the trend, not the raw
latest reading: reverse-engineering reference scans shows an asymmetric projection
(~5.5 min ahead when rising, ~0.5 min when falling, rate over a ~6 min window).
Add predictDisplayGlucose mirroring that, alongside the existing predictBloodSugar.
Parameters are fitted from limited data and left tunable. Display only - it must
not drive dosing, since Loop applies its own momentum prediction.
Replace the old symmetric 10-minute extrapolation (predictBloodSugar) in the
settings-only current-glucose projection with predictDisplayGlucose, the
asymmetric trend projection that mirrors the official reader. Stamp the result
at the newest reading, since it is a projected current value shown now, not a
future reading. predictBloodSugar stays as a tested utility. Display only; not
sent to Loop.
…ing highs

The reader keeps an out-of-range reading and shows LO below 40 / HI above 500
(exclusive; 40 and 500 are shown as numbers), rather than dropping it. We
previously clamped lows to 40 but discarded readings above 500, which produces a
silent gap during a very high reading - no value is reported at all. Clamp both
ends to the sensor's rated range instead, so a severe high still surfaces.
Non-finite inputs still return nil.

NOTE for review: this changes the value sent downstream for readings above 500
from (dropped) to 500. Surfacing LO/HI as explicit display states over the
unclamped value (as the reader does) is a larger change left for a follow-up.
When a calibrated reading falls outside the sensor's 40-500 mg/dL range, carry
GlucoseCondition .belowRange / .aboveRange on the glucose and pass it to the
NewGlucoseSample (previously hardcoded nil). The value is still clamped to the
boundary, but Loop/Nightscout now know it is really below/above range and show
LO/HI, matching the official reader.

This is the correct LoopKit mechanism for out-of-range - not isDisplayOnly, which
marks a value as not-for-dosing and would make Loop ignore a genuine low. The
condition survives smoothing (CalculateSmothedData5Points mutates in place).

NOTE for review: assumes GlucoseCondition is Codable (LibreGlucose is Codable);
verify on build. Loop's handling of belowRange/aboveRange should be confirmed in-app.
Glucose and temperature smoothing were two separate switches, and both
could be on at once, adding their lag. They are now one choice in
Glucose processing, one kind at a time:

- Off: nothing is smoothed.
- Temperature: the sensor temperature is filtered before temperature
  compensation; readings are not averaged.
- Glucose (previous, default): trend readings are averaged over about
  five minutes, as before.

Whoever had glucose smoothing on or off before keeps it that way, so
nobody's readings change until they choose Temperature.
@dabear
dabear force-pushed the glucose-algorithm-robustness branch from d372f45 to a781b18 Compare November 24, 2026 22:25
Bjørn Inge Berg and others added 6 commits November 25, 2026 00:07
The comment said unfiltered temperature changes show up as 5-7 % glucose
noise per °C. The temperature compensation, 1.045^(32.5 - t), gives
4.5 % per °C. It also now says that the thermistor leading the sensor's
chemistry is assumed, not measured.
The AgeCorrection model (ageFactor) scaled sensor sensitivity by a
day-one deficit and a lifetime drift term, but shipped neutral
(earlyDeficit = 0, drift = 0), so it never changed a reading. Its shape
was a guess that was never fitted against reference blood glucose, so
drop it rather than carry a dormant, unvalidated correction.

The sensorStart -> sensorAge plumbing stays: the warmup drop in
calibratedGlucoses still uses it. Only the parts that existed solely to
feed ageFactor are removed - the sensorAge argument threaded down through
calibratedGlucose/glucoseValueFromRaw/glucose, and the sensorStart
parameter of createBloodSugarPrediction, which fed nothing but the
neutral correction.

Remove testDefaultAgeCorrectionIsNeutral and testAgeFactorShape; the
warmup tests that exercise sensorStart are unchanged.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The display-only projection ("Last Blood Sugar prediction" in Settings)
projected rises 5.5 minutes ahead but falls only 0.5, from a 6 minute
window. Those horizons came from simulator scans. Measured against the
official reader's algorithm on synthetic ramps, it projects rises and
falls alike, about 8 minutes once a trend is established, so a fall was
shown up to ~14 mg/dL less urgent than the reader shows it.

- One horizon of 8 minutes for rises and falls.
- The rate comes from the last 16 minutes instead of 6. A Libre 2 BLE
  packet alone holds readings 0, 2, 4, 6, 7, 12 and 15 minutes old, so
  the projection works from the first packet, and buffered readings fill
  the minutes in between. 16 rather than 15 keeps the 15 minute slot in
  the window despite a few seconds of drift in buffered readings' dates.
  The longer window is also steadier: about 1.25 sigma (NFC) and 1.41
  sigma (one BLE packet) of displayed noise, against 1.43 before.
- A fall is limited to 15 mg/dL below the newest reading. The reader
  limits established falls by level (about 6 mg/dL ending at 70, 10 at
  80, 15 at 100-120, 12 at 220, 9 at 300); 15 is its largest, so a fall
  is never shown smaller than the reader shows it. Rises aren't limited.

On 98 ramp frames run through both: established rises within +1 mg/dL
of the reader, established falls never smaller (0 to 11 mg/dL more).
Trends younger than ~15 minutes are projected further than the reader,
which projects only 2-3 minutes until its history covers them.

Still display-only: never sent to Loop, which projects on its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Over BLE, a sensor past its wear limit (maxMinutesWearTime from the FRAM
footer) only got an expiry notification; its readings kept going to
Loop. The official reader stops then: it reports up to and including the
limit minute and nothing after (checked minute by minute). The
FRAM/transmitter path already stops, on the sensor's own state byte.

Now the BLE path reports LibreError.expiredSensor and no readings once
the sensor age is past the limit. An unknown limit (0) cuts off nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The official reader rounds to whole mg/dL first: 39.5 shows as 40 and
500.04 as 500, in range; 39.4 is LO and 500.5 is HI. The below/above
range condition compared the unrounded value, so 39.5 was marked LO and
500.04 HI. The reported (clamped) value itself is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Frames built from Libre2.Example2 (decrypted; public test data) with all
records set to one reading, run through the official reader's algorithm
(LibreLink 2.3.0's libDataProcessing, unmodified, on an emulator; one
cold scan per frame, each scanned twice and agreeing). The tests check
LibreTransmitter against its output:

- temperature compensation at 26-37 °C and levels 60-350: identical;
- the LO/HI edges (its 39 and 501), decided on the rounded value;
- the wear limit: reported at the limit minute, nothing after;
- warmup, which differs on purpose and is recorded so a change is
  deliberate: the reader reports uncorrected values from minute 57 and
  adds its sensor-age offset from minute 60; LibreTransmitter reports
  nothing before 60 and has no age offset.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@dabear
dabear force-pushed the glucose-algorithm-robustness branch from ce7fa31 to 2d3c474 Compare November 26, 2026 09:41
Bjørn Inge Berg and others added 4 commits November 26, 2026 13:55
…ult)

The official reader adds an offset to each reading that depends only on
the reading's sensor age (measured black-box on flat FRAM frames of three
real sensors; 287 cold scans, every one reproduced within ±1 mg/dL by the
fitted curve, not the reader's code). It is additive, the same at 100,
200 and 300 mg/dL:

- early: a difference of two exponentials from sensor start, +7.6 at 60
  minutes, peaking at +18.2 at about 5.4 h, gone by about 38 h;
- low: from 63 to 556 minutes only, readings below 90 mg/dL get
  (0.306 - 0.0135 t) * (90 - G) on top (+30 instead of +17 at 40 mg/dL
  and 4 h);
- late: from day 10, +4/3 mg/dL per day.

A new setting, "Match the official reader's sensor-age adjustment
(experimental)", adds it to trend and history readings and the Settings
projection, before the 40-500 clamp (early in wear the reader turns 30
into ~60, not LO). Off by default; turning it on goes through a warning:
it raises readings on a new sensor, lows most of all, which can delay
low alerts and raise dosing, and nothing shows the adjusted values are
more accurate. Validated for Libre 2 EU (and Libre 1 calibrations); the
reader's separate warmup-referenced early correction is not included.

Tests reproduce 19 measured outputs exactly, the regression vectors that
depend on age (128 at minute 60, 126 at the wear limit) with it on, the
order before the clamp, and the default off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Over BLE only the newest reading of each packet went to Loop, so a gap in
delivery (out of range, the app suspended) stayed empty, although every
packet also holds three history readings on the sensor's 15-minute grid
(about 2-16, 17-31 and 32-46 minutes old) and older trend readings.

When "Backfill from history" is on (the existing setting, on by default)
and the newest reading is more than 7 minutes after the last one sent to
Loop, the packet's history and older trend readings dated inside the gap
are sent too, at least 4.5 minutes apart and from both ends of the gap,
marked as backfill, without a trend arrow. While readings arrive on time
nothing changes, and a reading is never backfilled twice: the last-sent
marker moves to the newest reading.

History dating: the packet's slots are placed as ((age - 2) / 15) * 15
and the two before it. Checked against the official algorithm on a real
FRAM dump: a single-record spike shows up at exactly the minute this
assigns. Reading the same records from FRAM agrees except when age is 2
minutes past a grid minute, where the two differ by a slot; history
readings from such packets are not used.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sensor-age offset: no offset for readings that round below 22 mg/dL.
The offset was added to any value, so with the setting on, a reading at
or below 0 (a sensor pulled off) could be lifted to about 40 mg/dL in
range in the first hours, instead of being dropped. The official reader
doesn't raise those readings either: measured on its algorithm, it
returns no reading for them during the first 12 hours and LO later, and
raises readings from 22 (21.40 gets nothing, 21.57 becomes 52-56, at
1.5, 4 and 8 h). Here they stay as they are: dropped at or below 0, LO
up to 21, as with the setting off. The reader's gap in the first 12
hours is not copied; LO is kept as the cautious choice.

LO/HI of trend readings: decided on the value sent, after smoothing.
The mark was set from each unsmoothed reading and smoothing then
averaged the values, so Loop could get 42.5 marked below range, or 494
marked above. Out-of-range readings are now held at the official
reader's own LO/HI values (39 / 501) before smoothing, and after it each
value is marked from its rounded result and clamped to 40-500. A fall
into LO that averages above 40 is sent unmarked; a steady low stays LO
at 40 and a steady high HI at 500. syncId keeps clamping to 40-500, so
identifiers don't change.

Tests: ten new official-reader vectors at the low edge (offset on), the
offset cut-off, falls into LO and rises into HI with and without
smoothing, steady LO/HI, and syncId.
@dabear
dabear merged commit bd99b0f into next-dev Nov 27, 2026
dabear pushed a commit that referenced this pull request Nov 29, 2026
…rst byte

Patch info can be 8 bytes (pairing accepts 6 or 8 since #66), but the
first-generation EU fallback only accepted 6, so such a sensor with an
unlisted first byte was rejected. It now reads bytes 2 and 3 from any
patch info of at least 4 bytes.

A generation 2 sensor can share a first byte with first-generation ones
(Australia: 7F 0E 3A 04 ..). It was read as Libre 2 and decrypted with
the first-generation key, which can't work. It is now rejected as the
wrong sensor type, with its patch info shown.
dabear added a commit that referenced this pull request Nov 29, 2026
…s) (#67)

* Libre 2 pairing: show the patch info when the sensor type is unknown

A new Libre 2 batch can report a first patch info byte we don't know yet
(EU sensors with serials starting with 303 now fail with "Wrong sensor type
detected"). The NFC message now ends with the 6 patch info bytes in hex,
so users can report them, and the rejection is logged with them. The error
sent to the app is now wrongSensorType, not noSensorData.

* Libre 2 EU: accept patch info first byte 0x84

EU Libre 2 sensors with serials starting with 303 report patch info
84 0E 30 01 .., which was rejected as the wrong sensor type. Apart from
the first byte it is an ordinary Libre 2: family 3 with security
version 0 (not generation 2) and the EU region, so it is read as one.

* Libre 2 EU: accept an unlisted first patch info byte

A new batch can again bring a first patch info byte that isn't listed.
When the rest of the patch info says Libre 2 (family 3) with a security
version below generation 2's (9) in the EU region, the sensor is read as
a Libre 2 instead of being rejected. Generation 2, other regions and
other families still need their first byte listed.

* Libre 2: read 8-byte patch info, reject generation 2 with a listed first byte

Patch info can be 8 bytes (pairing accepts 6 or 8 since #66), but the
first-generation EU fallback only accepted 6, so such a sensor with an
unlisted first byte was rejected. It now reads bytes 2 and 3 from any
patch info of at least 4 bytes.

A generation 2 sensor can share a first byte with first-generation ones
(Australia: 7F 0E 3A 04 ..). It was read as Libre 2 and decrypted with
the first-generation key, which can't work. It is now rejected as the
wrong sensor type, with its patch info shown.

---------

Co-authored-by: Bjørn Inge Berg <bjorninge-git@bjorninge.no>
dabear pushed a commit that referenced this pull request Nov 29, 2026
…rst byte

Patch info can be 8 bytes. Pairing now accepts 6 or 8, as next-dev does
since #66, and the first-generation EU fallback reads bytes 2 and 3 from
any patch info of at least 4 bytes instead of only 6.

A generation 2 sensor can share a first byte with first-generation ones
(Australia: 7F 0E 3A 04 ..). It was read as Libre 2 and decrypted with
the first-generation key, which can't work. It is now rejected as the
wrong sensor type, with its patch info shown.
dabear added a commit that referenced this pull request Nov 29, 2026
…s) [main] (#68)

* Libre 2 pairing: show the patch info when the sensor type is unknown

A new Libre 2 batch can report a first patch info byte we don't know yet
(EU sensors with serials starting with 303 now fail with "Wrong sensor type
detected"). The NFC message now ends with the 6 patch info bytes in hex,
so users can report them, and the rejection is logged with them. The error
sent to the app is now wrongSensorType, not noSensorData.

* Libre 2 EU: accept patch info first byte 0x84

EU Libre 2 sensors with serials starting with 303 report patch info
84 0E 30 01 .., which was rejected as the wrong sensor type. Apart from
the first byte it is an ordinary Libre 2: family 3 with security
version 0 (not generation 2) and the EU region, so it is read as one.

* Libre 2 EU: accept an unlisted first patch info byte

A new batch can again bring a first patch info byte that isn't listed.
When the rest of the patch info says Libre 2 (family 3) with a security
version below generation 2's (9) in the EU region, the sensor is read as
a Libre 2 instead of being rejected. Generation 2, other regions and
other families still need their first byte listed.

* Libre 2: read 8-byte patch info, reject generation 2 with a listed first byte

Patch info can be 8 bytes. Pairing now accepts 6 or 8, as next-dev does
since #66, and the first-generation EU fallback reads bytes 2 and 3 from
any patch info of at least 4 bytes instead of only 6.

A generation 2 sensor can share a first byte with first-generation ones
(Australia: 7F 0E 3A 04 ..). It was read as Libre 2 and decrypted with
the first-generation key, which can't work. It is now rejected as the
wrong sensor type, with its patch info shown.

---------

Co-authored-by: Bjørn Inge Berg <bjorninge-git@bjorninge.no>
ps2 added a commit to LoopKit/LoopWorkspace that referenced this pull request Dec 1, 2026
…LibreTransmitter and TrueTime.swift

- Loop, LoopKit, OmnipodKit, MinimedKit and MedtrumKit: the watch shows the
  current pump reservoir level from pump status (LoopKit/Loop#2706,
  LoopKit/LoopKit#709, loopandlearn/OmnipodKit#230, LoopKit/MinimedKit#50,
  LoopKit/MedtrumKit#13)
- Loop: reset the Presets icon when a restored preset expires
  (LoopKit/Loop#2685); watch layout moves up with Active Insulin first
  (LoopKit/Loop#2670)
- LoopKit: the preset ISF preview gets a per-unit quantity (LoopKit/LoopKit#711)
- G7SensorKit: a failed sensor shows as a row instead of its raw state name
  (LoopKit/G7SensorKit#142)
- LibreTransmitter: glucose algorithm robustness (LoopKit/LibreTransmitter#66);
  Libre 2 EU sensors with the new patch info first byte pair
  (LoopKit/LibreTransmitter#67)
- TrueTime.swift: iOS deployment target 15.0 (LoopKit/TrueTime.swift#4)
ps2 added a commit to LoopKit/LoopWorkspace that referenced this pull request Dec 1, 2026
…outService, MinimedKit, MedtrumKit, LibreTransmitter and TrueTime.swift; add GlookoService (#595)

* Bump Loop and OmnipodKit for watch plugin loading

Loop: the watch app loads its CGM kit at run time (LoopKit/Loop#2693), and
HealthKit authorization no longer blocks the main thread (LoopKit/Loop#2684).
OmnipodKit: the watch can load OmnipodKit at run time
(loopandlearn/OmnipodKit#225).

* Bump G7SensorKit for run-time watch loading and early control notifications

The watch loads G7SensorKit at run time (LoopKit/G7SensorKit#110), which the
Loop watch app change in LoopKit/Loop#2693 depends on. Control notifications
are enabled before authentication when eavesdropping (LoopKit/G7SensorKit#126).

* Bump G7SensorKit to include run-time watch loading

The previous bump stopped at LoopKit/G7SensorKit#126; next-dev's tip is
LoopKit/G7SensorKit#110, which the Loop watch app change depends on.

* Bump TrueTime.swift to ignore SIGPIPE on its sockets

A write to a socket the server had closed raised SIGPIPE and killed Loop
(LoopKit/TrueTime.swift#6).

* Add GlookoService

Adds Nutcasey/GlookoService at 459dc9d as a submodule, its project to the
workspace and GlookoServiceKitPlugin to the LoopWorkspace scheme.

* Bump G7SensorKit, LoopKit, Loop, TidepoolService and GlookoService

- G7SensorKit to c86d9bb: a link that delivered a reading isn't a stopped
  session (#127), rescan after a 2 s sleep and connect when another app
  connects (#130), reissue the connect at power-on after a restore (#134),
  and a new sensor or code from the phone keeps the watch's session (#128)
- LoopKit to bf8710f2: a device several controllers use can take a changed
  configuration in place (#706)
- Loop to 60007b90: active services in the Issue Report (#2700)
- TidepoolService to 365f124: pump component changes upload as
  reservoirChange and cannula prime events (#51)
- GlookoService to 8349aa0: three alerts instead of twelve, localised text

* Bump LoopKit, OmnipodKit, TidepoolService and NightscoutService for component replacement

- LoopKit to 4e2b9c50: pump events carry component replacement details
  (LoopKit/LoopKit#703)
- OmnipodKit to 681d4cc: the pod change is described with a
  ComponentReplacement (loopandlearn/OmnipodKit#224)
- TidepoolService to 71cc679: uploads the replacement details instead of
  decoding raw data (LoopKit/TidepoolService#52)
- NightscoutService to 6952920: Site Change notes include the replacement
  reason (LoopKit/NightscoutService#52)

* update Glooko: Add Glooko regions: United States, Canada, Germany and France, improve logging

* update Script/define_common to include GlookoService

* fix: update Script/define_common for next-dev branches

* Bump G7SensorKit for early setup from didConnect, the start-delay reconnect and the link hold

LoopKit/G7SensorKit#135 and LoopKit/G7SensorKit#138.

* Bump Loop, LoopKit, OmnipodKit, MinimedKit, MedtrumKit, G7SensorKit, LibreTransmitter and TrueTime.swift

- Loop, LoopKit, OmnipodKit, MinimedKit and MedtrumKit: the watch shows the
  current pump reservoir level from pump status (LoopKit/Loop#2706,
  LoopKit/LoopKit#709, loopandlearn/OmnipodKit#230, LoopKit/MinimedKit#50,
  LoopKit/MedtrumKit#13)
- Loop: reset the Presets icon when a restored preset expires
  (LoopKit/Loop#2685); watch layout moves up with Active Insulin first
  (LoopKit/Loop#2670)
- LoopKit: the preset ISF preview gets a per-unit quantity (LoopKit/LoopKit#711)
- G7SensorKit: a failed sensor shows as a row instead of its raw state name
  (LoopKit/G7SensorKit#142)
- LibreTransmitter: glucose algorithm robustness (LoopKit/LibreTransmitter#66);
  Libre 2 EU sensors with the new patch info first byte pair
  (LoopKit/LibreTransmitter#67)
- TrueTime.swift: iOS deployment target 15.0 (LoopKit/TrueTime.swift#4)

---------

Co-authored-by: marionbarker <marionbarker@earthlink.net>
dnzxy pushed a commit to loopandlearn/LibreTransmitter that referenced this pull request Dec 1, 2026
- Harden glucose algorithm and smooth sensor temperature
- Fix blood sugar prediction ordering, precision and input filtering
- Date Libre 2 BLE readings by their sensor minute, and backfill gaps from the packet's history readings
- Gate glucose on the sensor operating temperature range and drop readings taken during warmup
- Stop reporting Libre 2 BLE readings past the wear limit
- Clamp out-of-range glucose to 40-500 and report it with GlucoseCondition; decide LO/HI on the rounded value, as the official reader does
- Smoothing as one setting: Off, Temperature or Glucose (previous)
- Display-only symmetric current-glucose projection in Settings (8 minutes over 16)
- Optionally match the official reader's sensor-age offset (off by default)
- Add the LibreTransmitterTests unit test target, with regression vectors from the official reader's algorithm
- NFC: accept 6- or 8-byte patchInfo during pairing

(cherry picked from commit bd99b0f)
dnzxy pushed a commit to loopandlearn/LibreTransmitter that referenced this pull request Dec 1, 2026
…s) (LoopKit#67)

* Libre 2 pairing: show the patch info when the sensor type is unknown

A new Libre 2 batch can report a first patch info byte we don't know yet
(EU sensors with serials starting with 303 now fail with "Wrong sensor type
detected"). The NFC message now ends with the 6 patch info bytes in hex,
so users can report them, and the rejection is logged with them. The error
sent to the app is now wrongSensorType, not noSensorData.

* Libre 2 EU: accept patch info first byte 0x84

EU Libre 2 sensors with serials starting with 303 report patch info
84 0E 30 01 .., which was rejected as the wrong sensor type. Apart from
the first byte it is an ordinary Libre 2: family 3 with security
version 0 (not generation 2) and the EU region, so it is read as one.

* Libre 2 EU: accept an unlisted first patch info byte

A new batch can again bring a first patch info byte that isn't listed.
When the rest of the patch info says Libre 2 (family 3) with a security
version below generation 2's (9) in the EU region, the sensor is read as
a Libre 2 instead of being rejected. Generation 2, other regions and
other families still need their first byte listed.

* Libre 2: read 8-byte patch info, reject generation 2 with a listed first byte

Patch info can be 8 bytes (pairing accepts 6 or 8 since LoopKit#66), but the
first-generation EU fallback only accepted 6, so such a sensor with an
unlisted first byte was rejected. It now reads bytes 2 and 3 from any
patch info of at least 4 bytes.

A generation 2 sensor can share a first byte with first-generation ones
(Australia: 7F 0E 3A 04 ..). It was read as Libre 2 and decrypted with
the first-generation key, which can't work. It is now rejected as the
wrong sensor type, with its patch info shown.

---------

Co-authored-by: Bjørn Inge Berg <bjorninge-git@bjorninge.no>
(cherry picked from commit a2f098f)
dnzxy added a commit to loopandlearn/LibreTransmitter that referenced this pull request Dec 3, 2026
LoopKit#66 wrote this call against LoopKit's async CGMManagerDelegate, which
needs #696. Revert the await when that lands.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant