MainChartView.swift 34 KB

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