ReadPodStatusView.swift 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. //
  2. // ReadPodStatusView.swift
  3. // OmniKit
  4. //
  5. // Created by Joe Moran on 8/15/23.
  6. // Copyright © 2023 LoopKit Authors. All rights reserved.
  7. //
  8. import SwiftUI
  9. import LoopKit
  10. import OmniKit
  11. struct ReadPodStatusView: View {
  12. @Environment(\.horizontalSizeClass) var horizontalSizeClass
  13. @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
  14. var toRun: ((_ completion: @escaping (_ result: PumpManagerResult<DetailedStatus>) -> Void) -> Void)?
  15. private let title = LocalizedString("Read Pod Status", comment: "navigation title for read pod status")
  16. private let actionString = LocalizedString("Reading Pod Status...", comment: "button title when executing read pod status")
  17. private let failedString = LocalizedString("Failed to read pod status.", comment: "Alert title for error when reading pod status")
  18. @State private var alertIsPresented: Bool = false
  19. @State private var displayString: String = ""
  20. @State private var error: LocalizedError? = nil
  21. @State private var executing: Bool = false
  22. @State private var showActivityView: Bool = false
  23. var body: some View {
  24. VStack {
  25. List {
  26. Section {
  27. Text(self.displayString).fixedSize(horizontal: false, vertical: true)
  28. }
  29. }
  30. .toolbar {
  31. ToolbarItem(placement: .navigationBarTrailing) {
  32. Button(action: {
  33. self.showActivityView = true
  34. }) {
  35. Image(systemName: "square.and.arrow.up")
  36. }
  37. }
  38. }.sheet(isPresented: $showActivityView) {
  39. ActivityView(isPresented: $showActivityView, activityItems: [self.displayString])
  40. }
  41. VStack {
  42. Button(action: {
  43. asyncAction()
  44. }) {
  45. Text(buttonText)
  46. .actionButtonStyle(.primary)
  47. }
  48. .padding()
  49. .disabled(executing)
  50. }
  51. .padding(self.horizontalSizeClass == .regular ? .bottom : [])
  52. .background(Color(UIColor.secondarySystemGroupedBackground).shadow(radius: 5))
  53. }
  54. .insetGroupedListStyle()
  55. .navigationTitle(title)
  56. .navigationBarTitleDisplayMode(.automatic)
  57. .alert(isPresented: $alertIsPresented, content: { alert(error: error) })
  58. .onFirstAppear {
  59. asyncAction()
  60. }
  61. }
  62. private func asyncAction () {
  63. DispatchQueue.global(qos: .utility).async {
  64. executing = true
  65. self.displayString = ""
  66. toRun?() { (result) in
  67. executing = false
  68. switch result {
  69. case .success(let detailedStatus):
  70. self.displayString = podStatusString(status: detailedStatus)
  71. case .failure(let error):
  72. self.error = error
  73. self.alertIsPresented = true
  74. }
  75. }
  76. }
  77. }
  78. private var buttonText: String {
  79. if executing {
  80. return actionString
  81. } else {
  82. return title
  83. }
  84. }
  85. private func alert(error: Error?) -> SwiftUI.Alert {
  86. return SwiftUI.Alert(
  87. title: Text(failedString),
  88. message: Text(error?.localizedDescription ?? "No Error")
  89. )
  90. }
  91. }
  92. private func podStatusString(status: DetailedStatus) -> String {
  93. var result, str: String
  94. let formatter = DateComponentsFormatter()
  95. formatter.unitsStyle = .full
  96. formatter.allowedUnits = [.hour, .minute]
  97. formatter.unitsStyle = .short
  98. if let timeStr = formatter.string(from: status.timeActive) {
  99. str = timeStr
  100. } else {
  101. str = String(format: LocalizedString("%1$@ minutes", comment: "The format string for minutes (1: number of minutes string)"), String(describing: Int(status.timeActive / 60)))
  102. }
  103. result = String(format: LocalizedString("Pod Active: %1$@", comment: "The format string for Pod Active: (1: formatted time)"), str)
  104. result += String(format: LocalizedString("\nPod Progress: %1$@", comment: "The format string for Pod Progress: (1: pod progress string)"), String(describing: status.podProgressStatus))
  105. result += String(format: LocalizedString("\nDelivery Status: %1$@", comment: "The format string for Delivery Status: (1: delivery status string)"), String(describing: status.deliveryStatus))
  106. result += String(format: LocalizedString("\nLast Programming Seq Num: %1$@", comment: "The format string for last programming sequence number: (1: last programming sequence number)"), String(describing: status.lastProgrammingMessageSeqNum))
  107. result += String(format: LocalizedString("\nBolus Not Delivered: %1$@ U", comment: "The format string for Bolus Not Delivered: (1: bolus not delivered string)"), status.bolusNotDelivered.twoDecimals)
  108. result += String(format: LocalizedString("\nPulse Count: %1$d", comment: "The format string for Pulse Count (1: pulse count)"), Int(round(status.totalInsulinDelivered / Pod.pulseSize)))
  109. result += String(format: LocalizedString("\nReservoir Level: %1$@ U", comment: "The format string for Reservoir Level: (1: reservoir level string)"), status.reservoirLevel == Pod.reservoirLevelAboveThresholdMagicNumber ? "50+" : status.reservoirLevel.twoDecimals)
  110. result += String(format: LocalizedString("\nAlerts: %1$@", comment: "The format string for Alerts: (1: the alerts string)"), alertSetString(alertSet: status.unacknowledgedAlerts))
  111. if status.radioRSSI != 0 {
  112. result += String(format: LocalizedString("\nRSSI: %1$@", comment: "The format string for RSSI: (1: RSSI value)"), String(describing: status.radioRSSI))
  113. result += String(format: LocalizedString("\nReceiver Low Gain: %1$@", comment: "The format string for receiverLowGain: (1: receiverLowGain)"), String(describing: status.receiverLowGain))
  114. }
  115. if status.faultEventCode.faultType != .noFaults {
  116. // report the additional fault related information in a separate section
  117. result += String(format: LocalizedString("\n\n⚠️ Critical Pod Fault %1$03d (0x%2$02X)", comment: "The format string for fault code in decimal and hex: (1: fault code for decimal display) (2: fault code for hex display)"), status.faultEventCode.rawValue, status.faultEventCode.rawValue)
  118. result += String(format: "\n%1$@", status.faultEventCode.faultDescription)
  119. if let faultEventTimeSinceActivation = status.faultEventTimeSinceActivation,
  120. let faultTimeStr = formatter.string(from: faultEventTimeSinceActivation)
  121. {
  122. result += String(format: LocalizedString("\nFault Time: %1$@", comment: "The format string for fault time: (1: fault time string)"), faultTimeStr)
  123. }
  124. if let errorEventInfo = status.errorEventInfo {
  125. result += String(format: LocalizedString("\nFault Event Info: %1$03d (0x%2$02X),", comment: "The format string for fault event info: (1: fault event info)"), errorEventInfo.rawValue, errorEventInfo.rawValue)
  126. result += String(format: LocalizedString("\n Insulin State Table Corrupted: %@", comment: "The format string for insulin state table corrupted: (1: insulin state corrupted)"), String(describing: errorEventInfo.insulinStateTableCorruption))
  127. result += String(format: LocalizedString("\n Occlusion Type: %1$@", comment: "The format string for occlusion type: (1: occlusion type)"), String(describing: errorEventInfo.occlusionType))
  128. result += String(format: LocalizedString("\n Immediate Bolus In Progress: %1$@", comment: "The format string for immediate bolus in progress: (1: immediate bolus in progress)"), String(describing: errorEventInfo.immediateBolusInProgress))
  129. result += String(format: LocalizedString("\n Previous Pod Progress: %1$@", comment: "The format string for previous pod progress: (1: previous pod progress string)"), String(describing: errorEventInfo.podProgressStatus))
  130. }
  131. if let pdmRef = status.pdmRef {
  132. result += String(format: LocalizedString("\nRef: %@", comment: "The Ref format string (1: pdm ref string)"), pdmRef)
  133. }
  134. }
  135. return result
  136. }
  137. struct ReadPodStatusView_Previews: PreviewProvider {
  138. static var previews: some View {
  139. NavigationView {
  140. let detailedStatus = try! DetailedStatus(encodedData: Data([0x02, 0x0d, 0x00, 0x00, 0x00, 0x0e, 0x00, 0xc3, 0x6a, 0x02, 0x07, 0x03, 0xff, 0x02, 0x09, 0x20, 0x00, 0x28, 0x99, 0x08, 0x00, 0x82]))
  141. ReadPodStatusView() { completion in
  142. completion(.success(detailedStatus))
  143. }
  144. }
  145. }
  146. }