MainChartView.swift 38 KB

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