MainChartView2.swift 29 KB

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