DeviceStatus.swift 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. infoManager.clearInfoData(types: [.iob, .cob, .battery, .pump, .target, .isf, .carbRatio, .updated, .recBolus, .tdd])
  69. // For Loop, clear the current override here - For Trio, it is handled using treatments
  70. if Storage.shared.device.value == "Loop" {
  71. infoManager.clearInfoData(types: [.override])
  72. }
  73. if jsonDeviceStatus.count == 0 {
  74. LogManager.shared.log(category: .deviceStatus, message: "Device status is empty")
  75. TaskScheduler.shared.rescheduleTask(id: .deviceStatus, to: Date().addingTimeInterval(5 * 60))
  76. return
  77. }
  78. // Process the current data first
  79. let lastDeviceStatus = jsonDeviceStatus[0] as [String: AnyObject]?
  80. // pump and uploader
  81. let formatter = ISO8601DateFormatter()
  82. formatter.formatOptions = [.withFullDate,
  83. .withTime,
  84. .withDashSeparatorInDate,
  85. .withColonSeparatorInTime]
  86. Observable.shared.previousAlertLastLoopTime.value = Observable.shared.alertLastLoopTime.value
  87. if let lastPumpRecord = lastDeviceStatus?["pump"] as! [String: AnyObject]? {
  88. if let bolusIncrement = lastPumpRecord["bolusIncrement"] as? Double, bolusIncrement > 0 {
  89. Storage.shared.bolusIncrement.value = HKQuantity(unit: .internationalUnit(), doubleValue: bolusIncrement)
  90. Storage.shared.bolusIncrementDetected.value = true
  91. } else if let model = lastPumpRecord["model"] as? String, model == "Dash" {
  92. Storage.shared.bolusIncrement.value = HKQuantity(unit: .internationalUnit(), doubleValue: 0.05)
  93. Storage.shared.bolusIncrementDetected.value = true
  94. } else {
  95. Storage.shared.bolusIncrementDetected.value = false
  96. }
  97. if let clockString = lastPumpRecord["clock"] as? String,
  98. let lastPumpTime = formatter.date(from: clockString)?.timeIntervalSince1970
  99. {
  100. let storedTime = Observable.shared.alertLastLoopTime.value ?? 0
  101. if lastPumpTime > storedTime {
  102. Observable.shared.alertLastLoopTime.value = lastPumpTime
  103. }
  104. if let reservoirData = lastPumpRecord["reservoir"] as? Double {
  105. latestPumpVolume = reservoirData
  106. infoManager.updateInfoData(type: .pump, value: String(format: "%.0f", reservoirData) + "U")
  107. } else {
  108. latestPumpVolume = 50.0
  109. infoManager.updateInfoData(type: .pump, value: "50+U")
  110. }
  111. }
  112. if let uploader = lastDeviceStatus?["uploader"] as? [String: AnyObject],
  113. let upbat = uploader["battery"] as? Double
  114. {
  115. let batteryText: String
  116. if let isCharging = uploader["isCharging"] as? Bool, isCharging {
  117. batteryText = "⚡️ " + String(format: "%.0f", upbat) + "%"
  118. } else {
  119. batteryText = String(format: "%.0f", upbat) + "%"
  120. }
  121. infoManager.updateInfoData(type: .battery, value: batteryText)
  122. Observable.shared.deviceBatteryLevel.value = upbat
  123. let timestamp = uploader["timestamp"] as? Date ?? Date()
  124. let currentBattery = DataStructs.batteryStruct(batteryLevel: upbat, timestamp: timestamp)
  125. deviceBatteryData.append(currentBattery)
  126. // store only the last 30 battery readings
  127. if deviceBatteryData.count > 30 {
  128. deviceBatteryData.removeFirst()
  129. }
  130. }
  131. }
  132. // Loop - handle new data
  133. if let lastLoopRecord = lastDeviceStatus?["loop"] as! [String: AnyObject]? {
  134. DeviceStatusLoop(formatter: formatter, lastLoopRecord: lastLoopRecord)
  135. var oText = ""
  136. currentOverride = 1.0
  137. if let lastOverride = lastDeviceStatus?["override"] as? [String: AnyObject],
  138. let isActive = lastOverride["active"] as? Bool, isActive
  139. {
  140. if let lastCorrection = lastOverride["currentCorrectionRange"] as? [String: AnyObject],
  141. let minValue = lastCorrection["minValue"] as? Double,
  142. let maxValue = lastCorrection["maxValue"] as? Double
  143. {
  144. if let multiplier = lastOverride["multiplier"] as? Double {
  145. currentOverride = multiplier
  146. oText += String(format: "%.0f%%", multiplier * 100)
  147. } else {
  148. oText += "100%"
  149. }
  150. oText += " ("
  151. oText += Localizer.toDisplayUnits(String(minValue)) + "-" + Localizer.toDisplayUnits(String(maxValue)) + ")"
  152. }
  153. infoManager.updateInfoData(type: .override, value: oText)
  154. } else {
  155. infoManager.clearInfoData(type: .override)
  156. }
  157. }
  158. // OpenAPS - handle new data
  159. if let lastLoopRecord = lastDeviceStatus?["openaps"] as! [String: AnyObject]? {
  160. DeviceStatusOpenAPS(formatter: formatter, lastDeviceStatus: lastDeviceStatus, lastLoopRecord: lastLoopRecord)
  161. }
  162. // Start the timer based on the timestamp
  163. let now = dateTimeUtils.getNowTimeIntervalUTC()
  164. let secondsAgo = now - (Observable.shared.alertLastLoopTime.value ?? 0)
  165. DispatchQueue.main.async {
  166. if secondsAgo >= (20 * 60) {
  167. TaskScheduler.shared.rescheduleTask(
  168. id: .deviceStatus,
  169. to: Date().addingTimeInterval(5 * 60)
  170. )
  171. } else if secondsAgo >= (10 * 60) {
  172. TaskScheduler.shared.rescheduleTask(
  173. id: .deviceStatus,
  174. to: Date().addingTimeInterval(60)
  175. )
  176. } else if secondsAgo >= (7 * 60) {
  177. TaskScheduler.shared.rescheduleTask(
  178. id: .deviceStatus,
  179. to: Date().addingTimeInterval(30)
  180. )
  181. } else if secondsAgo >= (5 * 60) {
  182. TaskScheduler.shared.rescheduleTask(
  183. id: .deviceStatus,
  184. to: Date().addingTimeInterval(10)
  185. )
  186. } else {
  187. let interval = (310 - secondsAgo)
  188. TaskScheduler.shared.rescheduleTask(
  189. id: .deviceStatus,
  190. to: Date().addingTimeInterval(interval)
  191. )
  192. TaskScheduler.shared.rescheduleTask(id: .alarmCheck, to: Date().addingTimeInterval(3))
  193. }
  194. }
  195. evaluateNotLooping()
  196. // Mark device status as loaded for initial loading state
  197. markDataLoaded("deviceStatus")
  198. LogManager.shared.log(category: .deviceStatus, message: "Update Device Status done", isDebug: true)
  199. }
  200. }