NightScout.swift 60 KB

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