DeviceStatus.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. // LoopFollow
  2. // DeviceStatus.swift
  3. import Foundation
  4. import HealthKit
  5. import SwiftUI
  6. extension MainViewController {
  7. func webLoadNSDeviceStatus() {
  8. let parameters = ["count": "1"]
  9. NightscoutUtils.executeDynamicRequest(eventType: .deviceStatus, parameters: parameters) { result in
  10. switch result {
  11. case let .success(json):
  12. if let jsonDeviceStatus = json as? [[String: AnyObject]] {
  13. DispatchQueue.main.async {
  14. self.updateDeviceStatusDisplay(jsonDeviceStatus: jsonDeviceStatus)
  15. Storage.shared.lastLoopingChecked.value = Date()
  16. }
  17. } else {
  18. self.handleDeviceStatusError()
  19. }
  20. case .failure:
  21. self.handleDeviceStatusError()
  22. }
  23. }
  24. }
  25. private func handleDeviceStatusError() {
  26. LogManager.shared.log(category: .deviceStatus, message: "Device status fetch failed!", limitIdentifier: "Device status fetch failed!")
  27. DispatchQueue.main.async {
  28. Storage.shared.lastLoopingChecked.value = Date()
  29. TaskScheduler.shared.rescheduleTask(id: .deviceStatus, to: Date().addingTimeInterval(10))
  30. self.evaluateNotLooping()
  31. }
  32. }
  33. func evaluateNotLooping() {
  34. guard let lastLoopTime = Observable.shared.alertLastLoopTime.value, lastLoopTime > 0 else {
  35. return
  36. }
  37. let now = TimeInterval(Date().timeIntervalSince1970)
  38. let nonLoopingTimeThreshold: TimeInterval = 15 * 60
  39. if IsNightscoutEnabled(), (now - lastLoopTime) >= nonLoopingTimeThreshold, lastLoopTime > 0 {
  40. IsNotLooping = true
  41. Observable.shared.isNotLooping.value = true
  42. Observable.shared.loopStatusText.value = "⚠️ Not Looping!"
  43. Observable.shared.loopStatusColor.value = .yellow
  44. #if !targetEnvironment(macCatalyst)
  45. LiveActivityManager.shared.refreshFromCurrentState(reason: "notLooping")
  46. #endif
  47. } else {
  48. IsNotLooping = false
  49. Observable.shared.isNotLooping.value = false
  50. Observable.shared.loopStatusColor.value = .primary
  51. #if !targetEnvironment(macCatalyst)
  52. LiveActivityManager.shared.refreshFromCurrentState(reason: "loopingResumed")
  53. #endif
  54. }
  55. }
  56. // NS Device Status Response Processor
  57. func updateDeviceStatusDisplay(jsonDeviceStatus: [[String: AnyObject]]) {
  58. let previousIOBText = Observable.shared.iobText.value
  59. infoManager.clearInfoData(types: [.iob, .cob, .battery, .pump, .pumpBattery, .target, .isf, .carbRatio, .updated, .recBolus, .tdd])
  60. // For Loop, clear the current override here - For Trio, it is handled using treatments
  61. if Storage.shared.device.value == "Loop" {
  62. infoManager.clearInfoData(types: [.override])
  63. }
  64. if jsonDeviceStatus.count == 0 {
  65. LogManager.shared.log(category: .deviceStatus, message: "Device status is empty")
  66. TaskScheduler.shared.rescheduleTask(id: .deviceStatus, to: Date().addingTimeInterval(5 * 60))
  67. return
  68. }
  69. // Process the current data first
  70. let lastDeviceStatus = jsonDeviceStatus[0] as [String: AnyObject]?
  71. // pump and uploader
  72. let formatter = ISO8601DateFormatter()
  73. formatter.formatOptions = [.withFullDate,
  74. .withTime,
  75. .withDashSeparatorInDate,
  76. .withColonSeparatorInTime]
  77. Observable.shared.previousAlertLastLoopTime.value = Observable.shared.alertLastLoopTime.value
  78. if let lastPumpRecord = lastDeviceStatus?["pump"] as! [String: AnyObject]? {
  79. if let bolusIncrement = lastPumpRecord["bolusIncrement"] as? Double, bolusIncrement > 0 {
  80. Storage.shared.bolusIncrement.value = HKQuantity(unit: .internationalUnit(), doubleValue: bolusIncrement)
  81. Storage.shared.bolusIncrementDetected.value = true
  82. } else if let model = lastPumpRecord["model"] as? String, model == "Dash" {
  83. Storage.shared.bolusIncrement.value = HKQuantity(unit: .internationalUnit(), doubleValue: 0.05)
  84. Storage.shared.bolusIncrementDetected.value = true
  85. } else {
  86. Storage.shared.bolusIncrementDetected.value = false
  87. }
  88. if let clockString = lastPumpRecord["clock"] as? String,
  89. let lastPumpTime = formatter.date(from: clockString)?.timeIntervalSince1970
  90. {
  91. let storedTime = Observable.shared.alertLastLoopTime.value ?? 0
  92. if lastPumpTime > storedTime {
  93. Observable.shared.alertLastLoopTime.value = lastPumpTime
  94. Storage.shared.lastLoopTime.value = lastPumpTime
  95. }
  96. if let reservoirData = lastPumpRecord["reservoir"] as? Double {
  97. latestPumpVolume = reservoirData
  98. infoManager.updateInfoData(type: .pump, value: String(format: "%.0f", reservoirData) + "U")
  99. Storage.shared.lastPumpReservoirU.value = reservoirData
  100. } else {
  101. latestPumpVolume = 50.0
  102. infoManager.updateInfoData(type: .pump, value: "50+U")
  103. Storage.shared.lastPumpReservoirU.value = nil
  104. }
  105. }
  106. // Parse pump battery percentage
  107. if let pumpBatteryRecord = lastPumpRecord["battery"] as? [String: AnyObject],
  108. let pumpBatteryPercent = pumpBatteryRecord["percent"] as? Double
  109. {
  110. infoManager.updateInfoData(type: .pumpBattery, value: String(format: "%.0f", pumpBatteryPercent) + "%")
  111. Observable.shared.pumpBatteryLevel.value = pumpBatteryPercent
  112. }
  113. if let uploader = lastDeviceStatus?["uploader"] as? [String: AnyObject],
  114. let upbat = uploader["battery"] as? Double
  115. {
  116. let batteryText: String
  117. if let isCharging = uploader["isCharging"] as? Bool, isCharging {
  118. batteryText = "⚡️ " + String(format: "%.0f", upbat) + "%"
  119. } else {
  120. batteryText = String(format: "%.0f", upbat) + "%"
  121. }
  122. infoManager.updateInfoData(type: .battery, value: batteryText)
  123. Observable.shared.deviceBatteryLevel.value = upbat
  124. let timestamp = uploader["timestamp"] as? Date ?? Date()
  125. let currentBattery = DataStructs.batteryStruct(batteryLevel: upbat, timestamp: timestamp)
  126. deviceBatteryData.append(currentBattery)
  127. // store only the last 30 battery readings
  128. if deviceBatteryData.count > 30 {
  129. deviceBatteryData.removeFirst()
  130. }
  131. }
  132. }
  133. // Loop - handle new data
  134. if let lastLoopRecord = lastDeviceStatus?["loop"] as! [String: AnyObject]? {
  135. DeviceStatusLoop(formatter: formatter, lastLoopRecord: lastLoopRecord)
  136. var oText = ""
  137. currentOverride = 1.0
  138. if let lastOverride = lastDeviceStatus?["override"] as? [String: AnyObject],
  139. let isActive = lastOverride["active"] as? Bool, isActive
  140. {
  141. if let lastCorrection = lastOverride["currentCorrectionRange"] as? [String: AnyObject],
  142. let minValue = lastCorrection["minValue"] as? Double,
  143. let maxValue = lastCorrection["maxValue"] as? Double
  144. {
  145. if let multiplier = lastOverride["multiplier"] as? Double {
  146. currentOverride = multiplier
  147. oText += String(format: "%.0f%%", multiplier * 100)
  148. } else {
  149. oText += "100%"
  150. }
  151. oText += " ("
  152. oText += Localizer.toDisplayUnits(String(minValue)) + "-" + Localizer.toDisplayUnits(String(maxValue)) + ")"
  153. }
  154. infoManager.updateInfoData(type: .override, value: oText)
  155. } else {
  156. infoManager.clearInfoData(type: .override)
  157. }
  158. }
  159. // OpenAPS - handle new data
  160. if let lastLoopRecord = lastDeviceStatus?["openaps"] as! [String: AnyObject]? {
  161. DeviceStatusOpenAPS(formatter: formatter, lastDeviceStatus: lastDeviceStatus, lastLoopRecord: lastLoopRecord)
  162. }
  163. // Start the timer based on the timestamp
  164. let now = dateTimeUtils.getNowTimeIntervalUTC()
  165. let secondsAgo = now - (Observable.shared.alertLastLoopTime.value ?? 0)
  166. DispatchQueue.main.async {
  167. if secondsAgo >= (20 * 60) {
  168. TaskScheduler.shared.rescheduleTask(
  169. id: .deviceStatus,
  170. to: Date().addingTimeInterval(5 * 60)
  171. )
  172. } else if secondsAgo >= (10 * 60) {
  173. TaskScheduler.shared.rescheduleTask(
  174. id: .deviceStatus,
  175. to: Date().addingTimeInterval(60)
  176. )
  177. } else if secondsAgo >= (7 * 60) {
  178. TaskScheduler.shared.rescheduleTask(
  179. id: .deviceStatus,
  180. to: Date().addingTimeInterval(30)
  181. )
  182. } else if secondsAgo >= (5 * 60) {
  183. TaskScheduler.shared.rescheduleTask(
  184. id: .deviceStatus,
  185. to: Date().addingTimeInterval(10)
  186. )
  187. } else {
  188. let interval = (310 - secondsAgo)
  189. TaskScheduler.shared.rescheduleTask(
  190. id: .deviceStatus,
  191. to: Date().addingTimeInterval(interval)
  192. )
  193. TaskScheduler.shared.rescheduleTask(id: .alarmCheck, to: Date().addingTimeInterval(3))
  194. }
  195. }
  196. evaluateNotLooping()
  197. // Mark device status as loaded for initial loading state
  198. markDataLoaded("deviceStatus")
  199. if Storage.shared.contactEnabled.value, Storage.shared.contactIOB.value != .off,
  200. Observable.shared.iobText.value != previousIOBText
  201. {
  202. contactImageUpdater.updateContactImage(
  203. bgValue: Observable.shared.bgText.value,
  204. trend: Observable.shared.directionText.value,
  205. delta: Observable.shared.deltaText.value,
  206. iob: Observable.shared.iobText.value,
  207. stale: Observable.shared.bgStale.value
  208. )
  209. }
  210. LogManager.shared.log(category: .deviceStatus, message: "Update Device Status done", isDebug: true)
  211. }
  212. }