MainChartView.swift 38 KB

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