MainChartView.swift 36 KB

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