MainChartView.swift 38 KB

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