LoopAPNSBolusView.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. // LoopFollow
  2. // LoopAPNSBolusView.swift
  3. import HealthKit
  4. import LocalAuthentication
  5. import SwiftUI
  6. struct LoopAPNSBolusView: View {
  7. @Environment(\.presentationMode) var presentationMode
  8. @State private var insulinAmount = HKQuantity(unit: .internationalUnit(), doubleValue: 0.0)
  9. @State private var isLoading = false
  10. @State private var showAlert = false
  11. @State private var alertMessage = ""
  12. @State private var alertType: AlertType = .success
  13. @FocusState private var insulinFieldIsFocused: Bool
  14. // Add state for recommended bolus and warning
  15. @State private var recommendedBolus: Double? = nil
  16. @State private var lastLoopTime: TimeInterval? = nil
  17. @State private var otpTimeRemaining: Int? = nil
  18. @State private var showOldCalculationWarning = false
  19. @State private var showTOTPWarning = false
  20. private let otpPeriod: TimeInterval = 30
  21. private var otpTimer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
  22. // Computed property to check if TOTP should be blocked
  23. private var isTOTPBlocked: Bool {
  24. TOTPService.shared.isTOTPBlocked(qrCodeURL: Storage.shared.loopAPNSQrCodeURL.value)
  25. }
  26. enum AlertType {
  27. case success
  28. case error
  29. case confirmation
  30. case oldCalculationWarning
  31. }
  32. var body: some View {
  33. NavigationView {
  34. VStack {
  35. Form {
  36. // Recommended bolus section
  37. if let recommendedBolus = recommendedBolus, recommendedBolus > 0, let lastLoopTime = lastLoopTime {
  38. let timeSinceCalculation = Date().timeIntervalSince1970 - lastLoopTime
  39. let minutesSinceCalculation = Int(timeSinceCalculation / 60)
  40. // Only show if calculation is less than 12 minutes old
  41. if minutesSinceCalculation < 12 {
  42. Section(header: Text("Recommended Bolus")) {
  43. Button(action: {
  44. handleRecommendedBolusTap()
  45. }) {
  46. HStack {
  47. VStack(alignment: .leading, spacing: 4) {
  48. Text("\(String(format: "%.2f", recommendedBolus))U")
  49. .font(.headline)
  50. .foregroundColor(.primary)
  51. Text("Calculated \(minutesSinceCalculation) minute\(minutesSinceCalculation == 1 ? "" : "s") ago")
  52. .font(.caption)
  53. .foregroundColor(.secondary)
  54. }
  55. Spacer()
  56. Image(systemName: "arrow.up.circle.fill")
  57. .foregroundColor(.blue)
  58. .font(.title2)
  59. }
  60. .padding(.vertical, 8)
  61. }
  62. .buttonStyle(PlainButtonStyle())
  63. }
  64. }
  65. }
  66. Section {
  67. HKQuantityInputView(
  68. label: "Insulin Amount",
  69. quantity: $insulinAmount,
  70. unit: .internationalUnit(),
  71. maxLength: 5,
  72. minValue: HKQuantity(unit: .internationalUnit(), doubleValue: 0.025),
  73. maxValue: Storage.shared.maxBolus.value,
  74. isFocused: $insulinFieldIsFocused,
  75. onValidationError: { message in
  76. alertMessage = message
  77. alertType = .error
  78. showAlert = true
  79. }
  80. )
  81. }
  82. // Warning section for recommended bolus age
  83. if let recommendedBolus = recommendedBolus, let lastLoopTime = lastLoopTime {
  84. let timeSinceCalculation = Date().timeIntervalSince1970 - lastLoopTime
  85. let minutesSinceCalculation = Int(timeSinceCalculation / 60)
  86. // Only show warning if calculation is less than 12 minutes old
  87. if minutesSinceCalculation < 12 {
  88. Section {
  89. let warningColor: Color = minutesSinceCalculation >= 5 ? .red : .yellow
  90. VStack(alignment: .leading, spacing: 8) {
  91. Text("WARNING: New treatments may have occurred since the last recommended bolus was calculated \(presentableMinutesFormat(timeInterval: timeSinceCalculation)) ago.")
  92. .font(.callout)
  93. .foregroundColor(warningColor)
  94. .multilineTextAlignment(.leading)
  95. }
  96. }
  97. }
  98. }
  99. Section {
  100. Button(action: sendInsulin) {
  101. if isLoading {
  102. HStack {
  103. ProgressView()
  104. .scaleEffect(0.8)
  105. Text("Sending...")
  106. }
  107. } else {
  108. Text("Send Insulin")
  109. }
  110. }
  111. .disabled(insulinAmount.doubleValue(for: .internationalUnit()) <= 0 || isLoading || isTOTPBlocked)
  112. .frame(maxWidth: .infinity)
  113. }
  114. // TOTP Blocking Warning Section
  115. if isTOTPBlocked && showTOTPWarning {
  116. Section {
  117. VStack(alignment: .leading, spacing: 8) {
  118. HStack {
  119. Image(systemName: "exclamationmark.triangle.fill")
  120. .foregroundColor(.orange)
  121. Text("TOTP Code Already Used")
  122. .font(.headline)
  123. .foregroundColor(.orange)
  124. }
  125. Text("This TOTP code has already been used for a command. Please wait for the next code to be generated before sending another command.")
  126. .font(.caption)
  127. .foregroundColor(.secondary)
  128. .multilineTextAlignment(.leading)
  129. }
  130. .padding(.vertical, 4)
  131. }
  132. }
  133. Section(header: Text("Security")) {
  134. VStack(alignment: .leading) {
  135. Text("Current OTP Code")
  136. .font(.headline)
  137. if let otpCode = TOTPGenerator.extractOTPFromURL(Storage.shared.loopAPNSQrCodeURL.value) {
  138. HStack {
  139. Text(otpCode)
  140. .font(.system(.body, design: .monospaced))
  141. .foregroundColor(.green)
  142. .padding(.vertical, 4)
  143. .padding(.horizontal, 8)
  144. .background(Color.green.opacity(0.1))
  145. .cornerRadius(4)
  146. Text("(" + (otpTimeRemaining.map { "\($0)s left" } ?? "-") + ")")
  147. .font(.caption)
  148. .foregroundColor(.secondary)
  149. }
  150. } else {
  151. Text("Invalid QR code URL")
  152. .foregroundColor(.red)
  153. }
  154. }
  155. }
  156. }
  157. .navigationTitle("Insulin")
  158. .navigationBarTitleDisplayMode(.inline)
  159. }
  160. .onAppear {
  161. // Validate APNS setup
  162. let apnsService = LoopAPNSService()
  163. if !apnsService.validateSetup() {
  164. alertMessage = "Loop APNS setup is incomplete. Please configure all required fields in settings."
  165. alertType = .error
  166. showAlert = true
  167. }
  168. loadRecommendedBolus()
  169. // Reset timer state so it shows '-' until first tick
  170. otpTimeRemaining = nil
  171. // Don't reset TOTP usage flag here - let the timer handle it
  172. // Validate TOTP state when view appears
  173. _ = isTOTPBlocked
  174. // Add delay before showing TOTP warning to prevent flash after successful send
  175. if isTOTPBlocked {
  176. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  177. showTOTPWarning = true
  178. }
  179. } else {
  180. showTOTPWarning = false
  181. }
  182. }
  183. .onReceive(otpTimer) { _ in
  184. let now = Date().timeIntervalSince1970
  185. let newOtpTimeRemaining = Int(otpPeriod - (now.truncatingRemainder(dividingBy: otpPeriod)))
  186. // Check if we've moved to a new TOTP period (when time remaining increases)
  187. if let currentOtpTimeRemaining = otpTimeRemaining,
  188. newOtpTimeRemaining > currentOtpTimeRemaining
  189. {
  190. // New TOTP code generated, reset the usage flag
  191. TOTPService.shared.resetTOTPUsage()
  192. }
  193. // Also check if we're at the very beginning of a new period (when time remaining is close to 30)
  194. if newOtpTimeRemaining >= 29 {
  195. // We're at the start of a new TOTP period, reset the usage flag
  196. TOTPService.shared.resetTOTPUsage()
  197. }
  198. otpTimeRemaining = newOtpTimeRemaining
  199. // Check if recommended bolus calculation is older than 5 minutes (but less than 12 minutes)
  200. if let lastLoopTime = lastLoopTime {
  201. let timeSinceCalculation = now - lastLoopTime
  202. let minutesSinceCalculation = Int(timeSinceCalculation / 60)
  203. // Only show warning if calculation is between 5-12 minutes old
  204. if minutesSinceCalculation > 5 && minutesSinceCalculation < 12 && !showOldCalculationWarning {
  205. showOldCalculationWarning = true
  206. alertMessage = "This recommended bolus was calculated \(minutesSinceCalculation) minutes ago. New treatments may have occurred since then. Proceed with caution."
  207. alertType = .oldCalculationWarning
  208. showAlert = true
  209. }
  210. }
  211. }
  212. .alert(isPresented: $showAlert) {
  213. switch alertType {
  214. case .success:
  215. return Alert(
  216. title: Text("Success"),
  217. message: Text(alertMessage),
  218. dismissButton: .default(Text("OK")) {
  219. presentationMode.wrappedValue.dismiss()
  220. }
  221. )
  222. case .error:
  223. return Alert(
  224. title: Text("Error"),
  225. message: Text(alertMessage),
  226. dismissButton: .default(Text("OK"))
  227. )
  228. case .confirmation:
  229. return Alert(
  230. title: Text("Confirm Insulin"),
  231. message: Text("Send \(String(format: "%.2f", insulinAmount.doubleValue(for: .internationalUnit()))) units of insulin?"),
  232. primaryButton: .default(Text("Send")) {
  233. authenticateAndSendInsulin()
  234. },
  235. secondaryButton: .cancel()
  236. )
  237. case .oldCalculationWarning:
  238. return Alert(
  239. title: Text("Old Calculation Warning"),
  240. message: Text(alertMessage),
  241. primaryButton: .default(Text("Use Anyway")) {
  242. applyRecommendedBolus()
  243. },
  244. secondaryButton: .cancel()
  245. )
  246. }
  247. }
  248. }
  249. }
  250. private func loadRecommendedBolus() {
  251. // Load recommended bolus from Observable
  252. recommendedBolus = Observable.shared.deviceRecBolus.value
  253. lastLoopTime = Observable.shared.alertLastLoopTime.value
  254. // Reset warning state when new data is loaded
  255. showOldCalculationWarning = false
  256. }
  257. private func handleRecommendedBolusTap() {
  258. guard let recommendedBolus = recommendedBolus, recommendedBolus > 0 else { return }
  259. // Apply the recommended bolus directly (warning is handled by timer)
  260. applyRecommendedBolus()
  261. }
  262. private func applyRecommendedBolus() {
  263. guard let recommendedBolus = recommendedBolus, recommendedBolus > 0 else { return }
  264. insulinAmount = HKQuantity(unit: .internationalUnit(), doubleValue: recommendedBolus)
  265. }
  266. private func presentableMinutesFormat(timeInterval: TimeInterval) -> String {
  267. let minutes = Int(timeInterval / 60)
  268. var result = "\(minutes) minute"
  269. if minutes == 0 || minutes > 1 {
  270. result += "s"
  271. }
  272. return result
  273. }
  274. private func sendInsulin() {
  275. guard insulinAmount.doubleValue(for: .internationalUnit()) > 0 else {
  276. alertMessage = "Please enter a valid insulin amount"
  277. alertType = .error
  278. showAlert = true
  279. return
  280. }
  281. // Check guardrails
  282. let maxBolus = Storage.shared.maxBolus.value.doubleValue(for: .internationalUnit())
  283. let insulinValue = insulinAmount.doubleValue(for: .internationalUnit())
  284. if insulinValue > maxBolus {
  285. alertMessage = "Insulin amount (\(String(format: "%.2f", insulinValue))U) exceeds the maximum allowed (\(String(format: "%.2f", maxBolus))U). Please reduce the amount."
  286. alertType = .error
  287. showAlert = true
  288. return
  289. }
  290. alertType = .confirmation
  291. showAlert = true
  292. }
  293. private func authenticateAndSendInsulin() {
  294. AuthService.authenticate(reason: "Confirm your identity to send insulin.") { result in
  295. DispatchQueue.main.async {
  296. switch result {
  297. case .success:
  298. self.sendInsulinConfirmed()
  299. case let .unavailable(message):
  300. self.alertMessage = message
  301. self.alertType = .error
  302. self.showAlert = true
  303. case .failed:
  304. self.alertMessage = "Authentication failed"
  305. self.alertType = .error
  306. self.showAlert = true
  307. case .canceled:
  308. // User canceled: no alert to avoid spammy UX
  309. break
  310. }
  311. }
  312. }
  313. }
  314. private func sendInsulinConfirmed() {
  315. isLoading = true
  316. // Extract OTP from QR code URL
  317. guard let otpCode = TOTPGenerator.extractOTPFromURL(Storage.shared.loopAPNSQrCodeURL.value) else {
  318. alertMessage = "Invalid QR code URL. Please re-scan the QR code in settings."
  319. alertType = .error
  320. isLoading = false
  321. showAlert = true
  322. return
  323. }
  324. let payload = LoopAPNSPayload(
  325. type: .bolus,
  326. bolusAmount: insulinAmount.doubleValue(for: .internationalUnit()),
  327. otp: otpCode
  328. )
  329. let apnsService = LoopAPNSService()
  330. apnsService.sendBolusViaAPNS(payload: payload) { success, errorMessage in
  331. DispatchQueue.main.async {
  332. self.isLoading = false
  333. if success {
  334. // Mark TOTP code as used
  335. TOTPService.shared.markTOTPAsUsed(qrCodeURL: Storage.shared.loopAPNSQrCodeURL.value)
  336. self.alertMessage = "Insulin sent successfully!"
  337. self.alertType = .success
  338. LogManager.shared.log(
  339. category: .apns,
  340. message: "Insulin sent - Amount: \(insulinAmount.doubleValue(for: .internationalUnit()))U"
  341. )
  342. } else {
  343. self.alertMessage = errorMessage ?? "Failed to send insulin. Check your Loop APNS configuration."
  344. self.alertType = .error
  345. LogManager.shared.log(
  346. category: .apns,
  347. message: "Failed to send insulin: \(errorMessage ?? "unknown error")"
  348. )
  349. }
  350. self.showAlert = true
  351. }
  352. }
  353. }
  354. }