LoopStatusView.swift 13 KB

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