DeviceStatus.swift 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. //
  2. // DeviceStatus.swift
  3. // LoopFollow
  4. //
  5. // Created by Jonas Björkert on 2023-10-05.
  6. // Copyright © 2023 Jon Fawcett. All rights reserved.
  7. //
  8. import Foundation
  9. import UIKit
  10. import Charts
  11. extension MainViewController {
  12. func webLoadNSDeviceStatus() {
  13. let parameters: [String: String] = ["count": "1"]
  14. NightscoutUtils.executeDynamicRequest(eventType: .deviceStatus, parameters: parameters) { result in
  15. switch result {
  16. case .success(let json):
  17. if let jsonDeviceStatus = json as? [[String: AnyObject]] {
  18. DispatchQueue.main.async {
  19. self.updateDeviceStatusDisplay(jsonDeviceStatus: jsonDeviceStatus)
  20. }
  21. } else {
  22. self.handleDeviceStatusError()
  23. }
  24. case .failure:
  25. self.handleDeviceStatusError()
  26. }
  27. }
  28. }
  29. private func handleDeviceStatusError() {
  30. LogManager.shared.log(category: .deviceStatus, message: "Device status fetch failed!")
  31. DispatchQueue.main.async {
  32. TaskScheduler.shared.rescheduleTask(id: .deviceStatus, to: Date().addingTimeInterval(10))
  33. }
  34. }
  35. func evaluateNotLooping(lastLoopTime: TimeInterval) {
  36. if let statusStackView = LoopStatusLabel.superview as? UIStackView {
  37. if ((TimeInterval(Date().timeIntervalSince1970) - lastLoopTime) / 60) > 15 {
  38. IsNotLooping = true
  39. // Change the distribution to 'fill' to allow manual resizing of arranged subviews
  40. statusStackView.distribution = .fill
  41. // Hide PredictionLabel and expand LoopStatusLabel to fill the entire stack view
  42. PredictionLabel.isHidden = true
  43. LoopStatusLabel.frame = CGRect(x: 0, y: 0, width: statusStackView.frame.width, height: statusStackView.frame.height)
  44. // Update LoopStatusLabel's properties to display Not Looping
  45. LoopStatusLabel.textAlignment = .center
  46. LoopStatusLabel.text = "⚠️ Not Looping!"
  47. LoopStatusLabel.textColor = UIColor.systemYellow
  48. LoopStatusLabel.font = UIFont.boldSystemFont(ofSize: 18)
  49. } else {
  50. IsNotLooping = false
  51. // Restore the original distribution and visibility of labels
  52. statusStackView.distribution = .fillEqually
  53. PredictionLabel.isHidden = false
  54. // Reset LoopStatusLabel's properties
  55. LoopStatusLabel.textAlignment = .right
  56. LoopStatusLabel.font = UIFont.systemFont(ofSize: 17)
  57. if UserDefaultsRepository.forceDarkMode.value {
  58. LoopStatusLabel.textColor = UIColor.white
  59. } else {
  60. LoopStatusLabel.textColor = UIColor.black
  61. }
  62. }
  63. }
  64. latestLoopTime = lastLoopTime
  65. }
  66. // NS Device Status Response Processor
  67. func updateDeviceStatusDisplay(jsonDeviceStatus: [[String:AnyObject]]) {
  68. infoManager.clearInfoData(types: [.iob, .cob, .override, .battery, .pump, .target, .isf, .carbRatio, .updated, .recBolus, .tdd])
  69. if jsonDeviceStatus.count == 0 {
  70. LogManager.shared.log(category: .deviceStatus, message: "Device status is empty")
  71. return
  72. }
  73. //Process the current data first
  74. let lastDeviceStatus = jsonDeviceStatus[0] as [String : AnyObject]?
  75. //pump and uploader
  76. let formatter = ISO8601DateFormatter()
  77. formatter.formatOptions = [.withFullDate,
  78. .withTime,
  79. .withDashSeparatorInDate,
  80. .withColonSeparatorInTime]
  81. if let lastPumpRecord = lastDeviceStatus?["pump"] as! [String : AnyObject]? {
  82. if let lastPumpTime = formatter.date(from: (lastPumpRecord["clock"] as! String))?.timeIntervalSince1970 {
  83. if let reservoirData = lastPumpRecord["reservoir"] as? Double {
  84. latestPumpVolume = reservoirData
  85. infoManager.updateInfoData(type: .pump, value: String(format: "%.0f", reservoirData) + "U")
  86. } else {
  87. latestPumpVolume = 50.0
  88. infoManager.updateInfoData(type: .pump, value: "50+U")
  89. }
  90. if let uploader = lastDeviceStatus?["uploader"] as? [String: AnyObject],
  91. let upbat = uploader["battery"] as? Double {
  92. infoManager.updateInfoData(type: .battery, value: String(format: "%.0f", upbat) + "%")
  93. UserDefaultsRepository.deviceBatteryLevel.value = upbat
  94. }
  95. }
  96. }
  97. // Loop - handle new data
  98. if let lastLoopRecord = lastDeviceStatus?["loop"] as! [String : AnyObject]? {
  99. DeviceStatusLoop(formatter: formatter, lastLoopRecord: lastLoopRecord)
  100. var oText = ""
  101. currentOverride = 1.0
  102. if let lastOverride = lastDeviceStatus?["override"] as? [String: AnyObject],
  103. let isActive = lastOverride["active"] as? Bool, isActive {
  104. if let lastCorrection = lastOverride["currentCorrectionRange"] as? [String: AnyObject],
  105. let minValue = lastCorrection["minValue"] as? Double,
  106. let maxValue = lastCorrection["maxValue"] as? Double {
  107. if let multiplier = lastOverride["multiplier"] as? Double {
  108. currentOverride = multiplier
  109. oText += String(format: "%.0f%%", (multiplier * 100))
  110. } else {
  111. oText += "100%"
  112. }
  113. oText += " ("
  114. oText += Localizer.toDisplayUnits(String(minValue)) + "-" + Localizer.toDisplayUnits(String(maxValue)) + ")"
  115. }
  116. infoManager.updateInfoData(type: .override, value: oText)
  117. } else {
  118. infoManager.clearInfoData(type: .override)
  119. }
  120. }
  121. // OpenAPS - handle new data
  122. if let lastLoopRecord = lastDeviceStatus?["openaps"] as! [String : AnyObject]? {
  123. DeviceStatusOpenAPS(formatter: formatter, lastDeviceStatus: lastDeviceStatus, lastLoopRecord: lastLoopRecord)
  124. }
  125. // Start the timer based on the timestamp
  126. let now = dateTimeUtils.getNowTimeIntervalUTC()
  127. let secondsAgo = now - latestLoopTime
  128. DispatchQueue.main.async {
  129. if secondsAgo >= (20 * 60) {
  130. TaskScheduler.shared.rescheduleTask(
  131. id: .deviceStatus,
  132. to: Date().addingTimeInterval(5 * 60)
  133. )
  134. } else if secondsAgo >= (10 * 60) {
  135. TaskScheduler.shared.rescheduleTask(
  136. id: .deviceStatus,
  137. to: Date().addingTimeInterval(60)
  138. )
  139. } else if secondsAgo >= (7 * 60) {
  140. TaskScheduler.shared.rescheduleTask(
  141. id: .deviceStatus,
  142. to: Date().addingTimeInterval(30)
  143. )
  144. } else if secondsAgo >= (5 * 60) {
  145. TaskScheduler.shared.rescheduleTask(
  146. id: .deviceStatus,
  147. to: Date().addingTimeInterval(10)
  148. )
  149. } else {
  150. let interval = (310 - secondsAgo)
  151. TaskScheduler.shared.rescheduleTask(
  152. id: .deviceStatus,
  153. to: Date().addingTimeInterval(interval)
  154. )
  155. }
  156. }
  157. LogManager.shared.log(category: .deviceStatus, message: "Update Device Status done", isDebug: true)
  158. }
  159. }