MainChartView.swift 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  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 MainChartView: View {
  45. private enum Config {
  46. static let bolusSize: CGFloat = 5
  47. static let bolusScale: CGFloat = 1
  48. static let carbsSize: CGFloat = 5
  49. static let carbsScale: CGFloat = 0.3
  50. static let fpuSize: CGFloat = 10
  51. static let maxGlucose = 270
  52. static let minGlucose = 45
  53. }
  54. @Binding var glucose: [BloodGlucose]
  55. @Binding var units: GlucoseUnits
  56. @Binding var eventualBG: Int?
  57. @Binding var suggestion: Suggestion?
  58. @Binding var tempBasals: [PumpHistoryEvent]
  59. @Binding var boluses: [PumpHistoryEvent]
  60. @Binding var suspensions: [PumpHistoryEvent]
  61. @Binding var announcement: [Announcement]
  62. @Binding var hours: Int
  63. @Binding var maxBasal: Decimal
  64. @Binding var autotunedBasalProfile: [BasalProfileEntry]
  65. @Binding var basalProfile: [BasalProfileEntry]
  66. @Binding var tempTargets: [TempTarget]
  67. @Binding var carbs: [CarbsEntry]
  68. @Binding var smooth: Bool
  69. @Binding var highGlucose: Decimal
  70. @Binding var lowGlucose: Decimal
  71. @Binding var screenHours: Int16
  72. @Binding var displayXgridLines: Bool
  73. @Binding var displayYgridLines: Bool
  74. @Binding var thresholdLines: Bool
  75. @Binding var isTempTargetActive: Bool
  76. @StateObject var state = Home.StateModel()
  77. @State var didAppearTrigger = false
  78. @State private var BasalProfiles: [BasalProfile] = []
  79. @State private var TempBasals: [PumpHistoryEvent] = []
  80. @State private var ChartTempTargets: [ChartTempTarget] = []
  81. @State private var Predictions: [Prediction] = []
  82. @State private var ChartCarbs: [Carb] = []
  83. @State private var ChartFpus: [Carb] = []
  84. @State private var ChartBoluses: [ChartBolus] = []
  85. @State private var count: Decimal = 1
  86. @State private var startMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 - 86400))
  87. @State private var endMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 + 10800))
  88. @State private var glucoseUpdateCount = 0
  89. @State private var maxUpdateCount = 12
  90. @State private var minValue: Int = 45
  91. @State private var maxValue: Int = 270
  92. private var bolusFormatter: NumberFormatter {
  93. let formatter = NumberFormatter()
  94. formatter.numberStyle = .decimal
  95. formatter.minimumIntegerDigits = 0
  96. formatter.maximumFractionDigits = 2
  97. formatter.decimalSeparator = "."
  98. return formatter
  99. }
  100. private var carbsFormatter: NumberFormatter {
  101. let formatter = NumberFormatter()
  102. formatter.numberStyle = .decimal
  103. formatter.maximumFractionDigits = 0
  104. return formatter
  105. }
  106. var body: some View {
  107. VStack {
  108. ScrollViewReader { scroller in
  109. ScrollView(.horizontal, showsIndicators: false) {
  110. VStack(spacing: -0.00002) {
  111. BasalChart()
  112. MainChart()
  113. }.onChange(of: screenHours) { _ in
  114. updateStartEndMarkers()
  115. scroller.scrollTo("MainChart", anchor: .trailing)
  116. }.onChange(of: glucose) { _ in
  117. updateStartEndMarkers()
  118. scroller.scrollTo("MainChart", anchor: .trailing)
  119. }
  120. .onChange(of: suggestion) { _ in
  121. updateStartEndMarkers()
  122. scroller.scrollTo("MainChart", anchor: .trailing)
  123. }
  124. .onChange(of: tempBasals) { _ in
  125. updateStartEndMarkers()
  126. scroller.scrollTo("MainChart", anchor: .trailing)
  127. }
  128. .onAppear {
  129. updateStartEndMarkers()
  130. scroller.scrollTo("MainChart", anchor: .trailing)
  131. }
  132. }
  133. }
  134. legendPanel.padding(.top, 8)
  135. }
  136. }
  137. }
  138. // MARK: Components
  139. extension MainChartView {
  140. private func MainChart() -> some View {
  141. VStack {
  142. Chart {
  143. /// high and low treshold lines
  144. if thresholdLines {
  145. RuleMark(y: .value("High", highGlucose)).foregroundStyle(Color.loopYellow)
  146. .lineStyle(.init(lineWidth: 2, dash: [2]))
  147. RuleMark(y: .value("Low", lowGlucose)).foregroundStyle(Color.loopRed)
  148. .lineStyle(.init(lineWidth: 2, dash: [2]))
  149. }
  150. RuleMark(
  151. x: .value(
  152. "",
  153. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  154. unit: .second
  155. )
  156. ).lineStyle(.init(lineWidth: 2, dash: [2])).foregroundStyle(Color.insulin)
  157. RuleMark(
  158. x: .value(
  159. "",
  160. startMarker,
  161. unit: .second
  162. )
  163. ).foregroundStyle(Color.clear)
  164. RuleMark(
  165. x: .value(
  166. "",
  167. endMarker,
  168. unit: .second
  169. )
  170. ).foregroundStyle(Color.clear)
  171. /// carbs
  172. ForEach(ChartCarbs, id: \.self) { carb in
  173. let carbAmount = carb.amount
  174. PointMark(
  175. x: .value("Time", carb.timestamp, unit: .second),
  176. y: .value("Value", 60)
  177. )
  178. .symbolSize((Config.carbsSize + CGFloat(carbAmount) * Config.carbsScale) * 10)
  179. .foregroundStyle(Color.orange)
  180. .annotation(position: .bottom) {
  181. Text(carbsFormatter.string(from: carbAmount as NSNumber)!).font(.caption2).foregroundStyle(Color.orange)
  182. }
  183. }
  184. /// fpus
  185. ForEach(ChartFpus, id: \.self) { fpu in
  186. let fpuAmount = fpu.amount
  187. let size = (Config.fpuSize + CGFloat(fpuAmount) * Config.carbsScale) * 1.8
  188. PointMark(
  189. x: .value("Time", fpu.timestamp, unit: .second),
  190. y: .value("Value", 60)
  191. )
  192. .symbolSize(size)
  193. .foregroundStyle(Color.brown)
  194. }
  195. /// smbs in triangle form
  196. ForEach(ChartBoluses, id: \.self) { bolus in
  197. let bolusAmount = bolus.amount
  198. let size = (Config.bolusSize + CGFloat(bolusAmount) * Config.bolusScale) * 1.8
  199. PointMark(
  200. x: .value("Time", bolus.timestamp, unit: .second),
  201. y: .value("Value", bolus.yPosition)
  202. )
  203. .symbol {
  204. Image(systemName: "arrowtriangle.down.fill").font(.system(size: size))
  205. }
  206. .foregroundStyle(Color.insulin)
  207. .annotation(position: .top) {
  208. Text(bolusFormatter.string(from: bolusAmount as NSNumber)!).font(.caption2).foregroundStyle(Color.insulin)
  209. }
  210. }
  211. /// temp targets
  212. ForEach(ChartTempTargets, id: \.self) { target in
  213. RuleMark(
  214. xStart: .value("Start", target.start),
  215. xEnd: .value("End", target.end),
  216. y: .value("Value", target.amount)
  217. )
  218. .foregroundStyle(Color.purple.opacity(0.5)).lineStyle(.init(lineWidth: 8))
  219. }
  220. /// predictions
  221. ForEach(Predictions, id: \.self) { info in
  222. /// ensure that there are no values below 0 in the chart
  223. let yValue = max(info.amount, 0)
  224. if info.type == .uam {
  225. LineMark(
  226. x: .value("Time", info.timestamp, unit: .second),
  227. y: .value("Value", yValue),
  228. series: .value("uam", "uam")
  229. ).foregroundStyle(Color.uam).symbolSize(16)
  230. }
  231. if info.type == .cob {
  232. LineMark(
  233. x: .value("Time", info.timestamp, unit: .second),
  234. y: .value("Value", yValue),
  235. series: .value("cob", "cob")
  236. ).foregroundStyle(Color.orange).symbolSize(16)
  237. }
  238. if info.type == .iob {
  239. LineMark(
  240. x: .value("Time", info.timestamp, unit: .second),
  241. y: .value("Value", yValue),
  242. series: .value("iob", "iob")
  243. ).foregroundStyle(Color.insulin).symbolSize(16)
  244. }
  245. if info.type == .zt {
  246. LineMark(
  247. x: .value("Time", info.timestamp, unit: .second),
  248. y: .value("Value", yValue),
  249. series: .value("zt", "zt")
  250. ).foregroundStyle(Color.zt).symbolSize(16)
  251. }
  252. }
  253. /// glucose point mark
  254. /// filtering for high and low bounds in settings
  255. ForEach(glucose.filter { $0.sgv ?? 0 > Int(highGlucose) }) { item in
  256. if let sgv = item.sgv {
  257. PointMark(
  258. x: .value("Time", item.dateString, unit: .second),
  259. y: .value("Value", sgv)
  260. ).foregroundStyle(Color.orange.gradient).symbolSize(25)
  261. if smooth {
  262. PointMark(
  263. x: .value("Time", item.dateString, unit: .second),
  264. y: .value("Value", sgv)
  265. ).foregroundStyle(Color.orange.gradient).symbolSize(25)
  266. .interpolationMethod(.cardinal)
  267. }
  268. }
  269. }
  270. ForEach(glucose.filter { $0.sgv ?? 0 < Int(lowGlucose) }) { item in
  271. if let sgv = item.sgv {
  272. PointMark(
  273. x: .value("Time", item.dateString, unit: .second),
  274. y: .value("Value", sgv)
  275. ).foregroundStyle(Color.red.gradient).symbolSize(25)
  276. if smooth {
  277. PointMark(
  278. x: .value("Time", item.dateString, unit: .second),
  279. y: .value("Value", sgv)
  280. ).foregroundStyle(Color.red.gradient).symbolSize(25)
  281. .interpolationMethod(.cardinal)
  282. }
  283. }
  284. }
  285. ForEach(glucose.filter { $0.sgv ?? 0 >= Int(lowGlucose) && $0.sgv ?? 0 <= Int(highGlucose) }) { item in
  286. if let sgv = item.sgv {
  287. PointMark(
  288. x: .value("Time", item.dateString, unit: .second),
  289. y: .value("Value", sgv)
  290. ).foregroundStyle(Color.green.gradient).symbolSize(25)
  291. if smooth {
  292. PointMark(
  293. x: .value("Time", item.dateString, unit: .second),
  294. y: .value("Value", sgv)
  295. ).foregroundStyle(Color.green.gradient).symbolSize(25)
  296. .interpolationMethod(.cardinal)
  297. }
  298. }
  299. }
  300. }.id("MainChart")
  301. .onChange(of: glucose) { _ in
  302. calculatePredictions()
  303. calculateFpus()
  304. counter()
  305. }
  306. .onChange(of: carbs) { _ in
  307. calculateCarbs()
  308. calculateFpus()
  309. }
  310. .onChange(of: boluses) { _ in
  311. calculateBoluses()
  312. state.roundedTotalBolus = state.calculateTINS()
  313. }
  314. .onChange(of: tempTargets) { _ in
  315. calculateTTs()
  316. }
  317. .onChange(of: didAppearTrigger) { _ in
  318. calculatePredictions()
  319. calculateTTs()
  320. }.onChange(of: suggestion) { _ in
  321. calculatePredictions()
  322. }
  323. .onReceive(
  324. Foundation.NotificationCenter.default
  325. .publisher(for: UIApplication.willEnterForegroundNotification)
  326. ) { _ in
  327. calculatePredictions()
  328. }
  329. .frame(
  330. minHeight: UIScreen.main.bounds.height / 3
  331. )
  332. .frame(width: fullWidth(viewWidth: screenSize.width))
  333. .chartYScale(domain: minValue ... maxValue)
  334. .chartXScale(domain: startMarker ... endMarker)
  335. .chartXAxis {
  336. AxisMarks(values: .stride(by: .hour, count: screenHours == 24 ? 4 : 2)) { _ in
  337. if displayXgridLines {
  338. AxisGridLine(stroke: .init(lineWidth: 0.3, dash: [2, 3]))
  339. } else {
  340. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  341. }
  342. AxisValueLabel(format: .dateTime.hour(.defaultDigits(amPM: .narrow)), anchor: .top)
  343. }
  344. }
  345. .chartYAxis {
  346. AxisMarks { _ in
  347. if displayYgridLines {
  348. AxisGridLine(stroke: .init(lineWidth: 0.3, dash: [2, 3]))
  349. } else {
  350. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  351. }
  352. AxisValueLabel()
  353. }
  354. }
  355. }
  356. }
  357. func BasalChart() -> some View {
  358. VStack {
  359. Chart {
  360. RuleMark(
  361. x: .value(
  362. "",
  363. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  364. unit: .second
  365. )
  366. ).lineStyle(.init(lineWidth: 2, dash: [2])).foregroundStyle(Color.insulin)
  367. RuleMark(
  368. x: .value(
  369. "",
  370. startMarker,
  371. unit: .second
  372. )
  373. ).foregroundStyle(Color.clear)
  374. RuleMark(
  375. x: .value(
  376. "",
  377. endMarker,
  378. unit: .second
  379. )
  380. ).foregroundStyle(Color.clear)
  381. ForEach(TempBasals) {
  382. BarMark(
  383. x: .value("Time", $0.timestamp),
  384. y: .value("Rate", $0.rate ?? 0)
  385. ).foregroundStyle(Color.insulin)
  386. }
  387. ForEach(BasalProfiles, id: \.self) { profile in
  388. LineMark(
  389. x: .value("Start Date", profile.startDate),
  390. y: .value("Amount", profile.amount),
  391. series: .value("profile", "profile")
  392. ).lineStyle(.init(lineWidth: 2, dash: [2, 3])).foregroundStyle(Color.insulin)
  393. LineMark(
  394. x: .value("End Date", profile.endDate ?? endMarker),
  395. y: .value("Amount", profile.amount),
  396. series: .value("profile", "profile")
  397. ).lineStyle(.init(lineWidth: 2.5, dash: [2, 3])).foregroundStyle(Color.insulin)
  398. }
  399. }.onChange(of: tempBasals) { _ in
  400. calculateBasals()
  401. calculateTempBasals()
  402. }
  403. .onChange(of: maxBasal) { _ in
  404. calculateBasals()
  405. calculateTempBasals()
  406. }
  407. .onChange(of: autotunedBasalProfile) { _ in
  408. calculateBasals()
  409. calculateTempBasals()
  410. }
  411. .onChange(of: didAppearTrigger) { _ in
  412. calculateBasals()
  413. calculateTempBasals()
  414. }.onChange(of: basalProfile) { _ in
  415. calculateTempBasals()
  416. }
  417. .frame(
  418. minHeight: UIScreen.main.bounds.height / 10
  419. )
  420. .frame(width: fullWidth(viewWidth: screenSize.width))
  421. .rotationEffect(.degrees(180))
  422. .scaleEffect(x: -1, y: 1)
  423. .chartXScale(domain: startMarker ... endMarker)
  424. .chartXAxis(.hidden)
  425. .chartXAxis {
  426. AxisMarks(values: .stride(by: .hour, count: screenHours == 24 ? 4 : 2)) { _ in
  427. }
  428. }
  429. .chartYAxis {
  430. AxisMarks(position: .trailing) { _ in
  431. AxisTick(length: 25, stroke: .init(lineWidth: 4))
  432. .foregroundStyle(Color.clear)
  433. }
  434. }
  435. }
  436. }
  437. var legendPanel: some View {
  438. ZStack {
  439. HStack(alignment: .center) {
  440. Spacer()
  441. Group {
  442. Circle().fill(Color.loopGreen).frame(width: 8, height: 8)
  443. Text("BG")
  444. .font(.system(size: 10, weight: .bold)).foregroundColor(.loopGreen)
  445. }
  446. Group {
  447. Circle().fill(Color.insulin).frame(width: 8, height: 8)
  448. .padding(.leading, 8)
  449. Text("IOB")
  450. .font(.system(size: 10, weight: .bold)).foregroundColor(.insulin)
  451. }
  452. Group {
  453. Circle().fill(Color.zt).frame(width: 8, height: 8)
  454. .padding(.leading, 8)
  455. Text("ZT")
  456. .font(.system(size: 10, weight: .bold)).foregroundColor(.zt)
  457. }
  458. Group {
  459. Circle().fill(Color.loopYellow).frame(width: 8, height: 8).padding(.leading, 8)
  460. Text("COB")
  461. .font(.system(size: 10, weight: .bold)).foregroundColor(.loopYellow)
  462. }
  463. Group {
  464. Circle().fill(Color.uam).frame(width: 8, height: 8)
  465. .padding(.leading, 8)
  466. Text("UAM")
  467. .font(.system(size: 10, weight: .bold)).foregroundColor(.uam)
  468. }
  469. Spacer()
  470. }
  471. .padding(.horizontal, 10)
  472. .frame(maxWidth: .infinity)
  473. }
  474. }
  475. }
  476. // MARK: Calculations
  477. /// calculates the glucose value thats the nearest to parameter 'time'
  478. /// if time is later than all the arrays values return the last element of BloodGlucose
  479. extension MainChartView {
  480. private func timeToNearestGlucose(time: TimeInterval) -> BloodGlucose {
  481. var nextIndex = 0
  482. if glucose.last?.dateString.timeIntervalSince1970 ?? Date().timeIntervalSince1970 < time {
  483. return glucose.last ?? BloodGlucose(
  484. date: 0,
  485. dateString: Date(),
  486. unfiltered: nil,
  487. filtered: nil,
  488. noise: nil,
  489. type: nil
  490. )
  491. }
  492. for (index, value) in glucose.enumerated() {
  493. if value.dateString.timeIntervalSince1970 > time {
  494. nextIndex = index
  495. print("Break", value.dateString.timeIntervalSince1970, time)
  496. break
  497. }
  498. }
  499. return glucose[nextIndex]
  500. }
  501. private func fullWidth(viewWidth: CGFloat) -> CGFloat {
  502. viewWidth * CGFloat(hours) / CGFloat(min(max(screenHours, 2), 24))
  503. }
  504. private func calculateCarbs() {
  505. var calculatedCarbs: [Carb] = []
  506. /// check if carbs are not fpus before adding them to the chart
  507. /// this solves the problem of a first CARB entry with the amount of the single fpu entries that was made at current time when adding ONLY fpus
  508. let realCarbs = carbs.filter { !($0.isFPU ?? false) }
  509. realCarbs.forEach { carb in
  510. let bg = timeToNearestGlucose(time: carb.createdAt.timeIntervalSince1970)
  511. calculatedCarbs.append(Carb(amount: carb.carbs, timestamp: carb.createdAt, nearestGlucose: bg))
  512. }
  513. ChartCarbs = calculatedCarbs
  514. }
  515. private func calculateFpus() {
  516. var calculatedFpus: [Carb] = []
  517. /// check for only fpus
  518. let fpus = carbs.filter { $0.isFPU ?? false }
  519. fpus.forEach { fpu in
  520. let bg = timeToNearestGlucose(
  521. time: TimeInterval(rawValue: (fpu.actualDate?.timeIntervalSince1970)!) ?? fpu.createdAt
  522. .timeIntervalSince1970
  523. )
  524. calculatedFpus
  525. .append(Carb(amount: fpu.carbs, timestamp: fpu.actualDate ?? Date(), nearestGlucose: bg))
  526. }
  527. ChartFpus = calculatedFpus
  528. }
  529. private func calculateBoluses() {
  530. var calculatedBoluses: [ChartBolus] = []
  531. boluses.forEach { bolus in
  532. let bg = timeToNearestGlucose(time: bolus.timestamp.timeIntervalSince1970)
  533. let yPosition = (bg.sgv ?? 120) + 30
  534. calculatedBoluses
  535. .append(ChartBolus(
  536. amount: bolus.amount ?? 0,
  537. timestamp: bolus.timestamp,
  538. nearestGlucose: bg,
  539. yPosition: yPosition
  540. ))
  541. }
  542. ChartBoluses = calculatedBoluses
  543. }
  544. /// calculations for temp target bar mark
  545. private func calculateTTs() {
  546. var groupedPackages: [[TempTarget]] = []
  547. var currentPackage: [TempTarget] = []
  548. var calculatedTTs: [ChartTempTarget] = []
  549. for target in tempTargets {
  550. if target.duration > 0 {
  551. if !currentPackage.isEmpty {
  552. groupedPackages.append(currentPackage)
  553. currentPackage = []
  554. }
  555. currentPackage.append(target)
  556. } else {
  557. if let lastNonZeroTempTarget = currentPackage.last(where: { $0.duration > 0 }) {
  558. if target.createdAt >= lastNonZeroTempTarget.createdAt,
  559. target.createdAt <= lastNonZeroTempTarget.createdAt
  560. .addingTimeInterval(TimeInterval(lastNonZeroTempTarget.duration * 60))
  561. {
  562. currentPackage.append(target)
  563. }
  564. }
  565. }
  566. }
  567. // appends last package, if exists
  568. if !currentPackage.isEmpty {
  569. groupedPackages.append(currentPackage)
  570. }
  571. for package in groupedPackages {
  572. guard let firstNonZeroTarget = package.first(where: { $0.duration > 0 }) else {
  573. continue
  574. }
  575. var end = firstNonZeroTarget.createdAt.addingTimeInterval(TimeInterval(firstNonZeroTarget.duration * 60))
  576. let earliestCancelTarget = package.filter({ $0.duration == 0 }).min(by: { $0.createdAt < $1.createdAt })
  577. if let earliestCancelTarget = earliestCancelTarget {
  578. end = min(earliestCancelTarget.createdAt, end)
  579. }
  580. let now = Date()
  581. isTempTargetActive = firstNonZeroTarget.createdAt <= now && now <= end
  582. if firstNonZeroTarget.targetTop != nil {
  583. calculatedTTs
  584. .append(ChartTempTarget(
  585. amount: firstNonZeroTarget.targetTop ?? 0,
  586. start: firstNonZeroTarget.createdAt,
  587. end: end
  588. ))
  589. }
  590. }
  591. ChartTempTargets = calculatedTTs
  592. }
  593. private func calculatePredictions() {
  594. var calculatedPredictions: [Prediction] = []
  595. let uam = suggestion?.predictions?.uam ?? []
  596. let iob = suggestion?.predictions?.iob ?? []
  597. let cob = suggestion?.predictions?.cob ?? []
  598. let zt = suggestion?.predictions?.zt ?? []
  599. guard let deliveredAt = suggestion?.deliverAt else {
  600. return
  601. }
  602. uam.indices.forEach { index in
  603. let predTime = Date(
  604. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  605. .timeInterval
  606. )
  607. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  608. calculatedPredictions.append(
  609. Prediction(amount: uam[index], timestamp: predTime, type: .uam)
  610. )
  611. }
  612. }
  613. iob.indices.forEach { index in
  614. let predTime = Date(
  615. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  616. .timeInterval
  617. )
  618. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  619. calculatedPredictions.append(
  620. Prediction(amount: iob[index], timestamp: predTime, type: .iob)
  621. )
  622. }
  623. }
  624. cob.indices.forEach { index in
  625. let predTime = Date(
  626. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  627. .timeInterval
  628. )
  629. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  630. calculatedPredictions.append(
  631. Prediction(amount: cob[index], timestamp: predTime, type: .cob)
  632. )
  633. }
  634. }
  635. zt.indices.forEach { index in
  636. let predTime = Date(
  637. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  638. .timeInterval
  639. )
  640. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  641. calculatedPredictions.append(
  642. Prediction(amount: zt[index], timestamp: predTime, type: .zt)
  643. )
  644. }
  645. }
  646. Predictions = calculatedPredictions
  647. }
  648. private func getLastUam() -> Int {
  649. let uam = suggestion?.predictions?.uam ?? []
  650. return uam.last ?? 0
  651. }
  652. private func calculateTempBasals() {
  653. var basals = tempBasals
  654. var returnTempBasalRates: [PumpHistoryEvent] = []
  655. var finished: [Int: Bool] = [:]
  656. basals.indices.forEach { i in
  657. basals.indices.forEach { j in
  658. if basals[i].timestamp == basals[j].timestamp, i != j, !(finished[i] ?? false), !(finished[j] ?? false) {
  659. let rate = basals[i].rate ?? basals[j].rate
  660. let durationMin = basals[i].durationMin ?? basals[j].durationMin
  661. finished[i] = true
  662. if rate != 0 || durationMin != 0 {
  663. returnTempBasalRates.append(
  664. PumpHistoryEvent(
  665. id: basals[i].id, type: FreeAPS.EventType.tempBasal,
  666. timestamp: basals[i].timestamp,
  667. durationMin: durationMin,
  668. rate: rate
  669. )
  670. )
  671. }
  672. }
  673. }
  674. }
  675. TempBasals = returnTempBasalRates
  676. }
  677. private func findRegularBasalPoints(
  678. timeBegin: TimeInterval,
  679. timeEnd: TimeInterval,
  680. autotuned: Bool
  681. ) -> [BasalProfile] {
  682. guard timeBegin < timeEnd else {
  683. return []
  684. }
  685. let beginDate = Date(timeIntervalSince1970: timeBegin)
  686. let calendar = Calendar.current
  687. let startOfDay = calendar.startOfDay(for: beginDate)
  688. let profile = autotuned ? autotunedBasalProfile : basalProfile
  689. let basalNormalized = profile.map {
  690. (
  691. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  692. rate: $0.rate
  693. )
  694. } + profile.map {
  695. (
  696. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval)
  697. .timeIntervalSince1970,
  698. rate: $0.rate
  699. )
  700. } + profile.map {
  701. (
  702. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 2.days.timeInterval)
  703. .timeIntervalSince1970,
  704. rate: $0.rate
  705. )
  706. }
  707. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  708. .compactMap { window -> BasalProfile? in
  709. let window = Array(window)
  710. if window[0].time < timeBegin, window[1].time < timeBegin {
  711. return nil
  712. }
  713. if window[0].time < timeBegin, window[1].time >= timeBegin {
  714. let startDate = Date(timeIntervalSince1970: timeBegin)
  715. let rate = window[0].rate
  716. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  717. }
  718. if window[0].time >= timeBegin, window[0].time < timeEnd {
  719. let startDate = Date(timeIntervalSince1970: window[0].time)
  720. let rate = window[0].rate
  721. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  722. }
  723. return nil
  724. }
  725. return basalTruncatedPoints
  726. }
  727. /// update start and end marker to fix scroll update problem with x axis
  728. private func updateStartEndMarkers() {
  729. startMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 - 86400))
  730. endMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 + 10800))
  731. }
  732. /// get y axis scale
  733. /// but only call the function every 60min, i.e. every 12th glucose value
  734. private func counter() {
  735. glucoseUpdateCount += 1
  736. if glucoseUpdateCount >= maxUpdateCount {
  737. maxValue = glucose.compactMap(\.glucose).max() ?? Config.maxGlucose
  738. if let maxPredValue = maxPredValue() {
  739. maxValue = max(maxValue, maxPredValue)
  740. }
  741. minValue = glucose.compactMap(\.glucose).min() ?? Config.minGlucose
  742. if let minPredValue = minPredValue() {
  743. minValue = min(minValue, minPredValue)
  744. }
  745. if minValue > Config.minGlucose {
  746. minValue = Config.minGlucose
  747. }
  748. if maxValue < Config.maxGlucose {
  749. maxValue = Config.maxGlucose
  750. }
  751. glucoseUpdateCount = 0
  752. }
  753. }
  754. private func maxPredValue() -> Int? {
  755. [
  756. suggestion?.predictions?.cob ?? [],
  757. suggestion?.predictions?.iob ?? [],
  758. suggestion?.predictions?.zt ?? [],
  759. suggestion?.predictions?.uam ?? []
  760. ].flatMap {
  761. $0
  762. }.max()
  763. }
  764. private func minPredValue() -> Int? {
  765. [
  766. suggestion?.predictions?.cob ?? [],
  767. suggestion?.predictions?.iob ?? [],
  768. suggestion?.predictions?.zt ?? [],
  769. suggestion?.predictions?.uam ?? []
  770. ].flatMap {
  771. $0
  772. }.min()
  773. }
  774. /* private func generateYAxisValues(maxYLabel: Int) -> [Int] {
  775. var yAxisValues = [50, 100, 150]
  776. if maxYLabel > 170, maxYLabel < 200 {
  777. yAxisValues.append(maxYLabel)
  778. } else if maxYLabel > 200, maxYLabel < 250 {
  779. yAxisValues += [200, maxYLabel]
  780. } else if maxYLabel > 250, maxYLabel < 350 {
  781. yAxisValues += [200, 250, maxYLabel]
  782. } else if maxYLabel > 350 {
  783. yAxisValues += [200, 250, 300, maxYLabel]
  784. } else if maxYLabel == 400 {
  785. yAxisValues += [200, 250, 300, 350, 400]
  786. }
  787. return yAxisValues
  788. } */
  789. private func calculateBasals() {
  790. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  791. let firstTempTime = (tempBasals.first?.timestamp ?? Date()).timeIntervalSince1970
  792. let regularPoints = findRegularBasalPoints(
  793. timeBegin: dayAgoTime,
  794. timeEnd: endMarker.timeIntervalSince1970,
  795. autotuned: false
  796. )
  797. let autotunedBasalPoints = findRegularBasalPoints(
  798. timeBegin: dayAgoTime,
  799. timeEnd: endMarker.timeIntervalSince1970,
  800. autotuned: true
  801. )
  802. var totalBasal = regularPoints + autotunedBasalPoints
  803. totalBasal.sort {
  804. $0.startDate.timeIntervalSince1970 < $1.startDate.timeIntervalSince1970
  805. }
  806. var basals: [BasalProfile] = []
  807. totalBasal.indices.forEach { index in
  808. basals.append(BasalProfile(
  809. amount: totalBasal[index].amount,
  810. isOverwritten: totalBasal[index].isOverwritten,
  811. startDate: totalBasal[index].startDate,
  812. endDate: totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker
  813. ))
  814. print(
  815. "Basal",
  816. totalBasal[index].startDate,
  817. totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker,
  818. totalBasal[index].amount,
  819. totalBasal[index].isOverwritten
  820. )
  821. }
  822. BasalProfiles = basals
  823. }
  824. }