DeviceStatusOpenAPS.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. // DeviceStatusOpenAPS.swift
  2. // LoopFollow
  3. // Created by Jonas Björkert on 2024-05-19.
  4. // Copyright © 2024 Jon Fawcett. All rights reserved.
  5. import Foundation
  6. import UIKit
  7. import HealthKit
  8. extension MainViewController {
  9. func DeviceStatusOpenAPS(formatter: ISO8601DateFormatter, lastDeviceStatus: [String: AnyObject]?, lastLoopRecord: [String: AnyObject]) {
  10. if let createdAtString = lastDeviceStatus?["created_at"] as? String,
  11. let lastLoopTime = formatter.date(from: createdAtString)?.timeIntervalSince1970 {
  12. UserDefaultsRepository.alertLastLoopTime.value = lastLoopTime
  13. ObservableUserDefaults.shared.device.value = lastDeviceStatus?["device"] as? String ?? ""
  14. if lastLoopRecord["failureReason"] != nil {
  15. LoopStatusLabel.text = "X"
  16. latestLoopStatusString = "X"
  17. } else {
  18. guard let enacted = lastLoopRecord["enacted"] as? [String: AnyObject] else {
  19. LoopStatusLabel.text = "↻"
  20. latestLoopStatusString = "↻"
  21. evaluateNotLooping(lastLoopTime: lastLoopTime)
  22. return
  23. }
  24. let wasEnacted = true
  25. var determinedUnit: HKUnit = .milligramsPerDeciliter
  26. // Determine the unit based on the threshold value since no unit is provided
  27. if let enactedTargetValue = enacted["threshold"] as? Double {
  28. if enactedTargetValue < 40 {
  29. determinedUnit = .millimolesPerLiter
  30. }
  31. }
  32. // Updated
  33. if let enactedTimestamp = enacted["timestamp"] as? String,
  34. let enactedTime = formatter.date(from: enactedTimestamp)?.timeIntervalSince1970 {
  35. let formattedTime = Localizer.formatTimestampToLocalString(enactedTime)
  36. infoManager.updateInfoData(type: .updated, value: formattedTime)
  37. }
  38. // ISF
  39. let profileISF = profileManager.currentISF()
  40. var enactedISF: HKQuantity?
  41. if let enactedISFValue = enacted["ISF"] as? Double {
  42. enactedISF = HKQuantity(unit: determinedUnit, doubleValue: enactedISFValue)
  43. }
  44. if let profileISF = profileISF, let enactedISF = enactedISF, profileISF != enactedISF {
  45. infoManager.updateInfoData(type: .isf, firstValue: profileISF, secondValue: enactedISF, separator: .arrow)
  46. } else if let profileISF = profileISF {
  47. infoManager.updateInfoData(type: .isf, value: profileISF)
  48. }
  49. // Carb Ratio (CR)
  50. let profileCR = profileManager.currentCarbRatio()
  51. var enactedCR: Double?
  52. if let reasonString = enacted["reason"] as? String {
  53. let pattern = "CR: (\\d+(?:\\.\\d+)?)"
  54. if let regex = try? NSRegularExpression(pattern: pattern) {
  55. let nsString = reasonString as NSString
  56. if let match = regex.firstMatch(in: reasonString, range: NSRange(location: 0, length: nsString.length)) {
  57. let crString = nsString.substring(with: match.range(at: 1))
  58. enactedCR = Double(crString)
  59. }
  60. }
  61. }
  62. if let profileCR = profileCR, let enactedCR = enactedCR, profileCR != enactedCR {
  63. infoManager.updateInfoData(type: .carbRatio, value: profileCR, enactedValue: enactedCR, separator: .arrow)
  64. } else if let profileCR = profileCR {
  65. infoManager.updateInfoData(type: .carbRatio, value: profileCR)
  66. }
  67. // IOB
  68. if let iobMetric = InsulinMetric(from: lastLoopRecord["iob"], key: "iob") {
  69. infoManager.updateInfoData(type: .iob, value: iobMetric)
  70. latestIOB = iobMetric
  71. }
  72. // COB
  73. if let cobMetric = CarbMetric(from: enacted, key: "COB") {
  74. infoManager.updateInfoData(type: .cob, value: cobMetric)
  75. latestCOB = cobMetric
  76. }
  77. // Insulin Required
  78. if let insulinReqMetric = InsulinMetric(from: enacted, key: "insulinReq") {
  79. infoManager.updateInfoData(type: .recBolus, value: insulinReqMetric)
  80. UserDefaultsRepository.deviceRecBolus.value = insulinReqMetric.value
  81. } else {
  82. UserDefaultsRepository.deviceRecBolus.value = 0
  83. }
  84. // Autosens
  85. if let sens = enacted["sensitivityRatio"] as? Double {
  86. let formattedSens = String(format: "%.0f", sens * 100.0) + "%"
  87. infoManager.updateInfoData(type: .autosens, value: formattedSens)
  88. }
  89. // Eventual BG
  90. if let eventualBGValue = enacted["eventualBG"] as? Double {
  91. let eventualBGQuantity = HKQuantity(unit: .milligramsPerDeciliter, doubleValue: eventualBGValue)
  92. PredictionLabel.text = Localizer.formatQuantity(eventualBGQuantity)
  93. }
  94. // Target
  95. let profileTargetHigh = profileManager.currentTargetHigh()
  96. var enactedTarget: HKQuantity?
  97. if let enactedTargetValue = enacted["current_target"] as? Double {
  98. enactedTarget = HKQuantity(unit: .milligramsPerDeciliter, doubleValue: enactedTargetValue)
  99. }
  100. if let profileTargetHigh = profileTargetHigh, let enactedTarget = enactedTarget {
  101. let profileTargetHighFormatted = Localizer.formatQuantity(profileTargetHigh)
  102. let enactedTargetFormatted = Localizer.formatQuantity(enactedTarget)
  103. // Compare formatted values to avoid issues with minor floating-point differences
  104. // Profile target could be in another unit than enacted target
  105. if profileTargetHighFormatted != enactedTargetFormatted {
  106. infoManager.updateInfoData(type: .target, firstValue: profileTargetHigh, secondValue: enactedTarget, separator: .arrow)
  107. } else {
  108. infoManager.updateInfoData(type: .target, value: profileTargetHigh)
  109. }
  110. }
  111. // TDD
  112. if let tddMetric = InsulinMetric(from: enacted, key: "TDD") {
  113. infoManager.updateInfoData(type: .tdd, value: tddMetric)
  114. }
  115. let predictioncolor = UIColor.systemGray
  116. PredictionLabel.textColor = predictioncolor
  117. topPredictionBG = UserDefaultsRepository.minBGScale.value
  118. if let predbgdata = enacted["predBGs"] as? [String: AnyObject] {
  119. let predictionTypes: [(type: String, colorName: String, dataIndex: Int)] = [
  120. ("ZT", "ZT", 12),
  121. ("IOB", "Insulin", 13),
  122. ("COB", "LoopYellow", 14),
  123. ("UAM", "UAM", 15)
  124. ]
  125. var minPredBG = Double.infinity
  126. var maxPredBG = -Double.infinity
  127. for (type, colorName, dataIndex) in predictionTypes {
  128. var predictionData = [ShareGlucoseData]()
  129. if let graphdata = predbgdata[type] as? [Double] {
  130. var predictionTime = lastLoopTime
  131. let toLoad = Int(UserDefaultsRepository.predictionToLoad.value * 12)
  132. for i in 0...toLoad {
  133. if i < graphdata.count {
  134. let predictionValue = graphdata[i]
  135. minPredBG = min(minPredBG, predictionValue)
  136. maxPredBG = max(maxPredBG, predictionValue)
  137. let prediction = ShareGlucoseData(sgv: Int(round(predictionValue)), date: predictionTime, direction: "flat")
  138. predictionData.append(prediction)
  139. predictionTime += 300
  140. }
  141. }
  142. }
  143. let color = UIColor(named: colorName) ?? UIColor.systemPurple
  144. updatePredictionGraphGeneric(
  145. dataIndex: dataIndex,
  146. predictionData: predictionData,
  147. chartLabel: type,
  148. color: color
  149. )
  150. }
  151. if minPredBG != Double.infinity && maxPredBG != -Double.infinity {
  152. let value = "\(Localizer.toDisplayUnits(String(minPredBG)))/\(Localizer.toDisplayUnits(String(maxPredBG)))"
  153. infoManager.updateInfoData(type: .minMax, value: value)
  154. } else {
  155. infoManager.updateInfoData(type: .minMax, value: "N/A")
  156. }
  157. }
  158. if let loopStatus = lastLoopRecord["recommendedTempBasal"] as? [String: AnyObject] {
  159. if let tempBasalTime = formatter.date(from: (loopStatus["timestamp"] as! String))?.timeIntervalSince1970 {
  160. var lastBGTime = lastLoopTime
  161. if bgData.count > 0 {
  162. lastBGTime = bgData[bgData.count - 1].date
  163. }
  164. if tempBasalTime > lastBGTime && !wasEnacted {
  165. LoopStatusLabel.text = "⏀"
  166. latestLoopStatusString = "⏀"
  167. } else {
  168. LoopStatusLabel.text = "↻"
  169. latestLoopStatusString = "↻"
  170. }
  171. }
  172. } else {
  173. LoopStatusLabel.text = "↻"
  174. latestLoopStatusString = "↻"
  175. }
  176. }
  177. evaluateNotLooping(lastLoopTime: lastLoopTime)
  178. }
  179. }
  180. }