DeviceStatus.swift 7.9 KB

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