LoopStatusView.swift 12 KB

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