BGData.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. // LoopFollow
  2. // BGData.swift
  3. import Foundation
  4. import UIKit
  5. extension MainViewController {
  6. // Dex Share Web Call
  7. func webLoadDexShare() {
  8. // Dexcom Share only returns 24 hrs of data as of now
  9. // Requesting more just for consistency with NS
  10. let graphHours = 24 * Storage.shared.downloadDays.value
  11. let count = graphHours * 12
  12. dexShare?.fetchData(count) { err, result in
  13. if let error = err {
  14. LogManager.shared.log(category: .dexcom, message: "Error fetching Dexcom data: \(error.localizedDescription)", limitIdentifier: "Error fetching Dexcom data")
  15. self.webLoadNSBGData()
  16. return
  17. }
  18. guard let data = result, !data.isEmpty else {
  19. LogManager.shared.log(category: .dexcom, message: "Received empty data array from Dexcom", limitIdentifier: "Received empty data array from Dexcom")
  20. self.webLoadNSBGData()
  21. return
  22. }
  23. // If Dex data is old, load from NS instead
  24. let latestDate = data[0].date
  25. let now = dateTimeUtils.getNowTimeIntervalUTC()
  26. if (latestDate + 330) < now, IsNightscoutEnabled() {
  27. LogManager.shared.log(category: .dexcom, message: "Dexcom data is old, loading from NS instead", limitIdentifier: "Dexcom data is old, loading from NS instead")
  28. self.webLoadNSBGData()
  29. return
  30. }
  31. // Dexcom Share can return duplicate readings when multiple uploaders
  32. // write to the same Dexcom account. Dedup before any further use.
  33. let dedupedData = self.deduplicateBGReadings(data)
  34. // Supplement with NS if Dex data doesn't cover the full requested window.
  35. let dexCutoff = dateTimeUtils.getNowTimeIntervalUTC() - Double(graphHours) * 3600
  36. let dexCoversFull = dedupedData.last.map { $0.date <= dexCutoff } ?? false
  37. if !dexCoversFull, IsNightscoutEnabled() {
  38. self.webLoadNSBGData(dexData: dedupedData)
  39. } else {
  40. self.ProcessDexBGData(data: dedupedData, 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. Storage.shared.lastBGChecked.value = Date()
  49. return
  50. }
  51. var parameters: [String: String] = [:]
  52. let date = Calendar.current.date(byAdding: .day, value: -1 * Storage.shared.downloadDays.value, to: Date())!
  53. parameters["count"] = "\(Storage.shared.downloadDays.value * globalVariables.maxExpectedUploaders * 24 * 60 / 5)"
  54. parameters["find[date][$gte]"] = "\(Int(date.timeIntervalSince1970 * 1000))"
  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 let .success(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 = self.deduplicateBGReadings(nsData)
  69. // merge NS and Dex data if needed; use recent Dex data and older NS data
  70. var sourceName = "Nightscout"
  71. if !dexData.isEmpty {
  72. let oldestDexDate = dexData[dexData.count - 1].date
  73. var itemsToRemove = 0
  74. while itemsToRemove < nsData2.count, nsData2[itemsToRemove].date >= oldestDexDate {
  75. itemsToRemove += 1
  76. }
  77. nsData2.removeFirst(itemsToRemove)
  78. nsData2 = dexData + nsData2
  79. sourceName = "Dexcom"
  80. }
  81. // trigger the processor for the data after downloading.
  82. self.ProcessDexBGData(data: nsData2, sourceName: sourceName)
  83. }
  84. case let .failure(error):
  85. LogManager.shared.log(category: .nightscout, message: "Failed to fetch bg data: \(error)", limitIdentifier: "Failed to fetch bg data")
  86. DispatchQueue.main.async {
  87. TaskScheduler.shared.rescheduleTask(
  88. id: .fetchBG,
  89. to: Date().addingTimeInterval(10)
  90. )
  91. }
  92. // if we have Dex data, use it
  93. if !dexData.isEmpty {
  94. self.ProcessDexBGData(data: dexData, sourceName: "Dexcom")
  95. } else {
  96. Storage.shared.lastBGChecked.value = Date()
  97. }
  98. return
  99. }
  100. }
  101. }
  102. /// Removes consecutive duplicate readings (same SGV within 30 s). Expects newest-first input.
  103. func deduplicateBGReadings(_ readings: [ShareGlucoseData]) -> [ShareGlucoseData] {
  104. var result: [ShareGlucoseData] = []
  105. var lastTime = Double.infinity
  106. var lastSGV: Int?
  107. for reading in readings {
  108. if lastSGV == nil || lastSGV != reading.sgv || lastTime - reading.date >= 30 {
  109. result.append(reading)
  110. lastTime = reading.date
  111. lastSGV = reading.sgv
  112. }
  113. }
  114. return result
  115. }
  116. /// Processes incoming BG data.
  117. func ProcessDexBGData(data: [ShareGlucoseData], sourceName: String) {
  118. let graphHours = 24 * Storage.shared.downloadDays.value
  119. guard !data.isEmpty else {
  120. LogManager.shared.log(category: .nightscout, message: "No bg data received. Skipping processing.", limitIdentifier: "No bg data received. Skipping processing.")
  121. Storage.shared.lastBGChecked.value = Date()
  122. return
  123. }
  124. let latestReading = data[0]
  125. let sensorTimestamp = latestReading.date
  126. let now = dateTimeUtils.getNowTimeIntervalUTC()
  127. // secondsAgo is how old the newest reading is
  128. let secondsAgo = now - sensorTimestamp
  129. // Compute the current sensor schedule offset
  130. let currentOffset = CycleHelper.cycleOffset(for: sensorTimestamp, interval: 5 * 60)
  131. if Storage.shared.sensorScheduleOffset.value != currentOffset {
  132. Storage.shared.sensorScheduleOffset.value = currentOffset
  133. LogManager.shared.log(category: .nightscout,
  134. message: "Sensor schedule offset: \(currentOffset) seconds.",
  135. isDebug: true)
  136. }
  137. // Determine the next polling delay.
  138. var delayToSchedule: Double = 0
  139. DispatchQueue.main.async {
  140. // Fallback scheduling for older readings.
  141. if secondsAgo >= (20 * 60) {
  142. delayToSchedule = 5 * 60
  143. LogManager.shared.log(category: .nightscout,
  144. message: "Reading is very old (\(secondsAgo) sec). Scheduling next fetch in 5 minutes.",
  145. isDebug: true)
  146. } else if secondsAgo >= (10 * 60) {
  147. delayToSchedule = 60
  148. LogManager.shared.log(category: .nightscout,
  149. message: "Reading is moderately old (\(secondsAgo) sec). Scheduling next fetch in 60 seconds.",
  150. isDebug: true)
  151. } else if secondsAgo >= (7 * 60) {
  152. delayToSchedule = 30
  153. LogManager.shared.log(category: .nightscout,
  154. message: "Reading is a bit old (\(secondsAgo) sec). Scheduling next fetch in 30 seconds.",
  155. isDebug: true)
  156. } else if secondsAgo >= (5 * 60) {
  157. delayToSchedule = 5
  158. LogManager.shared.log(category: .nightscout,
  159. message: "Reading is close to 5 minutes old (\(secondsAgo) sec). Scheduling next fetch in 5 seconds.",
  160. isDebug: true)
  161. } else {
  162. delayToSchedule = 300 - secondsAgo + Double(Storage.shared.bgUpdateDelay.value)
  163. LogManager.shared.log(category: .nightscout,
  164. message: "Fresh reading. Scheduling next fetch in \(delayToSchedule) seconds.",
  165. isDebug: true)
  166. TaskScheduler.shared.rescheduleTask(id: .alarmCheck, to: Date().addingTimeInterval(3))
  167. }
  168. TaskScheduler.shared.rescheduleTask(id: .fetchBG, to: Date().addingTimeInterval(delayToSchedule))
  169. // Evaluate speak conditions if there is a previous value.
  170. if data.count > 1 {
  171. self.evaluateSpeakConditions(currentValue: data[0].sgv, previousValue: data[1].sgv)
  172. }
  173. }
  174. // Process data for graph display.
  175. bgData.removeAll()
  176. for i in 0 ..< data.count {
  177. let readingTimestamp = data[data.count - 1 - i].date
  178. if readingTimestamp >= dateTimeUtils.getTimeIntervalNHoursAgo(N: graphHours) {
  179. let sgvValue = data[data.count - 1 - i].sgv
  180. // Skip outlier values (e.g. first reading of a new sensor might be abnormally high).
  181. if sgvValue > 600 {
  182. LogManager.shared.log(category: .nightscout,
  183. message: "Skipping reading with sgv \(sgvValue) as it exceeds threshold.",
  184. isDebug: true)
  185. continue
  186. }
  187. let reading = ShareGlucoseData(sgv: sgvValue, date: readingTimestamp, direction: data[data.count - 1 - i].direction)
  188. bgData.append(reading)
  189. }
  190. }
  191. LogManager.shared.log(category: .nightscout,
  192. message: "Graph data updated with \(bgData.count) entries.",
  193. isDebug: true)
  194. viewUpdateNSBG(sourceName: sourceName)
  195. }
  196. func updateServerText(with serverText: String? = nil) {
  197. if Storage.shared.showDisplayName.value, let displayName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String {
  198. Observable.shared.serverText.value = displayName
  199. } else if let serverText = serverText {
  200. Observable.shared.serverText.value = serverText
  201. }
  202. }
  203. // NS BG Data Front end updater
  204. func viewUpdateNSBG(sourceName: String) {
  205. DispatchQueue.main.async {
  206. TaskScheduler.shared.rescheduleTask(id: .minAgoUpdate, to: Date())
  207. let entries = self.bgData
  208. if entries.count < 2 { // Protect index out of bounds
  209. Storage.shared.lastBGChecked.value = Date()
  210. return
  211. }
  212. self.updateBGGraph()
  213. self.updateStats()
  214. let latestEntryIndex = entries.count - 1
  215. let latestBG = entries[latestEntryIndex].sgv
  216. let priorBG = entries[latestEntryIndex - 1].sgv
  217. let deltaBG = latestBG - priorBG
  218. let lastBGTime = entries[latestEntryIndex].date
  219. self.updateServerText(with: sourceName)
  220. // Set BGText with the latest BG value
  221. self.updateBGTextAppearance()
  222. if latestBG <= globalVariables.minDisplayGlucose {
  223. Observable.shared.bgText.value = "LOW"
  224. } else if latestBG >= globalVariables.maxDisplayGlucose {
  225. Observable.shared.bgText.value = "HIGH"
  226. } else {
  227. Observable.shared.bgText.value = Localizer.toDisplayUnits(String(latestBG))
  228. }
  229. Observable.shared.bg.value = latestBG
  230. // Direction handling
  231. if let directionBG = entries[latestEntryIndex].direction {
  232. Observable.shared.directionText.value = self.bgDirectionGraphic(directionBG)
  233. } else {
  234. Observable.shared.directionText.value = ""
  235. }
  236. // Delta handling
  237. if deltaBG < 0 {
  238. Observable.shared.deltaText.value = Localizer.toDisplayUnits(String(deltaBG))
  239. } else {
  240. Observable.shared.deltaText.value = "+" + Localizer.toDisplayUnits(String(deltaBG))
  241. }
  242. // Live Activity storage
  243. Storage.shared.lastBgReadingTimeSeconds.value = lastBGTime
  244. Storage.shared.lastDeltaMgdl.value = Double(deltaBG)
  245. Storage.shared.lastTrendCode.value = entries[latestEntryIndex].direction
  246. // Mark BG data as loaded for initial loading state
  247. self.markDataLoaded("bg")
  248. // Live Activity update
  249. #if !targetEnvironment(macCatalyst)
  250. LiveActivityManager.shared.refreshFromCurrentState(reason: "bg")
  251. #endif
  252. // Update contact
  253. if Storage.shared.contactEnabled.value {
  254. self.contactImageUpdater
  255. .updateContactImage(
  256. bgValue: Observable.shared.bgText.value,
  257. trend: Observable.shared.directionText.value,
  258. delta: Observable.shared.deltaText.value,
  259. iob: Observable.shared.iobText.value,
  260. stale: Observable.shared.bgStale.value
  261. )
  262. }
  263. Storage.shared.lastBGChecked.value = Date()
  264. }
  265. }
  266. }