LoopStatusView.swift 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. import SwiftUI
  2. struct LoopStatusView: View {
  3. @Environment(\.colorScheme) var colorScheme
  4. @Environment(AppState.self) var appState
  5. var state: Home.StateModel
  6. @State var sheetDetent = PresentationDetent.medium
  7. @State private var statusTitle: String = ""
  8. var body: some View {
  9. NavigationStack {
  10. VStack(alignment: .leading, spacing: 10) {
  11. Text("Current Loop Status").bold().padding(.top, 20)
  12. Text(statusTitle)
  13. .font(.headline)
  14. .foregroundColor(statusBadgeTextColor)
  15. .padding(.horizontal, 12)
  16. .padding(.vertical, 6)
  17. .background(statusBadgeColor)
  18. .clipShape(Capsule())
  19. if let errorMessage = state.errorMessage, let date = state.errorDate {
  20. Group {
  21. Text("Error During Algorithm Run at \(Formatter.dateFormatter.string(from: date))").font(.headline)
  22. Text(errorMessage).font(.caption)
  23. }.foregroundColor(.loopRed)
  24. }
  25. if let determination = state.determinationsFromPersistence.first {
  26. if determination.glucose == 400 {
  27. Text("Invalid CGM reading (HIGH).")
  28. .bold()
  29. .padding(.top)
  30. .foregroundStyle(Color.loopRed)
  31. Text("SMBs and Non-Zero Temp. Basal Rates are disabled.")
  32. .font(.subheadline)
  33. } else {
  34. Text("Latest Raw Algorithm Output")
  35. .bold()
  36. .padding(.top)
  37. Text(
  38. "Trio is currently using these metrics and values as determined by the oref algorithm:"
  39. )
  40. .font(.subheadline)
  41. let tags = !state.isSmoothingEnabled ? determination.reasonParts : determination
  42. .reasonParts + ["Smoothing: On"]
  43. TagCloudView(
  44. tags: tags,
  45. shouldParseToMmolL: state.units == .mmolL
  46. )
  47. Text("Current Algorithm Reasoning").bold().padding(.top)
  48. Text(
  49. self
  50. .parseReasonConclusion(
  51. determination.reasonConclusion,
  52. isMmolL: state.units == .mmolL
  53. )
  54. ).font(.subheadline)
  55. }
  56. } else {
  57. Text("No recent oref algorithm determination.")
  58. }
  59. Spacer()
  60. Button {
  61. state.isLoopStatusPresented.toggle()
  62. } label: {
  63. Text("Got it!")
  64. .frame(maxWidth: .infinity, alignment: .center)
  65. }
  66. .buttonStyle(.bordered)
  67. .padding(.top)
  68. }
  69. .padding(.vertical)
  70. .padding(.horizontal, 20)
  71. .presentationDetents(
  72. [.fraction(0.8), .large],
  73. selection: $sheetDetent
  74. )
  75. .ignoresSafeArea(edges: .top)
  76. .background(appState.trioBackgroundColor(for: colorScheme))
  77. .onAppear {
  78. setStatusTitle()
  79. }
  80. }
  81. .scrollContentBackground(.hidden)
  82. }
  83. private var statusBadgeColor: Color {
  84. guard let determination = state.determinationsFromPersistence.first, determination.timestamp != nil
  85. else {
  86. // previously the .timestamp property was used here because this only gets updated when the reportenacted function in the aps manager gets called
  87. return .secondary
  88. }
  89. let delta = state.timerDate.timeIntervalSince(state.lastLoopDate) - 30
  90. if delta <= 5.minutes.timeInterval {
  91. guard determination.timestamp != nil else {
  92. return .loopYellow
  93. }
  94. return .loopGreen
  95. } else if delta <= 10.minutes.timeInterval {
  96. return .loopYellow
  97. } else {
  98. return .loopRed
  99. }
  100. }
  101. private var statusBadgeTextColor: Color {
  102. statusBadgeColor == .secondary || statusBadgeColor == .loopYellow ? .black :
  103. .white
  104. }
  105. private func setStatusTitle() {
  106. if let determination = state.determinationsFromPersistence.first {
  107. statusTitle =
  108. "Enacted at \(Formatter.dateFormatter.string(from: determination.deliverAt ?? Date()))"
  109. } else {
  110. statusTitle = "Not enacted."
  111. }
  112. }
  113. // TODO: Consolidate all mmol parsing methods (in TagCloudView, NightscoutManager and HomeRootView) to one central func
  114. private func parseReasonConclusion(_ reasonConclusion: String, isMmolL _: Bool) -> String {
  115. let patterns = [
  116. "minGuardBG\\s*-?\\d+\\.?\\d*<-?\\d+\\.?\\d*",
  117. "Eventual BG\\s*-?\\d+\\.?\\d*\\s*>=\\s*-?\\d+\\.?\\d*",
  118. "\\S+\\s+-?\\d+\\.?\\d*\\s*>\\s*\\d+%\\s+of\\s+BG\\s+-?\\d+\\.?\\d*"
  119. ]
  120. let pattern = patterns.joined(separator: "|")
  121. let regex = try! NSRegularExpression(pattern: pattern)
  122. func convertToMmolL(_ value: String) -> String {
  123. if let glucoseValue = Double(value.replacingOccurrences(of: "[^\\d.-]", with: "", options: .regularExpression)) {
  124. let mmolValue = Decimal(glucoseValue).asMmolL
  125. return mmolValue.description
  126. }
  127. return value
  128. }
  129. let matches = regex.matches(
  130. in: reasonConclusion,
  131. range: NSRange(reasonConclusion.startIndex..., in: reasonConclusion)
  132. )
  133. var updatedConclusion = reasonConclusion
  134. for match in matches.reversed() {
  135. guard let range = Range(match.range, in: reasonConclusion) else { continue }
  136. let matchedString = String(reasonConclusion[range])
  137. if matchedString.contains("<") {
  138. // Handle "minGuardBG x<y" pattern
  139. let parts = matchedString.components(separatedBy: "<")
  140. if parts.count == 2,
  141. let firstValue = Double(
  142. parts[0]
  143. .components(separatedBy: CharacterSet(charactersIn: "0123456789.-").inverted).joined()
  144. ),
  145. let secondValue = Double(
  146. parts[1]
  147. .components(separatedBy: CharacterSet(charactersIn: "0123456789.-").inverted).joined()
  148. )
  149. {
  150. let formattedFirstValue = convertToMmolL(String(firstValue))
  151. let formattedSecondValue = convertToMmolL(String(secondValue))
  152. let formattedString = "minGuardBG \(formattedFirstValue)<\(formattedSecondValue)"
  153. updatedConclusion.replaceSubrange(range, with: formattedString)
  154. }
  155. } else if matchedString.contains(">=") {
  156. // Handle "Eventual BG x >= target" pattern
  157. let parts = matchedString.components(separatedBy: " >= ")
  158. if parts.count == 2,
  159. let firstValue = Double(
  160. parts[0]
  161. .components(separatedBy: CharacterSet(charactersIn: "0123456789.-").inverted).joined()
  162. ),
  163. let secondValue = Double(
  164. parts[1]
  165. .components(separatedBy: CharacterSet(charactersIn: "0123456789.-").inverted).joined()
  166. )
  167. {
  168. let formattedFirstValue = convertToMmolL(String(firstValue))
  169. let formattedSecondValue = convertToMmolL(String(secondValue))
  170. let formattedString = "Eventual BG \(formattedFirstValue) >= \(formattedSecondValue)"
  171. updatedConclusion.replaceSubrange(range, with: formattedString)
  172. }
  173. } else if matchedString.contains(">") {
  174. // Handle "maxDelta 37 > 20% of BG 95" style
  175. let pattern = "(\\S+)\\s+(-?\\d+\\.?\\d*)\\s*>\\s*(\\d+)%\\s+of\\s+BG\\s+(-?\\d+\\.?\\d*)"
  176. let localRegex = try! NSRegularExpression(pattern: pattern)
  177. if let localMatch = localRegex.firstMatch(
  178. in: matchedString,
  179. range: NSRange(matchedString.startIndex..., in: matchedString)
  180. ) {
  181. let metric = String(matchedString[Range(localMatch.range(at: 1), in: matchedString)!])
  182. let firstValue = String(matchedString[Range(localMatch.range(at: 2), in: matchedString)!])
  183. let percentage = String(matchedString[Range(localMatch.range(at: 3), in: matchedString)!])
  184. let bgValue = String(matchedString[Range(localMatch.range(at: 4), in: matchedString)!])
  185. let formattedFirstValue = convertToMmolL(firstValue)
  186. let formattedBGValue = convertToMmolL(bgValue)
  187. let formattedString = "\(metric) \(formattedFirstValue) > \(percentage)% of BG \(formattedBGValue)"
  188. updatedConclusion.replaceSubrange(range, with: formattedString)
  189. }
  190. }
  191. }
  192. return updatedConclusion.capitalizingFirstLetter()
  193. }
  194. }