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
12 changes: 10 additions & 2 deletions LoopFollow.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@
656F8C102E49F36F0008DC1D /* QRCodeDisplayView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 656F8C0F2E49F36F0008DC1D /* QRCodeDisplayView.swift */; };
656F8C122E49F3780008DC1D /* QRCodeGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 656F8C112E49F3780008DC1D /* QRCodeGenerator.swift */; };
656F8C142E49F3D20008DC1D /* RemoteCommandSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = 656F8C132E49F3D20008DC1D /* RemoteCommandSettings.swift */; };
65E153C32E4BB69100693A4F /* URLTokenValidationView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 65E153C22E4BB69100693A4F /* URLTokenValidationView.swift */; };
6584B1012E4A263900135D4D /* TOTPService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6584B1002E4A263900135D4D /* TOTPService.swift */; };
65E153C32E4BB69100693A4F /* URLTokenValidationView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 65E153C22E4BB69100693A4F /* URLTokenValidationView.swift */; };
65E8A2862E44B0300065037B /* VolumeButtonHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 65E8A2852E44B0300065037B /* VolumeButtonHandler.swift */; };
DD0247592DB2E89600FCADF6 /* AlarmCondition.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD0247582DB2E89600FCADF6 /* AlarmCondition.swift */; };
DD0247712DB4337700FCADF6 /* BuildExpireCondition.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD02475B2DB2E8FB00FCADF6 /* BuildExpireCondition.swift */; };
Expand Down Expand Up @@ -408,8 +408,8 @@
656F8C0F2E49F36F0008DC1D /* QRCodeDisplayView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QRCodeDisplayView.swift; sourceTree = "<group>"; };
656F8C112E49F3780008DC1D /* QRCodeGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QRCodeGenerator.swift; sourceTree = "<group>"; };
656F8C132E49F3D20008DC1D /* RemoteCommandSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RemoteCommandSettings.swift; sourceTree = "<group>"; };
65E153C22E4BB69100693A4F /* URLTokenValidationView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = URLTokenValidationView.swift; sourceTree = "<group>"; };
6584B1002E4A263900135D4D /* TOTPService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TOTPService.swift; sourceTree = "<group>"; };
65E153C22E4BB69100693A4F /* URLTokenValidationView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = URLTokenValidationView.swift; sourceTree = "<group>"; };
65E8A2852E44B0300065037B /* VolumeButtonHandler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VolumeButtonHandler.swift; sourceTree = "<group>"; };
A7D55B42A22051DAD69E89D0 /* Pods_LoopFollow.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_LoopFollow.framework; sourceTree = BUILT_PRODUCTS_DIR; };
DD0247582DB2E89600FCADF6 /* AlarmCondition.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AlarmCondition.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -788,6 +788,8 @@
/* End PBXFileReference section */

/* Begin PBXFileSystemSynchronizedRootGroup section */
65AC25F52ECFD5E800421360 /* Stats */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = Stats; sourceTree = "<group>"; };
65AC26702ED245DF00421360 /* Treatments */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = Treatments; sourceTree = "<group>"; };
DDCC3AD72DDE1790006F1C10 /* Tests */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = Tests; sourceTree = "<group>"; };
/* End PBXFileSystemSynchronizedRootGroup section */

Expand Down Expand Up @@ -1438,6 +1440,8 @@
FC8DEEE32485D1680075863F /* LoopFollow */ = {
isa = PBXGroup;
children = (
65AC26702ED245DF00421360 /* Treatments */,
65AC25F52ECFD5E800421360 /* Stats */,
DDCF9A7E2D85FCE6004DF4DD /* Alarm */,
FC16A97624995FEE003D6245 /* Application */,
DDFF3D792D140F1800BF9D9E /* BackgroundRefresh */,
Expand Down Expand Up @@ -1592,6 +1596,10 @@
);
dependencies = (
);
fileSystemSynchronizedGroups = (
65AC25F52ECFD5E800421360 /* Stats */,
65AC26702ED245DF00421360 /* Treatments */,
);
name = LoopFollow;
packageProductDependencies = (
DD48781B2C7DAF140048F05C /* SwiftJWT */,
Expand Down
14 changes: 7 additions & 7 deletions LoopFollow/Controllers/MainViewController+updateStats.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,16 @@ extension MainViewController {

let stats = StatsData(bgData: lastDayOfData)

statsLowPercent.text = String(format: "%.1f%", stats.percentLow) + "%"
statsInRangePercent.text = String(format: "%.1f%", stats.percentRange) + "%"
statsHighPercent.text = String(format: "%.1f%", stats.percentHigh) + "%"
statsAvgBG.text = Localizer.toDisplayUnits(String(format: "%.0f%", stats.avgBG))
statsLowPercent.text = String(format: "%.1f%%", stats.percentLow)
statsInRangePercent.text = String(format: "%.1f%%", stats.percentRange)
statsHighPercent.text = String(format: "%.1f%%", stats.percentHigh)
statsAvgBG.text = Localizer.toDisplayUnits(String(format: "%.0f", stats.avgBG))
if Storage.shared.useIFCC.value {
statsEstA1C.text = String(format: "%.0f%", stats.a1C)
statsEstA1C.text = String(format: "%.0f", stats.a1C)
} else {
statsEstA1C.text = String(format: "%.1f%", stats.a1C)
statsEstA1C.text = String(format: "%.1f%%", stats.a1C)
}
statsStdDev.text = String(format: "%.2f%", stats.stdDev)
statsStdDev.text = String(format: "%.2f", stats.stdDev)

createStatsPie(pieData: stats.pie)
}
Expand Down
4 changes: 3 additions & 1 deletion LoopFollow/Controllers/Nightscout/Treatments.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@ extension MainViewController {
if !Storage.shared.downloadTreatments.value { return }

let startTimeString = dateTimeUtils.getDateTimeString(addingDays: -1 * Storage.shared.downloadDays.value)
let currentTimeString = dateTimeUtils.getDateTimeString(addingHours: 6)
let currentTimeString = dateTimeUtils.getDateTimeString()
let estimatedCount = max(Storage.shared.downloadDays.value * 100, 5000)
let parameters: [String: String] = [
"find[created_at][$gte]": startTimeString,
"find[created_at][$lte]": currentTimeString,
"count": "\(estimatedCount)",
]
NightscoutUtils.executeDynamicRequest(eventType: .treatments, parameters: parameters) { (result: Result<Any, Error>) in
switch result {
Expand Down
55 changes: 55 additions & 0 deletions LoopFollow/Settings/SettingsMenuView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,7 @@ private enum Sheet: Hashable, Identifiable {
case calendar, contact
case advanced
case viewLog
case aggregatedStats

var id: Self { self }

Expand All @@ -301,10 +302,64 @@ private enum Sheet: Hashable, Identifiable {
case .contact: ContactSettingsView(viewModel: .init())
case .advanced: AdvancedSettingsView(viewModel: .init())
case .viewLog: LogView(viewModel: .init())
case .aggregatedStats:
AggregatedStatsViewWrapper()
}
}
}

// Helper view to access MainViewController
struct AggregatedStatsViewWrapper: View {
@State private var mainViewController: MainViewController?

var body: some View {
Group {
if let mainVC = mainViewController {
AggregatedStatsView(viewModel: AggregatedStatsViewModel(mainViewController: mainVC))
} else {
Text("Loading stats...")
.onAppear {
mainViewController = getMainViewController()
}
}
}
}

private func getMainViewController() -> MainViewController? {
guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
let window = windowScene.windows.first,
let rootVC = window.rootViewController
else {
return nil
}

if let mainVC = rootVC as? MainViewController {
return mainVC
}

if let navVC = rootVC as? UINavigationController,
let mainVC = navVC.viewControllers.first as? MainViewController
{
return mainVC
}

if let tabVC = rootVC as? UITabBarController {
for vc in tabVC.viewControllers ?? [] {
if let mainVC = vc as? MainViewController {
return mainVC
}
if let navVC = vc as? UINavigationController,
let mainVC = navVC.viewControllers.first as? MainViewController
{
return mainVC
}
}
}

return nil
}
}

// MARK: – UIKit helpers (unchanged)

import UIKit
Expand Down
70 changes: 70 additions & 0 deletions LoopFollow/Stats/AGP/AGPCalculator.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// LoopFollow
// AGPCalculator.swift

import Foundation

class AGPCalculator {
static func calculate(bgData: [ShareGlucoseData]) -> [AGPDataPoint] {
guard !bgData.isEmpty else { return [] }

var hourData: [Int: [Double]] = [:]
let calendar = Calendar.current

for reading in bgData {
let date = Date(timeIntervalSince1970: reading.date)
let components = calendar.dateComponents([.hour], from: date)
let hour = components.hour ?? 0

let glucose = Double(reading.sgv)
let glucoseMgdL = Storage.shared.units.value == "mg/dL" ? glucose : glucose * GlucoseConversion.mmolToMgDl

if hourData[hour] == nil {
hourData[hour] = []
}
hourData[hour]?.append(glucoseMgdL)
}

var agpPoints: [AGPDataPoint] = []
for hour in 0 ..< 24 {
guard let values = hourData[hour], !values.isEmpty else { continue }

let sorted = values.sorted()
let p5 = PercentileCalculator.percentile(sorted, p: 0.05)
let p25 = PercentileCalculator.percentile(sorted, p: 0.25)
let p50 = PercentileCalculator.percentile(sorted, p: 0.50)
let p75 = PercentileCalculator.percentile(sorted, p: 0.75)
let p95 = PercentileCalculator.percentile(sorted, p: 0.95)

let convert: (Double) -> Double = { value in
Storage.shared.units.value == "mg/dL" ? value : value * GlucoseConversion.mgDlToMmolL
}

let minutesSinceMidnight = hour * 60

agpPoints.append(AGPDataPoint(
timeOfDay: minutesSinceMidnight,
p5: convert(p5),
p25: convert(p25),
p50: convert(p50),
p75: convert(p75),
p95: convert(p95)
))
}

return agpPoints.sorted { $0.timeOfDay < $1.timeOfDay }
}
}

class PercentileCalculator {
static func percentile(_ sorted: [Double], p: Double) -> Double {
guard !sorted.isEmpty else { return 0.0 }
if sorted.count == 1 { return sorted[0] }

let index = p * Double(sorted.count - 1)
let lower = Int(index.rounded(.down))
let upper = min(lower + 1, sorted.count - 1)
let weight = index - Double(lower)

return sorted[lower] * (1.0 - weight) + sorted[upper] * weight
}
}
13 changes: 13 additions & 0 deletions LoopFollow/Stats/AGP/AGPDataPoint.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// LoopFollow
// AGPDataPoint.swift

import Foundation

struct AGPDataPoint {
let timeOfDay: Int
let p5: Double
let p25: Double
let p50: Double
let p75: Double
let p95: Double
}
144 changes: 144 additions & 0 deletions LoopFollow/Stats/AGP/AGPGraphView.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
// LoopFollow
// AGPGraphView.swift

import Charts
import SwiftUI

struct AGPGraphView: UIViewRepresentable {
let agpData: [AGPDataPoint]

func makeCoordinator() -> Coordinator {
Coordinator()
}

func makeUIView(context _: Context) -> UIView {
let containerView = NonInteractiveContainerView()
containerView.backgroundColor = .systemBackground

let chartView = LineChartView()
chartView.rightAxis.enabled = true
chartView.leftAxis.enabled = false
chartView.xAxis.labelPosition = .bottom
chartView.rightAxis.drawGridLinesEnabled = false
chartView.leftAxis.drawGridLinesEnabled = false
chartView.xAxis.drawGridLinesEnabled = false
chartView.rightAxis.valueFormatter = ChartYMMOLValueFormatter()
chartView.legend.enabled = false
chartView.chartDescription.enabled = false
chartView.isUserInteractionEnabled = false

containerView.addSubview(chartView)
chartView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
chartView.topAnchor.constraint(equalTo: containerView.topAnchor),
chartView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
chartView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),
chartView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor),
])

return containerView
}

class Coordinator {}

func updateUIView(_ containerView: UIView, context _: Context) {
guard let chartView = containerView.subviews.first as? LineChartView else { return }
guard !agpData.isEmpty else { return }
var p5Entries: [ChartDataEntry] = []
var p25Entries: [ChartDataEntry] = []
var p50Entries: [ChartDataEntry] = []
var p75Entries: [ChartDataEntry] = []
var p95Entries: [ChartDataEntry] = []

for point in agpData {
let x = Double(point.timeOfDay) / 60.0
p5Entries.append(ChartDataEntry(x: x, y: point.p5))
p25Entries.append(ChartDataEntry(x: x, y: point.p25))
p50Entries.append(ChartDataEntry(x: x, y: point.p50))
p75Entries.append(ChartDataEntry(x: x, y: point.p75))
p95Entries.append(ChartDataEntry(x: x, y: point.p95))
}

let sortedP5 = p5Entries.sorted { $0.x < $1.x }
let sortedP25 = p25Entries.sorted { $0.x < $1.x }
let sortedP50 = p50Entries.sorted { $0.x < $1.x }
let sortedP75 = p75Entries.sorted { $0.x < $1.x }
let sortedP95 = p95Entries.sorted { $0.x < $1.x }

guard !sortedP5.isEmpty, !sortedP25.isEmpty, !sortedP50.isEmpty,
!sortedP75.isEmpty, !sortedP95.isEmpty
else {
return
}
let p5DataSet = LineChartDataSet(entries: sortedP5, label: "5th")
p5DataSet.colors = [NSUIColor.systemGray.withAlphaComponent(0.6)]
p5DataSet.lineWidth = 1.5
p5DataSet.drawCirclesEnabled = false
p5DataSet.drawValuesEnabled = false
p5DataSet.drawFilledEnabled = false
p5DataSet.mode = .linear

let p25DataSet = LineChartDataSet(entries: sortedP25, label: "25th")
p25DataSet.colors = [NSUIColor.systemBlue.withAlphaComponent(0.7)]
p25DataSet.lineWidth = 1.5
p25DataSet.drawCirclesEnabled = false
p25DataSet.drawValuesEnabled = false
p25DataSet.drawFilledEnabled = false
p25DataSet.mode = .linear

let p50DataSet = LineChartDataSet(entries: sortedP50, label: "Median")
p50DataSet.colors = [NSUIColor.systemBlue]
p50DataSet.lineWidth = 3
p50DataSet.drawCirclesEnabled = false
p50DataSet.drawValuesEnabled = false
p50DataSet.drawFilledEnabled = false
p50DataSet.mode = .linear

let p75DataSet = LineChartDataSet(entries: sortedP75, label: "75th")
p75DataSet.colors = [NSUIColor.systemBlue.withAlphaComponent(0.7)]
p75DataSet.lineWidth = 1.5
p75DataSet.drawCirclesEnabled = false
p75DataSet.drawValuesEnabled = false
p75DataSet.drawFilledEnabled = false
p75DataSet.mode = .linear

let p95DataSet = LineChartDataSet(entries: sortedP95, label: "95th")
p95DataSet.colors = [NSUIColor.systemGray.withAlphaComponent(0.6)]
p95DataSet.lineWidth = 1.5
p95DataSet.drawCirclesEnabled = false
p95DataSet.drawValuesEnabled = false
p95DataSet.drawFilledEnabled = false
p95DataSet.mode = .linear
let maxY = max(sortedP95.map { $0.y }.max() ?? 300, 300) + 10
let hourMinY = min(sortedP5.map { $0.y }.min() ?? 0, 0) - 10

var hourLines: [ChartDataEntry] = []
for hour in 0 ... 24 {
let x = Double(hour)
hourLines.append(ChartDataEntry(x: x, y: hourMinY))
hourLines.append(ChartDataEntry(x: x, y: maxY))
if hour < 24 {
hourLines.append(ChartDataEntry(x: x + 0.0001, y: hourMinY))
}
}

let hourLinesDataSet = LineChartDataSet(entries: hourLines, label: "Hours")
hourLinesDataSet.colors = [NSUIColor.label.withAlphaComponent(0.3)]
hourLinesDataSet.lineWidth = 1
hourLinesDataSet.drawCirclesEnabled = false
hourLinesDataSet.drawValuesEnabled = false
hourLinesDataSet.drawFilledEnabled = false

let data = LineChartData()
data.append(p5DataSet)
data.append(p25DataSet)
data.append(p50DataSet)
data.append(p75DataSet)
data.append(p95DataSet)
data.append(hourLinesDataSet)

chartView.data = data
chartView.notifyDataSetChanged()
chartView.setNeedsDisplay()
}
}
Loading