Predictions.swift 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import Charts
  2. import CoreData
  3. import SwiftUI
  4. import Swinject
  5. struct PredictionView: View {
  6. @Binding var predictions: Predictions?
  7. @Binding var units: GlucoseUnits
  8. var body: some View {
  9. chart()
  10. }
  11. func chart() -> some View {
  12. // Data Source
  13. let iob = predictions?.iob ?? [Int]()
  14. let cob = predictions?.cob ?? [Int]()
  15. let uam = predictions?.uam ?? [Int]()
  16. let zt = predictions?.zt ?? [Int]()
  17. let count = max(iob.count, cob.count, uam.count, zt.count)
  18. var now = Date.now
  19. var startIndex = 0
  20. let conversion = units == .mmolL ? 0.0555 : 1
  21. // Organize the data needed for prediction chart.
  22. var data = [ChartData]()
  23. repeat {
  24. now = now.addingTimeInterval(5.minutes.timeInterval)
  25. if startIndex < count {
  26. let addedData = ChartData(
  27. date: now,
  28. iob: startIndex < iob.count ? Double(iob[startIndex]) * conversion : 0,
  29. zt: startIndex < zt.count ? Double(zt[startIndex]) * conversion : 0,
  30. cob: startIndex < cob.count ? Double(cob[startIndex]) * conversion : 0,
  31. uam: startIndex < uam.count ? Double(uam[startIndex]) * conversion : 0,
  32. id: UUID()
  33. )
  34. data.append(addedData)
  35. }
  36. startIndex += 1
  37. } while startIndex < count
  38. // Chart
  39. return Chart(data) { item in
  40. // Remove 0 (empty) values
  41. if item.iob != 0 {
  42. LineMark(
  43. x: .value("Time", item.date),
  44. y: .value("IOB", item.iob),
  45. series: .value("IOB", "A")
  46. )
  47. .foregroundStyle(Color(.insulin))
  48. .lineStyle(StrokeStyle(lineWidth: 2))
  49. }
  50. if item.uam != 0 {
  51. LineMark(
  52. x: .value("Time", item.date),
  53. y: .value("UAM", item.uam),
  54. series: .value("UAM", "B")
  55. )
  56. .foregroundStyle(Color(.UAM))
  57. .lineStyle(StrokeStyle(lineWidth: 2))
  58. }
  59. if item.cob != 0 {
  60. LineMark(
  61. x: .value("Time", item.date),
  62. y: .value("COB", item.cob),
  63. series: .value("COB", "C")
  64. )
  65. .foregroundStyle(Color(.loopYellow))
  66. .lineStyle(StrokeStyle(lineWidth: 2))
  67. }
  68. if item.zt != 0 {
  69. LineMark(
  70. x: .value("Time", item.date),
  71. y: .value("ZT", item.zt),
  72. series: .value("ZT", "D")
  73. )
  74. .foregroundStyle(Color(.ZT))
  75. .lineStyle(StrokeStyle(lineWidth: 2))
  76. }
  77. }
  78. .frame(minHeight: 150)
  79. .chartForegroundStyleScale([
  80. "IOB": Color(.insulin),
  81. "UAM": Color(.UAM),
  82. "COB": Color(.loopYellow),
  83. "ZT": Color(.ZT)
  84. ])
  85. .chartYAxisLabel("Glucose (" + units.rawValue + ")")
  86. }
  87. }