MainChartView.swift 37 KB

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