MainChartView2.swift 29 KB

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