MainChartView.swift 37 KB

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