MainChartView.swift 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  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 = 2
  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)).foregroundStyle(Color.insulin)
  205. }
  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. state.roundedTotalBolus = state.calculateTINS()
  312. }
  313. .onChange(of: tempTargets) { _ in
  314. calculateTTs()
  315. }
  316. .onChange(of: didAppearTrigger) { _ in
  317. calculatePredictions()
  318. calculateTTs()
  319. }.onChange(of: suggestion) { _ in
  320. calculatePredictions()
  321. }
  322. .onReceive(
  323. Foundation.NotificationCenter.default
  324. .publisher(for: UIApplication.willEnterForegroundNotification)
  325. ) { _ in
  326. calculatePredictions()
  327. }
  328. .frame(
  329. minHeight: UIScreen.main.bounds.height / 3
  330. )
  331. .frame(width: fullWidth(viewWidth: screenSize.width))
  332. .chartYScale(domain: minValue ... maxValue)
  333. .chartXScale(domain: startMarker ... endMarker)
  334. .chartXAxis {
  335. AxisMarks(values: .stride(by: .hour, count: screenHours == 24 ? 4 : 2)) { _ in
  336. if displayXgridLines {
  337. AxisGridLine(stroke: .init(lineWidth: 0.3, dash: [2, 3]))
  338. } else {
  339. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  340. }
  341. AxisValueLabel(format: .dateTime.hour(.defaultDigits(amPM: .narrow)), anchor: .top)
  342. }
  343. }
  344. .chartYAxis {
  345. AxisMarks { _ in
  346. if displayYgridLines {
  347. AxisGridLine(stroke: .init(lineWidth: 0.3, dash: [2, 3]))
  348. } else {
  349. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  350. }
  351. AxisValueLabel()
  352. }
  353. }
  354. }
  355. }
  356. func BasalChart() -> some View {
  357. VStack {
  358. Chart {
  359. RuleMark(
  360. x: .value(
  361. "",
  362. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  363. unit: .second
  364. )
  365. ).lineStyle(.init(lineWidth: 2, dash: [2])).foregroundStyle(Color.insulin)
  366. RuleMark(
  367. x: .value(
  368. "",
  369. startMarker,
  370. unit: .second
  371. )
  372. ).foregroundStyle(Color.clear)
  373. RuleMark(
  374. x: .value(
  375. "",
  376. endMarker,
  377. unit: .second
  378. )
  379. ).foregroundStyle(Color.clear)
  380. /// temp basal rects
  381. ForEach(TempBasals) { temp in
  382. /// calculate end time of temp basal adding duration to start time
  383. let end = temp.timestamp + (temp.durationMin ?? 0).minutes.timeInterval
  384. let now = Date()
  385. /// ensure that temp basals that are set cannot exceed current date -> i.e. scheduled temp basals are not shown
  386. /// we could display scheduled temp basals with opacity etc... in the future
  387. let maxEndTime = min(end, now)
  388. RectangleMark(
  389. xStart: .value("start", temp.timestamp),
  390. xEnd: .value("end", maxEndTime),
  391. yStart: .value("rate-start", 0),
  392. yEnd: .value("rate-end", temp.rate ?? 0)
  393. ).foregroundStyle(Color.insulin)
  394. }
  395. /// dashed profile line
  396. ForEach(BasalProfiles, id: \.self) { profile in
  397. LineMark(
  398. x: .value("Start Date", profile.startDate),
  399. y: .value("Amount", profile.amount),
  400. series: .value("profile", "profile")
  401. ).lineStyle(.init(lineWidth: 2, dash: [2, 3])).foregroundStyle(Color.insulin)
  402. LineMark(
  403. x: .value("End Date", profile.endDate ?? endMarker),
  404. y: .value("Amount", profile.amount),
  405. series: .value("profile", "profile")
  406. ).lineStyle(.init(lineWidth: 2.5, dash: [2, 3])).foregroundStyle(Color.insulin)
  407. }
  408. }.onChange(of: tempBasals) { _ in
  409. calculateBasals()
  410. calculateTempBasals()
  411. }
  412. .onChange(of: maxBasal) { _ in
  413. calculateBasals()
  414. calculateTempBasals()
  415. }
  416. .onChange(of: autotunedBasalProfile) { _ in
  417. calculateBasals()
  418. calculateTempBasals()
  419. }
  420. .onChange(of: didAppearTrigger) { _ in
  421. calculateBasals()
  422. calculateTempBasals()
  423. }.onChange(of: basalProfile) { _ in
  424. calculateTempBasals()
  425. }
  426. .frame(
  427. minHeight: UIScreen.main.bounds.height / 10
  428. )
  429. .frame(width: fullWidth(viewWidth: screenSize.width))
  430. .rotationEffect(.degrees(180))
  431. .scaleEffect(x: -1, y: 1)
  432. .chartXScale(domain: startMarker ... endMarker)
  433. .chartXAxis(.hidden)
  434. .chartXAxis {
  435. AxisMarks(values: .stride(by: .hour, count: screenHours == 24 ? 4 : 2)) { _ in
  436. }
  437. }
  438. .chartYAxis {
  439. AxisMarks(position: .trailing) { _ in
  440. AxisTick(length: 25, stroke: .init(lineWidth: 4))
  441. .foregroundStyle(Color.clear)
  442. }
  443. }
  444. }
  445. }
  446. var legendPanel: some View {
  447. ZStack {
  448. HStack(alignment: .center) {
  449. Spacer()
  450. Group {
  451. Circle().fill(Color.loopGreen).frame(width: 8, height: 8)
  452. Text("BG")
  453. .font(.system(size: 10, weight: .bold)).foregroundColor(.loopGreen)
  454. }
  455. Group {
  456. Circle().fill(Color.insulin).frame(width: 8, height: 8)
  457. .padding(.leading, 8)
  458. Text("IOB")
  459. .font(.system(size: 10, weight: .bold)).foregroundColor(.insulin)
  460. }
  461. Group {
  462. Circle().fill(Color.zt).frame(width: 8, height: 8)
  463. .padding(.leading, 8)
  464. Text("ZT")
  465. .font(.system(size: 10, weight: .bold)).foregroundColor(.zt)
  466. }
  467. Group {
  468. Circle().fill(Color.loopYellow).frame(width: 8, height: 8).padding(.leading, 8)
  469. Text("COB")
  470. .font(.system(size: 10, weight: .bold)).foregroundColor(.loopYellow)
  471. }
  472. Group {
  473. Circle().fill(Color.uam).frame(width: 8, height: 8)
  474. .padding(.leading, 8)
  475. Text("UAM")
  476. .font(.system(size: 10, weight: .bold)).foregroundColor(.uam)
  477. }
  478. Spacer()
  479. }
  480. .padding(.horizontal, 10)
  481. .frame(maxWidth: .infinity)
  482. }
  483. }
  484. }
  485. // MARK: Calculations
  486. /// calculates the glucose value thats the nearest to parameter 'time'
  487. /// if time is later than all the arrays values return the last element of BloodGlucose
  488. extension MainChartView {
  489. // private func timeToNearestGlucose(time: TimeInterval) -> BloodGlucose {
  490. // var nextIndex = 0
  491. // if glucose.last?.dateString.timeIntervalSince1970 ?? Date().timeIntervalSince1970 < time {
  492. // return glucose.last ?? BloodGlucose(
  493. // date: 0,
  494. // dateString: Date(),
  495. // unfiltered: nil,
  496. // filtered: nil,
  497. // noise: nil,
  498. // type: nil
  499. // )
  500. // }
  501. // for (index, value) in glucose.enumerated() {
  502. // if value.dateString.timeIntervalSince1970 > time {
  503. // nextIndex = index
  504. // print("Break", value.dateString.timeIntervalSince1970, time)
  505. // break
  506. // }
  507. // }
  508. // return glucose[nextIndex]
  509. // }
  510. // MARK: TEST
  511. /// fix for index out of range problem in simulator
  512. private func timeToNearestGlucose(time: TimeInterval) -> BloodGlucose {
  513. /// If the glucose array is empty, return a default BloodGlucose object or handle it accordingly
  514. guard let lastGlucose = glucose.last else {
  515. return BloodGlucose(
  516. date: 0,
  517. dateString: Date(),
  518. unfiltered: nil,
  519. filtered: nil,
  520. noise: nil,
  521. type: nil
  522. )
  523. }
  524. /// If the last glucose entry is before the specified time, return the last entry
  525. if lastGlucose.dateString.timeIntervalSince1970 < time {
  526. return lastGlucose
  527. }
  528. /// Find the index of the first element in the array whose date is greater than the specified time
  529. if let nextIndex = glucose.firstIndex(where: { $0.dateString.timeIntervalSince1970 > time }) {
  530. return glucose[nextIndex]
  531. } else {
  532. /// If no such element is found, return the last element in the array
  533. return lastGlucose
  534. }
  535. }
  536. private func fullWidth(viewWidth: CGFloat) -> CGFloat {
  537. viewWidth * CGFloat(hours) / CGFloat(min(max(screenHours, 2), 24))
  538. }
  539. private func calculateCarbs() {
  540. var calculatedCarbs: [Carb] = []
  541. /// check if carbs are not fpus before adding them to the chart
  542. /// 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
  543. let realCarbs = carbs.filter { !($0.isFPU ?? false) }
  544. realCarbs.forEach { carb in
  545. let bg = timeToNearestGlucose(time: carb.createdAt.timeIntervalSince1970)
  546. calculatedCarbs.append(Carb(amount: carb.carbs, timestamp: carb.createdAt, nearestGlucose: bg))
  547. }
  548. ChartCarbs = calculatedCarbs
  549. }
  550. private func calculateFpus() {
  551. var calculatedFpus: [Carb] = []
  552. /// check for only fpus
  553. let fpus = carbs.filter { $0.isFPU ?? false }
  554. fpus.forEach { fpu in
  555. let bg = timeToNearestGlucose(
  556. time: TimeInterval(rawValue: (fpu.actualDate?.timeIntervalSince1970)!) ?? fpu.createdAt
  557. .timeIntervalSince1970
  558. )
  559. calculatedFpus
  560. .append(Carb(amount: fpu.carbs, timestamp: fpu.actualDate ?? Date(), nearestGlucose: bg))
  561. }
  562. ChartFpus = calculatedFpus
  563. }
  564. private func calculateBoluses() {
  565. var calculatedBoluses: [ChartBolus] = []
  566. boluses.forEach { bolus in
  567. let bg = timeToNearestGlucose(time: bolus.timestamp.timeIntervalSince1970)
  568. let yPosition = (bg.sgv ?? 120) + 30
  569. calculatedBoluses
  570. .append(ChartBolus(
  571. amount: bolus.amount ?? 0,
  572. timestamp: bolus.timestamp,
  573. nearestGlucose: bg,
  574. yPosition: yPosition
  575. ))
  576. }
  577. ChartBoluses = calculatedBoluses
  578. }
  579. /// calculations for temp target bar mark
  580. private func calculateTTs() {
  581. var groupedPackages: [[TempTarget]] = []
  582. var currentPackage: [TempTarget] = []
  583. var calculatedTTs: [ChartTempTarget] = []
  584. for target in tempTargets {
  585. if target.duration > 0 {
  586. if !currentPackage.isEmpty {
  587. groupedPackages.append(currentPackage)
  588. currentPackage = []
  589. }
  590. currentPackage.append(target)
  591. } else {
  592. if let lastNonZeroTempTarget = currentPackage.last(where: { $0.duration > 0 }) {
  593. if target.createdAt >= lastNonZeroTempTarget.createdAt,
  594. target.createdAt <= lastNonZeroTempTarget.createdAt
  595. .addingTimeInterval(TimeInterval(lastNonZeroTempTarget.duration * 60))
  596. {
  597. currentPackage.append(target)
  598. }
  599. }
  600. }
  601. }
  602. // appends last package, if exists
  603. if !currentPackage.isEmpty {
  604. groupedPackages.append(currentPackage)
  605. }
  606. for package in groupedPackages {
  607. guard let firstNonZeroTarget = package.first(where: { $0.duration > 0 }) else {
  608. continue
  609. }
  610. var end = firstNonZeroTarget.createdAt.addingTimeInterval(TimeInterval(firstNonZeroTarget.duration * 60))
  611. let earliestCancelTarget = package.filter({ $0.duration == 0 }).min(by: { $0.createdAt < $1.createdAt })
  612. if let earliestCancelTarget = earliestCancelTarget {
  613. end = min(earliestCancelTarget.createdAt, end)
  614. }
  615. let now = Date()
  616. isTempTargetActive = firstNonZeroTarget.createdAt <= now && now <= end
  617. if firstNonZeroTarget.targetTop != nil {
  618. calculatedTTs
  619. .append(ChartTempTarget(
  620. amount: firstNonZeroTarget.targetTop ?? 0,
  621. start: firstNonZeroTarget.createdAt,
  622. end: end
  623. ))
  624. }
  625. }
  626. ChartTempTargets = calculatedTTs
  627. }
  628. private func calculatePredictions() {
  629. var calculatedPredictions: [Prediction] = []
  630. let uam = suggestion?.predictions?.uam ?? []
  631. let iob = suggestion?.predictions?.iob ?? []
  632. let cob = suggestion?.predictions?.cob ?? []
  633. let zt = suggestion?.predictions?.zt ?? []
  634. guard let deliveredAt = suggestion?.deliverAt else {
  635. return
  636. }
  637. uam.indices.forEach { index in
  638. let predTime = Date(
  639. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  640. .timeInterval
  641. )
  642. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  643. calculatedPredictions.append(
  644. Prediction(amount: uam[index], timestamp: predTime, type: .uam)
  645. )
  646. }
  647. }
  648. iob.indices.forEach { index in
  649. let predTime = Date(
  650. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  651. .timeInterval
  652. )
  653. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  654. calculatedPredictions.append(
  655. Prediction(amount: iob[index], timestamp: predTime, type: .iob)
  656. )
  657. }
  658. }
  659. cob.indices.forEach { index in
  660. let predTime = Date(
  661. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  662. .timeInterval
  663. )
  664. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  665. calculatedPredictions.append(
  666. Prediction(amount: cob[index], timestamp: predTime, type: .cob)
  667. )
  668. }
  669. }
  670. zt.indices.forEach { index in
  671. let predTime = Date(
  672. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  673. .timeInterval
  674. )
  675. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  676. calculatedPredictions.append(
  677. Prediction(amount: zt[index], timestamp: predTime, type: .zt)
  678. )
  679. }
  680. }
  681. Predictions = calculatedPredictions
  682. }
  683. private func getLastUam() -> Int {
  684. let uam = suggestion?.predictions?.uam ?? []
  685. return uam.last ?? 0
  686. }
  687. private func calculateTempBasals() {
  688. var basals = tempBasals
  689. var returnTempBasalRates: [PumpHistoryEvent] = []
  690. var finished: [Int: Bool] = [:]
  691. basals.indices.forEach { i in
  692. basals.indices.forEach { j in
  693. if basals[i].timestamp == basals[j].timestamp, i != j, !(finished[i] ?? false), !(finished[j] ?? false) {
  694. let rate = basals[i].rate ?? basals[j].rate
  695. let durationMin = basals[i].durationMin ?? basals[j].durationMin
  696. finished[i] = true
  697. if rate != 0 || durationMin != 0 {
  698. returnTempBasalRates.append(
  699. PumpHistoryEvent(
  700. id: basals[i].id, type: FreeAPS.EventType.tempBasal,
  701. timestamp: basals[i].timestamp,
  702. durationMin: durationMin,
  703. rate: rate
  704. )
  705. )
  706. }
  707. }
  708. }
  709. }
  710. TempBasals = returnTempBasalRates
  711. }
  712. private func findRegularBasalPoints(
  713. timeBegin: TimeInterval,
  714. timeEnd: TimeInterval,
  715. autotuned: Bool
  716. ) -> [BasalProfile] {
  717. guard timeBegin < timeEnd else {
  718. return []
  719. }
  720. let beginDate = Date(timeIntervalSince1970: timeBegin)
  721. let calendar = Calendar.current
  722. let startOfDay = calendar.startOfDay(for: beginDate)
  723. let profile = autotuned ? autotunedBasalProfile : basalProfile
  724. let basalNormalized = profile.map {
  725. (
  726. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  727. rate: $0.rate
  728. )
  729. } + profile.map {
  730. (
  731. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval)
  732. .timeIntervalSince1970,
  733. rate: $0.rate
  734. )
  735. } + profile.map {
  736. (
  737. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 2.days.timeInterval)
  738. .timeIntervalSince1970,
  739. rate: $0.rate
  740. )
  741. }
  742. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  743. .compactMap { window -> BasalProfile? in
  744. let window = Array(window)
  745. if window[0].time < timeBegin, window[1].time < timeBegin {
  746. return nil
  747. }
  748. if window[0].time < timeBegin, window[1].time >= timeBegin {
  749. let startDate = Date(timeIntervalSince1970: timeBegin)
  750. let rate = window[0].rate
  751. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  752. }
  753. if window[0].time >= timeBegin, window[0].time < timeEnd {
  754. let startDate = Date(timeIntervalSince1970: window[0].time)
  755. let rate = window[0].rate
  756. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  757. }
  758. return nil
  759. }
  760. return basalTruncatedPoints
  761. }
  762. /// update start and end marker to fix scroll update problem with x axis
  763. private func updateStartEndMarkers() {
  764. startMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 - 86400))
  765. endMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 + 10800))
  766. }
  767. /// get y axis scale
  768. /// but only call the function every 60min, i.e. every 12th glucose value
  769. private func counter() {
  770. glucoseUpdateCount += 1
  771. if glucoseUpdateCount >= maxUpdateCount {
  772. maxValue = glucose.compactMap(\.glucose).max() ?? Config.maxGlucose
  773. if let maxPredValue = maxPredValue() {
  774. maxValue = max(maxValue, maxPredValue)
  775. }
  776. minValue = glucose.compactMap(\.glucose).min() ?? Config.minGlucose
  777. if let minPredValue = minPredValue() {
  778. minValue = min(minValue, minPredValue)
  779. }
  780. if minValue > Config.minGlucose {
  781. minValue = Config.minGlucose
  782. }
  783. if maxValue < Config.maxGlucose {
  784. maxValue = Config.maxGlucose
  785. }
  786. glucoseUpdateCount = 0
  787. }
  788. }
  789. private func maxPredValue() -> Int? {
  790. [
  791. suggestion?.predictions?.cob ?? [],
  792. suggestion?.predictions?.iob ?? [],
  793. suggestion?.predictions?.zt ?? [],
  794. suggestion?.predictions?.uam ?? []
  795. ].flatMap {
  796. $0
  797. }.max()
  798. }
  799. private func minPredValue() -> Int? {
  800. [
  801. suggestion?.predictions?.cob ?? [],
  802. suggestion?.predictions?.iob ?? [],
  803. suggestion?.predictions?.zt ?? [],
  804. suggestion?.predictions?.uam ?? []
  805. ].flatMap {
  806. $0
  807. }.min()
  808. }
  809. /* private func generateYAxisValues(maxYLabel: Int) -> [Int] {
  810. var yAxisValues = [50, 100, 150]
  811. if maxYLabel > 170, maxYLabel < 200 {
  812. yAxisValues.append(maxYLabel)
  813. } else if maxYLabel > 200, maxYLabel < 250 {
  814. yAxisValues += [200, maxYLabel]
  815. } else if maxYLabel > 250, maxYLabel < 350 {
  816. yAxisValues += [200, 250, maxYLabel]
  817. } else if maxYLabel > 350 {
  818. yAxisValues += [200, 250, 300, maxYLabel]
  819. } else if maxYLabel == 400 {
  820. yAxisValues += [200, 250, 300, 350, 400]
  821. }
  822. return yAxisValues
  823. } */
  824. private func calculateBasals() {
  825. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  826. let firstTempTime = (tempBasals.first?.timestamp ?? Date()).timeIntervalSince1970
  827. let regularPoints = findRegularBasalPoints(
  828. timeBegin: dayAgoTime,
  829. timeEnd: endMarker.timeIntervalSince1970,
  830. autotuned: false
  831. )
  832. let autotunedBasalPoints = findRegularBasalPoints(
  833. timeBegin: dayAgoTime,
  834. timeEnd: endMarker.timeIntervalSince1970,
  835. autotuned: true
  836. )
  837. var totalBasal = regularPoints + autotunedBasalPoints
  838. totalBasal.sort {
  839. $0.startDate.timeIntervalSince1970 < $1.startDate.timeIntervalSince1970
  840. }
  841. var basals: [BasalProfile] = []
  842. totalBasal.indices.forEach { index in
  843. basals.append(BasalProfile(
  844. amount: totalBasal[index].amount,
  845. isOverwritten: totalBasal[index].isOverwritten,
  846. startDate: totalBasal[index].startDate,
  847. endDate: totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker
  848. ))
  849. print(
  850. "Basal",
  851. totalBasal[index].startDate,
  852. totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker,
  853. totalBasal[index].amount,
  854. totalBasal[index].isOverwritten
  855. )
  856. }
  857. BasalProfiles = basals
  858. }
  859. }