NightScout.swift 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873
  1. //
  2. // NightScout.swift
  3. // LoopFollow
  4. //
  5. // Created by Jon Fawcett on 6/16/20.
  6. // Copyright © 2020 Jon Fawcett. All rights reserved.
  7. //
  8. import Foundation
  9. import UIKit
  10. extension MainViewController {
  11. //NS Carbs Struct
  12. struct carbsData: Codable {
  13. var carbs: Double?
  14. }
  15. //NS Cage Struct
  16. struct cageData: Codable {
  17. var created_at: String
  18. }
  19. //NS Basal Profile Struct
  20. struct basalProfileStruct: Codable {
  21. var value: Double
  22. var time: String
  23. var timeAsSeconds: Double
  24. }
  25. //NS Basal Data Struct
  26. struct basalGraphStruct: Codable {
  27. var basalRate: Double
  28. var date: TimeInterval
  29. }
  30. //NS Bolus Data Struct
  31. struct bolusGraphStruct: Codable {
  32. var value: Double
  33. var date: TimeInterval
  34. var sgv: Int
  35. }
  36. //NS Bolus Data Struct
  37. struct carbGraphStruct: Codable {
  38. var value: Double
  39. var date: TimeInterval
  40. var sgv: Int
  41. var absorptionTime: Int
  42. }
  43. func isStaleData() -> Bool {
  44. if bgData.count > 0 {
  45. let now = dateTimeUtils.getNowTimeIntervalUTC()
  46. let lastReadingTime = bgData.last!.date
  47. let secondsAgo = now - lastReadingTime
  48. if secondsAgo >= 20*60 {
  49. return true
  50. } else {
  51. return false
  52. }
  53. } else {
  54. return false
  55. }
  56. }
  57. // Dex Share Web Call
  58. func webLoadDexShare(onlyPullLastRecord: Bool = false) {
  59. // Dexcom Share only returns 24 hrs of data as of now
  60. // Requesting more just for consistency with NS
  61. let graphHours = 24 * UserDefaultsRepository.downloadDays.value
  62. var count = graphHours * 12
  63. if onlyPullLastRecord { count = 1 }
  64. dexShare?.fetchData(count) { (err, result) -> () in
  65. // TODO: add error checking
  66. if(err == nil) {
  67. var data = result!
  68. // If Dex data is old, load from NS instead
  69. let latestDate = data[0].date
  70. let now = dateTimeUtils.getNowTimeIntervalUTC()
  71. if (latestDate + 330) < now && UserDefaultsRepository.url.value != "" {
  72. self.webLoadNSBGData(onlyPullLastRecord: onlyPullLastRecord)
  73. print("dex didn't load, triggered NS attempt")
  74. return
  75. }
  76. // Dexcom only returns 24 hrs of data. If we need more, call NS.
  77. if graphHours > 24 && !onlyPullLastRecord && UserDefaultsRepository.url.value != "" {
  78. self.webLoadNSBGData(onlyPullLastRecord: onlyPullLastRecord, dexData: data)
  79. } else {
  80. self.ProcessDexBGData(data: data, onlyPullLastRecord: onlyPullLastRecord, sourceName: "Dexcom")
  81. }
  82. } else {
  83. // If we get an error, immediately try to pull NS BG Data
  84. if UserDefaultsRepository.url.value != "" {
  85. self.webLoadNSBGData(onlyPullLastRecord: onlyPullLastRecord)
  86. }
  87. if globalVariables.dexVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  88. globalVariables.dexVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  89. DispatchQueue.main.async {
  90. //self.sendNotification(title: "Dexcom Share Error", body: "Please double check user name and password, internet connection, and sharing status.")
  91. }
  92. }
  93. }
  94. }
  95. }
  96. // NS BG Data Web call
  97. func webLoadNSBGData(onlyPullLastRecord: Bool = false, dexData: [ShareGlucoseData] = []) {
  98. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: BG") }
  99. // This kicks it out in the instance where dexcom fails but they aren't using NS &&
  100. if UserDefaultsRepository.url.value == "" {
  101. self.startBGTimer(time: 10)
  102. return
  103. }
  104. // URL processor
  105. var urlBGDataPath: String = UserDefaultsRepository.url.value + "/api/v1/entries/sgv.json?"
  106. if onlyPullLastRecord {
  107. urlBGDataPath = urlBGDataPath + "count=1"
  108. } else {
  109. //Fetch entries for the time period of "downloadDays"
  110. let utcISODateFormatter = ISO8601DateFormatter()
  111. let date = Calendar.current.date(byAdding: .day, value: -1 * UserDefaultsRepository.downloadDays.value, to: Date())!
  112. urlBGDataPath = urlBGDataPath + "count=1000&find[dateString][$gte]=" + utcISODateFormatter.string(from: date)
  113. }
  114. if !token.isEmpty {
  115. urlBGDataPath = urlBGDataPath + "&token=" + token
  116. }
  117. guard let urlBGData = URL(string: urlBGDataPath) else {
  118. // if we have Dex data, use it
  119. if !dexData.isEmpty {
  120. self.ProcessDexBGData(data: dexData, onlyPullLastRecord: onlyPullLastRecord, sourceName: "Dexcom")
  121. return
  122. }
  123. if globalVariables.nsVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  124. globalVariables.nsVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  125. //self.sendNotification(title: "Nightscout Error", body: "Please double check url, token, and internet connection. This may also indicate a temporary Nightscout issue")
  126. }
  127. DispatchQueue.main.async {
  128. if self.bgTimer.isValid {
  129. self.bgTimer.invalidate()
  130. }
  131. self.startBGTimer(time: 10)
  132. }
  133. return
  134. }
  135. var request = URLRequest(url: urlBGData)
  136. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  137. // Downloader
  138. let getBGTask = URLSession.shared.dataTask(with: request) { data, response, error in
  139. guard error == nil else {
  140. if globalVariables.nsVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  141. globalVariables.nsVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  142. //self.sendNotification(title: "Nightscout Error", body: "Please double check url, token, and internet connection. This may also indicate a temporary Nightscout issue")
  143. }
  144. DispatchQueue.main.async {
  145. if self.bgTimer.isValid {
  146. self.bgTimer.invalidate()
  147. }
  148. self.startBGTimer(time: 10)
  149. }
  150. // if we have Dex data, use it
  151. if !dexData.isEmpty {
  152. self.ProcessDexBGData(data: dexData, onlyPullLastRecord: onlyPullLastRecord, sourceName: "Dexcom")
  153. }
  154. return
  155. }
  156. guard let data = data else {
  157. if globalVariables.nsVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  158. globalVariables.nsVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  159. //self.sendNotification(title: "Nightscout Error", body: "Please double check url, token, and internet connection. This may also indicate a temporary Nightscout issue")
  160. }
  161. DispatchQueue.main.async {
  162. if self.bgTimer.isValid {
  163. self.bgTimer.invalidate()
  164. }
  165. self.startBGTimer(time: 10)
  166. }
  167. return
  168. }
  169. var entriesResponse: [ShareGlucoseData]?
  170. let decoder = JSONDecoder()
  171. do {
  172. entriesResponse = try decoder.decode([ShareGlucoseData].self, from: data)
  173. } catch let DecodingError.dataCorrupted(context) {
  174. print("Data corrupted: \(context)")
  175. } catch let DecodingError.keyNotFound(key, context) {
  176. print("Key '\(key)' not found: \(context.debugDescription)")
  177. print("codingPath: \(context.codingPath)")
  178. } catch let DecodingError.valueNotFound(value, context) {
  179. print("Value '\(value)' not found: \(context.debugDescription)")
  180. print("codingPath: \(context.codingPath)")
  181. } catch let DecodingError.typeMismatch(type, context) {
  182. print("Type '\(type)' mismatch: \(context.debugDescription)")
  183. print("codingPath: \(context.codingPath)")
  184. } catch {
  185. print("Error decoding JSON: \(error)")
  186. }
  187. if var nsData = entriesResponse {
  188. DispatchQueue.main.async {
  189. // transform NS data to look like Dex data
  190. for i in 0..<nsData.count {
  191. // convert the NS timestamp to seconds instead of milliseconds
  192. nsData[i].date /= 1000
  193. nsData[i].date.round(FloatingPointRoundingRule.toNearestOrEven)
  194. }
  195. print(nsData.count)
  196. //Avoid duplicate entries messing up the graph, only use one reading per 5 minutes.
  197. let graphHours = 24 * UserDefaultsRepository.downloadDays.value
  198. let points = graphHours * 12 + 1
  199. var nsData2 = [ShareGlucoseData]()
  200. let timestamp = Date().timeIntervalSince1970
  201. for i in 0..<points {
  202. //Starting with "now" and then step 5 minutes back in time
  203. let target = timestamp - Double(i) * 60 * 5
  204. //Find the reading closest to the target, but not too far away
  205. let closest = nsData.filter{ abs($0.date - target) < 3 * 60 }.min { abs($0.date - target) < abs($1.date - target) }
  206. //If a reading is found, add it to the new array
  207. if let item = closest {
  208. nsData2.append(item)
  209. }
  210. }
  211. print(nsData2.count)
  212. // merge NS and Dex data if needed; use recent Dex data and older NS data
  213. var sourceName = "Nightscout"
  214. if !dexData.isEmpty {
  215. let oldestDexDate = dexData[dexData.count - 1].date
  216. var itemsToRemove = 0
  217. while itemsToRemove < nsData2.count && nsData2[itemsToRemove].date >= oldestDexDate {
  218. itemsToRemove += 1
  219. }
  220. nsData2.removeFirst(itemsToRemove)
  221. nsData2 = dexData + nsData2
  222. sourceName = "Dexcom"
  223. }
  224. // trigger the processor for the data after downloading.
  225. self.ProcessDexBGData(data: nsData2, onlyPullLastRecord: onlyPullLastRecord, sourceName: sourceName)
  226. }
  227. } else {
  228. if globalVariables.nsVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  229. globalVariables.nsVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  230. //self.sendNotification(title: "Nightscout Failure", body: "Please double check url, token, and internet connection. This may also indicate a temporary Nightscout issue")
  231. }
  232. DispatchQueue.main.async {
  233. if self.bgTimer.isValid {
  234. self.bgTimer.invalidate()
  235. }
  236. self.startBGTimer(time: 10)
  237. }
  238. return
  239. }
  240. }
  241. getBGTask.resume()
  242. }
  243. // Dexcom BG Data Response processor
  244. func ProcessDexBGData(data: [ShareGlucoseData], onlyPullLastRecord: Bool, sourceName: String){
  245. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: BG") }
  246. let graphHours = 24 * UserDefaultsRepository.downloadDays.value
  247. let pullDate = data[data.count - 1].date
  248. let latestDate = data[0].date
  249. let now = dateTimeUtils.getNowTimeIntervalUTC()
  250. // Start the BG timer based on the reading
  251. let secondsAgo = now - latestDate
  252. DispatchQueue.main.async {
  253. // if reading is overdue over: 20:00, re-attempt every 5 minutes
  254. if secondsAgo >= (20 * 60) {
  255. self.startBGTimer(time: (5 * 60))
  256. print("##### started 5 minute bg timer")
  257. // if the reading is overdue: 10:00-19:59, re-attempt every minute
  258. } else if secondsAgo >= (10 * 60) {
  259. self.startBGTimer(time: 60)
  260. print("##### started 1 minute bg timer")
  261. // if the reading is overdue: 7:00-9:59, re-attempt every 30 seconds
  262. } else if secondsAgo >= (7 * 60) {
  263. self.startBGTimer(time: 30)
  264. print("##### started 30 second bg timer")
  265. // if the reading is overdue: 5:00-6:59 re-attempt every 10 seconds
  266. } else if secondsAgo >= (5 * 60) {
  267. self.startBGTimer(time: 10)
  268. print("##### started 10 second bg timer")
  269. // We have a current reading. Set timer to 5:10 from last reading
  270. } else {
  271. self.startBGTimer(time: 300 - secondsAgo + Double(UserDefaultsRepository.bgUpdateDelay.value))
  272. let timerVal = 310 - secondsAgo
  273. print("##### started 5:10 bg timer: \(timerVal)")
  274. self.updateBadge(val: data[0].sgv)
  275. if UserDefaultsRepository.speakBG.value {
  276. self.speakBG(currentValue: data[0].sgv, previousValue: data[1].sgv)
  277. }
  278. }
  279. }
  280. // If we already have data, we're going to pop it to the end and remove the first. If we have old or no data, we'll destroy the whole array and start over. This is simpler than determining how far back we need to get new data from in case Dex back-filled readings
  281. if !onlyPullLastRecord {
  282. bgData.removeAll()
  283. } else if bgData[bgData.count - 1].date != pullDate {
  284. bgData.removeFirst()
  285. } else {
  286. return
  287. }
  288. // loop through the data so we can reverse the order to oldest first for the graph
  289. for i in 0..<data.count {
  290. let dateString = data[data.count - 1 - i].date
  291. if dateString >= dateTimeUtils.getTimeIntervalNHoursAgo(N: graphHours) {
  292. let sgvValue = data[data.count - 1 - i].sgv
  293. // Skip the current iteration if the sgv value is over 600
  294. // First time a user starts a G7, they get a value of 4000
  295. if sgvValue > 600 {
  296. continue
  297. }
  298. let reading = ShareGlucoseData(sgv: sgvValue, date: dateString, direction: data[data.count - 1 - i].direction)
  299. bgData.append(reading)
  300. }
  301. }
  302. viewUpdateNSBG(sourceName: sourceName)
  303. }
  304. // NS BG Data Front end updater
  305. func viewUpdateNSBG (sourceName: String) {
  306. DispatchQueue.main.async {
  307. if UserDefaultsRepository.debugLog.value {
  308. self.writeDebugLog(value: "Display: BG")
  309. self.writeDebugLog(value: "Num BG: " + self.bgData.count.description)
  310. }
  311. let entries = self.bgData
  312. if entries.count < 1 { return }
  313. self.updateBGGraph()
  314. self.updateStats()
  315. let latestEntryi = entries.count - 1
  316. let latestBG = entries[latestEntryi].sgv
  317. let priorBG = entries[latestEntryi - 1].sgv
  318. let deltaBG = latestBG - priorBG as Int
  319. let lastBGTime = entries[latestEntryi].date
  320. let deltaTime = (TimeInterval(Date().timeIntervalSince1970)-lastBGTime) / 60
  321. var userUnit = " mg/dL"
  322. if self.mmol {
  323. userUnit = " mmol/L"
  324. }
  325. self.serverText.text = sourceName
  326. var snoozerBG = ""
  327. var snoozerDirection = ""
  328. var snoozerDelta = ""
  329. self.BGText.text = bgUnits.toDisplayUnits(String(latestBG))
  330. snoozerBG = bgUnits.toDisplayUnits(String(latestBG))
  331. self.setBGTextColor()
  332. if let directionBG = entries[latestEntryi].direction {
  333. self.DirectionText.text = self.bgDirectionGraphic(directionBG)
  334. snoozerDirection = self.bgDirectionGraphic(directionBG)
  335. self.latestDirectionString = self.bgDirectionGraphic(directionBG)
  336. }
  337. else
  338. {
  339. self.DirectionText.text = ""
  340. snoozerDirection = ""
  341. self.latestDirectionString = ""
  342. }
  343. if deltaBG < 0 {
  344. self.DeltaText.text = bgUnits.toDisplayUnits(String(deltaBG))
  345. snoozerDelta = bgUnits.toDisplayUnits(String(deltaBG))
  346. self.latestDeltaString = String(deltaBG)
  347. }
  348. else
  349. {
  350. self.DeltaText.text = "+" + bgUnits.toDisplayUnits(String(deltaBG))
  351. snoozerDelta = "+" + bgUnits.toDisplayUnits(String(deltaBG))
  352. self.latestDeltaString = "+" + String(deltaBG)
  353. }
  354. // Snoozer Display
  355. guard let snoozer = self.tabBarController!.viewControllers?[2] as? SnoozeViewController else { return }
  356. snoozer.BGLabel.text = snoozerBG
  357. snoozer.DirectionLabel.text = snoozerDirection
  358. snoozer.DeltaLabel.text = snoozerDelta
  359. }
  360. }
  361. // NS Device Status Web Call
  362. func webLoadNSDeviceStatus() {
  363. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: device status") }
  364. let urlUser = UserDefaultsRepository.url.value
  365. // NS Api is not working to find by greater than date
  366. var urlStringDeviceStatus = urlUser + "/api/v1/devicestatus.json?count=288"
  367. if token != "" {
  368. urlStringDeviceStatus = urlUser + "/api/v1/devicestatus.json?count=288&token=" + token
  369. }
  370. let escapedAddress = urlStringDeviceStatus.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
  371. guard let urlDeviceStatus = URL(string: escapedAddress!) else {
  372. if globalVariables.nsVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  373. globalVariables.nsVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  374. //self.sendNotification(title: "Nightscout Failure", body: "Please double check url, token, and internet connection. This may also indicate a temporary Nightscout issue")
  375. }
  376. DispatchQueue.main.async {
  377. if self.deviceStatusTimer.isValid {
  378. self.deviceStatusTimer.invalidate()
  379. }
  380. self.startDeviceStatusTimer(time: 10)
  381. }
  382. return
  383. }
  384. var requestDeviceStatus = URLRequest(url: urlDeviceStatus)
  385. requestDeviceStatus.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  386. let deviceStatusTask = URLSession.shared.dataTask(with: requestDeviceStatus) { data, response, error in
  387. guard error == nil else {
  388. if globalVariables.nsVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  389. globalVariables.nsVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  390. //self.sendNotification(title: "Nightscout Error", body: "Please double check url, token, and internet connection. This may also indicate a temporary Nightscout issue")
  391. }
  392. DispatchQueue.main.async {
  393. if self.deviceStatusTimer.isValid {
  394. self.deviceStatusTimer.invalidate()
  395. }
  396. self.startDeviceStatusTimer(time: 10)
  397. }
  398. return
  399. }
  400. guard let data = data else {
  401. if globalVariables.nsVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  402. globalVariables.nsVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  403. //self.sendNotification(title: "Nightscout Error", body: "Please double check url, token, and internet connection. This may also indicate a temporary Nightscout issue")
  404. }
  405. DispatchQueue.main.async {
  406. if self.deviceStatusTimer.isValid {
  407. self.deviceStatusTimer.invalidate()
  408. }
  409. self.startDeviceStatusTimer(time: 10)
  410. }
  411. return
  412. }
  413. let json = try? (JSONSerialization.jsonObject(with: data) as? [[String:AnyObject]])
  414. if let json = json {
  415. DispatchQueue.main.async {
  416. self.updateDeviceStatusDisplay(jsonDeviceStatus: json)
  417. }
  418. } else {
  419. if globalVariables.nsVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  420. globalVariables.nsVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  421. //self.sendNotification(title: "Nightscout Error", body: "Please double check url, token, and internet connection. This may also indicate a temporary Nightscout issue")
  422. }
  423. DispatchQueue.main.async {
  424. if self.deviceStatusTimer.isValid {
  425. self.deviceStatusTimer.invalidate()
  426. }
  427. self.startDeviceStatusTimer(time: 10)
  428. }
  429. return
  430. }
  431. }
  432. deviceStatusTask.resume()
  433. }
  434. // NS Device Status Response Processor
  435. func updateDeviceStatusDisplay(jsonDeviceStatus: [[String:AnyObject]]) {
  436. self.clearLastInfoData(index: 0)
  437. self.clearLastInfoData(index: 1)
  438. self.clearLastInfoData(index: 3)
  439. self.clearLastInfoData(index: 4)
  440. self.clearLastInfoData(index: 5)
  441. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: device status") }
  442. if jsonDeviceStatus.count == 0 {
  443. return
  444. }
  445. //Process the current data first
  446. let lastDeviceStatus = jsonDeviceStatus[0] as [String : AnyObject]?
  447. //pump and uploader
  448. let formatter = ISO8601DateFormatter()
  449. formatter.formatOptions = [.withFullDate,
  450. .withTime,
  451. .withDashSeparatorInDate,
  452. .withColonSeparatorInTime]
  453. if let lastPumpRecord = lastDeviceStatus?["pump"] as! [String : AnyObject]? {
  454. if let lastPumpTime = formatter.date(from: (lastPumpRecord["clock"] as! String))?.timeIntervalSince1970 {
  455. if let reservoirData = lastPumpRecord["reservoir"] as? Double {
  456. latestPumpVolume = reservoirData
  457. tableData[5].value = String(format:"%.0f", reservoirData) + "U"
  458. } else {
  459. latestPumpVolume = 50.0
  460. tableData[5].value = "50+U"
  461. }
  462. if let uploader = lastDeviceStatus?["uploader"] as? [String:AnyObject] {
  463. let upbat = uploader["battery"] as! Double
  464. tableData[4].value = String(format:"%.0f", upbat) + "%"
  465. UserDefaultsRepository.deviceBatteryLevel.value = upbat
  466. }
  467. }
  468. }
  469. // Loop
  470. if let lastLoopRecord = lastDeviceStatus?["loop"] as! [String : AnyObject]? {
  471. //print("Loop: \(lastLoopRecord)")
  472. if let lastLoopTime = formatter.date(from: (lastLoopRecord["timestamp"] as! String))?.timeIntervalSince1970 {
  473. UserDefaultsRepository.alertLastLoopTime.value = lastLoopTime
  474. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "lastLoopTime: " + String(lastLoopTime)) }
  475. if let failure = lastLoopRecord["failureReason"] {
  476. LoopStatusLabel.text = "X"
  477. latestLoopStatusString = "X"
  478. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Loop Failure: X") }
  479. } else {
  480. var wasEnacted = false
  481. if let enacted = lastLoopRecord["enacted"] as? [String:AnyObject] {
  482. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Loop: Was Enacted") }
  483. wasEnacted = true
  484. if let lastTempBasal = enacted["rate"] as? Double {
  485. }
  486. }
  487. if let iobdata = lastLoopRecord["iob"] as? [String:AnyObject] {
  488. tableData[0].value = String(format:"%.2f", (iobdata["iob"] as! Double))
  489. latestIOB = String(format:"%.2f", (iobdata["iob"] as! Double))
  490. }
  491. if let cobdata = lastLoopRecord["cob"] as? [String:AnyObject] {
  492. tableData[1].value = String(format:"%.0f", cobdata["cob"] as! Double)
  493. latestCOB = String(format:"%.0f", cobdata["cob"] as! Double)
  494. }
  495. if let predictdata = lastLoopRecord["predicted"] as? [String:AnyObject] {
  496. let prediction = predictdata["values"] as! [Double]
  497. PredictionLabel.text = bgUnits.toDisplayUnits(String(Int(prediction.last!)))
  498. PredictionLabel.textColor = UIColor.systemPurple
  499. if UserDefaultsRepository.downloadPrediction.value && latestLoopTime < lastLoopTime {
  500. predictionData.removeAll()
  501. var predictionTime = lastLoopTime
  502. let toLoad = Int(UserDefaultsRepository.predictionToLoad.value * 12)
  503. var i = 0
  504. while i <= toLoad {
  505. if i < prediction.count {
  506. let sgvValue = Int(round(prediction[i]))
  507. // Skip values higher than 600
  508. if sgvValue <= 600 {
  509. let prediction = ShareGlucoseData(sgv: sgvValue, date: predictionTime, direction: "flat")
  510. predictionData.append(prediction)
  511. }
  512. predictionTime += 300
  513. }
  514. i += 1
  515. }
  516. let predMin = prediction.min()
  517. let predMax = prediction.max()
  518. tableData[9].value = bgUnits.toDisplayUnits(String(predMin!)) + "/" + bgUnits.toDisplayUnits(String(predMax!))
  519. updatePredictionGraph()
  520. }
  521. }
  522. if let recBolus = lastLoopRecord["recommendedBolus"] as? Double {
  523. tableData[8].value = String(format:"%.2fU", recBolus)
  524. }
  525. if let loopStatus = lastLoopRecord["recommendedTempBasal"] as? [String:AnyObject] {
  526. if let tempBasalTime = formatter.date(from: (loopStatus["timestamp"] as! String))?.timeIntervalSince1970 {
  527. var lastBGTime = lastLoopTime
  528. if bgData.count > 0 {
  529. lastBGTime = bgData[bgData.count - 1].date
  530. }
  531. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "tempBasalTime: " + String(tempBasalTime)) }
  532. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "lastBGTime: " + String(lastBGTime)) }
  533. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "wasEnacted: " + String(wasEnacted)) }
  534. if tempBasalTime > lastBGTime && !wasEnacted {
  535. LoopStatusLabel.text = "⏀"
  536. latestLoopStatusString = "⏀"
  537. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Open Loop: recommended temp. temp time > bg time, was not enacted") }
  538. } else {
  539. LoopStatusLabel.text = "↻"
  540. latestLoopStatusString = "↻"
  541. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Looping: recommended temp, but temp time is < bg time and/or was enacted") }
  542. }
  543. }
  544. } else {
  545. LoopStatusLabel.text = "↻"
  546. latestLoopStatusString = "↻"
  547. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Looping: no recommended temp") }
  548. }
  549. }
  550. if ((TimeInterval(Date().timeIntervalSince1970) - lastLoopTime) / 60) > 15 {
  551. LoopStatusLabel.text = "⚠"
  552. latestLoopStatusString = "⚠"
  553. }
  554. latestLoopTime = lastLoopTime
  555. } // end lastLoopTime
  556. } // end lastLoop Record
  557. var oText = "" as String
  558. currentOverride = 1.0
  559. if let lastOverride = lastDeviceStatus?["override"] as! [String : AnyObject]? {
  560. if let lastOverrideTime = formatter.date(from: (lastOverride["timestamp"] as! String))?.timeIntervalSince1970 {
  561. }
  562. if lastOverride["active"] as! Bool {
  563. let lastCorrection = lastOverride["currentCorrectionRange"] as! [String: AnyObject]
  564. if let multiplier = lastOverride["multiplier"] as? Double {
  565. currentOverride = multiplier
  566. oText += String(format: "%.0f%%", (multiplier * 100))
  567. }
  568. else
  569. {
  570. oText += "100%"
  571. }
  572. oText += " ("
  573. let minValue = lastCorrection["minValue"] as! Double
  574. let maxValue = lastCorrection["maxValue"] as! Double
  575. oText += bgUnits.toDisplayUnits(String(minValue)) + "-" + bgUnits.toDisplayUnits(String(maxValue)) + ")"
  576. tableData[3].value = oText
  577. }
  578. }
  579. infoTable.reloadData()
  580. // Start the timer based on the timestamp
  581. let now = dateTimeUtils.getNowTimeIntervalUTC()
  582. let secondsAgo = now - latestLoopTime
  583. DispatchQueue.main.async {
  584. // if Loop is overdue over: 20:00, re-attempt every 5 minutes
  585. if secondsAgo >= (20 * 60) {
  586. self.startDeviceStatusTimer(time: (5 * 60))
  587. print("started 5 minute device status timer")
  588. // if the Loop is overdue: 10:00-19:59, re-attempt every minute
  589. } else if secondsAgo >= (10 * 60) {
  590. self.startDeviceStatusTimer(time: 60)
  591. print("started 1 minute device status timer")
  592. // if the Loop is overdue: 7:00-9:59, re-attempt every 30 seconds
  593. } else if secondsAgo >= (7 * 60) {
  594. self.startDeviceStatusTimer(time: 30)
  595. print("started 30 second device status timer")
  596. // if the Loop is overdue: 5:00-6:59 re-attempt every 10 seconds
  597. } else if secondsAgo >= (5 * 60) {
  598. self.startDeviceStatusTimer(time: 10)
  599. print("started 10 second device status timer")
  600. // We have a current Loop. Set timer to 5:10 from last reading
  601. } else {
  602. self.startDeviceStatusTimer(time: 310 - secondsAgo)
  603. let timerVal = 310 - secondsAgo
  604. print("started 5:10 device status timer: \(timerVal)")
  605. }
  606. }
  607. }
  608. // NS Carbs Today Web Call
  609. func webLoadNSCarbsToday() {
  610. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: Carbs Today") }
  611. let urlUser = UserDefaultsRepository.url.value
  612. let now = Date()
  613. let timeZone = TimeZone.current
  614. var calendar = Calendar(identifier: .gregorian)
  615. calendar.timeZone = timeZone
  616. var dateComponents = calendar.dateComponents(in: timeZone, from: now)
  617. dateComponents.hour = 0
  618. dateComponents.minute = 0
  619. dateComponents.second = 0
  620. guard let date = dateComponents.date else { fatalError("Invalid date components") }
  621. let dateFormatter = DateFormatter()
  622. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
  623. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  624. let utcDateString = dateFormatter.string(from: date)
  625. var urlString = urlUser + "/api/v1/treatments.json?count=1000&find[eventType]=Carb+Correction&find[timestamp][$gte]=" + utcDateString
  626. if token != "" {
  627. urlString = urlUser + "/api/v1/treatments.json?token=" + token + "&count=1000&find[eventType]=Carb+Correction&find[timestamp][$gte]=" + utcDateString
  628. }
  629. guard let urlData = URL(string: urlString) else {
  630. return
  631. }
  632. var request = URLRequest(url: urlData)
  633. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  634. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  635. guard error == nil else {
  636. return
  637. }
  638. guard let data = data else {
  639. return
  640. }
  641. let decoder = JSONDecoder()
  642. let entriesResponse = try? decoder.decode([carbsData].self, from: data)
  643. if let entriesResponse = entriesResponse {
  644. DispatchQueue.main.async {
  645. self.updateCarbsToday(data: entriesResponse)
  646. }
  647. } else {
  648. return
  649. }
  650. }
  651. task.resume()
  652. }
  653. // NS CarbsToday Response Processor
  654. func updateCarbsToday(data: [carbsData]) {
  655. self.clearLastInfoData(index: 10)
  656. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: carbs") }
  657. if data.count == 0 {
  658. return
  659. }
  660. let totalCarbs = data.reduce(0.0) { $0 + ($1.carbs ?? 0.0) }
  661. let resultString = String(format: "%.0f", totalCarbs)
  662. tableData[10].value = resultString
  663. infoTable.reloadData()
  664. }
  665. // NS Cage Web Call
  666. func webLoadNSCage() {
  667. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: CAGE") }
  668. let urlUser = UserDefaultsRepository.url.value
  669. var urlString = urlUser + "/api/v1/treatments.json?find[eventType]=Site%20Change&count=1"
  670. if token != "" {
  671. urlString = urlUser + "/api/v1/treatments.json?token=" + token + "&find[eventType]=Site%20Change&count=1"
  672. }
  673. guard let urlData = URL(string: urlString) else {
  674. return
  675. }
  676. var request = URLRequest(url: urlData)
  677. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  678. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  679. guard error == nil else {
  680. return
  681. }
  682. guard let data = data else {
  683. return
  684. }
  685. let decoder = JSONDecoder()
  686. let entriesResponse = try? decoder.decode([cageData].self, from: data)
  687. if let entriesResponse = entriesResponse {
  688. DispatchQueue.main.async {
  689. self.updateCage(data: entriesResponse)
  690. }
  691. } else {
  692. return
  693. }
  694. }
  695. task.resume()
  696. }
  697. // NS Cage Response Processor
  698. func updateCage(data: [cageData]) {
  699. self.clearLastInfoData(index: 7)
  700. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: CAGE") }
  701. if data.count == 0 {
  702. return
  703. }
  704. let lastCageString = data[0].created_at
  705. let formatter = ISO8601DateFormatter()
  706. formatter.formatOptions = [.withFullDate,
  707. .withTime,
  708. .withDashSeparatorInDate,
  709. .withColonSeparatorInTime]
  710. UserDefaultsRepository.alertCageInsertTime.value = formatter.date(from: (lastCageString))?.timeIntervalSince1970 as! TimeInterval
  711. if let cageTime = formatter.date(from: (lastCageString))?.timeIntervalSince1970 {
  712. let now = dateTimeUtils.getNowTimeIntervalUTC()
  713. let secondsAgo = now - cageTime
  714. //let days = 24 * 60 * 60
  715. let formatter = DateComponentsFormatter()
  716. formatter.unitsStyle = .positional // Use the appropriate positioning for the current locale
  717. formatter.allowedUnits = [ .day, .hour ] // Units to display in the formatted string
  718. formatter.zeroFormattingBehavior = [ .pad ] // Pad with zeroes where appropriate for the locale
  719. let formattedDuration = formatter.string(from: secondsAgo)
  720. tableData[7].value = formattedDuration ?? ""
  721. }
  722. infoTable.reloadData()
  723. }
  724. // NS Sage Web Call
  725. func webLoadNSSage() {
  726. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: SAGE") }
  727. let lastDateString = dateTimeUtils.nowMinus10DaysTimeInterval()
  728. let urlUser = UserDefaultsRepository.url.value
  729. var urlString = urlUser + "/api/v1/treatments.json?find[eventType]=Sensor%20Start&find[created_at][$gte]=" + lastDateString + "&count=1"
  730. if token != "" {
  731. urlString = urlUser + "/api/v1/treatments.json?token=" + token + "&find[eventType]=Sensor%20Start&find[created_at][$gte]=" + lastDateString + "&count=1"
  732. }
  733. guard let urlData = URL(string: urlString) else {
  734. return
  735. }
  736. var request = URLRequest(url: urlData)
  737. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  738. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  739. guard error == nil else {
  740. return
  741. }
  742. guard let data = data else {
  743. return
  744. }
  745. let decoder = JSONDecoder()
  746. let entriesResponse = try? decoder.decode([cageData].self, from: data)
  747. if let entriesResponse = entriesResponse {
  748. DispatchQueue.main.async {
  749. self.updateSage(data: entriesResponse)
  750. }
  751. } else {
  752. return
  753. }
  754. }
  755. task.resume()
  756. }
  757. // NS Sage Response Processor
  758. func updateSage(data: [cageData]) {
  759. self.clearLastInfoData(index: 6)
  760. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process/Display: SAGE") }
  761. if data.count == 0 {
  762. return
  763. }
  764. var lastSageString = data[0].created_at
  765. let formatter = ISO8601DateFormatter()
  766. formatter.formatOptions = [.withFullDate,
  767. .withTime,
  768. .withDashSeparatorInDate,
  769. .withColonSeparatorInTime]
  770. UserDefaultsRepository.alertSageInsertTime.value = formatter.date(from: (lastSageString))?.timeIntervalSince1970 as! TimeInterval
  771. if UserDefaultsRepository.alertAutoSnoozeCGMStart.value && (dateTimeUtils.getNowTimeIntervalUTC() - UserDefaultsRepository.alertSageInsertTime.value < 7200){
  772. let snoozeTime = Date(timeIntervalSince1970: UserDefaultsRepository.alertSageInsertTime.value + 7200)
  773. UserDefaultsRepository.alertSnoozeAllTime.value = snoozeTime
  774. UserDefaultsRepository.alertSnoozeAllIsSnoozed.value = true
  775. guard let alarms = self.tabBarController!.viewControllers?[1] as? AlarmViewController else { return }
  776. alarms.reloadIsSnoozed(key: "alertSnoozeAllIsSnoozed", value: true)
  777. alarms.reloadSnoozeTime(key: "alertSnoozeAllTime", setNil: false, value: snoozeTime)
  778. }
  779. if let sageTime = formatter.date(from: (lastSageString as! String))?.timeIntervalSince1970 {
  780. let now = dateTimeUtils.getNowTimeIntervalUTC()
  781. let secondsAgo = now - sageTime
  782. let days = 24 * 60 * 60
  783. let formatter = DateComponentsFormatter()
  784. formatter.unitsStyle = .positional // Use the appropriate positioning for the current locale
  785. formatter.allowedUnits = [ .day, .hour] // Units to display in the formatted string
  786. formatter.zeroFormattingBehavior = [ .pad ] // Pad with zeroes where appropriate for the locale
  787. let formattedDuration = formatter.string(from: secondsAgo)
  788. tableData[6].value = formattedDuration ?? ""
  789. }
  790. infoTable.reloadData()
  791. }
  792. // NS Profile Web Call
  793. func webLoadNSProfile() {
  794. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: profile") }
  795. let urlUser = UserDefaultsRepository.url.value
  796. var urlString = urlUser + "/api/v1/profile/current.json"
  797. if token != "" {
  798. urlString = urlUser + "/api/v1/profile/current.json?token=" + token
  799. }
  800. let escapedAddress = urlString.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
  801. guard let url = URL(string: escapedAddress!) else {
  802. return
  803. }
  804. var request = URLRequest(url: url)
  805. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  806. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  807. guard error == nil else {
  808. return
  809. }
  810. guard let data = data else {
  811. return
  812. }
  813. let json = try? JSONSerialization.jsonObject(with: data) as! Dictionary<String, Any>
  814. if let json = json {
  815. DispatchQueue.main.async {
  816. self.updateProfile(jsonDeviceStatus: json)
  817. }
  818. } else {
  819. return
  820. }
  821. }
  822. task.resume()
  823. }
  824. // NS Profile Response Processor
  825. func updateProfile(jsonDeviceStatus: Dictionary<String, Any>) {
  826. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: profile") }
  827. if jsonDeviceStatus.count == 0 {
  828. return
  829. }
  830. if jsonDeviceStatus[keyPath: "message"] != nil { return }
  831. let basal = try jsonDeviceStatus[keyPath: "store.Default.basal"] as! NSArray
  832. basalProfile.removeAll()
  833. for i in 0..<basal.count {
  834. let dict = basal[i] as! Dictionary<String, Any>
  835. do {
  836. let thisValue = try dict[keyPath: "value"] as! Double
  837. let thisTime = dict[keyPath: "time"] as! String
  838. let thisTimeAsSeconds = dict[keyPath: "timeAsSeconds"] as! Double
  839. let entry = basalProfileStruct(value: thisValue, time: thisTime, timeAsSeconds: thisTimeAsSeconds)
  840. basalProfile.append(entry)
  841. } catch {
  842. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: profile wrapped in quotes") }
  843. }
  844. }
  845. // Don't process the basal or draw the graph until after the BG has been fully processeed and drawn
  846. if firstGraphLoad { return }
  847. var basalSegments: [DataStructs.basalProfileSegment] = []
  848. let graphHours = 24 * UserDefaultsRepository.downloadDays.value
  849. // Build scheduled basal segments from right to left by
  850. // moving pointers to the current midnight and current basal
  851. var midnight = dateTimeUtils.getTimeIntervalMidnightToday()
  852. var basalProfileIndex = basalProfile.count - 1
  853. var start = midnight + basalProfile[basalProfileIndex].timeAsSeconds
  854. var end = dateTimeUtils.getNowTimeIntervalUTC()
  855. // Move back until we're in the graph range
  856. while start > end {
  857. basalProfileIndex -= 1
  858. start = midnight + basalProfile[basalProfileIndex].timeAsSeconds
  859. }
  860. // Add records while they're still within the graph
  861. let graphStart = dateTimeUtils.getTimeIntervalNHoursAgo(N: graphHours)
  862. while end >= graphStart {
  863. let entry = DataStructs.basalProfileSegment(
  864. basalRate: basalProfile[basalProfileIndex].value, startDate: start, endDate: end)
  865. basalSegments.append(entry)
  866. basalProfileIndex -= 1
  867. if basalProfileIndex < 0 {
  868. basalProfileIndex = basalProfile.count - 1
  869. midnight = midnight.advanced(by: -24*60*60)
  870. }
  871. end = start - 1
  872. start = midnight + basalProfile[basalProfileIndex].timeAsSeconds
  873. }
  874. // reverse the result to get chronological order
  875. basalSegments.reverse()
  876. var firstPass = true
  877. // Runs the scheduled basal to the end of the prediction line
  878. var predictionEndTime = dateTimeUtils.getNowTimeIntervalUTC() + (3600 * UserDefaultsRepository.predictionToLoad.value)
  879. basalScheduleData.removeAll()
  880. for i in 0..<basalSegments.count {
  881. let timeStart = dateTimeUtils.getTimeIntervalNHoursAgo(N: graphHours)
  882. // This processed everything after the first one.
  883. if firstPass == false
  884. && basalSegments[i].startDate <= predictionEndTime {
  885. let startDot = basalGraphStruct(basalRate: basalSegments[i].basalRate, date: basalSegments[i].startDate)
  886. basalScheduleData.append(startDot)
  887. var endDate = basalSegments[i].endDate
  888. // if it's the last one needed, set it to end at the prediction end time
  889. if endDate > predictionEndTime || i == basalSegments.count - 1 {
  890. endDate = Double(predictionEndTime)
  891. }
  892. let endDot = basalGraphStruct(basalRate: basalSegments[i].basalRate, date: endDate)
  893. basalScheduleData.append(endDot)
  894. }
  895. // we need to manually set the first one
  896. // Check that this is the first one and there are no existing entries
  897. if firstPass == true {
  898. // check that the timestamp is > the current entry and < the next entry
  899. if timeStart >= basalSegments[i].startDate && timeStart < basalSegments[i].endDate {
  900. // Set the start time to match the BG start
  901. let startDot = basalGraphStruct(basalRate: basalSegments[i].basalRate, date: Double(timeStart + (60 * 5)))
  902. basalScheduleData.append(startDot)
  903. // set the enddot where the next one will start
  904. var endDate = basalSegments[i].endDate
  905. let endDot = basalGraphStruct(basalRate: basalSegments[i].basalRate, date: endDate)
  906. basalScheduleData.append(endDot)
  907. firstPass = false
  908. }
  909. }
  910. }
  911. if UserDefaultsRepository.graphBasal.value {
  912. updateBasalScheduledGraph()
  913. }
  914. }
  915. // NS Treatments Web Call
  916. // Downloads Basal, Bolus, Carbs, BG Check, Notes, Overrides
  917. func WebLoadNSTreatments() {
  918. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: Treatments") }
  919. if !UserDefaultsRepository.downloadTreatments.value { return }
  920. let graphHours = 24 * UserDefaultsRepository.downloadDays.value
  921. let startTimeString = dateTimeUtils.nowMinusNHoursTimeInterval(N: graphHours)
  922. var urlString = UserDefaultsRepository.url.value + "/api/v1/treatments.json?find[created_at][$gte]=" + startTimeString
  923. if token != "" {
  924. urlString = UserDefaultsRepository.url.value + "/api/v1/treatments.json?token=" + token + "&find[created_at][$gte]=" + startTimeString
  925. }
  926. guard let urlData = URL(string: urlString) else {
  927. return
  928. }
  929. var request = URLRequest(url: urlData)
  930. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  931. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  932. guard error == nil else {
  933. return
  934. }
  935. guard let data = data else {
  936. return
  937. }
  938. let json = try? (JSONSerialization.jsonObject(with: data) as? [[String:AnyObject]])
  939. if let json = json {
  940. DispatchQueue.main.async {
  941. self.updateTreatments(entries: json)
  942. }
  943. } else {
  944. return
  945. }
  946. }
  947. task.resume()
  948. }
  949. // Process and split out treatments to individual tasks
  950. func updateTreatments(entries: [[String:AnyObject]]) {
  951. var tempBasal: [[String:AnyObject]] = []
  952. var bolus: [[String:AnyObject]] = []
  953. var carbs: [[String:AnyObject]] = []
  954. var temporaryOverride: [[String:AnyObject]] = []
  955. var note: [[String:AnyObject]] = []
  956. var bgCheck: [[String:AnyObject]] = []
  957. var suspendPump: [[String:AnyObject]] = []
  958. var resumePump: [[String:AnyObject]] = []
  959. var pumpSiteChange: [[String:AnyObject]] = []
  960. var cgmSensorStart: [[String:AnyObject]] = []
  961. for i in 0..<entries.count {
  962. let entry = entries[i] as [String : AnyObject]?
  963. switch entry?["eventType"] as! String {
  964. case "Temp Basal":
  965. tempBasal.append(entry!)
  966. case "Correction Bolus":
  967. bolus.append(entry!)
  968. case "Meal Bolus":
  969. carbs.append(entry!)
  970. bolus.append(entry!)
  971. case "Carb Correction":
  972. carbs.append(entry!)
  973. case "Temporary Override":
  974. temporaryOverride.append(entry!)
  975. case "Note":
  976. note.append(entry!)
  977. print("Note: \(String(describing: entry))")
  978. case "BG Check":
  979. bgCheck.append(entry!)
  980. case "Suspend Pump":
  981. suspendPump.append(entry!)
  982. case "Resume Pump":
  983. resumePump.append(entry!)
  984. case "Pump Site Change":
  985. pumpSiteChange.append(entry!)
  986. case "Sensor Start":
  987. cgmSensorStart.append(entry!)
  988. default:
  989. print("No Match: \(String(describing: entry))")
  990. }
  991. }
  992. // end of for loop
  993. if tempBasal.count > 0 {
  994. processNSBasals(entries: tempBasal)
  995. } else {
  996. if basalData.count < 0 {
  997. clearOldTempBasal()
  998. }
  999. }
  1000. if bolus.count > 0 {
  1001. processNSBolus(entries: bolus)
  1002. } else {
  1003. if bolusData.count > 0 {
  1004. clearOldBolus()
  1005. }
  1006. }
  1007. if carbs.count > 0 {
  1008. processNSCarbs(entries: carbs)
  1009. } else {
  1010. if carbData.count > 0 {
  1011. clearOldCarb()
  1012. }
  1013. }
  1014. if bgCheck.count > 0 {
  1015. processNSBGCheck(entries: bgCheck)
  1016. } else {
  1017. if bgCheckData.count > 0 {
  1018. clearOldBGCheck()
  1019. }
  1020. }
  1021. if temporaryOverride.count > 0 {
  1022. processNSOverrides(entries: temporaryOverride)
  1023. } else {
  1024. if overrideGraphData.count > 0 {
  1025. clearOldOverride()
  1026. }
  1027. }
  1028. if suspendPump.count > 0 {
  1029. processSuspendPump(entries: suspendPump)
  1030. } else {
  1031. if suspendGraphData.count > 0 {
  1032. clearOldSuspend()
  1033. }
  1034. }
  1035. if resumePump.count > 0 {
  1036. processResumePump(entries: resumePump)
  1037. } else {
  1038. if resumeGraphData.count > 0 {
  1039. clearOldResume()
  1040. }
  1041. }
  1042. if cgmSensorStart.count > 0 {
  1043. processSensorStart(entries: cgmSensorStart)
  1044. } else {
  1045. if sensorStartGraphData.count > 0 {
  1046. clearOldSensor()
  1047. }
  1048. }
  1049. if note.count > 0 {
  1050. processNotes(entries: note)
  1051. } else {
  1052. if noteGraphData.count > 0 {
  1053. clearOldNotes()
  1054. }
  1055. }
  1056. }
  1057. func clearOldTempBasal()
  1058. {
  1059. basalData.removeAll()
  1060. updateBasalGraph()
  1061. }
  1062. func clearOldBolus()
  1063. {
  1064. bolusData.removeAll()
  1065. updateBolusGraph()
  1066. }
  1067. func clearOldCarb()
  1068. {
  1069. carbData.removeAll()
  1070. updateCarbGraph()
  1071. }
  1072. func clearOldBGCheck()
  1073. {
  1074. bgCheckData.removeAll()
  1075. updateBGCheckGraph()
  1076. }
  1077. func clearOldOverride()
  1078. {
  1079. overrideGraphData.removeAll()
  1080. updateOverrideGraph()
  1081. }
  1082. func clearOldSuspend()
  1083. {
  1084. suspendGraphData.removeAll()
  1085. updateSuspendGraph()
  1086. }
  1087. func clearOldResume()
  1088. {
  1089. resumeGraphData.removeAll()
  1090. updateResumeGraph()
  1091. }
  1092. func clearOldSensor()
  1093. {
  1094. sensorStartGraphData.removeAll()
  1095. updateSensorStart()
  1096. }
  1097. func clearOldNotes()
  1098. {
  1099. noteGraphData.removeAll()
  1100. updateNotes()
  1101. }
  1102. // NS Temp Basal Response Processor
  1103. func processNSBasals(entries: [[String:AnyObject]]) {
  1104. self.clearLastInfoData(index: 2)
  1105. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Basal") }
  1106. // due to temp basal durations, we're going to destroy the array and load everything each cycle for the time being.
  1107. basalData.removeAll()
  1108. var lastEndDot = 0.0
  1109. var tempArray = entries
  1110. tempArray.reverse()
  1111. for i in 0..<tempArray.count {
  1112. let currentEntry = tempArray[i] as [String : AnyObject]?
  1113. var basalDate: String
  1114. if currentEntry?["timestamp"] != nil {
  1115. basalDate = currentEntry?["timestamp"] as! String
  1116. } else if currentEntry?["created_at"] != nil {
  1117. basalDate = currentEntry?["created_at"] as! String
  1118. } else {
  1119. continue
  1120. }
  1121. var strippedZone = String(basalDate.dropLast())
  1122. strippedZone = strippedZone.replacingOccurrences(of: "\\.\\d+", with: "", options: .regularExpression)
  1123. let dateFormatter = DateFormatter()
  1124. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1125. dateFormatter.locale = Locale(identifier: "en_US")
  1126. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1127. guard let dateString = dateFormatter.date(from: strippedZone) else { continue }
  1128. let dateTimeStamp = dateString.timeIntervalSince1970
  1129. guard let basalRate = currentEntry?["absolute"] as? Double else {
  1130. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: Null Basal entry")}
  1131. continue
  1132. }
  1133. let midnightTime = dateTimeUtils.getTimeIntervalMidnightToday()
  1134. // Setting end dots
  1135. var duration = 0.0
  1136. do {
  1137. duration = try currentEntry?["duration"] as! Double
  1138. } catch {
  1139. print("No Duration Found")
  1140. }
  1141. // This adds scheduled basal wherever there is a break between temps. can't check the prior ending on the first item. it is 24 hours old, so it isn't important for display anyway
  1142. if i > 0 {
  1143. let priorEntry = tempArray[i - 1] as [String : AnyObject]?
  1144. var priorBasalDate: String
  1145. if priorEntry?["timestamp"] != nil {
  1146. priorBasalDate = priorEntry?["timestamp"] as! String
  1147. } else if currentEntry?["created_at"] != nil {
  1148. priorBasalDate = priorEntry?["created_at"] as! String
  1149. } else {
  1150. continue
  1151. }
  1152. var priorStrippedZone = String(priorBasalDate.dropLast())
  1153. priorStrippedZone = priorStrippedZone.replacingOccurrences(of: "\\.\\d+", with: "", options: .regularExpression)
  1154. let priorDateFormatter = DateFormatter()
  1155. priorDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1156. priorDateFormatter.locale = Locale(identifier: "en_US")
  1157. priorDateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1158. guard let priorDateString = dateFormatter.date(from: priorStrippedZone) else { continue }
  1159. let priorDateTimeStamp = priorDateString.timeIntervalSince1970
  1160. let priorDuration = priorEntry?["duration"] as? Double ?? 0.0
  1161. // if difference between time stamps is greater than the duration of the last entry, there is a gap. Give a 15 second leeway on the timestamp
  1162. if Double( dateTimeStamp - priorDateTimeStamp ) > Double( (priorDuration * 60) + 15 ) {
  1163. var scheduled = 0.0
  1164. var midGap = false
  1165. var midGapTime: TimeInterval = 0
  1166. var midGapValue: Double = 0
  1167. // cycle through basal profiles.
  1168. // TODO figure out how to deal with profile changes that happen mid-gap
  1169. for b in 0..<self.basalScheduleData.count {
  1170. if (priorDateTimeStamp + (priorDuration * 60)) >= basalScheduleData[b].date {
  1171. scheduled = basalScheduleData[b].basalRate
  1172. // deal with mid-gap scheduled basal change
  1173. // don't do it on the last scheudled basal entry
  1174. if b < self.basalScheduleData.count - 1 {
  1175. if dateTimeStamp > self.basalScheduleData[b + 1].date {
  1176. // midGap = true
  1177. // TODO: finish this to handle mid-gap items without crashing from overlapping entries
  1178. midGapTime = self.basalScheduleData[b + 1].date
  1179. midGapValue = self.basalScheduleData[b + 1].basalRate
  1180. }
  1181. }
  1182. }
  1183. }
  1184. // Make the starting dot at the last ending dot
  1185. let startDot = basalGraphStruct(basalRate: scheduled, date: Double(priorDateTimeStamp + (priorDuration * 60)))
  1186. basalData.append(startDot)
  1187. if midGap {
  1188. // Make the ending dot at the new scheduled basal
  1189. let endDot1 = basalGraphStruct(basalRate: scheduled, date: Double(midGapTime))
  1190. basalData.append(endDot1)
  1191. // Make the starting dot at the scheduled Time
  1192. let startDot2 = basalGraphStruct(basalRate: midGapValue, date: Double(midGapTime))
  1193. basalData.append(startDot2)
  1194. // Make the ending dot at the new basal value
  1195. let endDot2 = basalGraphStruct(basalRate: midGapValue, date: Double(dateTimeStamp))
  1196. basalData.append(endDot2)
  1197. } else {
  1198. // Make the ending dot at the new starting dot
  1199. let endDot = basalGraphStruct(basalRate: scheduled, date: Double(dateTimeStamp))
  1200. basalData.append(endDot)
  1201. }
  1202. }
  1203. }
  1204. // Make the starting dot
  1205. let startDot = basalGraphStruct(basalRate: basalRate, date: Double(dateTimeStamp))
  1206. basalData.append(startDot)
  1207. // Make the ending dot
  1208. // If it's the last one and has no duration, extend it for 30 minutes past the start. Otherwise set ending at duration
  1209. // duration is already set to 0 if there is no duration set on it.
  1210. //if i == tempArray.count - 1 && dateTimeStamp + duration <= dateTimeUtils.getNowTimeIntervalUTC() {
  1211. if i == tempArray.count - 1 && duration == 0.0 {
  1212. lastEndDot = dateTimeStamp + (30 * 60)
  1213. latestBasal = String(format:"%.2f", basalRate)
  1214. } else {
  1215. lastEndDot = dateTimeStamp + (duration * 60)
  1216. latestBasal = String(format:"%.2f", basalRate)
  1217. }
  1218. // Double check for overlaps of incorrectly ended TBRs and sent it to end when the next one starts if it finds a discrepancy
  1219. if i < tempArray.count - 1 {
  1220. let nextEntry = tempArray[i + 1] as [String : AnyObject]?
  1221. var nextBasalDate: String
  1222. if nextEntry?["timestamp"] != nil {
  1223. nextBasalDate = nextEntry?["timestamp"] as! String
  1224. } else if currentEntry?["created_at"] != nil {
  1225. nextBasalDate = nextEntry?["created_at"] as! String
  1226. } else {
  1227. continue
  1228. }
  1229. var nextStrippedZone = String(nextBasalDate.dropLast())
  1230. nextStrippedZone = nextStrippedZone.replacingOccurrences(of: "\\.\\d+", with: "", options: .regularExpression)
  1231. let nextDateFormatter = DateFormatter()
  1232. nextDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1233. nextDateFormatter.locale = Locale(identifier: "en_US")
  1234. nextDateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1235. guard let nextDateString = dateFormatter.date(from: nextStrippedZone) else { continue }
  1236. let nextDateTimeStamp = nextDateString.timeIntervalSince1970
  1237. if nextDateTimeStamp < (dateTimeStamp + (duration * 60)) {
  1238. lastEndDot = nextDateTimeStamp
  1239. }
  1240. }
  1241. let endDot = basalGraphStruct(basalRate: basalRate, date: Double(lastEndDot))
  1242. basalData.append(endDot)
  1243. }
  1244. // If last basal was prior to right now, we need to create one last scheduled entry
  1245. if lastEndDot <= dateTimeUtils.getNowTimeIntervalUTC() {
  1246. var scheduled = 0.0
  1247. // cycle through basal profiles.
  1248. // TODO figure out how to deal with profile changes that happen mid-gap
  1249. for b in 0..<self.basalProfile.count {
  1250. let scheduleTimeYesterday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightYesterday()
  1251. let scheduleTimeToday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightToday()
  1252. // check the prior temp ending to the profile seconds from midnight
  1253. print("yesterday " + String(scheduleTimeYesterday))
  1254. print("today " + String(scheduleTimeToday))
  1255. if lastEndDot >= scheduleTimeToday {
  1256. scheduled = basalProfile[b].value
  1257. }
  1258. }
  1259. latestBasal = String(format:"%.2f", scheduled)
  1260. // Make the starting dot at the last ending dot
  1261. let startDot = basalGraphStruct(basalRate: scheduled, date: Double(lastEndDot))
  1262. basalData.append(startDot)
  1263. // Make the ending dot 10 minutes after now
  1264. let endDot = basalGraphStruct(basalRate: scheduled, date: Double(Date().timeIntervalSince1970 + (60 * 10)))
  1265. basalData.append(endDot)
  1266. }
  1267. tableData[2].value = latestBasal
  1268. infoTable.reloadData()
  1269. if UserDefaultsRepository.graphBasal.value {
  1270. updateBasalGraph()
  1271. }
  1272. infoTable.reloadData()
  1273. }
  1274. // NS Meal Bolus Response Processor
  1275. func processNSBolus(entries: [[String:AnyObject]]) {
  1276. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Bolus") }
  1277. // because it's a small array, we're going to destroy and reload every time.
  1278. bolusData.removeAll()
  1279. var lastFoundIndex = 0
  1280. for i in 0..<entries.count {
  1281. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1282. var bolusDate: String
  1283. if currentEntry?["timestamp"] != nil {
  1284. bolusDate = currentEntry?["timestamp"] as! String
  1285. } else if currentEntry?["created_at"] != nil {
  1286. bolusDate = currentEntry?["created_at"] as! String
  1287. } else {
  1288. continue
  1289. }
  1290. // fix to remove millisecond (after period in timestamp) for FreeAPS users
  1291. var strippedZone = String(bolusDate.dropLast())
  1292. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1293. let dateFormatter = DateFormatter()
  1294. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1295. dateFormatter.locale = Locale(identifier: "en_US")
  1296. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1297. guard let dateString = dateFormatter.date(from: strippedZone) else { continue }
  1298. let dateTimeStamp = dateString.timeIntervalSince1970
  1299. guard let bolus = currentEntry?["insulin"] as? Double else { continue }
  1300. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1301. lastFoundIndex = sgv.foundIndex
  1302. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1303. // Make the dot
  1304. let dot = bolusGraphStruct(value: bolus, date: Double(dateTimeStamp), sgv: Int(sgv.sgv + 20))
  1305. bolusData.append(dot)
  1306. }
  1307. }
  1308. if UserDefaultsRepository.graphBolus.value {
  1309. updateBolusGraph()
  1310. }
  1311. }
  1312. // NS Carb Bolus Response Processor
  1313. func processNSCarbs(entries: [[String:AnyObject]]) {
  1314. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Carbs") }
  1315. // because it's a small array, we're going to destroy and reload every time.
  1316. carbData.removeAll()
  1317. var lastFoundIndex = 0
  1318. var lastFoundBolus = 0
  1319. for i in 0..<entries.count {
  1320. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1321. var carbDate: String
  1322. if currentEntry?["timestamp"] != nil {
  1323. carbDate = currentEntry?["timestamp"] as! String
  1324. } else if currentEntry?["created_at"] != nil {
  1325. carbDate = currentEntry?["created_at"] as! String
  1326. } else {
  1327. continue
  1328. }
  1329. let absorptionTime = currentEntry?["absorptionTime"] as? Int ?? 0
  1330. // Fix for FreeAPS milliseconds in timestamp
  1331. var strippedZone = String(carbDate.dropLast())
  1332. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1333. let dateFormatter = DateFormatter()
  1334. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1335. dateFormatter.locale = Locale(identifier: "en_US")
  1336. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1337. guard let dateString = dateFormatter.date(from: strippedZone) else { continue }
  1338. var dateTimeStamp = dateString.timeIntervalSince1970
  1339. guard let carbs = currentEntry?["carbs"] as? Double else {
  1340. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: Null Carb entry")}
  1341. continue
  1342. }
  1343. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1344. lastFoundIndex = sgv.foundIndex
  1345. var offset = -50
  1346. if sgv.sgv < Double(topBG - 100) {
  1347. let bolusTime = findNearestBolusbyTime(timeWithin: 300, needle: dateTimeStamp, haystack: bolusData, startingIndex: lastFoundBolus)
  1348. lastFoundBolus = bolusTime.foundIndex
  1349. if bolusTime.offset {
  1350. offset = 70
  1351. } else {
  1352. offset = 20
  1353. }
  1354. }
  1355. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1356. // Make the dot
  1357. let dot = carbGraphStruct(value: Double(carbs), date: Double(dateTimeStamp), sgv: Int(sgv.sgv + Double(offset)), absorptionTime: absorptionTime)
  1358. carbData.append(dot)
  1359. }
  1360. }
  1361. if UserDefaultsRepository.graphCarbs.value {
  1362. updateCarbGraph()
  1363. }
  1364. }
  1365. // NS Suspend Pump Response Processor
  1366. func processSuspendPump(entries: [[String:AnyObject]]) {
  1367. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Suspend Pump") }
  1368. // because it's a small array, we're going to destroy and reload every time.
  1369. suspendGraphData.removeAll()
  1370. var lastFoundIndex = 0
  1371. for i in 0..<entries.count {
  1372. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1373. var date: String
  1374. if currentEntry?["timestamp"] != nil {
  1375. date = currentEntry?["timestamp"] as! String
  1376. } else if currentEntry?["created_at"] != nil {
  1377. date = currentEntry?["created_at"] as! String
  1378. } else {
  1379. return
  1380. }
  1381. // Fix for FreeAPS milliseconds in timestamp
  1382. var strippedZone = String(date.dropLast())
  1383. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1384. let dateFormatter = DateFormatter()
  1385. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1386. dateFormatter.locale = Locale(identifier: "en_US")
  1387. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1388. let dateString = dateFormatter.date(from: strippedZone)
  1389. let dateTimeStamp = dateString!.timeIntervalSince1970
  1390. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1391. lastFoundIndex = sgv.foundIndex
  1392. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1393. // Make the dot
  1394. let dot = DataStructs.timestampOnlyStruct(date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  1395. suspendGraphData.append(dot)
  1396. }
  1397. }
  1398. if UserDefaultsRepository.graphOtherTreatments.value {
  1399. updateSuspendGraph()
  1400. }
  1401. }
  1402. // NS Resume Pump Response Processor
  1403. func processResumePump(entries: [[String:AnyObject]]) {
  1404. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Resume Pump") }
  1405. // because it's a small array, we're going to destroy and reload every time.
  1406. resumeGraphData.removeAll()
  1407. var lastFoundIndex = 0
  1408. for i in 0..<entries.count {
  1409. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1410. var date: String
  1411. if currentEntry?["timestamp"] != nil {
  1412. date = currentEntry?["timestamp"] as! String
  1413. } else if currentEntry?["created_at"] != nil {
  1414. date = currentEntry?["created_at"] as! String
  1415. } else {
  1416. return
  1417. }
  1418. // Fix for FreeAPS milliseconds in timestamp
  1419. var strippedZone = String(date.dropLast())
  1420. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1421. let dateFormatter = DateFormatter()
  1422. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1423. dateFormatter.locale = Locale(identifier: "en_US")
  1424. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1425. let dateString = dateFormatter.date(from: strippedZone)
  1426. let dateTimeStamp = dateString!.timeIntervalSince1970
  1427. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1428. lastFoundIndex = sgv.foundIndex
  1429. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1430. // Make the dot
  1431. let dot = DataStructs.timestampOnlyStruct(date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  1432. resumeGraphData.append(dot)
  1433. }
  1434. }
  1435. if UserDefaultsRepository.graphOtherTreatments.value {
  1436. updateResumeGraph()
  1437. }
  1438. }
  1439. // NS Sensor Start Response Processor
  1440. func processSensorStart(entries: [[String:AnyObject]]) {
  1441. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Sensor Start") }
  1442. // because it's a small array, we're going to destroy and reload every time.
  1443. sensorStartGraphData.removeAll()
  1444. var lastFoundIndex = 0
  1445. for i in 0..<entries.count {
  1446. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1447. var date: String
  1448. if currentEntry?["timestamp"] != nil {
  1449. date = currentEntry?["timestamp"] as! String
  1450. } else if currentEntry?["created_at"] != nil {
  1451. date = currentEntry?["created_at"] as! String
  1452. } else {
  1453. return
  1454. }
  1455. // Fix for FreeAPS milliseconds in timestamp
  1456. var strippedZone = String(date.dropLast())
  1457. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1458. let dateFormatter = DateFormatter()
  1459. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1460. dateFormatter.locale = Locale(identifier: "en_US")
  1461. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1462. let dateString = dateFormatter.date(from: strippedZone)
  1463. let dateTimeStamp = dateString!.timeIntervalSince1970
  1464. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1465. lastFoundIndex = sgv.foundIndex
  1466. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1467. // Make the dot
  1468. let dot = DataStructs.timestampOnlyStruct(date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  1469. sensorStartGraphData.append(dot)
  1470. }
  1471. }
  1472. if UserDefaultsRepository.graphOtherTreatments.value {
  1473. updateSensorStart()
  1474. }
  1475. }
  1476. // NS Note Response Processor
  1477. func processNotes(entries: [[String:AnyObject]]) {
  1478. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Notes") }
  1479. // because it's a small array, we're going to destroy and reload every time.
  1480. noteGraphData.removeAll()
  1481. var lastFoundIndex = 0
  1482. for i in 0..<entries.count {
  1483. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1484. var date: String
  1485. if currentEntry?["timestamp"] != nil {
  1486. date = currentEntry?["timestamp"] as! String
  1487. } else if currentEntry?["created_at"] != nil {
  1488. date = currentEntry?["created_at"] as! String
  1489. } else {
  1490. return
  1491. }
  1492. // Fix for FreeAPS milliseconds in timestamp
  1493. var strippedZone = String(date.dropLast())
  1494. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1495. let dateFormatter = DateFormatter()
  1496. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1497. dateFormatter.locale = Locale(identifier: "en_US")
  1498. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1499. let dateString = dateFormatter.date(from: strippedZone)
  1500. let dateTimeStamp = dateString!.timeIntervalSince1970
  1501. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1502. lastFoundIndex = sgv.foundIndex
  1503. guard let thisNote = currentEntry?["notes"] as? String else { continue }
  1504. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1505. // Make the dot
  1506. let dot = DataStructs.noteStruct(date: Double(dateTimeStamp), sgv: Int(sgv.sgv), note: thisNote)
  1507. noteGraphData.append(dot)
  1508. }
  1509. }
  1510. if UserDefaultsRepository.graphOtherTreatments.value {
  1511. updateNotes()
  1512. }
  1513. }
  1514. // NS BG Check Response Processor
  1515. func processNSBGCheck(entries: [[String:AnyObject]]) {
  1516. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: BG Check") }
  1517. // because it's a small array, we're going to destroy and reload every time.
  1518. bgCheckData.removeAll()
  1519. for i in 0..<entries.count {
  1520. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1521. var date: String
  1522. if currentEntry?["timestamp"] != nil {
  1523. date = currentEntry?["timestamp"] as! String
  1524. } else if currentEntry?["created_at"] != nil {
  1525. date = currentEntry?["created_at"] as! String
  1526. } else {
  1527. return
  1528. }
  1529. // Fix for FreeAPS milliseconds in timestamp
  1530. var strippedZone = String(date.dropLast())
  1531. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1532. let dateFormatter = DateFormatter()
  1533. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1534. dateFormatter.locale = Locale(identifier: "en_US")
  1535. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1536. let dateString = dateFormatter.date(from: strippedZone)
  1537. let dateTimeStamp = dateString!.timeIntervalSince1970
  1538. guard let sgv = currentEntry?["glucose"] as? Int else {
  1539. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: Non-Int Glucose entry")}
  1540. continue
  1541. }
  1542. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1543. // Make the dot
  1544. //let dot = ShareGlucoseData(value: Double(carbs), date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  1545. let dot = ShareGlucoseData(sgv: sgv, date: Double(dateTimeStamp), direction: "")
  1546. bgCheckData.append(dot)
  1547. }
  1548. }
  1549. if UserDefaultsRepository.graphOtherTreatments.value {
  1550. updateBGCheckGraph()
  1551. }
  1552. }
  1553. // NS Override Response Processor
  1554. func processNSOverrides(entries: [[String:AnyObject]]) {
  1555. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Overrides") }
  1556. // because it's a small array, we're going to destroy and reload every time.
  1557. overrideGraphData.removeAll()
  1558. for i in 0..<entries.count {
  1559. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1560. var date: String
  1561. if currentEntry?["timestamp"] != nil {
  1562. date = currentEntry?["timestamp"] as! String
  1563. } else if currentEntry?["created_at"] != nil {
  1564. date = currentEntry?["created_at"] as! String
  1565. } else {
  1566. return
  1567. }
  1568. // Fix for FreeAPS milliseconds in timestamp
  1569. var strippedZone = String(date.dropLast())
  1570. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1571. let dateFormatter = DateFormatter()
  1572. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1573. dateFormatter.locale = Locale(identifier: "en_US")
  1574. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1575. let dateString = dateFormatter.date(from: strippedZone)
  1576. var dateTimeStamp = dateString!.timeIntervalSince1970
  1577. let graphHours = 24 * UserDefaultsRepository.downloadDays.value
  1578. if dateTimeStamp < dateTimeUtils.getTimeIntervalNHoursAgo(N: graphHours) {
  1579. dateTimeStamp = dateTimeUtils.getTimeIntervalNHoursAgo(N: graphHours)
  1580. }
  1581. var multiplier: Double = 1.0
  1582. if currentEntry?["insulinNeedsScaleFactor"] != nil {
  1583. multiplier = currentEntry?["insulinNeedsScaleFactor"] as! Double
  1584. }
  1585. var duration: Double = 5.0
  1586. if let durationType = currentEntry?["durationType"] as? String {
  1587. duration = dateTimeUtils.getNowTimeIntervalUTC() - dateTimeStamp + (60 * 60)
  1588. } else {
  1589. duration = (currentEntry?["duration"] as? Double)!
  1590. duration = duration * 60
  1591. }
  1592. // Skip overrides that aren't 5 minutes long. This prevents overlapping that causes bars to not display.
  1593. if duration < 300 { continue }
  1594. guard let enteredBy = currentEntry?["enteredBy"] as? String else { continue }
  1595. guard let reason = currentEntry?["reason"] as? String else { continue }
  1596. var range: [Int] = []
  1597. if let ranges = currentEntry?["correctionRange"] as? [Int] {
  1598. if ranges.count == 2 {
  1599. guard let low = ranges[0] as? Int else { continue }
  1600. guard let high = ranges[1] as? Int else { continue }
  1601. range.append(low)
  1602. range.append(high)
  1603. }
  1604. }
  1605. let endDate = dateTimeStamp + (duration)
  1606. let dot = DataStructs.overrideStruct(insulNeedsScaleFactor: multiplier, date: dateTimeStamp, endDate: endDate, duration: duration, correctionRange: range, enteredBy: enteredBy, reason: reason, sgv: -20)
  1607. overrideGraphData.append(dot)
  1608. }
  1609. if UserDefaultsRepository.graphOtherTreatments.value {
  1610. updateOverrideGraph()
  1611. }
  1612. }
  1613. }