NightScout.swift 83 KB

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