OpenAPS.swift 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  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.totalDailyDose = self.decimalToNSDecimalNumber(determination.tdd)
  30. newOrefDetermination.insulinSensitivity = self.decimalToNSDecimalNumber(determination.isf)
  31. newOrefDetermination.currentTarget = self.decimalToNSDecimalNumber(determination.current_target)
  32. newOrefDetermination.eventualBG = determination.eventualBG.map(NSDecimalNumber.init)
  33. newOrefDetermination.deliverAt = determination.deliverAt
  34. newOrefDetermination.insulinForManualBolus = self.decimalToNSDecimalNumber(determination.insulinForManualBolus)
  35. newOrefDetermination.carbRatio = self.decimalToNSDecimalNumber(determination.carbRatio)
  36. newOrefDetermination.glucose = self.decimalToNSDecimalNumber(determination.bg)
  37. newOrefDetermination.reservoir = self.decimalToNSDecimalNumber(determination.reservoir)
  38. newOrefDetermination.insulinReq = self.decimalToNSDecimalNumber(determination.insulinReq)
  39. newOrefDetermination.temp = determination.temp?.rawValue ?? "absolute"
  40. newOrefDetermination.rate = self.decimalToNSDecimalNumber(determination.rate)
  41. newOrefDetermination.reason = determination.reason
  42. newOrefDetermination.duration = self.decimalToNSDecimalNumber(determination.duration)
  43. newOrefDetermination.iob = self.decimalToNSDecimalNumber(determination.iob)
  44. newOrefDetermination.threshold = self.decimalToNSDecimalNumber(determination.threshold)
  45. newOrefDetermination.minDelta = self.decimalToNSDecimalNumber(determination.minDelta)
  46. newOrefDetermination.sensitivityRatio = self.decimalToNSDecimalNumber(determination.sensitivityRatio)
  47. newOrefDetermination.expectedDelta = self.decimalToNSDecimalNumber(determination.expectedDelta)
  48. newOrefDetermination.cob = Int16(Int(determination.cob ?? 0))
  49. newOrefDetermination.manualBolusErrorString = self.decimalToNSDecimalNumber(determination.manualBolusErrorString)
  50. newOrefDetermination.tempBasal = determination.insulin?.temp_basal.map { NSDecimalNumber(decimal: $0) }
  51. newOrefDetermination.scheduledBasal = determination.insulin?.scheduled_basal.map { NSDecimalNumber(decimal: $0) }
  52. newOrefDetermination.bolus = determination.insulin?.bolus.map { NSDecimalNumber(decimal: $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: self.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: self.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()
  78. }
  79. func attemptToSaveContext() async {
  80. await context.perform {
  81. do {
  82. guard self.context.hasChanges else { return }
  83. try self.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. private func fetchAndProcessGlucose() async -> String {
  91. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  92. ofType: GlucoseStored.self,
  93. onContext: context,
  94. predicate: NSPredicate.predicateForOneDayAgoInMinutes,
  95. key: "date",
  96. ascending: false,
  97. fetchLimit: 72,
  98. batchSize: 24
  99. )
  100. return await context.perform {
  101. guard let glucoseResults = results as? [GlucoseStored] else {
  102. return ""
  103. }
  104. // convert to JSON
  105. return self.jsonConverter.convertToJSON(glucoseResults)
  106. }
  107. }
  108. private func fetchAndProcessCarbs(additionalCarbs: Decimal? = nil) async -> String {
  109. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  110. ofType: CarbEntryStored.self,
  111. onContext: context,
  112. predicate: NSPredicate.predicateForOneDayAgo,
  113. key: "date",
  114. ascending: false
  115. )
  116. let json = await context.perform {
  117. guard let carbResults = results as? [CarbEntryStored] else {
  118. return ""
  119. }
  120. var jsonArray = self.jsonConverter.convertToJSON(carbResults)
  121. if let additionalCarbs = additionalCarbs {
  122. let additionalEntry = [
  123. "carbs": Double(additionalCarbs),
  124. "actualDate": ISO8601DateFormatter().string(from: Date()),
  125. "id": UUID().uuidString,
  126. "note": NSNull(),
  127. "protein": 0,
  128. "created_at": ISO8601DateFormatter().string(from: Date()),
  129. "isFPU": false,
  130. "fat": 0,
  131. "enteredBy": "Trio"
  132. ] as [String: Any]
  133. // Assuming jsonArray is a String, convert it to a list of dictionaries first
  134. if let jsonData = jsonArray.data(using: .utf8) {
  135. var jsonList = try? JSONSerialization.jsonObject(with: jsonData, options: []) as? [[String: Any]]
  136. jsonList?.append(additionalEntry)
  137. // Convert back to JSON string
  138. if let updatedJsonData = try? JSONSerialization
  139. .data(withJSONObject: jsonList ?? [], options: .prettyPrinted)
  140. {
  141. jsonArray = String(data: updatedJsonData, encoding: .utf8) ?? jsonArray
  142. }
  143. }
  144. }
  145. return jsonArray
  146. }
  147. return json
  148. }
  149. private func fetchPumpHistoryObjectIDs() async -> [NSManagedObjectID]? {
  150. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  151. ofType: PumpEventStored.self,
  152. onContext: context,
  153. predicate: NSPredicate.pumpHistoryLast1440Minutes,
  154. key: "timestamp",
  155. ascending: false,
  156. batchSize: 50
  157. )
  158. return await context.perform {
  159. guard let pumpEventResults = results as? [PumpEventStored] else {
  160. return nil
  161. }
  162. return pumpEventResults.map(\.objectID)
  163. }
  164. }
  165. private func parsePumpHistory(_ pumpHistoryObjectIDs: [NSManagedObjectID], iob: Decimal? = nil) async -> String {
  166. // Return an empty JSON object if the list of object IDs is empty
  167. guard !pumpHistoryObjectIDs.isEmpty else { return "{}" }
  168. // Execute all operations on the background context
  169. return await context.perform {
  170. // Load and map pump events to DTOs
  171. var dtos = self.loadAndMapPumpEvents(pumpHistoryObjectIDs)
  172. // Optionally add the IOB as a DTO
  173. if let iob = iob {
  174. let iobDTO = self.createIOBDTO(iob: iob)
  175. dtos.insert(iobDTO, at: 0)
  176. }
  177. // Convert the DTOs to JSON
  178. return self.jsonConverter.convertToJSON(dtos)
  179. }
  180. }
  181. private func loadAndMapPumpEvents(_ pumpHistoryObjectIDs: [NSManagedObjectID]) -> [PumpEventDTO] {
  182. // Load the pump events from the object IDs
  183. let pumpHistory: [PumpEventStored] = pumpHistoryObjectIDs
  184. .compactMap { self.context.object(with: $0) as? PumpEventStored }
  185. // Create the DTOs
  186. let dtos: [PumpEventDTO] = pumpHistory.flatMap { event -> [PumpEventDTO] in
  187. var eventDTOs: [PumpEventDTO] = []
  188. if let bolusDTO = event.toBolusDTOEnum() {
  189. eventDTOs.append(bolusDTO)
  190. }
  191. if let tempBasalDurationDTO = event.toTempBasalDurationDTOEnum() {
  192. eventDTOs.append(tempBasalDurationDTO)
  193. }
  194. if let tempBasalDTO = event.toTempBasalDTOEnum() {
  195. eventDTOs.append(tempBasalDTO)
  196. }
  197. return eventDTOs
  198. }
  199. return dtos
  200. }
  201. private func createIOBDTO(iob: Decimal) -> PumpEventDTO {
  202. let oneSecondAgo = Calendar.current
  203. .date(
  204. byAdding: .second,
  205. value: -1,
  206. to: Date()
  207. )! // adding -1s to the current Date ensures that oref actually uses the mock entry to calculate iob and not guard it away
  208. let dateFormatted = PumpEventStored.dateFormatter.string(from: oneSecondAgo)
  209. let bolusDTO = BolusDTO(
  210. id: UUID().uuidString,
  211. timestamp: dateFormatted,
  212. amount: Double(iob),
  213. isExternal: false,
  214. isSMB: true,
  215. duration: 0,
  216. _type: "Bolus"
  217. )
  218. return .bolus(bolusDTO)
  219. }
  220. func determineBasal(
  221. currentTemp: TempBasal,
  222. clock: Date = Date(),
  223. carbs: Decimal? = nil,
  224. iob: Decimal? = nil,
  225. simulation: Bool = false
  226. ) async throws -> Determination? {
  227. debug(.openAPS, "Start determineBasal")
  228. // temp_basal
  229. let tempBasal = currentTemp.rawJSON
  230. // Perform asynchronous calls in parallel
  231. async let pumpHistoryObjectIDs = fetchPumpHistoryObjectIDs() ?? []
  232. async let carbs = fetchAndProcessCarbs(additionalCarbs: carbs ?? 0)
  233. async let glucose = fetchAndProcessGlucose()
  234. async let oref2 = oref2()
  235. async let profileAsync = loadFileFromStorageAsync(name: Settings.profile)
  236. async let basalAsync = loadFileFromStorageAsync(name: Settings.basalProfile)
  237. async let autosenseAsync = loadFileFromStorageAsync(name: Settings.autosense)
  238. async let reservoirAsync = loadFileFromStorageAsync(name: Monitor.reservoir)
  239. async let preferencesAsync = loadFileFromStorageAsync(name: Settings.preferences)
  240. // Await the results of asynchronous tasks
  241. let (
  242. pumpHistoryJSON,
  243. carbsAsJSON,
  244. glucoseAsJSON,
  245. oref2_variables,
  246. profile,
  247. basalProfile,
  248. autosens,
  249. reservoir,
  250. preferences
  251. ) = await (
  252. parsePumpHistory(await pumpHistoryObjectIDs, iob: iob),
  253. carbs,
  254. glucose,
  255. oref2,
  256. profileAsync,
  257. basalAsync,
  258. autosenseAsync,
  259. reservoirAsync,
  260. preferencesAsync
  261. )
  262. // Meal calculation
  263. let meal = try await self.meal(
  264. pumphistory: pumpHistoryJSON,
  265. profile: profile,
  266. basalProfile: basalProfile,
  267. clock: clock,
  268. carbs: carbsAsJSON,
  269. glucose: glucoseAsJSON
  270. )
  271. // IOB calculation
  272. let iob = try await self.iob(
  273. pumphistory: pumpHistoryJSON,
  274. profile: profile,
  275. clock: clock,
  276. autosens: autosens.isEmpty ? .null : autosens
  277. )
  278. // TODO: refactor this to core data
  279. if !simulation {
  280. storage.save(iob, as: Monitor.iob)
  281. }
  282. // Determine basal
  283. let orefDetermination = try await determineBasal(
  284. glucose: glucoseAsJSON,
  285. currentTemp: tempBasal,
  286. iob: iob,
  287. profile: profile,
  288. autosens: autosens.isEmpty ? .null : autosens,
  289. meal: meal,
  290. microBolusAllowed: true,
  291. reservoir: reservoir,
  292. pumpHistory: pumpHistoryJSON,
  293. preferences: preferences,
  294. basalProfile: basalProfile,
  295. oref2_variables: oref2_variables
  296. )
  297. debug(.openAPS, "Determinated: \(orefDetermination)")
  298. if var determination = Determination(from: orefDetermination), let deliverAt = determination.deliverAt {
  299. // set both timestamp and deliverAt to the SAME date; this will be updated for timestamp once it is enacted
  300. // AAPS does it the same way! we'll follow their example!
  301. determination.timestamp = deliverAt
  302. if !simulation {
  303. // save to core data asynchronously
  304. await processDetermination(determination)
  305. }
  306. return determination
  307. } else {
  308. return nil
  309. }
  310. }
  311. func oref2() async -> RawJSON {
  312. await context.perform {
  313. // Retrieve preferences
  314. let preferences = self.storage.retrieve(OpenAPS.Settings.preferences, as: Preferences.self)
  315. var hbt_ = preferences?.halfBasalExerciseTarget ?? 160
  316. let wp = preferences?.weightPercentage ?? 1.0
  317. let smbMinutes = preferences?.maxSMBBasalMinutes ?? 30
  318. let uamMinutes = preferences?.maxUAMSMBBasalMinutes ?? 30
  319. let tenDaysAgo = Date().addingTimeInterval(-10.days.timeInterval)
  320. let twoHoursAgo = Date().addingTimeInterval(-2.hours.timeInterval)
  321. // Fetch unique events for TDD calculation
  322. var uniqueEvents = [[String: Any]]()
  323. let requestTDD = OrefDetermination.fetchRequest() as NSFetchRequest<NSFetchRequestResult>
  324. requestTDD.predicate = NSPredicate(format: "timestamp > %@ AND totalDailyDose > 0", tenDaysAgo as NSDate)
  325. requestTDD.propertiesToFetch = ["timestamp", "totalDailyDose"]
  326. let sortTDD = NSSortDescriptor(key: "timestamp", ascending: true)
  327. requestTDD.sortDescriptors = [sortTDD]
  328. requestTDD.resultType = .dictionaryResultType
  329. do {
  330. if let fetchedResults = try self.context.fetch(requestTDD) as? [[String: Any]] {
  331. uniqueEvents = fetchedResults
  332. }
  333. } catch {
  334. debugPrint("Failed to fetch TDD Data")
  335. }
  336. // Get the last active Override
  337. var overrideArray = [OverrideStored]()
  338. let requestOverrides = OverrideStored.fetchRequest() as NSFetchRequest<OverrideStored>
  339. let sortOverride = NSSortDescriptor(key: "date", ascending: false)
  340. requestOverrides.sortDescriptors = [sortOverride]
  341. requestOverrides.predicate = NSPredicate.lastActiveOverride
  342. requestOverrides.fetchLimit = 1
  343. try? overrideArray = self.context.fetch(requestOverrides)
  344. // Get the last active Temp Target
  345. var tempTargetsArray = [TempTargetStored]()
  346. let requestTempTargets = TempTargetStored.fetchRequest() as NSFetchRequest<TempTargetStored>
  347. let sortTT = NSSortDescriptor(key: "date", ascending: false)
  348. requestTempTargets.sortDescriptors = [sortTT]
  349. requestTempTargets.predicate = NSPredicate.lastActiveTempTarget
  350. requestTempTargets.fetchLimit = 1
  351. try? tempTargetsArray = self.context.fetch(requestTempTargets)
  352. var isTemptargetActive = tempTargetsArray.first?.enabled ?? false
  353. // Calculate averages for TDD
  354. let total = uniqueEvents.compactMap { ($0["totalDailyDose"] as? NSDecimalNumber)?.decimalValue }.reduce(0, +)
  355. var indices = uniqueEvents.count
  356. // Fetch data for the past two hours
  357. let twoHoursArray = uniqueEvents.filter { ($0["timestamp"] as? Date ?? Date()) >= twoHoursAgo }
  358. var nrOfIndices = twoHoursArray.count
  359. let totalAmount = twoHoursArray.compactMap { ($0["totalDailyDose"] as? NSDecimalNumber)?.decimalValue }
  360. .reduce(0, +)
  361. var useOverride = overrideArray.first?.enabled ?? false
  362. var overridePercentage = Decimal(overrideArray.first?.percentage ?? 100)
  363. var unlimited = overrideArray.first?.indefinite ?? true
  364. var disableSMBs = overrideArray.first?.smbIsOff ?? false
  365. let currentTDD = uniqueEvents.last?["totalDailyDose"] as? Decimal ?? 0
  366. if indices == 0 { indices = 1 }
  367. if nrOfIndices == 0 { nrOfIndices = 1 }
  368. let average2hours = totalAmount / Decimal(nrOfIndices)
  369. let average14 = total / Decimal(indices)
  370. let weightedAverage = wp * average2hours + (1 - wp) * average14
  371. var duration: Decimal = 0
  372. var overrideTarget: Decimal = 0
  373. // Handle Overrides
  374. if useOverride {
  375. duration = overrideArray.first?.duration?.decimalValue ?? 0
  376. overrideTarget = overrideArray.first?.target?.decimalValue ?? 0
  377. let advancedSettings = overrideArray.first?.advancedSettings ?? false
  378. let addedMinutes = Int(truncating: overrideArray.first?.duration ?? 0)
  379. let date = overrideArray.first?.date ?? Date()
  380. let overrideEndTime = date.addingTimeInterval(Double(addedMinutes) * 60)
  381. if overrideEndTime < Date(), !unlimited {
  382. // Override has expired
  383. useOverride = false
  384. let saveToCoreData = OverrideStored(context: self.context)
  385. saveToCoreData.enabled = false
  386. saveToCoreData.date = Date()
  387. saveToCoreData.duration = 0
  388. saveToCoreData.indefinite = false
  389. saveToCoreData.percentage = 100
  390. do {
  391. guard self.context.hasChanges else { return "{}" }
  392. try self.context.save()
  393. } catch {
  394. print(error.localizedDescription)
  395. }
  396. }
  397. }
  398. if !useOverride {
  399. // Reset to default values if no override is active
  400. unlimited = true
  401. overridePercentage = 100
  402. duration = 0
  403. overrideTarget = 0
  404. disableSMBs = false
  405. }
  406. // Temp Target Handling
  407. if isTemptargetActive {
  408. if let tempTarget = tempTargetsArray.first {
  409. let tempDuration = tempTarget.duration?.doubleValue ?? 0
  410. let halfBasalTarget = tempTarget.halfBasalTarget ?? NSDecimalNumber(decimal: hbt_)
  411. let startDate = tempTarget.date ?? Date()
  412. let tempTargetEndTime = startDate.addingTimeInterval(tempDuration * 60)
  413. let timeRemaining = tempTargetEndTime.timeIntervalSinceNow / 60 // Time remaining in minutes
  414. if timeRemaining > 0 {
  415. hbt_ = halfBasalTarget.decimalValue
  416. isTemptargetActive = true
  417. }
  418. }
  419. }
  420. // Prepare Oref2 variables
  421. let averages = Oref2_variables(
  422. average_total_data: currentTDD > 0 ? average14 : 0,
  423. weightedAverage: currentTDD > 0 ? weightedAverage : 1,
  424. past2hoursAverage: currentTDD > 0 ? average2hours : 0,
  425. date: Date(),
  426. isEnabled: isTemptargetActive,
  427. presetActive: isTemptargetActive,
  428. overridePercentage: overridePercentage,
  429. useOverride: useOverride,
  430. duration: duration,
  431. unlimited: unlimited,
  432. hbt: hbt_,
  433. overrideTarget: overrideTarget,
  434. smbIsOff: disableSMBs,
  435. advancedSettings: overrideArray.first?.advancedSettings ?? false,
  436. isfAndCr: overrideArray.first?.isfAndCr ?? false,
  437. isf: overrideArray.first?.isf ?? false,
  438. cr: overrideArray.first?.cr ?? false,
  439. smbIsScheduledOff: overrideArray.first?.smbIsScheduledOff ?? false,
  440. start: (overrideArray.first?.start ?? 0) as Decimal,
  441. end: (overrideArray.first?.end ?? 0) as Decimal,
  442. smbMinutes: overrideArray.first?.smbMinutes?.decimalValue ?? smbMinutes,
  443. uamMinutes: overrideArray.first?.uamMinutes?.decimalValue ?? uamMinutes
  444. )
  445. // Save and return the Oref2 variables
  446. self.storage.save(averages, as: OpenAPS.Monitor.oref2_variables)
  447. return self.loadFileFromStorage(name: Monitor.oref2_variables)
  448. }
  449. }
  450. func autosense() async throws -> Autosens? {
  451. debug(.openAPS, "Start autosens")
  452. // Perform asynchronous calls in parallel
  453. async let pumpHistoryObjectIDs = fetchPumpHistoryObjectIDs() ?? []
  454. async let carbs = fetchAndProcessCarbs()
  455. async let glucose = fetchAndProcessGlucose()
  456. async let getProfile = loadFileFromStorageAsync(name: Settings.profile)
  457. async let getBasalProfile = loadFileFromStorageAsync(name: Settings.basalProfile)
  458. async let getTempTargets = loadFileFromStorageAsync(name: Settings.tempTargets)
  459. // Await the results of asynchronous tasks
  460. let (pumpHistoryJSON, carbsAsJSON, glucoseAsJSON, profile, basalProfile, tempTargets) = await (
  461. parsePumpHistory(await pumpHistoryObjectIDs),
  462. carbs,
  463. glucose,
  464. getProfile,
  465. getBasalProfile,
  466. getTempTargets
  467. )
  468. // Autosense
  469. let autosenseResult = try await autosense(
  470. glucose: glucoseAsJSON,
  471. pumpHistory: pumpHistoryJSON,
  472. basalprofile: basalProfile,
  473. profile: profile,
  474. carbs: carbsAsJSON,
  475. temptargets: tempTargets
  476. )
  477. debug(.openAPS, "AUTOSENS: \(autosenseResult)")
  478. if var autosens = Autosens(from: autosenseResult) {
  479. autosens.timestamp = Date()
  480. await storage.saveAsync(autosens, as: Settings.autosense)
  481. return autosens
  482. } else {
  483. return nil
  484. }
  485. }
  486. func autotune(categorizeUamAsBasal: Bool = false, tuneInsulinCurve: Bool = false) async -> Autotune? {
  487. debug(.openAPS, "Start autotune")
  488. // Perform asynchronous calls in parallel
  489. async let pumpHistoryObjectIDs = fetchPumpHistoryObjectIDs() ?? []
  490. async let carbs = fetchAndProcessCarbs()
  491. async let glucose = fetchAndProcessGlucose()
  492. async let getProfile = loadFileFromStorageAsync(name: Settings.profile)
  493. async let getPumpProfile = loadFileFromStorageAsync(name: Settings.pumpProfile)
  494. async let getPreviousAutotune = storage.retrieveAsync(Settings.autotune, as: RawJSON.self)
  495. // Await the results of asynchronous tasks
  496. let (pumpHistoryJSON, carbsAsJSON, glucoseAsJSON, profile, pumpProfile, previousAutotune) = await (
  497. parsePumpHistory(await pumpHistoryObjectIDs),
  498. carbs,
  499. glucose,
  500. getProfile,
  501. getPumpProfile,
  502. getPreviousAutotune
  503. )
  504. // Error need to be handled here because the function is not declared as throws
  505. do {
  506. // Autotune Prepare
  507. let autotunePreppedGlucose = try await autotunePrepare(
  508. pumphistory: pumpHistoryJSON,
  509. profile: profile,
  510. glucose: glucoseAsJSON,
  511. pumpprofile: pumpProfile,
  512. carbs: carbsAsJSON,
  513. categorizeUamAsBasal: categorizeUamAsBasal,
  514. tuneInsulinCurve: tuneInsulinCurve
  515. )
  516. debug(.openAPS, "AUTOTUNE PREP: \(autotunePreppedGlucose)")
  517. // Autotune Run
  518. let autotuneResult = try await autotuneRun(
  519. autotunePreparedData: autotunePreppedGlucose,
  520. previousAutotuneResult: previousAutotune ?? profile,
  521. pumpProfile: pumpProfile
  522. )
  523. debug(.openAPS, "AUTOTUNE RESULT: \(autotuneResult)")
  524. if let autotune = Autotune(from: autotuneResult) {
  525. storage.save(autotuneResult, as: Settings.autotune)
  526. return autotune
  527. } else {
  528. return nil
  529. }
  530. } catch {
  531. debug(.openAPS, "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to prepare/run Autotune")
  532. return nil
  533. }
  534. }
  535. func makeProfiles(useAutotune _: Bool) async -> Autotune? {
  536. debug(.openAPS, "Start makeProfiles")
  537. async let getPreferences = loadFileFromStorageAsync(name: Settings.preferences)
  538. async let getPumpSettings = loadFileFromStorageAsync(name: Settings.settings)
  539. async let getBGTargets = loadFileFromStorageAsync(name: Settings.bgTargets)
  540. async let getBasalProfile = loadFileFromStorageAsync(name: Settings.basalProfile)
  541. async let getISF = loadFileFromStorageAsync(name: Settings.insulinSensitivities)
  542. async let getCR = loadFileFromStorageAsync(name: Settings.carbRatios)
  543. async let getTempTargets = loadFileFromStorageAsync(name: Settings.tempTargets)
  544. async let getModel = loadFileFromStorageAsync(name: Settings.model)
  545. async let getAutotune = loadFileFromStorageAsync(name: Settings.autotune)
  546. async let getFreeAPS = loadFileFromStorageAsync(name: FreeAPS.settings)
  547. let (preferences, pumpSettings, bgTargets, basalProfile, isf, cr, tempTargets, model, autotune, freeaps) = await (
  548. getPreferences,
  549. getPumpSettings,
  550. getBGTargets,
  551. getBasalProfile,
  552. getISF,
  553. getCR,
  554. getTempTargets,
  555. getModel,
  556. getAutotune,
  557. getFreeAPS
  558. )
  559. var adjustedPreferences = preferences
  560. if adjustedPreferences.isEmpty {
  561. adjustedPreferences = Preferences().rawJSON
  562. }
  563. do {
  564. // Pump Profile
  565. let pumpProfile = try await makeProfile(
  566. preferences: adjustedPreferences,
  567. pumpSettings: pumpSettings,
  568. bgTargets: bgTargets,
  569. basalProfile: basalProfile,
  570. isf: isf,
  571. carbRatio: cr,
  572. tempTargets: tempTargets,
  573. model: model,
  574. autotune: RawJSON.null,
  575. freeaps: freeaps
  576. )
  577. // Profile
  578. let profile = try await makeProfile(
  579. preferences: adjustedPreferences,
  580. pumpSettings: pumpSettings,
  581. bgTargets: bgTargets,
  582. basalProfile: basalProfile,
  583. isf: isf,
  584. carbRatio: cr,
  585. tempTargets: tempTargets,
  586. model: model,
  587. autotune: autotune.isEmpty ? .null : autotune,
  588. freeaps: freeaps
  589. )
  590. await storage.saveAsync(pumpProfile, as: Settings.pumpProfile)
  591. await storage.saveAsync(profile, as: Settings.profile)
  592. if let tunedProfile = Autotune(from: profile) {
  593. return tunedProfile
  594. } else {
  595. return nil
  596. }
  597. } catch {
  598. debug(
  599. .apsManager,
  600. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to execute makeProfiles() to return Autoune results"
  601. )
  602. return nil
  603. }
  604. }
  605. // MARK: - Private
  606. private func iob(pumphistory: JSON, profile: JSON, clock: JSON, autosens: JSON) async throws -> RawJSON {
  607. await withCheckedContinuation { continuation in
  608. jsWorker.inCommonContext { worker in
  609. worker.evaluateBatch(scripts: [
  610. Script(name: Prepare.log),
  611. Script(name: Bundle.iob),
  612. Script(name: Prepare.iob)
  613. ])
  614. let result = worker.call(function: Function.generate, with: [
  615. pumphistory,
  616. profile,
  617. clock,
  618. autosens
  619. ])
  620. continuation.resume(returning: result)
  621. }
  622. }
  623. }
  624. private func meal(
  625. pumphistory: JSON,
  626. profile: JSON,
  627. basalProfile: JSON,
  628. clock: JSON,
  629. carbs: JSON,
  630. glucose: JSON
  631. ) async throws -> RawJSON {
  632. try await withCheckedThrowingContinuation { continuation in
  633. jsWorker.inCommonContext { worker in
  634. worker.evaluateBatch(scripts: [
  635. Script(name: Prepare.log),
  636. Script(name: Bundle.meal),
  637. Script(name: Prepare.meal)
  638. ])
  639. let result = worker.call(function: Function.generate, with: [
  640. pumphistory,
  641. profile,
  642. clock,
  643. glucose,
  644. basalProfile,
  645. carbs
  646. ])
  647. continuation.resume(returning: result)
  648. }
  649. }
  650. }
  651. private func autosense(
  652. glucose: JSON,
  653. pumpHistory: JSON,
  654. basalprofile: JSON,
  655. profile: JSON,
  656. carbs: JSON,
  657. temptargets: JSON
  658. ) async throws -> RawJSON {
  659. try await withCheckedThrowingContinuation { continuation in
  660. jsWorker.inCommonContext { worker in
  661. worker.evaluateBatch(scripts: [
  662. Script(name: Prepare.log),
  663. Script(name: Bundle.autosens),
  664. Script(name: Prepare.autosens)
  665. ])
  666. let result = worker.call(function: Function.generate, with: [
  667. glucose,
  668. pumpHistory,
  669. basalprofile,
  670. profile,
  671. carbs,
  672. temptargets
  673. ])
  674. continuation.resume(returning: result)
  675. }
  676. }
  677. }
  678. private func autotunePrepare(
  679. pumphistory: JSON,
  680. profile: JSON,
  681. glucose: JSON,
  682. pumpprofile: JSON,
  683. carbs: JSON,
  684. categorizeUamAsBasal: Bool,
  685. tuneInsulinCurve: Bool
  686. ) async throws -> RawJSON {
  687. try await withCheckedThrowingContinuation { continuation in
  688. jsWorker.inCommonContext { worker in
  689. worker.evaluateBatch(scripts: [
  690. Script(name: Prepare.log),
  691. Script(name: Bundle.autotunePrep),
  692. Script(name: Prepare.autotunePrep)
  693. ])
  694. let result = worker.call(function: Function.generate, with: [
  695. pumphistory,
  696. profile,
  697. glucose,
  698. pumpprofile,
  699. carbs,
  700. categorizeUamAsBasal,
  701. tuneInsulinCurve
  702. ])
  703. continuation.resume(returning: result)
  704. }
  705. }
  706. }
  707. private func autotuneRun(
  708. autotunePreparedData: JSON,
  709. previousAutotuneResult: JSON,
  710. pumpProfile: JSON
  711. ) async throws -> RawJSON {
  712. try await withCheckedThrowingContinuation { continuation in
  713. jsWorker.inCommonContext { worker in
  714. worker.evaluateBatch(scripts: [
  715. Script(name: Prepare.log),
  716. Script(name: Bundle.autotuneCore),
  717. Script(name: Prepare.autotuneCore)
  718. ])
  719. let result = worker.call(function: Function.generate, with: [
  720. autotunePreparedData,
  721. previousAutotuneResult,
  722. pumpProfile
  723. ])
  724. continuation.resume(returning: result)
  725. }
  726. }
  727. }
  728. private func determineBasal(
  729. glucose: JSON,
  730. currentTemp: JSON,
  731. iob: JSON,
  732. profile: JSON,
  733. autosens: JSON,
  734. meal: JSON,
  735. microBolusAllowed: Bool,
  736. reservoir: JSON,
  737. pumpHistory: JSON,
  738. preferences: JSON,
  739. basalProfile: JSON,
  740. oref2_variables: JSON
  741. ) async throws -> RawJSON {
  742. try await withCheckedThrowingContinuation { continuation in
  743. jsWorker.inCommonContext { worker in
  744. worker.evaluateBatch(scripts: [
  745. Script(name: Prepare.log),
  746. Script(name: Prepare.determineBasal),
  747. Script(name: Bundle.basalSetTemp),
  748. Script(name: Bundle.getLastGlucose),
  749. Script(name: Bundle.determineBasal)
  750. ])
  751. if let middleware = self.middlewareScript(name: OpenAPS.Middleware.determineBasal) {
  752. worker.evaluate(script: middleware)
  753. }
  754. let result = worker.call(function: Function.generate, with: [
  755. iob,
  756. currentTemp,
  757. glucose,
  758. profile,
  759. autosens,
  760. meal,
  761. microBolusAllowed,
  762. reservoir,
  763. Date(),
  764. pumpHistory,
  765. preferences,
  766. basalProfile,
  767. oref2_variables
  768. ])
  769. continuation.resume(returning: result)
  770. }
  771. }
  772. }
  773. private func exportDefaultPreferences() -> RawJSON {
  774. dispatchPrecondition(condition: .onQueue(processQueue))
  775. return jsWorker.inCommonContext { worker in
  776. worker.evaluateBatch(scripts: [
  777. Script(name: Prepare.log),
  778. Script(name: Bundle.profile),
  779. Script(name: Prepare.profile)
  780. ])
  781. return worker.call(function: Function.exportDefaults, with: [])
  782. }
  783. }
  784. private func makeProfile(
  785. preferences: JSON,
  786. pumpSettings: JSON,
  787. bgTargets: JSON,
  788. basalProfile: JSON,
  789. isf: JSON,
  790. carbRatio: JSON,
  791. tempTargets: JSON,
  792. model: JSON,
  793. autotune: JSON,
  794. freeaps: JSON
  795. ) async throws -> RawJSON {
  796. try await withCheckedThrowingContinuation { continuation in
  797. jsWorker.inCommonContext { worker in
  798. worker.evaluateBatch(scripts: [
  799. Script(name: Prepare.log),
  800. Script(name: Bundle.profile),
  801. Script(name: Prepare.profile)
  802. ])
  803. let result = worker.call(function: Function.generate, with: [
  804. pumpSettings,
  805. bgTargets,
  806. isf,
  807. basalProfile,
  808. preferences,
  809. carbRatio,
  810. tempTargets,
  811. model,
  812. autotune,
  813. freeaps
  814. ])
  815. continuation.resume(returning: result)
  816. }
  817. }
  818. }
  819. private func loadJSON(name: String) -> String {
  820. try! String(contentsOf: Foundation.Bundle.main.url(forResource: "json/\(name)", withExtension: "json")!)
  821. }
  822. private func loadFileFromStorage(name: String) -> RawJSON {
  823. storage.retrieveRaw(name) ?? OpenAPS.defaults(for: name)
  824. }
  825. private func loadFileFromStorageAsync(name: String) async -> RawJSON {
  826. await withCheckedContinuation { continuation in
  827. DispatchQueue.global(qos: .userInitiated).async {
  828. let result = self.storage.retrieveRaw(name) ?? OpenAPS.defaults(for: name)
  829. continuation.resume(returning: result)
  830. }
  831. }
  832. }
  833. private func middlewareScript(name: String) -> Script? {
  834. if let body = storage.retrieveRaw(name) {
  835. return Script(name: "Middleware", body: body)
  836. }
  837. if let url = Foundation.Bundle.main.url(forResource: "javascript/\(name)", withExtension: "") {
  838. return Script(name: "Middleware", body: try! String(contentsOf: url))
  839. }
  840. return nil
  841. }
  842. static func defaults(for file: String) -> RawJSON {
  843. let prefix = file.hasSuffix(".json") ? "json/defaults" : "javascript"
  844. guard let url = Foundation.Bundle.main.url(forResource: "\(prefix)/\(file)", withExtension: "") else {
  845. return ""
  846. }
  847. return (try? String(contentsOf: url)) ?? ""
  848. }
  849. func processAndSave(forecastData: [String: [Int]]) {
  850. let currentDate = Date()
  851. context.perform {
  852. for (type, values) in forecastData {
  853. self.createForecast(type: type, values: values, date: currentDate, context: self.context)
  854. }
  855. do {
  856. guard self.context.hasChanges else { return }
  857. try self.context.save()
  858. } catch {
  859. print(error.localizedDescription)
  860. }
  861. }
  862. }
  863. func createForecast(type: String, values: [Int], date: Date, context: NSManagedObjectContext) {
  864. let forecast = Forecast(context: context)
  865. forecast.id = UUID()
  866. forecast.date = date
  867. forecast.type = type
  868. for (index, value) in values.enumerated() {
  869. let forecastValue = ForecastValue(context: context)
  870. forecastValue.value = Int32(value)
  871. forecastValue.index = Int32(index)
  872. forecastValue.forecast = forecast
  873. }
  874. }
  875. }