MainChartView.swift 30 KB

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