MainChartView.swift 35 KB

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