OpenAPS.swift 41 KB

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