BackgroundRefreshSettingsView.swift 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. // LoopFollow
  2. // BackgroundRefreshSettingsView.swift
  3. import SwiftUI
  4. struct BackgroundRefreshSettingsView: View {
  5. @ObservedObject var viewModel: BackgroundRefreshSettingsViewModel
  6. @State private var forceRefresh = false
  7. @State private var timer: Timer?
  8. @ObservedObject var bleManager = BLEManager.shared
  9. var body: some View {
  10. Form {
  11. refreshTypeSection
  12. if viewModel.backgroundRefreshType.isBluetooth {
  13. selectedDeviceSection
  14. availableDevicesSection
  15. }
  16. }
  17. .onAppear {
  18. startTimer()
  19. }
  20. .onDisappear {
  21. stopTimer()
  22. }
  23. .preferredColorScheme(Storage.shared.appearanceMode.value.colorScheme)
  24. .navigationBarTitle("Background Refresh Settings", displayMode: .inline)
  25. }
  26. // MARK: - Subviews / Computed Properties
  27. private var refreshTypeSection: some View {
  28. Section {
  29. Picker("Background Refresh Type", selection: $viewModel.backgroundRefreshType) {
  30. ForEach(BackgroundRefreshType.allCases, id: \.self) { type in
  31. Text(type.rawValue).tag(type)
  32. }
  33. }
  34. .pickerStyle(MenuPickerStyle())
  35. VStack(alignment: .leading, spacing: 4) {
  36. Text("Adjust the background refresh type.")
  37. .font(.footnote)
  38. .foregroundColor(.secondary)
  39. switch viewModel.backgroundRefreshType {
  40. case .none:
  41. Text("No background refresh. Alarms and updates will not work unless the app is open in the foreground.")
  42. .font(.footnote)
  43. .foregroundColor(.secondary)
  44. case .silentTune:
  45. Text("A silent tune will play in the background, keeping the app active. May be interrupted by other apps. Allows continuous updates but consumes more battery.")
  46. .font(.footnote)
  47. .foregroundColor(.secondary)
  48. case .rileyLink:
  49. Text("Requires a RileyLink-compatible device within Bluetooth range. Provides updates once per minute and uses less battery than the silent tune method.")
  50. .font(.footnote)
  51. .foregroundColor(.secondary)
  52. case .dexcom:
  53. Text("Requires a Dexcom G6/ONE/G7/ONE+ transmitter within Bluetooth range. Provides updates every 5 minutes and uses less battery than the silent tune method. If you have more than one device to choose from, select the one with the smallest expected bg delay.")
  54. .font(.footnote)
  55. .foregroundColor(.secondary)
  56. case .omnipodDash:
  57. Text("Requires an OmniPod DASH pod paired with this device within Bluetooth range. Provides updates once every 3 minutes and uses less battery than the silent tune method.")
  58. .font(.footnote)
  59. .foregroundColor(.secondary)
  60. }
  61. }
  62. }
  63. }
  64. @ViewBuilder
  65. private var selectedDeviceSection: some View {
  66. if let storedDevice = bleManager.getSelectedDevice() {
  67. Section(header: Text("Selected Device")) {
  68. VStack(alignment: .leading, spacing: 4) {
  69. Text(storedDevice.name ?? "Unknown Device")
  70. .font(.headline)
  71. deviceConnectionStatus(for: storedDevice)
  72. if storedDevice.rssi != 0 {
  73. Text("RSSI: \(storedDevice.rssi) dBm")
  74. .foregroundColor(.secondary)
  75. .font(.footnote)
  76. }
  77. if let offset = BLEManager.shared.expectedSensorFetchOffsetString(for: storedDevice) {
  78. Text("Expected bg delay: \(offset)")
  79. .foregroundColor(.secondary)
  80. .font(.footnote)
  81. }
  82. HStack {
  83. Spacer()
  84. Button(action: {
  85. bleManager.disconnect()
  86. }) {
  87. Text("Disconnect")
  88. .foregroundColor(.blue)
  89. }
  90. .buttonStyle(BorderlessButtonStyle())
  91. Spacer()
  92. }
  93. }
  94. .padding(.vertical, 8)
  95. }
  96. .id(forceRefresh)
  97. }
  98. }
  99. private func formattedTimeString(from seconds: TimeInterval) -> String {
  100. if seconds < 60 {
  101. return "\(Int(seconds)) seconds"
  102. } else {
  103. let minutes = Int(seconds / 60)
  104. let seconds = Int(seconds.truncatingRemainder(dividingBy: 60))
  105. return "\(minutes):\(String(format: "%02d", seconds)) minutes"
  106. }
  107. }
  108. private var availableDevicesSection: some View {
  109. Section(header: scanningStatusHeader) {
  110. BLEDeviceSelectionView(
  111. bleManager: bleManager,
  112. selectedFilter: viewModel.backgroundRefreshType,
  113. onSelectDevice: { device in
  114. bleManager.connect(device: device)
  115. }
  116. )
  117. }
  118. }
  119. private var scanningStatusHeader: some View {
  120. Text("Scanning for \(viewModel.backgroundRefreshType.rawValue)...")
  121. .font(.subheadline)
  122. .foregroundColor(.secondary)
  123. }
  124. private func deviceConnectionStatus(for device: BLEDevice) -> some View {
  125. let expectedConnectionTime: TimeInterval = bleManager.expectedHeartbeatInterval() ?? 300
  126. let now = Date()
  127. let timeSinceLastConnection = device.isConnected ? 0 : now.timeIntervalSince(device.lastConnected ?? now)
  128. if device.isConnected {
  129. return Text("Connected")
  130. .foregroundColor(.green)
  131. } else if let lastConnected = device.lastConnected {
  132. let timeRatio = timeSinceLastConnection / expectedConnectionTime
  133. let timeString = formattedTimeString(from: timeSinceLastConnection)
  134. if timeRatio < 1.0 {
  135. return Text("Disconnected for \(timeString)")
  136. .foregroundColor(.green)
  137. } else if timeRatio <= 1.15 {
  138. return Text("Disconnected for \(timeString)")
  139. .foregroundColor(.orange)
  140. } else if timeRatio <= 3.0 {
  141. return Text("Disconnected for \(timeString)")
  142. .foregroundColor(.red)
  143. } else {
  144. let date = dateTimeUtils.formattedDate(from: lastConnected)
  145. return Text("Last connection: \(date)")
  146. .foregroundColor(.red)
  147. }
  148. } else {
  149. return Text("Reconnecting...")
  150. .foregroundColor(.orange)
  151. }
  152. }
  153. private func startTimer() {
  154. timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
  155. self.forceRefresh.toggle()
  156. }
  157. }
  158. private func stopTimer() {
  159. timer?.invalidate()
  160. timer = nil
  161. }
  162. }