LoopAPNSBolusView.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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. // TOTP Blocking Warning Section
  100. if isTOTPBlocked && showTOTPWarning {
  101. Section {
  102. VStack(alignment: .leading, spacing: 8) {
  103. HStack {
  104. Image(systemName: "exclamationmark.triangle.fill")
  105. .foregroundColor(.orange)
  106. Text("TOTP Code Already Used")
  107. .font(.headline)
  108. .foregroundColor(.orange)
  109. }
  110. Text("This TOTP code has already been used for a command. Please wait for the next code to be generated before sending another command.")
  111. .font(.caption)
  112. .foregroundColor(.secondary)
  113. .multilineTextAlignment(.leading)
  114. }
  115. .padding(.vertical, 4)
  116. }
  117. }
  118. Section(header: Text("Security")) {
  119. VStack(alignment: .leading) {
  120. Text("Current OTP Code")
  121. .font(.headline)
  122. if let otpCode = TOTPGenerator.extractOTPFromURL(Storage.shared.loopAPNSQrCodeURL.value) {
  123. HStack {
  124. Text(otpCode)
  125. .font(.system(.body, design: .monospaced))
  126. .foregroundColor(.green)
  127. .padding(.vertical, 4)
  128. .padding(.horizontal, 8)
  129. .background(Color.green.opacity(0.1))
  130. .cornerRadius(4)
  131. Text("(" + (otpTimeRemaining.map { "\($0)s left" } ?? "-") + ")")
  132. .font(.caption)
  133. .foregroundColor(.secondary)
  134. }
  135. } else {
  136. Text("Invalid QR code URL")
  137. .foregroundColor(.red)
  138. }
  139. }
  140. }
  141. }
  142. .safeAreaInset(edge: .bottom) {
  143. Button(action: sendInsulin) {
  144. if isLoading {
  145. HStack {
  146. ProgressView()
  147. .scaleEffect(0.8)
  148. Text("Sending...")
  149. }
  150. .frame(maxWidth: .infinity)
  151. } else {
  152. Text("Send Insulin")
  153. .frame(maxWidth: .infinity)
  154. }
  155. }
  156. .buttonStyle(.borderedProminent)
  157. .controlSize(.large)
  158. .disabled(insulinAmount.doubleValue(for: .internationalUnit()) <= 0 || isLoading || isTOTPBlocked)
  159. .padding(.horizontal)
  160. .padding(.vertical, 8)
  161. .background(.bar)
  162. }
  163. .navigationTitle("Insulin")
  164. .navigationBarTitleDisplayMode(.inline)
  165. }
  166. .onAppear {
  167. // Validate APNS setup
  168. let apnsService = LoopAPNSService()
  169. if !apnsService.validateSetup() {
  170. alertMessage = "Loop APNS setup is incomplete. Please configure all required fields in settings."
  171. alertType = .error
  172. showAlert = true
  173. }
  174. loadRecommendedBolus()
  175. // Reset timer state so it shows '-' until first tick
  176. otpTimeRemaining = nil
  177. // Don't reset TOTP usage flag here - let the timer handle it
  178. // Validate TOTP state when view appears
  179. _ = isTOTPBlocked
  180. // Add delay before showing TOTP warning to prevent flash after successful send
  181. if isTOTPBlocked {
  182. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  183. showTOTPWarning = true
  184. }
  185. } else {
  186. showTOTPWarning = false
  187. }
  188. }
  189. .onReceive(otpTimer) { _ in
  190. let now = Date().timeIntervalSince1970
  191. let newOtpTimeRemaining = Int(otpPeriod - (now.truncatingRemainder(dividingBy: otpPeriod)))
  192. // Check if we've moved to a new TOTP period (when time remaining increases)
  193. if let currentOtpTimeRemaining = otpTimeRemaining,
  194. newOtpTimeRemaining > currentOtpTimeRemaining
  195. {
  196. // New TOTP code generated, reset the usage flag
  197. TOTPService.shared.resetTOTPUsage()
  198. }
  199. // Also check if we're at the very beginning of a new period (when time remaining is close to 30)
  200. if newOtpTimeRemaining >= 29 {
  201. // We're at the start of a new TOTP period, reset the usage flag
  202. TOTPService.shared.resetTOTPUsage()
  203. }
  204. otpTimeRemaining = newOtpTimeRemaining
  205. // Check if recommended bolus calculation is older than 5 minutes (but less than 12 minutes)
  206. if let lastLoopTime = lastLoopTime {
  207. let timeSinceCalculation = now - lastLoopTime
  208. let minutesSinceCalculation = Int(timeSinceCalculation / 60)
  209. // Only show warning if calculation is between 5-12 minutes old
  210. if minutesSinceCalculation > 5 && minutesSinceCalculation < 12 && !showOldCalculationWarning {
  211. showOldCalculationWarning = true
  212. alertMessage = "This recommended bolus was calculated \(minutesSinceCalculation) minutes ago. New treatments may have occurred since then. Proceed with caution."
  213. alertType = .oldCalculationWarning
  214. showAlert = true
  215. }
  216. }
  217. }
  218. .alert(isPresented: $showAlert) {
  219. switch alertType {
  220. case .success:
  221. return Alert(
  222. title: Text("Success"),
  223. message: Text(alertMessage),
  224. dismissButton: .default(Text("OK")) {
  225. presentationMode.wrappedValue.dismiss()
  226. }
  227. )
  228. case .error:
  229. return Alert(
  230. title: Text("Error"),
  231. message: Text(alertMessage),
  232. dismissButton: .default(Text("OK"))
  233. )
  234. case .confirmation:
  235. return Alert(
  236. title: Text("Confirm Insulin"),
  237. message: Text("Send \(String(format: "%.2f", insulinAmount.doubleValue(for: .internationalUnit()))) units of insulin?"),
  238. primaryButton: .default(Text("Send")) {
  239. authenticateAndSendInsulin()
  240. },
  241. secondaryButton: .cancel()
  242. )
  243. case .oldCalculationWarning:
  244. return Alert(
  245. title: Text("Old Calculation Warning"),
  246. message: Text(alertMessage),
  247. primaryButton: .default(Text("Use Anyway")) {
  248. applyRecommendedBolus()
  249. },
  250. secondaryButton: .cancel()
  251. )
  252. }
  253. }
  254. }
  255. }
  256. private func loadRecommendedBolus() {
  257. // Load recommended bolus from Observable
  258. recommendedBolus = Observable.shared.deviceRecBolus.value
  259. lastLoopTime = Observable.shared.alertLastLoopTime.value
  260. // Reset warning state when new data is loaded
  261. showOldCalculationWarning = false
  262. }
  263. private func handleRecommendedBolusTap() {
  264. guard let recommendedBolus = recommendedBolus, recommendedBolus > 0 else { return }
  265. // Apply the recommended bolus directly (warning is handled by timer)
  266. applyRecommendedBolus()
  267. }
  268. private func applyRecommendedBolus() {
  269. guard let recommendedBolus = recommendedBolus, recommendedBolus > 0 else { return }
  270. insulinAmount = HKQuantity(unit: .internationalUnit(), doubleValue: recommendedBolus)
  271. }
  272. private func presentableMinutesFormat(timeInterval: TimeInterval) -> String {
  273. let minutes = Int(timeInterval / 60)
  274. var result = "\(minutes) minute"
  275. if minutes == 0 || minutes > 1 {
  276. result += "s"
  277. }
  278. return result
  279. }
  280. private func sendInsulin() {
  281. guard insulinAmount.doubleValue(for: .internationalUnit()) > 0 else {
  282. alertMessage = "Please enter a valid insulin amount"
  283. alertType = .error
  284. showAlert = true
  285. return
  286. }
  287. // Check guardrails
  288. let maxBolus = Storage.shared.maxBolus.value.doubleValue(for: .internationalUnit())
  289. let insulinValue = insulinAmount.doubleValue(for: .internationalUnit())
  290. if insulinValue > maxBolus {
  291. alertMessage = "Insulin amount (\(String(format: "%.2f", insulinValue))U) exceeds the maximum allowed (\(String(format: "%.2f", maxBolus))U). Please reduce the amount."
  292. alertType = .error
  293. showAlert = true
  294. return
  295. }
  296. alertType = .confirmation
  297. showAlert = true
  298. }
  299. private func authenticateAndSendInsulin() {
  300. AuthService.authenticate(reason: "Confirm your identity to send insulin.") { result in
  301. DispatchQueue.main.async {
  302. switch result {
  303. case .success:
  304. self.sendInsulinConfirmed()
  305. case let .unavailable(message):
  306. self.alertMessage = message
  307. self.alertType = .error
  308. self.showAlert = true
  309. case .failed:
  310. self.alertMessage = "Authentication failed"
  311. self.alertType = .error
  312. self.showAlert = true
  313. case .canceled:
  314. // User canceled: no alert to avoid spammy UX
  315. break
  316. }
  317. }
  318. }
  319. }
  320. private func sendInsulinConfirmed() {
  321. isLoading = true
  322. // Extract OTP from QR code URL
  323. guard let otpCode = TOTPGenerator.extractOTPFromURL(Storage.shared.loopAPNSQrCodeURL.value) else {
  324. alertMessage = "Invalid QR code URL. Please re-scan the QR code in settings."
  325. alertType = .error
  326. isLoading = false
  327. showAlert = true
  328. return
  329. }
  330. let payload = LoopAPNSPayload(
  331. type: .bolus,
  332. bolusAmount: insulinAmount.doubleValue(for: .internationalUnit()),
  333. otp: otpCode
  334. )
  335. let apnsService = LoopAPNSService()
  336. apnsService.sendBolusViaAPNS(payload: payload) { success, errorMessage in
  337. DispatchQueue.main.async {
  338. self.isLoading = false
  339. if success {
  340. // Mark TOTP code as used
  341. TOTPService.shared.markTOTPAsUsed(qrCodeURL: Storage.shared.loopAPNSQrCodeURL.value)
  342. self.alertMessage = "Insulin sent successfully!"
  343. self.alertType = .success
  344. LogManager.shared.log(
  345. category: .apns,
  346. message: "Insulin sent - Amount: \(insulinAmount.doubleValue(for: .internationalUnit()))U"
  347. )
  348. } else {
  349. self.alertMessage = errorMessage ?? "Failed to send insulin. Check your Loop APNS configuration."
  350. self.alertType = .error
  351. LogManager.shared.log(
  352. category: .apns,
  353. message: "Failed to send insulin: \(errorMessage ?? "unknown error")"
  354. )
  355. }
  356. self.showAlert = true
  357. }
  358. }
  359. }
  360. }