DeviceStatus.swift 9.6 KB

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