OpenAPS.swift 35 KB

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