diff --git a/LoopFollow/Alarm/AlarmCondition/AlarmCondition.swift b/LoopFollow/Alarm/AlarmCondition/AlarmCondition.swift index 242d84069..2f82b69e1 100644 --- a/LoopFollow/Alarm/AlarmCondition/AlarmCondition.swift +++ b/LoopFollow/Alarm/AlarmCondition/AlarmCondition.swift @@ -27,7 +27,8 @@ extension AlarmCondition { func passesBGLimits(alarm: Alarm, data: AlarmData) -> Bool { let bgReading = data.bgReadings.last?.sgv let haveBG = (bgReading ?? 0) > 0 - let bgValue = Double(bgReading ?? 0) + let normalize = UnitSettingsStore.shared.normalizeToDisplayPrecision + let bgValue = normalize(Double(bgReading ?? 0)) // ──────────────────────────────────── // 1. BG-based alarms always need data @@ -51,7 +52,7 @@ extension AlarmCondition { // BG-based alarms already bailed out above. guard haveBG else { return false } - switch (alarm.belowBG, alarm.aboveBG) { + switch (alarm.belowBG.map(normalize), alarm.aboveBG.map(normalize)) { case let (lo?, hi?): return lo < hi ? (bgValue <= lo || bgValue >= hi) // fire outside band : (hi <= bgValue && bgValue <= lo) // fire inside band diff --git a/LoopFollow/Alarm/AlarmCondition/HighBGCondition.swift b/LoopFollow/Alarm/AlarmCondition/HighBGCondition.swift index 6ba8b9b47..8884e6e96 100644 --- a/LoopFollow/Alarm/AlarmCondition/HighBGCondition.swift +++ b/LoopFollow/Alarm/AlarmCondition/HighBGCondition.swift @@ -14,8 +14,11 @@ struct HighBGCondition: AlarmCondition { // ──────────────────────────────── guard let high = alarm.aboveBG else { return false } + let normalize = UnitSettingsStore.shared.normalizeToDisplayPrecision + let highLimit = normalize(high) + func isHigh(_ g: GlucoseValue) -> Bool { - g.sgv > 0 && Double(g.sgv) >= high + g.sgv > 0 && normalize(Double(g.sgv)) >= highLimit } // we already know from `passesBGLimits` that the **latest** reading is ≥ high, diff --git a/LoopFollow/Alarm/AlarmCondition/LowBGCondition.swift b/LoopFollow/Alarm/AlarmCondition/LowBGCondition.swift index 2d48fe25f..134c4649d 100644 --- a/LoopFollow/Alarm/AlarmCondition/LowBGCondition.swift +++ b/LoopFollow/Alarm/AlarmCondition/LowBGCondition.swift @@ -33,8 +33,11 @@ struct LowBGCondition: AlarmCondition { guard let belowBG = alarm.belowBG else { return false } guard let latest = data.bgReadings.last, latest.sgv > 0 else { return false } + let normalize = UnitSettingsStore.shared.normalizeToDisplayPrecision + let lowLimit = normalize(belowBG) + func isLow(_ g: GlucoseValue) -> Bool { - g.sgv > 0 && Double(g.sgv) <= belowBG + g.sgv > 0 && normalize(Double(g.sgv)) <= lowLimit } // ──────────────────────────────── diff --git a/LoopFollow/Charts/BGChartModel.swift b/LoopFollow/Charts/BGChartModel.swift index 525fcfcb2..23fed5036 100644 --- a/LoopFollow/Charts/BGChartModel.swift +++ b/LoopFollow/Charts/BGChartModel.swift @@ -273,12 +273,10 @@ final class BGChartModel: ObservableObject { } private func colorFor(_ sgv: Int, thresholds: (low: Double, high: Double)) -> Color { - if Double(sgv) >= thresholds.high { - return .yellow - } else if Double(sgv) <= thresholds.low { - return .red - } else { - return .green + switch UnitSettingsStore.shared.glucoseBand(for: Double(sgv), thresholds: thresholds) { + case .high: return .yellow + case .low: return .red + case .inRange: return .green } } diff --git a/LoopFollow/Contact/ContactColorMode.swift b/LoopFollow/Contact/ContactColorMode.swift index 7d146040c..25ec4bc8a 100644 --- a/LoopFollow/Contact/ContactColorMode.swift +++ b/LoopFollow/Contact/ContactColorMode.swift @@ -16,21 +16,16 @@ enum ContactColorMode: String, Codable, CaseIterable { } } - /// Returns the appropriate text color based on the mode and BG value + /// Returns the appropriate text color based on the mode and BG value (in mg/dL). func textColor(for bgValue: Double, staticColor: UIColor) -> UIColor { switch self { case .staticColor: return staticColor case .dynamic: - let highLine = Storage.shared.highLine.value - let lowLine = Storage.shared.lowLine.value - - if bgValue >= highLine { - return .systemYellow - } else if bgValue <= lowLine { - return .systemRed - } else { - return .systemGreen + switch UnitSettingsStore.shared.glucoseBand(for: bgValue) { + case .high: return .systemYellow + case .low: return .systemRed + case .inRange: return .systemGreen } } } diff --git a/LoopFollow/Controllers/Stats.swift b/LoopFollow/Controllers/Stats.swift index 15447db9d..29358dc33 100644 --- a/LoopFollow/Controllers/Stats.swift +++ b/LoopFollow/Controllers/Stats.swift @@ -27,17 +27,13 @@ class StatsData { coefficientOfVariation = 0.0 let thresholds = UnitSettingsStore.shared.effectiveThresholds() - let lowThreshold = thresholds.low - let highThreshold = thresholds.high for i in 0 ..< bgData.count { // Set low/range/high counts for pie chart and %'s - if Double(bgData[i].sgv) < lowThreshold { - countLow += 1 - } else if Double(bgData[i].sgv) > highThreshold { - countHigh += 1 - } else { - countRange += 1 + switch UnitSettingsStore.shared.glucoseBand(for: Double(bgData[i].sgv), thresholds: thresholds) { + case .low: countLow += 1 + case .high: countHigh += 1 + case .inRange: countRange += 1 } // set total bg for average diff --git a/LoopFollow/Helpers/Localizer.swift b/LoopFollow/Helpers/Localizer.swift index 3d32a51da..27a343197 100644 --- a/LoopFollow/Helpers/Localizer.swift +++ b/LoopFollow/Helpers/Localizer.swift @@ -111,6 +111,18 @@ final class UnitSettingsStore { ) } + /// Rounds a mg/dL value to the display precision of the current unit, so colors, + /// stats and alarms match the number shown. Apply to both the reading and the threshold. + func normalizeToDisplayPrecision(_ mgdl: Double) -> Double { + GlucoseConversion.toDisplayPrecision(mgdl, mmol: glucoseUnit == .mmolL) + } + + /// Band of a mg/dL reading against the selected range (or `thresholds` when given). + func glucoseBand(for mgdl: Double, thresholds: (low: Double, high: Double)? = nil) -> GlucoseBand { + let range = thresholds ?? effectiveThresholds() + return GlucoseBand.of(mgdl, low: range.low, high: range.high, mmol: glucoseUnit == .mmolL) + } + var glycemicMetricMode: GlycemicMetricMode { get { Storage.shared.showGMI.value ? .gmi : .ehba1c diff --git a/LoopFollow/Helpers/Views/BGPicker.swift b/LoopFollow/Helpers/Views/BGPicker.swift index 86c99a706..0a7c9fd20 100644 --- a/LoopFollow/Helpers/Views/BGPicker.swift +++ b/LoopFollow/Helpers/Views/BGPicker.swift @@ -17,9 +17,10 @@ struct BGPicker: View { private var allValues: [Double] { if unit == .millimolesPerLiter { let step = 0.1 - let lower = ceil((range.lowerBound / 18) / step) * step - let upper = floor((range.upperBound / 18) / step) * step - return stride(from: lower, through: upper, by: step).map { $0 * 18 } + let factor = GlucoseConversion.mmolToMgDl + let lower = ceil((range.lowerBound / factor) / step) * step + let upper = floor((range.upperBound / factor) / step) * step + return stride(from: lower, through: upper, by: step).map { $0 * factor } } else { return Array(stride(from: range.lowerBound, through: range.upperBound, diff --git a/LoopFollow/InfoTable/RetroSnapshot.swift b/LoopFollow/InfoTable/RetroSnapshot.swift index d7a0a7cff..11765def4 100644 --- a/LoopFollow/InfoTable/RetroSnapshot.swift +++ b/LoopFollow/InfoTable/RetroSnapshot.swift @@ -101,13 +101,10 @@ extension MainViewController { bgText = Localizer.toDisplayUnits(String(reading.sgv)) } if Storage.shared.colorBGText.value { - let thresholds = UnitSettingsStore.shared.effectiveThresholds() - if Double(reading.sgv) >= thresholds.high { - bgColor = .yellow - } else if Double(reading.sgv) <= thresholds.low { - bgColor = .red - } else { - bgColor = .green + switch UnitSettingsStore.shared.glucoseBand(for: Double(reading.sgv)) { + case .high: bgColor = .yellow + case .low: bgColor = .red + case .inRange: bgColor = .green } } if let direction = reading.direction { diff --git a/LoopFollow/LiveActivity/LiveActivityManager.swift b/LoopFollow/LiveActivity/LiveActivityManager.swift index 0d3e61fe5..923140660 100644 --- a/LoopFollow/LiveActivity/LiveActivityManager.swift +++ b/LoopFollow/LiveActivity/LiveActivityManager.swift @@ -5,6 +5,7 @@ #if !targetEnvironment(macCatalyst) @preconcurrency import ActivityKit +import Combine import Foundation import os import UIKit @@ -44,6 +45,17 @@ final class LiveActivityManager { ) startPushToStartTokenObservation() startActivityUpdatesObservation() + + // dropFirst: @Published emits its current value on subscribe; only react to changes. + Publishers.Merge( + Storage.shared.lowLine.$value.dropFirst().map { _ in () }, + Storage.shared.highLine.$value.dropFirst().map { _ in () } + ) + .receive(on: DispatchQueue.main) + .sink { [weak self] _ in + self?.refreshFromCurrentState(reason: "thresholds changed") + } + .store(in: &cancellables) } // MARK: - Push-to-start observation @@ -433,6 +445,7 @@ final class LiveActivityManager { /// and arrives within a few seconds of the first request. private static let pushToStartTokenRetryDelay: TimeInterval = 10 + private var cancellables = Set() private(set) var current: Activity? private var stateObserverTask: Task? private var updateTask: Task? diff --git a/LoopFollow/Stats/GRI/GRICalculator.swift b/LoopFollow/Stats/GRI/GRICalculator.swift index fd170f55b..6efbbff7f 100644 --- a/LoopFollow/Stats/GRI/GRICalculator.swift +++ b/LoopFollow/Stats/GRI/GRICalculator.swift @@ -25,16 +25,23 @@ class GRICalculator { var highCount = 0 var vHighCount = 0 + // Compare at display precision so readings that show the same value share a band. + let normalize = UnitSettingsStore.shared.normalizeToDisplayPrecision + let vLowLimit = normalize(vLowThreshold) + let lowLimit = normalize(lowThreshold) + let highLimit = normalize(highThreshold) + let vHighLimit = normalize(vHighThreshold) + for reading in bgData { - let glucose = Double(reading.sgv) + let glucose = normalize(Double(reading.sgv)) - if glucose < vLowThreshold { + if glucose < vLowLimit { vLowCount += 1 - } else if glucose < lowThreshold { + } else if glucose < lowLimit { lowCount += 1 - } else if glucose > vHighThreshold { + } else if glucose > vHighLimit { vHighCount += 1 - } else if glucose > highThreshold { + } else if glucose > highLimit { highCount += 1 } } diff --git a/LoopFollow/Stats/TIR/TIRCalculator.swift b/LoopFollow/Stats/TIR/TIRCalculator.swift index a27eef414..08a5c9d30 100644 --- a/LoopFollow/Stats/TIR/TIRCalculator.swift +++ b/LoopFollow/Stats/TIR/TIRCalculator.swift @@ -108,14 +108,22 @@ class TIRCalculator { var highCount = 0 var veryHighCount = 0 - for glucose in readings { - if glucose < veryLowThreshold { + // Compare at display precision so readings that show the same value share a band. + let normalize = UnitSettingsStore.shared.normalizeToDisplayPrecision + let veryLowLimit = normalize(veryLowThreshold) + let lowLimit = normalize(lowThreshold) + let highLimit = normalize(highThreshold) + let veryHighLimit = normalize(veryHighThreshold) + + for reading in readings { + let glucose = normalize(reading) + if glucose < veryLowLimit { veryLowCount += 1 - } else if glucose < lowThreshold { + } else if glucose < lowLimit { lowCount += 1 - } else if glucose > veryHighThreshold { + } else if glucose > veryHighLimit { veryHighCount += 1 - } else if glucose > highThreshold { + } else if glucose > highLimit { highCount += 1 } else { inRangeCount += 1 diff --git a/LoopFollow/ViewControllers/MainViewController.swift b/LoopFollow/ViewControllers/MainViewController.swift index b4af72f72..71167539f 100644 --- a/LoopFollow/ViewControllers/MainViewController.swift +++ b/LoopFollow/ViewControllers/MainViewController.swift @@ -860,13 +860,10 @@ class MainViewController: UIViewController, UNUserNotificationCenterDelegate { if bgData.count > 0 { let latestBG = bgData[bgData.count - 1].sgv if Storage.shared.colorBGText.value { - let thresholds = UnitSettingsStore.shared.effectiveThresholds() - if Double(latestBG) >= thresholds.high { - Observable.shared.bgTextColor.value = .yellow - } else if Double(latestBG) <= thresholds.low { - Observable.shared.bgTextColor.value = .red - } else { - Observable.shared.bgTextColor.value = .green + switch UnitSettingsStore.shared.glucoseBand(for: Double(latestBG)) { + case .high: Observable.shared.bgTextColor.value = .yellow + case .low: Observable.shared.bgTextColor.value = .red + case .inRange: Observable.shared.bgTextColor.value = .green } } else { Observable.shared.bgTextColor.value = .primary diff --git a/LoopFollowLAExtension/LoopFollowLiveActivity.swift b/LoopFollowLAExtension/LoopFollowLiveActivity.swift index a9018ca94..90de47f42 100644 --- a/LoopFollowLAExtension/LoopFollowLiveActivity.swift +++ b/LoopFollowLAExtension/LoopFollowLiveActivity.swift @@ -809,36 +809,39 @@ private enum LAFormat { // MARK: - Threshold-driven colors private enum LAColors { + private static func band(for snapshot: GlucoseSnapshot, low: Double, high: Double) -> GlucoseBand { + GlucoseBand.of(snapshot.glucose, low: low, high: high, mmol: snapshot.unit == .mmol) + } + static func backgroundTint(for snapshot: GlucoseSnapshot) -> Color { let mgdl = snapshot.glucose let t = LAAppGroupSettings.thresholdsMgdl() let low = t.low let high = t.high - if mgdl <= low { + switch band(for: snapshot, low: low, high: high) { + case .low: let raw = 0.48 + (0.85 - 0.48) * ((low - mgdl) / max(low - GlucoseThresholds.veryLow, 1)) let opacity = min(max(raw, 0.48), 0.85) return Color(uiColor: UIColor.systemRed).opacity(opacity) - } else if mgdl >= high { + case .high: let raw = 0.44 + (0.85 - 0.44) * ((mgdl - high) / max(324.0 - high, 1)) let opacity = min(max(raw, 0.44), 0.85) return Color(uiColor: UIColor.systemOrange).opacity(opacity) - } else { + case .inRange: return Color(uiColor: UIColor.systemGreen).opacity(0.36) } } static func keyline(for snapshot: GlucoseSnapshot) -> Color { - let mgdl = snapshot.glucose let t = LAAppGroupSettings.thresholdsMgdl() - let low = t.low - let high = t.high - if mgdl <= low { + switch band(for: snapshot, low: t.low, high: t.high) { + case .low: return Color(uiColor: UIColor.systemRed) - } else if mgdl >= high { + case .high: return Color(uiColor: UIColor.systemOrange) - } else { + case .inRange: return Color(uiColor: UIColor.systemGreen) } } diff --git a/LoopFollowWatch/ChartPage.swift b/LoopFollowWatch/ChartPage.swift index d8f17d7f9..a1b8d04db 100644 --- a/LoopFollowWatch/ChartPage.swift +++ b/LoopFollowWatch/ChartPage.swift @@ -87,7 +87,7 @@ struct ChartScrubView: View { HStack(spacing: 3) { if let reading { Circle() - .fill(WatchFormat.bgColor(reading.v, lowMgdl: state.lowMgdl, highMgdl: state.highMgdl)) + .fill(WatchFormat.bgColor(reading.v, lowMgdl: state.lowMgdl, highMgdl: state.highMgdl, unit: state.snapshot?.unit ?? .mgdl)) .frame(width: 7, height: 7) Text(WatchFormat.glucose(reading.v, unit: state.snapshot?.unit ?? .mgdl)) } else { diff --git a/LoopFollowWatch/GlucosePage.swift b/LoopFollowWatch/GlucosePage.swift index d07086dd2..8303e1a51 100644 --- a/LoopFollowWatch/GlucosePage.swift +++ b/LoopFollowWatch/GlucosePage.swift @@ -47,7 +47,7 @@ struct GlucosePage: View { // The arrow hangs off the number's trailing edge so the digits, and the delta under them, stay centered. Text(WatchFormat.glucose(snapshot.glucose, unit: snapshot.unit)) .font(.system(size: 56, weight: .black)) - .foregroundStyle(WatchFormat.bgColor(snapshot.glucose, lowMgdl: state.lowMgdl, highMgdl: state.highMgdl, colored: state.colorBGText)) + .foregroundStyle(WatchFormat.bgColor(snapshot.glucose, lowMgdl: state.lowMgdl, highMgdl: state.highMgdl, unit: snapshot.unit, colored: state.colorBGText)) .strikethrough(isStale, pattern: .solid, color: .red) .lineLimit(1) .minimumScaleFactor(0.5) @@ -212,7 +212,7 @@ struct Sparkline: View { ForEach(readings, id: \.t) { reading in PointMark(x: .value("Time", reading.date), y: .value("BG", reading.v)) .symbolSize(12) - .foregroundStyle(WatchFormat.bgColor(reading.v, lowMgdl: state.lowMgdl, highMgdl: state.highMgdl)) + .foregroundStyle(WatchFormat.bgColor(reading.v, lowMgdl: state.lowMgdl, highMgdl: state.highMgdl, unit: state.snapshot?.unit ?? .mgdl)) } } .chartXScale(domain: start ... now) diff --git a/LoopFollowWatch/WatchChartView.swift b/LoopFollowWatch/WatchChartView.swift index 71cc3225f..5874af4e5 100644 --- a/LoopFollowWatch/WatchChartView.swift +++ b/LoopFollowWatch/WatchChartView.swift @@ -83,7 +83,7 @@ struct WatchChartView: View { y: .value("BG", min(reading.v, top)) ) .symbolSize(spanHours <= 3 ? 14 : 6) - .foregroundStyle(WatchFormat.bgColor(reading.v, lowMgdl: state.lowMgdl, highMgdl: state.highMgdl)) + .foregroundStyle(WatchFormat.bgColor(reading.v, lowMgdl: state.lowMgdl, highMgdl: state.highMgdl, unit: unit)) } ForEach(state.carbs.filter { window.contains($0.date) }, id: \.t) { carb in diff --git a/LoopFollowWatchWidgets/GlucoseComplicationView.swift b/LoopFollowWatchWidgets/GlucoseComplicationView.swift index 7e42e5f29..66fd621b0 100644 --- a/LoopFollowWatchWidgets/GlucoseComplicationView.swift +++ b/LoopFollowWatchWidgets/GlucoseComplicationView.swift @@ -24,7 +24,7 @@ struct GlucoseComplicationView: View { private var bgColor: Color { guard let state = entry.state, let snapshot else { return .secondary } if isStale { return .secondary } - return WatchFormat.bgColor(snapshot.glucose, lowMgdl: state.lowMgdl, highMgdl: state.highMgdl, colored: state.colorBGText) + return WatchFormat.bgColor(snapshot.glucose, lowMgdl: state.lowMgdl, highMgdl: state.highMgdl, unit: snapshot.unit, colored: state.colorBGText) } private var trendText: String { @@ -106,7 +106,7 @@ struct GlucoseComplicationView: View { ForEach(readings, id: \.t) { reading in PointMark(x: .value("Time", reading.date), y: .value("BG", min(max(reading.v, 40), 300))) .symbolSize(6) - .foregroundStyle(WatchFormat.bgColor(reading.v, lowMgdl: state.lowMgdl, highMgdl: state.highMgdl)) + .foregroundStyle(WatchFormat.bgColor(reading.v, lowMgdl: state.lowMgdl, highMgdl: state.highMgdl, unit: state.snapshot?.unit ?? .mgdl)) } } .chartXScale(domain: start ... entry.date) diff --git a/Shared/GlucoseConversion.swift b/Shared/GlucoseConversion.swift index dab205bfa..e31231e83 100644 --- a/Shared/GlucoseConversion.swift +++ b/Shared/GlucoseConversion.swift @@ -10,4 +10,38 @@ enum GlucoseConversion { static func toMmol(_ mgdl: Double) -> Double { mgdl * mgDlToMmolL } + + /// Converts mg/dL to mmol/L rounded to the one-decimal precision used for display. + static func toDisplayedMmol(_ mgdl: Double) -> Double { + (toMmol(mgdl) * 10).rounded() / 10 + } + + /// Rounds a mg/dL value to the precision it is shown at: whole mg/dL, or one-decimal mmol/L. + /// Lines picked in mmol/L are stored as fractional mg/dL, so both units need rounding. + static func toDisplayPrecision(_ mgdl: Double, mmol: Bool) -> Double { + mmol ? toDisplayedMmol(mgdl) : mgdl.rounded() + } +} + +/// Which side of the low/high lines a reading falls on. +enum GlucoseBand { + case low + case inRange + case high + + /// Classifies a mg/dL reading at the precision shown to the user, so the result + /// always matches the displayed number. A reading on a line is in range. + static func of(_ mgdl: Double, low: Double, high: Double, mmol: Bool) -> GlucoseBand { + let value = GlucoseConversion.toDisplayPrecision(mgdl, mmol: mmol) + let lowLimit = GlucoseConversion.toDisplayPrecision(low, mmol: mmol) + let highLimit = GlucoseConversion.toDisplayPrecision(high, mmol: mmol) + + if value < lowLimit { + return .low + } + if value > highLimit { + return .high + } + return .inRange + } } diff --git a/Tests/AlarmConditions/BGDisplayPrecisionTests.swift b/Tests/AlarmConditions/BGDisplayPrecisionTests.swift new file mode 100644 index 000000000..f0647e874 --- /dev/null +++ b/Tests/AlarmConditions/BGDisplayPrecisionTests.swift @@ -0,0 +1,111 @@ +// LoopFollow +// BGDisplayPrecisionTests.swift + +import Foundation +@testable import LoopFollow +import Testing + +/// In mmol/L, two mg/dL readings that display the same value must get the same +/// alarm result, and a threshold picked as X.X mmol/L must fire for a reading +/// that displays as X.X, regardless of which conversion factor stored it. +@Suite(.serialized) +struct BGDisplayPrecisionTests { + private func withMmol(_ body: () -> Void) { + let previous = Storage.shared.units.value + Storage.shared.units.value = GlucoseDisplayUnit.mmolL.rawValue + defer { Storage.shared.units.value = previous } + body() + } + + private func highAlarm(aboveBG: Double) -> Alarm { + var alarm = Alarm(type: .high) + alarm.aboveBG = aboveBG + return alarm + } + + private func fires(_ alarm: Alarm, sgv: Int) -> Bool { + let data = AlarmData.withReadings([sgv]) + if alarm.type == .high { + return HighBGCondition().evaluate(alarm: alarm, data: data, now: Date()) + } + return LowBGCondition().evaluate(alarm: alarm, data: data, now: Date()) + } + + @Test("high 10.0 mmol/L fires for both mg/dL readings that display 10.0") + func highBoundaryDisplaysAsLimit() { + withMmol { + // 10.0 mmol/L stored with the shared factor and with the old x18 picker factor. + for stored in [10.0 * GlucoseConversion.mmolToMgDl, 10.0 * 18] { + let alarm = highAlarm(aboveBG: stored) + #expect(!fires(alarm, sgv: 179)) + #expect(fires(alarm, sgv: 180)) + #expect(fires(alarm, sgv: 181)) + #expect(fires(alarm, sgv: 182)) + } + } + } + + @Test("high 7.8 mmol/L fires at 140, which displays 7.8, even when stored as 140.4") + func highLegacyPickerValue() { + withMmol { + let alarm = highAlarm(aboveBG: 7.8 * 18) + #expect(!fires(alarm, sgv: 139)) + #expect(fires(alarm, sgv: 140)) + #expect(fires(alarm, sgv: 141)) + } + } + + @Test("low 3.9 mmol/L fires for both mg/dL readings that display 3.9") + func lowBoundaryDisplaysAsLimit() { + withMmol { + for stored in [3.9 * GlucoseConversion.mmolToMgDl, 3.9 * 18] { + let alarm = Alarm.low(belowBG: stored) + #expect(fires(alarm, sgv: 69)) + #expect(fires(alarm, sgv: 70)) + #expect(fires(alarm, sgv: 71)) + #expect(!fires(alarm, sgv: 72)) + } + } + } + + @Test("mg/dL compares whole numbers") + func mgdlUnchanged() { + let previous = Storage.shared.units.value + Storage.shared.units.value = GlucoseDisplayUnit.mgdL.rawValue + defer { Storage.shared.units.value = previous } + + #expect(fires(highAlarm(aboveBG: 180), sgv: 180)) + #expect(!fires(highAlarm(aboveBG: 180), sgv: 179)) + #expect(fires(Alarm.low(belowBG: 70), sgv: 70)) + #expect(!fires(Alarm.low(belowBG: 70), sgv: 71)) + } + + @Test("mg/dL: a threshold picked in mmol/L fires at the whole number it displays") + func mgdlFractionalThreshold() { + let previous = Storage.shared.units.value + Storage.shared.units.value = GlucoseDisplayUnit.mgdL.rawValue + defer { Storage.shared.units.value = previous } + + // 3.9 mmol/L is stored as 70.2 or 70.26 and displays as 70 mg/dL. + for stored in [3.9 * 18, 3.9 * GlucoseConversion.mmolToMgDl] { + #expect(fires(Alarm.low(belowBG: stored), sgv: 70)) + #expect(!fires(Alarm.low(belowBG: stored), sgv: 71)) + } + // 10.0 mmol/L is stored as 180.16 and displays as 180 mg/dL. + let high = 10.0 * GlucoseConversion.mmolToMgDl + #expect(fires(highAlarm(aboveBG: high), sgv: 180)) + #expect(!fires(highAlarm(aboveBG: high), sgv: 179)) + } + + @Test("every mmol/L picker value round-trips to the value that was picked") + func pickerValuesRoundTrip() { + withMmol { + for tenths in 20 ... 400 { + let picked = Double(tenths) / 10 + let stored = picked * GlucoseConversion.mmolToMgDl + let normalized = UnitSettingsStore.shared.normalizeToDisplayPrecision(stored) + #expect(Int((normalized * 10).rounded()) == tenths) + } + } + } +} diff --git a/Tests/GlucoseBandTests.swift b/Tests/GlucoseBandTests.swift new file mode 100644 index 000000000..e48764440 --- /dev/null +++ b/Tests/GlucoseBandTests.swift @@ -0,0 +1,48 @@ +// LoopFollow +// GlucoseBandTests.swift + +@testable import LoopFollow +import Testing + +struct GlucoseBandTests { + @Test("mg/dL: a reading on a line is in range") + func mgdlBoundaries() { + #expect(GlucoseBand.of(69, low: 70, high: 180, mmol: false) == .low) + #expect(GlucoseBand.of(70, low: 70, high: 180, mmol: false) == .inRange) + #expect(GlucoseBand.of(71, low: 70, high: 180, mmol: false) == .inRange) + #expect(GlucoseBand.of(180, low: 70, high: 180, mmol: false) == .inRange) + #expect(GlucoseBand.of(181, low: 70, high: 180, mmol: false) == .high) + } + + @Test("mg/dL: a line picked in mmol/L is compared as the whole number it displays") + func mgdlFractionalLine() { + // 3.9 mmol/L is stored as 70.26 (shared factor) or 70.2 (old x18 factor) and shows as 70. + for low in [3.9 * GlucoseConversion.mmolToMgDl, 3.9 * 18] { + #expect(GlucoseBand.of(69, low: low, high: 180, mmol: false) == .low) + #expect(GlucoseBand.of(70, low: low, high: 180, mmol: false) == .inRange) + } + // 10.0 mmol/L is stored as 180.16 and shows as 180. + let high = 10.0 * GlucoseConversion.mmolToMgDl + #expect(GlucoseBand.of(180, low: 70, high: high, mmol: false) == .inRange) + #expect(GlucoseBand.of(181, low: 70, high: high, mmol: false) == .high) + } + + @Test("mmol/L: readings that display the same value get the same band") + func mmolSameDisplayedValue() { + // 70 and 71 mg/dL both display 3.9; 180 and 181 both display 10.0. + #expect(GlucoseBand.of(69, low: 70, high: 180, mmol: true) == .low) // 3.8 + #expect(GlucoseBand.of(70, low: 70, high: 180, mmol: true) == .inRange) + #expect(GlucoseBand.of(71, low: 70, high: 180, mmol: true) == .inRange) + #expect(GlucoseBand.of(180, low: 70, high: 180, mmol: true) == .inRange) + #expect(GlucoseBand.of(181, low: 70, high: 180, mmol: true) == .inRange) + #expect(GlucoseBand.of(182, low: 70, high: 180, mmol: true) == .high) // 10.1 + } + + @Test("mmol/L: a line stored with the old x18 picker factor behaves like the picked value") + func mmolLegacyPickerLine() { + // 3.9 mmol/L picked with x18 is 70.2 mg/dL; 10.0 mmol/L is 180.0. + #expect(GlucoseBand.of(69, low: 70.2, high: 180, mmol: true) == .low) + #expect(GlucoseBand.of(70, low: 70.2, high: 180, mmol: true) == .inRange) + #expect(GlucoseBand.of(71, low: 70.2, high: 180, mmol: true) == .inRange) + } +} diff --git a/Tests/StatsBoundaryTests.swift b/Tests/StatsBoundaryTests.swift new file mode 100644 index 000000000..ffb0dfd43 --- /dev/null +++ b/Tests/StatsBoundaryTests.swift @@ -0,0 +1,70 @@ +// LoopFollow +// StatsBoundaryTests.swift + +import Foundation +@testable import LoopFollow +import Testing + +/// TIR and GRI use inclusive bands (70-180 is in range), compared at the display +/// precision of the current unit. +@Suite(.serialized) +struct StatsBoundaryTests { + private func withUnit(_ unit: GlucoseDisplayUnit, _ body: () -> Void) { + let previous = Storage.shared.units.value + Storage.shared.units.value = unit.rawValue + defer { Storage.shared.units.value = previous } + body() + } + + private let readings: [Double] = [53, 54, 69, 70, 71, 180, 181, 182, 250, 251] + + private func tir() -> (veryLow: Double, low: Double, inRange: Double, high: Double, veryHigh: Double) { + TIRCalculator.calculatePercentages( + readings: readings, + veryLowThreshold: 54, + lowThreshold: 70, + highThreshold: 180, + veryHighThreshold: 250 + ) + } + + @Test("TIR mg/dL: 70 and 180 are in range, 54 and 250 are not extreme") + func tirMgdl() { + withUnit(.mgdL) { + let p = tir() + #expect(p.veryLow == 10) // 53 + #expect(p.low == 20) // 54, 69 + #expect(p.inRange == 30) // 70, 71, 180 + #expect(p.high == 30) // 181, 182, 250 + #expect(p.veryHigh == 10) // 251 + } + } + + @Test("TIR mmol/L: readings that display the same value share a band") + func tirMmol() { + withUnit(.mmolL) { + let p = tir() + #expect(p.veryLow == 10) // 53 -> 2.9 + #expect(p.low == 20) // 54 -> 3.0, 69 -> 3.8 + #expect(p.inRange == 40) // 70, 71 -> 3.9; 180, 181 -> 10.0 + #expect(p.high == 30) // 182 -> 10.1; 250, 251 -> 13.9 + #expect(p.veryHigh == 0) + } + } + + @Test("GRI: on-a-line readings are not counted as low or high; display precision applies") + func gri() { + let data = [71, 181].map { ShareGlucoseData(sgv: $0, date: 0, direction: nil) } + + withUnit(.mgdL) { + let result = GRICalculator.calculate(bgData: data) + #expect(result.hypoComponent == 0) + #expect(result.hyperComponent == 25) // 181 is above 180: 0.5 x 50% + } + withUnit(.mmolL) { + let result = GRICalculator.calculate(bgData: data) + #expect(result.hypoComponent == 0) + #expect(result.hyperComponent == 0) // 181 displays 10.0 + } + } +} diff --git a/Tests/WatchProtocolTests.swift b/Tests/WatchProtocolTests.swift index ebb5231b0..78e37e99f 100644 --- a/Tests/WatchProtocolTests.swift +++ b/Tests/WatchProtocolTests.swift @@ -94,11 +94,20 @@ struct WatchProtocolTests { #expect(!WatchFormat.delta(0.5, unit: .mmol).hasPrefix("+")) } - @Test("Range colors match the phone: red at or below low, yellow at or above high") + @Test("Range colors match the phone: a reading on a line is in range") func rangeColors() { - #expect(WatchFormat.bgColor(70, lowMgdl: 70, highMgdl: 180) == .red) - #expect(WatchFormat.bgColor(71, lowMgdl: 70, highMgdl: 180) == .green) - #expect(WatchFormat.bgColor(180, lowMgdl: 70, highMgdl: 180) == .yellow) - #expect(WatchFormat.bgColor(250, lowMgdl: 70, highMgdl: 180, colored: false) == .primary) + #expect(WatchFormat.bgColor(69, lowMgdl: 70, highMgdl: 180, unit: .mgdl) == .red) + #expect(WatchFormat.bgColor(70, lowMgdl: 70, highMgdl: 180, unit: .mgdl) == .green) + #expect(WatchFormat.bgColor(180, lowMgdl: 70, highMgdl: 180, unit: .mgdl) == .green) + #expect(WatchFormat.bgColor(181, lowMgdl: 70, highMgdl: 180, unit: .mgdl) == .yellow) + #expect(WatchFormat.bgColor(250, lowMgdl: 70, highMgdl: 180, unit: .mgdl, colored: false) == .primary) + } + + @Test("Range colors compare at the displayed mmol/L precision") + func rangeColorsMmol() { + // 181 mg/dL displays 10.0, the high line; 182 displays 10.1. + #expect(WatchFormat.bgColor(181, lowMgdl: 70, highMgdl: 180, unit: .mmol) == .green) + #expect(WatchFormat.bgColor(182, lowMgdl: 70, highMgdl: 180, unit: .mmol) == .yellow) + #expect(WatchFormat.bgColor(69, lowMgdl: 70, highMgdl: 180, unit: .mmol) == .red) } } diff --git a/WatchShared/WatchFormat.swift b/WatchShared/WatchFormat.swift index 24502d318..60241e5c7 100644 --- a/WatchShared/WatchFormat.swift +++ b/WatchShared/WatchFormat.swift @@ -93,12 +93,15 @@ enum WatchFormat { return "\(minutes) min" } - /// Phone semantics: yellow at or above high, red at or below low, green in - /// range. White when the phone's "Color BG Text" setting is off. - static func bgColor(_ mgdl: Double, lowMgdl: Double, highMgdl: Double, colored: Bool = true) -> Color { + /// Phone semantics: yellow above high, red below low, green in range, with a + /// reading on a line in range. Compared at the precision shown in `unit`, so the + /// color matches the displayed number. Primary when "Color BG Text" is off. + static func bgColor(_ mgdl: Double, lowMgdl: Double, highMgdl: Double, unit: GlucoseSnapshot.Unit, colored: Bool = true) -> Color { guard colored else { return .primary } - if mgdl >= highMgdl { return .yellow } - if mgdl <= lowMgdl { return .red } - return .green + switch GlucoseBand.of(mgdl, low: lowMgdl, high: highMgdl, mmol: unit == .mmol) { + case .high: return .yellow + case .low: return .red + case .inRange: return .green + } } }