Skip to content

Commit

Permalink
Include basal in TINS
Browse files Browse the repository at this point in the history
thamks to @Marvout
  • Loading branch information
mountrcg committed May 18, 2024
2 parents 11abad8 + 785e2af commit 6638bca
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 18 deletions.
2 changes: 1 addition & 1 deletion Config.xcconfig
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
APP_DISPLAY_NAME = iAPS
APP_VERSION = 3.6.1
APP_VERSION = 3.6.2
APP_BUILD_NUMBER = 1
COPYRIGHT_NOTICE = autoISF 3.0
DEVELOPER_TEAM = ##TEAM_ID##
Expand Down
64 changes: 56 additions & 8 deletions FreeAPS/Sources/Modules/Home/HomeStateModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,14 @@ extension Home {
@Published var overrides: [Override] = []
@Published var alwaysUseColors: Bool = true
@Published var timeSettings: Bool = true
@Published var calculatedTins: String = ""

private var numberFormatter: NumberFormatter {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
return formatter
}

let coredataContext = CoreDataStack.shared.persistentContainer.viewContext

Expand Down Expand Up @@ -335,21 +343,61 @@ extension Home {
let date = Date()
let calendar = Calendar.current
let offset = hours

var offsetComponents = DateComponents()
// offsetComponents.hour = -offset.rawValue
offsetComponents.hour = -Int(offset)

let startTime = calendar.date(byAdding: offsetComponents, to: date)!
// print("******************")
// print("TINS calc start time: \(startTime)")

let bolusesForCurrentDay = boluses.filter { $0.timestamp >= startTime && $0.type == .bolus }
guard let basalInsulinForCurrentDay = getDeliveredBasal() else { return "" }

/// add all boluses for specified time together
let totalBoluses = bolusesForCurrentDay.map { $0.amount ?? 0 }.reduce(0, +)
/// final TINS value, i.e. boluses AND delivered basal
let total = totalBoluses + basalInsulinForCurrentDay
debug(.default, "TINS Bolus \(startTime): \(numberFormatter.string(from: totalBoluses as NSNumber) ?? "NaN")")
debug(.default, "TINS Basal: \(numberFormatter.string(from: basalInsulinForCurrentDay as NSNumber) ?? "NaN")")

let totalBolus = bolusesForCurrentDay.map { $0.amount ?? 0 }.reduce(0, +)
let roundedTotalBolus = Decimal(round(100 * Double(totalBolus)) / 100)
calculatedTins = numberFormatter.string(from: total as NSNumber) ?? "NaN"

return calculatedTins
}

private func getDeliveredBasal() -> Decimal? {
let date = Date()
let calendar = Calendar.current
let offset = hours
var offsetComponents = DateComponents()
offsetComponents.hour = -Int(offset)
let startTime = calendar.date(byAdding: offsetComponents, to: date)!

/// retrieve basal entries in defined time
let basalEntriesForCurrentDay = tempBasals.filter { $0.timestamp >= startTime && $0.type == .tempBasal }

/// sort basal entries in order to prepare for the duration calculation
let basalEntriesForCurrentDaySorted = basalEntriesForCurrentDay.sorted { $0.timestamp < $1.timestamp }
/// empty array to append basal entries
var basalDurations: [Double] = []
/// calculate every basal entries duration
for (index, basalEntry) in basalEntriesForCurrentDaySorted.enumerated() {
/// proof if a next entry exists
if index + 1 < basalEntriesForCurrentDaySorted.count {
let nextEntry = basalEntriesForCurrentDaySorted[index + 1]
/// calculate difference of timestamps, result is in seconds
let durationInSeconds = nextEntry.timestamp.timeIntervalSince(basalEntry.timestamp)
let durationInHours = durationInSeconds / 3600 /// conversion to hours
basalDurations.append(durationInHours)
}
}
/// calculate how much insulin was given, i.e. rate * duration for every entry
let basalInsulinForCurrentDay = zip(basalEntriesForCurrentDaySorted, basalDurations).map { basalEntry, duration in
if let rate = basalEntry.rate {
return rate * Decimal(duration)
} else {
return 0
}
}.reduce(0, +)

return "\(roundedTotalBolus)"
return basalInsulinForCurrentDay > 0 ? basalInsulinForCurrentDay : nil
}

private func setupSuspensions() {
Expand Down
28 changes: 19 additions & 9 deletions FreeAPS/Sources/Modules/Home/View/HomeRootView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@ extension Home {
}

@State var timeButtons: [Buttons] = [
Buttons(label: "2h", number: "2", active: false, hours: 2),
Buttons(label: "4h", number: "4", active: false, hours: 4),
Buttons(label: "3h", number: "3", active: false, hours: 3),
Buttons(label: "6h", number: "6", active: false, hours: 6),
Buttons(label: "12h", number: "12", active: false, hours: 12),
Buttons(label: "24h", number: "24", active: false, hours: 24)
Buttons(label: "24h", number: "24", active: false, hours: 24),
Buttons(label: "36h", number: "36", active: false, hours: 36)
]

let buttonFont = Font.custom("TimeButtonFont", size: 14)
Expand Down Expand Up @@ -315,12 +315,22 @@ extension Home {
.padding(.leading, 8)
}
if state.tins {
Text(
"TINS: \(state.calculateTINS())" +
NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
)
.font(.system(size: 12, weight: .bold))
.foregroundColor(.insulin)
HStack {
Text(
"TINS: \(state.calculatedTins)" +
NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
)
.font(.system(size: 12, weight: .bold))
.foregroundColor(.insulin)
.onChange(of: state.hours) { _ in
state.calculatedTins = state.calculateTINS()
}
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
state.calculatedTins = state.calculateTINS()
}
}
}
}

if let tempTargetString = tempTargetString {
Expand Down

1 comment on commit 6638bca

@Marvout
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there, I was mentioned in this commit, but I actually dont know why :D Could you explain what I might have helped ;D
Greetings Marvin

Please sign in to comment.