DeviceStatusOpenAPS.swift 10 KB

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