MainChartView.swift 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986
  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 glucose: [BloodGlucose]
  44. @Binding var manualGlucose: [BloodGlucose]
  45. @Binding var fpusForChart: [CarbsEntry]
  46. @Binding var units: GlucoseUnits
  47. @Binding var eventualBG: Int?
  48. @Binding var suggestion: Suggestion?
  49. @Binding var tempBasals: [PumpHistoryEvent]
  50. @Binding var boluses: [PumpHistoryEvent]
  51. @Binding var suspensions: [PumpHistoryEvent]
  52. @Binding var announcement: [Announcement]
  53. @Binding var hours: Int
  54. @Binding var maxBasal: Decimal
  55. @Binding var autotunedBasalProfile: [BasalProfileEntry]
  56. @Binding var basalProfile: [BasalProfileEntry]
  57. @Binding var tempTargets: [TempTarget]
  58. @Binding var smooth: Bool
  59. @Binding var highGlucose: Decimal
  60. @Binding var lowGlucose: Decimal
  61. @Binding var screenHours: Int16
  62. @Binding var displayXgridLines: Bool
  63. @Binding var displayYgridLines: Bool
  64. @Binding var thresholdLines: Bool
  65. @Binding var isTempTargetActive: Bool
  66. @StateObject var state = Home.StateModel()
  67. @State var didAppearTrigger = false
  68. @State private var BasalProfiles: [BasalProfile] = []
  69. @State private var TempBasals: [PumpHistoryEvent] = []
  70. @State private var ChartTempTargets: [ChartTempTarget] = []
  71. @State private var Predictions: [Prediction] = []
  72. @State private var count: Decimal = 1
  73. @State private var startMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 - 86400))
  74. @State private var endMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 + 10800))
  75. @State private var minValue: Decimal = 45
  76. @State private var maxValue: Decimal = 270
  77. @State private var selection: Date? = nil
  78. private let now = Date.now
  79. @Environment(\.colorScheme) var colorScheme
  80. @Environment(\.calendar) var calendar
  81. // MARK: - Core Data Fetch Requests
  82. @FetchRequest(
  83. entity: MealsStored.entity(),
  84. sortDescriptors: [NSSortDescriptor(keyPath: \MealsStored.date, ascending: true)],
  85. predicate: NSPredicate.predicateForOneDayAgo
  86. ) var carbsFromPersistence: FetchedResults<MealsStored>
  87. @FetchRequest(
  88. entity: InsulinStored.entity(),
  89. sortDescriptors: [NSSortDescriptor(keyPath: \InsulinStored.date, ascending: true)],
  90. predicate: NSPredicate.predicateForOneDayAgo,
  91. animation: Animation.bouncy
  92. ) var insulinFromPersistence: FetchedResults<InsulinStored>
  93. @FetchRequest(
  94. entity: GlucoseStored.entity(),
  95. sortDescriptors: [NSSortDescriptor(keyPath: \GlucoseStored.date, ascending: true)],
  96. predicate: NSPredicate.predicateForOneDayAgo,
  97. animation: Animation.bouncy
  98. ) var glucoseFromPersistence: FetchedResults<GlucoseStored>
  99. private var bolusFormatter: NumberFormatter {
  100. let formatter = NumberFormatter()
  101. formatter.numberStyle = .decimal
  102. formatter.minimumIntegerDigits = 0
  103. formatter.maximumFractionDigits = 2
  104. formatter.decimalSeparator = "."
  105. return formatter
  106. }
  107. private var carbsFormatter: NumberFormatter {
  108. let formatter = NumberFormatter()
  109. formatter.numberStyle = .decimal
  110. formatter.maximumFractionDigits = 0
  111. return formatter
  112. }
  113. private var conversionFactor: Decimal {
  114. units == .mmolL ? 0.0555 : 1
  115. }
  116. private var upperLimit: Decimal {
  117. units == .mgdL ? 400 : 22.2
  118. }
  119. private var defaultBolusPosition: Int {
  120. units == .mgdL ? 120 : 7
  121. }
  122. private var bolusOffset: Decimal {
  123. units == .mgdL ? 30 : 1.66
  124. }
  125. private var selectedGlucose: GlucoseStored? {
  126. if let selection = selection {
  127. let lowerBound = selection.addingTimeInterval(-120)
  128. let upperBound = selection.addingTimeInterval(120)
  129. return glucoseFromPersistence.first { $0.date ?? now >= lowerBound && $0.date ?? now <= upperBound }
  130. } else {
  131. return nil
  132. }
  133. }
  134. var body: some View {
  135. VStack {
  136. ScrollViewReader { scroller in
  137. ScrollView(.horizontal, showsIndicators: false) {
  138. VStack(spacing: 0) {
  139. mainChart
  140. basalChart
  141. }.onChange(of: screenHours) { _ in
  142. updateStartEndMarkers()
  143. yAxisChartData()
  144. scroller.scrollTo("MainChart", anchor: .trailing)
  145. }.onChange(of: glucose) { _ in
  146. updateStartEndMarkers()
  147. yAxisChartData()
  148. scroller.scrollTo("MainChart", anchor: .trailing)
  149. }
  150. .onChange(of: suggestion) { _ in
  151. updateStartEndMarkers()
  152. scroller.scrollTo("MainChart", anchor: .trailing)
  153. }
  154. .onChange(of: tempBasals) { _ in
  155. updateStartEndMarkers()
  156. scroller.scrollTo("MainChart", anchor: .trailing)
  157. }
  158. .onChange(of: units) { _ in
  159. yAxisChartData()
  160. }
  161. .onAppear {
  162. updateStartEndMarkers()
  163. scroller.scrollTo("MainChart", anchor: .trailing)
  164. }
  165. }
  166. }
  167. legendPanel.padding(.top, 8)
  168. }
  169. }
  170. }
  171. // MARK: - Components
  172. struct Backport<Content: View> {
  173. let content: Content
  174. }
  175. extension View {
  176. var backport: Backport<Self> { Backport(content: self) }
  177. }
  178. extension Backport {
  179. @ViewBuilder func chartXSelection(value: Binding<Date?>) -> some View {
  180. if #available(iOS 17, *) {
  181. content.chartXSelection(value: value)
  182. } else {
  183. content
  184. }
  185. }
  186. }
  187. extension MainChartView {
  188. private var mainChart: some View {
  189. VStack {
  190. Chart {
  191. drawStartRuleMark()
  192. drawEndRuleMark()
  193. drawCurrentTimeMarker()
  194. drawCarbs()
  195. drawFpus()
  196. drawBoluses()
  197. drawTempTargets()
  198. drawPredictions()
  199. drawGlucose()
  200. drawManualGlucose()
  201. /// high and low treshold lines
  202. if thresholdLines {
  203. RuleMark(y: .value("High", highGlucose * conversionFactor)).foregroundStyle(Color.loopYellow)
  204. .lineStyle(.init(lineWidth: 1, dash: [5]))
  205. RuleMark(y: .value("Low", lowGlucose * conversionFactor)).foregroundStyle(Color.loopRed)
  206. .lineStyle(.init(lineWidth: 1, dash: [5]))
  207. }
  208. /// show glucose value when hovering over it
  209. if let selectedGlucose {
  210. RuleMark(x: .value("Selection", selectedGlucose.date ?? now, unit: .minute))
  211. .foregroundStyle(Color.tabBar)
  212. .offset(yStart: 70)
  213. .lineStyle(.init(lineWidth: 2, dash: [5]))
  214. .annotation(position: .top) {
  215. selectionPopover
  216. }
  217. }
  218. }
  219. .id("MainChart")
  220. .onChange(of: glucose) { _ in
  221. calculatePredictions()
  222. }
  223. .onChange(of: boluses) { _ in
  224. state.roundedTotalBolus = state.calculateTINS()
  225. }
  226. .onChange(of: tempTargets) { _ in
  227. calculateTTs()
  228. }
  229. .onChange(of: didAppearTrigger) { _ in
  230. calculatePredictions()
  231. calculateTTs()
  232. }.onChange(of: suggestion) { _ in
  233. calculatePredictions()
  234. }
  235. .onReceive(
  236. Foundation.NotificationCenter.default
  237. .publisher(for: UIApplication.willEnterForegroundNotification)
  238. ) { _ in
  239. calculatePredictions()
  240. }
  241. .frame(minHeight: UIScreen.main.bounds.height * 0.2)
  242. .frame(width: fullWidth(viewWidth: screenSize.width))
  243. .chartXScale(domain: startMarker ... endMarker)
  244. .chartXAxis { mainChartXAxis }
  245. // .chartXAxis(.hidden)
  246. .chartYAxis { mainChartYAxis }
  247. .chartYScale(domain: minValue ... maxValue)
  248. .backport.chartXSelection(value: $selection)
  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(height: 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) { bolus in
  327. let bolusAmount = bolus.amount ?? 0 as NSDecimalNumber
  328. let bolusDate = bolus.date ?? Date()
  329. let glucose = timeToNearestGlucose(time: bolusDate.timeIntervalSince1970)
  330. let yPosition = (Decimal(glucose.sgv ?? defaultBolusPosition) * conversionFactor) + bolusOffset
  331. let size = (Config.bolusSize + CGFloat(truncating: bolusAmount) * Config.bolusScale) * 1.8
  332. PointMark(
  333. x: .value("Time", bolus.date ?? Date(), unit: .second),
  334. y: .value("Value", yPosition)
  335. )
  336. .symbol {
  337. Image(systemName: "arrowtriangle.down.fill").font(.system(size: size)).foregroundStyle(Color.insulin)
  338. }
  339. .annotation(position: .top) {
  340. Text(bolusFormatter.string(from: bolusAmount) ?? "")
  341. .font(.caption2)
  342. .foregroundStyle(Color.insulin)
  343. }
  344. }
  345. }
  346. private func drawCarbs() -> some ChartContent {
  347. /// carbs
  348. ForEach(carbsFromPersistence) { carb in
  349. let carbAmount = carb.carbs
  350. let yPosition = units == .mgdL ? 60 : 3.33
  351. PointMark(
  352. x: .value("Time", carb.date ?? Date(), unit: .second),
  353. y: .value("Value", yPosition)
  354. )
  355. .symbolSize((Config.carbsSize + CGFloat(carbAmount) * Config.carbsScale) * 10)
  356. .foregroundStyle(Color.orange)
  357. .annotation(position: .bottom) {
  358. Text(carbsFormatter.string(from: carbAmount as NSNumber)!).font(.caption2)
  359. .foregroundStyle(Color.orange)
  360. }
  361. }
  362. }
  363. private func drawFpus() -> some ChartContent {
  364. /// fpus
  365. ForEach(fpusForChart) { fpu in
  366. let fpuAmount = fpu.carbs
  367. let size = (Config.fpuSize + CGFloat(fpuAmount) * Config.carbsScale) * 1.8
  368. let yPosition = units == .mgdL ? 60 : 3.33
  369. PointMark(
  370. x: .value("Time", fpu.actualDate ?? Date(), unit: .second),
  371. y: .value("Value", yPosition)
  372. )
  373. .symbolSize(size)
  374. .foregroundStyle(Color.brown)
  375. }
  376. }
  377. private func drawGlucose() -> some ChartContent {
  378. /// glucose point mark
  379. /// filtering for high and low bounds in settings
  380. ForEach(glucoseFromPersistence) { item in
  381. if smooth {
  382. if item.glucose > Int(highGlucose) {
  383. PointMark(
  384. x: .value("Time", item.date ?? Date(), unit: .second),
  385. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  386. ).foregroundStyle(Color.orange.gradient).symbolSize(25).interpolationMethod(.cardinal)
  387. } else if item.glucose < Int(lowGlucose) {
  388. PointMark(
  389. x: .value("Time", item.date ?? Date(), unit: .second),
  390. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  391. ).foregroundStyle(Color.red.gradient).symbolSize(25).interpolationMethod(.cardinal)
  392. } else {
  393. PointMark(
  394. x: .value("Time", item.date ?? Date(), unit: .second),
  395. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  396. ).foregroundStyle(Color.green.gradient).symbolSize(25).interpolationMethod(.cardinal)
  397. }
  398. } else {
  399. if item.glucose > Int(highGlucose) {
  400. PointMark(
  401. x: .value("Time", item.date ?? Date(), unit: .second),
  402. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  403. ).foregroundStyle(Color.orange.gradient).symbolSize(25)
  404. } else if item.glucose < Int(lowGlucose) {
  405. PointMark(
  406. x: .value("Time", item.date ?? Date(), unit: .second),
  407. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  408. ).foregroundStyle(Color.red.gradient).symbolSize(25)
  409. } else {
  410. PointMark(
  411. x: .value("Time", item.date ?? Date(), unit: .second),
  412. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  413. ).foregroundStyle(Color.green.gradient).symbolSize(25)
  414. }
  415. }
  416. }
  417. }
  418. private func drawPredictions() -> some ChartContent {
  419. /// predictions
  420. ForEach(Predictions, id: \.self) { info in
  421. let y = max(info.amount, 0)
  422. if info.type == .uam {
  423. LineMark(
  424. x: .value("Time", info.timestamp, unit: .second),
  425. y: .value("Value", Decimal(y) * conversionFactor),
  426. series: .value("uam", "uam")
  427. ).foregroundStyle(Color.uam).symbolSize(16)
  428. }
  429. if info.type == .cob {
  430. LineMark(
  431. x: .value("Time", info.timestamp, unit: .second),
  432. y: .value("Value", Decimal(y) * conversionFactor),
  433. series: .value("cob", "cob")
  434. ).foregroundStyle(Color.orange).symbolSize(16)
  435. }
  436. if info.type == .iob {
  437. LineMark(
  438. x: .value("Time", info.timestamp, unit: .second),
  439. y: .value("Value", Decimal(y) * conversionFactor),
  440. series: .value("iob", "iob")
  441. ).foregroundStyle(Color.insulin).symbolSize(16)
  442. }
  443. if info.type == .zt {
  444. LineMark(
  445. x: .value("Time", info.timestamp, unit: .second),
  446. y: .value("Value", Decimal(y) * conversionFactor),
  447. series: .value("zt", "zt")
  448. ).foregroundStyle(Color.zt).symbolSize(16)
  449. }
  450. }
  451. }
  452. private func drawCurrentTimeMarker() -> some ChartContent {
  453. RuleMark(
  454. x: .value(
  455. "",
  456. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  457. unit: .second
  458. )
  459. ).lineStyle(.init(lineWidth: 2, dash: [3])).foregroundStyle(Color(.systemGray2))
  460. }
  461. private func drawStartRuleMark() -> some ChartContent {
  462. RuleMark(
  463. x: .value(
  464. "",
  465. startMarker,
  466. unit: .second
  467. )
  468. ).foregroundStyle(Color.clear)
  469. }
  470. private func drawEndRuleMark() -> some ChartContent {
  471. RuleMark(
  472. x: .value(
  473. "",
  474. endMarker,
  475. unit: .second
  476. )
  477. ).foregroundStyle(Color.clear)
  478. }
  479. private func drawTempTargets() -> some ChartContent {
  480. /// temp targets
  481. ForEach(ChartTempTargets, id: \.self) { target in
  482. let targetLimited = min(max(target.amount, 0), upperLimit)
  483. RuleMark(
  484. xStart: .value("Start", target.start),
  485. xEnd: .value("End", target.end),
  486. y: .value("Value", targetLimited)
  487. )
  488. .foregroundStyle(Color.purple.opacity(0.5)).lineStyle(.init(lineWidth: 8))
  489. }
  490. }
  491. private func drawManualGlucose() -> some ChartContent {
  492. /// manual glucose mark
  493. ForEach(manualGlucose) { item in
  494. if let manualGlucose = item.glucose {
  495. PointMark(
  496. x: .value("Time", item.dateString, unit: .second),
  497. y: .value("Value", Decimal(manualGlucose) * conversionFactor)
  498. )
  499. .symbol {
  500. Image(systemName: "drop.fill").font(.system(size: 10)).symbolRenderingMode(.monochrome)
  501. .foregroundStyle(.red)
  502. }
  503. }
  504. }
  505. }
  506. private func drawSuspensions() -> some ChartContent {
  507. /// pump suspensions
  508. ForEach(suspensions) { suspension in
  509. let now = Date()
  510. if suspension.type == EventType.pumpSuspend {
  511. let suspensionStart = suspension.timestamp
  512. let suspensionEnd = min(
  513. suspensions
  514. .first(where: { $0.timestamp > suspension.timestamp && $0.type == EventType.pumpResume })?
  515. .timestamp ?? now,
  516. now
  517. )
  518. let basalProfileDuringSuspension = BasalProfiles.first(where: { $0.startDate <= suspensionStart })
  519. let suspensionMarkHeight = basalProfileDuringSuspension?.amount ?? 1
  520. RectangleMark(
  521. xStart: .value("start", suspensionStart),
  522. xEnd: .value("end", suspensionEnd),
  523. yStart: .value("suspend-start", 0),
  524. yEnd: .value("suspend-end", suspensionMarkHeight)
  525. )
  526. .foregroundStyle(Color.loopGray.opacity(colorScheme == .dark ? 0.3 : 0.8))
  527. }
  528. }
  529. }
  530. private func drawTempBasals() -> some ChartContent {
  531. /// temp basal rects
  532. ForEach(TempBasals) { temp in
  533. /// calculate end time of temp basal adding duration to start time
  534. let end = temp.timestamp + (temp.durationMin ?? 0).minutes.timeInterval
  535. let now = Date()
  536. /// ensure that temp basals that are set cannot exceed current date -> i.e. scheduled temp basals are not shown
  537. /// we could display scheduled temp basals with opacity etc... in the future
  538. let maxEndTime = min(end, now)
  539. /// set mark height to 0 when insulin delivery is suspended
  540. let isInsulinSuspended = suspensions
  541. .first(where: { $0.timestamp >= temp.timestamp && $0.timestamp <= maxEndTime }) != nil
  542. let rate = (temp.rate ?? 0) * (isInsulinSuspended ? 0 : 1)
  543. /// find next basal entry and if available set end of current entry to start of next entry
  544. if let nextTemp = TempBasals.first(where: { $0.timestamp > temp.timestamp }) {
  545. let nextTempStart = nextTemp.timestamp
  546. RectangleMark(
  547. xStart: .value("start", temp.timestamp),
  548. xEnd: .value("end", nextTempStart),
  549. yStart: .value("rate-start", 0),
  550. yEnd: .value("rate-end", rate)
  551. ).foregroundStyle(Color.insulin.opacity(0.2))
  552. LineMark(x: .value("Start Date", temp.timestamp), y: .value("Amount", rate))
  553. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  554. LineMark(x: .value("End Date", nextTempStart), y: .value("Amount", rate))
  555. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  556. } else {
  557. RectangleMark(
  558. xStart: .value("start", temp.timestamp),
  559. xEnd: .value("end", maxEndTime),
  560. yStart: .value("rate-start", 0),
  561. yEnd: .value("rate-end", rate)
  562. ).foregroundStyle(Color.insulin.opacity(0.2))
  563. LineMark(x: .value("Start Date", temp.timestamp), y: .value("Amount", rate))
  564. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  565. LineMark(x: .value("End Date", maxEndTime), y: .value("Amount", rate))
  566. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  567. }
  568. }
  569. }
  570. private func drawBasalProfile() -> some ChartContent {
  571. /// dashed profile line
  572. ForEach(BasalProfiles, id: \.self) { profile in
  573. LineMark(
  574. x: .value("Start Date", profile.startDate),
  575. y: .value("Amount", profile.amount),
  576. series: .value("profile", "profile")
  577. ).lineStyle(.init(lineWidth: 2, dash: [2, 4])).foregroundStyle(Color.insulin)
  578. LineMark(
  579. x: .value("End Date", profile.endDate ?? endMarker),
  580. y: .value("Amount", profile.amount),
  581. series: .value("profile", "profile")
  582. ).lineStyle(.init(lineWidth: 2.5, dash: [2, 4])).foregroundStyle(Color.insulin)
  583. }
  584. }
  585. /// calculates the glucose value thats the nearest to parameter 'time'
  586. /// if time is later than all the arrays values return the last element of BloodGlucose
  587. private func timeToNearestGlucose(time: TimeInterval) -> BloodGlucose {
  588. /// If the glucose array is empty, return a default BloodGlucose object or handle it accordingly
  589. guard let lastGlucose = glucose.last else {
  590. return BloodGlucose(
  591. date: 0,
  592. dateString: Date(),
  593. unfiltered: nil,
  594. filtered: nil,
  595. noise: nil,
  596. type: nil
  597. )
  598. }
  599. /// If the last glucose entry is before the specified time, return the last entry
  600. if lastGlucose.dateString.timeIntervalSince1970 < time {
  601. return lastGlucose
  602. }
  603. /// Find the index of the first element in the array whose date is greater than the specified time
  604. if let nextIndex = glucose.firstIndex(where: { $0.dateString.timeIntervalSince1970 > time }) {
  605. return glucose[nextIndex]
  606. } else {
  607. /// If no such element is found, return the last element in the array
  608. return lastGlucose
  609. }
  610. }
  611. private func fullWidth(viewWidth: CGFloat) -> CGFloat {
  612. viewWidth * CGFloat(hours) / CGFloat(min(max(screenHours, 2), 24))
  613. }
  614. /// calculations for temp target bar mark
  615. private func calculateTTs() {
  616. var groupedPackages: [[TempTarget]] = []
  617. var currentPackage: [TempTarget] = []
  618. var calculatedTTs: [ChartTempTarget] = []
  619. for target in tempTargets {
  620. if target.duration > 0 {
  621. if !currentPackage.isEmpty {
  622. groupedPackages.append(currentPackage)
  623. currentPackage = []
  624. }
  625. currentPackage.append(target)
  626. } else {
  627. if let lastNonZeroTempTarget = currentPackage.last(where: { $0.duration > 0 }) {
  628. if target.createdAt >= lastNonZeroTempTarget.createdAt,
  629. target.createdAt <= lastNonZeroTempTarget.createdAt
  630. .addingTimeInterval(TimeInterval(lastNonZeroTempTarget.duration * 60))
  631. {
  632. currentPackage.append(target)
  633. }
  634. }
  635. }
  636. }
  637. // appends last package, if exists
  638. if !currentPackage.isEmpty {
  639. groupedPackages.append(currentPackage)
  640. }
  641. for package in groupedPackages {
  642. guard let firstNonZeroTarget = package.first(where: { $0.duration > 0 }) else {
  643. continue
  644. }
  645. var end = firstNonZeroTarget.createdAt.addingTimeInterval(TimeInterval(firstNonZeroTarget.duration * 60))
  646. let earliestCancelTarget = package.filter({ $0.duration == 0 }).min(by: { $0.createdAt < $1.createdAt })
  647. if let earliestCancelTarget = earliestCancelTarget {
  648. end = min(earliestCancelTarget.createdAt, end)
  649. }
  650. let now = Date()
  651. isTempTargetActive = firstNonZeroTarget.createdAt <= now && now <= end
  652. if firstNonZeroTarget.targetTop != nil {
  653. calculatedTTs
  654. .append(ChartTempTarget(
  655. amount: (firstNonZeroTarget.targetTop ?? 0) * conversionFactor,
  656. start: firstNonZeroTarget.createdAt,
  657. end: end
  658. ))
  659. }
  660. }
  661. ChartTempTargets = calculatedTTs
  662. }
  663. private func addPredictions(_ predictions: [Int], type: PredictionType, deliveredAt: Date, endMarker: Date) -> [Prediction] {
  664. var calculatedPredictions: [Prediction] = []
  665. predictions.indices.forEach { index in
  666. let predTime = Date(
  667. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes.timeInterval
  668. )
  669. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  670. calculatedPredictions.append(
  671. Prediction(amount: predictions[index], timestamp: predTime, type: type)
  672. )
  673. }
  674. }
  675. return calculatedPredictions
  676. }
  677. private func calculatePredictions() {
  678. guard let suggestion = suggestion, let deliveredAt = suggestion.deliverAt else { return }
  679. let uamPredictions = suggestion.predictions?.uam ?? []
  680. let iobPredictions = suggestion.predictions?.iob ?? []
  681. let cobPredictions = suggestion.predictions?.cob ?? []
  682. let ztPredictions = suggestion.predictions?.zt ?? []
  683. let uam = addPredictions(uamPredictions, type: .uam, deliveredAt: deliveredAt, endMarker: endMarker)
  684. let iob = addPredictions(iobPredictions, type: .iob, deliveredAt: deliveredAt, endMarker: endMarker)
  685. let cob = addPredictions(cobPredictions, type: .cob, deliveredAt: deliveredAt, endMarker: endMarker)
  686. let zt = addPredictions(ztPredictions, type: .zt, deliveredAt: deliveredAt, endMarker: endMarker)
  687. Predictions = uam + iob + cob + zt
  688. }
  689. private func calculateTempBasals() {
  690. let basals = tempBasals
  691. var returnTempBasalRates: [PumpHistoryEvent] = []
  692. var finished: [Int: Bool] = [:]
  693. basals.indices.forEach { i in
  694. basals.indices.forEach { j in
  695. if basals[i].timestamp == basals[j].timestamp, i != j, !(finished[i] ?? false), !(finished[j] ?? false) {
  696. let rate = basals[i].rate ?? basals[j].rate
  697. let durationMin = basals[i].durationMin ?? basals[j].durationMin
  698. finished[i] = true
  699. if rate != 0 || durationMin != 0 {
  700. returnTempBasalRates.append(
  701. PumpHistoryEvent(
  702. id: basals[i].id, type: FreeAPS.EventType.tempBasal,
  703. timestamp: basals[i].timestamp,
  704. durationMin: durationMin,
  705. rate: rate
  706. )
  707. )
  708. }
  709. }
  710. }
  711. }
  712. TempBasals = returnTempBasalRates
  713. }
  714. private func findRegularBasalPoints(
  715. timeBegin: TimeInterval,
  716. timeEnd: TimeInterval,
  717. autotuned: Bool
  718. ) -> [BasalProfile] {
  719. guard timeBegin < timeEnd else {
  720. return []
  721. }
  722. let beginDate = Date(timeIntervalSince1970: timeBegin)
  723. let calendar = Calendar.current
  724. let startOfDay = calendar.startOfDay(for: beginDate)
  725. let profile = autotuned ? autotunedBasalProfile : basalProfile
  726. let basalNormalized = profile.map {
  727. (
  728. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  729. rate: $0.rate
  730. )
  731. } + profile.map {
  732. (
  733. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval)
  734. .timeIntervalSince1970,
  735. rate: $0.rate
  736. )
  737. } + profile.map {
  738. (
  739. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 2.days.timeInterval)
  740. .timeIntervalSince1970,
  741. rate: $0.rate
  742. )
  743. }
  744. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  745. .compactMap { window -> BasalProfile? in
  746. let window = Array(window)
  747. if window[0].time < timeBegin, window[1].time < timeBegin {
  748. return nil
  749. }
  750. if window[0].time < timeBegin, window[1].time >= timeBegin {
  751. let startDate = Date(timeIntervalSince1970: timeBegin)
  752. let rate = window[0].rate
  753. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  754. }
  755. if window[0].time >= timeBegin, window[0].time < timeEnd {
  756. let startDate = Date(timeIntervalSince1970: window[0].time)
  757. let rate = window[0].rate
  758. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  759. }
  760. return nil
  761. }
  762. return basalTruncatedPoints
  763. }
  764. /// update start and end marker to fix scroll update problem with x axis
  765. private func updateStartEndMarkers() {
  766. startMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 - 86400))
  767. endMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 + 10800))
  768. }
  769. private func calculateBasals() {
  770. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  771. let regularPoints = findRegularBasalPoints(
  772. timeBegin: dayAgoTime,
  773. timeEnd: endMarker.timeIntervalSince1970,
  774. autotuned: false
  775. )
  776. let autotunedBasalPoints = findRegularBasalPoints(
  777. timeBegin: dayAgoTime,
  778. timeEnd: endMarker.timeIntervalSince1970,
  779. autotuned: true
  780. )
  781. var totalBasal = regularPoints + autotunedBasalPoints
  782. totalBasal.sort {
  783. $0.startDate.timeIntervalSince1970 < $1.startDate.timeIntervalSince1970
  784. }
  785. var basals: [BasalProfile] = []
  786. totalBasal.indices.forEach { index in
  787. basals.append(BasalProfile(
  788. amount: totalBasal[index].amount,
  789. isOverwritten: totalBasal[index].isOverwritten,
  790. startDate: totalBasal[index].startDate,
  791. endDate: totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker
  792. ))
  793. print(
  794. "Basal",
  795. totalBasal[index].startDate,
  796. totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker,
  797. totalBasal[index].amount,
  798. totalBasal[index].isOverwritten
  799. )
  800. }
  801. BasalProfiles = basals
  802. }
  803. // MARK: - Chart formatting
  804. private func yAxisChartData() {
  805. let glucoseMapped = glucose.compactMap(\.glucose)
  806. guard let minGlucose = glucoseMapped.min(), let maxGlucose = glucoseMapped.max() else {
  807. // default values
  808. minValue = 45 * conversionFactor - 20 * conversionFactor
  809. maxValue = 270 * conversionFactor + 50 * conversionFactor
  810. return
  811. }
  812. minValue = Decimal(minGlucose) * conversionFactor - 20 * conversionFactor
  813. maxValue = Decimal(maxGlucose) * conversionFactor + 50 * conversionFactor
  814. debug(.default, "min \(minValue)")
  815. debug(.default, "max \(maxValue)")
  816. }
  817. private func basalChartPlotStyle(_ plotContent: ChartPlotContent) -> some View {
  818. plotContent
  819. .rotationEffect(.degrees(180))
  820. .scaleEffect(x: -1, y: 1)
  821. .chartXAxis(.hidden)
  822. }
  823. private var mainChartXAxis: some AxisContent {
  824. AxisMarks(values: .stride(by: .hour, count: screenHours == 24 ? 4 : 2)) { _ in
  825. if displayXgridLines {
  826. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  827. } else {
  828. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  829. }
  830. }
  831. }
  832. private var basalChartXAxis: some AxisContent {
  833. AxisMarks(values: .stride(by: .hour, count: screenHours == 24 ? 4 : 2)) { _ in
  834. if displayXgridLines {
  835. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  836. } else {
  837. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  838. }
  839. AxisValueLabel(format: .dateTime.hour(.defaultDigits(amPM: .narrow)), anchor: .top)
  840. .font(.footnote)
  841. }
  842. }
  843. private var mainChartYAxis: some AxisContent {
  844. AxisMarks(position: .trailing) { value in
  845. if displayXgridLines {
  846. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  847. } else {
  848. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  849. }
  850. if let glucoseValue = value.as(Double.self), glucoseValue > 0 {
  851. /// fix offset between the two charts...
  852. if units == .mmolL {
  853. AxisTick(length: 7, stroke: .init(lineWidth: 7)).foregroundStyle(Color.clear)
  854. }
  855. AxisValueLabel().font(.footnote)
  856. }
  857. }
  858. }
  859. private var basalChartYAxis: some AxisContent {
  860. AxisMarks(position: .trailing) { _ in
  861. AxisTick(length: units == .mmolL ? 25 : 27, stroke: .init(lineWidth: 4))
  862. .foregroundStyle(Color.clear).font(.footnote)
  863. }
  864. }
  865. }
  866. struct LegendItem: View {
  867. var color: Color
  868. var label: String
  869. var body: some View {
  870. Group {
  871. Circle().fill(color).frame(width: 8, height: 8)
  872. Text(label)
  873. .font(.system(size: 10, weight: .bold))
  874. .foregroundColor(color)
  875. }
  876. }
  877. }