OpenAPS.swift 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  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 tempBasalDurationDTO = event.toTempBasalDurationDTOEnum() {
  216. eventDTOs.append(tempBasalDurationDTO)
  217. }
  218. if let tempBasalDTO = event.toTempBasalDTOEnum() {
  219. eventDTOs.append(tempBasalDTO)
  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. // Retrieve preferences
  338. let preferences = self.storage.retrieve(OpenAPS.Settings.preferences, as: Preferences.self)
  339. var hbt_ = preferences?.halfBasalExerciseTarget ?? 160
  340. let wp = preferences?.weightPercentage ?? 1.0
  341. let smbMinutes = preferences?.maxSMBBasalMinutes ?? 30
  342. let uamMinutes = preferences?.maxUAMSMBBasalMinutes ?? 30
  343. let tenDaysAgo = Date().addingTimeInterval(-10.days.timeInterval)
  344. let twoHoursAgo = Date().addingTimeInterval(-2.hours.timeInterval)
  345. // Fetch unique events for TDD calculation
  346. var uniqueEvents = [[String: Any]]()
  347. let requestTDD = OrefDetermination.fetchRequest() as NSFetchRequest<NSFetchRequestResult>
  348. requestTDD.predicate = NSPredicate(format: "timestamp > %@ AND totalDailyDose > 0", tenDaysAgo as NSDate)
  349. requestTDD.propertiesToFetch = ["timestamp", "totalDailyDose"]
  350. let sortTDD = NSSortDescriptor(key: "timestamp", ascending: true)
  351. requestTDD.sortDescriptors = [sortTDD]
  352. requestTDD.resultType = .dictionaryResultType
  353. do {
  354. if let fetchedResults = try self.context.fetch(requestTDD) as? [[String: Any]] {
  355. uniqueEvents = fetchedResults
  356. }
  357. } catch {
  358. debugPrint("Failed to fetch TDD Data")
  359. }
  360. // Get the last active Override
  361. var overrideArray = [OverrideStored]()
  362. let requestOverrides = OverrideStored.fetchRequest() as NSFetchRequest<OverrideStored>
  363. let sortOverride = NSSortDescriptor(key: "date", ascending: false)
  364. requestOverrides.sortDescriptors = [sortOverride]
  365. requestOverrides.predicate = NSPredicate.lastActiveOverride
  366. requestOverrides.fetchLimit = 1
  367. try? overrideArray = self.context.fetch(requestOverrides)
  368. // Get the last active Temp Target
  369. var tempTargetsArray = [TempTargetStored]()
  370. let requestTempTargets = TempTargetStored.fetchRequest() as NSFetchRequest<TempTargetStored>
  371. let sortTT = NSSortDescriptor(key: "date", ascending: false)
  372. requestTempTargets.sortDescriptors = [sortTT]
  373. requestTempTargets.predicate = NSPredicate.lastActiveTempTarget
  374. requestTempTargets.fetchLimit = 1
  375. try? tempTargetsArray = self.context.fetch(requestTempTargets)
  376. var isTemptargetActive = tempTargetsArray.first?.enabled ?? false
  377. // Calculate averages for TDD
  378. let total = uniqueEvents.compactMap { ($0["totalDailyDose"] as? NSDecimalNumber)?.decimalValue }.reduce(0, +)
  379. var indices = uniqueEvents.count
  380. // Fetch data for the past two hours
  381. let twoHoursArray = uniqueEvents.filter { ($0["timestamp"] as? Date ?? Date()) >= twoHoursAgo }
  382. var nrOfIndices = twoHoursArray.count
  383. let totalAmount = twoHoursArray.compactMap { ($0["totalDailyDose"] as? NSDecimalNumber)?.decimalValue }.reduce(0, +)
  384. var useOverride = overrideArray.first?.enabled ?? false
  385. var overridePercentage = Decimal(overrideArray.first?.percentage ?? 100)
  386. var unlimited = overrideArray.first?.indefinite ?? true
  387. var disableSMBs = overrideArray.first?.smbIsOff ?? false
  388. let currentTDD = uniqueEvents.last?["totalDailyDose"] as? Decimal ?? 0
  389. if indices == 0 { indices = 1 }
  390. if nrOfIndices == 0 { nrOfIndices = 1 }
  391. let average2hours = totalAmount / Decimal(nrOfIndices)
  392. let average14 = total / Decimal(indices)
  393. let weightedAverage = wp * average2hours + (1 - wp) * average14
  394. var duration: Decimal = 0
  395. var overrideTarget: Decimal = 0
  396. // Handle Overrides
  397. if useOverride {
  398. duration = overrideArray.first?.duration?.decimalValue ?? 0
  399. overrideTarget = overrideArray.first?.target?.decimalValue ?? 0
  400. let advancedSettings = overrideArray.first?.advancedSettings ?? false
  401. let addedMinutes = Int(truncating: overrideArray.first?.duration ?? 0)
  402. let date = overrideArray.first?.date ?? Date()
  403. let overrideEndTime = date.addingTimeInterval(Double(addedMinutes) * 60)
  404. if overrideEndTime < Date(), !unlimited {
  405. // Override has expired
  406. useOverride = false
  407. let saveToCoreData = OverrideStored(context: self.context)
  408. saveToCoreData.enabled = false
  409. saveToCoreData.date = Date()
  410. saveToCoreData.duration = 0
  411. saveToCoreData.indefinite = false
  412. saveToCoreData.percentage = 100
  413. do {
  414. guard self.context.hasChanges else { return "{}" }
  415. try self.context.save()
  416. } catch {
  417. print(error.localizedDescription)
  418. }
  419. }
  420. }
  421. if !useOverride {
  422. // Reset to default values if no override is active
  423. unlimited = true
  424. overridePercentage = 100
  425. duration = 0
  426. overrideTarget = 0
  427. disableSMBs = false
  428. }
  429. // Temp Target Handling
  430. if isTemptargetActive {
  431. if let tempTarget = tempTargetsArray.first {
  432. let tempDuration = tempTarget.duration?.doubleValue ?? 0
  433. let halfBasalTarget = tempTarget.halfBasalTarget ?? NSDecimalNumber(decimal: hbt_)
  434. let startDate = tempTarget.date ?? Date()
  435. let tempTargetEndTime = startDate.addingTimeInterval(tempDuration * 60)
  436. let timeRemaining = tempTargetEndTime.timeIntervalSinceNow / 60 // Time remaining in minutes
  437. if timeRemaining > 0 {
  438. hbt_ = halfBasalTarget.decimalValue
  439. isTemptargetActive = true
  440. }
  441. }
  442. }
  443. // Prepare Oref2 variables
  444. let averages = Oref2_variables(
  445. average_total_data: currentTDD > 0 ? average14 : 0,
  446. weightedAverage: currentTDD > 0 ? weightedAverage : 1,
  447. past2hoursAverage: currentTDD > 0 ? average2hours : 0,
  448. date: Date(),
  449. isEnabled: isTemptargetActive,
  450. presetActive: isTemptargetActive,
  451. overridePercentage: overridePercentage,
  452. useOverride: useOverride,
  453. duration: duration,
  454. unlimited: unlimited,
  455. hbt: hbt_,
  456. overrideTarget: overrideTarget,
  457. smbIsOff: disableSMBs,
  458. advancedSettings: overrideArray.first?.advancedSettings ?? false,
  459. isfAndCr: overrideArray.first?.isfAndCr ?? false,
  460. isf: overrideArray.first?.isf ?? false,
  461. cr: overrideArray.first?.cr ?? false,
  462. smbMinutes: overrideArray.first?.smbMinutes?.decimalValue ?? smbMinutes,
  463. uamMinutes: overrideArray.first?.uamMinutes?.decimalValue ?? uamMinutes
  464. )
  465. // Save and return the Oref2 variables
  466. self.storage.save(averages, as: OpenAPS.Monitor.oref2_variables)
  467. return self.loadFileFromStorage(name: Monitor.oref2_variables)
  468. }
  469. }
  470. func autosense() async throws -> Autosens? {
  471. debug(.openAPS, "Start autosens")
  472. // Perform asynchronous calls in parallel
  473. async let pumpHistoryObjectIDs = fetchPumpHistoryObjectIDs() ?? []
  474. async let carbs = fetchAndProcessCarbs()
  475. async let glucose = fetchAndProcessGlucose()
  476. async let getProfile = loadFileFromStorageAsync(name: Settings.profile)
  477. async let getBasalProfile = loadFileFromStorageAsync(name: Settings.basalProfile)
  478. async let getTempTargets = loadFileFromStorageAsync(name: Settings.tempTargets)
  479. // Await the results of asynchronous tasks
  480. let (pumpHistoryJSON, carbsAsJSON, glucoseAsJSON, profile, basalProfile, tempTargets) = await (
  481. parsePumpHistory(await pumpHistoryObjectIDs),
  482. carbs,
  483. glucose,
  484. getProfile,
  485. getBasalProfile,
  486. getTempTargets
  487. )
  488. // Autosense
  489. let autosenseResult = try await autosense(
  490. glucose: glucoseAsJSON,
  491. pumpHistory: pumpHistoryJSON,
  492. basalprofile: basalProfile,
  493. profile: profile,
  494. carbs: carbsAsJSON,
  495. temptargets: tempTargets
  496. )
  497. debug(.openAPS, "AUTOSENS: \(autosenseResult)")
  498. if var autosens = Autosens(from: autosenseResult) {
  499. autosens.timestamp = Date()
  500. await storage.saveAsync(autosens, as: Settings.autosense)
  501. return autosens
  502. } else {
  503. return nil
  504. }
  505. }
  506. func autotune(categorizeUamAsBasal: Bool = false, tuneInsulinCurve: Bool = false) async -> Autotune? {
  507. debug(.openAPS, "Start autotune")
  508. // Perform asynchronous calls in parallel
  509. async let pumpHistoryObjectIDs = fetchPumpHistoryObjectIDs() ?? []
  510. async let carbs = fetchAndProcessCarbs()
  511. async let glucose = fetchAndProcessGlucose()
  512. async let getProfile = loadFileFromStorageAsync(name: Settings.profile)
  513. async let getPumpProfile = loadFileFromStorageAsync(name: Settings.pumpProfile)
  514. async let getPreviousAutotune = storage.retrieveAsync(Settings.autotune, as: RawJSON.self)
  515. // Await the results of asynchronous tasks
  516. let (pumpHistoryJSON, carbsAsJSON, glucoseAsJSON, profile, pumpProfile, previousAutotune) = await (
  517. parsePumpHistory(await pumpHistoryObjectIDs),
  518. carbs,
  519. glucose,
  520. getProfile,
  521. getPumpProfile,
  522. getPreviousAutotune
  523. )
  524. // Error need to be handled here because the function is not declared as throws
  525. do {
  526. // Autotune Prepare
  527. let autotunePreppedGlucose = try await autotunePrepare(
  528. pumphistory: pumpHistoryJSON,
  529. profile: profile,
  530. glucose: glucoseAsJSON,
  531. pumpprofile: pumpProfile,
  532. carbs: carbsAsJSON,
  533. categorizeUamAsBasal: categorizeUamAsBasal,
  534. tuneInsulinCurve: tuneInsulinCurve
  535. )
  536. debug(.openAPS, "AUTOTUNE PREP: \(autotunePreppedGlucose)")
  537. // Autotune Run
  538. let autotuneResult = try await autotuneRun(
  539. autotunePreparedData: autotunePreppedGlucose,
  540. previousAutotuneResult: previousAutotune ?? profile,
  541. pumpProfile: pumpProfile
  542. )
  543. debug(.openAPS, "AUTOTUNE RESULT: \(autotuneResult)")
  544. if let autotune = Autotune(from: autotuneResult) {
  545. storage.save(autotuneResult, as: Settings.autotune)
  546. return autotune
  547. } else {
  548. return nil
  549. }
  550. } catch {
  551. debug(.openAPS, "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to prepare/run Autotune")
  552. return nil
  553. }
  554. }
  555. func makeProfiles(useAutotune _: Bool) async -> Autotune? {
  556. debug(.openAPS, "Start makeProfiles")
  557. async let getPreferences = loadFileFromStorageAsync(name: Settings.preferences)
  558. async let getPumpSettings = loadFileFromStorageAsync(name: Settings.settings)
  559. async let getBGTargets = loadFileFromStorageAsync(name: Settings.bgTargets)
  560. async let getBasalProfile = loadFileFromStorageAsync(name: Settings.basalProfile)
  561. async let getISF = loadFileFromStorageAsync(name: Settings.insulinSensitivities)
  562. async let getCR = loadFileFromStorageAsync(name: Settings.carbRatios)
  563. async let getTempTargets = loadFileFromStorageAsync(name: Settings.tempTargets)
  564. async let getModel = loadFileFromStorageAsync(name: Settings.model)
  565. async let getAutotune = loadFileFromStorageAsync(name: Settings.autotune)
  566. async let getFreeAPS = loadFileFromStorageAsync(name: FreeAPS.settings)
  567. let (preferences, pumpSettings, bgTargets, basalProfile, isf, cr, tempTargets, model, autotune, freeaps) = await (
  568. getPreferences,
  569. getPumpSettings,
  570. getBGTargets,
  571. getBasalProfile,
  572. getISF,
  573. getCR,
  574. getTempTargets,
  575. getModel,
  576. getAutotune,
  577. getFreeAPS
  578. )
  579. var adjustedPreferences = preferences
  580. if adjustedPreferences.isEmpty {
  581. adjustedPreferences = Preferences().rawJSON
  582. }
  583. do {
  584. // Pump Profile
  585. let pumpProfile = try await makeProfile(
  586. preferences: adjustedPreferences,
  587. pumpSettings: pumpSettings,
  588. bgTargets: bgTargets,
  589. basalProfile: basalProfile,
  590. isf: isf,
  591. carbRatio: cr,
  592. tempTargets: tempTargets,
  593. model: model,
  594. autotune: RawJSON.null,
  595. freeaps: freeaps
  596. )
  597. // Profile
  598. let profile = try await makeProfile(
  599. preferences: adjustedPreferences,
  600. pumpSettings: pumpSettings,
  601. bgTargets: bgTargets,
  602. basalProfile: basalProfile,
  603. isf: isf,
  604. carbRatio: cr,
  605. tempTargets: tempTargets,
  606. model: model,
  607. autotune: autotune.isEmpty ? .null : autotune,
  608. freeaps: freeaps
  609. )
  610. await storage.saveAsync(pumpProfile, as: Settings.pumpProfile)
  611. await storage.saveAsync(profile, as: Settings.profile)
  612. if let tunedProfile = Autotune(from: profile) {
  613. return tunedProfile
  614. } else {
  615. return nil
  616. }
  617. } catch {
  618. debug(
  619. .apsManager,
  620. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to execute makeProfiles() to return Autoune results"
  621. )
  622. return nil
  623. }
  624. }
  625. // MARK: - Private
  626. private func iob(pumphistory: JSON, profile: JSON, clock: JSON, autosens: JSON) async throws -> RawJSON {
  627. await withCheckedContinuation { continuation in
  628. jsWorker.inCommonContext { worker in
  629. worker.evaluateBatch(scripts: [
  630. Script(name: Prepare.log),
  631. Script(name: Bundle.iob),
  632. Script(name: Prepare.iob)
  633. ])
  634. let result = worker.call(function: Function.generate, with: [
  635. pumphistory,
  636. profile,
  637. clock,
  638. autosens
  639. ])
  640. continuation.resume(returning: result)
  641. }
  642. }
  643. }
  644. private func meal(
  645. pumphistory: JSON,
  646. profile: JSON,
  647. basalProfile: JSON,
  648. clock: JSON,
  649. carbs: JSON,
  650. glucose: JSON
  651. ) async throws -> RawJSON {
  652. try await withCheckedThrowingContinuation { continuation in
  653. jsWorker.inCommonContext { worker in
  654. worker.evaluateBatch(scripts: [
  655. Script(name: Prepare.log),
  656. Script(name: Bundle.meal),
  657. Script(name: Prepare.meal)
  658. ])
  659. let result = worker.call(function: Function.generate, with: [
  660. pumphistory,
  661. profile,
  662. clock,
  663. glucose,
  664. basalProfile,
  665. carbs
  666. ])
  667. continuation.resume(returning: result)
  668. }
  669. }
  670. }
  671. private func autosense(
  672. glucose: JSON,
  673. pumpHistory: JSON,
  674. basalprofile: JSON,
  675. profile: JSON,
  676. carbs: JSON,
  677. temptargets: JSON
  678. ) async throws -> RawJSON {
  679. try await withCheckedThrowingContinuation { continuation in
  680. jsWorker.inCommonContext { worker in
  681. worker.evaluateBatch(scripts: [
  682. Script(name: Prepare.log),
  683. Script(name: Bundle.autosens),
  684. Script(name: Prepare.autosens)
  685. ])
  686. let result = worker.call(function: Function.generate, with: [
  687. glucose,
  688. pumpHistory,
  689. basalprofile,
  690. profile,
  691. carbs,
  692. temptargets
  693. ])
  694. continuation.resume(returning: result)
  695. }
  696. }
  697. }
  698. private func autotunePrepare(
  699. pumphistory: JSON,
  700. profile: JSON,
  701. glucose: JSON,
  702. pumpprofile: JSON,
  703. carbs: JSON,
  704. categorizeUamAsBasal: Bool,
  705. tuneInsulinCurve: Bool
  706. ) async throws -> RawJSON {
  707. try await withCheckedThrowingContinuation { continuation in
  708. jsWorker.inCommonContext { worker in
  709. worker.evaluateBatch(scripts: [
  710. Script(name: Prepare.log),
  711. Script(name: Bundle.autotunePrep),
  712. Script(name: Prepare.autotunePrep)
  713. ])
  714. let result = worker.call(function: Function.generate, with: [
  715. pumphistory,
  716. profile,
  717. glucose,
  718. pumpprofile,
  719. carbs,
  720. categorizeUamAsBasal,
  721. tuneInsulinCurve
  722. ])
  723. continuation.resume(returning: result)
  724. }
  725. }
  726. }
  727. private func autotuneRun(
  728. autotunePreparedData: JSON,
  729. previousAutotuneResult: JSON,
  730. pumpProfile: JSON
  731. ) async throws -> RawJSON {
  732. try await withCheckedThrowingContinuation { continuation in
  733. jsWorker.inCommonContext { worker in
  734. worker.evaluateBatch(scripts: [
  735. Script(name: Prepare.log),
  736. Script(name: Bundle.autotuneCore),
  737. Script(name: Prepare.autotuneCore)
  738. ])
  739. let result = worker.call(function: Function.generate, with: [
  740. autotunePreparedData,
  741. previousAutotuneResult,
  742. pumpProfile
  743. ])
  744. continuation.resume(returning: result)
  745. }
  746. }
  747. }
  748. private func determineBasal(
  749. glucose: JSON,
  750. currentTemp: JSON,
  751. iob: JSON,
  752. profile: JSON,
  753. autosens: JSON,
  754. meal: JSON,
  755. microBolusAllowed: Bool,
  756. reservoir: JSON,
  757. pumpHistory: JSON,
  758. preferences: JSON,
  759. basalProfile: JSON,
  760. oref2_variables: JSON
  761. ) async throws -> RawJSON {
  762. try await withCheckedThrowingContinuation { continuation in
  763. jsWorker.inCommonContext { worker in
  764. worker.evaluateBatch(scripts: [
  765. Script(name: Prepare.log),
  766. Script(name: Prepare.determineBasal),
  767. Script(name: Bundle.basalSetTemp),
  768. Script(name: Bundle.getLastGlucose),
  769. Script(name: Bundle.determineBasal)
  770. ])
  771. if let middleware = self.middlewareScript(name: OpenAPS.Middleware.determineBasal) {
  772. worker.evaluate(script: middleware)
  773. }
  774. let result = worker.call(function: Function.generate, with: [
  775. iob,
  776. currentTemp,
  777. glucose,
  778. profile,
  779. autosens,
  780. meal,
  781. microBolusAllowed,
  782. reservoir,
  783. Date(),
  784. pumpHistory,
  785. preferences,
  786. basalProfile,
  787. oref2_variables
  788. ])
  789. continuation.resume(returning: result)
  790. }
  791. }
  792. }
  793. private func exportDefaultPreferences() -> RawJSON {
  794. dispatchPrecondition(condition: .onQueue(processQueue))
  795. return jsWorker.inCommonContext { worker in
  796. worker.evaluateBatch(scripts: [
  797. Script(name: Prepare.log),
  798. Script(name: Bundle.profile),
  799. Script(name: Prepare.profile)
  800. ])
  801. return worker.call(function: Function.exportDefaults, with: [])
  802. }
  803. }
  804. private func makeProfile(
  805. preferences: JSON,
  806. pumpSettings: JSON,
  807. bgTargets: JSON,
  808. basalProfile: JSON,
  809. isf: JSON,
  810. carbRatio: JSON,
  811. tempTargets: JSON,
  812. model: JSON,
  813. autotune: JSON,
  814. freeaps: JSON
  815. ) async throws -> RawJSON {
  816. try await withCheckedThrowingContinuation { continuation in
  817. jsWorker.inCommonContext { worker in
  818. worker.evaluateBatch(scripts: [
  819. Script(name: Prepare.log),
  820. Script(name: Bundle.profile),
  821. Script(name: Prepare.profile)
  822. ])
  823. let result = worker.call(function: Function.generate, with: [
  824. pumpSettings,
  825. bgTargets,
  826. isf,
  827. basalProfile,
  828. preferences,
  829. carbRatio,
  830. tempTargets,
  831. model,
  832. autotune,
  833. freeaps
  834. ])
  835. continuation.resume(returning: result)
  836. }
  837. }
  838. }
  839. private func loadJSON(name: String) -> String {
  840. try! String(contentsOf: Foundation.Bundle.main.url(forResource: "json/\(name)", withExtension: "json")!)
  841. }
  842. private func loadFileFromStorage(name: String) -> RawJSON {
  843. storage.retrieveRaw(name) ?? OpenAPS.defaults(for: name)
  844. }
  845. private func loadFileFromStorageAsync(name: String) async -> RawJSON {
  846. await withCheckedContinuation { continuation in
  847. DispatchQueue.global(qos: .userInitiated).async {
  848. let result = self.storage.retrieveRaw(name) ?? OpenAPS.defaults(for: name)
  849. continuation.resume(returning: result)
  850. }
  851. }
  852. }
  853. private func middlewareScript(name: String) -> Script? {
  854. if let body = storage.retrieveRaw(name) {
  855. return Script(name: "Middleware", body: body)
  856. }
  857. if let url = Foundation.Bundle.main.url(forResource: "javascript/\(name)", withExtension: "") {
  858. return Script(name: "Middleware", body: try! String(contentsOf: url))
  859. }
  860. return nil
  861. }
  862. static func defaults(for file: String) -> RawJSON {
  863. let prefix = file.hasSuffix(".json") ? "json/defaults" : "javascript"
  864. guard let url = Foundation.Bundle.main.url(forResource: "\(prefix)/\(file)", withExtension: "") else {
  865. return ""
  866. }
  867. return (try? String(contentsOf: url)) ?? ""
  868. }
  869. func processAndSave(forecastData: [String: [Int]]) {
  870. let currentDate = Date()
  871. context.perform {
  872. for (type, values) in forecastData {
  873. self.createForecast(type: type, values: values, date: currentDate, context: self.context)
  874. }
  875. do {
  876. guard self.context.hasChanges else { return }
  877. try self.context.save()
  878. } catch {
  879. print(error.localizedDescription)
  880. }
  881. }
  882. }
  883. func createForecast(type: String, values: [Int], date: Date, context: NSManagedObjectContext) {
  884. let forecast = Forecast(context: context)
  885. forecast.id = UUID()
  886. forecast.date = date
  887. forecast.type = type
  888. for (index, value) in values.enumerated() {
  889. let forecastValue = ForecastValue(context: context)
  890. forecastValue.value = Int32(value)
  891. forecastValue.index = Int32(index)
  892. forecastValue.forecast = forecast
  893. }
  894. }
  895. }