BGData.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. //
  2. // BGData.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. extension MainViewController {
  11. // Dex Share Web Call
  12. func webLoadDexShare() {
  13. // Dexcom Share only returns 24 hrs of data as of now
  14. // Requesting more just for consistency with NS
  15. let graphHours = 24 * UserDefaultsRepository.downloadDays.value
  16. let count = graphHours * 12
  17. dexShare?.fetchData(count) { (err, result) -> () in
  18. if let error = err {
  19. LogManager.shared.log(category: .dexcom, message: "Error fetching Dexcom data: \(error.localizedDescription)")
  20. self.webLoadNSBGData()
  21. return
  22. }
  23. guard let data = result else {
  24. LogManager.shared.log(category: .dexcom, message: "Received nil data from Dexcom")
  25. self.webLoadNSBGData()
  26. return
  27. }
  28. // If Dex data is old, load from NS instead
  29. let latestDate = data[0].date
  30. let now = dateTimeUtils.getNowTimeIntervalUTC()
  31. if (latestDate + 330) < now && IsNightscoutEnabled() {
  32. LogManager.shared.log(category: .dexcom, message: "Dexcom data is old, loading from NS instead")
  33. self.webLoadNSBGData()
  34. return
  35. }
  36. // Dexcom only returns 24 hrs of data. If we need more, call NS.
  37. if graphHours > 24 && IsNightscoutEnabled() {
  38. self.webLoadNSBGData(dexData: data)
  39. } else {
  40. self.ProcessDexBGData(data: data, sourceName: "Dexcom")
  41. }
  42. }
  43. }
  44. // NS BG Data Web call
  45. func webLoadNSBGData(dexData: [ShareGlucoseData] = []) {
  46. // This kicks it out in the instance where dexcom fails but they aren't using NS &&
  47. if !IsNightscoutEnabled() {
  48. return
  49. }
  50. var parameters: [String: String] = [:]
  51. let utcISODateFormatter = ISO8601DateFormatter()
  52. let date = Calendar.current.date(byAdding: .day, value: -1 * UserDefaultsRepository.downloadDays.value, to: Date())!
  53. parameters["count"] = "\(UserDefaultsRepository.downloadDays.value * 2 * 24 * 60 / 5)"
  54. parameters["find[dateString][$gte]"] = utcISODateFormatter.string(from: date)
  55. // Exclude 'cal' entries
  56. parameters["find[type][$ne]"] = "cal"
  57. NightscoutUtils.executeRequest(eventType: .sgv, parameters: parameters) { (result: Result<[ShareGlucoseData], Error>) in
  58. switch result {
  59. case .success(let entriesResponse):
  60. var nsData = entriesResponse
  61. DispatchQueue.main.async {
  62. // transform NS data to look like Dex data
  63. for i in 0..<nsData.count {
  64. // convert the NS timestamp to seconds instead of milliseconds
  65. nsData[i].date /= 1000
  66. nsData[i].date.round(FloatingPointRoundingRule.toNearestOrEven)
  67. }
  68. var nsData2: [ShareGlucoseData] = []
  69. var lastAddedTime = Double.infinity
  70. var lastAddedSGV: Int? = nil
  71. let minInterval: Double = 30
  72. for reading in nsData {
  73. if (lastAddedSGV == nil || lastAddedSGV != reading.sgv) || (lastAddedTime - reading.date >= minInterval) {
  74. nsData2.append(reading)
  75. lastAddedTime = reading.date
  76. lastAddedSGV = reading.sgv
  77. }
  78. }
  79. // merge NS and Dex data if needed; use recent Dex data and older NS data
  80. var sourceName = "Nightscout"
  81. if !dexData.isEmpty {
  82. let oldestDexDate = dexData[dexData.count - 1].date
  83. var itemsToRemove = 0
  84. while itemsToRemove < nsData2.count && nsData2[itemsToRemove].date >= oldestDexDate {
  85. itemsToRemove += 1
  86. }
  87. nsData2.removeFirst(itemsToRemove)
  88. nsData2 = dexData + nsData2
  89. sourceName = "Dexcom"
  90. }
  91. // trigger the processor for the data after downloading.
  92. self.ProcessDexBGData(data: nsData2, sourceName: sourceName)
  93. }
  94. case .failure(let error):
  95. LogManager.shared.log(category: .nightscout, message: "Failed to fetch data: \(error)")
  96. DispatchQueue.main.async {
  97. TaskScheduler.shared.rescheduleTask(
  98. id: .fetchBG,
  99. to: Date().addingTimeInterval(10)
  100. )
  101. }
  102. // if we have Dex data, use it
  103. if !dexData.isEmpty {
  104. self.ProcessDexBGData(data: dexData, sourceName: "Dexcom")
  105. }
  106. return
  107. }
  108. }
  109. }
  110. // Dexcom BG Data Response processor
  111. func ProcessDexBGData(data: [ShareGlucoseData], sourceName: String){
  112. let graphHours = 24 * UserDefaultsRepository.downloadDays.value
  113. if data.count == 0 {
  114. return
  115. }
  116. let latestDate = data[0].date
  117. let now = dateTimeUtils.getNowTimeIntervalUTC()
  118. // Start the BG timer based on the reading
  119. let secondsAgo = now - latestDate
  120. DispatchQueue.main.async {
  121. if secondsAgo >= (20 * 60) {
  122. TaskScheduler.shared.rescheduleTask(
  123. id: .fetchBG,
  124. to: Date().addingTimeInterval(5 * 60)
  125. )
  126. } else if secondsAgo >= (10 * 60) {
  127. TaskScheduler.shared.rescheduleTask(
  128. id: .fetchBG,
  129. to: Date().addingTimeInterval(60)
  130. )
  131. } else if secondsAgo >= (7 * 60) {
  132. TaskScheduler.shared.rescheduleTask(
  133. id: .fetchBG,
  134. to: Date().addingTimeInterval(30)
  135. )
  136. } else if secondsAgo >= (5 * 60) {
  137. TaskScheduler.shared.rescheduleTask(
  138. id: .fetchBG,
  139. to: Date().addingTimeInterval(10)
  140. )
  141. } else {
  142. let delay = (300 - secondsAgo + Double(UserDefaultsRepository.bgUpdateDelay.value))
  143. TaskScheduler.shared.rescheduleTask(
  144. id: .fetchBG,
  145. to: Date().addingTimeInterval(delay)
  146. )
  147. if data.count > 1 {
  148. self.evaluateSpeakConditions(currentValue: data[0].sgv, previousValue: data[1].sgv)
  149. }
  150. }
  151. }
  152. bgData.removeAll()
  153. // loop through the data so we can reverse the order to oldest first for the graph
  154. for i in 0..<data.count {
  155. let dateString = data[data.count - 1 - i].date
  156. if dateString >= dateTimeUtils.getTimeIntervalNHoursAgo(N: graphHours) {
  157. let sgvValue = data[data.count - 1 - i].sgv
  158. // Skip the current iteration if the sgv value is over 600
  159. // First time a user starts a G7, they get a value of 4000
  160. if sgvValue > 600 {
  161. continue
  162. }
  163. let reading = ShareGlucoseData(sgv: sgvValue, date: dateString, direction: data[data.count - 1 - i].direction)
  164. bgData.append(reading)
  165. }
  166. }
  167. viewUpdateNSBG(sourceName: sourceName)
  168. }
  169. func updateServerText(with serverText: String? = nil) {
  170. if UserDefaultsRepository.showDisplayName.value, let displayName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String {
  171. self.serverText.text = displayName
  172. } else if let serverText = serverText {
  173. self.serverText.text = serverText
  174. }
  175. }
  176. // NS BG Data Front end updater
  177. func viewUpdateNSBG(sourceName: String) {
  178. DispatchQueue.main.async {
  179. TaskScheduler.shared.rescheduleTask(id: .minAgoUpdate, to: Date())
  180. let entries = self.bgData
  181. if entries.count < 2 { return } // Protect index out of bounds
  182. self.updateBGGraph()
  183. self.updateStats()
  184. let latestEntryIndex = entries.count - 1
  185. let latestBG = entries[latestEntryIndex].sgv
  186. let priorBG = entries[latestEntryIndex - 1].sgv
  187. let deltaBG = latestBG - priorBG
  188. let lastBGTime = entries[latestEntryIndex].date
  189. let deltaTime = (TimeInterval(Date().timeIntervalSince1970) - lastBGTime) / 60
  190. self.updateServerText(with: sourceName)
  191. var snoozerBG = ""
  192. var snoozerDirection = ""
  193. var snoozerDelta = ""
  194. // Set BGText with the latest BG value
  195. self.BGText.text = Localizer.toDisplayUnits(String(latestBG))
  196. snoozerBG = Localizer.toDisplayUnits(String(latestBG))
  197. self.setBGTextColor()
  198. // Direction handling
  199. if let directionBG = entries[latestEntryIndex].direction {
  200. self.DirectionText.text = self.bgDirectionGraphic(directionBG)
  201. snoozerDirection = self.bgDirectionGraphic(directionBG)
  202. self.latestDirectionString = self.bgDirectionGraphic(directionBG)
  203. } else {
  204. self.DirectionText.text = ""
  205. snoozerDirection = ""
  206. self.latestDirectionString = ""
  207. }
  208. // Delta handling
  209. if deltaBG < 0 {
  210. self.latestDeltaString = Localizer.toDisplayUnits(String(deltaBG))
  211. } else {
  212. self.latestDeltaString = "+" + Localizer.toDisplayUnits(String(deltaBG))
  213. }
  214. self.DeltaText.text = self.latestDeltaString
  215. snoozerDelta = self.latestDeltaString
  216. // Apply strikethrough to BGText based on the staleness of the data
  217. let bgTextStr = self.BGText.text ?? ""
  218. let attributeString = NSMutableAttributedString(string: bgTextStr)
  219. attributeString.addAttribute(.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: NSRange(location: 0, length: attributeString.length))
  220. if deltaTime >= 12 { // Data is stale
  221. attributeString.addAttribute(.strikethroughColor, value: UIColor.systemRed, range: NSRange(location: 0, length: attributeString.length))
  222. self.updateBadge(val: 0)
  223. } else { // Data is fresh
  224. attributeString.addAttribute(.strikethroughColor, value: UIColor.clear, range: NSRange(location: 0, length: attributeString.length))
  225. self.updateBadge(val: latestBG)
  226. }
  227. self.BGText.attributedText = attributeString
  228. // Snoozer Display
  229. guard let snoozer = self.tabBarController!.viewControllers?[2] as? SnoozeViewController else { return }
  230. snoozer.BGLabel.text = snoozerBG
  231. snoozer.DirectionLabel.text = snoozerDirection
  232. snoozer.DeltaLabel.text = snoozerDelta
  233. // Update contact
  234. if Storage.shared.contactEnabled.value {
  235. self.contactImageUpdater.updateContactImage(bgValue: bgTextStr, trend: snoozerDirection, delta: snoozerDelta, stale: deltaTime >= 12)
  236. }
  237. }
  238. }
  239. }