NightScout.swift 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009
  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 600
  294. // First time a user starts a G7, they get a value of 4000
  295. if sgvValue > 600 {
  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 sgvValue = Int(round(prediction[i]))
  507. // Skip values higher than 600
  508. if sgvValue <= 600 {
  509. let prediction = ShareGlucoseData(sgv: sgvValue, date: predictionTime, direction: "flat")
  510. predictionData.append(prediction)
  511. }
  512. predictionTime += 300
  513. }
  514. i += 1
  515. }
  516. let predMin = prediction.min()
  517. let predMax = prediction.max()
  518. tableData[9].value = bgUnits.toDisplayUnits(String(predMin!)) + "/" + bgUnits.toDisplayUnits(String(predMax!))
  519. updatePredictionGraph()
  520. }
  521. }
  522. if let recBolus = lastLoopRecord["recommendedBolus"] as? Double {
  523. tableData[8].value = String(format:"%.2fU", recBolus)
  524. }
  525. if let loopStatus = lastLoopRecord["recommendedTempBasal"] as? [String:AnyObject] {
  526. if let tempBasalTime = formatter.date(from: (loopStatus["timestamp"] as! String))?.timeIntervalSince1970 {
  527. var lastBGTime = lastLoopTime
  528. if bgData.count > 0 {
  529. lastBGTime = bgData[bgData.count - 1].date
  530. }
  531. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "tempBasalTime: " + String(tempBasalTime)) }
  532. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "lastBGTime: " + String(lastBGTime)) }
  533. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "wasEnacted: " + String(wasEnacted)) }
  534. if tempBasalTime > lastBGTime && !wasEnacted {
  535. LoopStatusLabel.text = "⏀"
  536. latestLoopStatusString = "⏀"
  537. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Open Loop: recommended temp. temp time > bg time, was not enacted") }
  538. } else {
  539. LoopStatusLabel.text = "↻"
  540. latestLoopStatusString = "↻"
  541. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Looping: recommended temp, but temp time is < bg time and/or was enacted") }
  542. }
  543. }
  544. } else {
  545. LoopStatusLabel.text = "↻"
  546. latestLoopStatusString = "↻"
  547. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Looping: no recommended temp") }
  548. }
  549. }
  550. if ((TimeInterval(Date().timeIntervalSince1970) - lastLoopTime) / 60) > 15 {
  551. LoopStatusLabel.text = "⚠"
  552. latestLoopStatusString = "⚠"
  553. }
  554. latestLoopTime = lastLoopTime
  555. } // end lastLoopTime
  556. } // end lastLoop Record
  557. if let lastLoopRecord = lastDeviceStatus?["openaps"] as! [String : AnyObject]? {
  558. if let lastLoopTime = formatter.date(from: (lastDeviceStatus?["created_at"] as! String))?.timeIntervalSince1970 {
  559. UserDefaultsRepository.alertLastLoopTime.value = lastLoopTime
  560. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "lastLoopTime: " + String(lastLoopTime)) }
  561. if let failure = lastLoopRecord["failureReason"] {
  562. LoopStatusLabel.text = "X"
  563. latestLoopStatusString = "X"
  564. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Loop Failure: X") }
  565. } else {
  566. var wasEnacted = false
  567. if let enacted = lastLoopRecord["enacted"] as? [String:AnyObject] {
  568. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Loop: Was Enacted") }
  569. wasEnacted = true
  570. if let lastTempBasal = enacted["rate"] as? Double {
  571. }
  572. }
  573. if let iobdata = lastLoopRecord["iob"] as? [String:AnyObject] {
  574. tableData[0].value = String(format:"%.2f", (iobdata["iob"] as! Double))
  575. latestIOB = String(format:"%.2f", (iobdata["iob"] as! Double))
  576. }
  577. if let cobdata = lastLoopRecord["enacted"] as? [String:AnyObject] {
  578. tableData[1].value = String(format:"%.1f", cobdata["COB"] as! Double)
  579. latestCOB = String(format:"%.1f", cobdata["COB"] as! Double)
  580. }
  581. if let recbolusdata = lastLoopRecord["enacted"] as? [String:AnyObject] {
  582. tableData[8].value = String(format:"%.2fU", recbolusdata["insulinReq"] as! Double)
  583. }
  584. if let autosensdata = lastLoopRecord["enacted"] as? [String:AnyObject] {
  585. let sens = autosensdata["sensitivityRatio"] as! Double * 100.0
  586. tableData[11].value = String(format:"%.0f", sens) + "%"
  587. }
  588. //Picks COB prediction if available, else UAM, else IOB, else ZT
  589. //Ideal is to predict all 4 in Loop Follow but this is a quick start
  590. var graphtype = ""
  591. var predictioncolor = UIColor.systemGray
  592. PredictionLabel.textColor = predictioncolor
  593. if let enactdata = lastLoopRecord["enacted"] as? [String:AnyObject] {
  594. if let predbgdata = enactdata["predBGs"] as? [String:AnyObject] {
  595. if predbgdata["COB"] != nil {
  596. graphtype="COB"
  597. predictioncolor = UIColor.systemYellow
  598. PredictionLabel.textColor = predictioncolor
  599. }
  600. else if predbgdata["UAM"] != nil {
  601. graphtype="UAM"
  602. predictioncolor = UIColor.systemOrange
  603. PredictionLabel.textColor = predictioncolor
  604. }
  605. else if predbgdata["IOB"] != nil {
  606. graphtype="IOB"
  607. predictioncolor = UIColor.systemBlue
  608. PredictionLabel.textColor = predictioncolor
  609. }
  610. else {
  611. graphtype="ZT"
  612. predictioncolor = UIColor.systemGreen
  613. PredictionLabel.textColor = predictioncolor
  614. }
  615. let graphdata = predbgdata[graphtype] as! [Double]
  616. if let eventualdata = lastLoopRecord["enacted"] as? [String:AnyObject] {
  617. PredictionLabel.text = String(format:"%.0f", eventualdata["eventualBG"] as! Double)
  618. }
  619. if UserDefaultsRepository.downloadPrediction.value && latestLoopTime < lastLoopTime {
  620. predictionData.removeAll()
  621. var predictionTime = lastLoopTime
  622. let toLoad = Int(UserDefaultsRepository.predictionToLoad.value * 12)
  623. var i = 0
  624. while i <= toLoad {
  625. if i < graphdata.count {
  626. let prediction = ShareGlucoseData(sgv: Int(round(graphdata[i])), date: predictionTime, direction: "flat")
  627. predictionData.append(prediction)
  628. predictionTime += 300
  629. }
  630. i += 1
  631. }
  632. }
  633. let predMin = graphdata.min()
  634. let predMax = graphdata.max()
  635. tableData[9].value = bgUnits.toDisplayUnits(String(predMin!)) + "/" + bgUnits.toDisplayUnits(String(predMax!))
  636. updatePredictionGraph(color: predictioncolor)
  637. }
  638. }
  639. if let loopStatus = lastLoopRecord["recommendedTempBasal"] as? [String:AnyObject] {
  640. if let tempBasalTime = formatter.date(from: (loopStatus["timestamp"] as! String))?.timeIntervalSince1970 {
  641. var lastBGTime = lastLoopTime
  642. if bgData.count > 0 {
  643. lastBGTime = bgData[bgData.count - 1].date
  644. }
  645. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "tempBasalTime: " + String(tempBasalTime)) }
  646. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "lastBGTime: " + String(lastBGTime)) }
  647. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "wasEnacted: " + String(wasEnacted)) }
  648. if tempBasalTime > lastBGTime && !wasEnacted {
  649. LoopStatusLabel.text = "⏀"
  650. latestLoopStatusString = "⏀"
  651. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Open Loop: recommended temp. temp time > bg time, was not enacted") }
  652. } else {
  653. LoopStatusLabel.text = "↻"
  654. latestLoopStatusString = "↻"
  655. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Looping: recommended temp, but temp time is < bg time and/or was enacted") }
  656. }
  657. }
  658. } else {
  659. LoopStatusLabel.text = "↻"
  660. latestLoopStatusString = "↻"
  661. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Looping: no recommended temp") }
  662. }
  663. }
  664. if ((TimeInterval(Date().timeIntervalSince1970) - lastLoopTime) / 60) > 15 {
  665. LoopStatusLabel.text = "⚠"
  666. latestLoopStatusString = "⚠"
  667. }
  668. latestLoopTime = lastLoopTime
  669. }
  670. }
  671. var oText = "" as String
  672. currentOverride = 1.0
  673. if let lastOverride = lastDeviceStatus?["override"] as! [String : AnyObject]? {
  674. if lastOverride["active"] as! Bool {
  675. let lastCorrection = lastOverride["currentCorrectionRange"] as! [String: AnyObject]
  676. if let multiplier = lastOverride["multiplier"] as? Double {
  677. currentOverride = multiplier
  678. oText += String(format: "%.0f%%", (multiplier * 100))
  679. }
  680. else
  681. {
  682. oText += "100%"
  683. }
  684. oText += " ("
  685. let minValue = lastCorrection["minValue"] as! Double
  686. let maxValue = lastCorrection["maxValue"] as! Double
  687. oText += bgUnits.toDisplayUnits(String(minValue)) + "-" + bgUnits.toDisplayUnits(String(maxValue)) + ")"
  688. tableData[3].value = oText
  689. }
  690. }
  691. infoTable.reloadData()
  692. // Start the timer based on the timestamp
  693. let now = dateTimeUtils.getNowTimeIntervalUTC()
  694. let secondsAgo = now - latestLoopTime
  695. DispatchQueue.main.async {
  696. // if Loop is overdue over: 20:00, re-attempt every 5 minutes
  697. if secondsAgo >= (20 * 60) {
  698. self.startDeviceStatusTimer(time: (5 * 60))
  699. print("started 5 minute device status timer")
  700. // if the Loop is overdue: 10:00-19:59, re-attempt every minute
  701. } else if secondsAgo >= (10 * 60) {
  702. self.startDeviceStatusTimer(time: 60)
  703. print("started 1 minute device status timer")
  704. // if the Loop is overdue: 7:00-9:59, re-attempt every 30 seconds
  705. } else if secondsAgo >= (7 * 60) {
  706. self.startDeviceStatusTimer(time: 30)
  707. print("started 30 second device status timer")
  708. // if the Loop is overdue: 5:00-6:59 re-attempt every 10 seconds
  709. } else if secondsAgo >= (5 * 60) {
  710. self.startDeviceStatusTimer(time: 10)
  711. print("started 10 second device status timer")
  712. // We have a current Loop. Set timer to 5:10 from last reading
  713. } else {
  714. self.startDeviceStatusTimer(time: 310 - secondsAgo)
  715. let timerVal = 310 - secondsAgo
  716. print("started 5:10 device status timer: \(timerVal)")
  717. }
  718. }
  719. }
  720. // NS Carbs Today Web Call
  721. func webLoadNSCarbsToday() {
  722. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: Carbs Today") }
  723. let urlUser = UserDefaultsRepository.url.value
  724. let now = Date()
  725. let timeZone = TimeZone.current
  726. var calendar = Calendar(identifier: .gregorian)
  727. calendar.timeZone = timeZone
  728. var dateComponents = calendar.dateComponents(in: timeZone, from: now)
  729. dateComponents.hour = 0
  730. dateComponents.minute = 0
  731. dateComponents.second = 0
  732. guard let date = dateComponents.date else { fatalError("Invalid date components") }
  733. let dateFormatter = DateFormatter()
  734. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
  735. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  736. let utcDateString = dateFormatter.string(from: date)
  737. var urlString = urlUser + "/api/v1/treatments.json?count=1000&find[eventType]=Carb+Correction&find[created_at][$gte]=" + utcDateString
  738. if token != "" {
  739. urlString = urlUser + "/api/v1/treatments.json?token=" + token + "&count=1000&find[eventType]=Carb+Correction&find[created_at][$gte]=" + utcDateString
  740. }
  741. guard let urlData = URL(string: urlString) else {
  742. return
  743. }
  744. var request = URLRequest(url: urlData)
  745. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  746. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  747. guard error == nil else {
  748. return
  749. }
  750. guard let data = data else {
  751. return
  752. }
  753. let decoder = JSONDecoder()
  754. print("*** \(data)")
  755. let entriesResponse = try? decoder.decode([carbsData].self, from: data)
  756. if let entriesResponse = entriesResponse {
  757. DispatchQueue.main.async {
  758. self.updateCarbsToday(data: entriesResponse)
  759. }
  760. } else {
  761. return
  762. }
  763. }
  764. task.resume()
  765. }
  766. // NS CarbsToday Response Processor
  767. func updateCarbsToday(data: [carbsData]) {
  768. self.clearLastInfoData(index: 10)
  769. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: carbs") }
  770. if data.count == 0 {
  771. return
  772. }
  773. let totalCarbs = data.reduce(0.0) { $0 + ($1.carbs ?? 0.0) }
  774. let resultString = String(format: "%.0f", totalCarbs)
  775. tableData[10].value = resultString
  776. infoTable.reloadData()
  777. }
  778. // NS Cage Web Call
  779. func webLoadNSCage() {
  780. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: CAGE") }
  781. let urlUser = UserDefaultsRepository.url.value
  782. var urlString = urlUser + "/api/v1/treatments.json?find[eventType]=Site%20Change&count=1"
  783. if token != "" {
  784. urlString = urlUser + "/api/v1/treatments.json?token=" + token + "&find[eventType]=Site%20Change&count=1"
  785. }
  786. guard let urlData = URL(string: urlString) else {
  787. return
  788. }
  789. var request = URLRequest(url: urlData)
  790. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  791. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  792. guard error == nil else {
  793. return
  794. }
  795. guard let data = data else {
  796. return
  797. }
  798. let decoder = JSONDecoder()
  799. let entriesResponse = try? decoder.decode([cageData].self, from: data)
  800. if let entriesResponse = entriesResponse {
  801. DispatchQueue.main.async {
  802. self.updateCage(data: entriesResponse)
  803. }
  804. } else {
  805. return
  806. }
  807. }
  808. task.resume()
  809. }
  810. // NS Cage Response Processor
  811. func updateCage(data: [cageData]) {
  812. self.clearLastInfoData(index: 7)
  813. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: CAGE") }
  814. if data.count == 0 {
  815. return
  816. }
  817. let lastCageString = data[0].created_at
  818. let formatter = ISO8601DateFormatter()
  819. formatter.formatOptions = [.withFullDate,
  820. .withTime,
  821. .withDashSeparatorInDate,
  822. .withColonSeparatorInTime]
  823. UserDefaultsRepository.alertCageInsertTime.value = formatter.date(from: (lastCageString))?.timeIntervalSince1970 as! TimeInterval
  824. if let cageTime = formatter.date(from: (lastCageString))?.timeIntervalSince1970 {
  825. let now = dateTimeUtils.getNowTimeIntervalUTC()
  826. let secondsAgo = now - cageTime
  827. //let days = 24 * 60 * 60
  828. let formatter = DateComponentsFormatter()
  829. formatter.unitsStyle = .positional // Use the appropriate positioning for the current locale
  830. formatter.allowedUnits = [ .day, .hour ] // Units to display in the formatted string
  831. formatter.zeroFormattingBehavior = [ .pad ] // Pad with zeroes where appropriate for the locale
  832. let formattedDuration = formatter.string(from: secondsAgo)
  833. tableData[7].value = formattedDuration ?? ""
  834. }
  835. infoTable.reloadData()
  836. }
  837. // NS Sage Web Call
  838. func webLoadNSSage() {
  839. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: SAGE") }
  840. let lastDateString = dateTimeUtils.nowMinus10DaysTimeInterval()
  841. let urlUser = UserDefaultsRepository.url.value
  842. var urlString = urlUser + "/api/v1/treatments.json?find[eventType]=Sensor%20Start&find[created_at][$gte]=" + lastDateString + "&count=1"
  843. if token != "" {
  844. urlString = urlUser + "/api/v1/treatments.json?token=" + token + "&find[eventType]=Sensor%20Start&find[created_at][$gte]=" + lastDateString + "&count=1"
  845. }
  846. guard let urlData = URL(string: urlString) else {
  847. return
  848. }
  849. var request = URLRequest(url: urlData)
  850. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  851. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  852. guard error == nil else {
  853. return
  854. }
  855. guard let data = data else {
  856. return
  857. }
  858. let decoder = JSONDecoder()
  859. let entriesResponse = try? decoder.decode([cageData].self, from: data)
  860. if let entriesResponse = entriesResponse {
  861. DispatchQueue.main.async {
  862. self.updateSage(data: entriesResponse)
  863. }
  864. } else {
  865. return
  866. }
  867. }
  868. task.resume()
  869. }
  870. // NS Sage Response Processor
  871. func updateSage(data: [cageData]) {
  872. self.clearLastInfoData(index: 6)
  873. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process/Display: SAGE") }
  874. if data.count == 0 {
  875. return
  876. }
  877. var lastSageString = data[0].created_at
  878. let formatter = ISO8601DateFormatter()
  879. formatter.formatOptions = [.withFullDate,
  880. .withTime,
  881. .withDashSeparatorInDate,
  882. .withColonSeparatorInTime]
  883. UserDefaultsRepository.alertSageInsertTime.value = formatter.date(from: (lastSageString))?.timeIntervalSince1970 as! TimeInterval
  884. if UserDefaultsRepository.alertAutoSnoozeCGMStart.value && (dateTimeUtils.getNowTimeIntervalUTC() - UserDefaultsRepository.alertSageInsertTime.value < 7200){
  885. let snoozeTime = Date(timeIntervalSince1970: UserDefaultsRepository.alertSageInsertTime.value + 7200)
  886. UserDefaultsRepository.alertSnoozeAllTime.value = snoozeTime
  887. UserDefaultsRepository.alertSnoozeAllIsSnoozed.value = true
  888. guard let alarms = self.tabBarController!.viewControllers?[1] as? AlarmViewController else { return }
  889. alarms.reloadIsSnoozed(key: "alertSnoozeAllIsSnoozed", value: true)
  890. alarms.reloadSnoozeTime(key: "alertSnoozeAllTime", setNil: false, value: snoozeTime)
  891. }
  892. if let sageTime = formatter.date(from: (lastSageString as! String))?.timeIntervalSince1970 {
  893. let now = dateTimeUtils.getNowTimeIntervalUTC()
  894. let secondsAgo = now - sageTime
  895. let days = 24 * 60 * 60
  896. let formatter = DateComponentsFormatter()
  897. formatter.unitsStyle = .positional // Use the appropriate positioning for the current locale
  898. formatter.allowedUnits = [ .day, .hour] // Units to display in the formatted string
  899. formatter.zeroFormattingBehavior = [ .pad ] // Pad with zeroes where appropriate for the locale
  900. let formattedDuration = formatter.string(from: secondsAgo)
  901. tableData[6].value = formattedDuration ?? ""
  902. }
  903. infoTable.reloadData()
  904. }
  905. // NS Profile Web Call
  906. func webLoadNSProfile() {
  907. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: profile") }
  908. let urlUser = UserDefaultsRepository.url.value
  909. var urlString = urlUser + "/api/v1/profile/current.json"
  910. if token != "" {
  911. urlString = urlUser + "/api/v1/profile/current.json?token=" + token
  912. }
  913. let escapedAddress = urlString.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
  914. guard let url = URL(string: escapedAddress!) else {
  915. return
  916. }
  917. var request = URLRequest(url: url)
  918. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  919. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  920. guard error == nil else {
  921. return
  922. }
  923. guard let data = data else {
  924. return
  925. }
  926. let json = try? JSONSerialization.jsonObject(with: data) as! Dictionary<String, Any>
  927. if let json = json {
  928. DispatchQueue.main.async {
  929. self.updateProfile(jsonDeviceStatus: json)
  930. }
  931. } else {
  932. return
  933. }
  934. }
  935. task.resume()
  936. }
  937. // NS Profile Response Processor
  938. func updateProfile(jsonDeviceStatus: Dictionary<String, Any>) {
  939. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: profile") }
  940. if jsonDeviceStatus.count == 0 {
  941. return
  942. }
  943. if jsonDeviceStatus[keyPath: "message"] != nil { return }
  944. if let basal = jsonDeviceStatus[keyPath: "store.default.basal"] as? NSArray ?? jsonDeviceStatus[keyPath: "store.Default.basal"] as? NSArray {
  945. basalProfile.removeAll()
  946. for i in 0..<basal.count {
  947. let dict = basal[i] as! Dictionary<String, Any>
  948. do {
  949. let thisValue = try dict[keyPath: "value"] as! Double
  950. let thisTime = dict[keyPath: "time"] as! String
  951. let thisTimeAsSeconds = dict[keyPath: "timeAsSeconds"] as! Double
  952. let entry = basalProfileStruct(value: thisValue, time: thisTime, timeAsSeconds: thisTimeAsSeconds)
  953. basalProfile.append(entry)
  954. } catch {
  955. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: profile wrapped in quotes") }
  956. }
  957. }
  958. }
  959. // Don't process the basal or draw the graph until after the BG has been fully processeed and drawn
  960. if firstGraphLoad { return }
  961. var basalSegments: [DataStructs.basalProfileSegment] = []
  962. let graphHours = 24 * UserDefaultsRepository.downloadDays.value
  963. // Build scheduled basal segments from right to left by
  964. // moving pointers to the current midnight and current basal
  965. var midnight = dateTimeUtils.getTimeIntervalMidnightToday()
  966. var basalProfileIndex = basalProfile.count - 1
  967. var start = midnight + basalProfile[basalProfileIndex].timeAsSeconds
  968. var end = dateTimeUtils.getNowTimeIntervalUTC()
  969. // Move back until we're in the graph range
  970. while start > end {
  971. basalProfileIndex -= 1
  972. start = midnight + basalProfile[basalProfileIndex].timeAsSeconds
  973. }
  974. // Add records while they're still within the graph
  975. let graphStart = dateTimeUtils.getTimeIntervalNHoursAgo(N: graphHours)
  976. while end >= graphStart {
  977. let entry = DataStructs.basalProfileSegment(
  978. basalRate: basalProfile[basalProfileIndex].value, startDate: start, endDate: end)
  979. basalSegments.append(entry)
  980. basalProfileIndex -= 1
  981. if basalProfileIndex < 0 {
  982. basalProfileIndex = basalProfile.count - 1
  983. midnight = midnight.advanced(by: -24*60*60)
  984. }
  985. end = start - 1
  986. start = midnight + basalProfile[basalProfileIndex].timeAsSeconds
  987. }
  988. // reverse the result to get chronological order
  989. basalSegments.reverse()
  990. var firstPass = true
  991. // Runs the scheduled basal to the end of the prediction line
  992. var predictionEndTime = dateTimeUtils.getNowTimeIntervalUTC() + (3600 * UserDefaultsRepository.predictionToLoad.value)
  993. basalScheduleData.removeAll()
  994. for i in 0..<basalSegments.count {
  995. let timeStart = dateTimeUtils.getTimeIntervalNHoursAgo(N: graphHours)
  996. // This processed everything after the first one.
  997. if firstPass == false
  998. && basalSegments[i].startDate <= predictionEndTime {
  999. let startDot = basalGraphStruct(basalRate: basalSegments[i].basalRate, date: basalSegments[i].startDate)
  1000. basalScheduleData.append(startDot)
  1001. var endDate = basalSegments[i].endDate
  1002. // if it's the last one needed, set it to end at the prediction end time
  1003. if endDate > predictionEndTime || i == basalSegments.count - 1 {
  1004. endDate = Double(predictionEndTime)
  1005. }
  1006. let endDot = basalGraphStruct(basalRate: basalSegments[i].basalRate, date: endDate)
  1007. basalScheduleData.append(endDot)
  1008. }
  1009. // we need to manually set the first one
  1010. // Check that this is the first one and there are no existing entries
  1011. if firstPass == true {
  1012. // check that the timestamp is > the current entry and < the next entry
  1013. if timeStart >= basalSegments[i].startDate && timeStart < basalSegments[i].endDate {
  1014. // Set the start time to match the BG start
  1015. let startDot = basalGraphStruct(basalRate: basalSegments[i].basalRate, date: Double(timeStart + (60 * 5)))
  1016. basalScheduleData.append(startDot)
  1017. // set the enddot where the next one will start
  1018. var endDate = basalSegments[i].endDate
  1019. let endDot = basalGraphStruct(basalRate: basalSegments[i].basalRate, date: endDate)
  1020. basalScheduleData.append(endDot)
  1021. firstPass = false
  1022. }
  1023. }
  1024. }
  1025. if UserDefaultsRepository.graphBasal.value {
  1026. updateBasalScheduledGraph()
  1027. }
  1028. }
  1029. // NS Treatments Web Call
  1030. // Downloads Basal, Bolus, Carbs, BG Check, Notes, Overrides
  1031. func WebLoadNSTreatments() {
  1032. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: Treatments") }
  1033. if !UserDefaultsRepository.downloadTreatments.value { return }
  1034. let graphHours = 24 * UserDefaultsRepository.downloadDays.value
  1035. let startTimeString = dateTimeUtils.nowMinusNHoursTimeInterval(N: graphHours)
  1036. var urlString = UserDefaultsRepository.url.value + "/api/v1/treatments.json?find[created_at][$gte]=" + startTimeString
  1037. if token != "" {
  1038. urlString = UserDefaultsRepository.url.value + "/api/v1/treatments.json?token=" + token + "&find[created_at][$gte]=" + startTimeString
  1039. }
  1040. guard let urlData = URL(string: urlString) else {
  1041. return
  1042. }
  1043. var request = URLRequest(url: urlData)
  1044. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  1045. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  1046. guard error == nil else {
  1047. return
  1048. }
  1049. guard let data = data else {
  1050. return
  1051. }
  1052. let json = try? (JSONSerialization.jsonObject(with: data) as? [[String:AnyObject]])
  1053. if let json = json {
  1054. DispatchQueue.main.async {
  1055. self.updateTreatments(entries: json)
  1056. }
  1057. } else {
  1058. return
  1059. }
  1060. }
  1061. task.resume()
  1062. }
  1063. // Process and split out treatments to individual tasks
  1064. func updateTreatments(entries: [[String:AnyObject]]) {
  1065. var tempBasal: [[String:AnyObject]] = []
  1066. var bolus: [[String:AnyObject]] = []
  1067. var carbs: [[String:AnyObject]] = []
  1068. var temporaryOverride: [[String:AnyObject]] = []
  1069. var note: [[String:AnyObject]] = []
  1070. var bgCheck: [[String:AnyObject]] = []
  1071. var suspendPump: [[String:AnyObject]] = []
  1072. var resumePump: [[String:AnyObject]] = []
  1073. var pumpSiteChange: [[String:AnyObject]] = []
  1074. var cgmSensorStart: [[String:AnyObject]] = []
  1075. for i in 0..<entries.count {
  1076. let entry = entries[i] as [String : AnyObject]?
  1077. switch entry?["eventType"] as! String {
  1078. case "Temp Basal":
  1079. tempBasal.append(entry!)
  1080. case "Correction Bolus":
  1081. bolus.append(entry!)
  1082. case "Bolus":
  1083. bolus.append(entry!)
  1084. case "Meal Bolus":
  1085. carbs.append(entry!)
  1086. bolus.append(entry!)
  1087. case "Carb Correction":
  1088. carbs.append(entry!)
  1089. case "Temporary Override":
  1090. temporaryOverride.append(entry!)
  1091. case "Temporary Target":
  1092. temporaryOverride.append(entry!)
  1093. case "Note":
  1094. note.append(entry!)
  1095. print("Note: \(String(describing: entry))")
  1096. case "BG Check":
  1097. bgCheck.append(entry!)
  1098. case "Suspend Pump":
  1099. suspendPump.append(entry!)
  1100. case "Resume Pump":
  1101. resumePump.append(entry!)
  1102. case "Pump Site Change":
  1103. pumpSiteChange.append(entry!)
  1104. case "Sensor Start":
  1105. cgmSensorStart.append(entry!)
  1106. default:
  1107. print("No Match: \(String(describing: entry))")
  1108. }
  1109. }
  1110. // end of for loop
  1111. if tempBasal.count > 0 {
  1112. processNSBasals(entries: tempBasal)
  1113. } else {
  1114. if basalData.count < 0 {
  1115. clearOldTempBasal()
  1116. }
  1117. }
  1118. if bolus.count > 0 {
  1119. processNSBolus(entries: bolus)
  1120. } else {
  1121. if bolusData.count > 0 {
  1122. clearOldBolus()
  1123. }
  1124. }
  1125. if carbs.count > 0 {
  1126. processNSCarbs(entries: carbs)
  1127. } else {
  1128. if carbData.count > 0 {
  1129. clearOldCarb()
  1130. }
  1131. }
  1132. if bgCheck.count > 0 {
  1133. processNSBGCheck(entries: bgCheck)
  1134. } else {
  1135. if bgCheckData.count > 0 {
  1136. clearOldBGCheck()
  1137. }
  1138. }
  1139. if temporaryOverride.count > 0 {
  1140. processNSOverrides(entries: temporaryOverride)
  1141. } else {
  1142. if overrideGraphData.count > 0 {
  1143. clearOldOverride()
  1144. }
  1145. }
  1146. if suspendPump.count > 0 {
  1147. processSuspendPump(entries: suspendPump)
  1148. } else {
  1149. if suspendGraphData.count > 0 {
  1150. clearOldSuspend()
  1151. }
  1152. }
  1153. if resumePump.count > 0 {
  1154. processResumePump(entries: resumePump)
  1155. } else {
  1156. if resumeGraphData.count > 0 {
  1157. clearOldResume()
  1158. }
  1159. }
  1160. if cgmSensorStart.count > 0 {
  1161. processSensorStart(entries: cgmSensorStart)
  1162. } else {
  1163. if sensorStartGraphData.count > 0 {
  1164. clearOldSensor()
  1165. }
  1166. }
  1167. if note.count > 0 {
  1168. processNotes(entries: note)
  1169. } else {
  1170. if noteGraphData.count > 0 {
  1171. clearOldNotes()
  1172. }
  1173. }
  1174. }
  1175. func clearOldTempBasal()
  1176. {
  1177. basalData.removeAll()
  1178. updateBasalGraph()
  1179. }
  1180. func clearOldBolus()
  1181. {
  1182. bolusData.removeAll()
  1183. updateBolusGraph()
  1184. }
  1185. func clearOldCarb()
  1186. {
  1187. carbData.removeAll()
  1188. updateCarbGraph()
  1189. }
  1190. func clearOldBGCheck()
  1191. {
  1192. bgCheckData.removeAll()
  1193. updateBGCheckGraph()
  1194. }
  1195. func clearOldOverride()
  1196. {
  1197. overrideGraphData.removeAll()
  1198. updateOverrideGraph()
  1199. }
  1200. func clearOldSuspend()
  1201. {
  1202. suspendGraphData.removeAll()
  1203. updateSuspendGraph()
  1204. }
  1205. func clearOldResume()
  1206. {
  1207. resumeGraphData.removeAll()
  1208. updateResumeGraph()
  1209. }
  1210. func clearOldSensor()
  1211. {
  1212. sensorStartGraphData.removeAll()
  1213. updateSensorStart()
  1214. }
  1215. func clearOldNotes()
  1216. {
  1217. noteGraphData.removeAll()
  1218. updateNotes()
  1219. }
  1220. // NS Temp Basal Response Processor
  1221. func processNSBasals(entries: [[String:AnyObject]]) {
  1222. self.clearLastInfoData(index: 2)
  1223. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Basal") }
  1224. // due to temp basal durations, we're going to destroy the array and load everything each cycle for the time being.
  1225. basalData.removeAll()
  1226. var lastEndDot = 0.0
  1227. var tempArray = entries
  1228. tempArray.reverse()
  1229. for i in 0..<tempArray.count {
  1230. let currentEntry = tempArray[i] as [String : AnyObject]?
  1231. var basalDate: String
  1232. if currentEntry?["timestamp"] != nil {
  1233. basalDate = currentEntry?["timestamp"] as! String
  1234. } else if currentEntry?["created_at"] != nil {
  1235. basalDate = currentEntry?["created_at"] as! String
  1236. } else {
  1237. continue
  1238. }
  1239. var strippedZone = String(basalDate.dropLast())
  1240. strippedZone = strippedZone.replacingOccurrences(of: "\\.\\d+", with: "", options: .regularExpression)
  1241. let dateFormatter = DateFormatter()
  1242. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1243. dateFormatter.locale = Locale(identifier: "en_US")
  1244. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1245. guard let dateString = dateFormatter.date(from: strippedZone) else { continue }
  1246. let dateTimeStamp = dateString.timeIntervalSince1970
  1247. guard let basalRate = currentEntry?["absolute"] as? Double else {
  1248. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: Null Basal entry")}
  1249. continue
  1250. }
  1251. let midnightTime = dateTimeUtils.getTimeIntervalMidnightToday()
  1252. // Setting end dots
  1253. var duration = 0.0
  1254. do {
  1255. duration = try currentEntry?["duration"] as! Double
  1256. } catch {
  1257. print("No Duration Found")
  1258. }
  1259. // 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
  1260. if i > 0 {
  1261. let priorEntry = tempArray[i - 1] as [String : AnyObject]?
  1262. var priorBasalDate: String
  1263. if priorEntry?["timestamp"] != nil {
  1264. priorBasalDate = priorEntry?["timestamp"] as! String
  1265. } else if currentEntry?["created_at"] != nil {
  1266. priorBasalDate = priorEntry?["created_at"] as! String
  1267. } else {
  1268. continue
  1269. }
  1270. var priorStrippedZone = String(priorBasalDate.dropLast())
  1271. priorStrippedZone = priorStrippedZone.replacingOccurrences(of: "\\.\\d+", with: "", options: .regularExpression)
  1272. let priorDateFormatter = DateFormatter()
  1273. priorDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1274. priorDateFormatter.locale = Locale(identifier: "en_US")
  1275. priorDateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1276. guard let priorDateString = dateFormatter.date(from: priorStrippedZone) else { continue }
  1277. let priorDateTimeStamp = priorDateString.timeIntervalSince1970
  1278. let priorDuration = priorEntry?["duration"] as? Double ?? 0.0
  1279. // 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
  1280. if Double( dateTimeStamp - priorDateTimeStamp ) > Double( (priorDuration * 60) + 15 ) {
  1281. var scheduled = 0.0
  1282. var midGap = false
  1283. var midGapTime: TimeInterval = 0
  1284. var midGapValue: Double = 0
  1285. // cycle through basal profiles.
  1286. // TODO figure out how to deal with profile changes that happen mid-gap
  1287. for b in 0..<self.basalScheduleData.count {
  1288. if (priorDateTimeStamp + (priorDuration * 60)) >= basalScheduleData[b].date {
  1289. scheduled = basalScheduleData[b].basalRate
  1290. // deal with mid-gap scheduled basal change
  1291. // don't do it on the last scheudled basal entry
  1292. if b < self.basalScheduleData.count - 1 {
  1293. if dateTimeStamp > self.basalScheduleData[b + 1].date {
  1294. // midGap = true
  1295. // TODO: finish this to handle mid-gap items without crashing from overlapping entries
  1296. midGapTime = self.basalScheduleData[b + 1].date
  1297. midGapValue = self.basalScheduleData[b + 1].basalRate
  1298. }
  1299. }
  1300. }
  1301. }
  1302. // Make the starting dot at the last ending dot
  1303. let startDot = basalGraphStruct(basalRate: scheduled, date: Double(priorDateTimeStamp + (priorDuration * 60)))
  1304. basalData.append(startDot)
  1305. if midGap {
  1306. // Make the ending dot at the new scheduled basal
  1307. let endDot1 = basalGraphStruct(basalRate: scheduled, date: Double(midGapTime))
  1308. basalData.append(endDot1)
  1309. // Make the starting dot at the scheduled Time
  1310. let startDot2 = basalGraphStruct(basalRate: midGapValue, date: Double(midGapTime))
  1311. basalData.append(startDot2)
  1312. // Make the ending dot at the new basal value
  1313. let endDot2 = basalGraphStruct(basalRate: midGapValue, date: Double(dateTimeStamp))
  1314. basalData.append(endDot2)
  1315. } else {
  1316. // Make the ending dot at the new starting dot
  1317. let endDot = basalGraphStruct(basalRate: scheduled, date: Double(dateTimeStamp))
  1318. basalData.append(endDot)
  1319. }
  1320. }
  1321. }
  1322. // Make the starting dot
  1323. let startDot = basalGraphStruct(basalRate: basalRate, date: Double(dateTimeStamp))
  1324. basalData.append(startDot)
  1325. // Make the ending dot
  1326. // If it's the last one and has no duration, extend it for 30 minutes past the start. Otherwise set ending at duration
  1327. // duration is already set to 0 if there is no duration set on it.
  1328. //if i == tempArray.count - 1 && dateTimeStamp + duration <= dateTimeUtils.getNowTimeIntervalUTC() {
  1329. if i == tempArray.count - 1 && duration == 0.0 {
  1330. lastEndDot = dateTimeStamp + (30 * 60)
  1331. latestBasal = String(format:"%.2f", basalRate)
  1332. } else {
  1333. lastEndDot = dateTimeStamp + (duration * 60)
  1334. latestBasal = String(format:"%.2f", basalRate)
  1335. }
  1336. // Double check for overlaps of incorrectly ended TBRs and sent it to end when the next one starts if it finds a discrepancy
  1337. if i < tempArray.count - 1 {
  1338. let nextEntry = tempArray[i + 1] as [String : AnyObject]?
  1339. var nextBasalDate: String
  1340. if nextEntry?["timestamp"] != nil {
  1341. nextBasalDate = nextEntry?["timestamp"] as! String
  1342. } else if currentEntry?["created_at"] != nil {
  1343. nextBasalDate = nextEntry?["created_at"] as! String
  1344. } else {
  1345. continue
  1346. }
  1347. var nextStrippedZone = String(nextBasalDate.dropLast())
  1348. nextStrippedZone = nextStrippedZone.replacingOccurrences(of: "\\.\\d+", with: "", options: .regularExpression)
  1349. let nextDateFormatter = DateFormatter()
  1350. nextDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1351. nextDateFormatter.locale = Locale(identifier: "en_US")
  1352. nextDateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1353. guard let nextDateString = dateFormatter.date(from: nextStrippedZone) else { continue }
  1354. let nextDateTimeStamp = nextDateString.timeIntervalSince1970
  1355. if nextDateTimeStamp < (dateTimeStamp + (duration * 60)) {
  1356. lastEndDot = nextDateTimeStamp
  1357. }
  1358. }
  1359. let endDot = basalGraphStruct(basalRate: basalRate, date: Double(lastEndDot))
  1360. basalData.append(endDot)
  1361. }
  1362. // If last basal was prior to right now, we need to create one last scheduled entry
  1363. if lastEndDot <= dateTimeUtils.getNowTimeIntervalUTC() {
  1364. var scheduled = 0.0
  1365. // cycle through basal profiles.
  1366. // TODO figure out how to deal with profile changes that happen mid-gap
  1367. for b in 0..<self.basalProfile.count {
  1368. let scheduleTimeYesterday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightYesterday()
  1369. let scheduleTimeToday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightToday()
  1370. // check the prior temp ending to the profile seconds from midnight
  1371. print("yesterday " + String(scheduleTimeYesterday))
  1372. print("today " + String(scheduleTimeToday))
  1373. if lastEndDot >= scheduleTimeToday {
  1374. scheduled = basalProfile[b].value
  1375. }
  1376. }
  1377. latestBasal = String(format:"%.2f", scheduled)
  1378. // Make the starting dot at the last ending dot
  1379. let startDot = basalGraphStruct(basalRate: scheduled, date: Double(lastEndDot))
  1380. basalData.append(startDot)
  1381. // Make the ending dot 10 minutes after now
  1382. let endDot = basalGraphStruct(basalRate: scheduled, date: Double(Date().timeIntervalSince1970 + (60 * 10)))
  1383. basalData.append(endDot)
  1384. }
  1385. tableData[2].value = latestBasal
  1386. infoTable.reloadData()
  1387. if UserDefaultsRepository.graphBasal.value {
  1388. updateBasalGraph()
  1389. }
  1390. infoTable.reloadData()
  1391. }
  1392. // NS Meal Bolus Response Processor
  1393. func processNSBolus(entries: [[String:AnyObject]]) {
  1394. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Bolus") }
  1395. // because it's a small array, we're going to destroy and reload every time.
  1396. bolusData.removeAll()
  1397. var lastFoundIndex = 0
  1398. for i in 0..<entries.count {
  1399. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1400. var bolusDate: String
  1401. if currentEntry?["timestamp"] != nil {
  1402. bolusDate = currentEntry?["timestamp"] as! String
  1403. } else if currentEntry?["created_at"] != nil {
  1404. bolusDate = currentEntry?["created_at"] as! String
  1405. } else {
  1406. continue
  1407. }
  1408. // fix to remove millisecond (after period in timestamp) for FreeAPS users
  1409. var strippedZone = String(bolusDate.dropLast())
  1410. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1411. let dateFormatter = DateFormatter()
  1412. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1413. dateFormatter.locale = Locale(identifier: "en_US")
  1414. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1415. guard let dateString = dateFormatter.date(from: strippedZone) else { continue }
  1416. let dateTimeStamp = dateString.timeIntervalSince1970
  1417. guard let bolus = currentEntry?["insulin"] as? Double else { continue }
  1418. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1419. lastFoundIndex = sgv.foundIndex
  1420. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1421. // Make the dot
  1422. let dot = bolusGraphStruct(value: bolus, date: Double(dateTimeStamp), sgv: Int(sgv.sgv + 20))
  1423. bolusData.append(dot)
  1424. }
  1425. }
  1426. if UserDefaultsRepository.graphBolus.value {
  1427. updateBolusGraph()
  1428. }
  1429. }
  1430. // NS Carb Bolus Response Processor
  1431. func processNSCarbs(entries: [[String:AnyObject]]) {
  1432. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Carbs") }
  1433. // because it's a small array, we're going to destroy and reload every time.
  1434. carbData.removeAll()
  1435. var lastFoundIndex = 0
  1436. var lastFoundBolus = 0
  1437. for i in 0..<entries.count {
  1438. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1439. var carbDate: String
  1440. if currentEntry?["timestamp"] != nil {
  1441. carbDate = currentEntry?["timestamp"] as! String
  1442. } else if currentEntry?["created_at"] != nil {
  1443. carbDate = currentEntry?["created_at"] as! String
  1444. } else {
  1445. continue
  1446. }
  1447. let absorptionTime = currentEntry?["absorptionTime"] as? Int ?? 0
  1448. // Fix for FreeAPS milliseconds in timestamp
  1449. var strippedZone = String(carbDate.dropLast())
  1450. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1451. let dateFormatter = DateFormatter()
  1452. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1453. dateFormatter.locale = Locale(identifier: "en_US")
  1454. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1455. guard let dateString = dateFormatter.date(from: strippedZone) else { continue }
  1456. var dateTimeStamp = dateString.timeIntervalSince1970
  1457. guard let carbs = currentEntry?["carbs"] as? Double else {
  1458. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: Null Carb entry")}
  1459. continue
  1460. }
  1461. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1462. lastFoundIndex = sgv.foundIndex
  1463. var offset = -50
  1464. if sgv.sgv < Double(topBG - 100) {
  1465. let bolusTime = findNearestBolusbyTime(timeWithin: 300, needle: dateTimeStamp, haystack: bolusData, startingIndex: lastFoundBolus)
  1466. lastFoundBolus = bolusTime.foundIndex
  1467. if bolusTime.offset {
  1468. offset = 70
  1469. } else {
  1470. offset = 20
  1471. }
  1472. }
  1473. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1474. // Make the dot
  1475. let dot = carbGraphStruct(value: Double(carbs), date: Double(dateTimeStamp), sgv: Int(sgv.sgv + Double(offset)), absorptionTime: absorptionTime)
  1476. carbData.append(dot)
  1477. }
  1478. }
  1479. if UserDefaultsRepository.graphCarbs.value {
  1480. updateCarbGraph()
  1481. }
  1482. }
  1483. // NS Suspend Pump Response Processor
  1484. func processSuspendPump(entries: [[String:AnyObject]]) {
  1485. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Suspend Pump") }
  1486. // because it's a small array, we're going to destroy and reload every time.
  1487. suspendGraphData.removeAll()
  1488. var lastFoundIndex = 0
  1489. for i in 0..<entries.count {
  1490. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1491. var date: String
  1492. if currentEntry?["timestamp"] != nil {
  1493. date = currentEntry?["timestamp"] as! String
  1494. } else if currentEntry?["created_at"] != nil {
  1495. date = currentEntry?["created_at"] as! String
  1496. } else {
  1497. return
  1498. }
  1499. // Fix for FreeAPS milliseconds in timestamp
  1500. var strippedZone = String(date.dropLast())
  1501. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1502. let dateFormatter = DateFormatter()
  1503. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1504. dateFormatter.locale = Locale(identifier: "en_US")
  1505. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1506. let dateString = dateFormatter.date(from: strippedZone)
  1507. let dateTimeStamp = dateString!.timeIntervalSince1970
  1508. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1509. lastFoundIndex = sgv.foundIndex
  1510. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1511. // Make the dot
  1512. let dot = DataStructs.timestampOnlyStruct(date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  1513. suspendGraphData.append(dot)
  1514. }
  1515. }
  1516. if UserDefaultsRepository.graphOtherTreatments.value {
  1517. updateSuspendGraph()
  1518. }
  1519. }
  1520. // NS Resume Pump Response Processor
  1521. func processResumePump(entries: [[String:AnyObject]]) {
  1522. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Resume Pump") }
  1523. // because it's a small array, we're going to destroy and reload every time.
  1524. resumeGraphData.removeAll()
  1525. var lastFoundIndex = 0
  1526. for i in 0..<entries.count {
  1527. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1528. var date: String
  1529. if currentEntry?["timestamp"] != nil {
  1530. date = currentEntry?["timestamp"] as! String
  1531. } else if currentEntry?["created_at"] != nil {
  1532. date = currentEntry?["created_at"] as! String
  1533. } else {
  1534. return
  1535. }
  1536. // Fix for FreeAPS milliseconds in timestamp
  1537. var strippedZone = String(date.dropLast())
  1538. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1539. let dateFormatter = DateFormatter()
  1540. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1541. dateFormatter.locale = Locale(identifier: "en_US")
  1542. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1543. let dateString = dateFormatter.date(from: strippedZone)
  1544. let dateTimeStamp = dateString!.timeIntervalSince1970
  1545. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1546. lastFoundIndex = sgv.foundIndex
  1547. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1548. // Make the dot
  1549. let dot = DataStructs.timestampOnlyStruct(date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  1550. resumeGraphData.append(dot)
  1551. }
  1552. }
  1553. if UserDefaultsRepository.graphOtherTreatments.value {
  1554. updateResumeGraph()
  1555. }
  1556. }
  1557. // NS Sensor Start Response Processor
  1558. func processSensorStart(entries: [[String:AnyObject]]) {
  1559. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Sensor Start") }
  1560. // because it's a small array, we're going to destroy and reload every time.
  1561. sensorStartGraphData.removeAll()
  1562. var lastFoundIndex = 0
  1563. for i in 0..<entries.count {
  1564. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1565. var date: String
  1566. if currentEntry?["timestamp"] != nil {
  1567. date = currentEntry?["timestamp"] as! String
  1568. } else if currentEntry?["created_at"] != nil {
  1569. date = currentEntry?["created_at"] as! String
  1570. } else {
  1571. return
  1572. }
  1573. // Fix for FreeAPS milliseconds in timestamp
  1574. var strippedZone = String(date.dropLast())
  1575. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1576. let dateFormatter = DateFormatter()
  1577. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1578. dateFormatter.locale = Locale(identifier: "en_US")
  1579. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1580. let dateString = dateFormatter.date(from: strippedZone)
  1581. let dateTimeStamp = dateString!.timeIntervalSince1970
  1582. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1583. lastFoundIndex = sgv.foundIndex
  1584. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1585. // Make the dot
  1586. let dot = DataStructs.timestampOnlyStruct(date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  1587. sensorStartGraphData.append(dot)
  1588. }
  1589. }
  1590. if UserDefaultsRepository.graphOtherTreatments.value {
  1591. updateSensorStart()
  1592. }
  1593. }
  1594. // NS Note Response Processor
  1595. func processNotes(entries: [[String:AnyObject]]) {
  1596. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Notes") }
  1597. // because it's a small array, we're going to destroy and reload every time.
  1598. noteGraphData.removeAll()
  1599. var lastFoundIndex = 0
  1600. for i in 0..<entries.count {
  1601. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1602. var date: String
  1603. if currentEntry?["timestamp"] != nil {
  1604. date = currentEntry?["timestamp"] as! String
  1605. } else if currentEntry?["created_at"] != nil {
  1606. date = currentEntry?["created_at"] as! String
  1607. } else {
  1608. return
  1609. }
  1610. // Fix for FreeAPS milliseconds in timestamp
  1611. var strippedZone = String(date.dropLast())
  1612. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1613. let dateFormatter = DateFormatter()
  1614. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1615. dateFormatter.locale = Locale(identifier: "en_US")
  1616. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1617. let dateString = dateFormatter.date(from: strippedZone)
  1618. let dateTimeStamp = dateString!.timeIntervalSince1970
  1619. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1620. lastFoundIndex = sgv.foundIndex
  1621. guard let thisNote = currentEntry?["notes"] as? String else { continue }
  1622. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1623. // Make the dot
  1624. let dot = DataStructs.noteStruct(date: Double(dateTimeStamp), sgv: Int(sgv.sgv), note: thisNote)
  1625. noteGraphData.append(dot)
  1626. }
  1627. }
  1628. if UserDefaultsRepository.graphOtherTreatments.value {
  1629. updateNotes()
  1630. }
  1631. }
  1632. // NS BG Check Response Processor
  1633. func processNSBGCheck(entries: [[String:AnyObject]]) {
  1634. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: BG Check") }
  1635. // because it's a small array, we're going to destroy and reload every time.
  1636. bgCheckData.removeAll()
  1637. for i in 0..<entries.count {
  1638. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1639. var date: String
  1640. if currentEntry?["timestamp"] != nil {
  1641. date = currentEntry?["timestamp"] as! String
  1642. } else if currentEntry?["created_at"] != nil {
  1643. date = currentEntry?["created_at"] as! String
  1644. } else {
  1645. return
  1646. }
  1647. // Fix for FreeAPS milliseconds in timestamp
  1648. var strippedZone = String(date.dropLast())
  1649. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1650. let dateFormatter = DateFormatter()
  1651. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1652. dateFormatter.locale = Locale(identifier: "en_US")
  1653. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1654. let dateString = dateFormatter.date(from: strippedZone)
  1655. let dateTimeStamp = dateString!.timeIntervalSince1970
  1656. guard let sgv = currentEntry?["glucose"] as? Int else {
  1657. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: Non-Int Glucose entry")}
  1658. continue
  1659. }
  1660. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1661. // Make the dot
  1662. //let dot = ShareGlucoseData(value: Double(carbs), date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  1663. let dot = ShareGlucoseData(sgv: sgv, date: Double(dateTimeStamp), direction: "")
  1664. bgCheckData.append(dot)
  1665. }
  1666. }
  1667. if UserDefaultsRepository.graphOtherTreatments.value {
  1668. updateBGCheckGraph()
  1669. }
  1670. }
  1671. // NS Override Response Processor
  1672. func processNSOverrides(entries: [[String:AnyObject]]) {
  1673. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Overrides") }
  1674. // because it's a small array, we're going to destroy and reload every time.
  1675. overrideGraphData.removeAll()
  1676. for i in 0..<entries.count {
  1677. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1678. var date: String
  1679. if currentEntry?["timestamp"] != nil {
  1680. date = currentEntry?["timestamp"] as! String
  1681. } else if currentEntry?["created_at"] != nil {
  1682. date = currentEntry?["created_at"] as! String
  1683. } else {
  1684. return
  1685. }
  1686. // Fix for FreeAPS milliseconds in timestamp
  1687. var strippedZone = String(date.dropLast())
  1688. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1689. let dateFormatter = DateFormatter()
  1690. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1691. dateFormatter.locale = Locale(identifier: "en_US")
  1692. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1693. let dateString = dateFormatter.date(from: strippedZone)
  1694. var dateTimeStamp = dateString!.timeIntervalSince1970
  1695. let graphHours = 24 * UserDefaultsRepository.downloadDays.value
  1696. if dateTimeStamp < dateTimeUtils.getTimeIntervalNHoursAgo(N: graphHours) {
  1697. dateTimeStamp = dateTimeUtils.getTimeIntervalNHoursAgo(N: graphHours)
  1698. }
  1699. var multiplier: Double = 1.0
  1700. if currentEntry?["insulinNeedsScaleFactor"] != nil {
  1701. multiplier = currentEntry?["insulinNeedsScaleFactor"] as! Double
  1702. }
  1703. var duration: Double = 5.0
  1704. if let durationType = currentEntry?["durationType"] as? String {
  1705. duration = dateTimeUtils.getNowTimeIntervalUTC() - dateTimeStamp + (60 * 60)
  1706. } else {
  1707. duration = (currentEntry?["duration"] as? Double)!
  1708. duration = duration * 60
  1709. }
  1710. // Skip overrides that aren't 5 minutes long. This prevents overlapping that causes bars to not display.
  1711. if duration < 300 { continue }
  1712. guard let enteredBy = currentEntry?["enteredBy"] as? String else { continue }
  1713. guard let reason = currentEntry?["reason"] as? String else { continue }
  1714. var range: [Int] = []
  1715. if let ranges = currentEntry?["correctionRange"] as? [Int] {
  1716. if ranges.count == 2 {
  1717. guard let low = ranges[0] as? Int else { continue }
  1718. guard let high = ranges[1] as? Int else { continue }
  1719. range.append(low)
  1720. range.append(high)
  1721. }
  1722. } else {
  1723. guard let low = currentEntry?["targetBottom"] as? Int else { continue }
  1724. guard let high = currentEntry?["targetTop"] as? Int else { continue }
  1725. range.append(low)
  1726. range.append(high)
  1727. }
  1728. let endDate = dateTimeStamp + (duration)
  1729. let dot = DataStructs.overrideStruct(insulNeedsScaleFactor: multiplier, date: dateTimeStamp, endDate: endDate, duration: duration, correctionRange: range, enteredBy: enteredBy, reason: reason, sgv: -20)
  1730. overrideGraphData.append(dot)
  1731. }
  1732. if UserDefaultsRepository.graphOtherTreatments.value {
  1733. updateOverrideGraph()
  1734. }
  1735. }
  1736. }