OpenAPS.swift 38 KB

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