MainChartView.swift 36 KB

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