OpenAPS.swift 38 KB

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