MainChartView.swift 38 KB

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