BGData.swift 13 KB

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