DeviceStatus.swift 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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. self.clearLastInfoData(index: 0)
  75. self.clearLastInfoData(index: 1)
  76. self.clearLastInfoData(index: 3)
  77. self.clearLastInfoData(index: 4)
  78. self.clearLastInfoData(index: 5)
  79. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: device status") }
  80. if jsonDeviceStatus.count == 0 {
  81. return
  82. }
  83. //Process the current data first
  84. let lastDeviceStatus = jsonDeviceStatus[0] as [String : AnyObject]?
  85. //pump and uploader
  86. let formatter = ISO8601DateFormatter()
  87. formatter.formatOptions = [.withFullDate,
  88. .withTime,
  89. .withDashSeparatorInDate,
  90. .withColonSeparatorInTime]
  91. if let lastPumpRecord = lastDeviceStatus?["pump"] as! [String : AnyObject]? {
  92. if let lastPumpTime = formatter.date(from: (lastPumpRecord["clock"] as! String))?.timeIntervalSince1970 {
  93. if let reservoirData = lastPumpRecord["reservoir"] as? Double {
  94. latestPumpVolume = reservoirData
  95. tableData[5].value = String(format:"%.0f", reservoirData) + "U"
  96. } else {
  97. latestPumpVolume = 50.0
  98. tableData[5].value = "50+U"
  99. }
  100. if let uploader = lastDeviceStatus?["uploader"] as? [String:AnyObject] {
  101. let upbat = uploader["battery"] as! Double
  102. tableData[4].value = String(format:"%.0f", upbat) + "%"
  103. UserDefaultsRepository.deviceBatteryLevel.value = upbat
  104. }
  105. }
  106. }
  107. // Loop - handle new data
  108. if let lastLoopRecord = lastDeviceStatus?["loop"] as! [String : AnyObject]? {
  109. DeviceStatusLoop(formatter: formatter, lastLoopRecord: lastLoopRecord)
  110. }
  111. // OpenAPS - handle new data
  112. if let lastLoopRecord = lastDeviceStatus?["openaps"] as! [String : AnyObject]? {
  113. DeviceStatusOpenAPS(formatter: formatter, lastDeviceStatus: lastDeviceStatus, lastLoopRecord: lastLoopRecord)
  114. }
  115. var oText = "" as String
  116. currentOverride = 1.0
  117. if let lastOverride = lastDeviceStatus?["override"] as! [String : AnyObject]? {
  118. if lastOverride["active"] as! Bool {
  119. let lastCorrection = lastOverride["currentCorrectionRange"] as! [String: AnyObject]
  120. if let multiplier = lastOverride["multiplier"] as? Double {
  121. currentOverride = multiplier
  122. oText += String(format: "%.0f%%", (multiplier * 100))
  123. }
  124. else
  125. {
  126. oText += "100%"
  127. }
  128. oText += " ("
  129. let minValue = lastCorrection["minValue"] as! Double
  130. let maxValue = lastCorrection["maxValue"] as! Double
  131. oText += bgUnits.toDisplayUnits(String(minValue)) + "-" + bgUnits.toDisplayUnits(String(maxValue)) + ")"
  132. tableData[3].value = oText
  133. }
  134. }
  135. infoTable.reloadData()
  136. // Start the timer based on the timestamp
  137. let now = dateTimeUtils.getNowTimeIntervalUTC()
  138. let secondsAgo = now - latestLoopTime
  139. DispatchQueue.main.async {
  140. // if Loop is overdue over: 20:00, re-attempt every 5 minutes
  141. if secondsAgo >= (20 * 60) {
  142. self.startDeviceStatusTimer(time: (5 * 60))
  143. print("started 5 minute device status timer")
  144. // if the Loop is overdue: 10:00-19:59, re-attempt every minute
  145. } else if secondsAgo >= (10 * 60) {
  146. self.startDeviceStatusTimer(time: 60)
  147. print("started 1 minute device status timer")
  148. // if the Loop is overdue: 7:00-9:59, re-attempt every 30 seconds
  149. } else if secondsAgo >= (7 * 60) {
  150. self.startDeviceStatusTimer(time: 30)
  151. print("started 30 second device status timer")
  152. // if the Loop is overdue: 5:00-6:59 re-attempt every 10 seconds
  153. } else if secondsAgo >= (5 * 60) {
  154. self.startDeviceStatusTimer(time: 10)
  155. print("started 10 second device status timer")
  156. // We have a current Loop. Set timer to 5:10 from last reading
  157. } else {
  158. self.startDeviceStatusTimer(time: 310 - secondsAgo)
  159. let timerVal = 310 - secondsAgo
  160. print("started 5:10 device status timer: \(timerVal)")
  161. }
  162. }
  163. }
  164. }