OpenAPS.swift 34 KB

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