DeviceStatus.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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, .pumpBattery, .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. // Parse pump battery percentage
  113. if let pumpBatteryRecord = lastPumpRecord["battery"] as? [String: AnyObject],
  114. let pumpBatteryPercent = pumpBatteryRecord["percent"] as? Double
  115. {
  116. infoManager.updateInfoData(type: .pumpBattery, value: String(format: "%.0f", pumpBatteryPercent) + "%")
  117. Observable.shared.pumpBatteryLevel.value = pumpBatteryPercent
  118. }
  119. if let uploader = lastDeviceStatus?["uploader"] as? [String: AnyObject],
  120. let upbat = uploader["battery"] as? Double
  121. {
  122. let batteryText: String
  123. if let isCharging = uploader["isCharging"] as? Bool, isCharging {
  124. batteryText = "⚡️ " + String(format: "%.0f", upbat) + "%"
  125. } else {
  126. batteryText = String(format: "%.0f", upbat) + "%"
  127. }
  128. infoManager.updateInfoData(type: .battery, value: batteryText)
  129. Observable.shared.deviceBatteryLevel.value = upbat
  130. let timestamp = uploader["timestamp"] as? Date ?? Date()
  131. let currentBattery = DataStructs.batteryStruct(batteryLevel: upbat, timestamp: timestamp)
  132. deviceBatteryData.append(currentBattery)
  133. // store only the last 30 battery readings
  134. if deviceBatteryData.count > 30 {
  135. deviceBatteryData.removeFirst()
  136. }
  137. }
  138. }
  139. // Loop - handle new data
  140. if let lastLoopRecord = lastDeviceStatus?["loop"] as! [String: AnyObject]? {
  141. DeviceStatusLoop(formatter: formatter, lastLoopRecord: lastLoopRecord)
  142. var oText = ""
  143. currentOverride = 1.0
  144. if let lastOverride = lastDeviceStatus?["override"] as? [String: AnyObject],
  145. let isActive = lastOverride["active"] as? Bool, isActive
  146. {
  147. if let lastCorrection = lastOverride["currentCorrectionRange"] as? [String: AnyObject],
  148. let minValue = lastCorrection["minValue"] as? Double,
  149. let maxValue = lastCorrection["maxValue"] as? Double
  150. {
  151. if let multiplier = lastOverride["multiplier"] as? Double {
  152. currentOverride = multiplier
  153. oText += String(format: "%.0f%%", multiplier * 100)
  154. } else {
  155. oText += "100%"
  156. }
  157. oText += " ("
  158. oText += Localizer.toDisplayUnits(String(minValue)) + "-" + Localizer.toDisplayUnits(String(maxValue)) + ")"
  159. }
  160. infoManager.updateInfoData(type: .override, value: oText)
  161. } else {
  162. infoManager.clearInfoData(type: .override)
  163. }
  164. }
  165. // OpenAPS - handle new data
  166. if let lastLoopRecord = lastDeviceStatus?["openaps"] as! [String: AnyObject]? {
  167. DeviceStatusOpenAPS(formatter: formatter, lastDeviceStatus: lastDeviceStatus, lastLoopRecord: lastLoopRecord)
  168. }
  169. // Start the timer based on the timestamp
  170. let now = dateTimeUtils.getNowTimeIntervalUTC()
  171. let secondsAgo = now - (Observable.shared.alertLastLoopTime.value ?? 0)
  172. DispatchQueue.main.async {
  173. if secondsAgo >= (20 * 60) {
  174. TaskScheduler.shared.rescheduleTask(
  175. id: .deviceStatus,
  176. to: Date().addingTimeInterval(5 * 60)
  177. )
  178. } else if secondsAgo >= (10 * 60) {
  179. TaskScheduler.shared.rescheduleTask(
  180. id: .deviceStatus,
  181. to: Date().addingTimeInterval(60)
  182. )
  183. } else if secondsAgo >= (7 * 60) {
  184. TaskScheduler.shared.rescheduleTask(
  185. id: .deviceStatus,
  186. to: Date().addingTimeInterval(30)
  187. )
  188. } else if secondsAgo >= (5 * 60) {
  189. TaskScheduler.shared.rescheduleTask(
  190. id: .deviceStatus,
  191. to: Date().addingTimeInterval(10)
  192. )
  193. } else {
  194. let interval = (310 - secondsAgo)
  195. TaskScheduler.shared.rescheduleTask(
  196. id: .deviceStatus,
  197. to: Date().addingTimeInterval(interval)
  198. )
  199. TaskScheduler.shared.rescheduleTask(id: .alarmCheck, to: Date().addingTimeInterval(3))
  200. }
  201. }
  202. evaluateNotLooping()
  203. // Mark device status as loaded for initial loading state
  204. markDataLoaded("deviceStatus")
  205. LogManager.shared.log(category: .deviceStatus, message: "Update Device Status done", isDebug: true)
  206. }
  207. }