OpenAPS.swift 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248
  1. import Combine
  2. import CoreData
  3. import Foundation
  4. import JavaScriptCore
  5. final class OpenAPS {
  6. private let jsWorker = JavaScriptWorker()
  7. private let processQueue = DispatchQueue(label: "OpenAPS.processQueue", qos: .utility)
  8. private let storage: FileStorage
  9. private let tddStorage: TDDStorage
  10. let jsonConverter = JSONConverter()
  11. private func newContext(_ name: String) -> NSManagedObjectContext {
  12. let context = CoreDataStack.shared.newTaskContext()
  13. context.name = name
  14. return context
  15. }
  16. init(storage: FileStorage, tddStorage: TDDStorage) {
  17. self.storage = storage
  18. self.tddStorage = tddStorage
  19. }
  20. static let dateFormatter: ISO8601DateFormatter = {
  21. let formatter = ISO8601DateFormatter()
  22. formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
  23. return formatter
  24. }()
  25. // Helper function to convert a Decimal? to NSDecimalNumber?
  26. func decimalToNSDecimalNumber(_ value: Decimal?) -> NSDecimalNumber? {
  27. guard let value = value else { return nil }
  28. return NSDecimalNumber(decimal: value)
  29. }
  30. // Use the helper function for cleaner code
  31. func processDetermination(_ determination: Determination, on context: NSManagedObjectContext) async {
  32. await context.perform {
  33. let newOrefDetermination = OrefDetermination(context: context)
  34. newOrefDetermination.id = UUID()
  35. newOrefDetermination.insulinSensitivity = self.decimalToNSDecimalNumber(determination.isf)
  36. newOrefDetermination.currentTarget = self.decimalToNSDecimalNumber(determination.current_target)
  37. newOrefDetermination.eventualBG = determination.eventualBG.map(NSDecimalNumber.init)
  38. newOrefDetermination.deliverAt = determination.deliverAt
  39. newOrefDetermination.carbRatio = self.decimalToNSDecimalNumber(determination.carbRatio)
  40. newOrefDetermination.glucose = self.decimalToNSDecimalNumber(determination.bg)
  41. newOrefDetermination.reservoir = self.decimalToNSDecimalNumber(determination.reservoir)
  42. newOrefDetermination.insulinReq = self.decimalToNSDecimalNumber(determination.insulinReq)
  43. newOrefDetermination.temp = determination.temp?.rawValue ?? "absolute"
  44. newOrefDetermination.rate = self.decimalToNSDecimalNumber(determination.rate)
  45. newOrefDetermination.reason = determination.reason
  46. newOrefDetermination.duration = self.decimalToNSDecimalNumber(determination.duration)
  47. newOrefDetermination.iob = self.decimalToNSDecimalNumber(determination.iob)
  48. newOrefDetermination.threshold = self.decimalToNSDecimalNumber(determination.threshold)
  49. newOrefDetermination.minDelta = self.decimalToNSDecimalNumber(determination.minDelta)
  50. newOrefDetermination.sensitivityRatio = self.decimalToNSDecimalNumber(determination.sensitivityRatio)
  51. newOrefDetermination.expectedDelta = self.decimalToNSDecimalNumber(determination.expectedDelta)
  52. newOrefDetermination.cob = Int16(Int(determination.cob ?? 0))
  53. newOrefDetermination.smbToDeliver = determination.units.map { NSDecimalNumber(decimal: $0) }
  54. newOrefDetermination.carbsRequired = Int16(Int(determination.carbsReq ?? 0))
  55. newOrefDetermination.isUploadedToNS = false
  56. if let predictions = determination.predictions {
  57. ["iob": predictions.iob, "zt": predictions.zt, "cob": predictions.cob, "uam": predictions.uam]
  58. .forEach { type, values in
  59. if let values = values {
  60. let forecast = Forecast(context: context)
  61. forecast.id = UUID()
  62. forecast.type = type
  63. forecast.date = Date()
  64. forecast.orefDetermination = newOrefDetermination
  65. for (index, value) in values.enumerated() {
  66. let forecastValue = ForecastValue(context: context)
  67. forecastValue.index = Int32(index)
  68. forecastValue.value = Int32(value)
  69. forecast.addToForecastValues(forecastValue)
  70. }
  71. newOrefDetermination.addToForecasts(forecast)
  72. }
  73. }
  74. }
  75. }
  76. // First save the current Determination to Core Data
  77. await attemptToSaveContext(on: context)
  78. }
  79. func attemptToSaveContext(on context: NSManagedObjectContext) async {
  80. await context.perform {
  81. do {
  82. guard context.hasChanges else { return }
  83. try context.save()
  84. } catch {
  85. debugPrint("\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to save Determination to Core Data")
  86. }
  87. }
  88. }
  89. // fetch glucose to pass it to the meal function and to determine basal
  90. func fetchAndProcessGlucose(
  91. context: NSManagedObjectContext,
  92. shouldSmoothGlucose: Bool,
  93. fetchLimit: Int?,
  94. fetchHours: Decimal = 24
  95. ) async throws -> String {
  96. // Time window from `fetchHours` hours ago up to now. determineBasal feeds
  97. // `maxMealAbsorptionTime + 0.5h` (just enough glucose to cover the longest
  98. // tracked meal absorption plus a small lead-in); Autosens uses the default
  99. // 24h because its sensitivity algorithm needs that full window.
  100. let cutoff = Date().addingTimeInterval(-(Double(truncating: fetchHours as NSNumber) * 3600))
  101. let timePredicate = NSPredicate(format: "date >= %@", cutoff as NSDate)
  102. let results = try await CoreDataStack.shared.fetchEntitiesAsync(
  103. ofType: GlucoseStored.self,
  104. onContext: context,
  105. predicate: timePredicate,
  106. key: "date",
  107. ascending: false,
  108. fetchLimit: fetchLimit,
  109. batchSize: 48
  110. )
  111. // mapping within the context closure, JSON conversion outside
  112. let algorithmGlucose = try await context.perform {
  113. guard let glucoseResults = results as? [GlucoseStored] else {
  114. throw CoreDataError.fetchError(function: #function, file: #file)
  115. }
  116. // extracting handler to only create it 1x
  117. let roundingBehavior = NSDecimalNumberHandler(
  118. roundingMode: .plain,
  119. scale: 0,
  120. raiseOnExactness: false,
  121. raiseOnOverflow: false,
  122. raiseOnUnderflow: false,
  123. raiseOnDivideByZero: false
  124. )
  125. return glucoseResults.map { glucose -> AlgorithmGlucose in
  126. let glucoseValue: Int16
  127. if shouldSmoothGlucose {
  128. if !glucose.isManual, let smoothedGlucose = glucose.smoothedGlucose, smoothedGlucose != 0 {
  129. glucoseValue = smoothedGlucose.rounding(accordingToBehavior: roundingBehavior).int16Value
  130. } else {
  131. // use the raw value = finger prick, so manual readings are always included for algorithm decision making
  132. // cf. https://github.com/nightscout/Trio/issues/1054
  133. glucoseValue = glucose.glucose
  134. }
  135. } else {
  136. glucoseValue = glucose.glucose
  137. }
  138. return AlgorithmGlucose(
  139. date: glucose.date,
  140. direction: glucose.direction,
  141. glucose: glucoseValue,
  142. id: glucose.id,
  143. isManual: glucose.isManual
  144. )
  145. }
  146. }
  147. return jsonConverter.convertToJSON(algorithmGlucose)
  148. }
  149. private func fetchAndProcessCarbs(
  150. on context: NSManagedObjectContext,
  151. additionalCarbs: Decimal? = nil,
  152. carbsDate: Date? = nil
  153. ) async throws -> String {
  154. let results = try await CoreDataStack.shared.fetchEntitiesAsync(
  155. ofType: CarbEntryStored.self,
  156. onContext: context,
  157. predicate: NSPredicate.predicateForOneDayAgo,
  158. key: "date",
  159. ascending: false
  160. )
  161. let json = try await context.perform {
  162. guard let carbResults = results as? [CarbEntryStored] else {
  163. throw CoreDataError.fetchError(function: #function, file: #file)
  164. }
  165. var jsonArray = self.jsonConverter.convertToJSON(carbResults)
  166. if let additionalCarbs = additionalCarbs {
  167. let formattedDate = carbsDate.map { ISO8601DateFormatter().string(from: $0) } ?? ISO8601DateFormatter()
  168. .string(from: Date())
  169. let additionalEntry = [
  170. "carbs": Double(additionalCarbs),
  171. "actualDate": formattedDate,
  172. "id": UUID().uuidString,
  173. "note": NSNull(),
  174. "protein": 0,
  175. "created_at": formattedDate,
  176. "isFPU": false,
  177. "fat": 0,
  178. "enteredBy": "Trio"
  179. ] as [String: Any]
  180. // Assuming jsonArray is a String, convert it to a list of dictionaries first
  181. if let jsonData = jsonArray.data(using: .utf8) {
  182. var jsonList = try? JSONSerialization.jsonObject(with: jsonData, options: []) as? [[String: Any]]
  183. jsonList?.append(additionalEntry)
  184. // Convert back to JSON string
  185. if let updatedJsonData = try? JSONSerialization
  186. .data(withJSONObject: jsonList ?? [], options: .prettyPrinted)
  187. {
  188. jsonArray = String(data: updatedJsonData, encoding: .utf8) ?? jsonArray
  189. }
  190. }
  191. }
  192. return jsonArray
  193. }
  194. return json
  195. }
  196. private func fetchPumpHistoryObjectIDs(on context: NSManagedObjectContext) async throws -> [NSManagedObjectID]? {
  197. let results = try await CoreDataStack.shared.fetchEntitiesAsync(
  198. ofType: PumpEventStored.self,
  199. onContext: context,
  200. predicate: NSPredicate.pumpHistoryLast1440Minutes,
  201. key: "timestamp",
  202. ascending: false,
  203. batchSize: 50,
  204. relationshipKeyPathsForPrefetching: ["bolus", "tempBasal"]
  205. )
  206. return try await context.perform {
  207. guard let pumpEventResults = results as? [PumpEventStored] else {
  208. throw CoreDataError.fetchError(function: #function, file: #file)
  209. }
  210. return pumpEventResults.map(\.objectID)
  211. }
  212. }
  213. private func parsePumpHistory(
  214. on context: NSManagedObjectContext,
  215. _ pumpHistoryObjectIDs: [NSManagedObjectID],
  216. simulatedBolusAmount: Decimal? = nil
  217. ) async throws -> String {
  218. // Return an empty JSON object if the list of object IDs is empty
  219. guard !pumpHistoryObjectIDs.isEmpty else { return "{}" }
  220. // Addresses https://github.com/nightscout/Trio/issues/898
  221. //
  222. // On a cold start (new user, fresh onboarding, or pump disconnected > 24h),
  223. // the oldest event in pump history can be a resume with no preceding pump
  224. // activity. oref interprets this as the end of a suspend that never started,
  225. // which drives negative IOB and can cause excessive insulin delivery.
  226. let orphanedResumes = try await fetchOrphanedResumes(on: context)
  227. // Execute all operations on the background context
  228. return await context.perform {
  229. // Load and map pump events to DTOs
  230. var dtos = self.loadAndMapPumpEvents(pumpHistoryObjectIDs, orphanedResumes: orphanedResumes, on: context)
  231. // Optionally add the IOB as a DTO
  232. if let simulatedBolusAmount = simulatedBolusAmount {
  233. let simulatedBolusDTO = self.createSimulatedBolusDTO(simulatedBolusAmount: simulatedBolusAmount)
  234. dtos.insert(simulatedBolusDTO, at: 0)
  235. }
  236. // Convert the DTOs to JSON
  237. return self.jsonConverter.convertToJSON(dtos)
  238. }
  239. }
  240. private func loadAndMapPumpEvents(
  241. _ pumpHistoryObjectIDs: [NSManagedObjectID],
  242. orphanedResumes: [NSManagedObjectID],
  243. on context: NSManagedObjectContext
  244. ) -> [PumpEventDTO] {
  245. OpenAPS.loadAndMapPumpEvents(pumpHistoryObjectIDs, orphanedResumes: orphanedResumes, from: context)
  246. }
  247. /// Fetches and parses pump events, expose this as static and not private for testing
  248. static func loadAndMapPumpEvents(
  249. _ pumpHistoryObjectIDs: [NSManagedObjectID],
  250. orphanedResumes: [NSManagedObjectID],
  251. from context: NSManagedObjectContext
  252. ) -> [PumpEventDTO] {
  253. let orphanedSet = Set(orphanedResumes)
  254. let filteredObjectIds = pumpHistoryObjectIDs.filter { !orphanedSet.contains($0) }
  255. // Load the pump events from the object IDs
  256. let pumpHistory: [PumpEventStored] = filteredObjectIds
  257. .compactMap { context.object(with: $0) as? PumpEventStored }
  258. // Create the DTOs
  259. let dtos: [PumpEventDTO] = pumpHistory.flatMap { event -> [PumpEventDTO] in
  260. var eventDTOs: [PumpEventDTO] = []
  261. if let bolusDTO = event.toBolusDTOEnum() {
  262. eventDTOs.append(bolusDTO)
  263. }
  264. if let tempBasalDurationDTO = event.toTempBasalDurationDTOEnum() {
  265. eventDTOs.append(tempBasalDurationDTO)
  266. }
  267. if let tempBasalDTO = event.toTempBasalDTOEnum() {
  268. eventDTOs.append(tempBasalDTO)
  269. }
  270. if let pumpSuspendDTO = event.toPumpSuspendDTO() {
  271. eventDTOs.append(pumpSuspendDTO)
  272. }
  273. if let pumpResumeDTO = event.toPumpResumeDTO() {
  274. eventDTOs.append(pumpResumeDTO)
  275. }
  276. if let rewindDTO = event.toRewindDTO() {
  277. eventDTOs.append(rewindDTO)
  278. }
  279. if let primeDTO = event.toPrimeDTO() {
  280. eventDTOs.append(primeDTO)
  281. }
  282. return eventDTOs
  283. }
  284. return dtos
  285. }
  286. private func createSimulatedBolusDTO(simulatedBolusAmount: Decimal) -> PumpEventDTO {
  287. let oneSecondAgo = Calendar.current
  288. .date(
  289. byAdding: .second,
  290. value: -1,
  291. to: Date()
  292. )! // adding -1s to the current Date ensures that oref actually uses the mock entry to calculate iob and not guard it away
  293. let dateFormatted = PumpEventStored.dateFormatter.string(from: oneSecondAgo)
  294. let bolusDTO = BolusDTO(
  295. id: UUID().uuidString,
  296. timestamp: dateFormatted,
  297. amount: Double(simulatedBolusAmount),
  298. isExternal: false,
  299. isSMB: true,
  300. duration: 0,
  301. _type: "Bolus"
  302. )
  303. return .bolus(bolusDTO)
  304. }
  305. /// Detects a cold-start orphaned resume: returns the resume's object ID if it's an orphaned resume
  306. private func fetchOrphanedResumes(on context: NSManagedObjectContext) async throws -> [NSManagedObjectID] {
  307. let results = try await CoreDataStack.shared.fetchEntitiesAsync(
  308. ofType: PumpEventStored.self,
  309. onContext: context,
  310. predicate: NSPredicate.pumpHistoryLast48h,
  311. key: "timestamp",
  312. ascending: true,
  313. batchSize: 250
  314. )
  315. return try await context.perform {
  316. guard let pumpEventResultsFull = results as? [PumpEventStored] else {
  317. throw CoreDataError.fetchError(function: #function, file: #file)
  318. }
  319. let pumpEventResults = pumpEventResultsFull
  320. .filter { $0.type == EventType.pumpSuspend.rawValue || $0.type == EventType.pumpResume.rawValue }
  321. // we define an orphaned resume as one without a paired suspend within
  322. // the most recent 24 hours.
  323. // **Important**: we pick 48 hours because the standard pump history
  324. // is 24 hours + 24 hours of inspection for resumes.
  325. let orphanedResumes = zip(pumpEventResults, pumpEventResults.dropFirst())
  326. .compactMap { (prev, curr) -> PumpEventStored? in
  327. guard let prevTimestamp = prev.timestamp, let currTimestamp = curr.timestamp else {
  328. return nil
  329. }
  330. let interval = currTimestamp.timeIntervalSince(prevTimestamp)
  331. // check if the current event is an orphaned resume
  332. // - previous event not a suspend
  333. // - previous event is a suspend but it's more than 24 hours ago
  334. if curr.type == EventType.pumpResume.rawValue,
  335. prev.type != EventType.pumpSuspend.rawValue || interval > TimeInterval(hours: 24)
  336. {
  337. return curr
  338. }
  339. return nil
  340. }
  341. // check the first event to see if it's an orphaned resume
  342. let firstResumeOrphaned = pumpEventResults.first.flatMap({ event -> [PumpEventStored]? in
  343. guard event.type == EventType.pumpResume.rawValue else { return nil }
  344. return [event]
  345. }) ?? []
  346. return (firstResumeOrphaned + orphanedResumes).map(\.objectID)
  347. }
  348. }
  349. func determineBasal(
  350. currentTemp: TempBasal,
  351. shouldSmoothGlucose: Bool,
  352. useJavascriptOref: Bool,
  353. clock: Date = Date(),
  354. simulatedCarbsAmount: Decimal? = nil,
  355. simulatedBolusAmount: Decimal? = nil,
  356. simulatedCarbsDate: Date? = nil,
  357. simulation: Bool = false
  358. ) async throws -> Determination? {
  359. debug(.openAPS, "Start determineBasal")
  360. let context = newContext("determineBasal")
  361. // temp_basal
  362. let tempBasal = currentTemp.rawJSON
  363. // Perform asynchronous calls in parallel
  364. async let pumpHistoryObjectIDs = fetchPumpHistoryObjectIDs(on: context) ?? []
  365. async let carbs = fetchAndProcessCarbs(
  366. on: context,
  367. additionalCarbs: simulatedCarbsAmount ?? 0,
  368. carbsDate: simulatedCarbsDate
  369. )
  370. var preferences = await storage.retrieveAsync(OpenAPS.Settings.preferences, as: Preferences.self) ?? Preferences()
  371. let glucoseFetchHours = preferences.maxMealAbsorptionTime + 0.5 // MMAT + half hour buffer
  372. async let glucose = fetchAndProcessGlucose(
  373. context: context,
  374. shouldSmoothGlucose: shouldSmoothGlucose,
  375. fetchLimit: nil,
  376. fetchHours: glucoseFetchHours
  377. )
  378. async let prepareTrioCustomOrefVariables = prepareTrioCustomOrefVariables(on: context)
  379. async let profileAsync = loadFileFromStorageAsync(name: Settings.profile)
  380. async let basalAsync = loadFileFromStorageAsync(name: Settings.basalProfile)
  381. async let autosenseAsync = loadFileFromStorageAsync(name: Settings.autosense)
  382. async let reservoirAsync = loadFileFromStorageAsync(name: Monitor.reservoir)
  383. async let hasSufficientTddForDynamic = tddStorage.hasSufficientTDD()
  384. // Await the results of asynchronous tasks
  385. let (
  386. pumpHistoryJSON,
  387. carbsAsJSON,
  388. glucoseAsJSON,
  389. trioCustomOrefVariables,
  390. profile,
  391. basalProfile,
  392. autosens,
  393. reservoir,
  394. hasSufficientTdd
  395. ) = await (
  396. try parsePumpHistory(on: context, await pumpHistoryObjectIDs, simulatedBolusAmount: simulatedBolusAmount),
  397. try carbs,
  398. try glucose,
  399. try prepareTrioCustomOrefVariables,
  400. profileAsync,
  401. basalAsync,
  402. autosenseAsync,
  403. reservoirAsync,
  404. try hasSufficientTddForDynamic
  405. )
  406. // Meal calculation
  407. let meal = try await self.meal(
  408. pumphistory: pumpHistoryJSON,
  409. profile: profile,
  410. basalProfile: basalProfile,
  411. clock: clock,
  412. carbs: carbsAsJSON,
  413. glucose: glucoseAsJSON,
  414. useJavascriptOref: useJavascriptOref
  415. )
  416. // IOB calculation
  417. let iob = try await self.iob(
  418. pumphistory: pumpHistoryJSON,
  419. profile: profile,
  420. clock: clock,
  421. autosens: autosens.isEmpty ? .null : autosens,
  422. useJavascriptOref: useJavascriptOref
  423. )
  424. // TODO: refactor this to core data
  425. if !simulation {
  426. storage.save(iob, as: Monitor.iob)
  427. }
  428. if !hasSufficientTdd, preferences.useNewFormula || (preferences.useNewFormula && preferences.sigmoid) {
  429. debug(.openAPS, "Insufficient TDD for dynamic formula; disabling for determine basal run.")
  430. preferences.useNewFormula = false
  431. preferences.sigmoid = false
  432. }
  433. // Determine basal
  434. let orefDetermination = try await determineBasal(
  435. glucose: glucoseAsJSON,
  436. currentTemp: tempBasal,
  437. iob: iob,
  438. profile: profile,
  439. autosens: autosens.isEmpty ? .null : autosens,
  440. meal: meal,
  441. microBolusAllowed: true,
  442. reservoir: reservoir,
  443. pumpHistory: pumpHistoryJSON,
  444. preferences: preferences,
  445. basalProfile: basalProfile,
  446. trioCustomOrefVariables: trioCustomOrefVariables,
  447. useJavascriptOref: useJavascriptOref
  448. )
  449. debug(.openAPS, "\(simulation ? "[SIMULATION]" : "") OREF DETERMINATION: \(orefDetermination)")
  450. if var determination = Determination(from: orefDetermination), let deliverAt = determination.deliverAt {
  451. // set both timestamp and deliverAt to the SAME date; this will be updated for timestamp once it is enacted
  452. // AAPS does it the same way! we'll follow their example!
  453. determination.timestamp = deliverAt
  454. if !simulation {
  455. // save to core data asynchronously
  456. await processDetermination(determination, on: context)
  457. }
  458. return determination
  459. } else {
  460. debug(
  461. .openAPS,
  462. "\(DebuggingIdentifiers.failed) No determination data. orefDetermination: \(orefDetermination), Determination(from: orefDetermination): \(String(describing: Determination(from: orefDetermination))), deliverAt: \(String(describing: Determination(from: orefDetermination)?.deliverAt))"
  463. )
  464. throw APSError.apsError(message: "No determination data.")
  465. }
  466. }
  467. func prepareTrioCustomOrefVariables(on context: NSManagedObjectContext) async throws -> RawJSON {
  468. try await context.perform {
  469. // Retrieve user preferences
  470. let userPreferences = self.storage.retrieve(OpenAPS.Settings.preferences, as: Preferences.self)
  471. let weightPercentage = userPreferences?.weightPercentage ?? 1.0
  472. let maxSMBBasalMinutes = userPreferences?.maxSMBBasalMinutes ?? 30
  473. let maxUAMBasalMinutes = userPreferences?.maxUAMSMBBasalMinutes ?? 30
  474. // Fetch historical events for Total Daily Dose (TDD) calculation
  475. let tenDaysAgo = Date().addingTimeInterval(-10.days.timeInterval)
  476. let twoHoursAgo = Date().addingTimeInterval(-2.hours.timeInterval)
  477. let historicalTDDData = try self.fetchHistoricalTDDData(from: tenDaysAgo, on: context)
  478. // Fetch the last active Override
  479. let activeOverrides = try self.fetchActiveOverrides(on: context)
  480. let isOverrideActive = activeOverrides.first?.enabled ?? false
  481. let overridePercentage = Decimal(activeOverrides.first?.percentage ?? 100)
  482. let isOverrideIndefinite = activeOverrides.first?.indefinite ?? true
  483. let disableSMBs = activeOverrides.first?.smbIsOff ?? false
  484. let overrideTargetBG = activeOverrides.first?.target?.decimalValue ?? 0
  485. // Calculate averages for Total Daily Dose (TDD)
  486. let totalTDD = historicalTDDData.compactMap { ($0["total"] as? NSDecimalNumber)?.decimalValue }.reduce(0, +)
  487. let totalDaysCount = max(historicalTDDData.count, 1)
  488. // Fetch recent TDD data for the past two hours
  489. let recentTDDData = historicalTDDData.filter { ($0["date"] as? Date ?? Date()) >= twoHoursAgo }
  490. let recentDataCount = max(recentTDDData.count, 1)
  491. let recentTotalTDD = recentTDDData.compactMap { ($0["total"] as? NSDecimalNumber)?.decimalValue }
  492. .reduce(0, +)
  493. let currentTDD = historicalTDDData.last?["total"] as? Decimal ?? 0
  494. let averageTDDLastTwoHours = recentTotalTDD / Decimal(recentDataCount)
  495. let averageTDDLastTenDays = totalTDD / Decimal(totalDaysCount)
  496. let weightedTDD = weightPercentage * averageTDDLastTwoHours + (1 - weightPercentage) * averageTDDLastTenDays
  497. let glucose = try self.fetchGlucose(on: context)
  498. // Prepare Trio's custom oref variables
  499. let trioCustomOrefVariablesData = TrioCustomOrefVariables(
  500. average_total_data: currentTDD > 0 ? averageTDDLastTenDays : 0,
  501. weightedAverage: currentTDD > 0 ? weightedTDD : 1,
  502. currentTDD: currentTDD,
  503. past2hoursAverage: currentTDD > 0 ? averageTDDLastTwoHours : 0,
  504. date: Date(),
  505. overridePercentage: overridePercentage,
  506. useOverride: isOverrideActive,
  507. duration: activeOverrides.first?.duration?.decimalValue ?? 0,
  508. unlimited: isOverrideIndefinite,
  509. overrideTarget: overrideTargetBG,
  510. smbIsOff: disableSMBs,
  511. advancedSettings: activeOverrides.first?.advancedSettings ?? false,
  512. isfAndCr: activeOverrides.first?.isfAndCr ?? false,
  513. isf: activeOverrides.first?.isf ?? false,
  514. cr: activeOverrides.first?.cr ?? false,
  515. smbIsScheduledOff: activeOverrides.first?.smbIsScheduledOff ?? false,
  516. start: (activeOverrides.first?.start ?? 0) as Decimal,
  517. end: (activeOverrides.first?.end ?? 0) as Decimal,
  518. smbMinutes: activeOverrides.first?.smbMinutes?.decimalValue ?? maxSMBBasalMinutes,
  519. uamMinutes: activeOverrides.first?.uamMinutes?.decimalValue ?? maxUAMBasalMinutes
  520. )
  521. // Save and return contents of Trio's custom oref variables
  522. self.storage.save(trioCustomOrefVariablesData, as: OpenAPS.Monitor.trio_custom_oref_variables)
  523. return self.loadFileFromStorage(name: Monitor.trio_custom_oref_variables)
  524. }
  525. }
  526. func autosense(shouldSmoothGlucose: Bool, useJavascriptOref: Bool) async throws -> Autosens? {
  527. debug(.openAPS, "Start autosens")
  528. let context = newContext("autosense")
  529. // Perform asynchronous calls in parallel
  530. async let pumpHistoryObjectIDs = fetchPumpHistoryObjectIDs(on: context) ?? []
  531. async let carbs = fetchAndProcessCarbs(on: context)
  532. async let glucose = fetchAndProcessGlucose(context: context, shouldSmoothGlucose: shouldSmoothGlucose, fetchLimit: nil)
  533. async let getProfile = loadFileFromStorageAsync(name: Settings.profile)
  534. async let getBasalProfile = loadFileFromStorageAsync(name: Settings.basalProfile)
  535. async let getTempTargets = loadFileFromStorageAsync(name: Settings.tempTargets)
  536. // Await the results of asynchronous tasks
  537. let (pumpHistoryJSON, carbsAsJSON, glucoseAsJSON, profile, basalProfile, tempTargets) = await (
  538. try parsePumpHistory(on: context, await pumpHistoryObjectIDs),
  539. try carbs,
  540. try glucose,
  541. getProfile,
  542. getBasalProfile,
  543. getTempTargets
  544. )
  545. // Autosense
  546. let autosenseResult = try await autosense(
  547. glucose: glucoseAsJSON,
  548. pumpHistory: pumpHistoryJSON,
  549. basalprofile: basalProfile,
  550. profile: profile,
  551. carbs: carbsAsJSON,
  552. temptargets: tempTargets,
  553. useJavascriptOref: useJavascriptOref
  554. )
  555. debug(.openAPS, "AUTOSENS: \(autosenseResult)")
  556. if var autosens = Autosens(from: autosenseResult) {
  557. autosens.timestamp = Date()
  558. await storage.saveAsync(autosens, as: Settings.autosense)
  559. return autosens
  560. } else {
  561. return nil
  562. }
  563. }
  564. func createProfiles(useJavascriptOref: Bool) async throws {
  565. debug(.openAPS, "Start creating pump profile and user profile")
  566. // Load required settings and profiles asynchronously
  567. async let getPumpSettings = loadFileFromStorageAsync(name: Settings.settings)
  568. async let getBGTargets = loadFileFromStorageAsync(name: Settings.bgTargets)
  569. async let getBasalProfile = loadFileFromStorageAsync(name: Settings.basalProfile)
  570. async let getISF = loadFileFromStorageAsync(name: Settings.insulinSensitivities)
  571. async let getCR = loadFileFromStorageAsync(name: Settings.carbRatios)
  572. async let getTempTargets = loadFileFromStorageAsync(name: Settings.tempTargets)
  573. async let getModel = loadFileFromStorageAsync(name: Settings.model)
  574. async let getTrioSettingDefaults = loadFileFromStorageAsync(name: Trio.settings)
  575. let (pumpSettings, bgTargets, basalProfile, isf, cr, tempTargets, model, trioSettings) = await (
  576. getPumpSettings,
  577. getBGTargets,
  578. getBasalProfile,
  579. getISF,
  580. getCR,
  581. getTempTargets,
  582. getModel,
  583. getTrioSettingDefaults
  584. )
  585. // Retrieve user preferences, or set defaults if not available
  586. let preferences = storage.retrieve(OpenAPS.Settings.preferences, as: Preferences.self) ?? Preferences()
  587. let defaultHalfBasalTarget = preferences.halfBasalExerciseTarget
  588. var adjustedPreferences = preferences
  589. // Check for active Temp Targets and adjust HBT if necessary
  590. let context = newContext("createProfiles")
  591. try await context.perform {
  592. // Check if a Temp Target is active and check HBT differs from setting and adjust
  593. if let activeTempTarget = try self.fetchActiveTempTargets(on: context).first,
  594. activeTempTarget.enabled,
  595. let targetValue = activeTempTarget.target?.decimalValue
  596. {
  597. // Compute effective HBT - handles both custom HBT and standard TT (where HBT might need adjustment)
  598. let effectiveHBT = TempTargetCalculations.computeEffectiveHBT(
  599. tempTargetHalfBasalTarget: activeTempTarget.halfBasalTarget?.decimalValue,
  600. settingHalfBasalTarget: defaultHalfBasalTarget,
  601. target: targetValue,
  602. autosensMax: preferences.autosensMax
  603. )
  604. if let effectiveHBT, effectiveHBT != defaultHalfBasalTarget {
  605. adjustedPreferences.halfBasalExerciseTarget = effectiveHBT
  606. let percentage = Int(TempTargetCalculations.computeAdjustedPercentage(
  607. halfBasalTarget: effectiveHBT,
  608. target: targetValue,
  609. autosensMax: preferences.autosensMax
  610. ))
  611. debug(
  612. .openAPS,
  613. "TempTarget: target=\(targetValue), HBT=\(defaultHalfBasalTarget), effectiveHBT=\(effectiveHBT), percentage=\(percentage)%, adjustmentType=Custom"
  614. )
  615. }
  616. }
  617. // Overwrite the lowTTlowersSens if autosensMax does not support it
  618. if preferences.lowTemptargetLowersSensitivity, preferences.autosensMax <= 1 {
  619. adjustedPreferences.lowTemptargetLowersSensitivity = false
  620. debug(.openAPS, "Setting lowTTlowersSens to false due to insufficient autosensMax: \(preferences.autosensMax)")
  621. }
  622. }
  623. let clock = Date()
  624. do {
  625. let pumpProfile = try await makeProfile(
  626. preferences: adjustedPreferences,
  627. pumpSettings: pumpSettings,
  628. bgTargets: bgTargets,
  629. basalProfile: basalProfile,
  630. isf: isf,
  631. carbRatio: cr,
  632. tempTargets: tempTargets,
  633. model: model,
  634. autotune: RawJSON.null,
  635. trioSettings: trioSettings,
  636. useJavascriptOref: useJavascriptOref,
  637. clock: clock
  638. )
  639. let profile = try await makeProfile(
  640. preferences: adjustedPreferences,
  641. pumpSettings: pumpSettings,
  642. bgTargets: bgTargets,
  643. basalProfile: basalProfile,
  644. isf: isf,
  645. carbRatio: cr,
  646. tempTargets: tempTargets,
  647. model: model,
  648. autotune: RawJSON.null,
  649. trioSettings: trioSettings,
  650. useJavascriptOref: useJavascriptOref,
  651. clock: clock
  652. )
  653. // Save the profiles
  654. await storage.saveAsync(pumpProfile, as: Settings.pumpProfile)
  655. await storage.saveAsync(profile, as: Settings.profile)
  656. } catch {
  657. debug(
  658. .apsManager,
  659. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to create pump profile and normal profile: \(error)"
  660. )
  661. throw error
  662. }
  663. }
  664. private func iob(
  665. pumphistory: JSON,
  666. profile: JSON,
  667. clock: JSON,
  668. autosens: JSON,
  669. useJavascriptOref: Bool
  670. ) async throws -> RawJSON {
  671. // FIXME: For now we'll just remove duplicate suspends here (ISSUE-399)
  672. var pumphistory = pumphistory
  673. if let pumpHistoryArray = try? JSONBridge.pumpHistory(from: pumphistory) {
  674. pumphistory = pumpHistoryArray.removingDuplicateSuspendResumeEvents().rawJSON
  675. }
  676. if useJavascriptOref {
  677. let jsResult = await iobJavascript(pumphistory: pumphistory, profile: profile, clock: clock, autosens: autosens)
  678. return try jsResult.returnOrThrow()
  679. } else {
  680. let swiftResult = OpenAPSSwift
  681. .iob(pumphistory: pumphistory, profile: profile, clock: clock, autosens: autosens)
  682. return try swiftResult.returnOrThrow()
  683. }
  684. }
  685. func iobJavascript(pumphistory: JSON, profile: JSON, clock: JSON, autosens: JSON) async -> OrefFunctionResult {
  686. do {
  687. let result = try await withCheckedThrowingContinuation { continuation in
  688. jsWorker.inCommonContext { worker in
  689. worker.evaluateBatch(scripts: [
  690. Script(name: Prepare.log),
  691. Script(name: Bundle.iob),
  692. Script(name: Prepare.iob)
  693. ])
  694. let result = worker.call(function: Function.generate, with: [
  695. pumphistory,
  696. profile,
  697. clock,
  698. autosens
  699. ])
  700. continuation.resume(returning: result)
  701. }
  702. }
  703. return .success(result)
  704. } catch {
  705. return .failure(error)
  706. }
  707. }
  708. private func meal(
  709. pumphistory: JSON,
  710. profile: JSON,
  711. basalProfile: JSON,
  712. clock: JSON,
  713. carbs: JSON,
  714. glucose: JSON,
  715. useJavascriptOref: Bool
  716. ) async throws -> RawJSON {
  717. if useJavascriptOref {
  718. let jsResult = await mealJavascript(
  719. pumphistory: pumphistory,
  720. profile: profile,
  721. basalProfile: basalProfile,
  722. clock: clock,
  723. carbs: carbs,
  724. glucose: glucose
  725. )
  726. return try jsResult.returnOrThrow()
  727. } else {
  728. let swiftResult = OpenAPSSwift
  729. .meal(
  730. pumphistory: pumphistory,
  731. profile: profile,
  732. basalProfile: basalProfile,
  733. clock: clock,
  734. carbs: carbs,
  735. glucose: glucose
  736. )
  737. return try swiftResult.returnOrThrow()
  738. }
  739. }
  740. private func mealJavascript(
  741. pumphistory: JSON,
  742. profile: JSON,
  743. basalProfile: JSON,
  744. clock: JSON,
  745. carbs: JSON,
  746. glucose: JSON
  747. ) async -> OrefFunctionResult {
  748. do {
  749. let result = try await withCheckedThrowingContinuation { continuation in
  750. jsWorker.inCommonContext { worker in
  751. worker.evaluateBatch(scripts: [
  752. Script(name: Prepare.log),
  753. Script(name: Bundle.meal),
  754. Script(name: Prepare.meal)
  755. ])
  756. let result = worker.call(function: Function.generate, with: [
  757. pumphistory,
  758. profile,
  759. clock,
  760. glucose,
  761. basalProfile,
  762. carbs
  763. ])
  764. continuation.resume(returning: result)
  765. }
  766. }
  767. return .success(result)
  768. } catch {
  769. return .failure(error)
  770. }
  771. }
  772. private func autosense(
  773. glucose: JSON,
  774. pumpHistory: JSON,
  775. basalprofile: JSON,
  776. profile: JSON,
  777. carbs: JSON,
  778. temptargets: JSON,
  779. useJavascriptOref: Bool
  780. ) async throws -> RawJSON {
  781. if useJavascriptOref {
  782. let jsResult = await autosenseJavascript(
  783. glucose: glucose,
  784. pumpHistory: pumpHistory,
  785. basalprofile: basalprofile,
  786. profile: profile,
  787. carbs: carbs,
  788. temptargets: temptargets
  789. )
  790. return try jsResult.returnOrThrow()
  791. } else {
  792. let swiftResult = OpenAPSSwift
  793. .autosense(
  794. glucose: glucose,
  795. pumpHistory: pumpHistory,
  796. basalProfile: basalprofile,
  797. profile: profile,
  798. carbs: carbs,
  799. tempTargets: temptargets,
  800. clock: Date()
  801. )
  802. return try swiftResult.returnOrThrow()
  803. }
  804. }
  805. private func autosenseJavascript(
  806. glucose: JSON,
  807. pumpHistory: JSON,
  808. basalprofile: JSON,
  809. profile: JSON,
  810. carbs: JSON,
  811. temptargets: JSON
  812. ) async -> OrefFunctionResult {
  813. do {
  814. let result = try await withCheckedThrowingContinuation { continuation in
  815. jsWorker.inCommonContext { worker in
  816. worker.evaluateBatch(scripts: [
  817. Script(name: Prepare.log),
  818. Script(name: Bundle.autosens),
  819. Script(name: Prepare.autosens)
  820. ])
  821. let result = worker.call(function: Function.generate, with: [
  822. glucose,
  823. pumpHistory,
  824. basalprofile,
  825. profile,
  826. carbs,
  827. temptargets
  828. ])
  829. continuation.resume(returning: result)
  830. }
  831. }
  832. return .success(result)
  833. } catch {
  834. return .failure(error)
  835. }
  836. }
  837. private func determineBasal(
  838. glucose: JSON,
  839. currentTemp: JSON,
  840. iob: JSON,
  841. profile: JSON,
  842. autosens: JSON,
  843. meal: JSON,
  844. microBolusAllowed: Bool,
  845. reservoir: JSON,
  846. pumpHistory: JSON,
  847. preferences: JSON,
  848. basalProfile: JSON,
  849. trioCustomOrefVariables: JSON,
  850. useJavascriptOref: Bool
  851. ) async throws -> RawJSON {
  852. let clock = Date()
  853. if useJavascriptOref {
  854. let jsResult = await determineBasalJavascript(
  855. glucose: glucose,
  856. currentTemp: currentTemp,
  857. iob: iob,
  858. profile: profile,
  859. autosens: autosens,
  860. meal: meal,
  861. microBolusAllowed: microBolusAllowed,
  862. reservoir: reservoir,
  863. pumpHistory: pumpHistory,
  864. preferences: preferences,
  865. basalProfile: basalProfile,
  866. trioCustomOrefVariables: trioCustomOrefVariables,
  867. clock: clock
  868. )
  869. return try jsResult.returnOrThrow()
  870. } else {
  871. let swiftResult = OpenAPSSwift.determineBasal(
  872. glucose: glucose,
  873. currentTemp: currentTemp,
  874. iob: iob,
  875. profile: profile,
  876. autosens: autosens,
  877. meal: meal,
  878. microBolusAllowed: microBolusAllowed,
  879. reservoir: reservoir,
  880. pumpHistory: pumpHistory,
  881. preferences: preferences,
  882. basalProfile: basalProfile,
  883. trioCustomOrefVariables: trioCustomOrefVariables,
  884. clock: clock
  885. )
  886. return try swiftResult.returnOrThrow()
  887. }
  888. }
  889. private func determineBasalJavascript(
  890. glucose: JSON,
  891. currentTemp: JSON,
  892. iob: JSON,
  893. profile: JSON,
  894. autosens: JSON,
  895. meal: JSON,
  896. microBolusAllowed: Bool,
  897. reservoir: JSON,
  898. pumpHistory: JSON,
  899. preferences: JSON,
  900. basalProfile: JSON,
  901. trioCustomOrefVariables: JSON,
  902. clock: Date
  903. ) async -> OrefFunctionResult {
  904. do {
  905. let result = try await withCheckedThrowingContinuation { continuation in
  906. jsWorker.inCommonContext { worker in
  907. worker.evaluateBatch(scripts: [
  908. Script(name: Prepare.log),
  909. Script(name: Prepare.determineBasal),
  910. Script(name: Bundle.basalSetTemp),
  911. Script(name: Bundle.getLastGlucose),
  912. Script(name: Bundle.determineBasal)
  913. ])
  914. let result = worker.call(function: Function.generate, with: [
  915. iob,
  916. currentTemp,
  917. glucose,
  918. profile,
  919. autosens,
  920. meal,
  921. microBolusAllowed,
  922. reservoir,
  923. clock,
  924. pumpHistory,
  925. preferences,
  926. basalProfile,
  927. trioCustomOrefVariables
  928. ])
  929. continuation.resume(returning: result)
  930. }
  931. }
  932. return .success(result)
  933. } catch {
  934. return .failure(error)
  935. }
  936. }
  937. private func exportDefaultPreferences() -> RawJSON {
  938. dispatchPrecondition(condition: .onQueue(processQueue))
  939. return jsWorker.inCommonContext { worker in
  940. worker.evaluateBatch(scripts: [
  941. Script(name: Prepare.log),
  942. Script(name: Bundle.profile),
  943. Script(name: Prepare.profile)
  944. ])
  945. return worker.call(function: Function.exportDefaults, with: [])
  946. }
  947. }
  948. // use `internal` protection to expose to unit tests
  949. func makeProfileJavascript(
  950. preferences: JSON,
  951. pumpSettings: JSON,
  952. bgTargets: JSON,
  953. basalProfile: JSON,
  954. isf: JSON,
  955. carbRatio: JSON,
  956. tempTargets: JSON,
  957. model: JSON,
  958. autotune: JSON,
  959. trioSettings: JSON
  960. ) async -> OrefFunctionResult {
  961. do {
  962. let result = try await withCheckedThrowingContinuation { continuation in
  963. jsWorker.inCommonContext { worker in
  964. worker.evaluateBatch(scripts: [
  965. Script(name: Prepare.log),
  966. Script(name: Bundle.profile),
  967. Script(name: Prepare.profile)
  968. ])
  969. let result = worker.call(function: Function.generate, with: [
  970. pumpSettings,
  971. bgTargets,
  972. isf,
  973. basalProfile,
  974. preferences,
  975. carbRatio,
  976. tempTargets,
  977. model,
  978. autotune,
  979. trioSettings
  980. ])
  981. continuation.resume(returning: result)
  982. }
  983. }
  984. return .success(result)
  985. } catch {
  986. return .failure(error)
  987. }
  988. }
  989. private func makeProfile(
  990. preferences: JSON,
  991. pumpSettings: JSON,
  992. bgTargets: JSON,
  993. basalProfile: JSON,
  994. isf: JSON,
  995. carbRatio: JSON,
  996. tempTargets: JSON,
  997. model: JSON,
  998. autotune: JSON,
  999. trioSettings: JSON,
  1000. useJavascriptOref: Bool,
  1001. clock: Date
  1002. ) async throws -> RawJSON {
  1003. if useJavascriptOref {
  1004. let jsResult = await makeProfileJavascript(
  1005. preferences: preferences,
  1006. pumpSettings: pumpSettings,
  1007. bgTargets: bgTargets,
  1008. basalProfile: basalProfile,
  1009. isf: isf,
  1010. carbRatio: carbRatio,
  1011. tempTargets: tempTargets,
  1012. model: model,
  1013. autotune: autotune,
  1014. trioSettings: trioSettings
  1015. )
  1016. return try jsResult.returnOrThrow()
  1017. } else {
  1018. let swiftResult = OpenAPSSwift.makeProfile(
  1019. preferences: preferences,
  1020. pumpSettings: pumpSettings,
  1021. bgTargets: bgTargets,
  1022. basalProfile: basalProfile,
  1023. isf: isf,
  1024. carbRatio: carbRatio,
  1025. tempTargets: tempTargets,
  1026. model: model,
  1027. trioSettings: trioSettings,
  1028. clock: clock
  1029. )
  1030. return try swiftResult.returnOrThrow()
  1031. }
  1032. }
  1033. private func loadJSON(name: String) -> String {
  1034. try! String(contentsOf: Foundation.Bundle.main.url(forResource: "json/\(name)", withExtension: "json")!)
  1035. }
  1036. private func loadFileFromStorage(name: String) -> RawJSON {
  1037. storage.retrieveRaw(name) ?? OpenAPS.defaults(for: name)
  1038. }
  1039. private func loadFileFromStorageAsync(name: String) async -> RawJSON {
  1040. await withCheckedContinuation { continuation in
  1041. DispatchQueue.global(qos: .userInitiated).async {
  1042. let result = self.storage.retrieveRaw(name) ?? OpenAPS.defaults(for: name)
  1043. continuation.resume(returning: result)
  1044. }
  1045. }
  1046. }
  1047. static func defaults(for file: String) -> RawJSON {
  1048. let prefix = file.hasSuffix(".json") ? "json/defaults" : "javascript"
  1049. guard let url = Foundation.Bundle.main.url(forResource: "\(prefix)/\(file)", withExtension: "") else {
  1050. return ""
  1051. }
  1052. return (try? String(contentsOf: url)) ?? ""
  1053. }
  1054. func processAndSave(forecastData: [String: [Int]]) {
  1055. let currentDate = Date()
  1056. let context = newContext("processAndSave")
  1057. context.perform {
  1058. for (type, values) in forecastData {
  1059. self.createForecast(type: type, values: values, date: currentDate, context: context)
  1060. }
  1061. do {
  1062. guard context.hasChanges else { return }
  1063. try context.save()
  1064. } catch {
  1065. print(error.localizedDescription)
  1066. }
  1067. }
  1068. }
  1069. func createForecast(type: String, values: [Int], date: Date, context: NSManagedObjectContext) {
  1070. let forecast = Forecast(context: context)
  1071. forecast.id = UUID()
  1072. forecast.date = date
  1073. forecast.type = type
  1074. for (index, value) in values.enumerated() {
  1075. let forecastValue = ForecastValue(context: context)
  1076. forecastValue.value = Int32(value)
  1077. forecastValue.index = Int32(index)
  1078. forecastValue.forecast = forecast
  1079. }
  1080. }
  1081. }
  1082. // Non-Async fetch methods for trio_custom_oref_variables
  1083. extension OpenAPS {
  1084. func fetchActiveTempTargets(on context: NSManagedObjectContext) throws -> [TempTargetStored] {
  1085. try CoreDataStack.shared.fetchEntities(
  1086. ofType: TempTargetStored.self,
  1087. onContext: context,
  1088. predicate: NSPredicate.lastActiveTempTarget,
  1089. key: "date",
  1090. ascending: false,
  1091. fetchLimit: 1
  1092. ) as? [TempTargetStored] ?? []
  1093. }
  1094. func fetchActiveOverrides(on context: NSManagedObjectContext) throws -> [OverrideStored] {
  1095. try CoreDataStack.shared.fetchEntities(
  1096. ofType: OverrideStored.self,
  1097. onContext: context,
  1098. predicate: NSPredicate.lastActiveOverride,
  1099. key: "date",
  1100. ascending: false,
  1101. fetchLimit: 1
  1102. ) as? [OverrideStored] ?? []
  1103. }
  1104. func fetchHistoricalTDDData(from date: Date, on context: NSManagedObjectContext) throws -> [[String: Any]] {
  1105. try CoreDataStack.shared.fetchEntities(
  1106. ofType: TDDStored.self,
  1107. onContext: context,
  1108. predicate: NSPredicate(format: "date > %@ AND total > 0", date as NSDate),
  1109. key: "date",
  1110. ascending: true,
  1111. propertiesToFetch: ["date", "total"]
  1112. ) as? [[String: Any]] ?? []
  1113. }
  1114. func fetchGlucose(on context: NSManagedObjectContext) throws -> [GlucoseStored] {
  1115. let results = try CoreDataStack.shared.fetchEntities(
  1116. ofType: GlucoseStored.self,
  1117. onContext: context,
  1118. predicate: NSPredicate.predicateFor30MinAgo,
  1119. key: "date",
  1120. ascending: false,
  1121. fetchLimit: 4
  1122. )
  1123. return try context.perform {
  1124. guard let glucoseResults = results as? [GlucoseStored] else {
  1125. throw CoreDataError.fetchError(function: #function, file: #file)
  1126. }
  1127. return glucoseResults
  1128. }
  1129. }
  1130. }