NightScout.swift 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136
  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. //
  12. // //NS BG Struct
  13. // struct sgvData: Codable {
  14. // var sgv: Int
  15. // var date: TimeInterval
  16. // var direction: String?
  17. // }
  18. //NS Cage Struct
  19. struct cageData: Codable {
  20. var created_at: String
  21. }
  22. //NS Basal Profile Struct
  23. struct basalProfileStruct: Codable {
  24. var value: Double
  25. var time: String
  26. var timeAsSeconds: Double
  27. }
  28. //NS Basal Data Struct
  29. struct basalGraphStruct: Codable {
  30. var basalRate: Double
  31. var date: TimeInterval
  32. }
  33. //NS Bolus Data Struct
  34. struct bolusCarbGraphStruct: Codable {
  35. var value: Double
  36. var date: TimeInterval
  37. var sgv: Int
  38. }
  39. // Main loader for all data
  40. func nightscoutLoader(forceLoad: Bool = false) {
  41. var needsLoaded: Bool = false
  42. var staleData: Bool = false
  43. var onlyPullLastRecord = false
  44. // If we have existing data and it's within 5 minutes, we aren't going to do a BG network call
  45. // if we have stale BG data 10 min or older, we're only going to attempt to pull BG and Loop status
  46. // to not have a full refresh every 15 seconds. The remaining data will start pulling again on the
  47. // next BG reading that comes in.
  48. if bgData.count > 0 {
  49. let now = NSDate().timeIntervalSince1970
  50. let lastReadingTime = bgData[bgData.count - 1].date
  51. let secondsAgo = now - lastReadingTime
  52. if secondsAgo >= 5*60 {
  53. needsLoaded = true
  54. if secondsAgo < 10*60 {
  55. onlyPullLastRecord = true
  56. } else {
  57. staleData = true
  58. }
  59. }
  60. } else {
  61. needsLoaded = true
  62. }
  63. if forceLoad { needsLoaded = true}
  64. // Only update if we don't have a current reading or forced to load
  65. if needsLoaded {
  66. self.clearLastInfoData()
  67. webLoadNSDeviceStatus()
  68. webLoadNSBGData(onlyPullLastRecord: onlyPullLastRecord)
  69. if !staleData {
  70. webLoadNSProfile()
  71. if UserDefaultsRepository.downloadBasal.value {
  72. WebLoadNSTempBasals()
  73. }
  74. if UserDefaultsRepository.downloadBolus.value {
  75. webLoadNSBoluses()
  76. }
  77. if UserDefaultsRepository.downloadCarbs.value {
  78. webLoadNSCarbs()
  79. }
  80. webLoadNSCage()
  81. webLoadNSSage()
  82. }
  83. // Give the alarms and calendar 15 seconds delay to allow time for data to compile
  84. // if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Start view timer") }
  85. self.startViewTimer(time: viewTimeInterval)
  86. } else {
  87. // Things to do if we already have data and don't need a network call
  88. // Leaving all downloads off for right now.
  89. /*
  90. webLoadNSDeviceStatus()
  91. if UserDefaultsRepository.downloadBolus.value {
  92. webLoadNSBoluses()
  93. }
  94. if UserDefaultsRepository.downloadCarbs.value {
  95. webLoadNSCarbs()
  96. }*/
  97. if bgData.count > 0 {
  98. self.checkAlarms(bgs: bgData)
  99. }
  100. }
  101. }
  102. // NS BG Data Web call
  103. func webLoadNSBGData(onlyPullLastRecord: Bool = false) {
  104. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: BG") }
  105. // Set the count= in the url either to pull 24 hours or only the last record
  106. var points = "1"
  107. if !onlyPullLastRecord {
  108. points = String(self.graphHours * 12 + 1)
  109. }
  110. // URL processor
  111. var urlBGDataPath: String = UserDefaultsRepository.url.value + "/api/v1/entries/sgv.json?"
  112. if token == "" {
  113. urlBGDataPath = urlBGDataPath + "count=" + points
  114. } else {
  115. urlBGDataPath = urlBGDataPath + "token=" + token + "&count=" + points
  116. }
  117. guard let urlBGData = URL(string: urlBGDataPath) else {
  118. return
  119. }
  120. var request = URLRequest(url: urlBGData)
  121. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  122. // Downloader
  123. let getBGTask = URLSession.shared.dataTask(with: request) { data, response, error in
  124. guard error == nil else {
  125. return
  126. }
  127. guard let data = data else {
  128. return
  129. }
  130. let decoder = JSONDecoder()
  131. let entriesResponse = try? decoder.decode([DataStructs.sgvData].self, from: data)
  132. if let entriesResponse = entriesResponse {
  133. DispatchQueue.main.async {
  134. // trigger the processor for the data after downloading.
  135. self.ProcessNSBGData(data: entriesResponse, onlyPullLastRecord: onlyPullLastRecord)
  136. }
  137. } else {
  138. return
  139. }
  140. }
  141. getBGTask.resume()
  142. }
  143. // NS BG Data Response processor
  144. func ProcessNSBGData(data: [DataStructs.sgvData], onlyPullLastRecord: Bool){
  145. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: BG") }
  146. var pullDate = data[data.count - 1].date / 1000
  147. pullDate.round(FloatingPointRoundingRule.toNearestOrEven)
  148. // 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
  149. if !onlyPullLastRecord {
  150. bgData.removeAll()
  151. } else if bgData[bgData.count - 1].date != pullDate {
  152. bgData.removeFirst()
  153. if data.count > 0 && UserDefaultsRepository.speakBG.value {
  154. speakBG(sgv: data[data.count - 1].sgv)
  155. }
  156. } else {
  157. if data.count > 0 {
  158. self.updateBadge(val: data[data.count - 1].sgv)
  159. }
  160. // self.viewUpdateNSBG()
  161. return
  162. }
  163. // loop through the data so we can reverse the order to oldest first for the graph and convert the NS timestamp to seconds instead of milliseconds. Makes date comparisons easier for everything else.
  164. for i in 0..<data.count{
  165. var dateString = data[data.count - 1 - i].date / 1000
  166. dateString.round(FloatingPointRoundingRule.toNearestOrEven)
  167. if dateString >= dateTimeUtils.getTimeInterval24HoursAgo() {
  168. let reading = DataStructs.sgvData(sgv: data[data.count - 1 - i].sgv, date: dateString, direction: data[data.count - 1 - i].direction)
  169. bgData.append(reading)
  170. }
  171. }
  172. viewUpdateNSBG()
  173. }
  174. // NS BG Data Front end updater
  175. func viewUpdateNSBG () {
  176. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Display: BG") }
  177. guard let snoozer = self.tabBarController!.viewControllers?[2] as? SnoozeViewController else { return }
  178. let entries = bgData
  179. if entries.count > 0 {
  180. let latestEntryi = entries.count - 1
  181. let latestBG = entries[latestEntryi].sgv
  182. let priorBG = entries[latestEntryi - 1].sgv
  183. let deltaBG = latestBG - priorBG as Int
  184. let lastBGTime = entries[latestEntryi].date
  185. let deltaTime = (TimeInterval(Date().timeIntervalSince1970)-lastBGTime) / 60
  186. var userUnit = " mg/dL"
  187. if mmol {
  188. userUnit = " mmol/L"
  189. }
  190. BGText.text = bgUnits.toDisplayUnits(String(latestBG))
  191. snoozer.BGLabel.text = bgUnits.toDisplayUnits(String(latestBG))
  192. setBGTextColor()
  193. if let directionBG = entries[latestEntryi].direction {
  194. DirectionText.text = bgDirectionGraphic(directionBG)
  195. snoozer.DirectionLabel.text = bgDirectionGraphic(directionBG)
  196. latestDirectionString = bgDirectionGraphic(directionBG)
  197. }
  198. else
  199. {
  200. DirectionText.text = ""
  201. snoozer.DirectionLabel.text = ""
  202. latestDirectionString = ""
  203. }
  204. if deltaBG < 0 {
  205. self.DeltaText.text = bgUnits.toDisplayUnits(String(deltaBG))
  206. snoozer.DeltaLabel.text = bgUnits.toDisplayUnits(String(deltaBG))
  207. latestDeltaString = String(deltaBG)
  208. }
  209. else
  210. {
  211. self.DeltaText.text = "+" + bgUnits.toDisplayUnits(String(deltaBG))
  212. snoozer.DeltaLabel.text = "+" + bgUnits.toDisplayUnits(String(deltaBG))
  213. latestDeltaString = "+" + String(deltaBG)
  214. }
  215. self.updateBadge(val: latestBG)
  216. }
  217. else
  218. {
  219. return
  220. }
  221. updateBGGraph()
  222. updateMinAgo()
  223. updateStats()
  224. }
  225. // NS Device Status Web Call
  226. func webLoadNSDeviceStatus() {
  227. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: device status") }
  228. let urlUser = UserDefaultsRepository.url.value
  229. // NS Api is not working to find by greater than date
  230. var urlStringDeviceStatus = urlUser + "/api/v1/devicestatus.json?count=288"
  231. if token != "" {
  232. urlStringDeviceStatus = urlUser + "/api/v1/devicestatus.json?count=288&token=" + token
  233. }
  234. let escapedAddress = urlStringDeviceStatus.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
  235. guard let urlDeviceStatus = URL(string: escapedAddress!) else {
  236. return
  237. }
  238. var requestDeviceStatus = URLRequest(url: urlDeviceStatus)
  239. requestDeviceStatus.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  240. let deviceStatusTask = URLSession.shared.dataTask(with: requestDeviceStatus) { data, response, error in
  241. guard error == nil else {
  242. return
  243. }
  244. guard let data = data else {
  245. return
  246. }
  247. let json = try? (JSONSerialization.jsonObject(with: data) as? [[String:AnyObject]])
  248. if let json = json {
  249. DispatchQueue.main.async {
  250. self.updateDeviceStatusDisplay(jsonDeviceStatus: json)
  251. }
  252. } else {
  253. return
  254. } }
  255. deviceStatusTask.resume()
  256. }
  257. // NS Device Status Response Processor
  258. func updateDeviceStatusDisplay(jsonDeviceStatus: [[String:AnyObject]]) {
  259. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: device status") }
  260. if jsonDeviceStatus.count == 0 {
  261. return
  262. }
  263. //Process the current data first
  264. let lastDeviceStatus = jsonDeviceStatus[0] as [String : AnyObject]?
  265. //pump and uploader
  266. let formatter = ISO8601DateFormatter()
  267. formatter.formatOptions = [.withFullDate,
  268. .withTime,
  269. .withDashSeparatorInDate,
  270. .withColonSeparatorInTime]
  271. if let lastPumpRecord = lastDeviceStatus?["pump"] as! [String : AnyObject]? {
  272. if let lastPumpTime = formatter.date(from: (lastPumpRecord["clock"] as! String))?.timeIntervalSince1970 {
  273. if let reservoirData = lastPumpRecord["reservoir"] as? Double {
  274. tableData[5].value = String(format:"%.0f", reservoirData) + "U"
  275. } else {
  276. tableData[5].value = "50+U"
  277. }
  278. if let uploader = lastDeviceStatus?["uploader"] as? [String:AnyObject] {
  279. let upbat = uploader["battery"] as! Double
  280. tableData[4].value = String(format:"%.0f", upbat) + "%"
  281. }
  282. }
  283. }
  284. // Loop
  285. if let lastLoopRecord = lastDeviceStatus?["loop"] as! [String : AnyObject]? {
  286. if let lastLoopTime = formatter.date(from: (lastLoopRecord["timestamp"] as! String))?.timeIntervalSince1970 {
  287. UserDefaultsRepository.alertLastLoopTime.value = lastLoopTime
  288. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "lastLoopTime: " + String(lastLoopTime)) }
  289. if let failure = lastLoopRecord["failureReason"] {
  290. LoopStatusLabel.text = "X"
  291. latestLoopStatusString = "X"
  292. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Loop Failure: X") }
  293. } else {
  294. var wasEnacted = false
  295. if let enacted = lastLoopRecord["enacted"] as? [String:AnyObject] {
  296. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Loop: Was Enacted") }
  297. wasEnacted = true
  298. if let lastTempBasal = enacted["rate"] as? Double {
  299. // tableData[2].value = String(format:"%.1f", lastTempBasal)
  300. }
  301. }
  302. if let iobdata = lastLoopRecord["iob"] as? [String:AnyObject] {
  303. tableData[0].value = String(format:"%.2f", (iobdata["iob"] as! Double))
  304. latestIOB = String(format:"%.2f", (iobdata["iob"] as! Double))
  305. }
  306. if let cobdata = lastLoopRecord["cob"] as? [String:AnyObject] {
  307. tableData[1].value = String(format:"%.0f", cobdata["cob"] as! Double)
  308. latestCOB = String(format:"%.0f", cobdata["cob"] as! Double)
  309. }
  310. if let predictdata = lastLoopRecord["predicted"] as? [String:AnyObject] {
  311. let prediction = predictdata["values"] as! [Int]
  312. PredictionLabel.text = bgUnits.toDisplayUnits(String(Int(prediction.last!)))
  313. PredictionLabel.textColor = UIColor.systemPurple
  314. if UserDefaultsRepository.downloadPrediction.value && latestLoopTime < lastLoopTime {
  315. predictionData.removeAll()
  316. var predictionTime = lastLoopTime + 300
  317. let toLoad = Int(UserDefaultsRepository.predictionToLoad.value * 12)
  318. var i = 1
  319. while i <= toLoad {
  320. let prediction = DataStructs.sgvData(sgv: prediction[i], date: predictionTime, direction: "flat")
  321. predictionData.append(prediction)
  322. predictionTime += 300
  323. i += 1
  324. }
  325. }
  326. if UserDefaultsRepository.graphPrediction.value {
  327. updatePredictionGraph()
  328. }
  329. }
  330. if let loopStatus = lastLoopRecord["recommendedTempBasal"] as? [String:AnyObject] {
  331. if let tempBasalTime = formatter.date(from: (loopStatus["timestamp"] as! String))?.timeIntervalSince1970 {
  332. var lastBGTime = lastLoopTime
  333. if bgData.count > 0 {
  334. lastBGTime = bgData[bgData.count - 1].date
  335. }
  336. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "tempBasalTime: " + String(tempBasalTime)) }
  337. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "lastBGTime: " + String(lastBGTime)) }
  338. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "wasEnacted: " + String(wasEnacted)) }
  339. if tempBasalTime > lastBGTime && !wasEnacted {
  340. LoopStatusLabel.text = "⏀"
  341. latestLoopStatusString = "⏀"
  342. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Open Loop: recommended temp. temp time > bg time, was not enacted") }
  343. } else {
  344. LoopStatusLabel.text = "↻"
  345. latestLoopStatusString = "↻"
  346. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Looping: recommended temp, but temp time is < bg time and/or was enacted") }
  347. }
  348. }
  349. } else {
  350. LoopStatusLabel.text = "↻"
  351. latestLoopStatusString = "↻"
  352. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Looping: no recommended temp") }
  353. }
  354. }
  355. if ((TimeInterval(Date().timeIntervalSince1970) - lastLoopTime) / 60) > 15 {
  356. LoopStatusLabel.text = "⚠"
  357. latestLoopStatusString = "⚠"
  358. }
  359. latestLoopTime = lastLoopTime
  360. } // end lastLoopTime
  361. } // end lastLoop Record
  362. var oText = "" as String
  363. currentOverride = 1.0
  364. if let lastOverride = lastDeviceStatus?["override"] as! [String : AnyObject]? {
  365. if let lastOverrideTime = formatter.date(from: (lastOverride["timestamp"] as! String))?.timeIntervalSince1970 {
  366. }
  367. if lastOverride["active"] as! Bool {
  368. let lastCorrection = lastOverride["currentCorrectionRange"] as! [String: AnyObject]
  369. if let multiplier = lastOverride["multiplier"] as? Double {
  370. currentOverride = multiplier
  371. oText += String(format:"%.1f", multiplier*100)
  372. }
  373. else
  374. {
  375. oText += String(format:"%.1f", 100)
  376. }
  377. oText += "% ("
  378. let minValue = lastCorrection["minValue"] as! Double
  379. let maxValue = lastCorrection["maxValue"] as! Double
  380. oText += bgUnits.toDisplayUnits(String(minValue)) + "-" + bgUnits.toDisplayUnits(String(maxValue)) + ")"
  381. tableData[3].value = oText
  382. }
  383. }
  384. infoTable.reloadData()
  385. // Process Override Data
  386. overrideData.removeAll()
  387. for i in 0..<jsonDeviceStatus.count {
  388. let deviceStatus = jsonDeviceStatus[i] as [String : AnyObject]?
  389. if let override = deviceStatus?["override"] as! [String : AnyObject]? {
  390. let formatter = ISO8601DateFormatter()
  391. formatter.formatOptions = [.withFullDate,
  392. .withTime,
  393. .withDashSeparatorInDate,
  394. .withColonSeparatorInTime]
  395. if let timestamp = formatter.date(from: (override["timestamp"] as! String))?.timeIntervalSince1970 {
  396. if timestamp > dateTimeUtils.getTimeInterval24HoursAgo() {
  397. if let isActive = override["active"] as? Bool {
  398. if isActive {
  399. if let multiplier = override["multiplier"] as? Double {
  400. let override = DataStructs.overrideGraphStruct(value: multiplier, date: timestamp, sgv: Int(UserDefaultsRepository.overrideDisplayLocation.value))
  401. overrideData.append(override)
  402. }
  403. } else {
  404. let multiplier = 1.0 as Double
  405. let override = DataStructs.overrideGraphStruct(value: multiplier, date: timestamp, sgv: Int(UserDefaultsRepository.overrideDisplayLocation.value))
  406. overrideData.append(override)
  407. }
  408. }
  409. }
  410. }
  411. }
  412. }
  413. overrideData.reverse()
  414. updateOverrideGraph()
  415. }
  416. // NS Cage Web Call
  417. func webLoadNSCage() {
  418. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: CAGE") }
  419. let urlUser = UserDefaultsRepository.url.value
  420. var urlString = urlUser + "/api/v1/treatments.json?find[eventType]=Site%20Change&count=1"
  421. if token != "" {
  422. urlString = urlUser + "/api/v1/treatments.json?token=" + token + "&find[eventType]=Site%20Change&count=1"
  423. }
  424. guard let urlData = URL(string: urlString) else {
  425. return
  426. }
  427. var request = URLRequest(url: urlData)
  428. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  429. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  430. guard error == nil else {
  431. return
  432. }
  433. guard let data = data else {
  434. return
  435. }
  436. let decoder = JSONDecoder()
  437. let entriesResponse = try? decoder.decode([cageData].self, from: data)
  438. if let entriesResponse = entriesResponse {
  439. DispatchQueue.main.async {
  440. self.updateCage(data: entriesResponse)
  441. }
  442. } else {
  443. return
  444. }
  445. }
  446. task.resume()
  447. }
  448. // NS Cage Response Processor
  449. func updateCage(data: [cageData]) {
  450. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: CAGE") }
  451. if data.count == 0 {
  452. return
  453. }
  454. let lastCageString = data[0].created_at
  455. let formatter = ISO8601DateFormatter()
  456. formatter.formatOptions = [.withFullDate,
  457. .withTime,
  458. .withDashSeparatorInDate,
  459. .withColonSeparatorInTime]
  460. UserDefaultsRepository.alertCageInsertTime.value = formatter.date(from: (lastCageString))?.timeIntervalSince1970 as! TimeInterval
  461. if let cageTime = formatter.date(from: (lastCageString))?.timeIntervalSince1970 {
  462. let now = NSDate().timeIntervalSince1970
  463. let secondsAgo = now - cageTime
  464. //let days = 24 * 60 * 60
  465. let formatter = DateComponentsFormatter()
  466. formatter.unitsStyle = .positional // Use the appropriate positioning for the current locale
  467. formatter.allowedUnits = [ .day, .hour ] // Units to display in the formatted string
  468. formatter.zeroFormattingBehavior = [ .pad ] // Pad with zeroes where appropriate for the locale
  469. let formattedDuration = formatter.string(from: secondsAgo)
  470. tableData[7].value = formattedDuration ?? ""
  471. }
  472. infoTable.reloadData()
  473. }
  474. // NS Sage Web Call
  475. func webLoadNSSage() {
  476. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: SAGE") }
  477. let lastDateString = dateTimeUtils.nowMinus10DaysTimeInterval()
  478. let urlUser = UserDefaultsRepository.url.value
  479. var urlString = urlUser + "/api/v1/treatments.json?find[eventType]=Sensor%20Start&find[created_at][$gte]=" + lastDateString + "&count=1"
  480. if token != "" {
  481. urlString = urlUser + "/api/v1/treatments.json?token=" + token + "&find[eventType]=Sensor%20Start&find[created_at][$gte]=" + lastDateString + "&count=1"
  482. }
  483. guard let urlData = URL(string: urlString) else {
  484. return
  485. }
  486. var request = URLRequest(url: urlData)
  487. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  488. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  489. guard error == nil else {
  490. return
  491. }
  492. guard let data = data else {
  493. return
  494. }
  495. let decoder = JSONDecoder()
  496. let entriesResponse = try? decoder.decode([cageData].self, from: data)
  497. if let entriesResponse = entriesResponse {
  498. DispatchQueue.main.async {
  499. self.updateSage(data: entriesResponse)
  500. }
  501. } else {
  502. return
  503. }
  504. }
  505. task.resume()
  506. }
  507. // NS Sage Response Processor
  508. func updateSage(data: [cageData]) {
  509. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process/Display: SAGE") }
  510. if data.count == 0 {
  511. return
  512. }
  513. var lastSageString = data[0].created_at
  514. let formatter = ISO8601DateFormatter()
  515. formatter.formatOptions = [.withFullDate,
  516. .withTime,
  517. .withDashSeparatorInDate,
  518. .withColonSeparatorInTime]
  519. UserDefaultsRepository.alertSageInsertTime.value = formatter.date(from: (lastSageString))?.timeIntervalSince1970 as! TimeInterval
  520. if let sageTime = formatter.date(from: (lastSageString as! String))?.timeIntervalSince1970 {
  521. let now = NSDate().timeIntervalSince1970
  522. let secondsAgo = now - sageTime
  523. let days = 24 * 60 * 60
  524. let formatter = DateComponentsFormatter()
  525. formatter.unitsStyle = .positional // Use the appropriate positioning for the current locale
  526. formatter.allowedUnits = [ .day, .hour] // Units to display in the formatted string
  527. formatter.zeroFormattingBehavior = [ .pad ] // Pad with zeroes where appropriate for the locale
  528. let formattedDuration = formatter.string(from: secondsAgo)
  529. tableData[6].value = formattedDuration ?? ""
  530. }
  531. infoTable.reloadData()
  532. }
  533. // NS Profile Web Call
  534. func webLoadNSProfile() {
  535. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: profile") }
  536. let urlUser = UserDefaultsRepository.url.value
  537. var urlString = urlUser + "/api/v1/profile/current.json"
  538. if token != "" {
  539. urlString = urlUser + "/api/v1/profile/current.json?token=" + token
  540. }
  541. let escapedAddress = urlString.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
  542. guard let url = URL(string: escapedAddress!) else {
  543. return
  544. }
  545. var request = URLRequest(url: url)
  546. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  547. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  548. guard error == nil else {
  549. return
  550. }
  551. guard let data = data else {
  552. return
  553. }
  554. let json = try? JSONSerialization.jsonObject(with: data) as! Dictionary<String, Any>
  555. if let json = json {
  556. DispatchQueue.main.async {
  557. self.updateProfile(jsonDeviceStatus: json)
  558. }
  559. } else {
  560. return
  561. }
  562. }
  563. task.resume()
  564. }
  565. // NS Profile Response Processor
  566. func updateProfile(jsonDeviceStatus: Dictionary<String, Any>) {
  567. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: profile") }
  568. if jsonDeviceStatus.count == 0 {
  569. return
  570. }
  571. if jsonDeviceStatus[keyPath: "message"] != nil { return }
  572. let basal = try jsonDeviceStatus[keyPath: "store.Default.basal"] as! NSArray
  573. basalProfile.removeAll()
  574. for i in 0..<basal.count {
  575. let dict = basal[i] as! Dictionary<String, Any>
  576. do {
  577. let thisValue = try dict[keyPath: "value"] as! Double
  578. let thisTime = dict[keyPath: "time"] as! String
  579. let thisTimeAsSeconds = dict[keyPath: "timeAsSeconds"] as! Double
  580. let entry = basalProfileStruct(value: thisValue, time: thisTime, timeAsSeconds: thisTimeAsSeconds)
  581. basalProfile.append(entry)
  582. } catch {
  583. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: profile wrapped in quotes") }
  584. }
  585. }
  586. // Don't process the basal or draw the graph until after the BG has been fully processeed and drawn
  587. if firstGraphLoad { return }
  588. // Make temporary array with all values of yesterday and today
  589. let yesterdayStart = dateTimeUtils.getTimeIntervalMidnightYesterday()
  590. let todayStart = dateTimeUtils.getTimeIntervalMidnightToday()
  591. var basal2Day: [DataStructs.basal2DayProfile] = []
  592. // Run twice to add in order yesterday then today.
  593. for p in 0..<basalProfile.count {
  594. let start = yesterdayStart + basalProfile[p].timeAsSeconds
  595. var end = yesterdayStart
  596. // set the endings 1 second before the next one starts
  597. if p < basalProfile.count - 1 {
  598. end = yesterdayStart + basalProfile[p + 1].timeAsSeconds - 1
  599. } else {
  600. // set the end 1 second before midnight
  601. end = yesterdayStart + 86399
  602. }
  603. let entry = DataStructs.basal2DayProfile(basalRate: basalProfile[p].value, startDate: start, endDate: end)
  604. basal2Day.append(entry)
  605. }
  606. for p in 0..<basalProfile.count {
  607. let start = todayStart + basalProfile[p].timeAsSeconds
  608. var end = todayStart
  609. // set the endings 1 second before the next one starts
  610. if p < basalProfile.count - 1 {
  611. end = todayStart + basalProfile[p + 1].timeAsSeconds - 1
  612. } else {
  613. // set the end 1 second before midnight
  614. end = todayStart + 86399
  615. }
  616. let entry = DataStructs.basal2DayProfile(basalRate: basalProfile[p].value, startDate: start, endDate: end)
  617. basal2Day.append(entry)
  618. }
  619. let now = dateTimeUtils.nowMinus24HoursTimeInterval()
  620. var firstPass = true
  621. basalScheduleData.removeAll()
  622. for i in 0..<basal2Day.count {
  623. var timeYesterday = dateTimeUtils.getTimeInterval24HoursAgo()
  624. // This processed everything after the first one.
  625. if firstPass == false
  626. && basal2Day[i].startDate <= dateTimeUtils.getNowTimeIntervalUTC() {
  627. let startDot = basalGraphStruct(basalRate: basal2Day[i].basalRate, date: basal2Day[i].startDate)
  628. basalScheduleData.append(startDot)
  629. var endDate = basal2Day[i].endDate
  630. // if it's the last one in the profile or date is greater than now, set it to the last BG dot
  631. if i == basal2Day.count - 1 || endDate > dateTimeUtils.getNowTimeIntervalUTC() {
  632. endDate = Double(dateTimeUtils.getNowTimeIntervalUTC())
  633. }
  634. let endDot = basalGraphStruct(basalRate: basal2Day[i].basalRate, date: endDate)
  635. basalScheduleData.append(endDot)
  636. }
  637. // we need to manually set the first one
  638. // Check that this is the first one and there are no existing entries
  639. if firstPass == true {
  640. // check that the timestamp is > the current entry and < the next entry
  641. if timeYesterday >= basal2Day[i].startDate && timeYesterday < basal2Day[i].endDate {
  642. // Set the start time to match the BG start
  643. let startDot = basalGraphStruct(basalRate: basal2Day[i].basalRate, date: Double(dateTimeUtils.getTimeInterval24HoursAgo() + (60 * 5)))
  644. basalScheduleData.append(startDot)
  645. // set the enddot where the next one will start
  646. var endDate = basal2Day[i].endDate
  647. let endDot = basalGraphStruct(basalRate: basal2Day[i].basalRate, date: endDate)
  648. basalScheduleData.append(endDot)
  649. firstPass = false
  650. }
  651. }
  652. }
  653. if UserDefaultsRepository.graphBasal.value {
  654. updateBasalScheduledGraph()
  655. }
  656. }
  657. // NS Temp Basal Web Call
  658. func WebLoadNSTempBasals() {
  659. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: Basal") }
  660. if !UserDefaultsRepository.downloadBasal.value { return }
  661. let yesterdayString = dateTimeUtils.nowMinus24HoursTimeInterval()
  662. var urlString = UserDefaultsRepository.url.value + "/api/v1/treatments.json?find[eventType][$eq]=Temp%20Basal&find[created_at][$gte]=" + yesterdayString
  663. if token != "" {
  664. urlString = UserDefaultsRepository.url.value + "/api/v1/treatments.json?token=" + token + "&find[eventType][$eq]=Temp%20Basal&find[created_at][$gte]=" + yesterdayString
  665. }
  666. guard let urlData = URL(string: urlString) else {
  667. return
  668. }
  669. var request = URLRequest(url: urlData)
  670. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  671. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  672. guard error == nil else {
  673. return
  674. }
  675. guard let data = data else {
  676. return
  677. }
  678. let json = try? (JSONSerialization.jsonObject(with: data) as? [[String:AnyObject]])
  679. if let json = json {
  680. DispatchQueue.main.async {
  681. self.updateBasals(entries: json)
  682. }
  683. } else {
  684. return
  685. }
  686. }
  687. task.resume()
  688. }
  689. // NS Temp Basal Response Processor
  690. func updateBasals(entries: [[String:AnyObject]]) {
  691. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Basal") }
  692. // due to temp basal durations, we're going to destroy the array and load everything each cycle for the time being.
  693. basalData.removeAll()
  694. var lastEndDot = 0.0
  695. var tempArray = entries
  696. tempArray.reverse()
  697. for i in 0..<tempArray.count {
  698. let currentEntry = tempArray[i] as [String : AnyObject]?
  699. var basalDate: String
  700. if currentEntry?["timestamp"] != nil {
  701. basalDate = currentEntry?["timestamp"] as! String
  702. } else if currentEntry?["created_at"] != nil {
  703. basalDate = currentEntry?["created_at"] as! String
  704. } else {
  705. return
  706. }
  707. let strippedZone = String(basalDate.dropLast())
  708. let dateFormatter = DateFormatter()
  709. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  710. dateFormatter.locale = Locale(identifier: "en_US")
  711. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  712. let dateString = dateFormatter.date(from: strippedZone)
  713. let dateTimeStamp = dateString!.timeIntervalSince1970
  714. let basalRate = currentEntry?["absolute"] as! Double
  715. let midnightTime = dateTimeUtils.getTimeIntervalMidnightToday()
  716. // Setting end dots
  717. var duration = 0.0
  718. do {
  719. duration = try currentEntry?["duration"] as! Double
  720. } catch {
  721. print("No Duration Found")
  722. }
  723. // 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
  724. if i > 0 {
  725. let priorEntry = tempArray[i - 1] as [String : AnyObject]?
  726. let priorBasalDate = priorEntry?["timestamp"] as! String
  727. let priorStrippedZone = String(priorBasalDate.dropLast())
  728. let priorDateFormatter = DateFormatter()
  729. priorDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  730. priorDateFormatter.locale = Locale(identifier: "en_US")
  731. priorDateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  732. let priorDateString = dateFormatter.date(from: priorStrippedZone)
  733. let priorDateTimeStamp = priorDateString!.timeIntervalSince1970
  734. let priorDuration = priorEntry?["duration"] as! Double
  735. // 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
  736. if Double( dateTimeStamp - priorDateTimeStamp ) > Double( (priorDuration * 60) + 15 ) {
  737. var scheduled = 0.0
  738. // cycle through basal profiles.
  739. // TODO figure out how to deal with profile changes that happen mid-gap
  740. for b in 0..<self.basalProfile.count {
  741. let scheduleTimeYesterday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightYesterday()
  742. let scheduleTimeToday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightToday()
  743. // check the prior temp ending to the profile seconds from midnight
  744. if (priorDateTimeStamp + (priorDuration * 60)) >= scheduleTimeYesterday {
  745. scheduled = basalProfile[b].value
  746. }
  747. if (priorDateTimeStamp + (priorDuration * 60)) >= scheduleTimeToday {
  748. scheduled = basalProfile[b].value
  749. }
  750. // This will iterate through from midnight on and set it for the highest matching one.
  751. }
  752. // Make the starting dot at the last ending dot
  753. let startDot = basalGraphStruct(basalRate: scheduled, date: Double(priorDateTimeStamp + (priorDuration * 60)))
  754. basalData.append(startDot)
  755. //if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Basal: Scheduled " + String(scheduled) + " " + String(dateTimeStamp)) }
  756. // Make the ending dot at the new starting dot
  757. let endDot = basalGraphStruct(basalRate: scheduled, date: Double(dateTimeStamp))
  758. basalData.append(endDot)
  759. }
  760. }
  761. // Make the starting dot
  762. let startDot = basalGraphStruct(basalRate: basalRate, date: Double(dateTimeStamp))
  763. basalData.append(startDot)
  764. // Make the ending dot
  765. // If it's the last one and has no duration, extend it for 30 minutes past the start. Otherwise set ending at duration
  766. // duration is already set to 0 if there is no duration set on it.
  767. //if i == tempArray.count - 1 && dateTimeStamp + duration <= dateTimeUtils.getNowTimeIntervalUTC() {
  768. if i == tempArray.count - 1 && duration == 0.0 {
  769. lastEndDot = dateTimeStamp + (30 * 60)
  770. latestBasal = String(format:"%.2f", basalRate)
  771. } else {
  772. lastEndDot = dateTimeStamp + (duration * 60)
  773. latestBasal = String(format:"%.2f", basalRate)
  774. }
  775. // Double check for overlaps of incorrectly ended TBRs and sent it to end when the next one starts if it finds a discrepancy
  776. if i < tempArray.count - 1 {
  777. let nextEntry = tempArray[i + 1] as [String : AnyObject]?
  778. let nextBasalDate = nextEntry?["timestamp"] as! String
  779. let nextStrippedZone = String(nextBasalDate.dropLast())
  780. let nextDateFormatter = DateFormatter()
  781. nextDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  782. nextDateFormatter.locale = Locale(identifier: "en_US")
  783. nextDateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  784. let nextDateString = dateFormatter.date(from: nextStrippedZone)
  785. let nextDateTimeStamp = nextDateString!.timeIntervalSince1970
  786. if nextDateTimeStamp < (dateTimeStamp + (duration * 60)) {
  787. lastEndDot = nextDateTimeStamp
  788. }
  789. }
  790. let endDot = basalGraphStruct(basalRate: basalRate, date: Double(lastEndDot))
  791. basalData.append(endDot)
  792. }
  793. // If last basal was prior to right now, we need to create one last scheduled entry
  794. if lastEndDot <= dateTimeUtils.getNowTimeIntervalUTC() {
  795. var scheduled = 0.0
  796. // cycle through basal profiles.
  797. // TODO figure out how to deal with profile changes that happen mid-gap
  798. for b in 0..<self.basalProfile.count {
  799. let scheduleTimeYesterday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightYesterday()
  800. let scheduleTimeToday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightToday()
  801. // check the prior temp ending to the profile seconds from midnight
  802. print("yesterday " + String(scheduleTimeYesterday))
  803. print("today " + String(scheduleTimeToday))
  804. if lastEndDot >= scheduleTimeToday {
  805. scheduled = basalProfile[b].value
  806. }
  807. }
  808. latestBasal = String(format:"%.2f", scheduled)
  809. // Make the starting dot at the last ending dot
  810. let startDot = basalGraphStruct(basalRate: scheduled, date: Double(lastEndDot))
  811. basalData.append(startDot)
  812. // Make the ending dot 10 minutes after now
  813. let endDot = basalGraphStruct(basalRate: scheduled, date: Double(Date().timeIntervalSince1970 + (60 * 10)))
  814. basalData.append(endDot)
  815. }
  816. tableData[2].value = latestBasal
  817. if UserDefaultsRepository.graphBasal.value {
  818. updateBasalGraph()
  819. }
  820. }
  821. // NS Bolus Web Call
  822. func webLoadNSBoluses(){
  823. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: Bolus") }
  824. if !UserDefaultsRepository.downloadBolus.value { return }
  825. let yesterdayString = dateTimeUtils.nowMinus24HoursTimeInterval()
  826. let urlUser = UserDefaultsRepository.url.value
  827. var searchString = "find[eventType]=Correction%20Bolus&find[created_at][$gte]=" + yesterdayString
  828. var urlDataPath: String = urlUser + "/api/v1/treatments.json?"
  829. if token == "" {
  830. urlDataPath = urlDataPath + searchString
  831. }
  832. else
  833. {
  834. urlDataPath = urlDataPath + "token=" + token + "&" + searchString
  835. }
  836. guard let urlData = URL(string: urlDataPath) else {
  837. return
  838. }
  839. var request = URLRequest(url: urlData)
  840. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  841. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  842. guard error == nil else {
  843. return
  844. }
  845. guard let data = data else {
  846. return
  847. }
  848. let json = try? (JSONSerialization.jsonObject(with: data) as? [[String:AnyObject]])
  849. if let json = json {
  850. DispatchQueue.main.async {
  851. self.processNSBolus(entries: json)
  852. }
  853. } else {
  854. return
  855. }
  856. }
  857. task.resume()
  858. }
  859. // NS Meal Bolus Response Processor
  860. func processNSBolus(entries: [[String:AnyObject]]) {
  861. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Bolus") }
  862. // because it's a small array, we're going to destroy and reload every time.
  863. bolusData.removeAll()
  864. var lastFoundIndex = 0
  865. for i in 0..<entries.count {
  866. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  867. var bolusDate: String
  868. if currentEntry?["timestamp"] != nil {
  869. bolusDate = currentEntry?["timestamp"] as! String
  870. } else if currentEntry?["created_at"] != nil {
  871. bolusDate = currentEntry?["created_at"] as! String
  872. } else {
  873. return
  874. }
  875. let strippedZone = String(bolusDate.dropLast())
  876. let dateFormatter = DateFormatter()
  877. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  878. dateFormatter.locale = Locale(identifier: "en_US")
  879. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  880. let dateString = dateFormatter.date(from: strippedZone)
  881. let dateTimeStamp = dateString!.timeIntervalSince1970
  882. do {
  883. let bolus = try currentEntry?["insulin"] as! Double
  884. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  885. lastFoundIndex = sgv.foundIndex
  886. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  887. // Make the dot
  888. let dot = bolusCarbGraphStruct(value: bolus, date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  889. bolusData.append(dot)
  890. }
  891. } catch {
  892. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: Null Bolus") }
  893. }
  894. }
  895. if UserDefaultsRepository.graphBolus.value {
  896. updateBolusGraph()
  897. }
  898. }
  899. // NS Carb Web Call
  900. func webLoadNSCarbs(){
  901. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: Carbs") }
  902. if !UserDefaultsRepository.downloadCarbs.value { return }
  903. let yesterdayString = dateTimeUtils.nowMinus24HoursTimeInterval()
  904. let urlUser = UserDefaultsRepository.url.value
  905. var searchString = "find[eventType]=Meal%20Bolus&find[created_at][$gte]=" + yesterdayString
  906. var urlDataPath: String = urlUser + "/api/v1/treatments.json?"
  907. if token == "" {
  908. urlDataPath = urlDataPath + searchString
  909. }
  910. else
  911. {
  912. urlDataPath = urlDataPath + "token=" + token + "&" + searchString
  913. }
  914. guard let urlData = URL(string: urlDataPath) else {
  915. return
  916. }
  917. var request = URLRequest(url: urlData)
  918. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  919. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  920. guard error == nil else {
  921. return
  922. }
  923. guard let data = data else {
  924. return
  925. }
  926. let json = try? (JSONSerialization.jsonObject(with: data) as? [[String:AnyObject]])
  927. if let json = json {
  928. DispatchQueue.main.async {
  929. self.processNSCarbs(entries: json)
  930. }
  931. } else {
  932. return
  933. }
  934. }
  935. task.resume()
  936. }
  937. // NS Carb Bolus Response Processor
  938. func processNSCarbs(entries: [[String:AnyObject]]) {
  939. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Carbs") }
  940. // because it's a small array, we're going to destroy and reload every time.
  941. carbData.removeAll()
  942. var lastFoundIndex = 0
  943. for i in 0..<entries.count {
  944. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  945. var carbDate: String
  946. if currentEntry?["timestamp"] != nil {
  947. carbDate = currentEntry?["timestamp"] as! String
  948. } else if currentEntry?["created_at"] != nil {
  949. carbDate = currentEntry?["created_at"] as! String
  950. } else {
  951. return
  952. }
  953. let strippedZone = String(carbDate.dropLast())
  954. let dateFormatter = DateFormatter()
  955. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  956. dateFormatter.locale = Locale(identifier: "en_US")
  957. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  958. let dateString = dateFormatter.date(from: strippedZone)
  959. let dateTimeStamp = dateString!.timeIntervalSince1970
  960. do {
  961. let carbs = try currentEntry?["carbs"] as! Double
  962. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  963. lastFoundIndex = sgv.foundIndex
  964. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  965. // Make the dot
  966. let dot = bolusCarbGraphStruct(value: carbs, date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  967. carbData.append(dot)
  968. }
  969. } catch {
  970. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: Null Carb entry") }
  971. }
  972. }
  973. if UserDefaultsRepository.graphCarbs.value {
  974. updateCarbGraph()
  975. }
  976. }
  977. }