MainChartView.swift 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  1. import Charts
  2. import SwiftUI
  3. let screenSize: CGRect = UIScreen.main.bounds
  4. let calendar = Calendar.current
  5. private struct BasalProfile: Hashable {
  6. let amount: Double
  7. var isOverwritten: Bool
  8. let startDate: Date
  9. let endDate: Date?
  10. init(amount: Double, isOverwritten: Bool, startDate: Date, endDate: Date? = nil) {
  11. self.amount = amount
  12. self.isOverwritten = isOverwritten
  13. self.startDate = startDate
  14. self.endDate = endDate
  15. }
  16. }
  17. private struct Prediction: Hashable {
  18. let amount: Int
  19. let timestamp: Date
  20. let type: PredictionType
  21. }
  22. private struct ChartTempTarget: Hashable {
  23. let amount: Decimal
  24. let start: Date
  25. let end: Date
  26. }
  27. private enum PredictionType: Hashable {
  28. case iob
  29. case cob
  30. case zt
  31. case uam
  32. }
  33. struct MainChartView: View {
  34. private enum Config {
  35. static let bolusSize: CGFloat = 5
  36. static let bolusScale: CGFloat = 1
  37. static let carbsSize: CGFloat = 5
  38. static let carbsScale: CGFloat = 0.3
  39. static let fpuSize: CGFloat = 10
  40. static let maxGlucose = 270
  41. static let minGlucose = 45
  42. }
  43. @Binding var units: GlucoseUnits
  44. @Binding var tempBasals: [PumpHistoryEvent]
  45. @Binding var boluses: [PumpHistoryEvent]
  46. @Binding var suspensions: [PumpHistoryEvent]
  47. @Binding var announcement: [Announcement]
  48. @Binding var hours: Int
  49. @Binding var maxBasal: Decimal
  50. @Binding var autotunedBasalProfile: [BasalProfileEntry]
  51. @Binding var basalProfile: [BasalProfileEntry]
  52. @Binding var tempTargets: [TempTarget]
  53. @Binding var smooth: Bool
  54. @Binding var highGlucose: Decimal
  55. @Binding var lowGlucose: Decimal
  56. @Binding var screenHours: Int16
  57. @Binding var displayXgridLines: Bool
  58. @Binding var displayYgridLines: Bool
  59. @Binding var thresholdLines: Bool
  60. @Binding var isTempTargetActive: Bool
  61. @StateObject var state = Home.StateModel()
  62. @State var didAppearTrigger = false
  63. @State private var BasalProfiles: [BasalProfile] = []
  64. @State private var TempBasals: [PumpHistoryEvent] = []
  65. @State private var ChartTempTargets: [ChartTempTarget] = []
  66. @State private var Predictions: [Prediction] = []
  67. @State private var count: Decimal = 1
  68. @State private var startMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 - 86400))
  69. @State private var endMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 + 10800))
  70. @State private var minValue: Decimal = 45
  71. @State private var maxValue: Decimal = 270
  72. @State private var selection: Date? = nil
  73. private let now = Date.now
  74. @Environment(\.colorScheme) var colorScheme
  75. @Environment(\.calendar) var calendar
  76. // MARK: - Core Data Fetch Requests
  77. @FetchRequest(
  78. fetchRequest: CarbEntryStored.fetch(NSPredicate.carbsForChart),
  79. animation: Animation.bouncy
  80. ) var carbsFromPersistence: FetchedResults<CarbEntryStored>
  81. @FetchRequest(
  82. fetchRequest: CarbEntryStored.fetch(NSPredicate.fpusForChart),
  83. animation: Animation.bouncy
  84. ) var fpusFromPersistence: FetchedResults<CarbEntryStored>
  85. @FetchRequest(
  86. fetchRequest: PumpEventStored.fetch(NSPredicate.pumpHistoryLast24h, ascending: true),
  87. animation: Animation.bouncy
  88. ) var insulinFromPersistence: FetchedResults<PumpEventStored>
  89. @FetchRequest(
  90. fetchRequest: GlucoseStored.fetch(NSPredicate.glucose, ascending: true),
  91. animation: Animation.bouncy
  92. ) var glucoseFromPersistence: FetchedResults<GlucoseStored>
  93. @FetchRequest(
  94. fetchRequest: GlucoseStored.fetch(NSPredicate.manualGlucose, ascending: true),
  95. animation: Animation.bouncy
  96. ) var manualGlucoseFromPersistence: FetchedResults<GlucoseStored>
  97. @FetchRequest(
  98. fetchRequest: OrefDetermination.fetch(NSPredicate.enactedDetermination),
  99. animation: Animation.bouncy
  100. ) var determinations: FetchedResults<OrefDetermination>
  101. @FetchRequest(
  102. fetchRequest: Forecast.fetch(NSPredicate.predicateFor30MinAgo, ascending: false),
  103. animation: .default
  104. ) var forecasts: FetchedResults<Forecast>
  105. private var bolusFormatter: NumberFormatter {
  106. let formatter = NumberFormatter()
  107. formatter.numberStyle = .decimal
  108. formatter.minimumIntegerDigits = 0
  109. formatter.maximumFractionDigits = 2
  110. formatter.decimalSeparator = "."
  111. return formatter
  112. }
  113. private var carbsFormatter: NumberFormatter {
  114. let formatter = NumberFormatter()
  115. formatter.numberStyle = .decimal
  116. formatter.maximumFractionDigits = 0
  117. return formatter
  118. }
  119. private var conversionFactor: Decimal {
  120. units == .mmolL ? 0.0555 : 1
  121. }
  122. private var upperLimit: Decimal {
  123. units == .mgdL ? 400 : 22.2
  124. }
  125. private var defaultBolusPosition: Int {
  126. units == .mgdL ? 120 : 7
  127. }
  128. private var bolusOffset: Decimal {
  129. units == .mgdL ? 30 : 1.66
  130. }
  131. private var selectedGlucose: GlucoseStored? {
  132. if let selection = selection {
  133. let lowerBound = selection.addingTimeInterval(-120)
  134. let upperBound = selection.addingTimeInterval(120)
  135. return glucoseFromPersistence.first { $0.date ?? now >= lowerBound && $0.date ?? now <= upperBound }
  136. } else {
  137. return nil
  138. }
  139. }
  140. var body: some View {
  141. VStack {
  142. ScrollViewReader { scroller in
  143. ScrollView(.horizontal, showsIndicators: false) {
  144. LazyVStack(spacing: 0) {
  145. mainChart
  146. basalChart
  147. }.onChange(of: screenHours) { _ in
  148. updateStartEndMarkers()
  149. yAxisChartData()
  150. scroller.scrollTo("MainChart", anchor: .trailing)
  151. }.onChange(of: glucoseFromPersistence.map(\.id)) { _ in
  152. updateStartEndMarkers()
  153. yAxisChartData()
  154. scroller.scrollTo("MainChart", anchor: .trailing)
  155. }
  156. .onChange(of: determinations.map(\.id)) { _ in
  157. updateStartEndMarkers()
  158. scroller.scrollTo("MainChart", anchor: .trailing)
  159. }
  160. .onChange(of: tempBasals) { _ in
  161. updateStartEndMarkers()
  162. scroller.scrollTo("MainChart", anchor: .trailing)
  163. }
  164. .onChange(of: units) { _ in
  165. yAxisChartData()
  166. }
  167. .onAppear {
  168. updateStartEndMarkers()
  169. scroller.scrollTo("MainChart", anchor: .trailing)
  170. }
  171. }
  172. }
  173. legendPanel.padding(.top, 8)
  174. }
  175. }
  176. }
  177. // MARK: - Components
  178. struct Backport<Content: View> {
  179. let content: Content
  180. }
  181. extension View {
  182. var backport: Backport<Self> { Backport(content: self) }
  183. }
  184. extension Backport {
  185. @ViewBuilder func chartXSelection(value: Binding<Date?>) -> some View {
  186. if #available(iOS 17, *) {
  187. content.chartXSelection(value: value)
  188. } else {
  189. content
  190. }
  191. }
  192. }
  193. extension MainChartView {
  194. private var mainChart: some View {
  195. VStack {
  196. Chart {
  197. drawStartRuleMark()
  198. drawEndRuleMark()
  199. drawCurrentTimeMarker()
  200. drawCarbs()
  201. drawFpus()
  202. drawBoluses()
  203. drawTempTargets()
  204. drawForecasts()
  205. drawGlucose()
  206. drawManualGlucose()
  207. /// high and low threshold lines
  208. if thresholdLines {
  209. RuleMark(y: .value("High", highGlucose * conversionFactor)).foregroundStyle(Color.loopYellow)
  210. .lineStyle(.init(lineWidth: 1, dash: [5]))
  211. RuleMark(y: .value("Low", lowGlucose * conversionFactor)).foregroundStyle(Color.loopRed)
  212. .lineStyle(.init(lineWidth: 1, dash: [5]))
  213. }
  214. /// show glucose value when hovering over it
  215. if let selectedGlucose {
  216. RuleMark(x: .value("Selection", selectedGlucose.date ?? now, unit: .minute))
  217. .foregroundStyle(Color.tabBar)
  218. .offset(yStart: 70)
  219. .lineStyle(.init(lineWidth: 2, dash: [5]))
  220. .annotation(position: .top) {
  221. selectionPopover
  222. }
  223. }
  224. }
  225. .id("MainChart")
  226. .onChange(of: boluses) { _ in
  227. state.roundedTotalBolus = state.calculateTINS()
  228. }
  229. .onChange(of: tempTargets) { _ in
  230. calculateTTs()
  231. }
  232. .onChange(of: didAppearTrigger) { _ in
  233. calculateTTs()
  234. }
  235. .frame(minHeight: UIScreen.main.bounds.height * 0.3)
  236. .frame(width: fullWidth(viewWidth: screenSize.width))
  237. .chartXScale(domain: startMarker ... endMarker)
  238. .chartXAxis { mainChartXAxis }
  239. .backport.chartXSelection(value: $selection)
  240. .chartYAxis { mainChartYAxis }
  241. .chartYScale(domain: minValue ... maxValue)
  242. .chartForegroundStyleScale([
  243. "zt": Color.zt,
  244. "uam": Color.uam,
  245. "cob": .orange,
  246. "iob": .blue
  247. ])
  248. .chartLegend(.hidden)
  249. }
  250. }
  251. @ViewBuilder var selectionPopover: some View {
  252. if let sgv = selectedGlucose?.glucose {
  253. let glucoseToShow = Decimal(sgv) * conversionFactor
  254. VStack {
  255. Text(selectedGlucose?.date?.formatted(.dateTime.hour().minute(.twoDigits)) ?? "")
  256. HStack {
  257. Text(glucoseToShow.formatted(.number.precision(units == .mmolL ? .fractionLength(1) : .fractionLength(0))))
  258. .fontWeight(.bold)
  259. .foregroundStyle(
  260. Decimal(sgv) < lowGlucose ? Color
  261. .red : (Decimal(sgv) > highGlucose ? Color.orange : Color.primary)
  262. )
  263. Text(units.rawValue).foregroundColor(.secondary)
  264. }
  265. }
  266. .padding(6)
  267. .background {
  268. RoundedRectangle(cornerRadius: 4)
  269. .fill(Color.gray.opacity(0.1))
  270. .shadow(color: .blue, radius: 2)
  271. }
  272. }
  273. }
  274. private var basalChart: some View {
  275. VStack {
  276. Chart {
  277. drawStartRuleMark()
  278. drawEndRuleMark()
  279. drawCurrentTimeMarker()
  280. drawTempBasals()
  281. drawBasalProfile()
  282. drawSuspensions()
  283. }.onChange(of: tempBasals) { _ in
  284. calculateBasals()
  285. calculateTempBasals()
  286. }
  287. .onChange(of: maxBasal) { _ in
  288. calculateBasals()
  289. calculateTempBasals()
  290. }
  291. .onChange(of: autotunedBasalProfile) { _ in
  292. calculateBasals()
  293. calculateTempBasals()
  294. }
  295. .onChange(of: didAppearTrigger) { _ in
  296. calculateBasals()
  297. calculateTempBasals()
  298. }.onChange(of: basalProfile) { _ in
  299. calculateTempBasals()
  300. }
  301. .frame(maxHeight: UIScreen.main.bounds.height * 0.08)
  302. .frame(width: fullWidth(viewWidth: screenSize.width))
  303. .chartXScale(domain: startMarker ... endMarker)
  304. .chartXAxis { basalChartXAxis }
  305. .chartYAxis { basalChartYAxis }
  306. }
  307. }
  308. var legendPanel: some View {
  309. HStack(spacing: 10) {
  310. Spacer()
  311. LegendItem(color: .loopGreen, label: "BG")
  312. LegendItem(color: .insulin, label: "IOB")
  313. LegendItem(color: .zt, label: "ZT")
  314. LegendItem(color: .loopYellow, label: "COB")
  315. LegendItem(color: .uam, label: "UAM")
  316. Spacer()
  317. }
  318. .padding(.horizontal, 10)
  319. .frame(maxWidth: .infinity)
  320. }
  321. }
  322. // MARK: - Calculations
  323. extension MainChartView {
  324. private func drawBoluses() -> some ChartContent {
  325. /// smbs in triangle form
  326. ForEach(insulinFromPersistence) { insulin in
  327. let amount = insulin.bolus?.amount ?? 0 as NSDecimalNumber
  328. let bolusDate = insulin.timestamp ?? Date()
  329. let glucose = timeToNearestGlucose(time: bolusDate.timeIntervalSince1970)
  330. let yPosition = (Decimal(glucose.glucose) * conversionFactor) + bolusOffset
  331. let size = (Config.bolusSize + CGFloat(truncating: amount) * Config.bolusScale) * 1.8
  332. // don't display triangles if it is no smb
  333. if amount != 0 {
  334. PointMark(
  335. x: .value("Time", bolusDate, unit: .second),
  336. y: .value("Value", yPosition)
  337. )
  338. .symbol {
  339. Image(systemName: "arrowtriangle.down.fill").font(.system(size: size)).foregroundStyle(Color.insulin)
  340. }
  341. .annotation(position: .top) {
  342. Text(bolusFormatter.string(from: amount) ?? "")
  343. .font(.caption2)
  344. .foregroundStyle(Color.insulin)
  345. }
  346. }
  347. }
  348. }
  349. private func drawCarbs() -> some ChartContent {
  350. /// carbs
  351. ForEach(carbsFromPersistence) { carb in
  352. let carbAmount = carb.carbs
  353. let yPosition = units == .mgdL ? 60 : 3.33
  354. PointMark(
  355. x: .value("Time", carb.date ?? Date(), unit: .second),
  356. y: .value("Value", yPosition)
  357. )
  358. .symbolSize((Config.carbsSize + CGFloat(carbAmount) * Config.carbsScale) * 10)
  359. .foregroundStyle(Color.orange)
  360. .annotation(position: .bottom) {
  361. Text(carbsFormatter.string(from: carbAmount as NSNumber)!).font(.caption2)
  362. .foregroundStyle(Color.orange)
  363. }
  364. }
  365. }
  366. private func drawFpus() -> some ChartContent {
  367. /// fpus
  368. ForEach(fpusFromPersistence) { fpu in
  369. let fpuAmount = fpu.carbs
  370. let size = (Config.fpuSize + CGFloat(fpuAmount) * Config.carbsScale) * 1.8
  371. let yPosition = units == .mgdL ? 60 : 3.33
  372. PointMark(
  373. x: .value("Time", fpu.date ?? Date(), unit: .second),
  374. y: .value("Value", yPosition)
  375. )
  376. .symbolSize(size)
  377. .foregroundStyle(Color.brown)
  378. }
  379. }
  380. private func drawGlucose() -> some ChartContent {
  381. /// glucose point mark
  382. /// filtering for high and low bounds in settings
  383. ForEach(glucoseFromPersistence) { item in
  384. if smooth {
  385. if item.glucose > Int(highGlucose) {
  386. PointMark(
  387. x: .value("Time", item.date ?? Date(), unit: .second),
  388. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  389. ).foregroundStyle(Color.orange.gradient).symbolSize(25).interpolationMethod(.cardinal)
  390. } else if item.glucose < Int(lowGlucose) {
  391. PointMark(
  392. x: .value("Time", item.date ?? Date(), unit: .second),
  393. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  394. ).foregroundStyle(Color.red.gradient).symbolSize(25).interpolationMethod(.cardinal)
  395. } else {
  396. PointMark(
  397. x: .value("Time", item.date ?? Date(), unit: .second),
  398. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  399. ).foregroundStyle(Color.green.gradient).symbolSize(25).interpolationMethod(.cardinal)
  400. }
  401. } else {
  402. if item.glucose > Int(highGlucose) {
  403. PointMark(
  404. x: .value("Time", item.date ?? Date(), unit: .second),
  405. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  406. ).foregroundStyle(Color.orange.gradient).symbolSize(25)
  407. } else if item.glucose < Int(lowGlucose) {
  408. PointMark(
  409. x: .value("Time", item.date ?? Date(), unit: .second),
  410. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  411. ).foregroundStyle(Color.red.gradient).symbolSize(25)
  412. } else {
  413. PointMark(
  414. x: .value("Time", item.date ?? Date(), unit: .second),
  415. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  416. ).foregroundStyle(Color.green.gradient).symbolSize(25)
  417. }
  418. }
  419. }
  420. }
  421. private func timeForIndex(_ index: Int32) -> Date {
  422. let currentTime = Date()
  423. let timeInterval = TimeInterval(index * 300)
  424. return currentTime.addingTimeInterval(timeInterval)
  425. }
  426. private func getForecasts(_ determination: OrefDetermination) -> [Forecast] {
  427. guard let forecastSet = determination.forecasts, let forecasts = Array(forecastSet) as? [Forecast] else {
  428. return []
  429. }
  430. return forecasts
  431. }
  432. private func getForecastValues(_ forecast: Forecast) -> [ForecastValue] {
  433. guard let forecastValueSet = forecast.forecastValues,
  434. let forecastValues = Array(forecastValueSet) as? [ForecastValue]
  435. else {
  436. return []
  437. }
  438. return forecastValues.sorted(by: { $0.index < $1.index })
  439. }
  440. private func drawForecasts() -> some ChartContent {
  441. /// for every determination in determinations get the forecasts
  442. ForEach(determinations.flatMap { determination -> [(id: UUID, forecast: Forecast, forecastValue: ForecastValue)] in
  443. let forecasts = getForecasts(determination) /// returns array of Forecast objects
  444. /// now get the values for every forecast and add it to a tuple, identify it with an ID
  445. return forecasts.flatMap { forecast in
  446. getForecastValues(forecast).map { forecastValue in
  447. (id: UUID(), forecast: forecast, forecastValue: forecastValue)
  448. }
  449. }
  450. }, id: \.id) { tuple in
  451. LineMark(
  452. x: .value("Time", timeForIndex(tuple.forecastValue.index)),
  453. y: .value("Value", Int(tuple.forecastValue.value))
  454. )
  455. .foregroundStyle(by: .value("Predictions", tuple.forecast.type ?? ""))
  456. }
  457. }
  458. private func drawCurrentTimeMarker() -> some ChartContent {
  459. RuleMark(
  460. x: .value(
  461. "",
  462. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  463. unit: .second
  464. )
  465. ).lineStyle(.init(lineWidth: 2, dash: [3])).foregroundStyle(Color(.systemGray2))
  466. }
  467. private func drawStartRuleMark() -> some ChartContent {
  468. RuleMark(
  469. x: .value(
  470. "",
  471. startMarker,
  472. unit: .second
  473. )
  474. ).foregroundStyle(Color.clear)
  475. }
  476. private func drawEndRuleMark() -> some ChartContent {
  477. RuleMark(
  478. x: .value(
  479. "",
  480. endMarker,
  481. unit: .second
  482. )
  483. ).foregroundStyle(Color.clear)
  484. }
  485. private func drawTempTargets() -> some ChartContent {
  486. /// temp targets
  487. ForEach(ChartTempTargets, id: \.self) { target in
  488. let targetLimited = min(max(target.amount, 0), upperLimit)
  489. RuleMark(
  490. xStart: .value("Start", target.start),
  491. xEnd: .value("End", target.end),
  492. y: .value("Value", targetLimited)
  493. )
  494. .foregroundStyle(Color.purple.opacity(0.5)).lineStyle(.init(lineWidth: 8))
  495. }
  496. }
  497. private func drawManualGlucose() -> some ChartContent {
  498. /// manual glucose mark
  499. ForEach(manualGlucoseFromPersistence) { item in
  500. let manualGlucose = item.glucose
  501. PointMark(
  502. x: .value("Time", item.date ?? Date(), unit: .second),
  503. y: .value("Value", Decimal(manualGlucose) * conversionFactor)
  504. )
  505. .symbol {
  506. Image(systemName: "drop.fill").font(.system(size: 10)).symbolRenderingMode(.monochrome)
  507. .foregroundStyle(.red)
  508. }
  509. }
  510. }
  511. private func drawSuspensions() -> some ChartContent {
  512. /// pump suspensions
  513. ForEach(suspensions) { suspension in
  514. let now = Date()
  515. if suspension.type == EventType.pumpSuspend {
  516. let suspensionStart = suspension.timestamp
  517. let suspensionEnd = min(
  518. suspensions
  519. .first(where: { $0.timestamp > suspension.timestamp && $0.type == EventType.pumpResume })?
  520. .timestamp ?? now,
  521. now
  522. )
  523. let basalProfileDuringSuspension = BasalProfiles.first(where: { $0.startDate <= suspensionStart })
  524. let suspensionMarkHeight = basalProfileDuringSuspension?.amount ?? 1
  525. RectangleMark(
  526. xStart: .value("start", suspensionStart),
  527. xEnd: .value("end", suspensionEnd),
  528. yStart: .value("suspend-start", 0),
  529. yEnd: .value("suspend-end", suspensionMarkHeight)
  530. )
  531. .foregroundStyle(Color.loopGray.opacity(colorScheme == .dark ? 0.3 : 0.8))
  532. }
  533. }
  534. }
  535. private func prepareTempBasals() -> [(start: Date, end: Date, rate: Double)] {
  536. let now = Date()
  537. return insulinFromPersistence.compactMap { temp -> (start: Date, end: Date, rate: Double)? in
  538. let duration = temp.tempBasal?.duration ?? 0
  539. let timestamp = temp.timestamp ?? Date()
  540. let end = min(timestamp + duration.minutes, now)
  541. let isInsulinSuspended = suspensions.contains { $0.timestamp >= timestamp && $0.timestamp <= end }
  542. let rate = Double(truncating: temp.tempBasal?.rate ?? Decimal.zero as NSDecimalNumber) * (isInsulinSuspended ? 0 : 1)
  543. // Check if there's a subsequent temp basal to determine the end time
  544. guard let nextTemp = insulinFromPersistence.first(where: { $0.timestamp ?? .distantPast > timestamp }) else {
  545. return (timestamp, end, rate)
  546. }
  547. return (timestamp, nextTemp.timestamp ?? Date(), rate) // end defaults to current time
  548. }
  549. }
  550. private func drawTempBasals() -> some ChartContent {
  551. ForEach(prepareTempBasals(), id: \.rate) { basal in
  552. RectangleMark(
  553. xStart: .value("start", basal.start),
  554. xEnd: .value("end", basal.end),
  555. yStart: .value("rate-start", 0),
  556. yEnd: .value("rate-end", basal.rate)
  557. ).foregroundStyle(Color.insulin.opacity(0.2))
  558. LineMark(x: .value("Start Date", basal.start), y: .value("Amount", basal.rate))
  559. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  560. LineMark(x: .value("End Date", basal.end), y: .value("Amount", basal.rate))
  561. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  562. }
  563. }
  564. private func drawBasalProfile() -> some ChartContent {
  565. /// dashed profile line
  566. ForEach(BasalProfiles, id: \.self) { profile in
  567. LineMark(
  568. x: .value("Start Date", profile.startDate),
  569. y: .value("Amount", profile.amount),
  570. series: .value("profile", "profile")
  571. ).lineStyle(.init(lineWidth: 2, dash: [2, 4])).foregroundStyle(Color.insulin)
  572. LineMark(
  573. x: .value("End Date", profile.endDate ?? endMarker),
  574. y: .value("Amount", profile.amount),
  575. series: .value("profile", "profile")
  576. ).lineStyle(.init(lineWidth: 2.5, dash: [2, 4])).foregroundStyle(Color.insulin)
  577. }
  578. }
  579. /// calculates the glucose value thats the nearest to parameter 'time'
  580. /// if time is later than all the arrays values return the last element of BloodGlucose
  581. private func timeToNearestGlucose(time: TimeInterval) -> GlucoseStored {
  582. guard !glucoseFromPersistence.isEmpty else {
  583. return GlucoseStored()
  584. }
  585. var low = 0
  586. var high = glucoseFromPersistence.count - 1
  587. while low < high {
  588. let mid = low + (high - low) / 2
  589. let midTime = glucoseFromPersistence[mid].date?.timeIntervalSince1970 ?? 0
  590. if midTime == time {
  591. return glucoseFromPersistence[mid]
  592. } else if midTime < time {
  593. low = mid + 1
  594. } else {
  595. high = mid
  596. }
  597. }
  598. if high == glucoseFromPersistence.count - 1 || glucoseFromPersistence[high].date?.timeIntervalSince1970 ?? 0 > time {
  599. return glucoseFromPersistence[max(high - 1, 0)]
  600. }
  601. return glucoseFromPersistence[high]
  602. }
  603. private func fullWidth(viewWidth: CGFloat) -> CGFloat {
  604. viewWidth * CGFloat(hours) / CGFloat(min(max(screenHours, 2), 24))
  605. }
  606. /// calculations for temp target bar mark
  607. private func calculateTTs() {
  608. var groupedPackages: [[TempTarget]] = []
  609. var currentPackage: [TempTarget] = []
  610. var calculatedTTs: [ChartTempTarget] = []
  611. for target in tempTargets {
  612. if target.duration > 0 {
  613. if !currentPackage.isEmpty {
  614. groupedPackages.append(currentPackage)
  615. currentPackage = []
  616. }
  617. currentPackage.append(target)
  618. } else {
  619. if let lastNonZeroTempTarget = currentPackage.last(where: { $0.duration > 0 }) {
  620. if target.createdAt >= lastNonZeroTempTarget.createdAt,
  621. target.createdAt <= lastNonZeroTempTarget.createdAt
  622. .addingTimeInterval(TimeInterval(lastNonZeroTempTarget.duration * 60))
  623. {
  624. currentPackage.append(target)
  625. }
  626. }
  627. }
  628. }
  629. // appends last package, if exists
  630. if !currentPackage.isEmpty {
  631. groupedPackages.append(currentPackage)
  632. }
  633. for package in groupedPackages {
  634. guard let firstNonZeroTarget = package.first(where: { $0.duration > 0 }) else {
  635. continue
  636. }
  637. var end = firstNonZeroTarget.createdAt.addingTimeInterval(TimeInterval(firstNonZeroTarget.duration * 60))
  638. let earliestCancelTarget = package.filter({ $0.duration == 0 }).min(by: { $0.createdAt < $1.createdAt })
  639. if let earliestCancelTarget = earliestCancelTarget {
  640. end = min(earliestCancelTarget.createdAt, end)
  641. }
  642. let now = Date()
  643. isTempTargetActive = firstNonZeroTarget.createdAt <= now && now <= end
  644. if firstNonZeroTarget.targetTop != nil {
  645. calculatedTTs
  646. .append(ChartTempTarget(
  647. amount: (firstNonZeroTarget.targetTop ?? 0) * conversionFactor,
  648. start: firstNonZeroTarget.createdAt,
  649. end: end
  650. ))
  651. }
  652. }
  653. ChartTempTargets = calculatedTTs
  654. }
  655. private func calculateTempBasals() {
  656. let basals = tempBasals
  657. var returnTempBasalRates: [PumpHistoryEvent] = []
  658. var finished: [Int: Bool] = [:]
  659. basals.indices.forEach { i in
  660. basals.indices.forEach { j in
  661. if basals[i].timestamp == basals[j].timestamp, i != j, !(finished[i] ?? false), !(finished[j] ?? false) {
  662. let rate = basals[i].rate ?? basals[j].rate
  663. let durationMin = basals[i].durationMin ?? basals[j].durationMin
  664. finished[i] = true
  665. if rate != 0 || durationMin != 0 {
  666. returnTempBasalRates.append(
  667. PumpHistoryEvent(
  668. id: basals[i].id, type: FreeAPS.EventType.tempBasal,
  669. timestamp: basals[i].timestamp,
  670. durationMin: durationMin,
  671. rate: rate
  672. )
  673. )
  674. }
  675. }
  676. }
  677. }
  678. TempBasals = returnTempBasalRates
  679. }
  680. private func findRegularBasalPoints(
  681. timeBegin: TimeInterval,
  682. timeEnd: TimeInterval,
  683. autotuned: Bool
  684. ) -> [BasalProfile] {
  685. guard timeBegin < timeEnd else {
  686. return []
  687. }
  688. let beginDate = Date(timeIntervalSince1970: timeBegin)
  689. let calendar = Calendar.current
  690. let startOfDay = calendar.startOfDay(for: beginDate)
  691. let profile = autotuned ? autotunedBasalProfile : basalProfile
  692. let basalNormalized = profile.map {
  693. (
  694. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  695. rate: $0.rate
  696. )
  697. } + profile.map {
  698. (
  699. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval)
  700. .timeIntervalSince1970,
  701. rate: $0.rate
  702. )
  703. } + profile.map {
  704. (
  705. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 2.days.timeInterval)
  706. .timeIntervalSince1970,
  707. rate: $0.rate
  708. )
  709. }
  710. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  711. .compactMap { window -> BasalProfile? in
  712. let window = Array(window)
  713. if window[0].time < timeBegin, window[1].time < timeBegin {
  714. return nil
  715. }
  716. if window[0].time < timeBegin, window[1].time >= timeBegin {
  717. let startDate = Date(timeIntervalSince1970: timeBegin)
  718. let rate = window[0].rate
  719. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  720. }
  721. if window[0].time >= timeBegin, window[0].time < timeEnd {
  722. let startDate = Date(timeIntervalSince1970: window[0].time)
  723. let rate = window[0].rate
  724. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  725. }
  726. return nil
  727. }
  728. return basalTruncatedPoints
  729. }
  730. /// update start and end marker to fix scroll update problem with x axis
  731. private func updateStartEndMarkers() {
  732. startMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 - 86400))
  733. endMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 + 10800))
  734. }
  735. private func calculateBasals() {
  736. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  737. let regularPoints = findRegularBasalPoints(
  738. timeBegin: dayAgoTime,
  739. timeEnd: endMarker.timeIntervalSince1970,
  740. autotuned: false
  741. )
  742. let autotunedBasalPoints = findRegularBasalPoints(
  743. timeBegin: dayAgoTime,
  744. timeEnd: endMarker.timeIntervalSince1970,
  745. autotuned: true
  746. )
  747. var totalBasal = regularPoints + autotunedBasalPoints
  748. totalBasal.sort {
  749. $0.startDate.timeIntervalSince1970 < $1.startDate.timeIntervalSince1970
  750. }
  751. var basals: [BasalProfile] = []
  752. totalBasal.indices.forEach { index in
  753. basals.append(BasalProfile(
  754. amount: totalBasal[index].amount,
  755. isOverwritten: totalBasal[index].isOverwritten,
  756. startDate: totalBasal[index].startDate,
  757. endDate: totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker
  758. ))
  759. // print(
  760. // "Basal",
  761. // totalBasal[index].startDate,
  762. // totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker,
  763. // totalBasal[index].amount,
  764. // totalBasal[index].isOverwritten
  765. // )
  766. }
  767. BasalProfiles = basals
  768. }
  769. // MARK: - Chart formatting
  770. private func yAxisChartData() {
  771. let glucoseMapped = glucoseFromPersistence.map(\.glucose)
  772. guard let minGlucose = glucoseMapped.min(), let maxGlucose = glucoseMapped.max() else {
  773. // default values
  774. minValue = 45 * conversionFactor - 20 * conversionFactor
  775. maxValue = 270 * conversionFactor + 50 * conversionFactor
  776. return
  777. }
  778. minValue = Decimal(minGlucose) * conversionFactor - 20 * conversionFactor
  779. maxValue = Decimal(maxGlucose) * conversionFactor + 50 * conversionFactor
  780. debug(.default, "min \(minValue)")
  781. debug(.default, "max \(maxValue)")
  782. }
  783. private func basalChartPlotStyle(_ plotContent: ChartPlotContent) -> some View {
  784. plotContent
  785. .rotationEffect(.degrees(180))
  786. .scaleEffect(x: -1, y: 1)
  787. .chartXAxis(.hidden)
  788. }
  789. private var mainChartXAxis: some AxisContent {
  790. AxisMarks(values: .stride(by: .hour, count: screenHours == 24 ? 4 : 2)) { _ in
  791. if displayXgridLines {
  792. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  793. } else {
  794. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  795. }
  796. }
  797. }
  798. private var basalChartXAxis: some AxisContent {
  799. AxisMarks(values: .stride(by: .hour, count: screenHours == 24 ? 4 : 2)) { _ in
  800. if displayXgridLines {
  801. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  802. } else {
  803. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  804. }
  805. AxisValueLabel(format: .dateTime.hour(.defaultDigits(amPM: .narrow)), anchor: .top)
  806. .font(.footnote)
  807. }
  808. }
  809. private var mainChartYAxis: some AxisContent {
  810. AxisMarks(position: .trailing) { value in
  811. if displayXgridLines {
  812. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  813. } else {
  814. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  815. }
  816. if let glucoseValue = value.as(Double.self), glucoseValue > 0 {
  817. /// fix offset between the two charts...
  818. if units == .mmolL {
  819. AxisTick(length: 7, stroke: .init(lineWidth: 7)).foregroundStyle(Color.clear)
  820. }
  821. AxisValueLabel().font(.footnote)
  822. }
  823. }
  824. }
  825. private var basalChartYAxis: some AxisContent {
  826. AxisMarks(position: .trailing) { _ in
  827. AxisTick(length: units == .mmolL ? 25 : 27, stroke: .init(lineWidth: 4))
  828. .foregroundStyle(Color.clear).font(.footnote)
  829. }
  830. }
  831. }
  832. struct LegendItem: View {
  833. var color: Color
  834. var label: String
  835. var body: some View {
  836. Group {
  837. Circle().fill(color).frame(width: 8, height: 8)
  838. Text(label)
  839. .font(.system(size: 10, weight: .bold))
  840. .foregroundColor(color)
  841. }
  842. }
  843. }
  844. extension Int16 {
  845. var minutes: TimeInterval {
  846. TimeInterval(self) * 60
  847. }
  848. }