MainChartView.swift 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  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. @State var didAppearTrigger = false
  74. @State private var BasalProfiles: [BasalProfile] = []
  75. @State private var TempBasals: [PumpHistoryEvent] = []
  76. @State private var ChartTempTargets: [ChartTempTarget] = []
  77. @State private var Predictions: [Prediction] = []
  78. @State private var ChartCarbs: [Carb] = []
  79. @State private var ChartFpus: [Carb] = []
  80. @State private var ChartBoluses: [ChartBolus] = []
  81. @State private var count: Decimal = 1
  82. @State private var startMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 - 86400))
  83. @State private var endMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 + 10800))
  84. private var bolusFormatter: NumberFormatter {
  85. let formatter = NumberFormatter()
  86. formatter.numberStyle = .decimal
  87. formatter.minimumIntegerDigits = 0
  88. formatter.maximumFractionDigits = 2
  89. formatter.decimalSeparator = "."
  90. return formatter
  91. }
  92. private var carbsFormatter: NumberFormatter {
  93. let formatter = NumberFormatter()
  94. formatter.numberStyle = .decimal
  95. formatter.maximumFractionDigits = 0
  96. return formatter
  97. }
  98. var body: some View {
  99. VStack {
  100. ScrollViewReader { scroller in
  101. ScrollView(.horizontal, showsIndicators: false) {
  102. VStack {
  103. BasalChart()
  104. MainChart()
  105. }.onChange(of: screenHours) {
  106. updateStartEndMarkers()
  107. scroller.scrollTo("MainChart", anchor: .trailing)
  108. }.onChange(of: glucose) {
  109. updateStartEndMarkers()
  110. scroller.scrollTo("MainChart", anchor: .trailing)
  111. }
  112. .onChange(of: suggestion) {
  113. updateStartEndMarkers()
  114. scroller.scrollTo("MainChart", anchor: .trailing)
  115. }
  116. .onChange(of: tempBasals) {
  117. updateStartEndMarkers()
  118. scroller.scrollTo("MainChart", anchor: .trailing)
  119. }
  120. .onAppear {
  121. updateStartEndMarkers()
  122. scroller.scrollTo("MainChart", anchor: .trailing)
  123. }
  124. }
  125. }
  126. // Legend().padding(.vertical, 4)
  127. }
  128. }
  129. }
  130. // MARK: Components
  131. extension MainChartView {
  132. private func MainChart() -> some View {
  133. VStack {
  134. Chart {
  135. /// high and low treshold lines
  136. if thresholdLines {
  137. RuleMark(y: .value("High", highGlucose)).foregroundStyle(Color.loopYellow)
  138. .lineStyle(.init(lineWidth: 2, dash: [2]))
  139. RuleMark(y: .value("Low", lowGlucose)).foregroundStyle(Color.loopRed)
  140. .lineStyle(.init(lineWidth: 2, dash: [2]))
  141. }
  142. RuleMark(
  143. x: .value(
  144. "",
  145. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  146. unit: .second
  147. )
  148. ).lineStyle(.init(lineWidth: 2, dash: [2]))
  149. RuleMark(
  150. x: .value(
  151. "",
  152. startMarker,
  153. unit: .second
  154. )
  155. ).foregroundStyle(Color.clear)
  156. RuleMark(
  157. x: .value(
  158. "",
  159. endMarker,
  160. unit: .second
  161. )
  162. ).foregroundStyle(Color.clear)
  163. /// carbs
  164. ForEach(ChartCarbs, id: \.self) { carb in
  165. let carbAmount = carb.amount
  166. PointMark(
  167. x: .value("Time", carb.timestamp, unit: .second),
  168. y: .value("Value", carb.yPosition)
  169. )
  170. .symbolSize((Config.carbsSize + CGFloat(carbAmount) * Config.carbsScale) * 10)
  171. .foregroundStyle(Color.orange)
  172. .annotation(position: .bottom) {
  173. Text(carbsFormatter.string(from: carbAmount as NSNumber)!).font(.caption2).foregroundStyle(Color.orange)
  174. }
  175. }
  176. /// fpus
  177. ForEach(ChartFpus, id: \.self) { fpu in
  178. PointMark(
  179. x: .value("Time", fpu.timestamp, unit: .second),
  180. y: .value("Value", fpu.nearestGlucose.sgv ?? 120)
  181. )
  182. .symbolSize(22)
  183. .foregroundStyle(Color.brown)
  184. }
  185. /// smbs in triangle form
  186. ForEach(ChartBoluses, id: \.self) { bolus in
  187. let bolusAmount = bolus.amount
  188. let size = (Config.bolusSize + CGFloat(bolusAmount) * Config.bolusScale) * 1.8
  189. PointMark(
  190. x: .value("Time", bolus.timestamp, unit: .second),
  191. y: .value("Value", bolus.yPosition)
  192. )
  193. .symbol {
  194. Image(systemName: "arrowtriangle.down.fill").font(.system(size: size))
  195. }
  196. .foregroundStyle(Color.blue.gradient)
  197. .annotation(position: .top) {
  198. Text(bolusFormatter.string(from: bolusAmount as NSNumber)!).font(.caption2).foregroundStyle(Color.insulin)
  199. }
  200. }
  201. /// temp targets
  202. ForEach(tempTargets, id: \.self) { tt in
  203. let duration = tt.duration
  204. let end = tt.createdAt.addingTimeInterval(TimeInterval(duration * 60))
  205. RuleMark(
  206. xStart: .value("Start", tt.createdAt),
  207. xEnd: .value("End", end),
  208. y: .value("Value", tt.targetTop ?? 0)
  209. )
  210. .foregroundStyle(Color.purple).lineStyle(.init(lineWidth: 8, dash: [2, 3]))
  211. }
  212. /// predictions
  213. ForEach(Predictions, id: \.self) { info in
  214. /// ensure that there are no values below 0 in the chart
  215. let yValue = max(info.amount, 0)
  216. if info.type == .uam {
  217. LineMark(
  218. x: .value("Time", info.timestamp, unit: .second),
  219. y: .value("Value", yValue),
  220. series: .value("uam", "uam")
  221. ).foregroundStyle(Color.uam).symbolSize(16)
  222. }
  223. if info.type == .cob {
  224. LineMark(
  225. x: .value("Time", info.timestamp, unit: .second),
  226. y: .value("Value", yValue),
  227. series: .value("cob", "cob")
  228. ).foregroundStyle(Color.orange).symbolSize(16)
  229. }
  230. if info.type == .iob {
  231. LineMark(
  232. x: .value("Time", info.timestamp, unit: .second),
  233. y: .value("Value", yValue),
  234. series: .value("iob", "iob")
  235. ).foregroundStyle(Color.insulin).symbolSize(16)
  236. }
  237. if info.type == .zt {
  238. LineMark(
  239. x: .value("Time", info.timestamp, unit: .second),
  240. y: .value("Value", yValue),
  241. series: .value("zt", "zt")
  242. ).foregroundStyle(Color.zt).symbolSize(16)
  243. }
  244. }
  245. /// glucose point mark
  246. ForEach(glucose) {
  247. if let sgv = $0.sgv {
  248. PointMark(
  249. x: .value("Time", $0.dateString, unit: .second),
  250. y: .value("Value", sgv)
  251. ).foregroundStyle(Color.green.gradient).symbolSize(25)
  252. if smooth {
  253. LineMark(
  254. x: .value("Time", $0.dateString, unit: .second),
  255. y: .value("Value", sgv)
  256. ).foregroundStyle(Color.green.gradient).symbolSize(25)
  257. .interpolationMethod(.cardinal)
  258. }
  259. }
  260. }
  261. }.id("MainChart")
  262. .onChange(of: glucose) {
  263. calculatePredictions()
  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. extension MainChartView {
  446. private func timeToNearestGlucose(time: TimeInterval) -> BloodGlucose {
  447. var nextIndex = 0
  448. if glucose.last?.dateString.timeIntervalSince1970 ?? Date().timeIntervalSince1970 < time {
  449. return glucose.last ?? BloodGlucose(
  450. date: 0,
  451. dateString: Date(),
  452. unfiltered: nil,
  453. filtered: nil,
  454. noise: nil,
  455. type: nil
  456. )
  457. }
  458. for (index, value) in glucose.enumerated() {
  459. if value.dateString.timeIntervalSince1970 > time {
  460. nextIndex = index
  461. print("Break", value.dateString.timeIntervalSince1970, time)
  462. break
  463. }
  464. }
  465. return glucose[nextIndex]
  466. }
  467. private func fullWidth(viewWidth: CGFloat) -> CGFloat {
  468. viewWidth * CGFloat(hours) / CGFloat(min(max(screenHours, 2), 24))
  469. }
  470. private func calculateCarbs() {
  471. var calculatedCarbs: [Carb] = []
  472. carbs.forEach { carb in
  473. let bg = timeToNearestGlucose(time: carb.createdAt.timeIntervalSince1970)
  474. let yPosition = (bg.sgv ?? 120) - 30
  475. calculatedCarbs.append(Carb(amount: carb.carbs, timestamp: carb.createdAt, nearestGlucose: bg, yPosition: yPosition))
  476. }
  477. ChartCarbs = calculatedCarbs
  478. }
  479. private func calculateFpus() {
  480. var calculatedFpus: [Carb] = []
  481. let fpus = carbs.filter { $0.isFPU ?? false }
  482. let yPosition = 120
  483. fpus.forEach { fpu in
  484. let bg = timeToNearestGlucose(time: fpu.createdAt.timeIntervalSince1970)
  485. calculatedFpus
  486. .append(Carb(amount: fpu.carbs, timestamp: fpu.actualDate ?? Date(), nearestGlucose: bg, yPosition: yPosition))
  487. }
  488. ChartFpus = calculatedFpus
  489. }
  490. private func calculateBoluses() {
  491. var calculatedBoluses: [ChartBolus] = []
  492. boluses.forEach { bolus in
  493. let bg = timeToNearestGlucose(time: bolus.timestamp.timeIntervalSince1970)
  494. let yPosition = (bg.sgv ?? 120) + 30
  495. calculatedBoluses
  496. .append(ChartBolus(
  497. amount: bolus.amount ?? 0,
  498. timestamp: bolus.timestamp,
  499. nearestGlucose: bg,
  500. yPosition: yPosition
  501. ))
  502. }
  503. ChartBoluses = calculatedBoluses
  504. }
  505. private func calculateTTs() {
  506. var calculatedTTs: [ChartTempTarget] = []
  507. tempTargets.forEach { tt in
  508. let end = tt.createdAt.addingTimeInterval(TimeInterval(tt.duration * 60))
  509. if tt.targetTop != nil {
  510. calculatedTTs
  511. .append(ChartTempTarget(amount: tt.targetTop ?? 0, start: tt.createdAt, end: end))
  512. }
  513. }
  514. ChartTempTargets = calculatedTTs
  515. }
  516. private func calculatePredictions() {
  517. var calculatedPredictions: [Prediction] = []
  518. let uam = suggestion?.predictions?.uam ?? []
  519. let iob = suggestion?.predictions?.iob ?? []
  520. let cob = suggestion?.predictions?.cob ?? []
  521. let zt = suggestion?.predictions?.zt ?? []
  522. guard let deliveredAt = suggestion?.deliverAt else {
  523. return
  524. }
  525. uam.indices.forEach { index in
  526. let predTime = Date(
  527. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  528. .timeInterval
  529. )
  530. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  531. calculatedPredictions.append(
  532. Prediction(amount: uam[index], timestamp: predTime, type: .uam)
  533. )
  534. }
  535. }
  536. iob.indices.forEach { index in
  537. let predTime = Date(
  538. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  539. .timeInterval
  540. )
  541. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  542. calculatedPredictions.append(
  543. Prediction(amount: iob[index], timestamp: predTime, type: .iob)
  544. )
  545. }
  546. }
  547. cob.indices.forEach { index in
  548. let predTime = Date(
  549. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  550. .timeInterval
  551. )
  552. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  553. calculatedPredictions.append(
  554. Prediction(amount: cob[index], timestamp: predTime, type: .cob)
  555. )
  556. }
  557. }
  558. zt.indices.forEach { index in
  559. let predTime = Date(
  560. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  561. .timeInterval
  562. )
  563. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  564. calculatedPredictions.append(
  565. Prediction(amount: zt[index], timestamp: predTime, type: .zt)
  566. )
  567. }
  568. }
  569. Predictions = calculatedPredictions
  570. }
  571. private func getLastUam() -> Int {
  572. let uam = suggestion?.predictions?.uam ?? []
  573. return uam.last ?? 0
  574. }
  575. private func calculateTempBasals() {
  576. var basals = tempBasals
  577. var returnTempBasalRates: [PumpHistoryEvent] = []
  578. var finished: [Int: Bool] = [:]
  579. basals.indices.forEach { i in
  580. basals.indices.forEach { j in
  581. if basals[i].timestamp == basals[j].timestamp, i != j, !(finished[i] ?? false), !(finished[j] ?? false) {
  582. let rate = basals[i].rate ?? basals[j].rate
  583. let durationMin = basals[i].durationMin ?? basals[j].durationMin
  584. finished[i] = true
  585. if rate != 0 || durationMin != 0 {
  586. returnTempBasalRates.append(
  587. PumpHistoryEvent(
  588. id: basals[i].id, type: FreeAPS.EventType.tempBasal,
  589. timestamp: basals[i].timestamp,
  590. durationMin: durationMin,
  591. rate: rate
  592. )
  593. )
  594. }
  595. }
  596. }
  597. }
  598. TempBasals = returnTempBasalRates
  599. }
  600. private func findRegularBasalPoints(
  601. timeBegin: TimeInterval,
  602. timeEnd: TimeInterval,
  603. autotuned: Bool
  604. ) -> [BasalProfile] {
  605. guard timeBegin < timeEnd else {
  606. return []
  607. }
  608. let beginDate = Date(timeIntervalSince1970: timeBegin)
  609. let calendar = Calendar.current
  610. let startOfDay = calendar.startOfDay(for: beginDate)
  611. let profile = autotuned ? autotunedBasalProfile : basalProfile
  612. let basalNormalized = profile.map {
  613. (
  614. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  615. rate: $0.rate
  616. )
  617. } + profile.map {
  618. (
  619. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval)
  620. .timeIntervalSince1970,
  621. rate: $0.rate
  622. )
  623. } + profile.map {
  624. (
  625. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 2.days.timeInterval)
  626. .timeIntervalSince1970,
  627. rate: $0.rate
  628. )
  629. }
  630. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  631. .compactMap { window -> BasalProfile? in
  632. let window = Array(window)
  633. if window[0].time < timeBegin, window[1].time < timeBegin {
  634. return nil
  635. }
  636. if window[0].time < timeBegin, window[1].time >= timeBegin {
  637. let startDate = Date(timeIntervalSince1970: timeBegin)
  638. let rate = window[0].rate
  639. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  640. }
  641. if window[0].time >= timeBegin, window[0].time < timeEnd {
  642. let startDate = Date(timeIntervalSince1970: window[0].time)
  643. let rate = window[0].rate
  644. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  645. }
  646. return nil
  647. }
  648. return basalTruncatedPoints
  649. }
  650. ///update start and end marker to fix scroll update problem with x axis
  651. private func updateStartEndMarkers() {
  652. startMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 - 86400))
  653. endMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 + 10800))
  654. }
  655. private func calculateBasals() {
  656. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  657. let firstTempTime = (tempBasals.first?.timestamp ?? Date()).timeIntervalSince1970
  658. let regularPoints = findRegularBasalPoints(
  659. timeBegin: dayAgoTime,
  660. timeEnd: endMarker.timeIntervalSince1970,
  661. autotuned: false
  662. )
  663. let autotunedBasalPoints = findRegularBasalPoints(
  664. timeBegin: dayAgoTime,
  665. timeEnd: endMarker.timeIntervalSince1970,
  666. autotuned: true
  667. )
  668. var totalBasal = regularPoints + autotunedBasalPoints
  669. totalBasal.sort {
  670. $0.startDate.timeIntervalSince1970 < $1.startDate.timeIntervalSince1970
  671. }
  672. var basals: [BasalProfile] = []
  673. totalBasal.indices.forEach { index in
  674. basals.append(BasalProfile(
  675. amount: totalBasal[index].amount,
  676. isOverwritten: totalBasal[index].isOverwritten,
  677. startDate: totalBasal[index].startDate,
  678. endDate: totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker
  679. ))
  680. print(
  681. "Basal",
  682. totalBasal[index].startDate,
  683. totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker,
  684. totalBasal[index].amount,
  685. totalBasal[index].isOverwritten
  686. )
  687. }
  688. BasalProfiles = basals
  689. }
  690. }