OpenAPS.swift 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  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. 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 overrideTarget: Decimal = 0
  404. if useOverride {
  405. duration = (overrideArray.first?.duration ?? 0) as Decimal
  406. overrideTarget = (overrideArray.first?.target ?? 0) as Decimal
  407. let advancedSettings = overrideArray.first?.advancedSettings ?? false
  408. let addedMinutes = Int(duration)
  409. let date = overrideArray.first?.date ?? Date()
  410. if date.addingTimeInterval(addedMinutes.minutes.timeInterval) < Date(),
  411. !unlimited
  412. {
  413. useOverride = false
  414. let saveToCoreData = OverrideStored(context: self.context)
  415. saveToCoreData.enabled = false
  416. saveToCoreData.date = Date()
  417. saveToCoreData.duration = 0
  418. saveToCoreData.indefinite = false
  419. saveToCoreData.percentage = 100
  420. do {
  421. guard self.context.hasChanges else { return "{}" }
  422. try self.context.save()
  423. } catch {
  424. print(error.localizedDescription)
  425. }
  426. }
  427. }
  428. if !useOverride {
  429. unlimited = true
  430. overridePercentage = 100
  431. duration = 0
  432. overrideTarget = 0
  433. disableSMBs = false
  434. }
  435. if temptargetActive {
  436. var duration_ = 0
  437. var hbt = Double(hbt_)
  438. var dd = 0.0
  439. if temptargetActive {
  440. duration_ = Int(truncating: tempTargetsArray.first?.duration ?? 0)
  441. hbt = tempTargetsArray.first?.hbt ?? Double(hbt_)
  442. let startDate = tempTargetsArray.first?.startDate ?? Date()
  443. let durationPlusStart = startDate.addingTimeInterval(duration_.minutes.timeInterval)
  444. dd = durationPlusStart.timeIntervalSinceNow.minutes
  445. if dd > 0.1 {
  446. hbt_ = Decimal(hbt)
  447. temptargetActive = true
  448. } else {
  449. temptargetActive = false
  450. }
  451. }
  452. }
  453. if currentTDD > 0 {
  454. let averages = Oref2_variables(
  455. average_total_data: average14,
  456. weightedAverage: weighted_average,
  457. past2hoursAverage: average2hours,
  458. date: Date(),
  459. isEnabled: temptargetActive,
  460. presetActive: isPercentageEnabled,
  461. overridePercentage: overridePercentage,
  462. useOverride: useOverride,
  463. duration: duration,
  464. unlimited: unlimited,
  465. hbt: hbt_,
  466. overrideTarget: overrideTarget,
  467. smbIsOff: disableSMBs,
  468. advancedSettings: overrideArray.first?.advancedSettings ?? false,
  469. isfAndCr: overrideArray.first?.isfAndCr ?? false,
  470. isf: overrideArray.first?.isf ?? false,
  471. cr: overrideArray.first?.cr ?? false,
  472. smbMinutes: (overrideArray.first?.smbMinutes ?? smbMinutes) as Decimal,
  473. uamMinutes: (overrideArray.first?.uamMinutes ?? uamMinutes) as Decimal
  474. )
  475. self.storage.save(averages, as: OpenAPS.Monitor.oref2_variables)
  476. return self.loadFileFromStorage(name: Monitor.oref2_variables)
  477. } else {
  478. let averages = Oref2_variables(
  479. average_total_data: 0,
  480. weightedAverage: 1,
  481. past2hoursAverage: 0,
  482. date: Date(),
  483. isEnabled: temptargetActive,
  484. presetActive: isPercentageEnabled,
  485. overridePercentage: overridePercentage,
  486. useOverride: useOverride,
  487. duration: duration,
  488. unlimited: unlimited,
  489. hbt: hbt_,
  490. overrideTarget: overrideTarget,
  491. smbIsOff: disableSMBs,
  492. advancedSettings: overrideArray.first?.advancedSettings ?? false,
  493. isfAndCr: overrideArray.first?.isfAndCr ?? false,
  494. isf: overrideArray.first?.isf ?? false,
  495. cr: overrideArray.first?.cr ?? false,
  496. smbMinutes: (overrideArray.first?.smbMinutes ?? smbMinutes) as Decimal,
  497. uamMinutes: (overrideArray.first?.uamMinutes ?? uamMinutes) as Decimal
  498. )
  499. self.storage.save(averages, as: OpenAPS.Monitor.oref2_variables)
  500. return self.loadFileFromStorage(name: Monitor.oref2_variables)
  501. }
  502. }
  503. }
  504. func autosense() async throws -> Autosens? {
  505. debug(.openAPS, "Start autosens")
  506. // Perform asynchronous calls in parallel
  507. async let pumpHistoryObjectIDs = fetchPumpHistoryObjectIDs() ?? []
  508. async let carbs = fetchAndProcessCarbs()
  509. async let glucose = fetchAndProcessGlucose()
  510. async let getProfile = loadFileFromStorageAsync(name: Settings.profile)
  511. async let getBasalProfile = loadFileFromStorageAsync(name: Settings.basalProfile)
  512. async let getTempTargets = loadFileFromStorageAsync(name: Settings.tempTargets)
  513. // Await the results of asynchronous tasks
  514. let (pumpHistoryJSON, carbsAsJSON, glucoseAsJSON, profile, basalProfile, tempTargets) = await (
  515. parsePumpHistory(await pumpHistoryObjectIDs),
  516. carbs,
  517. glucose,
  518. getProfile,
  519. getBasalProfile,
  520. getTempTargets
  521. )
  522. // Autosense
  523. let autosenseResult = try await autosense(
  524. glucose: glucoseAsJSON,
  525. pumpHistory: pumpHistoryJSON,
  526. basalprofile: basalProfile,
  527. profile: profile,
  528. carbs: carbsAsJSON,
  529. temptargets: tempTargets
  530. )
  531. debug(.openAPS, "AUTOSENS: \(autosenseResult)")
  532. if var autosens = Autosens(from: autosenseResult) {
  533. autosens.timestamp = Date()
  534. await storage.saveAsync(autosens, as: Settings.autosense)
  535. return autosens
  536. } else {
  537. return nil
  538. }
  539. }
  540. func autotune(categorizeUamAsBasal: Bool = false, tuneInsulinCurve: Bool = false) async -> Autotune? {
  541. debug(.openAPS, "Start autotune")
  542. // Perform asynchronous calls in parallel
  543. async let pumpHistoryObjectIDs = fetchPumpHistoryObjectIDs() ?? []
  544. async let carbs = fetchAndProcessCarbs()
  545. async let glucose = fetchAndProcessGlucose()
  546. async let getProfile = loadFileFromStorageAsync(name: Settings.profile)
  547. async let getPumpProfile = loadFileFromStorageAsync(name: Settings.pumpProfile)
  548. async let getPreviousAutotune = storage.retrieveAsync(Settings.autotune, as: RawJSON.self)
  549. // Await the results of asynchronous tasks
  550. let (pumpHistoryJSON, carbsAsJSON, glucoseAsJSON, profile, pumpProfile, previousAutotune) = await (
  551. parsePumpHistory(await pumpHistoryObjectIDs),
  552. carbs,
  553. glucose,
  554. getProfile,
  555. getPumpProfile,
  556. getPreviousAutotune
  557. )
  558. // Error need to be handled here because the function is not declared as throws
  559. do {
  560. // Autotune Prepare
  561. let autotunePreppedGlucose = try await autotunePrepare(
  562. pumphistory: pumpHistoryJSON,
  563. profile: profile,
  564. glucose: glucoseAsJSON,
  565. pumpprofile: pumpProfile,
  566. carbs: carbsAsJSON,
  567. categorizeUamAsBasal: categorizeUamAsBasal,
  568. tuneInsulinCurve: tuneInsulinCurve
  569. )
  570. debug(.openAPS, "AUTOTUNE PREP: \(autotunePreppedGlucose)")
  571. // Autotune Run
  572. let autotuneResult = try await autotuneRun(
  573. autotunePreparedData: autotunePreppedGlucose,
  574. previousAutotuneResult: previousAutotune ?? profile,
  575. pumpProfile: pumpProfile
  576. )
  577. debug(.openAPS, "AUTOTUNE RESULT: \(autotuneResult)")
  578. if let autotune = Autotune(from: autotuneResult) {
  579. storage.save(autotuneResult, as: Settings.autotune)
  580. return autotune
  581. } else {
  582. return nil
  583. }
  584. } catch {
  585. debug(.openAPS, "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to prepare/run Autotune")
  586. return nil
  587. }
  588. }
  589. func makeProfiles(useAutotune _: Bool) async -> Autotune? {
  590. debug(.openAPS, "Start makeProfiles")
  591. async let getPreferences = loadFileFromStorageAsync(name: Settings.preferences)
  592. async let getPumpSettings = loadFileFromStorageAsync(name: Settings.settings)
  593. async let getBGTargets = loadFileFromStorageAsync(name: Settings.bgTargets)
  594. async let getBasalProfile = loadFileFromStorageAsync(name: Settings.basalProfile)
  595. async let getISF = loadFileFromStorageAsync(name: Settings.insulinSensitivities)
  596. async let getCR = loadFileFromStorageAsync(name: Settings.carbRatios)
  597. async let getTempTargets = loadFileFromStorageAsync(name: Settings.tempTargets)
  598. async let getModel = loadFileFromStorageAsync(name: Settings.model)
  599. async let getAutotune = loadFileFromStorageAsync(name: Settings.autotune)
  600. async let getFreeAPS = loadFileFromStorageAsync(name: FreeAPS.settings)
  601. let (preferences, pumpSettings, bgTargets, basalProfile, isf, cr, tempTargets, model, autotune, freeaps) = await (
  602. getPreferences,
  603. getPumpSettings,
  604. getBGTargets,
  605. getBasalProfile,
  606. getISF,
  607. getCR,
  608. getTempTargets,
  609. getModel,
  610. getAutotune,
  611. getFreeAPS
  612. )
  613. var adjustedPreferences = preferences
  614. if adjustedPreferences.isEmpty {
  615. adjustedPreferences = Preferences().rawJSON
  616. }
  617. do {
  618. // Pump Profile
  619. let pumpProfile = try await makeProfile(
  620. preferences: adjustedPreferences,
  621. pumpSettings: pumpSettings,
  622. bgTargets: bgTargets,
  623. basalProfile: basalProfile,
  624. isf: isf,
  625. carbRatio: cr,
  626. tempTargets: tempTargets,
  627. model: model,
  628. autotune: RawJSON.null,
  629. freeaps: freeaps
  630. )
  631. // Profile
  632. let profile = try await makeProfile(
  633. preferences: adjustedPreferences,
  634. pumpSettings: pumpSettings,
  635. bgTargets: bgTargets,
  636. basalProfile: basalProfile,
  637. isf: isf,
  638. carbRatio: cr,
  639. tempTargets: tempTargets,
  640. model: model,
  641. autotune: autotune.isEmpty ? .null : autotune,
  642. freeaps: freeaps
  643. )
  644. await storage.saveAsync(pumpProfile, as: Settings.pumpProfile)
  645. await storage.saveAsync(profile, as: Settings.profile)
  646. if let tunedProfile = Autotune(from: profile) {
  647. return tunedProfile
  648. } else {
  649. return nil
  650. }
  651. } catch {
  652. debug(
  653. .apsManager,
  654. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to execute makeProfiles() to return Autoune results"
  655. )
  656. return nil
  657. }
  658. }
  659. // MARK: - Private
  660. private func iob(pumphistory: JSON, profile: JSON, clock: JSON, autosens: JSON) async throws -> RawJSON {
  661. await withCheckedContinuation { continuation in
  662. jsWorker.inCommonContext { worker in
  663. worker.evaluateBatch(scripts: [
  664. Script(name: Prepare.log),
  665. Script(name: Bundle.iob),
  666. Script(name: Prepare.iob)
  667. ])
  668. let result = worker.call(function: Function.generate, with: [
  669. pumphistory,
  670. profile,
  671. clock,
  672. autosens
  673. ])
  674. continuation.resume(returning: result)
  675. }
  676. }
  677. }
  678. private func meal(
  679. pumphistory: JSON,
  680. profile: JSON,
  681. basalProfile: JSON,
  682. clock: JSON,
  683. carbs: JSON,
  684. glucose: JSON
  685. ) async throws -> RawJSON {
  686. try await withCheckedThrowingContinuation { continuation in
  687. jsWorker.inCommonContext { worker in
  688. worker.evaluateBatch(scripts: [
  689. Script(name: Prepare.log),
  690. Script(name: Bundle.meal),
  691. Script(name: Prepare.meal)
  692. ])
  693. let result = worker.call(function: Function.generate, with: [
  694. pumphistory,
  695. profile,
  696. clock,
  697. glucose,
  698. basalProfile,
  699. carbs
  700. ])
  701. continuation.resume(returning: result)
  702. }
  703. }
  704. }
  705. private func autosense(
  706. glucose: JSON,
  707. pumpHistory: JSON,
  708. basalprofile: JSON,
  709. profile: JSON,
  710. carbs: JSON,
  711. temptargets: JSON
  712. ) async throws -> RawJSON {
  713. try await withCheckedThrowingContinuation { continuation in
  714. jsWorker.inCommonContext { worker in
  715. worker.evaluateBatch(scripts: [
  716. Script(name: Prepare.log),
  717. Script(name: Bundle.autosens),
  718. Script(name: Prepare.autosens)
  719. ])
  720. let result = worker.call(function: Function.generate, with: [
  721. glucose,
  722. pumpHistory,
  723. basalprofile,
  724. profile,
  725. carbs,
  726. temptargets
  727. ])
  728. continuation.resume(returning: result)
  729. }
  730. }
  731. }
  732. private func autotunePrepare(
  733. pumphistory: JSON,
  734. profile: JSON,
  735. glucose: JSON,
  736. pumpprofile: JSON,
  737. carbs: JSON,
  738. categorizeUamAsBasal: Bool,
  739. tuneInsulinCurve: Bool
  740. ) async throws -> RawJSON {
  741. try await withCheckedThrowingContinuation { continuation in
  742. jsWorker.inCommonContext { worker in
  743. worker.evaluateBatch(scripts: [
  744. Script(name: Prepare.log),
  745. Script(name: Bundle.autotunePrep),
  746. Script(name: Prepare.autotunePrep)
  747. ])
  748. let result = worker.call(function: Function.generate, with: [
  749. pumphistory,
  750. profile,
  751. glucose,
  752. pumpprofile,
  753. carbs,
  754. categorizeUamAsBasal,
  755. tuneInsulinCurve
  756. ])
  757. continuation.resume(returning: result)
  758. }
  759. }
  760. }
  761. private func autotuneRun(
  762. autotunePreparedData: JSON,
  763. previousAutotuneResult: JSON,
  764. pumpProfile: JSON
  765. ) async throws -> RawJSON {
  766. try await withCheckedThrowingContinuation { continuation in
  767. jsWorker.inCommonContext { worker in
  768. worker.evaluateBatch(scripts: [
  769. Script(name: Prepare.log),
  770. Script(name: Bundle.autotuneCore),
  771. Script(name: Prepare.autotuneCore)
  772. ])
  773. let result = worker.call(function: Function.generate, with: [
  774. autotunePreparedData,
  775. previousAutotuneResult,
  776. pumpProfile
  777. ])
  778. continuation.resume(returning: result)
  779. }
  780. }
  781. }
  782. private func determineBasal(
  783. glucose: JSON,
  784. currentTemp: JSON,
  785. iob: JSON,
  786. profile: JSON,
  787. autosens: JSON,
  788. meal: JSON,
  789. microBolusAllowed: Bool,
  790. reservoir: JSON,
  791. pumpHistory: JSON,
  792. preferences: JSON,
  793. basalProfile: JSON,
  794. oref2_variables: JSON
  795. ) async throws -> RawJSON {
  796. try await withCheckedThrowingContinuation { continuation in
  797. jsWorker.inCommonContext { worker in
  798. worker.evaluateBatch(scripts: [
  799. Script(name: Prepare.log),
  800. Script(name: Prepare.determineBasal),
  801. Script(name: Bundle.basalSetTemp),
  802. Script(name: Bundle.getLastGlucose),
  803. Script(name: Bundle.determineBasal)
  804. ])
  805. if let middleware = self.middlewareScript(name: OpenAPS.Middleware.determineBasal) {
  806. worker.evaluate(script: middleware)
  807. }
  808. let result = worker.call(function: Function.generate, with: [
  809. iob,
  810. currentTemp,
  811. glucose,
  812. profile,
  813. autosens,
  814. meal,
  815. microBolusAllowed,
  816. reservoir,
  817. Date(),
  818. pumpHistory,
  819. preferences,
  820. basalProfile,
  821. oref2_variables
  822. ])
  823. continuation.resume(returning: result)
  824. }
  825. }
  826. }
  827. private func exportDefaultPreferences() -> RawJSON {
  828. dispatchPrecondition(condition: .onQueue(processQueue))
  829. return jsWorker.inCommonContext { worker in
  830. worker.evaluateBatch(scripts: [
  831. Script(name: Prepare.log),
  832. Script(name: Bundle.profile),
  833. Script(name: Prepare.profile)
  834. ])
  835. return worker.call(function: Function.exportDefaults, with: [])
  836. }
  837. }
  838. private func makeProfile(
  839. preferences: JSON,
  840. pumpSettings: JSON,
  841. bgTargets: JSON,
  842. basalProfile: JSON,
  843. isf: JSON,
  844. carbRatio: JSON,
  845. tempTargets: JSON,
  846. model: JSON,
  847. autotune: JSON,
  848. freeaps: JSON
  849. ) async throws -> RawJSON {
  850. try await withCheckedThrowingContinuation { continuation in
  851. jsWorker.inCommonContext { worker in
  852. worker.evaluateBatch(scripts: [
  853. Script(name: Prepare.log),
  854. Script(name: Bundle.profile),
  855. Script(name: Prepare.profile)
  856. ])
  857. let result = worker.call(function: Function.generate, with: [
  858. pumpSettings,
  859. bgTargets,
  860. isf,
  861. basalProfile,
  862. preferences,
  863. carbRatio,
  864. tempTargets,
  865. model,
  866. autotune,
  867. freeaps
  868. ])
  869. continuation.resume(returning: result)
  870. }
  871. }
  872. }
  873. private func loadJSON(name: String) -> String {
  874. try! String(contentsOf: Foundation.Bundle.main.url(forResource: "json/\(name)", withExtension: "json")!)
  875. }
  876. private func loadFileFromStorage(name: String) -> RawJSON {
  877. storage.retrieveRaw(name) ?? OpenAPS.defaults(for: name)
  878. }
  879. private func loadFileFromStorageAsync(name: String) async -> RawJSON {
  880. await withCheckedContinuation { continuation in
  881. DispatchQueue.global(qos: .userInitiated).async {
  882. let result = self.storage.retrieveRaw(name) ?? OpenAPS.defaults(for: name)
  883. continuation.resume(returning: result)
  884. }
  885. }
  886. }
  887. private func middlewareScript(name: String) -> Script? {
  888. if let body = storage.retrieveRaw(name) {
  889. return Script(name: "Middleware", body: body)
  890. }
  891. if let url = Foundation.Bundle.main.url(forResource: "javascript/\(name)", withExtension: "") {
  892. return Script(name: "Middleware", body: try! String(contentsOf: url))
  893. }
  894. return nil
  895. }
  896. static func defaults(for file: String) -> RawJSON {
  897. let prefix = file.hasSuffix(".json") ? "json/defaults" : "javascript"
  898. guard let url = Foundation.Bundle.main.url(forResource: "\(prefix)/\(file)", withExtension: "") else {
  899. return ""
  900. }
  901. return (try? String(contentsOf: url)) ?? ""
  902. }
  903. func processAndSave(forecastData: [String: [Int]]) {
  904. let currentDate = Date()
  905. context.perform {
  906. for (type, values) in forecastData {
  907. self.createForecast(type: type, values: values, date: currentDate, context: self.context)
  908. }
  909. do {
  910. guard self.context.hasChanges else { return }
  911. try self.context.save()
  912. } catch {
  913. print(error.localizedDescription)
  914. }
  915. }
  916. }
  917. func createForecast(type: String, values: [Int], date: Date, context: NSManagedObjectContext) {
  918. let forecast = Forecast(context: context)
  919. forecast.id = UUID()
  920. forecast.date = date
  921. forecast.type = type
  922. for (index, value) in values.enumerated() {
  923. let forecastValue = ForecastValue(context: context)
  924. forecastValue.value = Int32(value)
  925. forecastValue.index = Int32(index)
  926. forecastValue.forecast = forecast
  927. }
  928. }
  929. }