MainChartView.swift 38 KB

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