BackgroundRefreshSettingsView.swift 7.1 KB

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