MainChartView2.swift 28 KB

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