LoopStatusView.swift 12 KB

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