OpenAPS.swift 44 KB

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