DeviceStatusOpenAPS.swift 10 KB

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