MainChartView2.swift 28 KB

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