OpenAPS.swift 36 KB

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