OpenAPS.swift 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  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) {
  26. 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 = Int16(determination.duration ?? 0)
  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. if let predictions = determination.predictions {
  56. ["iob": predictions.iob, "zt": predictions.zt, "cob": predictions.cob, "uam": predictions.uam]
  57. .forEach { type, values in
  58. if let values = values {
  59. let forecast = Forecast(context: self.context)
  60. forecast.id = UUID()
  61. forecast.type = type
  62. forecast.date = Date()
  63. forecast.orefDetermination = newOrefDetermination
  64. for (index, value) in values.enumerated() {
  65. let forecastValue = ForecastValue(context: self.context)
  66. forecastValue.index = Int32(index)
  67. forecastValue.value = Int32(value)
  68. forecast.addToForecastValues(forecastValue)
  69. }
  70. newOrefDetermination.addToForecasts(forecast)
  71. }
  72. }
  73. }
  74. self.attemptToSaveContext()
  75. }
  76. }
  77. func attemptToSaveContext() {
  78. do {
  79. guard context.hasChanges else { return }
  80. try context.save()
  81. } catch {
  82. print(error.localizedDescription)
  83. }
  84. }
  85. // fetch glucose to pass it to the meal function and to determine basal
  86. private func fetchAndProcessGlucose() -> String {
  87. var glucoseAsJSON: String?
  88. context.performAndWait {
  89. let results = CoreDataStack.shared.fetchEntities(
  90. ofType: GlucoseStored.self,
  91. onContext: context,
  92. predicate: NSPredicate.predicateForSixHoursAgo,
  93. key: "date",
  94. ascending: false,
  95. fetchLimit: 72,
  96. batchSize: 24
  97. )
  98. // convert to json
  99. glucoseAsJSON = self.jsonConverter.convertToJSON(results)
  100. }
  101. return glucoseAsJSON ?? "{}"
  102. }
  103. private func fetchAndProcessCarbs() -> String {
  104. // perform fetch AND conversion on the same thread
  105. // if we do it like this we do not change the thread and do not have to pass the objectIDs
  106. var carbsAsJSON: String?
  107. context.performAndWait {
  108. let results = CoreDataStack.shared.fetchEntities(
  109. ofType: CarbEntryStored.self,
  110. onContext: context,
  111. predicate: NSPredicate.predicateForOneDayAgo,
  112. key: "date",
  113. ascending: false
  114. )
  115. // convert to json
  116. carbsAsJSON = self.jsonConverter.convertToJSON(results)
  117. }
  118. return carbsAsJSON ?? "{}"
  119. }
  120. private func fetchPumpHistoryObjectIDs() -> [NSManagedObjectID]? {
  121. context.performAndWait {
  122. let results = CoreDataStack.shared.fetchEntities(
  123. ofType: PumpEventStored.self,
  124. onContext: context,
  125. predicate: NSPredicate.pumpHistoryLast24h,
  126. key: "timestamp",
  127. ascending: false,
  128. batchSize: 50
  129. )
  130. return results.map(\.objectID)
  131. }
  132. }
  133. private func parsePumpHistory(_ pumpHistoryObjectIDs: [NSManagedObjectID]) -> String {
  134. // Return an empty JSON object if the list of object IDs is empty
  135. guard !pumpHistoryObjectIDs.isEmpty else { return "{}" }
  136. // Execute all operations on the background context
  137. let jsonResult = context.performAndWait {
  138. // Load the pump events from the object IDs
  139. let pumpHistory: [PumpEventStored] = pumpHistoryObjectIDs
  140. .compactMap { context.object(with: $0) as? PumpEventStored }
  141. // Create the DTOs
  142. let dtos: [PumpEventDTO] = pumpHistory.flatMap { event -> [PumpEventDTO] in
  143. var eventDTOs: [PumpEventDTO] = []
  144. if let bolusDTO = event.toBolusDTOEnum() {
  145. eventDTOs.append(bolusDTO)
  146. }
  147. if let tempBasalDTO = event.toTempBasalDTOEnum() {
  148. eventDTOs.append(tempBasalDTO)
  149. }
  150. if let tempBasalDurationDTO = event.toTempBasalDurationDTOEnum() {
  151. eventDTOs.append(tempBasalDurationDTO)
  152. }
  153. return eventDTOs
  154. }
  155. // Convert the DTOs to JSON
  156. return jsonConverter.convertToJSON(dtos)
  157. }
  158. // Return the JSON result
  159. return jsonResult
  160. }
  161. func determineBasal(currentTemp: TempBasal, clock: Date = Date()) -> Future<Determination?, Never> {
  162. Future { promise in
  163. self.processQueue.async {
  164. debug(.openAPS, "Start determineBasal")
  165. // clock
  166. let dateFormatted = OpenAPS.dateFormatter.string(from: clock)
  167. let dateFormattedAsString = "\"\(dateFormatted)\""
  168. // temp_basal
  169. let tempBasal = currentTemp.rawJSON
  170. let pumpHistoryObjectIDs = self.fetchPumpHistoryObjectIDs() ?? []
  171. let pumpHistoryJSON = self.parsePumpHistory(pumpHistoryObjectIDs)
  172. // carbs
  173. let carbsAsJSON = self.fetchAndProcessCarbs()
  174. // glucose
  175. let glucoseAsJSON = self.fetchAndProcessGlucose()
  176. // TODO: - Save and fetch profile/basalProfile in/from UserDefaults
  177. // profile
  178. let profile = self.loadFileFromStorage(name: Settings.profile)
  179. let basalProfile = self.loadFileFromStorage(name: Settings.basalProfile)
  180. // meal
  181. let meal = self.meal(
  182. pumphistory: pumpHistoryJSON,
  183. profile: profile,
  184. basalProfile: basalProfile,
  185. clock: dateFormattedAsString,
  186. carbs: carbsAsJSON,
  187. glucose: glucoseAsJSON
  188. )
  189. // iob
  190. let autosens = self.loadFileFromStorage(name: Settings.autosense)
  191. let iob = self.iob(
  192. pumphistory: pumpHistoryJSON,
  193. profile: profile,
  194. clock: dateFormattedAsString,
  195. autosens: autosens.isEmpty ? .null : autosens
  196. )
  197. self.storage.save(iob, as: Monitor.iob)
  198. // determine-basal
  199. let reservoir = self.loadFileFromStorage(name: Monitor.reservoir)
  200. let preferences = self.loadFileFromStorage(name: Settings.preferences)
  201. let oref2_variables = self.oref2()
  202. let orefDetermination = self.determineBasal(
  203. glucose: glucoseAsJSON,
  204. currentTemp: tempBasal,
  205. iob: iob,
  206. profile: profile,
  207. autosens: autosens.isEmpty ? .null : autosens,
  208. meal: meal,
  209. microBolusAllowed: true,
  210. reservoir: reservoir,
  211. pumpHistory: pumpHistoryJSON,
  212. preferences: preferences,
  213. basalProfile: basalProfile,
  214. oref2_variables: oref2_variables
  215. )
  216. debug(.openAPS, "Determinated: \(orefDetermination)")
  217. if var determination = Determination(from: orefDetermination) {
  218. determination.timestamp = determination.deliverAt ?? clock
  219. // save to core data asynchronously
  220. self.processDetermination(determination)
  221. promise(.success(determination))
  222. } else {
  223. promise(.success(nil))
  224. }
  225. }
  226. }
  227. }
  228. func oref2() -> RawJSON {
  229. context.performAndWait {
  230. let preferences = storage.retrieve(OpenAPS.Settings.preferences, as: Preferences.self)
  231. var hbt_ = preferences?.halfBasalExerciseTarget ?? 160
  232. let wp = preferences?.weightPercentage ?? 1
  233. let smbMinutes = (preferences?.maxSMBBasalMinutes ?? 30) as NSDecimalNumber
  234. let uamMinutes = (preferences?.maxUAMSMBBasalMinutes ?? 30) as NSDecimalNumber
  235. let tenDaysAgo = Date().addingTimeInterval(-10.days.timeInterval)
  236. let twoHoursAgo = Date().addingTimeInterval(-2.hours.timeInterval)
  237. var uniqueEvents = [OrefDetermination]()
  238. let requestTDD = OrefDetermination.fetchRequest() as NSFetchRequest<OrefDetermination>
  239. requestTDD.predicate = NSPredicate(format: "timestamp > %@ AND totalDailyDose > 0", tenDaysAgo as NSDate)
  240. requestTDD.propertiesToFetch = ["timestamp", "totalDailyDose"]
  241. let sortTDD = NSSortDescriptor(key: "timestamp", ascending: true)
  242. requestTDD.sortDescriptors = [sortTDD]
  243. try? uniqueEvents = context.fetch(requestTDD)
  244. var sliderArray = [TempTargetsSlider]()
  245. let requestIsEnbled = TempTargetsSlider.fetchRequest() as NSFetchRequest<TempTargetsSlider>
  246. let sortIsEnabled = NSSortDescriptor(key: "date", ascending: false)
  247. requestIsEnbled.sortDescriptors = [sortIsEnabled]
  248. // requestIsEnbled.fetchLimit = 1
  249. try? sliderArray = context.fetch(requestIsEnbled)
  250. var overrideArray = [Override]()
  251. let requestOverrides = Override.fetchRequest() as NSFetchRequest<Override>
  252. let sortOverride = NSSortDescriptor(key: "date", ascending: false)
  253. requestOverrides.sortDescriptors = [sortOverride]
  254. // requestOverrides.fetchLimit = 1
  255. try? overrideArray = context.fetch(requestOverrides)
  256. var tempTargetsArray = [TempTargets]()
  257. let requestTempTargets = TempTargets.fetchRequest() as NSFetchRequest<TempTargets>
  258. let sortTT = NSSortDescriptor(key: "date", ascending: false)
  259. requestTempTargets.sortDescriptors = [sortTT]
  260. requestTempTargets.fetchLimit = 1
  261. try? tempTargetsArray = context.fetch(requestTempTargets)
  262. let total = uniqueEvents.compactMap({ each in each.totalDailyDose as? Decimal ?? 0 }).reduce(0, +)
  263. var indeces = uniqueEvents.count
  264. // Only fetch once. Use same (previous) fetch
  265. let twoHoursArray = uniqueEvents.filter({ ($0.timestamp ?? Date()) >= twoHoursAgo })
  266. var nrOfIndeces = twoHoursArray.count
  267. let totalAmount = twoHoursArray.compactMap({ each in each.totalDailyDose as? Decimal ?? 0 }).reduce(0, +)
  268. var temptargetActive = tempTargetsArray.first?.active ?? false
  269. let isPercentageEnabled = sliderArray.first?.enabled ?? false
  270. var useOverride = overrideArray.first?.enabled ?? false
  271. var overridePercentage = Decimal(overrideArray.first?.percentage ?? 100)
  272. var unlimited = overrideArray.first?.indefinite ?? true
  273. var disableSMBs = overrideArray.first?.smbIsOff ?? false
  274. let currentTDD = (uniqueEvents.last?.totalDailyDose ?? 0) as Decimal
  275. if indeces == 0 {
  276. indeces = 1
  277. }
  278. if nrOfIndeces == 0 {
  279. nrOfIndeces = 1
  280. }
  281. let average2hours = totalAmount / Decimal(nrOfIndeces)
  282. let average14 = total / Decimal(indeces)
  283. let weight = wp
  284. let weighted_average = weight * average2hours + (1 - weight) * average14
  285. var duration: Decimal = 0
  286. var newDuration: Decimal = 0
  287. var overrideTarget: Decimal = 0
  288. if useOverride {
  289. duration = (overrideArray.first?.duration ?? 0) as Decimal
  290. overrideTarget = (overrideArray.first?.target ?? 0) as Decimal
  291. let advancedSettings = overrideArray.first?.advancedSettings ?? false
  292. let addedMinutes = Int(duration)
  293. let date = overrideArray.first?.date ?? Date()
  294. if date.addingTimeInterval(addedMinutes.minutes.timeInterval) < Date(),
  295. !unlimited
  296. {
  297. useOverride = false
  298. let saveToCoreData = Override(context: self.context)
  299. saveToCoreData.enabled = false
  300. saveToCoreData.date = Date()
  301. saveToCoreData.duration = 0
  302. saveToCoreData.indefinite = false
  303. saveToCoreData.percentage = 100
  304. do {
  305. guard self.context.hasChanges else { return "{}" }
  306. try self.context.save()
  307. } catch {
  308. print(error.localizedDescription)
  309. }
  310. }
  311. }
  312. if !useOverride {
  313. unlimited = true
  314. overridePercentage = 100
  315. duration = 0
  316. overrideTarget = 0
  317. disableSMBs = false
  318. }
  319. if temptargetActive {
  320. var duration_ = 0
  321. var hbt = Double(hbt_)
  322. var dd = 0.0
  323. if temptargetActive {
  324. duration_ = Int(truncating: tempTargetsArray.first?.duration ?? 0)
  325. hbt = tempTargetsArray.first?.hbt ?? Double(hbt_)
  326. let startDate = tempTargetsArray.first?.startDate ?? Date()
  327. let durationPlusStart = startDate.addingTimeInterval(duration_.minutes.timeInterval)
  328. dd = durationPlusStart.timeIntervalSinceNow.minutes
  329. if dd > 0.1 {
  330. hbt_ = Decimal(hbt)
  331. temptargetActive = true
  332. } else {
  333. temptargetActive = false
  334. }
  335. }
  336. }
  337. if currentTDD > 0 {
  338. let averages = Oref2_variables(
  339. average_total_data: average14,
  340. weightedAverage: weighted_average,
  341. past2hoursAverage: average2hours,
  342. date: Date(),
  343. isEnabled: temptargetActive,
  344. presetActive: isPercentageEnabled,
  345. overridePercentage: overridePercentage,
  346. useOverride: useOverride,
  347. duration: duration,
  348. unlimited: unlimited,
  349. hbt: hbt_,
  350. overrideTarget: overrideTarget,
  351. smbIsOff: disableSMBs,
  352. advancedSettings: overrideArray.first?.advancedSettings ?? false,
  353. isfAndCr: overrideArray.first?.isfAndCr ?? false,
  354. isf: overrideArray.first?.isf ?? false,
  355. cr: overrideArray.first?.cr ?? false,
  356. smbIsAlwaysOff: overrideArray.first?.smbIsAlwaysOff ?? false,
  357. start: (overrideArray.first?.start ?? 0) as Decimal,
  358. end: (overrideArray.first?.end ?? 0) as Decimal,
  359. smbMinutes: (overrideArray.first?.smbMinutes ?? smbMinutes) as Decimal,
  360. uamMinutes: (overrideArray.first?.uamMinutes ?? uamMinutes) as Decimal
  361. )
  362. storage.save(averages, as: OpenAPS.Monitor.oref2_variables)
  363. return self.loadFileFromStorage(name: Monitor.oref2_variables)
  364. } else {
  365. let averages = Oref2_variables(
  366. average_total_data: 0,
  367. weightedAverage: 1,
  368. past2hoursAverage: 0,
  369. date: Date(),
  370. isEnabled: temptargetActive,
  371. presetActive: isPercentageEnabled,
  372. overridePercentage: overridePercentage,
  373. useOverride: useOverride,
  374. duration: duration,
  375. unlimited: unlimited,
  376. hbt: hbt_,
  377. overrideTarget: overrideTarget,
  378. smbIsOff: disableSMBs,
  379. advancedSettings: overrideArray.first?.advancedSettings ?? false,
  380. isfAndCr: overrideArray.first?.isfAndCr ?? false,
  381. isf: overrideArray.first?.isf ?? false,
  382. cr: overrideArray.first?.cr ?? false,
  383. smbIsAlwaysOff: overrideArray.first?.smbIsAlwaysOff ?? false,
  384. start: (overrideArray.first?.start ?? 0) as Decimal,
  385. end: (overrideArray.first?.end ?? 0) as Decimal,
  386. smbMinutes: (overrideArray.first?.smbMinutes ?? smbMinutes) as Decimal,
  387. uamMinutes: (overrideArray.first?.uamMinutes ?? uamMinutes) as Decimal
  388. )
  389. storage.save(averages, as: OpenAPS.Monitor.oref2_variables)
  390. return self.loadFileFromStorage(name: Monitor.oref2_variables)
  391. }
  392. }
  393. }
  394. func autosense() -> Future<Autosens?, Never> {
  395. Future { promise in
  396. self.processQueue.async {
  397. debug(.openAPS, "Start autosens")
  398. // pump history
  399. let pumpHistoryObjectIDs = self.fetchPumpHistoryObjectIDs() ?? []
  400. let pumpHistoryJSON = self.parsePumpHistory(pumpHistoryObjectIDs)
  401. // carbs
  402. let carbsAsJSON = self.fetchAndProcessCarbs()
  403. /// glucose
  404. let glucoseAsJSON = self.fetchAndProcessGlucose()
  405. let profile = self.loadFileFromStorage(name: Settings.profile)
  406. let basalProfile = self.loadFileFromStorage(name: Settings.basalProfile)
  407. let tempTargets = self.loadFileFromStorage(name: Settings.tempTargets)
  408. let autosensResult = self.autosense(
  409. glucose: glucoseAsJSON,
  410. pumpHistory: pumpHistoryJSON,
  411. basalprofile: basalProfile,
  412. profile: profile,
  413. carbs: carbsAsJSON,
  414. temptargets: tempTargets
  415. )
  416. debug(.openAPS, "AUTOSENS: \(autosensResult)")
  417. if var autosens = Autosens(from: autosensResult) {
  418. autosens.timestamp = Date()
  419. self.storage.save(autosens, as: Settings.autosense)
  420. promise(.success(autosens))
  421. } else {
  422. promise(.success(nil))
  423. }
  424. }
  425. }
  426. }
  427. func autotune(categorizeUamAsBasal: Bool = false, tuneInsulinCurve: Bool = false) -> Future<Autotune?, Never> {
  428. Future { promise in
  429. self.processQueue.async {
  430. debug(.openAPS, "Start autotune")
  431. // pump history
  432. let pumpHistoryObjectIDs = self.fetchPumpHistoryObjectIDs() ?? []
  433. let pumpHistoryJSON = self.parsePumpHistory(pumpHistoryObjectIDs)
  434. /// glucose
  435. let glucoseAsJSON = self.fetchAndProcessGlucose()
  436. let profile = self.loadFileFromStorage(name: Settings.profile)
  437. let pumpProfile = self.loadFileFromStorage(name: Settings.pumpProfile)
  438. // carbs
  439. let carbsAsJSON = self.fetchAndProcessCarbs()
  440. let autotunePreppedGlucose = self.autotunePrepare(
  441. pumphistory: pumpHistoryJSON,
  442. profile: profile,
  443. glucose: glucoseAsJSON,
  444. pumpprofile: pumpProfile,
  445. carbs: carbsAsJSON,
  446. categorizeUamAsBasal: categorizeUamAsBasal,
  447. tuneInsulinCurve: tuneInsulinCurve
  448. )
  449. debug(.openAPS, "AUTOTUNE PREP: \(autotunePreppedGlucose)")
  450. let previousAutotune = self.storage.retrieve(Settings.autotune, as: RawJSON.self)
  451. let autotuneResult = self.autotuneRun(
  452. autotunePreparedData: autotunePreppedGlucose,
  453. previousAutotuneResult: previousAutotune ?? profile,
  454. pumpProfile: pumpProfile
  455. )
  456. debug(.openAPS, "AUTOTUNE RESULT: \(autotuneResult)")
  457. if let autotune = Autotune(from: autotuneResult) {
  458. self.storage.save(autotuneResult, as: Settings.autotune)
  459. promise(.success(autotune))
  460. } else {
  461. promise(.success(nil))
  462. }
  463. }
  464. }
  465. }
  466. func makeProfiles(useAutotune: Bool) -> Future<Autotune?, Never> {
  467. Future { promise in
  468. debug(.openAPS, "Start makeProfiles")
  469. self.processQueue.async {
  470. var preferences = self.loadFileFromStorage(name: Settings.preferences)
  471. if preferences.isEmpty {
  472. preferences = Preferences().rawJSON
  473. }
  474. let pumpSettings = self.loadFileFromStorage(name: Settings.settings)
  475. let bgTargets = self.loadFileFromStorage(name: Settings.bgTargets)
  476. let basalProfile = self.loadFileFromStorage(name: Settings.basalProfile)
  477. let isf = self.loadFileFromStorage(name: Settings.insulinSensitivities)
  478. let cr = self.loadFileFromStorage(name: Settings.carbRatios)
  479. let tempTargets = self.loadFileFromStorage(name: Settings.tempTargets)
  480. let model = self.loadFileFromStorage(name: Settings.model)
  481. let autotune = useAutotune ? self.loadFileFromStorage(name: Settings.autotune) : .empty
  482. let freeaps = self.loadFileFromStorage(name: FreeAPS.settings)
  483. let pumpProfile = self.makeProfile(
  484. preferences: preferences,
  485. pumpSettings: pumpSettings,
  486. bgTargets: bgTargets,
  487. basalProfile: basalProfile,
  488. isf: isf,
  489. carbRatio: cr,
  490. tempTargets: tempTargets,
  491. model: model,
  492. autotune: RawJSON.null,
  493. freeaps: freeaps
  494. )
  495. let profile = self.makeProfile(
  496. preferences: preferences,
  497. pumpSettings: pumpSettings,
  498. bgTargets: bgTargets,
  499. basalProfile: basalProfile,
  500. isf: isf,
  501. carbRatio: cr,
  502. tempTargets: tempTargets,
  503. model: model,
  504. autotune: autotune.isEmpty ? .null : autotune,
  505. freeaps: freeaps
  506. )
  507. self.storage.save(pumpProfile, as: Settings.pumpProfile)
  508. self.storage.save(profile, as: Settings.profile)
  509. if let tunedProfile = Autotune(from: profile) {
  510. promise(.success(tunedProfile))
  511. return
  512. }
  513. promise(.success(nil))
  514. }
  515. }
  516. }
  517. // MARK: - Private
  518. private func iob(pumphistory: JSON, profile: JSON, clock: JSON, autosens: JSON) -> RawJSON {
  519. dispatchPrecondition(condition: .onQueue(processQueue))
  520. return jsWorker.inCommonContext { worker in
  521. worker.evaluateBatch(scripts: [
  522. Script(name: Prepare.log),
  523. Script(name: Bundle.iob),
  524. Script(name: Prepare.iob)
  525. ])
  526. return worker.call(function: Function.generate, with: [
  527. pumphistory,
  528. profile,
  529. clock,
  530. autosens
  531. ])
  532. }
  533. }
  534. private func meal(pumphistory: JSON, profile: JSON, basalProfile: JSON, clock: JSON, carbs: JSON, glucose: JSON) -> RawJSON {
  535. dispatchPrecondition(condition: .onQueue(processQueue))
  536. return jsWorker.inCommonContext { worker in
  537. worker.evaluateBatch(scripts: [
  538. Script(name: Prepare.log),
  539. Script(name: Bundle.meal),
  540. Script(name: Prepare.meal)
  541. ])
  542. return worker.call(function: Function.generate, with: [
  543. pumphistory,
  544. profile,
  545. clock,
  546. glucose,
  547. basalProfile,
  548. carbs
  549. ])
  550. }
  551. }
  552. private func autosense(
  553. glucose: JSON,
  554. pumpHistory: JSON,
  555. basalprofile: JSON,
  556. profile: JSON,
  557. carbs: JSON,
  558. temptargets: JSON
  559. ) -> RawJSON {
  560. dispatchPrecondition(condition: .onQueue(processQueue))
  561. return jsWorker.inCommonContext { worker in
  562. worker.evaluateBatch(scripts: [
  563. Script(name: Prepare.log),
  564. Script(name: Bundle.autosens),
  565. Script(name: Prepare.autosens)
  566. ])
  567. return worker.call(function: Function.generate, with: [
  568. glucose,
  569. pumpHistory,
  570. basalprofile,
  571. profile,
  572. carbs,
  573. temptargets
  574. ])
  575. }
  576. }
  577. private func autotunePrepare(
  578. pumphistory: JSON,
  579. profile: JSON,
  580. glucose: JSON,
  581. pumpprofile: JSON,
  582. carbs: JSON,
  583. categorizeUamAsBasal: Bool,
  584. tuneInsulinCurve: Bool
  585. ) -> RawJSON {
  586. dispatchPrecondition(condition: .onQueue(processQueue))
  587. return jsWorker.inCommonContext { worker in
  588. worker.evaluateBatch(scripts: [
  589. Script(name: Prepare.log),
  590. Script(name: Bundle.autotunePrep),
  591. Script(name: Prepare.autotunePrep)
  592. ])
  593. return worker.call(function: Function.generate, with: [
  594. pumphistory,
  595. profile,
  596. glucose,
  597. pumpprofile,
  598. carbs,
  599. categorizeUamAsBasal,
  600. tuneInsulinCurve
  601. ])
  602. }
  603. }
  604. private func autotuneRun(autotunePreparedData: JSON, previousAutotuneResult: JSON, pumpProfile: JSON) -> RawJSON {
  605. dispatchPrecondition(condition: .onQueue(processQueue))
  606. return jsWorker.inCommonContext { worker in
  607. worker.evaluateBatch(scripts: [
  608. Script(name: Prepare.log),
  609. Script(name: Bundle.autotuneCore),
  610. Script(name: Prepare.autotuneCore)
  611. ])
  612. return worker.call(function: Function.generate, with: [
  613. autotunePreparedData,
  614. previousAutotuneResult,
  615. pumpProfile
  616. ])
  617. }
  618. }
  619. private func determineBasal(
  620. glucose: JSON,
  621. currentTemp: JSON,
  622. iob: JSON,
  623. profile: JSON,
  624. autosens: JSON,
  625. meal: JSON,
  626. microBolusAllowed: Bool,
  627. reservoir: JSON,
  628. pumpHistory: JSON,
  629. preferences: JSON,
  630. basalProfile: JSON,
  631. oref2_variables: JSON
  632. ) -> RawJSON {
  633. dispatchPrecondition(condition: .onQueue(processQueue))
  634. return jsWorker.inCommonContext { worker in
  635. worker.evaluateBatch(scripts: [
  636. Script(name: Prepare.log),
  637. Script(name: Prepare.determineBasal),
  638. Script(name: Bundle.basalSetTemp),
  639. Script(name: Bundle.getLastGlucose),
  640. Script(name: Bundle.determineBasal)
  641. ])
  642. if let middleware = self.middlewareScript(name: OpenAPS.Middleware.determineBasal) {
  643. worker.evaluate(script: middleware)
  644. }
  645. return worker.call(function: Function.generate, with: [
  646. iob,
  647. currentTemp,
  648. glucose,
  649. profile,
  650. autosens,
  651. meal,
  652. microBolusAllowed,
  653. reservoir,
  654. Date(),
  655. pumpHistory,
  656. preferences,
  657. basalProfile,
  658. oref2_variables
  659. ])
  660. }
  661. }
  662. private func exportDefaultPreferences() -> RawJSON {
  663. dispatchPrecondition(condition: .onQueue(processQueue))
  664. return jsWorker.inCommonContext { worker in
  665. worker.evaluateBatch(scripts: [
  666. Script(name: Prepare.log),
  667. Script(name: Bundle.profile),
  668. Script(name: Prepare.profile)
  669. ])
  670. return worker.call(function: Function.exportDefaults, with: [])
  671. }
  672. }
  673. private func makeProfile(
  674. preferences: JSON,
  675. pumpSettings: JSON,
  676. bgTargets: JSON,
  677. basalProfile: JSON,
  678. isf: JSON,
  679. carbRatio: JSON,
  680. tempTargets: JSON,
  681. model: JSON,
  682. autotune: JSON,
  683. freeaps: JSON
  684. ) -> RawJSON {
  685. dispatchPrecondition(condition: .onQueue(processQueue))
  686. return jsWorker.inCommonContext { worker in
  687. worker.evaluateBatch(scripts: [
  688. Script(name: Prepare.log),
  689. Script(name: Bundle.profile),
  690. Script(name: Prepare.profile)
  691. ])
  692. return worker.call(function: Function.generate, with: [
  693. pumpSettings,
  694. bgTargets,
  695. isf,
  696. basalProfile,
  697. preferences,
  698. carbRatio,
  699. tempTargets,
  700. model,
  701. autotune,
  702. freeaps
  703. ])
  704. }
  705. }
  706. private func loadJSON(name: String) -> String {
  707. try! String(contentsOf: Foundation.Bundle.main.url(forResource: "json/\(name)", withExtension: "json")!)
  708. }
  709. private func loadFileFromStorage(name: String) -> RawJSON {
  710. storage.retrieveRaw(name) ?? OpenAPS.defaults(for: name)
  711. }
  712. private func middlewareScript(name: String) -> Script? {
  713. if let body = storage.retrieveRaw(name) {
  714. return Script(name: "Middleware", body: body)
  715. }
  716. if let url = Foundation.Bundle.main.url(forResource: "javascript/\(name)", withExtension: "") {
  717. return Script(name: "Middleware", body: try! String(contentsOf: url))
  718. }
  719. return nil
  720. }
  721. static func defaults(for file: String) -> RawJSON {
  722. let prefix = file.hasSuffix(".json") ? "json/defaults" : "javascript"
  723. guard let url = Foundation.Bundle.main.url(forResource: "\(prefix)/\(file)", withExtension: "") else {
  724. return ""
  725. }
  726. return (try? String(contentsOf: url)) ?? ""
  727. }
  728. func processAndSave(forecastData: [String: [Int]]) {
  729. let currentDate = Date()
  730. context.perform {
  731. for (type, values) in forecastData {
  732. self.createForecast(type: type, values: values, date: currentDate, context: self.context)
  733. }
  734. do {
  735. guard self.context.hasChanges else { return }
  736. try self.context.save()
  737. } catch {
  738. print(error.localizedDescription)
  739. }
  740. }
  741. }
  742. func createForecast(type: String, values: [Int], date: Date, context: NSManagedObjectContext) {
  743. let forecast = Forecast(context: context)
  744. forecast.id = UUID()
  745. forecast.date = date
  746. forecast.type = type
  747. for (index, value) in values.enumerated() {
  748. let forecastValue = ForecastValue(context: context)
  749. forecastValue.value = Int32(value)
  750. forecastValue.index = Int32(index)
  751. forecastValue.forecast = forecast
  752. }
  753. }
  754. }