LoopStatusView.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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. if statusBadgeColor == .secondary {
  134. .black
  135. } else {
  136. colorScheme == .dark ? Color(red: 25.0 / 255.0, green: 39.0 / 255.0, blue: 53.0 / 255.0, opacity: 1.0) : .white
  137. }
  138. }
  139. private func setStatusTitle() {
  140. if let determination = state.determinationsFromPersistence.first {
  141. statusTitle =
  142. "Enacted at \(Formatter.dateFormatter.string(from: determination.deliverAt ?? Date()))"
  143. } else {
  144. statusTitle = "Not enacted."
  145. }
  146. }
  147. // TODO: Consolidate all mmol parsing methods (in TagCloudView, NightscoutManager and HomeRootView) to one central func
  148. private func parseReasonConclusion(_ reasonConclusion: String, isMmolL: Bool) -> String {
  149. let patterns = [
  150. "minGuardBG\\s*-?\\d+\\.?\\d*<-?\\d+\\.?\\d*", // minGuardBG x<y
  151. "Eventual BG\\s*-?\\d+\\.?\\d*\\s*>=\\s*-?\\d+\\.?\\d*", // Eventual BG x >= target
  152. "Eventual BG\\s*-?\\d+\\.?\\d*\\s*<\\s*-?\\d+\\.?\\d*", // Eventual BG x < target
  153. "(\\S+)\\s+(-?\\d+\\.?\\d*)\\s*>\\s*(\\d+)%\\s+of\\s+BG\\s+(-?\\d+\\.?\\d*)" // maxDelta x > y% of BG z
  154. ]
  155. let pattern = patterns.joined(separator: "|")
  156. let regex = try! NSRegularExpression(pattern: pattern)
  157. func convertToMmolL(_ value: String) -> String {
  158. if let glucoseValue = Double(value.replacingOccurrences(of: "[^\\d.-]", with: "", options: .regularExpression)) {
  159. let mmolValue = Decimal(glucoseValue).asMmolL
  160. return mmolValue.description
  161. }
  162. return value
  163. }
  164. let matches = regex.matches(
  165. in: reasonConclusion,
  166. range: NSRange(reasonConclusion.startIndex..., in: reasonConclusion)
  167. )
  168. var updatedConclusion = reasonConclusion
  169. for match in matches.reversed() {
  170. guard let range = Range(match.range, in: reasonConclusion) else { continue }
  171. let matchedString = String(reasonConclusion[range])
  172. if isMmolL {
  173. if matchedString.contains("<"), matchedString.contains("Eventual BG"), !matchedString.contains("=") {
  174. // Handle "Eventual BG x < target" pattern
  175. let parts = matchedString.components(separatedBy: "<")
  176. if parts.count == 2 {
  177. let bgPart = parts[0].replacingOccurrences(of: "Eventual BG", with: "")
  178. .trimmingCharacters(in: .whitespaces)
  179. let targetValue = parts[1].trimmingCharacters(in: .whitespaces)
  180. let formattedBGPart = convertToMmolL(bgPart)
  181. let formattedTargetValue = convertToMmolL(targetValue)
  182. let formattedString = "Eventual BG \(formattedBGPart)<\(formattedTargetValue)"
  183. updatedConclusion.replaceSubrange(range, with: formattedString)
  184. }
  185. } else if matchedString.contains("<"), matchedString.contains("minGuardBG") {
  186. // Handle "minGuardBG x<y" pattern
  187. let parts = matchedString.components(separatedBy: "<")
  188. if parts.count == 2 {
  189. let firstValue = parts[0].trimmingCharacters(in: .whitespaces)
  190. let secondValue = parts[1].trimmingCharacters(in: .whitespaces)
  191. let formattedFirstValue = convertToMmolL(firstValue)
  192. let formattedSecondValue = convertToMmolL(secondValue)
  193. let formattedString = "minGuardBG \(formattedFirstValue)<\(formattedSecondValue)"
  194. updatedConclusion.replaceSubrange(range, with: formattedString)
  195. }
  196. } else if matchedString.contains(">=") {
  197. // Handle "Eventual BG x >= target" pattern
  198. let parts = matchedString.components(separatedBy: " >= ")
  199. if parts.count == 2 {
  200. let firstValue = parts[0].replacingOccurrences(of: "Eventual BG", with: "")
  201. .trimmingCharacters(in: .whitespaces)
  202. let secondValue = parts[1].trimmingCharacters(in: .whitespaces)
  203. let formattedFirstValue = convertToMmolL(firstValue)
  204. let formattedSecondValue = convertToMmolL(secondValue)
  205. let formattedString = "Eventual BG \(formattedFirstValue) >= \(formattedSecondValue)"
  206. updatedConclusion.replaceSubrange(range, with: formattedString)
  207. }
  208. } else if let localMatch = regex.firstMatch(
  209. in: matchedString,
  210. range: NSRange(matchedString.startIndex..., in: matchedString)
  211. ) {
  212. // Handle "maxDelta 37 > 20% of BG 95" style
  213. if match.numberOfRanges == 5 {
  214. let metric = String(matchedString[Range(localMatch.range(at: 1), in: matchedString)!])
  215. let firstValue = String(matchedString[Range(localMatch.range(at: 2), in: matchedString)!])
  216. let percentage = String(matchedString[Range(localMatch.range(at: 3), in: matchedString)!])
  217. let bgValue = String(matchedString[Range(localMatch.range(at: 4), in: matchedString)!])
  218. let formattedFirstValue = convertToMmolL(firstValue)
  219. let formattedBGValue = convertToMmolL(bgValue)
  220. let formattedString = "\(metric) \(formattedFirstValue) > \(percentage)% of BG \(formattedBGValue)"
  221. updatedConclusion.replaceSubrange(range, with: formattedString)
  222. }
  223. }
  224. } else {
  225. // When isMmolL is false, ensure the original value is retained without duplication
  226. updatedConclusion.replaceSubrange(range, with: matchedString)
  227. }
  228. }
  229. return updatedConclusion.capitalizingFirstLetter()
  230. }
  231. }