OpenAPS.swift 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  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. let context = CoreDataStack.shared.newTaskContext()
  10. let jsonConverter = JSONConverter()
  11. init(storage: FileStorage) {
  12. self.storage = storage
  13. }
  14. static let dateFormatter: ISO8601DateFormatter = {
  15. let formatter = ISO8601DateFormatter()
  16. formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
  17. return formatter
  18. }()
  19. // Helper function to convert a Decimal? to NSDecimalNumber?
  20. func decimalToNSDecimalNumber(_ value: Decimal?) -> NSDecimalNumber? {
  21. guard let value = value else { return nil }
  22. return NSDecimalNumber(decimal: value)
  23. }
  24. // Use the helper function for cleaner code
  25. func processDetermination(_ determination: Determination) async {
  26. await context.perform {
  27. let newOrefDetermination = OrefDetermination(context: self.context)
  28. newOrefDetermination.id = UUID()
  29. newOrefDetermination.insulinSensitivity = self.decimalToNSDecimalNumber(determination.isf)
  30. newOrefDetermination.currentTarget = self.decimalToNSDecimalNumber(determination.current_target)
  31. newOrefDetermination.eventualBG = determination.eventualBG.map(NSDecimalNumber.init)
  32. newOrefDetermination.deliverAt = determination.deliverAt
  33. newOrefDetermination.insulinForManualBolus = self.decimalToNSDecimalNumber(determination.insulinForManualBolus)
  34. newOrefDetermination.carbRatio = self.decimalToNSDecimalNumber(determination.carbRatio)
  35. newOrefDetermination.glucose = self.decimalToNSDecimalNumber(determination.bg)
  36. newOrefDetermination.reservoir = self.decimalToNSDecimalNumber(determination.reservoir)
  37. newOrefDetermination.insulinReq = self.decimalToNSDecimalNumber(determination.insulinReq)
  38. newOrefDetermination.temp = determination.temp?.rawValue ?? "absolute"
  39. newOrefDetermination.rate = self.decimalToNSDecimalNumber(determination.rate)
  40. newOrefDetermination.reason = determination.reason
  41. newOrefDetermination.duration = self.decimalToNSDecimalNumber(determination.duration)
  42. newOrefDetermination.iob = self.decimalToNSDecimalNumber(determination.iob)
  43. newOrefDetermination.threshold = self.decimalToNSDecimalNumber(determination.threshold)
  44. newOrefDetermination.minDelta = self.decimalToNSDecimalNumber(determination.minDelta)
  45. newOrefDetermination.sensitivityRatio = self.decimalToNSDecimalNumber(determination.sensitivityRatio)
  46. newOrefDetermination.expectedDelta = self.decimalToNSDecimalNumber(determination.expectedDelta)
  47. newOrefDetermination.cob = Int16(Int(determination.cob ?? 0))
  48. newOrefDetermination.manualBolusErrorString = self.decimalToNSDecimalNumber(determination.manualBolusErrorString)
  49. newOrefDetermination.tempBasal = determination.insulin?.temp_basal.map { NSDecimalNumber(decimal: $0) }
  50. newOrefDetermination.scheduledBasal = determination.insulin?.scheduled_basal.map { NSDecimalNumber(decimal: $0) }
  51. newOrefDetermination.bolus = determination.insulin?.bolus.map { NSDecimalNumber(decimal: $0) }
  52. newOrefDetermination.smbToDeliver = determination.units.map { NSDecimalNumber(decimal: $0) }
  53. newOrefDetermination.carbsRequired = Int16(Int(determination.carbsReq ?? 0))
  54. newOrefDetermination.isUploadedToNS = false
  55. if let predictions = determination.predictions {
  56. ["iob": predictions.iob, "zt": predictions.zt, "cob": predictions.cob, "uam": predictions.uam]
  57. .forEach { type, values in
  58. if let values = values {
  59. let forecast = Forecast(context: self.context)
  60. forecast.id = UUID()
  61. forecast.type = type
  62. forecast.date = Date()
  63. forecast.orefDetermination = newOrefDetermination
  64. for (index, value) in values.enumerated() {
  65. let forecastValue = ForecastValue(context: self.context)
  66. forecastValue.index = Int32(index)
  67. forecastValue.value = Int32(value)
  68. forecast.addToForecastValues(forecastValue)
  69. }
  70. newOrefDetermination.addToForecasts(forecast)
  71. }
  72. }
  73. }
  74. }
  75. // First save the current Determination to Core Data
  76. await attemptToSaveContext()
  77. }
  78. func attemptToSaveContext() async {
  79. await context.perform {
  80. do {
  81. guard self.context.hasChanges else { return }
  82. try self.context.save()
  83. } catch {
  84. debugPrint("\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to save Determination to Core Data")
  85. }
  86. }
  87. }
  88. // fetch glucose to pass it to the meal function and to determine basal
  89. private func fetchAndProcessGlucose() async -> String {
  90. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  91. ofType: GlucoseStored.self,
  92. onContext: context,
  93. predicate: NSPredicate.predicateForOneDayAgoInMinutes,
  94. key: "date",
  95. ascending: false,
  96. fetchLimit: 72,
  97. batchSize: 24
  98. )
  99. return await context.perform {
  100. guard let glucoseResults = results as? [GlucoseStored] else {
  101. return ""
  102. }
  103. // convert to JSON
  104. return self.jsonConverter.convertToJSON(glucoseResults)
  105. }
  106. }
  107. private func fetchAndProcessCarbs(additionalCarbs: Decimal? = nil) async -> String {
  108. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  109. ofType: CarbEntryStored.self,
  110. onContext: context,
  111. predicate: NSPredicate.predicateForOneDayAgo,
  112. key: "date",
  113. ascending: false
  114. )
  115. let json = await context.perform {
  116. guard let carbResults = results as? [CarbEntryStored] else {
  117. return ""
  118. }
  119. var jsonArray = self.jsonConverter.convertToJSON(carbResults)
  120. if let additionalCarbs = additionalCarbs {
  121. let additionalEntry = [
  122. "carbs": Double(additionalCarbs),
  123. "actualDate": ISO8601DateFormatter().string(from: Date()),
  124. "id": UUID().uuidString,
  125. "note": NSNull(),
  126. "protein": 0,
  127. "created_at": ISO8601DateFormatter().string(from: Date()),
  128. "isFPU": false,
  129. "fat": 0,
  130. "enteredBy": "Trio"
  131. ] as [String: Any]
  132. // Assuming jsonArray is a String, convert it to a list of dictionaries first
  133. if let jsonData = jsonArray.data(using: .utf8) {
  134. var jsonList = try? JSONSerialization.jsonObject(with: jsonData, options: []) as? [[String: Any]]
  135. jsonList?.append(additionalEntry)
  136. // Convert back to JSON string
  137. if let updatedJsonData = try? JSONSerialization
  138. .data(withJSONObject: jsonList ?? [], options: .prettyPrinted)
  139. {
  140. jsonArray = String(data: updatedJsonData, encoding: .utf8) ?? jsonArray
  141. }
  142. }
  143. }
  144. return jsonArray
  145. }
  146. return json
  147. }
  148. private func fetchPumpHistoryObjectIDs() async -> [NSManagedObjectID]? {
  149. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  150. ofType: PumpEventStored.self,
  151. onContext: context,
  152. predicate: NSPredicate.pumpHistoryLast1440Minutes,
  153. key: "timestamp",
  154. ascending: false,
  155. batchSize: 50
  156. )
  157. return await context.perform {
  158. guard let pumpEventResults = results as? [PumpEventStored] else {
  159. return nil
  160. }
  161. return pumpEventResults.map(\.objectID)
  162. }
  163. }
  164. private func parsePumpHistory(_ pumpHistoryObjectIDs: [NSManagedObjectID], iob: Decimal? = nil) async -> String {
  165. // Return an empty JSON object if the list of object IDs is empty
  166. guard !pumpHistoryObjectIDs.isEmpty else { return "{}" }
  167. // Execute all operations on the background context
  168. return await context.perform {
  169. // Load and map pump events to DTOs
  170. var dtos = self.loadAndMapPumpEvents(pumpHistoryObjectIDs)
  171. // Optionally add the IOB as a DTO
  172. if let iob = iob {
  173. let iobDTO = self.createIOBDTO(iob: iob)
  174. dtos.insert(iobDTO, at: 0)
  175. }
  176. // Convert the DTOs to JSON
  177. return self.jsonConverter.convertToJSON(dtos)
  178. }
  179. }
  180. private func loadAndMapPumpEvents(_ pumpHistoryObjectIDs: [NSManagedObjectID]) -> [PumpEventDTO] {
  181. // Load the pump events from the object IDs
  182. let pumpHistory: [PumpEventStored] = pumpHistoryObjectIDs
  183. .compactMap { self.context.object(with: $0) as? PumpEventStored }
  184. // Create the DTOs
  185. let dtos: [PumpEventDTO] = pumpHistory.flatMap { event -> [PumpEventDTO] in
  186. var eventDTOs: [PumpEventDTO] = []
  187. if let bolusDTO = event.toBolusDTOEnum() {
  188. eventDTOs.append(bolusDTO)
  189. }
  190. if let tempBasalDurationDTO = event.toTempBasalDurationDTOEnum() {
  191. eventDTOs.append(tempBasalDurationDTO)
  192. }
  193. if let tempBasalDTO = event.toTempBasalDTOEnum() {
  194. eventDTOs.append(tempBasalDTO)
  195. }
  196. return eventDTOs
  197. }
  198. return dtos
  199. }
  200. private func createIOBDTO(iob: Decimal) -> PumpEventDTO {
  201. let oneSecondAgo = Calendar.current
  202. .date(
  203. byAdding: .second,
  204. value: -1,
  205. to: Date()
  206. )! // adding -1s to the current Date ensures that oref actually uses the mock entry to calculate iob and not guard it away
  207. let dateFormatted = PumpEventStored.dateFormatter.string(from: oneSecondAgo)
  208. let bolusDTO = BolusDTO(
  209. id: UUID().uuidString,
  210. timestamp: dateFormatted,
  211. amount: Double(iob),
  212. isExternal: false,
  213. isSMB: true,
  214. duration: 0,
  215. _type: "Bolus"
  216. )
  217. return .bolus(bolusDTO)
  218. }
  219. func determineBasal(
  220. currentTemp: TempBasal,
  221. clock: Date = Date(),
  222. carbs: Decimal? = nil,
  223. iob: Decimal? = nil,
  224. simulation: Bool = false
  225. ) async throws -> Determination? {
  226. debug(.openAPS, "Start determineBasal")
  227. // temp_basal
  228. let tempBasal = currentTemp.rawJSON
  229. // Perform asynchronous calls in parallel
  230. async let pumpHistoryObjectIDs = fetchPumpHistoryObjectIDs() ?? []
  231. async let carbs = fetchAndProcessCarbs(additionalCarbs: carbs ?? 0)
  232. async let glucose = fetchAndProcessGlucose()
  233. async let oref2 = oref2()
  234. async let profileAsync = loadFileFromStorageAsync(name: Settings.profile)
  235. async let basalAsync = loadFileFromStorageAsync(name: Settings.basalProfile)
  236. async let autosenseAsync = loadFileFromStorageAsync(name: Settings.autosense)
  237. async let reservoirAsync = loadFileFromStorageAsync(name: Monitor.reservoir)
  238. async let preferencesAsync = loadFileFromStorageAsync(name: Settings.preferences)
  239. // Await the results of asynchronous tasks
  240. let (
  241. pumpHistoryJSON,
  242. carbsAsJSON,
  243. glucoseAsJSON,
  244. oref2_variables,
  245. profile,
  246. basalProfile,
  247. autosens,
  248. reservoir,
  249. preferences
  250. ) = await (
  251. parsePumpHistory(await pumpHistoryObjectIDs, iob: iob),
  252. carbs,
  253. glucose,
  254. oref2,
  255. profileAsync,
  256. basalAsync,
  257. autosenseAsync,
  258. reservoirAsync,
  259. preferencesAsync
  260. )
  261. // Meal calculation
  262. let meal = try await self.meal(
  263. pumphistory: pumpHistoryJSON,
  264. profile: profile,
  265. basalProfile: basalProfile,
  266. clock: clock,
  267. carbs: carbsAsJSON,
  268. glucose: glucoseAsJSON
  269. )
  270. // IOB calculation
  271. let iob = try await self.iob(
  272. pumphistory: pumpHistoryJSON,
  273. profile: profile,
  274. clock: clock,
  275. autosens: autosens.isEmpty ? .null : autosens
  276. )
  277. // TODO: refactor this to core data
  278. if !simulation {
  279. storage.save(iob, as: Monitor.iob)
  280. }
  281. // Determine basal
  282. let orefDetermination = try await determineBasal(
  283. glucose: glucoseAsJSON,
  284. currentTemp: tempBasal,
  285. iob: iob,
  286. profile: profile,
  287. autosens: autosens.isEmpty ? .null : autosens,
  288. meal: meal,
  289. microBolusAllowed: true,
  290. reservoir: reservoir,
  291. pumpHistory: pumpHistoryJSON,
  292. preferences: preferences,
  293. basalProfile: basalProfile,
  294. oref2_variables: oref2_variables
  295. )
  296. debug(.openAPS, "Determinated: \(orefDetermination)")
  297. if var determination = Determination(from: orefDetermination), let deliverAt = determination.deliverAt {
  298. // set both timestamp and deliverAt to the SAME date; this will be updated for timestamp once it is enacted
  299. // AAPS does it the same way! we'll follow their example!
  300. determination.timestamp = deliverAt
  301. if !simulation {
  302. // save to core data asynchronously
  303. await processDetermination(determination)
  304. }
  305. return determination
  306. } else {
  307. return nil
  308. }
  309. }
  310. func oref2() async -> RawJSON {
  311. await context.perform {
  312. // Retrieve user preferences
  313. let userPreferences = self.storage.retrieve(OpenAPS.Settings.preferences, as: Preferences.self)
  314. let weightPercentage = userPreferences?.weightPercentage ?? 1.0
  315. let maxSMBBasalMinutes = userPreferences?.maxSMBBasalMinutes ?? 30
  316. let maxUAMBasalMinutes = userPreferences?.maxUAMSMBBasalMinutes ?? 30
  317. // Fetch historical events for Total Daily Dose (TDD) calculation
  318. let tenDaysAgo = Date().addingTimeInterval(-10.days.timeInterval)
  319. let twoHoursAgo = Date().addingTimeInterval(-2.hours.timeInterval)
  320. let historicalTDDData = self.fetchHistoricalTDDData(from: tenDaysAgo)
  321. // Fetch the last active Override
  322. let activeOverrides = self.fetchActiveOverrides()
  323. let isOverrideActive = activeOverrides.first?.enabled ?? false
  324. let overridePercentage = Decimal(activeOverrides.first?.percentage ?? 100)
  325. let isOverrideIndefinite = activeOverrides.first?.indefinite ?? true
  326. let disableSMBs = activeOverrides.first?.smbIsOff ?? false
  327. let overrideTargetBG = activeOverrides.first?.target?.decimalValue ?? 0
  328. // Calculate averages for Total Daily Dose (TDD)
  329. let totalTDD = historicalTDDData.compactMap { ($0["totalDailyDose"] as? NSDecimalNumber)?.decimalValue }.reduce(0, +)
  330. let totalDaysCount = max(historicalTDDData.count, 1)
  331. // Fetch recent TDD data for the past two hours
  332. let recentTDDData = historicalTDDData.filter { ($0["timestamp"] as? Date ?? Date()) >= twoHoursAgo }
  333. let recentDataCount = max(recentTDDData.count, 1)
  334. let recentTotalTDD = recentTDDData.compactMap { ($0["totalDailyDose"] as? NSDecimalNumber)?.decimalValue }
  335. .reduce(0, +)
  336. let currentTDD = historicalTDDData.last?["totalDailyDose"] as? Decimal ?? 0
  337. let averageTDDLastTwoHours = recentTotalTDD / Decimal(recentDataCount)
  338. let averageTDDLastTenDays = totalTDD / Decimal(totalDaysCount)
  339. let weightedTDD = weightPercentage * averageTDDLastTwoHours + (1 - weightPercentage) * averageTDDLastTenDays
  340. // Prepare Oref2 variables
  341. let oref2Data = Oref2_variables(
  342. average_total_data: currentTDD > 0 ? averageTDDLastTenDays : 0,
  343. weightedAverage: currentTDD > 0 ? weightedTDD : 1,
  344. currentTDD: currentTDD,
  345. past2hoursAverage: currentTDD > 0 ? averageTDDLastTwoHours : 0,
  346. date: Date(),
  347. overridePercentage: overridePercentage,
  348. useOverride: isOverrideActive,
  349. duration: activeOverrides.first?.duration?.decimalValue ?? 0,
  350. unlimited: isOverrideIndefinite,
  351. overrideTarget: overrideTargetBG,
  352. smbIsOff: disableSMBs,
  353. advancedSettings: activeOverrides.first?.advancedSettings ?? false,
  354. isfAndCr: activeOverrides.first?.isfAndCr ?? false,
  355. isf: activeOverrides.first?.isf ?? false,
  356. cr: activeOverrides.first?.cr ?? false,
  357. smbIsScheduledOff: activeOverrides.first?.smbIsScheduledOff ?? false,
  358. start: (activeOverrides.first?.start ?? 0) as Decimal,
  359. end: (activeOverrides.first?.end ?? 0) as Decimal,
  360. smbMinutes: activeOverrides.first?.smbMinutes?.decimalValue ?? maxSMBBasalMinutes,
  361. uamMinutes: activeOverrides.first?.uamMinutes?.decimalValue ?? maxUAMBasalMinutes
  362. )
  363. // Save and return the Oref2 variables
  364. self.storage.save(oref2Data, as: OpenAPS.Monitor.oref2_variables)
  365. return self.loadFileFromStorage(name: Monitor.oref2_variables)
  366. }
  367. }
  368. func autosense() async throws -> Autosens? {
  369. debug(.openAPS, "Start autosens")
  370. // Perform asynchronous calls in parallel
  371. async let pumpHistoryObjectIDs = fetchPumpHistoryObjectIDs() ?? []
  372. async let carbs = fetchAndProcessCarbs()
  373. async let glucose = fetchAndProcessGlucose()
  374. async let getProfile = loadFileFromStorageAsync(name: Settings.profile)
  375. async let getBasalProfile = loadFileFromStorageAsync(name: Settings.basalProfile)
  376. async let getTempTargets = loadFileFromStorageAsync(name: Settings.tempTargets)
  377. // Await the results of asynchronous tasks
  378. let (pumpHistoryJSON, carbsAsJSON, glucoseAsJSON, profile, basalProfile, tempTargets) = await (
  379. parsePumpHistory(await pumpHistoryObjectIDs),
  380. carbs,
  381. glucose,
  382. getProfile,
  383. getBasalProfile,
  384. getTempTargets
  385. )
  386. // Autosense
  387. let autosenseResult = try await autosense(
  388. glucose: glucoseAsJSON,
  389. pumpHistory: pumpHistoryJSON,
  390. basalprofile: basalProfile,
  391. profile: profile,
  392. carbs: carbsAsJSON,
  393. temptargets: tempTargets
  394. )
  395. debug(.openAPS, "AUTOSENS: \(autosenseResult)")
  396. if var autosens = Autosens(from: autosenseResult) {
  397. autosens.timestamp = Date()
  398. await storage.saveAsync(autosens, as: Settings.autosense)
  399. return autosens
  400. } else {
  401. return nil
  402. }
  403. }
  404. func createProfiles() async {
  405. debug(.openAPS, "Start creating pump profile and user profile")
  406. // Load required settings and profiles asynchronously
  407. async let getPumpSettings = loadFileFromStorageAsync(name: Settings.settings)
  408. async let getBGTargets = loadFileFromStorageAsync(name: Settings.bgTargets)
  409. async let getBasalProfile = loadFileFromStorageAsync(name: Settings.basalProfile)
  410. async let getISF = loadFileFromStorageAsync(name: Settings.insulinSensitivities)
  411. async let getCR = loadFileFromStorageAsync(name: Settings.carbRatios)
  412. async let getTempTargets = loadFileFromStorageAsync(name: Settings.tempTargets)
  413. async let getModel = loadFileFromStorageAsync(name: Settings.model)
  414. async let getFreeAPS = loadFileFromStorageAsync(name: FreeAPS.settings)
  415. let (pumpSettings, bgTargets, basalProfile, isf, cr, tempTargets, model, freeaps) = await (
  416. getPumpSettings,
  417. getBGTargets,
  418. getBasalProfile,
  419. getISF,
  420. getCR,
  421. getTempTargets,
  422. getModel,
  423. getFreeAPS
  424. )
  425. // Retrieve user preferences, or set defaults if not available
  426. let preferences = storage.retrieve(OpenAPS.Settings.preferences, as: Preferences.self) ?? Preferences()
  427. let defaultHalfBasalTarget = preferences.halfBasalExerciseTarget
  428. var adjustedPreferences = preferences
  429. // Check for active Temp Targets and adjust HBT if necessary
  430. await context.perform {
  431. // Check if a Temp Target is active and if its HBT differs from user preferences
  432. if let activeTempTarget = self.fetchActiveTempTargets().first,
  433. activeTempTarget.enabled,
  434. let activeHBT = activeTempTarget.halfBasalTarget?.decimalValue,
  435. activeHBT != defaultHalfBasalTarget
  436. {
  437. // Overwrite the HBT in preferences
  438. adjustedPreferences.halfBasalExerciseTarget = activeHBT
  439. debug(.openAPS, "Updated halfBasalExerciseTarget to active Temp Target value: \(activeHBT)")
  440. }
  441. }
  442. do {
  443. let pumpProfile = try await makeProfile(
  444. preferences: adjustedPreferences,
  445. pumpSettings: pumpSettings,
  446. bgTargets: bgTargets,
  447. basalProfile: basalProfile,
  448. isf: isf,
  449. carbRatio: cr,
  450. tempTargets: tempTargets,
  451. model: model,
  452. autotune: RawJSON.null,
  453. freeaps: freeaps
  454. )
  455. let profile = try await makeProfile(
  456. preferences: adjustedPreferences,
  457. pumpSettings: pumpSettings,
  458. bgTargets: bgTargets,
  459. basalProfile: basalProfile,
  460. isf: isf,
  461. carbRatio: cr,
  462. tempTargets: tempTargets,
  463. model: model,
  464. autotune: RawJSON.null,
  465. freeaps: freeaps
  466. )
  467. // Save the profiles
  468. await storage.saveAsync(pumpProfile, as: Settings.pumpProfile)
  469. await storage.saveAsync(profile, as: Settings.profile)
  470. } catch {
  471. debug(
  472. .apsManager,
  473. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to create pump profile and normal profile: \(error)"
  474. )
  475. }
  476. }
  477. private func iob(pumphistory: JSON, profile: JSON, clock: JSON, autosens: JSON) async throws -> RawJSON {
  478. await withCheckedContinuation { continuation in
  479. jsWorker.inCommonContext { worker in
  480. worker.evaluateBatch(scripts: [
  481. Script(name: Prepare.log),
  482. Script(name: Bundle.iob),
  483. Script(name: Prepare.iob)
  484. ])
  485. let result = worker.call(function: Function.generate, with: [
  486. pumphistory,
  487. profile,
  488. clock,
  489. autosens
  490. ])
  491. continuation.resume(returning: result)
  492. }
  493. }
  494. }
  495. private func meal(
  496. pumphistory: JSON,
  497. profile: JSON,
  498. basalProfile: JSON,
  499. clock: JSON,
  500. carbs: JSON,
  501. glucose: JSON
  502. ) async throws -> RawJSON {
  503. try await withCheckedThrowingContinuation { continuation in
  504. jsWorker.inCommonContext { worker in
  505. worker.evaluateBatch(scripts: [
  506. Script(name: Prepare.log),
  507. Script(name: Bundle.meal),
  508. Script(name: Prepare.meal)
  509. ])
  510. let result = worker.call(function: Function.generate, with: [
  511. pumphistory,
  512. profile,
  513. clock,
  514. glucose,
  515. basalProfile,
  516. carbs
  517. ])
  518. continuation.resume(returning: result)
  519. }
  520. }
  521. }
  522. private func autosense(
  523. glucose: JSON,
  524. pumpHistory: JSON,
  525. basalprofile: JSON,
  526. profile: JSON,
  527. carbs: JSON,
  528. temptargets: JSON
  529. ) async throws -> RawJSON {
  530. try await withCheckedThrowingContinuation { continuation in
  531. jsWorker.inCommonContext { worker in
  532. worker.evaluateBatch(scripts: [
  533. Script(name: Prepare.log),
  534. Script(name: Bundle.autosens),
  535. Script(name: Prepare.autosens)
  536. ])
  537. let result = worker.call(function: Function.generate, with: [
  538. glucose,
  539. pumpHistory,
  540. basalprofile,
  541. profile,
  542. carbs,
  543. temptargets
  544. ])
  545. continuation.resume(returning: result)
  546. }
  547. }
  548. }
  549. private func determineBasal(
  550. glucose: JSON,
  551. currentTemp: JSON,
  552. iob: JSON,
  553. profile: JSON,
  554. autosens: JSON,
  555. meal: JSON,
  556. microBolusAllowed: Bool,
  557. reservoir: JSON,
  558. pumpHistory: JSON,
  559. preferences: JSON,
  560. basalProfile: JSON,
  561. oref2_variables: JSON
  562. ) async throws -> RawJSON {
  563. try await withCheckedThrowingContinuation { continuation in
  564. jsWorker.inCommonContext { worker in
  565. worker.evaluateBatch(scripts: [
  566. Script(name: Prepare.log),
  567. Script(name: Prepare.determineBasal),
  568. Script(name: Bundle.basalSetTemp),
  569. Script(name: Bundle.getLastGlucose),
  570. Script(name: Bundle.determineBasal)
  571. ])
  572. if let middleware = self.middlewareScript(name: OpenAPS.Middleware.determineBasal) {
  573. worker.evaluate(script: middleware)
  574. }
  575. let result = worker.call(function: Function.generate, with: [
  576. iob,
  577. currentTemp,
  578. glucose,
  579. profile,
  580. autosens,
  581. meal,
  582. microBolusAllowed,
  583. reservoir,
  584. Date(),
  585. pumpHistory,
  586. preferences,
  587. basalProfile,
  588. oref2_variables
  589. ])
  590. continuation.resume(returning: result)
  591. }
  592. }
  593. }
  594. private func exportDefaultPreferences() -> RawJSON {
  595. dispatchPrecondition(condition: .onQueue(processQueue))
  596. return jsWorker.inCommonContext { worker in
  597. worker.evaluateBatch(scripts: [
  598. Script(name: Prepare.log),
  599. Script(name: Bundle.profile),
  600. Script(name: Prepare.profile)
  601. ])
  602. return worker.call(function: Function.exportDefaults, with: [])
  603. }
  604. }
  605. private func makeProfile(
  606. preferences: JSON,
  607. pumpSettings: JSON,
  608. bgTargets: JSON,
  609. basalProfile: JSON,
  610. isf: JSON,
  611. carbRatio: JSON,
  612. tempTargets: JSON,
  613. model: JSON,
  614. autotune: JSON,
  615. freeaps: JSON
  616. ) async throws -> RawJSON {
  617. try await withCheckedThrowingContinuation { continuation in
  618. jsWorker.inCommonContext { worker in
  619. worker.evaluateBatch(scripts: [
  620. Script(name: Prepare.log),
  621. Script(name: Bundle.profile),
  622. Script(name: Prepare.profile)
  623. ])
  624. let result = worker.call(function: Function.generate, with: [
  625. pumpSettings,
  626. bgTargets,
  627. isf,
  628. basalProfile,
  629. preferences,
  630. carbRatio,
  631. tempTargets,
  632. model,
  633. autotune,
  634. freeaps
  635. ])
  636. continuation.resume(returning: result)
  637. }
  638. }
  639. }
  640. private func loadJSON(name: String) -> String {
  641. try! String(contentsOf: Foundation.Bundle.main.url(forResource: "json/\(name)", withExtension: "json")!)
  642. }
  643. private func loadFileFromStorage(name: String) -> RawJSON {
  644. storage.retrieveRaw(name) ?? OpenAPS.defaults(for: name)
  645. }
  646. private func loadFileFromStorageAsync(name: String) async -> RawJSON {
  647. await withCheckedContinuation { continuation in
  648. DispatchQueue.global(qos: .userInitiated).async {
  649. let result = self.storage.retrieveRaw(name) ?? OpenAPS.defaults(for: name)
  650. continuation.resume(returning: result)
  651. }
  652. }
  653. }
  654. private func middlewareScript(name: String) -> Script? {
  655. if let body = storage.retrieveRaw(name) {
  656. return Script(name: name, body: body)
  657. }
  658. if let url = Foundation.Bundle.main.url(forResource: "javascript/\(name)", withExtension: "") {
  659. return Script(name: name, body: try! String(contentsOf: url))
  660. }
  661. return nil
  662. }
  663. static func defaults(for file: String) -> RawJSON {
  664. let prefix = file.hasSuffix(".json") ? "json/defaults" : "javascript"
  665. guard let url = Foundation.Bundle.main.url(forResource: "\(prefix)/\(file)", withExtension: "") else {
  666. return ""
  667. }
  668. return (try? String(contentsOf: url)) ?? ""
  669. }
  670. func processAndSave(forecastData: [String: [Int]]) {
  671. let currentDate = Date()
  672. context.perform {
  673. for (type, values) in forecastData {
  674. self.createForecast(type: type, values: values, date: currentDate, context: self.context)
  675. }
  676. do {
  677. guard self.context.hasChanges else { return }
  678. try self.context.save()
  679. } catch {
  680. print(error.localizedDescription)
  681. }
  682. }
  683. }
  684. func createForecast(type: String, values: [Int], date: Date, context: NSManagedObjectContext) {
  685. let forecast = Forecast(context: context)
  686. forecast.id = UUID()
  687. forecast.date = date
  688. forecast.type = type
  689. for (index, value) in values.enumerated() {
  690. let forecastValue = ForecastValue(context: context)
  691. forecastValue.value = Int32(value)
  692. forecastValue.index = Int32(index)
  693. forecastValue.forecast = forecast
  694. }
  695. }
  696. }
  697. // Non-Async fetch methods for oref2
  698. extension OpenAPS {
  699. func fetchActiveTempTargets() -> [TempTargetStored] {
  700. CoreDataStack.shared.fetchEntities(
  701. ofType: TempTargetStored.self,
  702. onContext: context,
  703. predicate: NSPredicate.lastActiveTempTarget,
  704. key: "date",
  705. ascending: false,
  706. fetchLimit: 1
  707. ) as? [TempTargetStored] ?? []
  708. }
  709. func fetchActiveOverrides() -> [OverrideStored] {
  710. CoreDataStack.shared.fetchEntities(
  711. ofType: OverrideStored.self,
  712. onContext: context,
  713. predicate: NSPredicate.lastActiveOverride,
  714. key: "date",
  715. ascending: false,
  716. fetchLimit: 1
  717. ) as? [OverrideStored] ?? []
  718. }
  719. func fetchHistoricalTDDData(from date: Date) -> [[String: Any]] {
  720. CoreDataStack.shared.fetchEntities(
  721. ofType: OrefDetermination.self,
  722. onContext: context,
  723. predicate: NSPredicate(format: "timestamp > %@ AND totalDailyDose > 0", date as NSDate),
  724. key: "timestamp",
  725. ascending: true,
  726. propertiesToFetch: ["timestamp", "totalDailyDose"]
  727. ) as? [[String: Any]] ?? []
  728. }
  729. }