MainChartView2.swift 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  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 MainChartView2: 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. private var fpuFormatter: NumberFormatter {
  99. let formatter = NumberFormatter()
  100. formatter.numberStyle = .decimal
  101. formatter.maximumFractionDigits = 1
  102. formatter.decimalSeparator = "."
  103. formatter.minimumIntegerDigits = 0
  104. return formatter
  105. }
  106. var body: some View {
  107. VStack(alignment: .center, spacing: 8, content: {
  108. ScrollViewReader { scroller in
  109. ScrollView(.horizontal, showsIndicators: false) {
  110. VStack {
  111. BasalChart()
  112. MainChart()
  113. }.onChange(of: screenHours) { _ in
  114. scroller.scrollTo("MainChart", anchor: .trailing)
  115. }.onAppear {
  116. scroller.scrollTo("MainChart", anchor: .trailing)
  117. }.onChange(of: glucose) { _ in
  118. scroller.scrollTo("MainChart", anchor: .trailing)
  119. }
  120. .onChange(of: suggestion) { _ in
  121. scroller.scrollTo("MainChart", anchor: .trailing)
  122. }
  123. .onChange(of: tempBasals) { _ in
  124. scroller.scrollTo("MainChart", anchor: .trailing)
  125. }
  126. }
  127. }
  128. Legend().padding(.vertical, 4)
  129. })
  130. }
  131. }
  132. // MARK: Components
  133. extension MainChartView2 {
  134. private func MainChart() -> some View {
  135. VStack {
  136. Chart {
  137. if thresholdLines {
  138. RuleMark(y: .value("High", highGlucose)).foregroundStyle(Color.loopYellow)
  139. .lineStyle(.init(lineWidth: 1, dash: [2]))
  140. RuleMark(y: .value("Low", lowGlucose)).foregroundStyle(Color.loopRed)
  141. .lineStyle(.init(lineWidth: 1, dash: [2]))
  142. }
  143. RuleMark(
  144. x: .value(
  145. "",
  146. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  147. unit: .second
  148. )
  149. ).lineStyle(.init(lineWidth: 1, 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. 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(bolusFormatter.string(from: carbAmount as NSNumber)!).font(.caption2).foregroundStyle(Color.orange)
  174. }
  175. }
  176. ForEach(ChartFpus, id: \.self) { fpu in
  177. // let fpuAmount = fpu.amount
  178. PointMark(
  179. x: .value("Time", fpu.timestamp, unit: .second),
  180. y: .value("Value", fpu.nearestGlucose.sgv ?? 120)
  181. )
  182. // .symbolSize((Config.fpuSize + CGFloat(fpuAmount) * Config.carbsScale) * 10)
  183. .symbolSize(22)
  184. .foregroundStyle(Color.brown)
  185. }
  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. ForEach(ChartTempTargets, id: \.self) { tt in
  202. let randomString = UUID().uuidString
  203. LineMark(
  204. x: .value("Time", tt.start),
  205. y: .value("Value", tt.amount),
  206. series: .value("tt", randomString)
  207. )
  208. .foregroundStyle(Color.purple).lineStyle(.init(lineWidth: 8, dash: [2, 3]))
  209. LineMark(
  210. x: .value("Time", tt.end),
  211. y: .value("Value", tt.amount),
  212. series: .value("tt", randomString)
  213. )
  214. .foregroundStyle(Color.purple).lineStyle(.init(lineWidth: 8, dash: [2, 3]))
  215. }
  216. ForEach(Predictions, id: \.self) { info in
  217. if info.type == .uam {
  218. LineMark(
  219. x: .value("Time", info.timestamp, unit: .second),
  220. y: .value("Value", info.amount),
  221. series: .value("uam", "uam")
  222. ).foregroundStyle(Color.uam).symbolSize(16)
  223. }
  224. if info.type == .cob {
  225. LineMark(
  226. x: .value("Time", info.timestamp, unit: .second),
  227. y: .value("Value", info.amount),
  228. series: .value("cob", "cob")
  229. ).foregroundStyle(Color.orange).symbolSize(16)
  230. }
  231. if info.type == .iob {
  232. LineMark(
  233. x: .value("Time", info.timestamp, unit: .second),
  234. y: .value("Value", info.amount),
  235. series: .value("iob", "iob")
  236. ).foregroundStyle(Color.insulin).symbolSize(16)
  237. }
  238. if info.type == .zt {
  239. LineMark(
  240. x: .value("Time", info.timestamp, unit: .second),
  241. y: .value("Value", info.amount),
  242. series: .value("zt", "zt")
  243. ).foregroundStyle(Color.zt).symbolSize(16)
  244. }
  245. }
  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) { _ in
  263. calculatePredictions()
  264. }
  265. .onChange(of: carbs) { _ in
  266. calculateCarbs()
  267. calculateFpus()
  268. }
  269. .onChange(of: boluses) { _ in
  270. calculateBoluses()
  271. }
  272. .onChange(of: tempTargets) { _ in
  273. calculateTTs()
  274. }
  275. .onChange(of: didAppearTrigger) { _ in
  276. calculatePredictions()
  277. calculateTTs()
  278. }.onChange(of: suggestion) { _ in
  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 / 3.3
  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.5, 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(position: .trailing) { value in
  304. if displayYgridLines {
  305. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  306. } else {
  307. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  308. }
  309. if let glucoseValue = value.as(Double.self), glucoseValue > 0 {
  310. AxisTick(length: 4, stroke: .init(lineWidth: 4))
  311. .foregroundStyle(Color.gray)
  312. AxisValueLabel()
  313. }
  314. }
  315. }
  316. }
  317. }
  318. func BasalChart() -> some View {
  319. VStack {
  320. Chart {
  321. RuleMark(
  322. x: .value(
  323. "",
  324. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  325. unit: .second
  326. )
  327. ).lineStyle(.init(lineWidth: 1, dash: [2]))
  328. RuleMark(
  329. x: .value(
  330. "",
  331. startMarker,
  332. unit: .second
  333. )
  334. ).foregroundStyle(Color.clear)
  335. RuleMark(
  336. x: .value(
  337. "",
  338. endMarker,
  339. unit: .second
  340. )
  341. ).foregroundStyle(Color.clear)
  342. ForEach(TempBasals) {
  343. BarMark(
  344. x: .value("Time", $0.timestamp),
  345. y: .value("Rate", $0.rate ?? 0)
  346. )
  347. }
  348. ForEach(BasalProfiles, id: \.self) { profile in
  349. LineMark(
  350. x: .value("Start Date", profile.startDate),
  351. y: .value("Amount", profile.amount),
  352. series: .value("profile", "profile")
  353. ).lineStyle(.init(lineWidth: 2, dash: [2, 3]))
  354. LineMark(
  355. x: .value("End Date", profile.endDate ?? endMarker),
  356. y: .value("Amount", profile.amount),
  357. series: .value("profile", "profile")
  358. ).lineStyle(.init(lineWidth: 2, dash: [2, 3]))
  359. }
  360. }.onChange(of: tempBasals) { _ in
  361. calculateBasals()
  362. calculateTempBasals()
  363. }
  364. .onChange(of: maxBasal) { _ in
  365. calculateBasals()
  366. calculateTempBasals()
  367. }
  368. .onChange(of: autotunedBasalProfile) { _ in
  369. calculateBasals()
  370. calculateTempBasals()
  371. }
  372. .onChange(of: didAppearTrigger) { _ in
  373. calculateBasals()
  374. calculateTempBasals()
  375. }.onChange(of: basalProfile) { _ in
  376. calculateBasals()
  377. calculateTempBasals()
  378. }
  379. .frame(
  380. width: max(0, screenSize.width - 20, fullWidth(viewWidth: screenSize.width)),
  381. height: UIScreen.main.bounds.height / 10.5
  382. )
  383. .rotationEffect(.degrees(180))
  384. .scaleEffect(x: -1, y: 1)
  385. .chartXScale(domain: startMarker ... endMarker)
  386. .chartXAxis(.hidden)
  387. .chartXAxis {
  388. AxisMarks(values: .stride(by: .hour, count: screenHours == 24 ? 4 : 2)) { _ in
  389. if displayXgridLines {
  390. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  391. } else {
  392. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  393. }
  394. // AxisValueLabel(format: .dateTime.hour(.defaultDigits(amPM: .narrow)), anchor: .top)
  395. // AxisValueLabel(format: .dateTime.hour())
  396. }
  397. }
  398. .chartYAxis {
  399. AxisMarks(position: .trailing) { _ in
  400. if displayYgridLines {
  401. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  402. } else {
  403. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  404. }
  405. AxisTick(length: 30, stroke: .init(lineWidth: 4))
  406. .foregroundStyle(Color.clear)
  407. }
  408. }
  409. }
  410. }
  411. private func Legend() -> some View {
  412. ZStack {
  413. Capsule(style: .circular).foregroundStyle(.gray.opacity(0.1)).padding(.horizontal, 30).frame(maxHeight: 15)
  414. HStack {
  415. Image(systemName: "line.diagonal")
  416. .fontWeight(.bold)
  417. .rotationEffect(Angle(degrees: 45))
  418. .foregroundColor(.green)
  419. Text("BG")
  420. .foregroundColor(.secondary)
  421. Spacer()
  422. Image(systemName: "line.diagonal")
  423. .fontWeight(.bold)
  424. .rotationEffect(Angle(degrees: 45))
  425. .foregroundColor(.insulin)
  426. Text("IOB")
  427. .foregroundColor(.secondary)
  428. Spacer()
  429. Image(systemName: "line.diagonal")
  430. .fontWeight(.bold)
  431. .rotationEffect(Angle(degrees: 45))
  432. .foregroundColor(.purple)
  433. Text("ZT")
  434. .foregroundColor(.secondary)
  435. Spacer()
  436. Image(systemName: "line.diagonal")
  437. .fontWeight(.bold)
  438. .frame(height: 10)
  439. .rotationEffect(Angle(degrees: 45))
  440. .foregroundColor(.loopYellow)
  441. Text("COB")
  442. .foregroundColor(.secondary)
  443. Spacer()
  444. Image(systemName: "line.diagonal")
  445. .fontWeight(.bold)
  446. .rotationEffect(Angle(degrees: 45))
  447. .foregroundColor(.orange)
  448. Text("UAM")
  449. .foregroundColor(.secondary)
  450. if eventualBG != nil {
  451. Text("⇢ " + String(eventualBG ?? 0))
  452. }
  453. }
  454. .font(.caption2)
  455. .padding(.horizontal, 40)
  456. .padding(.vertical, 1)
  457. }
  458. }
  459. }
  460. // MARK: Calculations
  461. extension MainChartView2 {
  462. private func timeToNearestGlucose(time: TimeInterval) -> BloodGlucose {
  463. var nextIndex = 0
  464. if glucose.last?.dateString.timeIntervalSince1970 ?? Date().timeIntervalSince1970 < time {
  465. return glucose.last ?? BloodGlucose(
  466. date: 0,
  467. dateString: Date(),
  468. unfiltered: nil,
  469. filtered: nil,
  470. noise: nil,
  471. type: nil
  472. )
  473. }
  474. for (index, value) in glucose.enumerated() {
  475. if value.dateString.timeIntervalSince1970 > time {
  476. nextIndex = index
  477. print("Break", value.dateString.timeIntervalSince1970, time)
  478. break
  479. }
  480. }
  481. return glucose[nextIndex]
  482. }
  483. private func fullWidth(viewWidth: CGFloat) -> CGFloat {
  484. viewWidth * CGFloat(hours) / CGFloat(min(max(screenHours, 2), 24))
  485. }
  486. private func calculateCarbs() {
  487. var calculatedCarbs: [Carb] = []
  488. carbs.forEach { carb in
  489. let bg = timeToNearestGlucose(time: carb.createdAt.timeIntervalSince1970)
  490. let yPosition = (bg.sgv ?? 120) - 30
  491. calculatedCarbs.append(Carb(amount: carb.carbs, timestamp: carb.createdAt, nearestGlucose: bg, yPosition: yPosition))
  492. }
  493. ChartCarbs = calculatedCarbs
  494. }
  495. private func calculateFpus() {
  496. var calculatedFpus: [Carb] = []
  497. let fpus = carbs.filter { $0.isFPU ?? false }
  498. let yPosition = 120
  499. fpus.forEach { fpu in
  500. let bg = timeToNearestGlucose(time: fpu.createdAt.timeIntervalSince1970)
  501. calculatedFpus
  502. .append(Carb(amount: fpu.carbs, timestamp: fpu.actualDate ?? Date(), nearestGlucose: bg, yPosition: yPosition))
  503. }
  504. ChartFpus = calculatedFpus
  505. }
  506. private func calculateBoluses() {
  507. var calculatedBoluses: [ChartBolus] = []
  508. boluses.forEach { bolus in
  509. let bg = timeToNearestGlucose(time: bolus.timestamp.timeIntervalSince1970)
  510. let yPosition = (bg.sgv ?? 120) + 30
  511. calculatedBoluses
  512. .append(ChartBolus(
  513. amount: bolus.amount ?? 0,
  514. timestamp: bolus.timestamp,
  515. nearestGlucose: bg,
  516. yPosition: yPosition
  517. ))
  518. }
  519. ChartBoluses = calculatedBoluses
  520. }
  521. private func calculateTTs() {
  522. var calculatedTTs: [ChartTempTarget] = []
  523. tempTargets.forEach { tt in
  524. let end = tt.createdAt.addingTimeInterval(TimeInterval(tt.duration * 60))
  525. if tt.targetTop != nil {
  526. calculatedTTs
  527. .append(ChartTempTarget(amount: tt.targetTop ?? 0, start: tt.createdAt, end: end))
  528. }
  529. }
  530. ChartTempTargets = calculatedTTs
  531. }
  532. private func calculatePredictions() {
  533. var calculatedPredictions: [Prediction] = []
  534. let uam = suggestion?.predictions?.uam ?? []
  535. let iob = suggestion?.predictions?.iob ?? []
  536. let cob = suggestion?.predictions?.cob ?? []
  537. let zt = suggestion?.predictions?.zt ?? []
  538. guard let deliveredAt = suggestion?.deliverAt else {
  539. return
  540. }
  541. uam.indices.forEach { index in
  542. let predTime = Date(
  543. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  544. .timeInterval
  545. )
  546. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  547. calculatedPredictions.append(
  548. Prediction(amount: uam[index], timestamp: predTime, type: .uam)
  549. )
  550. }
  551. }
  552. iob.indices.forEach { index in
  553. let predTime = Date(
  554. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  555. .timeInterval
  556. )
  557. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  558. calculatedPredictions.append(
  559. Prediction(amount: iob[index], timestamp: predTime, type: .iob)
  560. )
  561. }
  562. }
  563. cob.indices.forEach { index in
  564. let predTime = Date(
  565. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  566. .timeInterval
  567. )
  568. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  569. calculatedPredictions.append(
  570. Prediction(amount: cob[index], timestamp: predTime, type: .cob)
  571. )
  572. }
  573. }
  574. zt.indices.forEach { index in
  575. let predTime = Date(
  576. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  577. .timeInterval
  578. )
  579. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  580. calculatedPredictions.append(
  581. Prediction(amount: zt[index], timestamp: predTime, type: .zt)
  582. )
  583. }
  584. }
  585. Predictions = calculatedPredictions
  586. }
  587. private func getLastUam() -> Int {
  588. let uam = suggestion?.predictions?.uam ?? []
  589. return uam.last ?? 0
  590. }
  591. private func calculateTempBasals() {
  592. var basals = tempBasals
  593. var returnTempBasalRates: [PumpHistoryEvent] = []
  594. var finished: [Int: Bool] = [:]
  595. basals.indices.forEach { i in
  596. basals.indices.forEach { j in
  597. if basals[i].timestamp == basals[j].timestamp, i != j, !(finished[i] ?? false), !(finished[j] ?? false) {
  598. let rate = basals[i].rate ?? basals[j].rate
  599. let durationMin = basals[i].durationMin ?? basals[j].durationMin
  600. finished[i] = true
  601. if rate != 0 || durationMin != 0 {
  602. returnTempBasalRates.append(
  603. PumpHistoryEvent(
  604. id: basals[i].id, type: FreeAPS.EventType.tempBasal,
  605. timestamp: basals[i].timestamp,
  606. durationMin: durationMin,
  607. rate: rate
  608. )
  609. )
  610. }
  611. }
  612. }
  613. }
  614. TempBasals = returnTempBasalRates
  615. }
  616. private func findRegularBasalPoints(
  617. timeBegin: TimeInterval,
  618. timeEnd: TimeInterval,
  619. autotuned: Bool
  620. ) -> [BasalProfile] {
  621. guard timeBegin < timeEnd else {
  622. return []
  623. }
  624. let beginDate = Date(timeIntervalSince1970: timeBegin)
  625. let calendar = Calendar.current
  626. let startOfDay = calendar.startOfDay(for: beginDate)
  627. let profile = autotuned ? autotunedBasalProfile : basalProfile
  628. let basalNormalized = profile.map {
  629. (
  630. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  631. rate: $0.rate
  632. )
  633. } + profile.map {
  634. (
  635. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval)
  636. .timeIntervalSince1970,
  637. rate: $0.rate
  638. )
  639. } + profile.map {
  640. (
  641. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 2.days.timeInterval)
  642. .timeIntervalSince1970,
  643. rate: $0.rate
  644. )
  645. }
  646. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  647. .compactMap { window -> BasalProfile? in
  648. let window = Array(window)
  649. if window[0].time < timeBegin, window[1].time < timeBegin {
  650. return nil
  651. }
  652. if window[0].time < timeBegin, window[1].time >= timeBegin {
  653. let startDate = Date(timeIntervalSince1970: timeBegin)
  654. let rate = window[0].rate
  655. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  656. }
  657. if window[0].time >= timeBegin, window[0].time < timeEnd {
  658. let startDate = Date(timeIntervalSince1970: window[0].time)
  659. let rate = window[0].rate
  660. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  661. }
  662. return nil
  663. }
  664. return basalTruncatedPoints
  665. }
  666. private func calculateBasals() {
  667. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  668. let firstTempTime = (tempBasals.first?.timestamp ?? Date()).timeIntervalSince1970
  669. let regularPoints = findRegularBasalPoints(
  670. timeBegin: dayAgoTime,
  671. timeEnd: endMarker.timeIntervalSince1970,
  672. autotuned: false
  673. )
  674. let autotunedBasalPoints = findRegularBasalPoints(
  675. timeBegin: dayAgoTime,
  676. timeEnd: endMarker.timeIntervalSince1970,
  677. autotuned: true
  678. )
  679. var totalBasal = regularPoints + autotunedBasalPoints
  680. totalBasal.sort {
  681. $0.startDate.timeIntervalSince1970 < $1.startDate.timeIntervalSince1970
  682. }
  683. var basals: [BasalProfile] = []
  684. totalBasal.indices.forEach { index in
  685. basals.append(BasalProfile(
  686. amount: totalBasal[index].amount,
  687. isOverwritten: totalBasal[index].isOverwritten,
  688. startDate: totalBasal[index].startDate,
  689. endDate: totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker
  690. ))
  691. print(
  692. "Basal",
  693. totalBasal[index].startDate,
  694. totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker,
  695. totalBasal[index].amount,
  696. totalBasal[index].isOverwritten
  697. )
  698. }
  699. BasalProfiles = basals
  700. }
  701. }