NightScout.swift 58 KB

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