MainChartView.swift 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  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. @Environment(\.colorScheme) var colorScheme
  79. @Environment(\.calendar) var calendar
  80. // MARK: - Core Data Fetch Requests
  81. @FetchRequest(
  82. entity: MealsStored.entity(),
  83. sortDescriptors: [NSSortDescriptor(keyPath: \MealsStored.date, ascending: true)],
  84. predicate: NSPredicate.predicateForOneDayAgo
  85. ) var carbsFromPersistence: FetchedResults<MealsStored>
  86. @FetchRequest(
  87. entity: InsulinStored.entity(),
  88. sortDescriptors: [NSSortDescriptor(keyPath: \InsulinStored.date, ascending: true)],
  89. predicate: NSPredicate.predicateForOneDayAgo,
  90. animation: Animation.bouncy
  91. ) var insulinFromPersistence: FetchedResults<InsulinStored>
  92. @FetchRequest(
  93. entity: GlucoseStored.entity(),
  94. sortDescriptors: [NSSortDescriptor(keyPath: \GlucoseStored.date, ascending: true)],
  95. predicate: NSPredicate.predicateForOneDayAgo,
  96. animation: Animation.bouncy
  97. ) var glucoseFromPersistence: FetchedResults<GlucoseStored>
  98. private var bolusFormatter: NumberFormatter {
  99. let formatter = NumberFormatter()
  100. formatter.numberStyle = .decimal
  101. formatter.minimumIntegerDigits = 0
  102. formatter.maximumFractionDigits = 2
  103. formatter.decimalSeparator = "."
  104. return formatter
  105. }
  106. private var carbsFormatter: NumberFormatter {
  107. let formatter = NumberFormatter()
  108. formatter.numberStyle = .decimal
  109. formatter.maximumFractionDigits = 0
  110. return formatter
  111. }
  112. private var conversionFactor: Decimal {
  113. units == .mmolL ? 0.0555 : 1
  114. }
  115. private var upperLimit: Decimal {
  116. units == .mgdL ? 400 : 22.2
  117. }
  118. private var defaultBolusPosition: Int {
  119. units == .mgdL ? 120 : 7
  120. }
  121. private var bolusOffset: Decimal {
  122. units == .mgdL ? 30 : 1.66
  123. }
  124. private var selectedGlucose: BloodGlucose? {
  125. if let selection = selection {
  126. let lowerBound = selection.addingTimeInterval(-120)
  127. let upperBound = selection.addingTimeInterval(120)
  128. return glucose.first { $0.dateString >= lowerBound && $0.dateString <= upperBound }
  129. } else {
  130. return nil
  131. }
  132. }
  133. var body: some View {
  134. VStack {
  135. ScrollViewReader { scroller in
  136. ScrollView(.horizontal, showsIndicators: false) {
  137. VStack(spacing: 0) {
  138. mainChart
  139. basalChart
  140. }.onChange(of: screenHours) { _ in
  141. updateStartEndMarkers()
  142. yAxisChartData()
  143. scroller.scrollTo("MainChart", anchor: .trailing)
  144. }.onChange(of: glucose) { _ in
  145. updateStartEndMarkers()
  146. yAxisChartData()
  147. scroller.scrollTo("MainChart", anchor: .trailing)
  148. }
  149. .onChange(of: suggestion) { _ in
  150. updateStartEndMarkers()
  151. scroller.scrollTo("MainChart", anchor: .trailing)
  152. }
  153. .onChange(of: tempBasals) { _ in
  154. updateStartEndMarkers()
  155. scroller.scrollTo("MainChart", anchor: .trailing)
  156. }
  157. .onChange(of: units) { _ in
  158. yAxisChartData()
  159. }
  160. .onAppear {
  161. updateStartEndMarkers()
  162. scroller.scrollTo("MainChart", anchor: .trailing)
  163. }
  164. }
  165. }
  166. legendPanel.padding(.top, 8)
  167. }
  168. }
  169. }
  170. // MARK: - Components
  171. struct Backport<Content: View> {
  172. let content: Content
  173. }
  174. extension View {
  175. var backport: Backport<Self> { Backport(content: self) }
  176. }
  177. extension Backport {
  178. @ViewBuilder func chartXSelection(value: Binding<Date?>) -> some View {
  179. if #available(iOS 17, *) {
  180. content.chartXSelection(value: value)
  181. } else {
  182. content
  183. }
  184. }
  185. }
  186. extension MainChartView {
  187. private var mainChart: some View {
  188. VStack {
  189. Chart {
  190. drawStartRuleMark()
  191. drawEndRuleMark()
  192. drawCurrentTimeMarker()
  193. drawCarbs()
  194. drawFpus()
  195. drawBoluses()
  196. drawTempTargets()
  197. drawPredictions()
  198. drawGlucose()
  199. drawManualGlucose()
  200. /// high and low treshold lines
  201. if thresholdLines {
  202. RuleMark(y: .value("High", highGlucose * conversionFactor)).foregroundStyle(Color.loopYellow)
  203. .lineStyle(.init(lineWidth: 1, dash: [5]))
  204. RuleMark(y: .value("Low", lowGlucose * conversionFactor)).foregroundStyle(Color.loopRed)
  205. .lineStyle(.init(lineWidth: 1, dash: [5]))
  206. }
  207. /// show glucose value when hovering over it
  208. if let selectedGlucose {
  209. RuleMark(x: .value("Selection", selectedGlucose.dateString, unit: .minute))
  210. .foregroundStyle(Color.tabBar)
  211. .offset(yStart: 70)
  212. .lineStyle(.init(lineWidth: 2, dash: [5]))
  213. .annotation(position: .top) {
  214. selectionPopover
  215. }
  216. }
  217. }
  218. .id("MainChart")
  219. .onChange(of: glucose) { _ in
  220. calculatePredictions()
  221. }
  222. .onChange(of: boluses) { _ in
  223. state.roundedTotalBolus = state.calculateTINS()
  224. }
  225. .onChange(of: tempTargets) { _ in
  226. calculateTTs()
  227. }
  228. .onChange(of: didAppearTrigger) { _ in
  229. calculatePredictions()
  230. calculateTTs()
  231. }.onChange(of: suggestion) { _ in
  232. calculatePredictions()
  233. }
  234. .onReceive(
  235. Foundation.NotificationCenter.default
  236. .publisher(for: UIApplication.willEnterForegroundNotification)
  237. ) { _ in
  238. calculatePredictions()
  239. }
  240. .frame(minHeight: UIScreen.main.bounds.height * 0.2)
  241. .frame(width: fullWidth(viewWidth: screenSize.width))
  242. .chartXScale(domain: startMarker ... endMarker)
  243. .chartXAxis { mainChartXAxis }
  244. // .chartXAxis(.hidden)
  245. .chartYAxis { mainChartYAxis }
  246. .chartYScale(domain: minValue ... maxValue)
  247. .backport.chartXSelection(value: $selection)
  248. }
  249. }
  250. @ViewBuilder var selectionPopover: some View {
  251. if let sgv = selectedGlucose?.sgv {
  252. let glucoseToShow = Decimal(sgv) * conversionFactor
  253. VStack {
  254. Text(selectedGlucose?.dateString.formatted(.dateTime.hour().minute(.twoDigits)) ?? "")
  255. HStack {
  256. Text(glucoseToShow.formatted(.number.precision(units == .mmolL ? .fractionLength(1) : .fractionLength(0))))
  257. .fontWeight(.bold)
  258. .foregroundStyle(
  259. Decimal(sgv) < lowGlucose ? Color
  260. .red : (Decimal(sgv) > highGlucose ? Color.orange : Color.primary)
  261. )
  262. Text(units.rawValue).foregroundColor(.secondary)
  263. }
  264. }
  265. .padding(6)
  266. .background {
  267. RoundedRectangle(cornerRadius: 4)
  268. .fill(Color.gray.opacity(0.1))
  269. .shadow(color: .blue, radius: 2)
  270. }
  271. }
  272. }
  273. private var basalChart: some View {
  274. VStack {
  275. Chart {
  276. drawStartRuleMark()
  277. drawEndRuleMark()
  278. drawCurrentTimeMarker()
  279. drawTempBasals()
  280. drawBasalProfile()
  281. drawSuspensions()
  282. }.onChange(of: tempBasals) { _ in
  283. calculateBasals()
  284. calculateTempBasals()
  285. }
  286. .onChange(of: maxBasal) { _ in
  287. calculateBasals()
  288. calculateTempBasals()
  289. }
  290. .onChange(of: autotunedBasalProfile) { _ in
  291. calculateBasals()
  292. calculateTempBasals()
  293. }
  294. .onChange(of: didAppearTrigger) { _ in
  295. calculateBasals()
  296. calculateTempBasals()
  297. }.onChange(of: basalProfile) { _ in
  298. calculateTempBasals()
  299. }
  300. .frame(height: UIScreen.main.bounds.height * 0.08)
  301. .frame(width: fullWidth(viewWidth: screenSize.width))
  302. .chartXScale(domain: startMarker ... endMarker)
  303. .chartXAxis { basalChartXAxis }
  304. .chartYAxis { basalChartYAxis }
  305. }
  306. }
  307. var legendPanel: some View {
  308. HStack(spacing: 10) {
  309. Spacer()
  310. LegendItem(color: .loopGreen, label: "BG")
  311. LegendItem(color: .insulin, label: "IOB")
  312. LegendItem(color: .zt, label: "ZT")
  313. LegendItem(color: .loopYellow, label: "COB")
  314. LegendItem(color: .uam, label: "UAM")
  315. Spacer()
  316. }
  317. .padding(.horizontal, 10)
  318. .frame(maxWidth: .infinity)
  319. }
  320. }
  321. // MARK: - Calculations
  322. extension MainChartView {
  323. private func drawBoluses() -> some ChartContent {
  324. /// smbs in triangle form
  325. ForEach(insulinFromPersistence) { bolus in
  326. let bolusAmount = bolus.amount ?? 0 as NSDecimalNumber
  327. let bolusDate = bolus.date ?? Date()
  328. let glucose = timeToNearestGlucose(time: bolusDate.timeIntervalSince1970)
  329. let yPosition = (Decimal(glucose.sgv ?? defaultBolusPosition) * conversionFactor) + bolusOffset
  330. let size = (Config.bolusSize + CGFloat(truncating: bolusAmount) * Config.bolusScale) * 1.8
  331. PointMark(
  332. x: .value("Time", bolus.date ?? Date(), unit: .second),
  333. y: .value("Value", yPosition)
  334. )
  335. .symbol {
  336. Image(systemName: "arrowtriangle.down.fill").font(.system(size: size)).foregroundStyle(Color.insulin)
  337. }
  338. .annotation(position: .top) {
  339. Text(bolusFormatter.string(from: bolusAmount) ?? "")
  340. .font(.caption2)
  341. .foregroundStyle(Color.insulin)
  342. }
  343. }
  344. }
  345. private func drawCarbs() -> some ChartContent {
  346. /// carbs
  347. ForEach(carbsFromPersistence) { carb in
  348. let carbAmount = carb.carbs
  349. let yPosition = units == .mgdL ? 60 : 3.33
  350. PointMark(
  351. x: .value("Time", carb.date ?? Date(), unit: .second),
  352. y: .value("Value", yPosition)
  353. )
  354. .symbolSize((Config.carbsSize + CGFloat(carbAmount) * Config.carbsScale) * 10)
  355. .foregroundStyle(Color.orange)
  356. .annotation(position: .bottom) {
  357. Text(carbsFormatter.string(from: carbAmount as NSNumber)!).font(.caption2)
  358. .foregroundStyle(Color.orange)
  359. }
  360. }
  361. }
  362. private func drawFpus() -> some ChartContent {
  363. /// fpus
  364. ForEach(fpusForChart) { fpu in
  365. let fpuAmount = fpu.carbs
  366. let size = (Config.fpuSize + CGFloat(fpuAmount) * Config.carbsScale) * 1.8
  367. let yPosition = units == .mgdL ? 60 : 3.33
  368. PointMark(
  369. x: .value("Time", fpu.actualDate ?? Date(), unit: .second),
  370. y: .value("Value", yPosition)
  371. )
  372. .symbolSize(size)
  373. .foregroundStyle(Color.brown)
  374. }
  375. }
  376. private func drawGlucose() -> some ChartContent {
  377. /// glucose point mark
  378. /// filtering for high and low bounds in settings
  379. ForEach(glucoseFromPersistence) { item in
  380. if smooth {
  381. if item.glucose > Int(highGlucose) {
  382. PointMark(
  383. x: .value("Time", item.date ?? Date(), unit: .second),
  384. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  385. ).foregroundStyle(Color.orange.gradient).symbolSize(25).interpolationMethod(.cardinal)
  386. } else if item.glucose < Int(lowGlucose) {
  387. PointMark(
  388. x: .value("Time", item.date ?? Date(), unit: .second),
  389. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  390. ).foregroundStyle(Color.red.gradient).symbolSize(25).interpolationMethod(.cardinal)
  391. } else {
  392. PointMark(
  393. x: .value("Time", item.date ?? Date(), unit: .second),
  394. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  395. ).foregroundStyle(Color.green.gradient).symbolSize(25).interpolationMethod(.cardinal)
  396. }
  397. } else {
  398. if item.glucose > Int(highGlucose) {
  399. PointMark(
  400. x: .value("Time", item.date ?? Date(), unit: .second),
  401. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  402. ).foregroundStyle(Color.orange.gradient).symbolSize(25)
  403. } else if item.glucose < Int(lowGlucose) {
  404. PointMark(
  405. x: .value("Time", item.date ?? Date(), unit: .second),
  406. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  407. ).foregroundStyle(Color.red.gradient).symbolSize(25)
  408. } else {
  409. PointMark(
  410. x: .value("Time", item.date ?? Date(), unit: .second),
  411. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  412. ).foregroundStyle(Color.green.gradient).symbolSize(25)
  413. }
  414. }
  415. }
  416. }
  417. private func drawPredictions() -> some ChartContent {
  418. /// predictions
  419. ForEach(Predictions, id: \.self) { info in
  420. let y = max(info.amount, 0)
  421. if info.type == .uam {
  422. LineMark(
  423. x: .value("Time", info.timestamp, unit: .second),
  424. y: .value("Value", Decimal(y) * conversionFactor),
  425. series: .value("uam", "uam")
  426. ).foregroundStyle(Color.uam).symbolSize(16)
  427. }
  428. if info.type == .cob {
  429. LineMark(
  430. x: .value("Time", info.timestamp, unit: .second),
  431. y: .value("Value", Decimal(y) * conversionFactor),
  432. series: .value("cob", "cob")
  433. ).foregroundStyle(Color.orange).symbolSize(16)
  434. }
  435. if info.type == .iob {
  436. LineMark(
  437. x: .value("Time", info.timestamp, unit: .second),
  438. y: .value("Value", Decimal(y) * conversionFactor),
  439. series: .value("iob", "iob")
  440. ).foregroundStyle(Color.insulin).symbolSize(16)
  441. }
  442. if info.type == .zt {
  443. LineMark(
  444. x: .value("Time", info.timestamp, unit: .second),
  445. y: .value("Value", Decimal(y) * conversionFactor),
  446. series: .value("zt", "zt")
  447. ).foregroundStyle(Color.zt).symbolSize(16)
  448. }
  449. }
  450. }
  451. private func drawCurrentTimeMarker() -> some ChartContent {
  452. RuleMark(
  453. x: .value(
  454. "",
  455. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  456. unit: .second
  457. )
  458. ).lineStyle(.init(lineWidth: 2, dash: [3])).foregroundStyle(Color(.systemGray2))
  459. }
  460. private func drawStartRuleMark() -> some ChartContent {
  461. RuleMark(
  462. x: .value(
  463. "",
  464. startMarker,
  465. unit: .second
  466. )
  467. ).foregroundStyle(Color.clear)
  468. }
  469. private func drawEndRuleMark() -> some ChartContent {
  470. RuleMark(
  471. x: .value(
  472. "",
  473. endMarker,
  474. unit: .second
  475. )
  476. ).foregroundStyle(Color.clear)
  477. }
  478. private func drawTempTargets() -> some ChartContent {
  479. /// temp targets
  480. ForEach(ChartTempTargets, id: \.self) { target in
  481. let targetLimited = min(max(target.amount, 0), upperLimit)
  482. RuleMark(
  483. xStart: .value("Start", target.start),
  484. xEnd: .value("End", target.end),
  485. y: .value("Value", targetLimited)
  486. )
  487. .foregroundStyle(Color.purple.opacity(0.5)).lineStyle(.init(lineWidth: 8))
  488. }
  489. }
  490. private func drawManualGlucose() -> some ChartContent {
  491. /// manual glucose mark
  492. ForEach(manualGlucose) { item in
  493. if let manualGlucose = item.glucose {
  494. PointMark(
  495. x: .value("Time", item.dateString, unit: .second),
  496. y: .value("Value", Decimal(manualGlucose) * conversionFactor)
  497. )
  498. .symbol {
  499. Image(systemName: "drop.fill").font(.system(size: 10)).symbolRenderingMode(.monochrome)
  500. .foregroundStyle(.red)
  501. }
  502. }
  503. }
  504. }
  505. private func drawSuspensions() -> some ChartContent {
  506. /// pump suspensions
  507. ForEach(suspensions) { suspension in
  508. let now = Date()
  509. if suspension.type == EventType.pumpSuspend {
  510. let suspensionStart = suspension.timestamp
  511. let suspensionEnd = min(
  512. suspensions
  513. .first(where: { $0.timestamp > suspension.timestamp && $0.type == EventType.pumpResume })?
  514. .timestamp ?? now,
  515. now
  516. )
  517. let basalProfileDuringSuspension = BasalProfiles.first(where: { $0.startDate <= suspensionStart })
  518. let suspensionMarkHeight = basalProfileDuringSuspension?.amount ?? 1
  519. RectangleMark(
  520. xStart: .value("start", suspensionStart),
  521. xEnd: .value("end", suspensionEnd),
  522. yStart: .value("suspend-start", 0),
  523. yEnd: .value("suspend-end", suspensionMarkHeight)
  524. )
  525. .foregroundStyle(Color.loopGray.opacity(colorScheme == .dark ? 0.3 : 0.8))
  526. }
  527. }
  528. }
  529. private func drawTempBasals() -> some ChartContent {
  530. /// temp basal rects
  531. ForEach(TempBasals) { temp in
  532. /// calculate end time of temp basal adding duration to start time
  533. let end = temp.timestamp + (temp.durationMin ?? 0).minutes.timeInterval
  534. let now = Date()
  535. /// ensure that temp basals that are set cannot exceed current date -> i.e. scheduled temp basals are not shown
  536. /// we could display scheduled temp basals with opacity etc... in the future
  537. let maxEndTime = min(end, now)
  538. /// set mark height to 0 when insulin delivery is suspended
  539. let isInsulinSuspended = suspensions
  540. .first(where: { $0.timestamp >= temp.timestamp && $0.timestamp <= maxEndTime }) != nil
  541. let rate = (temp.rate ?? 0) * (isInsulinSuspended ? 0 : 1)
  542. /// find next basal entry and if available set end of current entry to start of next entry
  543. if let nextTemp = TempBasals.first(where: { $0.timestamp > temp.timestamp }) {
  544. let nextTempStart = nextTemp.timestamp
  545. RectangleMark(
  546. xStart: .value("start", temp.timestamp),
  547. xEnd: .value("end", nextTempStart),
  548. yStart: .value("rate-start", 0),
  549. yEnd: .value("rate-end", rate)
  550. ).foregroundStyle(Color.insulin.opacity(0.2))
  551. LineMark(x: .value("Start Date", temp.timestamp), y: .value("Amount", rate))
  552. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  553. LineMark(x: .value("End Date", nextTempStart), y: .value("Amount", rate))
  554. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  555. } else {
  556. RectangleMark(
  557. xStart: .value("start", temp.timestamp),
  558. xEnd: .value("end", maxEndTime),
  559. yStart: .value("rate-start", 0),
  560. yEnd: .value("rate-end", rate)
  561. ).foregroundStyle(Color.insulin.opacity(0.2))
  562. LineMark(x: .value("Start Date", temp.timestamp), y: .value("Amount", rate))
  563. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  564. LineMark(x: .value("End Date", maxEndTime), y: .value("Amount", rate))
  565. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  566. }
  567. }
  568. }
  569. private func drawBasalProfile() -> some ChartContent {
  570. /// dashed profile line
  571. ForEach(BasalProfiles, id: \.self) { profile in
  572. LineMark(
  573. x: .value("Start Date", profile.startDate),
  574. y: .value("Amount", profile.amount),
  575. series: .value("profile", "profile")
  576. ).lineStyle(.init(lineWidth: 2, dash: [2, 4])).foregroundStyle(Color.insulin)
  577. LineMark(
  578. x: .value("End Date", profile.endDate ?? endMarker),
  579. y: .value("Amount", profile.amount),
  580. series: .value("profile", "profile")
  581. ).lineStyle(.init(lineWidth: 2.5, dash: [2, 4])).foregroundStyle(Color.insulin)
  582. }
  583. }
  584. /// calculates the glucose value thats the nearest to parameter 'time'
  585. /// if time is later than all the arrays values return the last element of BloodGlucose
  586. private func timeToNearestGlucose(time: TimeInterval) -> BloodGlucose {
  587. /// If the glucose array is empty, return a default BloodGlucose object or handle it accordingly
  588. guard let lastGlucose = glucose.last else {
  589. return BloodGlucose(
  590. date: 0,
  591. dateString: Date(),
  592. unfiltered: nil,
  593. filtered: nil,
  594. noise: nil,
  595. type: nil
  596. )
  597. }
  598. /// If the last glucose entry is before the specified time, return the last entry
  599. if lastGlucose.dateString.timeIntervalSince1970 < time {
  600. return lastGlucose
  601. }
  602. /// Find the index of the first element in the array whose date is greater than the specified time
  603. if let nextIndex = glucose.firstIndex(where: { $0.dateString.timeIntervalSince1970 > time }) {
  604. return glucose[nextIndex]
  605. } else {
  606. /// If no such element is found, return the last element in the array
  607. return lastGlucose
  608. }
  609. }
  610. private func fullWidth(viewWidth: CGFloat) -> CGFloat {
  611. viewWidth * CGFloat(hours) / CGFloat(min(max(screenHours, 2), 24))
  612. }
  613. /// calculations for temp target bar mark
  614. private func calculateTTs() {
  615. var groupedPackages: [[TempTarget]] = []
  616. var currentPackage: [TempTarget] = []
  617. var calculatedTTs: [ChartTempTarget] = []
  618. for target in tempTargets {
  619. if target.duration > 0 {
  620. if !currentPackage.isEmpty {
  621. groupedPackages.append(currentPackage)
  622. currentPackage = []
  623. }
  624. currentPackage.append(target)
  625. } else {
  626. if let lastNonZeroTempTarget = currentPackage.last(where: { $0.duration > 0 }) {
  627. if target.createdAt >= lastNonZeroTempTarget.createdAt,
  628. target.createdAt <= lastNonZeroTempTarget.createdAt
  629. .addingTimeInterval(TimeInterval(lastNonZeroTempTarget.duration * 60))
  630. {
  631. currentPackage.append(target)
  632. }
  633. }
  634. }
  635. }
  636. // appends last package, if exists
  637. if !currentPackage.isEmpty {
  638. groupedPackages.append(currentPackage)
  639. }
  640. for package in groupedPackages {
  641. guard let firstNonZeroTarget = package.first(where: { $0.duration > 0 }) else {
  642. continue
  643. }
  644. var end = firstNonZeroTarget.createdAt.addingTimeInterval(TimeInterval(firstNonZeroTarget.duration * 60))
  645. let earliestCancelTarget = package.filter({ $0.duration == 0 }).min(by: { $0.createdAt < $1.createdAt })
  646. if let earliestCancelTarget = earliestCancelTarget {
  647. end = min(earliestCancelTarget.createdAt, end)
  648. }
  649. let now = Date()
  650. isTempTargetActive = firstNonZeroTarget.createdAt <= now && now <= end
  651. if firstNonZeroTarget.targetTop != nil {
  652. calculatedTTs
  653. .append(ChartTempTarget(
  654. amount: (firstNonZeroTarget.targetTop ?? 0) * conversionFactor,
  655. start: firstNonZeroTarget.createdAt,
  656. end: end
  657. ))
  658. }
  659. }
  660. ChartTempTargets = calculatedTTs
  661. }
  662. private func addPredictions(_ predictions: [Int], type: PredictionType, deliveredAt: Date, endMarker: Date) -> [Prediction] {
  663. var calculatedPredictions: [Prediction] = []
  664. predictions.indices.forEach { index in
  665. let predTime = Date(
  666. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes.timeInterval
  667. )
  668. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  669. calculatedPredictions.append(
  670. Prediction(amount: predictions[index], timestamp: predTime, type: type)
  671. )
  672. }
  673. }
  674. return calculatedPredictions
  675. }
  676. private func calculatePredictions() {
  677. guard let suggestion = suggestion, let deliveredAt = suggestion.deliverAt else { return }
  678. let uamPredictions = suggestion.predictions?.uam ?? []
  679. let iobPredictions = suggestion.predictions?.iob ?? []
  680. let cobPredictions = suggestion.predictions?.cob ?? []
  681. let ztPredictions = suggestion.predictions?.zt ?? []
  682. let uam = addPredictions(uamPredictions, type: .uam, deliveredAt: deliveredAt, endMarker: endMarker)
  683. let iob = addPredictions(iobPredictions, type: .iob, deliveredAt: deliveredAt, endMarker: endMarker)
  684. let cob = addPredictions(cobPredictions, type: .cob, deliveredAt: deliveredAt, endMarker: endMarker)
  685. let zt = addPredictions(ztPredictions, type: .zt, deliveredAt: deliveredAt, endMarker: endMarker)
  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. }