LoopStatusView.swift 14 KB

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