Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More loop statistics. #896

Merged
merged 5 commits into from
Oct 10, 2024
Merged
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
5 changes: 3 additions & 2 deletions Core_Data.xcdatamodeld/Core_Data.xcdatamodel/contents
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<model type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="22758" systemVersion="23G93" minimumToolsVersion="Automatic" sourceLanguage="Swift" userDefinedModelVersionIdentifier="">
<model type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="23231" systemVersion="23G93" minimumToolsVersion="Automatic" sourceLanguage="Swift" userDefinedModelVersionIdentifier="">
<entity name="ActiveProfile" representedClassName="ActiveProfile" syncable="YES" codeGenerationType="class">
<attribute name="active" optional="YES" attributeType="Boolean" usesScalarValueType="YES"/>
<attribute name="date" optional="YES" attributeType="Date" usesScalarValueType="NO"/>
Expand Down Expand Up @@ -57,6 +57,7 @@
<entity name="LoopStatRecord" representedClassName="LoopStatRecord" syncable="YES" codeGenerationType="class">
<attribute name="duration" optional="YES" attributeType="Double" defaultValueString="0.0" usesScalarValueType="YES"/>
<attribute name="end" optional="YES" attributeType="Date" usesScalarValueType="NO"/>
<attribute name="error" optional="YES" attributeType="String"/>
<attribute name="interval" optional="YES" attributeType="Double" defaultValueString="0.0" usesScalarValueType="YES"/>
<attribute name="loopStatus" optional="YES" attributeType="String"/>
<attribute name="start" optional="YES" attributeType="Date" usesScalarValueType="NO"/>
Expand Down Expand Up @@ -199,4 +200,4 @@
<attribute name="dev" optional="YES" attributeType="String"/>
<attribute name="nr" optional="YES" attributeType="String"/>
</entity>
</model>
</model>
8 changes: 6 additions & 2 deletions FreeAPS/Sources/APS/APSManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,7 @@ final class BaseAPSManager: APSManager, Injectable {
lastError.send(nil)
}

loopStats(loopStatRecord: loopStatRecord)
loopStats(loopStatRecord: loopStatRecord, error: error)

if settings.closedLoop {
reportEnacted(received: error == nil)
Expand Down Expand Up @@ -1304,7 +1304,7 @@ final class BaseAPSManager: APSManager, Injectable {
return branch
}

private func loopStats(loopStatRecord: LoopStats) {
private func loopStats(loopStatRecord: LoopStats, error: Error?) {
coredataContext.perform {
let nLS = LoopStatRecord(context: self.coredataContext)

Expand All @@ -1314,6 +1314,10 @@ final class BaseAPSManager: APSManager, Injectable {
nLS.duration = loopStatRecord.duration ?? 0.0
nLS.interval = loopStatRecord.interval ?? 0.0

if let error = error {
nLS.error = error.localizedDescription.string
}

try? self.coredataContext.save()
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1880,6 +1880,15 @@ Enact a temp Basal or a temp target */
/* Loop Errors in statPanel */
"Errors" = "Errors";

/* Loop Statistics pop-up description */
"Success = Started / Completed (loops)" = "Success = Started / Completed (loops)";

/* Loop Statistics pop-up */
"Most Frequent Error" = "Most Frequent Error";

/* Loop Statistics pop-up */
"Non-completed Loops" = "Non-completed Loops";

/* Average loop interval */
"Interval" = "Interval";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1877,6 +1877,15 @@ Enact a temp Basal or a temp target */
/* Loop Errors in statPanel */
"Errors" = "Fel";

/* Loop Statistics pop-up description */
"Success = Started / Completed (loops)" = "Lyckades = Påbörjade / Avslutade (loopar)";

/* Loop Statistics pop-up */
"Most Frequent Error" = "Vanligaste fel";

/* Loop Statistics pop-up */
"Non-completed Loops" = "ej avslutade loopar";

/* Average loop interval */
"Interval" = "Intervall";

Expand Down
37 changes: 37 additions & 0 deletions FreeAPS/Sources/Modules/Home/View/HomeRootView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ extension Home {
@State var triggerUpdate = false
@State var display = false
@State var displayGlucose = false
@State var animateLoop = Date.distantPast
@State var animateTIR = Date.distantPast

let buttonFont = Font.custom("TimeButtonFont", size: 14)
let viewPadding: CGFloat = 5

Expand Down Expand Up @@ -478,9 +481,16 @@ extension Home {
.clipShape(RoundedRectangle(cornerRadius: 15))
.addShadows()
.padding(.horizontal, 10)
.blur(radius: animateTIRView ? 2 : 0)
.onTapGesture {
timeIsNowTIR()
state.showModal(for: .statistics)
}
.overlay {
if animateTIRView {
animation.asAny()
}
}
}

var infoPanelView: some View {
Expand Down Expand Up @@ -536,9 +546,16 @@ extension Home {
.clipShape(RoundedRectangle(cornerRadius: 15))
.addShadows()
.padding(.horizontal, 10)
.blur(radius: animateLoopView ? 2.5 : 0)
.onTapGesture {
timeIsNowLoop()
state.showModal(for: .statistics)
}
.overlay {
if animateLoopView {
animation.asAny()
}
}
}

var profileView: some View {
Expand Down Expand Up @@ -702,6 +719,26 @@ extension Home {
.background(TimeEllipse(characters: string.count))
}

private var animateLoopView: Bool {
-1 * animateLoop.timeIntervalSinceNow < 1.5
}

private var animateTIRView: Bool {
-1 * animateTIR.timeIntervalSinceNow < 1.5
}

private func timeIsNowLoop() {
animateLoop = Date.now
}

private func timeIsNowTIR() {
animateTIR = Date.now
}

private var animation: any View {
ActivityIndicator(isAnimating: .constant(true), style: .large)
}

var body: some View {
GeometryReader { geo in
VStack(spacing: 0) {
Expand Down
2 changes: 1 addition & 1 deletion FreeAPS/Sources/Modules/Stat/View/StatRootView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ extension Stat {
.pickerStyle(.segmented).background(.cyan.opacity(0.2))
stats()
}
.dynamicTypeSize(...DynamicTypeSize.xxLarge)
.dynamicTypeSize(...DynamicTypeSize.xLarge)
.onAppear(perform: configureView)
.navigationBarTitle("Statistics")
.navigationBarTitleDisplayMode(.inline)
Expand Down
72 changes: 70 additions & 2 deletions FreeAPS/Sources/Modules/Stat/View/StatsView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ struct StatsView: View {
@FetchRequest var fetchRequestReadings: FetchedResults<Readings>

@State var headline: Color = .secondary
@State var errorReasons: Bool = false

@Binding var highLimit: Decimal
@Binding var lowLimit: Decimal
Expand Down Expand Up @@ -83,11 +84,26 @@ struct StatsView: View {
)
}
VStack(spacing: 5) {
Text("Success").font(.subheadline).foregroundColor(headline)
let succesPercentage = successRate ?? 100
HStack {
Text("Success").foregroundColor(headline)
if succesPercentage != 100 {
Image(systemName: "info.circle").foregroundStyle(.blue)
}
}.font(.subheadline)
Text(
((successRate ?? 100) / 100)
(succesPercentage / 100)
.formatted(.percent.grouping(.never).rounded().precision(.fractionLength(1)))
)
}.onTapGesture {
errorReasons.toggle()
}
}
.overlay {
VStack {
if errorReasons {
errors(loopCount - successsNR)
}
}
}
}
Expand Down Expand Up @@ -119,6 +135,49 @@ struct StatsView: View {
return sorted[length / 2]
}

private func errors(_ nonCompleted: Int) -> some View {
ZStack {
if nonCompleted > 0 {
let errors = fetchRequest.compactMap(\.error)
if errors.isNotEmpty {
let mostFrequent = errors.mostFrequent()?.description ?? ""
let mostFrequentCount = errors.filter({ $0 == mostFrequent }).count
RoundedRectangle(cornerRadius: 6)
.fill(Color(.systemGray2))
.frame(width: 380, height: 200)
.shadow(radius: 5)
.overlay {
ZStack {
Text("Success = Started / Completed (loops)")
.padding(.horizontal, 5)
.padding(.top, 20)
.foregroundStyle(.secondary)
.frame(maxHeight: .infinity, alignment: .top)
VStack {
Text(
NSLocalizedString("Most Frequent Error", comment: "Loop Statistics pop-up") +
" (\(mostFrequentCount) " +
NSLocalizedString("of", comment: "") +
" \(nonCompleted)):"
)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.vertical, 3)
.bold()
Text(mostFrequent)
.frame(maxWidth: .infinity, alignment: .leading)
}
.frame(maxHeight: .infinity, alignment: .bottom)
.padding(.horizontal, 20)
.padding(.bottom, 20)
}
}
}
}
}
.offset(y: -160)
.onTapGesture { errorReasons.toggle() }
}

var hba1c: some View {
HStack(spacing: 50) {
let useUnit: GlucoseUnits = (units == .mmolL && overrideUnit) ? .mgdL :
Expand Down Expand Up @@ -276,3 +335,12 @@ struct StatsView: View {
return array
}
}

extension Collection {
/**
Returns the most frequent element in the collection.
*/
func mostFrequent() -> Element? where Element: Hashable {
reduce(into: [:]) { $0[$1, default: 0] += 1 }.max(by: { $0.1 < $1.1 })?.key
}
}