Repository navigation
Glucose algorithm robustness - #66
Merged
Merged
Conversation
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
force-pushed
the
glucose-algorithm-robustness
branch
from
November 24, 2026 22:25
d372f45 to
a781b18
Compare
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
force-pushed
the
glucose-algorithm-robustness
branch
from
November 26, 2026 09:41
ce7fa31 to
2d3c474
Compare
…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
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.What changes for the user
What reaches Loop
The above/below-range mark uses LoopKit's
GlucoseCondition(.aboveRange/.belowRange), notisDisplayOnly. 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:
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)
Changes
Algorithm hardening (
GlucoseFromRaw.swift,GlucoseAlgorithm): returnsnilinstead 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;syncIdstill 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 toNewGlucoseSample.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.syncIdstill 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
isBackfillsamples 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:
(0.306 − 0.0135·t)·(90 − G)more (+30 instead of +17 at 40 mg/dL and 4 h);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.
Test target: adds the
LibreTransmitterTestsunit test bundle the shared scheme already pointed to.Regression vectors: synthetic frames from
Libre2.Example2with 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):traces/. At that level the temperature filter changes readings by about 0.1 mg/dL.Hence the default stays Glucose (previous), and Temperature stays an option rather than a recommendation.
Needs a clinical decision
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?Known minor issues (not addressed here)
Testing
Sharedscheme, built in LoopWorkspace). They cover:syncId.>, wear limit>=, unrounded LO/HI) each fail the intended test.isBackfill = 1and 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.GlucoseConditionshows as LO/HI in Loop and Nightscout. The new picker has been built but not checked on screen.