BGData.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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. self.webLoadNSBGData()
  33. print("Dex data is old, loading from NS instead")
  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. print(nsData.count)
  69. //Avoid duplicate entries messing up the graph, only use one reading per 5 minutes.
  70. let graphHours = 24 * UserDefaultsRepository.downloadDays.value
  71. let points = graphHours * 12 + 1
  72. var nsData2 = [ShareGlucoseData]()
  73. let timestamp = Date().timeIntervalSince1970
  74. for i in 0..<points {
  75. //Starting with "now" and then step 5 minutes back in time
  76. let target = timestamp - Double(i) * 60 * 5
  77. //Find the reading closest to the target, but not too far away
  78. let closest = nsData.filter{ abs($0.date - target) < 3 * 60 }.min { abs($0.date - target) < abs($1.date - target) }
  79. //If a reading is found, add it to the new array
  80. if let item = closest {
  81. nsData2.append(item)
  82. }
  83. }
  84. print(nsData2.count)
  85. // merge NS and Dex data if needed; use recent Dex data and older NS data
  86. var sourceName = "Nightscout"
  87. if !dexData.isEmpty {
  88. let oldestDexDate = dexData[dexData.count - 1].date
  89. var itemsToRemove = 0
  90. while itemsToRemove < nsData2.count && nsData2[itemsToRemove].date >= oldestDexDate {
  91. itemsToRemove += 1
  92. }
  93. nsData2.removeFirst(itemsToRemove)
  94. nsData2 = dexData + nsData2
  95. sourceName = "Dexcom"
  96. }
  97. // trigger the processor for the data after downloading.
  98. self.ProcessDexBGData(data: nsData2, sourceName: sourceName)
  99. }
  100. case .failure(let error):
  101. print("Failed to fetch data: \(error)")
  102. DispatchQueue.main.async {
  103. TaskScheduler.shared.rescheduleTask(
  104. id: .fetchBG,
  105. to: Date().addingTimeInterval(10)
  106. )
  107. }
  108. // if we have Dex data, use it
  109. if !dexData.isEmpty {
  110. self.ProcessDexBGData(data: dexData, sourceName: "Dexcom")
  111. }
  112. return
  113. }
  114. }
  115. }
  116. // Dexcom BG Data Response processor
  117. func ProcessDexBGData(data: [ShareGlucoseData], sourceName: String){
  118. let graphHours = 24 * UserDefaultsRepository.downloadDays.value
  119. if data.count == 0 {
  120. return
  121. }
  122. let pullDate = data[data.count - 1].date
  123. let latestDate = data[0].date
  124. let now = dateTimeUtils.getNowTimeIntervalUTC()
  125. // Start the BG timer based on the reading
  126. let secondsAgo = now - latestDate
  127. DispatchQueue.main.async {
  128. if secondsAgo >= (20 * 60) {
  129. TaskScheduler.shared.rescheduleTask(
  130. id: .fetchBG,
  131. to: Date().addingTimeInterval(5 * 60)
  132. )
  133. print("##### scheduled BG task in 5 minutes")
  134. } else if secondsAgo >= (10 * 60) {
  135. TaskScheduler.shared.rescheduleTask(
  136. id: .fetchBG,
  137. to: Date().addingTimeInterval(60)
  138. )
  139. print("##### scheduled BG task in 1 minute")
  140. } else if secondsAgo >= (7 * 60) {
  141. TaskScheduler.shared.rescheduleTask(
  142. id: .fetchBG,
  143. to: Date().addingTimeInterval(30)
  144. )
  145. print("##### scheduled BG task in 30 seconds")
  146. } else if secondsAgo >= (5 * 60) {
  147. TaskScheduler.shared.rescheduleTask(
  148. id: .fetchBG,
  149. to: Date().addingTimeInterval(10)
  150. )
  151. print("##### scheduled BG task in 10 seconds")
  152. } else {
  153. let delay = (300 - secondsAgo + Double(UserDefaultsRepository.bgUpdateDelay.value))
  154. TaskScheduler.shared.rescheduleTask(
  155. id: .fetchBG,
  156. to: Date().addingTimeInterval(delay)
  157. )
  158. print("##### scheduled BG task in \(delay) seconds")
  159. }
  160. }
  161. bgData.removeAll()
  162. // loop through the data so we can reverse the order to oldest first for the graph
  163. for i in 0..<data.count {
  164. let dateString = data[data.count - 1 - i].date
  165. if dateString >= dateTimeUtils.getTimeIntervalNHoursAgo(N: graphHours) {
  166. let sgvValue = data[data.count - 1 - i].sgv
  167. // Skip the current iteration if the sgv value is over 600
  168. // First time a user starts a G7, they get a value of 4000
  169. if sgvValue > 600 {
  170. continue
  171. }
  172. let reading = ShareGlucoseData(sgv: sgvValue, date: dateString, direction: data[data.count - 1 - i].direction)
  173. bgData.append(reading)
  174. }
  175. }
  176. viewUpdateNSBG(sourceName: sourceName)
  177. }
  178. func updateServerText(with serverText: String? = nil) {
  179. if UserDefaultsRepository.showDisplayName.value, let displayName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String {
  180. self.serverText.text = displayName
  181. } else if let serverText = serverText {
  182. self.serverText.text = serverText
  183. }
  184. }
  185. // NS BG Data Front end updater
  186. func viewUpdateNSBG(sourceName: String) {
  187. DispatchQueue.main.async {
  188. TaskScheduler.shared.rescheduleTask(id: .minAgoUpdate, to: Date())
  189. let entries = self.bgData
  190. if entries.count < 2 { return } // Protect index out of bounds
  191. self.updateBGGraph()
  192. self.updateStats()
  193. let latestEntryIndex = entries.count - 1
  194. let latestBG = entries[latestEntryIndex].sgv
  195. let priorBG = entries[latestEntryIndex - 1].sgv
  196. let deltaBG = latestBG - priorBG
  197. let lastBGTime = entries[latestEntryIndex].date
  198. let deltaTime = (TimeInterval(Date().timeIntervalSince1970) - lastBGTime) / 60
  199. self.updateServerText(with: sourceName)
  200. var snoozerBG = ""
  201. var snoozerDirection = ""
  202. var snoozerDelta = ""
  203. // Set BGText with the latest BG value
  204. self.BGText.text = Localizer.toDisplayUnits(String(latestBG))
  205. snoozerBG = Localizer.toDisplayUnits(String(latestBG))
  206. self.setBGTextColor()
  207. // Direction handling
  208. if let directionBG = entries[latestEntryIndex].direction {
  209. self.DirectionText.text = self.bgDirectionGraphic(directionBG)
  210. snoozerDirection = self.bgDirectionGraphic(directionBG)
  211. self.latestDirectionString = self.bgDirectionGraphic(directionBG)
  212. } else {
  213. self.DirectionText.text = ""
  214. snoozerDirection = ""
  215. self.latestDirectionString = ""
  216. }
  217. // Delta handling
  218. if deltaBG < 0 {
  219. self.DeltaText.text = Localizer.toDisplayUnits(String(deltaBG))
  220. snoozerDelta = Localizer.toDisplayUnits(String(deltaBG))
  221. self.latestDeltaString = String(deltaBG)
  222. } else {
  223. self.DeltaText.text = "+" + Localizer.toDisplayUnits(String(deltaBG))
  224. snoozerDelta = "+" + Localizer.toDisplayUnits(String(deltaBG))
  225. self.latestDeltaString = "+" + String(deltaBG)
  226. }
  227. // Apply strikethrough to BGText based on the staleness of the data
  228. let bgTextStr = self.BGText.text ?? ""
  229. let attributeString = NSMutableAttributedString(string: bgTextStr)
  230. attributeString.addAttribute(.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: NSRange(location: 0, length: attributeString.length))
  231. if deltaTime >= 12 { // Data is stale
  232. attributeString.addAttribute(.strikethroughColor, value: UIColor.systemRed, range: NSRange(location: 0, length: attributeString.length))
  233. self.updateBadge(val: 0)
  234. } else { // Data is fresh
  235. attributeString.addAttribute(.strikethroughColor, value: UIColor.clear, range: NSRange(location: 0, length: attributeString.length))
  236. self.updateBadge(val: latestBG)
  237. }
  238. self.BGText.attributedText = attributeString
  239. // Snoozer Display
  240. guard let snoozer = self.tabBarController!.viewControllers?[2] as? SnoozeViewController else { return }
  241. snoozer.BGLabel.text = snoozerBG
  242. snoozer.DirectionLabel.text = snoozerDirection
  243. snoozer.DeltaLabel.text = snoozerDelta
  244. // Update contact
  245. if ObservableUserDefaults.shared.contactEnabled.value {
  246. var extra: String = ""
  247. if ObservableUserDefaults.shared.contactTrend.value {
  248. extra = snoozerDirection
  249. } else if ObservableUserDefaults.shared.contactDelta.value {
  250. extra = snoozerDelta
  251. }
  252. self.contactImageUpdater.updateContactImage(bgValue: bgTextStr, extra: extra, stale: deltaTime >= 12)
  253. }
  254. }
  255. }
  256. }