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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 4 additions & 6 deletions LoopFollow/Charts/BGChartModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}

Expand Down
15 changes: 5 additions & 10 deletions LoopFollow/Contact/ContactColorMode.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
}
Expand Down
12 changes: 4 additions & 8 deletions LoopFollow/Controllers/Stats.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions LoopFollow/Helpers/Localizer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 4 additions & 7 deletions LoopFollow/InfoTable/RetroSnapshot.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
13 changes: 13 additions & 0 deletions LoopFollow/LiveActivity/LiveActivityManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
#if !targetEnvironment(macCatalyst)

@preconcurrency import ActivityKit
import Combine
import Foundation
import os
import UIKit
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -459,6 +471,7 @@ final class LiveActivityManager {
/// and arrives within a few seconds of the first request.
private static let pushToStartTokenRetryDelay: TimeInterval = 10

private var cancellables = Set<AnyCancellable>()
private(set) var current: Activity<GlucoseLiveActivityAttributes>?
/// The `logReason` of the bind that made `current` the tracked activity.
private var currentBindReason = ""
Expand Down
17 changes: 12 additions & 5 deletions LoopFollow/Stats/GRI/GRICalculator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
Expand Down
18 changes: 13 additions & 5 deletions LoopFollow/Stats/TIR/TIRCalculator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 4 additions & 7 deletions LoopFollow/ViewControllers/MainViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -940,13 +940,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
Expand Down
21 changes: 12 additions & 9 deletions LoopFollowLAExtension/LoopFollowLiveActivity.swift
Original file line number Diff line number Diff line change
Expand Up @@ -829,36 +829,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)
}
}
Expand Down
2 changes: 1 addition & 1 deletion LoopFollowWatch/ChartPage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
4 changes: 2 additions & 2 deletions LoopFollowWatch/GlucosePage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion LoopFollowWatch/WatchChartView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions LoopFollowWatchWidgets/GlucoseComplicationView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
Expand Down
34 changes: 34 additions & 0 deletions Shared/GlucoseConversion.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
Loading