BGData.swift 13 KB

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