NightScout.swift 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126
  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. latestLoopTime = lastLoopTime
  289. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "lastLoopTime: " + String(lastLoopTime)) }
  290. if let failure = lastLoopRecord["failureReason"] {
  291. LoopStatusLabel.text = "X"
  292. latestLoopStatusString = "X"
  293. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Loop Failure: X") }
  294. } else {
  295. var wasEnacted = false
  296. if let enacted = lastLoopRecord["enacted"] as? [String:AnyObject] {
  297. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Loop: Was Enacted") }
  298. wasEnacted = true
  299. if let lastTempBasal = enacted["rate"] as? Double {
  300. // tableData[2].value = String(format:"%.1f", lastTempBasal)
  301. }
  302. }
  303. if let iobdata = lastLoopRecord["iob"] as? [String:AnyObject] {
  304. tableData[0].value = String(format:"%.2f", (iobdata["iob"] as! Double))
  305. latestIOB = String(format:"%.2f", (iobdata["iob"] as! Double))
  306. }
  307. if let cobdata = lastLoopRecord["cob"] as? [String:AnyObject] {
  308. tableData[1].value = String(format:"%.0f", cobdata["cob"] as! Double)
  309. latestCOB = String(format:"%.0f", cobdata["cob"] as! Double)
  310. }
  311. if let predictdata = lastLoopRecord["predicted"] as? [String:AnyObject] {
  312. let prediction = predictdata["values"] as! [Double]
  313. PredictionLabel.text = bgUnits.toDisplayUnits(String(Int(prediction.last!)))
  314. PredictionLabel.textColor = UIColor.systemPurple
  315. predictionData.removeAll()
  316. if UserDefaultsRepository.downloadPrediction.value {
  317. var i = 1
  318. while i <= 12 {
  319. predictionData.append(prediction[i])
  320. i += 1
  321. }
  322. }
  323. }
  324. if let loopStatus = lastLoopRecord["recommendedTempBasal"] as? [String:AnyObject] {
  325. if let tempBasalTime = formatter.date(from: (loopStatus["timestamp"] as! String))?.timeIntervalSince1970 {
  326. var lastBGTime = lastLoopTime
  327. if bgData.count > 0 {
  328. lastBGTime = bgData[bgData.count - 1].date
  329. }
  330. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "tempBasalTime: " + String(tempBasalTime)) }
  331. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "lastBGTime: " + String(lastBGTime)) }
  332. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "wasEnacted: " + String(wasEnacted)) }
  333. if tempBasalTime > lastBGTime && !wasEnacted {
  334. LoopStatusLabel.text = "⏀"
  335. latestLoopStatusString = "⏀"
  336. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Open Loop: recommended temp. temp time > bg time, was not enacted") }
  337. } else {
  338. LoopStatusLabel.text = "↻"
  339. latestLoopStatusString = "↻"
  340. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Looping: recommended temp, but temp time is < bg time and/or was enacted") }
  341. }
  342. }
  343. } else {
  344. LoopStatusLabel.text = "↻"
  345. latestLoopStatusString = "↻"
  346. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Looping: no recommended temp") }
  347. }
  348. }
  349. if ((TimeInterval(Date().timeIntervalSince1970) - lastLoopTime) / 60) > 15 {
  350. LoopStatusLabel.text = "⚠"
  351. latestLoopStatusString = "⚠"
  352. }
  353. } // end lastLoopTime
  354. } // end lastLoop Record
  355. var oText = "" as String
  356. currentOverride = 1.0
  357. if let lastOverride = lastDeviceStatus?["override"] as! [String : AnyObject]? {
  358. if let lastOverrideTime = formatter.date(from: (lastOverride["timestamp"] as! String))?.timeIntervalSince1970 {
  359. }
  360. if lastOverride["active"] as! Bool {
  361. let lastCorrection = lastOverride["currentCorrectionRange"] as! [String: AnyObject]
  362. if let multiplier = lastOverride["multiplier"] as? Double {
  363. currentOverride = multiplier
  364. oText += String(format:"%.1f", multiplier*100)
  365. }
  366. else
  367. {
  368. oText += String(format:"%.1f", 100)
  369. }
  370. oText += "% ("
  371. let minValue = lastCorrection["minValue"] as! Double
  372. let maxValue = lastCorrection["maxValue"] as! Double
  373. oText += bgUnits.toDisplayUnits(String(minValue)) + "-" + bgUnits.toDisplayUnits(String(maxValue)) + ")"
  374. tableData[3].value = oText
  375. }
  376. }
  377. infoTable.reloadData()
  378. // Process Override Data
  379. overrideData.removeAll()
  380. for i in 0..<jsonDeviceStatus.count {
  381. let deviceStatus = jsonDeviceStatus[i] as [String : AnyObject]?
  382. if let override = deviceStatus?["override"] as! [String : AnyObject]? {
  383. let formatter = ISO8601DateFormatter()
  384. formatter.formatOptions = [.withFullDate,
  385. .withTime,
  386. .withDashSeparatorInDate,
  387. .withColonSeparatorInTime]
  388. if let timestamp = formatter.date(from: (override["timestamp"] as! String))?.timeIntervalSince1970 {
  389. if let isActive = override["active"] as? Bool {
  390. if isActive {
  391. if let multiplier = override["multiplier"] as? Double {
  392. let override = DataStructs.overrideGraphStruct(value: multiplier, date: timestamp, sgv: 40)
  393. overrideData.append(override)
  394. }
  395. } else {
  396. let multiplier = 1.0 as Double
  397. let override = DataStructs.overrideGraphStruct(value: multiplier, date: timestamp, sgv: 40)
  398. overrideData.append(override)
  399. }
  400. }
  401. }
  402. }
  403. }
  404. overrideData.reverse()
  405. updateOverrideGraph()
  406. }
  407. // NS Cage Web Call
  408. func webLoadNSCage() {
  409. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: CAGE") }
  410. let urlUser = UserDefaultsRepository.url.value
  411. var urlString = urlUser + "/api/v1/treatments.json?find[eventType]=Site%20Change&count=1"
  412. if token != "" {
  413. urlString = urlUser + "/api/v1/treatments.json?token=" + token + "&find[eventType]=Site%20Change&count=1"
  414. }
  415. guard let urlData = URL(string: urlString) else {
  416. return
  417. }
  418. var request = URLRequest(url: urlData)
  419. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  420. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  421. guard error == nil else {
  422. return
  423. }
  424. guard let data = data else {
  425. return
  426. }
  427. let decoder = JSONDecoder()
  428. let entriesResponse = try? decoder.decode([cageData].self, from: data)
  429. if let entriesResponse = entriesResponse {
  430. DispatchQueue.main.async {
  431. self.updateCage(data: entriesResponse)
  432. }
  433. } else {
  434. return
  435. }
  436. }
  437. task.resume()
  438. }
  439. // NS Cage Response Processor
  440. func updateCage(data: [cageData]) {
  441. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: CAGE") }
  442. if data.count == 0 {
  443. return
  444. }
  445. let lastCageString = data[0].created_at
  446. let formatter = ISO8601DateFormatter()
  447. formatter.formatOptions = [.withFullDate,
  448. .withTime,
  449. .withDashSeparatorInDate,
  450. .withColonSeparatorInTime]
  451. UserDefaultsRepository.alertCageInsertTime.value = formatter.date(from: (lastCageString))?.timeIntervalSince1970 as! TimeInterval
  452. if let cageTime = formatter.date(from: (lastCageString))?.timeIntervalSince1970 {
  453. let now = NSDate().timeIntervalSince1970
  454. let secondsAgo = now - cageTime
  455. //let days = 24 * 60 * 60
  456. let formatter = DateComponentsFormatter()
  457. formatter.unitsStyle = .positional // Use the appropriate positioning for the current locale
  458. formatter.allowedUnits = [ .day, .hour ] // Units to display in the formatted string
  459. formatter.zeroFormattingBehavior = [ .pad ] // Pad with zeroes where appropriate for the locale
  460. let formattedDuration = formatter.string(from: secondsAgo)
  461. tableData[7].value = formattedDuration ?? ""
  462. }
  463. infoTable.reloadData()
  464. }
  465. // NS Sage Web Call
  466. func webLoadNSSage() {
  467. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: SAGE") }
  468. let lastDateString = dateTimeUtils.nowMinus10DaysTimeInterval()
  469. let urlUser = UserDefaultsRepository.url.value
  470. var urlString = urlUser + "/api/v1/treatments.json?find[eventType]=Sensor%20Start&find[created_at][$gte]=" + lastDateString + "&count=1"
  471. if token != "" {
  472. urlString = urlUser + "/api/v1/treatments.json?token=" + token + "&find[eventType]=Sensor%20Start&find[created_at][$gte]=" + lastDateString + "&count=1"
  473. }
  474. guard let urlData = URL(string: urlString) else {
  475. return
  476. }
  477. var request = URLRequest(url: urlData)
  478. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  479. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  480. guard error == nil else {
  481. return
  482. }
  483. guard let data = data else {
  484. return
  485. }
  486. let decoder = JSONDecoder()
  487. let entriesResponse = try? decoder.decode([cageData].self, from: data)
  488. if let entriesResponse = entriesResponse {
  489. DispatchQueue.main.async {
  490. self.updateSage(data: entriesResponse)
  491. }
  492. } else {
  493. return
  494. }
  495. }
  496. task.resume()
  497. }
  498. // NS Sage Response Processor
  499. func updateSage(data: [cageData]) {
  500. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process/Display: SAGE") }
  501. if data.count == 0 {
  502. return
  503. }
  504. var lastSageString = data[0].created_at
  505. let formatter = ISO8601DateFormatter()
  506. formatter.formatOptions = [.withFullDate,
  507. .withTime,
  508. .withDashSeparatorInDate,
  509. .withColonSeparatorInTime]
  510. UserDefaultsRepository.alertSageInsertTime.value = formatter.date(from: (lastSageString))?.timeIntervalSince1970 as! TimeInterval
  511. if let sageTime = formatter.date(from: (lastSageString as! String))?.timeIntervalSince1970 {
  512. let now = NSDate().timeIntervalSince1970
  513. let secondsAgo = now - sageTime
  514. let days = 24 * 60 * 60
  515. let formatter = DateComponentsFormatter()
  516. formatter.unitsStyle = .positional // Use the appropriate positioning for the current locale
  517. formatter.allowedUnits = [ .day, .hour] // Units to display in the formatted string
  518. formatter.zeroFormattingBehavior = [ .pad ] // Pad with zeroes where appropriate for the locale
  519. let formattedDuration = formatter.string(from: secondsAgo)
  520. tableData[6].value = formattedDuration ?? ""
  521. }
  522. infoTable.reloadData()
  523. }
  524. // NS Profile Web Call
  525. func webLoadNSProfile() {
  526. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: profile") }
  527. let urlUser = UserDefaultsRepository.url.value
  528. var urlString = urlUser + "/api/v1/profile/current.json"
  529. if token != "" {
  530. urlString = urlUser + "/api/v1/profile/current.json?token=" + token
  531. }
  532. let escapedAddress = urlString.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
  533. guard let url = URL(string: escapedAddress!) else {
  534. return
  535. }
  536. var request = URLRequest(url: url)
  537. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  538. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  539. guard error == nil else {
  540. return
  541. }
  542. guard let data = data else {
  543. return
  544. }
  545. let json = try? JSONSerialization.jsonObject(with: data) as! Dictionary<String, Any>
  546. if let json = json {
  547. DispatchQueue.main.async {
  548. self.updateProfile(jsonDeviceStatus: json)
  549. }
  550. } else {
  551. return
  552. }
  553. }
  554. task.resume()
  555. }
  556. // NS Profile Response Processor
  557. func updateProfile(jsonDeviceStatus: Dictionary<String, Any>) {
  558. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: profile") }
  559. if jsonDeviceStatus.count == 0 {
  560. return
  561. }
  562. if jsonDeviceStatus[keyPath: "message"] != nil { return }
  563. let basal = try jsonDeviceStatus[keyPath: "store.Default.basal"] as! NSArray
  564. basalProfile.removeAll()
  565. for i in 0..<basal.count {
  566. let dict = basal[i] as! Dictionary<String, Any>
  567. do {
  568. let thisValue = try dict[keyPath: "value"] as! Double
  569. let thisTime = dict[keyPath: "time"] as! String
  570. let thisTimeAsSeconds = dict[keyPath: "timeAsSeconds"] as! Double
  571. let entry = basalProfileStruct(value: thisValue, time: thisTime, timeAsSeconds: thisTimeAsSeconds)
  572. basalProfile.append(entry)
  573. } catch {
  574. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: profile wrapped in quotes") }
  575. }
  576. }
  577. // Don't process the basal or draw the graph until after the BG has been fully processeed and drawn
  578. if firstGraphLoad { return }
  579. // Make temporary array with all values of yesterday and today
  580. let yesterdayStart = dateTimeUtils.getTimeIntervalMidnightYesterday()
  581. let todayStart = dateTimeUtils.getTimeIntervalMidnightToday()
  582. var basal2Day: [DataStructs.basal2DayProfile] = []
  583. // Run twice to add in order yesterday then today.
  584. for p in 0..<basalProfile.count {
  585. let start = yesterdayStart + basalProfile[p].timeAsSeconds
  586. var end = yesterdayStart
  587. // set the endings 1 second before the next one starts
  588. if p < basalProfile.count - 1 {
  589. end = yesterdayStart + basalProfile[p + 1].timeAsSeconds - 1
  590. } else {
  591. // set the end 1 second before midnight
  592. end = yesterdayStart + 86399
  593. }
  594. let entry = DataStructs.basal2DayProfile(basalRate: basalProfile[p].value, startDate: start, endDate: end)
  595. basal2Day.append(entry)
  596. }
  597. for p in 0..<basalProfile.count {
  598. let start = todayStart + basalProfile[p].timeAsSeconds
  599. var end = todayStart
  600. // set the endings 1 second before the next one starts
  601. if p < basalProfile.count - 1 {
  602. end = todayStart + basalProfile[p + 1].timeAsSeconds - 1
  603. } else {
  604. // set the end 1 second before midnight
  605. end = todayStart + 86399
  606. }
  607. let entry = DataStructs.basal2DayProfile(basalRate: basalProfile[p].value, startDate: start, endDate: end)
  608. basal2Day.append(entry)
  609. }
  610. let now = dateTimeUtils.nowMinus24HoursTimeInterval()
  611. var firstPass = true
  612. basalScheduleData.removeAll()
  613. for i in 0..<basal2Day.count {
  614. var timeYesterday = dateTimeUtils.getTimeInterval24HoursAgo()
  615. // This processed everything after the first one.
  616. if firstPass == false
  617. && basal2Day[i].startDate <= dateTimeUtils.getNowTimeIntervalUTC() {
  618. let startDot = basalGraphStruct(basalRate: basal2Day[i].basalRate, date: basal2Day[i].startDate)
  619. basalScheduleData.append(startDot)
  620. var endDate = basal2Day[i].endDate
  621. // if it's the last one in the profile or date is greater than now, set it to the last BG dot
  622. if i == basal2Day.count - 1 || endDate > dateTimeUtils.getNowTimeIntervalUTC() {
  623. endDate = Double(dateTimeUtils.getNowTimeIntervalUTC())
  624. }
  625. let endDot = basalGraphStruct(basalRate: basal2Day[i].basalRate, date: endDate)
  626. basalScheduleData.append(endDot)
  627. }
  628. // we need to manually set the first one
  629. // Check that this is the first one and there are no existing entries
  630. if firstPass == true {
  631. // check that the timestamp is > the current entry and < the next entry
  632. if timeYesterday >= basal2Day[i].startDate && timeYesterday < basal2Day[i].endDate {
  633. // Set the start time to match the BG start
  634. let startDot = basalGraphStruct(basalRate: basal2Day[i].basalRate, date: Double(dateTimeUtils.getTimeInterval24HoursAgo() + (60 * 5)))
  635. basalScheduleData.append(startDot)
  636. // set the enddot where the next one will start
  637. var endDate = basal2Day[i].endDate
  638. let endDot = basalGraphStruct(basalRate: basal2Day[i].basalRate, date: endDate)
  639. basalScheduleData.append(endDot)
  640. firstPass = false
  641. }
  642. }
  643. }
  644. if UserDefaultsRepository.graphBasal.value {
  645. updateBasalScheduledGraph()
  646. }
  647. }
  648. // NS Temp Basal Web Call
  649. func WebLoadNSTempBasals() {
  650. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: Basal") }
  651. if !UserDefaultsRepository.downloadBasal.value { return }
  652. let yesterdayString = dateTimeUtils.nowMinus24HoursTimeInterval()
  653. var urlString = UserDefaultsRepository.url.value + "/api/v1/treatments.json?find[eventType][$eq]=Temp%20Basal&find[created_at][$gte]=" + yesterdayString
  654. if token != "" {
  655. urlString = UserDefaultsRepository.url.value + "/api/v1/treatments.json?token=" + token + "&find[eventType][$eq]=Temp%20Basal&find[created_at][$gte]=" + yesterdayString
  656. }
  657. guard let urlData = URL(string: urlString) else {
  658. return
  659. }
  660. var request = URLRequest(url: urlData)
  661. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  662. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  663. guard error == nil else {
  664. return
  665. }
  666. guard let data = data else {
  667. return
  668. }
  669. let json = try? (JSONSerialization.jsonObject(with: data) as? [[String:AnyObject]])
  670. if let json = json {
  671. DispatchQueue.main.async {
  672. self.updateBasals(entries: json)
  673. }
  674. } else {
  675. return
  676. }
  677. }
  678. task.resume()
  679. }
  680. // NS Temp Basal Response Processor
  681. func updateBasals(entries: [[String:AnyObject]]) {
  682. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Basal") }
  683. // due to temp basal durations, we're going to destroy the array and load everything each cycle for the time being.
  684. basalData.removeAll()
  685. var lastEndDot = 0.0
  686. var tempArray = entries
  687. tempArray.reverse()
  688. for i in 0..<tempArray.count {
  689. let currentEntry = tempArray[i] as [String : AnyObject]?
  690. var basalDate: String
  691. if currentEntry?["timestamp"] != nil {
  692. basalDate = currentEntry?["timestamp"] as! String
  693. } else if currentEntry?["created_at"] != nil {
  694. basalDate = currentEntry?["created_at"] as! String
  695. } else {
  696. return
  697. }
  698. let strippedZone = String(basalDate.dropLast())
  699. let dateFormatter = DateFormatter()
  700. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  701. dateFormatter.locale = Locale(identifier: "en_US")
  702. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  703. let dateString = dateFormatter.date(from: strippedZone)
  704. let dateTimeStamp = dateString!.timeIntervalSince1970
  705. let basalRate = currentEntry?["absolute"] as! Double
  706. let midnightTime = dateTimeUtils.getTimeIntervalMidnightToday()
  707. // Setting end dots
  708. var duration = 0.0
  709. do {
  710. duration = try currentEntry?["duration"] as! Double
  711. } catch {
  712. print("No Duration Found")
  713. }
  714. // 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
  715. if i > 0 {
  716. let priorEntry = tempArray[i - 1] as [String : AnyObject]?
  717. let priorBasalDate = priorEntry?["timestamp"] as! String
  718. let priorStrippedZone = String(priorBasalDate.dropLast())
  719. let priorDateFormatter = DateFormatter()
  720. priorDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  721. priorDateFormatter.locale = Locale(identifier: "en_US")
  722. priorDateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  723. let priorDateString = dateFormatter.date(from: priorStrippedZone)
  724. let priorDateTimeStamp = priorDateString!.timeIntervalSince1970
  725. let priorDuration = priorEntry?["duration"] as! Double
  726. // 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
  727. if Double( dateTimeStamp - priorDateTimeStamp ) > Double( (priorDuration * 60) + 15 ) {
  728. var scheduled = 0.0
  729. // cycle through basal profiles.
  730. // TODO figure out how to deal with profile changes that happen mid-gap
  731. for b in 0..<self.basalProfile.count {
  732. let scheduleTimeYesterday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightYesterday()
  733. let scheduleTimeToday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightToday()
  734. // check the prior temp ending to the profile seconds from midnight
  735. if (priorDateTimeStamp + (priorDuration * 60)) >= scheduleTimeYesterday {
  736. scheduled = basalProfile[b].value
  737. }
  738. if (priorDateTimeStamp + (priorDuration * 60)) >= scheduleTimeToday {
  739. scheduled = basalProfile[b].value
  740. }
  741. // This will iterate through from midnight on and set it for the highest matching one.
  742. }
  743. // Make the starting dot at the last ending dot
  744. let startDot = basalGraphStruct(basalRate: scheduled, date: Double(priorDateTimeStamp + (priorDuration * 60)))
  745. basalData.append(startDot)
  746. //if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Basal: Scheduled " + String(scheduled) + " " + String(dateTimeStamp)) }
  747. // Make the ending dot at the new starting dot
  748. let endDot = basalGraphStruct(basalRate: scheduled, date: Double(dateTimeStamp))
  749. basalData.append(endDot)
  750. }
  751. }
  752. // Make the starting dot
  753. let startDot = basalGraphStruct(basalRate: basalRate, date: Double(dateTimeStamp))
  754. basalData.append(startDot)
  755. // Make the ending dot
  756. // If it's the last one and has no duration, extend it for 30 minutes past the start. Otherwise set ending at duration
  757. // duration is already set to 0 if there is no duration set on it.
  758. //if i == tempArray.count - 1 && dateTimeStamp + duration <= dateTimeUtils.getNowTimeIntervalUTC() {
  759. if i == tempArray.count - 1 && duration == 0.0 {
  760. lastEndDot = dateTimeStamp + (30 * 60)
  761. latestBasal = String(format:"%.2f", basalRate)
  762. } else {
  763. lastEndDot = dateTimeStamp + (duration * 60)
  764. latestBasal = String(format:"%.2f", basalRate)
  765. }
  766. // Double check for overlaps of incorrectly ended TBRs and sent it to end when the next one starts if it finds a discrepancy
  767. if i < tempArray.count - 1 {
  768. let nextEntry = tempArray[i + 1] as [String : AnyObject]?
  769. let nextBasalDate = nextEntry?["timestamp"] as! String
  770. let nextStrippedZone = String(nextBasalDate.dropLast())
  771. let nextDateFormatter = DateFormatter()
  772. nextDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  773. nextDateFormatter.locale = Locale(identifier: "en_US")
  774. nextDateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  775. let nextDateString = dateFormatter.date(from: nextStrippedZone)
  776. let nextDateTimeStamp = nextDateString!.timeIntervalSince1970
  777. if nextDateTimeStamp < (dateTimeStamp + (duration * 60)) {
  778. lastEndDot = nextDateTimeStamp
  779. }
  780. }
  781. let endDot = basalGraphStruct(basalRate: basalRate, date: Double(lastEndDot))
  782. basalData.append(endDot)
  783. }
  784. // If last basal was prior to right now, we need to create one last scheduled entry
  785. if lastEndDot <= dateTimeUtils.getNowTimeIntervalUTC() {
  786. var scheduled = 0.0
  787. // cycle through basal profiles.
  788. // TODO figure out how to deal with profile changes that happen mid-gap
  789. for b in 0..<self.basalProfile.count {
  790. let scheduleTimeYesterday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightYesterday()
  791. let scheduleTimeToday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightToday()
  792. // check the prior temp ending to the profile seconds from midnight
  793. print("yesterday " + String(scheduleTimeYesterday))
  794. print("today " + String(scheduleTimeToday))
  795. if lastEndDot >= scheduleTimeToday {
  796. scheduled = basalProfile[b].value
  797. }
  798. }
  799. latestBasal = String(format:"%.2f", scheduled)
  800. // Make the starting dot at the last ending dot
  801. let startDot = basalGraphStruct(basalRate: scheduled, date: Double(lastEndDot))
  802. basalData.append(startDot)
  803. // Make the ending dot 10 minutes after now
  804. let endDot = basalGraphStruct(basalRate: scheduled, date: Double(Date().timeIntervalSince1970 + (60 * 10)))
  805. basalData.append(endDot)
  806. }
  807. tableData[2].value = latestBasal
  808. if UserDefaultsRepository.graphBasal.value {
  809. updateBasalGraph()
  810. }
  811. }
  812. // NS Bolus Web Call
  813. func webLoadNSBoluses(){
  814. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: Bolus") }
  815. if !UserDefaultsRepository.downloadBolus.value { return }
  816. let yesterdayString = dateTimeUtils.nowMinus24HoursTimeInterval()
  817. let urlUser = UserDefaultsRepository.url.value
  818. var searchString = "find[eventType]=Correction%20Bolus&find[created_at][$gte]=" + yesterdayString
  819. var urlDataPath: String = urlUser + "/api/v1/treatments.json?"
  820. if token == "" {
  821. urlDataPath = urlDataPath + searchString
  822. }
  823. else
  824. {
  825. urlDataPath = urlDataPath + "token=" + token + "&" + searchString
  826. }
  827. guard let urlData = URL(string: urlDataPath) else {
  828. return
  829. }
  830. var request = URLRequest(url: urlData)
  831. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  832. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  833. guard error == nil else {
  834. return
  835. }
  836. guard let data = data else {
  837. return
  838. }
  839. let json = try? (JSONSerialization.jsonObject(with: data) as? [[String:AnyObject]])
  840. if let json = json {
  841. DispatchQueue.main.async {
  842. self.processNSBolus(entries: json)
  843. }
  844. } else {
  845. return
  846. }
  847. }
  848. task.resume()
  849. }
  850. // NS Meal Bolus Response Processor
  851. func processNSBolus(entries: [[String:AnyObject]]) {
  852. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Bolus") }
  853. // because it's a small array, we're going to destroy and reload every time.
  854. bolusData.removeAll()
  855. var lastFoundIndex = 0
  856. for i in 0..<entries.count {
  857. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  858. var bolusDate: String
  859. if currentEntry?["timestamp"] != nil {
  860. bolusDate = currentEntry?["timestamp"] as! String
  861. } else if currentEntry?["created_at"] != nil {
  862. bolusDate = currentEntry?["created_at"] as! String
  863. } else {
  864. return
  865. }
  866. let strippedZone = String(bolusDate.dropLast())
  867. let dateFormatter = DateFormatter()
  868. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  869. dateFormatter.locale = Locale(identifier: "en_US")
  870. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  871. let dateString = dateFormatter.date(from: strippedZone)
  872. let dateTimeStamp = dateString!.timeIntervalSince1970
  873. do {
  874. let bolus = try currentEntry?["insulin"] as! Double
  875. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  876. lastFoundIndex = sgv.foundIndex
  877. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  878. // Make the dot
  879. let dot = bolusCarbGraphStruct(value: bolus, date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  880. bolusData.append(dot)
  881. }
  882. } catch {
  883. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: Null Bolus") }
  884. }
  885. }
  886. if UserDefaultsRepository.graphBolus.value {
  887. updateBolusGraph()
  888. }
  889. }
  890. // NS Carb Web Call
  891. func webLoadNSCarbs(){
  892. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: Carbs") }
  893. if !UserDefaultsRepository.downloadCarbs.value { return }
  894. let yesterdayString = dateTimeUtils.nowMinus24HoursTimeInterval()
  895. let urlUser = UserDefaultsRepository.url.value
  896. var searchString = "find[eventType]=Meal%20Bolus&find[created_at][$gte]=" + yesterdayString
  897. var urlDataPath: String = urlUser + "/api/v1/treatments.json?"
  898. if token == "" {
  899. urlDataPath = urlDataPath + searchString
  900. }
  901. else
  902. {
  903. urlDataPath = urlDataPath + "token=" + token + "&" + searchString
  904. }
  905. guard let urlData = URL(string: urlDataPath) else {
  906. return
  907. }
  908. var request = URLRequest(url: urlData)
  909. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  910. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  911. guard error == nil else {
  912. return
  913. }
  914. guard let data = data else {
  915. return
  916. }
  917. let json = try? (JSONSerialization.jsonObject(with: data) as? [[String:AnyObject]])
  918. if let json = json {
  919. DispatchQueue.main.async {
  920. self.processNSCarbs(entries: json)
  921. }
  922. } else {
  923. return
  924. }
  925. }
  926. task.resume()
  927. }
  928. // NS Carb Bolus Response Processor
  929. func processNSCarbs(entries: [[String:AnyObject]]) {
  930. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Carbs") }
  931. // because it's a small array, we're going to destroy and reload every time.
  932. carbData.removeAll()
  933. var lastFoundIndex = 0
  934. for i in 0..<entries.count {
  935. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  936. var carbDate: String
  937. if currentEntry?["timestamp"] != nil {
  938. carbDate = currentEntry?["timestamp"] as! String
  939. } else if currentEntry?["created_at"] != nil {
  940. carbDate = currentEntry?["created_at"] as! String
  941. } else {
  942. return
  943. }
  944. let strippedZone = String(carbDate.dropLast())
  945. let dateFormatter = DateFormatter()
  946. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  947. dateFormatter.locale = Locale(identifier: "en_US")
  948. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  949. let dateString = dateFormatter.date(from: strippedZone)
  950. let dateTimeStamp = dateString!.timeIntervalSince1970
  951. do {
  952. let carbs = try currentEntry?["carbs"] as! Double
  953. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  954. lastFoundIndex = sgv.foundIndex
  955. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  956. // Make the dot
  957. let dot = bolusCarbGraphStruct(value: carbs, date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  958. carbData.append(dot)
  959. }
  960. } catch {
  961. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: Null Carb entry") }
  962. }
  963. }
  964. if UserDefaultsRepository.graphCarbs.value {
  965. updateCarbGraph()
  966. }
  967. }
  968. }