MainChartView.swift 38 KB

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