DeviceStatus.swift 11 KB

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