OpenAPS.swift 35 KB

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