MainChartView.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  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. }
  52. @Binding var glucose: [BloodGlucose]
  53. @Binding var eventualBG: Int?
  54. @Binding var suggestion: Suggestion?
  55. @Binding var tempBasals: [PumpHistoryEvent]
  56. @Binding var boluses: [PumpHistoryEvent]
  57. @Binding var suspensions: [PumpHistoryEvent]
  58. @Binding var announcement: [Announcement]
  59. @Binding var hours: Int
  60. @Binding var maxBasal: Decimal
  61. @Binding var autotunedBasalProfile: [BasalProfileEntry]
  62. @Binding var basalProfile: [BasalProfileEntry]
  63. @Binding var tempTargets: [TempTarget]
  64. @Binding var carbs: [CarbsEntry]
  65. @Binding var smooth: Bool
  66. @Binding var highGlucose: Decimal
  67. @Binding var lowGlucose: Decimal
  68. @Binding var screenHours: Int16
  69. @Binding var displayXgridLines: Bool
  70. @Binding var displayYgridLines: Bool
  71. @Binding var thresholdLines: Bool
  72. @State var didAppearTrigger = false
  73. @State private var BasalProfiles: [BasalProfile] = []
  74. @State private var TempBasals: [PumpHistoryEvent] = []
  75. @State private var ChartTempTargets: [ChartTempTarget] = []
  76. @State private var Predictions: [Prediction] = []
  77. @State private var ChartCarbs: [Carb] = []
  78. @State private var ChartFpus: [Carb] = []
  79. @State private var ChartBoluses: [ChartBolus] = []
  80. @State private var count: Decimal = 1
  81. @State private var startMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 - 86400))
  82. @State private var endMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 + 10800))
  83. private var bolusFormatter: NumberFormatter {
  84. let formatter = NumberFormatter()
  85. formatter.numberStyle = .decimal
  86. formatter.minimumIntegerDigits = 0
  87. formatter.maximumFractionDigits = 2
  88. formatter.decimalSeparator = "."
  89. return formatter
  90. }
  91. private var carbsFormatter: NumberFormatter {
  92. let formatter = NumberFormatter()
  93. formatter.numberStyle = .decimal
  94. formatter.maximumFractionDigits = 0
  95. return formatter
  96. }
  97. var body: some View {
  98. VStack {
  99. ScrollViewReader { scroller in
  100. ScrollView(.horizontal, showsIndicators: false) {
  101. VStack {
  102. BasalChart()
  103. MainChart()
  104. }.onChange(of: screenHours) {
  105. updateStartEndMarkers()
  106. scroller.scrollTo("MainChart", anchor: .trailing)
  107. }.onChange(of: glucose) {
  108. updateStartEndMarkers()
  109. scroller.scrollTo("MainChart", anchor: .trailing)
  110. }
  111. .onChange(of: suggestion) {
  112. updateStartEndMarkers()
  113. scroller.scrollTo("MainChart", anchor: .trailing)
  114. }
  115. .onChange(of: tempBasals) {
  116. updateStartEndMarkers()
  117. scroller.scrollTo("MainChart", anchor: .trailing)
  118. }
  119. .onAppear {
  120. updateStartEndMarkers()
  121. scroller.scrollTo("MainChart", anchor: .trailing)
  122. }
  123. }
  124. }
  125. // Legend().padding(.vertical, 4)
  126. }
  127. }
  128. }
  129. // MARK: Components
  130. extension MainChartView {
  131. private func MainChart() -> some View {
  132. VStack {
  133. Chart {
  134. /// high and low treshold lines
  135. if thresholdLines {
  136. RuleMark(y: .value("High", highGlucose)).foregroundStyle(Color.loopYellow)
  137. .lineStyle(.init(lineWidth: 2, dash: [2]))
  138. RuleMark(y: .value("Low", lowGlucose)).foregroundStyle(Color.loopRed)
  139. .lineStyle(.init(lineWidth: 2, dash: [2]))
  140. }
  141. RuleMark(
  142. x: .value(
  143. "",
  144. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  145. unit: .second
  146. )
  147. ).lineStyle(.init(lineWidth: 2, dash: [2]))
  148. RuleMark(
  149. x: .value(
  150. "",
  151. startMarker,
  152. unit: .second
  153. )
  154. ).foregroundStyle(Color.clear)
  155. RuleMark(
  156. x: .value(
  157. "",
  158. endMarker,
  159. unit: .second
  160. )
  161. ).foregroundStyle(Color.clear)
  162. /// carbs
  163. ForEach(ChartCarbs, id: \.self) { carb in
  164. let carbAmount = carb.amount
  165. PointMark(
  166. x: .value("Time", carb.timestamp, unit: .second),
  167. y: .value("Value", 40)
  168. )
  169. .symbolSize((Config.carbsSize + CGFloat(carbAmount) * Config.carbsScale) * 10)
  170. .foregroundStyle(Color.orange)
  171. .annotation(position: .bottom) {
  172. Text(carbsFormatter.string(from: carbAmount as NSNumber)!).font(.caption2).foregroundStyle(Color.orange)
  173. }
  174. }
  175. /// fpus
  176. ForEach(ChartFpus, id: \.self) { fpu in
  177. let fpuAmount = fpu.amount
  178. let size = (Config.fpuSize + CGFloat(fpuAmount) * Config.carbsScale) * 1.8
  179. PointMark(
  180. x: .value("Time", fpu.timestamp, unit: .second),
  181. y: .value("Value", 40)
  182. )
  183. .symbolSize(size)
  184. .foregroundStyle(Color.brown)
  185. }
  186. /// smbs in triangle form
  187. ForEach(ChartBoluses, id: \.self) { bolus in
  188. let bolusAmount = bolus.amount
  189. let size = (Config.bolusSize + CGFloat(bolusAmount) * Config.bolusScale) * 1.8
  190. PointMark(
  191. x: .value("Time", bolus.timestamp, unit: .second),
  192. y: .value("Value", bolus.yPosition)
  193. )
  194. .symbol {
  195. Image(systemName: "arrowtriangle.down.fill").font(.system(size: size))
  196. }
  197. .foregroundStyle(Color.blue.gradient)
  198. .annotation(position: .top) {
  199. Text(bolusFormatter.string(from: bolusAmount as NSNumber)!).font(.caption2).foregroundStyle(Color.insulin)
  200. }
  201. }
  202. /// temp targets
  203. ForEach(ChartTempTargets, id: \.self) { tt in
  204. BarMark(
  205. xStart:.value("Time", tt.start),
  206. xEnd: .value("Time", tt.end),
  207. y: .value("Value", tt.amount)
  208. )
  209. .foregroundStyle(Color.purple.opacity(0.3)).lineStyle(.init(lineWidth: 8, dash: [2, 3]))
  210. }
  211. /// predictions
  212. ForEach(Predictions, id: \.self) { info in
  213. /// ensure that there are no values below 0 in the chart
  214. let yValue = max(info.amount, 0)
  215. if info.type == .uam {
  216. LineMark(
  217. x: .value("Time", info.timestamp, unit: .second),
  218. y: .value("Value", yValue),
  219. series: .value("uam", "uam")
  220. ).foregroundStyle(Color.uam).symbolSize(16)
  221. }
  222. if info.type == .cob {
  223. LineMark(
  224. x: .value("Time", info.timestamp, unit: .second),
  225. y: .value("Value", yValue),
  226. series: .value("cob", "cob")
  227. ).foregroundStyle(Color.orange).symbolSize(16)
  228. }
  229. if info.type == .iob {
  230. LineMark(
  231. x: .value("Time", info.timestamp, unit: .second),
  232. y: .value("Value", yValue),
  233. series: .value("iob", "iob")
  234. ).foregroundStyle(Color.insulin).symbolSize(16)
  235. }
  236. if info.type == .zt {
  237. LineMark(
  238. x: .value("Time", info.timestamp, unit: .second),
  239. y: .value("Value", yValue),
  240. series: .value("zt", "zt")
  241. ).foregroundStyle(Color.zt).symbolSize(16)
  242. }
  243. }
  244. /// glucose point mark
  245. ForEach(glucose) {
  246. if let sgv = $0.sgv {
  247. PointMark(
  248. x: .value("Time", $0.dateString, unit: .second),
  249. y: .value("Value", sgv)
  250. ).foregroundStyle(Color.green.gradient).symbolSize(25)
  251. if smooth {
  252. LineMark(
  253. x: .value("Time", $0.dateString, unit: .second),
  254. y: .value("Value", sgv)
  255. ).foregroundStyle(Color.green.gradient).symbolSize(25)
  256. .interpolationMethod(.cardinal)
  257. }
  258. }
  259. }
  260. }.id("MainChart")
  261. .onChange(of: glucose) {
  262. calculatePredictions()
  263. calculateFpus()
  264. }
  265. .onChange(of: carbs) {
  266. calculateCarbs()
  267. calculateFpus()
  268. }
  269. .onChange(of: boluses) {
  270. calculateBoluses()
  271. }
  272. .onChange(of: tempTargets) {
  273. calculateTTs()
  274. }
  275. .onChange(of: didAppearTrigger) {
  276. calculatePredictions()
  277. calculateTTs()
  278. }.onChange(of: suggestion) {
  279. calculatePredictions()
  280. }
  281. .onReceive(
  282. Foundation.NotificationCenter.default
  283. .publisher(for: UIApplication.willEnterForegroundNotification)
  284. ) { _ in
  285. calculatePredictions()
  286. }
  287. .frame(
  288. width: max(0, screenSize.width - 20, fullWidth(viewWidth: screenSize.width)),
  289. height: UIScreen.main.bounds.height / 2.9
  290. )
  291. .chartXScale(domain: startMarker ... endMarker)
  292. .chartXAxis {
  293. AxisMarks(values: .stride(by: .hour, count: screenHours == 24 ? 4 : 2)) { _ in
  294. if displayXgridLines {
  295. AxisGridLine(stroke: .init(lineWidth: 0.3, dash: [2, 3]))
  296. } else {
  297. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  298. }
  299. AxisValueLabel(format: .dateTime.hour(.defaultDigits(amPM: .narrow)), anchor: .top)
  300. }
  301. }
  302. .chartYAxis {
  303. AxisMarks { _ in
  304. if displayYgridLines {
  305. AxisGridLine(stroke: .init(lineWidth: 0.3, dash: [2, 3]))
  306. } else {
  307. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  308. }
  309. AxisTick(length: 4, stroke: .init(lineWidth: 4)).foregroundStyle(Color.gray)
  310. AxisValueLabel()
  311. }
  312. }
  313. }
  314. }
  315. func BasalChart() -> some View {
  316. VStack {
  317. Chart {
  318. RuleMark(
  319. x: .value(
  320. "",
  321. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  322. unit: .second
  323. )
  324. ).lineStyle(.init(lineWidth: 2, dash: [2]))
  325. RuleMark(
  326. x: .value(
  327. "",
  328. startMarker,
  329. unit: .second
  330. )
  331. ).foregroundStyle(Color.clear)
  332. RuleMark(
  333. x: .value(
  334. "",
  335. endMarker,
  336. unit: .second
  337. )
  338. ).foregroundStyle(Color.clear)
  339. ForEach(TempBasals) {
  340. BarMark(
  341. x: .value("Time", $0.timestamp),
  342. y: .value("Rate", $0.rate ?? 0)
  343. )
  344. }
  345. ForEach(BasalProfiles, id: \.self) { profile in
  346. LineMark(
  347. x: .value("Start Date", profile.startDate),
  348. y: .value("Amount", profile.amount),
  349. series: .value("profile", "profile")
  350. ).lineStyle(.init(lineWidth: 2, dash: [2, 3]))
  351. LineMark(
  352. x: .value("End Date", profile.endDate ?? endMarker),
  353. y: .value("Amount", profile.amount),
  354. series: .value("profile", "profile")
  355. ).lineStyle(.init(lineWidth: 2.5, dash: [2, 3]))
  356. }
  357. }.onChange(of: tempBasals) {
  358. calculateBasals()
  359. calculateTempBasals()
  360. }
  361. .onChange(of: maxBasal) {
  362. calculateBasals()
  363. calculateTempBasals()
  364. }
  365. .onChange(of: autotunedBasalProfile) {
  366. calculateBasals()
  367. calculateTempBasals()
  368. }
  369. .onChange(of: didAppearTrigger) {
  370. calculateBasals()
  371. calculateTempBasals()
  372. }.onChange(of: basalProfile) {
  373. calculateTempBasals()
  374. }
  375. .frame(
  376. width: max(0, screenSize.width - 20, fullWidth(viewWidth: screenSize.width)),
  377. height: UIScreen.main.bounds.height / 10.5
  378. )
  379. .rotationEffect(.degrees(180))
  380. .scaleEffect(x: -1, y: 1)
  381. .chartXScale(domain: startMarker ... endMarker)
  382. .chartXAxis(.hidden)
  383. .chartXAxis {
  384. AxisMarks(values: .stride(by: .hour, count: screenHours == 24 ? 4 : 2)) { _ in
  385. }
  386. }
  387. .chartYAxis {
  388. AxisMarks(position: .trailing) { _ in
  389. AxisTick(length: 30, stroke: .init(lineWidth: 4))
  390. .foregroundStyle(Color.clear)
  391. }
  392. }
  393. }
  394. }
  395. private func Legend() -> some View {
  396. ZStack {
  397. Capsule(style: .circular).foregroundStyle(.gray.opacity(0.1)).padding(.horizontal, 30).frame(maxHeight: 15)
  398. HStack {
  399. Image(systemName: "line.diagonal")
  400. .fontWeight(.bold)
  401. .rotationEffect(Angle(degrees: 45))
  402. .foregroundColor(.green)
  403. Text("BG")
  404. .foregroundColor(.secondary)
  405. Spacer()
  406. Image(systemName: "line.diagonal")
  407. .fontWeight(.bold)
  408. .rotationEffect(Angle(degrees: 45))
  409. .foregroundColor(.insulin)
  410. Text("IOB")
  411. .foregroundColor(.secondary)
  412. Spacer()
  413. Image(systemName: "line.diagonal")
  414. .fontWeight(.bold)
  415. .rotationEffect(Angle(degrees: 45))
  416. .foregroundColor(.purple)
  417. Text("ZT")
  418. .foregroundColor(.secondary)
  419. Spacer()
  420. Image(systemName: "line.diagonal")
  421. .fontWeight(.bold)
  422. .frame(height: 10)
  423. .rotationEffect(Angle(degrees: 45))
  424. .foregroundColor(.loopYellow)
  425. Text("COB")
  426. .foregroundColor(.secondary)
  427. Spacer()
  428. Image(systemName: "line.diagonal")
  429. .fontWeight(.bold)
  430. .rotationEffect(Angle(degrees: 45))
  431. .foregroundColor(.orange)
  432. Text("UAM")
  433. .foregroundColor(.secondary)
  434. if eventualBG != nil {
  435. Text("⇢ " + String(eventualBG ?? 0))
  436. }
  437. }
  438. .font(.caption2)
  439. .padding(.horizontal, 40)
  440. .padding(.vertical, 1)
  441. }
  442. }
  443. }
  444. // MARK: Calculations
  445. ///calculates the glucose value thats the nearest to parameter 'time'
  446. ///if time is later than all the arrays values return the last element of BloodGlucose
  447. extension MainChartView {
  448. private func timeToNearestGlucose(time: TimeInterval) -> BloodGlucose {
  449. var nextIndex = 0
  450. if glucose.last?.dateString.timeIntervalSince1970 ?? Date().timeIntervalSince1970 < time {
  451. return glucose.last ?? BloodGlucose(
  452. date: 0,
  453. dateString: Date(),
  454. unfiltered: nil,
  455. filtered: nil,
  456. noise: nil,
  457. type: nil
  458. )
  459. }
  460. for (index, value) in glucose.enumerated() {
  461. if value.dateString.timeIntervalSince1970 > time {
  462. nextIndex = index
  463. print("Break", value.dateString.timeIntervalSince1970, time)
  464. break
  465. }
  466. }
  467. return glucose[nextIndex]
  468. }
  469. private func fullWidth(viewWidth: CGFloat) -> CGFloat {
  470. viewWidth * CGFloat(hours) / CGFloat(min(max(screenHours, 2), 24))
  471. }
  472. private func calculateCarbs() {
  473. var calculatedCarbs: [Carb] = []
  474. ///check if carbs are not fpus before adding them to the chart
  475. ///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
  476. let realCarbs = carbs.filter { !($0.isFPU ?? false) }
  477. realCarbs.forEach { carb in
  478. let bg = timeToNearestGlucose(time: carb.createdAt.timeIntervalSince1970)
  479. calculatedCarbs.append(Carb(amount: carb.carbs, timestamp: carb.createdAt, nearestGlucose: bg))
  480. }
  481. ChartCarbs = calculatedCarbs
  482. }
  483. private func calculateFpus() {
  484. var calculatedFpus: [Carb] = []
  485. ///check for only fpus
  486. let fpus = carbs.filter { $0.isFPU ?? false }
  487. fpus.forEach { fpu in
  488. let bg = timeToNearestGlucose(time: TimeInterval(rawValue: (fpu.actualDate?.timeIntervalSince1970)!) ?? fpu.createdAt.timeIntervalSince1970)
  489. calculatedFpus
  490. .append(Carb(amount: fpu.carbs, timestamp: fpu.actualDate ?? Date(), nearestGlucose: bg))
  491. }
  492. ChartFpus = calculatedFpus
  493. }
  494. private func calculateBoluses() {
  495. var calculatedBoluses: [ChartBolus] = []
  496. boluses.forEach { bolus in
  497. let bg = timeToNearestGlucose(time: bolus.timestamp.timeIntervalSince1970)
  498. let yPosition = (bg.sgv ?? 120) + 30
  499. calculatedBoluses
  500. .append(ChartBolus(
  501. amount: bolus.amount ?? 0,
  502. timestamp: bolus.timestamp,
  503. nearestGlucose: bg,
  504. yPosition: yPosition
  505. ))
  506. }
  507. ChartBoluses = calculatedBoluses
  508. }
  509. ///calculations for temp target bar mark
  510. ///it is now quite complicated because the remove function in TempTargetStorage does not actually remove the current temp target but instead creates a new temp target with a duration of 0 minutes
  511. ///therefore it is necessary to check if a temp target was cancelled, i.e. the last temp target in the temp target array has a duration of 0 and then remove the last TWO elements of the array
  512. private func calculateTTs() {
  513. var calculatedTTs: [ChartTempTarget] = []
  514. ///check if last element has a duration of 0
  515. if let lastTempTarget = tempTargets.last, lastTempTarget.duration == 0 {
  516. ///remove the last TWO elements if the last element has a duration of 0
  517. let filteredTempTargets = Array(tempTargets.dropLast(2))
  518. ///use filtered temp targets for calculation
  519. calculatedTTs = filteredTempTargets.compactMap { tt in
  520. guard let targetTop = tt.targetTop else { return nil }
  521. let end = tt.createdAt.addingTimeInterval(TimeInterval(tt.duration * 60))
  522. return ChartTempTarget(amount: targetTop, start: tt.createdAt, end: end)
  523. }
  524. } else {
  525. ///if the last temp target has NOT a duration of 0 use unfiltered temp targets for calculation
  526. calculatedTTs = tempTargets.compactMap { tt in
  527. guard let targetTop = tt.targetTop else { return nil }
  528. let end = tt.createdAt.addingTimeInterval(TimeInterval(tt.duration * 60))
  529. return ChartTempTarget(amount: targetTop, start: tt.createdAt, end: end)
  530. }
  531. }
  532. ChartTempTargets = calculatedTTs
  533. }
  534. private func calculatePredictions() {
  535. var calculatedPredictions: [Prediction] = []
  536. let uam = suggestion?.predictions?.uam ?? []
  537. let iob = suggestion?.predictions?.iob ?? []
  538. let cob = suggestion?.predictions?.cob ?? []
  539. let zt = suggestion?.predictions?.zt ?? []
  540. guard let deliveredAt = suggestion?.deliverAt else {
  541. return
  542. }
  543. uam.indices.forEach { index in
  544. let predTime = Date(
  545. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  546. .timeInterval
  547. )
  548. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  549. calculatedPredictions.append(
  550. Prediction(amount: uam[index], timestamp: predTime, type: .uam)
  551. )
  552. }
  553. }
  554. iob.indices.forEach { index in
  555. let predTime = Date(
  556. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  557. .timeInterval
  558. )
  559. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  560. calculatedPredictions.append(
  561. Prediction(amount: iob[index], timestamp: predTime, type: .iob)
  562. )
  563. }
  564. }
  565. cob.indices.forEach { index in
  566. let predTime = Date(
  567. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  568. .timeInterval
  569. )
  570. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  571. calculatedPredictions.append(
  572. Prediction(amount: cob[index], timestamp: predTime, type: .cob)
  573. )
  574. }
  575. }
  576. zt.indices.forEach { index in
  577. let predTime = Date(
  578. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  579. .timeInterval
  580. )
  581. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  582. calculatedPredictions.append(
  583. Prediction(amount: zt[index], timestamp: predTime, type: .zt)
  584. )
  585. }
  586. }
  587. Predictions = calculatedPredictions
  588. }
  589. private func getLastUam() -> Int {
  590. let uam = suggestion?.predictions?.uam ?? []
  591. return uam.last ?? 0
  592. }
  593. private func calculateTempBasals() {
  594. var basals = tempBasals
  595. var returnTempBasalRates: [PumpHistoryEvent] = []
  596. var finished: [Int: Bool] = [:]
  597. basals.indices.forEach { i in
  598. basals.indices.forEach { j in
  599. if basals[i].timestamp == basals[j].timestamp, i != j, !(finished[i] ?? false), !(finished[j] ?? false) {
  600. let rate = basals[i].rate ?? basals[j].rate
  601. let durationMin = basals[i].durationMin ?? basals[j].durationMin
  602. finished[i] = true
  603. if rate != 0 || durationMin != 0 {
  604. returnTempBasalRates.append(
  605. PumpHistoryEvent(
  606. id: basals[i].id, type: FreeAPS.EventType.tempBasal,
  607. timestamp: basals[i].timestamp,
  608. durationMin: durationMin,
  609. rate: rate
  610. )
  611. )
  612. }
  613. }
  614. }
  615. }
  616. TempBasals = returnTempBasalRates
  617. }
  618. private func findRegularBasalPoints(
  619. timeBegin: TimeInterval,
  620. timeEnd: TimeInterval,
  621. autotuned: Bool
  622. ) -> [BasalProfile] {
  623. guard timeBegin < timeEnd else {
  624. return []
  625. }
  626. let beginDate = Date(timeIntervalSince1970: timeBegin)
  627. let calendar = Calendar.current
  628. let startOfDay = calendar.startOfDay(for: beginDate)
  629. let profile = autotuned ? autotunedBasalProfile : basalProfile
  630. let basalNormalized = profile.map {
  631. (
  632. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  633. rate: $0.rate
  634. )
  635. } + profile.map {
  636. (
  637. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval)
  638. .timeIntervalSince1970,
  639. rate: $0.rate
  640. )
  641. } + profile.map {
  642. (
  643. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 2.days.timeInterval)
  644. .timeIntervalSince1970,
  645. rate: $0.rate
  646. )
  647. }
  648. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  649. .compactMap { window -> BasalProfile? in
  650. let window = Array(window)
  651. if window[0].time < timeBegin, window[1].time < timeBegin {
  652. return nil
  653. }
  654. if window[0].time < timeBegin, window[1].time >= timeBegin {
  655. let startDate = Date(timeIntervalSince1970: timeBegin)
  656. let rate = window[0].rate
  657. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  658. }
  659. if window[0].time >= timeBegin, window[0].time < timeEnd {
  660. let startDate = Date(timeIntervalSince1970: window[0].time)
  661. let rate = window[0].rate
  662. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  663. }
  664. return nil
  665. }
  666. return basalTruncatedPoints
  667. }
  668. ///update start and end marker to fix scroll update problem with x axis
  669. private func updateStartEndMarkers() {
  670. startMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 - 86400))
  671. endMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 + 10800))
  672. }
  673. private func calculateBasals() {
  674. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  675. let firstTempTime = (tempBasals.first?.timestamp ?? Date()).timeIntervalSince1970
  676. let regularPoints = findRegularBasalPoints(
  677. timeBegin: dayAgoTime,
  678. timeEnd: endMarker.timeIntervalSince1970,
  679. autotuned: false
  680. )
  681. let autotunedBasalPoints = findRegularBasalPoints(
  682. timeBegin: dayAgoTime,
  683. timeEnd: endMarker.timeIntervalSince1970,
  684. autotuned: true
  685. )
  686. var totalBasal = regularPoints + autotunedBasalPoints
  687. totalBasal.sort {
  688. $0.startDate.timeIntervalSince1970 < $1.startDate.timeIntervalSince1970
  689. }
  690. var basals: [BasalProfile] = []
  691. totalBasal.indices.forEach { index in
  692. basals.append(BasalProfile(
  693. amount: totalBasal[index].amount,
  694. isOverwritten: totalBasal[index].isOverwritten,
  695. startDate: totalBasal[index].startDate,
  696. endDate: totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker
  697. ))
  698. print(
  699. "Basal",
  700. totalBasal[index].startDate,
  701. totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker,
  702. totalBasal[index].amount,
  703. totalBasal[index].isOverwritten
  704. )
  705. }
  706. BasalProfiles = basals
  707. }
  708. }