DeviceStatus.swift 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. // LoopFollow
  2. // DeviceStatus.swift
  3. // Created by Jonas Björkert on 2023-10-05.
  4. import Charts
  5. import Foundation
  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. }
  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. TaskScheduler.shared.rescheduleTask(id: .deviceStatus, to: Date().addingTimeInterval(10))
  29. self.evaluateNotLooping()
  30. }
  31. }
  32. func evaluateNotLooping() {
  33. guard let statusStackView = LoopStatusLabel.superview as? UIStackView else { return }
  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. statusStackView.distribution = .fill
  42. PredictionLabel.isHidden = true
  43. LoopStatusLabel.frame = CGRect(x: 0, y: 0, width: statusStackView.frame.width, height: statusStackView.frame.height)
  44. LoopStatusLabel.textAlignment = .center
  45. LoopStatusLabel.text = "⚠️ Not Looping!"
  46. LoopStatusLabel.textColor = UIColor.systemYellow
  47. LoopStatusLabel.font = UIFont.boldSystemFont(ofSize: 18)
  48. } else {
  49. IsNotLooping = false
  50. statusStackView.distribution = .fillEqually
  51. PredictionLabel.isHidden = false
  52. LoopStatusLabel.textAlignment = .right
  53. LoopStatusLabel.font = UIFont.systemFont(ofSize: 17)
  54. if Storage.shared.forceDarkMode.value {
  55. LoopStatusLabel.textColor = UIColor.white
  56. } else {
  57. LoopStatusLabel.textColor = UIColor.black
  58. }
  59. }
  60. }
  61. // NS Device Status Response Processor
  62. func updateDeviceStatusDisplay(jsonDeviceStatus: [[String: AnyObject]]) {
  63. infoManager.clearInfoData(types: [.iob, .cob, .override, .battery, .pump, .target, .isf, .carbRatio, .updated, .recBolus, .tdd])
  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. if let lastPumpRecord = lastDeviceStatus?["pump"] as! [String: AnyObject]? {
  78. if let lastPumpTime = formatter.date(from: (lastPumpRecord["clock"] as! String))?.timeIntervalSince1970 {
  79. if let reservoirData = lastPumpRecord["reservoir"] as? Double {
  80. latestPumpVolume = reservoirData
  81. infoManager.updateInfoData(type: .pump, value: String(format: "%.0f", reservoirData) + "U")
  82. } else {
  83. latestPumpVolume = 50.0
  84. infoManager.updateInfoData(type: .pump, value: "50+U")
  85. }
  86. if let uploader = lastDeviceStatus?["uploader"] as? [String: AnyObject],
  87. let upbat = uploader["battery"] as? Double
  88. {
  89. let batteryText: String
  90. if let isCharging = uploader["isCharging"] as? Bool, isCharging {
  91. batteryText = "⚡️ " + String(format: "%.0f", upbat) + "%"
  92. } else {
  93. batteryText = String(format: "%.0f", upbat) + "%"
  94. }
  95. infoManager.updateInfoData(type: .battery, value: batteryText)
  96. Observable.shared.deviceBatteryLevel.value = upbat
  97. let timestamp = uploader["timestamp"] as? Date ?? Date()
  98. let currentBattery = DataStructs.batteryStruct(batteryLevel: upbat, timestamp: timestamp)
  99. deviceBatteryData.append(currentBattery)
  100. // store only the last 30 battery readings
  101. if deviceBatteryData.count > 30 {
  102. deviceBatteryData.removeFirst()
  103. }
  104. }
  105. }
  106. }
  107. // Loop - handle new data
  108. if let lastLoopRecord = lastDeviceStatus?["loop"] as! [String: AnyObject]? {
  109. DeviceStatusLoop(formatter: formatter, lastLoopRecord: lastLoopRecord)
  110. var oText = ""
  111. currentOverride = 1.0
  112. if let lastOverride = lastDeviceStatus?["override"] as? [String: AnyObject],
  113. let isActive = lastOverride["active"] as? Bool, isActive
  114. {
  115. if let lastCorrection = lastOverride["currentCorrectionRange"] as? [String: AnyObject],
  116. let minValue = lastCorrection["minValue"] as? Double,
  117. let maxValue = lastCorrection["maxValue"] as? Double
  118. {
  119. if let multiplier = lastOverride["multiplier"] as? Double {
  120. currentOverride = multiplier
  121. oText += String(format: "%.0f%%", multiplier * 100)
  122. } else {
  123. oText += "100%"
  124. }
  125. oText += " ("
  126. oText += Localizer.toDisplayUnits(String(minValue)) + "-" + Localizer.toDisplayUnits(String(maxValue)) + ")"
  127. }
  128. infoManager.updateInfoData(type: .override, value: oText)
  129. } else {
  130. infoManager.clearInfoData(type: .override)
  131. }
  132. }
  133. // OpenAPS - handle new data
  134. if let lastLoopRecord = lastDeviceStatus?["openaps"] as! [String: AnyObject]? {
  135. DeviceStatusOpenAPS(formatter: formatter, lastDeviceStatus: lastDeviceStatus, lastLoopRecord: lastLoopRecord)
  136. }
  137. // Start the timer based on the timestamp
  138. let now = dateTimeUtils.getNowTimeIntervalUTC()
  139. let secondsAgo = now - (Observable.shared.alertLastLoopTime.value ?? 0)
  140. DispatchQueue.main.async {
  141. if secondsAgo >= (20 * 60) {
  142. TaskScheduler.shared.rescheduleTask(
  143. id: .deviceStatus,
  144. to: Date().addingTimeInterval(5 * 60)
  145. )
  146. } else if secondsAgo >= (10 * 60) {
  147. TaskScheduler.shared.rescheduleTask(
  148. id: .deviceStatus,
  149. to: Date().addingTimeInterval(60)
  150. )
  151. } else if secondsAgo >= (7 * 60) {
  152. TaskScheduler.shared.rescheduleTask(
  153. id: .deviceStatus,
  154. to: Date().addingTimeInterval(30)
  155. )
  156. } else if secondsAgo >= (5 * 60) {
  157. TaskScheduler.shared.rescheduleTask(
  158. id: .deviceStatus,
  159. to: Date().addingTimeInterval(10)
  160. )
  161. } else {
  162. let interval = (310 - secondsAgo)
  163. TaskScheduler.shared.rescheduleTask(
  164. id: .deviceStatus,
  165. to: Date().addingTimeInterval(interval)
  166. )
  167. }
  168. }
  169. evaluateNotLooping()
  170. LogManager.shared.log(category: .deviceStatus, message: "Update Device Status done", isDebug: true)
  171. }
  172. }