diff --git a/app/src/androidTest/kotlin/app/aaps/ReplayApsResultsTest.kt b/app/src/androidTest/kotlin/app/aaps/ReplayApsResultsTest.kt index 0a0a4df85d0..2aab6c27227 100644 --- a/app/src/androidTest/kotlin/app/aaps/ReplayApsResultsTest.kt +++ b/app/src/androidTest/kotlin/app/aaps/ReplayApsResultsTest.kt @@ -14,13 +14,12 @@ import app.aaps.core.interfaces.aps.OapsProfileAutoIsf import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.maintenance.FileListProvider -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.storage.Storage import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.keys.DoubleKey import app.aaps.core.keys.IntKey -import app.aaps.core.keys.Preferences import app.aaps.core.keys.StringKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.utils.JsonHelper import app.aaps.di.TestApplication import app.aaps.plugins.aps.openAPSAMA.DetermineBasalAMA @@ -57,7 +56,6 @@ class ReplayApsResultsTest @Inject constructor() { @Inject lateinit var determineBasalAMA: DetermineBasalAMA @Inject lateinit var determineBasalSMBDynamicISF: DetermineBasalSMB @Inject lateinit var determineBasalAutoISF: DetermineBasalAutoISF - @Inject lateinit var sp: SP @Inject lateinit var dateUtil: DateUtil @Inject lateinit var preferences: Preferences @@ -610,7 +608,7 @@ class ReplayApsResultsTest @Inject constructor() { JSONAssert.assertEquals( "Error in file $filename", output.toString(), - result?.json()?.apply { + result.json()?.apply { // this is added afterwards to json. Copy from original put("timestamp", output.getString("timestamp")) }.toString(), diff --git a/app/src/androidTest/kotlin/app/aaps/plugins/aps/openAPS/APSResultObject.kt b/app/src/androidTest/kotlin/app/aaps/plugins/aps/openAPS/APSResultObject.kt index 7dc963dc1f1..2a212e33984 100644 --- a/app/src/androidTest/kotlin/app/aaps/plugins/aps/openAPS/APSResultObject.kt +++ b/app/src/androidTest/kotlin/app/aaps/plugins/aps/openAPS/APSResultObject.kt @@ -24,7 +24,7 @@ import app.aaps.core.interfaces.profile.ProfileFunction import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.utils.DecimalFormatter import app.aaps.core.keys.IntKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.extensions.convertedToAbsolute import app.aaps.core.objects.extensions.convertedToPercent import app.aaps.core.ui.R diff --git a/app/src/androidTest/kotlin/app/aaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.kt b/app/src/androidTest/kotlin/app/aaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.kt index 2e8d867281b..86f9e7a9dc7 100644 --- a/app/src/androidTest/kotlin/app/aaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.kt +++ b/app/src/androidTest/kotlin/app/aaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.kt @@ -1,11 +1,11 @@ package app.aaps.plugins.aps.openAPSAMA import androidx.annotation.VisibleForTesting -import app.aaps.core.interfaces.aps.IobTotal import app.aaps.core.data.model.GlucoseUnit import app.aaps.core.interfaces.aps.APSResult import app.aaps.core.interfaces.aps.DetermineBasalAdapter import app.aaps.core.interfaces.aps.GlucoseStatus +import app.aaps.core.interfaces.aps.IobTotal import app.aaps.core.interfaces.aps.MealData import app.aaps.core.interfaces.constraints.ConstraintsChecker import app.aaps.core.interfaces.db.ProcessedTbrEbData @@ -13,11 +13,10 @@ import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.profile.Profile import app.aaps.core.interfaces.profile.ProfileFunction -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.keys.BooleanKey import app.aaps.core.keys.DoubleKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.extensions.convertToJSONArray import app.aaps.core.objects.extensions.convertedToAbsolute import app.aaps.core.objects.extensions.getPassedDurationToTimeInMinutes @@ -46,7 +45,6 @@ class DetermineBasalAdapterAMAJS(private val scriptReader: ScriptReader, private @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var constraintChecker: ConstraintsChecker - @Inject lateinit var sp: SP @Inject lateinit var preferences: Preferences @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var processedTbrEbData: ProcessedTbrEbData @@ -137,7 +135,7 @@ class DetermineBasalAdapterAMAJS(private val scriptReader: ScriptReader, private } else { aapsLogger.error(LTag.APS, "Problem loading JS Functions") } - } catch (e: IOException) { + } catch (_: IOException) { aapsLogger.error(LTag.APS, "IOException") } catch (e: RhinoException) { aapsLogger.error(LTag.APS, "RhinoException: (" + e.lineNumber() + "," + e.columnNumber() + ") " + e.toString()) diff --git a/app/src/androidTest/kotlin/app/aaps/plugins/aps/openAPSAMA/TestOpenAPSAMAPlugin.kt b/app/src/androidTest/kotlin/app/aaps/plugins/aps/openAPSAMA/TestOpenAPSAMAPlugin.kt index 9dfea104740..fc182304a17 100644 --- a/app/src/androidTest/kotlin/app/aaps/plugins/aps/openAPSAMA/TestOpenAPSAMAPlugin.kt +++ b/app/src/androidTest/kotlin/app/aaps/plugins/aps/openAPSAMA/TestOpenAPSAMAPlugin.kt @@ -30,7 +30,7 @@ import app.aaps.core.interfaces.utils.Round import app.aaps.core.interfaces.utils.fabric.FabricPrivacy import app.aaps.core.keys.BooleanKey import app.aaps.core.keys.DoubleKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.constraints.ConstraintObject import app.aaps.core.objects.extensions.target import app.aaps.core.utils.MidnightUtils diff --git a/app/src/androidTest/kotlin/app/aaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.kt b/app/src/androidTest/kotlin/app/aaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.kt index 04f54a70f5d..9f857301bf8 100644 --- a/app/src/androidTest/kotlin/app/aaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.kt +++ b/app/src/androidTest/kotlin/app/aaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.kt @@ -15,12 +15,11 @@ import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.plugin.ActivePlugin import app.aaps.core.interfaces.profile.Profile import app.aaps.core.interfaces.profile.ProfileFunction -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.keys.BooleanKey import app.aaps.core.keys.DoubleKey import app.aaps.core.keys.IntKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.extensions.convertToJSONArray import app.aaps.core.objects.extensions.convertedToAbsolute import app.aaps.core.objects.extensions.getPassedDurationToTimeInMinutes @@ -48,7 +47,6 @@ class DetermineBasalAdapterSMBJS(private val scriptReader: ScriptReader, private @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var constraintChecker: ConstraintsChecker - @Inject lateinit var sp: SP @Inject lateinit var preferences: Preferences @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var processedTbrEbData: ProcessedTbrEbData @@ -230,7 +228,7 @@ class DetermineBasalAdapterSMBJS(private val scriptReader: ScriptReader, private //if (mealData.usedMinCarbsImpact > 0) { // mProfile.put("min_5m_carbimpact", mealData.usedMinCarbsImpact); //} else { - // mProfile.put("min_5m_carbimpact", SP.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact)); + // mProfile.put("min_5m_carbimpact", preferences.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact)); //} this.profile.put("remainingCarbsCap", SMBDefaults.remainingCarbsCap) this.profile.put("enableUAM", uamAllowed) diff --git a/app/src/androidTest/kotlin/app/aaps/plugins/aps/openAPSSMB/TestOpenAPSSMBPlugin.kt b/app/src/androidTest/kotlin/app/aaps/plugins/aps/openAPSSMB/TestOpenAPSSMBPlugin.kt index 2cd2ecb7286..866abb3704a 100644 --- a/app/src/androidTest/kotlin/app/aaps/plugins/aps/openAPSSMB/TestOpenAPSSMBPlugin.kt +++ b/app/src/androidTest/kotlin/app/aaps/plugins/aps/openAPSSMB/TestOpenAPSSMBPlugin.kt @@ -34,7 +34,7 @@ import app.aaps.core.interfaces.utils.HardLimits import app.aaps.core.interfaces.utils.Round import app.aaps.core.keys.BooleanKey import app.aaps.core.keys.DoubleKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.constraints.ConstraintObject import app.aaps.core.objects.extensions.target import app.aaps.core.utils.MidnightUtils diff --git a/app/src/androidTest/kotlin/app/aaps/plugins/aps/openAPSSMBAutoISF/DetermineBasalAdapterAutoISFJS.kt b/app/src/androidTest/kotlin/app/aaps/plugins/aps/openAPSSMBAutoISF/DetermineBasalAdapterAutoISFJS.kt index 95e940d3f07..7dcb6402258 100644 --- a/app/src/androidTest/kotlin/app/aaps/plugins/aps/openAPSSMBAutoISF/DetermineBasalAdapterAutoISFJS.kt +++ b/app/src/androidTest/kotlin/app/aaps/plugins/aps/openAPSSMBAutoISF/DetermineBasalAdapterAutoISFJS.kt @@ -16,13 +16,11 @@ import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.plugin.ActivePlugin import app.aaps.core.interfaces.profile.Profile import app.aaps.core.interfaces.profile.ProfileFunction -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.keys.BooleanKey import app.aaps.core.keys.DoubleKey import app.aaps.core.keys.IntKey -import app.aaps.core.keys.Preferences -import app.aaps.core.keys.UnitDoubleKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.extensions.convertToJSONArray import app.aaps.core.objects.extensions.convertedToAbsolute import app.aaps.core.objects.extensions.getPassedDurationToTimeInMinutes @@ -52,7 +50,6 @@ class DetermineBasalAdapterAutoISFJS(private val scriptReader: ScriptReader, pri @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var constraintChecker: ConstraintsChecker - @Inject lateinit var sp: SP @Inject lateinit var preferences: Preferences @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var processedTbrEbData: ProcessedTbrEbData @@ -234,7 +231,7 @@ class DetermineBasalAdapterAutoISFJS(private val scriptReader: ScriptReader, pri //if (mealData.usedMinCarbsImpact > 0) { // mProfile.put("min_5m_carbimpact", mealData.usedMinCarbsImpact); //} else { - // mProfile.put("min_5m_carbimpact", SP.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact)); + // mProfile.put("min_5m_carbimpact", preferences.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact)); //} this.profile.put("remainingCarbsCap", SMBDefaults.remainingCarbsCap) this.profile.put("enableUAM", uamAllowed) diff --git a/app/src/androidTest/kotlin/app/aaps/plugins/aps/openAPSSMBDynamicISF/DetermineBasalAdapterSMBDynamicISFJS.kt b/app/src/androidTest/kotlin/app/aaps/plugins/aps/openAPSSMBDynamicISF/DetermineBasalAdapterSMBDynamicISFJS.kt index cc08ed863ea..0a6b82c8780 100644 --- a/app/src/androidTest/kotlin/app/aaps/plugins/aps/openAPSSMBDynamicISF/DetermineBasalAdapterSMBDynamicISFJS.kt +++ b/app/src/androidTest/kotlin/app/aaps/plugins/aps/openAPSSMBDynamicISF/DetermineBasalAdapterSMBDynamicISFJS.kt @@ -14,14 +14,13 @@ import app.aaps.core.interfaces.plugin.ActivePlugin import app.aaps.core.interfaces.profile.Profile import app.aaps.core.interfaces.profile.ProfileFunction import app.aaps.core.interfaces.profile.ProfileUtil -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.Round import app.aaps.core.keys.BooleanKey import app.aaps.core.keys.DoubleKey import app.aaps.core.keys.IntKey -import app.aaps.core.keys.Preferences import app.aaps.core.keys.UnitDoubleKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.extensions.convertToJSONArray import app.aaps.core.objects.extensions.convertedToAbsolute import app.aaps.core.objects.extensions.getPassedDurationToTimeInMinutes @@ -51,7 +50,6 @@ import kotlin.math.ln class DetermineBasalAdapterSMBDynamicISFJS(private val scriptReader: ScriptReader, private val injector: HasAndroidInjector) : DetermineBasalAdapter { @Inject lateinit var aapsLogger: AAPSLogger - @Inject lateinit var sp: SP @Inject lateinit var preferences: Preferences @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var processedTbrEbData: ProcessedTbrEbData @@ -251,7 +249,7 @@ class DetermineBasalAdapterSMBDynamicISFJS(private val scriptReader: ScriptReade //if (mealData.usedMinCarbsImpact > 0) { // mProfile.put("min_5m_carbimpact", mealData.usedMinCarbsImpact); //} else { - // mProfile.put("min_5m_carbimpact", SP.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact)); + // mProfile.put("min_5m_carbimpact", preferences.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact)); //} this.profile.put("remainingCarbsCap", SMBDefaults.remainingCarbsCap) this.profile.put("enableUAM", uamAllowed) diff --git a/app/src/androidTest/kotlin/app/aaps/plugins/aps/openAPSSMBDynamicISF/TestOpenAPSSMBDynamicISFPlugin.kt b/app/src/androidTest/kotlin/app/aaps/plugins/aps/openAPSSMBDynamicISF/TestOpenAPSSMBDynamicISFPlugin.kt index 84b140cdb36..05cf7896677 100644 --- a/app/src/androidTest/kotlin/app/aaps/plugins/aps/openAPSSMBDynamicISF/TestOpenAPSSMBDynamicISFPlugin.kt +++ b/app/src/androidTest/kotlin/app/aaps/plugins/aps/openAPSSMBDynamicISF/TestOpenAPSSMBDynamicISFPlugin.kt @@ -21,7 +21,7 @@ import app.aaps.core.interfaces.stats.TddCalculator import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.HardLimits -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.plugins.aps.R import app.aaps.plugins.aps.openAPSSMB.DetermineBasalAdapterSMBJS import app.aaps.plugins.aps.openAPSSMB.TestOpenAPSSMBPlugin diff --git a/app/src/androidTest/kotlin/app/aaps/unusedTests/RealPumpTest.kt b/app/src/androidTest/kotlin/app/aaps/unusedTests/RealPumpTest.kt index 0d360fcbb06..d30d0892a29 100644 --- a/app/src/androidTest/kotlin/app/aaps/unusedTests/RealPumpTest.kt +++ b/app/src/androidTest/kotlin/app/aaps/unusedTests/RealPumpTest.kt @@ -23,7 +23,7 @@ class RealPumpTest { @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin @Inject lateinit var objectivesPlugin: ObjectivesPlugin @Inject lateinit var treatmentsPlugin: TreatmentsPlugin - @Inject lateinit var sp: SP + @Inject lateinit var preferences: Preferences @Rule @JvmField diff --git a/app/src/main/kotlin/app/aaps/MainActivity.kt b/app/src/main/kotlin/app/aaps/MainActivity.kt index 54edb9d9a57..1aff715650e 100644 --- a/app/src/main/kotlin/app/aaps/MainActivity.kt +++ b/app/src/main/kotlin/app/aaps/MainActivity.kt @@ -49,7 +49,6 @@ import app.aaps.core.interfaces.rx.events.EventAppExit import app.aaps.core.interfaces.rx.events.EventAppInitialized import app.aaps.core.interfaces.rx.events.EventPreferenceChange import app.aaps.core.interfaces.rx.events.EventRebuildTabs -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.smsCommunicator.SmsCommunicator import app.aaps.core.interfaces.ui.IconsProvider import app.aaps.core.interfaces.ui.UiInteraction @@ -89,7 +88,6 @@ class MainActivity : DaggerAppCompatActivityWithResult() { private val disposable = CompositeDisposable() @Inject lateinit var aapsSchedulers: AapsSchedulers - @Inject lateinit var sp: SP @Inject lateinit var versionCheckerUtils: VersionCheckerUtils @Inject lateinit var smsCommunicator: SmsCommunicator @Inject lateinit var loop: Loop diff --git a/app/src/main/kotlin/app/aaps/MainApp.kt b/app/src/main/kotlin/app/aaps/MainApp.kt index d002697cc6f..6b5a8037cba 100644 --- a/app/src/main/kotlin/app/aaps/MainApp.kt +++ b/app/src/main/kotlin/app/aaps/MainApp.kt @@ -9,6 +9,7 @@ import android.os.Build import android.os.Handler import android.os.HandlerThread import androidx.lifecycle.ProcessLifecycleOwner +import app.aaps.core.data.configuration.Constants import app.aaps.core.data.model.GlucoseUnit import app.aaps.core.data.model.TE import app.aaps.core.data.ue.Action @@ -24,12 +25,14 @@ import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.interfaces.utils.DateUtil +import app.aaps.core.interfaces.utils.SafeParse import app.aaps.core.interfaces.versionChecker.VersionCheckerUtils import app.aaps.core.keys.BooleanKey import app.aaps.core.keys.IntKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.LongComposedKey import app.aaps.core.keys.StringKey import app.aaps.core.keys.UnitDoubleKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.ui.extensions.runOnUiThread import app.aaps.core.ui.locale.LocaleHelper import app.aaps.database.persistence.CompatDBHelper @@ -37,8 +40,13 @@ import app.aaps.di.DaggerAppComponent import app.aaps.implementation.lifecycle.ProcessLifecycleListener import app.aaps.implementation.plugin.PluginStore import app.aaps.implementation.receivers.NetworkChangeReceiver +import app.aaps.plugins.configuration.keys.ConfigurationBooleanComposedKey +import app.aaps.plugins.constraints.objectives.keys.ObjectivesLongComposedKey import app.aaps.plugins.main.general.overview.notifications.NotificationStore import app.aaps.plugins.main.general.themes.ThemeSwitcherPlugin +import app.aaps.plugins.main.profile.keys.ProfileComposedBooleanKey +import app.aaps.plugins.main.profile.keys.ProfileComposedDoubleKey +import app.aaps.plugins.main.profile.keys.ProfileComposedStringKey import app.aaps.receivers.BTReceiver import app.aaps.receivers.ChargingStateReceiver import app.aaps.receivers.KeepAliveWorker @@ -113,6 +121,8 @@ class MainApp : DaggerApplication() { // trigger here to see the new version on app start after an update handler.postDelayed({ versionCheckersUtils.triggerCheckVersion() }, 30000) + doMigrations() + // Register all tabs in app here pluginStore.plugins = plugins configBuilder.initialize() @@ -139,7 +149,6 @@ class MainApp : DaggerApplication() { KeepAliveWorker.schedule(this@MainApp) localAlertUtils.shortenSnoozeInterval() localAlertUtils.preSnoozeAlarms() - doMigrations() // schedule widget update refreshWidget = Runnable { @@ -181,13 +190,6 @@ class MainApp : DaggerApplication() { private fun doMigrations() { // set values for different builds - // 3.1.0 - if (preferences.getIfExists(StringKey.MaintenanceEmail) == "logs@androidaps.org") - preferences.put(StringKey.MaintenanceEmail, "logs@aaps.app") - // fix values for theme switching - sp.putString(app.aaps.plugins.main.R.string.value_dark_theme, "dark") - sp.putString(app.aaps.plugins.main.R.string.value_light_theme, "light") - sp.putString(app.aaps.plugins.main.R.string.value_system_theme, "system") // 3.3 if (preferences.get(IntKey.OverviewEatingSoonDuration) == 0) preferences.remove(IntKey.OverviewEatingSoonDuration) if (preferences.get(UnitDoubleKey.OverviewEatingSoonTarget) == 0.0) preferences.remove(UnitDoubleKey.OverviewEatingSoonTarget) @@ -215,6 +217,120 @@ class MainApp : DaggerApplication() { } // Clear SmsOtpPassword if wrongly replaced if (preferences.get(StringKey.SmsOtpPassword).length > 10) preferences.put(StringKey.SmsOtpPassword, "") + + val keys: Map = sp.getAll() + // Migrate ActivityMonitor + for ((key, value) in keys) { + if (key.startsWith("Monitor") && key.endsWith("total")) { + val activity = key.split("_")[1] + if (value is String) + preferences.put(LongComposedKey.ActivityMonitorTotal, activity, value = SafeParse.stringToLong(value)) + else + preferences.put(LongComposedKey.ActivityMonitorTotal, activity, value = value as Long) + sp.remove(key) + } + if (key.startsWith("Monitor") && key.endsWith("resumed")) { + val activity = key.split("_")[1] + if (value is String) + preferences.put(LongComposedKey.ActivityMonitorResumed, activity, value = SafeParse.stringToLong(value)) + else + preferences.put(LongComposedKey.ActivityMonitorResumed, activity, value = value as Long) + sp.remove(key) + } + if (key.startsWith("Monitor") && key.endsWith("start")) { + val activity = key.split("_")[1] + if (value is String) + preferences.put(LongComposedKey.ActivityMonitorStart, activity, value = SafeParse.stringToLong(value)) + else + preferences.put(LongComposedKey.ActivityMonitorStart, activity, value = value as Long) + sp.remove(key) + } + } + // Migrate Objectives + for ((key, value) in keys) { + if (key.startsWith("Objectives_") && key.endsWith("_started")) { + val objective = key.split("_")[1] + if (value is String) + preferences.put(ObjectivesLongComposedKey.Started, objective, value = SafeParse.stringToLong(value)) + else + preferences.put(ObjectivesLongComposedKey.Started, objective, value = value as Long) + sp.remove(key) + } + if (key.startsWith("Objectives_") && key.endsWith("_accomplished")) { + val objective = key.split("_")[1] + if (value is String) + preferences.put(ObjectivesLongComposedKey.Accomplished, objective, value = SafeParse.stringToLong(value)) + else + preferences.put(ObjectivesLongComposedKey.Accomplished, objective, value = value as Long) + sp.remove(key) + } + } + // Migrate ConfigBuilder + for ((key, value) in keys) { + if (key.startsWith("ConfigBuilder_") && key.endsWith("_Enabled")) { + val plugin = key.split("_")[1] + "_" + key.split("_")[2] + preferences.put(ConfigurationBooleanComposedKey.ConfigBuilderEnabled, plugin, value = value as Boolean) + sp.remove(key) + } + if (key.startsWith("ConfigBuilder_") && key.endsWith("_Visible")) { + val plugin = key.split("_")[1] + "_" + key.split("_")[2] + preferences.put(ConfigurationBooleanComposedKey.ConfigBuilderVisible, plugin, value = value as Boolean) + sp.remove(key) + } + } + // Migrate Profile + for ((key, value) in keys) { + if (key.startsWith(Constants.LOCAL_PROFILE + "_") && key.endsWith("_mgdl")) { + val number = key.split("_")[1] + preferences.put(ProfileComposedBooleanKey.LocalProfileNumberedMgdl, SafeParse.stringToInt(number), value = value as Boolean) + sp.remove(key) + } + if (key.startsWith(Constants.LOCAL_PROFILE + "_") && key.endsWith("_isf")) { + val number = key.split("_")[1] + preferences.put(ProfileComposedStringKey.LocalProfileNumberedIsf, SafeParse.stringToInt(number), value = value as String) + sp.remove(key) + } + if (key.startsWith(Constants.LOCAL_PROFILE + "_") && key.endsWith("_ic")) { + val number = key.split("_")[1] + preferences.put(ProfileComposedStringKey.LocalProfileNumberedIc, SafeParse.stringToInt(number), value = value as String) + sp.remove(key) + } + if (key.startsWith(Constants.LOCAL_PROFILE + "_") && key.endsWith("_ic")) { + val number = key.split("_")[1] + preferences.put(ProfileComposedStringKey.LocalProfileNumberedIc, SafeParse.stringToInt(number), value = value as String) + sp.remove(key) + } + if (key.startsWith(Constants.LOCAL_PROFILE + "_") && key.endsWith("_basal")) { + val number = key.split("_")[1] + preferences.put(ProfileComposedStringKey.LocalProfileNumberedBasal, SafeParse.stringToInt(number), value = value as String) + sp.remove(key) + } + if (key.startsWith(Constants.LOCAL_PROFILE + "_") && key.endsWith("_targetlow")) { + val number = key.split("_")[1] + preferences.put(ProfileComposedStringKey.LocalProfileNumberedTargetLow, SafeParse.stringToInt(number), value = value as String) + sp.remove(key) + } + if (key.startsWith(Constants.LOCAL_PROFILE + "_") && key.endsWith("_targethigh")) { + val number = key.split("_")[1] + preferences.put(ProfileComposedStringKey.LocalProfileNumberedTargetHigh, SafeParse.stringToInt(number), value = value as String) + sp.remove(key) + } + if (key.startsWith(Constants.LOCAL_PROFILE + "_") && key.endsWith("_name")) { + val number = key.split("_")[1] + preferences.put(ProfileComposedStringKey.LocalProfileNumberedName, SafeParse.stringToInt(number), value = value as String) + sp.remove(key) + } + if (key.startsWith(Constants.LOCAL_PROFILE + "_") && key.endsWith("_dia")) { + val number = key.split("_")[1] + if (value is String) + preferences.put(ProfileComposedDoubleKey.LocalProfileNumberedDia, SafeParse.stringToInt(number), value = SafeParse.stringToDouble(value)) + else if (value is Float) + preferences.put(ProfileComposedDoubleKey.LocalProfileNumberedDia, SafeParse.stringToInt(number), value = value.toDouble()) + else + preferences.put(ProfileComposedDoubleKey.LocalProfileNumberedDia, SafeParse.stringToInt(number), value = value as Double) + sp.remove(key) + } + } } override fun applicationInjector(): AndroidInjector { diff --git a/app/src/main/kotlin/app/aaps/activities/HistoryBrowseActivity.kt b/app/src/main/kotlin/app/aaps/activities/HistoryBrowseActivity.kt index e6ae2367125..5579f36c65d 100644 --- a/app/src/main/kotlin/app/aaps/activities/HistoryBrowseActivity.kt +++ b/app/src/main/kotlin/app/aaps/activities/HistoryBrowseActivity.kt @@ -26,8 +26,8 @@ import app.aaps.core.interfaces.rx.events.EventUpdateOverviewGraph import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.fabric.FabricPrivacy import app.aaps.core.interfaces.workflow.CalculationWorkflow -import app.aaps.core.keys.Preferences import app.aaps.core.keys.UnitDoubleKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.ui.activities.TranslatedDaggerAppCompatActivity import app.aaps.core.ui.extensions.toVisibility import app.aaps.core.ui.extensions.toVisibilityKeepSpace diff --git a/app/src/main/kotlin/app/aaps/activities/HistoryBrowserData.kt b/app/src/main/kotlin/app/aaps/activities/HistoryBrowserData.kt index 26f418eb2e0..ac437fcf4d3 100644 --- a/app/src/main/kotlin/app/aaps/activities/HistoryBrowserData.kt +++ b/app/src/main/kotlin/app/aaps/activities/HistoryBrowserData.kt @@ -8,12 +8,11 @@ import app.aaps.core.interfaces.profile.ProfileFunction import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.AapsSchedulers import app.aaps.core.interfaces.rx.bus.RxBus -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.DecimalFormatter import app.aaps.core.interfaces.utils.fabric.FabricPrivacy import app.aaps.core.interfaces.workflow.CalculationWorkflow -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.plugins.main.general.overview.OverviewDataImpl import app.aaps.plugins.main.iob.iobCobCalculator.IobCobCalculatorPlugin import javax.inject.Inject @@ -26,7 +25,6 @@ class HistoryBrowserData @Inject constructor( aapsLogger: AAPSLogger, rh: ResourceHelper, dateUtil: DateUtil, - sp: SP, preferences: Preferences, activePlugin: ActivePlugin, profileFunction: ProfileFunction, @@ -39,7 +37,7 @@ class HistoryBrowserData @Inject constructor( // We don't want to use injected singletons but own instance working on top of different data val overviewData = - OverviewDataImpl(rh, dateUtil, sp, activePlugin, profileFunction, persistenceLayer, processedTbrEbData) + OverviewDataImpl(rh, dateUtil, preferences, activePlugin, profileFunction, persistenceLayer, processedTbrEbData) val iobCobCalculator = IobCobCalculatorPlugin( aapsLogger, aapsSchedulers, rxBus, preferences, rh, profileFunction, activePlugin, diff --git a/app/src/main/kotlin/app/aaps/activities/MyPreferenceFragment.kt b/app/src/main/kotlin/app/aaps/activities/MyPreferenceFragment.kt index 109b013c377..a5acdf60a65 100644 --- a/app/src/main/kotlin/app/aaps/activities/MyPreferenceFragment.kt +++ b/app/src/main/kotlin/app/aaps/activities/MyPreferenceFragment.kt @@ -25,20 +25,19 @@ import app.aaps.core.interfaces.protection.PasswordCheck import app.aaps.core.interfaces.protection.ProtectionCheck.ProtectionType.BIOMETRIC import app.aaps.core.interfaces.protection.ProtectionCheck.ProtectionType.CUSTOM_PASSWORD import app.aaps.core.interfaces.protection.ProtectionCheck.ProtectionType.CUSTOM_PIN -import app.aaps.core.interfaces.protection.ProtectionCheck.ProtectionType.NONE import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventPreferenceChange import app.aaps.core.interfaces.rx.events.EventRebuildTabs -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.keys.BooleanKey -import app.aaps.core.keys.DoublePreferenceKey import app.aaps.core.keys.IntKey -import app.aaps.core.keys.IntPreferenceKey -import app.aaps.core.keys.Preferences import app.aaps.core.keys.StringKey -import app.aaps.core.keys.StringPreferenceKey +import app.aaps.core.keys.interfaces.DoublePreferenceKey +import app.aaps.core.keys.interfaces.IntPreferenceKey +import app.aaps.core.keys.interfaces.PreferenceKey +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.core.keys.interfaces.StringPreferenceKey import app.aaps.core.ui.dialogs.OKDialog import app.aaps.core.utils.extensions.safeGetSerializable import app.aaps.core.validators.DefaultEditTextValidator @@ -66,7 +65,6 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang @Inject lateinit var rxBus: RxBus @Inject lateinit var rh: ResourceHelper - @Inject lateinit var sp: SP @Inject lateinit var preferences: Preferences @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var config: Config @@ -152,8 +150,8 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang } try { initSummary(preferenceScreen, pluginName != null) - } catch (_: Exception) { - throw Exception("Error in onCreatePreferences pluginName=$pluginName customPreference=$customPreference rootKey=$rootKey filter=$filter") + } catch (e: Exception) { + throw Exception("Error in onCreatePreferences pluginName=$pluginName customPreference=$customPreference rootKey=$rootKey filter=$filter", e) } preprocessPreferences() if (filter != "") updateFilterVisibility(filter, preferenceScreen) @@ -179,7 +177,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang OKDialog.show(it, rh.gs(app.aaps.plugins.configuration.R.string.configbuilder_sensitivity), rh.gs(R.string.sensitivity_warning)) } } - checkForBiometricFallback(key) + checkForBiometricFallback(preferences.get(key) as PreferenceKey?) preprocessCustomVisibility(preferenceScreen) updatePrefSummary(findPreference(key)) @@ -199,11 +197,11 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang } } - private fun checkForBiometricFallback(key: String) { + private fun checkForBiometricFallback(key: PreferenceKey?) { // Biometric protection activated without set master password - if ((IntKey.ProtectionTypeSettings.key == key || IntKey.ProtectionTypeApplication.key == key || IntKey.ProtectionTypeBolus.key == key) && + if ((IntKey.ProtectionTypeSettings == key || IntKey.ProtectionTypeApplication == key || IntKey.ProtectionTypeBolus == key) && preferences.get(StringKey.ProtectionMasterPassword) == "" && - sp.getInt(key, NONE.ordinal) == BIOMETRIC.ordinal + preferences.get(key as IntKey) == BIOMETRIC.ordinal ) { activity?.let { val title = rh.gs(app.aaps.core.ui.R.string.unsecure_fallback_biometric) @@ -216,7 +214,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang val isBiometricActivated = preferences.get(IntKey.ProtectionTypeSettings) == BIOMETRIC.ordinal || preferences.get(IntKey.ProtectionTypeApplication) == BIOMETRIC.ordinal || preferences.get(IntKey.ProtectionTypeBolus) == BIOMETRIC.ordinal - if (StringKey.ProtectionMasterPassword.key == key && sp.getString(key, "") == "" && isBiometricActivated) { + if (StringKey.ProtectionMasterPassword == key && preferences.get(key as StringKey) == "" && isBiometricActivated) { activity?.let { val title = rh.gs(app.aaps.core.ui.R.string.unsecure_fallback_biometric) val message = rh.gs(app.aaps.core.ui.R.string.unsecure_fallback_descriotion_biometric) @@ -290,7 +288,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang } is StringPreferenceKey -> { - val value = sp.getString(pref.key, "") + val value = preferences.get(keyDefinition) when { // We use Preference and custom editor instead of EditTextPreference // to hash password while it is saved and never have to show it, even hashed @@ -436,8 +434,8 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang addPreference( AdaptiveClickPreference(ctx = context, stringKey = StringKey.ProtectionMasterPassword, title = app.aaps.core.ui.R.string.master_password, onPreferenceClickListener = { - passwordCheck.queryPassword(context, app.aaps.plugins.configuration.R.string.current_master_password, StringKey.ProtectionMasterPassword.key, { - passwordCheck.setPassword(context, app.aaps.core.ui.R.string.master_password, StringKey.ProtectionMasterPassword.key) + passwordCheck.queryPassword(context, app.aaps.plugins.configuration.R.string.current_master_password, StringKey.ProtectionMasterPassword, { + passwordCheck.setPassword(context, app.aaps.core.ui.R.string.master_password, StringKey.ProtectionMasterPassword) }) true } @@ -447,7 +445,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang addPreference( AdaptiveClickPreference(ctx = context, stringKey = StringKey.ProtectionSettingsPassword, title = app.aaps.core.ui.R.string.settings_password, onPreferenceClickListener = { - passwordCheck.setPassword(context, app.aaps.core.ui.R.string.settings_password, StringKey.ProtectionSettingsPassword.key) + passwordCheck.setPassword(context, app.aaps.core.ui.R.string.settings_password, StringKey.ProtectionSettingsPassword) true }, calculatedVisibility = { preferences.get(IntKey.ProtectionTypeSettings) == CUSTOM_PASSWORD.ordinal }) @@ -455,7 +453,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang addPreference( AdaptiveClickPreference(ctx = context, stringKey = StringKey.ProtectionSettingsPin, title = app.aaps.core.ui.R.string.settings_pin, onPreferenceClickListener = { - passwordCheck.setPassword(context, app.aaps.core.ui.R.string.settings_pin, StringKey.ProtectionSettingsPin.key, pinInput = true) + passwordCheck.setPassword(context, app.aaps.core.ui.R.string.settings_pin, StringKey.ProtectionSettingsPin, pinInput = true) true }, calculatedVisibility = { preferences.get(IntKey.ProtectionTypeSettings) == CUSTOM_PIN.ordinal }) @@ -464,7 +462,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang addPreference( AdaptiveClickPreference(ctx = context, stringKey = StringKey.ProtectionApplicationPassword, title = app.aaps.core.ui.R.string.application_password, onPreferenceClickListener = { - passwordCheck.setPassword(context, app.aaps.core.ui.R.string.application_password, StringKey.ProtectionApplicationPassword.key) + passwordCheck.setPassword(context, app.aaps.core.ui.R.string.application_password, StringKey.ProtectionApplicationPassword) true }, calculatedVisibility = { preferences.get(IntKey.ProtectionTypeApplication) == CUSTOM_PASSWORD.ordinal }) @@ -472,7 +470,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang addPreference( AdaptiveClickPreference(ctx = context, stringKey = StringKey.ProtectionApplicationPin, title = app.aaps.core.ui.R.string.application_pin, onPreferenceClickListener = { - passwordCheck.setPassword(context, app.aaps.core.ui.R.string.application_pin, StringKey.ProtectionApplicationPin.key, pinInput = true) + passwordCheck.setPassword(context, app.aaps.core.ui.R.string.application_pin, StringKey.ProtectionApplicationPin, pinInput = true) true }, calculatedVisibility = { preferences.get(IntKey.ProtectionTypeApplication) == CUSTOM_PIN.ordinal }) @@ -481,7 +479,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang addPreference( AdaptiveClickPreference(ctx = context, stringKey = StringKey.ProtectionBolusPassword, title = app.aaps.core.ui.R.string.bolus_password, onPreferenceClickListener = { - passwordCheck.setPassword(context, app.aaps.core.ui.R.string.bolus_password, StringKey.ProtectionBolusPassword.key) + passwordCheck.setPassword(context, app.aaps.core.ui.R.string.bolus_password, StringKey.ProtectionBolusPassword) true }, calculatedVisibility = { preferences.get(IntKey.ProtectionTypeBolus) == CUSTOM_PASSWORD.ordinal }) @@ -489,7 +487,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang addPreference( AdaptiveClickPreference(ctx = context, stringKey = StringKey.ProtectionBolusPin, title = app.aaps.core.ui.R.string.bolus_pin, onPreferenceClickListener = { - passwordCheck.setPassword(context, app.aaps.core.ui.R.string.bolus_pin, StringKey.ProtectionBolusPin.key, pinInput = true) + passwordCheck.setPassword(context, app.aaps.core.ui.R.string.bolus_pin, StringKey.ProtectionBolusPin, pinInput = true) true }, calculatedVisibility = { preferences.get(IntKey.ProtectionTypeBolus) == CUSTOM_PIN.ordinal }) diff --git a/app/src/main/kotlin/app/aaps/implementations/ConfigImpl.kt b/app/src/main/kotlin/app/aaps/implementations/ConfigImpl.kt index bfbe9457f0d..1fb37e249ed 100644 --- a/app/src/main/kotlin/app/aaps/implementations/ConfigImpl.kt +++ b/app/src/main/kotlin/app/aaps/implementations/ConfigImpl.kt @@ -5,13 +5,14 @@ import app.aaps.BuildConfig import app.aaps.R import app.aaps.core.interfaces.configuration.Config import app.aaps.core.interfaces.maintenance.FileListProvider +import dagger.Lazy import dagger.Reusable import javax.inject.Inject @Suppress("KotlinConstantConditions") @Reusable class ConfigImpl @Inject constructor( - private val fileListProvider: FileListProvider + private val fileListProvider: Lazy ) : Config { override val SUPPORTED_NS_VERSION = 150000 // 15.0.0 @@ -42,10 +43,10 @@ class ConfigImpl @Inject constructor( private var doNotSendSmsOnProfileChange: Boolean? = null override fun isEngineeringModeOrRelease(): Boolean = if (!APS) true else isEngineeringMode() || !isDev() - override fun isEngineeringMode(): Boolean = isEngineeringMode ?: (fileListProvider.ensureExtraDirExists()?.findFile("engineering_mode") != null).also { isEngineeringMode = it } - override fun isUnfinishedMode(): Boolean = isUnfinishedMode ?: (fileListProvider.ensureExtraDirExists()?.findFile("unfinished_mode") != null).also { isUnfinishedMode = it } + override fun isEngineeringMode(): Boolean = isEngineeringMode ?: (fileListProvider.get().ensureExtraDirExists()?.findFile("engineering_mode") != null).also { isEngineeringMode = it } + override fun isUnfinishedMode(): Boolean = isUnfinishedMode ?: (fileListProvider.get().ensureExtraDirExists()?.findFile("unfinished_mode") != null).also { isUnfinishedMode = it } override fun isDev(): Boolean = (VERSION.contains("-") || VERSION.matches(Regex(".*[a-zA-Z]+.*"))) && !VERSION.contains("-beta") && !VERSION.contains("-rc") - override fun showUserActionsOnWatchOnly(): Boolean = showUserActionsOnWatchOnly ?: (fileListProvider.ensureExtraDirExists()?.findFile("show_user_actions_on_watch_only") != null).also { showUserActionsOnWatchOnly = it } - override fun ignoreNightscoutV3Errors(): Boolean = ignoreNightscoutV3Errors ?: (fileListProvider.ensureExtraDirExists()?.findFile("ignore_nightscout_v3_errors") != null).also { ignoreNightscoutV3Errors = it } - override fun doNotSendSmsOnProfileChange(): Boolean = doNotSendSmsOnProfileChange ?: (fileListProvider.ensureExtraDirExists()?.findFile("do_not_send_sms_on_profile_change") != null).also { doNotSendSmsOnProfileChange = it } + override fun showUserActionsOnWatchOnly(): Boolean = showUserActionsOnWatchOnly ?: (fileListProvider.get().ensureExtraDirExists()?.findFile("show_user_actions_on_watch_only") != null).also { showUserActionsOnWatchOnly = it } + override fun ignoreNightscoutV3Errors(): Boolean = ignoreNightscoutV3Errors ?: (fileListProvider.get().ensureExtraDirExists()?.findFile("ignore_nightscout_v3_errors") != null).also { ignoreNightscoutV3Errors = it } + override fun doNotSendSmsOnProfileChange(): Boolean = doNotSendSmsOnProfileChange ?: (fileListProvider.get().ensureExtraDirExists()?.findFile("do_not_send_sms_on_profile_change") != null).also { doNotSendSmsOnProfileChange = it } } \ No newline at end of file diff --git a/app/src/main/kotlin/app/aaps/receivers/KeepAliveWorker.kt b/app/src/main/kotlin/app/aaps/receivers/KeepAliveWorker.kt index c665ed1b4de..b589b08b95b 100644 --- a/app/src/main/kotlin/app/aaps/receivers/KeepAliveWorker.kt +++ b/app/src/main/kotlin/app/aaps/receivers/KeepAliveWorker.kt @@ -11,7 +11,6 @@ import androidx.work.WorkManager import androidx.work.WorkQuery import androidx.work.WorkerParameters import androidx.work.workDataOf -import app.aaps.R import app.aaps.core.data.time.T import app.aaps.core.interfaces.alerts.LocalAlertUtils import app.aaps.core.interfaces.aps.Loop @@ -27,9 +26,10 @@ import app.aaps.core.interfaces.queue.CommandQueue import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventProfileSwitchChanged -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.fabric.FabricPrivacy +import app.aaps.core.keys.LongNonKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.profile.ProfileSealed import app.aaps.core.objects.workflow.LoggingWorker import app.aaps.plugins.configuration.maintenance.MaintenancePlugin @@ -56,7 +56,7 @@ class KeepAliveWorker( @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var maintenancePlugin: MaintenancePlugin @Inject lateinit var rh: ResourceHelper - @Inject lateinit var sp: SP + @Inject lateinit var preferences: Preferences companion object { @@ -140,11 +140,11 @@ class KeepAliveWorker( // Perform history data cleanup every day // Keep 6 months private fun databaseCleanup() { - val lastRun = sp.getLong(R.string.key_last_cleanup_run, 0L) + val lastRun = preferences.get(LongNonKey.LastCleanupRun) if (lastRun < dateUtil.now() - T.days(1).msecs()) { val result = persistenceLayer.cleanupDatabase(6 * 31, deleteTrackedChanges = false) aapsLogger.debug(LTag.CORE, "Cleanup result: $result") - sp.putLong(R.string.key_last_cleanup_run, dateUtil.now()) + preferences.put(LongNonKey.LastCleanupRun, dateUtil.now()) } } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 3e1988b7f9b..e6b86d782c6 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1,7 +1,6 @@ System default - last_cleanup_run %1$s Preferences Exit Delta diff --git a/core/graph/src/main/kotlin/app/aaps/core/graph/data/BolusDataPoint.kt b/core/graph/src/main/kotlin/app/aaps/core/graph/data/BolusDataPoint.kt index eba50fa88ad..d69b48d7dbb 100644 --- a/core/graph/src/main/kotlin/app/aaps/core/graph/data/BolusDataPoint.kt +++ b/core/graph/src/main/kotlin/app/aaps/core/graph/data/BolusDataPoint.kt @@ -5,8 +5,8 @@ import android.graphics.Paint import app.aaps.core.data.model.BS import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.utils.DecimalFormatter -import app.aaps.core.keys.Preferences import app.aaps.core.keys.UnitDoubleKey +import app.aaps.core.keys.interfaces.Preferences class BolusDataPoint( val data: BS, diff --git a/core/graph/src/main/kotlin/app/aaps/core/graph/data/InMemoryGlucoseValueDataPoint.kt b/core/graph/src/main/kotlin/app/aaps/core/graph/data/InMemoryGlucoseValueDataPoint.kt index a7780fa5919..8c0408f59a0 100644 --- a/core/graph/src/main/kotlin/app/aaps/core/graph/data/InMemoryGlucoseValueDataPoint.kt +++ b/core/graph/src/main/kotlin/app/aaps/core/graph/data/InMemoryGlucoseValueDataPoint.kt @@ -9,8 +9,8 @@ import app.aaps.core.data.iob.InMemoryGlucoseValue import app.aaps.core.data.model.GlucoseUnit import app.aaps.core.interfaces.profile.ProfileFunction import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.keys.Preferences import app.aaps.core.keys.UnitDoubleKey +import app.aaps.core.keys.interfaces.Preferences class InMemoryGlucoseValueDataPoint( val data: InMemoryGlucoseValue, diff --git a/core/graph/src/test/kotlin/app/aaps/core/grap/data/InMemoryGlucoseValueDataPointTest.kt b/core/graph/src/test/kotlin/app/aaps/core/grap/data/InMemoryGlucoseValueDataPointTest.kt index 1559fab6934..041e2bdcc9a 100644 --- a/core/graph/src/test/kotlin/app/aaps/core/grap/data/InMemoryGlucoseValueDataPointTest.kt +++ b/core/graph/src/test/kotlin/app/aaps/core/grap/data/InMemoryGlucoseValueDataPointTest.kt @@ -8,7 +8,7 @@ import app.aaps.core.data.model.SourceSensor import app.aaps.core.graph.data.InMemoryGlucoseValueDataPoint import app.aaps.core.interfaces.profile.ProfileFunction import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import com.google.common.truth.Truth.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test diff --git a/core/interfaces/build.gradle.kts b/core/interfaces/build.gradle.kts index 93c0066ac98..cc24547f7ba 100644 --- a/core/interfaces/build.gradle.kts +++ b/core/interfaces/build.gradle.kts @@ -18,6 +18,7 @@ android { dependencies { implementation(project(":core:data")) + implementation(project(":core:keys")) api(libs.androidx.appcompat) diff --git a/core/interfaces/src/main/kotlin/app/aaps/core/interfaces/logging/L.kt b/core/interfaces/src/main/kotlin/app/aaps/core/interfaces/logging/L.kt index 8e571d97c59..516b7e6554a 100644 --- a/core/interfaces/src/main/kotlin/app/aaps/core/interfaces/logging/L.kt +++ b/core/interfaces/src/main/kotlin/app/aaps/core/interfaces/logging/L.kt @@ -4,5 +4,5 @@ interface L { fun resetToDefaults() fun findByName(name: String): LogElement - fun getLogElements(): List + fun logElements(): List } \ No newline at end of file diff --git a/core/interfaces/src/main/kotlin/app/aaps/core/interfaces/logging/LTag.kt b/core/interfaces/src/main/kotlin/app/aaps/core/interfaces/logging/LTag.kt index 69a38331b76..2ec1668ec2e 100644 --- a/core/interfaces/src/main/kotlin/app/aaps/core/interfaces/logging/LTag.kt +++ b/core/interfaces/src/main/kotlin/app/aaps/core/interfaces/logging/LTag.kt @@ -10,7 +10,6 @@ enum class LTag(val tag: String, val defaultValue: Boolean = true, val requiresR CONFIGBUILDER("CONFIGBUILDER"), CONSTRAINTS("CONSTRAINTS"), DATABASE("DATABASE"), - DATATREATMENTS("DATATREATMENTS"), EVENTS("EVENTS", defaultValue = false, requiresRestart = true), GARMIN("GARMIN"), GLUCOSE("GLUCOSE", defaultValue = false), diff --git a/core/interfaces/src/main/kotlin/app/aaps/core/interfaces/plugin/PluginBaseWithPreferences.kt b/core/interfaces/src/main/kotlin/app/aaps/core/interfaces/plugin/PluginBaseWithPreferences.kt new file mode 100644 index 00000000000..9e24bf7bde6 --- /dev/null +++ b/core/interfaces/src/main/kotlin/app/aaps/core/interfaces/plugin/PluginBaseWithPreferences.kt @@ -0,0 +1,22 @@ +package app.aaps.core.interfaces.plugin + +import app.aaps.core.interfaces.logging.AAPSLogger +import app.aaps.core.interfaces.resources.ResourceHelper +import app.aaps.core.keys.interfaces.NonPreferenceKey +import app.aaps.core.keys.interfaces.Preferences + +/** + * Add preference handling to [PluginBase] + */ +abstract class PluginBaseWithPreferences( + pluginDescription: PluginDescription, + val ownPreferences: List> = emptyList(), + aapsLogger: AAPSLogger, + rh: ResourceHelper, + val preferences: Preferences +) : PluginBase(pluginDescription, aapsLogger, rh) { + + init { + ownPreferences.forEach { preferences.registerPreferences(it) } + } +} \ No newline at end of file diff --git a/core/interfaces/src/main/kotlin/app/aaps/core/interfaces/plugin/PluginDescription.kt b/core/interfaces/src/main/kotlin/app/aaps/core/interfaces/plugin/PluginDescription.kt index 3a91124767f..3e28181b478 100644 --- a/core/interfaces/src/main/kotlin/app/aaps/core/interfaces/plugin/PluginDescription.kt +++ b/core/interfaces/src/main/kotlin/app/aaps/core/interfaces/plugin/PluginDescription.kt @@ -14,7 +14,7 @@ open class PluginDescription { const val PREFERENCE_NONE = -1 /** - * Plugin generates [PreferenceScreen] directly + * Plugin generates [androidx.preference.PreferenceScreen] directly */ const val PREFERENCE_SCREEN = 0 } diff --git a/core/interfaces/src/main/kotlin/app/aaps/core/interfaces/profile/ProfileUtil.kt b/core/interfaces/src/main/kotlin/app/aaps/core/interfaces/profile/ProfileUtil.kt index fbfc183422b..e8452995aa7 100644 --- a/core/interfaces/src/main/kotlin/app/aaps/core/interfaces/profile/ProfileUtil.kt +++ b/core/interfaces/src/main/kotlin/app/aaps/core/interfaces/profile/ProfileUtil.kt @@ -6,7 +6,7 @@ import app.aaps.core.data.pump.defs.PumpType interface ProfileUtil { /** - * Units selected in [app.aaps.core.interfaces.sharedPreferences.SP] + * Units selected in sharedPreferences * * @return GlucoseUnit for UI */ diff --git a/core/interfaces/src/main/kotlin/app/aaps/core/interfaces/protection/PasswordCheck.kt b/core/interfaces/src/main/kotlin/app/aaps/core/interfaces/protection/PasswordCheck.kt index c52288a9ab4..a52a81de711 100644 --- a/core/interfaces/src/main/kotlin/app/aaps/core/interfaces/protection/PasswordCheck.kt +++ b/core/interfaces/src/main/kotlin/app/aaps/core/interfaces/protection/PasswordCheck.kt @@ -2,6 +2,7 @@ package app.aaps.core.interfaces.protection import android.content.Context import androidx.annotation.StringRes +import app.aaps.core.keys.interfaces.StringPreferenceKey interface PasswordCheck { @@ -11,7 +12,7 @@ interface PasswordCheck { fun queryPassword( context: Context, @StringRes labelId: Int, - preference: String, + preference: StringPreferenceKey, ok: ((String) -> Unit)?, cancel: (() -> Unit)? = null, fail: (() -> Unit)? = null, @@ -21,7 +22,7 @@ interface PasswordCheck { fun setPassword( context: Context, @StringRes labelId: Int, - preference: String, + preference: StringPreferenceKey, ok: ((String) -> Unit)? = null, cancel: (() -> Unit)? = null, clear: (() -> Unit)? = null, @@ -34,7 +35,7 @@ interface PasswordCheck { * since this query does NOT check validity of password. */ fun queryAnyPassword( - context: Context, @StringRes labelId: Int, preference: String, @StringRes passwordExplanation: Int?, + context: Context, @StringRes labelId: Int, preference: StringPreferenceKey, @StringRes passwordExplanation: Int?, @StringRes passwordWarning: Int?, ok: ((String) -> Unit)?, cancel: (() -> Unit)? = null ) diff --git a/core/interfaces/src/main/kotlin/app/aaps/core/interfaces/pump/PumpPluginBase.kt b/core/interfaces/src/main/kotlin/app/aaps/core/interfaces/pump/PumpPluginBase.kt index 96c315434e0..8d276ce6122 100644 --- a/core/interfaces/src/main/kotlin/app/aaps/core/interfaces/pump/PumpPluginBase.kt +++ b/core/interfaces/src/main/kotlin/app/aaps/core/interfaces/pump/PumpPluginBase.kt @@ -5,17 +5,24 @@ import android.os.HandlerThread import app.aaps.core.data.plugin.PluginType import app.aaps.core.interfaces.R import app.aaps.core.interfaces.logging.AAPSLogger -import app.aaps.core.interfaces.plugin.PluginBase +import app.aaps.core.interfaces.plugin.PluginBaseWithPreferences import app.aaps.core.interfaces.plugin.PluginDescription import app.aaps.core.interfaces.queue.CommandQueue import app.aaps.core.interfaces.resources.ResourceHelper +import app.aaps.core.keys.interfaces.NonPreferenceKey +import app.aaps.core.keys.interfaces.Preferences +/** + * Add command queue to [PluginBaseWithPreferences] + */ abstract class PumpPluginBase( pluginDescription: PluginDescription, + ownPreferences: List> = emptyList(), aapsLogger: AAPSLogger, rh: ResourceHelper, + preferences: Preferences, val commandQueue: CommandQueue -) : PluginBase(pluginDescription, aapsLogger, rh) { +) : PluginBaseWithPreferences(pluginDescription, ownPreferences, aapsLogger, rh, preferences) { var handler: Handler? = null diff --git a/core/interfaces/src/main/kotlin/app/aaps/core/interfaces/sharedPreferences/SP.kt b/core/interfaces/src/main/kotlin/app/aaps/core/interfaces/sharedPreferences/SP.kt index 2e008c77870..f7a153ae1e9 100644 --- a/core/interfaces/src/main/kotlin/app/aaps/core/interfaces/sharedPreferences/SP.kt +++ b/core/interfaces/src/main/kotlin/app/aaps/core/interfaces/sharedPreferences/SP.kt @@ -67,7 +67,7 @@ interface SP { fun getInt(key: String, defaultValue: Int): Int fun getLong(@StringRes resourceID: Int, defaultValue: Long): Long fun getLong(key: String, defaultValue: Long): Long - fun incLong(@StringRes resourceID: Int) + fun incLong(key: String) fun putBoolean(key: String, value: Boolean) fun putBoolean(@StringRes resourceID: Int, value: Boolean) fun putDouble(key: String, value: Double) @@ -76,7 +76,7 @@ interface SP { fun putLong(@StringRes resourceID: Int, value: Long) fun putInt(key: String, value: Int) fun putInt(@StringRes resourceID: Int, value: Int) - fun incInt(@StringRes resourceID: Int) + fun incInt(key: String) fun putString(@StringRes resourceID: Int, value: String) fun putString(key: String, value: String) } \ No newline at end of file diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/BooleanComposedKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/BooleanComposedKey.kt new file mode 100644 index 00000000000..150983cffb2 --- /dev/null +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/BooleanComposedKey.kt @@ -0,0 +1,14 @@ +package app.aaps.core.keys + +import app.aaps.core.keys.interfaces.BooleanComposedNonPreferenceKey + +enum class BooleanComposedKey( + override val key: String, + override val format: String, + override val defaultValue: Boolean, + override val exportable: Boolean = true +) : BooleanComposedNonPreferenceKey { + + Log("log_", "%s", false), + WidgetUseBlack("appwidget_use_black_", "%d", false), +} \ No newline at end of file diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/BooleanKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/BooleanKey.kt index 045c59a4c07..a038ce66539 100644 --- a/core/keys/src/main/kotlin/app/aaps/core/keys/BooleanKey.kt +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/BooleanKey.kt @@ -1,5 +1,7 @@ package app.aaps.core.keys +import app.aaps.core.keys.interfaces.BooleanPreferenceKey + enum class BooleanKey( override val key: String, override val defaultValue: Boolean, @@ -11,7 +13,8 @@ enum class BooleanKey( override val dependency: BooleanPreferenceKey? = null, override val negativeDependency: BooleanPreferenceKey? = null, override val hideParentScreenIfHidden: Boolean = false, - override val engineeringModeOnly: Boolean = false + override val engineeringModeOnly: Boolean = false, + override val exportable: Boolean = true ) : BooleanPreferenceKey { GeneralSimpleMode("simple_mode", true), @@ -74,7 +77,6 @@ enum class BooleanKey( SmsReportPumpUnreachable("smscommunicator_report_pump_unreachable", true), VirtualPumpStatusUpload("virtualpump_uploadstatus", false, showInNsClientMode = false), - GarminLocalHttpServer("communication_http", false, defaultedBySM = true, hideParentScreenIfHidden = true), NsClientUploadData("ns_upload", true, showInNsClientMode = false, hideParentScreenIfHidden = true), NsClientAcceptCgmData("ns_receive_cgm", false, showInNsClientMode = false, hideParentScreenIfHidden = true), NsClientAcceptProfileStore("ns_receive_profile_store", true, showInNsClientMode = false, hideParentScreenIfHidden = true), @@ -112,4 +114,8 @@ enum class BooleanKey( WearCustomWatchfaceAuthorization(key = "wear_custom_watchface_autorization", defaultValue = false), WearNotifyOnSmb(key = "wear_notifySMB", defaultValue = true), WearBroadcastData(key = "wear_broadcast_data", defaultValue = false), + WizardCalculationVisible("wizard_calculation_visible", defaultValue = false), + WizardCorrectionPercent("wizard_correction_percent", defaultValue = false), + WizardIncludeCob("wizard_include_cob", defaultValue = false), + WizardIncludeTrend("wizard_include_trend_bg", defaultValue = false), } \ No newline at end of file diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/BooleanNonKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/BooleanNonKey.kt new file mode 100644 index 00000000000..22061a5e5ac --- /dev/null +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/BooleanNonKey.kt @@ -0,0 +1,23 @@ +package app.aaps.core.keys + +import app.aaps.core.keys.interfaces.BooleanNonPreferenceKey + +@Suppress("SpellCheckingInspection") +enum class BooleanNonKey( + override val key: String, + override val defaultValue: Boolean, + override val exportable: Boolean = true +) : BooleanNonPreferenceKey { + + SetupWizardIUnderstand("I_understand", false), + ObjectivesLoopUsed("ObjectivesLoopUsed", false), + ObjectivesActionsUsed("ObjectivesActionsUsed", false), + ObjectivesScaleUsed("ObjectivesScaleUsed", false), + ObjectivesPumpStatusIsAvailableInNS("ObjectivespumpStatusIsAvailableInNS", false), + ObjectivesBgIsAvailableInNs("ObjectivesbgIsAvailableInNS", false), + ObjectivesProfileSwitchUsed("ObjectivesProfileSwitchUsed", false), + ObjectivesDisconnectUsed("ObjectivesDisconnectUsed", false), + ObjectivesReconnectUsed("ObjectivesReconnectUsed", false), + ObjectivesTempTargetUsed("ObjectivesTempTargetUsed", false), + AutosensUsedOnMainPhone("used_autosens_on_main_phone", false), +} \ No newline at end of file diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/DoubleKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/DoubleKey.kt index d5fba943142..f5602eb1bdb 100644 --- a/core/keys/src/main/kotlin/app/aaps/core/keys/DoubleKey.kt +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/DoubleKey.kt @@ -1,5 +1,8 @@ package app.aaps.core.keys +import app.aaps.core.keys.interfaces.BooleanPreferenceKey +import app.aaps.core.keys.interfaces.DoublePreferenceKey + enum class DoubleKey( override val key: String, override val defaultValue: Double, @@ -12,7 +15,8 @@ enum class DoubleKey( override val showInPumpControlMode: Boolean = true, override val dependency: BooleanPreferenceKey? = null, override val negativeDependency: BooleanPreferenceKey? = null, - override val hideParentScreenIfHidden: Boolean = false + override val hideParentScreenIfHidden: Boolean = false, + override val exportable: Boolean = true ) : DoublePreferenceKey { OverviewInsulinButtonIncrement1("insulin_button_increment_1", 0.5, -5.0, 5.0, defaultedBySM = true, dependency = BooleanKey.OverviewShowInsulinButton), diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/IntComposedKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/IntComposedKey.kt new file mode 100644 index 00000000000..663662b8e2f --- /dev/null +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/IntComposedKey.kt @@ -0,0 +1,13 @@ +package app.aaps.core.keys + +import app.aaps.core.keys.interfaces.IntComposedNonPreferenceKey + +enum class IntComposedKey( + override val key: String, + override val format: String, + override val defaultValue: Int, + override val exportable: Boolean = true +) : IntComposedNonPreferenceKey { + + WidgetOpacity("appwidget_", "%d", 25) +} \ No newline at end of file diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/IntKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/IntKey.kt index 35995f39710..293242a2a27 100644 --- a/core/keys/src/main/kotlin/app/aaps/core/keys/IntKey.kt +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/IntKey.kt @@ -1,5 +1,8 @@ package app.aaps.core.keys +import app.aaps.core.keys.interfaces.BooleanPreferenceKey +import app.aaps.core.keys.interfaces.IntPreferenceKey + enum class IntKey( override val key: String, override val defaultValue: Int, @@ -13,7 +16,8 @@ enum class IntKey( override val dependency: BooleanPreferenceKey? = null, override val negativeDependency: BooleanPreferenceKey? = null, override val hideParentScreenIfHidden: Boolean = false, - override val engineeringModeOnly: Boolean = false + override val engineeringModeOnly: Boolean = false, + override val exportable: Boolean = true ) : IntPreferenceKey { OverviewCarbsButtonIncrement1("carbs_button_increment_1", 5, -50, 50, defaultedBySM = true), @@ -64,7 +68,6 @@ enum class IntKey( SmsRemoteBolusDistance("smscommunicator_remotebolusmindistance", 15, 3, 60), BgSourceRandomInterval("randombg_interval_min", 5, 1, 15, defaultedBySM = true), - GarminLocalHttpPort("communication_http_port", 28891, 1001, 65535, defaultedBySM = true, hideParentScreenIfHidden = true), NsClientAlarmStaleData("ns_alarm_stale_data_value", 16, 15, 120), NsClientUrgentAlarmStaleData("ns_alarm_urgent_stale_data_value", 31, 30, 180), } \ No newline at end of file diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/IntNonKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/IntNonKey.kt new file mode 100644 index 00000000000..cb9abee091d --- /dev/null +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/IntNonKey.kt @@ -0,0 +1,14 @@ +package app.aaps.core.keys + +import app.aaps.core.keys.interfaces.IntNonPreferenceKey + +@Suppress("SpellCheckingInspection") +enum class IntNonKey( + override val key: String, + override val defaultValue: Int, + override val exportable: Boolean = true +) : IntNonPreferenceKey { + + ObjectivesManualEnacts("ObjectivesmanualEnacts", 0), + RangeToDisplay("rangetodisplay", 6) +} \ No newline at end of file diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/IntentKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/IntentKey.kt index 7417c1e8854..2eb3888068b 100644 --- a/core/keys/src/main/kotlin/app/aaps/core/keys/IntentKey.kt +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/IntentKey.kt @@ -1,5 +1,8 @@ package app.aaps.core.keys +import app.aaps.core.keys.interfaces.BooleanPreferenceKey +import app.aaps.core.keys.interfaces.IntentPreferenceKey + enum class IntentKey( override val key: String, override val defaultedBySM: Boolean = false, @@ -8,7 +11,8 @@ enum class IntentKey( override val showInPumpControlMode: Boolean = true, override val dependency: BooleanPreferenceKey? = null, override val negativeDependency: BooleanPreferenceKey? = null, - override val hideParentScreenIfHidden: Boolean = false + override val hideParentScreenIfHidden: Boolean = false, + override val exportable: Boolean = false ) : IntentPreferenceKey { ApsLinkToDocs(key = "link_to_docs"), diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/LongComposedKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/LongComposedKey.kt new file mode 100644 index 00000000000..1aa84faa9b5 --- /dev/null +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/LongComposedKey.kt @@ -0,0 +1,18 @@ +package app.aaps.core.keys + +import app.aaps.core.keys.interfaces.LongComposedNonPreferenceKey + +enum class LongComposedKey( + override val key: String, + override val format: String, + override val defaultValue: Long, + override val exportable: Boolean = true +) : LongComposedNonPreferenceKey { + + NotificationSnoozedTo("snoozedTo", "%s", 0L), + ActivityMonitorStart("Monitor_start_", "%s", 0L), + ActivityMonitorResumed("Monitor_resumed_", "%s", 0L), + ActivityMonitorTotal("Monitor_total_", "%s", 0L), + ; + +} \ No newline at end of file diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/LongNonKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/LongNonKey.kt new file mode 100644 index 00000000000..ea0c09042bc --- /dev/null +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/LongNonKey.kt @@ -0,0 +1,16 @@ +package app.aaps.core.keys + +import app.aaps.core.keys.interfaces.LongNonPreferenceKey + +enum class LongNonKey( + override val key: String, + override val defaultValue: Long, + override val exportable: Boolean = true +) : LongNonPreferenceKey { + + LocalProfileLastChange("local_profile_last_change", 0L), + BtWatchdogLastBark("bt_watchdog_last", 0L), + ActivePumpChangeTimestamp("active_pump_change_timestamp", 0L), + LastCleanupRun("last_cleanup_run", 0L), +} + diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/Preferences.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/Preferences.kt deleted file mode 100644 index 9a05a1c0f31..00000000000 --- a/core/keys/src/main/kotlin/app/aaps/core/keys/Preferences.kt +++ /dev/null @@ -1,265 +0,0 @@ -package app.aaps.core.keys - -interface Preferences { - - /** - * Are we in currently in SimpleMode ? - */ - val simpleMode: Boolean - - /** - * Are we in currently in APS build ? - */ - val apsMode: Boolean - - /** - * Are we in currently in NSClient build ? - */ - val nsclientMode: Boolean - - /** - * Are we in currently in PumpControl build ? - */ - val pumpControlMode: Boolean - - /** - * Get [Boolean] value from [android.content.SharedPreferences] - * In SimpleMode return default value - * In FullMode return value from [android.content.SharedPreferences] - * - * @param key [BooleanPreferenceKey] enum - * @return value - */ - fun get(key: BooleanPreferenceKey): Boolean - - /** - * Get [Boolean] value from [android.content.SharedPreferences] or null if doesn't exist - * - * @param key [BooleanPreferenceKey] enum - * @return value or null - */ - fun getIfExists(key: BooleanPreferenceKey): Boolean? - - /** - * Update [Boolean] value in [android.content.SharedPreferences] - * - * @param key [BooleanPreferenceKey] enum - * @param value value - */ - fun put(key: BooleanPreferenceKey, value: Boolean) - - /** - * Get [String] value from [android.content.SharedPreferences] - * - * @param key [StringNonPreferenceKey] enum - * @return value - */ - fun get(key: StringNonPreferenceKey): String - - /** - * Get [String] value from [android.content.SharedPreferences] or null if doesn't exist - * - * @param key [StringNonPreferenceKey] enum - * @return value or null - */ - fun getIfExists(key: StringNonPreferenceKey): String? - - /** - * Update [String] value in [android.content.SharedPreferences] - * - * @param key [StringNonPreferenceKey] enum - * @param value value - */ - fun put(key: StringNonPreferenceKey, value: String) - - /** - * Get [String] value from [android.content.SharedPreferences] - * In SimpleMode return default value - * In FullMode return value from [android.content.SharedPreferences] - * - * @param key [StringPreferenceKey] enum - * @return value - */ - fun get(key: StringPreferenceKey): String - - /** - * Get [String] value from [android.content.SharedPreferences] - * In SimpleMode return default value - * In FullMode return value from [android.content.SharedPreferences] - * - * @param key [String2PreferenceKey] enum - * @param appendix appendix to compose final key as key + delimiter + appendix - * @return value - */ - fun get(key: String2PreferenceKey, appendix: String): String - - /** - * Get [String] value from [android.content.SharedPreferences] or null if doesn't exist - * - * @param key [String2PreferenceKey] enum - * @param appendix appendix to compose final key as key + delimiter + appendix - * @return value or null - */ - fun getIfExists(key: String2PreferenceKey, appendix: String): String? - - /** - * Update [String] value in [android.content.SharedPreferences] - * - * @param key [String2PreferenceKey] enum - * @param appendix appendix to compose final key as key + delimiter + appendix - * @param value value - */ - fun put(key: String2PreferenceKey, appendix: String, value: String) - - /** - * Get [Double] value from [android.content.SharedPreferences] - * In SimpleMode return default value - * In FullMode return value from [android.content.SharedPreferences] - * - * @param key [DoublePreferenceKey] enum - * @return value - */ - fun get(key: DoublePreferenceKey): Double - - /** - * Get [Double] value from [android.content.SharedPreferences] or null if doesn't exist - * - * @param key [DoublePreferenceKey] enum - * @return value or null - */ - fun getIfExists(key: DoublePreferenceKey): Double? - - /** - * Update [Double] value in [android.content.SharedPreferences] - * - * @param key [DoublePreferenceKey] enum - * @param value value - */ - fun put(key: DoublePreferenceKey, value: Double) - - /** - * Get [Double] value from [android.content.SharedPreferences] converted to current units - * In SimpleMode return default value - * In FullMode return value from [android.content.SharedPreferences] - * - * @param key [UnitDoublePreferenceKey] enum - * @return value - */ - fun get(key: UnitDoublePreferenceKey): Double - - /** - * Get [Double] value from [android.content.SharedPreferences] or null if doesn't exist - * - * @param key [UnitDoublePreferenceKey] enum - * @return value or null - */ - fun getIfExists(key: UnitDoublePreferenceKey): Double? - - /** - * Update [Double] value in [android.content.SharedPreferences] - * - * @param key [UnitDoublePreferenceKey] enum - * @param value value - */ - fun put(key: UnitDoublePreferenceKey, value: Double) - - /** - * Get [Int] value from [android.content.SharedPreferences] - * In SimpleMode return default value - * In FullMode return value from [android.content.SharedPreferences] - * - * @param key [IntPreferenceKey] enum - * @return value - */ - fun get(key: IntPreferenceKey): Int - - /** - * Get [Int] value from [android.content.SharedPreferences] or null if doesn't exist - * - * @param key [IntPreferenceKey] enum - * @return value or null - */ - fun getIfExists(key: IntPreferenceKey): Int? - - /** - * Update [Int] value in [android.content.SharedPreferences] - * - * @param key [IntPreferenceKey] enum - * @param value value - */ - fun put(key: IntPreferenceKey, value: Int) - - /** - * Get [Long] value from [android.content.SharedPreferences] - * In SimpleMode return default value - * In FullMode return value from [android.content.SharedPreferences] - * - * @param key [LongPreferenceKey] enum - * @return value - */ - fun get(key: LongPreferenceKey): Long - - /** - * Get [Long] value from [android.content.SharedPreferences] or null if doesn't exist - * - * @param key [LongPreferenceKey] enum - * @return value or null - */ - fun getIfExists(key: LongPreferenceKey): Long? - - /** - * Update [Long] value in [android.content.SharedPreferences] - * - * @param key [LongPreferenceKey] enum - * @param value value - */ - fun put(key: LongPreferenceKey, value: Long) - - /** - * Remove value from [android.content.SharedPreferences] - * - * @param key [PreferenceKey] enum - */ - fun remove(key: NonPreferenceKey) - - /** - * Remove value from [android.content.SharedPreferences] - * - * @param key [PreferenceKey] enum - * @param appendix appendix to compose final key as key + delimiter + appendix - */ - fun remove(key: String2PreferenceKey, appendix: String) - - /** - * @param key string representation of key - * @return true if key is unit dependent - */ - fun isUnitDependent(key: String): Boolean - - /** - * Find [NonPreferenceKey] definition - * @param key string representation of key - * @return [NonPreferenceKey] - */ - fun get(key: String): NonPreferenceKey - - /** - * Find [NonPreferenceKey] definition - * @param key string representation of key - * @return [NonPreferenceKey] or null - */ - fun getIfExists(key: String): NonPreferenceKey? - - /** - * Find all [PreferenceKey] which have `dependency` or `negativeDependency` - * @param key string representation of key - * @return list of [PreferenceKey] - */ - fun getDependingOn(key: String): List - - /** - * Make new class available to Preference system - * Called from PluginBase::init - */ - fun registerPreferences(clazz: Class) -} \ No newline at end of file diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/String2PreferenceKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/String2PreferenceKey.kt deleted file mode 100644 index 4b55e7d13ec..00000000000 --- a/core/keys/src/main/kotlin/app/aaps/core/keys/String2PreferenceKey.kt +++ /dev/null @@ -1,18 +0,0 @@ -package app.aaps.core.keys - -/** - * Preference key with dynamic appendix - */ -interface String2PreferenceKey : PreferenceKey { - - /** - * Default value if not changed from preferences - */ - val defaultValue: String - - /** - * Delimiter - * Final key is composed as key + delimiter + dynamic_part - */ - val delimiter: String -} \ No newline at end of file diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/StringKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/StringKey.kt index 5eb5e2a9474..b7a483d28f9 100644 --- a/core/keys/src/main/kotlin/app/aaps/core/keys/StringKey.kt +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/StringKey.kt @@ -1,5 +1,8 @@ package app.aaps.core.keys +import app.aaps.core.keys.interfaces.BooleanPreferenceKey +import app.aaps.core.keys.interfaces.StringPreferenceKey + enum class StringKey( override val key: String, override val defaultValue: String, @@ -11,7 +14,8 @@ enum class StringKey( override val negativeDependency: BooleanPreferenceKey? = null, override val hideParentScreenIfHidden: Boolean = false, override val isPassword: Boolean = false, - override val isPin: Boolean = false + override val isPin: Boolean = false, + override val exportable: Boolean = true ) : StringPreferenceKey { GeneralUnits("units", "mg/dl"), @@ -40,7 +44,6 @@ enum class StringKey( SmsAllowedNumbers("smscommunicator_allowednumbers", ""), SmsOtpPassword("smscommunicator_otp_password", "", dependency = BooleanKey.SmsAllowRemoteCommands, isPassword = true), - SmsOtpSecret("smscommunicator_otp_secret", ""), // Move to StringNonKey VirtualPumpType("virtualpump_type", "Generic AAPS"), @@ -51,5 +54,7 @@ enum class StringKey( TidepoolUsername("tidepool_username", ""), TidepoolPassword("tidepool_password", "", isPassword = true), TidepoolTestLogin(key = "tidepool_test_login", ""), - GarminRequestKey(key = "garmin_aaps_key", defaultValue = ""), + + PumpCommonBolusStorage("pump_sync_storage_bolus", ""), + PumpCommonTbrStorage("pump_sync_storage_tbr", ""), } \ No newline at end of file diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/StringNonKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/StringNonKey.kt new file mode 100644 index 00000000000..938b34c5469 --- /dev/null +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/StringNonKey.kt @@ -0,0 +1,20 @@ +package app.aaps.core.keys + +import app.aaps.core.keys.interfaces.StringNonPreferenceKey + +enum class StringNonKey( + override val key: String, + override val defaultValue: String, + override val exportable: Boolean = true +) : StringNonPreferenceKey { + + QuickWizard(key = "QuickWizard", defaultValue = "[]"), + WearCwfWatchfaceName(key = "wear_cwf_watchface_name", defaultValue = ""), + WearCwfAuthorVersion(key = "wear_cwf_author_version", defaultValue = ""), + WearCwfFileName(key = "wear_cwf_filename", defaultValue = ""), + BolusInfoStorage(key = "key_bolus_storage", defaultValue = ""), + ActivePumpType(key = "active_pump_type", defaultValue = ""), + ActivePumpSerialNumber(key = "active_pump_serial_number", defaultValue = ""), + SmsOtpSecret("smscommunicator_otp_secret", defaultValue = ""), + TotalBaseBasal("TBB", defaultValue = "10.00") +} diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/UnitDoubleKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/UnitDoubleKey.kt index 243195a5a5a..4f67f00c237 100644 --- a/core/keys/src/main/kotlin/app/aaps/core/keys/UnitDoubleKey.kt +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/UnitDoubleKey.kt @@ -1,5 +1,8 @@ package app.aaps.core.keys +import app.aaps.core.keys.interfaces.BooleanPreferenceKey +import app.aaps.core.keys.interfaces.UnitDoublePreferenceKey + enum class UnitDoubleKey( override val key: String, override val defaultValue: Double, @@ -11,7 +14,8 @@ enum class UnitDoubleKey( override val showInPumpControlMode: Boolean = true, override val dependency: BooleanPreferenceKey? = null, override val negativeDependency: BooleanPreferenceKey? = null, - override val hideParentScreenIfHidden: Boolean = false + override val hideParentScreenIfHidden: Boolean = false, + override val exportable: Boolean = true ) : UnitDoublePreferenceKey { OverviewEatingSoonTarget("eatingsoon_target", 90.0, 72, 160, defaultedBySM = true), diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/BooleanComposedNonPreferenceKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/BooleanComposedNonPreferenceKey.kt new file mode 100644 index 00000000000..4e01472e758 --- /dev/null +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/BooleanComposedNonPreferenceKey.kt @@ -0,0 +1,33 @@ +package app.aaps.core.keys.interfaces + +import java.util.Locale + +/** + * Preference key where key is a format string see [String::format] + * + * Final key is composed as key + String.format(Locale.ENGLISH, format, *arguments) + */ +interface BooleanComposedNonPreferenceKey : NonPreferenceKey, ComposedKey { + + /** + * Key is used as prefix for recognizing the preference + * + * Final key is composed as key + String.format(Locale.ENGLISH, format, *arguments) + */ + override val key: String + + /** + * String used to format vararg + */ + override val format: String + + /** + * Default value + */ + val defaultValue: Boolean + + /** + * Compose final key from arguments + */ + fun composeKey(vararg arguments: Any): String = String.format(Locale.ENGLISH, key + format, *arguments) +} \ No newline at end of file diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/BooleanNonPreferenceKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/BooleanNonPreferenceKey.kt new file mode 100644 index 00000000000..75d12dc6516 --- /dev/null +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/BooleanNonPreferenceKey.kt @@ -0,0 +1,9 @@ +package app.aaps.core.keys.interfaces + +interface BooleanNonPreferenceKey : NonPreferenceKey { + + /** + * Default value + */ + val defaultValue: Boolean +} \ No newline at end of file diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/BooleanPreferenceKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/BooleanPreferenceKey.kt similarity index 67% rename from core/keys/src/main/kotlin/app/aaps/core/keys/BooleanPreferenceKey.kt rename to core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/BooleanPreferenceKey.kt index 51cb58e5271..c021f0570cb 100644 --- a/core/keys/src/main/kotlin/app/aaps/core/keys/BooleanPreferenceKey.kt +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/BooleanPreferenceKey.kt @@ -1,11 +1,11 @@ -package app.aaps.core.keys +package app.aaps.core.keys.interfaces -interface BooleanPreferenceKey : PreferenceKey { +interface BooleanPreferenceKey : PreferenceKey, BooleanNonPreferenceKey { /** * Default value if not changed from preferences */ - val defaultValue: Boolean + override val defaultValue: Boolean /** * Default value is calculated instead of `defaultValue` diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/ComposedKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/ComposedKey.kt new file mode 100644 index 00000000000..951011d6b53 --- /dev/null +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/ComposedKey.kt @@ -0,0 +1,16 @@ +package app.aaps.core.keys.interfaces + +interface ComposedKey { + + /** + * Key is used as prefix for recognizing the preference + * + * Final key is composed as key + String.format(Locale.ENGLISH, format, *arguments) + */ + val key: String + + /** + * String used to format vararg + */ + val format: String +} \ No newline at end of file diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/DoubleComposedNonPreferenceKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/DoubleComposedNonPreferenceKey.kt new file mode 100644 index 00000000000..e87705dad1f --- /dev/null +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/DoubleComposedNonPreferenceKey.kt @@ -0,0 +1,33 @@ +package app.aaps.core.keys.interfaces + +import java.util.Locale + +/** + * Preference key where key is a format string see [String::format] + * + * Final key is composed as key + String.format(Locale.ENGLISH, format, *arguments) + */ +interface DoubleComposedNonPreferenceKey : NonPreferenceKey, ComposedKey { + + /** + * Key is used as prefix for recognizing the preference + * + * Final key is composed as key + String.format(Locale.ENGLISH, format, *arguments) + */ + override val key: String + + /** + * String used to format vararg + */ + override val format: String + + /** + * Default value + */ + val defaultValue: Double + + /** + * Compose final key from arguments + */ + fun composeKey(vararg arguments: Any): String = String.format(Locale.ENGLISH, key + format, *arguments) +} \ No newline at end of file diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/DoubleNonPreferenceKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/DoubleNonPreferenceKey.kt new file mode 100644 index 00000000000..a2e6bb72162 --- /dev/null +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/DoubleNonPreferenceKey.kt @@ -0,0 +1,9 @@ +package app.aaps.core.keys.interfaces + +interface DoubleNonPreferenceKey : NonPreferenceKey { + + /** + * Default value + */ + val defaultValue: Double +} \ No newline at end of file diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/DoublePreferenceKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/DoublePreferenceKey.kt similarity index 67% rename from core/keys/src/main/kotlin/app/aaps/core/keys/DoublePreferenceKey.kt rename to core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/DoublePreferenceKey.kt index 7080244a936..aa6a674fb17 100644 --- a/core/keys/src/main/kotlin/app/aaps/core/keys/DoublePreferenceKey.kt +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/DoublePreferenceKey.kt @@ -1,11 +1,11 @@ -package app.aaps.core.keys +package app.aaps.core.keys.interfaces -interface DoublePreferenceKey : PreferenceKey { +interface DoublePreferenceKey : PreferenceKey, DoubleNonPreferenceKey { /** * Default value if not changed from preferences */ - val defaultValue: Double + override val defaultValue: Double /** * Minimal allowed value diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/IntComposedNonPreferenceKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/IntComposedNonPreferenceKey.kt new file mode 100644 index 00000000000..f4f174ae2f5 --- /dev/null +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/IntComposedNonPreferenceKey.kt @@ -0,0 +1,33 @@ +package app.aaps.core.keys.interfaces + +import java.util.Locale + +/** + * Preference key where key is a format string see [String::format] + * + * Final key is composed as key + String.format(Locale.ENGLISH, format, *arguments) + */ +interface IntComposedNonPreferenceKey : NonPreferenceKey, ComposedKey { + + /** + * Key is used as prefix for recognizing the preference + * + * Final key is composed as key + String.format(Locale.ENGLISH, format, *arguments) + */ + override val key: String + + /** + * String used to format vararg + */ + override val format: String + + /** + * Default value + */ + val defaultValue: Int + + /** + * Compose final key from arguments + */ + fun composeKey(vararg arguments: Any): String = String.format(Locale.ENGLISH, key + format, *arguments) +} \ No newline at end of file diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/IntNonPreferenceKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/IntNonPreferenceKey.kt new file mode 100644 index 00000000000..b4dbd4a151a --- /dev/null +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/IntNonPreferenceKey.kt @@ -0,0 +1,9 @@ +package app.aaps.core.keys.interfaces + +interface IntNonPreferenceKey : NonPreferenceKey { + + /** + * Default value + */ + val defaultValue: Int +} \ No newline at end of file diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/IntPreferenceKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/IntPreferenceKey.kt similarity index 75% rename from core/keys/src/main/kotlin/app/aaps/core/keys/IntPreferenceKey.kt rename to core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/IntPreferenceKey.kt index 20ea0efd382..3daf6212b29 100644 --- a/core/keys/src/main/kotlin/app/aaps/core/keys/IntPreferenceKey.kt +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/IntPreferenceKey.kt @@ -1,11 +1,11 @@ -package app.aaps.core.keys +package app.aaps.core.keys.interfaces -interface IntPreferenceKey : PreferenceKey { +interface IntPreferenceKey : PreferenceKey, IntNonPreferenceKey { /** * Default value if not changed from preferences */ - val defaultValue: Int + override val defaultValue: Int /** * Minimal allowed value diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/IntentPreferenceKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/IntentPreferenceKey.kt similarity index 54% rename from core/keys/src/main/kotlin/app/aaps/core/keys/IntentPreferenceKey.kt rename to core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/IntentPreferenceKey.kt index 30411a9eaab..9ee14deb108 100644 --- a/core/keys/src/main/kotlin/app/aaps/core/keys/IntentPreferenceKey.kt +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/IntentPreferenceKey.kt @@ -1,3 +1,3 @@ -package app.aaps.core.keys +package app.aaps.core.keys.interfaces interface IntentPreferenceKey : PreferenceKey \ No newline at end of file diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/LongComposedNonPreferenceKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/LongComposedNonPreferenceKey.kt new file mode 100644 index 00000000000..6e37a207bbb --- /dev/null +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/LongComposedNonPreferenceKey.kt @@ -0,0 +1,33 @@ +package app.aaps.core.keys.interfaces + +import java.util.Locale + +/** + * Preference key where key is a format string see [String::format] + * + * Final key is composed as key + String.format(Locale.ENGLISH, format, *arguments) + */ +interface LongComposedNonPreferenceKey : NonPreferenceKey, ComposedKey { + + /** + * Key is used as prefix for recognizing the preference + * + * Final key is composed as key + String.format(Locale.ENGLISH, format, *arguments) + */ + override val key: String + + /** + * String used to format vararg + */ + override val format: String + + /** + * Default value + */ + val defaultValue: Long + + /** + * Compose final key from arguments + */ + fun composeKey(vararg arguments: Any): String = String.format(Locale.ENGLISH, key + format, *arguments) +} \ No newline at end of file diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/LongNonPreferenceKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/LongNonPreferenceKey.kt new file mode 100644 index 00000000000..b2d75821bbc --- /dev/null +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/LongNonPreferenceKey.kt @@ -0,0 +1,9 @@ +package app.aaps.core.keys.interfaces + +interface LongNonPreferenceKey : NonPreferenceKey { + + /** + * Default value + */ + val defaultValue: Long +} \ No newline at end of file diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/LongPreferenceKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/LongPreferenceKey.kt similarity index 75% rename from core/keys/src/main/kotlin/app/aaps/core/keys/LongPreferenceKey.kt rename to core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/LongPreferenceKey.kt index 3a27641d504..9bfb39c9426 100644 --- a/core/keys/src/main/kotlin/app/aaps/core/keys/LongPreferenceKey.kt +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/LongPreferenceKey.kt @@ -1,11 +1,11 @@ -package app.aaps.core.keys +package app.aaps.core.keys.interfaces -interface LongPreferenceKey : PreferenceKey { +interface LongPreferenceKey : PreferenceKey, LongNonPreferenceKey { /** * Default value if not changed from preferences */ - val defaultValue: Long + override val defaultValue: Long /** * Minimal allowed value diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/NonPreferenceKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/NonPreferenceKey.kt similarity index 64% rename from core/keys/src/main/kotlin/app/aaps/core/keys/NonPreferenceKey.kt rename to core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/NonPreferenceKey.kt index c9d14187c9f..ed4db699d70 100644 --- a/core/keys/src/main/kotlin/app/aaps/core/keys/NonPreferenceKey.kt +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/NonPreferenceKey.kt @@ -1,4 +1,4 @@ -package app.aaps.core.keys +package app.aaps.core.keys.interfaces /** * Defines shared preference encapsulation that works inside a module without preferences UI @@ -9,4 +9,9 @@ interface NonPreferenceKey { * Associated [android.content.SharedPreferences] key */ val key: String + + /** + * If true, this preference is exported + */ + val exportable: Boolean } \ No newline at end of file diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/PreferenceKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/PreferenceKey.kt similarity index 97% rename from core/keys/src/main/kotlin/app/aaps/core/keys/PreferenceKey.kt rename to core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/PreferenceKey.kt index 5b0115d2c08..6d58ee4c355 100644 --- a/core/keys/src/main/kotlin/app/aaps/core/keys/PreferenceKey.kt +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/PreferenceKey.kt @@ -1,4 +1,4 @@ -package app.aaps.core.keys +package app.aaps.core.keys.interfaces /** * Defines shared preference encapsulation diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/Preferences.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/Preferences.kt new file mode 100644 index 00000000000..ef6913f603d --- /dev/null +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/Preferences.kt @@ -0,0 +1,468 @@ +package app.aaps.core.keys.interfaces + +interface Preferences { + + /** + * Are we in currently in SimpleMode ? + */ + val simpleMode: Boolean + + /** + * Are we in currently in APS build ? + */ + val apsMode: Boolean + + /** + * Are we in currently in NSClient build ? + */ + val nsclientMode: Boolean + + /** + * Are we in currently in PumpControl build ? + */ + val pumpControlMode: Boolean + + /* BOOLEAN */ + + /** + * Get [String] value from [android.content.SharedPreferences] + * + * @param key [app.aaps.core.keys.interfaces.BooleanNonPreferenceKey] enum + * @return value + */ + fun get(key: BooleanNonPreferenceKey): Boolean + + /** + * Get [Boolean] value from [android.content.SharedPreferences] or null if doesn't exist + * + * @param key [app.aaps.core.keys.interfaces.BooleanNonPreferenceKey] enum + * @return value or null + */ + fun getIfExists(key: BooleanNonPreferenceKey): Boolean? + + /** + * Update [String] value in [android.content.SharedPreferences] + * + * @param key [app.aaps.core.keys.interfaces.BooleanNonPreferenceKey] enum + * @param value value + */ + fun put(key: BooleanNonPreferenceKey, value: Boolean) + + /** + * Get [Boolean] value from [android.content.SharedPreferences] + * In SimpleMode return default value + * In FullMode return value from [android.content.SharedPreferences] + * + * @param key [app.aaps.core.keys.interfaces.BooleanPreferenceKey] enum + * @return value + */ + fun get(key: BooleanPreferenceKey): Boolean + + /** + * Get [String] value from [android.content.SharedPreferences] + * * + * @param key [app.aaps.core.keys.interfaces.BooleanComposedNonPreferenceKey] enum + * @param arguments arguments to compose final key using String::format + * @return value + */ + fun get(key: BooleanComposedNonPreferenceKey, vararg arguments: Any): Boolean + + /** + * Get [String] value from [android.content.SharedPreferences] + * * + * @param key [app.aaps.core.keys.interfaces.BooleanComposedNonPreferenceKey] enum + * @param arguments arguments to compose final key using String::format + * @param defaultValue alternative default value + * @return value + */ + fun get(key: BooleanComposedNonPreferenceKey, vararg arguments: Any, defaultValue: Boolean): Boolean + + /** + * Get [String] value from [android.content.SharedPreferences] or null if doesn't exist + * + * @param key [app.aaps.core.keys.interfaces.BooleanComposedNonPreferenceKey] enum + * @param arguments arguments to compose final key using String::format + * @return value or null + */ + fun getIfExists(key: BooleanComposedNonPreferenceKey, vararg arguments: Any): Boolean? + + /** + * Update [String] value in [android.content.SharedPreferences] + * + * @param key [app.aaps.core.keys.interfaces.BooleanComposedNonPreferenceKey] enum + * @param arguments arguments to compose final key using String::format + * @param value value + */ + fun put(key: BooleanComposedNonPreferenceKey, vararg arguments: Any, value: Boolean) + + /* STRING */ + + /** + * Get [String] value from [android.content.SharedPreferences] + * + * @param key [StringNonPreferenceKey] enum + * @return value + */ + fun get(key: StringNonPreferenceKey): String + + /** + * Get [String] value from [android.content.SharedPreferences] or null if doesn't exist + * + * @param key [StringNonPreferenceKey] enum + * @return value or null + */ + fun getIfExists(key: StringNonPreferenceKey): String? + + /** + * Update [String] value in [android.content.SharedPreferences] + * + * @param key [StringNonPreferenceKey] enum + * @param value value + */ + fun put(key: StringNonPreferenceKey, value: String) + + /** + * Get [String] value from [android.content.SharedPreferences] + * In SimpleMode return default value + * In FullMode return value from [android.content.SharedPreferences] + * + * @param key [StringPreferenceKey] enum + * @return value + */ + fun get(key: StringPreferenceKey): String + + /** + * Get [String] value from [android.content.SharedPreferences] + * * + * @param key [app.aaps.core.keys.interfaces.StringComposedNonPreferenceKey] enum + * @param arguments arguments to compose final key using String::format + * @return value + */ + fun get(key: StringComposedNonPreferenceKey, vararg arguments: Any): String + + /** + * Get [String] value from [android.content.SharedPreferences] or null if doesn't exist + * + * @param key [app.aaps.core.keys.interfaces.StringComposedNonPreferenceKey] enum + * @param arguments arguments to compose final key using String::format + * @return value or null + */ + fun getIfExists(key: StringComposedNonPreferenceKey, vararg arguments: Any): String? + + /** + * Update [String] value in [android.content.SharedPreferences] + * + * @param key [app.aaps.core.keys.interfaces.StringComposedNonPreferenceKey] enum + * @param arguments arguments to compose final key using String::format + * @param value value + */ + fun put(key: StringComposedNonPreferenceKey, vararg arguments: Any, value: String) + + /** + * Remove value from [android.content.SharedPreferences] + * + * @param key [app.aaps.core.keys.interfaces.PreferenceKey] enum + * @param arguments arguments to compose final key using String::format + */ + fun remove(key: StringComposedNonPreferenceKey, vararg arguments: Any) + + /* DOUBLE */ + + /** + * Get [Double] value from [android.content.SharedPreferences] + * In SimpleMode return default value + * In FullMode return value from [android.content.SharedPreferences] + * + * @param key [app.aaps.core.keys.interfaces.DoubleNonPreferenceKey] enum + * @return value + */ + fun get(key: DoubleNonPreferenceKey): Double + + /** + * Get [Double] value from [android.content.SharedPreferences] + * In SimpleMode return default value + * In FullMode return value from [android.content.SharedPreferences] + * + * @param key [app.aaps.core.keys.interfaces.DoublePreferenceKey] enum + * @return value + */ + fun get(key: DoublePreferenceKey): Double + + /** + * Get [Double] value from [android.content.SharedPreferences] or null if doesn't exist + * + * @param key [app.aaps.core.keys.interfaces.DoublePreferenceKey] enum + * @return value or null + */ + fun getIfExists(key: DoublePreferenceKey): Double? + + /** + * Update [Double] value in [android.content.SharedPreferences] + * + * @param key [app.aaps.core.keys.interfaces.DoubleNonPreferenceKey] enum + * @param value value + */ + fun put(key: DoubleNonPreferenceKey, value: Double) + + /** + * Get [String] value from [android.content.SharedPreferences] + * * + * @param key [app.aaps.core.keys.interfaces.DoubleComposedNonPreferenceKey] enum + * @param arguments arguments to compose final key using String::format + * @return value + */ + fun get(key: DoubleComposedNonPreferenceKey, vararg arguments: Any): Double + + /** + * Get [String] value from [android.content.SharedPreferences] or null if doesn't exist + * + * @param key [app.aaps.core.keys.interfaces.DoubleComposedNonPreferenceKey] enum + * @param arguments arguments to compose final key using String::format + * @return value or null + */ + fun getIfExists(key: DoubleComposedNonPreferenceKey, vararg arguments: Any): Double? + + /** + * Update [String] value in [android.content.SharedPreferences] + * + * @param key [app.aaps.core.keys.interfaces.DoubleComposedNonPreferenceKey] enum + * @param arguments arguments to compose final key using String::format + * @param value value + */ + fun put(key: DoubleComposedNonPreferenceKey, vararg arguments: Any, value: Double) + + /* UNIT DOUBLE */ + + /** + * Get [Double] value from [android.content.SharedPreferences] converted to current units + * In SimpleMode return default value + * In FullMode return value from [android.content.SharedPreferences] + * + * @param key [UnitDoublePreferenceKey] enum + * @return value + */ + fun get(key: UnitDoublePreferenceKey): Double + + /** + * Get [Double] value from [android.content.SharedPreferences] or null if doesn't exist + * + * @param key [UnitDoublePreferenceKey] enum + * @return value or null + */ + fun getIfExists(key: UnitDoublePreferenceKey): Double? + + /** + * Update [Double] value in [android.content.SharedPreferences] + * + * @param key [UnitDoublePreferenceKey] enum + * @param value value + */ + fun put(key: UnitDoublePreferenceKey, value: Double) + + /* INT */ + + /** + * Get [Int] value from [android.content.SharedPreferences] + * In SimpleMode return default value + * In FullMode return value from [android.content.SharedPreferences] + * + * @param key [app.aaps.core.keys.interfaces.IntNonPreferenceKey] enum + * @return value + */ + fun get(key: IntNonPreferenceKey): Int + + /** + * Get [Int] value from [android.content.SharedPreferences] or null if doesn't exist + * + * @param key [app.aaps.core.keys.interfaces.IntNonPreferenceKey] enum + * @return value or null + */ + fun getIfExists(key: IntNonPreferenceKey): Int? + + /** + * Update [Int] value in [android.content.SharedPreferences] + * + * @param key [app.aaps.core.keys.interfaces.IntComposedNonPreferenceKey] enum + * @param arguments arguments to compose final key using String::format + * @param value value + */ + fun put(key: IntComposedNonPreferenceKey, vararg arguments: Any, value: Int) + + /** + * Update [Int] value in [android.content.SharedPreferences] + * + * @param key [app.aaps.core.keys.interfaces.IntNonPreferenceKey] enum + * @param value value + */ + fun put(key: IntNonPreferenceKey, value: Int) + + /** + * Increment [Int] value in [android.content.SharedPreferences] + * + * @param key [app.aaps.core.keys.interfaces.IntNonPreferenceKey] enum + * @param value value + */ + fun inc(key: IntNonPreferenceKey) + + /** + * Get [Int] value from [android.content.SharedPreferences] + * * + * @param key [app.aaps.core.keys.interfaces.IntComposedNonPreferenceKey] enum + * @param arguments arguments to compose final key using String::format + * @return value + */ + fun get(key: IntComposedNonPreferenceKey, vararg arguments: Any): Int + + /** + * Get [Int] value from [android.content.SharedPreferences] + * In SimpleMode return default value + * In FullMode return value from [android.content.SharedPreferences] + * + * @param key [app.aaps.core.keys.interfaces.IntPreferenceKey] enum + * @return value + */ + fun get(key: IntPreferenceKey): Int + + /* LONG */ + + /** + * Get [Long] value from [android.content.SharedPreferences] + * In SimpleMode return default value + * In FullMode return value from [android.content.SharedPreferences] + * + * @param key [app.aaps.core.keys.interfaces.LongNonPreferenceKey] enum + * @return value + */ + fun get(key: LongNonPreferenceKey): Long + + /** + * Get [Long] value from [android.content.SharedPreferences] or null if doesn't exist + * + * @param key [app.aaps.core.keys.interfaces.LongNonPreferenceKey] enum + * @return value or null + */ + fun getIfExists(key: LongNonPreferenceKey): Long? + + /** + * Update [Long] value in [android.content.SharedPreferences] + * + * @param key [app.aaps.core.keys.interfaces.LongNonPreferenceKey] enum + * @param value value + */ + fun put(key: LongNonPreferenceKey, value: Long) + + /** + * Get [Long] value from [android.content.SharedPreferences] + * In SimpleMode return default value + * In FullMode return value from [android.content.SharedPreferences] + * + * @param key [app.aaps.core.keys.interfaces.LongPreferenceKey] enum + * @return value + */ + fun get(key: LongPreferenceKey): Long + + /** + * Increment [Long] value in [android.content.SharedPreferences] + * + * @param key [LongNonPreferenceKey] enum + * @param value value + */ + fun inc(key: LongNonPreferenceKey) + + /** + * Get [Long] value from [android.content.SharedPreferences] + * * + * @param key [app.aaps.core.keys.interfaces.LongComposedNonPreferenceKey] enum + * @param arguments arguments to compose final key using String::format + * @return value + */ + fun get(key: LongComposedNonPreferenceKey, vararg arguments: Any): Long + + /** + * Get [Long] value from [android.content.SharedPreferences] or null if doesn't exist + * + * @param key [app.aaps.core.keys.interfaces.LongComposedNonPreferenceKey] enum + * @param arguments arguments to compose final key using String::format + * @return value or null + */ + fun getIfExists(key: LongComposedNonPreferenceKey, vararg arguments: Any): Long? + + /** + * Update [Long] value in [android.content.SharedPreferences] + * + * @param key [app.aaps.core.keys.interfaces.LongComposedNonPreferenceKey] enum + * @param arguments arguments to compose final key using String::format + * @param value value + */ + fun put(key: LongComposedNonPreferenceKey, vararg arguments: Any, value: Long) + + /** + * Remove value from [android.content.SharedPreferences] + * + * @param key [app.aaps.core.keys.interfaces.LongComposedNonPreferenceKey] enum + * @param arguments arguments to compose final key using String::format + */ + fun remove(key: LongComposedNonPreferenceKey, vararg arguments: Any) + + /* GENERAL */ + + /** + * Remove value from [android.content.SharedPreferences] + * + * @param key [app.aaps.core.keys.interfaces.PreferenceKey] enum + */ + fun remove(key: NonPreferenceKey) + + /** + * @param key string representation of key + * @return true if key is unit dependent + */ + fun isUnitDependent(key: String): Boolean + + /** + * Find [app.aaps.core.keys.interfaces.NonPreferenceKey] definition + * @param key string representation of key + * @return [app.aaps.core.keys.interfaces.NonPreferenceKey] or null for [ComposedKey] + */ + fun get(key: String): NonPreferenceKey? + + /** + * Find [app.aaps.core.keys.interfaces.NonPreferenceKey] definition + * @param key string representation of key + * @return [app.aaps.core.keys.interfaces.NonPreferenceKey] or null + */ + fun getIfExists(key: String): NonPreferenceKey? + + /** + * Find all [app.aaps.core.keys.interfaces.PreferenceKey] which have `dependency` or `negativeDependency` + * @param key string representation of key + * @return list of [app.aaps.core.keys.interfaces.PreferenceKey] + */ + fun getDependingOn(key: String): List + + /** + * Make new class available to Preference system + * Called from PluginBase::init + */ + fun registerPreferences(clazz: Class) + + /** + * List all stored preferences formatters + * Note: only single formatting "%s" parameter is supported + */ + fun allMatchingStrings(key: ComposedKey): List + + /** + * List all stored preferences formatters + * Note: only single formatting "%d" parameter is supported + */ + fun allMatchingInts(key: ComposedKey): List + + /** + * Check if the key string looks like a valid registered key and is set exportable + * ie it does match exactly + * or has a valid registered prefix + * @return true if exportable key + */ + fun isExportableKey(key: String): Boolean +} \ No newline at end of file diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/StringComposedNonPreferenceKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/StringComposedNonPreferenceKey.kt new file mode 100644 index 00000000000..111b7a18213 --- /dev/null +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/StringComposedNonPreferenceKey.kt @@ -0,0 +1,33 @@ +package app.aaps.core.keys.interfaces + +import java.util.Locale + +/** + * Preference key where key is a format string see [String::format] + * + * Final key is composed as key + String.format(Locale.ENGLISH, format, *arguments) + */ +interface StringComposedNonPreferenceKey : NonPreferenceKey, ComposedKey { + + /** + * Key is used as prefix for recognizing the preference + * + * Final key is composed as key + String.format(Locale.ENGLISH, format, *arguments) + */ + override val key: String + + /** + * String used to format vararg + */ + override val format: String + + /** + * Default value + */ + val defaultValue: String + + /** + * Compose final key from arguments + */ + fun composeKey(vararg arguments: Any): String = String.format(Locale.ENGLISH, key + format, *arguments) +} \ No newline at end of file diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/StringNonPreferenceKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/StringNonPreferenceKey.kt similarity index 76% rename from core/keys/src/main/kotlin/app/aaps/core/keys/StringNonPreferenceKey.kt rename to core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/StringNonPreferenceKey.kt index ec743db12b9..d6f98a260c7 100644 --- a/core/keys/src/main/kotlin/app/aaps/core/keys/StringNonPreferenceKey.kt +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/StringNonPreferenceKey.kt @@ -1,4 +1,4 @@ -package app.aaps.core.keys +package app.aaps.core.keys.interfaces interface StringNonPreferenceKey : NonPreferenceKey { diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/StringPreferenceKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/StringPreferenceKey.kt similarity index 85% rename from core/keys/src/main/kotlin/app/aaps/core/keys/StringPreferenceKey.kt rename to core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/StringPreferenceKey.kt index f677e754769..be93de35fce 100644 --- a/core/keys/src/main/kotlin/app/aaps/core/keys/StringPreferenceKey.kt +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/StringPreferenceKey.kt @@ -1,4 +1,4 @@ -package app.aaps.core.keys +package app.aaps.core.keys.interfaces interface StringPreferenceKey : PreferenceKey, StringNonPreferenceKey { diff --git a/core/keys/src/main/kotlin/app/aaps/core/keys/UnitDoublePreferenceKey.kt b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/UnitDoublePreferenceKey.kt similarity index 88% rename from core/keys/src/main/kotlin/app/aaps/core/keys/UnitDoublePreferenceKey.kt rename to core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/UnitDoublePreferenceKey.kt index c035fe97dca..0a7dcfdcadd 100644 --- a/core/keys/src/main/kotlin/app/aaps/core/keys/UnitDoublePreferenceKey.kt +++ b/core/keys/src/main/kotlin/app/aaps/core/keys/interfaces/UnitDoublePreferenceKey.kt @@ -1,4 +1,4 @@ -package app.aaps.core.keys +package app.aaps.core.keys.interfaces interface UnitDoublePreferenceKey : PreferenceKey { diff --git a/core/objects/src/main/kotlin/app/aaps/core/objects/aps/DetermineBasalResult.kt b/core/objects/src/main/kotlin/app/aaps/core/objects/aps/DetermineBasalResult.kt index ab47edb33d6..3ec6e3c3446 100644 --- a/core/objects/src/main/kotlin/app/aaps/core/objects/aps/DetermineBasalResult.kt +++ b/core/objects/src/main/kotlin/app/aaps/core/objects/aps/DetermineBasalResult.kt @@ -26,7 +26,7 @@ import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.DecimalFormatter import app.aaps.core.keys.IntKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.extensions.convertedToAbsolute import app.aaps.core.objects.extensions.convertedToPercent import app.aaps.core.ui.R diff --git a/core/objects/src/main/kotlin/app/aaps/core/objects/extensions/JSONObjectExt.kt b/core/objects/src/main/kotlin/app/aaps/core/objects/extensions/JSONObjectExt.kt index 7fe71c1cdfd..cfd2302d4d5 100644 --- a/core/objects/src/main/kotlin/app/aaps/core/objects/extensions/JSONObjectExt.kt +++ b/core/objects/src/main/kotlin/app/aaps/core/objects/extensions/JSONObjectExt.kt @@ -1,15 +1,12 @@ package app.aaps.core.objects.extensions -import androidx.annotation.StringRes -import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.sharedPreferences.SP -import app.aaps.core.keys.BooleanPreferenceKey -import app.aaps.core.keys.DoublePreferenceKey -import app.aaps.core.keys.IntPreferenceKey -import app.aaps.core.keys.LongPreferenceKey -import app.aaps.core.keys.Preferences -import app.aaps.core.keys.StringPreferenceKey -import app.aaps.core.keys.UnitDoublePreferenceKey +import app.aaps.core.keys.interfaces.BooleanNonPreferenceKey +import app.aaps.core.keys.interfaces.DoublePreferenceKey +import app.aaps.core.keys.interfaces.IntPreferenceKey +import app.aaps.core.keys.interfaces.LongPreferenceKey +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.core.keys.interfaces.StringNonPreferenceKey +import app.aaps.core.keys.interfaces.UnitDoublePreferenceKey import org.json.JSONObject fun JSONObject.put(key: IntPreferenceKey, preferences: Preferences): JSONObject = @@ -24,13 +21,10 @@ fun JSONObject.put(key: DoublePreferenceKey, preferences: Preferences): JSONObje fun JSONObject.put(key: UnitDoublePreferenceKey, preferences: Preferences): JSONObject = this.also { it.put(key.key, preferences.get(key)) } -fun JSONObject.putString(@StringRes key: Int, sp: SP, rh: ResourceHelper): JSONObject = - if (sp.contains(key)) put(rh.gs(key), sp.getString(key, "")) else this - -fun JSONObject.put(key: StringPreferenceKey, preferences: Preferences): JSONObject = +fun JSONObject.put(key: StringNonPreferenceKey, preferences: Preferences): JSONObject = this.also { it.put(key.key, preferences.get(key)) } -fun JSONObject.put(key: BooleanPreferenceKey, preferences: Preferences): JSONObject = +fun JSONObject.put(key: BooleanNonPreferenceKey, preferences: Preferences): JSONObject = this.also { it.put(key.key, preferences.get(key)) } fun JSONObject.store(key: IntPreferenceKey, preferences: Preferences): JSONObject { @@ -53,22 +47,12 @@ fun JSONObject.store(key: UnitDoublePreferenceKey, preferences: Preferences): JS return this } -fun JSONObject.storeString(@StringRes key: Int, sp: SP, rh: ResourceHelper): JSONObject { - if (has(rh.gs(key))) sp.putString(key, getString(rh.gs(key)).toString()) - return this -} - -fun JSONObject.store(key: StringPreferenceKey, preferences: Preferences): JSONObject { +fun JSONObject.store(key: StringNonPreferenceKey, preferences: Preferences): JSONObject { if (has(key.key)) preferences.put(key, getString(key.key)) return this } -fun JSONObject.storeBoolean(@StringRes key: Int, sp: SP, rh: ResourceHelper): JSONObject { - if (has(rh.gs(key))) sp.putBoolean(key, getBoolean(rh.gs(key))) - return this -} - -fun JSONObject.store(key: BooleanPreferenceKey, preferences: Preferences): JSONObject { +fun JSONObject.store(key: BooleanNonPreferenceKey, preferences: Preferences): JSONObject { if (has(key.key)) preferences.put(key, getBoolean(key.key)) return this } diff --git a/core/objects/src/main/kotlin/app/aaps/core/objects/wizard/BolusWizard.kt b/core/objects/src/main/kotlin/app/aaps/core/objects/wizard/BolusWizard.kt index c9845038568..59cdce06bfa 100644 --- a/core/objects/src/main/kotlin/app/aaps/core/objects/wizard/BolusWizard.kt +++ b/core/objects/src/main/kotlin/app/aaps/core/objects/wizard/BolusWizard.kt @@ -36,13 +36,12 @@ import app.aaps.core.interfaces.queue.CommandQueue import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventRefreshOverview -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.DecimalFormatter import app.aaps.core.interfaces.utils.Round import app.aaps.core.keys.BooleanKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.constraints.ConstraintObject import app.aaps.core.objects.extensions.formatColor import app.aaps.core.objects.extensions.highValueToUnitsToString @@ -66,7 +65,6 @@ class BolusWizard @Inject constructor( @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var rh: ResourceHelper @Inject lateinit var rxBus: RxBus - @Inject lateinit var sp: SP @Inject lateinit var preferences: Preferences @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileUtil: ProfileUtil diff --git a/core/objects/src/main/kotlin/app/aaps/core/objects/wizard/QuickWizard.kt b/core/objects/src/main/kotlin/app/aaps/core/objects/wizard/QuickWizard.kt index a57b650cb86..fa02406519c 100644 --- a/core/objects/src/main/kotlin/app/aaps/core/objects/wizard/QuickWizard.kt +++ b/core/objects/src/main/kotlin/app/aaps/core/objects/wizard/QuickWizard.kt @@ -1,6 +1,7 @@ package app.aaps.core.objects.wizard -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.StringNonKey +import app.aaps.core.keys.interfaces.Preferences import dagger.android.HasAndroidInjector import org.json.JSONArray import org.json.JSONObject @@ -10,14 +11,14 @@ import javax.inject.Singleton @Singleton class QuickWizard @Inject constructor( - private val sp: SP, + private val preferences: Preferences, private val injector: HasAndroidInjector ) { private var storage = JSONArray() init { - setData(JSONArray(sp.getString(app.aaps.core.utils.R.string.key_quickwizard, "[]"))) + setData(JSONArray(preferences.get(StringNonKey.QuickWizard))) setGuidsForOldEntries() } @@ -45,7 +46,7 @@ class QuickWizard @Inject constructor( } fun save() { - sp.putString(app.aaps.core.utils.R.string.key_quickwizard, storage.toString()) + preferences.put(StringNonKey.QuickWizard, storage.toString()) } fun size(): Int = storage.length() diff --git a/core/objects/src/main/kotlin/app/aaps/core/objects/wizard/QuickWizardEntry.kt b/core/objects/src/main/kotlin/app/aaps/core/objects/wizard/QuickWizardEntry.kt index 55333a00741..f23cd8764c4 100644 --- a/core/objects/src/main/kotlin/app/aaps/core/objects/wizard/QuickWizardEntry.kt +++ b/core/objects/src/main/kotlin/app/aaps/core/objects/wizard/QuickWizardEntry.kt @@ -9,11 +9,10 @@ import app.aaps.core.interfaces.iob.IobCobCalculator import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.profile.Profile import app.aaps.core.interfaces.profile.ProfileFunction -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.keys.BooleanKey import app.aaps.core.keys.IntKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.extensions.valueToUnits import app.aaps.core.utils.JsonHelper.safeGetInt import app.aaps.core.utils.JsonHelper.safeGetString @@ -27,7 +26,6 @@ import javax.inject.Inject class QuickWizardEntry @Inject constructor(private val injector: HasAndroidInjector) { @Inject lateinit var aapsLogger: AAPSLogger - @Inject lateinit var sp: SP @Inject lateinit var preferences: Preferences @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var loop: Loop diff --git a/core/objects/src/test/kotlin/app/aaps/core/objects/profile/ProfileSealedTest.kt b/core/objects/src/test/kotlin/app/aaps/core/objects/profile/ProfileSealedTest.kt index 2ababdeaf73..2c4a6364af1 100644 --- a/core/objects/src/test/kotlin/app/aaps/core/objects/profile/ProfileSealedTest.kt +++ b/core/objects/src/test/kotlin/app/aaps/core/objects/profile/ProfileSealedTest.kt @@ -6,10 +6,9 @@ import app.aaps.core.interfaces.configuration.Config import app.aaps.core.interfaces.nsclient.ProcessedDeviceStatusData import app.aaps.core.interfaces.plugin.ActivePlugin import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.HardLimits -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.extensions.pureProfileFromJson import app.aaps.shared.impl.utils.DateUtilImpl import app.aaps.shared.tests.HardLimitsMock @@ -34,7 +33,6 @@ class ProfileSealedTest : TestBase() { @Mock lateinit var rh: ResourceHelper @Mock lateinit var context: Context @Mock lateinit var config: Config - @Mock lateinit var sp: SP @Mock lateinit var preferences: Preferences @Mock lateinit var aps: APS @Mock lateinit var processedDeviceStatusData: ProcessedDeviceStatusData @@ -62,7 +60,7 @@ class ProfileSealedTest : TestBase() { fun prepare() { testPumpPlugin = TestPumpPlugin(rh) dateUtil = DateUtilImpl(context) - hardLimits = HardLimitsMock(sp, preferences, rh) + hardLimits = HardLimitsMock(preferences, rh) `when`(activePlugin.activePump).thenReturn(testPumpPlugin) `when`(rh.gs(app.aaps.core.ui.R.string.profile_per_unit)).thenReturn("/U") `when`(rh.gs(app.aaps.core.ui.R.string.profile_carbs_per_unit)).thenReturn("g/U") diff --git a/core/objects/src/test/kotlin/app/aaps/core/objects/wizard/QuickWizardTest.kt b/core/objects/src/test/kotlin/app/aaps/core/objects/wizard/QuickWizardTest.kt index 41edb3713c6..ff8a8cc6255 100644 --- a/core/objects/src/test/kotlin/app/aaps/core/objects/wizard/QuickWizardTest.kt +++ b/core/objects/src/test/kotlin/app/aaps/core/objects/wizard/QuickWizardTest.kt @@ -2,7 +2,8 @@ package app.aaps.core.objects.wizard import app.aaps.core.interfaces.aps.Loop import app.aaps.core.interfaces.profile.ProfileFunction -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.StringNonKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.shared.tests.TestBase import com.google.common.truth.Truth.assertThat import dagger.android.AndroidInjector @@ -15,7 +16,7 @@ import org.mockito.Mockito.`when` class QuickWizardTest : TestBase() { - @Mock lateinit var sp: SP + @Mock lateinit var preferences: Preferences @Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var loop: Loop @@ -36,7 +37,7 @@ class QuickWizardTest : TestBase() { AndroidInjector { if (it is QuickWizardEntry) { it.aapsLogger = aapsLogger - it.sp = sp + it.preferences = preferences it.profileFunction = profileFunction it.loop = loop it.time = mockedTime @@ -48,8 +49,8 @@ class QuickWizardTest : TestBase() { @BeforeEach fun setup() { - `when`(sp.getString(app.aaps.core.utils.R.string.key_quickwizard, "[]")).thenReturn("[]") - quickWizard = QuickWizard(sp, injector) + `when`(preferences.get(StringNonKey.QuickWizard)).thenReturn("[]") + quickWizard = QuickWizard(preferences, injector) } @Test diff --git a/core/ui/src/main/kotlin/app/aaps/core/ui/locale/LocaleHelper.kt b/core/ui/src/main/kotlin/app/aaps/core/ui/locale/LocaleHelper.kt index 525f8d73949..ea28d4f0226 100644 --- a/core/ui/src/main/kotlin/app/aaps/core/ui/locale/LocaleHelper.kt +++ b/core/ui/src/main/kotlin/app/aaps/core/ui/locale/LocaleHelper.kt @@ -15,7 +15,7 @@ object LocaleHelper { else PreferenceManager.getDefaultSharedPreferences(context).getString("language", "default") ?: "default" // injection not possible because of use in attachBaseContext - //SP.getString(R.string.key_language, Locale.getDefault().language) + //preferences.get(R.string.key_language, Locale.getDefault().language) fun currentLocale(context: Context): Locale { val language = selectedLanguage(context) diff --git a/core/ui/src/main/res/values/strings.xml b/core/ui/src/main/res/values/strings.xml index 8ca726110d2..0bf263229b6 100644 --- a/core/ui/src/main/res/values/strings.xml +++ b/core/ui/src/main/res/values/strings.xml @@ -446,7 +446,6 @@ - raise_urgent_alarms_as_android_notification Use system notifications for alerts and notifications Urgent Alarm INFO diff --git a/core/utils/src/main/res/values/keys.xml b/core/utils/src/main/res/values/keys.xml index 31b4be268dd..0dfca3ffc0a 100644 --- a/core/utils/src/main/res/values/keys.xml +++ b/core/utils/src/main/res/values/keys.xml @@ -1,36 +1,6 @@ - bt_watchdog_last - QuickWizard units_mgdl - medtronic_settings - insight_local_settings - active_pump_change_timestamp - active_pump_type - active_pump_serial_number - app_expiration - nextPumpDisconnectedAlarm - nextMissedReadingsAlarm - rangetodisplay - local_profile_last_change - ObjectivesProfileSwitchUsed - ObjectivesTempTargetUsed - ObjectivesDisconnectUsed - ObjectivesReconnectUsed - wear_detailediob - wear_showbgi - wear_detailed_delta - wear_cwf_watchface_name - wear_cwf_author_version - wear_cwf_filename - ObjectivesbgIsAvailableInNS - ObjectivespumpStatusIsAvailableInNS - snoozedTo - ObjectivesLoopUsed - ObjectivesmanualEnacts - ObjectivesActionsUsed - ObjectivesScaleUsed - used_autosens_on_main_phone \ No newline at end of file diff --git a/core/validators/src/main/kotlin/app/aaps/core/validators/ValidatingEditTextPreference.kt b/core/validators/src/main/kotlin/app/aaps/core/validators/ValidatingEditTextPreference.kt index 23f1fad1d11..05f888f1dec 100644 --- a/core/validators/src/main/kotlin/app/aaps/core/validators/ValidatingEditTextPreference.kt +++ b/core/validators/src/main/kotlin/app/aaps/core/validators/ValidatingEditTextPreference.kt @@ -7,7 +7,7 @@ import androidx.preference.EditTextPreference import androidx.preference.PreferenceViewHolder import app.aaps.core.interfaces.profile.ProfileUtil import app.aaps.core.interfaces.utils.SafeParse -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import dagger.android.HasAndroidInjector import javax.inject.Inject diff --git a/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveClickPreference.kt b/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveClickPreference.kt index cf38f3320f3..3fc42909230 100644 --- a/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveClickPreference.kt +++ b/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveClickPreference.kt @@ -1,13 +1,12 @@ package app.aaps.core.validators.preferences import android.content.Context -import android.content.SharedPreferences import android.util.AttributeSet import androidx.annotation.StringRes import androidx.preference.Preference import androidx.preference.PreferenceViewHolder -import app.aaps.core.keys.Preferences -import app.aaps.core.keys.StringPreferenceKey +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.core.keys.interfaces.StringPreferenceKey import dagger.android.HasAndroidInjector import javax.inject.Inject @@ -24,7 +23,6 @@ class AdaptiveClickPreference( private val preferenceKey: StringPreferenceKey @Inject lateinit var preferences: Preferences - @Inject lateinit var sharedPrefs: SharedPreferences // Inflater constructor constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, stringKey = null, title = null) @@ -51,11 +49,11 @@ class AdaptiveClickPreference( isVisible = false; isEnabled = false } preferenceKey.dependency?.let { - if (!sharedPrefs.getBoolean(it.key, false)) + if (!preferences.get(it)) isVisible = false } preferenceKey.negativeDependency?.let { - if (sharedPrefs.getBoolean(it.key, false)) + if (preferences.get(it)) isVisible = false } calculatedVisibility?.let { isVisible = it.invoke() } diff --git a/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveDoublePreference.kt b/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveDoublePreference.kt index 2d1b6d4d0ee..1a65f383911 100644 --- a/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveDoublePreference.kt +++ b/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveDoublePreference.kt @@ -1,7 +1,6 @@ package app.aaps.core.validators.preferences import android.content.Context -import android.content.SharedPreferences import android.text.InputType import android.util.AttributeSet import androidx.annotation.StringRes @@ -9,8 +8,8 @@ import androidx.preference.EditTextPreference import androidx.preference.PreferenceViewHolder import app.aaps.core.interfaces.profile.ProfileUtil import app.aaps.core.interfaces.utils.SafeParse -import app.aaps.core.keys.DoublePreferenceKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.DoublePreferenceKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.validators.DefaultEditTextValidator import app.aaps.core.validators.EditTextValidator import app.aaps.core.validators.R @@ -31,7 +30,6 @@ class AdaptiveDoublePreference( @Inject lateinit var profileUtil: ProfileUtil @Inject lateinit var preferences: Preferences - @Inject lateinit var sharedPrefs: SharedPreferences // Inflater constructor constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, doubleKey = null, title = null) @@ -58,11 +56,11 @@ class AdaptiveDoublePreference( isVisible = false; isEnabled = false } preferenceKey.dependency?.let { - if (!sharedPrefs.getBoolean(it.key, false)) + if (!preferences.get(it)) isVisible = false } preferenceKey.negativeDependency?.let { - if (sharedPrefs.getBoolean(it.key, false)) + if (preferences.get(it)) isVisible = false } validatorParameters = obtainValidatorParameters(attrs) diff --git a/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveIntPreference.kt b/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveIntPreference.kt index 926df19d87e..71e852ae3de 100644 --- a/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveIntPreference.kt +++ b/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveIntPreference.kt @@ -1,7 +1,6 @@ package app.aaps.core.validators.preferences import android.content.Context -import android.content.SharedPreferences import android.text.InputType import android.util.AttributeSet import androidx.annotation.StringRes @@ -10,8 +9,8 @@ import androidx.preference.PreferenceViewHolder import app.aaps.core.interfaces.configuration.Config import app.aaps.core.interfaces.profile.ProfileUtil import app.aaps.core.interfaces.utils.SafeParse -import app.aaps.core.keys.IntPreferenceKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.IntPreferenceKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.validators.DefaultEditTextValidator import app.aaps.core.validators.EditTextValidator import app.aaps.core.validators.R @@ -34,7 +33,6 @@ class AdaptiveIntPreference( @Inject lateinit var profileUtil: ProfileUtil @Inject lateinit var preferences: Preferences - @Inject lateinit var sharedPrefs: SharedPreferences @Inject lateinit var config: Config // Inflater constructor @@ -64,11 +62,11 @@ class AdaptiveIntPreference( isVisible = false; isEnabled = false } preferenceKey.dependency?.let { - if (!sharedPrefs.getBoolean(it.key, false)) + if (!preferences.get(it)) isVisible = false } preferenceKey.negativeDependency?.let { - if (sharedPrefs.getBoolean(it.key, false)) + if (preferences.get(it)) isVisible = false } validatorParameters = if (validatorParams != null) validatorParams else obtainValidatorParameters(attrs) diff --git a/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveIntentPreference.kt b/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveIntentPreference.kt index f2fb60207a7..1560b41feeb 100644 --- a/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveIntentPreference.kt +++ b/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveIntentPreference.kt @@ -2,13 +2,11 @@ package app.aaps.core.validators.preferences import android.content.Context import android.content.Intent -import android.content.SharedPreferences import android.util.AttributeSet import androidx.annotation.StringRes import androidx.preference.Preference -import app.aaps.core.keys.IntentKey -import app.aaps.core.keys.IntentPreferenceKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.IntentPreferenceKey +import app.aaps.core.keys.interfaces.Preferences import dagger.android.HasAndroidInjector import javax.inject.Inject @@ -18,11 +16,10 @@ class AdaptiveIntentPreference( intentKey: IntentPreferenceKey?, intent: Intent? = null, @StringRes summary: Int? = null, - @StringRes title: Int? = null, + @StringRes title: Int? = null ) : Preference(ctx, attrs) { @Inject lateinit var preferences: Preferences - @Inject lateinit var sharedPrefs: SharedPreferences // Inflater constructor constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, intentKey = null, intent = null) @@ -47,11 +44,11 @@ class AdaptiveIntentPreference( isVisible = false; isEnabled = false } preferenceKey.dependency?.let { - if (!sharedPrefs.getBoolean(it.key, false)) + if (!preferences.get(it)) isVisible = false } preferenceKey.negativeDependency?.let { - if (sharedPrefs.getBoolean(it.key, false)) + if (preferences.get(it)) isVisible = false } } diff --git a/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveListIntPreference.kt b/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveListIntPreference.kt index 51ff7e67b2a..2b85cfb5688 100644 --- a/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveListIntPreference.kt +++ b/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveListIntPreference.kt @@ -1,12 +1,11 @@ package app.aaps.core.validators.preferences import android.content.Context -import android.content.SharedPreferences import android.util.AttributeSet import androidx.annotation.StringRes import androidx.preference.ListPreference -import app.aaps.core.keys.IntPreferenceKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.IntPreferenceKey +import app.aaps.core.keys.interfaces.Preferences import dagger.android.HasAndroidInjector import javax.inject.Inject @@ -23,7 +22,6 @@ open class AdaptiveListIntPreference( ) : ListPreference(ctx, attrs) { @Inject lateinit var preferences: Preferences - @Inject lateinit var sharedPrefs: SharedPreferences // Inflater constructor constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, intKey = null, title = null) @@ -51,11 +49,11 @@ open class AdaptiveListIntPreference( isVisible = false; isEnabled = false } preferenceKey.dependency?.let { - if (!sharedPrefs.getBoolean(it.key, false)) + if (!preferences.get(it)) isVisible = false } preferenceKey.negativeDependency?.let { - if (sharedPrefs.getBoolean(it.key, false)) + if (preferences.get(it)) isVisible = false } setDefaultValue(preferenceKey.defaultValue.toString()) diff --git a/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveListPreference.kt b/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveListPreference.kt index d143277c705..4a0fb033dc1 100644 --- a/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveListPreference.kt +++ b/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveListPreference.kt @@ -1,12 +1,11 @@ package app.aaps.core.validators.preferences import android.content.Context -import android.content.SharedPreferences import android.util.AttributeSet import androidx.annotation.StringRes import androidx.preference.ListPreference -import app.aaps.core.keys.Preferences -import app.aaps.core.keys.StringPreferenceKey +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.core.keys.interfaces.StringPreferenceKey import dagger.android.HasAndroidInjector import javax.inject.Inject @@ -23,7 +22,6 @@ open class AdaptiveListPreference( ) : ListPreference(ctx, attrs) { @Inject lateinit var preferences: Preferences - @Inject lateinit var sharedPrefs: SharedPreferences // Inflater constructor constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, stringKey = null, title = null) @@ -51,11 +49,11 @@ open class AdaptiveListPreference( isVisible = false; isEnabled = false } preferenceKey.dependency?.let { - if (!sharedPrefs.getBoolean(it.key, false)) + if (!preferences.get(it)) isVisible = false } preferenceKey.negativeDependency?.let { - if (sharedPrefs.getBoolean(it.key, false)) + if (preferences.get(it)) isVisible = false } setDefaultValue(preferenceKey.defaultValue) diff --git a/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveStringPreference.kt b/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveStringPreference.kt index 4086df388d9..932b463fc1e 100644 --- a/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveStringPreference.kt +++ b/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveStringPreference.kt @@ -1,15 +1,14 @@ package app.aaps.core.validators.preferences import android.content.Context -import android.content.SharedPreferences import android.text.InputType import android.util.AttributeSet import androidx.annotation.StringRes import androidx.preference.EditTextPreference import androidx.preference.PreferenceViewHolder import app.aaps.core.interfaces.profile.ProfileUtil -import app.aaps.core.keys.Preferences -import app.aaps.core.keys.StringPreferenceKey +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.core.keys.interfaces.StringPreferenceKey import app.aaps.core.validators.DefaultEditTextValidator import app.aaps.core.validators.EditTextValidator import app.aaps.core.validators.R @@ -32,7 +31,6 @@ class AdaptiveStringPreference( @Inject lateinit var profileUtil: ProfileUtil @Inject lateinit var preferences: Preferences - @Inject lateinit var sharedPrefs: SharedPreferences // Inflater constructor constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, stringKey = null, title = null) @@ -60,11 +58,11 @@ class AdaptiveStringPreference( isVisible = false; isEnabled = false } preferenceKey.dependency?.let { - if (!sharedPrefs.getBoolean(it.key, false)) + if (!preferences.get(it)) isVisible = false } preferenceKey.negativeDependency?.let { - if (sharedPrefs.getBoolean(it.key, false)) + if (preferences.get(it)) isVisible = false } validatorParameters = validatorParams ?: obtainValidatorParameters(attrs) diff --git a/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveSwitchPreference.kt b/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveSwitchPreference.kt index 396bcff88ed..c42ba24c836 100644 --- a/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveSwitchPreference.kt +++ b/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveSwitchPreference.kt @@ -1,13 +1,12 @@ package app.aaps.core.validators.preferences import android.content.Context -import android.content.SharedPreferences import android.util.AttributeSet import androidx.annotation.StringRes import androidx.preference.SwitchPreference import app.aaps.core.interfaces.configuration.Config -import app.aaps.core.keys.BooleanPreferenceKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.BooleanPreferenceKey +import app.aaps.core.keys.interfaces.Preferences import dagger.android.HasAndroidInjector import javax.inject.Inject @@ -20,7 +19,6 @@ class AdaptiveSwitchPreference( ) : SwitchPreference(ctx, attrs) { @Inject lateinit var preferences: Preferences - @Inject lateinit var sharedPrefs: SharedPreferences @Inject lateinit var config: Config // Inflater constructor @@ -48,11 +46,11 @@ class AdaptiveSwitchPreference( isVisible = false; isEnabled = false } preferenceKey.dependency?.let { - if (!sharedPrefs.getBoolean(it.key, false)) + if (!preferences.get(it)) isVisible = false } preferenceKey.negativeDependency?.let { - if (sharedPrefs.getBoolean(it.key, false)) + if (preferences.get(it)) isVisible = false } setDefaultValue(preferenceKey.defaultValue) diff --git a/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveUnitPreference.kt b/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveUnitPreference.kt index 3a592f37e9a..b774125620d 100644 --- a/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveUnitPreference.kt +++ b/core/validators/src/main/kotlin/app/aaps/core/validators/preferences/AdaptiveUnitPreference.kt @@ -1,7 +1,6 @@ package app.aaps.core.validators.preferences import android.content.Context -import android.content.SharedPreferences import android.text.InputType import android.util.AttributeSet import androidx.annotation.StringRes @@ -10,8 +9,8 @@ import androidx.preference.PreferenceViewHolder import app.aaps.core.data.model.GlucoseUnit import app.aaps.core.interfaces.profile.ProfileUtil import app.aaps.core.interfaces.utils.SafeParse -import app.aaps.core.keys.Preferences -import app.aaps.core.keys.UnitDoublePreferenceKey +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.core.keys.interfaces.UnitDoublePreferenceKey import app.aaps.core.validators.DefaultEditTextValidator import app.aaps.core.validators.EditTextValidator import app.aaps.core.validators.R @@ -34,7 +33,6 @@ class AdaptiveUnitPreference( @Inject lateinit var profileUtil: ProfileUtil @Inject lateinit var preferences: Preferences - @Inject lateinit var sharedPrefs: SharedPreferences // Inflater constructor constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, unitKey = null, title = null) @@ -68,11 +66,11 @@ class AdaptiveUnitPreference( isVisible = false; isEnabled = false } preferenceKey.dependency?.let { - if (!sharedPrefs.getBoolean(it.key, false)) + if (!preferences.get(it)) isVisible = false } preferenceKey.negativeDependency?.let { - if (sharedPrefs.getBoolean(it.key, false)) + if (preferences.get(it)) isVisible = false } validatorParameters = obtainValidatorParameters(attrs) diff --git a/implementation/src/main/kotlin/app/aaps/implementation/alerts/LocalAlertUtilsImpl.kt b/implementation/src/main/kotlin/app/aaps/implementation/alerts/LocalAlertUtilsImpl.kt index a5420a3c1e8..f29061b07b8 100644 --- a/implementation/src/main/kotlin/app/aaps/implementation/alerts/LocalAlertUtilsImpl.kt +++ b/implementation/src/main/kotlin/app/aaps/implementation/alerts/LocalAlertUtilsImpl.kt @@ -17,14 +17,14 @@ import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventDismissNotification import app.aaps.core.interfaces.rx.events.EventNewNotification -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.smsCommunicator.SmsCommunicator import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.keys.BooleanKey import app.aaps.core.keys.IntKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.extensions.asAnnouncement import app.aaps.core.ui.R +import app.aaps.implementation.alerts.keys.LocalAlertLongKey import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import javax.inject.Inject @@ -37,7 +37,6 @@ import kotlin.math.min @Singleton class LocalAlertUtilsImpl @Inject constructor( private val aapsLogger: AAPSLogger, - private val sp: SP, private val preferences: Preferences, private val rxBus: RxBus, private val rh: ResourceHelper, @@ -49,6 +48,10 @@ class LocalAlertUtilsImpl @Inject constructor( private val dateUtil: DateUtil ) : LocalAlertUtils { + init { + preferences.registerPreferences(LocalAlertLongKey::class.java) + } + private val disposable = CompositeDisposable() private fun missedReadingsThreshold(): Long { @@ -61,11 +64,11 @@ class LocalAlertUtilsImpl @Inject constructor( override fun checkPumpUnreachableAlarm(lastConnection: Long, isStatusOutdated: Boolean, isDisconnected: Boolean) { val alarmTimeoutExpired = isAlarmTimeoutExpired(lastConnection, pumpUnreachableThreshold()) - val nextAlarmOccurrenceReached = sp.getLong(app.aaps.core.utils.R.string.key_next_pump_disconnected_alarm, 0L) < dateUtil.now() + val nextAlarmOccurrenceReached = preferences.get(LocalAlertLongKey.NextPumpDisconnectedAlarm) < dateUtil.now() if (config.APS && isStatusOutdated && alarmTimeoutExpired && nextAlarmOccurrenceReached && !isDisconnected) { if (preferences.get(BooleanKey.AlertPumpUnreachable)) { aapsLogger.debug(LTag.CORE, "Generating pump unreachable alarm. lastConnection: " + dateUtil.dateAndTimeString(lastConnection) + " isStatusOutdated: true") - sp.putLong(app.aaps.core.utils.R.string.key_next_pump_disconnected_alarm, dateUtil.now() + pumpUnreachableThreshold()) + preferences.put(LocalAlertLongKey.NextPumpDisconnectedAlarm, dateUtil.now() + pumpUnreachableThreshold()) rxBus.send(EventNewNotification(Notification(Notification.PUMP_UNREACHABLE, rh.gs(R.string.pump_unreachable), Notification.URGENT).also { it.soundId = R.raw.alarm })) if (preferences.get(BooleanKey.NsClientCreateAnnouncementsFromErrors) && config.APS) disposable += persistenceLayer.insertPumpTherapyEventIfNewByTimestamp( @@ -95,21 +98,21 @@ class LocalAlertUtilsImpl @Inject constructor( * Call only at startup! */ override fun preSnoozeAlarms() { - if (sp.getLong(app.aaps.core.utils.R.string.key_next_missed_reading_alarm, 0L) < dateUtil.now()) { - sp.putLong(app.aaps.core.utils.R.string.key_next_missed_reading_alarm, dateUtil.now() + 5 * 60 * 1000) + if (preferences.get(LocalAlertLongKey.NextMissedReadingsAlarm) < dateUtil.now()) { + preferences.put(LocalAlertLongKey.NextMissedReadingsAlarm, dateUtil.now() + 5 * 60 * 1000) } - if (sp.getLong(app.aaps.core.utils.R.string.key_next_pump_disconnected_alarm, 0L) < dateUtil.now()) { - sp.putLong(app.aaps.core.utils.R.string.key_next_pump_disconnected_alarm, dateUtil.now() + 5 * 60 * 1000) + if (preferences.get(LocalAlertLongKey.NextPumpDisconnectedAlarm) < dateUtil.now()) { + preferences.put(LocalAlertLongKey.NextPumpDisconnectedAlarm, dateUtil.now() + 5 * 60 * 1000) } } override fun shortenSnoozeInterval() { //shortens alarm times in case of setting changes or future data - var nextMissedReadingsAlarm = sp.getLong(app.aaps.core.utils.R.string.key_next_missed_reading_alarm, 0L) + var nextMissedReadingsAlarm = preferences.get(LocalAlertLongKey.NextMissedReadingsAlarm) nextMissedReadingsAlarm = min(dateUtil.now() + missedReadingsThreshold(), nextMissedReadingsAlarm) - sp.putLong(app.aaps.core.utils.R.string.key_next_missed_reading_alarm, nextMissedReadingsAlarm) - var nextPumpDisconnectedAlarm = sp.getLong(app.aaps.core.utils.R.string.key_next_pump_disconnected_alarm, 0L) + preferences.put(LocalAlertLongKey.NextMissedReadingsAlarm, nextMissedReadingsAlarm) + var nextPumpDisconnectedAlarm = preferences.get(LocalAlertLongKey.NextPumpDisconnectedAlarm) nextPumpDisconnectedAlarm = min(dateUtil.now() + pumpUnreachableThreshold(), nextPumpDisconnectedAlarm) - sp.putLong(app.aaps.core.utils.R.string.key_next_pump_disconnected_alarm, nextPumpDisconnectedAlarm) + preferences.put(LocalAlertLongKey.NextPumpDisconnectedAlarm, nextPumpDisconnectedAlarm) } override fun reportPumpStatusRead() { @@ -118,8 +121,8 @@ class LocalAlertUtilsImpl @Inject constructor( if (profile != null) { val lastConnection = pump.lastDataTime() val earliestAlarmTime = lastConnection + pumpUnreachableThreshold() - if (sp.getLong(app.aaps.core.utils.R.string.key_next_pump_disconnected_alarm, 0L) < earliestAlarmTime) { - sp.putLong(app.aaps.core.utils.R.string.key_next_pump_disconnected_alarm, earliestAlarmTime) + if (preferences.get(LocalAlertLongKey.NextPumpDisconnectedAlarm) < earliestAlarmTime) { + preferences.put(LocalAlertLongKey.NextPumpDisconnectedAlarm, earliestAlarmTime) } } } @@ -128,11 +131,11 @@ class LocalAlertUtilsImpl @Inject constructor( val bgReading = persistenceLayer.getLastGlucoseValue() ?: return if (preferences.get(BooleanKey.AlertMissedBgReading) && bgReading.timestamp + missedReadingsThreshold() < dateUtil.now() - && sp.getLong(app.aaps.core.utils.R.string.key_next_missed_reading_alarm, 0L) < dateUtil.now() + && preferences.get(LocalAlertLongKey.NextMissedReadingsAlarm) < dateUtil.now() ) { val n = Notification(Notification.BG_READINGS_MISSED, rh.gs(R.string.missed_bg_readings), Notification.URGENT) n.soundId = R.raw.alarm - sp.putLong(app.aaps.core.utils.R.string.key_next_missed_reading_alarm, dateUtil.now() + missedReadingsThreshold()) + preferences.put(LocalAlertLongKey.NextMissedReadingsAlarm, dateUtil.now() + missedReadingsThreshold()) rxBus.send(EventNewNotification(n)) if (preferences.get(BooleanKey.NsClientCreateAnnouncementsFromErrors) && config.APS) { disposable += persistenceLayer.insertPumpTherapyEventIfNewByTimestamp( diff --git a/implementation/src/main/kotlin/app/aaps/implementation/alerts/keys/LocalAlertLongKey.kt b/implementation/src/main/kotlin/app/aaps/implementation/alerts/keys/LocalAlertLongKey.kt new file mode 100644 index 00000000000..c8651af5377 --- /dev/null +++ b/implementation/src/main/kotlin/app/aaps/implementation/alerts/keys/LocalAlertLongKey.kt @@ -0,0 +1,13 @@ +package app.aaps.implementation.alerts.keys + +import app.aaps.core.keys.interfaces.LongNonPreferenceKey + +enum class LocalAlertLongKey( + override val key: String, + override val defaultValue: Long, + override val exportable: Boolean = true +) : LongNonPreferenceKey { + + NextPumpDisconnectedAlarm("nextPumpDisconnectedAlarm", 0L), + NextMissedReadingsAlarm("nextMissedReadingsAlarm", 0L) +} \ No newline at end of file diff --git a/implementation/src/main/kotlin/app/aaps/implementation/di/ImplementationModule.kt b/implementation/src/main/kotlin/app/aaps/implementation/di/ImplementationModule.kt index 558425b4adb..7092284d329 100644 --- a/implementation/src/main/kotlin/app/aaps/implementation/di/ImplementationModule.kt +++ b/implementation/src/main/kotlin/app/aaps/implementation/di/ImplementationModule.kt @@ -34,7 +34,7 @@ import app.aaps.core.interfaces.utils.HardLimits import app.aaps.core.interfaces.utils.Translator import app.aaps.core.interfaces.utils.TrendCalculator import app.aaps.core.interfaces.utils.fabric.FabricPrivacy -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.implementation.alerts.LocalAlertUtilsImpl import app.aaps.implementation.androidNotification.NotificationHolderImpl import app.aaps.implementation.db.ProcessedTbrEbDataImpl diff --git a/implementation/src/main/kotlin/app/aaps/implementation/instantiator/InstantiatorImpl.kt b/implementation/src/main/kotlin/app/aaps/implementation/instantiator/InstantiatorImpl.kt index 60e67d65704..6a21902c633 100644 --- a/implementation/src/main/kotlin/app/aaps/implementation/instantiator/InstantiatorImpl.kt +++ b/implementation/src/main/kotlin/app/aaps/implementation/instantiator/InstantiatorImpl.kt @@ -12,7 +12,7 @@ import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.HardLimits -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.aps.DetermineBasalResult import app.aaps.implementation.iob.AutosensDataObject import app.aaps.implementation.profile.ProfileStoreObject diff --git a/implementation/src/main/kotlin/app/aaps/implementation/iob/AutosensDataObject.kt b/implementation/src/main/kotlin/app/aaps/implementation/iob/AutosensDataObject.kt index a9e6878b543..21586b09c17 100644 --- a/implementation/src/main/kotlin/app/aaps/implementation/iob/AutosensDataObject.kt +++ b/implementation/src/main/kotlin/app/aaps/implementation/iob/AutosensDataObject.kt @@ -6,7 +6,7 @@ import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.keys.DoubleKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import java.util.Locale import kotlin.math.min diff --git a/implementation/src/main/kotlin/app/aaps/implementation/overview/LastBgDataImpl.kt b/implementation/src/main/kotlin/app/aaps/implementation/overview/LastBgDataImpl.kt index 04db6298acd..dedb68d23fe 100644 --- a/implementation/src/main/kotlin/app/aaps/implementation/overview/LastBgDataImpl.kt +++ b/implementation/src/main/kotlin/app/aaps/implementation/overview/LastBgDataImpl.kt @@ -10,8 +10,8 @@ import app.aaps.core.interfaces.overview.LastBgData import app.aaps.core.interfaces.profile.ProfileFunction import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.utils.DateUtil -import app.aaps.core.keys.Preferences import app.aaps.core.keys.UnitDoubleKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.extensions.fromGv import app.aaps.core.objects.extensions.valueToUnits import dagger.Reusable diff --git a/implementation/src/main/kotlin/app/aaps/implementation/profile/ProfileFunctionImpl.kt b/implementation/src/main/kotlin/app/aaps/implementation/profile/ProfileFunctionImpl.kt index 9f722965f4b..cbc607f5c38 100644 --- a/implementation/src/main/kotlin/app/aaps/implementation/profile/ProfileFunctionImpl.kt +++ b/implementation/src/main/kotlin/app/aaps/implementation/profile/ProfileFunctionImpl.kt @@ -22,8 +22,8 @@ import app.aaps.core.interfaces.rx.events.EventEffectiveProfileSwitchChanged import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.HardLimits import app.aaps.core.interfaces.utils.fabric.FabricPrivacy -import app.aaps.core.keys.Preferences import app.aaps.core.keys.StringKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.profile.ProfileSealed import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign diff --git a/implementation/src/main/kotlin/app/aaps/implementation/profile/ProfileUtilImpl.kt b/implementation/src/main/kotlin/app/aaps/implementation/profile/ProfileUtilImpl.kt index 45c11f49efe..b3bcf743825 100644 --- a/implementation/src/main/kotlin/app/aaps/implementation/profile/ProfileUtilImpl.kt +++ b/implementation/src/main/kotlin/app/aaps/implementation/profile/ProfileUtilImpl.kt @@ -6,8 +6,8 @@ import app.aaps.core.interfaces.profile.Profile import app.aaps.core.interfaces.profile.ProfileUtil import app.aaps.core.interfaces.pump.defs.determineCorrectBasalSize import app.aaps.core.interfaces.utils.DecimalFormatter -import app.aaps.core.keys.Preferences import app.aaps.core.keys.StringKey +import app.aaps.core.keys.interfaces.Preferences import dagger.Reusable import java.util.Locale import javax.inject.Inject diff --git a/implementation/src/main/kotlin/app/aaps/implementation/protection/BiometricCheck.kt b/implementation/src/main/kotlin/app/aaps/implementation/protection/BiometricCheck.kt index 4e769ef9ae7..656469a4540 100644 --- a/implementation/src/main/kotlin/app/aaps/implementation/protection/BiometricCheck.kt +++ b/implementation/src/main/kotlin/app/aaps/implementation/protection/BiometricCheck.kt @@ -43,7 +43,7 @@ object BiometricCheck { ToastUtils.errorToast(activity.baseContext, errString.toString()) // fallback to master password runOnUiThread { - passwordCheck.queryPassword(activity, R.string.master_password, StringKey.ProtectionMasterPassword.key, { ok?.run() }, { cancel?.run() }, { fail?.run() }) + passwordCheck.queryPassword(activity, R.string.master_password, StringKey.ProtectionMasterPassword, { ok?.run() }, { cancel?.run() }, { fail?.run() }) } } @@ -55,7 +55,7 @@ object BiometricCheck { // no pin set // fallback to master password runOnUiThread { - passwordCheck.queryPassword(activity, R.string.master_password, StringKey.ProtectionMasterPassword.key, { ok?.run() }, { cancel?.run() }, { fail?.run() }) + passwordCheck.queryPassword(activity, R.string.master_password, StringKey.ProtectionMasterPassword, { ok?.run() }, { cancel?.run() }, { fail?.run() }) } } @@ -64,7 +64,7 @@ object BiometricCheck { ERROR_HW_NOT_PRESENT, ERROR_NO_BIOMETRICS -> runOnUiThread { - passwordCheck.queryPassword(activity, R.string.master_password, StringKey.ProtectionMasterPassword.key, { ok?.run() }, { cancel?.run() }, { fail?.run() }) + passwordCheck.queryPassword(activity, R.string.master_password, StringKey.ProtectionMasterPassword, { ok?.run() }, { cancel?.run() }, { fail?.run() }) } } } diff --git a/implementation/src/main/kotlin/app/aaps/implementation/protection/ExportPasswordDataStoreImpl.kt b/implementation/src/main/kotlin/app/aaps/implementation/protection/ExportPasswordDataStoreImpl.kt index d0d57fd6fb5..914a2915f0f 100644 --- a/implementation/src/main/kotlin/app/aaps/implementation/protection/ExportPasswordDataStoreImpl.kt +++ b/implementation/src/main/kotlin/app/aaps/implementation/protection/ExportPasswordDataStoreImpl.kt @@ -2,7 +2,6 @@ package app.aaps.implementation.protection import android.content.Context import androidx.datastore.core.DataStore -import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.preferencesDataStore @@ -12,9 +11,9 @@ import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.maintenance.FileListProvider import app.aaps.core.interfaces.protection.ExportPasswordDataStore import app.aaps.core.interfaces.protection.SecureEncrypt -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.keys.BooleanKey +import app.aaps.core.keys.interfaces.Preferences import kotlinx.coroutines.runBlocking import javax.inject.Inject import javax.inject.Singleton @@ -39,9 +38,9 @@ import javax.inject.Singleton @Singleton class ExportPasswordDataStoreImpl @Inject constructor( private var log: AAPSLogger, - private var sp: SP, + private var preferences: Preferences, private var config: Config - ) : ExportPasswordDataStore { +) : ExportPasswordDataStore { @Inject lateinit var dateUtil: DateUtil @Inject lateinit var secureEncrypt: SecureEncrypt @@ -50,8 +49,10 @@ class ExportPasswordDataStoreImpl @Inject constructor( @Inject lateinit var fileListProvider: FileListProvider companion object { + // Internal constant stings const val MODULE = "ExportPasswordDataStore" + // KeyStore alias name to use for encrypting const val KEYSTORE_ALIAS = "UnattendedExportAlias" @@ -60,13 +61,13 @@ class ExportPasswordDataStoreImpl @Inject constructor( const val PASSWORD_PREFERENCE_NAME = "$DATASTORE_NAME.unattended_export" // On enabling & password expiry (fixed defaults) - private var exportPasswordStoreIsEnabled = false // Set from prefs, disabled by default - private var passwordValidityWindow: Long = 35 * 24 * 3600 * 1000L // 5 weeks (including grace period) - private var passwordExpiryGracePeriod: Long = 7 * 24 * 3600 * 1000L // 1 week + private var exportPasswordStoreIsEnabled = false // Set from prefs, disabled by default + private var passwordValidityWindow: Long = 35 * 24 * 3600 * 1000L // 5 weeks (including grace period) + private var passwordExpiryGracePeriod: Long = 7 * 24 * 3600 * 1000L // 1 week } // Declare DataStore - private val Context.dataStore: DataStore by preferencesDataStore( + private val Context.dataStore: DataStore by preferencesDataStore( name = DATASTORE_NAME ) @@ -87,9 +88,9 @@ class ExportPasswordDataStoreImpl @Inject constructor( * - var passwordValidityWindow * - var passwordExpiryGracePeriod */ - override fun exportPasswordStoreEnabled() : Boolean { + override fun exportPasswordStoreEnabled(): Boolean { // Is password storing enabled? - exportPasswordStoreIsEnabled = sp.getBoolean(BooleanKey.MaintenanceEnableExportSettingsAutomation.key, false) + exportPasswordStoreIsEnabled = preferences.get(BooleanKey.MaintenanceEnableExportSettingsAutomation) if (!exportPasswordStoreIsEnabled) return false // Easy, done! // Use fixed defaults for password validity window, optional overrule defaults from prefs: @@ -105,13 +106,12 @@ class ExportPasswordDataStoreImpl @Inject constructor( log.warn(LTag.CORE, "$MODULE: ExportPasswordDataStore running DEBUG(DEV) mode!") /*** Debug/testing mode ***/ passwordValidityWindow = 20 * 60 * 1000L // Valid for 20 min - passwordExpiryGracePeriod = passwordValidityWindow/2 // Grace period 10 min - } - else if (debug) { + passwordExpiryGracePeriod = passwordValidityWindow / 2 // Grace period 10 min + } else if (debug) { log.warn(LTag.CORE, "$MODULE: ExportPasswordDataStore running DEBUG mode!") /*** Debug mode ***/ passwordValidityWindow = 2 * 24 * 3600 * 1000L // 2 Days (including grace period) - passwordExpiryGracePeriod = passwordValidityWindow/2 // Grace period 1 days + passwordExpiryGracePeriod = passwordValidityWindow / 2 // Grace period 1 days } } // END @@ -146,7 +146,7 @@ class ExportPasswordDataStoreImpl @Inject constructor( * Return Triple (ok, password string, isExpired, isAboutToExpire) */ override fun getPasswordFromDataStore(context: Context): Triple { - if (!exportPasswordStoreEnabled()) return Triple ("", true, true) + if (!exportPasswordStoreEnabled()) return Triple("", true, true) val passwordData = this.retrievePassword(context) with(passwordData) { @@ -155,20 +155,20 @@ class ExportPasswordDataStoreImpl @Inject constructor( return Triple(password, isExpired, isAboutToExpire) } } - return Triple ("", true, true) + return Triple("", true, true) } /************************************************************************* * Private functions - *************************************************************************/ + *************************************************************************/ /*** * Check if timestamp is in validity window T...T+duration */ - private fun isInValidityWindow(timestamp: Long, duration: Long?, gracePeriod: Long?):Pair { + private fun isInValidityWindow(timestamp: Long, duration: Long?, gracePeriod: Long?): Pair { val expired = dateUtil.now() !in timestamp..timestamp + (duration ?: 0L) val expires = dateUtil.now() !in timestamp..timestamp + (duration ?: 0L) - (gracePeriod ?: 0L) - return Pair (expired, expires) + return Pair(expired, expires) } /*** @@ -177,7 +177,7 @@ class ExportPasswordDataStoreImpl @Inject constructor( private fun clearPassword(context: Context): String { // Write setting to android datastore and return password - fun updatePrefString(name: String) = runBlocking { + fun updatePrefString(name: String) = runBlocking { context.dataStore.edit { settings -> // Clear password as string value settings[stringPreferencesKey("$name.key")] = "" // Password @@ -189,14 +189,13 @@ class ExportPasswordDataStoreImpl @Inject constructor( return updatePrefString(PASSWORD_PREFERENCE_NAME) } - /*** * Store password and set timestamp to current */ private fun storePassword(context: Context, password: String): String { // Write encrypted password key and timestamp to the local phone's android datastore and return password - fun updatePrefString(name: String, str: String) = runBlocking { + fun updatePrefString(name: String, str: String) = runBlocking { context.dataStore.edit { settings -> // If current password is empty, update to new timestamp "now" or else leave it settings[stringPreferencesKey("$name.ts")] = dateUtil.now().toString() @@ -212,7 +211,7 @@ class ExportPasswordDataStoreImpl @Inject constructor( /*** * Retrieve password from local phone's data store. * Reset password when validity expired - ***/ + ***/ private fun retrievePassword(context: Context): ClassPasswordData { // Read encrypted password key and timestamp from the local phone's android datastore and return password @@ -222,8 +221,8 @@ class ExportPasswordDataStoreImpl @Inject constructor( runBlocking { val keyName = PASSWORD_PREFERENCE_NAME context.dataStore.edit { settings -> - passwordStr = settings[stringPreferencesKey("$keyName.key")] ?:"" - timestampStr = (settings[stringPreferencesKey("$keyName.ts")] ?:"") + passwordStr = settings[stringPreferencesKey("$keyName.key")] ?: "" + timestampStr = (settings[stringPreferencesKey("$keyName.ts")] ?: "") } } @@ -231,7 +230,7 @@ class ExportPasswordDataStoreImpl @Inject constructor( password = passwordStr, timestamp = if (timestampStr.isEmpty()) 0L else timestampStr.toLong(), isExpired = true, - isAboutToExpire = true + isAboutToExpire = true ) // Get the password value stored diff --git a/implementation/src/main/kotlin/app/aaps/implementation/protection/PasswordCheckImpl.kt b/implementation/src/main/kotlin/app/aaps/implementation/protection/PasswordCheckImpl.kt index f1d39089a36..0679fceb5ad 100644 --- a/implementation/src/main/kotlin/app/aaps/implementation/protection/PasswordCheckImpl.kt +++ b/implementation/src/main/kotlin/app/aaps/implementation/protection/PasswordCheckImpl.kt @@ -13,7 +13,8 @@ import android.widget.TextView import androidx.annotation.StringRes import app.aaps.core.interfaces.protection.ExportPasswordDataStore import app.aaps.core.interfaces.protection.PasswordCheck -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.core.keys.interfaces.StringPreferenceKey import app.aaps.core.objects.R import app.aaps.core.objects.crypto.CryptoUtil import app.aaps.core.ui.extensions.runOnUiThread @@ -24,7 +25,7 @@ import javax.inject.Inject @Reusable class PasswordCheckImpl @Inject constructor( - private val sp: SP, + private val preferences: Preferences, private val cryptoUtil: CryptoUtil ) : PasswordCheck { @@ -38,8 +39,8 @@ class PasswordCheckImpl @Inject constructor( Asks for "managed" kind of password, checking if it is valid. */ @SuppressLint("InflateParams") - override fun queryPassword(context: Context, @StringRes labelId: Int, preference: String, ok: ((String) -> Unit)?, cancel: (() -> Unit)?, fail: (() -> Unit)?, pinInput: Boolean) { - val password = sp.getString(preference, "") + override fun queryPassword(context: Context, @StringRes labelId: Int, preference: StringPreferenceKey, ok: ((String) -> Unit)?, cancel: (() -> Unit)?, fail: (() -> Unit)?, pinInput: Boolean) { + val password = preferences.get(preference) if (password == "") { ok?.invoke("") return @@ -99,7 +100,7 @@ class PasswordCheckImpl @Inject constructor( } @SuppressLint("InflateParams") - override fun setPassword(context: Context, @StringRes labelId: Int, preference: String, ok: ((String) -> Unit)?, cancel: (() -> Unit)?, clear: (() -> Unit)?, pinInput: Boolean) { + override fun setPassword(context: Context, @StringRes labelId: Int, preference: StringPreferenceKey, ok: ((String) -> Unit)?, cancel: (() -> Unit)?, clear: (() -> Unit)?, pinInput: Boolean) { val promptsView = LayoutInflater.from(context).inflate(R.layout.passwordprompt, null) val alertDialogBuilder = MaterialAlertDialogBuilder(context, app.aaps.core.ui.R.style.DialogTheme) alertDialogBuilder.setView(promptsView) @@ -125,14 +126,14 @@ class PasswordCheckImpl @Inject constructor( val msg = if (pinInput) app.aaps.core.ui.R.string.pin_dont_match else app.aaps.core.ui.R.string.passwords_dont_match ToastUtils.errorToast(context, context.getString(msg)) } else if (enteredPassword.isNotEmpty()) { - sp.putString(preference, cryptoUtil.hashPassword(enteredPassword)) + preferences.put(preference, cryptoUtil.hashPassword(enteredPassword)) exportPasswordDataStore.clearPasswordDataStore(context) val msg = if (pinInput) app.aaps.core.ui.R.string.pin_set else app.aaps.core.ui.R.string.password_set ToastUtils.okToast(context, context.getString(msg)) ok?.invoke(enteredPassword) } else { - if (sp.contains(preference)) { - sp.remove(preference) + if (preferences.getIfExists(preference) != null) { + preferences.remove(preference) val msg = if (pinInput) app.aaps.core.ui.R.string.pin_cleared else app.aaps.core.ui.R.string.password_cleared ToastUtils.graphicalToast(context, context.getString(msg), app.aaps.core.ui.R.drawable.ic_toast_delete_confirm) clear?.invoke() @@ -163,7 +164,7 @@ class PasswordCheckImpl @Inject constructor( */ @SuppressLint("InflateParams") override fun queryAnyPassword( - context: Context, @StringRes labelId: Int, preference: String, @StringRes passwordExplanation: Int?, + context: Context, @StringRes labelId: Int, preference: StringPreferenceKey, @StringRes passwordExplanation: Int?, @StringRes passwordWarning: Int?, ok: ((String) -> Unit)?, cancel: (() -> Unit)? ) { @@ -173,7 +174,7 @@ class PasswordCheckImpl @Inject constructor( passwordExplanation?.let { alertDialogBuilder.setMessage(it) } passwordWarning?.let { - val extraWarning: TextView = promptsView.findViewById(R.id.password_prompt_extra_message) as TextView + val extraWarning: TextView = promptsView.findViewById(R.id.password_prompt_extra_message) extraWarning.text = context.getString(it) extraWarning.visibility = View.VISIBLE } @@ -183,7 +184,7 @@ class PasswordCheckImpl @Inject constructor( userInput2.visibility = View.GONE - userInput.setAutofillHints(View.AUTOFILL_HINT_PASSWORD, "aaps_${preference}") + userInput.setAutofillHints(View.AUTOFILL_HINT_PASSWORD, "aaps_${preference.key}") userInput.importantForAutofill = View.IMPORTANT_FOR_AUTOFILL_YES fun validatePassword() { diff --git a/implementation/src/main/kotlin/app/aaps/implementation/protection/ProtectionCheckImpl.kt b/implementation/src/main/kotlin/app/aaps/implementation/protection/ProtectionCheckImpl.kt index 91d058523d5..6305b974aa1 100644 --- a/implementation/src/main/kotlin/app/aaps/implementation/protection/ProtectionCheckImpl.kt +++ b/implementation/src/main/kotlin/app/aaps/implementation/protection/ProtectionCheckImpl.kt @@ -4,18 +4,16 @@ import androidx.annotation.UiThread import androidx.fragment.app.FragmentActivity import app.aaps.core.interfaces.protection.PasswordCheck import app.aaps.core.interfaces.protection.ProtectionCheck -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.keys.IntKey -import app.aaps.core.keys.Preferences import app.aaps.core.keys.StringKey +import app.aaps.core.keys.interfaces.Preferences import dagger.Reusable import java.util.concurrent.TimeUnit import javax.inject.Inject @Reusable class ProtectionCheckImpl @Inject constructor( - private val sp: SP, private val preferences: Preferences, private val passwordCheck: PasswordCheck, private val dateUtil: DateUtil @@ -24,21 +22,21 @@ class ProtectionCheckImpl @Inject constructor( private var lastAuthorization = mutableListOf(0L, 0L, 0L) private val passwordsResourceIDs = listOf( - StringKey.ProtectionSettingsPassword.key, - StringKey.ProtectionApplicationPassword.key, - StringKey.ProtectionBolusPassword.key + StringKey.ProtectionSettingsPassword, + StringKey.ProtectionApplicationPassword, + StringKey.ProtectionBolusPassword ) private val pinsResourceIDs = listOf( - StringKey.ProtectionSettingsPin.key, - StringKey.ProtectionApplicationPin.key, - StringKey.ProtectionBolusPin.key + StringKey.ProtectionSettingsPin, + StringKey.ProtectionApplicationPin, + StringKey.ProtectionBolusPin ) private val protectionTypeResourceIDs = listOf( - IntKey.ProtectionTypeSettings.key, - IntKey.ProtectionTypeApplication.key, - IntKey.ProtectionTypeBolus.key + IntKey.ProtectionTypeSettings, + IntKey.ProtectionTypeApplication, + IntKey.ProtectionTypeBolus ) private val titlePassResourceIDs = listOf( @@ -57,12 +55,12 @@ class ProtectionCheckImpl @Inject constructor( if (activeSession(protection)) { return false } - return when (ProtectionCheck.ProtectionType.entries[sp.getInt(protectionTypeResourceIDs[protection.ordinal], ProtectionCheck.ProtectionType.NONE.ordinal)]) { + return when (ProtectionCheck.ProtectionType.entries[preferences.get(protectionTypeResourceIDs[protection.ordinal])]) { ProtectionCheck.ProtectionType.NONE -> false ProtectionCheck.ProtectionType.BIOMETRIC -> true ProtectionCheck.ProtectionType.MASTER_PASSWORD -> preferences.get(StringKey.ProtectionMasterPassword) != "" - ProtectionCheck.ProtectionType.CUSTOM_PASSWORD -> sp.getString(passwordsResourceIDs[protection.ordinal], "") != "" - ProtectionCheck.ProtectionType.CUSTOM_PIN -> sp.getString(pinsResourceIDs[protection.ordinal], "") != "" + ProtectionCheck.ProtectionType.CUSTOM_PASSWORD -> preferences.get(passwordsResourceIDs[protection.ordinal]) != "" + ProtectionCheck.ProtectionType.CUSTOM_PIN -> preferences.get(pinsResourceIDs[protection.ordinal]) != "" } } @@ -91,7 +89,7 @@ class ProtectionCheckImpl @Inject constructor( return } - when (ProtectionCheck.ProtectionType.entries[sp.getInt(protectionTypeResourceIDs[protection.ordinal], ProtectionCheck.ProtectionType.NONE.ordinal)]) { + when (ProtectionCheck.ProtectionType.entries[preferences.get(protectionTypeResourceIDs[protection.ordinal])]) { ProtectionCheck.ProtectionType.NONE -> ok?.run() @@ -102,7 +100,7 @@ class ProtectionCheckImpl @Inject constructor( passwordCheck.queryPassword( activity, app.aaps.core.ui.R.string.master_password, - StringKey.ProtectionMasterPassword.key, + StringKey.ProtectionMasterPassword, { onOk(protection); ok?.run() }, { cancel?.run() }, { fail?.run() }) diff --git a/implementation/src/main/kotlin/app/aaps/implementation/pump/DetailedBolusInfoStorageImpl.kt b/implementation/src/main/kotlin/app/aaps/implementation/pump/DetailedBolusInfoStorageImpl.kt index b45131bff51..37b9d2601dd 100644 --- a/implementation/src/main/kotlin/app/aaps/implementation/pump/DetailedBolusInfoStorageImpl.kt +++ b/implementation/src/main/kotlin/app/aaps/implementation/pump/DetailedBolusInfoStorageImpl.kt @@ -6,8 +6,8 @@ import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.pump.DetailedBolusInfo import app.aaps.core.interfaces.pump.DetailedBolusInfoStorage import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.sharedPreferences.SP -import app.aaps.implementation.R +import app.aaps.core.keys.StringNonKey +import app.aaps.core.keys.interfaces.Preferences import com.google.gson.Gson import com.google.gson.reflect.TypeToken import javax.inject.Inject @@ -17,7 +17,7 @@ import kotlin.math.abs @Singleton class DetailedBolusInfoStorageImpl @Inject constructor( val aapsLogger: AAPSLogger, - val sp: SP, + val preferences: Preferences, val rh: ResourceHelper ) : DetailedBolusInfoStorage { @@ -75,11 +75,11 @@ class DetailedBolusInfoStorageImpl @Inject constructor( lastTwoEntries = ArrayList(store.subList(store.size - 2, store.size)) } val jsonString = Gson().toJson(lastTwoEntries) - sp.putString(rh.gs(R.string.key_bolus_storage), jsonString) + preferences.put(StringNonKey.BolusInfoStorage, jsonString) } private fun loadStore(): ArrayList { - val jsonString = sp.getString(rh.gs(R.string.key_bolus_storage), "") + val jsonString = preferences.get(StringNonKey.BolusInfoStorage) return if (jsonString.isNotEmpty()) { val type = object : TypeToken>() {}.type Gson().fromJson(jsonString, type) diff --git a/implementation/src/main/kotlin/app/aaps/implementation/pump/PumpSyncImplementation.kt b/implementation/src/main/kotlin/app/aaps/implementation/pump/PumpSyncImplementation.kt index 7248c179709..3748ef1ff94 100644 --- a/implementation/src/main/kotlin/app/aaps/implementation/pump/PumpSyncImplementation.kt +++ b/implementation/src/main/kotlin/app/aaps/implementation/pump/PumpSyncImplementation.kt @@ -24,8 +24,10 @@ import app.aaps.core.interfaces.pump.VirtualPump import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventNewNotification -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.DateUtil +import app.aaps.core.keys.LongNonKey +import app.aaps.core.keys.StringNonKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.extensions.asAnnouncement import app.aaps.core.ui.R import app.aaps.implementation.extensions.toUeSource @@ -36,7 +38,7 @@ import javax.inject.Inject class PumpSyncImplementation @Inject constructor( private val aapsLogger: AAPSLogger, private val dateUtil: DateUtil, - private val sp: SP, + private val preferences: Preferences, private val rxBus: RxBus, private val rh: ResourceHelper, private val profileFunction: ProfileFunction, @@ -55,14 +57,14 @@ class PumpSyncImplementation @Inject constructor( syncStopExtendedBolusWithPumpId(dateUtil.now(), dateUtil.now(), it.pumpType, it.pumpSerial) } } - sp.remove(app.aaps.core.utils.R.string.key_active_pump_type) - sp.remove(app.aaps.core.utils.R.string.key_active_pump_serial_number) - sp.remove(app.aaps.core.utils.R.string.key_active_pump_change_timestamp) + preferences.remove(StringNonKey.ActivePumpType) + preferences.remove(StringNonKey.ActivePumpSerialNumber) + preferences.remove(LongNonKey.ActivePumpChangeTimestamp) } override fun verifyPumpIdentification(type: PumpType, serialNumber: String): Boolean { - val storedType = sp.getString(app.aaps.core.utils.R.string.key_active_pump_type, "") - val storedSerial = sp.getString(app.aaps.core.utils.R.string.key_active_pump_serial_number, "") + val storedType = preferences.get(StringNonKey.ActivePumpType) + val storedSerial = preferences.get(StringNonKey.ActivePumpSerialNumber) if (activePlugin.activePump is VirtualPump) return true if (type.description == storedType && serialNumber == storedSerial) return true aapsLogger.debug(LTag.PUMP, "verifyPumpIdentification failed for $type $serialNumber") @@ -78,16 +80,16 @@ class PumpSyncImplementation @Inject constructor( * @return true if data is allowed */ private fun confirmActivePump(timestamp: Long, type: PumpType, serialNumber: String, showNotification: Boolean = true): Boolean { - val storedType = sp.getString(app.aaps.core.utils.R.string.key_active_pump_type, "") - val storedSerial = sp.getString(app.aaps.core.utils.R.string.key_active_pump_serial_number, "") - val storedTimestamp = sp.getLong(app.aaps.core.utils.R.string.key_active_pump_change_timestamp, 0L) + val storedType = preferences.get(StringNonKey.ActivePumpType) + val storedSerial = preferences.get(StringNonKey.ActivePumpSerialNumber) + val storedTimestamp = preferences.get(LongNonKey.ActivePumpChangeTimestamp) // If no value stored assume we start using new pump from now if (storedType.isEmpty() || storedSerial.isEmpty()) { aapsLogger.debug(LTag.PUMP, "Registering new pump ${type.description} $serialNumber") - sp.putString(app.aaps.core.utils.R.string.key_active_pump_type, type.description) - sp.putString(app.aaps.core.utils.R.string.key_active_pump_serial_number, serialNumber) - sp.putLong(app.aaps.core.utils.R.string.key_active_pump_change_timestamp, dateUtil.now()) // allow only data newer than register time (ie. ignore older history) + preferences.put(StringNonKey.ActivePumpType, type.description) + preferences.put(StringNonKey.ActivePumpSerialNumber, serialNumber) + preferences.put(LongNonKey.ActivePumpChangeTimestamp, dateUtil.now()) // allow only data newer than register time (ie. ignore older history) return timestamp > dateUtil.now() - T.mins(1).msecs() // allow first record to be 1 min old } @@ -144,7 +146,7 @@ class PumpSyncImplementation @Inject constructor( ) }, profile = profileFunction.getProfile(), - serialNumber = sp.getString(app.aaps.core.utils.R.string.key_active_pump_serial_number, "") + serialNumber = preferences.get(StringNonKey.ActivePumpSerialNumber) ) } diff --git a/implementation/src/main/kotlin/app/aaps/implementation/queue/CommandQueueImplementation.kt b/implementation/src/main/kotlin/app/aaps/implementation/queue/CommandQueueImplementation.kt index 6985708267a..cf30656d2bc 100644 --- a/implementation/src/main/kotlin/app/aaps/implementation/queue/CommandQueueImplementation.kt +++ b/implementation/src/main/kotlin/app/aaps/implementation/queue/CommandQueueImplementation.kt @@ -44,12 +44,11 @@ import app.aaps.core.interfaces.rx.events.EventMobileToWear import app.aaps.core.interfaces.rx.events.EventNewNotification import app.aaps.core.interfaces.rx.events.EventProfileSwitchChanged import app.aaps.core.interfaces.rx.weardata.EventData -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.DecimalFormatter import app.aaps.core.interfaces.utils.fabric.FabricPrivacy -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.constraints.ConstraintObject import app.aaps.core.objects.extensions.getCustomizedName import app.aaps.core.objects.profile.ProfileSealed @@ -95,7 +94,6 @@ class CommandQueueImplementation @Inject constructor( private val profileFunction: ProfileFunction, private val activePlugin: ActivePlugin, private val context: Context, - private val sp: SP, private val preferences: Preferences, private val config: Config, private val dateUtil: DateUtil, @@ -251,7 +249,7 @@ class CommandQueueImplementation @Inject constructor( aapsLogger.debug(LTag.PUMPQUEUE, "Starting new queue") val tempCommandQueue = CommandQueueImplementation( injector, aapsLogger, rxBus, aapsSchedulers, rh, - constraintChecker, profileFunction, activePlugin, context, sp, preferences, + constraintChecker, profileFunction, activePlugin, context, preferences, config, dateUtil, fabricPrivacy, androidPermission, uiInteraction, persistenceLayer, decimalFormatter, instantiator, CommandQueueName("CommandQueueIndependentInstance"), workManager ) tempCommandQueue.readStatus(reason, callback) diff --git a/implementation/src/main/kotlin/app/aaps/implementation/queue/QueueWorker.kt b/implementation/src/main/kotlin/app/aaps/implementation/queue/QueueWorker.kt index 78d971a731a..4b9cfbcacbf 100644 --- a/implementation/src/main/kotlin/app/aaps/implementation/queue/QueueWorker.kt +++ b/implementation/src/main/kotlin/app/aaps/implementation/queue/QueueWorker.kt @@ -19,9 +19,9 @@ import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventDismissBolusProgressIfRunning import app.aaps.core.interfaces.rx.events.EventPumpStatusChanged import app.aaps.core.interfaces.rx.events.EventQueueChanged -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.keys.BooleanKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.LongNonKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.workflow.LoggingWorker import app.aaps.core.ui.R import app.aaps.core.utils.extensions.safeDisable @@ -39,7 +39,6 @@ class QueueWorker internal constructor( @Inject lateinit var rxBus: RxBus @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var rh: ResourceHelper - @Inject lateinit var sp: SP @Inject lateinit var preferences: Preferences @Inject lateinit var androidPermission: AndroidPermission @Inject lateinit var config: Config @@ -74,12 +73,12 @@ class QueueWorker internal constructor( //BLUETOOTH-WATCHDOG var watchdog = preferences.get(BooleanKey.PumpBtWatchdog) - val lastWatchdog = sp.getLong(app.aaps.core.utils.R.string.key_btwatchdog_lastbark, 0L) + val lastWatchdog = preferences.get(LongNonKey.BtWatchdogLastBark) watchdog = watchdog && System.currentTimeMillis() - lastWatchdog > Constants.MIN_WATCHDOG_INTERVAL_IN_SECONDS * 1000 if (watchdog) { aapsLogger.debug(LTag.PUMPQUEUE, "BT watchdog - toggling the phone bluetooth") //write time - sp.putLong(app.aaps.core.utils.R.string.key_btwatchdog_lastbark, System.currentTimeMillis()) + preferences.put(LongNonKey.BtWatchdogLastBark, System.currentTimeMillis()) //toggle BT pump.disconnect("watchdog") SystemClock.sleep(1000) diff --git a/implementation/src/main/kotlin/app/aaps/implementation/queue/commands/CommandSMBBolus.kt b/implementation/src/main/kotlin/app/aaps/implementation/queue/commands/CommandSMBBolus.kt index 19ce57705cd..824edc58597 100644 --- a/implementation/src/main/kotlin/app/aaps/implementation/queue/commands/CommandSMBBolus.kt +++ b/implementation/src/main/kotlin/app/aaps/implementation/queue/commands/CommandSMBBolus.kt @@ -13,7 +13,7 @@ import app.aaps.core.interfaces.queue.Command import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.keys.IntKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import dagger.android.HasAndroidInjector import javax.inject.Inject diff --git a/implementation/src/main/kotlin/app/aaps/implementation/sharedPreferences/PreferencesImpl.kt b/implementation/src/main/kotlin/app/aaps/implementation/sharedPreferences/PreferencesImpl.kt index 702945a375d..d8d7cf95e20 100644 --- a/implementation/src/main/kotlin/app/aaps/implementation/sharedPreferences/PreferencesImpl.kt +++ b/implementation/src/main/kotlin/app/aaps/implementation/sharedPreferences/PreferencesImpl.kt @@ -8,24 +8,42 @@ import app.aaps.core.interfaces.profile.ProfileUtil import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.HardLimits +import app.aaps.core.interfaces.utils.SafeParse +import app.aaps.core.keys.BooleanComposedKey import app.aaps.core.keys.BooleanKey -import app.aaps.core.keys.BooleanPreferenceKey +import app.aaps.core.keys.BooleanNonKey import app.aaps.core.keys.DoubleKey -import app.aaps.core.keys.DoublePreferenceKey +import app.aaps.core.keys.IntComposedKey import app.aaps.core.keys.IntKey -import app.aaps.core.keys.IntPreferenceKey +import app.aaps.core.keys.IntNonKey import app.aaps.core.keys.IntentKey -import app.aaps.core.keys.LongPreferenceKey -import app.aaps.core.keys.NonPreferenceKey -import app.aaps.core.keys.PreferenceKey -import app.aaps.core.keys.Preferences -import app.aaps.core.keys.String2PreferenceKey +import app.aaps.core.keys.LongComposedKey +import app.aaps.core.keys.LongNonKey import app.aaps.core.keys.StringKey -import app.aaps.core.keys.StringNonPreferenceKey -import app.aaps.core.keys.StringPreferenceKey +import app.aaps.core.keys.StringNonKey import app.aaps.core.keys.UnitDoubleKey -import app.aaps.core.keys.UnitDoublePreferenceKey +import app.aaps.core.keys.interfaces.BooleanComposedNonPreferenceKey +import app.aaps.core.keys.interfaces.BooleanNonPreferenceKey +import app.aaps.core.keys.interfaces.BooleanPreferenceKey +import app.aaps.core.keys.interfaces.ComposedKey +import app.aaps.core.keys.interfaces.DoubleComposedNonPreferenceKey +import app.aaps.core.keys.interfaces.DoubleNonPreferenceKey +import app.aaps.core.keys.interfaces.DoublePreferenceKey +import app.aaps.core.keys.interfaces.IntComposedNonPreferenceKey +import app.aaps.core.keys.interfaces.IntNonPreferenceKey +import app.aaps.core.keys.interfaces.IntPreferenceKey +import app.aaps.core.keys.interfaces.LongComposedNonPreferenceKey +import app.aaps.core.keys.interfaces.LongNonPreferenceKey +import app.aaps.core.keys.interfaces.LongPreferenceKey +import app.aaps.core.keys.interfaces.NonPreferenceKey +import app.aaps.core.keys.interfaces.PreferenceKey +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.core.keys.interfaces.StringComposedNonPreferenceKey +import app.aaps.core.keys.interfaces.StringNonPreferenceKey +import app.aaps.core.keys.interfaces.StringPreferenceKey +import app.aaps.core.keys.interfaces.UnitDoublePreferenceKey import dagger.Lazy +import java.util.Locale import javax.inject.Inject import javax.inject.Singleton import kotlin.math.max @@ -49,12 +67,19 @@ class PreferencesImpl @Inject constructor( private val prefsList: MutableList> = mutableListOf( + BooleanComposedKey::class.java, BooleanKey::class.java, - IntKey::class.java, + BooleanNonKey::class.java, DoubleKey::class.java, - UnitDoubleKey::class.java, - StringKey::class.java, IntentKey::class.java, + IntKey::class.java, + IntComposedKey::class.java, + IntNonKey::class.java, + LongComposedKey::class.java, + LongNonKey::class.java, + StringKey::class.java, + StringNonKey::class.java, + UnitDoubleKey::class.java, ) private fun isHidden(key: PreferenceKey): Boolean = @@ -63,19 +88,22 @@ class PreferencesImpl @Inject constructor( else if (pumpControlMode && key.showInPumpControlMode == false) true else false - override fun get(key: BooleanPreferenceKey): Boolean = - if (!config.isEngineeringMode() && key.engineeringModeOnly) key.defaultValue - else if (simpleMode && key.defaultedBySM) calculatedDefaultValue(key) - else if (key.calculatedDefaultValue && isHidden(key)) calculatedDefaultValue(key) - else sp.getBoolean(key.key, calculatedDefaultValue(key)) + override fun get(key: BooleanNonPreferenceKey): Boolean = + sp.getBoolean(key.key, key.defaultValue) - override fun getIfExists(key: BooleanPreferenceKey): Boolean? = + override fun getIfExists(key: BooleanNonPreferenceKey): Boolean? = if (sp.contains(key.key)) sp.getBoolean(key.key, key.defaultValue) else null - override fun put(key: BooleanPreferenceKey, value: Boolean) { + override fun put(key: BooleanNonPreferenceKey, value: Boolean) { sp.putBoolean(key.key, value) } + override fun get(key: BooleanPreferenceKey): Boolean = + if (!config.isEngineeringMode() && key.engineeringModeOnly) key.defaultValue + else if (simpleMode && key.defaultedBySM) calculatedDefaultValue(key) + else if (key.calculatedDefaultValue && isHidden(key)) calculatedDefaultValue(key) + else sp.getBoolean(key.key, calculatedDefaultValue(key)) + override fun get(key: StringNonPreferenceKey): String = sp.getString(key.key, key.defaultValue) @@ -90,16 +118,8 @@ class PreferencesImpl @Inject constructor( sp.putString(key.key, value) } - override fun get(key: String2PreferenceKey, appendix: String): String = - if (simpleMode && key.defaultedBySM) key.defaultValue - else sp.getString(key.key + key.delimiter + appendix, key.defaultValue) - - override fun getIfExists(key: String2PreferenceKey, appendix: String): String? = - if (sp.contains(key.key + key.delimiter + appendix)) sp.getString(key.key + key.delimiter + appendix, key.defaultValue) else null - - override fun put(key: String2PreferenceKey, appendix: String, value: String) { - sp.putString(key.key + key.delimiter + appendix, value) - } + override fun get(key: DoubleNonPreferenceKey): Double = + sp.getDouble(key.key, key.defaultValue) override fun get(key: DoublePreferenceKey): Double = if (simpleMode && key.calculatedBySM) calculatePreference(key) @@ -109,10 +129,20 @@ class PreferencesImpl @Inject constructor( override fun getIfExists(key: DoublePreferenceKey): Double? = if (sp.contains(key.key)) sp.getDouble(key.key, key.defaultValue) else null - override fun put(key: DoublePreferenceKey, value: Double) { + override fun put(key: DoubleNonPreferenceKey, value: Double) { sp.putDouble(key.key, value) } + override fun get(key: DoubleComposedNonPreferenceKey, vararg arguments: Any): Double = + sp.getDouble(key.composeKey(*arguments), key.defaultValue) + + override fun getIfExists(key: DoubleComposedNonPreferenceKey, vararg arguments: Any): Double? = + if (sp.contains(key.composeKey(*arguments))) sp.getDouble(key.composeKey(*arguments), key.defaultValue) else null + + override fun put(key: DoubleComposedNonPreferenceKey, vararg arguments: Any, value: Double) { + sp.putDouble(key.composeKey(*arguments), value) + } + override fun get(key: UnitDoublePreferenceKey): Double = if (simpleMode && key.defaultedBySM) key.defaultValue else profileUtil.get().valueInCurrentUnitsDetect(sp.getDouble(key.key, key.defaultValue)) @@ -124,17 +154,45 @@ class PreferencesImpl @Inject constructor( sp.putDouble(key.key, value) } + override fun get(key: IntNonPreferenceKey): Int = + sp.getInt(key.key, key.defaultValue) + + override fun getIfExists(key: IntNonPreferenceKey): Int? = + if (sp.contains(key.key)) sp.getInt(key.key, key.defaultValue) else null + + override fun put(key: IntNonPreferenceKey, value: Int) { + sp.putInt(key.key, value) + } + + override fun inc(key: IntNonPreferenceKey) { + sp.incInt(key.key) + } + override fun get(key: IntPreferenceKey): Int = if (!config.isEngineeringMode() && key.engineeringModeOnly) key.defaultValue else if (simpleMode && key.defaultedBySM) calculatedDefaultValue(key) else if (key.calculatedDefaultValue && isHidden(key)) calculatedDefaultValue(key) else sp.getInt(key.key, calculatedDefaultValue(key)) - override fun getIfExists(key: IntPreferenceKey): Int? = - if (sp.contains(key.key)) sp.getInt(key.key, calculatedDefaultValue(key)) else null + override fun get(key: IntComposedNonPreferenceKey, vararg arguments: Any): Int = + sp.getInt(key.composeKey(*arguments), key.defaultValue) - override fun put(key: IntPreferenceKey, value: Int) { - sp.putInt(key.key, value) + override fun put(key: IntComposedNonPreferenceKey, vararg arguments: Any, value: Int) { + sp.putInt(key.composeKey(*arguments), value) + } + + override fun get(key: LongNonPreferenceKey): Long = + sp.getLong(key.key, key.defaultValue) + + override fun inc(key: LongNonPreferenceKey) { + sp.incLong(key.key) + } + + override fun getIfExists(key: LongNonPreferenceKey): Long? = + if (sp.contains(key.key)) sp.getLong(key.key, key.defaultValue) else null + + override fun put(key: LongNonPreferenceKey, value: Long) { + sp.putLong(key.key, value) } override fun get(key: LongPreferenceKey): Long = @@ -143,29 +201,35 @@ class PreferencesImpl @Inject constructor( else if (key.calculatedDefaultValue && isHidden(key)) calculatedDefaultValue(key) else sp.getLong(key.key, calculatedDefaultValue(key)) - override fun getIfExists(key: LongPreferenceKey): Long? = - if (sp.contains(key.key)) sp.getLong(key.key, calculatedDefaultValue(key)) else null + override fun remove(key: NonPreferenceKey) { + sp.remove(key.key) + } - override fun put(key: LongPreferenceKey, value: Long) { - sp.putLong(key.key, value) + override fun get(key: LongComposedNonPreferenceKey, vararg arguments: Any): Long = + sp.getLong(key.composeKey(*arguments), key.defaultValue) + + override fun getIfExists(key: LongComposedNonPreferenceKey, vararg arguments: Any): Long? = + if (sp.contains(key.composeKey(*arguments))) sp.getLong(key.composeKey(*arguments), key.defaultValue) else null + + override fun put(key: LongComposedNonPreferenceKey, vararg arguments: Any, value: Long) { + sp.putLong(key.composeKey(*arguments), value) } - override fun remove(key: NonPreferenceKey) { - sp.remove(key.key) + override fun remove(key: LongComposedNonPreferenceKey, vararg arguments: Any) { + sp.remove(String.format(Locale.ENGLISH, key.key, arguments)) } - override fun remove(key: String2PreferenceKey, appendix: String) { - sp.remove(key.key + key.delimiter + appendix) + override fun remove(key: StringComposedNonPreferenceKey, vararg arguments: Any) { + sp.remove(String.format(Locale.ENGLISH, key.key, arguments)) } override fun isUnitDependent(key: String): Boolean = UnitDoubleKey.entries.any { it.key == key } - override fun get(key: String): NonPreferenceKey = + override fun get(key: String): NonPreferenceKey? = prefsList .flatMap { it.enumConstants!!.asIterable() } .find { it.key == key } - ?: error("Key $key not found") override fun getIfExists(key: String): NonPreferenceKey? = prefsList @@ -184,10 +248,59 @@ class PreferencesImpl @Inject constructor( } } + override fun get(key: BooleanComposedNonPreferenceKey, vararg arguments: Any): Boolean = + sp.getBoolean(key.composeKey(*arguments), key.defaultValue) + + override fun get(key: BooleanComposedNonPreferenceKey, vararg arguments: Any, defaultValue: Boolean): Boolean = + sp.getBoolean(key.composeKey(*arguments), defaultValue) + + override fun getIfExists(key: BooleanComposedNonPreferenceKey, vararg arguments: Any): Boolean? = + if (sp.contains(key.composeKey(*arguments))) sp.getBoolean(key.composeKey(*arguments), key.defaultValue) else null + + override fun put(key: BooleanComposedNonPreferenceKey, vararg arguments: Any, value: Boolean) { + sp.putBoolean(key.composeKey(*arguments), value) + } + + override fun get(key: StringComposedNonPreferenceKey, vararg arguments: Any): String = + sp.getString(key.composeKey(*arguments), key.defaultValue) + + override fun getIfExists(key: StringComposedNonPreferenceKey, vararg arguments: Any): String? = + if (sp.contains(key.composeKey(*arguments))) sp.getString(key.composeKey(*arguments), key.defaultValue) else null + + override fun put(key: StringComposedNonPreferenceKey, vararg arguments: Any, value: String) { + sp.putString(key.composeKey(*arguments), value) + } + override fun registerPreferences(clazz: Class) { if (clazz !in prefsList) prefsList.add(clazz) } + override fun allMatchingStrings(key: ComposedKey): List = + mutableListOf().also { + assert(key.format == "%s") + val keys: Map = sp.getAll() + for ((singleKey, _) in keys) + if (singleKey.startsWith(key.key)) it.add(singleKey.split(key.key)[1]) + } + + override fun allMatchingInts(key: ComposedKey): List = + mutableListOf().also { + assert(key.format == "%d") + val keys: Map = sp.getAll() + for ((singleKey, _) in keys) + if (singleKey.startsWith(key.key)) it.add(SafeParse.stringToInt(singleKey.split(key.key)[1])) + } + + override fun isExportableKey(key: String): Boolean { + prefsList + .flatMap { it.enumConstants!!.asIterable() } + .forEach { + if (it.key == key && it.exportable) return true + if (it is ComposedKey && key.startsWith(it.key) && it.exportable) return true + } + return false + } + private fun calculatedDefaultValue(key: IntPreferenceKey): Int = if (key.calculatedDefaultValue) when (key) { diff --git a/implementation/src/main/kotlin/app/aaps/implementation/utils/HardLimitsImpl.kt b/implementation/src/main/kotlin/app/aaps/implementation/utils/HardLimitsImpl.kt index 5dd01bc36ca..f9e61db619a 100644 --- a/implementation/src/main/kotlin/app/aaps/implementation/utils/HardLimitsImpl.kt +++ b/implementation/src/main/kotlin/app/aaps/implementation/utils/HardLimitsImpl.kt @@ -11,8 +11,8 @@ import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.HardLimits -import app.aaps.core.keys.Preferences import app.aaps.core.keys.StringKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.extensions.asAnnouncement import dagger.Reusable import io.reactivex.rxjava3.disposables.CompositeDisposable diff --git a/implementation/src/main/kotlin/app/aaps/implementation/utils/fabric/FabricPrivacyImpl.kt b/implementation/src/main/kotlin/app/aaps/implementation/utils/fabric/FabricPrivacyImpl.kt index e52a57efb26..fc072c52d73 100644 --- a/implementation/src/main/kotlin/app/aaps/implementation/utils/fabric/FabricPrivacyImpl.kt +++ b/implementation/src/main/kotlin/app/aaps/implementation/utils/fabric/FabricPrivacyImpl.kt @@ -1,10 +1,10 @@ package app.aaps.implementation.utils.fabric +import android.content.SharedPreferences import android.os.Bundle import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.rx.weardata.EventData -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.fabric.FabricPrivacy import app.aaps.core.keys.BooleanKey import com.google.firebase.analytics.FirebaseAnalytics @@ -25,7 +25,7 @@ import javax.inject.Inject @Reusable class FabricPrivacyImpl @Inject constructor( private val aapsLogger: AAPSLogger, - private val sp: SP + private val sharedPreferences: SharedPreferences // Injecting Preferences is causing circular dependencies ) : FabricPrivacy { private val firebaseAnalytics: FirebaseAnalytics = Firebase.analytics @@ -99,7 +99,7 @@ class FabricPrivacyImpl @Inject constructor( } override fun fabricEnabled(): Boolean { - return sp.getBoolean(BooleanKey.MaintenanceEnableFabric.key, BooleanKey.MaintenanceEnableFabric.defaultValue) + return sharedPreferences.getBoolean(BooleanKey.MaintenanceEnableFabric.key, true) } override fun logWearException(wearException: EventData.WearException) { diff --git a/implementation/src/main/res/values/strings.xml b/implementation/src/main/res/values/strings.xml index f930f96ac41..0d087974b54 100644 --- a/implementation/src/main/res/values/strings.xml +++ b/implementation/src/main/res/values/strings.xml @@ -1,7 +1,5 @@ - key_bolus_storage - Command is executed right now Basal value below minimum. Profile not set! diff --git a/implementation/src/test/kotlin/app/aaps/implementation/profile/ProfileUtilImplTest.kt b/implementation/src/test/kotlin/app/aaps/implementation/profile/ProfileUtilImplTest.kt index 6ffaf39a818..0b17917e810 100644 --- a/implementation/src/test/kotlin/app/aaps/implementation/profile/ProfileUtilImplTest.kt +++ b/implementation/src/test/kotlin/app/aaps/implementation/profile/ProfileUtilImplTest.kt @@ -5,7 +5,7 @@ import app.aaps.core.data.model.GlucoseUnit import app.aaps.core.data.model.SourceSensor import app.aaps.core.data.model.TrendArrow import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.implementation.utils.DecimalFormatterImpl import app.aaps.shared.tests.TestBase import com.google.common.truth.Truth.assertThat diff --git a/implementation/src/test/kotlin/app/aaps/implementation/protection/ExportPasswordDataStoreImplTest.kt b/implementation/src/test/kotlin/app/aaps/implementation/protection/ExportPasswordDataStoreImplTest.kt index a781d6ac729..08824f3565d 100644 --- a/implementation/src/test/kotlin/app/aaps/implementation/protection/ExportPasswordDataStoreImplTest.kt +++ b/implementation/src/test/kotlin/app/aaps/implementation/protection/ExportPasswordDataStoreImplTest.kt @@ -11,17 +11,17 @@ class ExportPasswordDataStoreImplTest : TestBaseWithProfile() { private val somePassword = "somePassword" val sut: ExportPasswordDataStoreImpl by lazy { - ExportPasswordDataStoreImpl(aapsLogger, sp, config) + ExportPasswordDataStoreImpl(aapsLogger, preferences, config) } @Test fun exportPasswordStoreEnabled() { // When disabled - `when`(sp.getBoolean(BooleanKey.MaintenanceEnableExportSettingsAutomation.key, false)).thenReturn(false) + `when`(preferences.get(BooleanKey.MaintenanceEnableExportSettingsAutomation)).thenReturn(false) assertFalse(sut.exportPasswordStoreEnabled()) // When enabled - `when`(sp.getBoolean(BooleanKey.MaintenanceEnableExportSettingsAutomation.key, false)).thenReturn(true) + `when`(preferences.get(BooleanKey.MaintenanceEnableExportSettingsAutomation)).thenReturn(true) assertTrue(sut.exportPasswordStoreEnabled()) assertTrue(sut.clearPasswordDataStore(context).isEmpty()) @@ -32,19 +32,19 @@ class ExportPasswordDataStoreImplTest : TestBaseWithProfile() { @Test fun clearPasswordDataStore() { - `when`(sp.getBoolean(BooleanKey.MaintenanceEnableExportSettingsAutomation.key, false)).thenReturn(false) + `when`(preferences.get(BooleanKey.MaintenanceEnableExportSettingsAutomation)).thenReturn(false) assertTrue(sut.clearPasswordDataStore(context).isEmpty()) } @Test fun putPasswordToDataStore() { - `when`(sp.getBoolean(BooleanKey.MaintenanceEnableExportSettingsAutomation.key, false)).thenReturn(false) + `when`(preferences.get(BooleanKey.MaintenanceEnableExportSettingsAutomation)).thenReturn(false) assertTrue(sut.putPasswordToDataStore(context, somePassword) == somePassword) } @Test fun getPasswordFromDataStore() { - `when`(sp.getBoolean(BooleanKey.MaintenanceEnableExportSettingsAutomation.key, false)).thenReturn(false) + `when`(preferences.get(BooleanKey.MaintenanceEnableExportSettingsAutomation)).thenReturn(false) assertTrue(sut.getPasswordFromDataStore(context) == Triple("", true, true)) } } \ No newline at end of file diff --git a/implementation/src/test/kotlin/app/aaps/implementation/pump/DetailedBolusInfoStorageTest.kt b/implementation/src/test/kotlin/app/aaps/implementation/pump/DetailedBolusInfoStorageTest.kt index 6d49756754b..cca9125db75 100644 --- a/implementation/src/test/kotlin/app/aaps/implementation/pump/DetailedBolusInfoStorageTest.kt +++ b/implementation/src/test/kotlin/app/aaps/implementation/pump/DetailedBolusInfoStorageTest.kt @@ -2,8 +2,8 @@ package app.aaps.implementation.pump import app.aaps.core.interfaces.pump.DetailedBolusInfo import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.sharedPreferences.SP -import app.aaps.implementation.R +import app.aaps.core.keys.StringNonKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.shared.tests.TestBase import com.google.common.truth.Truth.assertThat import org.junit.jupiter.api.BeforeEach @@ -13,7 +13,7 @@ import org.mockito.Mockito class DetailedBolusInfoStorageTest : TestBase() { - @Mock lateinit var sp: SP + @Mock lateinit var preferences: Preferences @Mock lateinit var rh: ResourceHelper private val info1 = DetailedBolusInfo() @@ -33,8 +33,8 @@ class DetailedBolusInfoStorageTest : TestBase() { @BeforeEach fun prepare() { - Mockito.`when`(sp.getString(rh.gs(R.string.key_bolus_storage), "")).thenReturn("") - detailedBolusInfoStorage = DetailedBolusInfoStorageImpl(aapsLogger, sp, rh) + Mockito.`when`(preferences.get(StringNonKey.BolusInfoStorage)).thenReturn("") + detailedBolusInfoStorage = DetailedBolusInfoStorageImpl(aapsLogger, preferences, rh) } private fun setUp() { diff --git a/implementation/src/test/kotlin/app/aaps/implementation/queue/CommandQueueImplementationTest.kt b/implementation/src/test/kotlin/app/aaps/implementation/queue/CommandQueueImplementationTest.kt index 86c1d0226c4..4016f8626c1 100644 --- a/implementation/src/test/kotlin/app/aaps/implementation/queue/CommandQueueImplementationTest.kt +++ b/implementation/src/test/kotlin/app/aaps/implementation/queue/CommandQueueImplementationTest.kt @@ -25,12 +25,11 @@ import app.aaps.core.interfaces.queue.CustomCommand import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.AapsSchedulers import app.aaps.core.interfaces.rx.bus.RxBus -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.DecimalFormatter import app.aaps.core.interfaces.utils.fabric.FabricPrivacy -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.constraints.ConstraintObject import app.aaps.implementation.queue.commands.CommandBolus import app.aaps.implementation.queue.commands.CommandCancelExtendedBolus @@ -82,7 +81,6 @@ class CommandQueueImplementationTest : TestBaseWithProfile() { profileFunction: ProfileFunction, activePlugin: ActivePlugin, context: Context, - sp: SP, preferences: Preferences, config: Config, dateUtil: DateUtil, @@ -96,7 +94,7 @@ class CommandQueueImplementationTest : TestBaseWithProfile() { workManager: WorkManager ) : CommandQueueImplementation( injector, aapsLogger, rxBus, aapsSchedulers, rh, constraintChecker, profileFunction, - activePlugin, context, sp, preferences, config, dateUtil, fabricPrivacy, androidPermission, + activePlugin, context, preferences, config, dateUtil, fabricPrivacy, androidPermission, uiInteraction, persistenceLayer, decimalFormatter, instantiator, jobName, workManager ) { @@ -179,7 +177,6 @@ class CommandQueueImplementationTest : TestBaseWithProfile() { it.rxBus = rxBus it.activePlugin = activePlugin it.rh = rh - it.sp = sp it.preferences = preferences it.androidPermission = androidPermission it.config = config @@ -193,7 +190,7 @@ class CommandQueueImplementationTest : TestBaseWithProfile() { fun prepare() { commandQueue = CommandQueueMocked( injector, aapsLogger, rxBus, aapsSchedulers, rh, constraintChecker, profileFunction, activePlugin, context, - sp, preferences, config, dateUtil, fabricPrivacy, androidPermission, uiInteraction, persistenceLayer, decimalFormatter, instantiator, jobName, workManager + preferences, config, dateUtil, fabricPrivacy, androidPermission, uiInteraction, persistenceLayer, decimalFormatter, instantiator, jobName, workManager ) testPumpPlugin.pumpDescription.basalMinimumRate = 0.1 testPumpPlugin.connected = true @@ -237,7 +234,7 @@ class CommandQueueImplementationTest : TestBaseWithProfile() { fun commandIsPickedUp() { commandQueue = CommandQueueImplementation( injector, aapsLogger, rxBus, aapsSchedulers, rh, - constraintChecker, profileFunction, activePlugin, context, sp, preferences, + constraintChecker, profileFunction, activePlugin, context, preferences, config, dateUtil, fabricPrivacy, androidPermission, uiInteraction, persistenceLayer, decimalFormatter, instantiator, jobName, workManager ) val handler = mock(Handler::class.java) diff --git a/implementation/src/test/kotlin/app/aaps/implementation/queue/QueueWorkerTest.kt b/implementation/src/test/kotlin/app/aaps/implementation/queue/QueueWorkerTest.kt index 1dd4a55ae7b..f9293896f43 100644 --- a/implementation/src/test/kotlin/app/aaps/implementation/queue/QueueWorkerTest.kt +++ b/implementation/src/test/kotlin/app/aaps/implementation/queue/QueueWorkerTest.kt @@ -48,7 +48,6 @@ class QueueWorkerTest : TestBaseWithProfile() { it.rxBus = rxBus it.activePlugin = activePlugin it.rh = rh - it.sp = sp it.preferences = preferences it.androidPermission = androidPermission it.config = config @@ -63,7 +62,7 @@ class QueueWorkerTest : TestBaseWithProfile() { fun prepare() { commandQueue = CommandQueueImplementation( injector, aapsLogger, rxBus, aapsSchedulers, rh, constraintChecker, - profileFunction, activePlugin, context, sp, preferences, config, dateUtil, fabricPrivacy, androidPermission, + profileFunction, activePlugin, context, preferences, config, dateUtil, fabricPrivacy, androidPermission, uiInteraction, persistenceLayer, decimalFormatter, instantiator, jobName, workManager ) diff --git a/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/autotune/AutotuneCore.kt b/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/autotune/AutotuneCore.kt index 10d50bb9a28..03f435b9392 100644 --- a/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/autotune/AutotuneCore.kt +++ b/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/autotune/AutotuneCore.kt @@ -2,7 +2,7 @@ package app.aaps.plugins.aps.autotune import app.aaps.core.interfaces.utils.Round import app.aaps.core.keys.DoubleKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.utils.Percentile import app.aaps.plugins.aps.autotune.data.ATProfile import app.aaps.plugins.aps.autotune.data.LocalInsulin diff --git a/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/autotune/AutotuneFragment.kt b/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/autotune/AutotuneFragment.kt index 18b64caf415..ff299011338 100644 --- a/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/autotune/AutotuneFragment.kt +++ b/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/autotune/AutotuneFragment.kt @@ -41,7 +41,7 @@ import app.aaps.core.interfaces.utils.SafeParse import app.aaps.core.interfaces.utils.fabric.FabricPrivacy import app.aaps.core.keys.BooleanKey import app.aaps.core.keys.IntKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.profile.ProfileSealed import app.aaps.core.ui.dialogs.OKDialog import app.aaps.core.ui.elements.WeekDay diff --git a/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/autotune/AutotuneIob.kt b/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/autotune/AutotuneIob.kt index 06dee1e62a1..19514cdfa1c 100644 --- a/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/autotune/AutotuneIob.kt +++ b/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/autotune/AutotuneIob.kt @@ -19,7 +19,7 @@ import app.aaps.core.interfaces.profile.ProfileFunction import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.Round import app.aaps.core.keys.BooleanKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.extensions.convertedToAbsolute import app.aaps.core.objects.extensions.durationInMinutes import app.aaps.core.objects.extensions.round diff --git a/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/autotune/AutotunePlugin.kt b/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/autotune/AutotunePlugin.kt index 6bf969dbfb4..f7c56cf6be3 100644 --- a/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/autotune/AutotunePlugin.kt +++ b/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/autotune/AutotunePlugin.kt @@ -20,20 +20,19 @@ import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.logging.UserEntryLogger import app.aaps.core.interfaces.objects.Instantiator import app.aaps.core.interfaces.plugin.ActivePlugin -import app.aaps.core.interfaces.plugin.PluginBase +import app.aaps.core.interfaces.plugin.PluginBaseWithPreferences import app.aaps.core.interfaces.plugin.PluginDescription import app.aaps.core.interfaces.profile.Profile import app.aaps.core.interfaces.profile.ProfileFunction import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventLocalProfileChanged -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.MidnightTime import app.aaps.core.keys.BooleanKey import app.aaps.core.keys.IntKey -import app.aaps.core.keys.Preferences import app.aaps.core.keys.StringKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.extensions.pureProfileFromJson import app.aaps.core.objects.profile.ProfileSealed import app.aaps.core.ui.elements.WeekDay @@ -45,6 +44,7 @@ import app.aaps.plugins.aps.autotune.data.ATProfile import app.aaps.plugins.aps.autotune.data.LocalInsulin import app.aaps.plugins.aps.autotune.data.PreppedGlucose import app.aaps.plugins.aps.autotune.events.EventAutotuneUpdateGui +import app.aaps.plugins.aps.autotune.keys.AutotuneStringKey import dagger.android.HasAndroidInjector import org.json.JSONException import org.json.JSONObject @@ -61,9 +61,9 @@ import javax.inject.Singleton @Singleton class AutotunePlugin @Inject constructor( private val injector: HasAndroidInjector, - resourceHelper: ResourceHelper, - private val sp: SP, - private val preferences: Preferences, + aapsLogger: AAPSLogger, + rh: ResourceHelper, + preferences: Preferences, private val rxBus: RxBus, private val profileFunction: ProfileFunction, private val dateUtil: DateUtil, @@ -74,10 +74,9 @@ class AutotunePlugin @Inject constructor( private val autotuneCore: AutotuneCore, private val config: Config, private val uel: UserEntryLogger, - aapsLogger: AAPSLogger, private val instantiator: Instantiator -) : PluginBase( - PluginDescription() +) : PluginBaseWithPreferences( + pluginDescription = PluginDescription() .mainType(PluginType.GENERAL) .fragmentClass(AutotuneFragment::class.qualifiedName) .pluginIcon(app.aaps.core.objects.R.drawable.ic_autotune) @@ -86,7 +85,8 @@ class AutotunePlugin @Inject constructor( .preferencesId(PluginDescription.PREFERENCE_SCREEN) .showInList { config.isEngineeringMode() && config.isDev() } .description(R.string.autotune_description), - aapsLogger, resourceHelper + ownPreferences = listOf(AutotuneStringKey::class.java), + aapsLogger, rh, preferences ), Autotune { @Volatile override var lastRunSuccess: Boolean = false @@ -407,14 +407,14 @@ class AutotunePlugin @Inject constructor( } json.put("result", result) json.put("updateButtonVisibility", updateButtonVisibility) - sp.putString(R.string.key_autotune_last_run, json.toString()) + preferences.put(AutotuneStringKey.AutotuneLastRun, json.toString()) } fun loadLastRun() { result = "" lastRunSuccess = false try { - val json = JSONObject(sp.getString(R.string.key_autotune_last_run, "")) + val json = JSONObject(preferences.get(AutotuneStringKey.AutotuneLastRun)) lastNbDays = JsonHelper.safeGetString(json, "lastNbDays", "") lastRun = JsonHelper.safeGetLong(json, "lastRun") val pumpPeak = JsonHelper.safeGetInt(json, "pumpPeak") diff --git a/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/autotune/AutotunePrep.kt b/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/autotune/AutotunePrep.kt index b5269250694..8659dd1a8de 100644 --- a/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/autotune/AutotunePrep.kt +++ b/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/autotune/AutotunePrep.kt @@ -9,7 +9,7 @@ import app.aaps.core.interfaces.utils.MidnightTime import app.aaps.core.interfaces.utils.Round import app.aaps.core.keys.BooleanKey import app.aaps.core.keys.DoubleKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.plugins.aps.autotune.data.ATProfile import app.aaps.plugins.aps.autotune.data.BGDatum import app.aaps.plugins.aps.autotune.data.CRDatum diff --git a/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/autotune/data/ATProfile.kt b/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/autotune/data/ATProfile.kt index 7313825f560..6f29a08fa84 100644 --- a/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/autotune/data/ATProfile.kt +++ b/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/autotune/data/ATProfile.kt @@ -15,12 +15,11 @@ import app.aaps.core.interfaces.profile.ProfileUtil import app.aaps.core.interfaces.profile.PureProfile import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.bus.RxBus -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.Round import app.aaps.core.keys.DoubleKey import app.aaps.core.keys.IntKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.extensions.blockValueBySeconds import app.aaps.core.objects.extensions.pureProfileFromJson import app.aaps.core.objects.profile.ProfileSealed @@ -38,7 +37,6 @@ import kotlin.math.min class ATProfile(profile: Profile, var localInsulin: LocalInsulin, val injector: HasAndroidInjector) { @Inject lateinit var activePlugin: ActivePlugin - @Inject lateinit var sp: SP @Inject lateinit var preferences: Preferences @Inject lateinit var profileUtil: ProfileUtil @Inject lateinit var dateUtil: DateUtil @@ -108,7 +106,7 @@ class ATProfile(profile: Profile, var localInsulin: LocalInsulin, val injector: val insulinInterface: Insulin = activePlugin.activeInsulin try { json.put("name", profileName) - json.put("min_5m_carbimpact", sp.getDouble("openapsama_min_5m_carbimpact", 3.0)) + json.put("min_5m_carbimpact", preferences.get(DoubleKey.ApsAmaMin5MinCarbsImpact)) json.put("dia", dia) if (insulinInterface.id === Insulin.InsulinType.OREF_ULTRA_RAPID_ACTING) json.put( "curve", diff --git a/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/autotune/keys/AutotuneStringKey.kt b/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/autotune/keys/AutotuneStringKey.kt new file mode 100644 index 00000000000..4aea063122f --- /dev/null +++ b/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/autotune/keys/AutotuneStringKey.kt @@ -0,0 +1,12 @@ +package app.aaps.plugins.aps.autotune.keys + +import app.aaps.core.keys.interfaces.StringNonPreferenceKey + +enum class AutotuneStringKey( + override val key: String, + override val defaultValue: String, + override val exportable: Boolean = true +) : StringNonPreferenceKey { + + AutotuneLastRun("key_autotune_last_run", ""), +} diff --git a/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/loop/LoopFragment.kt b/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/loop/LoopFragment.kt index f4bb81a8a4a..ca798248ebe 100644 --- a/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/loop/LoopFragment.kt +++ b/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/loop/LoopFragment.kt @@ -18,10 +18,11 @@ import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.AapsSchedulers import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventLoopUpdateGui -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.DecimalFormatter import app.aaps.core.interfaces.utils.fabric.FabricPrivacy +import app.aaps.core.keys.BooleanNonKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.constraints.ConstraintObject import app.aaps.core.utils.HtmlHelper import app.aaps.plugins.aps.R @@ -39,7 +40,7 @@ class LoopFragment : DaggerFragment(), MenuProvider { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var rxBus: RxBus - @Inject lateinit var sp: SP + @Inject lateinit var preferences: Preferences @Inject lateinit var rh: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var loop: Loop @@ -116,7 +117,7 @@ class LoopFragment : DaggerFragment(), MenuProvider { }, fabricPrivacy::logException) updateGUI() - sp.putBoolean(app.aaps.core.utils.R.string.key_objectiveuseloop, true) + preferences.put(BooleanNonKey.ObjectivesLoopUsed, true) } @Synchronized diff --git a/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/loop/LoopPlugin.kt b/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/loop/LoopPlugin.kt index 95de7027b76..7665c266608 100644 --- a/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/loop/LoopPlugin.kt +++ b/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/loop/LoopPlugin.kt @@ -64,15 +64,15 @@ import app.aaps.core.interfaces.rx.events.EventNewNotification import app.aaps.core.interfaces.rx.events.EventNewOpenLoopNotification import app.aaps.core.interfaces.rx.events.EventTempTargetChange import app.aaps.core.interfaces.rx.weardata.EventData -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.HardLimits import app.aaps.core.interfaces.utils.fabric.FabricPrivacy import app.aaps.core.keys.BooleanKey import app.aaps.core.keys.IntKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.IntNonKey import app.aaps.core.keys.StringKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.nssdk.interfaces.RunningConfiguration import app.aaps.core.objects.constraints.ConstraintObject import app.aaps.core.objects.extensions.asAnnouncement @@ -98,7 +98,6 @@ class LoopPlugin @Inject constructor( aapsLogger: AAPSLogger, private val aapsSchedulers: AapsSchedulers, private val rxBus: RxBus, - private val sp: SP, private val preferences: Preferences, private val config: Config, private val constraintChecker: ConstraintsChecker, @@ -329,13 +328,9 @@ class LoopPlugin @Inject constructor( closedLoopEnabled = constraintChecker.isClosedLoopAllowed() if (closedLoopEnabled?.value() == true) { if (allowNotification) { - if (resultAfterConstraints.isCarbsRequired - && resultAfterConstraints.carbsReq >= sp.getInt( - R.string.key_smb_enable_carbs_suggestions_threshold, - 0 - ) && carbsSuggestionsSuspendedUntil < System.currentTimeMillis() && !treatmentTimeThreshold(-15) + if (resultAfterConstraints.isCarbsRequired && carbsSuggestionsSuspendedUntil < System.currentTimeMillis() && !treatmentTimeThreshold(-15) ) { - if (preferences.get(BooleanKey.AlertCarbsRequired) && !sp.getBoolean(app.aaps.core.ui.R.string.key_raise_notifications_as_android_notifications, true) + if (preferences.get(BooleanKey.AlertCarbsRequired) && !preferences.get(BooleanKey.AlertUrgentAsAndroidNotification) ) { val carbReqLocal = Notification(Notification.CARBS_REQUIRED, resultAfterConstraints.carbsRequiredText, Notification.NORMAL) rxBus.send(EventNewNotification(carbReqLocal)) @@ -350,7 +345,7 @@ class LoopPlugin @Inject constructor( listValues = listOf() ).subscribe() } - if (preferences.get(BooleanKey.AlertCarbsRequired) && sp.getBoolean(app.aaps.core.ui.R.string.key_raise_notifications_as_android_notifications, true) + if (preferences.get(BooleanKey.AlertCarbsRequired) && preferences.get(BooleanKey.AlertUrgentAsAndroidNotification) ) { val intentAction5m = Intent(context, CarbSuggestionReceiver::class.java) intentAction5m.putExtra("ignoreDuration", 5) @@ -392,7 +387,7 @@ class LoopPlugin @Inject constructor( rxBus.send(EventNewOpenLoopNotification()) //only send to wear if Native notifications are turned off - if (!sp.getBoolean(app.aaps.core.ui.R.string.key_raise_notifications_as_android_notifications, true)) { + if (!preferences.get(BooleanKey.AlertUrgentAsAndroidNotification)) { // Send to Wear sendToWear(resultAfterConstraints.carbsRequiredText) } @@ -544,7 +539,7 @@ class LoopPlugin @Inject constructor( lastRun.lastTBREnact = dateUtil.now() lastRun.lastOpenModeAccept = dateUtil.now() scheduleBuildAndStoreDeviceStatus("acceptChangeRequest") - sp.incInt(app.aaps.core.utils.R.string.key_ObjectivesmanualEnacts) + preferences.inc(IntNonKey.ObjectivesManualEnacts) } rxBus.send(EventAcceptOpenLoopChange()) } diff --git a/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.kt b/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.kt index 339ee51aa24..32cf3ba1a2f 100644 --- a/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.kt +++ b/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.kt @@ -38,7 +38,7 @@ import app.aaps.core.interfaces.utils.Round import app.aaps.core.keys.BooleanKey import app.aaps.core.keys.DoubleKey import app.aaps.core.keys.IntentKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.aps.DetermineBasalResult import app.aaps.core.objects.constraints.ConstraintObject import app.aaps.core.objects.extensions.convertedToAbsolute diff --git a/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/openAPSAutoISF/OpenAPSAutoISFPlugin.kt b/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/openAPSAutoISF/OpenAPSAutoISFPlugin.kt index 6f941b8d72f..17e8a133456 100644 --- a/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/openAPSAutoISF/OpenAPSAutoISFPlugin.kt +++ b/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/openAPSAutoISF/OpenAPSAutoISFPlugin.kt @@ -50,8 +50,8 @@ import app.aaps.core.keys.BooleanKey import app.aaps.core.keys.DoubleKey import app.aaps.core.keys.IntKey import app.aaps.core.keys.IntentKey -import app.aaps.core.keys.Preferences import app.aaps.core.keys.UnitDoubleKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.aps.DetermineBasalResult import app.aaps.core.objects.constraints.ConstraintObject import app.aaps.core.objects.extensions.convertedToAbsolute @@ -146,7 +146,6 @@ open class OpenAPSAutoISFPlugin @Inject constructor( val normalTarget = 100 private val minutesClass; get() = if (preferences.get(IntKey.ApsMaxSmbFrequency) == 1) 6L else 30L // ga-zelle: later get correct 1 min CGM flag from glucoseStatus ? ... or from apsResults? - override fun onStart() { super.onStart() var count = 0 diff --git a/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.kt b/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.kt index 4c3c8da0e55..18b6fc6405a 100644 --- a/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.kt +++ b/plugins/aps/src/main/kotlin/app/aaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.kt @@ -50,8 +50,8 @@ import app.aaps.core.keys.BooleanKey import app.aaps.core.keys.DoubleKey import app.aaps.core.keys.IntKey import app.aaps.core.keys.IntentKey -import app.aaps.core.keys.Preferences import app.aaps.core.keys.UnitDoubleKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.aps.DetermineBasalResult import app.aaps.core.objects.constraints.ConstraintObject import app.aaps.core.objects.extensions.convertedToAbsolute @@ -335,7 +335,13 @@ open class OpenAPSSMBPlugin @Inject constructor( // End of check, start gathering data - val dynIsfMode = preferences.get(BooleanKey.ApsUseDynamicSensitivity) && hardLimits.checkHardLimits(preferences.get(IntKey.ApsDynIsfAdjustmentFactor).toDouble(), R.string.dyn_isf_adjust_title, IntKey.ApsDynIsfAdjustmentFactor.min.toDouble(), IntKey.ApsDynIsfAdjustmentFactor.max.toDouble()) + val dynIsfMode = + preferences.get(BooleanKey.ApsUseDynamicSensitivity) && hardLimits.checkHardLimits( + preferences.get(IntKey.ApsDynIsfAdjustmentFactor).toDouble(), + R.string.dyn_isf_adjust_title, + IntKey.ApsDynIsfAdjustmentFactor.min.toDouble(), + IntKey.ApsDynIsfAdjustmentFactor.max.toDouble() + ) val smbEnabled = preferences.get(BooleanKey.ApsUseSmb) val advancedFiltering = constraintsChecker.isAdvancedFilteringEnabled().also { inputConstraints.copyReasons(it) }.value() diff --git a/plugins/aps/src/main/res/values/strings.xml b/plugins/aps/src/main/res/values/strings.xml index d5d2573bd31..30e1e85f956 100644 --- a/plugins/aps/src/main/res/values/strings.xml +++ b/plugins/aps/src/main/res/values/strings.xml @@ -1,8 +1,6 @@ - key_autotune_last_run - Enable TDD based sensitivity ratio for basal and glucose target modification Uses the last 24h TDD/7D TDD to calculate sensitivity ratio used for increasing or decreasing basal rate, and also adjust glucose target if these options are enabled, in the same way Autosens does. It is recommended to start with this option turned off DynamicISF Adjustment Factor % @@ -106,8 +104,6 @@ Peak - smb_enable_carbs_suggestions_threshold - Run now A bolus was delivered within the last 3 minutes, skipping SMB Pump not initialized! diff --git a/plugins/aps/src/test/kotlin/app/aaps/plugins/aps/autotune/AutotunePluginTest.kt b/plugins/aps/src/test/kotlin/app/aaps/plugins/aps/autotune/AutotunePluginTest.kt index 1fdf61a9dfe..0eeddbf156e 100644 --- a/plugins/aps/src/test/kotlin/app/aaps/plugins/aps/autotune/AutotunePluginTest.kt +++ b/plugins/aps/src/test/kotlin/app/aaps/plugins/aps/autotune/AutotunePluginTest.kt @@ -1,6 +1,5 @@ package app.aaps.plugins.aps.autotune -import android.content.SharedPreferences import app.aaps.core.interfaces.logging.UserEntryLogger import app.aaps.core.validators.preferences.AdaptiveIntPreference import app.aaps.core.validators.preferences.AdaptiveSwitchPreference @@ -15,7 +14,6 @@ class AutotunePluginTest : TestBaseWithProfile() { @Mock lateinit var autotuneFS: AutotuneFS @Mock lateinit var autotuneIob: AutotuneIob @Mock lateinit var autotunePrep: AutotunePrep - @Mock lateinit var sharedPrefs: SharedPreferences @Mock lateinit var autotuneCore: AutotuneCore @Mock lateinit var uel: UserEntryLogger private lateinit var autotunePlugin: AutotunePlugin @@ -25,12 +23,10 @@ class AutotunePluginTest : TestBaseWithProfile() { if (it is AdaptiveIntPreference) { it.profileUtil = profileUtil it.preferences = preferences - it.sharedPrefs = sharedPrefs it.config = config } if (it is AdaptiveSwitchPreference) { it.preferences = preferences - it.sharedPrefs = sharedPrefs it.config = config } } @@ -38,8 +34,8 @@ class AutotunePluginTest : TestBaseWithProfile() { @BeforeEach fun prepare() { autotunePlugin = AutotunePlugin( - injector, rh, sp, preferences, rxBus, profileFunction, dateUtil, activePlugin, - autotuneFS, autotuneIob, autotunePrep, autotuneCore, config, uel, aapsLogger, instantiator + injector, aapsLogger, rh, preferences, rxBus, profileFunction, dateUtil, activePlugin, + autotuneFS, autotuneIob, autotunePrep, autotuneCore, config, uel, instantiator ) } diff --git a/plugins/aps/src/test/kotlin/app/aaps/plugins/aps/autotune/AutotunePrepTest.kt b/plugins/aps/src/test/kotlin/app/aaps/plugins/aps/autotune/AutotunePrepTest.kt index 04240500294..4d3baa0027d 100644 --- a/plugins/aps/src/test/kotlin/app/aaps/plugins/aps/autotune/AutotunePrepTest.kt +++ b/plugins/aps/src/test/kotlin/app/aaps/plugins/aps/autotune/AutotunePrepTest.kt @@ -17,7 +17,7 @@ import app.aaps.core.interfaces.profile.PureProfile import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.keys.BooleanKey import app.aaps.core.keys.DoubleKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.extensions.shiftBlock import app.aaps.core.objects.profile.ProfileSealed import app.aaps.core.utils.JsonHelper diff --git a/plugins/aps/src/test/kotlin/app/aaps/plugins/aps/loop/LoopPluginTest.kt b/plugins/aps/src/test/kotlin/app/aaps/plugins/aps/loop/LoopPluginTest.kt index 8b162e38303..6a13d1892f1 100644 --- a/plugins/aps/src/test/kotlin/app/aaps/plugins/aps/loop/LoopPluginTest.kt +++ b/plugins/aps/src/test/kotlin/app/aaps/plugins/aps/loop/LoopPluginTest.kt @@ -2,7 +2,6 @@ package app.aaps.plugins.aps.loop import android.app.NotificationManager import android.content.Context -import android.content.SharedPreferences import androidx.preference.PreferenceManager import app.aaps.core.data.aps.ApsMode import app.aaps.core.data.plugin.PluginType @@ -17,8 +16,6 @@ import app.aaps.core.interfaces.receivers.ReceiverStatusStore import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.keys.StringKey import app.aaps.core.nssdk.interfaces.RunningConfiguration -import app.aaps.core.validators.preferences.AdaptiveIntPreference -import app.aaps.core.validators.preferences.AdaptiveListPreference import app.aaps.pump.virtual.VirtualPumpPlugin import app.aaps.shared.tests.TestBaseWithProfile import com.google.common.truth.Truth.assertThat @@ -38,29 +35,14 @@ class LoopPluginTest : TestBaseWithProfile() { @Mock lateinit var uel: UserEntryLogger @Mock lateinit var runningConfiguration: RunningConfiguration @Mock lateinit var uiInteraction: UiInteraction - @Mock lateinit var sharedPrefs: SharedPreferences @Mock lateinit var processedDeviceStatusData: ProcessedDeviceStatusData private lateinit var loopPlugin: LoopPlugin - init { - addInjector { - if (it is AdaptiveIntPreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - it.config = config - } - if (it is AdaptiveListPreference) { - it.preferences = preferences - } - } - } - @BeforeEach fun prepare() { preferenceManager = PreferenceManager(context) loopPlugin = LoopPlugin( - aapsLogger, aapsSchedulers, rxBus, sp, preferences, config, + aapsLogger, aapsSchedulers, rxBus, preferences, config, constraintChecker, rh, profileFunction, context, commandQueue, activePlugin, virtualPumpPlugin, iobCobCalculator, processedTbrEbData, receiverStatusStore, fabricPrivacy, dateUtil, uel, persistenceLayer, runningConfiguration, uiInteraction, instantiator, processedDeviceStatusData ) diff --git a/plugins/aps/src/test/kotlin/app/aaps/plugins/aps/openAPSAMA/OpenAPSAMAPluginTest.kt b/plugins/aps/src/test/kotlin/app/aaps/plugins/aps/openAPSAMA/OpenAPSAMAPluginTest.kt index c531a89298c..f9fcfd52163 100644 --- a/plugins/aps/src/test/kotlin/app/aaps/plugins/aps/openAPSAMA/OpenAPSAMAPluginTest.kt +++ b/plugins/aps/src/test/kotlin/app/aaps/plugins/aps/openAPSAMA/OpenAPSAMAPluginTest.kt @@ -1,14 +1,8 @@ package app.aaps.plugins.aps.openAPSAMA -import android.content.SharedPreferences import app.aaps.core.interfaces.constraints.ConstraintsChecker import app.aaps.core.interfaces.db.PersistenceLayer import app.aaps.core.interfaces.iob.GlucoseStatusProvider -import app.aaps.core.validators.preferences.AdaptiveDoublePreference -import app.aaps.core.validators.preferences.AdaptiveIntPreference -import app.aaps.core.validators.preferences.AdaptiveIntentPreference -import app.aaps.core.validators.preferences.AdaptiveSwitchPreference -import app.aaps.core.validators.preferences.AdaptiveUnitPreference import app.aaps.shared.tests.TestBaseWithProfile import com.google.common.truth.Truth.assertThat import org.junit.jupiter.api.BeforeEach @@ -21,39 +15,8 @@ class OpenAPSAMAPluginTest : TestBaseWithProfile() { @Mock lateinit var persistenceLayer: PersistenceLayer @Mock lateinit var glucoseStatusProvider: GlucoseStatusProvider @Mock lateinit var determineBasalAMA: DetermineBasalAMA - @Mock lateinit var sharedPrefs: SharedPreferences private lateinit var openAPSAMAPlugin: OpenAPSAMAPlugin - init { - addInjector { - if (it is AdaptiveDoublePreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveIntPreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - it.config = config - } - if (it is AdaptiveIntentPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveUnitPreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveSwitchPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - it.config = config - } - } - } - @BeforeEach fun prepare() { openAPSAMAPlugin = OpenAPSAMAPlugin( injector, aapsLogger, rxBus, constraintChecker, rh, config, profileFunction, activePlugin, diff --git a/plugins/aps/src/test/kotlin/app/aaps/plugins/aps/openAPSAutoISF/OpenAPSAutoISFPluginTest.kt b/plugins/aps/src/test/kotlin/app/aaps/plugins/aps/openAPSAutoISF/OpenAPSAutoISFPluginTest.kt index 3b605808662..8c475ee62a8 100644 --- a/plugins/aps/src/test/kotlin/app/aaps/plugins/aps/openAPSAutoISF/OpenAPSAutoISFPluginTest.kt +++ b/plugins/aps/src/test/kotlin/app/aaps/plugins/aps/openAPSAutoISF/OpenAPSAutoISFPluginTest.kt @@ -1,6 +1,5 @@ package app.aaps.plugins.aps.openAPSAutoISF -import android.content.SharedPreferences import app.aaps.core.data.aps.SMBDefaults import app.aaps.core.interfaces.aps.OapsProfileAutoIsf import app.aaps.core.interfaces.bgQualityCheck.BgQualityCheck @@ -13,11 +12,6 @@ import app.aaps.core.keys.BooleanKey import app.aaps.core.keys.DoubleKey import app.aaps.core.keys.IntKey import app.aaps.core.keys.UnitDoubleKey -import app.aaps.core.validators.preferences.AdaptiveDoublePreference -import app.aaps.core.validators.preferences.AdaptiveIntPreference -import app.aaps.core.validators.preferences.AdaptiveIntentPreference -import app.aaps.core.validators.preferences.AdaptiveSwitchPreference -import app.aaps.core.validators.preferences.AdaptiveUnitPreference import app.aaps.shared.tests.TestBaseWithProfile import com.google.common.truth.Truth.assertThat import org.junit.jupiter.api.BeforeEach @@ -31,42 +25,11 @@ class OpenAPSAutoISFPluginTest : TestBaseWithProfile() { @Mock lateinit var persistenceLayer: PersistenceLayer @Mock lateinit var glucoseStatusProvider: GlucoseStatusProvider @Mock lateinit var determineBasalSMB: DetermineBasalAutoISF - @Mock lateinit var sharedPrefs: SharedPreferences @Mock lateinit var bgQualityCheck: BgQualityCheck @Mock lateinit var profiler: Profiler @Mock lateinit var uiInteraction: UiInteraction private lateinit var openAPSAutoISFPlugin: OpenAPSAutoISFPlugin - init { - addInjector { - if (it is AdaptiveDoublePreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveIntPreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - it.config = config - } - if (it is AdaptiveIntentPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveUnitPreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveSwitchPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - it.config = config - } - } - } - @BeforeEach fun prepare() { openAPSAutoISFPlugin = OpenAPSAutoISFPlugin( injector, aapsLogger, rxBus, constraintChecker, rh, profileFunction, profileUtil, config, activePlugin, diff --git a/plugins/aps/src/test/kotlin/app/aaps/plugins/aps/openAPSSMB/OpenAPSSMBPluginTest.kt b/plugins/aps/src/test/kotlin/app/aaps/plugins/aps/openAPSSMB/OpenAPSSMBPluginTest.kt index ea468b645d4..63f681085b3 100644 --- a/plugins/aps/src/test/kotlin/app/aaps/plugins/aps/openAPSSMB/OpenAPSSMBPluginTest.kt +++ b/plugins/aps/src/test/kotlin/app/aaps/plugins/aps/openAPSSMB/OpenAPSSMBPluginTest.kt @@ -1,6 +1,5 @@ package app.aaps.plugins.aps.openAPSSMB -import android.content.SharedPreferences import app.aaps.core.interfaces.bgQualityCheck.BgQualityCheck import app.aaps.core.interfaces.constraints.ConstraintsChecker import app.aaps.core.interfaces.db.PersistenceLayer @@ -8,11 +7,6 @@ import app.aaps.core.interfaces.iob.GlucoseStatusProvider import app.aaps.core.interfaces.profiling.Profiler import app.aaps.core.interfaces.stats.TddCalculator import app.aaps.core.interfaces.ui.UiInteraction -import app.aaps.core.validators.preferences.AdaptiveDoublePreference -import app.aaps.core.validators.preferences.AdaptiveIntPreference -import app.aaps.core.validators.preferences.AdaptiveIntentPreference -import app.aaps.core.validators.preferences.AdaptiveSwitchPreference -import app.aaps.core.validators.preferences.AdaptiveUnitPreference import app.aaps.shared.tests.TestBaseWithProfile import com.google.common.truth.Truth.assertThat import org.junit.jupiter.api.BeforeEach @@ -25,43 +19,12 @@ class OpenAPSSMBPluginTest : TestBaseWithProfile() { @Mock lateinit var persistenceLayer: PersistenceLayer @Mock lateinit var glucoseStatusProvider: GlucoseStatusProvider @Mock lateinit var determineBasalSMB: DetermineBasalSMB - @Mock lateinit var sharedPrefs: SharedPreferences @Mock lateinit var bgQualityCheck: BgQualityCheck @Mock lateinit var tddCalculator: TddCalculator @Mock lateinit var uiInteraction: UiInteraction @Mock lateinit var profiler: Profiler private lateinit var openAPSSMBPlugin: OpenAPSSMBPlugin - init { - addInjector { - if (it is AdaptiveDoublePreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveIntPreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - it.config = config - } - if (it is AdaptiveIntentPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveUnitPreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveSwitchPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - it.config = config - } - } - } - @BeforeEach fun prepare() { openAPSSMBPlugin = OpenAPSSMBPlugin( injector, aapsLogger, rxBus, constraintChecker, rh, profileFunction, profileUtil, config, activePlugin, diff --git a/plugins/automation/src/main/kotlin/app/aaps/plugins/automation/AutomationPlugin.kt b/plugins/automation/src/main/kotlin/app/aaps/plugins/automation/AutomationPlugin.kt index 1e1905a1e29..20f0267309b 100644 --- a/plugins/automation/src/main/kotlin/app/aaps/plugins/automation/AutomationPlugin.kt +++ b/plugins/automation/src/main/kotlin/app/aaps/plugins/automation/AutomationPlugin.kt @@ -20,6 +20,7 @@ import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.plugin.ActivePlugin import app.aaps.core.interfaces.plugin.PluginBase +import app.aaps.core.interfaces.plugin.PluginBaseWithPreferences import app.aaps.core.interfaces.plugin.PluginDescription import app.aaps.core.interfaces.queue.Callback import app.aaps.core.interfaces.resources.ResourceHelper @@ -31,8 +32,8 @@ import app.aaps.core.interfaces.rx.events.EventNetworkChange import app.aaps.core.interfaces.rx.events.EventPreferenceChange import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.fabric.FabricPrivacy -import app.aaps.core.keys.Preferences import app.aaps.core.keys.StringKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.validators.preferences.AdaptiveListPreference import app.aaps.plugins.automation.actions.Action import app.aaps.plugins.automation.actions.ActionAlarm @@ -95,22 +96,22 @@ import javax.inject.Singleton @Singleton class AutomationPlugin @Inject constructor( private val injector: HasAndroidInjector, + aapsLogger: AAPSLogger, rh: ResourceHelper, + preferences: Preferences, private val context: Context, - private val preferences: Preferences, private val fabricPrivacy: FabricPrivacy, private val loop: Loop, private val rxBus: RxBus, private val constraintChecker: ConstraintsChecker, - aapsLogger: AAPSLogger, private val aapsSchedulers: AapsSchedulers, private val config: Config, private val locationServiceHelper: LocationServiceHelper, private val dateUtil: DateUtil, private val activePlugin: ActivePlugin, private val timerUtil: TimerUtil -) : PluginBase( - PluginDescription() +) : PluginBaseWithPreferences( + pluginDescription = PluginDescription() .mainType(PluginType.GENERAL) .fragmentClass(AutomationFragment::class.qualifiedName) .pluginIcon(app.aaps.core.objects.R.drawable.ic_automation) @@ -120,13 +121,12 @@ class AutomationPlugin @Inject constructor( .neverVisible(!config.APS) .preferencesId(PluginDescription.PREFERENCE_SCREEN) .description(R.string.automation_description), - aapsLogger, rh + ownPreferences = listOf(AutomationStringKey::class.java), + aapsLogger, rh, preferences ), Automation { private var disposable: CompositeDisposable = CompositeDisposable() - private val keyAutomationEvents = "AUTOMATION_EVENTS" - private val automationEvents = ArrayList() var executionLog: MutableList = ArrayList() var btConnects: MutableList = ArrayList() @@ -141,9 +141,6 @@ class AutomationPlugin @Inject constructor( } init { - // Make plugin preferences available to AAPS - preferences.registerPreferences(AutomationStringKey::class.java) - refreshLoop = Runnable { processActions() handler?.postDelayed(refreshLoop, T.secs(150).msecs()) diff --git a/plugins/automation/src/main/kotlin/app/aaps/plugins/automation/actions/ActionRunAutotune.kt b/plugins/automation/src/main/kotlin/app/aaps/plugins/automation/actions/ActionRunAutotune.kt index cb583481270..5700c1b03b0 100644 --- a/plugins/automation/src/main/kotlin/app/aaps/plugins/automation/actions/ActionRunAutotune.kt +++ b/plugins/automation/src/main/kotlin/app/aaps/plugins/automation/actions/ActionRunAutotune.kt @@ -10,7 +10,7 @@ import app.aaps.core.interfaces.queue.Callback import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.keys.BooleanKey import app.aaps.core.keys.IntKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.ui.elements.WeekDay import app.aaps.core.utils.JsonHelper import app.aaps.plugins.automation.R diff --git a/plugins/automation/src/main/kotlin/app/aaps/plugins/automation/actions/ActionSettingsExport.kt b/plugins/automation/src/main/kotlin/app/aaps/plugins/automation/actions/ActionSettingsExport.kt index 74ea6cb0b56..aa5d62fc452 100644 --- a/plugins/automation/src/main/kotlin/app/aaps/plugins/automation/actions/ActionSettingsExport.kt +++ b/plugins/automation/src/main/kotlin/app/aaps/plugins/automation/actions/ActionSettingsExport.kt @@ -18,7 +18,7 @@ import app.aaps.core.interfaces.rx.events.EventNewNotification import app.aaps.core.interfaces.rx.events.EventRefreshOverview import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.keys.BooleanKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.extensions.asAnnouncement import app.aaps.core.objects.extensions.asSettingsExport import app.aaps.core.utils.JsonHelper @@ -90,8 +90,7 @@ class ActionSettingsExport(injector: HasAndroidInjector) : Action(injector) { notification = NotificationUserMessage(exportResultMessage, Notification.URGENT) // URGENT -> e.g. color RED announceAlert = true } - } - else { + } else { // No password or was expired and needs re-entering by user exportResultComment = app.aaps.core.ui.R.string.export_expired exportResultMessage = rh.gs(app.aaps.core.ui.R.string.export_result_message_expired) @@ -101,8 +100,7 @@ class ActionSettingsExport(injector: HasAndroidInjector) : Action(injector) { exportPasswordDataStore.clearPasswordDataStore(context) announceAlert = true } - } - else { + } else { // Not enabled, do nothing and notify user exportResultComment = app.aaps.core.ui.R.string.export_disabled exportResultMessage = rh.gs(app.aaps.core.ui.R.string.export_result_message_disabled) @@ -116,7 +114,7 @@ class ActionSettingsExport(injector: HasAndroidInjector) : Action(injector) { val error = "${text.value}: $exportResultMessage" aapsLogger.debug(LTag.AUTOMATION, "Insert therapy EXPORT_SETTINGS event, error=:${error}, doAlsoAnnouncement=$announceAlert") disposable += persistenceLayer.insertPumpTherapyEventIfNewByTimestamp( - therapyEvent = TE.asSettingsExport(error=error), + therapyEvent = TE.asSettingsExport(error = error), timestamp = dateUtil.now(), action = app.aaps.core.data.ue.Action.EXPORT_SETTINGS, // Signal export was done to automation! source = Sources.Automation, @@ -124,13 +122,12 @@ class ActionSettingsExport(injector: HasAndroidInjector) : Action(injector) { listValues = listOf() ).subscribe() - if (announceAlert && preferences.get(BooleanKey.NsClientCreateAnnouncementsFromErrors) && config.APS) - { + if (announceAlert && preferences.get(BooleanKey.NsClientCreateAnnouncementsFromErrors) && config.APS) { // Do additional event type announcement for aapsClient alerting val alert = "${rh.gs(app.aaps.core.ui.R.string.export_alert)}(${text.value}): $exportResultMessage" aapsLogger.debug(LTag.AUTOMATION, "Insert therapy ALERT/ANNOUNCEMENT event, error=:${alert}") disposable += persistenceLayer.insertPumpTherapyEventIfNewByTimestamp( - therapyEvent = TE.asAnnouncement(error=alert), + therapyEvent = TE.asAnnouncement(error = alert), timestamp = dateUtil.now(), action = app.aaps.core.data.ue.Action.EXPORT_SETTINGS, source = Sources.Automation, diff --git a/plugins/automation/src/main/kotlin/app/aaps/plugins/automation/keys/AutomationStringKey.kt b/plugins/automation/src/main/kotlin/app/aaps/plugins/automation/keys/AutomationStringKey.kt index 42d69c59c72..2890255b37c 100644 --- a/plugins/automation/src/main/kotlin/app/aaps/plugins/automation/keys/AutomationStringKey.kt +++ b/plugins/automation/src/main/kotlin/app/aaps/plugins/automation/keys/AutomationStringKey.kt @@ -1,10 +1,11 @@ package app.aaps.plugins.automation.keys -import app.aaps.core.keys.StringNonPreferenceKey +import app.aaps.core.keys.interfaces.StringNonPreferenceKey enum class AutomationStringKey( override val key: String, override val defaultValue: String, + override val exportable: Boolean = true ) : StringNonPreferenceKey { AutomationEvents("AUTOMATION_EVENTS", ""), diff --git a/plugins/automation/src/main/kotlin/app/aaps/plugins/automation/services/LocationService.kt b/plugins/automation/src/main/kotlin/app/aaps/plugins/automation/services/LocationService.kt index 1aad11c916c..0154484ec0e 100644 --- a/plugins/automation/src/main/kotlin/app/aaps/plugins/automation/services/LocationService.kt +++ b/plugins/automation/src/main/kotlin/app/aaps/plugins/automation/services/LocationService.kt @@ -19,8 +19,8 @@ import app.aaps.core.interfaces.rx.AapsSchedulers import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventAppExit import app.aaps.core.interfaces.utils.fabric.FabricPrivacy -import app.aaps.core.keys.Preferences import app.aaps.core.keys.StringKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.ui.toast.ToastUtils import app.aaps.plugins.automation.events.EventLocationChange import com.google.android.gms.location.LocationServices diff --git a/plugins/automation/src/main/kotlin/app/aaps/plugins/automation/triggers/Trigger.kt b/plugins/automation/src/main/kotlin/app/aaps/plugins/automation/triggers/Trigger.kt index 533743992b4..367edc8a9c8 100644 --- a/plugins/automation/src/main/kotlin/app/aaps/plugins/automation/triggers/Trigger.kt +++ b/plugins/automation/src/main/kotlin/app/aaps/plugins/automation/triggers/Trigger.kt @@ -18,7 +18,7 @@ import app.aaps.core.interfaces.profile.ProfileUtil import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.utils.DateUtil -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.plugins.automation.R import app.aaps.plugins.automation.dialogs.ChooseTriggerDialog import app.aaps.plugins.automation.events.EventTriggerChanged diff --git a/plugins/automation/src/test/kotlin/app/aaps/plugins/automation/AutomationPluginTest.kt b/plugins/automation/src/test/kotlin/app/aaps/plugins/automation/AutomationPluginTest.kt index 79ef9f507dd..a9c1cee6d0a 100644 --- a/plugins/automation/src/test/kotlin/app/aaps/plugins/automation/AutomationPluginTest.kt +++ b/plugins/automation/src/test/kotlin/app/aaps/plugins/automation/AutomationPluginTest.kt @@ -31,7 +31,7 @@ class AutomationPluginTest : TestBaseWithProfile() { @BeforeEach fun prepare() { automationPlugin = AutomationPlugin( - injector, rh, context, preferences, fabricPrivacy, loop, rxBus, constraintChecker, aapsLogger, + injector, aapsLogger, rh, preferences, context, fabricPrivacy, loop, rxBus, constraintChecker, aapsSchedulers, config, locationServiceHelper, dateUtil, activePlugin, timerUtil ) } diff --git a/plugins/automation/src/test/kotlin/app/aaps/plugins/automation/BolusTimerImplTest.kt b/plugins/automation/src/test/kotlin/app/aaps/plugins/automation/BolusTimerImplTest.kt index 11b5d2a945d..69192351c30 100644 --- a/plugins/automation/src/test/kotlin/app/aaps/plugins/automation/BolusTimerImplTest.kt +++ b/plugins/automation/src/test/kotlin/app/aaps/plugins/automation/BolusTimerImplTest.kt @@ -10,7 +10,7 @@ import app.aaps.core.interfaces.profile.ProfileFunction import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.fabric.FabricPrivacy -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.plugins.automation.services.LocationServiceHelper import app.aaps.plugins.automation.triggers.Trigger import app.aaps.plugins.automation.ui.TimerUtil @@ -56,7 +56,7 @@ class BolusTimerImplTest : TestBase() { Mockito.`when`(profileFunction.getUnits()).thenReturn(GlucoseUnit.MGDL) dateUtil = DateUtilImpl(context) automationPlugin = AutomationPlugin( - injector, rh, context, preferences, fabricPrivacy, loop, rxBus, constraintChecker, aapsLogger, aapsSchedulers, config, locationServiceHelper, dateUtil, + injector, aapsLogger, rh, preferences, context, fabricPrivacy, loop, rxBus, constraintChecker, aapsSchedulers, config, locationServiceHelper, dateUtil, activePlugin, timerUtil ) } diff --git a/plugins/automation/src/test/kotlin/app/aaps/plugins/automation/CarbTimerImplTest.kt b/plugins/automation/src/test/kotlin/app/aaps/plugins/automation/CarbTimerImplTest.kt index ed3512c8c3e..adb0a8e2069 100644 --- a/plugins/automation/src/test/kotlin/app/aaps/plugins/automation/CarbTimerImplTest.kt +++ b/plugins/automation/src/test/kotlin/app/aaps/plugins/automation/CarbTimerImplTest.kt @@ -10,7 +10,7 @@ import app.aaps.core.interfaces.profile.ProfileFunction import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.fabric.FabricPrivacy -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.plugins.automation.services.LocationServiceHelper import app.aaps.plugins.automation.triggers.Trigger import app.aaps.plugins.automation.ui.TimerUtil @@ -58,7 +58,7 @@ class CarbTimerImplTest : TestBase() { dateUtil = DateUtilImpl(context) timerUtil = TimerUtil(context) automationPlugin = AutomationPlugin( - injector, rh, context, preferences, fabricPrivacy, loop, rxBus, constraintChecker, aapsLogger, aapsSchedulers, config, locationServiceHelper, dateUtil, activePlugin, timerUtil + injector, aapsLogger, rh, preferences, context, fabricPrivacy, loop, rxBus, constraintChecker, aapsSchedulers, config, locationServiceHelper, dateUtil, activePlugin, timerUtil ) } diff --git a/plugins/automation/src/test/kotlin/app/aaps/plugins/automation/actions/ActionCarePortalEventTest.kt b/plugins/automation/src/test/kotlin/app/aaps/plugins/automation/actions/ActionCarePortalEventTest.kt index 8598427b4f3..107caef07af 100644 --- a/plugins/automation/src/test/kotlin/app/aaps/plugins/automation/actions/ActionCarePortalEventTest.kt +++ b/plugins/automation/src/test/kotlin/app/aaps/plugins/automation/actions/ActionCarePortalEventTest.kt @@ -11,7 +11,6 @@ import com.google.common.truth.Truth.assertThat import io.reactivex.rxjava3.core.Single import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test -import org.mockito.ArgumentMatchers import org.mockito.Mockito.anyLong import org.mockito.Mockito.`when` import org.skyscreamer.jsonassert.JSONAssert @@ -22,7 +21,6 @@ class ActionCarePortalEventTest : ActionsTestBase() { @BeforeEach fun setup() { - `when`(sp.getString(ArgumentMatchers.anyString(), ArgumentMatchers.anyString())).thenReturn("AAPS") `when`(rh.gs(app.aaps.core.ui.R.string.careportal_note_message)).thenReturn("Note : %s") `when`(dateUtil.now()).thenReturn(0) `when`(profileFunction.getUnits()).thenReturn(GlucoseUnit.MGDL) diff --git a/plugins/automation/src/test/kotlin/app/aaps/plugins/automation/triggers/TriggerCOBTest.kt b/plugins/automation/src/test/kotlin/app/aaps/plugins/automation/triggers/TriggerCOBTest.kt index 7ac312a0be2..f2555cb88e7 100644 --- a/plugins/automation/src/test/kotlin/app/aaps/plugins/automation/triggers/TriggerCOBTest.kt +++ b/plugins/automation/src/test/kotlin/app/aaps/plugins/automation/triggers/TriggerCOBTest.kt @@ -4,18 +4,12 @@ import app.aaps.core.data.iob.CobInfo import app.aaps.plugins.automation.elements.Comparator import com.google.common.truth.Truth.assertThat import org.json.JSONObject -import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test -import org.mockito.ArgumentMatchers import org.mockito.Mockito.`when` import org.skyscreamer.jsonassert.JSONAssert class TriggerCOBTest : TriggerTestBase() { - @BeforeEach fun mock() { - `when`(sp.getInt(ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt())).thenReturn(48) - } - @Test fun shouldRunTest() { // COB value is 6 `when`(iobCobCalculator.getCobInfo("AutomationTriggerCOB")).thenReturn(CobInfo(0, 6.0, 2.0)) diff --git a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/activities/DaggerAppCompatActivityWithResult.kt b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/activities/DaggerAppCompatActivityWithResult.kt index 3e9ec33313f..99921aca830 100644 --- a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/activities/DaggerAppCompatActivityWithResult.kt +++ b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/activities/DaggerAppCompatActivityWithResult.kt @@ -17,8 +17,8 @@ import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventAAPSDirectorySelected import app.aaps.core.interfaces.rx.events.EventThemeSwitch -import app.aaps.core.keys.Preferences import app.aaps.core.keys.StringKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.ui.locale.LocaleHelper import app.aaps.core.ui.toast.ToastUtils import app.aaps.plugins.configuration.maintenance.CustomWatchfaceFileContract diff --git a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/configBuilder/ConfigBuilderPlugin.kt b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/configBuilder/ConfigBuilderPlugin.kt index f1479d9e917..e4ad885b861 100644 --- a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/configBuilder/ConfigBuilderPlugin.kt +++ b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/configBuilder/ConfigBuilderPlugin.kt @@ -22,6 +22,7 @@ import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.logging.UserEntryLogger import app.aaps.core.interfaces.plugin.ActivePlugin import app.aaps.core.interfaces.plugin.PluginBase +import app.aaps.core.interfaces.plugin.PluginBaseWithPreferences import app.aaps.core.interfaces.plugin.PluginDescription import app.aaps.core.interfaces.profile.ProfileSource import app.aaps.core.interfaces.protection.ProtectionCheck @@ -32,18 +33,19 @@ import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventAppInitialized import app.aaps.core.interfaces.rx.events.EventConfigBuilderChange import app.aaps.core.interfaces.rx.events.EventRebuildTabs -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.smoothing.Smoothing import app.aaps.core.interfaces.source.BgSource import app.aaps.core.interfaces.sync.NsClient import app.aaps.core.interfaces.ui.UiInteraction -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.ui.dialogs.OKDialog import app.aaps.core.ui.extensions.toVisibility import app.aaps.plugins.configuration.R import app.aaps.plugins.configuration.configBuilder.events.EventConfigBuilderUpdateGui import app.aaps.plugins.configuration.databinding.ConfigbuilderSingleCategoryBinding import app.aaps.plugins.configuration.databinding.ConfigbuilderSinglePluginBinding +import app.aaps.plugins.configuration.keys.ConfigurationBooleanComposedKey +import app.aaps.plugins.configuration.keys.ConfigurationBooleanKey import javax.inject.Inject import javax.inject.Singleton @@ -51,16 +53,15 @@ import javax.inject.Singleton class ConfigBuilderPlugin @Inject constructor( aapsLogger: AAPSLogger, rh: ResourceHelper, - private val sp: SP, - private val preferences: Preferences, + preferences: Preferences, private val rxBus: RxBus, private val activePlugin: ActivePlugin, private val uel: UserEntryLogger, private val pumpSync: PumpSync, private val protectionCheck: ProtectionCheck, private val uiInteraction: UiInteraction -) : PluginBase( - PluginDescription() +) : PluginBaseWithPreferences( + pluginDescription = PluginDescription() .mainType(PluginType.GENERAL) .fragmentClass(ConfigBuilderFragment::class.java.name) .alwaysEnabled(true) @@ -68,7 +69,8 @@ class ConfigBuilderPlugin @Inject constructor( .pluginName(R.string.config_builder) .shortName(R.string.config_builder_shortname) .description(R.string.description_config_builder), - aapsLogger, rh + ownPreferences = listOf(ConfigurationBooleanKey::class.java, ConfigurationBooleanComposedKey::class.java), + aapsLogger, rh, preferences ), ConfigBuilder { override fun initialize() { @@ -97,11 +99,13 @@ class ConfigBuilderPlugin @Inject constructor( } private fun savePref(p: PluginBase, type: PluginType) { - val settingEnabled = "ConfigBuilder_" + type.name + "_" + p.javaClass.simpleName + "_Enabled" - sp.putBoolean(settingEnabled, p.isEnabled()) - aapsLogger.debug(LTag.CONFIGBUILDER, "Storing: " + settingEnabled + ":" + p.isEnabled()) + // val settingEnabled = "ConfigBuilder_" + type.name + "_" + p.javaClass.simpleName + "_Enabled" + // sp.putBoolean(settingEnabled, p.isEnabled()) + preferences.put(ConfigurationBooleanComposedKey.ConfigBuilderEnabled, type.name + "_" + p.javaClass.simpleName, value = p.isEnabled()) + aapsLogger.debug(LTag.CONFIGBUILDER, "Storing: " + ConfigurationBooleanComposedKey.ConfigBuilderEnabled.composeKey(type.name + "_" + p.javaClass.simpleName) + ":" + p.isEnabled()) val settingVisible = "ConfigBuilder_" + type.name + "_" + p.javaClass.simpleName + "_Visible" - sp.putBoolean(settingVisible, p.isFragmentVisible()) + //sp.putBoolean(settingVisible, p.isFragmentVisible()) + preferences.put(ConfigurationBooleanComposedKey.ConfigBuilderVisible, type.name + "_" + p.javaClass.simpleName, value = p.isFragmentVisible()) aapsLogger.debug(LTag.CONFIGBUILDER, "Storing: " + settingVisible + ":" + p.isFragmentVisible()) } @@ -115,18 +119,22 @@ class ConfigBuilderPlugin @Inject constructor( } private fun loadPref(p: PluginBase, type: PluginType) { - val settingEnabled = "ConfigBuilder_" + type.name + "_" + p.javaClass.simpleName + "_Enabled" - if (sp.contains(settingEnabled)) p.setPluginEnabled(type, sp.getBoolean(settingEnabled, false)) + // val settingEnabled = "ConfigBuilder_" + type.name + "_" + p.javaClass.simpleName + "_Enabled" + // if (sp.contains(settingEnabled)) p.setPluginEnabled(type, sp.getBoolean(settingEnabled, false)) + val existing = preferences.getIfExists(ConfigurationBooleanComposedKey.ConfigBuilderEnabled, type.name + "_" + p.javaClass.simpleName) + if (existing != null) p.setPluginEnabled(type, existing) else if (p.getType() == type && (p.pluginDescription.enableByDefault || p.pluginDescription.alwaysEnabled)) { p.setPluginEnabled(type, true) } - aapsLogger.debug(LTag.CONFIGBUILDER, "Loaded: " + settingEnabled + ":" + p.isEnabled(type)) - val settingVisible = "ConfigBuilder_" + type.name + "_" + p.javaClass.simpleName + "_Visible" - if (sp.contains(settingVisible)) p.setFragmentVisible(type, sp.getBoolean(settingVisible, false) && sp.getBoolean(settingEnabled, false)) + aapsLogger.debug(LTag.CONFIGBUILDER, "Loaded: " + ConfigurationBooleanComposedKey.ConfigBuilderEnabled.composeKey(type.name + "_" + p.javaClass.simpleName) + ":" + p.isEnabled(type)) + //val settingVisible = "ConfigBuilder_" + type.name + "_" + p.javaClass.simpleName + "_Visible" + //if (sp.contains(settingVisible)) p.setFragmentVisible(type, sp.getBoolean(settingVisible, false) && sp.getBoolean(settingEnabled, false)) + val existingVisible = preferences.getIfExists(ConfigurationBooleanComposedKey.ConfigBuilderVisible, type.name + "_" + p.javaClass.simpleName) + if (existingVisible != null) p.setFragmentVisible(type, existingVisible) else if (p.getType() == type && p.pluginDescription.visibleByDefault) { p.setFragmentVisible(type, true) } - aapsLogger.debug(LTag.CONFIGBUILDER, "Loaded: " + settingVisible + ":" + p.isFragmentVisible()) + aapsLogger.debug(LTag.CONFIGBUILDER, "Loaded: " + ConfigurationBooleanComposedKey.ConfigBuilderVisible.composeKey(type.name + "_" + p.javaClass.simpleName) + ":" + p.isFragmentVisible()) } fun logPluginStatus() { @@ -159,7 +167,7 @@ class ConfigBuilderPlugin @Inject constructor( } private fun confirmPumpPluginActivation(changedPlugin: PluginBase, newState: Boolean, activity: FragmentActivity, type: PluginType) { - val allowHardwarePump = sp.getBoolean("allow_hardware_pump", false) + val allowHardwarePump = preferences.get(ConfigurationBooleanKey.AllowHardwarePump) if (allowHardwarePump) { performPluginSwitch(changedPlugin, newState, type) pumpSync.connectNewPump() @@ -167,7 +175,7 @@ class ConfigBuilderPlugin @Inject constructor( OKDialog.showConfirmation(activity, rh.gs(R.string.allow_hardware_pump_text), { performPluginSwitch(changedPlugin, newState, type) pumpSync.connectNewPump() - sp.putBoolean("allow_hardware_pump", true) + preferences.put(ConfigurationBooleanKey.AllowHardwarePump, true) uel.log( action = Action.HW_PUMP_ALLOWED, source = Sources.ConfigBuilder, diff --git a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/configBuilder/RunningConfigurationImpl.kt b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/configBuilder/RunningConfigurationImpl.kt index 8eb84e17d0b..3232ce762ca 100644 --- a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/configBuilder/RunningConfigurationImpl.kt +++ b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/configBuilder/RunningConfigurationImpl.kt @@ -19,8 +19,8 @@ import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventNSClientNewLog import app.aaps.core.interfaces.smoothing.Smoothing import app.aaps.core.interfaces.ui.UiInteraction -import app.aaps.core.keys.Preferences import app.aaps.core.keys.StringKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.nssdk.interfaces.RunningConfiguration import app.aaps.core.nssdk.localmodel.devicestatus.NSDeviceStatus import app.aaps.plugins.configuration.R diff --git a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/keys/ConfigurationBooleanComposedKey.kt b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/keys/ConfigurationBooleanComposedKey.kt new file mode 100644 index 00000000000..e72ecd48345 --- /dev/null +++ b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/keys/ConfigurationBooleanComposedKey.kt @@ -0,0 +1,14 @@ +package app.aaps.plugins.configuration.keys + +import app.aaps.core.keys.interfaces.BooleanComposedNonPreferenceKey + +enum class ConfigurationBooleanComposedKey( + override val key: String, + override val format: String, + override val defaultValue: Boolean, + override val exportable: Boolean = true +) : BooleanComposedNonPreferenceKey { + + ConfigBuilderEnabled(key = "ConfigBuilder_Enabled_", format = "%s", defaultValue = false), + ConfigBuilderVisible(key = "ConfigBuilder_Visible_", format = "%s", defaultValue = false), +} diff --git a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/keys/ConfigurationBooleanKey.kt b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/keys/ConfigurationBooleanKey.kt new file mode 100644 index 00000000000..f40b7567b86 --- /dev/null +++ b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/keys/ConfigurationBooleanKey.kt @@ -0,0 +1,12 @@ +package app.aaps.plugins.configuration.keys + +import app.aaps.core.keys.interfaces.BooleanNonPreferenceKey + +enum class ConfigurationBooleanKey( + override val key: String, + override val defaultValue: Boolean, + override val exportable: Boolean = true +) : BooleanNonPreferenceKey { + + AllowHardwarePump(key = "allow_hardware_pump", defaultValue = false), +} diff --git a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/maintenance/FileListProviderImpl.kt b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/maintenance/FileListProviderImpl.kt index caf88b009cb..636bf657d69 100644 --- a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/maintenance/FileListProviderImpl.kt +++ b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/maintenance/FileListProviderImpl.kt @@ -16,8 +16,8 @@ import app.aaps.core.interfaces.rx.weardata.EventData import app.aaps.core.interfaces.storage.Storage import app.aaps.core.interfaces.versionChecker.VersionCheckerUtils import app.aaps.core.keys.BooleanKey -import app.aaps.core.keys.Preferences import app.aaps.core.keys.StringKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.ui.toast.ToastUtils import app.aaps.plugins.configuration.R import app.aaps.plugins.configuration.maintenance.data.PrefMetadataMap diff --git a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/maintenance/ImportExportPrefsImpl.kt b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/maintenance/ImportExportPrefsImpl.kt index d10bded9254..936fba6b3dc 100644 --- a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/maintenance/ImportExportPrefsImpl.kt +++ b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/maintenance/ImportExportPrefsImpl.kt @@ -50,8 +50,8 @@ import app.aaps.core.interfaces.userEntry.UserEntryPresentationHelper import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.MidnightTime import app.aaps.core.keys.BooleanKey -import app.aaps.core.keys.Preferences import app.aaps.core.keys.StringKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.extensions.asSettingsExport import app.aaps.core.objects.workflow.LoggingWorker import app.aaps.core.ui.dialogs.OKDialog @@ -86,7 +86,7 @@ import kotlin.system.exitProcess @Reusable class ImportExportPrefsImpl @Inject constructor( - private var log: AAPSLogger, + private var aapsLogger: AAPSLogger, private val rh: ResourceHelper, private val sp: SP, private val preferences: Preferences, @@ -166,7 +166,7 @@ class ImportExportPrefsImpl @Inject constructor( } private fun askForMasterPass(activity: FragmentActivity, @StringRes canceledMsg: Int, then: ((password: String) -> Unit)) { - passwordCheck.queryPassword(activity, app.aaps.core.ui.R.string.master_password, StringKey.ProtectionMasterPassword.key, { password -> + passwordCheck.queryPassword(activity, app.aaps.core.ui.R.string.master_password, StringKey.ProtectionMasterPassword, { password -> then(password) }, { ToastUtils.warnToast(activity, rh.gs(canceledMsg)) @@ -178,7 +178,7 @@ class ImportExportPrefsImpl @Inject constructor( activity: FragmentActivity, @StringRes canceledMsg: Int, @StringRes passwordName: Int, @StringRes passwordExplanation: Int?, @StringRes passwordWarning: Int?, then: ((password: String) -> Unit) ) { - passwordCheck.queryAnyPassword(activity, passwordName, StringKey.ProtectionMasterPassword.key, passwordExplanation, passwordWarning, { password -> + passwordCheck.queryAnyPassword(activity, passwordName, StringKey.ProtectionMasterPassword, passwordExplanation, passwordWarning, { password -> then(password) }, { ToastUtils.warnToast(activity, rh.gs(canceledMsg)) @@ -280,22 +280,25 @@ class ImportExportPrefsImpl @Inject constructor( try { val entries: MutableMap = mutableMapOf() for ((key, value) in sp.getAll()) { - entries[key] = value.toString() + if (preferences.isExportableKey(key)) + entries[key] = value.toString() + else + aapsLogger.warn(LTag.CORE, "Not exportable key: $key $value") } val prefs = Prefs(entries, prepareMetadata(context)) encryptedPrefsFormat.savePreferences(newFile, prefs, password) resultOk = true // Assuming export was executed successfully (or it would have thrown an exception) } catch (e: FileNotFoundException) { - log.error(LTag.CORE, "Unhandled exception: file not found", e) + aapsLogger.error(LTag.CORE, "Unhandled exception: file not found", e) } catch (e: IOException) { - log.error(LTag.CORE, "Unhandled exception: IO exception", e) + aapsLogger.error(LTag.CORE, "Unhandled exception: IO exception", e) } catch (e: PrefFileNotFoundError) { - log.error(LTag.CORE, "File system exception: Pref File not found, export canceled", e) + aapsLogger.error(LTag.CORE, "File system exception: Pref File not found, export canceled", e) } catch (e: PrefIOError) { - log.error(LTag.CORE, "File system exception: PrefIOError, export canceled", e) + aapsLogger.error(LTag.CORE, "File system exception: PrefIOError, export canceled", e) } - log.debug(LTag.CORE, "savePreferences: $resultOk") + aapsLogger.debug(LTag.CORE, "savePreferences: $resultOk") return resultOk } @@ -342,7 +345,7 @@ class ImportExportPrefsImpl @Inject constructor( // this exception happens on some early implementations of ActivityResult contracts // when registered and called for the second time ToastUtils.errorToast(activity, rh.gs(R.string.goto_main_try_again)) - log.error(LTag.CORE, "Internal android framework exception", e) + aapsLogger.error(LTag.CORE, "Internal android framework exception", e) } } @@ -358,7 +361,7 @@ class ImportExportPrefsImpl @Inject constructor( // this exception happens on some early implementations of ActivityResult contracts // when registered and called for the second time ToastUtils.errorToast(activity, rh.gs(R.string.goto_main_try_again)) - log.error(LTag.CORE, "Internal android framework exception", e) + aapsLogger.error(LTag.CORE, "Internal android framework exception", e) } } @@ -414,9 +417,9 @@ class ImportExportPrefsImpl @Inject constructor( } catch (e: PrefFileNotFoundError) { ToastUtils.errorToast(activity, rh.gs(R.string.filenotfound) + " " + importFile) - log.error(LTag.CORE, "Unhandled exception", e) + aapsLogger.error(LTag.CORE, "Unhandled exception", e) } catch (e: PrefIOError) { - log.error(LTag.CORE, "Unhandled exception", e) + aapsLogger.error(LTag.CORE, "Unhandled exception", e) ToastUtils.errorToast(activity, e.message) } } @@ -437,7 +440,7 @@ class ImportExportPrefsImpl @Inject constructor( preferences.put(BooleanKey.GeneralSetupWizardProcessed, true) OKDialog.show(context, rh.gs(R.string.setting_imported), rh.gs(R.string.restartingapp)) { uel.log(Action.IMPORT_SETTINGS, Sources.Maintenance) - log.debug(LTag.CORE, "Exiting") + aapsLogger.debug(LTag.CORE, "Exiting") rxBus.send(EventAppExit()) if (context is AppCompatActivity) { context.finish() diff --git a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/maintenance/MaintenancePlugin.kt b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/maintenance/MaintenancePlugin.kt index aefeed19a88..c8398cbc848 100644 --- a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/maintenance/MaintenancePlugin.kt +++ b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/maintenance/MaintenancePlugin.kt @@ -21,8 +21,8 @@ import app.aaps.core.interfaces.plugin.PluginDescription import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.keys.BooleanKey import app.aaps.core.keys.IntKey -import app.aaps.core.keys.Preferences import app.aaps.core.keys.StringKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.ui.toast.ToastUtils import app.aaps.core.validators.DefaultEditTextValidator import app.aaps.core.validators.EditTextValidator diff --git a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/maintenance/activities/CustomWatchfaceImportListActivity.kt b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/maintenance/activities/CustomWatchfaceImportListActivity.kt index 53b8fa8b10e..efbe2c2bfb5 100644 --- a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/maintenance/activities/CustomWatchfaceImportListActivity.kt +++ b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/maintenance/activities/CustomWatchfaceImportListActivity.kt @@ -20,10 +20,10 @@ import app.aaps.core.interfaces.rx.weardata.CwfMetadataKey.CWF_FILENAME import app.aaps.core.interfaces.rx.weardata.CwfMetadataKey.CWF_NAME import app.aaps.core.interfaces.rx.weardata.CwfMetadataKey.CWF_VERSION import app.aaps.core.interfaces.rx.weardata.CwfMetadataMap -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.versionChecker.VersionCheckerUtils import app.aaps.core.keys.BooleanKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.StringNonKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.ui.activities.TranslatedDaggerAppCompatActivity import app.aaps.core.ui.extensions.toVisibility import app.aaps.plugins.configuration.R @@ -37,7 +37,6 @@ import javax.inject.Inject class CustomWatchfaceImportListActivity : TranslatedDaggerAppCompatActivity() { @Inject lateinit var rh: ResourceHelper - @Inject lateinit var sp: SP @Inject lateinit var preferences: Preferences @Inject lateinit var fileListProvider: FileListProvider @Inject lateinit var rxBus: RxBus @@ -70,9 +69,9 @@ class CustomWatchfaceImportListActivity : TranslatedDaggerAppCompatActivity() { root.isClickable = true customWatchfaceImportListItemBinding.root.setOnClickListener { val customWatchfaceFile = filelistName.tag as CwfFile - sp.putString(app.aaps.core.utils.R.string.key_wear_cwf_watchface_name, customWatchfaceFile.cwfData.metadata[CWF_NAME] ?: "") - sp.putString(app.aaps.core.utils.R.string.key_wear_cwf_author_version, customWatchfaceFile.cwfData.metadata[CWF_AUTHOR_VERSION] ?: "") - sp.putString(app.aaps.core.utils.R.string.key_wear_cwf_filename, customWatchfaceFile.cwfData.metadata[CWF_FILENAME] ?: "") + preferences.put(StringNonKey.WearCwfWatchfaceName, customWatchfaceFile.cwfData.metadata[CWF_NAME] ?: "") + preferences.put(StringNonKey.WearCwfAuthorVersion, customWatchfaceFile.cwfData.metadata[CWF_AUTHOR_VERSION] ?: "") + preferences.put(StringNonKey.WearCwfFileName, customWatchfaceFile.cwfData.metadata[CWF_FILENAME] ?: "") val i = Intent() setResult(RESULT_OK, i) diff --git a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/maintenance/activities/LogSettingActivity.kt b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/maintenance/activities/LogSettingActivity.kt index b4d35e8884f..2d6d9240ff9 100644 --- a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/maintenance/activities/LogSettingActivity.kt +++ b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/maintenance/activities/LogSettingActivity.kt @@ -39,7 +39,7 @@ class LogSettingActivity : TranslatedDaggerAppCompatActivity() { private fun createViewsForSettings() { binding.placeholder.removeAllViews() - for (element in l.getLogElements()) { + for (element in l.logElements()) { val logViewHolder = LogViewHolder(element) binding.placeholder.addView(logViewHolder.baseView) } diff --git a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/SWDefinition.kt b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/SWDefinition.kt index 21d9330c500..e770da4ce41 100644 --- a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/SWDefinition.kt +++ b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/SWDefinition.kt @@ -6,7 +6,6 @@ import android.content.Intent import android.net.Uri import android.provider.Settings import androidx.appcompat.app.AppCompatActivity -import app.aaps.core.data.configuration.Constants import app.aaps.core.data.plugin.PluginType import app.aaps.core.interfaces.androidPermissions.AndroidPermission import app.aaps.core.interfaces.aps.Loop @@ -28,14 +27,14 @@ import app.aaps.core.interfaces.rx.events.EventPumpStatusChanged import app.aaps.core.interfaces.rx.events.EventSWRLStatus import app.aaps.core.interfaces.rx.events.EventSWSyncStatus import app.aaps.core.interfaces.rx.events.EventSWUpdate -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.interfaces.utils.HardLimits +import app.aaps.core.keys.BooleanNonKey import app.aaps.core.keys.DoubleKey import app.aaps.core.keys.IntKey -import app.aaps.core.keys.Preferences import app.aaps.core.keys.StringKey import app.aaps.core.keys.UnitDoubleKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.crypto.CryptoUtil import app.aaps.core.objects.profile.ProfileSealed import app.aaps.core.utils.isRunningTest @@ -64,7 +63,6 @@ class SWDefinition @Inject constructor( private val rxBus: RxBus, private val context: Context, private val rh: ResourceHelper, - private val sp: SP, private val preferences: Preferences, private val profileFunction: ProfileFunction, private val activePlugin: ActivePlugin, @@ -88,7 +86,7 @@ class SWDefinition @Inject constructor( when { config.APS -> swDefinitionFull() config.PUMPCONTROL -> swDefinitionPumpControl() - config.AAPSCLIENT -> swDefinitionNSClient() + config.AAPSCLIENT -> swDefinitionNSClient() } } return screens @@ -111,13 +109,13 @@ class SWDefinition @Inject constructor( .add( SWButton(injector) .text(R.string.end_user_license_agreement_i_understand) - .visibility { !sp.getBoolean(R.string.key_i_understand, false) } + .visibility { !preferences.get(BooleanNonKey.SetupWizardIUnderstand) } .action { - sp.putBoolean(R.string.key_i_understand, true) + preferences.put(BooleanNonKey.SetupWizardIUnderstand, true) rxBus.send(EventSWUpdate(false)) }) - .visibility { !sp.getBoolean(R.string.key_i_understand, false) } - .validator { sp.getBoolean(R.string.key_i_understand, false) } + .visibility { !preferences.get(BooleanNonKey.SetupWizardIUnderstand) } + .validator { preferences.get(BooleanNonKey.SetupWizardIUnderstand) } private val screenUnits get() = SWScreen(injector, R.string.units) @@ -125,7 +123,7 @@ class SWDefinition @Inject constructor( .add( SWRadioButton(injector) .option(uiInteraction.unitsEntries, uiInteraction.unitsValues) - .preference(StringKey.GeneralUnits.key).label(R.string.units) + .preference(StringKey.GeneralUnits).label(R.string.units) .comment(R.string.setupwizard_units_prompt) ) .validator { preferences.getIfExists(StringKey.GeneralUnits) != null } @@ -134,7 +132,7 @@ class SWDefinition @Inject constructor( get() = SWScreen(injector, R.string.display_settings) .skippable(false) .add( - SWEditNumberWithUnits(injector, UnitDoubleKey.OverviewLowMark.defaultValue * Constants.MGDL_TO_MMOLL, 3.0, 8.0) + SWEditNumberWithUnits(injector) .preference(UnitDoubleKey.OverviewLowMark) .updateDelay(5) .label(R.string.low_mark) @@ -142,7 +140,7 @@ class SWDefinition @Inject constructor( ) .add(SWBreak(injector)) .add( - SWEditNumberWithUnits(injector, UnitDoubleKey.OverviewHighMark.defaultValue * Constants.MGDL_TO_MMOLL, 5.0, 20.0) + SWEditNumberWithUnits(injector) .preference(UnitDoubleKey.OverviewHighMark) .updateDelay(5) .label(R.string.high_mark) @@ -249,20 +247,20 @@ class SWDefinition @Inject constructor( .add( SWRadioButton(injector) .option(hardLimits.ageEntries(), hardLimits.ageEntryValues()) - .preference(StringKey.SafetyAge.key) + .preference(StringKey.SafetyAge) .label(app.aaps.core.ui.R.string.patient_type) .comment(app.aaps.core.ui.R.string.patient_age_summary) ) .add(SWBreak(injector)) .add( - SWEditNumber(injector, 3.0, 0.1, 25.0) + SWEditNumber(injector) .preference(DoubleKey.SafetyMaxBolus) .updateDelay(5) .label(app.aaps.core.ui.R.string.max_bolus_title) .comment(R.string.common_values) ) .add( - SWEditIntNumber(injector, 48, 1, 100) + SWEditIntNumber(injector) .preference(IntKey.SafetyMaxCarbs) .updateDelay(5) .label(app.aaps.core.ui.R.string.max_carbs_title) @@ -371,7 +369,7 @@ class SWDefinition @Inject constructor( .add( SWRadioButton(injector) .option(loop.entries(), loop.entryValues()) - .preference(StringKey.LoopApsMode.key).label(R.string.apsmode_title) + .preference(StringKey.LoopApsMode).label(R.string.apsmode_title) .comment(R.string.setupwizard_preferred_aps_mode) ) .validator { preferences.getIfExists(StringKey.LoopApsMode) != null } diff --git a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/elements/SWEditEncryptedPassword.kt b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/elements/SWEditEncryptedPassword.kt index 3ddcaa8c1de..88bd71feeb6 100644 --- a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/elements/SWEditEncryptedPassword.kt +++ b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/elements/SWEditEncryptedPassword.kt @@ -10,6 +10,7 @@ import android.widget.EditText import android.widget.LinearLayout import android.widget.TextView import app.aaps.core.keys.StringKey +import app.aaps.core.keys.interfaces.StringPreferenceKey import app.aaps.core.objects.crypto.CryptoUtil import app.aaps.core.ui.extensions.toVisibility import dagger.android.HasAndroidInjector @@ -33,7 +34,7 @@ class SWEditEncryptedPassword(injector: HasAndroidInjector, private val cryptoUt button?.setText(app.aaps.core.ui.R.string.unlock_settings) button?.setOnClickListener { scanForActivity(context)?.let { activity -> - passwordCheck.queryPassword(activity, app.aaps.core.ui.R.string.master_password, StringKey.ProtectionMasterPassword.key, { + passwordCheck.queryPassword(activity, app.aaps.core.ui.R.string.master_password, StringKey.ProtectionMasterPassword, { button?.visibility = View.GONE editText?.visibility = View.VISIBLE editText2?.visibility = View.VISIBLE @@ -89,7 +90,7 @@ class SWEditEncryptedPassword(injector: HasAndroidInjector, private val cryptoUt val watcher = object : TextWatcher { override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { - sp.remove(preference) + preferences.remove(preference as StringPreferenceKey) scheduleChange(updateDelay) if (validator.invoke(editText?.text.toString()) && validator.invoke(editText2?.text.toString()) && editText?.text.toString() == editText2?.text.toString()) save(s.toString(), updateDelay) @@ -102,12 +103,12 @@ class SWEditEncryptedPassword(injector: HasAndroidInjector, private val cryptoUt } fun preference(preference: StringKey): SWEditEncryptedPassword { - this.preference = preference.key + this.preference = preference return this } override fun save(value: CharSequence, updateDelay: Long) { - sp.putString(preference, cryptoUtil.hashPassword(value.toString())) + preferences.put(preference as StringPreferenceKey, cryptoUtil.hashPassword(value.toString())) scheduleChange(updateDelay) } } \ No newline at end of file diff --git a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/elements/SWEditIntNumber.kt b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/elements/SWEditIntNumber.kt index b04d0aa2ffd..3cf9fbe2fce 100644 --- a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/elements/SWEditIntNumber.kt +++ b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/elements/SWEditIntNumber.kt @@ -7,14 +7,14 @@ import android.view.View import android.widget.LinearLayout import android.widget.TextView import app.aaps.core.interfaces.utils.SafeParse -import app.aaps.core.keys.IntKey +import app.aaps.core.keys.interfaces.IntPreferenceKey import app.aaps.core.ui.elements.NumberPicker import dagger.android.HasAndroidInjector import java.text.DecimalFormat -class SWEditIntNumber(injector: HasAndroidInjector, private val init: Int, private val min: Int, private val max: Int) : SWItem(injector, Type.NUMBER) { +class SWEditIntNumber(injector: HasAndroidInjector) : SWItem(injector, Type.NUMBER) { - private val validator: (Int) -> Boolean = { value -> value in min..max } + private val validator: (Int) -> Boolean = { value -> value in (preference as IntPreferenceKey).min..(preference as IntPreferenceKey).max } private var updateDelay = 0 override fun generateDialog(layout: LinearLayout) { @@ -34,9 +34,9 @@ class SWEditIntNumber(injector: HasAndroidInjector, private val init: Int, priva label?.let { l.setText(it) } l.setTypeface(l.typeface, Typeface.BOLD) layout.addView(l) - val initValue = sp.getInt(preference, init) + val initValue = preferences.get(preference as IntPreferenceKey) val numberPicker = NumberPicker(context) - numberPicker.setParams(initValue.toDouble(), min.toDouble(), max.toDouble(), 1.0, DecimalFormat("0"), false, null, watcher) + numberPicker.setParams(initValue.toDouble(), (preference as IntPreferenceKey).min.toDouble(), (preference as IntPreferenceKey).max.toDouble(), 1.0, DecimalFormat("0"), false, null, watcher) layout.addView(numberPicker) val c = TextView(context) @@ -47,8 +47,8 @@ class SWEditIntNumber(injector: HasAndroidInjector, private val init: Int, priva super.generateDialog(layout) } - fun preference(preference: IntKey): SWEditIntNumber { - this.preference = preference.key + fun preference(preference: IntPreferenceKey): SWEditIntNumber { + this.preference = preference return this } diff --git a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/elements/SWEditNumber.kt b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/elements/SWEditNumber.kt index 920a67c9b78..64af70ec669 100644 --- a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/elements/SWEditNumber.kt +++ b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/elements/SWEditNumber.kt @@ -7,14 +7,14 @@ import android.view.View import android.widget.LinearLayout import android.widget.TextView import app.aaps.core.interfaces.utils.SafeParse -import app.aaps.core.keys.DoubleKey +import app.aaps.core.keys.interfaces.DoublePreferenceKey import app.aaps.core.ui.elements.NumberPicker import dagger.android.HasAndroidInjector import java.text.DecimalFormat -class SWEditNumber(injector: HasAndroidInjector, private val init: Double, private val min: Double, private val max: Double) : SWItem(injector, Type.DECIMAL_NUMBER) { +class SWEditNumber(injector: HasAndroidInjector) : SWItem(injector, Type.DECIMAL_NUMBER) { - private val validator: (Double) -> Boolean = { value -> value in min..max } + private val validator: (Double) -> Boolean = { value -> value in (preference as DoublePreferenceKey).min..(preference as DoublePreferenceKey).max } private var updateDelay = 0 override fun generateDialog(layout: LinearLayout) { @@ -34,9 +34,9 @@ class SWEditNumber(injector: HasAndroidInjector, private val init: Double, priva label?.let { l.setText(it) } l.setTypeface(l.typeface, Typeface.BOLD) layout.addView(l) - val initValue = sp.getDouble(preference, init) + val initValue = preferences.get(preference as DoublePreferenceKey) val numberPicker = NumberPicker(context) - numberPicker.setParams(initValue, min, max, 0.1, DecimalFormat("0.0"), false, null, watcher) + numberPicker.setParams(initValue, (preference as DoublePreferenceKey).min, (preference as DoublePreferenceKey).max, 0.1, DecimalFormat("0.0"), false, null, watcher) layout.addView(numberPicker) val c = TextView(context) @@ -47,8 +47,8 @@ class SWEditNumber(injector: HasAndroidInjector, private val init: Double, priva super.generateDialog(layout) } - fun preference(preference: DoubleKey): SWEditNumber { - this.preference = preference.key + fun preference(preference: DoublePreferenceKey): SWEditNumber { + this.preference = preference return this } diff --git a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/elements/SWEditNumberWithUnits.kt b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/elements/SWEditNumberWithUnits.kt index 5935513d130..123422a5bb6 100644 --- a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/elements/SWEditNumberWithUnits.kt +++ b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/elements/SWEditNumberWithUnits.kt @@ -10,19 +10,19 @@ import app.aaps.core.data.configuration.Constants import app.aaps.core.data.model.GlucoseUnit import app.aaps.core.interfaces.profile.ProfileUtil import app.aaps.core.interfaces.utils.SafeParse -import app.aaps.core.keys.UnitDoubleKey +import app.aaps.core.keys.interfaces.UnitDoublePreferenceKey import app.aaps.core.ui.elements.NumberPicker import dagger.android.HasAndroidInjector import java.text.DecimalFormat import javax.inject.Inject -class SWEditNumberWithUnits(injector: HasAndroidInjector, private val init: Double, private val minMmol: Double, private val maxMmol: Double) : SWItem(injector, Type.UNIT_NUMBER) { +class SWEditNumberWithUnits(injector: HasAndroidInjector) : SWItem(injector, Type.UNIT_NUMBER) { @Inject lateinit var profileUtil: ProfileUtil private val validator: (Double) -> Boolean = - if (profileUtil.units == GlucoseUnit.MMOL) { value -> value in minMmol..maxMmol } - else { value -> value in minMmol * Constants.MMOLL_TO_MGDL..maxMmol * Constants.MMOLL_TO_MGDL } + if (profileUtil.units == GlucoseUnit.MGDL) { value -> value in (preference as UnitDoublePreferenceKey).minMgdl.toDouble()..(preference as UnitDoublePreferenceKey).maxMgdl.toDouble() } + else { value -> value in (preference as UnitDoublePreferenceKey).minMgdl * Constants.MGDL_TO_MMOLL..(preference as UnitDoublePreferenceKey).maxMgdl * Constants.MGDL_TO_MMOLL } private var updateDelay = 0 override fun generateDialog(layout: LinearLayout) { @@ -42,13 +42,13 @@ class SWEditNumberWithUnits(injector: HasAndroidInjector, private val init: Doub label?.let { l.setText(it) } l.setTypeface(l.typeface, Typeface.BOLD) layout.addView(l) - var initValue = sp.getDouble(preference, init) + var initValue = preferences.get(preference as UnitDoublePreferenceKey) initValue = profileUtil.valueInCurrentUnitsDetect(initValue) val numberPicker = NumberPicker(context) if (profileUtil.units == GlucoseUnit.MMOL) - numberPicker.setParams(initValue, minMmol, maxMmol, 0.1, DecimalFormat("0.0"), false, null, watcher) + numberPicker.setParams(initValue, (preference as UnitDoublePreferenceKey).minMgdl * Constants.MGDL_TO_MMOLL, (preference as UnitDoublePreferenceKey).maxMgdl * Constants.MGDL_TO_MMOLL, 0.1, DecimalFormat("0.0"), false, null, watcher) else - numberPicker.setParams(initValue, minMmol * Constants.MMOLL_TO_MGDL, maxMmol * Constants.MMOLL_TO_MGDL, 1.0, DecimalFormat("0"), false, null, watcher) + numberPicker.setParams(initValue, (preference as UnitDoublePreferenceKey).minMgdl.toDouble(), (preference as UnitDoublePreferenceKey).maxMgdl.toDouble(), 1.0, DecimalFormat("0"), false, null, watcher) layout.addView(numberPicker) val c = TextView(context) @@ -59,8 +59,8 @@ class SWEditNumberWithUnits(injector: HasAndroidInjector, private val init: Doub super.generateDialog(layout) } - fun preference(preference: UnitDoubleKey): SWEditNumberWithUnits { - this.preference = preference.key + fun preference(preference: UnitDoublePreferenceKey): SWEditNumberWithUnits { + this.preference = preference return this } diff --git a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/elements/SWEditString.kt b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/elements/SWEditString.kt index 7ebcb936b8f..c992c3b9fbb 100644 --- a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/elements/SWEditString.kt +++ b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/elements/SWEditString.kt @@ -8,7 +8,7 @@ import android.view.View import android.widget.EditText import android.widget.LinearLayout import android.widget.TextView -import app.aaps.core.keys.StringKey +import app.aaps.core.keys.interfaces.StringPreferenceKey import dagger.android.HasAndroidInjector class SWEditString(injector: HasAndroidInjector) : SWItem(injector, Type.STRING) { @@ -32,7 +32,7 @@ class SWEditString(injector: HasAndroidInjector) : SWItem(injector, Type.STRING) editText.id = View.generateViewId() editText.inputType = InputType.TYPE_CLASS_TEXT editText.maxLines = 1 - editText.setText(sp.getString(preference, "")) + editText.setText(preferences.get(preference as StringPreferenceKey)) layout.addView(editText) super.generateDialog(layout) editText.addTextChangedListener(object : TextWatcher { @@ -45,8 +45,8 @@ class SWEditString(injector: HasAndroidInjector) : SWItem(injector, Type.STRING) }) } - fun preference(preference: StringKey): SWEditString { - this.preference = preference.key + fun preference(preference: StringPreferenceKey): SWEditString { + this.preference = preference return this } diff --git a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/elements/SWEditUrl.kt b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/elements/SWEditUrl.kt index a6f4606c399..cc50ecc8fdf 100644 --- a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/elements/SWEditUrl.kt +++ b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/elements/SWEditUrl.kt @@ -9,6 +9,7 @@ import android.view.View import android.widget.EditText import android.widget.LinearLayout import android.widget.TextView +import app.aaps.core.keys.interfaces.StringPreferenceKey import app.aaps.plugins.configuration.setupwizard.events.EventSWLabel import dagger.android.HasAndroidInjector @@ -32,7 +33,7 @@ class SWEditUrl(injector: HasAndroidInjector) : SWItem(injector, Type.URL) { editText.id = View.generateViewId() editText.inputType = InputType.TYPE_CLASS_TEXT editText.maxLines = 1 - editText.setText(sp.getString(preference, "")) + editText.setText(preferences.get(preference as StringPreferenceKey)) layout.addView(editText) super.generateDialog(layout) editText.addTextChangedListener(object : TextWatcher { @@ -45,7 +46,7 @@ class SWEditUrl(injector: HasAndroidInjector) : SWItem(injector, Type.URL) { }) } - fun preference(preference: String): SWEditUrl { + fun preference(preference: StringPreferenceKey): SWEditUrl { this.preference = preference return this } diff --git a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/elements/SWItem.kt b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/elements/SWItem.kt index 06cd6c972d3..cded8a91517 100644 --- a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/elements/SWItem.kt +++ b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/elements/SWItem.kt @@ -13,8 +13,10 @@ import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventPreferenceChange import app.aaps.core.interfaces.rx.events.EventSWUpdate -import app.aaps.core.interfaces.sharedPreferences.SP -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.PreferenceKey +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.core.keys.interfaces.StringNonPreferenceKey +import app.aaps.core.keys.interfaces.StringPreferenceKey import dagger.android.HasAndroidInjector import java.util.concurrent.Executors import java.util.concurrent.ScheduledFuture @@ -26,7 +28,6 @@ open class SWItem(val injector: HasAndroidInjector, var type: Type) { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var rxBus: RxBus @Inject lateinit var rh: ResourceHelper - @Inject lateinit var sp: SP @Inject lateinit var preferences: Preferences @Inject lateinit var passwordCheck: PasswordCheck @@ -46,7 +47,7 @@ open class SWItem(val injector: HasAndroidInjector, var type: Type) { var label: Int? = null var comment: Int? = null - var preference = "UNKNOWN" + var preference: PreferenceKey? = null open fun label(@StringRes label: Int): SWItem { this.label = label @@ -59,7 +60,10 @@ open class SWItem(val injector: HasAndroidInjector, var type: Type) { } open fun save(value: CharSequence, updateDelay: Long) { - sp.putString(preference, value.toString()) + if (preference is StringNonPreferenceKey) + preferences.put(preference as StringNonPreferenceKey, value.toString()) + if (preference is StringPreferenceKey) + preferences.put(preference as StringPreferenceKey, value.toString()) scheduleChange(updateDelay) } @@ -77,7 +81,7 @@ open class SWItem(val injector: HasAndroidInjector, var type: Type) { override fun run() { aapsLogger.debug(LTag.CORE, "Firing EventPreferenceChange") - rxBus.send(EventPreferenceChange(preference)) + rxBus.send(EventPreferenceChange(preference?.key ?: "")) rxBus.send(EventSWUpdate(false)) scheduledEventPost = null } diff --git a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/elements/SWRadioButton.kt b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/elements/SWRadioButton.kt index b27633eeb98..23292dbe706 100644 --- a/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/elements/SWRadioButton.kt +++ b/plugins/configuration/src/main/kotlin/app/aaps/plugins/configuration/setupwizard/elements/SWRadioButton.kt @@ -6,6 +6,7 @@ import android.widget.LinearLayout import android.widget.RadioButton import android.widget.RadioGroup import android.widget.TextView +import app.aaps.core.keys.interfaces.StringPreferenceKey import dagger.android.HasAndroidInjector class SWRadioButton(injector: HasAndroidInjector) : SWItem(injector, Type.RADIOBUTTON) { @@ -37,8 +38,8 @@ class SWRadioButton(injector: HasAndroidInjector) : SWItem(injector, Type.RADIOB desc.layoutParams = params layout.addView(desc) - // Get if there is already value in SP - val previousValue = preferences.get(preference) + // Get if there is already value in Preferences + val previousValue = preferences.get(preference as StringPreferenceKey) radioGroup = RadioGroup(context) radioGroup?.clearCheck() radioGroup?.orientation = LinearLayout.VERTICAL @@ -59,7 +60,7 @@ class SWRadioButton(injector: HasAndroidInjector) : SWItem(injector, Type.RADIOB super.generateDialog(layout) } - fun preference(preference: String): SWRadioButton { + fun preference(preference: StringPreferenceKey): SWRadioButton { this.preference = preference return this } diff --git a/plugins/configuration/src/main/res/values/strings.xml b/plugins/configuration/src/main/res/values/strings.xml index d5bbf9d7c8a..942df38e20b 100644 --- a/plugins/configuration/src/main/res/values/strings.xml +++ b/plugins/configuration/src/main/res/values/strings.xml @@ -1,7 +1,5 @@ - I_understand - Units Select units you want to display values in Next diff --git a/plugins/configuration/src/test/kotlin/app/aaps/configuration/maintenance/MaintenancePluginTest.kt b/plugins/configuration/src/test/kotlin/app/aaps/configuration/maintenance/MaintenancePluginTest.kt index c2b929c141a..6ee67ca4bc9 100644 --- a/plugins/configuration/src/test/kotlin/app/aaps/configuration/maintenance/MaintenancePluginTest.kt +++ b/plugins/configuration/src/test/kotlin/app/aaps/configuration/maintenance/MaintenancePluginTest.kt @@ -1,13 +1,9 @@ package app.aaps.configuration.maintenance -import android.content.SharedPreferences import app.aaps.core.interfaces.logging.LoggerUtils import app.aaps.core.interfaces.logging.UserEntryLogger import app.aaps.core.interfaces.maintenance.FileListProvider import app.aaps.core.interfaces.nsclient.NSSettingsStatus -import app.aaps.core.validators.preferences.AdaptiveIntPreference -import app.aaps.core.validators.preferences.AdaptiveStringPreference -import app.aaps.core.validators.preferences.AdaptiveSwitchPreference import app.aaps.plugins.configuration.maintenance.MaintenancePlugin import app.aaps.shared.tests.TestBaseWithProfile import com.google.common.truth.Truth.assertThat @@ -21,32 +17,10 @@ class MaintenancePluginTest : TestBaseWithProfile() { @Mock lateinit var nsSettingsStatus: NSSettingsStatus @Mock lateinit var loggerUtils: LoggerUtils @Mock lateinit var fileListProvider: FileListProvider - @Mock lateinit var sharedPrefs: SharedPreferences @Mock lateinit var uel: UserEntryLogger private lateinit var sut: MaintenancePlugin - init { - addInjector { - if (it is AdaptiveIntPreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - it.config = config - } - if (it is AdaptiveSwitchPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - it.config = config - } - if (it is AdaptiveStringPreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - } - } - @BeforeEach fun mock() { sut = MaintenancePlugin(context, rh, preferences, nsSettingsStatus, aapsLogger, config, fileListProvider, loggerUtils, uel) diff --git a/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/dstHelper/DstHelperPlugin.kt b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/dstHelper/DstHelperPlugin.kt index 36607a70749..b3ad172baa4 100644 --- a/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/dstHelper/DstHelperPlugin.kt +++ b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/dstHelper/DstHelperPlugin.kt @@ -9,12 +9,13 @@ import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.notifications.Notification import app.aaps.core.interfaces.plugin.ActivePlugin -import app.aaps.core.interfaces.plugin.PluginBase +import app.aaps.core.interfaces.plugin.PluginBaseWithPreferences import app.aaps.core.interfaces.plugin.PluginDescription import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.ui.UiInteraction +import app.aaps.core.keys.interfaces.Preferences import app.aaps.plugins.constraints.R +import app.aaps.plugins.constraints.dstHelper.keys.DstHelperLongKey import java.util.Calendar import javax.inject.Inject import javax.inject.Singleton @@ -23,18 +24,19 @@ import javax.inject.Singleton class DstHelperPlugin @Inject constructor( aapsLogger: AAPSLogger, rh: ResourceHelper, - private val sp: SP, + preferences: Preferences, private val activePlugin: ActivePlugin, private val uiInteraction: UiInteraction, private val loop: Loop -) : PluginBase( - PluginDescription() +) : PluginBaseWithPreferences( + pluginDescription = PluginDescription() .mainType(PluginType.CONSTRAINTS) .neverVisible(true) .alwaysEnabled(true) .showInList { false } .pluginName(R.string.dst_plugin_name), - aapsLogger, rh + ownPreferences = listOf(DstHelperLongKey::class.java), + aapsLogger, rh, preferences ), PluginConstraints { companion object { @@ -52,10 +54,10 @@ class DstHelperPlugin @Inject constructor( } val cal = Calendar.getInstance() if (willBeDST(cal)) { - val snoozedTo: Long = sp.getLong(R.string.key_snooze_dst_in24h, 0L) + val snoozedTo: Long = preferences.get(DstHelperLongKey.SnoozeDstIn24h) if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo) { uiInteraction.addNotification(Notification.DST_IN_24H, rh.gs(R.string.dst_in_24h_warning), Notification.LOW, app.aaps.core.ui.R.string.snooze, { - sp.putLong(R.string.key_snooze_dst_in24h, System.currentTimeMillis() + T.hours(24).msecs()) + preferences.put(DstHelperLongKey.SnoozeDstIn24h, System.currentTimeMillis() + T.hours(24).msecs()) }, null) } } @@ -65,14 +67,14 @@ class DstHelperPlugin @Inject constructor( } if (wasDST(cal)) { if (!loop.isSuspended) { - val snoozedTo: Long = sp.getLong(R.string.key_snooze_loop_disabled, 0L) + val snoozedTo: Long = preferences.get(DstHelperLongKey.SnoozeLoopDisabled) if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo) { uiInteraction.addNotification( id = Notification.DST_LOOP_DISABLED, text = rh.gs(R.string.dst_loop_disabled_warning), level = Notification.LOW, actionButtonId = app.aaps.core.ui.R.string.snooze, - action = { sp.putLong(R.string.key_snooze_loop_disabled, System.currentTimeMillis() + T.hours(24).msecs()) }, + action = { preferences.put(DstHelperLongKey.SnoozeLoopDisabled, System.currentTimeMillis() + T.hours(24).msecs()) }, validityCheck = null ) } diff --git a/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/dstHelper/keys/DstHelperLongKey.kt b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/dstHelper/keys/DstHelperLongKey.kt new file mode 100644 index 00000000000..f21176f0b13 --- /dev/null +++ b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/dstHelper/keys/DstHelperLongKey.kt @@ -0,0 +1,13 @@ +package app.aaps.plugins.constraints.dstHelper.keys + +import app.aaps.core.keys.interfaces.LongNonPreferenceKey + +enum class DstHelperLongKey( + override val key: String, + override val defaultValue: Long, + override val exportable: Boolean = true +) : LongNonPreferenceKey { + + SnoozeDstIn24h(key = "snooze_dst_in24h", 0L), + SnoozeLoopDisabled(key = "snooze_loop_disabled", 0L), +} diff --git a/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/objectives/ObjectivesFragment.kt b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/objectives/ObjectivesFragment.kt index 8c37e0954be..6712794cb1c 100644 --- a/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/objectives/ObjectivesFragment.kt +++ b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/objectives/ObjectivesFragment.kt @@ -27,7 +27,6 @@ import app.aaps.core.interfaces.rx.AapsSchedulers import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventNtpStatus import app.aaps.core.interfaces.rx.events.EventSWUpdate -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.fabric.FabricPrivacy import app.aaps.core.ui.dialogs.OKDialog @@ -50,7 +49,6 @@ class ObjectivesFragment : DaggerFragment() { @Inject lateinit var rxBus: RxBus @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsSchedulers: AapsSchedulers - @Inject lateinit var sp: SP @Inject lateinit var rh: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var objectivesPlugin: ObjectivesPlugin diff --git a/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/objectives/ObjectivesPlugin.kt b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/objectives/ObjectivesPlugin.kt index e1ab50d7ca6..5fcfd0c6b27 100644 --- a/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/objectives/ObjectivesPlugin.kt +++ b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/objectives/ObjectivesPlugin.kt @@ -11,11 +11,15 @@ import app.aaps.core.interfaces.constraints.Objectives.Companion.MAXIOB_ZERO_CL_ import app.aaps.core.interfaces.constraints.Objectives.Companion.SMB_OBJECTIVE import app.aaps.core.interfaces.constraints.PluginConstraints import app.aaps.core.interfaces.logging.AAPSLogger -import app.aaps.core.interfaces.plugin.PluginBase +import app.aaps.core.interfaces.plugin.PluginBaseWithPreferences import app.aaps.core.interfaces.plugin.PluginDescription import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.BooleanNonKey +import app.aaps.core.keys.IntNonKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.plugins.constraints.R +import app.aaps.plugins.constraints.objectives.keys.ObjectivesBooleanComposedKey +import app.aaps.plugins.constraints.objectives.keys.ObjectivesLongComposedKey import app.aaps.plugins.constraints.objectives.objectives.Objective import app.aaps.plugins.constraints.objectives.objectives.Objective0 import app.aaps.plugins.constraints.objectives.objectives.Objective1 @@ -36,16 +40,17 @@ class ObjectivesPlugin @Inject constructor( private val injector: HasAndroidInjector, aapsLogger: AAPSLogger, rh: ResourceHelper, - private val sp: SP, -) : PluginBase( - PluginDescription() + preferences: Preferences +) : PluginBaseWithPreferences( + pluginDescription = PluginDescription() .mainType(PluginType.CONSTRAINTS) .fragmentClass(ObjectivesFragment::class.qualifiedName) .pluginIcon(app.aaps.core.ui.R.drawable.ic_graduation) .pluginName(app.aaps.core.ui.R.string.objectives) .shortName(R.string.objectives_shortname) .description(R.string.description_objectives), - aapsLogger, rh + ownPreferences = listOf(ObjectivesBooleanComposedKey::class.java, ObjectivesLongComposedKey::class.java), + aapsLogger, rh, preferences ), PluginConstraints, Objectives { var objectives: MutableList = ArrayList() @@ -74,16 +79,16 @@ class ObjectivesPlugin @Inject constructor( objective.startedOn = 0 objective.accomplishedOn = 0 } - sp.putBoolean(app.aaps.core.utils.R.string.key_objectives_bg_is_available_in_ns, false) - sp.putBoolean(app.aaps.core.utils.R.string.key_objectives_pump_status_is_available_in_ns, false) - sp.putInt(app.aaps.core.utils.R.string.key_ObjectivesmanualEnacts, 0) - sp.putBoolean(app.aaps.core.utils.R.string.key_objectiveuseprofileswitch, false) - sp.putBoolean(app.aaps.core.utils.R.string.key_objectiveusedisconnect, false) - sp.putBoolean(app.aaps.core.utils.R.string.key_objectiveusereconnect, false) - sp.putBoolean(app.aaps.core.utils.R.string.key_objectiveusetemptarget, false) - sp.putBoolean(app.aaps.core.utils.R.string.key_objectiveuseactions, false) - sp.putBoolean(app.aaps.core.utils.R.string.key_objectiveuseloop, false) - sp.putBoolean(app.aaps.core.utils.R.string.key_objectiveusescale, false) + preferences.put(BooleanNonKey.ObjectivesBgIsAvailableInNs, false) + preferences.put(BooleanNonKey.ObjectivesPumpStatusIsAvailableInNS, false) + preferences.put(IntNonKey.ObjectivesManualEnacts, 0) + preferences.put(BooleanNonKey.ObjectivesProfileSwitchUsed, false) + preferences.put(BooleanNonKey.ObjectivesDisconnectUsed, false) + preferences.put(BooleanNonKey.ObjectivesReconnectUsed, false) + preferences.put(BooleanNonKey.ObjectivesTempTargetUsed, false) + preferences.put(BooleanNonKey.ObjectivesActionsUsed, false) + preferences.put(BooleanNonKey.ObjectivesLoopUsed, false) + preferences.put(BooleanNonKey.ObjectivesScaleUsed, false) } fun allPriorAccomplished(position: Int): Boolean { diff --git a/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/objectives/keys/ObjectivesBooleanComposedKey.kt b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/objectives/keys/ObjectivesBooleanComposedKey.kt new file mode 100644 index 00000000000..1128b5bfed6 --- /dev/null +++ b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/objectives/keys/ObjectivesBooleanComposedKey.kt @@ -0,0 +1,14 @@ +package app.aaps.plugins.constraints.objectives.keys + +import app.aaps.core.keys.interfaces.BooleanComposedNonPreferenceKey + +enum class ObjectivesBooleanComposedKey( + override val key: String, + override val format: String, + override val defaultValue: Boolean, + override val exportable: Boolean = true +) : BooleanComposedNonPreferenceKey { + + AnsweredExam("ExamTask_", "%s", false), + AnsweredUi("UITask_", "%s", false), +} \ No newline at end of file diff --git a/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/objectives/keys/ObjectivesLongComposedKey.kt b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/objectives/keys/ObjectivesLongComposedKey.kt new file mode 100644 index 00000000000..5cf560550bc --- /dev/null +++ b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/objectives/keys/ObjectivesLongComposedKey.kt @@ -0,0 +1,15 @@ +package app.aaps.plugins.constraints.objectives.keys + +import app.aaps.core.keys.interfaces.LongComposedNonPreferenceKey + +enum class ObjectivesLongComposedKey( + override val key: String, + override val format: String, + override val defaultValue: Long, + override val exportable: Boolean = true +) : LongComposedNonPreferenceKey { + + Started("Objectives_started_", "%s", 0L), + Accomplished("Objectives_accomplished_", "%s", 0L), + DisabledTo("DisabledTo_", "%s", 0L), +} \ No newline at end of file diff --git a/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/objectives/objectives/Objective.kt b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/objectives/objectives/Objective.kt index 704d3724930..ca4d130498f 100644 --- a/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/objectives/objectives/Objective.kt +++ b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/objectives/objectives/Objective.kt @@ -8,10 +8,11 @@ import androidx.annotation.StringRes import androidx.fragment.app.FragmentActivity import app.aaps.core.data.time.T import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.DateUtil -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.plugins.constraints.R +import app.aaps.plugins.constraints.objectives.keys.ObjectivesBooleanComposedKey +import app.aaps.plugins.constraints.objectives.keys.ObjectivesLongComposedKey import dagger.android.HasAndroidInjector import kotlinx.coroutines.Runnable import javax.inject.Inject @@ -19,7 +20,6 @@ import kotlin.math.floor abstract class Objective(injector: HasAndroidInjector, spName: String, @StringRes objective: Int, @StringRes gate: Int) { - @Inject lateinit var sp: SP @Inject lateinit var preferences: Preferences @Inject lateinit var rh: ResourceHelper @Inject lateinit var dateUtil: DateUtil @@ -30,12 +30,12 @@ abstract class Objective(injector: HasAndroidInjector, spName: String, @StringRe var startedOn: Long = 0 set(value) { field = value - sp.putLong("Objectives_" + spName + "_started", startedOn) + preferences.put(ObjectivesLongComposedKey.Started, spName, value = startedOn) } var accomplishedOn: Long = 0 set(value) { field = value - sp.putLong("Objectives_" + spName + "_accomplished", value) + preferences.put(ObjectivesLongComposedKey.Accomplished, spName, value = value) } var tasks: MutableList = ArrayList() @@ -54,8 +54,8 @@ abstract class Objective(injector: HasAndroidInjector, spName: String, @StringRe this.spName = spName this.objective = objective this.gate = gate - startedOn = sp.getLong("Objectives_" + spName + "_started", 0L) - accomplishedOn = sp.getLong("Objectives_" + spName + "_accomplished", 0L) + startedOn = preferences.get(ObjectivesLongComposedKey.Started, spName) + accomplishedOn = preferences.get(ObjectivesLongComposedKey.Accomplished, spName) if (accomplishedOn - dateUtil.now() > T.hours(3).msecs() || startedOn - dateUtil.now() > T.hours(3).msecs()) { // more than 3 hours in the future startedOn = 0 accomplishedOn = 0 @@ -136,11 +136,11 @@ abstract class Objective(injector: HasAndroidInjector, spName: String, @StringRe var answered: Boolean = false set(value) { field = value - sp.putBoolean("UITask_$spIdentifier", value) + preferences.put(ObjectivesBooleanComposedKey.AnsweredUi, spIdentifier, value = value) } init { - answered = sp.getBoolean("UITask_$spIdentifier", false) + answered = preferences.get(ObjectivesBooleanComposedKey.AnsweredUi, spIdentifier) } override fun isCompleted(): Boolean = answered @@ -152,17 +152,17 @@ abstract class Objective(injector: HasAndroidInjector, spName: String, @StringRe var answered: Boolean = false set(value) { field = value - sp.putBoolean("ExamTask_$spIdentifier", value) + preferences.put(ObjectivesBooleanComposedKey.AnsweredExam, spIdentifier, value = value) } var disabledTo: Long = 0 set(value) { field = value - sp.putLong("DisabledTo_$spIdentifier", value) + preferences.put(ObjectivesLongComposedKey.DisabledTo, spIdentifier, value = value) } init { - answered = sp.getBoolean("ExamTask_$spIdentifier", false) - disabledTo = sp.getLong("DisabledTo_$spIdentifier", 0L) + answered = preferences.get(ObjectivesBooleanComposedKey.AnsweredExam, spIdentifier) + disabledTo = preferences.get(ObjectivesLongComposedKey.DisabledTo, spIdentifier) } override fun isCompleted(): Boolean = answered diff --git a/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/objectives/objectives/Objective0.kt b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/objectives/objectives/Objective0.kt index e790d82a52a..1fa61d41b42 100644 --- a/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/objectives/objectives/Objective0.kt +++ b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/objectives/objectives/Objective0.kt @@ -9,6 +9,7 @@ import app.aaps.core.interfaces.protection.PasswordCheck import app.aaps.core.interfaces.pump.VirtualPump import app.aaps.core.interfaces.sync.Tidepool import app.aaps.core.keys.BooleanKey +import app.aaps.core.keys.BooleanNonKey import app.aaps.core.keys.StringKey import app.aaps.core.ui.toast.ToastUtils import app.aaps.plugins.constraints.R @@ -29,7 +30,7 @@ class Objective0(injector: HasAndroidInjector) : Objective(injector, "config", R init { tasks.add(object : Task(this, R.string.objectives_bgavailableinns) { override fun isCompleted(): Boolean { - return sp.getBoolean(app.aaps.core.utils.R.string.key_objectives_bg_is_available_in_ns, false) || tidepoolPlugin?.hasWritePermission == true + return preferences.get(BooleanNonKey.ObjectivesBgIsAvailableInNs) || tidepoolPlugin?.hasWritePermission == true } }) tasks.add(object : Task(this, R.string.synchaswritepermission) { @@ -49,7 +50,7 @@ class Objective0(injector: HasAndroidInjector) : Objective(injector, "config", R tasks.add( object : Task(this, R.string.objectives_pumpstatusavailableinns) { override fun isCompleted(): Boolean { - return sp.getBoolean(app.aaps.core.utils.R.string.key_objectives_pump_status_is_available_in_ns, false) || tidepoolPlugin?.hasWritePermission == true + return preferences.get(BooleanNonKey.ObjectivesPumpStatusIsAvailableInNS) || tidepoolPlugin?.hasWritePermission == true } }.learned(Learned(R.string.objectives_0_learned)) ) @@ -77,7 +78,7 @@ class Objective0(injector: HasAndroidInjector) : Objective(injector, "config", R if (preferences.get(StringKey.ProtectionMasterPassword) == "") { ToastUtils.errorToast(context, app.aaps.core.ui.R.string.master_password_not_set) } else { - passwordCheck.queryPassword(context, app.aaps.core.ui.R.string.master_password, StringKey.ProtectionMasterPassword.key, + passwordCheck.queryPassword(context, app.aaps.core.ui.R.string.master_password, StringKey.ProtectionMasterPassword, ok = { task.answered = true callback.run() diff --git a/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/objectives/objectives/Objective1.kt b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/objectives/objectives/Objective1.kt index 1967a64f946..5ffe8b8e8d1 100644 --- a/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/objectives/objectives/Objective1.kt +++ b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/objectives/objectives/Objective1.kt @@ -2,6 +2,7 @@ package app.aaps.plugins.constraints.objectives.objectives import app.aaps.core.interfaces.plugin.ActivePlugin import app.aaps.core.interfaces.plugin.PluginBase +import app.aaps.core.keys.BooleanNonKey import app.aaps.plugins.constraints.R import dagger.android.HasAndroidInjector import javax.inject.Inject @@ -15,38 +16,38 @@ class Objective1 @Inject constructor(injector: HasAndroidInjector) : Objective(i init { tasks.add(object : Task(this, R.string.objectives_useprofileswitch) { override fun isCompleted(): Boolean { - return sp.getBoolean(app.aaps.core.utils.R.string.key_objectiveuseprofileswitch, false) + return preferences.get(BooleanNonKey.ObjectivesProfileSwitchUsed) } }) tasks.add(object : Task(this, R.string.objectives_usedisconnectpump) { override fun isCompleted(): Boolean { - return sp.getBoolean(app.aaps.core.utils.R.string.key_objectiveusedisconnect, false) + return preferences.get(BooleanNonKey.ObjectivesDisconnectUsed) } }.hint(Hint(R.string.disconnectpump_hint))) tasks.add(object : Task(this, R.string.objectives_usereconnectpump) { override fun isCompleted(): Boolean { - return sp.getBoolean(app.aaps.core.utils.R.string.key_objectiveusereconnect, false) + return preferences.get(BooleanNonKey.ObjectivesReconnectUsed) } }.hint(Hint(R.string.disconnectpump_hint))) tasks.add(object : Task(this, R.string.objectives_usetemptarget) { override fun isCompleted(): Boolean { - return sp.getBoolean(app.aaps.core.utils.R.string.key_objectiveusetemptarget, false) + return preferences.get(BooleanNonKey.ObjectivesTempTargetUsed) } }.hint(Hint(R.string.usetemptarget_hint))) tasks.add(object : Task(this, R.string.objectives_useactions) { override fun isCompleted(): Boolean { - return sp.getBoolean(app.aaps.core.utils.R.string.key_objectiveuseactions, false) && actionsPlugin.isEnabled() && actionsPlugin.isFragmentVisible() + return preferences.get(BooleanNonKey.ObjectivesActionsUsed) && actionsPlugin.isEnabled() && actionsPlugin.isFragmentVisible() } }.hint(Hint(R.string.useaction_hint))) tasks.add(object : Task(this, R.string.objectives_useloop) { override fun isCompleted(): Boolean { - return sp.getBoolean(app.aaps.core.utils.R.string.key_objectiveuseloop, false) + return preferences.get(BooleanNonKey.ObjectivesLoopUsed) } }.hint(Hint(R.string.useaction_hint))) tasks.add( object : Task(this, R.string.objectives_usescale) { override fun isCompleted(): Boolean { - return sp.getBoolean(app.aaps.core.utils.R.string.key_objectiveusescale, false) + return preferences.get(BooleanNonKey.ObjectivesScaleUsed) } }.hint(Hint(R.string.usescale_hint)) .learned(Learned(R.string.objectives_usage_learned)) diff --git a/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/objectives/objectives/Objective3.kt b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/objectives/objectives/Objective3.kt index bcbdf6be8b0..2869954e007 100644 --- a/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/objectives/objectives/Objective3.kt +++ b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/objectives/objectives/Objective3.kt @@ -2,6 +2,7 @@ package app.aaps.plugins.constraints.objectives.objectives import app.aaps.core.data.time.T import app.aaps.core.interfaces.plugin.ActivePlugin +import app.aaps.core.keys.IntNonKey import app.aaps.plugins.constraints.R import dagger.android.HasAndroidInjector import javax.inject.Inject @@ -16,14 +17,14 @@ class Objective3 @Inject constructor(injector: HasAndroidInjector) : Objective(i tasks.add( object : Task(this, R.string.objectives_manualenacts) { override fun isCompleted(): Boolean { - return sp.getInt(app.aaps.core.utils.R.string.key_ObjectivesmanualEnacts, 0) >= MANUAL_ENACTS_NEEDED + return preferences.get(IntNonKey.ObjectivesManualEnacts) >= MANUAL_ENACTS_NEEDED } override val progress: String get() = - if (sp.getInt(app.aaps.core.utils.R.string.key_ObjectivesmanualEnacts, 0) >= MANUAL_ENACTS_NEEDED) + if (preferences.get(IntNonKey.ObjectivesManualEnacts) >= MANUAL_ENACTS_NEEDED) rh.gs(R.string.completed_well_done) - else sp.getInt(app.aaps.core.utils.R.string.key_ObjectivesmanualEnacts, 0).toString() + " / " + MANUAL_ENACTS_NEEDED + else preferences.get(IntNonKey.ObjectivesManualEnacts).toString() + " / " + MANUAL_ENACTS_NEEDED }.learned(Learned(R.string.objectives_openloop_learned)) ) } diff --git a/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/safety/SafetyPlugin.kt b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/safety/SafetyPlugin.kt index 4cbc3eb373e..1dca8ae988e 100644 --- a/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/safety/SafetyPlugin.kt +++ b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/safety/SafetyPlugin.kt @@ -29,8 +29,8 @@ import app.aaps.core.interfaces.utils.HardLimits import app.aaps.core.interfaces.utils.Round import app.aaps.core.keys.DoubleKey import app.aaps.core.keys.IntKey -import app.aaps.core.keys.Preferences import app.aaps.core.keys.StringKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.constraints.ConstraintObject import app.aaps.core.objects.extensions.put import app.aaps.core.objects.extensions.store diff --git a/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/signatureVerifier/SignatureVerifierPlugin.kt b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/signatureVerifier/SignatureVerifierPlugin.kt index b9ff0185462..5cabe21643b 100644 --- a/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/signatureVerifier/SignatureVerifierPlugin.kt +++ b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/signatureVerifier/SignatureVerifierPlugin.kt @@ -9,12 +9,13 @@ import app.aaps.core.interfaces.constraints.Constraint import app.aaps.core.interfaces.constraints.PluginConstraints import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.notifications.Notification -import app.aaps.core.interfaces.plugin.PluginBase +import app.aaps.core.interfaces.plugin.PluginBaseWithPreferences import app.aaps.core.interfaces.plugin.PluginDescription import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.ui.UiInteraction +import app.aaps.core.keys.interfaces.Preferences import app.aaps.plugins.constraints.R +import app.aaps.plugins.constraints.signatureVerifier.keys.SignatureVerifierLongKey import org.spongycastle.util.encoders.Hex import java.io.ByteArrayOutputStream import java.io.File @@ -41,17 +42,18 @@ import javax.inject.Singleton class SignatureVerifierPlugin @Inject constructor( aapsLogger: AAPSLogger, rh: ResourceHelper, - private val sp: SP, + preferences: Preferences, private val context: Context, private val uiInteraction: UiInteraction -) : PluginBase( +) : PluginBaseWithPreferences( pluginDescription = PluginDescription() .mainType(PluginType.CONSTRAINTS) .neverVisible(true) .alwaysEnabled(true) .showInList { false } .pluginName(R.string.signature_verifier), - aapsLogger, rh + ownPreferences = listOf(SignatureVerifierLongKey::class.java), + aapsLogger, rh, preferences ), PluginConstraints { private var handler: Handler? = null @@ -170,13 +172,13 @@ class SignatureVerifierPlugin @Inject constructor( } private fun shouldDownloadCerts(): Boolean { - return System.currentTimeMillis() - sp.getLong(R.string.key_last_revoked_certs_check, 0L) >= UPDATE_INTERVAL + return System.currentTimeMillis() - preferences.get(SignatureVerifierLongKey.LastRevokedCertCheck) >= UPDATE_INTERVAL } @Throws(IOException::class) private fun downloadAndSaveRevokedCerts() { val download = downloadRevokedCerts() saveRevokedCerts(download) - sp.putLong(R.string.key_last_revoked_certs_check, System.currentTimeMillis()) + preferences.put(SignatureVerifierLongKey.LastRevokedCertCheck, System.currentTimeMillis()) synchronized(lock) { revokedCerts = parseRevokedCertsFile(download) } } diff --git a/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/signatureVerifier/keys/SignatureVerifierLongKey.kt b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/signatureVerifier/keys/SignatureVerifierLongKey.kt new file mode 100644 index 00000000000..d48fd637249 --- /dev/null +++ b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/signatureVerifier/keys/SignatureVerifierLongKey.kt @@ -0,0 +1,12 @@ +package app.aaps.plugins.constraints.signatureVerifier.keys + +import app.aaps.core.keys.interfaces.LongNonPreferenceKey + +enum class SignatureVerifierLongKey( + override val key: String, + override val defaultValue: Long, + override val exportable: Boolean = true +) : LongNonPreferenceKey { + + LastRevokedCertCheck("last_revoked_certs_check", 0L), +} diff --git a/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/versionChecker/VersionCheckerPlugin.kt b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/versionChecker/VersionCheckerPlugin.kt index d97e7c68d3a..2e980c9aecd 100644 --- a/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/versionChecker/VersionCheckerPlugin.kt +++ b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/versionChecker/VersionCheckerPlugin.kt @@ -6,15 +6,16 @@ import app.aaps.core.interfaces.constraints.Constraint import app.aaps.core.interfaces.constraints.PluginConstraints import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.notifications.Notification -import app.aaps.core.interfaces.plugin.PluginBase +import app.aaps.core.interfaces.plugin.PluginBaseWithPreferences import app.aaps.core.interfaces.plugin.PluginDescription import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.rx.bus.RxBus -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.versionChecker.VersionCheckerUtils +import app.aaps.core.keys.interfaces.Preferences import app.aaps.plugins.constraints.R +import app.aaps.plugins.constraints.versionChecker.keys.VersionCheckerComposedLongKey +import app.aaps.plugins.constraints.versionChecker.keys.VersionCheckerLongKey import java.util.concurrent.TimeUnit import javax.inject.Inject import javax.inject.Singleton @@ -22,22 +23,22 @@ import kotlin.math.roundToInt @Singleton class VersionCheckerPlugin @Inject constructor( - private val sp: SP, + aapsLogger: AAPSLogger, rh: ResourceHelper, + preferences: Preferences, private val versionCheckerUtils: VersionCheckerUtils, - val rxBus: RxBus, - aapsLogger: AAPSLogger, private val config: Config, private val dateUtil: DateUtil, private val uiInteraction: UiInteraction -) : PluginBase( - PluginDescription() +) : PluginBaseWithPreferences( + pluginDescription = PluginDescription() .mainType(PluginType.CONSTRAINTS) .neverVisible(true) .alwaysEnabled(true) .showInList { false } .pluginName(R.string.version_checker), - aapsLogger, rh + ownPreferences = listOf(VersionCheckerLongKey::class.java, VersionCheckerComposedLongKey::class.java), + aapsLogger, rh, preferences ), PluginConstraints { enum class GracePeriod(val warning: Long, val old: Long, val veryOld: Long) { @@ -63,7 +64,7 @@ class VersionCheckerPlugin @Inject constructor( versionCheckerUtils.triggerCheckVersion() if (lastCheckOlderThan(gracePeriod.veryOld.daysToMillis())) value.set(false, rh.gs(R.string.very_old_version), this) - val endDate = sp.getLong(rh.gs(app.aaps.core.utils.R.string.key_app_expiration) + "_" + config.VERSION_NAME, 0) + val endDate = preferences.get(VersionCheckerComposedLongKey.AppExpiration, config.VERSION_NAME) if (endDate != 0L && dateUtil.now() > endDate) value.set(false, rh.gs(R.string.application_expired), this) return value @@ -78,29 +79,29 @@ class VersionCheckerPlugin @Inject constructor( private fun checkWarning() { val now = dateUtil.now() - if (!sp.contains(R.string.key_last_versionchecker_plugin_warning_timestamp)) { - sp.putLong(R.string.key_last_versionchecker_plugin_warning_timestamp, now) + if (preferences.getIfExists(VersionCheckerLongKey.LastWarningTimestamp) == null) { + preferences.put(VersionCheckerLongKey.LastWarningTimestamp, now) return } if (lastCheckOlderThan(gracePeriod.warning.daysToMillis()) && shouldWarnAgain()) { // store last notification time - sp.putLong(R.string.key_last_versionchecker_plugin_warning_timestamp, now) + preferences.put(VersionCheckerLongKey.LastWarningTimestamp, now) //notify val message = rh.gs( R.string.new_version_warning, - ((now - sp.getLong(R.string.key_last_successful_version_check_timestamp, now)) / 1L.daysToMillis().toDouble()).roundToInt(), + ((now - preferences.get(VersionCheckerLongKey.LastSuccessfulVersionCheck)) / 1L.daysToMillis().toDouble()).roundToInt(), gracePeriod.old, gracePeriod.veryOld ) uiInteraction.addNotification(Notification.OLD_VERSION, message, Notification.NORMAL) } - val endDate = sp.getLong(rh.gs(app.aaps.core.utils.R.string.key_app_expiration) + "_" + config.VERSION_NAME, 0) + val endDate = preferences.get(VersionCheckerComposedLongKey.AppExpiration, config.VERSION_NAME) if (endDate != 0L && dateUtil.now() > endDate && shouldWarnAgain()) { // store last notification time - sp.putLong(R.string.key_last_versionchecker_plugin_warning_timestamp, now) + preferences.put(VersionCheckerLongKey.LastWarningTimestamp, now) //notify uiInteraction.addNotification(Notification.VERSION_EXPIRE, rh.gs(R.string.application_expired), Notification.URGENT) @@ -108,10 +109,10 @@ class VersionCheckerPlugin @Inject constructor( } private fun shouldWarnAgain() = - dateUtil.now() > sp.getLong(R.string.key_last_versionchecker_plugin_warning_timestamp, 0) + WARN_EVERY + dateUtil.now() > preferences.get(VersionCheckerLongKey.LastWarningTimestamp) + WARN_EVERY private fun lastCheckOlderThan(gracePeriod: Long): Boolean = - dateUtil.now() > sp.getLong(R.string.key_last_successful_version_check_timestamp, 0) + gracePeriod + dateUtil.now() > preferences.get(VersionCheckerLongKey.LastSuccessfulVersionCheck) + gracePeriod private fun Long.daysToMillis() = TimeUnit.DAYS.toMillis(this) } diff --git a/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/versionChecker/VersionCheckerUtilsImpl.kt b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/versionChecker/VersionCheckerUtilsImpl.kt index c171b8bcfa0..0cf0163abc9 100644 --- a/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/versionChecker/VersionCheckerUtilsImpl.kt +++ b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/versionChecker/VersionCheckerUtilsImpl.kt @@ -8,11 +8,13 @@ import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.notifications.Notification import app.aaps.core.interfaces.receivers.ReceiverStatusStore import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.versionChecker.VersionCheckerUtils +import app.aaps.core.keys.interfaces.Preferences import app.aaps.plugins.constraints.R +import app.aaps.plugins.constraints.versionChecker.keys.VersionCheckerComposedLongKey +import app.aaps.plugins.constraints.versionChecker.keys.VersionCheckerLongKey import dagger.Lazy import dagger.Reusable import java.io.IOException @@ -23,7 +25,7 @@ import javax.inject.Inject @Reusable class VersionCheckerUtilsImpl @Inject constructor( private val aapsLogger: AAPSLogger, - private val sp: SP, + private val preferences: Preferences, private val rh: ResourceHelper, private val config: Lazy, private val receiverStatusStore: ReceiverStatusStore, @@ -33,13 +35,13 @@ class VersionCheckerUtilsImpl @Inject constructor( override fun triggerCheckVersion() { - if (!sp.contains(R.string.key_last_successful_version_check_timestamp)) { + if (preferences.getIfExists(VersionCheckerLongKey.LastSuccessfulVersionCheck) == null) { // On a new installation, set it as 30 days old in order to warn that there is a new version. setLastCheckTimestamp(dateUtil.now() - TimeUnit.DAYS.toMillis(30)) } // If we are good, only check once every day. - if (dateUtil.now() > sp.getLong(R.string.key_last_successful_version_check_timestamp, 0) + CHECK_EVERY) { + if (dateUtil.now() > preferences.get(VersionCheckerLongKey.LastSuccessfulVersionCheck) + CHECK_EVERY) { checkVersion() } } @@ -54,11 +56,11 @@ class VersionCheckerUtilsImpl @Inject constructor( // App expiration if (newVersionByApi || config.get().isDev()) { - var endDate = sp.getLong(rh.gs(app.aaps.core.utils.R.string.key_app_expiration) + "_" + config.get().VERSION_NAME, 0) + var endDate = preferences.get(VersionCheckerComposedLongKey.AppExpiration, config.get().VERSION_NAME) AllowedVersions.findByVersion(definition, config.get().VERSION_NAME)?.let { expirationJson -> AllowedVersions.endDateToMilliseconds(expirationJson.getString("endDate"))?.let { ed -> endDate = ed + T.days(1).msecs() - sp.putLong(rh.gs(app.aaps.core.utils.R.string.key_app_expiration) + "_" + config.get().VERSION_NAME, endDate) + preferences.put(VersionCheckerComposedLongKey.AppExpiration, config.get().VERSION_NAME, value = endDate) } } if (endDate != 0L) onExpireDateDetected(config.get().VERSION_NAME, dateUtil.dateString(endDate)) @@ -123,26 +125,26 @@ class VersionCheckerUtilsImpl @Inject constructor( private fun onNewVersionDetected(currentVersion: String, newVersion: String?): Boolean { val now = dateUtil.now() - if (now > sp.getLong(R.string.key_last_versionchecker_warning, 0) + WARN_EVERY) { + if (now > preferences.get(VersionCheckerLongKey.LastVersionCheckWarning) + WARN_EVERY) { aapsLogger.debug(LTag.CORE, "Version $currentVersion outdated. Found $newVersion") uiInteraction.addNotification(Notification.NEW_VERSION_DETECTED, rh.gs(R.string.versionavailable, newVersion.toString()), Notification.LOW) - sp.putLong(R.string.key_last_versionchecker_warning, now) + preferences.put(VersionCheckerLongKey.LastVersionCheckWarning, now) } return true } private fun onExpireDateDetected(currentVersion: String, endDate: String?) { val now = dateUtil.now() - if (now > sp.getLong(R.string.key_last_expired_versionchecker_warning, 0) + WARN_EVERY) { + if (now > preferences.get(VersionCheckerLongKey.LastExpiredWarning) + WARN_EVERY) { aapsLogger.debug(LTag.CORE, rh.gs(R.string.version_expire, currentVersion, endDate)) uiInteraction.addNotification(Notification.VERSION_EXPIRE, rh.gs(R.string.version_expire, currentVersion, endDate), Notification.LOW) - sp.putLong(R.string.key_last_expired_versionchecker_warning, now) + preferences.put(VersionCheckerLongKey.LastExpiredWarning, now) } } private fun setLastCheckTimestamp(timestamp: Long) { aapsLogger.debug(LTag.CORE, "Setting key_last_successful_version_check_timestamp ${dateUtil.dateAndTimeAndSecondsString(timestamp)}") - sp.putLong(R.string.key_last_successful_version_check_timestamp, timestamp) + preferences.put(VersionCheckerLongKey.LastSuccessfulVersionCheck, timestamp) } private fun String?.toNumberList() = diff --git a/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/versionChecker/keys/VersionCheckerComposedLongKey.kt b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/versionChecker/keys/VersionCheckerComposedLongKey.kt new file mode 100644 index 00000000000..8f999289a0b --- /dev/null +++ b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/versionChecker/keys/VersionCheckerComposedLongKey.kt @@ -0,0 +1,13 @@ +package app.aaps.plugins.constraints.versionChecker.keys + +import app.aaps.core.keys.interfaces.LongComposedNonPreferenceKey + +enum class VersionCheckerComposedLongKey( + override val key: String, + override val format: String, + override val defaultValue: Long, + override val exportable: Boolean = true +) : LongComposedNonPreferenceKey { + + AppExpiration("app_expiration_", "%s", 0L), +} \ No newline at end of file diff --git a/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/versionChecker/keys/VersionCheckerLongKey.kt b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/versionChecker/keys/VersionCheckerLongKey.kt new file mode 100644 index 00000000000..d286b1f645e --- /dev/null +++ b/plugins/constraints/src/main/kotlin/app/aaps/plugins/constraints/versionChecker/keys/VersionCheckerLongKey.kt @@ -0,0 +1,16 @@ +package app.aaps.plugins.constraints.versionChecker.keys + +import app.aaps.core.keys.interfaces.LongNonPreferenceKey + +@Suppress("SpellCheckingInspection") +enum class VersionCheckerLongKey( + override val key: String, + override val defaultValue: Long, + override val exportable: Boolean = true +) : LongNonPreferenceKey { + + LastWarningTimestamp("last_versionchecker_plugin_warning_timestamp", 0L), + LastSuccessfulVersionCheck("last_successful_version_check_timestamp", 0L), + LastExpiredWarning("last_expired_version_checker_warning", 0L), + LastVersionCheckWarning("last_versionchecker_warning", 0L), +} \ No newline at end of file diff --git a/plugins/constraints/src/main/res/values/strings.xml b/plugins/constraints/src/main/res/values/strings.xml index b7e8e01af01..fbe8d8ce859 100644 --- a/plugins/constraints/src/main/res/values/strings.xml +++ b/plugins/constraints/src/main/res/values/strings.xml @@ -4,9 +4,6 @@ PhoneChecker - snooze_dst_in24h - snooze_loop_disabled - Daylight Saving time Daylight Saving time change in 24h or less Daylight Saving time change less than 3 hours ago - Closed loop disabled @@ -22,11 +19,6 @@ very old version Application expired New version has not been checked for at least %1$d days! Fallback to LGS after %2$d days, loop will be disabled after %3$d days. Restore internet connectivity! - last_successful_version_check_timestamp - last_versionchecker_warning - last_expired_version_checker_warning - last_versionchecker_plugin_warning_timestamp - last_revoked_certs_check We have detected that you are running an invalid version. Loop disabled! Version %1$s available Version %1$s expire on %2$s diff --git a/plugins/constraints/src/test/kotlin/app/aaps/plugins/constraints/ConstraintsCheckerImplTest.kt b/plugins/constraints/src/test/kotlin/app/aaps/plugins/constraints/ConstraintsCheckerImplTest.kt index 90fd49ea757..216bdfa0b9a 100644 --- a/plugins/constraints/src/test/kotlin/app/aaps/plugins/constraints/ConstraintsCheckerImplTest.kt +++ b/plugins/constraints/src/test/kotlin/app/aaps/plugins/constraints/ConstraintsCheckerImplTest.kt @@ -82,7 +82,6 @@ class ConstraintsCheckerImplTest : TestBaseWithProfile() { init { addInjector { if (it is Objective) { - it.sp = sp it.preferences = preferences it.dateUtil = dateUtil } @@ -118,10 +117,10 @@ class ConstraintsCheckerImplTest : TestBaseWithProfile() { `when`(rh.gs(R.string.objectivenotstarted)).thenReturn("Objective %1\$d not started") // RS constructor - `when`(preferences.get(DanaStringKey.DanaRsName)).thenReturn("") - `when`(preferences.get(DanaStringKey.DanaMacAddress)).thenReturn("") + `when`(preferences.get(DanaStringKey.RsName)).thenReturn("") + `when`(preferences.get(DanaStringKey.MacAddress)).thenReturn("") // R - `when`(preferences.get(DanaStringKey.DanaRName)).thenReturn("") + `when`(preferences.get(DanaStringKey.RName)).thenReturn("") //SafetyPlugin constraintChecker = ConstraintsCheckerImpl(activePlugin, aapsLogger) @@ -130,20 +129,20 @@ class ConstraintsCheckerImplTest : TestBaseWithProfile() { insightDbHelper = InsightDbHelper(insightDatabaseDao) danaPump = DanaPump(aapsLogger, preferences, dateUtil, instantiator, decimalFormatter) - objectivesPlugin = ObjectivesPlugin(injector, aapsLogger, rh, sp) + objectivesPlugin = ObjectivesPlugin(injector, aapsLogger, rh, preferences) danaRPlugin = DanaRPlugin( - aapsLogger, aapsSchedulers, rxBus, context, rh, constraintChecker, activePlugin, commandQueue, danaPump, dateUtil, fabricPrivacy, pumpSync, - preferences, uiInteraction, danaHistoryDatabase, decimalFormatter, instantiator + aapsLogger, rh, preferences, commandQueue, aapsSchedulers, rxBus, context, constraintChecker, activePlugin, danaPump, dateUtil, fabricPrivacy, pumpSync, + uiInteraction, danaHistoryDatabase, decimalFormatter, instantiator ) danaRSPlugin = DanaRSPlugin( - aapsLogger, aapsSchedulers, rxBus, context, rh, constraintChecker, profileFunction, - commandQueue, danaPump, pumpSync, preferences, detailedBolusInfoStorage, temporaryBasalStorage, + aapsLogger, rh, preferences, commandQueue, aapsSchedulers, rxBus, context, constraintChecker, profileFunction, + danaPump, pumpSync, detailedBolusInfoStorage, temporaryBasalStorage, fabricPrivacy, dateUtil, uiInteraction, danaHistoryDatabase, decimalFormatter, instantiator ) insightPlugin = InsightPlugin( - aapsLogger, rxBus, rh, sp, commandQueue, profileFunction, - context, config, dateUtil, insightDbHelper, pumpSync, insightDatabase, instantiator + aapsLogger, rh, preferences, commandQueue, rxBus, profileFunction, + context, dateUtil, insightDbHelper, pumpSync, insightDatabase, instantiator ) openAPSSMBPlugin = OpenAPSSMBPlugin( diff --git a/plugins/constraints/src/test/kotlin/app/aaps/plugins/constraints/dstHelper/DstHelperPluginTest.kt b/plugins/constraints/src/test/kotlin/app/aaps/plugins/constraints/dstHelper/DstHelperPluginTest.kt index 5108c3815ea..879592a2033 100644 --- a/plugins/constraints/src/test/kotlin/app/aaps/plugins/constraints/dstHelper/DstHelperPluginTest.kt +++ b/plugins/constraints/src/test/kotlin/app/aaps/plugins/constraints/dstHelper/DstHelperPluginTest.kt @@ -3,8 +3,8 @@ package app.aaps.plugins.constraints.dstHelper import app.aaps.core.interfaces.aps.Loop import app.aaps.core.interfaces.plugin.ActivePlugin import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.ui.UiInteraction +import app.aaps.core.keys.interfaces.Preferences import app.aaps.shared.tests.TestBase import com.google.common.truth.Truth.assertThat import org.junit.jupiter.api.BeforeEach @@ -19,7 +19,7 @@ import java.util.TimeZone class DstHelperPluginTest : TestBase() { @Mock lateinit var rh: ResourceHelper - @Mock lateinit var sp: SP + @Mock lateinit var preferences: Preferences @Mock lateinit var activePlugin: ActivePlugin @Mock lateinit var loop: Loop @Mock lateinit var uiInteraction: UiInteraction @@ -28,7 +28,7 @@ class DstHelperPluginTest : TestBase() { @BeforeEach fun mock() { - plugin = DstHelperPlugin(aapsLogger, rh, sp, activePlugin, uiInteraction, loop) + plugin = DstHelperPlugin(aapsLogger, rh, preferences, activePlugin, uiInteraction, loop) } @Test diff --git a/plugins/constraints/src/test/kotlin/app/aaps/plugins/constraints/objectives/ObjectivesPluginTest.kt b/plugins/constraints/src/test/kotlin/app/aaps/plugins/constraints/objectives/ObjectivesPluginTest.kt index c01f16830aa..0978c4d7e34 100644 --- a/plugins/constraints/src/test/kotlin/app/aaps/plugins/constraints/objectives/ObjectivesPluginTest.kt +++ b/plugins/constraints/src/test/kotlin/app/aaps/plugins/constraints/objectives/ObjectivesPluginTest.kt @@ -1,12 +1,9 @@ package app.aaps.plugins.constraints.objectives -import app.aaps.core.interfaces.configuration.Config import app.aaps.core.interfaces.constraints.Objectives -import app.aaps.core.interfaces.plugin.ActivePlugin import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.DateUtil -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.constraints.ConstraintObject import app.aaps.plugins.constraints.R import app.aaps.plugins.constraints.objectives.objectives.Objective @@ -22,18 +19,14 @@ import org.mockito.Mockito.`when` class ObjectivesPluginTest : TestBase() { @Mock lateinit var rh: ResourceHelper - @Mock lateinit var activePlugin: ActivePlugin - @Mock lateinit var sp: SP @Mock lateinit var preferences: Preferences @Mock lateinit var dateUtil: DateUtil - @Mock lateinit var config: Config private lateinit var objectivesPlugin: ObjectivesPlugin private val injector = HasAndroidInjector { AndroidInjector { if (it is Objective) { - it.sp = sp it.preferences = preferences it.rh = rh it.dateUtil = dateUtil @@ -42,7 +35,7 @@ class ObjectivesPluginTest : TestBase() { } @BeforeEach fun prepareMock() { - objectivesPlugin = ObjectivesPlugin(injector, aapsLogger, rh, sp) + objectivesPlugin = ObjectivesPlugin(injector, aapsLogger, rh, preferences) `when`(rh.gs(R.string.objectivenotstarted, 9)).thenReturn("Objective 9 not started") `when`(rh.gs(R.string.objectivenotstarted, 8)).thenReturn("Objective 8 not started") `when`(rh.gs(R.string.objectivenotstarted, 6)).thenReturn("Objective 6 not started") diff --git a/plugins/constraints/src/test/kotlin/app/aaps/plugins/constraints/safety/SafetyPluginTest.kt b/plugins/constraints/src/test/kotlin/app/aaps/plugins/constraints/safety/SafetyPluginTest.kt index f99a24d6c56..91e6f21162e 100644 --- a/plugins/constraints/src/test/kotlin/app/aaps/plugins/constraints/safety/SafetyPluginTest.kt +++ b/plugins/constraints/src/test/kotlin/app/aaps/plugins/constraints/safety/SafetyPluginTest.kt @@ -1,6 +1,5 @@ package app.aaps.plugins.constraints.safety -import android.content.SharedPreferences import app.aaps.core.data.aps.ApsMode import app.aaps.core.data.plugin.PluginType import app.aaps.core.data.pump.defs.PumpDescription @@ -18,9 +17,6 @@ import app.aaps.core.keys.DoubleKey import app.aaps.core.keys.IntKey import app.aaps.core.keys.StringKey import app.aaps.core.objects.constraints.ConstraintObject -import app.aaps.core.validators.preferences.AdaptiveDoublePreference -import app.aaps.core.validators.preferences.AdaptiveIntPreference -import app.aaps.core.validators.preferences.AdaptiveListPreference import app.aaps.plugins.aps.openAPSAMA.DetermineBasalAMA import app.aaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin import app.aaps.plugins.aps.openAPSSMB.DetermineBasalSMB @@ -47,7 +43,6 @@ class SafetyPluginTest : TestBaseWithProfile() { @Mock lateinit var tddCalculator: TddCalculator @Mock lateinit var determineBasalAMA: DetermineBasalAMA @Mock lateinit var determineBasalSMB: DetermineBasalSMB - @Mock lateinit var sharedPrefs: SharedPreferences private lateinit var safetyPlugin: SafetyPlugin private lateinit var openAPSAMAPlugin: OpenAPSAMAPlugin @@ -55,25 +50,6 @@ class SafetyPluginTest : TestBaseWithProfile() { private val pumpDescription = PumpDescription() - init { - addInjector { - if (it is AdaptiveDoublePreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveIntPreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - it.config = config - } - if (it is AdaptiveListPreference) { - it.preferences = preferences - } - } - } - @BeforeEach fun prepare() { `when`(rh.gs(app.aaps.plugins.constraints.R.string.hardlimit)).thenReturn("hard limit") diff --git a/plugins/constraints/src/test/kotlin/app/aaps/plugins/constraints/signatureVerifier/VersionCheckerUtilsKtTest.kt b/plugins/constraints/src/test/kotlin/app/aaps/plugins/constraints/signatureVerifier/VersionCheckerUtilsKtTest.kt index 4b70103c7d4..594621d9b85 100644 --- a/plugins/constraints/src/test/kotlin/app/aaps/plugins/constraints/signatureVerifier/VersionCheckerUtilsKtTest.kt +++ b/plugins/constraints/src/test/kotlin/app/aaps/plugins/constraints/signatureVerifier/VersionCheckerUtilsKtTest.kt @@ -3,10 +3,10 @@ package app.aaps.plugins.constraints.signatureVerifier import app.aaps.core.interfaces.configuration.Config import app.aaps.core.interfaces.receivers.ReceiverStatusStore import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.versionChecker.VersionCheckerUtils +import app.aaps.core.keys.interfaces.Preferences import app.aaps.plugins.constraints.versionChecker.VersionCheckerUtilsImpl import app.aaps.plugins.constraints.versionChecker.numericVersionPart import app.aaps.shared.tests.TestBase @@ -27,15 +27,15 @@ class VersionCheckerUtilsKtTest : TestBase() { private lateinit var versionCheckerUtils: VersionCheckerUtils - @Mock lateinit var sp: SP @Mock lateinit var rh: ResourceHelper @Mock lateinit var receiverStatusStore: ReceiverStatusStore @Mock lateinit var config: Lazy @Mock lateinit var dateUtil: DateUtil @Mock lateinit var uiInteraction: UiInteraction + @Mock lateinit var preferences: Preferences @BeforeEach fun setup() { - versionCheckerUtils = VersionCheckerUtilsImpl(aapsLogger, sp, rh, config, receiverStatusStore, dateUtil, uiInteraction) + versionCheckerUtils = VersionCheckerUtilsImpl(aapsLogger, preferences, rh, config, receiverStatusStore, dateUtil, uiInteraction) } @Test diff --git a/plugins/insulin/src/main/kotlin/app/aaps/plugins/insulin/InsulinOrefFreePeakPlugin.kt b/plugins/insulin/src/main/kotlin/app/aaps/plugins/insulin/InsulinOrefFreePeakPlugin.kt index 2569b5ec90f..b8c90beedbc 100644 --- a/plugins/insulin/src/main/kotlin/app/aaps/plugins/insulin/InsulinOrefFreePeakPlugin.kt +++ b/plugins/insulin/src/main/kotlin/app/aaps/plugins/insulin/InsulinOrefFreePeakPlugin.kt @@ -14,7 +14,7 @@ import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.interfaces.utils.HardLimits import app.aaps.core.keys.IntKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.extensions.put import app.aaps.core.objects.extensions.store import app.aaps.core.validators.preferences.AdaptiveIntPreference diff --git a/plugins/insulin/src/test/kotlin/app/aaps/plugins/insulin/InsulinOrefFreePeakPluginTest.kt b/plugins/insulin/src/test/kotlin/app/aaps/plugins/insulin/InsulinOrefFreePeakPluginTest.kt index e2be91b236c..6d6d1bf3abd 100644 --- a/plugins/insulin/src/test/kotlin/app/aaps/plugins/insulin/InsulinOrefFreePeakPluginTest.kt +++ b/plugins/insulin/src/test/kotlin/app/aaps/plugins/insulin/InsulinOrefFreePeakPluginTest.kt @@ -1,10 +1,8 @@ package app.aaps.plugins.insulin -import android.content.SharedPreferences import app.aaps.core.interfaces.insulin.Insulin import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.keys.IntKey -import app.aaps.core.validators.preferences.AdaptiveIntPreference import app.aaps.shared.tests.TestBaseWithProfile import com.google.common.truth.Truth.assertThat import org.junit.jupiter.api.BeforeEach @@ -22,18 +20,6 @@ class InsulinOrefFreePeakPluginTest : TestBaseWithProfile() { private lateinit var sut: InsulinOrefFreePeakPlugin @Mock lateinit var uiInteraction: UiInteraction - @Mock lateinit var sharedPrefs: SharedPreferences - - init { - addInjector { - if (it is AdaptiveIntPreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - it.config = config - } - } - } @BeforeEach fun setup() { diff --git a/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/actions/ActionsFragment.kt b/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/actions/ActionsFragment.kt index 4ba34d7848d..0a0f8752110 100644 --- a/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/actions/ActionsFragment.kt +++ b/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/actions/ActionsFragment.kt @@ -30,11 +30,12 @@ import app.aaps.core.interfaces.rx.events.EventExtendedBolusChange import app.aaps.core.interfaces.rx.events.EventInitializationChanged import app.aaps.core.interfaces.rx.events.EventTempBasalChange import app.aaps.core.interfaces.rx.events.EventTherapyEventChange -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.DecimalFormatter import app.aaps.core.interfaces.utils.fabric.FabricPrivacy +import app.aaps.core.keys.BooleanNonKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.extensions.toStringMedium import app.aaps.core.objects.extensions.toStringShort import app.aaps.core.ui.UIRunnable @@ -55,7 +56,7 @@ class ActionsFragment : DaggerFragment() { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var rxBus: RxBus - @Inject lateinit var sp: SP + @Inject lateinit var preferences: Preferences @Inject lateinit var dateUtil: DateUtil @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var decimalFormatter: DecimalFormatter @@ -184,7 +185,7 @@ class ActionsFragment : DaggerFragment() { uiInteraction.runCareDialog(childFragmentManager, UiInteraction.EventType.ANNOUNCEMENT, app.aaps.core.ui.R.string.careportal_announcement) } - sp.putBoolean(app.aaps.core.utils.R.string.key_objectiveuseactions, true) + preferences.put(BooleanNonKey.ObjectivesActionsUsed, true) } @Synchronized diff --git a/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/OverviewDataImpl.kt b/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/OverviewDataImpl.kt index 3a4c8c3f529..f61073a609c 100644 --- a/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/OverviewDataImpl.kt +++ b/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/OverviewDataImpl.kt @@ -21,8 +21,9 @@ import app.aaps.core.interfaces.overview.OverviewData import app.aaps.core.interfaces.plugin.ActivePlugin import app.aaps.core.interfaces.profile.ProfileFunction import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.DateUtil +import app.aaps.core.keys.IntNonKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.R import app.aaps.core.objects.extensions.convertedToPercent import app.aaps.core.objects.extensions.isInProgress @@ -37,7 +38,7 @@ import javax.inject.Singleton class OverviewDataImpl @Inject constructor( private val rh: ResourceHelper, private val dateUtil: DateUtil, - private val sp: SP, + private val preferences: Preferences, private val activePlugin: ActivePlugin, private val profileFunction: ProfileFunction, private val persistenceLayer: PersistenceLayer, @@ -99,7 +100,7 @@ class OverviewDataImpl @Inject constructor( } override fun initRange() { - rangeToDisplay = sp.getInt(app.aaps.core.utils.R.string.key_rangetodisplay, 6) + rangeToDisplay = preferences.get(IntNonKey.RangeToDisplay) val calendar = Calendar.getInstance().also { it.timeInMillis = System.currentTimeMillis() diff --git a/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/OverviewFragment.kt b/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/OverviewFragment.kt index 7c242575182..01943f61912 100644 --- a/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/OverviewFragment.kt +++ b/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/OverviewFragment.kt @@ -74,7 +74,6 @@ import app.aaps.core.interfaces.rx.events.EventUpdateOverviewIobCob import app.aaps.core.interfaces.rx.events.EventUpdateOverviewSensitivity import app.aaps.core.interfaces.rx.events.EventWearUpdateTiles import app.aaps.core.interfaces.rx.weardata.EventData -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.source.DexcomBoyda import app.aaps.core.interfaces.source.XDripSource import app.aaps.core.interfaces.ui.UiInteraction @@ -83,9 +82,11 @@ import app.aaps.core.interfaces.utils.DecimalFormatter import app.aaps.core.interfaces.utils.TrendCalculator import app.aaps.core.interfaces.utils.fabric.FabricPrivacy import app.aaps.core.keys.BooleanKey +import app.aaps.core.keys.BooleanNonKey import app.aaps.core.keys.DoubleKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.IntNonKey import app.aaps.core.keys.UnitDoubleKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.constraints.ConstraintObject import app.aaps.core.objects.extensions.directionToIcon import app.aaps.core.objects.extensions.displayText @@ -121,7 +122,6 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList @Inject lateinit var injector: HasAndroidInjector @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsSchedulers: AapsSchedulers - @Inject lateinit var sp: SP @Inject lateinit var preferences: Preferences @Inject lateinit var rxBus: RxBus @Inject lateinit var rh: ResourceHelper @@ -225,9 +225,9 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList binding.graphsLayout.bgGraph.setOnLongClickListener { overviewData.rangeToDisplay += 6 overviewData.rangeToDisplay = if (overviewData.rangeToDisplay > 24) 6 else overviewData.rangeToDisplay - sp.putInt(app.aaps.core.utils.R.string.key_rangetodisplay, overviewData.rangeToDisplay) - rxBus.send(EventPreferenceChange(rh.gs(app.aaps.core.utils.R.string.key_rangetodisplay))) - sp.putBoolean(app.aaps.core.utils.R.string.key_objectiveusescale, true) + preferences.put(IntNonKey.RangeToDisplay, overviewData.rangeToDisplay) + rxBus.send(EventPreferenceChange(IntNonKey.RangeToDisplay.key)) + preferences.put(BooleanNonKey.ObjectivesScaleUsed, true) false } prepareGraphsIfNeeded(overviewMenus.setting.size) @@ -291,9 +291,9 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList .observeOn(aapsSchedulers.main) .subscribe({ overviewData.rangeToDisplay = it.hours - sp.putInt(app.aaps.core.utils.R.string.key_rangetodisplay, it.hours) - rxBus.send(EventPreferenceChange(rh.gs(app.aaps.core.utils.R.string.key_rangetodisplay))) - sp.putBoolean(app.aaps.core.utils.R.string.key_objectiveusescale, true) + preferences.put(IntNonKey.RangeToDisplay, it.hours) + rxBus.send(EventPreferenceChange(IntNonKey.RangeToDisplay.key)) + preferences.put(BooleanNonKey.ObjectivesScaleUsed, true) }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventBucketedDataCreated::class.java) @@ -1148,7 +1148,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList _binding ?: return val lastAutosensData = iobCobCalculator.ads.getLastAutosensData("Overview", aapsLogger, dateUtil) val lastAutosensRatio = lastAutosensData?.let { it.autosensResult.ratio * 100 } - if (config.AAPSCLIENT && sp.getBoolean(app.aaps.core.utils.R.string.key_used_autosens_on_main_phone, false) || + if (config.AAPSCLIENT && preferences.get(BooleanNonKey.AutosensUsedOnMainPhone) || !config.AAPSCLIENT && constraintChecker.isAutosensModeEnabled().value() ) { binding.infoLayout.sensitivityIcon.setImageResource( diff --git a/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/OverviewMenusImpl.kt b/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/OverviewMenusImpl.kt index 6241fbe62e3..51e3d874c06 100644 --- a/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/OverviewMenusImpl.kt +++ b/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/OverviewMenusImpl.kt @@ -29,9 +29,9 @@ import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventRefreshOverview import app.aaps.core.interfaces.rx.events.EventScale -import app.aaps.core.interfaces.sharedPreferences.SP -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.plugins.main.R +import app.aaps.plugins.main.general.overview.keys.OverviewStringKey import com.google.gson.Gson import javax.inject.Inject import javax.inject.Singleton @@ -40,7 +40,6 @@ import javax.inject.Singleton class OverviewMenusImpl @Inject constructor( private val aapsLogger: AAPSLogger, private val rh: ResourceHelper, - private val sp: SP, private val preferences: Preferences, private val rxBus: RxBus, private val config: Config, @@ -113,14 +112,14 @@ class OverviewMenusImpl @Inject constructor( @Synchronized private fun storeGraphConfig() { val sts = Gson().toJson(_setting) - sp.putString(R.string.key_graph_config, sts) + preferences.put(OverviewStringKey.GraphConfig, sts) aapsLogger.debug(sts) } @Synchronized override fun loadGraphConfig() { assert(CharTypeData.entries.size == OverviewMenus.CharType.entries.size) - val sts = sp.getString(R.string.key_graph_config, "") + val sts = preferences.get(OverviewStringKey.GraphConfig) if (sts.isNotEmpty()) { _setting = Gson().fromJson(sts, Array>::class.java).toMutableList() // reset when new CharType added diff --git a/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/OverviewPlugin.kt b/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/OverviewPlugin.kt index 4438cda256b..63d12b3159a 100644 --- a/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/OverviewPlugin.kt +++ b/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/OverviewPlugin.kt @@ -15,7 +15,7 @@ import app.aaps.core.interfaces.nsclient.NSSettingsStatus import app.aaps.core.interfaces.overview.Overview import app.aaps.core.interfaces.overview.OverviewData import app.aaps.core.interfaces.overview.OverviewMenus -import app.aaps.core.interfaces.plugin.PluginBase +import app.aaps.core.interfaces.plugin.PluginBaseWithPreferences import app.aaps.core.interfaces.plugin.PluginDescription import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.AapsSchedulers @@ -26,21 +26,19 @@ import app.aaps.core.interfaces.rx.events.EventNewHistoryData import app.aaps.core.interfaces.rx.events.EventNewNotification import app.aaps.core.interfaces.rx.events.EventPumpStatusChanged import app.aaps.core.interfaces.rx.events.EventUpdateOverviewCalcProgress -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.interfaces.utils.fabric.FabricPrivacy import app.aaps.core.keys.BooleanKey +import app.aaps.core.keys.BooleanNonKey import app.aaps.core.keys.DoubleKey import app.aaps.core.keys.IntKey import app.aaps.core.keys.IntentKey -import app.aaps.core.keys.Preferences import app.aaps.core.keys.StringKey +import app.aaps.core.keys.StringNonKey import app.aaps.core.keys.UnitDoubleKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.extensions.put -import app.aaps.core.objects.extensions.putString import app.aaps.core.objects.extensions.store -import app.aaps.core.objects.extensions.storeBoolean -import app.aaps.core.objects.extensions.storeString import app.aaps.core.validators.preferences.AdaptiveClickPreference import app.aaps.core.validators.preferences.AdaptiveDoublePreference import app.aaps.core.validators.preferences.AdaptiveIntPreference @@ -48,11 +46,11 @@ import app.aaps.core.validators.preferences.AdaptiveIntentPreference import app.aaps.core.validators.preferences.AdaptiveSwitchPreference import app.aaps.core.validators.preferences.AdaptiveUnitPreference import app.aaps.plugins.main.R +import app.aaps.plugins.main.general.overview.keys.OverviewStringKey import app.aaps.plugins.main.general.overview.notifications.NotificationStore import app.aaps.plugins.main.general.overview.notifications.events.EventUpdateOverviewNotification import app.aaps.plugins.main.general.overview.notifications.receivers.DismissNotificationReceiver import app.aaps.shared.impl.rx.bus.RxBusImpl -import dagger.android.HasAndroidInjector import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import org.json.JSONObject @@ -61,23 +59,21 @@ import javax.inject.Singleton @Singleton class OverviewPlugin @Inject constructor( - private val injector: HasAndroidInjector, + aapsLogger: AAPSLogger, + rh: ResourceHelper, + preferences: Preferences, private val notificationStore: NotificationStore, private val fabricPrivacy: FabricPrivacy, private val rxBus: RxBus, - private val sp: SP, - private val preferences: Preferences, - aapsLogger: AAPSLogger, private val aapsSchedulers: AapsSchedulers, - rh: ResourceHelper, private val overviewData: OverviewData, private val overviewMenus: OverviewMenus, private val context: Context, private val constraintsChecker: ConstraintsChecker, private val uiInteraction: UiInteraction, private val nsSettingStatus: NSSettingsStatus -) : PluginBase( - PluginDescription() +) : PluginBaseWithPreferences( + pluginDescription = PluginDescription() .mainType(PluginType.GENERAL) .fragmentClass(OverviewFragment::class.qualifiedName) .alwaysVisible(true) @@ -88,7 +84,8 @@ class OverviewPlugin @Inject constructor( .shortName(R.string.overview_shortname) .preferencesId(PluginDescription.PREFERENCE_SCREEN) .description(R.string.description_overview), - aapsLogger, rh + ownPreferences = listOf(OverviewStringKey::class.java), + aapsLogger, rh, preferences ), Overview { private var disposable: CompositeDisposable = CompositeDisposable() @@ -141,7 +138,7 @@ class OverviewPlugin @Inject constructor( override fun configuration(): JSONObject = JSONObject() .put(StringKey.GeneralUnits, preferences) - .putString(app.aaps.core.utils.R.string.key_quickwizard, sp, rh) + .put(StringNonKey.QuickWizard, preferences) .put(IntKey.OverviewEatingSoonDuration, preferences) .put(UnitDoubleKey.OverviewEatingSoonTarget, preferences) .put(IntKey.OverviewActivityDuration, preferences) @@ -165,13 +162,13 @@ class OverviewPlugin @Inject constructor( .put(IntKey.OverviewBattWarning, preferences) .put(IntKey.OverviewBattCritical, preferences) .put(IntKey.OverviewBolusPercentage, preferences) - .put(rh.gs(app.aaps.core.utils.R.string.key_used_autosens_on_main_phone), constraintsChecker.isAutosensModeEnabled().value()) + .put(BooleanNonKey.AutosensUsedOnMainPhone.key, constraintsChecker.isAutosensModeEnabled().value()) override fun applyConfiguration(configuration: JSONObject) { val previousUnits = preferences.getIfExists(StringKey.GeneralUnits) ?: "old" configuration .store(StringKey.GeneralUnits, preferences) - .storeString(app.aaps.core.utils.R.string.key_quickwizard, sp, rh) + .store(StringNonKey.QuickWizard, preferences) .store(IntKey.OverviewEatingSoonDuration, preferences) .store(UnitDoubleKey.OverviewEatingSoonTarget, preferences) .store(IntKey.OverviewActivityDuration, preferences) @@ -195,7 +192,7 @@ class OverviewPlugin @Inject constructor( .store(IntKey.OverviewBattWarning, preferences) .store(IntKey.OverviewBattCritical, preferences) .store(IntKey.OverviewBolusPercentage, preferences) - .storeBoolean(app.aaps.core.utils.R.string.key_used_autosens_on_main_phone, sp, rh) + .store(BooleanNonKey.AutosensUsedOnMainPhone, preferences) val newUnits = preferences.getIfExists(StringKey.GeneralUnits) ?: "new" if (previousUnits != newUnits) { @@ -281,11 +278,13 @@ class OverviewPlugin @Inject constructor( addPreference(AdaptiveIntPreference(ctx = context, intKey = IntKey.OverviewBattCritical, title = R.string.statuslights_bat_critical)) addPreference(AdaptiveIntPreference(ctx = context, intKey = IntKey.OverviewBageWarning, title = R.string.statuslights_bage_warning)) addPreference(AdaptiveIntPreference(ctx = context, intKey = IntKey.OverviewBageCritical, title = R.string.statuslights_bage_critical)) - addPreference(AdaptiveClickPreference(ctx = context, stringKey = StringKey.OverviewCopySettingsFromNs, title = R.string.statuslights_copy_ns, - onPreferenceClickListener = { - nsSettingStatus.copyStatusLightsNsSettings(context) - true - })) + addPreference( + AdaptiveClickPreference(ctx = context, stringKey = StringKey.OverviewCopySettingsFromNs, title = R.string.statuslights_copy_ns, + onPreferenceClickListener = { + nsSettingStatus.copyStatusLightsNsSettings(context) + true + }) + ) }) addPreference(AdaptiveIntPreference(ctx = context, intKey = IntKey.OverviewBolusPercentage, dialogMessage = R.string.deliverpartofboluswizard, title = app.aaps.core.ui.R.string.partialboluswizard)) addPreference(AdaptiveIntPreference(ctx = context, intKey = IntKey.OverviewResetBolusPercentageTime, dialogMessage = R.string.deliver_part_of_boluswizard_reset_time, title = app.aaps.core.ui.R.string.partialboluswizard_reset_time)) diff --git a/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/graphData/GraphData.kt b/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/graphData/GraphData.kt index ce14a46ad0f..0f813994237 100644 --- a/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/graphData/GraphData.kt +++ b/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/graphData/GraphData.kt @@ -23,8 +23,8 @@ import app.aaps.core.interfaces.profile.ProfileFunction import app.aaps.core.interfaces.profile.ProfileUtil import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.utils.Round -import app.aaps.core.keys.Preferences import app.aaps.core.keys.UnitDoubleKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.ui.toast.ToastUtils import com.jjoe64.graphview.GraphView import com.jjoe64.graphview.series.DataPoint diff --git a/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/keys/OverviewStringKey.kt b/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/keys/OverviewStringKey.kt new file mode 100644 index 00000000000..e78bb2498e5 --- /dev/null +++ b/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/keys/OverviewStringKey.kt @@ -0,0 +1,13 @@ +package app.aaps.plugins.main.general.overview.keys + +import app.aaps.core.keys.interfaces.StringNonPreferenceKey + +@Suppress("SpellCheckingInspection") +enum class OverviewStringKey( + override val key: String, + override val defaultValue: String, + override val exportable: Boolean = true +) : StringNonPreferenceKey { + + GraphConfig("graphconfig", "") +} \ No newline at end of file diff --git a/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/notifications/NotificationStore.kt b/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/notifications/NotificationStore.kt index 2aeb5cc9cd5..c14275efb07 100644 --- a/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/notifications/NotificationStore.kt +++ b/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/notifications/NotificationStore.kt @@ -18,10 +18,11 @@ import app.aaps.core.interfaces.notifications.Notification import app.aaps.core.interfaces.notifications.NotificationHolder import app.aaps.core.interfaces.plugin.ActivePlugin import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.ui.IconsProvider import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.interfaces.utils.DateUtil +import app.aaps.core.keys.BooleanKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.plugins.main.R import app.aaps.plugins.main.databinding.OverviewNotificationItemBinding import app.aaps.plugins.main.general.overview.notifications.events.EventUpdateOverviewNotification @@ -33,7 +34,7 @@ import javax.inject.Singleton @Singleton class NotificationStore @Inject constructor( private val aapsLogger: AAPSLogger, - private val sp: SP, + private val preferences: Preferences, private val rh: ResourceHelper, private val context: Context, private val iconsProvider: IconsProvider, @@ -68,7 +69,7 @@ class NotificationStore @Inject constructor( } } store.add(n) - if (sp.getBoolean(app.aaps.core.ui.R.string.key_raise_notifications_as_android_notifications, true) && n !is NotificationWithAction) + if (preferences.get(BooleanKey.AlertUrgentAsAndroidNotification) && n !is NotificationWithAction) raiseSystemNotification(n) if (n.soundId != null && n.soundId != 0) uiInteraction.startAlarm(n.soundId!!, n.text) Collections.sort(store, NotificationComparator()) diff --git a/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/notifications/NotificationWithAction.kt b/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/notifications/NotificationWithAction.kt index 149cc3c0f6d..9348c49ba0f 100644 --- a/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/notifications/NotificationWithAction.kt +++ b/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/notifications/NotificationWithAction.kt @@ -7,9 +7,9 @@ import app.aaps.core.interfaces.notifications.Notification import app.aaps.core.interfaces.nsclient.NSAlarm import app.aaps.core.interfaces.plugin.ActivePlugin import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.keys.IntKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.LongComposedKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.plugins.main.R import dagger.android.HasAndroidInjector import javax.inject.Inject @@ -21,7 +21,6 @@ class NotificationWithAction( @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var rh: ResourceHelper - @Inject lateinit var sp: SP @Inject lateinit var preferences: Preferences @Inject lateinit var activePlugin: ActivePlugin @@ -70,7 +69,7 @@ class NotificationWithAction( aapsLogger.debug(LTag.NOTIFICATION, "Notification text is: $text") val msToSnooze = preferences.get(IntKey.NsClientAlarmStaleData) * 60 * 1000L aapsLogger.debug(LTag.NOTIFICATION, "snooze nsalarm_staledatavalue in minutes is ${T.msecs(msToSnooze).mins()} currentTimeMillis is: ${System.currentTimeMillis()}") - sp.putLong(rh.gs(app.aaps.core.utils.R.string.key_snoozed_to) + nsAlarm.level(), System.currentTimeMillis() + msToSnooze) + preferences.put(LongComposedKey.NotificationSnoozedTo, nsAlarm.level().toString(), value = System.currentTimeMillis() + msToSnooze) } } diff --git a/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/ui/StatusLightHandler.kt b/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/ui/StatusLightHandler.kt index 58eb88eb665..47180ee5c16 100644 --- a/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/ui/StatusLightHandler.kt +++ b/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/overview/ui/StatusLightHandler.kt @@ -13,7 +13,7 @@ import app.aaps.core.interfaces.stats.TddCalculator import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.DecimalFormatter import app.aaps.core.keys.IntKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob diff --git a/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/smsCommunicator/SmsCommunicatorPlugin.kt b/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/smsCommunicator/SmsCommunicatorPlugin.kt index 7e36ee88d28..85e64f9f9b7 100644 --- a/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/smsCommunicator/SmsCommunicatorPlugin.kt +++ b/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/smsCommunicator/SmsCommunicatorPlugin.kt @@ -59,9 +59,9 @@ import app.aaps.core.interfaces.utils.fabric.FabricPrivacy import app.aaps.core.keys.BooleanKey import app.aaps.core.keys.IntKey import app.aaps.core.keys.IntentKey -import app.aaps.core.keys.Preferences import app.aaps.core.keys.StringKey import app.aaps.core.keys.UnitDoubleKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.constraints.ConstraintObject import app.aaps.core.objects.extensions.generateCOBString import app.aaps.core.objects.extensions.round diff --git a/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/smsCommunicator/otp/OneTimePassword.kt b/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/smsCommunicator/otp/OneTimePassword.kt index de948cbce83..22d73904c70 100644 --- a/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/smsCommunicator/otp/OneTimePassword.kt +++ b/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/smsCommunicator/otp/OneTimePassword.kt @@ -4,8 +4,9 @@ import android.util.Base64 import app.aaps.core.data.configuration.Constants import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.utils.DateUtil -import app.aaps.core.keys.Preferences import app.aaps.core.keys.StringKey +import app.aaps.core.keys.StringNonKey +import app.aaps.core.keys.interfaces.Preferences import com.eatthepath.otp.HmacOneTimePasswordGenerator import com.google.common.io.BaseEncoding import java.net.URLEncoder @@ -47,13 +48,13 @@ class OneTimePassword @Inject constructor( */ fun ensureKey(forceNewKey: Boolean = false) { val keyBytes: ByteArray - val strSecret = preferences.get(StringKey.SmsOtpSecret).trim() + val strSecret = preferences.get(StringNonKey.SmsOtpSecret).trim() if (strSecret.isEmpty() || forceNewKey) { val keyGenerator = KeyGenerator.getInstance(totp.algorithm) keyGenerator.init(Constants.OTP_GENERATED_KEY_LENGTH_BITS) val generatedKey = keyGenerator.generateKey() keyBytes = generatedKey.encoded - preferences.put(StringKey.SmsOtpSecret, Base64.encodeToString(keyBytes, Base64.NO_WRAP + Base64.NO_PADDING)) + preferences.put(StringNonKey.SmsOtpSecret, Base64.encodeToString(keyBytes, Base64.NO_WRAP + Base64.NO_PADDING)) } else { keyBytes = Base64.decode(strSecret, Base64.DEFAULT) } diff --git a/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/themes/ThemeSwitcherPlugin.kt b/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/themes/ThemeSwitcherPlugin.kt index aa05c2680e1..5ca2a1f2b21 100644 --- a/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/themes/ThemeSwitcherPlugin.kt +++ b/plugins/main/src/main/kotlin/app/aaps/plugins/main/general/themes/ThemeSwitcherPlugin.kt @@ -12,8 +12,8 @@ import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventPreferenceChange import app.aaps.core.interfaces.rx.events.EventThemeSwitch -import app.aaps.core.keys.Preferences import app.aaps.core.keys.StringKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.plugins.main.R import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign @@ -52,9 +52,9 @@ class ThemeSwitcherPlugin @Inject constructor( fun setThemeMode() { val mode = try { when (preferences.get(StringKey.GeneralDarkMode)) { - rh.gs(R.string.value_dark_theme) -> MODE_NIGHT_YES + rh.gs(R.string.value_dark_theme) -> MODE_NIGHT_YES rh.gs(R.string.value_light_theme) -> MODE_NIGHT_NO - else -> MODE_NIGHT_FOLLOW_SYSTEM + else -> MODE_NIGHT_FOLLOW_SYSTEM } } catch (ignored: Exception) { MODE_NIGHT_FOLLOW_SYSTEM diff --git a/plugins/main/src/main/kotlin/app/aaps/plugins/main/iob/iobCobCalculator/IobCobCalculatorPlugin.kt b/plugins/main/src/main/kotlin/app/aaps/plugins/main/iob/iobCobCalculator/IobCobCalculatorPlugin.kt index 9f68ad23781..d37bd10f91b 100644 --- a/plugins/main/src/main/kotlin/app/aaps/plugins/main/iob/iobCobCalculator/IobCobCalculatorPlugin.kt +++ b/plugins/main/src/main/kotlin/app/aaps/plugins/main/iob/iobCobCalculator/IobCobCalculatorPlugin.kt @@ -43,8 +43,9 @@ import app.aaps.core.interfaces.utils.fabric.FabricPrivacy import app.aaps.core.interfaces.workflow.CalculationWorkflow import app.aaps.core.keys.DoubleKey import app.aaps.core.keys.IntKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.IntNonKey import app.aaps.core.keys.StringKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.extensions.combine import app.aaps.core.objects.extensions.convertedToAbsolute import app.aaps.core.objects.extensions.iobCalc @@ -135,7 +136,7 @@ class IobCobCalculatorPlugin @Inject constructor( overviewData.reset() rxBus.send(EventNewHistoryData(0, false)) } - if (event.isChanged(rh.gs(app.aaps.core.utils.R.string.key_rangetodisplay))) { + if (event.isChanged(IntNonKey.RangeToDisplay.key)) { overviewData.initRange() calculationWorkflow.runOnScaleChanged(this, overviewData) rxBus.send(EventNewHistoryData(0, false)) diff --git a/plugins/main/src/main/kotlin/app/aaps/plugins/main/profile/ProfilePlugin.kt b/plugins/main/src/main/kotlin/app/aaps/plugins/main/profile/ProfilePlugin.kt index 1d1ed9745b2..53b4adbde72 100644 --- a/plugins/main/src/main/kotlin/app/aaps/plugins/main/profile/ProfilePlugin.kt +++ b/plugins/main/src/main/kotlin/app/aaps/plugins/main/profile/ProfilePlugin.kt @@ -10,7 +10,7 @@ import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.notifications.Notification import app.aaps.core.interfaces.objects.Instantiator import app.aaps.core.interfaces.plugin.ActivePlugin -import app.aaps.core.interfaces.plugin.PluginBase +import app.aaps.core.interfaces.plugin.PluginBaseWithPreferences import app.aaps.core.interfaces.plugin.PluginDescription import app.aaps.core.interfaces.profile.Profile import app.aaps.core.interfaces.profile.ProfileFunction @@ -22,11 +22,16 @@ import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventLocalProfileChanged import app.aaps.core.interfaces.rx.events.EventProfileStoreChanged -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.DecimalFormatter import app.aaps.core.interfaces.utils.HardLimits +import app.aaps.core.keys.LongNonKey +import app.aaps.core.keys.interfaces.BooleanComposedNonPreferenceKey +import app.aaps.core.keys.interfaces.DoubleComposedNonPreferenceKey +import app.aaps.core.keys.interfaces.IntNonPreferenceKey +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.core.keys.interfaces.StringComposedNonPreferenceKey import app.aaps.core.objects.extensions.blockFromJsonArray import app.aaps.core.objects.extensions.pureProfileFromJson import app.aaps.core.objects.profile.ProfileSealed @@ -34,6 +39,10 @@ import app.aaps.core.ui.dialogs.OKDialog import app.aaps.core.ui.toast.ToastUtils import app.aaps.core.utils.JsonHelper import app.aaps.plugins.main.R +import app.aaps.plugins.main.profile.keys.ProfileComposedBooleanKey +import app.aaps.plugins.main.profile.keys.ProfileComposedDoubleKey +import app.aaps.plugins.main.profile.keys.ProfileComposedStringKey +import app.aaps.plugins.main.profile.keys.ProfileIntKey import org.json.JSONArray import org.json.JSONException import org.json.JSONObject @@ -46,7 +55,7 @@ class ProfilePlugin @Inject constructor( aapsLogger: AAPSLogger, private val rxBus: RxBus, rh: ResourceHelper, - private val sp: SP, + preferences: Preferences, private val profileFunction: ProfileFunction, private val profileUtil: ProfileUtil, private val activePlugin: ActivePlugin, @@ -56,8 +65,8 @@ class ProfilePlugin @Inject constructor( private val instantiator: Instantiator, private val decimalFormatter: DecimalFormatter, private val uiInteraction: UiInteraction -) : PluginBase( - PluginDescription() +) : PluginBaseWithPreferences( + pluginDescription = PluginDescription() .mainType(PluginType.PROFILE) .fragmentClass(ProfileFragment::class.java.name) .enableByDefault(true) @@ -67,12 +76,18 @@ class ProfilePlugin @Inject constructor( .shortName(R.string.localprofile_shortname) .description(R.string.description_profile_local) .setDefault(), - aapsLogger, rh + ownPreferences = listOf( + ProfileComposedStringKey::class.java, ProfileComposedDoubleKey::class.java, ProfileComposedBooleanKey::class.java, ProfileIntKey::class.java + ), + aapsLogger, rh, preferences ), ProfileSource { private var rawProfile: ProfileStore? = null - private val defaultArray = "[{\"time\":\"00:00\",\"timeAsSeconds\":0,\"value\":0}]" + companion object { + + const val DEFAULT_ARRAY = "[{\"time\":\"00:00\",\"timeAsSeconds\":0,\"value\":0}]" + } override fun onStart() { super.onStart() @@ -173,20 +188,19 @@ class ProfilePlugin @Inject constructor( override fun storeSettings(activity: FragmentActivity?, timestamp: Long) { for (i in 0 until numOfProfiles) { profiles[i].run { - val localProfileNumbered = Constants.LOCAL_PROFILE + "_" + i + "_" - sp.putString(localProfileNumbered + "name", name) - sp.putBoolean(localProfileNumbered + "mgdl", mgdl) - sp.putDouble(localProfileNumbered + "dia", dia) - sp.putString(localProfileNumbered + "ic", ic.toString()) - sp.putString(localProfileNumbered + "isf", isf.toString()) - sp.putString(localProfileNumbered + "basal", basal.toString()) - sp.putString(localProfileNumbered + "targetlow", targetLow.toString()) - sp.putString(localProfileNumbered + "targethigh", targetHigh.toString()) + preferences.put(ProfileComposedStringKey.LocalProfileNumberedName, i, value = name) + preferences.put(ProfileComposedBooleanKey.LocalProfileNumberedMgdl, i, value = mgdl) + preferences.put(ProfileComposedDoubleKey.LocalProfileNumberedDia, i, value = dia) + preferences.put(ProfileComposedStringKey.LocalProfileNumberedIc, i, value = ic.toString()) + preferences.put(ProfileComposedStringKey.LocalProfileNumberedIsf, i, value = isf.toString()) + preferences.put(ProfileComposedStringKey.LocalProfileNumberedBasal, i, value = basal.toString()) + preferences.put(ProfileComposedStringKey.LocalProfileNumberedTargetLow, i, value = targetLow.toString()) + preferences.put(ProfileComposedStringKey.LocalProfileNumberedTargetHigh, i, value = targetHigh.toString()) } } - sp.putInt(Constants.LOCAL_PROFILE + "_profiles", numOfProfiles) + preferences.put(ProfileIntKey.AmountOfProfiles, numOfProfiles) - sp.putLong(app.aaps.core.utils.R.string.key_local_profile_last_change, timestamp) + preferences.put(LongNonKey.LocalProfileLastChange, timestamp) createAndStoreConvertedProfile() isEdited = false aapsLogger.debug(LTag.PROFILE, "Storing settings: " + rawProfile?.data.toString()) @@ -200,25 +214,24 @@ class ProfilePlugin @Inject constructor( @Synchronized fun loadSettings() { - val numOfProfiles = sp.getInt(Constants.LOCAL_PROFILE + "_profiles", 0) + val numOfProfiles = preferences.get(ProfileIntKey.AmountOfProfiles) profiles.clear() // numOfProfiles = max(numOfProfiles, 1) // create at least one default profile if none exists for (i in 0 until numOfProfiles) { - val localProfileNumbered = Constants.LOCAL_PROFILE + "_" + i + "_" - val name = sp.getString(localProfileNumbered + "name", Constants.LOCAL_PROFILE + i) + val name = preferences.get(ProfileComposedStringKey.LocalProfileNumberedName, i) if (isExistingName(name)) continue try { profiles.add( ProfileSource.SingleProfile( name = name, - mgdl = sp.getBoolean(localProfileNumbered + "mgdl", false), - dia = sp.getDouble(localProfileNumbered + "dia", Constants.defaultDIA), - ic = JSONArray(sp.getString(localProfileNumbered + "ic", defaultArray)), - isf = JSONArray(sp.getString(localProfileNumbered + "isf", defaultArray)), - basal = JSONArray(sp.getString(localProfileNumbered + "basal", defaultArray)), - targetLow = JSONArray(sp.getString(localProfileNumbered + "targetlow", defaultArray)), - targetHigh = JSONArray(sp.getString(localProfileNumbered + "targethigh", defaultArray)) + mgdl = preferences.get(ProfileComposedBooleanKey.LocalProfileNumberedMgdl, i), + dia = preferences.get(ProfileComposedDoubleKey.LocalProfileNumberedDia, i), + ic = JSONArray(preferences.get(ProfileComposedStringKey.LocalProfileNumberedIc, i)), + isf = JSONArray(preferences.get(ProfileComposedStringKey.LocalProfileNumberedIsf, i)), + basal = JSONArray(preferences.get(ProfileComposedStringKey.LocalProfileNumberedBasal, i)), + targetLow = JSONArray(preferences.get(ProfileComposedStringKey.LocalProfileNumberedTargetLow, i)), + targetHigh = JSONArray(preferences.get(ProfileComposedStringKey.LocalProfileNumberedTargetHigh, i)) ) ) } catch (e: JSONException) { @@ -347,11 +360,11 @@ class ProfilePlugin @Inject constructor( name = Constants.LOCAL_PROFILE + free, mgdl = profileFunction.getUnits() == GlucoseUnit.MGDL, dia = Constants.defaultDIA, - ic = JSONArray(defaultArray), - isf = JSONArray(defaultArray), - basal = JSONArray(defaultArray), - targetLow = JSONArray(defaultArray), - targetHigh = JSONArray(defaultArray) + ic = JSONArray(DEFAULT_ARRAY), + isf = JSONArray(DEFAULT_ARRAY), + basal = JSONArray(DEFAULT_ARRAY), + targetLow = JSONArray(DEFAULT_ARRAY), + targetHigh = JSONArray(DEFAULT_ARRAY) ) ) currentProfileIndex = profiles.size - 1 @@ -406,7 +419,7 @@ class ProfilePlugin @Inject constructor( } } if (numOfProfiles > 0) json.put("defaultProfile", currentProfile()?.name) - val startDate = sp.getLong(app.aaps.core.utils.R.string.key_local_profile_last_change, dateUtil.now()) + val startDate = preferences.getIfExists(LongNonKey.LocalProfileLastChange) ?: dateUtil.now() json.put("date", startDate) json.put("created_at", dateUtil.toISOAsUTC(startDate)) json.put("startDate", dateUtil.toISOAsUTC(startDate)) diff --git a/plugins/main/src/main/kotlin/app/aaps/plugins/main/profile/keys/ProfileComposedBooleanKey.kt b/plugins/main/src/main/kotlin/app/aaps/plugins/main/profile/keys/ProfileComposedBooleanKey.kt new file mode 100644 index 00000000000..21ad3e293fc --- /dev/null +++ b/plugins/main/src/main/kotlin/app/aaps/plugins/main/profile/keys/ProfileComposedBooleanKey.kt @@ -0,0 +1,15 @@ +package app.aaps.plugins.main.profile.keys + +import app.aaps.core.data.configuration.Constants +import app.aaps.core.keys.interfaces.BooleanComposedNonPreferenceKey + +enum class ProfileComposedBooleanKey( + override val key: String, + override val format: String, + override val defaultValue: Boolean, + override val exportable: Boolean = true +) : BooleanComposedNonPreferenceKey { + + LocalProfileNumberedMgdl(Constants.LOCAL_PROFILE + "_mgdl_", "%d", false), +} + diff --git a/plugins/main/src/main/kotlin/app/aaps/plugins/main/profile/keys/ProfileComposedDoubleKey.kt b/plugins/main/src/main/kotlin/app/aaps/plugins/main/profile/keys/ProfileComposedDoubleKey.kt new file mode 100644 index 00000000000..14798a72081 --- /dev/null +++ b/plugins/main/src/main/kotlin/app/aaps/plugins/main/profile/keys/ProfileComposedDoubleKey.kt @@ -0,0 +1,14 @@ +package app.aaps.plugins.main.profile.keys + +import app.aaps.core.data.configuration.Constants +import app.aaps.core.keys.interfaces.DoubleComposedNonPreferenceKey + +enum class ProfileComposedDoubleKey( + override val key: String, + override val format: String, + override val defaultValue: Double, + override val exportable: Boolean = true +) : DoubleComposedNonPreferenceKey { + + LocalProfileNumberedDia(Constants.LOCAL_PROFILE + "_dia_", "%d", Constants.defaultDIA), +} diff --git a/plugins/main/src/main/kotlin/app/aaps/plugins/main/profile/keys/ProfileComposedStringKey.kt b/plugins/main/src/main/kotlin/app/aaps/plugins/main/profile/keys/ProfileComposedStringKey.kt new file mode 100644 index 00000000000..83db71c1736 --- /dev/null +++ b/plugins/main/src/main/kotlin/app/aaps/plugins/main/profile/keys/ProfileComposedStringKey.kt @@ -0,0 +1,20 @@ +package app.aaps.plugins.main.profile.keys + +import app.aaps.core.data.configuration.Constants +import app.aaps.core.keys.interfaces.StringComposedNonPreferenceKey +import app.aaps.plugins.main.profile.ProfilePlugin.Companion.DEFAULT_ARRAY + +enum class ProfileComposedStringKey( + override val key: String, + override val format: String, + override val defaultValue: String, + override val exportable: Boolean = true +) : StringComposedNonPreferenceKey { + + LocalProfileNumberedIsf(Constants.LOCAL_PROFILE + "_isf_", "%d", DEFAULT_ARRAY), + LocalProfileNumberedIc(Constants.LOCAL_PROFILE + "_ic_", "%d", DEFAULT_ARRAY), + LocalProfileNumberedBasal(Constants.LOCAL_PROFILE + "_basal_", "%d", DEFAULT_ARRAY), + LocalProfileNumberedTargetLow(Constants.LOCAL_PROFILE + "_targetlow_", "%d", DEFAULT_ARRAY), + LocalProfileNumberedTargetHigh(Constants.LOCAL_PROFILE + "_targethigh_", "%d", DEFAULT_ARRAY), + LocalProfileNumberedName(Constants.LOCAL_PROFILE + "_name_", "%d", Constants.LOCAL_PROFILE + "0"), +} diff --git a/plugins/main/src/main/kotlin/app/aaps/plugins/main/profile/keys/ProfileIntKey.kt b/plugins/main/src/main/kotlin/app/aaps/plugins/main/profile/keys/ProfileIntKey.kt new file mode 100644 index 00000000000..6a5b321ecee --- /dev/null +++ b/plugins/main/src/main/kotlin/app/aaps/plugins/main/profile/keys/ProfileIntKey.kt @@ -0,0 +1,13 @@ +package app.aaps.plugins.main.profile.keys + +import app.aaps.core.data.configuration.Constants +import app.aaps.core.keys.interfaces.IntNonPreferenceKey + +enum class ProfileIntKey( + override val key: String, + override val defaultValue: Int, + override val exportable: Boolean = true +) : IntNonPreferenceKey { + + AmountOfProfiles(Constants.LOCAL_PROFILE + "_profiles", 0), +} diff --git a/plugins/main/src/main/kotlin/app/aaps/plugins/main/skins/SkinProvider.kt b/plugins/main/src/main/kotlin/app/aaps/plugins/main/skins/SkinProvider.kt index d0472cf031d..2c5cdc9e06b 100644 --- a/plugins/main/src/main/kotlin/app/aaps/plugins/main/skins/SkinProvider.kt +++ b/plugins/main/src/main/kotlin/app/aaps/plugins/main/skins/SkinProvider.kt @@ -1,7 +1,7 @@ package app.aaps.plugins.main.skins -import app.aaps.core.keys.Preferences import app.aaps.core.keys.StringKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.plugins.main.di.SkinsModule import java.util.Collections import javax.inject.Inject diff --git a/plugins/main/src/main/res/values/strings.xml b/plugins/main/src/main/res/values/strings.xml index 56ca0bcead6..305b6e8cb8d 100644 --- a/plugins/main/src/main/res/values/strings.xml +++ b/plugins/main/src/main/res/values/strings.xml @@ -277,7 +277,6 @@ Run %s? - graphconfig Predictions Treatments Heart Rate diff --git a/plugins/main/src/test/kotlin/app/aaps/plugins/main/general/overview/OverviewPluginTest.kt b/plugins/main/src/test/kotlin/app/aaps/plugins/main/general/overview/OverviewPluginTest.kt index ebea9a917b7..4ec4f17c99c 100644 --- a/plugins/main/src/test/kotlin/app/aaps/plugins/main/general/overview/OverviewPluginTest.kt +++ b/plugins/main/src/test/kotlin/app/aaps/plugins/main/general/overview/OverviewPluginTest.kt @@ -1,18 +1,10 @@ package app.aaps.plugins.main.general.overview import android.app.Activity -import android.content.SharedPreferences import app.aaps.core.interfaces.nsclient.NSSettingsStatus import app.aaps.core.interfaces.overview.OverviewData import app.aaps.core.interfaces.overview.OverviewMenus import app.aaps.core.interfaces.ui.UiInteraction -import app.aaps.core.validators.preferences.AdaptiveClickPreference -import app.aaps.core.validators.preferences.AdaptiveDoublePreference -import app.aaps.core.validators.preferences.AdaptiveIntPreference -import app.aaps.core.validators.preferences.AdaptiveIntentPreference -import app.aaps.core.validators.preferences.AdaptiveStringPreference -import app.aaps.core.validators.preferences.AdaptiveSwitchPreference -import app.aaps.core.validators.preferences.AdaptiveUnitPreference import app.aaps.plugins.main.general.overview.notifications.NotificationStore import app.aaps.shared.tests.TestBaseWithProfile import com.google.common.truth.Truth.assertThat @@ -27,53 +19,14 @@ class OverviewPluginTest : TestBaseWithProfile() { @Mock lateinit var overviewMenus: OverviewMenus @Mock lateinit var notificationStore: NotificationStore @Mock lateinit var uiInteraction: UiInteraction - @Mock lateinit var sharedPrefs: SharedPreferences @Mock lateinit var nsSettingsStatus: NSSettingsStatus private lateinit var overviewPlugin: OverviewPlugin - init { - addInjector { - if (it is AdaptiveDoublePreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveIntPreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - it.config = config - } - if (it is AdaptiveUnitPreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveIntentPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveStringPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveSwitchPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - it.config = config - } - if (it is AdaptiveClickPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - } - } - @BeforeEach fun prepare() { overviewPlugin = OverviewPlugin( - injector, notificationStore, fabricPrivacy, rxBus, sp, preferences, - aapsLogger, aapsSchedulers, rh, overviewData, overviewMenus, context, constraintsChecker, uiInteraction, nsSettingsStatus + aapsLogger, rh, preferences, notificationStore, fabricPrivacy, rxBus, + aapsSchedulers, overviewData, overviewMenus, context, constraintsChecker, uiInteraction, nsSettingsStatus ) Mockito.`when`(uiInteraction.quickWizardListActivity).thenReturn(Activity::class.java) } diff --git a/plugins/main/src/test/kotlin/app/aaps/plugins/main/general/smsCommunicator/SmsCommunicatorPluginTest.kt b/plugins/main/src/test/kotlin/app/aaps/plugins/main/general/smsCommunicator/SmsCommunicatorPluginTest.kt index c06ded32bbf..331a58a6b4a 100644 --- a/plugins/main/src/test/kotlin/app/aaps/plugins/main/general/smsCommunicator/SmsCommunicatorPluginTest.kt +++ b/plugins/main/src/test/kotlin/app/aaps/plugins/main/general/smsCommunicator/SmsCommunicatorPluginTest.kt @@ -1,6 +1,5 @@ package app.aaps.plugins.main.general.smsCommunicator -import android.content.SharedPreferences import android.telephony.SmsManager import app.aaps.core.data.aps.ApsMode import app.aaps.core.data.configuration.Constants @@ -29,12 +28,6 @@ import app.aaps.core.keys.StringKey import app.aaps.core.keys.UnitDoubleKey import app.aaps.core.objects.constraints.ConstraintObject import app.aaps.core.objects.extensions.fromGv -import app.aaps.core.validators.preferences.AdaptiveDoublePreference -import app.aaps.core.validators.preferences.AdaptiveIntPreference -import app.aaps.core.validators.preferences.AdaptiveIntentPreference -import app.aaps.core.validators.preferences.AdaptiveStringPreference -import app.aaps.core.validators.preferences.AdaptiveSwitchPreference -import app.aaps.core.validators.preferences.AdaptiveUnitPreference import app.aaps.implementation.iob.GlucoseStatusProviderImpl import app.aaps.plugins.aps.loop.LoopPlugin import app.aaps.plugins.main.R @@ -67,39 +60,9 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { @Mock lateinit var dateUtilMocked: DateUtil @Mock lateinit var autosensDataStore: AutosensDataStore @Mock lateinit var smsManager: SmsManager - @Mock lateinit var sharedPrefs: SharedPreferences init { addInjector { - if (it is AdaptiveDoublePreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveIntPreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - it.config = config - } - if (it is AdaptiveUnitPreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveIntentPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveStringPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveSwitchPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - it.config = config - } if (it is AuthRequest) { it.aapsLogger = aapsLogger it.smsCommunicator = smsCommunicatorPlugin diff --git a/plugins/main/src/test/kotlin/app/aaps/plugins/main/iob/AutosensDataStoreTest.kt b/plugins/main/src/test/kotlin/app/aaps/plugins/main/iob/AutosensDataStoreTest.kt index 2633715699f..7cc2b16b9cf 100644 --- a/plugins/main/src/test/kotlin/app/aaps/plugins/main/iob/AutosensDataStoreTest.kt +++ b/plugins/main/src/test/kotlin/app/aaps/plugins/main/iob/AutosensDataStoreTest.kt @@ -8,7 +8,7 @@ import app.aaps.core.data.model.TrendArrow import app.aaps.core.data.time.T import app.aaps.core.interfaces.aps.AutosensData import app.aaps.core.interfaces.utils.DateUtil -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.implementation.iob.AutosensDataObject import app.aaps.plugins.main.iob.iobCobCalculator.data.AutosensDataStoreObject import app.aaps.shared.impl.utils.DateUtilImpl diff --git a/plugins/sensitivity/src/main/kotlin/app/aaps/plugins/sensitivity/AbstractSensitivityPlugin.kt b/plugins/sensitivity/src/main/kotlin/app/aaps/plugins/sensitivity/AbstractSensitivityPlugin.kt index 998a563babf..2e2f0269a00 100644 --- a/plugins/sensitivity/src/main/kotlin/app/aaps/plugins/sensitivity/AbstractSensitivityPlugin.kt +++ b/plugins/sensitivity/src/main/kotlin/app/aaps/plugins/sensitivity/AbstractSensitivityPlugin.kt @@ -8,10 +8,9 @@ import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.plugin.PluginBase import app.aaps.core.interfaces.plugin.PluginDescription import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.Round import app.aaps.core.keys.DoubleKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import kotlin.math.max import kotlin.math.min @@ -19,7 +18,6 @@ abstract class AbstractSensitivityPlugin( pluginDescription: PluginDescription, aapsLogger: AAPSLogger, rh: ResourceHelper, - val sp: SP, val preferences: Preferences ) : PluginBase(pluginDescription, aapsLogger, rh), Sensitivity { diff --git a/plugins/sensitivity/src/main/kotlin/app/aaps/plugins/sensitivity/SensitivityAAPSPlugin.kt b/plugins/sensitivity/src/main/kotlin/app/aaps/plugins/sensitivity/SensitivityAAPSPlugin.kt index 20de9f58402..39670513e77 100644 --- a/plugins/sensitivity/src/main/kotlin/app/aaps/plugins/sensitivity/SensitivityAAPSPlugin.kt +++ b/plugins/sensitivity/src/main/kotlin/app/aaps/plugins/sensitivity/SensitivityAAPSPlugin.kt @@ -15,11 +15,10 @@ import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.plugin.PluginDescription import app.aaps.core.interfaces.profile.ProfileFunction import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.keys.DoubleKey import app.aaps.core.keys.IntKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.extensions.put import app.aaps.core.objects.extensions.store import app.aaps.core.utils.MidnightUtils @@ -38,7 +37,6 @@ import kotlin.math.roundToInt class SensitivityAAPSPlugin @Inject constructor( aapsLogger: AAPSLogger, rh: ResourceHelper, - sp: SP, preferences: Preferences, private val profileFunction: ProfileFunction, private val dateUtil: DateUtil, @@ -51,7 +49,7 @@ class SensitivityAAPSPlugin @Inject constructor( .shortName(R.string.sensitivity_shortname) .preferencesId(PluginDescription.PREFERENCE_SCREEN) .description(R.string.description_sensitivity_aaps), - aapsLogger, rh, sp, preferences + aapsLogger, rh, preferences ) { override fun detectSensitivity(ads: AutosensDataStore, fromTime: Long, toTime: Long): AutosensResult { diff --git a/plugins/sensitivity/src/main/kotlin/app/aaps/plugins/sensitivity/SensitivityOref1Plugin.kt b/plugins/sensitivity/src/main/kotlin/app/aaps/plugins/sensitivity/SensitivityOref1Plugin.kt index 1e5db5c46f0..0dde19f6dcd 100644 --- a/plugins/sensitivity/src/main/kotlin/app/aaps/plugins/sensitivity/SensitivityOref1Plugin.kt +++ b/plugins/sensitivity/src/main/kotlin/app/aaps/plugins/sensitivity/SensitivityOref1Plugin.kt @@ -17,10 +17,9 @@ import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.plugin.PluginDescription import app.aaps.core.interfaces.profile.ProfileFunction import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.keys.DoubleKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.extensions.put import app.aaps.core.objects.extensions.store import app.aaps.core.utils.MidnightUtils @@ -38,7 +37,6 @@ import kotlin.math.roundToInt class SensitivityOref1Plugin @Inject constructor( aapsLogger: AAPSLogger, rh: ResourceHelper, - sp: SP, preferences: Preferences, private val profileFunction: ProfileFunction, private val dateUtil: DateUtil, @@ -53,7 +51,7 @@ class SensitivityOref1Plugin @Inject constructor( .preferencesId(PluginDescription.PREFERENCE_SCREEN) .description(R.string.description_sensitivity_oref1) .setDefault(), - aapsLogger, rh, sp, preferences + aapsLogger, rh, preferences ), PluginConstraints { override fun detectSensitivity(ads: AutosensDataStore, fromTime: Long, toTime: Long): AutosensResult { diff --git a/plugins/sensitivity/src/main/kotlin/app/aaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.kt b/plugins/sensitivity/src/main/kotlin/app/aaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.kt index b7cdedf1155..7907ee26c81 100644 --- a/plugins/sensitivity/src/main/kotlin/app/aaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.kt +++ b/plugins/sensitivity/src/main/kotlin/app/aaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.kt @@ -16,11 +16,10 @@ import app.aaps.core.interfaces.plugin.ActivePlugin import app.aaps.core.interfaces.plugin.PluginDescription import app.aaps.core.interfaces.profile.ProfileFunction import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.keys.DoubleKey import app.aaps.core.keys.IntKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.extensions.put import app.aaps.core.objects.extensions.store import app.aaps.core.utils.MidnightUtils @@ -35,7 +34,6 @@ import kotlin.math.roundToInt class SensitivityWeightedAveragePlugin @Inject constructor( aapsLogger: AAPSLogger, rh: ResourceHelper, - sp: SP, preferences: Preferences, private val profileFunction: ProfileFunction, private val dateUtil: DateUtil, @@ -49,7 +47,7 @@ class SensitivityWeightedAveragePlugin @Inject constructor( .shortName(R.string.sensitivity_shortname) .preferencesId(PluginDescription.PREFERENCE_SCREEN) .description(R.string.description_sensitivity_weighted_average), - aapsLogger, rh, sp, preferences + aapsLogger, rh, preferences ) { override fun detectSensitivity(ads: AutosensDataStore, fromTime: Long, toTime: Long): AutosensResult { diff --git a/plugins/sensitivity/src/test/kotlin/app/aaps/plugins/sensitivity/AbstractSensitivityPluginTest.kt b/plugins/sensitivity/src/test/kotlin/app/aaps/plugins/sensitivity/AbstractSensitivityPluginTest.kt index bd17f22c012..99628859234 100644 --- a/plugins/sensitivity/src/test/kotlin/app/aaps/plugins/sensitivity/AbstractSensitivityPluginTest.kt +++ b/plugins/sensitivity/src/test/kotlin/app/aaps/plugins/sensitivity/AbstractSensitivityPluginTest.kt @@ -6,8 +6,7 @@ import app.aaps.core.interfaces.aps.Sensitivity import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.plugin.PluginDescription import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.sharedPreferences.SP -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.shared.tests.TestBase import com.google.common.truth.Truth.assertThat import org.json.JSONObject @@ -18,11 +17,10 @@ class AbstractSensitivityPluginTest : TestBase() { @Mock lateinit var pluginDescription: PluginDescription @Mock lateinit var rh: ResourceHelper - @Mock lateinit var sp: SP @Mock lateinit var preferences: Preferences - private inner class SensitivityTestClass(pluginDescription: PluginDescription, aapsLogger: AAPSLogger, rh: ResourceHelper, sp: SP) : - AbstractSensitivityPlugin(pluginDescription, aapsLogger, rh, sp, preferences) { + private inner class SensitivityTestClass(pluginDescription: PluginDescription, aapsLogger: AAPSLogger, rh: ResourceHelper) : + AbstractSensitivityPlugin(pluginDescription, aapsLogger, rh, preferences) { override fun detectSensitivity(ads: AutosensDataStore, fromTime: Long, toTime: Long): AutosensResult { return AutosensResult() @@ -42,7 +40,7 @@ class AbstractSensitivityPluginTest : TestBase() { @Test fun fillResultTest() { - val sut = SensitivityTestClass(pluginDescription, aapsLogger, rh, sp) + val sut = SensitivityTestClass(pluginDescription, aapsLogger, rh) var ar = sut.fillResult(1.0, 1.0, "1", "1.2", "1", 12, 0.7, 1.2) assertThat(ar.ratio).isWithin(0.01).of(1.0) ar = sut.fillResult(1.2, 1.0, "1", "1.2", "1", 40, 0.7, 1.2) diff --git a/plugins/sensitivity/src/test/kotlin/app/aaps/plugins/sensitivity/SensitivityAAPSPluginTest.kt b/plugins/sensitivity/src/test/kotlin/app/aaps/plugins/sensitivity/SensitivityAAPSPluginTest.kt index 8c0e29cfe37..2bc7803af2b 100644 --- a/plugins/sensitivity/src/test/kotlin/app/aaps/plugins/sensitivity/SensitivityAAPSPluginTest.kt +++ b/plugins/sensitivity/src/test/kotlin/app/aaps/plugins/sensitivity/SensitivityAAPSPluginTest.kt @@ -1,11 +1,8 @@ package app.aaps.plugins.sensitivity -import android.content.SharedPreferences import androidx.preference.PreferenceManager import app.aaps.core.interfaces.aps.Sensitivity import app.aaps.core.interfaces.db.PersistenceLayer -import app.aaps.core.validators.preferences.AdaptiveDoublePreference -import app.aaps.core.validators.preferences.AdaptiveIntPreference import app.aaps.shared.tests.TestBaseWithProfile import com.google.common.truth.Truth.assertThat import org.junit.jupiter.api.BeforeEach @@ -15,30 +12,13 @@ import org.mockito.Mock class SensitivityAAPSPluginTest : TestBaseWithProfile() { @Mock lateinit var persistenceLayer: PersistenceLayer - @Mock lateinit var sharedPrefs: SharedPreferences private lateinit var sensitivityAAPSPlugin: SensitivityAAPSPlugin - init { - addInjector { - if (it is AdaptiveIntPreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - it.config = config - } - if (it is AdaptiveDoublePreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - } - } - @BeforeEach fun prepare() { preferenceManager = PreferenceManager(context) sensitivityAAPSPlugin = SensitivityAAPSPlugin( - aapsLogger, rh, sp, preferences, profileFunction, dateUtil, persistenceLayer + aapsLogger, rh, preferences, profileFunction, dateUtil, persistenceLayer ) } diff --git a/plugins/sensitivity/src/test/kotlin/app/aaps/plugins/sensitivity/SensitivityOref1PluginTest.kt b/plugins/sensitivity/src/test/kotlin/app/aaps/plugins/sensitivity/SensitivityOref1PluginTest.kt index 46b0daa04c3..893db82edc9 100644 --- a/plugins/sensitivity/src/test/kotlin/app/aaps/plugins/sensitivity/SensitivityOref1PluginTest.kt +++ b/plugins/sensitivity/src/test/kotlin/app/aaps/plugins/sensitivity/SensitivityOref1PluginTest.kt @@ -1,11 +1,8 @@ package app.aaps.plugins.sensitivity -import android.content.SharedPreferences import androidx.preference.PreferenceManager import app.aaps.core.interfaces.aps.Sensitivity import app.aaps.core.interfaces.db.PersistenceLayer -import app.aaps.core.validators.preferences.AdaptiveDoublePreference -import app.aaps.core.validators.preferences.AdaptiveIntPreference import app.aaps.shared.tests.TestBaseWithProfile import com.google.common.truth.Truth.assertThat import org.junit.jupiter.api.BeforeEach @@ -15,30 +12,13 @@ import org.mockito.Mock class SensitivityOref1PluginTest : TestBaseWithProfile() { @Mock lateinit var persistenceLayer: PersistenceLayer - @Mock lateinit var sharedPrefs: SharedPreferences private lateinit var sensitivityOref1Plugin: SensitivityOref1Plugin - init { - addInjector { - if (it is AdaptiveIntPreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - it.config = config - } - if (it is AdaptiveDoublePreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - } - } - @BeforeEach fun prepare() { preferenceManager = PreferenceManager(context) sensitivityOref1Plugin = SensitivityOref1Plugin( - aapsLogger, rh, sp, preferences, profileFunction, dateUtil, persistenceLayer + aapsLogger, rh, preferences, profileFunction, dateUtil, persistenceLayer ) } diff --git a/plugins/sensitivity/src/test/kotlin/app/aaps/plugins/sensitivity/SensitivityWeightedAveragePluginTest.kt b/plugins/sensitivity/src/test/kotlin/app/aaps/plugins/sensitivity/SensitivityWeightedAveragePluginTest.kt index f93cb44d377..6781589b981 100644 --- a/plugins/sensitivity/src/test/kotlin/app/aaps/plugins/sensitivity/SensitivityWeightedAveragePluginTest.kt +++ b/plugins/sensitivity/src/test/kotlin/app/aaps/plugins/sensitivity/SensitivityWeightedAveragePluginTest.kt @@ -1,11 +1,8 @@ package app.aaps.plugins.sensitivity -import android.content.SharedPreferences import androidx.preference.PreferenceManager import app.aaps.core.interfaces.aps.Sensitivity import app.aaps.core.interfaces.db.PersistenceLayer -import app.aaps.core.validators.preferences.AdaptiveDoublePreference -import app.aaps.core.validators.preferences.AdaptiveIntPreference import app.aaps.shared.tests.TestBaseWithProfile import com.google.common.truth.Truth.assertThat import org.junit.jupiter.api.BeforeEach @@ -16,34 +13,17 @@ import org.mockito.Mockito class SensitivityWeightedAveragePluginTest : TestBaseWithProfile() { @Mock lateinit var persistenceLayer: PersistenceLayer - @Mock lateinit var sharedPrefs: SharedPreferences private lateinit var sensitivityWeightedAveragePlugin: SensitivityWeightedAveragePlugin private lateinit var sensitivityAAPSPlugin: SensitivityAAPSPlugin - init { - addInjector { - if (it is AdaptiveIntPreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - it.config = config - } - if (it is AdaptiveDoublePreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - } - } - @BeforeEach fun prepare() { preferenceManager = PreferenceManager(context) sensitivityWeightedAveragePlugin = SensitivityWeightedAveragePlugin( - aapsLogger, rh, sp, preferences, profileFunction, dateUtil, persistenceLayer, activePlugin + aapsLogger, rh, preferences, profileFunction, dateUtil, persistenceLayer, activePlugin ) sensitivityAAPSPlugin = SensitivityAAPSPlugin( - aapsLogger, rh, sp, preferences, profileFunction, dateUtil, persistenceLayer + aapsLogger, rh, preferences, profileFunction, dateUtil, persistenceLayer ) Mockito.`when`(activePlugin.getPluginsList()).thenReturn(arrayListOf(sensitivityAAPSPlugin)) } diff --git a/plugins/source/src/main/kotlin/app/aaps/plugins/source/AbstractBgSourcePlugin.kt b/plugins/source/src/main/kotlin/app/aaps/plugins/source/AbstractBgSourcePlugin.kt index e6de7f4468b..f676d3692dc 100644 --- a/plugins/source/src/main/kotlin/app/aaps/plugins/source/AbstractBgSourcePlugin.kt +++ b/plugins/source/src/main/kotlin/app/aaps/plugins/source/AbstractBgSourcePlugin.kt @@ -5,18 +5,22 @@ import androidx.preference.PreferenceCategory import androidx.preference.PreferenceManager import androidx.preference.PreferenceScreen import app.aaps.core.interfaces.logging.AAPSLogger -import app.aaps.core.interfaces.plugin.PluginBase +import app.aaps.core.interfaces.plugin.PluginBaseWithPreferences import app.aaps.core.interfaces.plugin.PluginDescription import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.source.BgSource import app.aaps.core.keys.BooleanKey +import app.aaps.core.keys.interfaces.NonPreferenceKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.validators.preferences.AdaptiveSwitchPreference abstract class AbstractBgSourcePlugin( pluginDescription: PluginDescription, + ownPreferences: List> = emptyList(), aapsLogger: AAPSLogger, - rh: ResourceHelper -) : PluginBase(pluginDescription, aapsLogger, rh), BgSource { + rh: ResourceHelper, + preferences: Preferences +) : PluginBaseWithPreferences(pluginDescription, ownPreferences, aapsLogger, rh, preferences), BgSource { override fun addPreferenceScreen(preferenceManager: PreferenceManager, parent: PreferenceScreen, context: Context, requiredKey: String?) { if (requiredKey != null) return diff --git a/plugins/source/src/main/kotlin/app/aaps/plugins/source/DexcomPlugin.kt b/plugins/source/src/main/kotlin/app/aaps/plugins/source/DexcomPlugin.kt index 5eb8f432f05..aee0d7e7de9 100644 --- a/plugins/source/src/main/kotlin/app/aaps/plugins/source/DexcomPlugin.kt +++ b/plugins/source/src/main/kotlin/app/aaps/plugins/source/DexcomPlugin.kt @@ -21,12 +21,11 @@ import app.aaps.core.interfaces.logging.UserEntryLogger import app.aaps.core.interfaces.plugin.PluginDescription import app.aaps.core.interfaces.profile.ProfileUtil import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.source.BgSource import app.aaps.core.interfaces.source.DexcomBoyda import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.keys.BooleanKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.workflow.LoggingWorker import app.aaps.core.utils.receivers.DataWorkerStorage import app.aaps.plugins.source.activities.RequestDexcomPermissionActivity @@ -76,7 +75,6 @@ class DexcomPlugin @Inject constructor( @Inject lateinit var injector: HasAndroidInjector @Inject lateinit var dexcomPlugin: DexcomPlugin - @Inject lateinit var sp: SP @Inject lateinit var preferences: Preferences @Inject lateinit var dateUtil: DateUtil @Inject lateinit var dataWorkerStorage: DataWorkerStorage diff --git a/plugins/source/src/main/kotlin/app/aaps/plugins/source/GlimpPlugin.kt b/plugins/source/src/main/kotlin/app/aaps/plugins/source/GlimpPlugin.kt index 89ff186344c..aef1afa8421 100644 --- a/plugins/source/src/main/kotlin/app/aaps/plugins/source/GlimpPlugin.kt +++ b/plugins/source/src/main/kotlin/app/aaps/plugins/source/GlimpPlugin.kt @@ -15,6 +15,7 @@ import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.plugin.PluginDescription import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.source.BgSource +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.workflow.LoggingWorker import dagger.android.HasAndroidInjector import kotlinx.coroutines.Dispatchers @@ -24,9 +25,10 @@ import javax.inject.Singleton @Singleton class GlimpPlugin @Inject constructor( rh: ResourceHelper, - aapsLogger: AAPSLogger + aapsLogger: AAPSLogger, + preferences: Preferences ) : AbstractBgSourcePlugin( - PluginDescription() + pluginDescription = PluginDescription() .mainType(PluginType.BGSOURCE) .fragmentClass(BGSourceFragment::class.java.name) .pluginIcon(app.aaps.core.objects.R.drawable.ic_glimp) @@ -34,7 +36,8 @@ class GlimpPlugin @Inject constructor( .pluginName(R.string.glimp) .preferencesVisibleInSimpleMode(false) .description(R.string.description_source_glimp), - aapsLogger, rh + ownPreferences = emptyList(), + aapsLogger, rh, preferences ), BgSource { // cannot be inner class because of needed injection diff --git a/plugins/source/src/main/kotlin/app/aaps/plugins/source/GlunovoPlugin.kt b/plugins/source/src/main/kotlin/app/aaps/plugins/source/GlunovoPlugin.kt index 96e598df72b..81f87f45eff 100644 --- a/plugins/source/src/main/kotlin/app/aaps/plugins/source/GlunovoPlugin.kt +++ b/plugins/source/src/main/kotlin/app/aaps/plugins/source/GlunovoPlugin.kt @@ -18,10 +18,11 @@ import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.plugin.PluginDescription import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.source.BgSource import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.fabric.FabricPrivacy +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.plugins.source.keys.GlunovoLongKey import io.reactivex.rxjava3.disposables.CompositeDisposable import javax.inject.Inject import javax.inject.Singleton @@ -30,7 +31,7 @@ import javax.inject.Singleton class GlunovoPlugin @Inject constructor( resourceHelper: ResourceHelper, aapsLogger: AAPSLogger, - private val sp: SP, + preferences: Preferences, private val context: Context, private val persistenceLayer: PersistenceLayer, private val dateUtil: DateUtil, @@ -45,7 +46,8 @@ class GlunovoPlugin @Inject constructor( .shortName(R.string.glunovo) .preferencesVisibleInSimpleMode(false) .description(R.string.description_source_glunovo), - aapsLogger, resourceHelper + ownPreferences = listOf(GlunovoLongKey::class.java), + aapsLogger, resourceHelper, preferences ), BgSource { private var handler: Handler? = null @@ -61,7 +63,7 @@ class GlunovoPlugin @Inject constructor( fabricPrivacy.logException(e) aapsLogger.error("Error while processing data", e) } - val lastReadTimestamp = sp.getLong(R.string.key_last_processed_glunovo_timestamp, 0L) + val lastReadTimestamp = preferences.get(GlunovoLongKey.LastProcessedTimestamp) val differenceToNow = INTERVAL - (dateUtil.now() - lastReadTimestamp) % INTERVAL + T.secs(10).msecs() handler?.postDelayed(refreshLoop, differenceToNow) } @@ -98,7 +100,7 @@ class GlunovoPlugin @Inject constructor( val curr = cr.getDouble(2) // bypass already processed - if (timestamp < sp.getLong(R.string.key_last_processed_glunovo_timestamp, 0L)) { + if (timestamp < preferences.get(GlunovoLongKey.LastProcessedTimestamp)) { cr.moveToNext() continue } @@ -132,7 +134,7 @@ class GlunovoPlugin @Inject constructor( glucoseUnit = GlucoseUnit.MMOL ) ) - sp.putLong(R.string.key_last_processed_glunovo_timestamp, timestamp) + preferences.put(GlunovoLongKey.LastProcessedTimestamp, timestamp) cr.moveToNext() } cr.close() diff --git a/plugins/source/src/main/kotlin/app/aaps/plugins/source/IntelligoPlugin.kt b/plugins/source/src/main/kotlin/app/aaps/plugins/source/IntelligoPlugin.kt index c8bdccad2db..94fc4bf767d 100644 --- a/plugins/source/src/main/kotlin/app/aaps/plugins/source/IntelligoPlugin.kt +++ b/plugins/source/src/main/kotlin/app/aaps/plugins/source/IntelligoPlugin.kt @@ -18,10 +18,11 @@ import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.plugin.PluginDescription import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.source.BgSource import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.fabric.FabricPrivacy +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.plugins.source.keys.IntelligoLongKey import io.reactivex.rxjava3.disposables.CompositeDisposable import javax.inject.Inject import javax.inject.Singleton @@ -30,13 +31,13 @@ import javax.inject.Singleton class IntelligoPlugin @Inject constructor( resourceHelper: ResourceHelper, aapsLogger: AAPSLogger, - private val sp: SP, + preferences: Preferences, private val context: Context, private val persistenceLayer: PersistenceLayer, private val dateUtil: DateUtil, private val fabricPrivacy: FabricPrivacy ) : AbstractBgSourcePlugin( - PluginDescription() + pluginDescription = PluginDescription() .mainType(PluginType.BGSOURCE) .fragmentClass(BGSourceFragment::class.java.name) .pluginIcon(app.aaps.core.ui.R.drawable.ic_intelligo) @@ -45,7 +46,8 @@ class IntelligoPlugin @Inject constructor( .shortName(R.string.intelligo) .preferencesVisibleInSimpleMode(false) .description(R.string.description_source_intelligo), - aapsLogger, resourceHelper + ownPreferences = listOf(IntelligoLongKey::class.java), + aapsLogger, resourceHelper, preferences ), BgSource { private var handler: Handler? = null @@ -61,7 +63,7 @@ class IntelligoPlugin @Inject constructor( fabricPrivacy.logException(e) aapsLogger.error("Error while processing data", e) } - val lastReadTimestamp = sp.getLong(R.string.key_last_processed_intelligo_timestamp, 0L) + val lastReadTimestamp = preferences.get(IntelligoLongKey.LastProcessedTimestamp) val differenceToNow = INTERVAL - (dateUtil.now() - lastReadTimestamp) % INTERVAL + T.secs(10).msecs() handler?.postDelayed(refreshLoop, differenceToNow) } @@ -97,7 +99,7 @@ class IntelligoPlugin @Inject constructor( val curr = cr.getDouble(2) // bypass already processed - if (timestamp < sp.getLong(R.string.key_last_processed_intelligo_timestamp, 0L)) { + if (timestamp < preferences.get(IntelligoLongKey.LastProcessedTimestamp)) { cr.moveToNext() continue } @@ -131,7 +133,7 @@ class IntelligoPlugin @Inject constructor( glucoseUnit = GlucoseUnit.MMOL ) ) - sp.putLong(R.string.key_last_processed_intelligo_timestamp, timestamp) + preferences.put(IntelligoLongKey.LastProcessedTimestamp, timestamp) cr.moveToNext() } cr.close() diff --git a/plugins/source/src/main/kotlin/app/aaps/plugins/source/MM640gPlugin.kt b/plugins/source/src/main/kotlin/app/aaps/plugins/source/MM640gPlugin.kt index 93669268f6f..5a7b4085bd7 100644 --- a/plugins/source/src/main/kotlin/app/aaps/plugins/source/MM640gPlugin.kt +++ b/plugins/source/src/main/kotlin/app/aaps/plugins/source/MM640gPlugin.kt @@ -16,6 +16,7 @@ import app.aaps.core.interfaces.plugin.PluginDescription import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.source.BgSource import app.aaps.core.interfaces.utils.DateUtil +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.workflow.LoggingWorker import dagger.android.HasAndroidInjector import kotlinx.coroutines.Dispatchers @@ -27,9 +28,10 @@ import javax.inject.Singleton @Singleton class MM640gPlugin @Inject constructor( rh: ResourceHelper, - aapsLogger: AAPSLogger + aapsLogger: AAPSLogger, + preferences: Preferences ) : AbstractBgSourcePlugin( - PluginDescription() + pluginDescription = PluginDescription() .mainType(PluginType.BGSOURCE) .fragmentClass(BGSourceFragment::class.java.name) .preferencesId(PluginDescription.PREFERENCE_SCREEN) @@ -37,7 +39,8 @@ class MM640gPlugin @Inject constructor( .pluginName(R.string.mm640g) .preferencesVisibleInSimpleMode(false) .description(R.string.description_source_mm640g), - aapsLogger, rh + ownPreferences = emptyList(), + aapsLogger, rh, preferences ), BgSource { // cannot be inner class because of needed injection diff --git a/plugins/source/src/main/kotlin/app/aaps/plugins/source/OttaiPlugin.kt b/plugins/source/src/main/kotlin/app/aaps/plugins/source/OttaiPlugin.kt index 41deea9980b..50a1c4f4708 100755 --- a/plugins/source/src/main/kotlin/app/aaps/plugins/source/OttaiPlugin.kt +++ b/plugins/source/src/main/kotlin/app/aaps/plugins/source/OttaiPlugin.kt @@ -15,6 +15,7 @@ import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.plugin.PluginDescription import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.source.BgSource +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.workflow.LoggingWorker import dagger.android.HasAndroidInjector import kotlinx.coroutines.Dispatchers @@ -26,9 +27,10 @@ import javax.inject.Singleton @Singleton class OttaiPlugin @Inject constructor( rh: ResourceHelper, - aapsLogger: AAPSLogger + aapsLogger: AAPSLogger, + preferences: Preferences ) : AbstractBgSourcePlugin( - PluginDescription() + pluginDescription = PluginDescription() .mainType(PluginType.BGSOURCE) .fragmentClass(BGSourceFragment::class.java.name) .pluginIcon(app.aaps.core.objects.R.drawable.ic_ottai) @@ -36,8 +38,10 @@ class OttaiPlugin @Inject constructor( .pluginName(R.string.ottai_app) .preferencesVisibleInSimpleMode(false) .description(R.string.description_source_patched_ottai_app), - aapsLogger, rh + ownPreferences = emptyList(), + aapsLogger, rh, preferences ), BgSource { + class OttaiWorker( context: Context, params: WorkerParameters @@ -52,10 +56,10 @@ class OttaiPlugin @Inject constructor( var ret = Result.success() if (!ottaiPlugin.isEnabled()) return Result.success(workDataOf("Result" to "Plugin not enabled")) val collection = inputData.getString("collection") ?: return Result.failure(workDataOf("Error" to "missing collection")) - if (collection == "entries"){ + if (collection == "entries") { val data = inputData.getString("data") aapsLogger.debug(LTag.BGSOURCE, "Received Ottai Data $data") - if (!data.isNullOrEmpty()){ + if (!data.isNullOrEmpty()) { try { val glucoseValues = mutableListOf() val jsonArray = JSONArray(data) @@ -71,6 +75,7 @@ class OttaiPlugin @Inject constructor( trendArrow = TrendArrow.fromString(jsonObject.getString("direction")), sourceSensor = SourceSensor.OTTAI ) + else -> aapsLogger.debug(LTag.BGSOURCE, "Unknown entries type: $type") } } diff --git a/plugins/source/src/main/kotlin/app/aaps/plugins/source/PoctechPlugin.kt b/plugins/source/src/main/kotlin/app/aaps/plugins/source/PoctechPlugin.kt index dc162fd5c57..a3e9d45b8c5 100644 --- a/plugins/source/src/main/kotlin/app/aaps/plugins/source/PoctechPlugin.kt +++ b/plugins/source/src/main/kotlin/app/aaps/plugins/source/PoctechPlugin.kt @@ -17,6 +17,7 @@ import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.plugin.PluginDescription import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.source.BgSource +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.workflow.LoggingWorker import app.aaps.core.utils.JsonHelper.safeGetString import dagger.android.HasAndroidInjector @@ -29,7 +30,8 @@ import javax.inject.Singleton @Singleton class PoctechPlugin @Inject constructor( rh: ResourceHelper, - aapsLogger: AAPSLogger + aapsLogger: AAPSLogger, + preferences: Preferences ) : AbstractBgSourcePlugin( PluginDescription() .mainType(PluginType.BGSOURCE) @@ -39,7 +41,8 @@ class PoctechPlugin @Inject constructor( .pluginName(R.string.poctech) .preferencesVisibleInSimpleMode(false) .description(R.string.description_source_poctech), - aapsLogger, rh + ownPreferences = emptyList(), + aapsLogger, rh, preferences ), BgSource { // cannot be inner class because of needed injection diff --git a/plugins/source/src/main/kotlin/app/aaps/plugins/source/RandomBgPlugin.kt b/plugins/source/src/main/kotlin/app/aaps/plugins/source/RandomBgPlugin.kt index d60c34e00dd..0b17a3de6c5 100644 --- a/plugins/source/src/main/kotlin/app/aaps/plugins/source/RandomBgPlugin.kt +++ b/plugins/source/src/main/kotlin/app/aaps/plugins/source/RandomBgPlugin.kt @@ -28,7 +28,7 @@ import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.source.BgSource import app.aaps.core.keys.BooleanKey import app.aaps.core.keys.IntKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.utils.isRunningTest import app.aaps.core.validators.preferences.AdaptiveIntPreference import app.aaps.core.validators.preferences.AdaptiveSwitchPreference diff --git a/plugins/source/src/main/kotlin/app/aaps/plugins/source/SyaiTagPlugin.kt b/plugins/source/src/main/kotlin/app/aaps/plugins/source/SyaiTagPlugin.kt index 48c56f54a04..719909dfb7e 100755 --- a/plugins/source/src/main/kotlin/app/aaps/plugins/source/SyaiTagPlugin.kt +++ b/plugins/source/src/main/kotlin/app/aaps/plugins/source/SyaiTagPlugin.kt @@ -15,6 +15,7 @@ import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.plugin.PluginDescription import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.source.BgSource +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.workflow.LoggingWorker import dagger.android.HasAndroidInjector import kotlinx.coroutines.Dispatchers @@ -26,7 +27,8 @@ import javax.inject.Singleton @Singleton class SyaiTagPlugin @Inject constructor( rh: ResourceHelper, - aapsLogger: AAPSLogger + aapsLogger: AAPSLogger, + preferences: Preferences ) : AbstractBgSourcePlugin( PluginDescription() .mainType(PluginType.BGSOURCE) @@ -36,8 +38,10 @@ class SyaiTagPlugin @Inject constructor( .pluginName(R.string.syai_tag_app) .preferencesVisibleInSimpleMode(false) .description(R.string.description_source_patched_syai_tag_app), - aapsLogger, rh + ownPreferences = emptyList(), + aapsLogger, rh, preferences ), BgSource { + class SyaiTagWorker( context: Context, params: WorkerParameters @@ -52,10 +56,10 @@ class SyaiTagPlugin @Inject constructor( var ret = Result.success() if (!syaiTagPlugin.isEnabled()) return Result.success(workDataOf("Result" to "Plugin not enabled")) val collection = inputData.getString("collection") ?: return Result.failure(workDataOf("Error" to "missing collection")) - if (collection == "entries"){ + if (collection == "entries") { val data = inputData.getString("data") aapsLogger.debug(LTag.BGSOURCE, "Received Syai Tag Data $data") - if (!data.isNullOrEmpty()){ + if (!data.isNullOrEmpty()) { try { val glucoseValues = mutableListOf() val jsonArray = JSONArray(data) @@ -71,6 +75,7 @@ class SyaiTagPlugin @Inject constructor( trendArrow = TrendArrow.fromString(jsonObject.getString("direction")), sourceSensor = SourceSensor.SYAI_TAG ) + else -> aapsLogger.debug(LTag.BGSOURCE, "Unknown entries type: $type") } } diff --git a/plugins/source/src/main/kotlin/app/aaps/plugins/source/TomatoPlugin.kt b/plugins/source/src/main/kotlin/app/aaps/plugins/source/TomatoPlugin.kt index 3f8548acd15..bd44d5f24a8 100644 --- a/plugins/source/src/main/kotlin/app/aaps/plugins/source/TomatoPlugin.kt +++ b/plugins/source/src/main/kotlin/app/aaps/plugins/source/TomatoPlugin.kt @@ -13,8 +13,8 @@ import app.aaps.core.interfaces.db.PersistenceLayer import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.plugin.PluginDescription import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.source.BgSource +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.workflow.LoggingWorker import dagger.android.HasAndroidInjector import kotlinx.coroutines.Dispatchers @@ -24,7 +24,8 @@ import javax.inject.Singleton @Singleton class TomatoPlugin @Inject constructor( rh: ResourceHelper, - aapsLogger: AAPSLogger + aapsLogger: AAPSLogger, + preferences: Preferences ) : AbstractBgSourcePlugin( PluginDescription() .mainType(PluginType.BGSOURCE) @@ -35,7 +36,8 @@ class TomatoPlugin @Inject constructor( .shortName(R.string.tomato_short) .preferencesVisibleInSimpleMode(false) .description(R.string.description_source_tomato), - aapsLogger, rh + ownPreferences = emptyList(), + aapsLogger, rh, preferences ), BgSource { // cannot be inner class because of needed injection @@ -46,7 +48,6 @@ class TomatoPlugin @Inject constructor( @Inject lateinit var injector: HasAndroidInjector @Inject lateinit var tomatoPlugin: TomatoPlugin - @Inject lateinit var sp: SP @Inject lateinit var persistenceLayer: PersistenceLayer @SuppressLint("CheckResult") diff --git a/plugins/source/src/main/kotlin/app/aaps/plugins/source/XdripSourcePlugin.kt b/plugins/source/src/main/kotlin/app/aaps/plugins/source/XdripSourcePlugin.kt index f8d8bda04a9..b5102bbbcc8 100644 --- a/plugins/source/src/main/kotlin/app/aaps/plugins/source/XdripSourcePlugin.kt +++ b/plugins/source/src/main/kotlin/app/aaps/plugins/source/XdripSourcePlugin.kt @@ -23,7 +23,7 @@ import app.aaps.core.interfaces.source.BgSource import app.aaps.core.interfaces.source.XDripSource import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.keys.BooleanKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.workflow.LoggingWorker import app.aaps.core.utils.receivers.DataWorkerStorage import kotlinx.coroutines.Dispatchers diff --git a/plugins/source/src/main/kotlin/app/aaps/plugins/source/keys/GlunovoLongKey.kt b/plugins/source/src/main/kotlin/app/aaps/plugins/source/keys/GlunovoLongKey.kt new file mode 100644 index 00000000000..2cf0ea15922 --- /dev/null +++ b/plugins/source/src/main/kotlin/app/aaps/plugins/source/keys/GlunovoLongKey.kt @@ -0,0 +1,12 @@ +package app.aaps.plugins.source.keys + +import app.aaps.core.keys.interfaces.LongNonPreferenceKey + +enum class GlunovoLongKey( + override val key: String, + override val defaultValue: Long, + override val exportable: Boolean = true +) : LongNonPreferenceKey { + + LastProcessedTimestamp("last_processed_glunovo_timestamp", 0) +} \ No newline at end of file diff --git a/plugins/source/src/main/kotlin/app/aaps/plugins/source/keys/IntelligoLongKey.kt b/plugins/source/src/main/kotlin/app/aaps/plugins/source/keys/IntelligoLongKey.kt new file mode 100644 index 00000000000..3dd7d292cd7 --- /dev/null +++ b/plugins/source/src/main/kotlin/app/aaps/plugins/source/keys/IntelligoLongKey.kt @@ -0,0 +1,12 @@ +package app.aaps.plugins.source.keys + +import app.aaps.core.keys.interfaces.LongNonPreferenceKey + +enum class IntelligoLongKey( + override val key: String, + override val defaultValue: Long, + override val exportable: Boolean = true +) : LongNonPreferenceKey { + + LastProcessedTimestamp("last_processed_glunovo_timestamp", 0) +} \ No newline at end of file diff --git a/plugins/source/src/main/res/values/strings.xml b/plugins/source/src/main/res/values/strings.xml index 00b822b368c..af7401c8744 100644 --- a/plugins/source/src/main/res/values/strings.xml +++ b/plugins/source/src/main/res/values/strings.xml @@ -1,9 +1,6 @@ - last_processed_glunovo_timestamp - last_processed_intelligo_timestamp - NSClient BG NS BG Downloads BG data from Nightscout diff --git a/plugins/source/src/test/kotlin/app/aaps/plugins/source/GlimpPluginTest.kt b/plugins/source/src/test/kotlin/app/aaps/plugins/source/GlimpPluginTest.kt index 5e23fd8514e..6fe5bdac640 100644 --- a/plugins/source/src/test/kotlin/app/aaps/plugins/source/GlimpPluginTest.kt +++ b/plugins/source/src/test/kotlin/app/aaps/plugins/source/GlimpPluginTest.kt @@ -1,6 +1,7 @@ package app.aaps.plugins.source import app.aaps.core.interfaces.resources.ResourceHelper +import app.aaps.core.keys.interfaces.Preferences import app.aaps.shared.tests.TestBase import com.google.common.truth.Truth.assertThat import org.junit.jupiter.api.BeforeEach @@ -12,10 +13,11 @@ class GlimpPluginTest : TestBase() { private lateinit var glimpPlugin: GlimpPlugin @Mock lateinit var rh: ResourceHelper + @Mock lateinit var preferences: Preferences @BeforeEach fun setup() { - glimpPlugin = GlimpPlugin(rh, aapsLogger) + glimpPlugin = GlimpPlugin(rh, aapsLogger, preferences) } @Test fun advancedFilteringSupported() { diff --git a/plugins/source/src/test/kotlin/app/aaps/plugins/source/MM640GPluginTest.kt b/plugins/source/src/test/kotlin/app/aaps/plugins/source/MM640GPluginTest.kt index 0d08f77f8ec..dddbe43e872 100644 --- a/plugins/source/src/test/kotlin/app/aaps/plugins/source/MM640GPluginTest.kt +++ b/plugins/source/src/test/kotlin/app/aaps/plugins/source/MM640GPluginTest.kt @@ -1,6 +1,7 @@ package app.aaps.plugins.source import app.aaps.core.interfaces.resources.ResourceHelper +import app.aaps.core.keys.interfaces.Preferences import app.aaps.shared.tests.TestBase import com.google.common.truth.Truth.assertThat import org.junit.jupiter.api.BeforeEach @@ -12,10 +13,11 @@ class MM640GPluginTest : TestBase() { private lateinit var mM640gPlugin: MM640gPlugin @Mock lateinit var rh: ResourceHelper + @Mock lateinit var preferences: Preferences @BeforeEach fun setup() { - mM640gPlugin = MM640gPlugin(rh, aapsLogger) + mM640gPlugin = MM640gPlugin(rh, aapsLogger, preferences) } @Test fun advancedFilteringSupported() { diff --git a/plugins/source/src/test/kotlin/app/aaps/plugins/source/RandomBgPluginTest.kt b/plugins/source/src/test/kotlin/app/aaps/plugins/source/RandomBgPluginTest.kt index 394ed63ee20..9a7c6729b4e 100644 --- a/plugins/source/src/test/kotlin/app/aaps/plugins/source/RandomBgPluginTest.kt +++ b/plugins/source/src/test/kotlin/app/aaps/plugins/source/RandomBgPluginTest.kt @@ -1,11 +1,8 @@ package app.aaps.plugins.source -import android.content.SharedPreferences import androidx.preference.PreferenceManager import app.aaps.core.interfaces.db.PersistenceLayer import app.aaps.core.interfaces.pump.VirtualPump -import app.aaps.core.validators.preferences.AdaptiveIntPreference -import app.aaps.core.validators.preferences.AdaptiveSwitchPreference import app.aaps.shared.tests.TestBaseWithProfile import com.google.common.truth.Truth.assertThat import org.junit.jupiter.api.BeforeEach @@ -14,28 +11,11 @@ import org.mockito.Mock class RandomBgPluginTest : TestBaseWithProfile() { - @Mock lateinit var sharedPrefs: SharedPreferences @Mock lateinit var persistenceLayer: PersistenceLayer @Mock lateinit var virtualPump: VirtualPump private lateinit var randomBgPlugin: RandomBgPlugin - init { - addInjector { - if (it is AdaptiveSwitchPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - it.config = config - } - if (it is AdaptiveIntPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - it.profileUtil = profileUtil - it.config = config - } - } - } - @BeforeEach fun prepare() { preferenceManager = PreferenceManager(context) randomBgPlugin = RandomBgPlugin(context, rh, aapsLogger, persistenceLayer, virtualPump, preferences, config) diff --git a/plugins/source/src/test/kotlin/app/aaps/plugins/source/XdripSourcePluginTest.kt b/plugins/source/src/test/kotlin/app/aaps/plugins/source/XdripSourcePluginTest.kt index 556e3f69bcf..d722d108010 100644 --- a/plugins/source/src/test/kotlin/app/aaps/plugins/source/XdripSourcePluginTest.kt +++ b/plugins/source/src/test/kotlin/app/aaps/plugins/source/XdripSourcePluginTest.kt @@ -10,7 +10,7 @@ import app.aaps.core.interfaces.receivers.Intents import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.keys.BooleanKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.utils.receivers.DataWorkerStorage import app.aaps.shared.impl.utils.DateUtilImpl import app.aaps.shared.tests.BundleMock diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/garmin/GarminPlugin.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/garmin/GarminPlugin.kt index 39c20255b0e..0e4be0a37bb 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/garmin/GarminPlugin.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/garmin/GarminPlugin.kt @@ -10,22 +10,21 @@ import app.aaps.core.data.model.GlucoseUnit import app.aaps.core.data.plugin.PluginType import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.logging.LTag -import app.aaps.core.interfaces.plugin.PluginBase +import app.aaps.core.interfaces.plugin.PluginBaseWithPreferences import app.aaps.core.interfaces.plugin.PluginDescription import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventNewBG import app.aaps.core.interfaces.rx.events.EventPreferenceChange -import app.aaps.core.interfaces.sharedPreferences.SP -import app.aaps.core.keys.BooleanKey -import app.aaps.core.keys.IntKey -import app.aaps.core.keys.Preferences -import app.aaps.core.keys.StringKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.validators.DefaultEditTextValidator import app.aaps.core.validators.preferences.AdaptiveIntPreference import app.aaps.core.validators.preferences.AdaptiveStringPreference import app.aaps.core.validators.preferences.AdaptiveSwitchPreference import app.aaps.plugins.sync.R +import app.aaps.plugins.sync.garmin.keys.GarminBooleanKey +import app.aaps.plugins.sync.garmin.keys.GarminIntKey +import app.aaps.plugins.sync.garmin.keys.GarminStringKey import com.google.gson.JsonArray import com.google.gson.JsonObject import io.reactivex.rxjava3.disposables.CompositeDisposable @@ -57,24 +56,25 @@ import kotlin.math.roundToInt class GarminPlugin @Inject constructor( aapsLogger: AAPSLogger, resourceHelper: ResourceHelper, + preferences: Preferences, private val context: Context, private val loopHub: LoopHub, - private val rxBus: RxBus, - private val sp: SP, - private val preferences: Preferences -) : PluginBase( - PluginDescription() + private val rxBus: RxBus +) : PluginBaseWithPreferences( + pluginDescription = PluginDescription() .mainType(PluginType.SYNC) .pluginIcon(app.aaps.core.objects.R.drawable.ic_watch) .pluginName(R.string.garmin) .shortName(R.string.garmin) .description(R.string.garmin_description) .preferencesId(PluginDescription.PREFERENCE_SCREEN), - aapsLogger, resourceHelper + ownPreferences = listOf(GarminStringKey::class.java, GarminBooleanKey::class.java, GarminIntKey::class.java), + aapsLogger, resourceHelper, preferences ) { /** HTTP Server for local HTTP server communication (device app requests values) .*/ private var server: HttpServer? = null + @VisibleForTesting var garminMessengerField: GarminMessenger? = null val garminMessenger: GarminMessenger @@ -113,13 +113,13 @@ class GarminPlugin @Inject constructor( var newValue: Condition = valueLock.newCondition() private var lastGlucoseValueTimestamp: Long? = null private val glucoseUnitStr get() = if (loopHub.glucoseUnit == GlucoseUnit.MGDL) "mgdl" else "mmoll" - private val garminAapsKey get() = preferences.get(StringKey.GarminRequestKey) ?: "" + private val garminAapsKey get() = preferences.get(GarminStringKey.RequestKey) private fun onPreferenceChange(event: EventPreferenceChange) { when (event.changedKey) { - "communication_debug_mode" -> setupGarminMessenger() - BooleanKey.GarminLocalHttpServer.key, IntKey.GarminLocalHttpPort.key -> setupHttpServer() - StringKey.GarminRequestKey.key -> sendPhoneAppMessage() + "communication_ciq_debug_mode" -> setupGarminMessenger() + GarminBooleanKey.LocalHttpServer.key, GarminIntKey.LocalHttpPort.key -> setupHttpServer() + GarminStringKey.RequestKey.key -> sendPhoneAppMessage() } } @@ -129,7 +129,7 @@ class GarminPlugin @Inject constructor( } private fun createGarminMessenger(): GarminMessenger { - val enableDebug = sp.getBoolean("communication_ciq_debug_mode", false) + val enableDebug = false // sp.getBoolean("communication_ciq_debug_mode", false) aapsLogger.info(LTag.GARMIN, "initialize IQ messenger in debug=$enableDebug") return GarminMessenger( aapsLogger, context, glucoseAppIds, { _, _ -> }, true, enableDebug @@ -164,8 +164,8 @@ class GarminPlugin @Inject constructor( @VisibleForTesting fun setupHttpServer(wait: Duration) { - if (preferences.get(BooleanKey.GarminLocalHttpServer)) { - val port = preferences.get(IntKey.GarminLocalHttpPort) + if (preferences.get(GarminBooleanKey.LocalHttpServer)) { + val port = preferences.get(GarminIntKey.LocalHttpPort) if (server != null && server?.port == port) return aapsLogger.info(LTag.GARMIN, "starting HTTP server on $port") server?.close() @@ -345,7 +345,7 @@ class GarminPlugin @Inject constructor( val value = getQueryParameter(uri, name) return try { if (value.isNullOrEmpty()) defaultValue else value.toLong() - } catch (e: NumberFormatException) { + } catch (_: NumberFormatException) { aapsLogger.error(LTag.GARMIN, "invalid $name value '$value'") defaultValue } @@ -484,14 +484,17 @@ class GarminPlugin @Inject constructor( key = "garmin_settings" title = rh.gs(R.string.garmin) initialExpandedChildrenCount = 0 - addPreference(AdaptiveSwitchPreference(ctx = context, booleanKey = BooleanKey.GarminLocalHttpServer, title = R.string.garmin_local_http_server)) - addPreference(AdaptiveIntPreference(ctx = context, intKey = IntKey.GarminLocalHttpPort, title = R.string.garmin_local_http_server_port)) - addPreference(AdaptiveStringPreference( - ctx = context, - stringKey = StringKey.GarminRequestKey, - title = R.string.garmin_request_key, - summary = R.string.garmin_request_key_summary, - validatorParams = DefaultEditTextValidator.Parameters(emptyAllowed = true))) + addPreference(AdaptiveSwitchPreference(ctx = context, booleanKey = GarminBooleanKey.LocalHttpServer, title = R.string.garmin_local_http_server)) + addPreference(AdaptiveIntPreference(ctx = context, intKey = GarminIntKey.LocalHttpPort, title = R.string.garmin_local_http_server_port)) + addPreference( + AdaptiveStringPreference( + ctx = context, + stringKey = GarminStringKey.RequestKey, + title = R.string.garmin_request_key, + summary = R.string.garmin_request_key_summary, + validatorParams = DefaultEditTextValidator.Parameters(emptyAllowed = true) + ) + ) } } } diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/garmin/LoopHubImpl.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/garmin/LoopHubImpl.kt index 49ac3d8039f..90be628ddc5 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/garmin/LoopHubImpl.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/garmin/LoopHubImpl.kt @@ -22,9 +22,9 @@ import app.aaps.core.interfaces.profile.ProfileFunction import app.aaps.core.interfaces.profile.ProfileUtil import app.aaps.core.interfaces.pump.DetailedBolusInfo import app.aaps.core.interfaces.queue.CommandQueue -import app.aaps.core.keys.Preferences import app.aaps.core.keys.StringKey import app.aaps.core.keys.UnitDoubleKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.extensions.convertedToPercent import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign @@ -72,12 +72,12 @@ class LoopHubImpl @Inject constructor( get() = iobCobCalculator.calculateIobFromBolus().iob /** Returns the remaining bolus and basal insulin on board. */ - override val insulinBasalOnboard :Double + override val insulinBasalOnboard: Double get() = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().basaliob /** Returns the remaining carbs on board. */ override val carbsOnboard: Double? - get() = iobCobCalculator.getCobInfo("LoopHubImpl").displayCob + get() = iobCobCalculator.getCobInfo("LoopHubImpl").displayCob /** Returns true if the pump is connected. */ override val isConnected: Boolean get() = !loop.isDisconnected @@ -98,11 +98,15 @@ class LoopHubImpl @Inject constructor( } ?: Double.NaN } - override val lowGlucoseMark get() = profileUtil.convertToMgdl( - preferences.get(UnitDoubleKey.OverviewLowMark), glucoseUnit) + override val lowGlucoseMark + get() = profileUtil.convertToMgdl( + preferences.get(UnitDoubleKey.OverviewLowMark), glucoseUnit + ) - override val highGlucoseMark get() = profileUtil.convertToMgdl( - preferences.get(UnitDoubleKey.OverviewHighMark), glucoseUnit) + override val highGlucoseMark + get() = profileUtil.convertToMgdl( + preferences.get(UnitDoubleKey.OverviewHighMark), glucoseUnit + ) /** Tells the loop algorithm that the pump is physically connected. */ override fun connectPump() { diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/garmin/keys/GarminBooleanKey.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/garmin/keys/GarminBooleanKey.kt new file mode 100644 index 00000000000..5a8336db64b --- /dev/null +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/garmin/keys/GarminBooleanKey.kt @@ -0,0 +1,22 @@ +package app.aaps.plugins.sync.garmin.keys + +import app.aaps.core.keys.interfaces.BooleanPreferenceKey + +enum class GarminBooleanKey( + override val key: String, + override val defaultValue: Boolean, + override val calculatedDefaultValue: Boolean = false, + override val defaultedBySM: Boolean = false, + override val showInApsMode: Boolean = true, + override val showInNsClientMode: Boolean = true, + override val showInPumpControlMode: Boolean = true, + override val dependency: BooleanPreferenceKey? = null, + override val negativeDependency: BooleanPreferenceKey? = null, + override val hideParentScreenIfHidden: Boolean = false, + override val engineeringModeOnly: Boolean = false, + override val exportable: Boolean = true +) : BooleanPreferenceKey { + + LocalHttpServer("communication_http", false, defaultedBySM = true, hideParentScreenIfHidden = true), +} + diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/garmin/keys/GarminIntKey.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/garmin/keys/GarminIntKey.kt new file mode 100644 index 00000000000..3095521817f --- /dev/null +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/garmin/keys/GarminIntKey.kt @@ -0,0 +1,24 @@ +package app.aaps.plugins.sync.garmin.keys + +import app.aaps.core.keys.interfaces.BooleanPreferenceKey +import app.aaps.core.keys.interfaces.IntPreferenceKey + +enum class GarminIntKey( + override val key: String, + override val defaultValue: Int, + override val min: Int, + override val max: Int, + override val defaultedBySM: Boolean = false, + override val calculatedDefaultValue: Boolean = false, + override val showInApsMode: Boolean = true, + override val showInNsClientMode: Boolean = true, + override val showInPumpControlMode: Boolean = true, + override val dependency: BooleanPreferenceKey? = null, + override val negativeDependency: BooleanPreferenceKey? = null, + override val hideParentScreenIfHidden: Boolean = false, + override val engineeringModeOnly: Boolean = false, + override val exportable: Boolean = true +) : IntPreferenceKey { + + LocalHttpPort("communication_http_port", 28891, 1001, 65535, defaultedBySM = true, hideParentScreenIfHidden = true), +} \ No newline at end of file diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/garmin/keys/GarminStringKey.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/garmin/keys/GarminStringKey.kt new file mode 100644 index 00000000000..62ddd84e6be --- /dev/null +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/garmin/keys/GarminStringKey.kt @@ -0,0 +1,22 @@ +package app.aaps.plugins.sync.garmin.keys + +import app.aaps.core.keys.interfaces.BooleanPreferenceKey +import app.aaps.core.keys.interfaces.StringPreferenceKey + +enum class GarminStringKey( + override val key: String, + override val defaultValue: String, + override val defaultedBySM: Boolean = false, + override val showInApsMode: Boolean = true, + override val showInNsClientMode: Boolean = true, + override val showInPumpControlMode: Boolean = true, + override val dependency: BooleanPreferenceKey? = null, + override val negativeDependency: BooleanPreferenceKey? = null, + override val hideParentScreenIfHidden: Boolean = false, + override val isPassword: Boolean = false, + override val isPin: Boolean = false, + override val exportable: Boolean = true +) : StringPreferenceKey { + + RequestKey(key = "garmin_aaps_key", defaultValue = ""), +} diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsShared/NSClientFragment.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsShared/NSClientFragment.kt index 26bc4878e18..1caf92b9297 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsShared/NSClientFragment.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsShared/NSClientFragment.kt @@ -31,8 +31,8 @@ import app.aaps.core.interfaces.rx.AapsSchedulers import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventNSClientNewLog import app.aaps.core.interfaces.rx.events.EventNSClientRestart -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.fabric.FabricPrivacy +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.ui.dialogs.OKDialog import app.aaps.core.utils.HtmlHelper import app.aaps.plugins.sync.R @@ -41,6 +41,7 @@ import app.aaps.plugins.sync.databinding.NsClientLogItemBinding import app.aaps.plugins.sync.nsShared.events.EventNSClientUpdateGuiData import app.aaps.plugins.sync.nsShared.events.EventNSClientUpdateGuiQueue import app.aaps.plugins.sync.nsShared.events.EventNSClientUpdateGuiStatus +import app.aaps.plugins.sync.nsclientV3.keys.NsclientBooleanKey import dagger.android.support.DaggerFragment import io.reactivex.rxjava3.core.Completable import io.reactivex.rxjava3.disposables.CompositeDisposable @@ -51,7 +52,7 @@ import javax.inject.Inject class NSClientFragment : DaggerFragment(), MenuProvider, PluginFragment { - @Inject lateinit var sp: SP + @Inject lateinit var preferences: Preferences @Inject lateinit var rh: ResourceHelper @Inject lateinit var rxBus: RxBus @Inject lateinit var fabricPrivacy: FabricPrivacy @@ -99,7 +100,7 @@ class NSClientFragment : DaggerFragment(), MenuProvider, PluginFragment { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) - binding.paused.isChecked = sp.getBoolean(R.string.key_ns_paused, false) + binding.paused.isChecked = preferences.get(NsclientBooleanKey.NsPaused) binding.paused.setOnCheckedChangeListener { _, isChecked -> uel.log(action = if (isChecked) Action.NS_PAUSED else Action.NS_RESUME, source = Sources.NSClient) nsClientPlugin?.pause(isChecked) @@ -231,7 +232,7 @@ class NSClientFragment : DaggerFragment(), MenuProvider, PluginFragment { private fun updateStatus() { if (_binding == null) return - binding.paused.isChecked = sp.getBoolean(R.string.key_ns_paused, false) + binding.paused.isChecked = preferences.get(NsclientBooleanKey.NsPaused) binding.url.text = nsClientPlugin?.address binding.status.text = nsClientPlugin?.status } diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsShared/NsIncomingDataProcessor.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsShared/NsIncomingDataProcessor.kt index 1b5086f553d..4de0c4c7f0b 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsShared/NsIncomingDataProcessor.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsShared/NsIncomingDataProcessor.kt @@ -19,12 +19,13 @@ import app.aaps.core.interfaces.profile.ProfileSource import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventDismissNotification import app.aaps.core.interfaces.rx.events.EventNSClientNewLog -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.source.NSClientSource import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.keys.BooleanKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.BooleanNonKey +import app.aaps.core.keys.LongNonKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.nssdk.localmodel.entry.NSSgvV3 import app.aaps.core.nssdk.localmodel.food.NSFood import app.aaps.core.nssdk.localmodel.treatment.NSBolus @@ -61,7 +62,6 @@ import javax.inject.Singleton class NsIncomingDataProcessor @Inject constructor( private val aapsLogger: AAPSLogger, private val nsClientSource: NSClientSource, - private val sp: SP, private val preferences: Preferences, private val rxBus: RxBus, private val dateUtil: DateUtil, @@ -94,7 +94,7 @@ class NsIncomingDataProcessor @Inject constructor( @Suppress("SpellCheckingInspection") fun processSgvs(sgvs: Any, doFullSync: Boolean): Boolean { // Objective0 - sp.putBoolean(app.aaps.core.utils.R.string.key_objectives_bg_is_available_in_ns, true) + preferences.put(BooleanNonKey.ObjectivesBgIsAvailableInNs, true) if (!nsClientSource.isEnabled() && !preferences.get(BooleanKey.NsClientAcceptCgmData) && !doFullSync) return false @@ -201,9 +201,10 @@ class NsIncomingDataProcessor @Inject constructor( if (preferences.get(BooleanKey.NsClientAcceptTherapyEvent) || config.AAPSCLIENT || doFullSync) treatment.toTherapyEvent().let { therapyEvent -> storeDataForDb.addToTherapyEvents(therapyEvent) - if (therapyEvent.type == TE.Type.ANNOUNCEMENT && + if (therapyEvent.type == TE.Type.ANNOUNCEMENT && preferences.get(BooleanKey.NsClientNotificationsFromAnnouncements) && - therapyEvent.timestamp + T.mins(60).msecs() > dateUtil.now()) + therapyEvent.timestamp + T.mins(60).msecs() > dateUtil.now() + ) uiInteraction.addNotificationWithAction( id = Notification.NS_ANNOUNCEMENT, text = therapyEvent.note ?: "", @@ -283,7 +284,7 @@ class NsIncomingDataProcessor @Inject constructor( if (preferences.get(BooleanKey.NsClientAcceptProfileStore) || config.AAPSCLIENT || doFullSync) { val store = instantiator.provideProfileStore(profileJson) val createdAt = store.getStartDate() - val lastLocalChange = sp.getLong(app.aaps.core.utils.R.string.key_local_profile_last_change, 0) + val lastLocalChange = preferences.get(LongNonKey.LocalProfileLastChange) aapsLogger.debug(LTag.PROFILE, "Received profileStore: createdAt: $createdAt Local last modification: $lastLocalChange") if (createdAt > lastLocalChange || createdAt % 1000 == 0L) { // whole second means edited in NS profileSource.loadFromStore(store) diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsShared/StoreDataForDbImpl.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsShared/StoreDataForDbImpl.kt index e9c59daeb46..fb8654a34f7 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsShared/StoreDataForDbImpl.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsShared/StoreDataForDbImpl.kt @@ -28,12 +28,9 @@ import app.aaps.core.interfaces.nsclient.StoreDataForDb import app.aaps.core.interfaces.pump.VirtualPump import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventNSClientNewLog -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.source.NSClientSource -import app.aaps.core.interfaces.ui.UiInteraction -import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.keys.BooleanKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import io.reactivex.rxjava3.kotlin.subscribeBy @@ -48,14 +45,11 @@ class StoreDataForDbImpl @Inject constructor( private val aapsLogger: AAPSLogger, private val rxBus: RxBus, private val persistenceLayer: PersistenceLayer, - private val sp: SP, private val preferences: Preferences, private val uel: UserEntryLogger, - private val dateUtil: DateUtil, private val config: Config, private val nsClientSource: NSClientSource, - private val virtualPump: VirtualPump, - private val uiInteraction: UiInteraction + private val virtualPump: VirtualPump ) : StoreDataForDb { private val glucoseValues: MutableList = mutableListOf() diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/DataSyncSelectorV1.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/DataSyncSelectorV1.kt index ad1f65e76b2..ba36b3a0948 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/DataSyncSelectorV1.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/DataSyncSelectorV1.kt @@ -7,18 +7,19 @@ import app.aaps.core.interfaces.plugin.ActivePlugin import app.aaps.core.interfaces.profile.ProfileFunction import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventNSClientNewLog -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.source.NSClientSource import app.aaps.core.interfaces.sync.DataSyncSelector import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.keys.BooleanKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.LongNonKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.utils.JsonHelper import app.aaps.core.utils.waitMillis -import app.aaps.plugins.sync.R import app.aaps.plugins.sync.nsShared.events.EventNSClientUpdateGuiQueue import app.aaps.plugins.sync.nsShared.events.EventNSClientUpdateGuiStatus import app.aaps.plugins.sync.nsShared.extensions.onlyNsIdAdded +import app.aaps.plugins.sync.nsclientV3.keys.NsclientBooleanKey +import app.aaps.plugins.sync.nsclientV3.keys.NsclientLongKey import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob @@ -28,7 +29,6 @@ import javax.inject.Singleton @Singleton class DataSyncSelectorV1 @Inject constructor( - private val sp: SP, private val preferences: Preferences, private val aapsLogger: AAPSLogger, private val dateUtil: DateUtil, @@ -73,7 +73,7 @@ class DataSyncSelectorV1 @Inject constructor( } private val queueCounter = QueueCounter() - private val isPaused get() = sp.getBoolean(R.string.key_ns_paused, false) + private val isPaused get() = preferences.get(NsclientBooleanKey.NsPaused) override fun queueSize(): Long = queueCounter.size() @@ -92,19 +92,19 @@ class DataSyncSelectorV1 @Inject constructor( } rxBus.send(EventNSClientUpdateGuiStatus()) if (preferences.get(BooleanKey.NsClientUploadData) && !isPaused) { - queueCounter.bolusesRemaining = (persistenceLayer.getLastBolusId() ?: 0L) - sp.getLong(R.string.key_ns_bolus_last_synced_id, 0) - queueCounter.carbsRemaining = (persistenceLayer.getLastCarbsId() ?: 0L) - sp.getLong(R.string.key_ns_carbs_last_synced_id, 0) - queueCounter.bcrRemaining = (persistenceLayer.getLastBolusCalculatorResultId() ?: 0L) - sp.getLong(R.string.key_ns_bolus_calculator_result_last_synced_id, 0) - queueCounter.ttsRemaining = (persistenceLayer.getLastTemporaryTargetId() ?: 0L) - sp.getLong(R.string.key_ns_temporary_target_last_synced_id, 0) - queueCounter.foodsRemaining = (persistenceLayer.getLastFoodId() ?: 0L) - sp.getLong(R.string.key_ns_food_last_synced_id, 0) - queueCounter.gvsRemaining = (persistenceLayer.getLastGlucoseValueId() ?: 0L) - sp.getLong(R.string.key_ns_glucose_value_last_synced_id, 0) - queueCounter.tesRemaining = (persistenceLayer.getLastTherapyEventId() ?: 0L) - sp.getLong(R.string.key_ns_therapy_event_last_synced_id, 0) - queueCounter.dssRemaining = (persistenceLayer.getLastDeviceStatusId() ?: 0L) - sp.getLong(R.string.key_ns_device_status_last_synced_id, 0) - queueCounter.tbrsRemaining = (persistenceLayer.getLastTemporaryBasalId() ?: 0L) - sp.getLong(R.string.key_ns_temporary_basal_last_synced_id, 0) - queueCounter.ebsRemaining = (persistenceLayer.getLastExtendedBolusId() ?: 0L) - sp.getLong(R.string.key_ns_extended_bolus_last_synced_id, 0) - queueCounter.pssRemaining = (persistenceLayer.getLastProfileSwitchId() ?: 0L) - sp.getLong(R.string.key_ns_profile_switch_last_synced_id, 0) - queueCounter.epssRemaining = (persistenceLayer.getLastEffectiveProfileSwitchId() ?: 0L) - sp.getLong(R.string.key_ns_effective_profile_switch_last_synced_id, 0) - queueCounter.oesRemaining = (persistenceLayer.getLastOfflineEventId() ?: 0L) - sp.getLong(R.string.key_ns_offline_event_last_synced_id, 0) + queueCounter.bolusesRemaining = (persistenceLayer.getLastBolusId() ?: 0L) - preferences.get(NsclientLongKey.BolusLastSyncedId) + queueCounter.carbsRemaining = (persistenceLayer.getLastCarbsId() ?: 0L) - preferences.get(NsclientLongKey.CarbsLastSyncedId) + queueCounter.bcrRemaining = (persistenceLayer.getLastBolusCalculatorResultId() ?: 0L) - preferences.get(NsclientLongKey.BolusCalculatorLastSyncedId) + queueCounter.ttsRemaining = (persistenceLayer.getLastTemporaryTargetId() ?: 0L) - preferences.get(NsclientLongKey.TemporaryTargetLastSyncedId) + queueCounter.foodsRemaining = (persistenceLayer.getLastFoodId() ?: 0L) - preferences.get(NsclientLongKey.FoodLastSyncedId) + queueCounter.gvsRemaining = (persistenceLayer.getLastGlucoseValueId() ?: 0L) - preferences.get(NsclientLongKey.GlucoseValueLastSyncedId) + queueCounter.tesRemaining = (persistenceLayer.getLastTherapyEventId() ?: 0L) - preferences.get(NsclientLongKey.TherapyEventLastSyncedId) + queueCounter.dssRemaining = (persistenceLayer.getLastDeviceStatusId() ?: 0L) - preferences.get(NsclientLongKey.DeviceStatusLastSyncedId) + queueCounter.tbrsRemaining = (persistenceLayer.getLastTemporaryBasalId() ?: 0L) - preferences.get(NsclientLongKey.TemporaryBasalLastSyncedId) + queueCounter.ebsRemaining = (persistenceLayer.getLastExtendedBolusId() ?: 0L) - preferences.get(NsclientLongKey.ExtendedBolusLastSyncedId) + queueCounter.pssRemaining = (persistenceLayer.getLastProfileSwitchId() ?: 0L) - preferences.get(NsclientLongKey.ProfileSwitchLastSyncedId) + queueCounter.epssRemaining = (persistenceLayer.getLastEffectiveProfileSwitchId() ?: 0L) - preferences.get(NsclientLongKey.EffectiveProfileSwitchLastSyncedId) + queueCounter.oesRemaining = (persistenceLayer.getLastOfflineEventId() ?: 0L) - preferences.get(NsclientLongKey.OfflineEventLastSyncedId) rxBus.send(EventNSClientUpdateGuiQueue()) val boluses = scope.async { processChangedBoluses() } val carbs = scope.async { processChangedCarbs() } @@ -141,28 +141,28 @@ class DataSyncSelectorV1 @Inject constructor( } override fun resetToNextFullSync() { - sp.remove(R.string.key_ns_glucose_value_last_synced_id) - sp.remove(R.string.key_ns_temporary_basal_last_synced_id) - sp.remove(R.string.key_ns_temporary_target_last_synced_id) - sp.remove(R.string.key_ns_extended_bolus_last_synced_id) - sp.remove(R.string.key_ns_food_last_synced_id) - sp.remove(R.string.key_ns_bolus_last_synced_id) - sp.remove(R.string.key_ns_carbs_last_synced_id) - sp.remove(R.string.key_ns_bolus_calculator_result_last_synced_id) - sp.remove(R.string.key_ns_therapy_event_last_synced_id) - sp.remove(R.string.key_ns_profile_switch_last_synced_id) - sp.remove(R.string.key_ns_effective_profile_switch_last_synced_id) - sp.remove(R.string.key_ns_offline_event_last_synced_id) - sp.remove(R.string.key_ns_profile_store_last_synced_timestamp) + preferences.remove(NsclientLongKey.GlucoseValueLastSyncedId) + preferences.remove(NsclientLongKey.TemporaryBasalLastSyncedId) + preferences.remove(NsclientLongKey.TemporaryTargetLastSyncedId) + preferences.remove(NsclientLongKey.ExtendedBolusLastSyncedId) + preferences.remove(NsclientLongKey.FoodLastSyncedId) + preferences.remove(NsclientLongKey.BolusLastSyncedId) + preferences.remove(NsclientLongKey.CarbsLastSyncedId) + preferences.remove(NsclientLongKey.BolusCalculatorLastSyncedId) + preferences.remove(NsclientLongKey.TherapyEventLastSyncedId) + preferences.remove(NsclientLongKey.ProfileSwitchLastSyncedId) + preferences.remove(NsclientLongKey.EffectiveProfileSwitchLastSyncedId) + preferences.remove(NsclientLongKey.OfflineEventLastSyncedId) + preferences.remove(NsclientLongKey.ProfileStoreLastSyncedId) val lastDeviceStatusDbId = persistenceLayer.getLastDeviceStatusId() - if (lastDeviceStatusDbId != null) sp.putLong(R.string.key_ns_device_status_last_synced_id, lastDeviceStatusDbId) - else sp.remove(R.string.key_ns_device_status_last_synced_id) + if (lastDeviceStatusDbId != null) preferences.put(NsclientLongKey.DeviceStatusLastSyncedId, lastDeviceStatusDbId) + else preferences.remove(NsclientLongKey.DeviceStatusLastSyncedId) } private fun confirmLastBolusIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_ns_bolus_last_synced_id, 0)) { - sp.putLong(R.string.key_ns_bolus_last_synced_id, lastSynced) + if (lastSynced > preferences.get(NsclientLongKey.BolusLastSyncedId)) { + preferences.put(NsclientLongKey.BolusLastSyncedId, lastSynced) } } @@ -171,9 +171,9 @@ class DataSyncSelectorV1 @Inject constructor( while (cont) { if (isPaused) return val lastDbId = persistenceLayer.getLastBolusId() ?: 0L - var startId = sp.getLong(R.string.key_ns_bolus_last_synced_id, 0) + var startId = preferences.get(NsclientLongKey.BolusLastSyncedId) if (startId > lastDbId) { - sp.putLong(R.string.key_ns_bolus_last_synced_id, 0) + preferences.put(NsclientLongKey.BolusLastSyncedId, 0) startId = 0 } queueCounter.bolusesRemaining = lastDbId - startId @@ -209,8 +209,8 @@ class DataSyncSelectorV1 @Inject constructor( } private fun confirmLastCarbsIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_ns_carbs_last_synced_id, 0)) { - sp.putLong(R.string.key_ns_carbs_last_synced_id, lastSynced) + if (lastSynced > preferences.get(NsclientLongKey.CarbsLastSyncedId)) { + preferences.put(NsclientLongKey.CarbsLastSyncedId, lastSynced) } } @@ -219,9 +219,9 @@ class DataSyncSelectorV1 @Inject constructor( while (cont) { if (isPaused) return val lastDbId = persistenceLayer.getLastCarbsId() ?: 0L - var startId = sp.getLong(R.string.key_ns_carbs_last_synced_id, 0) + var startId = preferences.get(NsclientLongKey.CarbsLastSyncedId) if (startId > lastDbId) { - sp.putLong(R.string.key_ns_carbs_last_synced_id, 0) + preferences.put(NsclientLongKey.CarbsLastSyncedId, 0) startId = 0 } queueCounter.carbsRemaining = lastDbId - startId @@ -257,8 +257,8 @@ class DataSyncSelectorV1 @Inject constructor( } private fun confirmLastBolusCalculatorResultsIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_ns_bolus_calculator_result_last_synced_id, 0)) { - sp.putLong(R.string.key_ns_bolus_calculator_result_last_synced_id, lastSynced) + if (lastSynced > preferences.get(NsclientLongKey.BolusCalculatorLastSyncedId)) { + preferences.put(NsclientLongKey.BolusCalculatorLastSyncedId, lastSynced) } } @@ -267,9 +267,9 @@ class DataSyncSelectorV1 @Inject constructor( while (cont) { if (isPaused) return val lastDbId = persistenceLayer.getLastBolusCalculatorResultId() ?: 0L - var startId = sp.getLong(R.string.key_ns_bolus_calculator_result_last_synced_id, 0) + var startId = preferences.get(NsclientLongKey.BolusCalculatorLastSyncedId) if (startId > lastDbId) { - sp.putLong(R.string.key_ns_bolus_calculator_result_last_synced_id, 0) + preferences.put(NsclientLongKey.BolusCalculatorLastSyncedId, 0) startId = 0 } queueCounter.bcrRemaining = lastDbId - startId @@ -305,8 +305,8 @@ class DataSyncSelectorV1 @Inject constructor( } private fun confirmLastTempTargetsIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_ns_temporary_target_last_synced_id, 0)) { - sp.putLong(R.string.key_ns_temporary_target_last_synced_id, lastSynced) + if (lastSynced > preferences.get(NsclientLongKey.TemporaryTargetLastSyncedId)) { + preferences.put(NsclientLongKey.TemporaryTargetLastSyncedId, lastSynced) } } @@ -315,9 +315,9 @@ class DataSyncSelectorV1 @Inject constructor( while (cont) { if (isPaused) return val lastDbId = persistenceLayer.getLastTemporaryTargetId() ?: 0L - var startId = sp.getLong(R.string.key_ns_temporary_target_last_synced_id, 0) + var startId = preferences.get(NsclientLongKey.TemporaryTargetLastSyncedId) if (startId > lastDbId) { - sp.putLong(R.string.key_ns_temporary_target_last_synced_id, 0) + preferences.put(NsclientLongKey.TemporaryTargetLastSyncedId, 0) startId = 0 } queueCounter.ttsRemaining = lastDbId - startId @@ -353,8 +353,8 @@ class DataSyncSelectorV1 @Inject constructor( } private fun confirmLastFoodIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_ns_food_last_synced_id, 0)) { - sp.putLong(R.string.key_ns_food_last_synced_id, lastSynced) + if (lastSynced > preferences.get(NsclientLongKey.FoodLastSyncedId)) { + preferences.put(NsclientLongKey.FoodLastSyncedId, lastSynced) } } @@ -363,9 +363,9 @@ class DataSyncSelectorV1 @Inject constructor( while (cont) { if (isPaused) return val lastDbId = persistenceLayer.getLastFoodId() ?: 0L - var startId = sp.getLong(R.string.key_ns_food_last_synced_id, 0) + var startId = preferences.get(NsclientLongKey.FoodLastSyncedId) if (startId > lastDbId) { - sp.putLong(R.string.key_ns_food_last_synced_id, 0) + preferences.put(NsclientLongKey.FoodLastSyncedId, 0) startId = 0 } queueCounter.foodsRemaining = lastDbId - startId @@ -401,8 +401,8 @@ class DataSyncSelectorV1 @Inject constructor( } private fun confirmLastGlucoseValueIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_ns_glucose_value_last_synced_id, 0)) { - sp.putLong(R.string.key_ns_glucose_value_last_synced_id, lastSynced) + if (lastSynced > preferences.get(NsclientLongKey.GlucoseValueLastSyncedId)) { + preferences.put(NsclientLongKey.GlucoseValueLastSyncedId, lastSynced) } } @@ -411,9 +411,9 @@ class DataSyncSelectorV1 @Inject constructor( while (cont) { if (isPaused) return val lastDbId = persistenceLayer.getLastGlucoseValueId() ?: 0L - var startId = sp.getLong(R.string.key_ns_glucose_value_last_synced_id, 0) + var startId = preferences.get(NsclientLongKey.GlucoseValueLastSyncedId) if (startId > lastDbId) { - sp.putLong(R.string.key_ns_glucose_value_last_synced_id, 0) + preferences.put(NsclientLongKey.GlucoseValueLastSyncedId, 0) startId = 0 } queueCounter.gvsRemaining = lastDbId - startId @@ -451,8 +451,8 @@ class DataSyncSelectorV1 @Inject constructor( } private fun confirmLastTherapyEventIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_ns_therapy_event_last_synced_id, 0)) { - sp.putLong(R.string.key_ns_therapy_event_last_synced_id, lastSynced) + if (lastSynced > preferences.get(NsclientLongKey.TherapyEventLastSyncedId)) { + preferences.put(NsclientLongKey.TherapyEventLastSyncedId, lastSynced) } } @@ -461,9 +461,9 @@ class DataSyncSelectorV1 @Inject constructor( while (cont) { if (isPaused) return val lastDbId = persistenceLayer.getLastTherapyEventId() ?: 0L - var startId = sp.getLong(R.string.key_ns_therapy_event_last_synced_id, 0) + var startId = preferences.get(NsclientLongKey.TherapyEventLastSyncedId) if (startId > lastDbId) { - sp.putLong(R.string.key_ns_therapy_event_last_synced_id, 0) + preferences.put(NsclientLongKey.TherapyEventLastSyncedId, 0) startId = 0 } queueCounter.tesRemaining = lastDbId - startId @@ -499,8 +499,8 @@ class DataSyncSelectorV1 @Inject constructor( } private fun confirmLastDeviceStatusIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_ns_device_status_last_synced_id, 0)) { - sp.putLong(R.string.key_ns_device_status_last_synced_id, lastSynced) + if (lastSynced > preferences.get(NsclientLongKey.DeviceStatusLastSyncedId)) { + preferences.put(NsclientLongKey.DeviceStatusLastSyncedId, lastSynced) } } @@ -509,9 +509,9 @@ class DataSyncSelectorV1 @Inject constructor( while (cont) { if (isPaused) return val lastDbId = persistenceLayer.getLastDeviceStatusId() ?: 0L - var startId = sp.getLong(R.string.key_ns_device_status_last_synced_id, 0) + var startId = preferences.get(NsclientLongKey.DeviceStatusLastSyncedId) if (startId > lastDbId) { - sp.putLong(R.string.key_ns_device_status_last_synced_id, 0) + preferences.put(NsclientLongKey.DeviceStatusLastSyncedId, 0) startId = 0 } queueCounter.dssRemaining = lastDbId - startId @@ -530,8 +530,8 @@ class DataSyncSelectorV1 @Inject constructor( } private fun confirmLastTemporaryBasalIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_ns_temporary_basal_last_synced_id, 0)) { - sp.putLong(R.string.key_ns_temporary_basal_last_synced_id, lastSynced) + if (lastSynced > preferences.get(NsclientLongKey.TemporaryBasalLastSyncedId)) { + preferences.put(NsclientLongKey.TemporaryBasalLastSyncedId, lastSynced) } } @@ -540,9 +540,9 @@ class DataSyncSelectorV1 @Inject constructor( while (cont) { if (isPaused) return val lastDbId = persistenceLayer.getLastTemporaryBasalId() ?: 0L - var startId = sp.getLong(R.string.key_ns_temporary_basal_last_synced_id, 0) + var startId = preferences.get(NsclientLongKey.TemporaryBasalLastSyncedId) if (startId > lastDbId) { - sp.putLong(R.string.key_ns_temporary_basal_last_synced_id, 0) + preferences.put(NsclientLongKey.TemporaryBasalLastSyncedId, 0) startId = 0 } queueCounter.tbrsRemaining = lastDbId - startId @@ -581,8 +581,8 @@ class DataSyncSelectorV1 @Inject constructor( } private fun confirmLastExtendedBolusIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_ns_extended_bolus_last_synced_id, 0)) { - sp.putLong(R.string.key_ns_extended_bolus_last_synced_id, lastSynced) + if (lastSynced > preferences.get(NsclientLongKey.ExtendedBolusLastSyncedId)) { + preferences.put(NsclientLongKey.ExtendedBolusLastSyncedId, lastSynced) } } @@ -591,9 +591,9 @@ class DataSyncSelectorV1 @Inject constructor( while (cont) { if (isPaused) return val lastDbId = persistenceLayer.getLastExtendedBolusId() ?: 0L - var startId = sp.getLong(R.string.key_ns_extended_bolus_last_synced_id, 0) + var startId = preferences.get(NsclientLongKey.ExtendedBolusLastSyncedId) if (startId > lastDbId) { - sp.putLong(R.string.key_ns_extended_bolus_last_synced_id, 0) + preferences.put(NsclientLongKey.ExtendedBolusLastSyncedId, 0) startId = 0 } queueCounter.ebsRemaining = lastDbId - startId @@ -632,8 +632,8 @@ class DataSyncSelectorV1 @Inject constructor( } private fun confirmLastProfileSwitchIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_ns_profile_switch_last_synced_id, 0)) { - sp.putLong(R.string.key_ns_profile_switch_last_synced_id, lastSynced) + if (lastSynced > preferences.get(NsclientLongKey.ProfileSwitchLastSyncedId)) { + preferences.put(NsclientLongKey.ProfileSwitchLastSyncedId, lastSynced) } } @@ -642,9 +642,9 @@ class DataSyncSelectorV1 @Inject constructor( while (cont) { if (isPaused) return val lastDbId = persistenceLayer.getLastProfileSwitchId() ?: 0L - var startId = sp.getLong(R.string.key_ns_profile_switch_last_synced_id, 0) + var startId = preferences.get(NsclientLongKey.ProfileSwitchLastSyncedId) if (startId > lastDbId) { - sp.putLong(R.string.key_ns_profile_switch_last_synced_id, 0) + preferences.put(NsclientLongKey.ProfileSwitchLastSyncedId, 0) startId = 0 } queueCounter.pssRemaining = lastDbId - startId @@ -680,8 +680,8 @@ class DataSyncSelectorV1 @Inject constructor( } private fun confirmLastEffectiveProfileSwitchIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_ns_effective_profile_switch_last_synced_id, 0)) { - sp.putLong(R.string.key_ns_effective_profile_switch_last_synced_id, lastSynced) + if (lastSynced > preferences.get(NsclientLongKey.EffectiveProfileSwitchLastSyncedId)) { + preferences.put(NsclientLongKey.EffectiveProfileSwitchLastSyncedId, lastSynced) } } @@ -690,9 +690,9 @@ class DataSyncSelectorV1 @Inject constructor( while (cont) { if (isPaused) return val lastDbId = persistenceLayer.getLastEffectiveProfileSwitchId() ?: 0L - var startId = sp.getLong(R.string.key_ns_effective_profile_switch_last_synced_id, 0) + var startId = preferences.get(NsclientLongKey.EffectiveProfileSwitchLastSyncedId) if (startId > lastDbId) { - sp.putLong(R.string.key_ns_effective_profile_switch_last_synced_id, 0) + preferences.put(NsclientLongKey.EffectiveProfileSwitchLastSyncedId, 0) startId = 0 } queueCounter.epssRemaining = lastDbId - startId @@ -728,8 +728,8 @@ class DataSyncSelectorV1 @Inject constructor( } private fun confirmLastOfflineEventIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_ns_offline_event_last_synced_id, 0)) { - sp.putLong(R.string.key_ns_offline_event_last_synced_id, lastSynced) + if (lastSynced > preferences.get(NsclientLongKey.OfflineEventLastSyncedId)) { + preferences.put(NsclientLongKey.OfflineEventLastSyncedId, lastSynced) } } @@ -738,9 +738,9 @@ class DataSyncSelectorV1 @Inject constructor( while (cont) { if (isPaused) return val lastDbId = persistenceLayer.getLastOfflineEventId() ?: 0L - var startId = sp.getLong(R.string.key_ns_offline_event_last_synced_id, 0) + var startId = preferences.get(NsclientLongKey.OfflineEventLastSyncedId) if (startId > lastDbId) { - sp.putLong(R.string.key_ns_offline_event_last_synced_id, 0) + preferences.put(NsclientLongKey.OfflineEventLastSyncedId, 0) startId = 0 } queueCounter.oesRemaining = lastDbId - startId @@ -776,17 +776,17 @@ class DataSyncSelectorV1 @Inject constructor( } private fun confirmLastProfileStore(lastSynced: Long) { - sp.putLong(R.string.key_ns_profile_store_last_synced_timestamp, lastSynced) + preferences.put(NsclientLongKey.ProfileStoreLastSyncedId, lastSynced) } override fun profileReceived(timestamp: Long) { - sp.putLong(R.string.key_ns_profile_store_last_synced_timestamp, timestamp) + preferences.put(NsclientLongKey.ProfileStoreLastSyncedId, timestamp) } private suspend fun processChangedProfileStore() { if (isPaused) return - val lastSync = sp.getLong(R.string.key_ns_profile_store_last_synced_timestamp, 0) - val lastChange = sp.getLong(app.aaps.core.utils.R.string.key_local_profile_last_change, 0) + val lastSync = preferences.get(NsclientLongKey.ProfileStoreLastSyncedId) + val lastChange = preferences.get(LongNonKey.LocalProfileLastChange) if (lastChange == 0L) return if (lastChange > lastSync) { if (activePlugin.activeProfileSource.profile?.allProfilesValid != true) return diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/NSClientPlugin.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/NSClientPlugin.kt index 8ace50f7b50..930ad7ed4e8 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/NSClientPlugin.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/NSClientPlugin.kt @@ -25,7 +25,6 @@ import app.aaps.core.interfaces.rx.events.EventAppExit import app.aaps.core.interfaces.rx.events.EventNSClientNewLog import app.aaps.core.interfaces.rx.events.EventPreferenceChange import app.aaps.core.interfaces.rx.events.EventSWSyncStatus -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.sync.DataSyncSelector import app.aaps.core.interfaces.sync.NsClient import app.aaps.core.interfaces.sync.Sync @@ -34,8 +33,8 @@ import app.aaps.core.interfaces.utils.DecimalFormatter import app.aaps.core.interfaces.utils.fabric.FabricPrivacy import app.aaps.core.keys.BooleanKey import app.aaps.core.keys.IntKey -import app.aaps.core.keys.Preferences import app.aaps.core.keys.StringKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.extensions.toJson import app.aaps.core.validators.DefaultEditTextValidator import app.aaps.core.validators.EditTextValidator @@ -50,6 +49,7 @@ import app.aaps.plugins.sync.nsShared.events.EventNSClientUpdateGuiStatus import app.aaps.plugins.sync.nsclient.data.AlarmAck import app.aaps.plugins.sync.nsclient.extensions.toJson import app.aaps.plugins.sync.nsclient.services.NSClientService +import app.aaps.plugins.sync.nsclientV3.keys.NsclientBooleanKey import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import javax.inject.Inject @@ -63,7 +63,6 @@ class NSClientPlugin @Inject constructor( rh: ResourceHelper, private val context: Context, private val fabricPrivacy: FabricPrivacy, - private val sp: SP, private val preferences: Preferences, private val receiverDelegate: ReceiverDelegate, private val dataSyncSelectorV1: DataSyncSelectorV1, @@ -160,8 +159,8 @@ class NSClientPlugin @Inject constructor( } override fun pause(newState: Boolean) { - sp.putBoolean(R.string.key_ns_paused, newState) - rxBus.send(EventPreferenceChange(rh.gs(R.string.key_ns_paused))) + preferences.put(NsclientBooleanKey.NsPaused, newState) + rxBus.send(EventPreferenceChange(NsclientBooleanKey.NsPaused.key)) } override val address: String get() = nsClientService?.nsURL ?: "" diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/ReceiverDelegate.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/ReceiverDelegate.kt index 8499a6a31cc..e17dc70f5d1 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/ReceiverDelegate.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/ReceiverDelegate.kt @@ -9,8 +9,8 @@ import app.aaps.core.interfaces.rx.events.EventNetworkChange import app.aaps.core.interfaces.rx.events.EventPreferenceChange import app.aaps.core.interfaces.utils.fabric.FabricPrivacy import app.aaps.core.keys.BooleanKey -import app.aaps.core.keys.Preferences import app.aaps.core.keys.StringKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.plugins.sync.R import app.aaps.plugins.sync.nsShared.events.EventConnectivityOptionChanged import io.reactivex.rxjava3.disposables.CompositeDisposable diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/data/NSDeviceStatusHandler.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/data/NSDeviceStatusHandler.kt index 2d15b165b8f..9fd25e378a9 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/data/NSDeviceStatusHandler.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/data/NSDeviceStatusHandler.kt @@ -6,8 +6,9 @@ import app.aaps.core.interfaces.db.PersistenceLayer import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.nsclient.ProcessedDeviceStatusData -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.DateUtil +import app.aaps.core.keys.BooleanNonKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.nssdk.interfaces.RunningConfiguration import app.aaps.core.nssdk.localmodel.devicestatus.NSDeviceStatus import app.aaps.core.utils.HtmlHelper @@ -72,7 +73,7 @@ import javax.inject.Singleton @Suppress("SpellCheckingInspection") @Singleton class NSDeviceStatusHandler @Inject constructor( - private val sp: SP, + private val preferences: Preferences, private val config: Config, private val dateUtil: DateUtil, private val runningConfiguration: RunningConfiguration, @@ -100,7 +101,7 @@ class NSDeviceStatusHandler @Inject constructor( } if (config.APS) { - nsDeviceStatus.pump?.let { sp.putBoolean(app.aaps.core.utils.R.string.key_objectives_pump_status_is_available_in_ns, true) } // Objective 0 + nsDeviceStatus.pump?.let { preferences.put(BooleanNonKey.ObjectivesPumpStatusIsAvailableInNS, true) } // Objective 0 } } } diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/data/NSSettingsStatusImpl.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/data/NSSettingsStatusImpl.kt index 61170169f9d..b98d3cd3b85 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/data/NSSettingsStatusImpl.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/data/NSSettingsStatusImpl.kt @@ -16,7 +16,7 @@ import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventDismissNotification import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.keys.IntKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.ui.dialogs.OKDialog import app.aaps.core.utils.JsonHelper import app.aaps.plugins.sync.R diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/data/ProcessedDeviceStatusDataImpl.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/data/ProcessedDeviceStatusDataImpl.kt index f612a1dc748..68a11a13b16 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/data/ProcessedDeviceStatusDataImpl.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/data/ProcessedDeviceStatusDataImpl.kt @@ -10,7 +10,7 @@ import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.Round import app.aaps.core.keys.IntKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.utils.HtmlHelper import app.aaps.plugins.sync.R import javax.inject.Inject diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/services/NSClientService.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/services/NSClientService.kt index 7f6967a9456..6309274b684 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/services/NSClientService.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/services/NSClientService.kt @@ -20,13 +20,13 @@ import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.AapsSchedulers import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.* -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.fabric.FabricPrivacy import app.aaps.core.keys.BooleanKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.LongComposedKey import app.aaps.core.keys.StringKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.nssdk.localmodel.devicestatus.NSDeviceStatus import app.aaps.core.utils.JsonHelper.safeGetString import app.aaps.core.utils.JsonHelper.safeGetStringAllowNull @@ -46,6 +46,7 @@ import app.aaps.plugins.sync.nsclient.data.AlarmAck import app.aaps.plugins.sync.nsclient.data.NSDeviceStatusHandler import app.aaps.plugins.sync.nsclient.workers.NSClientAddUpdateWorker import app.aaps.plugins.sync.nsclient.workers.NSClientMbgWorker +import app.aaps.plugins.sync.nsclientV3.keys.NsclientBooleanKey import com.google.common.base.Charsets import com.google.common.hash.Hashing import com.google.gson.GsonBuilder @@ -79,7 +80,6 @@ class NSClientService : DaggerService() { @Inject lateinit var nsDeviceStatusHandler: NSDeviceStatusHandler @Inject lateinit var rxBus: RxBus @Inject lateinit var rh: ResourceHelper - @Inject lateinit var sp: SP @Inject lateinit var preferences: Preferences @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var nsClientPlugin: NSClientPlugin @@ -142,7 +142,7 @@ class NSClientService : DaggerService() { .subscribe({ event: EventPreferenceChange -> if (event.isChanged(StringKey.NsClientUrl.key) || event.isChanged(StringKey.NsClientApiSecret.key) || - event.isChanged(rh.gs(R.string.key_ns_paused)) + event.isChanged(NsclientBooleanKey.NsPaused.key) ) { latestDateInReceivedData = 0 destroy() @@ -255,7 +255,7 @@ class NSClientService : DaggerService() { if (!nsClientPlugin.isAllowed) { rxBus.send(EventNSClientNewLog("● NSCLIENT", nsClientPlugin.blockingReason)) rxBus.send(EventNSClientStatus(nsClientPlugin.blockingReason)) - } else if (sp.getBoolean(R.string.key_ns_paused, false)) { + } else if (preferences.get(NsclientBooleanKey.NsPaused)) { rxBus.send(EventNSClientNewLog("● NSCLIENT", "paused")) rxBus.send(EventNSClientStatus("Paused")) } else if (!nsEnabled) { @@ -649,7 +649,7 @@ class NSClientService : DaggerService() { private fun handleAlarm(alarm: JSONObject) { if (preferences.get(BooleanKey.NsClientNotificationsFromAlarms)) { - val snoozedTo = sp.getLong(rh.gs(app.aaps.core.utils.R.string.key_snoozed_to) + alarm.optString("level"), 0L) + val snoozedTo = preferences.get(LongComposedKey.NotificationSnoozedTo, alarm.optString("level")) if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo) { val nsAlarm = NSAlarmObject(alarm) uiInteraction.addNotificationWithAction(nsAlarm) @@ -661,7 +661,7 @@ class NSClientService : DaggerService() { private fun handleUrgentAlarm(alarm: JSONObject) { if (preferences.get(BooleanKey.NsClientNotificationsFromAlarms)) { - val snoozedTo = sp.getLong(rh.gs(app.aaps.core.utils.R.string.key_snoozed_to) + alarm.optString("level"), 0L) + val snoozedTo = preferences.get(LongComposedKey.NotificationSnoozedTo, alarm.optString("level")) if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo) { val nsAlarm = NSAlarmObject(alarm) uiInteraction.addNotificationWithAction(nsAlarm) diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/workers/NSClientAddAckWorker.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/workers/NSClientAddAckWorker.kt index 2e804e2c440..13e82985a4d 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/workers/NSClientAddAckWorker.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/workers/NSClientAddAckWorker.kt @@ -8,7 +8,6 @@ import app.aaps.core.interfaces.nsclient.StoreDataForDb import app.aaps.core.interfaces.rx.AapsSchedulers import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventNSClientNewLog -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.sync.DataSyncSelector import app.aaps.core.interfaces.sync.DataSyncSelector.PairBolus import app.aaps.core.interfaces.sync.DataSyncSelector.PairBolusCalculatorResult @@ -24,7 +23,7 @@ import app.aaps.core.interfaces.sync.DataSyncSelector.PairTemporaryBasal import app.aaps.core.interfaces.sync.DataSyncSelector.PairTemporaryTarget import app.aaps.core.interfaces.sync.DataSyncSelector.PairTherapyEvent import app.aaps.core.keys.BooleanKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.workflow.LoggingWorker import app.aaps.core.utils.notifyAll import app.aaps.core.utils.receivers.DataWorkerStorage @@ -40,7 +39,6 @@ class NSClientAddAckWorker( @Inject lateinit var dataWorkerStorage: DataWorkerStorage @Inject lateinit var rxBus: RxBus @Inject lateinit var aapsSchedulers: AapsSchedulers - @Inject lateinit var sp: SP @Inject lateinit var preferences: Preferences @Inject lateinit var storeDataForDb: StoreDataForDb diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/workers/NSClientAddUpdateWorker.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/workers/NSClientAddUpdateWorker.kt index d843135feed..ea830e4503c 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/workers/NSClientAddUpdateWorker.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/workers/NSClientAddUpdateWorker.kt @@ -22,7 +22,7 @@ import app.aaps.core.interfaces.pump.VirtualPump import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.keys.BooleanKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.workflow.LoggingWorker import app.aaps.core.utils.JsonHelper import app.aaps.core.utils.receivers.DataWorkerStorage diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/workers/NSClientMbgWorker.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/workers/NSClientMbgWorker.kt index e2a2d1752d1..47f952592ce 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/workers/NSClientMbgWorker.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclient/workers/NSClientMbgWorker.kt @@ -6,7 +6,7 @@ import androidx.work.workDataOf import app.aaps.core.interfaces.configuration.Config import app.aaps.core.interfaces.nsclient.StoreDataForDb import app.aaps.core.keys.BooleanKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.workflow.LoggingWorker import app.aaps.core.utils.receivers.DataWorkerStorage import app.aaps.plugins.sync.nsclient.data.NSMbg diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclientV3/DataSyncSelectorV3.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclientV3/DataSyncSelectorV3.kt index b4877526e35..8c4254dce3d 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclientV3/DataSyncSelectorV3.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclientV3/DataSyncSelectorV3.kt @@ -8,23 +8,23 @@ import app.aaps.core.interfaces.nsclient.StoreDataForDb import app.aaps.core.interfaces.plugin.ActivePlugin import app.aaps.core.interfaces.profile.ProfileFunction import app.aaps.core.interfaces.rx.bus.RxBus -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.source.NSClientSource import app.aaps.core.interfaces.sync.DataSyncSelector import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.keys.BooleanKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.LongNonKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.utils.JsonHelper -import app.aaps.plugins.sync.R import app.aaps.plugins.sync.nsShared.events.EventNSClientUpdateGuiQueue import app.aaps.plugins.sync.nsShared.events.EventNSClientUpdateGuiStatus import app.aaps.plugins.sync.nsShared.extensions.onlyNsIdAdded +import app.aaps.plugins.sync.nsclientV3.keys.NsclientBooleanKey +import app.aaps.plugins.sync.nsclientV3.keys.NsclientLongKey import javax.inject.Inject import javax.inject.Singleton @Singleton class DataSyncSelectorV3 @Inject constructor( - private val sp: SP, private val preferences: Preferences, private val aapsLogger: AAPSLogger, private val dateUtil: DateUtil, @@ -69,7 +69,7 @@ class DataSyncSelectorV3 @Inject constructor( } private val queueCounter = QueueCounter() - private val isPaused get() = sp.getBoolean(R.string.key_ns_paused, false) + private val isPaused get() = preferences.get(NsclientBooleanKey.NsPaused) override fun queueSize(): Long = queueCounter.size() @@ -78,19 +78,19 @@ class DataSyncSelectorV3 @Inject constructor( override suspend fun doUpload() { rxBus.send(EventNSClientUpdateGuiStatus()) if ((config.AAPSCLIENT || preferences.get(BooleanKey.NsClientUploadData)) && !isPaused) { - queueCounter.bolusesRemaining = (persistenceLayer.getLastBolusId() ?: 0L) - sp.getLong(R.string.key_ns_bolus_last_synced_id, 0) - queueCounter.carbsRemaining = (persistenceLayer.getLastCarbsId() ?: 0L) - sp.getLong(R.string.key_ns_carbs_last_synced_id, 0) - queueCounter.bcrRemaining = (persistenceLayer.getLastBolusCalculatorResultId() ?: 0L) - sp.getLong(R.string.key_ns_bolus_calculator_result_last_synced_id, 0) - queueCounter.ttsRemaining = (persistenceLayer.getLastTemporaryTargetId() ?: 0L) - sp.getLong(R.string.key_ns_temporary_target_last_synced_id, 0) - queueCounter.foodsRemaining = (persistenceLayer.getLastFoodId() ?: 0L) - sp.getLong(R.string.key_ns_food_last_synced_id, 0) - queueCounter.gvsRemaining = (persistenceLayer.getLastGlucoseValueId() ?: 0L) - sp.getLong(R.string.key_ns_glucose_value_last_synced_id, 0) - queueCounter.tesRemaining = (persistenceLayer.getLastTherapyEventId() ?: 0L) - sp.getLong(R.string.key_ns_therapy_event_last_synced_id, 0) - queueCounter.dssRemaining = (persistenceLayer.getLastDeviceStatusId() ?: 0L) - sp.getLong(R.string.key_ns_device_status_last_synced_id, 0) - queueCounter.tbrsRemaining = (persistenceLayer.getLastTemporaryBasalId() ?: 0L) - sp.getLong(R.string.key_ns_temporary_basal_last_synced_id, 0) - queueCounter.ebsRemaining = (persistenceLayer.getLastExtendedBolusId() ?: 0L) - sp.getLong(R.string.key_ns_extended_bolus_last_synced_id, 0) - queueCounter.pssRemaining = (persistenceLayer.getLastProfileSwitchId() ?: 0L) - sp.getLong(R.string.key_ns_profile_switch_last_synced_id, 0) - queueCounter.epssRemaining = (persistenceLayer.getLastEffectiveProfileSwitchId() ?: 0L) - sp.getLong(R.string.key_ns_effective_profile_switch_last_synced_id, 0) - queueCounter.oesRemaining = (persistenceLayer.getLastOfflineEventId() ?: 0L) - sp.getLong(R.string.key_ns_offline_event_last_synced_id, 0) + queueCounter.bolusesRemaining = (persistenceLayer.getLastBolusId() ?: 0L) - preferences.get(NsclientLongKey.BolusLastSyncedId) + queueCounter.carbsRemaining = (persistenceLayer.getLastCarbsId() ?: 0L) - preferences.get(NsclientLongKey.CarbsLastSyncedId) + queueCounter.bcrRemaining = (persistenceLayer.getLastBolusCalculatorResultId() ?: 0L) - preferences.get(NsclientLongKey.BolusCalculatorLastSyncedId) + queueCounter.ttsRemaining = (persistenceLayer.getLastTemporaryTargetId() ?: 0L) - preferences.get(NsclientLongKey.TemporaryTargetLastSyncedId) + queueCounter.foodsRemaining = (persistenceLayer.getLastFoodId() ?: 0L) - preferences.get(NsclientLongKey.FoodLastSyncedId) + queueCounter.gvsRemaining = (persistenceLayer.getLastGlucoseValueId() ?: 0L) - preferences.get(NsclientLongKey.GlucoseValueLastSyncedId) + queueCounter.tesRemaining = (persistenceLayer.getLastTherapyEventId() ?: 0L) - preferences.get(NsclientLongKey.TherapyEventLastSyncedId) + queueCounter.dssRemaining = (persistenceLayer.getLastDeviceStatusId() ?: 0L) - preferences.get(NsclientLongKey.DeviceStatusLastSyncedId) + queueCounter.tbrsRemaining = (persistenceLayer.getLastTemporaryBasalId() ?: 0L) - preferences.get(NsclientLongKey.TemporaryBasalLastSyncedId) + queueCounter.ebsRemaining = (persistenceLayer.getLastExtendedBolusId() ?: 0L) - preferences.get(NsclientLongKey.ExtendedBolusLastSyncedId) + queueCounter.pssRemaining = (persistenceLayer.getLastProfileSwitchId() ?: 0L) - preferences.get(NsclientLongKey.ProfileSwitchLastSyncedId) + queueCounter.epssRemaining = (persistenceLayer.getLastEffectiveProfileSwitchId() ?: 0L) - preferences.get(NsclientLongKey.EffectiveProfileSwitchLastSyncedId) + queueCounter.oesRemaining = (persistenceLayer.getLastOfflineEventId() ?: 0L) - preferences.get(NsclientLongKey.OfflineEventLastSyncedId) rxBus.send(EventNSClientUpdateGuiQueue()) processChangedGlucoseValues() processChangedBoluses() @@ -113,28 +113,28 @@ class DataSyncSelectorV3 @Inject constructor( } override fun resetToNextFullSync() { - sp.remove(R.string.key_ns_glucose_value_last_synced_id) - sp.remove(R.string.key_ns_temporary_basal_last_synced_id) - sp.remove(R.string.key_ns_temporary_target_last_synced_id) - sp.remove(R.string.key_ns_extended_bolus_last_synced_id) - sp.remove(R.string.key_ns_food_last_synced_id) - sp.remove(R.string.key_ns_bolus_last_synced_id) - sp.remove(R.string.key_ns_carbs_last_synced_id) - sp.remove(R.string.key_ns_bolus_calculator_result_last_synced_id) - sp.remove(R.string.key_ns_therapy_event_last_synced_id) - sp.remove(R.string.key_ns_profile_switch_last_synced_id) - sp.remove(R.string.key_ns_effective_profile_switch_last_synced_id) - sp.remove(R.string.key_ns_offline_event_last_synced_id) - sp.remove(R.string.key_ns_profile_store_last_synced_timestamp) + preferences.remove(NsclientLongKey.GlucoseValueLastSyncedId) + preferences.remove(NsclientLongKey.TemporaryBasalLastSyncedId) + preferences.remove(NsclientLongKey.TemporaryTargetLastSyncedId) + preferences.remove(NsclientLongKey.ExtendedBolusLastSyncedId) + preferences.remove(NsclientLongKey.FoodLastSyncedId) + preferences.remove(NsclientLongKey.BolusLastSyncedId) + preferences.remove(NsclientLongKey.CarbsLastSyncedId) + preferences.remove(NsclientLongKey.BolusCalculatorLastSyncedId) + preferences.remove(NsclientLongKey.TherapyEventLastSyncedId) + preferences.remove(NsclientLongKey.ProfileSwitchLastSyncedId) + preferences.remove(NsclientLongKey.EffectiveProfileSwitchLastSyncedId) + preferences.remove(NsclientLongKey.OfflineEventLastSyncedId) + preferences.remove(NsclientLongKey.ProfileStoreLastSyncedId) val lastDeviceStatusDbId = persistenceLayer.getLastDeviceStatusId() - if (lastDeviceStatusDbId != null) sp.putLong(R.string.key_ns_device_status_last_synced_id, lastDeviceStatusDbId) - else sp.remove(R.string.key_ns_device_status_last_synced_id) + if (lastDeviceStatusDbId != null) preferences.put(NsclientLongKey.DeviceStatusLastSyncedId, lastDeviceStatusDbId) + else preferences.remove(NsclientLongKey.DeviceStatusLastSyncedId) } private fun confirmLastBolusIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_ns_bolus_last_synced_id, 0)) { - sp.putLong(R.string.key_ns_bolus_last_synced_id, lastSynced) + if (lastSynced > preferences.get(NsclientLongKey.BolusLastSyncedId)) { + preferences.put(NsclientLongKey.BolusLastSyncedId, lastSynced) } } @@ -143,10 +143,10 @@ class DataSyncSelectorV3 @Inject constructor( while (cont) { if (isPaused) return val lastDbId = persistenceLayer.getLastBolusId() ?: 0L - var startId = sp.getLong(R.string.key_ns_bolus_last_synced_id, 0) + var startId = preferences.get(NsclientLongKey.BolusLastSyncedId) if (startId > lastDbId) { aapsLogger.info(LTag.NSCLIENT, "Resetting startId: $startId lastDbId: $lastDbId") - sp.putLong(R.string.key_ns_bolus_last_synced_id, 0) + preferences.put(NsclientLongKey.BolusLastSyncedId, 0) startId = 0 } queueCounter.bolusesRemaining = lastDbId - startId @@ -174,8 +174,8 @@ class DataSyncSelectorV3 @Inject constructor( } private fun confirmLastCarbsIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_ns_carbs_last_synced_id, 0)) { - sp.putLong(R.string.key_ns_carbs_last_synced_id, lastSynced) + if (lastSynced > preferences.get(NsclientLongKey.CarbsLastSyncedId)) { + preferences.put(NsclientLongKey.CarbsLastSyncedId, lastSynced) } } @@ -184,10 +184,10 @@ class DataSyncSelectorV3 @Inject constructor( while (cont) { if (isPaused) return val lastDbId = persistenceLayer.getLastCarbsId() ?: 0L - var startId = sp.getLong(R.string.key_ns_carbs_last_synced_id, 0) + var startId = preferences.get(NsclientLongKey.CarbsLastSyncedId) if (startId > lastDbId) { aapsLogger.info(LTag.NSCLIENT, "Resetting startId: $startId lastDbId: $lastDbId") - sp.putLong(R.string.key_ns_carbs_last_synced_id, 0) + preferences.put(NsclientLongKey.CarbsLastSyncedId, 0) startId = 0 } queueCounter.carbsRemaining = lastDbId - startId @@ -215,8 +215,8 @@ class DataSyncSelectorV3 @Inject constructor( } private fun confirmLastBolusCalculatorResultsIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_ns_bolus_calculator_result_last_synced_id, 0)) { - sp.putLong(R.string.key_ns_bolus_calculator_result_last_synced_id, lastSynced) + if (lastSynced > preferences.get(NsclientLongKey.BolusCalculatorLastSyncedId)) { + preferences.put(NsclientLongKey.BolusCalculatorLastSyncedId, lastSynced) } } @@ -225,10 +225,10 @@ class DataSyncSelectorV3 @Inject constructor( while (cont) { if (isPaused) return val lastDbId = persistenceLayer.getLastBolusCalculatorResultId() ?: 0L - var startId = sp.getLong(R.string.key_ns_bolus_calculator_result_last_synced_id, 0) + var startId = preferences.get(NsclientLongKey.BolusCalculatorLastSyncedId) if (startId > lastDbId) { aapsLogger.info(LTag.NSCLIENT, "Resetting startId: $startId lastDbId: $lastDbId") - sp.putLong(R.string.key_ns_bolus_calculator_result_last_synced_id, 0) + preferences.put(NsclientLongKey.BolusCalculatorLastSyncedId, 0) startId = 0 } queueCounter.bcrRemaining = lastDbId - startId @@ -264,8 +264,8 @@ class DataSyncSelectorV3 @Inject constructor( } private fun confirmLastTempTargetsIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_ns_temporary_target_last_synced_id, 0)) { - sp.putLong(R.string.key_ns_temporary_target_last_synced_id, lastSynced) + if (lastSynced > preferences.get(NsclientLongKey.TemporaryTargetLastSyncedId)) { + preferences.put(NsclientLongKey.TemporaryTargetLastSyncedId, lastSynced) } } @@ -274,10 +274,10 @@ class DataSyncSelectorV3 @Inject constructor( while (cont) { if (isPaused) return val lastDbId = persistenceLayer.getLastTemporaryTargetId() ?: 0L - var startId = sp.getLong(R.string.key_ns_temporary_target_last_synced_id, 0) + var startId = preferences.get(NsclientLongKey.TemporaryTargetLastSyncedId) if (startId > lastDbId) { aapsLogger.info(LTag.NSCLIENT, "Resetting startId: $startId lastDbId: $lastDbId") - sp.putLong(R.string.key_ns_temporary_target_last_synced_id, 0) + preferences.put(NsclientLongKey.TemporaryTargetLastSyncedId, 0) startId = 0 } queueCounter.ttsRemaining = lastDbId - startId @@ -305,8 +305,8 @@ class DataSyncSelectorV3 @Inject constructor( } private fun confirmLastFoodIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_ns_food_last_synced_id, 0)) { - sp.putLong(R.string.key_ns_food_last_synced_id, lastSynced) + if (lastSynced > preferences.get(NsclientLongKey.FoodLastSyncedId)) { + preferences.put(NsclientLongKey.FoodLastSyncedId, lastSynced) } } @@ -315,10 +315,10 @@ class DataSyncSelectorV3 @Inject constructor( while (cont) { if (isPaused) return val lastDbId = persistenceLayer.getLastFoodId() ?: 0L - var startId = sp.getLong(R.string.key_ns_food_last_synced_id, 0) + var startId = preferences.get(NsclientLongKey.FoodLastSyncedId) if (startId > lastDbId) { aapsLogger.info(LTag.NSCLIENT, "Resetting startId: $startId lastDbId: $lastDbId") - sp.putLong(R.string.key_ns_food_last_synced_id, 0) + preferences.put(NsclientLongKey.FoodLastSyncedId, 0) startId = 0 } queueCounter.foodsRemaining = lastDbId - startId @@ -346,8 +346,8 @@ class DataSyncSelectorV3 @Inject constructor( } private fun confirmLastGlucoseValueIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_ns_glucose_value_last_synced_id, 0)) { - sp.putLong(R.string.key_ns_glucose_value_last_synced_id, lastSynced) + if (lastSynced > preferences.get(NsclientLongKey.GlucoseValueLastSyncedId)) { + preferences.put(NsclientLongKey.GlucoseValueLastSyncedId, lastSynced) } } @@ -356,10 +356,10 @@ class DataSyncSelectorV3 @Inject constructor( while (cont) { if (isPaused) return val lastDbId = persistenceLayer.getLastGlucoseValueId() ?: 0L - var startId = sp.getLong(R.string.key_ns_glucose_value_last_synced_id, 0) + var startId = preferences.get(NsclientLongKey.GlucoseValueLastSyncedId) if (startId > lastDbId) { aapsLogger.info(LTag.NSCLIENT, "Resetting startId: $startId lastDbId: $lastDbId") - sp.putLong(R.string.key_ns_glucose_value_last_synced_id, 0) + preferences.put(NsclientLongKey.GlucoseValueLastSyncedId, 0) startId = 0 } queueCounter.gvsRemaining = lastDbId - startId @@ -389,8 +389,8 @@ class DataSyncSelectorV3 @Inject constructor( } private fun confirmLastTherapyEventIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_ns_therapy_event_last_synced_id, 0)) { - sp.putLong(R.string.key_ns_therapy_event_last_synced_id, lastSynced) + if (lastSynced > preferences.get(NsclientLongKey.TherapyEventLastSyncedId)) { + preferences.put(NsclientLongKey.TherapyEventLastSyncedId, lastSynced) } } @@ -399,10 +399,10 @@ class DataSyncSelectorV3 @Inject constructor( while (cont) { if (isPaused) return val lastDbId = persistenceLayer.getLastTherapyEventId() ?: 0L - var startId = sp.getLong(R.string.key_ns_therapy_event_last_synced_id, 0) + var startId = preferences.get(NsclientLongKey.TherapyEventLastSyncedId) if (startId > lastDbId) { aapsLogger.info(LTag.NSCLIENT, "Resetting startId: $startId lastDbId: $lastDbId") - sp.putLong(R.string.key_ns_therapy_event_last_synced_id, 0) + preferences.put(NsclientLongKey.TherapyEventLastSyncedId, 0) startId = 0 } queueCounter.tesRemaining = lastDbId - startId @@ -430,8 +430,8 @@ class DataSyncSelectorV3 @Inject constructor( } private fun confirmLastDeviceStatusIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_ns_device_status_last_synced_id, 0)) { - sp.putLong(R.string.key_ns_device_status_last_synced_id, lastSynced) + if (lastSynced > preferences.get(NsclientLongKey.DeviceStatusLastSyncedId)) { + preferences.put(NsclientLongKey.DeviceStatusLastSyncedId, lastSynced) } } @@ -440,10 +440,10 @@ class DataSyncSelectorV3 @Inject constructor( while (cont) { if (isPaused) return val lastDbId = persistenceLayer.getLastDeviceStatusId() ?: 0L - var startId = sp.getLong(R.string.key_ns_device_status_last_synced_id, 0) + var startId = preferences.get(NsclientLongKey.DeviceStatusLastSyncedId) if (startId > lastDbId) { aapsLogger.info(LTag.NSCLIENT, "Resetting startId: $startId lastDbId: $lastDbId") - sp.putLong(R.string.key_ns_device_status_last_synced_id, 0) + preferences.put(NsclientLongKey.DeviceStatusLastSyncedId, 0) startId = 0 } queueCounter.dssRemaining = lastDbId - startId @@ -459,8 +459,8 @@ class DataSyncSelectorV3 @Inject constructor( } private fun confirmLastTemporaryBasalIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_ns_temporary_basal_last_synced_id, 0)) { - sp.putLong(R.string.key_ns_temporary_basal_last_synced_id, lastSynced) + if (lastSynced > preferences.get(NsclientLongKey.TemporaryBasalLastSyncedId)) { + preferences.put(NsclientLongKey.TemporaryBasalLastSyncedId, lastSynced) } } @@ -469,10 +469,10 @@ class DataSyncSelectorV3 @Inject constructor( while (cont) { if (isPaused) return val lastDbId = persistenceLayer.getLastTemporaryBasalId() ?: 0L - var startId = sp.getLong(R.string.key_ns_temporary_basal_last_synced_id, 0) + var startId = preferences.get(NsclientLongKey.TemporaryBasalLastSyncedId) if (startId > lastDbId) { aapsLogger.info(LTag.NSCLIENT, "Resetting startId: $startId lastDbId: $lastDbId") - sp.putLong(R.string.key_ns_temporary_basal_last_synced_id, 0) + preferences.put(NsclientLongKey.TemporaryBasalLastSyncedId, 0) startId = 0 } queueCounter.tbrsRemaining = lastDbId - startId @@ -501,8 +501,8 @@ class DataSyncSelectorV3 @Inject constructor( } private fun confirmLastExtendedBolusIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_ns_extended_bolus_last_synced_id, 0)) { - sp.putLong(R.string.key_ns_extended_bolus_last_synced_id, lastSynced) + if (lastSynced > preferences.get(NsclientLongKey.ExtendedBolusLastSyncedId)) { + preferences.put(NsclientLongKey.ExtendedBolusLastSyncedId, lastSynced) } } @@ -511,10 +511,10 @@ class DataSyncSelectorV3 @Inject constructor( while (cont) { if (isPaused) return val lastDbId = persistenceLayer.getLastExtendedBolusId() ?: 0L - var startId = sp.getLong(R.string.key_ns_extended_bolus_last_synced_id, 0) + var startId = preferences.get(NsclientLongKey.ExtendedBolusLastSyncedId) if (startId > lastDbId) { aapsLogger.info(LTag.NSCLIENT, "Resetting startId: $startId lastDbId: $lastDbId") - sp.putLong(R.string.key_ns_extended_bolus_last_synced_id, 0) + preferences.put(NsclientLongKey.ExtendedBolusLastSyncedId, 0) startId = 0 } queueCounter.ebsRemaining = lastDbId - startId @@ -545,8 +545,8 @@ class DataSyncSelectorV3 @Inject constructor( } private fun confirmLastProfileSwitchIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_ns_profile_switch_last_synced_id, 0)) { - sp.putLong(R.string.key_ns_profile_switch_last_synced_id, lastSynced) + if (lastSynced > preferences.get(NsclientLongKey.ProfileSwitchLastSyncedId)) { + preferences.put(NsclientLongKey.ProfileSwitchLastSyncedId, lastSynced) } } @@ -555,10 +555,10 @@ class DataSyncSelectorV3 @Inject constructor( while (cont) { if (isPaused) return val lastDbId = persistenceLayer.getLastProfileSwitchId() ?: 0L - var startId = sp.getLong(R.string.key_ns_profile_switch_last_synced_id, 0) + var startId = preferences.get(NsclientLongKey.ProfileSwitchLastSyncedId) if (startId > lastDbId) { aapsLogger.info(LTag.NSCLIENT, "Resetting startId: $startId lastDbId: $lastDbId") - sp.putLong(R.string.key_ns_profile_switch_last_synced_id, 0) + preferences.put(NsclientLongKey.ProfileSwitchLastSyncedId, 0) startId = 0 } queueCounter.pssRemaining = lastDbId - startId @@ -586,8 +586,8 @@ class DataSyncSelectorV3 @Inject constructor( } private fun confirmLastEffectiveProfileSwitchIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_ns_effective_profile_switch_last_synced_id, 0)) { - sp.putLong(R.string.key_ns_effective_profile_switch_last_synced_id, lastSynced) + if (lastSynced > preferences.get(NsclientLongKey.EffectiveProfileSwitchLastSyncedId)) { + preferences.put(NsclientLongKey.EffectiveProfileSwitchLastSyncedId, lastSynced) } } @@ -596,10 +596,10 @@ class DataSyncSelectorV3 @Inject constructor( while (cont) { if (isPaused) return val lastDbId = persistenceLayer.getLastEffectiveProfileSwitchId() ?: 0L - var startId = sp.getLong(R.string.key_ns_effective_profile_switch_last_synced_id, 0) + var startId = preferences.get(NsclientLongKey.EffectiveProfileSwitchLastSyncedId) if (startId > lastDbId) { aapsLogger.info(LTag.NSCLIENT, "Resetting startId: $startId lastDbId: $lastDbId") - sp.putLong(R.string.key_ns_effective_profile_switch_last_synced_id, 0) + preferences.put(NsclientLongKey.EffectiveProfileSwitchLastSyncedId, 0) startId = 0 } queueCounter.epssRemaining = lastDbId - startId @@ -627,8 +627,8 @@ class DataSyncSelectorV3 @Inject constructor( } private fun confirmLastOfflineEventIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_ns_offline_event_last_synced_id, 0)) { - sp.putLong(R.string.key_ns_offline_event_last_synced_id, lastSynced) + if (lastSynced > preferences.get(NsclientLongKey.OfflineEventLastSyncedId)) { + preferences.put(NsclientLongKey.OfflineEventLastSyncedId, lastSynced) } } @@ -637,10 +637,10 @@ class DataSyncSelectorV3 @Inject constructor( while (cont) { if (isPaused) return val lastDbId = persistenceLayer.getLastOfflineEventId() ?: 0L - var startId = sp.getLong(R.string.key_ns_offline_event_last_synced_id, 0) + var startId = preferences.get(NsclientLongKey.OfflineEventLastSyncedId) if (startId > lastDbId) { aapsLogger.info(LTag.NSCLIENT, "Resetting startId: $startId lastDbId: $lastDbId") - sp.putLong(R.string.key_ns_offline_event_last_synced_id, 0) + preferences.put(NsclientLongKey.OfflineEventLastSyncedId, 0) startId = 0 } queueCounter.oesRemaining = lastDbId - startId @@ -668,17 +668,17 @@ class DataSyncSelectorV3 @Inject constructor( } private fun confirmLastProfileStore(lastSynced: Long) { - sp.putLong(R.string.key_ns_profile_store_last_synced_timestamp, lastSynced) + preferences.put(NsclientLongKey.ProfileStoreLastSyncedId, lastSynced) } override fun profileReceived(timestamp: Long) { - sp.putLong(R.string.key_ns_profile_store_last_synced_timestamp, timestamp) + preferences.put(NsclientLongKey.ProfileStoreLastSyncedId, timestamp) } private suspend fun processChangedProfileStore() { if (isPaused) return - val lastSync = sp.getLong(R.string.key_ns_profile_store_last_synced_timestamp, 0) - val lastChange = sp.getLong(app.aaps.core.utils.R.string.key_local_profile_last_change, 0) + val lastSync = preferences.get(NsclientLongKey.ProfileStoreLastSyncedId) + val lastChange = preferences.get(LongNonKey.LocalProfileLastChange) if (lastChange == 0L) return if (lastChange > lastSync) { if (activePlugin.activeProfileSource.profile?.allProfilesValid != true) return diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclientV3/NSClientV3Plugin.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclientV3/NSClientV3Plugin.kt index a7c8390a057..434bee25ff3 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclientV3/NSClientV3Plugin.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclientV3/NSClientV3Plugin.kt @@ -26,7 +26,7 @@ import app.aaps.core.interfaces.logging.L import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.nsclient.NSAlarm import app.aaps.core.interfaces.nsclient.StoreDataForDb -import app.aaps.core.interfaces.plugin.PluginBase +import app.aaps.core.interfaces.plugin.PluginBaseWithPreferences import app.aaps.core.interfaces.plugin.PluginDescription import app.aaps.core.interfaces.profile.Profile import app.aaps.core.interfaces.resources.ResourceHelper @@ -43,7 +43,6 @@ import app.aaps.core.interfaces.rx.events.EventProfileSwitchChanged import app.aaps.core.interfaces.rx.events.EventSWSyncStatus import app.aaps.core.interfaces.rx.events.EventTempTargetChange import app.aaps.core.interfaces.rx.events.EventTherapyEventChange -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.source.NSClientSource import app.aaps.core.interfaces.sync.DataSyncSelector import app.aaps.core.interfaces.sync.NsClient @@ -52,9 +51,11 @@ import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.DecimalFormatter import app.aaps.core.interfaces.utils.fabric.FabricPrivacy import app.aaps.core.keys.BooleanKey +import app.aaps.core.keys.BooleanNonKey import app.aaps.core.keys.IntKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.LongNonKey import app.aaps.core.keys.StringKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.nssdk.NSAndroidClientImpl import app.aaps.core.nssdk.interfaces.NSAndroidClient import app.aaps.core.nssdk.remotemodel.LastModified @@ -82,6 +83,9 @@ import app.aaps.plugins.sync.nsclientV3.extensions.toNSSvgV3 import app.aaps.plugins.sync.nsclientV3.extensions.toNSTemporaryBasal import app.aaps.plugins.sync.nsclientV3.extensions.toNSTemporaryTarget import app.aaps.plugins.sync.nsclientV3.extensions.toNSTherapyEvent +import app.aaps.plugins.sync.nsclientV3.keys.NsclientBooleanKey +import app.aaps.plugins.sync.nsclientV3.keys.NsclientLongKey +import app.aaps.plugins.sync.nsclientV3.keys.NsclientStringKey import app.aaps.plugins.sync.nsclientV3.services.NSClientV3Service import app.aaps.plugins.sync.nsclientV3.workers.DataSyncWorker import app.aaps.plugins.sync.nsclientV3.workers.LoadBgWorker @@ -103,13 +107,12 @@ import javax.inject.Singleton @Singleton class NSClientV3Plugin @Inject constructor( aapsLogger: AAPSLogger, + rh: ResourceHelper, + preferences: Preferences, private val aapsSchedulers: AapsSchedulers, private val rxBus: RxBus, - rh: ResourceHelper, private val context: Context, private val fabricPrivacy: FabricPrivacy, - private val sp: SP, - private val preferences: Preferences, private val receiverDelegate: ReceiverDelegate, private val config: Config, private val dateUtil: DateUtil, @@ -119,7 +122,7 @@ class NSClientV3Plugin @Inject constructor( private val storeDataForDb: StoreDataForDb, private val decimalFormatter: DecimalFormatter, private val l: L -) : NsClient, Sync, PluginBase( +) : NsClient, Sync, PluginBaseWithPreferences( PluginDescription() .mainType(PluginType.SYNC) .fragmentClass(NSClientFragment::class.java.name) @@ -128,7 +131,8 @@ class NSClientV3Plugin @Inject constructor( .shortName(R.string.ns_client_v3_short_name) .preferencesId(PluginDescription.PREFERENCE_SCREEN) .description(R.string.description_ns_client_v3), - aapsLogger, rh + ownPreferences = listOf(NsclientBooleanKey::class.java, NsclientStringKey::class.java, NsclientLongKey::class.java), + aapsLogger, rh, preferences ) { @Suppress("PrivatePropertyName") @@ -147,7 +151,7 @@ class NSClientV3Plugin @Inject constructor( override val status get() = when { - sp.getBoolean(R.string.key_ns_paused, false) -> rh.gs(app.aaps.core.ui.R.string.paused) + preferences.get(NsclientBooleanKey.NsPaused) -> rh.gs(app.aaps.core.ui.R.string.paused) isAllowed.not() -> blockingReason preferences.get(BooleanKey.NsClient3UseWs) && nsClientV3Service?.wsConnected == true -> "WS: " + rh.gs(app.aaps.core.interfaces.R.string.connected) preferences.get(BooleanKey.NsClient3UseWs) && nsClientV3Service?.wsConnected == false -> "WS: " + rh.gs(R.string.not_connected) @@ -173,6 +177,7 @@ class NSClientV3Plugin @Inject constructor( internal var initialLoadFinished = false private val fullSyncSemaphore = Object() + /** * Set to true if full sync is requested from fragment. * In this case we must enable accepting all data from NS even when disabled in preferences @@ -202,12 +207,7 @@ class NSClientV3Plugin @Inject constructor( super.onStart() handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper) - lastLoadedSrvModified = Json.decodeFromString( - sp.getString( - R.string.key_ns_client_v3_last_modified, - Json.encodeToString(LastModified.serializer(), LastModified(LastModified.Collections())) - ) - ) + lastLoadedSrvModified = Json.decodeFromString(preferences.get(NsclientStringKey.V3LastModified)) setClient() @@ -238,7 +238,7 @@ class NSClientV3Plugin @Inject constructor( if (ev.isChanged(StringKey.NsClientAccessToken.key) || ev.isChanged(StringKey.NsClientUrl.key) || ev.isChanged(BooleanKey.NsClient3UseWs.key) || - ev.isChanged(rh.gs(R.string.key_ns_paused)) || + ev.isChanged(NsclientBooleanKey.NsPaused.key) || ev.isChanged(BooleanKey.NsClientNotificationsFromAlarms.key) || ev.isChanged(BooleanKey.NsClientNotificationsFromAnnouncements.key) ) { @@ -246,7 +246,7 @@ class NSClientV3Plugin @Inject constructor( nsAndroidClient = null setClient() } - if (ev.isChanged(rh.gs(app.aaps.core.utils.R.string.key_local_profile_last_change))) + if (ev.isChanged(LongNonKey.LocalProfileLastChange.key)) executeUpload("PROFILE_CHANGE", forceNew = true) }, fabricPrivacy::logException) @@ -387,8 +387,8 @@ class NSClientV3Plugin @Inject constructor( } override fun pause(newState: Boolean) { - sp.putBoolean(R.string.key_ns_paused, newState) - rxBus.send(EventPreferenceChange(rh.gs(R.string.key_ns_paused))) + preferences.put(NsclientBooleanKey.NsPaused, newState) + rxBus.send(EventPreferenceChange(NsclientBooleanKey.NsPaused.key)) } override fun detectedNsVersion(): String? = nsAndroidClient?.lastStatus?.version @@ -489,7 +489,7 @@ class NSClientV3Plugin @Inject constructor( result.identifier?.let { dataPair.value.ids.nightscoutId = it storeDataForDb.addToNsIdDeviceStatuses(dataPair.value) - sp.putBoolean(app.aaps.core.utils.R.string.key_objectives_pump_status_is_available_in_ns, true) + preferences.put(BooleanNonKey.ObjectivesPumpStatusIsAvailableInNS, true) } slowDown() return true @@ -727,12 +727,12 @@ class NSClientV3Plugin @Inject constructor( } fun storeLastLoadedSrvModified() { - sp.putString(R.string.key_ns_client_v3_last_modified, Json.encodeToString(LastModified.serializer(), lastLoadedSrvModified)) + preferences.put(NsclientStringKey.V3LastModified, Json.encodeToString(LastModified.serializer(), lastLoadedSrvModified)) } internal fun executeLoop(origin: String, forceNew: Boolean) { if (preferences.get(BooleanKey.NsClient3UseWs) && initialLoadFinished) return - if (sp.getBoolean(R.string.key_ns_paused, false)) { + if (preferences.get(NsclientBooleanKey.NsPaused)) { rxBus.send(EventNSClientNewLog("● RUN", "paused $origin")) return } @@ -778,7 +778,7 @@ class NSClientV3Plugin @Inject constructor( } private fun executeUpload(origin: String, forceNew: Boolean) { - if (sp.getBoolean(R.string.key_ns_paused, false)) { + if (preferences.get(NsclientBooleanKey.NsPaused)) { rxBus.send(EventNSClientNewLog("● RUN", "paused")) return } diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclientV3/keys/NsclientBooleanKey.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclientV3/keys/NsclientBooleanKey.kt new file mode 100644 index 00000000000..41770714a39 --- /dev/null +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclientV3/keys/NsclientBooleanKey.kt @@ -0,0 +1,12 @@ +package app.aaps.plugins.sync.nsclientV3.keys + +import app.aaps.core.keys.interfaces.BooleanNonPreferenceKey + +enum class NsclientBooleanKey( + override val key: String, + override val defaultValue: Boolean, + override val exportable: Boolean = true +) : BooleanNonPreferenceKey { + + NsPaused("ns_client_paused", false) +} \ No newline at end of file diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclientV3/keys/NsclientLongKey.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclientV3/keys/NsclientLongKey.kt new file mode 100644 index 00000000000..a46965cdfa1 --- /dev/null +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclientV3/keys/NsclientLongKey.kt @@ -0,0 +1,25 @@ +package app.aaps.plugins.sync.nsclientV3.keys + +import app.aaps.core.keys.interfaces.LongNonPreferenceKey + +enum class NsclientLongKey( + override val key: String, + override val defaultValue: Long, + override val exportable: Boolean = true +) : LongNonPreferenceKey { + + BolusLastSyncedId("ns_bolus_last_synced_id", 0L), + CarbsLastSyncedId("ns_carbs_last_synced_id", 0L), + BolusCalculatorLastSyncedId("ns_bolus_calculator_result_last_synced_id", 0L), + TemporaryTargetLastSyncedId("ns_temporary_target_last_sync", 0L), + FoodLastSyncedId("ns_food_last_sync", 0L), + GlucoseValueLastSyncedId("ns_glucose_value_last_sync", 0L), + TherapyEventLastSyncedId("ns_therapy_event_last_sync", 0L), + DeviceStatusLastSyncedId("ns_device_status_last_synced_id", 0L), + TemporaryBasalLastSyncedId("ns_temporary_basal_last_synced_id", 0L), + ExtendedBolusLastSyncedId("ns_extended_bolus_last_synced_id", 0L), + ProfileSwitchLastSyncedId("ns_profile_switch_last_synced_id", 0L), + EffectiveProfileSwitchLastSyncedId("ns_effective_profile_switch_last_synced_id", 0L), + OfflineEventLastSyncedId("ns_offline_event_last_synced_id", 0L), + ProfileStoreLastSyncedId("ns_profile_store_last_synced_timestamp", 0L), +} \ No newline at end of file diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclientV3/keys/NsclientStringKey.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclientV3/keys/NsclientStringKey.kt new file mode 100644 index 00000000000..3c21c135d83 --- /dev/null +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclientV3/keys/NsclientStringKey.kt @@ -0,0 +1,14 @@ +package app.aaps.plugins.sync.nsclientV3.keys + +import app.aaps.core.keys.interfaces.StringNonPreferenceKey +import app.aaps.core.nssdk.remotemodel.LastModified +import kotlinx.serialization.json.Json + +enum class NsclientStringKey( + override val key: String, + override val defaultValue: String, + override val exportable: Boolean = true +) : StringNonPreferenceKey { + + V3LastModified("ns_client_v3_last_modified", Json.encodeToString(LastModified.serializer(), LastModified(LastModified.Collections()))) +} \ No newline at end of file diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclientV3/services/NSClientV3Service.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclientV3/services/NSClientV3Service.kt index cee8a68b6df..c09d1f9ec91 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclientV3/services/NSClientV3Service.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclientV3/services/NSClientV3Service.kt @@ -14,22 +14,22 @@ import app.aaps.core.interfaces.nsclient.StoreDataForDb import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.* -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.interfaces.utils.fabric.FabricPrivacy import app.aaps.core.keys.BooleanKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.LongComposedKey import app.aaps.core.keys.StringKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.nssdk.mapper.toNSDeviceStatus import app.aaps.core.nssdk.mapper.toNSFood import app.aaps.core.nssdk.mapper.toNSSgvV3 import app.aaps.core.nssdk.mapper.toNSTreatment -import app.aaps.plugins.sync.R import app.aaps.plugins.sync.nsShared.NSAlarmObject import app.aaps.plugins.sync.nsShared.NsIncomingDataProcessor import app.aaps.plugins.sync.nsShared.events.EventNSClientUpdateGuiStatus import app.aaps.plugins.sync.nsclient.data.NSDeviceStatusHandler import app.aaps.plugins.sync.nsclientV3.NSClientV3Plugin +import app.aaps.plugins.sync.nsclientV3.keys.NsclientBooleanKey import dagger.android.DaggerService import dagger.android.HasAndroidInjector import io.reactivex.rxjava3.disposables.CompositeDisposable @@ -49,7 +49,6 @@ class NSClientV3Service : DaggerService() { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var rxBus: RxBus @Inject lateinit var rh: ResourceHelper - @Inject lateinit var sp: SP @Inject lateinit var preferences: Preferences @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var nsClientV3Plugin: NSClientV3Plugin @@ -119,7 +118,7 @@ class NSClientV3Service : DaggerService() { val urlAlarm = preferences.get(StringKey.NsClientUrl).lowercase().replace(Regex("/$"), "") + "/alarm" if (!nsClientV3Plugin.isAllowed) { rxBus.send(EventNSClientNewLog("● WS", nsClientV3Plugin.blockingReason)) - } else if (sp.getBoolean(R.string.key_ns_paused, false)) { + } else if (preferences.get(NsclientBooleanKey.NsPaused)) { rxBus.send(EventNSClientNewLog("● WS", "paused")) } else { try { @@ -300,7 +299,7 @@ class NSClientV3Service : DaggerService() { rxBus.send(EventNSClientNewLog("◄ ALARM", data.optString("message"))) aapsLogger.debug(LTag.NSCLIENT, data.toString()) if (preferences.get(BooleanKey.NsClientNotificationsFromAlarms)) { - val snoozedTo = sp.getLong(rh.gs(app.aaps.core.utils.R.string.key_snoozed_to) + data.optString("level"), 0L) + val snoozedTo = preferences.get(LongComposedKey.NotificationSnoozedTo, data.optString("level")) if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo) uiInteraction.addNotificationWithAction(NSAlarmObject(data)) } @@ -311,7 +310,7 @@ class NSClientV3Service : DaggerService() { rxBus.send(EventNSClientNewLog("◄ URGENT ALARM", data.optString("message"))) aapsLogger.debug(LTag.NSCLIENT, data.toString()) if (preferences.get(BooleanKey.NsClientNotificationsFromAlarms)) { - val snoozedTo = sp.getLong(rh.gs(app.aaps.core.utils.R.string.key_snoozed_to) + data.optString("level"), 0L) + val snoozedTo = preferences.get(LongComposedKey.NotificationSnoozedTo, data.optString("level")) if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo) uiInteraction.addNotificationWithAction(NSAlarmObject(data)) } diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclientV3/workers/LoadBgWorker.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclientV3/workers/LoadBgWorker.kt index 36880cef482..94b5f96def1 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclientV3/workers/LoadBgWorker.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/nsclientV3/workers/LoadBgWorker.kt @@ -11,7 +11,7 @@ import app.aaps.core.interfaces.source.NSClientSource import app.aaps.core.interfaces.sync.NsClient import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.keys.BooleanKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.nssdk.interfaces.NSAndroidClient import app.aaps.core.nssdk.localmodel.entry.NSSgvV3 import app.aaps.core.objects.workflow.LoggingWorker diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/openhumans/OpenHumansUploaderPlugin.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/openhumans/OpenHumansUploaderPlugin.kt index 605dc1e9ce3..a56152b44d2 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/openhumans/OpenHumansUploaderPlugin.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/openhumans/OpenHumansUploaderPlugin.kt @@ -26,19 +26,21 @@ import app.aaps.core.data.model.data.Block import app.aaps.core.data.plugin.PluginType import app.aaps.core.interfaces.db.PersistenceLayer import app.aaps.core.interfaces.logging.AAPSLogger -import app.aaps.core.interfaces.plugin.PluginBase +import app.aaps.core.interfaces.plugin.PluginBaseWithPreferences import app.aaps.core.interfaces.plugin.PluginDescription import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventPreferenceChange import app.aaps.core.interfaces.sync.Sync import app.aaps.core.keys.BooleanKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.validators.preferences.AdaptiveSwitchPreference import app.aaps.plugins.sync.R import app.aaps.plugins.sync.openhumans.delegates.OHAppIDDelegate import app.aaps.plugins.sync.openhumans.delegates.OHCounterDelegate import app.aaps.plugins.sync.openhumans.delegates.OHStateDelegate +import app.aaps.plugins.sync.openhumans.keys.OhLongKey +import app.aaps.plugins.sync.openhumans.keys.OhStringKey import app.aaps.plugins.sync.openhumans.ui.OHFragment import app.aaps.plugins.sync.openhumans.ui.OHLoginActivity import io.reactivex.rxjava3.disposables.CompositeDisposable @@ -64,7 +66,7 @@ import javax.inject.Singleton class OpenHumansUploaderPlugin @Inject internal constructor( rh: ResourceHelper, aapsLogger: AAPSLogger, - private val preferences: Preferences, + preferences: Preferences, private val context: Context, private val persistenceLayer: PersistenceLayer, private val openHumansAPI: OpenHumansAPI, @@ -72,7 +74,7 @@ class OpenHumansUploaderPlugin @Inject internal constructor( counterDelegate: OHCounterDelegate, appIdDelegate: OHAppIDDelegate, private val rxBus: RxBus -) : Sync, PluginBase( +) : Sync, PluginBaseWithPreferences( PluginDescription() .mainType(PluginType.SYNC) .pluginIcon(R.drawable.open_humans_white) @@ -81,7 +83,8 @@ class OpenHumansUploaderPlugin @Inject internal constructor( .description(R.string.open_humans_description) .preferencesId(PluginDescription.PREFERENCE_SCREEN) .fragmentClass(OHFragment::class.qualifiedName), - aapsLogger, rh + ownPreferences = listOf(OhStringKey.AppId::class.java, OhLongKey.Counter::class.java), + aapsLogger, rh, preferences ) { private var openHumansState by stateDelegate diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/openhumans/delegates/OHAppIDDelegate.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/openhumans/delegates/OHAppIDDelegate.kt index 74a9918b198..1f1ab3d1404 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/openhumans/delegates/OHAppIDDelegate.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/openhumans/delegates/OHAppIDDelegate.kt @@ -1,6 +1,7 @@ package app.aaps.plugins.sync.openhumans.delegates -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.plugins.sync.openhumans.keys.OhStringKey import java.util.UUID import javax.inject.Inject import javax.inject.Singleton @@ -8,18 +9,18 @@ import kotlin.reflect.KProperty @Singleton internal class OHAppIDDelegate @Inject internal constructor( - private val sp: SP + private val preferences: Preferences ) { private var value: UUID? = null operator fun getValue(thisRef: Any?, property: KProperty<*>): UUID { if (value == null) { - val saved = sp.getStringOrNull("openhumans_appid", null) - if (saved == null) { + val saved = preferences.getIfExists(OhStringKey.AppId) + if (saved.isNullOrBlank()) { val generated = UUID.randomUUID() value = generated - sp.putString("openhumans_appid", generated.toString()) + preferences.put(OhStringKey.AppId, generated.toString()) } else { value = UUID.fromString(saved) } diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/openhumans/delegates/OHCounterDelegate.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/openhumans/delegates/OHCounterDelegate.kt index 0b9e62d74ad..db152032fb4 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/openhumans/delegates/OHCounterDelegate.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/openhumans/delegates/OHCounterDelegate.kt @@ -1,21 +1,22 @@ package app.aaps.plugins.sync.openhumans.delegates -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.plugins.sync.openhumans.keys.OhLongKey import javax.inject.Inject import javax.inject.Singleton import kotlin.reflect.KProperty @Singleton internal class OHCounterDelegate @Inject internal constructor( - private val sp: SP + private val preferences: Preferences ) { - private var value = sp.getLong("openhumans_counter", 1) + private var value = preferences.get(OhLongKey.Counter) operator fun getValue(thisRef: Any?, property: KProperty<*>): Long = value operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Long) { this.value = value - sp.putLong("openhumans_counter", value) + preferences.put(OhLongKey.Counter, value) } } \ No newline at end of file diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/openhumans/delegates/OHStateDelegate.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/openhumans/delegates/OHStateDelegate.kt index 97ca99286c3..2534569599c 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/openhumans/delegates/OHStateDelegate.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/openhumans/delegates/OHStateDelegate.kt @@ -2,15 +2,17 @@ package app.aaps.plugins.sync.openhumans.delegates import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences import app.aaps.plugins.sync.openhumans.OpenHumansState +import app.aaps.plugins.sync.openhumans.keys.OhLongKey +import app.aaps.plugins.sync.openhumans.keys.OhStringKey import javax.inject.Inject import javax.inject.Singleton import kotlin.reflect.KProperty @Singleton internal class OHStateDelegate @Inject internal constructor( - private val sp: SP + private val preferences: Preferences ) { private var _value = MutableLiveData(loadState()) @@ -18,15 +20,11 @@ internal class OHStateDelegate @Inject internal constructor( private fun loadState(): OpenHumansState? { return OpenHumansState( - accessToken = sp.getStringOrNull("openhumans_access_token", null) ?: return null, - refreshToken = sp.getStringOrNull("openhumans_refresh_token", null) ?: return null, - expiresAt = if (sp.contains("openhumans_expires_at")) - sp.getLong("openhumans_expires_at", 0) - else - return null, - projectMemberId = sp.getStringOrNull("openhumans_project_member_id", null) - ?: return null, - uploadOffset = sp.getLong("openhumans_upload_offset", 0) + accessToken = preferences.getIfExists(OhStringKey.AccessToken) ?: return null, + refreshToken = preferences.getIfExists(OhStringKey.RefreshToken) ?: return null, + expiresAt = preferences.getIfExists(OhLongKey.ExpiresAt) ?: return null, + projectMemberId = preferences.getIfExists(OhStringKey.ProjectMemberId) ?: return null, + uploadOffset = preferences.get(OhLongKey.UploadOffset) ) } @@ -35,17 +33,17 @@ internal class OHStateDelegate @Inject internal constructor( operator fun setValue(thisRef: Any?, property: KProperty<*>, value: OpenHumansState?) { this._value.value = value if (value == null) { - sp.remove("openhumans_access_token") - sp.remove("openhumans_refresh_token") - sp.remove("openhumans_expires_at") - sp.remove("openhumans_project_member_id") - sp.remove("openhumans_upload_offset") + preferences.remove(OhStringKey.AccessToken) + preferences.remove(OhStringKey.RefreshToken) + preferences.remove(OhLongKey.ExpiresAt) + preferences.remove(OhStringKey.ProjectMemberId) + preferences.remove(OhLongKey.UploadOffset) } else { - sp.putString("openhumans_access_token", value.accessToken) - sp.putString("openhumans_refresh_token", value.refreshToken) - sp.putLong("openhumans_expires_at", value.expiresAt) - sp.putString("openhumans_project_member_id", value.projectMemberId) - sp.putLong("openhumans_upload_offset", value.uploadOffset) + preferences.put(OhStringKey.AccessToken, value.accessToken) + preferences.put(OhStringKey.RefreshToken, value.refreshToken) + preferences.put(OhLongKey.ExpiresAt, value.expiresAt) + preferences.put(OhStringKey.ProjectMemberId, value.projectMemberId) + preferences.put(OhLongKey.UploadOffset, value.uploadOffset) } } } \ No newline at end of file diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/openhumans/keys/OhLongKey.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/openhumans/keys/OhLongKey.kt new file mode 100644 index 00000000000..9993e1535ee --- /dev/null +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/openhumans/keys/OhLongKey.kt @@ -0,0 +1,14 @@ +package app.aaps.plugins.sync.openhumans.keys + +import app.aaps.core.keys.interfaces.LongNonPreferenceKey + +enum class OhLongKey( + override val key: String, + override val defaultValue: Long, + override val exportable: Boolean = true +) : LongNonPreferenceKey { + + Counter("openhumans_counter", 1), + ExpiresAt("openhumans_expires_at", 0), + UploadOffset("openhumans_upload_offset", 0), +} \ No newline at end of file diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/openhumans/keys/OhStringKey.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/openhumans/keys/OhStringKey.kt new file mode 100644 index 00000000000..a3ba4ad6047 --- /dev/null +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/openhumans/keys/OhStringKey.kt @@ -0,0 +1,16 @@ +package app.aaps.plugins.sync.openhumans.keys + +import app.aaps.core.keys.interfaces.StringNonPreferenceKey + +@Suppress("SpellCheckingInspection") +enum class OhStringKey( + override val key: String, + override val defaultValue: String, + override val exportable: Boolean = true +) : StringNonPreferenceKey { + + AppId("openhumans_appid", ""), + AccessToken("openhumans_access_token", ""), + RefreshToken("openhumans_refresh_token", ""), + ProjectMemberId("openhumans_project_member_id", ""), +} \ No newline at end of file diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/tidepool/TidepoolFragment.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/tidepool/TidepoolFragment.kt index d1fefe3e0d7..ddf14663953 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/tidepool/TidepoolFragment.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/tidepool/TidepoolFragment.kt @@ -14,14 +14,15 @@ import androidx.lifecycle.Lifecycle import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.AapsSchedulers import app.aaps.core.interfaces.rx.bus.RxBus -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.fabric.FabricPrivacy +import app.aaps.core.keys.interfaces.Preferences import app.aaps.plugins.sync.R import app.aaps.plugins.sync.databinding.TidepoolFragmentBinding import app.aaps.plugins.sync.tidepool.comm.TidepoolUploader import app.aaps.plugins.sync.tidepool.events.EventTidepoolDoUpload import app.aaps.plugins.sync.tidepool.events.EventTidepoolResetData import app.aaps.plugins.sync.tidepool.events.EventTidepoolUpdateGUI +import app.aaps.plugins.sync.tidepool.keys.TidepoolLongKey import dagger.android.support.DaggerFragment import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign @@ -32,7 +33,7 @@ class TidepoolFragment : DaggerFragment(), MenuProvider { @Inject lateinit var rxBus: RxBus @Inject lateinit var tidepoolPlugin: TidepoolPlugin @Inject lateinit var tidepoolUploader: TidepoolUploader - @Inject lateinit var sp: SP + @Inject lateinit var preferences: Preferences @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var rh: ResourceHelper @@ -85,7 +86,7 @@ class TidepoolFragment : DaggerFragment(), MenuProvider { } ID_MENU_FULL_SYNC -> { - sp.putLong(R.string.key_tidepool_last_end, 0) + preferences.put(TidepoolLongKey.LastEnd, 0) true } diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/tidepool/TidepoolPlugin.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/tidepool/TidepoolPlugin.kt index ee9331c658e..8898fd1c090 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/tidepool/TidepoolPlugin.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/tidepool/TidepoolPlugin.kt @@ -10,7 +10,7 @@ import app.aaps.core.data.plugin.PluginType import app.aaps.core.data.time.T import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.logging.LTag -import app.aaps.core.interfaces.plugin.PluginBase +import app.aaps.core.interfaces.plugin.PluginBaseWithPreferences import app.aaps.core.interfaces.plugin.PluginDescription import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.AapsSchedulers @@ -19,13 +19,13 @@ import app.aaps.core.interfaces.rx.events.EventNSClientNewLog import app.aaps.core.interfaces.rx.events.EventNewBG import app.aaps.core.interfaces.rx.events.EventPreferenceChange import app.aaps.core.interfaces.rx.events.EventSWSyncStatus -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.sync.Sync import app.aaps.core.interfaces.sync.Tidepool import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.interfaces.utils.fabric.FabricPrivacy import app.aaps.core.keys.BooleanKey import app.aaps.core.keys.StringKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.utils.HtmlHelper import app.aaps.core.validators.DefaultEditTextValidator import app.aaps.core.validators.EditTextValidator @@ -41,6 +41,7 @@ import app.aaps.plugins.sync.tidepool.events.EventTidepoolDoUpload import app.aaps.plugins.sync.tidepool.events.EventTidepoolResetData import app.aaps.plugins.sync.tidepool.events.EventTidepoolStatus import app.aaps.plugins.sync.tidepool.events.EventTidepoolUpdateGUI +import app.aaps.plugins.sync.tidepool.keys.TidepoolLongKey import app.aaps.plugins.sync.tidepool.utils.RateLimit import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign @@ -51,17 +52,17 @@ import javax.inject.Singleton class TidepoolPlugin @Inject constructor( aapsLogger: AAPSLogger, rh: ResourceHelper, + preferences: Preferences, private val aapsSchedulers: AapsSchedulers, private val rxBus: RxBus, private val context: Context, private val fabricPrivacy: FabricPrivacy, private val tidepoolUploader: TidepoolUploader, private val uploadChunk: UploadChunk, - private val sp: SP, private val rateLimit: RateLimit, private val receiverDelegate: ReceiverDelegate, private val uiInteraction: UiInteraction -) : Sync, Tidepool, PluginBase( +) : Sync, Tidepool, PluginBaseWithPreferences( PluginDescription() .mainType(PluginType.SYNC) .pluginName(R.string.tidepool) @@ -69,7 +70,8 @@ class TidepoolPlugin @Inject constructor( .fragmentClass(TidepoolFragment::class.qualifiedName) .preferencesId(PluginDescription.PREFERENCE_SCREEN) .description(R.string.description_tidepool), - aapsLogger, rh + ownPreferences = listOf(TidepoolLongKey::class.java), + aapsLogger, rh, preferences ) { private var disposable: CompositeDisposable = CompositeDisposable() @@ -100,7 +102,7 @@ class TidepoolPlugin @Inject constructor( aapsLogger.debug(LTag.TIDEPOOL, "Not connected for delete Dataset") } else { tidepoolUploader.deleteDataSet() - sp.putLong(R.string.key_tidepool_last_end, 0) + preferences.put(TidepoolLongKey.LastEnd, 0) tidepoolUploader.doLogin() } }, fabricPrivacy::logException) @@ -170,7 +172,7 @@ class TidepoolPlugin @Inject constructor( } } textLog = HtmlHelper.fromHtml(newTextLog.toString()) - } catch (e: OutOfMemoryError) { + } catch (_: OutOfMemoryError) { uiInteraction.showToastAndNotification(context, "Out of memory!\nStop using this phone !!!", app.aaps.core.ui.R.raw.error) } } diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/tidepool/comm/TidepoolUploader.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/tidepool/comm/TidepoolUploader.kt index a47d76ddf79..f82958d69f2 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/tidepool/comm/TidepoolUploader.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/tidepool/comm/TidepoolUploader.kt @@ -12,7 +12,7 @@ import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.keys.BooleanKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.ui.dialogs.OKDialog import app.aaps.plugins.sync.R import app.aaps.plugins.sync.nsclient.ReceiverDelegate diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/tidepool/comm/UploadChunk.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/tidepool/comm/UploadChunk.kt index 8d4f70fceb3..48043a6ae84 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/tidepool/comm/UploadChunk.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/tidepool/comm/UploadChunk.kt @@ -10,9 +10,8 @@ import app.aaps.core.interfaces.plugin.ActivePlugin import app.aaps.core.interfaces.profile.ProfileFunction import app.aaps.core.interfaces.profile.ProfileUtil import app.aaps.core.interfaces.rx.bus.RxBus -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.DateUtil -import app.aaps.plugins.sync.R +import app.aaps.core.keys.interfaces.Preferences import app.aaps.plugins.sync.tidepool.elements.BasalElement import app.aaps.plugins.sync.tidepool.elements.BaseElement import app.aaps.plugins.sync.tidepool.elements.BloodGlucoseElement @@ -21,6 +20,7 @@ import app.aaps.plugins.sync.tidepool.elements.ProfileElement import app.aaps.plugins.sync.tidepool.elements.SensorGlucoseElement import app.aaps.plugins.sync.tidepool.elements.WizardElement import app.aaps.plugins.sync.tidepool.events.EventTidepoolStatus +import app.aaps.plugins.sync.tidepool.keys.TidepoolLongKey import app.aaps.plugins.sync.tidepool.utils.GsonInstance import java.util.LinkedList import javax.inject.Inject @@ -30,7 +30,7 @@ import kotlin.math.min @Singleton class UploadChunk @Inject constructor( - private val sp: SP, + private val preferences: Preferences, private val rxBus: RxBus, private val aapsLogger: AAPSLogger, private val profileFunction: ProfileFunction, @@ -81,13 +81,13 @@ class UploadChunk @Inject constructor( } fun getLastEnd(): Long { - val result = sp.getLong(R.string.key_tidepool_last_end, 0) + val result = preferences.get(TidepoolLongKey.LastEnd) return max(result, dateUtil.now() - T.months(2).msecs()) } fun setLastEnd(time: Long) { if (time > getLastEnd()) { - sp.putLong(R.string.key_tidepool_last_end, time) + preferences.put(TidepoolLongKey.LastEnd, time) val friendlyEnd = dateUtil.dateAndTimeString(time) rxBus.send(EventTidepoolStatus(("Marking uploaded data up to $friendlyEnd"))) aapsLogger.debug(LTag.TIDEPOOL, "Updating last end to: " + dateUtil.dateAndTimeString(time)) @@ -148,7 +148,7 @@ class UploadChunk @Inject constructor( private fun newInstanceOrNull(ps: EPS): ProfileElement? = try { ProfileElement(ps, activePlugin.activePump.serialNumber(), dateUtil, profileUtil) - } catch (e: Throwable) { + } catch (_: Throwable) { null } diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/tidepool/keys/TidepoolLongKey.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/tidepool/keys/TidepoolLongKey.kt new file mode 100644 index 00000000000..664b3ef259c --- /dev/null +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/tidepool/keys/TidepoolLongKey.kt @@ -0,0 +1,12 @@ +package app.aaps.plugins.sync.tidepool.keys + +import app.aaps.core.keys.interfaces.LongNonPreferenceKey + +enum class TidepoolLongKey( + override val key: String, + override val defaultValue: Long, + override val exportable: Boolean = true +) : LongNonPreferenceKey { + + LastEnd("tidepool_last_end", 0L) +} \ No newline at end of file diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/tidepool/messages/AuthRequestMessage.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/tidepool/messages/AuthRequestMessage.kt index 3c1213a04cb..ceb37ca0dc3 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/tidepool/messages/AuthRequestMessage.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/tidepool/messages/AuthRequestMessage.kt @@ -1,7 +1,7 @@ package app.aaps.plugins.sync.tidepool.messages -import app.aaps.core.keys.Preferences import app.aaps.core.keys.StringKey +import app.aaps.core.keys.interfaces.Preferences import okhttp3.Credentials object AuthRequestMessage : BaseMessage() { diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/tizen/TizenPlugin.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/tizen/TizenPlugin.kt index e261cceb120..41a547b61bd 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/tizen/TizenPlugin.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/tizen/TizenPlugin.kt @@ -28,8 +28,8 @@ import app.aaps.core.interfaces.rx.events.EventLoopUpdateGui import app.aaps.core.interfaces.rx.events.EventOverviewBolusProgress import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.fabric.FabricPrivacy -import app.aaps.core.keys.Preferences import app.aaps.core.keys.UnitDoubleKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.extensions.durationInMinutes import app.aaps.core.objects.extensions.round import app.aaps.core.objects.extensions.toStringFull diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/wear/WearFragment.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/wear/WearFragment.kt index 093bb0a4f67..13582a13286 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/wear/WearFragment.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/wear/WearFragment.kt @@ -16,7 +16,6 @@ import app.aaps.core.interfaces.rx.events.EventWearUpdateGui import app.aaps.core.interfaces.rx.weardata.CwfData import app.aaps.core.interfaces.rx.weardata.CwfMetadataKey import app.aaps.core.interfaces.rx.weardata.EventData -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.fabric.FabricPrivacy import app.aaps.core.ui.extensions.toVisibility @@ -39,7 +38,6 @@ class WearFragment : DaggerFragment() { @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var dateUtil: DateUtil @Inject lateinit var importExportPrefs: ImportExportPrefs - @Inject lateinit var sp: SP @Inject lateinit var rh: ResourceHelper @Inject lateinit var aapsLogger: AAPSLogger diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/wear/WearPlugin.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/wear/WearPlugin.kt index 86663c54705..96620856a71 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/wear/WearPlugin.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/wear/WearPlugin.kt @@ -27,10 +27,10 @@ import app.aaps.core.interfaces.rx.events.EventWearUpdateTiles import app.aaps.core.interfaces.rx.weardata.CwfData import app.aaps.core.interfaces.rx.weardata.CwfMetadataKey import app.aaps.core.interfaces.rx.weardata.EventData -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.fabric.FabricPrivacy import app.aaps.core.keys.BooleanKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.StringNonKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.validators.preferences.AdaptiveSwitchPreference import app.aaps.plugins.sync.R import app.aaps.plugins.sync.wear.receivers.WearDataReceiver @@ -47,7 +47,6 @@ class WearPlugin @Inject constructor( aapsLogger: AAPSLogger, rh: ResourceHelper, private val aapsSchedulers: AapsSchedulers, - private val sp: SP, private val preferences: Preferences, private val fabricPrivacy: FabricPrivacy, private val rxBus: RxBus, @@ -139,9 +138,9 @@ class WearPlugin @Inject constructor( fun checkCustomWatchfacePreferences() { savedCustomWatchface?.let { cwf -> val cwfAuthorization = preferences.get(BooleanKey.WearCustomWatchfaceAuthorization) - val cwfName = sp.getString(app.aaps.core.utils.R.string.key_wear_cwf_watchface_name, "") - val authorVersion = sp.getString(app.aaps.core.utils.R.string.key_wear_cwf_author_version, "") - val fileName = sp.getString(app.aaps.core.utils.R.string.key_wear_cwf_filename, "") + val cwfName = preferences.get(StringNonKey.WearCwfWatchfaceName) + val authorVersion = preferences.get(StringNonKey.WearCwfAuthorVersion) + val fileName = preferences.get(StringNonKey.WearCwfFileName) var toUpdate = false CwfData("", cwf.metadata, mutableMapOf()).also { if (cwfAuthorization != cwf.metadata[CwfMetadataKey.CWF_AUTHORIZATION]?.toBooleanStrictOrNull()) { diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/wear/activities/CwfInfosActivity.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/wear/activities/CwfInfosActivity.kt index f2644b4e41e..0ffa18557a8 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/wear/activities/CwfInfosActivity.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/wear/activities/CwfInfosActivity.kt @@ -18,7 +18,7 @@ import app.aaps.core.interfaces.rx.weardata.CwfMetadataMap import app.aaps.core.interfaces.utils.fabric.FabricPrivacy import app.aaps.core.interfaces.versionChecker.VersionCheckerUtils import app.aaps.core.keys.BooleanKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.ui.activities.TranslatedDaggerAppCompatActivity import app.aaps.plugins.sync.R import app.aaps.plugins.sync.databinding.CwfInfosActivityBinding diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/wear/wearintegration/DataHandlerMobile.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/wear/wearintegration/DataHandlerMobile.kt index 9b1cdd71385..853be32279d 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/wear/wearintegration/DataHandlerMobile.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/wear/wearintegration/DataHandlerMobile.kt @@ -62,7 +62,6 @@ import app.aaps.core.interfaces.rx.events.EventWearUpdateGui import app.aaps.core.interfaces.rx.weardata.CwfMetadataKey import app.aaps.core.interfaces.rx.weardata.EventData import app.aaps.core.interfaces.rx.weardata.EventData.LoopStatesList.AvailableLoopState -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.DecimalFormatter @@ -72,9 +71,10 @@ import app.aaps.core.interfaces.utils.fabric.FabricPrivacy import app.aaps.core.keys.BooleanKey import app.aaps.core.keys.DoubleKey import app.aaps.core.keys.IntKey -import app.aaps.core.keys.Preferences import app.aaps.core.keys.StringKey +import app.aaps.core.keys.StringNonKey import app.aaps.core.keys.UnitDoubleKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.constraints.ConstraintObject import app.aaps.core.objects.extensions.convertedToAbsolute import app.aaps.core.objects.extensions.generateCOBString @@ -110,7 +110,6 @@ class DataHandlerMobile @Inject constructor( private val rxBus: RxBus, private val aapsLogger: AAPSLogger, private val rh: ResourceHelper, - private val sp: SP, private val preferences: Preferences, private val config: Config, private val iobCobCalculator: IobCobCalculator, @@ -932,17 +931,20 @@ class DataHandlerMobile @Inject constructor( states.addAll(listOf(disconnect, reconnect)) AvailableLoopState(AvailableLoopState.LoopState.PUMP_DISCONNECT) } - !loop.isEnabled() -> { + + !loop.isEnabled() -> { // Disabled => Pump disconnect + Loop enable states.addAll(listOf(disconnect, enable)) disable } - loop.isSuspended -> { + + loop.isSuspended -> { // Suspended => Resume + Suspend again states.addAll(listOf(resume, suspend)) AvailableLoopState(AvailableLoopState.LoopState.LOOP_SUSPEND) } - else -> { + + else -> { // Some loop is enabled => Pump disconnect + Modes + Suspend + Disable states.add(disconnect) val mode = when (ApsMode.fromString(preferences.get(StringKey.LoopApsMode))) { @@ -950,17 +952,20 @@ class DataHandlerMobile @Inject constructor( states.addAll(listOf(lgs, open)) closed } - ApsMode.LGS -> { + + ApsMode.LGS -> { if (constraintChecker.isClosedLoopAllowed().value()) states.add(closed) states.add(open) lgs } - ApsMode.OPEN -> { + + ApsMode.OPEN -> { if (activePlugin.activeObjectives?.isAccomplished(Objectives.MAXIOB_OBJECTIVE) == true) states.add(closed) if (constraintChecker.isLgsAllowed().value()) states.add(lgs) open } - else -> AvailableLoopState(AvailableLoopState.LoopState.LOOP_UNKNOWN) + + else -> AvailableLoopState(AvailableLoopState.LoopState.LOOP_UNKNOWN) } states.addAll(listOf(suspend, disable)) mode @@ -969,65 +974,69 @@ class DataHandlerMobile @Inject constructor( if (loop.isSuperBolus) currentState = AvailableLoopState(AvailableLoopState.LoopState.SUPERBOLUS) lastAuthorizedLoopStateChangeTS = System.currentTimeMillis() lastLoopStates = states - rxBus.send(EventMobileToWear( - EventData.LoopStatesList(lastAuthorizedLoopStateChangeTS!!, states, currentState) - )) + rxBus.send( + EventMobileToWear( + EventData.LoopStatesList(lastAuthorizedLoopStateChangeTS!!, states, currentState) + ) + ) } private fun handleLoopStateSelected(action: EventData.LoopStateSelected) { if (action.timeStamp != lastAuthorizedLoopStateChangeTS) return sendError(rh.gs(R.string.wear_action_loop_state_unauthorized)) val newState = lastLoopStates?.elementAtOrNull(action.index) ?: return sendError(rh.gs(R.string.wear_action_loop_state_invalid)) val nDuration = action.duration ?: 0 - rxBus.send(EventMobileToWear( - EventData.ConfirmAction( - rh.gs(R.string.wear_action_loop_state_title), - when (newState.state) { - AvailableLoopState.LoopState.LOOP_CLOSED -> - rh.gs(R.string.wear_action_loop_state_changed, rh.gs(R.string.wear_action_loop_state_now_closed)) + rxBus.send( + EventMobileToWear( + EventData.ConfirmAction( + rh.gs(R.string.wear_action_loop_state_title), + when (newState.state) { + AvailableLoopState.LoopState.LOOP_CLOSED -> + rh.gs(R.string.wear_action_loop_state_changed, rh.gs(R.string.wear_action_loop_state_now_closed)) - AvailableLoopState.LoopState.LOOP_LGS -> - rh.gs(R.string.wear_action_loop_state_changed, rh.gs(R.string.wear_action_loop_state_now_lgs)) + AvailableLoopState.LoopState.LOOP_LGS -> + rh.gs(R.string.wear_action_loop_state_changed, rh.gs(R.string.wear_action_loop_state_now_lgs)) - AvailableLoopState.LoopState.LOOP_OPEN -> - rh.gs(R.string.wear_action_loop_state_changed, rh.gs(R.string.wear_action_loop_state_now_open)) + AvailableLoopState.LoopState.LOOP_OPEN -> + rh.gs(R.string.wear_action_loop_state_changed, rh.gs(R.string.wear_action_loop_state_now_open)) - AvailableLoopState.LoopState.LOOP_RESUME -> - rh.gs(R.string.wear_action_loop_state_changed, rh.gs(R.string.wear_action_loop_state_now_resumed)) + AvailableLoopState.LoopState.LOOP_RESUME -> + rh.gs(R.string.wear_action_loop_state_changed, rh.gs(R.string.wear_action_loop_state_now_resumed)) - AvailableLoopState.LoopState.LOOP_ENABLE -> - rh.gs(R.string.wear_action_loop_state_changed, rh.gs(R.string.wear_action_loop_state_now_enabled)) + AvailableLoopState.LoopState.LOOP_ENABLE -> + rh.gs(R.string.wear_action_loop_state_changed, rh.gs(R.string.wear_action_loop_state_now_enabled)) - AvailableLoopState.LoopState.LOOP_DISABLE -> - rh.gs(R.string.wear_action_loop_state_changed, rh.gs(R.string.wear_action_loop_state_now_disabled)) + AvailableLoopState.LoopState.LOOP_DISABLE -> + rh.gs(R.string.wear_action_loop_state_changed, rh.gs(R.string.wear_action_loop_state_now_disabled)) - AvailableLoopState.LoopState.PUMP_RECONNECT -> - rh.gs(R.string.wear_action_loop_state_changed, rh.gs(R.string.wear_action_loop_state_now_pump_reconnected)) + AvailableLoopState.LoopState.PUMP_RECONNECT -> + rh.gs(R.string.wear_action_loop_state_changed, rh.gs(R.string.wear_action_loop_state_now_pump_reconnected)) - AvailableLoopState.LoopState.SUPERBOLUS -> rh.gs( - R.string.wear_action_loop_state_changed, - rh.gs(R.string.wear_action_loop_state_now_superbolus) - ) + AvailableLoopState.LoopState.SUPERBOLUS -> rh.gs( + R.string.wear_action_loop_state_changed, + rh.gs(R.string.wear_action_loop_state_now_superbolus) + ) - AvailableLoopState.LoopState.LOOP_UNKNOWN -> rh.gs( - R.string.wear_action_loop_state_changed, - rh.gs(R.string.wear_action_loop_state_now_invalid) - ) + AvailableLoopState.LoopState.LOOP_UNKNOWN -> rh.gs( + R.string.wear_action_loop_state_changed, + rh.gs(R.string.wear_action_loop_state_now_invalid) + ) - AvailableLoopState.LoopState.LOOP_SUSPEND -> rh.gs( - R.string.wear_action_loop_state_changed_with_duration, - rh.gs(R.string.wear_action_loop_state_now_suspended), - nDuration - ) + AvailableLoopState.LoopState.LOOP_SUSPEND -> rh.gs( + R.string.wear_action_loop_state_changed_with_duration, + rh.gs(R.string.wear_action_loop_state_now_suspended), + nDuration + ) - AvailableLoopState.LoopState.PUMP_DISCONNECT -> rh.gs( - R.string.wear_action_loop_state_changed_with_duration, - rh.gs(R.string.wear_action_loop_state_now_pump_disconnected), - nDuration - ) - }, - EventData.LoopStateConfirmed(action.timeStamp, action.index, action.duration) + AvailableLoopState.LoopState.PUMP_DISCONNECT -> rh.gs( + R.string.wear_action_loop_state_changed_with_duration, + rh.gs(R.string.wear_action_loop_state_now_pump_disconnected), + nDuration + ) + }, + EventData.LoopStateConfirmed(action.timeStamp, action.index, action.duration) + ) ) - )) + ) } private fun handleLoopStateConfirmed(action: EventData.LoopStateConfirmed) { @@ -1039,25 +1048,28 @@ class DataHandlerMobile @Inject constructor( val nDuration = action.duration ?: 0 val durationValid = action.duration != null && action.duration!! > 0 when (newState.state) { - AvailableLoopState.LoopState.LOOP_CLOSED -> { + AvailableLoopState.LoopState.LOOP_CLOSED -> { uel.log(Action.CLOSED_LOOP_MODE, Sources.Wear) preferences.put(StringKey.LoopApsMode, ApsMode.CLOSED.name) rxBus.send(EventPreferenceChange(rh.gs(app.aaps.core.ui.R.string.closedloop))) rxBus.send(EventRefreshOverview("wear_loop_state")) } - AvailableLoopState.LoopState.LOOP_LGS -> { + + AvailableLoopState.LoopState.LOOP_LGS -> { uel.log(Action.LGS_LOOP_MODE, Sources.Wear) preferences.put(StringKey.LoopApsMode, ApsMode.LGS.name) rxBus.send(EventPreferenceChange(rh.gs(app.aaps.core.ui.R.string.lowglucosesuspend))) rxBus.send(EventRefreshOverview("wear_loop_state")) } - AvailableLoopState.LoopState.LOOP_OPEN -> { + + AvailableLoopState.LoopState.LOOP_OPEN -> { uel.log(Action.OPEN_LOOP_MODE, Sources.Wear) preferences.put(StringKey.LoopApsMode, ApsMode.OPEN.name) rxBus.send(EventPreferenceChange(rh.gs(app.aaps.core.ui.R.string.lowglucosesuspend))) // why in LoopDialog? rxBus.send(EventRefreshOverview("wear_loop_state")) } - AvailableLoopState.LoopState.LOOP_ENABLE -> { + + AvailableLoopState.LoopState.LOOP_ENABLE -> { (loop as PluginBase).setPluginEnabled(PluginType.LOOP, true) (loop as PluginBase).setFragmentVisible(PluginType.LOOP, true) configBuilder.storeSettings("EnablingLoop") @@ -1068,7 +1080,8 @@ class DataHandlerMobile @Inject constructor( ).subscribe() rxBus.send(EventRefreshOverview("wear_loop_state")) } - AvailableLoopState.LoopState.LOOP_DISABLE -> { + + AvailableLoopState.LoopState.LOOP_DISABLE -> { (loop as PluginBase).setPluginEnabled(PluginType.LOOP, false) (loop as PluginBase).setFragmentVisible(PluginType.LOOP, false) configBuilder.storeSettings("DisablingLoop") @@ -1086,6 +1099,7 @@ class DataHandlerMobile @Inject constructor( ).subscribe() rxBus.send(EventRefreshOverview("wear_loop_state")) } + AvailableLoopState.LoopState.PUMP_RECONNECT, AvailableLoopState.LoopState.LOOP_RESUME -> { disposable += persistenceLayer.cancelCurrentOfflineEvent( dateUtil.now(), @@ -1105,7 +1119,8 @@ class DataHandlerMobile @Inject constructor( }) rxBus.send(EventRefreshOverview("wear_loop_state")) } - AvailableLoopState.LoopState.LOOP_SUSPEND -> { + + AvailableLoopState.LoopState.LOOP_SUSPEND -> { if (!durationValid) return sendError(rh.gs(R.string.wear_action_loop_state_invalid)) loop.suspendLoop( nDuration, @@ -1115,7 +1130,8 @@ class DataHandlerMobile @Inject constructor( ) rxBus.send(EventRefreshOverview("wear_loop_state")) } - AvailableLoopState.LoopState.PUMP_DISCONNECT -> { + + AvailableLoopState.LoopState.PUMP_DISCONNECT -> { if (!durationValid) return sendError(rh.gs(R.string.wear_action_loop_state_invalid)) profileFunction.getProfile()?.let { profile -> loop.goToZeroTemp( @@ -1134,7 +1150,8 @@ class DataHandlerMobile @Inject constructor( rxBus.send(EventRefreshOverview("wear_loop_state")) } } - AvailableLoopState.LoopState.LOOP_UNKNOWN, AvailableLoopState.LoopState.SUPERBOLUS -> { + + AvailableLoopState.LoopState.LOOP_UNKNOWN, AvailableLoopState.LoopState.SUPERBOLUS -> { return sendError(rh.gs(R.string.wear_action_loop_state_invalid)) } } @@ -1818,12 +1835,12 @@ class DataHandlerMobile @Inject constructor( aapsLogger.debug(LTag.WEAR, "Custom Watchface received from ${command.sourceNodeId}") val cwfData = customWatchface.customWatchfaceData rxBus.send(EventWearUpdateGui(cwfData, command.exportFile)) - val watchfaceName = sp.getString(app.aaps.core.utils.R.string.key_wear_cwf_watchface_name, "") - val authorVersion = sp.getString(app.aaps.core.utils.R.string.key_wear_cwf_author_version, "") + val watchfaceName = preferences.get(StringNonKey.WearCwfWatchfaceName) + val authorVersion = preferences.get(StringNonKey.WearCwfAuthorVersion) if (cwfData.metadata[CwfMetadataKey.CWF_NAME] != watchfaceName || cwfData.metadata[CwfMetadataKey.CWF_AUTHOR_VERSION] != authorVersion) { - sp.putString(app.aaps.core.utils.R.string.key_wear_cwf_watchface_name, cwfData.metadata[CwfMetadataKey.CWF_NAME] ?: "") - sp.putString(app.aaps.core.utils.R.string.key_wear_cwf_author_version, cwfData.metadata[CwfMetadataKey.CWF_AUTHOR_VERSION] ?: "") - sp.putString(app.aaps.core.utils.R.string.key_wear_cwf_filename, cwfData.metadata[CwfMetadataKey.CWF_FILENAME] ?: "") + preferences.put(StringNonKey.WearCwfWatchfaceName, cwfData.metadata[CwfMetadataKey.CWF_NAME] ?: "") + preferences.put(StringNonKey.WearCwfAuthorVersion, cwfData.metadata[CwfMetadataKey.CWF_AUTHOR_VERSION] ?: "") + preferences.put(StringNonKey.WearCwfFileName, cwfData.metadata[CwfMetadataKey.CWF_FILENAME] ?: "") } if (command.exportFile) diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/wear/wearintegration/DataLayerListenerServiceMobile.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/wear/wearintegration/DataLayerListenerServiceMobile.kt index 20780767f00..ec6c7179484 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/wear/wearintegration/DataLayerListenerServiceMobile.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/wear/wearintegration/DataLayerListenerServiceMobile.kt @@ -17,7 +17,6 @@ import app.aaps.core.interfaces.rx.events.EventMobileToWear import app.aaps.core.interfaces.rx.events.EventMobileToWearWatchface import app.aaps.core.interfaces.rx.events.EventWearUpdateGui import app.aaps.core.interfaces.rx.weardata.EventData -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.fabric.FabricPrivacy import app.aaps.plugins.sync.R import app.aaps.plugins.sync.wear.WearPlugin @@ -52,7 +51,6 @@ class DataLayerListenerServiceMobile : WearableListenerService() { @Inject lateinit var rh: ResourceHelper @Inject lateinit var loop: Loop @Inject lateinit var wearPlugin: WearPlugin - @Inject lateinit var sp: SP @Inject lateinit var config: Config @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var rxBus: RxBus diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/xdrip/DataSyncSelectorXdripImpl.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/xdrip/DataSyncSelectorXdripImpl.kt index 9588953876a..a79e2fa41a5 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/xdrip/DataSyncSelectorXdripImpl.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/xdrip/DataSyncSelectorXdripImpl.kt @@ -8,13 +8,14 @@ import app.aaps.core.interfaces.plugin.ActivePlugin import app.aaps.core.interfaces.profile.ProfileFunction import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventXdripNewLog -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.sync.DataSyncSelector import app.aaps.core.interfaces.sync.DataSyncSelectorXdrip import app.aaps.core.interfaces.sync.XDripBroadcast import app.aaps.core.interfaces.utils.DateUtil +import app.aaps.core.keys.LongNonKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.utils.JsonHelper -import app.aaps.plugins.sync.R +import app.aaps.plugins.sync.xdrip.keys.XdripLongKey import dagger.Lazy import javax.inject.Inject import javax.inject.Singleton @@ -22,14 +23,14 @@ import javax.inject.Singleton @Suppress("unused") @Singleton class DataSyncSelectorXdripImpl @Inject constructor( - private val sp: SP, private val aapsLogger: AAPSLogger, private val dateUtil: DateUtil, private val profileFunction: ProfileFunction, private val activePlugin: ActivePlugin, private val xdripBroadcast: Lazy, private val persistenceLayer: PersistenceLayer, - private val rxBus: RxBus + private val rxBus: RxBus, + private val preferences: Preferences, ) : DataSyncSelectorXdrip { class QueueCounter( @@ -114,29 +115,29 @@ class DataSyncSelectorXdripImpl @Inject constructor( } override fun resetToNextFullSync() { - sp.remove(R.string.key_xdrip_glucose_value_last_synced_id) - sp.remove(R.string.key_xdrip_temporary_basal_last_synced_id) - sp.remove(R.string.key_xdrip_temporary_target_last_synced_id) - sp.remove(R.string.key_xdrip_extended_bolus_last_synced_id) - sp.remove(R.string.key_xdrip_food_last_synced_id) - sp.remove(R.string.key_xdrip_bolus_last_synced_id) - sp.remove(R.string.key_xdrip_carbs_last_synced_id) - sp.remove(R.string.key_xdrip_bolus_calculator_result_last_synced_id) - sp.remove(R.string.key_xdrip_therapy_event_last_synced_id) - sp.remove(R.string.key_xdrip_profile_switch_last_synced_id) - sp.remove(R.string.key_xdrip_effective_profile_switch_last_synced_id) - sp.remove(R.string.key_xdrip_offline_event_last_synced_id) - sp.remove(R.string.key_xdrip_profile_store_last_synced_timestamp) + preferences.remove(XdripLongKey.GlucoseValueLastSyncedId) + preferences.remove(XdripLongKey.TemporaryBasalLastSyncedId) + preferences.remove(XdripLongKey.TemporaryTargetLastSyncedId) + preferences.remove(XdripLongKey.ExtendedBolusLastSyncedId) + preferences.remove(XdripLongKey.FoodLastSyncedId) + preferences.remove(XdripLongKey.BolusLastSyncedId) + preferences.remove(XdripLongKey.CarbsLastSyncedId) + preferences.remove(XdripLongKey.BolusCalculatorLastSyncedId) + preferences.remove(XdripLongKey.TherapyEventLastSyncedId) + preferences.remove(XdripLongKey.ProfileSwitchLastSyncedId) + preferences.remove(XdripLongKey.EffectiveProfileSwitchLastSyncedId) + preferences.remove(XdripLongKey.OfflineEventLastSyncedId) + preferences.remove(XdripLongKey.ProfileStoreLastSyncedId) val lastDeviceStatusDbId = persistenceLayer.getLastDeviceStatusId() - if (lastDeviceStatusDbId != null) sp.putLong(R.string.key_xdrip_device_status_last_synced_id, lastDeviceStatusDbId) - else sp.remove(R.string.key_xdrip_device_status_last_synced_id) + if (lastDeviceStatusDbId != null) preferences.put(XdripLongKey.DeviceStatusLastSyncedId, lastDeviceStatusDbId) + else preferences.remove(XdripLongKey.DeviceStatusLastSyncedId) } private fun confirmLastGlucoseValueIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_xdrip_glucose_value_last_synced_id, 0)) { + if (lastSynced > preferences.get(XdripLongKey.GlucoseValueLastSyncedId)) { //aapsLogger.debug(LTag.XDRIP, "Setting GlucoseValue data sync from $lastSynced") - sp.putLong(R.string.key_xdrip_glucose_value_last_synced_id, lastSynced) + preferences.put(XdripLongKey.GlucoseValueLastSyncedId, lastSynced) } } @@ -145,9 +146,9 @@ class DataSyncSelectorXdripImpl @Inject constructor( val lastDbId = persistenceLayer.getLastGlucoseValueId() ?: 0L while (true) { if (!isEnabled) return - var startId = sp.getLong(R.string.key_xdrip_glucose_value_last_synced_id, 0) + var startId = preferences.get(XdripLongKey.GlucoseValueLastSyncedId) if (startId > lastDbId) { - sp.putLong(R.string.key_xdrip_glucose_value_last_synced_id, 0) + preferences.put(XdripLongKey.GlucoseValueLastSyncedId, 0) startId = 0 } queueCounter.gvsRemaining = lastDbId - startId @@ -185,9 +186,9 @@ class DataSyncSelectorXdripImpl @Inject constructor( } private fun confirmLastBolusIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_xdrip_bolus_last_synced_id, 0)) { + if (lastSynced > preferences.get(XdripLongKey.BolusLastSyncedId)) { //aapsLogger.debug(LTag.XDRIP, "Setting Bolus data sync from $lastSynced") - sp.putLong(R.string.key_xdrip_bolus_last_synced_id, lastSynced) + preferences.put(XdripLongKey.BolusLastSyncedId, lastSynced) } } @@ -196,9 +197,9 @@ class DataSyncSelectorXdripImpl @Inject constructor( val lastDbId = persistenceLayer.getLastBolusId() ?: 0L while (true) { if (!isEnabled) return - var startId = sp.getLong(R.string.key_xdrip_bolus_last_synced_id, 0) + var startId = preferences.get(XdripLongKey.BolusLastSyncedId) if (startId > lastDbId) { - sp.putLong(R.string.key_xdrip_bolus_last_synced_id, 0) + preferences.put(XdripLongKey.BolusLastSyncedId, 0) startId = 0 } queueCounter.bolusesRemaining = lastDbId - startId @@ -215,9 +216,9 @@ class DataSyncSelectorXdripImpl @Inject constructor( } private fun confirmLastCarbsIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_xdrip_carbs_last_synced_id, 0)) { + if (lastSynced > preferences.get(XdripLongKey.CarbsLastSyncedId)) { //aapsLogger.debug(LTag.XDRIP, "Setting Carbs data sync from $lastSynced") - sp.putLong(R.string.key_xdrip_carbs_last_synced_id, lastSynced) + preferences.put(XdripLongKey.CarbsLastSyncedId, lastSynced) } } @@ -226,9 +227,9 @@ class DataSyncSelectorXdripImpl @Inject constructor( val lastDbId = persistenceLayer.getLastCarbsId() ?: 0L while (true) { if (!isEnabled) return - var startId = sp.getLong(R.string.key_xdrip_carbs_last_synced_id, 0) + var startId = preferences.get(XdripLongKey.CarbsLastSyncedId) if (startId > lastDbId) { - sp.putLong(R.string.key_xdrip_carbs_last_synced_id, 0) + preferences.put(XdripLongKey.CarbsLastSyncedId, 0) startId = 0 } queueCounter.carbsRemaining = lastDbId - startId @@ -245,9 +246,9 @@ class DataSyncSelectorXdripImpl @Inject constructor( } private fun confirmLastBolusCalculatorResultsIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_xdrip_bolus_calculator_result_last_synced_id, 0)) { + if (lastSynced > preferences.get(XdripLongKey.BolusCalculatorLastSyncedId)) { //aapsLogger.debug(LTag.XDRIP, "Setting BolusCalculatorResult data sync from $lastSynced") - sp.putLong(R.string.key_xdrip_bolus_calculator_result_last_synced_id, lastSynced) + preferences.put(XdripLongKey.BolusCalculatorLastSyncedId, lastSynced) } } @@ -256,9 +257,9 @@ class DataSyncSelectorXdripImpl @Inject constructor( val lastDbId = persistenceLayer.getLastBolusCalculatorResultId() ?: 0L while (true) { if (!isEnabled) return - var startId = sp.getLong(R.string.key_xdrip_bolus_calculator_result_last_synced_id, 0) + var startId = preferences.get(XdripLongKey.BolusCalculatorLastSyncedId) if (startId > lastDbId) { - sp.putLong(R.string.key_xdrip_bolus_calculator_result_last_synced_id, 0) + preferences.put(XdripLongKey.BolusCalculatorLastSyncedId, 0) startId = 0 } queueCounter.bcrRemaining = lastDbId - startId @@ -275,9 +276,9 @@ class DataSyncSelectorXdripImpl @Inject constructor( } private fun confirmLastTempTargetsIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_xdrip_temporary_target_last_synced_id, 0)) { + if (lastSynced > preferences.get(XdripLongKey.TemporaryTargetLastSyncedId)) { //aapsLogger.debug(LTag.XDRIP, "Setting TemporaryTarget data sync from $lastSynced") - sp.putLong(R.string.key_xdrip_temporary_target_last_synced_id, lastSynced) + preferences.put(XdripLongKey.TemporaryTargetLastSyncedId, lastSynced) } } @@ -286,9 +287,9 @@ class DataSyncSelectorXdripImpl @Inject constructor( val lastDbId = persistenceLayer.getLastTemporaryTargetId() ?: 0L while (true) { if (!isEnabled) return - var startId = sp.getLong(R.string.key_xdrip_temporary_target_last_synced_id, 0) + var startId = preferences.get(XdripLongKey.TemporaryTargetLastSyncedId) if (startId > lastDbId) { - sp.putLong(R.string.key_xdrip_temporary_target_last_synced_id, 0) + preferences.put(XdripLongKey.TemporaryTargetLastSyncedId, 0) startId = 0 } queueCounter.ttsRemaining = lastDbId - startId @@ -305,9 +306,9 @@ class DataSyncSelectorXdripImpl @Inject constructor( } private fun confirmLastFoodIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_xdrip_food_last_synced_id, 0)) { + if (lastSynced > preferences.get(XdripLongKey.FoodLastSyncedId)) { //aapsLogger.debug(LTag.XDRIP, "Setting Food data sync from $lastSynced") - sp.putLong(R.string.key_xdrip_food_last_synced_id, lastSynced) + preferences.put(XdripLongKey.FoodLastSyncedId, lastSynced) } } @@ -316,9 +317,9 @@ class DataSyncSelectorXdripImpl @Inject constructor( val lastDbId = persistenceLayer.getLastFoodId() ?: 0L while (true) { if (!isEnabled) return - var startId = sp.getLong(R.string.key_xdrip_food_last_synced_id, 0) + var startId = preferences.get(XdripLongKey.FoodLastSyncedId) if (startId > lastDbId) { - sp.putLong(R.string.key_xdrip_food_last_synced_id, 0) + preferences.put(XdripLongKey.FoodLastSyncedId, 0) startId = 0 } queueCounter.foodsRemaining = lastDbId - startId @@ -334,9 +335,9 @@ class DataSyncSelectorXdripImpl @Inject constructor( } private fun confirmLastTherapyEventIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_xdrip_therapy_event_last_synced_id, 0)) { + if (lastSynced > preferences.get(XdripLongKey.TherapyEventLastSyncedId)) { //aapsLogger.debug(LTag.XDRIP, "Setting TherapyEvents data sync from $lastSynced") - sp.putLong(R.string.key_xdrip_therapy_event_last_synced_id, lastSynced) + preferences.put(XdripLongKey.TherapyEventLastSyncedId, lastSynced) } } @@ -345,9 +346,9 @@ class DataSyncSelectorXdripImpl @Inject constructor( val lastDbId = persistenceLayer.getLastTherapyEventId() ?: 0L while (true) { if (!isEnabled) return - var startId = sp.getLong(R.string.key_xdrip_therapy_event_last_synced_id, 0) + var startId = preferences.get(XdripLongKey.TherapyEventLastSyncedId) if (startId > lastDbId) { - sp.putLong(R.string.key_xdrip_therapy_event_last_synced_id, 0) + preferences.put(XdripLongKey.TherapyEventLastSyncedId, 0) startId = 0 } queueCounter.tesRemaining = lastDbId - startId @@ -364,9 +365,9 @@ class DataSyncSelectorXdripImpl @Inject constructor( } private fun confirmLastDeviceStatusIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_xdrip_device_status_last_synced_id, 0)) { + if (lastSynced > preferences.get(XdripLongKey.DeviceStatusLastSyncedId)) { //aapsLogger.debug(LTag.XDRIP, "Setting DeviceStatus data sync from $lastSynced") - sp.putLong(R.string.key_xdrip_device_status_last_synced_id, lastSynced) + preferences.put(XdripLongKey.DeviceStatusLastSyncedId, lastSynced) } } @@ -374,9 +375,9 @@ class DataSyncSelectorXdripImpl @Inject constructor( val lastDbId = persistenceLayer.getLastDeviceStatusId() ?: 0L while (true) { if (!isEnabled) return - var startId = sp.getLong(R.string.key_xdrip_device_status_last_synced_id, 0) + var startId = preferences.get(XdripLongKey.DeviceStatusLastSyncedId) if (startId > lastDbId) { - sp.putLong(R.string.key_xdrip_device_status_last_synced_id, 0) + preferences.put(XdripLongKey.DeviceStatusLastSyncedId, 0) startId = 0 } queueCounter.dssRemaining = lastDbId - startId @@ -390,9 +391,9 @@ class DataSyncSelectorXdripImpl @Inject constructor( } private fun confirmLastTemporaryBasalIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_xdrip_temporary_basal_last_synced_id, 0)) { + if (lastSynced > preferences.get(XdripLongKey.TemporaryBasalLastSyncedId)) { //aapsLogger.debug(LTag.XDRIP, "Setting TemporaryBasal data sync from $lastSynced") - sp.putLong(R.string.key_xdrip_temporary_basal_last_synced_id, lastSynced) + preferences.put(XdripLongKey.TemporaryBasalLastSyncedId, lastSynced) } } @@ -401,9 +402,9 @@ class DataSyncSelectorXdripImpl @Inject constructor( val lastDbId = persistenceLayer.getLastTemporaryBasalId() ?: 0L while (true) { if (!isEnabled) return - var startId = sp.getLong(R.string.key_xdrip_temporary_basal_last_synced_id, 0) + var startId = preferences.get(XdripLongKey.TemporaryBasalLastSyncedId) if (startId > lastDbId) { - sp.putLong(R.string.key_xdrip_temporary_basal_last_synced_id, 0) + preferences.put(XdripLongKey.TemporaryBasalLastSyncedId, 0) startId = 0 } queueCounter.tbrsRemaining = lastDbId - startId @@ -420,9 +421,9 @@ class DataSyncSelectorXdripImpl @Inject constructor( } private fun confirmLastExtendedBolusIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_xdrip_extended_bolus_last_synced_id, 0)) { + if (lastSynced > preferences.get(XdripLongKey.ExtendedBolusLastSyncedId)) { //aapsLogger.debug(LTag.XDRIP, "Setting ExtendedBolus data sync from $lastSynced") - sp.putLong(R.string.key_xdrip_extended_bolus_last_synced_id, lastSynced) + preferences.put(XdripLongKey.ExtendedBolusLastSyncedId, lastSynced) } } @@ -431,9 +432,9 @@ class DataSyncSelectorXdripImpl @Inject constructor( val lastDbId = persistenceLayer.getLastExtendedBolusId() ?: 0L while (true) { if (!isEnabled) return - var startId = sp.getLong(R.string.key_xdrip_extended_bolus_last_synced_id, 0) + var startId = preferences.get(XdripLongKey.ExtendedBolusLastSyncedId) if (startId > lastDbId) { - sp.putLong(R.string.key_xdrip_extended_bolus_last_synced_id, 0) + preferences.put(XdripLongKey.ExtendedBolusLastSyncedId, 0) startId = 0 } queueCounter.ebsRemaining = lastDbId - startId @@ -453,9 +454,9 @@ class DataSyncSelectorXdripImpl @Inject constructor( } private fun confirmLastProfileSwitchIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_xdrip_profile_switch_last_synced_id, 0)) { + if (lastSynced > preferences.get(XdripLongKey.ProfileSwitchLastSyncedId)) { //aapsLogger.debug(LTag.XDRIP, "Setting ProfileSwitch data sync from $lastSynced") - sp.putLong(R.string.key_xdrip_profile_switch_last_synced_id, lastSynced) + preferences.put(XdripLongKey.ProfileSwitchLastSyncedId, lastSynced) } } @@ -464,9 +465,9 @@ class DataSyncSelectorXdripImpl @Inject constructor( val lastDbId = persistenceLayer.getLastProfileSwitchId() ?: 0L while (true) { if (!isEnabled) return - var startId = sp.getLong(R.string.key_xdrip_profile_switch_last_synced_id, 0) + var startId = preferences.get(XdripLongKey.ProfileSwitchLastSyncedId) if (startId > lastDbId) { - sp.putLong(R.string.key_xdrip_profile_switch_last_synced_id, 0) + preferences.put(XdripLongKey.ProfileSwitchLastSyncedId, 0) startId = 0 } queueCounter.pssRemaining = lastDbId - startId @@ -483,9 +484,9 @@ class DataSyncSelectorXdripImpl @Inject constructor( } private fun confirmLastEffectiveProfileSwitchIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_xdrip_effective_profile_switch_last_synced_id, 0)) { + if (lastSynced > preferences.get(XdripLongKey.EffectiveProfileSwitchLastSyncedId)) { //aapsLogger.debug(LTag.XDRIP, "Setting EffectiveProfileSwitch data sync from $lastSynced") - sp.putLong(R.string.key_xdrip_effective_profile_switch_last_synced_id, lastSynced) + preferences.put(XdripLongKey.EffectiveProfileSwitchLastSyncedId, lastSynced) } } @@ -494,9 +495,9 @@ class DataSyncSelectorXdripImpl @Inject constructor( val lastDbId = persistenceLayer.getLastEffectiveProfileSwitchId() ?: 0L while (true) { if (!isEnabled) return - var startId = sp.getLong(R.string.key_xdrip_effective_profile_switch_last_synced_id, 0) + var startId = preferences.get(XdripLongKey.EffectiveProfileSwitchLastSyncedId) if (startId > lastDbId) { - sp.putLong(R.string.key_xdrip_effective_profile_switch_last_synced_id, 0) + preferences.put(XdripLongKey.EffectiveProfileSwitchLastSyncedId, 0) startId = 0 } queueCounter.epssRemaining = lastDbId - startId @@ -513,9 +514,9 @@ class DataSyncSelectorXdripImpl @Inject constructor( } private fun confirmLastOfflineEventIdIfGreater(lastSynced: Long) { - if (lastSynced > sp.getLong(R.string.key_xdrip_offline_event_last_synced_id, 0)) { + if (lastSynced > preferences.get(XdripLongKey.OfflineEventLastSyncedId)) { //aapsLogger.debug(LTag.XDRIP, "Setting OfflineEvent data sync from $lastSynced") - sp.putLong(R.string.key_xdrip_offline_event_last_synced_id, lastSynced) + preferences.put(XdripLongKey.OfflineEventLastSyncedId, lastSynced) } } @@ -524,9 +525,9 @@ class DataSyncSelectorXdripImpl @Inject constructor( val lastDbId = persistenceLayer.getLastOfflineEventId() ?: 0L while (true) { if (!isEnabled) return - var startId = sp.getLong(R.string.key_xdrip_offline_event_last_synced_id, 0) + var startId = preferences.get(XdripLongKey.OfflineEventLastSyncedId) if (startId > lastDbId) { - sp.putLong(R.string.key_xdrip_offline_event_last_synced_id, 0) + preferences.put(XdripLongKey.OfflineEventLastSyncedId, 0) startId = 0 } queueCounter.oesRemaining = lastDbId - startId @@ -543,17 +544,17 @@ class DataSyncSelectorXdripImpl @Inject constructor( } private fun confirmLastProfileStore(lastSynced: Long) { - sp.putLong(R.string.key_xdrip_profile_store_last_synced_timestamp, lastSynced) + preferences.put(XdripLongKey.ProfileStoreLastSyncedId, lastSynced) } override fun profileReceived(timestamp: Long) { - sp.putLong(R.string.key_xdrip_profile_store_last_synced_timestamp, timestamp) + preferences.put(XdripLongKey.ProfileStoreLastSyncedId, timestamp) } private fun processChangedProfileStore() { if (!isEnabled) return - val lastSync = sp.getLong(R.string.key_xdrip_profile_store_last_synced_timestamp, 0) - val lastChange = sp.getLong(app.aaps.core.utils.R.string.key_local_profile_last_change, 0) + val lastSync = preferences.get(XdripLongKey.ProfileStoreLastSyncedId) + val lastChange = preferences.get(LongNonKey.LocalProfileLastChange) if (lastChange == 0L) return if (lastChange > lastSync) { if (activePlugin.activeProfileSource.profile?.allProfilesValid != true) return diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/xdrip/XdripFragment.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/xdrip/XdripFragment.kt index 28897cd9964..17be39b4e81 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/xdrip/XdripFragment.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/xdrip/XdripFragment.kt @@ -19,7 +19,6 @@ import app.aaps.core.interfaces.plugin.PluginFragment import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.AapsSchedulers import app.aaps.core.interfaces.rx.bus.RxBus -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.sync.DataSyncSelectorXdrip import app.aaps.core.interfaces.utils.fabric.FabricPrivacy import app.aaps.core.ui.dialogs.OKDialog @@ -33,7 +32,6 @@ import javax.inject.Inject class XdripFragment : DaggerFragment(), MenuProvider, PluginFragment { - @Inject lateinit var sp: SP @Inject lateinit var rh: ResourceHelper @Inject lateinit var rxBus: RxBus @Inject lateinit var fabricPrivacy: FabricPrivacy diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/xdrip/XdripPlugin.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/xdrip/XdripPlugin.kt index b132986ac5e..01dda363f6e 100644 --- a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/xdrip/XdripPlugin.kt +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/xdrip/XdripPlugin.kt @@ -23,7 +23,7 @@ import app.aaps.core.interfaces.iob.GlucoseStatusProvider import app.aaps.core.interfaces.iob.IobCobCalculator import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.logging.LTag -import app.aaps.core.interfaces.plugin.PluginBase +import app.aaps.core.interfaces.plugin.PluginBaseWithPreferences import app.aaps.core.interfaces.plugin.PluginDescription import app.aaps.core.interfaces.profile.Profile import app.aaps.core.interfaces.profile.ProfileFunction @@ -47,7 +47,7 @@ import app.aaps.core.interfaces.utils.DecimalFormatter import app.aaps.core.interfaces.utils.fabric.FabricPrivacy import app.aaps.core.keys.BooleanKey import app.aaps.core.keys.IntentKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.extensions.generateCOBString import app.aaps.core.objects.extensions.round import app.aaps.core.objects.extensions.toStringShort @@ -59,6 +59,7 @@ import app.aaps.plugins.sync.R import app.aaps.plugins.sync.nsclient.extensions.toJson import app.aaps.plugins.sync.xdrip.events.EventXdripUpdateGUI import app.aaps.plugins.sync.xdrip.extensions.toXdripJson +import app.aaps.plugins.sync.xdrip.keys.XdripLongKey import app.aaps.plugins.sync.xdrip.workers.XdripDataSyncWorker import app.aaps.shared.impl.extensions.safeQueryBroadcastReceivers import io.reactivex.rxjava3.disposables.CompositeDisposable @@ -76,10 +77,11 @@ import javax.inject.Singleton @Singleton class XdripPlugin @Inject constructor( - private val preferences: Preferences, + aapsLogger: AAPSLogger, + rh: ResourceHelper, + preferences: Preferences, private val profileFunction: ProfileFunction, private val profileUtil: ProfileUtil, - rh: ResourceHelper, private val aapsSchedulers: AapsSchedulers, private val context: Context, private val fabricPrivacy: FabricPrivacy, @@ -89,12 +91,11 @@ class XdripPlugin @Inject constructor( private val rxBus: RxBus, private val uiInteraction: UiInteraction, private val dateUtil: DateUtil, - aapsLogger: AAPSLogger, private val config: Config, private val decimalFormatter: DecimalFormatter, private val glucoseStatusProvider: GlucoseStatusProvider -) : XDripBroadcast, Sync, PluginBase( - PluginDescription() +) : XDripBroadcast, Sync, PluginBaseWithPreferences( + pluginDescription = PluginDescription() .mainType(PluginType.SYNC) .fragmentClass(XdripFragment::class.java.name) .pluginIcon((app.aaps.core.objects.R.drawable.ic_blooddrop_48)) @@ -102,7 +103,8 @@ class XdripPlugin @Inject constructor( .shortName(R.string.xdrip_shortname) .preferencesId(PluginDescription.PREFERENCE_SCREEN) .description(R.string.description_xdrip), - aapsLogger, rh + ownPreferences = listOf(XdripLongKey::class.java), + aapsLogger, rh, preferences ) { @Suppress("PrivatePropertyName") diff --git a/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/xdrip/keys/XdripLongKey.kt b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/xdrip/keys/XdripLongKey.kt new file mode 100644 index 00000000000..e852428097d --- /dev/null +++ b/plugins/sync/src/main/kotlin/app/aaps/plugins/sync/xdrip/keys/XdripLongKey.kt @@ -0,0 +1,25 @@ +package app.aaps.plugins.sync.xdrip.keys + +import app.aaps.core.keys.interfaces.LongNonPreferenceKey + +enum class XdripLongKey( + override val key: String, + override val defaultValue: Long, + override val exportable: Boolean = true +) : LongNonPreferenceKey { + + BolusLastSyncedId("xdrip_bolus_last_synced_id", 0L), + CarbsLastSyncedId("xdrip_carbs_last_synced_id", 0L), + BolusCalculatorLastSyncedId("xdrip_bolus_calculator_result_last_synced_id", 0L), + TemporaryTargetLastSyncedId("xdrip_temporary_target_last_sync", 0L), + FoodLastSyncedId("xdrip_food_last_sync", 0L), + GlucoseValueLastSyncedId("xdrip_glucose_value_last_sync", 0L), + TherapyEventLastSyncedId("xdrip_therapy_event_last_sync", 0L), + DeviceStatusLastSyncedId("xdrip_device_status_last_synced_id", 0L), + TemporaryBasalLastSyncedId("xdrip_temporary_basal_last_synced_id", 0L), + ExtendedBolusLastSyncedId("xdrip_extended_bolus_last_synced_id", 0L), + ProfileSwitchLastSyncedId("profile_switch_last_synced_id", 0L), + EffectiveProfileSwitchLastSyncedId("xdrip_effective_profile_switch_last_synced_id", 0L), + OfflineEventLastSyncedId("xdrip_offline_event_last_synced_id", 0L), + ProfileStoreLastSyncedId("xdrip_profile_store_last_synced_timestamp", 0L), +} diff --git a/plugins/sync/src/main/res/values/strings.xml b/plugins/sync/src/main/res/values/strings.xml index 288e90faf66..194f324b912 100644 --- a/plugins/sync/src/main/res/values/strings.xml +++ b/plugins/sync/src/main/res/values/strings.xml @@ -1,21 +1,6 @@ - ns_temporary_target_last_sync - ns_glucose_value_last_sync - ns_food_last_sync - ns_therapy_event_last_sync - ns_bolus_calculator_result_last_synced_id - ns_carbs_last_synced_id - ns_bolus_last_synced_id - ns_device_status_last_synced_id - ns_temporary_basal_last_synced_id - ns_extended_bolus_last_synced_id - ns_profile_switch_last_synced_id - ns_effective_profile_switch_last_synced_id - ns_offline_event_last_synced_id - ns_profile_store_last_synced_timestamp - key_ns_client_v3_last_modified Use Cellular connection Use WiFi connection WiFi SSID @@ -39,7 +24,6 @@ NSClient malfunction. Consider NS and NSClient restart. - ns_client_paused NSCLIENT has no write permission. Wrong API secret? NSv3 NSClient @@ -93,7 +77,6 @@ Enabling means: faster updates, receiving alarms and announcements and higher battery consumption similar to v1. All other uploaders to NS must use v3 protocol. - tidepool_last_end Your Tidepool login user name, normally your email address Login User Name Your Tidepool login password @@ -123,20 +106,6 @@ Send Status line to xDrip+ xDrip+ not installed Calibration sent to xDrip+ - xdrip_temporary_target_last_sync - xdrip_glucose_value_last_sync - xdrip_food_last_sync - xdrip_therapy_event_last_sync - xdrip_bolus_calculator_result_last_synced_id - xdrip_carbs_last_synced_id - xdrip_bolus_last_synced_id - xdrip_device_status_last_synced_id - xdrip_temporary_basal_last_synced_id - xdrip_extended_bolus_last_synced_id - profile_switch_last_synced_id - xdrip_effective_profile_switch_last_synced_id - xdrip_offline_event_last_synced_id - xdrip_profile_store_last_synced_timestamp Send glucose and treatments data to xDrip+. Data Source \"xDrip+ Sync Follower\" must be selected and accepting of data must be enabled in Settings - Inter-app settings - Accept Glucose/Treatments Enable broadcasts to xDrip+. diff --git a/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/garmin/GarminPluginTest.kt b/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/garmin/GarminPluginTest.kt index 03d29c8bcdc..9534512e4e8 100644 --- a/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/garmin/GarminPluginTest.kt +++ b/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/garmin/GarminPluginTest.kt @@ -1,17 +1,19 @@ package app.aaps.plugins.sync.garmin -import android.content.SharedPreferences import app.aaps.core.data.model.GV import app.aaps.core.data.model.GlucoseUnit import app.aaps.core.data.model.SourceSensor import app.aaps.core.data.model.TrendArrow import app.aaps.core.interfaces.rx.events.EventNewBG -import app.aaps.core.keys.BooleanKey -import app.aaps.core.keys.IntKey -import app.aaps.core.keys.StringKey +import app.aaps.core.keys.BooleanNonKey +import app.aaps.core.keys.IntNonKey +import app.aaps.core.keys.StringNonKey import app.aaps.core.validators.preferences.AdaptiveIntPreference import app.aaps.core.validators.preferences.AdaptiveStringPreference import app.aaps.core.validators.preferences.AdaptiveSwitchPreference +import app.aaps.plugins.sync.garmin.keys.GarminBooleanKey +import app.aaps.plugins.sync.garmin.keys.GarminIntKey +import app.aaps.plugins.sync.garmin.keys.GarminStringKey import app.aaps.shared.tests.TestBaseWithProfile import com.google.common.truth.Truth import org.junit.jupiter.api.AfterEach @@ -21,10 +23,7 @@ import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.mockito.ArgumentCaptor -import org.mockito.ArgumentMatchers.anyBoolean -import org.mockito.ArgumentMatchers.anyInt import org.mockito.ArgumentMatchers.anyLong -import org.mockito.ArgumentMatchers.anyString import org.mockito.Mock import org.mockito.Mockito.atMost import org.mockito.Mockito.mock @@ -53,7 +52,6 @@ class GarminPluginTest : TestBaseWithProfile() { private lateinit var gp: GarminPlugin @Mock private lateinit var loopHub: LoopHub - @Mock lateinit var sharedPrefs: SharedPreferences private val clock = Clock.fixed(Instant.ofEpochMilli(10_000), ZoneId.of("UTC")) init { @@ -61,30 +59,27 @@ class GarminPluginTest : TestBaseWithProfile() { if (it is AdaptiveIntPreference) { it.profileUtil = profileUtil it.preferences = preferences - it.sharedPrefs = sharedPrefs it.config = config } if (it is AdaptiveSwitchPreference) { it.preferences = preferences - it.sharedPrefs = sharedPrefs it.config = config } if (it is AdaptiveStringPreference) { it.preferences = preferences - it.sharedPrefs = sharedPrefs } } } @BeforeEach fun setup() { - gp = GarminPlugin(aapsLogger, rh, context, loopHub, rxBus, sp, preferences) + gp = GarminPlugin(aapsLogger, rh, preferences, context, loopHub, rxBus) gp.clock = clock `when`(loopHub.currentProfileName).thenReturn("Default") - `when`(sp.getBoolean(anyString(), anyBoolean())).thenAnswer { i -> i.arguments[1] } - `when`(sp.getString(anyString(), anyString())).thenAnswer { i -> i.arguments[1] } - `when`(sp.getInt(anyString(), anyInt())).thenAnswer { i -> i.arguments[1] } - `when`(preferences.get(IntKey.GarminLocalHttpPort)).thenReturn(28890) + `when`(preferences.get(GarminIntKey.LocalHttpPort)).thenReturn(28890) + `when`(preferences.get(any())).thenAnswer { i -> 0 } + `when`(preferences.get(any())).thenAnswer { i -> false } + `when`(preferences.get(any())).thenAnswer { i -> "" } } @AfterEach @@ -181,21 +176,22 @@ class GarminPluginTest : TestBaseWithProfile() { @Test fun setupHttpServer_enabled() { - `when`(preferences.get(BooleanKey.GarminLocalHttpServer)).thenReturn(true) - `when`(preferences.get(IntKey.GarminLocalHttpPort)).thenReturn(28892) + `when`(preferences.get(GarminStringKey.RequestKey)).thenReturn("") + `when`(preferences.get(GarminBooleanKey.LocalHttpServer)).thenReturn(true) + `when`(preferences.get(GarminIntKey.LocalHttpPort)).thenReturn(28892) gp.setupHttpServer(Duration.ofSeconds(10)) val reqUri = URI("http://127.0.0.1:28892/get") val resp = reqUri.toURL().openConnection() as HttpURLConnection assertEquals(200, resp.responseCode) // Change port - `when`(preferences.get(IntKey.GarminLocalHttpPort)).thenReturn(28893) + `when`(preferences.get(GarminIntKey.LocalHttpPort)).thenReturn(28893) gp.setupHttpServer(Duration.ofSeconds(10)) val reqUri2 = URI("http://127.0.0.1:28893/get") val resp2 = reqUri2.toURL().openConnection() as HttpURLConnection assertEquals(200, resp2.responseCode) - `when`(preferences.get(BooleanKey.GarminLocalHttpServer)).thenReturn(false) + `when`(preferences.get(GarminBooleanKey.LocalHttpServer)).thenReturn(false) gp.setupHttpServer(Duration.ofSeconds(10)) assertThrows(ConnectException::class.java) { (reqUri2.toURL().openConnection() as HttpURLConnection).responseCode @@ -222,6 +218,7 @@ class GarminPluginTest : TestBaseWithProfile() { @Test fun requestHandler_NoKey() { + `when`(preferences.get(GarminStringKey.RequestKey)).thenReturn("") val uri = createUri(emptyMap()) val handler = gp.requestHandler { u: URI -> assertEquals(uri, u); "OK" } assertEquals( @@ -232,6 +229,7 @@ class GarminPluginTest : TestBaseWithProfile() { @Test fun requestHandler_KeyProvided() { + `when`(preferences.get(GarminStringKey.RequestKey)).thenReturn("") val uri = createUri(mapOf("key" to "foo")) val handler = gp.requestHandler { u: URI -> assertEquals(uri, u); "OK" } assertEquals( @@ -242,7 +240,7 @@ class GarminPluginTest : TestBaseWithProfile() { @Test fun requestHandler_KeyRequiredAndProvided() { - `when`(preferences.get(StringKey.GarminRequestKey)).thenReturn("foo") + `when`(preferences.get(GarminStringKey.RequestKey)).thenReturn("foo") val uri = createUri(mapOf("key" to "foo")) val handler = gp.requestHandler { u: URI -> assertEquals(uri, u); "OK" } assertEquals( @@ -256,7 +254,7 @@ class GarminPluginTest : TestBaseWithProfile() { fun requestHandler_KeyRequired() { gp.garminMessengerField = mock(GarminMessenger::class.java) - `when`(preferences.get(StringKey.GarminRequestKey)).thenReturn("foo") + `when`(preferences.get(GarminStringKey.RequestKey)).thenReturn("foo") val uri = createUri(emptyMap()) val handler = gp.requestHandler { u: URI -> assertEquals(uri, u); "OK" } assertEquals( @@ -287,7 +285,7 @@ class GarminPluginTest : TestBaseWithProfile() { @Test fun onConnectDevice() { gp.garminMessengerField = mock(GarminMessenger::class.java) - `when`(preferences.get(StringKey.GarminRequestKey)).thenReturn("foo") + `when`(preferences.get(GarminStringKey.RequestKey)).thenReturn("foo") val device = GarminDevice(mock(), 1, "Edge") gp.onConnectDevice(device) diff --git a/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/garmin/LoopHubTest.kt b/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/garmin/LoopHubTest.kt index 023f4bbeefe..d5abea3aafc 100644 --- a/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/garmin/LoopHubTest.kt +++ b/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/garmin/LoopHubTest.kt @@ -27,9 +27,9 @@ import app.aaps.core.interfaces.profile.ProfileFunction import app.aaps.core.interfaces.profile.ProfileUtil import app.aaps.core.interfaces.pump.DetailedBolusInfo import app.aaps.core.interfaces.queue.CommandQueue -import app.aaps.core.keys.Preferences import app.aaps.core.keys.StringKey import app.aaps.core.keys.UnitDoubleKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.shared.tests.TestBase import io.reactivex.rxjava3.core.Single import org.junit.jupiter.api.AfterEach @@ -312,7 +312,8 @@ class LoopHubTest : TestBase() { duration = samplingEnd.toEpochMilli() - samplingStart.toEpochMilli(), dateCreated = clock.millis(), beatsPerMinute = 101.0, - device = "Test Device") + device = "Test Device" + ) whenever(persistenceLayer.insertOrUpdateHeartRate(hr)).thenReturn( Single.just(PersistenceLayer.TransactionResult()) ) diff --git a/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/nsclient/NSClientPluginTest.kt b/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/nsclient/NSClientPluginTest.kt index 98e92dc700e..db24c6457e0 100644 --- a/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/nsclient/NSClientPluginTest.kt +++ b/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/nsclient/NSClientPluginTest.kt @@ -1,13 +1,6 @@ package app.aaps.plugins.sync.nsclient -import android.content.SharedPreferences import app.aaps.core.interfaces.nsclient.NSSettingsStatus -import app.aaps.core.validators.preferences.AdaptiveDoublePreference -import app.aaps.core.validators.preferences.AdaptiveIntPreference -import app.aaps.core.validators.preferences.AdaptiveIntentPreference -import app.aaps.core.validators.preferences.AdaptiveStringPreference -import app.aaps.core.validators.preferences.AdaptiveSwitchPreference -import app.aaps.core.validators.preferences.AdaptiveUnitPreference import app.aaps.shared.tests.TestBaseWithProfile import com.google.common.truth.Truth.assertThat import org.junit.jupiter.api.BeforeEach @@ -16,50 +9,15 @@ import org.mockito.Mock class NSClientPluginTest : TestBaseWithProfile() { - @Mock lateinit var sharedPrefs: SharedPreferences @Mock lateinit var receiverDelegate: ReceiverDelegate @Mock lateinit var dataSyncSelectorV1: DataSyncSelectorV1 @Mock lateinit var nsSettingsStatus: NSSettingsStatus private lateinit var nsClientPlugin: NSClientPlugin - init { - addInjector { - if (it is AdaptiveDoublePreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveIntPreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - it.config = config - } - if (it is AdaptiveIntentPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveUnitPreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveSwitchPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - it.config = config - } - if (it is AdaptiveStringPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - } - } - @BeforeEach fun prepare() { nsClientPlugin = NSClientPlugin( - aapsLogger, aapsSchedulers, rxBus, rh, context, fabricPrivacy, sp, preferences, receiverDelegate, dataSyncSelectorV1, + aapsLogger, aapsSchedulers, rxBus, rh, context, fabricPrivacy, preferences, receiverDelegate, dataSyncSelectorV1, dateUtil, profileUtil, nsSettingsStatus, decimalFormatter ) } diff --git a/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/nsclient/ReceiverDelegateTest.kt b/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/nsclient/ReceiverDelegateTest.kt index 8af86745ab8..e60c4263356 100644 --- a/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/nsclient/ReceiverDelegateTest.kt +++ b/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/nsclient/ReceiverDelegateTest.kt @@ -6,8 +6,8 @@ import app.aaps.core.interfaces.rx.events.EventChargingState import app.aaps.core.interfaces.rx.events.EventNetworkChange import app.aaps.core.interfaces.utils.fabric.FabricPrivacy import app.aaps.core.keys.BooleanKey -import app.aaps.core.keys.Preferences import app.aaps.core.keys.StringKey +import app.aaps.core.keys.interfaces.Preferences import app.aaps.shared.tests.TestBase import com.google.common.truth.Truth.assertThat import org.junit.jupiter.api.BeforeEach diff --git a/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/nsclientV3/NSClientV3PluginTest.kt b/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/nsclientV3/NSClientV3PluginTest.kt index aae4b7a33ca..34d10a1f765 100644 --- a/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/nsclientV3/NSClientV3PluginTest.kt +++ b/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/nsclientV3/NSClientV3PluginTest.kt @@ -1,6 +1,5 @@ package app.aaps.plugins.sync.nsclientV3 -import android.content.SharedPreferences import app.aaps.core.data.model.BCR import app.aaps.core.data.model.BS import app.aaps.core.data.model.CA @@ -24,20 +23,12 @@ import app.aaps.core.interfaces.db.PersistenceLayer import app.aaps.core.interfaces.insulin.Insulin import app.aaps.core.interfaces.logging.L import app.aaps.core.interfaces.logging.UserEntryLogger -import app.aaps.core.interfaces.nsclient.StoreDataForDb import app.aaps.core.interfaces.profile.ProfileFunction import app.aaps.core.interfaces.pump.VirtualPump import app.aaps.core.interfaces.source.NSClientSource import app.aaps.core.interfaces.sync.DataSyncSelector -import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.nssdk.interfaces.NSAndroidClient import app.aaps.core.nssdk.localmodel.treatment.CreateUpdateResponse -import app.aaps.core.validators.preferences.AdaptiveDoublePreference -import app.aaps.core.validators.preferences.AdaptiveIntPreference -import app.aaps.core.validators.preferences.AdaptiveIntentPreference -import app.aaps.core.validators.preferences.AdaptiveStringPreference -import app.aaps.core.validators.preferences.AdaptiveSwitchPreference -import app.aaps.core.validators.preferences.AdaptiveUnitPreference import app.aaps.plugins.sync.nsShared.StoreDataForDbImpl import app.aaps.plugins.sync.nsclient.ReceiverDelegate import app.aaps.shared.tests.TestBaseWithProfile @@ -53,7 +44,6 @@ import org.mockito.Mockito.anyLong internal class NSClientV3PluginTest : TestBaseWithProfile() { @Mock lateinit var receiverDelegate: ReceiverDelegate - @Mock lateinit var uiInteraction: UiInteraction @Mock lateinit var dataSyncSelectorV3: DataSyncSelectorV3 @Mock lateinit var nsAndroidClient: NSAndroidClient @Mock lateinit var uel: UserEntryLogger @@ -63,47 +53,12 @@ internal class NSClientV3PluginTest : TestBaseWithProfile() { @Mock lateinit var persistenceLayer: PersistenceLayer @Mock lateinit var insulin: Insulin @Mock lateinit var l: L - @Mock lateinit var sharedPrefs: SharedPreferences private lateinit var storeDataForDb: StoreDataForDbImpl private lateinit var sut: NSClientV3Plugin private var insulinConfiguration: ICfg = ICfg("Insulin", 360 * 60 * 1000, 60 * 60 * 1000) - init { - addInjector { - if (it is AdaptiveDoublePreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveIntPreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - it.config = config - } - if (it is AdaptiveIntentPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveUnitPreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveSwitchPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - it.config = config - } - if (it is AdaptiveStringPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - } - } - @BeforeEach fun mock() { Mockito.`when`(insulin.iCfg).thenReturn(insulinConfiguration) @@ -112,11 +67,11 @@ internal class NSClientV3PluginTest : TestBaseWithProfile() { @BeforeEach fun prepare() { - storeDataForDb = StoreDataForDbImpl(aapsLogger, rxBus, persistenceLayer, sp, preferences, uel, dateUtil, config, nsClientSource, virtualPump, uiInteraction) + storeDataForDb = StoreDataForDbImpl(aapsLogger, rxBus, persistenceLayer, preferences, uel, config, nsClientSource, virtualPump) sut = NSClientV3Plugin( - aapsLogger, aapsSchedulers, rxBus, rh, context, fabricPrivacy, - sp, preferences, receiverDelegate, config, dateUtil, dataSyncSelectorV3, persistenceLayer, + aapsLogger, rh, preferences, aapsSchedulers, rxBus, context, fabricPrivacy, + receiverDelegate, config, dateUtil, dataSyncSelectorV3, persistenceLayer, nsClientSource, storeDataForDb, decimalFormatter, l ) sut.nsAndroidClient = nsAndroidClient diff --git a/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/nsclientV3/extensions/DeviceStatusExtensionKtTest.kt b/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/nsclientV3/extensions/DeviceStatusExtensionKtTest.kt index 633d61dcb89..a294019283a 100644 --- a/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/nsclientV3/extensions/DeviceStatusExtensionKtTest.kt +++ b/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/nsclientV3/extensions/DeviceStatusExtensionKtTest.kt @@ -6,9 +6,8 @@ import app.aaps.core.interfaces.db.PersistenceLayer import app.aaps.core.interfaces.nsclient.ProcessedDeviceStatusData import app.aaps.core.interfaces.objects.Instantiator import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.DateUtil -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.nssdk.interfaces.RunningConfiguration import app.aaps.core.nssdk.mapper.convertToRemoteAndBack import app.aaps.plugins.sync.nsclient.data.NSDeviceStatusHandler @@ -23,7 +22,6 @@ import org.mockito.Mockito @Suppress("SpellCheckingInspection") internal class DeviceStatusExtensionKtTest : TestBase() { - @Mock lateinit var sp: SP @Mock lateinit var preferences: Preferences @Mock lateinit var rh: ResourceHelper @Mock lateinit var dateUtil: DateUtil @@ -38,7 +36,7 @@ internal class DeviceStatusExtensionKtTest : TestBase() { @BeforeEach fun setup() { processedDeviceStatusData = ProcessedDeviceStatusDataImpl(rh, dateUtil, preferences, instantiator) - nsDeviceStatusHandler = NSDeviceStatusHandler(sp, config, dateUtil, runningConfiguration, processedDeviceStatusData, aapsLogger, persistenceLayer) + nsDeviceStatusHandler = NSDeviceStatusHandler(preferences, config, dateUtil, runningConfiguration, processedDeviceStatusData, aapsLogger, persistenceLayer) Mockito.`when`(config.AAPSCLIENT).thenReturn(true) } diff --git a/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/nsclientV3/workers/LoadBgWorkerTest.kt b/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/nsclientV3/workers/LoadBgWorkerTest.kt index d949f4a2041..edf34de2577 100644 --- a/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/nsclientV3/workers/LoadBgWorkerTest.kt +++ b/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/nsclientV3/workers/LoadBgWorkerTest.kt @@ -17,13 +17,12 @@ import app.aaps.core.interfaces.logging.L import app.aaps.core.interfaces.nsclient.StoreDataForDb import app.aaps.core.interfaces.receivers.ReceiverStatusStore import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.source.NSClientSource import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.DecimalFormatter import app.aaps.core.interfaces.utils.fabric.FabricPrivacy import app.aaps.core.keys.BooleanKey -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.nssdk.interfaces.NSAndroidClient import app.aaps.core.nssdk.remotemodel.LastModified import app.aaps.core.utils.receivers.DataWorkerStorage @@ -52,7 +51,6 @@ internal class LoadBgWorkerTest : TestBase() { abstract class ContextWithInjector : Context(), HasAndroidInjector - @Mock lateinit var sp: SP @Mock lateinit var preferences: Preferences @Mock lateinit var fabricPrivacy: FabricPrivacy @Mock lateinit var dateUtil: DateUtil @@ -103,8 +101,8 @@ internal class LoadBgWorkerTest : TestBase() { dataWorkerStorage = DataWorkerStorage(context) receiverDelegate = ReceiverDelegate(rxBus, rh, preferences, receiverStatusStore, aapsSchedulers, fabricPrivacy) nsClientV3Plugin = NSClientV3Plugin( - aapsLogger, aapsSchedulers, rxBus, rh, context, fabricPrivacy, - sp, preferences, receiverDelegate, config, dateUtil, dataSyncSelectorV3, persistenceLayer, + aapsLogger, rh, preferences, aapsSchedulers, rxBus, context, fabricPrivacy, + receiverDelegate, config, dateUtil, dataSyncSelectorV3, persistenceLayer, nsClientSource, storeDataForDb, decimalFormatter, l ) nsClientV3Plugin.newestDataOnServer = LastModified(LastModified.Collections()) diff --git a/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/openhumans/OpenHumansUploaderPluginTest.kt b/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/openhumans/OpenHumansUploaderPluginTest.kt index 568dab7f22a..0d61144358b 100644 --- a/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/openhumans/OpenHumansUploaderPluginTest.kt +++ b/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/openhumans/OpenHumansUploaderPluginTest.kt @@ -1,8 +1,6 @@ package app.aaps.plugins.sync.openhumans -import android.content.SharedPreferences import app.aaps.core.interfaces.db.PersistenceLayer -import app.aaps.core.validators.preferences.AdaptiveSwitchPreference import app.aaps.plugins.sync.openhumans.delegates.OHAppIDDelegate import app.aaps.plugins.sync.openhumans.delegates.OHCounterDelegate import app.aaps.plugins.sync.openhumans.delegates.OHStateDelegate @@ -14,7 +12,6 @@ import org.mockito.Mock class OpenHumansUploaderPluginTest : TestBaseWithProfile() { - @Mock lateinit var sharedPrefs: SharedPreferences @Mock lateinit var persistenceLayer: PersistenceLayer @Mock lateinit var openHumansAPI: OpenHumansAPI @@ -23,20 +20,10 @@ class OpenHumansUploaderPluginTest : TestBaseWithProfile() { private lateinit var counterDelegate: OHCounterDelegate private lateinit var appIdDelegate: OHAppIDDelegate - init { - addInjector { - if (it is AdaptiveSwitchPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - it.config = config - } - } - } - @BeforeEach fun prepare() { - stateDelegate = OHStateDelegate(sp) - counterDelegate = OHCounterDelegate(sp) - appIdDelegate = OHAppIDDelegate(sp) + stateDelegate = OHStateDelegate(preferences) + counterDelegate = OHCounterDelegate(preferences) + appIdDelegate = OHAppIDDelegate(preferences) openHumansUploaderPlugin = OpenHumansUploaderPlugin(rh, aapsLogger, preferences, context, persistenceLayer, openHumansAPI, stateDelegate, counterDelegate, appIdDelegate, rxBus) } diff --git a/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/tidepool/TidepoolPluginTest.kt b/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/tidepool/TidepoolPluginTest.kt index dea434086a8..c091eeadc05 100644 --- a/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/tidepool/TidepoolPluginTest.kt +++ b/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/tidepool/TidepoolPluginTest.kt @@ -1,14 +1,6 @@ package app.aaps.plugins.sync.tidepool -import android.content.SharedPreferences import app.aaps.core.interfaces.ui.UiInteraction -import app.aaps.core.validators.preferences.AdaptiveClickPreference -import app.aaps.core.validators.preferences.AdaptiveDoublePreference -import app.aaps.core.validators.preferences.AdaptiveIntPreference -import app.aaps.core.validators.preferences.AdaptiveIntentPreference -import app.aaps.core.validators.preferences.AdaptiveStringPreference -import app.aaps.core.validators.preferences.AdaptiveSwitchPreference -import app.aaps.core.validators.preferences.AdaptiveUnitPreference import app.aaps.plugins.sync.nsclient.ReceiverDelegate import app.aaps.plugins.sync.tidepool.comm.TidepoolUploader import app.aaps.plugins.sync.tidepool.comm.UploadChunk @@ -21,7 +13,6 @@ import org.mockito.Mock class TidepoolPluginTest : TestBaseWithProfile() { - @Mock lateinit var sharedPrefs: SharedPreferences @Mock lateinit var tidepoolUploader: TidepoolUploader @Mock lateinit var uploadChunk: UploadChunk @Mock lateinit var receiverDelegate: ReceiverDelegate @@ -30,48 +21,10 @@ class TidepoolPluginTest : TestBaseWithProfile() { private lateinit var tidepoolPlugin: TidepoolPlugin private lateinit var rateLimit: RateLimit - init { - addInjector { - if (it is AdaptiveDoublePreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveIntPreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - it.config = config - } - if (it is AdaptiveIntentPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveUnitPreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveSwitchPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - it.config = config - } - if (it is AdaptiveStringPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveClickPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - } - } - @BeforeEach fun prepare() { rateLimit = RateLimit(dateUtil) tidepoolPlugin = TidepoolPlugin( - aapsLogger, rh, aapsSchedulers, rxBus, context, fabricPrivacy, tidepoolUploader, uploadChunk, sp, rateLimit, receiverDelegate, uiInteraction + aapsLogger, rh, preferences, aapsSchedulers, rxBus, context, fabricPrivacy, tidepoolUploader, uploadChunk, rateLimit, receiverDelegate, uiInteraction ) } diff --git a/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/wear/WearPluginTest.kt b/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/wear/WearPluginTest.kt index 13398d7f7fe..847137bdef6 100644 --- a/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/wear/WearPluginTest.kt +++ b/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/wear/WearPluginTest.kt @@ -1,6 +1,5 @@ package app.aaps.plugins.sync.wear -import android.content.SharedPreferences import app.aaps.core.validators.preferences.AdaptiveSwitchPreference import app.aaps.plugins.sync.tidepool.utils.RateLimit import app.aaps.plugins.sync.wear.wearintegration.DataHandlerMobile @@ -13,7 +12,6 @@ import org.mockito.Mock class WearPluginTest : TestBaseWithProfile() { - @Mock lateinit var sharedPrefs: SharedPreferences @Mock lateinit var dataHandlerMobile: DataHandlerMobile @Mock lateinit var dataLayerListenerServiceMobileHelper: DataLayerListenerServiceMobileHelper @@ -24,7 +22,6 @@ class WearPluginTest : TestBaseWithProfile() { addInjector { if (it is AdaptiveSwitchPreference) { it.preferences = preferences - it.sharedPrefs = sharedPrefs it.config = config } } @@ -32,7 +29,7 @@ class WearPluginTest : TestBaseWithProfile() { @BeforeEach fun prepare() { rateLimit = RateLimit(dateUtil) - wearPlugin = WearPlugin(aapsLogger, rh, aapsSchedulers, sp, preferences, fabricPrivacy, rxBus, context, dataHandlerMobile, dataLayerListenerServiceMobileHelper, config) + wearPlugin = WearPlugin(aapsLogger, rh, aapsSchedulers, preferences, fabricPrivacy, rxBus, context, dataHandlerMobile, dataLayerListenerServiceMobileHelper, config) } @Test diff --git a/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/xdrip/XdripPluginTest.kt b/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/xdrip/XdripPluginTest.kt index 01bd4474d2c..0019755d226 100644 --- a/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/xdrip/XdripPluginTest.kt +++ b/plugins/sync/src/test/kotlin/app/aaps/plugins/sync/xdrip/XdripPluginTest.kt @@ -1,6 +1,5 @@ package app.aaps.plugins.sync.xdrip -import android.content.SharedPreferences import app.aaps.core.interfaces.aps.Loop import app.aaps.core.interfaces.iob.GlucoseStatusProvider import app.aaps.core.interfaces.ui.UiInteraction @@ -15,7 +14,6 @@ import org.mockito.Mock class XdripPluginTest : TestBaseWithProfile() { - @Mock lateinit var sharedPrefs: SharedPreferences @Mock lateinit var loop: Loop @Mock lateinit var uiInteraction: UiInteraction @Mock lateinit var glucoseStatusProvider: GlucoseStatusProvider @@ -27,12 +25,10 @@ class XdripPluginTest : TestBaseWithProfile() { addInjector { if (it is AdaptiveSwitchPreference) { it.preferences = preferences - it.sharedPrefs = sharedPrefs it.config = config } if (it is AdaptiveIntentPreference) { it.preferences = preferences - it.sharedPrefs = sharedPrefs } } } @@ -40,7 +36,7 @@ class XdripPluginTest : TestBaseWithProfile() { @BeforeEach fun prepare() { rateLimit = RateLimit(dateUtil) xdripPlugin = XdripPlugin( - preferences, profileFunction, profileUtil, rh, aapsSchedulers, context, fabricPrivacy, loop, iobCobCalculator, processedTbrEbData, rxBus, uiInteraction, dateUtil, aapsLogger, config, decimalFormatter, glucoseStatusProvider + aapsLogger, rh, preferences, profileFunction, profileUtil, aapsSchedulers, context, fabricPrivacy, loop, iobCobCalculator, processedTbrEbData, rxBus, uiInteraction, dateUtil, config, decimalFormatter, glucoseStatusProvider ) } diff --git a/pump/combov2/build.gradle.kts b/pump/combov2/build.gradle.kts index 438b5116388..47fe2e7fd90 100644 --- a/pump/combov2/build.gradle.kts +++ b/pump/combov2/build.gradle.kts @@ -17,10 +17,12 @@ android { dependencies { implementation(project(":core:data")) implementation(project(":core:interfaces")) + implementation(project(":core:keys")) implementation(project(":core:libraries")) implementation(project(":core:objects")) implementation(project(":core:ui")) implementation(project(":core:utils")) + implementation(project(":core:validators")) implementation(project(":pump:combov2:comboctl")) api(libs.androidx.lifecycle.viewmodel) diff --git a/pump/combov2/comboctl/src/androidMain/kotlin/info/nightscout/comboctl/android/AndroidBluetoothDevice.kt b/pump/combov2/comboctl/src/androidMain/kotlin/info/nightscout/comboctl/android/AndroidBluetoothDevice.kt index 59a09c95f9b..0498fcb68a7 100644 --- a/pump/combov2/comboctl/src/androidMain/kotlin/info/nightscout/comboctl/android/AndroidBluetoothDevice.kt +++ b/pump/combov2/comboctl/src/androidMain/kotlin/info/nightscout/comboctl/android/AndroidBluetoothDevice.kt @@ -32,6 +32,7 @@ class AndroidBluetoothDevice( private val systemBluetoothAdapter: SystemBluetoothAdapter, override val address: BluetoothAddress ) : BluetoothDevice(Dispatchers.IO) { + private var systemBluetoothSocket: SystemBluetoothSocket? = null private var inputStream: InputStream? = null private var outputStream: OutputStream? = null @@ -80,7 +81,7 @@ class AndroidBluetoothDevice( } else { logger(LogLevel.DEBUG) { "Previous attempt to establish an RFCOMM client connection to the Combo failed with" + - "exception \"$previousException\"; trying again (this is attempt #${attemptNumber + 1} of 5)" + "exception \"$previousException\"; trying again (this is attempt #${attemptNumber + 1} of 5)" } } diff --git a/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/AAPSPumpStateStore.kt b/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/AAPSPumpStateStore.kt index ee6008a2987..4040bee48c7 100644 --- a/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/AAPSPumpStateStore.kt +++ b/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/AAPSPumpStateStore.kt @@ -218,6 +218,12 @@ class AAPSPumpStateStore( } } + /*** + * By @MilosKozak + * If changed see [ComboV2Plugin.ComboStringKey], [ComboV2Plugin.ComboIntKey], [ComboV2Plugin.ComboLongKey] + * + */ + private enum class PreferenceKeys(val str: String, val type: KClassifier) { BT_ADDRESS_KEY("combov2-bt-address-key", String::class), NONCE_KEY("combov2-nonce-key", String::class), diff --git a/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/ComboV2Plugin.kt b/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/ComboV2Plugin.kt index 27717cd0a7a..6da50d90284 100644 --- a/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/ComboV2Plugin.kt +++ b/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/ComboV2Plugin.kt @@ -6,8 +6,10 @@ import androidx.lifecycle.Lifecycle import androidx.lifecycle.coroutineScope import androidx.lifecycle.repeatOnLifecycle import androidx.preference.Preference +import androidx.preference.PreferenceCategory import androidx.preference.PreferenceFragmentCompat -import androidx.preference.SwitchPreference +import androidx.preference.PreferenceManager +import androidx.preference.PreferenceScreen import app.aaps.core.data.model.BS import app.aaps.core.data.model.TE import app.aaps.core.data.plugin.PluginType @@ -45,9 +47,13 @@ import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.DecimalFormatter +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.constraints.ConstraintObject import app.aaps.core.ui.dialogs.OKDialog import app.aaps.core.ui.toast.ToastUtils +import app.aaps.core.validators.preferences.AdaptiveIntPreference +import app.aaps.core.validators.preferences.AdaptiveIntentPreference +import app.aaps.core.validators.preferences.AdaptiveSwitchPreference import info.nightscout.comboctl.android.AndroidBluetoothInterface import info.nightscout.comboctl.base.BasicProgressStage import info.nightscout.comboctl.base.BluetoothException @@ -65,6 +71,12 @@ import info.nightscout.comboctl.parser.AlertScreenException import info.nightscout.comboctl.parser.BatteryState import info.nightscout.comboctl.parser.ReservoirState import info.nightscout.pump.combov2.activities.ComboV2PairingActivity +import info.nightscout.pump.combov2.keys.ComboBooleanKey +import info.nightscout.pump.combov2.keys.ComboIntKey +import info.nightscout.pump.combov2.keys.ComboIntNonKey +import info.nightscout.pump.combov2.keys.ComboIntentKey +import info.nightscout.pump.combov2.keys.ComboLongNonKey +import info.nightscout.pump.combov2.keys.ComboStringNonKey import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Deferred @@ -91,6 +103,7 @@ import kotlinx.datetime.toLocalDateTime import org.joda.time.DateTime import org.json.JSONException import org.json.JSONObject +import java.util.Locale import javax.inject.Inject import javax.inject.Singleton import kotlin.math.max @@ -109,6 +122,7 @@ internal const val PUMP_ERROR_TIMEOUT_INTERVAL_MSECS = 1000L * 60 * 5 class ComboV2Plugin @Inject constructor( aapsLogger: AAPSLogger, rh: ResourceHelper, + preferences: Preferences, commandQueue: CommandQueue, private val context: Context, private val rxBus: RxBus, @@ -123,15 +137,19 @@ class ComboV2Plugin @Inject constructor( private val instantiator: Instantiator ) : PumpPluginBase( - PluginDescription() + pluginDescription = PluginDescription() .mainType(PluginType.PUMP) .fragmentClass(ComboV2Fragment::class.java.name) .pluginIcon(R.drawable.ic_combov2) .pluginName(R.string.combov2_plugin_name) .shortName(R.string.combov2_plugin_shortname) .description(R.string.combov2_plugin_description) - .preferencesId(R.xml.pref_combov2), - aapsLogger, rh, commandQueue + .preferencesId(PluginDescription.PREFERENCE_SCREEN), + ownPreferences = listOf( + ComboIntentKey::class.java, ComboIntKey::class.java, ComboBooleanKey::class.java, + ComboStringNonKey::class.java, ComboIntNonKey::class.java, ComboLongNonKey::class.java + ), + aapsLogger, rh, preferences, commandQueue ), Pump, PluginConstraints { // Coroutine scope and the associated job. All coroutines @@ -444,22 +462,6 @@ class ComboV2Plugin @Inject constructor( override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) { super.preprocessPreferences(preferenceFragment) - val verboseLoggingPreference = preferenceFragment.findPreference(rh.gs(R.string.key_combov2_verbose_logging)) - verboseLoggingPreference?.setOnPreferenceChangeListener { _, newValue -> - updateComboCtlLogLevel(newValue as Boolean) - true - } - - val unpairPumpPreference: Preference? = preferenceFragment.findPreference(rh.gs(R.string.key_combov2_unpair_pump)) - unpairPumpPreference?.setOnPreferenceClickListener { - preferenceFragment.context?.let { ctx -> - OKDialog.showConfirmation(ctx, "Confirm pump unpairing", "Do you really want to unpair the pump?", ok = Runnable { - unpair() - }) - } - false - } - // Setup coroutine to enable/disable the pair and unpair // preferences depending on the pairing state. preferenceFragment.run { @@ -472,10 +474,8 @@ class ComboV2Plugin @Inject constructor( // recreates the fragment. lifecycle.coroutineScope.launch { lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { - val pairPref: Preference? = findPreference(rh.gs(R.string.key_combov2_pair_with_pump)) - val unpairPref: Preference? = findPreference(rh.gs(R.string.key_combov2_unpair_pump)) - - pairPref?.intent = Intent(activity, ComboV2PairingActivity::class.java) + val pairPref: Preference? = findPreference(ComboIntentKey.PairWithPump.key) + val unpairPref: Preference? = findPreference(ComboIntentKey.UnpairPump.key) val isInitiallyPaired = pairedStateUIFlow.value pairPref?.isEnabled = !isInitiallyPaired @@ -969,7 +969,7 @@ class ComboV2Plugin @Inject constructor( pumpStatus?.availableUnitsInReservoir?.let { newLevel -> _reservoirLevel?.let { currentLevel -> aapsLogger.debug(LTag.PUMP, "Current/new reservoir levels: $currentLevel / $newLevel") - if (sp.getBoolean(R.string.key_combov2_automatic_reservoir_entry, true) && (newLevel > currentLevel)) { + if (preferences.get(ComboBooleanKey.AutomaticReservoirEntry) && (newLevel > currentLevel)) { aapsLogger.debug(LTag.PUMP, "Auto-inserting reservoir change therapy event") pumpSync.insertTherapyEventIfNewWithTimestamp( timestamp = System.currentTimeMillis(), @@ -993,7 +993,7 @@ class ComboV2Plugin @Inject constructor( _batteryLevel?.let { currentLevel -> aapsLogger.debug(LTag.PUMP, "Current/new battery levels: $currentLevel / $newLevel") - if (sp.getBoolean(R.string.key_combov2_automatic_battery_entry, true) && (newLevel > currentLevel)) { + if (preferences.get(ComboBooleanKey.AutomaticBatteryEntry) && (newLevel > currentLevel)) { aapsLogger.debug(LTag.PUMP, "Auto-inserting battery change therapy event") pumpSync.insertTherapyEventIfNewWithTimestamp( timestamp = System.currentTimeMillis(), @@ -1108,7 +1108,7 @@ class ComboV2Plugin @Inject constructor( // Rethrowing to finish coroutine cancellation. throw e - } catch (e: ComboCtlPump.BolusCancelledByUserException) { + } catch (_: ComboCtlPump.BolusCancelledByUserException) { aapsLogger.info(LTag.PUMP, "Bolus cancelled via Combo CMD_CANCEL_BOLUS command") // This exception is thrown when the bolus is cancelled @@ -1118,13 +1118,13 @@ class ComboV2Plugin @Inject constructor( // error, hence the "success = true". reportFinishedBolus(R.string.combov2_bolus_cancelled, pumpEnactResult, succeeded = true) - } catch (e: ComboCtlPump.BolusNotDeliveredException) { + } catch (_: ComboCtlPump.BolusNotDeliveredException) { aapsLogger.error(LTag.PUMP, "Bolus not delivered") reportFinishedBolus(R.string.combov2_bolus_not_delivered, pumpEnactResult, succeeded = false) - } catch (e: ComboCtlPump.UnaccountedBolusDetectedException) { + } catch (_: ComboCtlPump.UnaccountedBolusDetectedException) { aapsLogger.error(LTag.PUMP, "Unaccounted bolus detected") reportFinishedBolus(R.string.combov2_unaccounted_bolus_detected_cancelling_bolus, pumpEnactResult, succeeded = false) - } catch (e: ComboCtlPump.InsufficientInsulinAvailableException) { + } catch (_: ComboCtlPump.InsufficientInsulinAvailableException) { aapsLogger.error(LTag.PUMP, "Insufficient insulin in reservoir") reportFinishedBolus(R.string.combov2_insufficient_insulin_in_reservoir, pumpEnactResult, succeeded = false) } catch (e: Exception) { @@ -1479,7 +1479,7 @@ class ComboV2Plugin @Inject constructor( val localBolusTimestamp = it.timestamp.toLocalDateTime(TimeZone.currentSystemDefault()) lines += rh.gs( R.string.combov2_short_status_last_bolus, decimalFormatter.to2Decimal(it.bolusAmount.cctlBolusToIU()), - String.format("%02d:%02d", localBolusTimestamp.hour, localBolusTimestamp.minute) + String.format(Locale.getDefault(), "%02d:%02d", localBolusTimestamp.hour, localBolusTimestamp.minute) ) } @@ -1644,7 +1644,7 @@ class ComboV2Plugin @Inject constructor( private var pairingPINChannel: Channel? = null fun startPairing() { - val discoveryDuration = sp.getInt(R.string.key_combov2_discovery_duration, 300) + val discoveryDuration = preferences.get(ComboIntKey.DiscoveryDuration) val newPINChannel = Channel(capacity = Channel.RENDEZVOUS) pairingPINChannel = newPINChannel @@ -2103,6 +2103,7 @@ class ComboV2Plugin @Inject constructor( is ComboCtlPump.Event.UnknownTbrDetected -> { // Inform about this unknown TBR that was observed (and automatically aborted). val remainingDurationString = String.format( + Locale.getDefault(), "%02d:%02d", event.remainingTbrDurationInMinutes / 60, event.remainingTbrDurationInMinutes % 60 @@ -2220,7 +2221,7 @@ class ComboV2Plugin @Inject constructor( private fun isPaired() = pairedStateUIFlow.value private fun updateComboCtlLogLevel() = - updateComboCtlLogLevel(sp.getBoolean(R.string.key_combov2_verbose_logging, false)) + updateComboCtlLogLevel(preferences.get(ComboBooleanKey.VerboseLogging)) private fun updateComboCtlLogLevel(enableVerbose: Boolean) { aapsLogger.debug(LTag.PUMP, "${if (enableVerbose) "Enabling" else "Disabling"} verbose logging") @@ -2440,4 +2441,43 @@ class ComboV2Plugin @Inject constructor( else -> false } + + override fun addPreferenceScreen(preferenceManager: PreferenceManager, parent: PreferenceScreen, context: Context, requiredKey: String?) { + if (requiredKey != null) return + + val category = PreferenceCategory(context) + parent.addPreference(category) + category.apply { + key = "combov2_settings" + title = rh.gs(R.string.combov2_title) + initialExpandedChildrenCount = 0 + addPreference( + AdaptiveIntentPreference( + ctx = context, intentKey = ComboIntentKey.PairWithPump, title = R.string.combov2_pair_with_pump_title, summary = R.string.combov2_pair_with_pump_summary, + intent = Intent(context, ComboV2PairingActivity::class.java) + ) + ) + addPreference( + AdaptiveIntentPreference( + ctx = context, intentKey = ComboIntentKey.UnpairPump, title = R.string.combov2_unpair_pump_title, summary = R.string.combov2_unpair_pump_summary + ).apply { + onPreferenceClickListener = Preference.OnPreferenceClickListener { preference -> + OKDialog.showConfirmation(preference.context, "Confirm pump unpairing", "Do you really want to unpair the pump?", ok = Runnable { unpair() }) + false + } + } + ) + addPreference(AdaptiveIntPreference(ctx = context, intKey = ComboIntKey.DiscoveryDuration, title = R.string.combov2_discovery_duration)) + addPreference(AdaptiveSwitchPreference(ctx = context, booleanKey = ComboBooleanKey.AutomaticReservoirEntry, title = R.string.combov2_automatic_reservoir_entry)) + addPreference(AdaptiveSwitchPreference(ctx = context, booleanKey = ComboBooleanKey.AutomaticBatteryEntry, title = R.string.combov2_automatic_battery_entry)) + addPreference( + AdaptiveSwitchPreference(ctx = context, booleanKey = ComboBooleanKey.VerboseLogging, title = R.string.combov2_verbose_logging).apply { + onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue -> + updateComboCtlLogLevel(newValue as Boolean) + true + } + } + ) + } + } } diff --git a/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/InternalSP.kt b/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/InternalSP.kt index 5c3e33b9b73..27f35b408ac 100644 --- a/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/InternalSP.kt +++ b/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/InternalSP.kt @@ -168,9 +168,14 @@ class InternalSP( } } - override fun incLong(resourceID: Int) { - val value = getLong(resourceID, 0) + 1L - sharedPreferences.edit().putLong(context.getString(resourceID), value).apply() + override fun incLong(key: String) { + val value = getLong(key, 0) + 1L + sharedPreferences.edit().putLong(key, value).apply() + } + + override fun incInt(key: String) { + val value = getInt(key, 0) + 1 + sharedPreferences.edit().putInt(key, value).apply() } override fun putBoolean(key: String, value: Boolean) = sharedPreferences.edit().putBoolean(key, value).apply() @@ -197,11 +202,6 @@ class InternalSP( override fun putInt(resourceID: Int, value: Int) = sharedPreferences.edit().putInt(context.getString(resourceID), value).apply() - override fun incInt(resourceID: Int) { - val value = getInt(resourceID, 0) + 1 - sharedPreferences.edit().putInt(context.getString(resourceID), value).apply() - } - override fun putString(resourceID: Int, value: String) = sharedPreferences.edit().putString(context.getString(resourceID), value).apply() diff --git a/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/keys/ComboBooleanKey.kt b/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/keys/ComboBooleanKey.kt new file mode 100644 index 00000000000..b60e456a741 --- /dev/null +++ b/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/keys/ComboBooleanKey.kt @@ -0,0 +1,23 @@ +package info.nightscout.pump.combov2.keys + +import app.aaps.core.keys.interfaces.BooleanPreferenceKey + +enum class ComboBooleanKey( + override val key: String, + override val defaultValue: Boolean, + override val calculatedDefaultValue: Boolean = false, + override val engineeringModeOnly: Boolean = false, + override val defaultedBySM: Boolean = false, + override val showInApsMode: Boolean = true, + override val showInNsClientMode: Boolean = true, + override val showInPumpControlMode: Boolean = true, + override val dependency: BooleanPreferenceKey? = null, + override val negativeDependency: BooleanPreferenceKey? = null, + override val hideParentScreenIfHidden: Boolean = false, + override val exportable: Boolean = true +) : BooleanPreferenceKey { + + AutomaticReservoirEntry("combov2_automatic_reservoir_entry", true), + AutomaticBatteryEntry("combov2_automatic_battery_entry", true), + VerboseLogging("combov2_verbose_logging", false), +} diff --git a/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/keys/ComboIntKey.kt b/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/keys/ComboIntKey.kt new file mode 100644 index 00000000000..c3f13d7d1f7 --- /dev/null +++ b/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/keys/ComboIntKey.kt @@ -0,0 +1,24 @@ +package info.nightscout.pump.combov2.keys + +import app.aaps.core.keys.interfaces.BooleanPreferenceKey +import app.aaps.core.keys.interfaces.IntPreferenceKey + +enum class ComboIntKey( + override val key: String, + override val defaultValue: Int, + override val min: Int = Int.MIN_VALUE, + override val max: Int = Int.MAX_VALUE, + override val calculatedDefaultValue: Boolean = false, + override val engineeringModeOnly: Boolean = false, + override val defaultedBySM: Boolean = false, + override val showInApsMode: Boolean = true, + override val showInNsClientMode: Boolean = true, + override val showInPumpControlMode: Boolean = true, + override val dependency: BooleanPreferenceKey? = null, + override val negativeDependency: BooleanPreferenceKey? = null, + override val hideParentScreenIfHidden: Boolean = false, + override val exportable: Boolean = true +) : IntPreferenceKey { + + DiscoveryDuration("combov2_bt_discovery_duration", defaultValue = 300, min = 30, max = 300), +} diff --git a/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/keys/ComboIntNonKey.kt b/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/keys/ComboIntNonKey.kt new file mode 100644 index 00000000000..967db50b0f3 --- /dev/null +++ b/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/keys/ComboIntNonKey.kt @@ -0,0 +1,15 @@ +package info.nightscout.pump.combov2.keys + +import app.aaps.core.keys.interfaces.IntNonPreferenceKey + +enum class ComboIntNonKey( + override val key: String, + override val defaultValue: Int, + override val exportable: Boolean = true +) : IntNonPreferenceKey { + + KeyResponseAddress("combov2-key-response-address-key", 0), + TbrPercentage("combov2-tbr-percentage", 0), + TbrDuration("combov2-tbr-duration", 0), + UtcOffset("combov2-utc-offset", 0), +} \ No newline at end of file diff --git a/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/keys/ComboIntentKey.kt b/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/keys/ComboIntentKey.kt new file mode 100644 index 00000000000..3008731678d --- /dev/null +++ b/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/keys/ComboIntentKey.kt @@ -0,0 +1,20 @@ +package info.nightscout.pump.combov2.keys + +import app.aaps.core.keys.interfaces.BooleanPreferenceKey +import app.aaps.core.keys.interfaces.IntentPreferenceKey + +enum class ComboIntentKey( + override val key: String, + override val defaultedBySM: Boolean = false, + override val showInApsMode: Boolean = true, + override val showInNsClientMode: Boolean = true, + override val showInPumpControlMode: Boolean = true, + override val dependency: BooleanPreferenceKey? = null, + override val negativeDependency: BooleanPreferenceKey? = null, + override val hideParentScreenIfHidden: Boolean = false, + override val exportable: Boolean = false +) : IntentPreferenceKey { + + PairWithPump(key = "combov2_pair_with_pump"), + UnpairPump(key = "combov2_unpair_pump"), +} \ No newline at end of file diff --git a/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/keys/ComboLongNonKey.kt b/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/keys/ComboLongNonKey.kt new file mode 100644 index 00000000000..0809a588e8f --- /dev/null +++ b/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/keys/ComboLongNonKey.kt @@ -0,0 +1,13 @@ +package info.nightscout.pump.combov2.keys + +import app.aaps.core.keys.interfaces.LongNonPreferenceKey + +@Suppress("unused") +enum class ComboLongNonKey( + override val key: String, + override val defaultValue: Long, + override val exportable: Boolean = true +) : LongNonPreferenceKey { + + TbrTimestamp("combov2-tbr-timestamp", 0), +} \ No newline at end of file diff --git a/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/keys/ComboStringNonKey.kt b/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/keys/ComboStringNonKey.kt new file mode 100644 index 00000000000..2d31dbf05e1 --- /dev/null +++ b/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/keys/ComboStringNonKey.kt @@ -0,0 +1,17 @@ +package info.nightscout.pump.combov2.keys + +import app.aaps.core.keys.interfaces.StringNonPreferenceKey + +enum class ComboStringNonKey( + override val key: String, + override val defaultValue: String, + override val exportable: Boolean = true +) : StringNonPreferenceKey { + + BtAddress("combov2-bt-address-key", ""), + Nonce("combov2-nonce-key", ""), + CpCipher("combov2-cp-cipher-key", ""), + PcCipher("combov2-pc-cipher-key", ""), + PumpID("combov2-pump-id-key", ""), + TbrType("combov2-tbr-type", ""), +} \ No newline at end of file diff --git a/pump/combov2/src/main/res/values/strings.xml b/pump/combov2/src/main/res/values/strings.xml index 1052b8aa66e..f35a2c0fae7 100644 --- a/pump/combov2/src/main/res/values/strings.xml +++ b/pump/combov2/src/main/res/values/strings.xml @@ -27,8 +27,6 @@ Current activity Bluetooth address combov2_settings - combov2_pair_with_pump - combov2_unpair_pump Start pairing Combo pairing in progress Steps to perform pairing with your Combo:\n\n @@ -77,9 +75,7 @@ buttons at the same time to cancel pairing)\n Updating pump datetime Updating pump status PIN did not work. Check if there was a typo. If this keeps happening, cancel and retry pairing. - combov2_bt_discovery_duration Discovery duration (in seconds) - combov2_verbose_logging Enable verbose Combo logging Getting basal profile; %1$d factor(s) read Setting basal profile; %1$d factor(s) written @@ -125,8 +121,6 @@ buttons at the same time to cancel pairing)\n low full Batt: %s - combov2_automatic_reservoir_entry - combov2_automatic_battery_entry Autodetect and automatically enter insulin reservoir change Autodetect and automatically enter battery change Timezone changed diff --git a/pump/combov2/src/main/res/xml/pref_combov2.xml b/pump/combov2/src/main/res/xml/pref_combov2.xml deleted file mode 100644 index f950b206df2..00000000000 --- a/pump/combov2/src/main/res/xml/pref_combov2.xml +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/pump/dana/src/main/kotlin/app/aaps/pump/dana/DanaPump.kt b/pump/dana/src/main/kotlin/app/aaps/pump/dana/DanaPump.kt index 8f0f17fd605..2ef2c0853d3 100644 --- a/pump/dana/src/main/kotlin/app/aaps/pump/dana/DanaPump.kt +++ b/pump/dana/src/main/kotlin/app/aaps/pump/dana/DanaPump.kt @@ -13,7 +13,7 @@ import app.aaps.core.interfaces.pump.PumpSync import app.aaps.core.interfaces.rx.events.EventOverviewBolusProgress import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.DecimalFormatter -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.dana.keys.DanaIntKey import app.aaps.pump.dana.keys.DanaStringKey import org.joda.time.DateTime @@ -386,11 +386,11 @@ class DanaPump @Inject constructor( } val isPasswordOK: Boolean - get() = password == preferences.get(DanaIntKey.DanaRPassword) + get() = password == preferences.get(DanaIntKey.Password) val isRSPasswordOK: Boolean get() = rsPassword.equals( - preferences.get(DanaStringKey.DanaRsPassword), + preferences.get(DanaStringKey.Password), ignoreCase = true ) || ignoreUserPassword diff --git a/pump/dana/src/main/kotlin/app/aaps/pump/dana/keys/DanaBooleanKey.kt b/pump/dana/src/main/kotlin/app/aaps/pump/dana/keys/DanaBooleanKey.kt index 5446f0ad93c..90930d15754 100644 --- a/pump/dana/src/main/kotlin/app/aaps/pump/dana/keys/DanaBooleanKey.kt +++ b/pump/dana/src/main/kotlin/app/aaps/pump/dana/keys/DanaBooleanKey.kt @@ -1,6 +1,6 @@ package app.aaps.pump.dana.keys -import app.aaps.core.keys.BooleanPreferenceKey +import app.aaps.core.keys.interfaces.BooleanPreferenceKey enum class DanaBooleanKey( override val key: String, @@ -13,10 +13,11 @@ enum class DanaBooleanKey( override val showInPumpControlMode: Boolean = true, override val dependency: BooleanPreferenceKey? = null, override val negativeDependency: BooleanPreferenceKey? = null, - override val hideParentScreenIfHidden: Boolean = false + override val hideParentScreenIfHidden: Boolean = false, + override val exportable: Boolean = true ) : BooleanPreferenceKey { - DanaRUseExtended("danar_useextended", true, defaultedBySM = true), - DanaRsLogCannulaChange("rs_logcanulachange", true), - DanaRsLogInsulinChange("rs_loginsulinchange", true), + UseExtended("danar_useextended", true, defaultedBySM = true), + LogCannulaChange("rs_logcanulachange", true), + LogInsulinChange("rs_loginsulinchange", true), } diff --git a/pump/dana/src/main/kotlin/app/aaps/pump/dana/keys/DanaIntKey.kt b/pump/dana/src/main/kotlin/app/aaps/pump/dana/keys/DanaIntKey.kt index d45cee8a446..e3503fe49de 100644 --- a/pump/dana/src/main/kotlin/app/aaps/pump/dana/keys/DanaIntKey.kt +++ b/pump/dana/src/main/kotlin/app/aaps/pump/dana/keys/DanaIntKey.kt @@ -1,7 +1,7 @@ package app.aaps.pump.dana.keys -import app.aaps.core.keys.BooleanPreferenceKey -import app.aaps.core.keys.IntPreferenceKey +import app.aaps.core.keys.interfaces.BooleanPreferenceKey +import app.aaps.core.keys.interfaces.IntPreferenceKey enum class DanaIntKey( override val key: String, @@ -16,9 +16,10 @@ enum class DanaIntKey( override val showInPumpControlMode: Boolean = true, override val dependency: BooleanPreferenceKey? = null, override val negativeDependency: BooleanPreferenceKey? = null, - override val hideParentScreenIfHidden: Boolean = false + override val hideParentScreenIfHidden: Boolean = false, + override val exportable: Boolean = true ) : IntPreferenceKey { - DanaRPassword("danar_password", 0), - DanaBolusSpeed("danars_bolusspeed", 0), + Password("danar_password", 0), + BolusSpeed("danars_bolusspeed", 0), } diff --git a/pump/dana/src/main/kotlin/app/aaps/pump/dana/keys/DanaIntentKey.kt b/pump/dana/src/main/kotlin/app/aaps/pump/dana/keys/DanaIntentKey.kt index e4e4ba7c0ee..de28a8d06e7 100644 --- a/pump/dana/src/main/kotlin/app/aaps/pump/dana/keys/DanaIntentKey.kt +++ b/pump/dana/src/main/kotlin/app/aaps/pump/dana/keys/DanaIntentKey.kt @@ -1,7 +1,7 @@ package app.aaps.pump.dana.keys -import app.aaps.core.keys.BooleanPreferenceKey -import app.aaps.core.keys.IntentPreferenceKey +import app.aaps.core.keys.interfaces.BooleanPreferenceKey +import app.aaps.core.keys.interfaces.IntentPreferenceKey enum class DanaIntentKey( override val key: String, @@ -11,8 +11,9 @@ enum class DanaIntentKey( override val showInPumpControlMode: Boolean = true, override val dependency: BooleanPreferenceKey? = null, override val negativeDependency: BooleanPreferenceKey? = null, - override val hideParentScreenIfHidden: Boolean = false + override val hideParentScreenIfHidden: Boolean = false, + override val exportable: Boolean = false ) : IntentPreferenceKey { - DanaRsBtSelector(key = "dana_rs_bt_selector") + BtSelector(key = "dana_rs_bt_selector") } \ No newline at end of file diff --git a/pump/dana/src/main/kotlin/app/aaps/pump/dana/keys/DanaLongKey.kt b/pump/dana/src/main/kotlin/app/aaps/pump/dana/keys/DanaLongKey.kt index bb97ee9322e..8d593ea029c 100644 --- a/pump/dana/src/main/kotlin/app/aaps/pump/dana/keys/DanaLongKey.kt +++ b/pump/dana/src/main/kotlin/app/aaps/pump/dana/keys/DanaLongKey.kt @@ -1,7 +1,7 @@ package app.aaps.pump.dana.keys -import app.aaps.core.keys.BooleanPreferenceKey -import app.aaps.core.keys.LongPreferenceKey +import app.aaps.core.keys.interfaces.BooleanPreferenceKey +import app.aaps.core.keys.interfaces.LongPreferenceKey enum class DanaLongKey( override val key: String, @@ -16,8 +16,9 @@ enum class DanaLongKey( override val showInPumpControlMode: Boolean = true, override val dependency: BooleanPreferenceKey? = null, override val negativeDependency: BooleanPreferenceKey? = null, - override val hideParentScreenIfHidden: Boolean = false + override val hideParentScreenIfHidden: Boolean = false, + override val exportable: Boolean = true ) : LongPreferenceKey { - DanaRsLastClearKeyRequest("rs_last_clear_key_request", 0), + LastClearKeyRequest("rs_last_clear_key_request", 0), } diff --git a/pump/dana/src/main/kotlin/app/aaps/pump/dana/keys/DanaString2Key.kt b/pump/dana/src/main/kotlin/app/aaps/pump/dana/keys/DanaString2Key.kt deleted file mode 100644 index 4954d509b45..00000000000 --- a/pump/dana/src/main/kotlin/app/aaps/pump/dana/keys/DanaString2Key.kt +++ /dev/null @@ -1,24 +0,0 @@ -package app.aaps.pump.dana.keys - -import app.aaps.core.keys.BooleanPreferenceKey -import app.aaps.core.keys.String2PreferenceKey - -enum class DanaString2Key( - override val key: String, - override val defaultValue: String, - override val delimiter: String, - override val defaultedBySM: Boolean = false, - override val showInApsMode: Boolean = true, - override val showInNsClientMode: Boolean = true, - override val showInPumpControlMode: Boolean = true, - override val dependency: BooleanPreferenceKey? = null, - override val negativeDependency: BooleanPreferenceKey? = null, - override val hideParentScreenIfHidden: Boolean = false -) : String2PreferenceKey { - - DanaRsParingKey("danars_pairing_key", "", delimiter = "_"), - DanaRsV3RandomParingKey("danars_v3_randompairing_key", "", delimiter = "_"), - DanaRsV3ParingKey("danars_v3_pairing_key", "", delimiter = "_"), - DanaRsV3RandomSyncKey("danars_v3_randomsync_key", "", delimiter = "_"), - DanaRsBle5PairingKey("dana_ble5_pairingkey", "", delimiter = ""), -} diff --git a/pump/dana/src/main/kotlin/app/aaps/pump/dana/keys/DanaStringComposedKey.kt b/pump/dana/src/main/kotlin/app/aaps/pump/dana/keys/DanaStringComposedKey.kt new file mode 100644 index 00000000000..4bd505bc3a3 --- /dev/null +++ b/pump/dana/src/main/kotlin/app/aaps/pump/dana/keys/DanaStringComposedKey.kt @@ -0,0 +1,17 @@ +package app.aaps.pump.dana.keys + +import app.aaps.core.keys.interfaces.StringComposedNonPreferenceKey + +enum class DanaStringComposedKey( + override val key: String, + override val format: String = "%s", + override val defaultValue: String, + override val exportable: Boolean = true +) : StringComposedNonPreferenceKey { + + ParingKey(key = "danars_pairing_key_", defaultValue = ""), + V3RandomParingKey(key = "danars_v3_randompairing_key_", defaultValue = ""), + V3ParingKey(key = "danars_v3_pairing_key_", defaultValue = ""), + V3RandomSyncKey(key = "danars_v3_randomsync_key_", defaultValue = ""), + Ble5PairingKey(key = "dana_ble5_pairingkey", defaultValue = ""), +} diff --git a/pump/dana/src/main/kotlin/app/aaps/pump/dana/keys/DanaStringKey.kt b/pump/dana/src/main/kotlin/app/aaps/pump/dana/keys/DanaStringKey.kt index a313c4a4326..ba7a32b13ff 100644 --- a/pump/dana/src/main/kotlin/app/aaps/pump/dana/keys/DanaStringKey.kt +++ b/pump/dana/src/main/kotlin/app/aaps/pump/dana/keys/DanaStringKey.kt @@ -1,7 +1,7 @@ package app.aaps.pump.dana.keys -import app.aaps.core.keys.BooleanPreferenceKey -import app.aaps.core.keys.StringPreferenceKey +import app.aaps.core.keys.interfaces.BooleanPreferenceKey +import app.aaps.core.keys.interfaces.StringPreferenceKey enum class DanaStringKey( override val key: String, @@ -14,12 +14,12 @@ enum class DanaStringKey( override val negativeDependency: BooleanPreferenceKey? = null, override val hideParentScreenIfHidden: Boolean = false, override val isPassword: Boolean = false, - override val isPin: Boolean = false + override val isPin: Boolean = false, + override val exportable: Boolean = true ) : StringPreferenceKey { - DanaRName("danar_bt_name", ""), - - DanaRsName("danars_name", ""), - DanaMacAddress("danars_address", ""), - DanaRsPassword("danars_password", ""), + RName("danar_bt_name", ""), + RsName("danars_name", ""), + MacAddress("danars_address", ""), + Password("danars_password", ""), } diff --git a/pump/danar/src/main/kotlin/app/aaps/pump/danar/AbstractDanaRPlugin.kt b/pump/danar/src/main/kotlin/app/aaps/pump/danar/AbstractDanaRPlugin.kt index 8ee65d8225e..61d3fe96e94 100644 --- a/pump/danar/src/main/kotlin/app/aaps/pump/danar/AbstractDanaRPlugin.kt +++ b/pump/danar/src/main/kotlin/app/aaps/pump/danar/AbstractDanaRPlugin.kt @@ -32,7 +32,7 @@ import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.DecimalFormatter import app.aaps.core.interfaces.utils.Round.roundTo -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.constraints.ConstraintObject import app.aaps.pump.dana.DanaFragment import app.aaps.pump.dana.DanaPump @@ -55,22 +55,22 @@ import kotlin.math.max */ abstract class AbstractDanaRPlugin protected constructor( protected var danaPump: DanaPump, + aapsLogger: AAPSLogger, rh: ResourceHelper, + preferences: Preferences, + commandQueue: CommandQueue, protected var constraintChecker: ConstraintsChecker, - aapsLogger: AAPSLogger, protected var aapsSchedulers: AapsSchedulers, - commandQueue: CommandQueue, protected var rxBus: RxBus, protected var activePlugin: ActivePlugin, protected var dateUtil: DateUtil, protected var pumpSync: PumpSync, - protected val preferences: Preferences, protected var uiInteraction: UiInteraction, protected var danaHistoryDatabase: DanaHistoryDatabase, protected var decimalFormatter: DecimalFormatter, protected var instantiator: Instantiator ) : PumpPluginBase( - PluginDescription() + pluginDescription = PluginDescription() .mainType(PluginType.PUMP) .fragmentClass(DanaFragment::class.java.name) .pluginIcon(app.aaps.core.ui.R.drawable.ic_danars_128) @@ -78,7 +78,8 @@ abstract class AbstractDanaRPlugin protected constructor( .shortName(app.aaps.pump.dana.R.string.danarpump_shortname) .preferencesId(PluginDescription.PREFERENCE_SCREEN) .description(app.aaps.pump.dana.R.string.description_pump_dana_r), - aapsLogger, rh, commandQueue + ownPreferences = listOf(DanaStringKey::class.java, DanaIntKey::class.java, DanaBooleanKey::class.java, DanaIntentKey::class.java), + aapsLogger, rh, preferences, commandQueue ), Pump, Dana, PluginConstraints, OwnDatabasePlugin { protected var executionService: AbstractDanaRExecutionService? = null @@ -86,14 +87,6 @@ abstract class AbstractDanaRPlugin protected constructor( override var pumpDescription = PumpDescription() protected set - // Make plugin preferences available to AAPS - init { - preferences.registerPreferences(DanaStringKey::class.java) - preferences.registerPreferences(DanaIntKey::class.java) - preferences.registerPreferences(DanaBooleanKey::class.java) - preferences.registerPreferences(DanaIntentKey::class.java) - } - override fun onStart() { super.onStart() disposable += rxBus @@ -105,13 +98,13 @@ abstract class AbstractDanaRPlugin protected constructor( .toObservable(EventPreferenceChange::class.java) .observeOn(aapsSchedulers.io) .subscribe { event: EventPreferenceChange -> - if (event.isChanged(DanaStringKey.DanaRName.key)) { + if (event.isChanged(DanaStringKey.RName.key)) { danaPump.reset() pumpSync.connectNewPump(true) commandQueue.readStatus(rh.gs(app.aaps.core.ui.R.string.device_changed), null) } } - danaPump.serialNumber = preferences.get(DanaStringKey.DanaRName) // fill at start to allow password reset + danaPump.serialNumber = preferences.get(DanaStringKey.RName) // fill at start to allow password reset } override fun onStop() { @@ -271,12 +264,12 @@ abstract class AbstractDanaRPlugin protected constructor( .duration(danaPump.extendedBolusRemainingMinutes) .absolute(danaPump.extendedBolusAbsoluteRate) .isPercent(false) - if (!preferences.get(DanaBooleanKey.DanaRUseExtended)) result.bolusDelivered(danaPump.extendedBolusAmount) + if (!preferences.get(DanaBooleanKey.UseExtended)) result.bolusDelivered(danaPump.extendedBolusAmount) pumpSync.syncExtendedBolusWithPumpId( danaPump.extendedBolusStart, danaPump.extendedBolusAmount, danaPump.extendedBolusDuration, - preferences.get(DanaBooleanKey.DanaRUseExtended), + preferences.get(DanaBooleanKey.UseExtended), danaPump.extendedBolusStart, pumpDescription.pumpType, serialNumber() diff --git a/pump/danar/src/main/kotlin/app/aaps/pump/danar/DanaRPlugin.kt b/pump/danar/src/main/kotlin/app/aaps/pump/danar/DanaRPlugin.kt index 29453208f6d..2ed9a901ae0 100644 --- a/pump/danar/src/main/kotlin/app/aaps/pump/danar/DanaRPlugin.kt +++ b/pump/danar/src/main/kotlin/app/aaps/pump/danar/DanaRPlugin.kt @@ -40,7 +40,7 @@ import app.aaps.core.interfaces.utils.Round.ceilTo import app.aaps.core.interfaces.utils.Round.floorTo import app.aaps.core.interfaces.utils.Round.roundTo import app.aaps.core.interfaces.utils.fabric.FabricPrivacy -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.constraints.ConstraintObject import app.aaps.core.ui.toast.ToastUtils import app.aaps.core.validators.DefaultEditTextValidator @@ -65,34 +65,34 @@ import kotlin.math.max @Singleton class DanaRPlugin @Inject constructor( aapsLogger: AAPSLogger, + rh: ResourceHelper, + preferences: Preferences, + commandQueue: CommandQueue, aapsSchedulers: AapsSchedulers, rxBus: RxBus, private val context: Context, - rh: ResourceHelper, constraintsChecker: ConstraintsChecker, activePlugin: ActivePlugin, - commandQueue: CommandQueue, danaPump: DanaPump, dateUtil: DateUtil, private val fabricPrivacy: FabricPrivacy, pumpSync: PumpSync, - preferences: Preferences, uiInteraction: UiInteraction, danaHistoryDatabase: DanaHistoryDatabase, decimalFormatter: DecimalFormatter, instantiator: Instantiator ) : AbstractDanaRPlugin( danaPump, + aapsLogger, rh, + preferences, + commandQueue, constraintsChecker, - aapsLogger, aapsSchedulers, - commandQueue, rxBus, activePlugin, dateUtil, pumpSync, - preferences, uiInteraction, danaHistoryDatabase, decimalFormatter, @@ -123,7 +123,7 @@ class DanaRPlugin @Inject constructor( .toObservable(EventPreferenceChange::class.java) .observeOn(aapsSchedulers.io) .subscribe({ - if (it.isChanged(DanaBooleanKey.DanaRUseExtended.key)) { + if (it.isChanged(DanaBooleanKey.UseExtended.key)) { if (pumpSync.expectedPumpState().extendedBolus != null) { executionService?.extendedBolusStop() } @@ -147,7 +147,7 @@ class DanaRPlugin @Inject constructor( get() = rh.gs(app.aaps.pump.dana.R.string.danarpump) override val isFakingTempsByExtendedBoluses: Boolean // Pump interface - get() = preferences.get(DanaBooleanKey.DanaRUseExtended) + get() = preferences.get(DanaBooleanKey.UseExtended) override fun isInitialized(): Boolean { return danaPump.lastConnection > 0 && danaPump.isExtendedBolusEnabled && danaPump.maxBasal > 0 && danaPump.isPasswordOK @@ -215,8 +215,8 @@ class DanaRPlugin @Inject constructor( absoluteRateReq = constraintChecker.applyBasalConstraints(ConstraintObject(absoluteRateReq, aapsLogger), profile).value() var doTempOff = baseBasalRate - absoluteRateReq == 0.0 && absoluteRateReq >= 0.10 val doLowTemp = absoluteRateReq < baseBasalRate || absoluteRateReq < 0.10 - val doHighTemp = absoluteRateReq > baseBasalRate && !preferences.get(DanaBooleanKey.DanaRUseExtended) - val doExtendedTemp = absoluteRateReq > baseBasalRate && preferences.get(DanaBooleanKey.DanaRUseExtended) + val doHighTemp = absoluteRateReq > baseBasalRate && !preferences.get(DanaBooleanKey.UseExtended) + val doExtendedTemp = absoluteRateReq > baseBasalRate && preferences.get(DanaBooleanKey.UseExtended) var percentRate = (absoluteRateReq / baseBasalRate * 100).toInt() // Any basal less than 0.10u/h will be dumped once per hour, not every 4 minutes. So if it's less than .10u/h, set a zero temp. if (absoluteRateReq < 0.10) percentRate = 0 @@ -229,7 +229,7 @@ class DanaRPlugin @Inject constructor( if (percentRate == 100) doTempOff = true if (doTempOff) { // If extended in progress - if (danaPump.isExtendedInProgress && preferences.get(DanaBooleanKey.DanaRUseExtended)) { + if (danaPump.isExtendedInProgress && preferences.get(DanaBooleanKey.UseExtended)) { aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: Stopping extended bolus (doTempOff)") return cancelExtendedBolus() } @@ -244,7 +244,7 @@ class DanaRPlugin @Inject constructor( } if (doLowTemp || doHighTemp) { // If extended in progress - if (danaPump.isExtendedInProgress && preferences.get(DanaBooleanKey.DanaRUseExtended)) { + if (danaPump.isExtendedInProgress && preferences.get(DanaBooleanKey.UseExtended)) { aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: Stopping extended bolus (doLowTemp || doHighTemp)") result = cancelExtendedBolus() if (!result.success) { @@ -325,7 +325,7 @@ class DanaRPlugin @Inject constructor( override fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult { if (danaPump.isTempBasalInProgress) return cancelRealTempBasal() - if (danaPump.isExtendedInProgress && preferences.get(DanaBooleanKey.DanaRUseExtended)) { + if (danaPump.isExtendedInProgress && preferences.get(DanaBooleanKey.UseExtended)) { return cancelExtendedBolus() } val result = instantiator.providePumpEnactResult() @@ -385,10 +385,19 @@ class DanaRPlugin @Inject constructor( key = "danar_settings" title = rh.gs(app.aaps.pump.dana.R.string.danar_pump_settings) initialExpandedChildrenCount = 0 - addPreference(AdaptiveListPreference(ctx = context, stringKey = DanaStringKey.DanaRName, title = app.aaps.pump.dana.R.string.danar_bt_name_title, dialogTitle = app.aaps.pump.dana.R.string.danar_bt_name_title, entries = entries, entryValues = entries)) + addPreference( + AdaptiveListPreference( + ctx = context, + stringKey = DanaStringKey.RName, + title = app.aaps.pump.dana.R.string.danar_bt_name_title, + dialogTitle = app.aaps.pump.dana.R.string.danar_bt_name_title, + entries = entries, + entryValues = entries + ) + ) addPreference( AdaptiveIntPreference( - ctx = context, intKey = DanaIntKey.DanaRPassword, title = app.aaps.pump.dana.R.string.danar_password_title, + ctx = context, intKey = DanaIntKey.Password, title = app.aaps.pump.dana.R.string.danar_password_title, validatorParams = DefaultEditTextValidator.Parameters( testType = EditTextValidator.TEST_REGEXP, customRegexp = rh.gs(app.aaps.core.validators.R.string.fourdigitnumber), @@ -396,8 +405,17 @@ class DanaRPlugin @Inject constructor( ) ) ) - addPreference(AdaptiveListIntPreference(ctx = context, intKey = DanaIntKey.DanaBolusSpeed, title = app.aaps.pump.dana.R.string.bolusspeed, dialogTitle = app.aaps.pump.dana.R.string.bolusspeed, entries = speedEntries, entryValues = speedValues)) - addPreference(AdaptiveSwitchPreference(ctx = context, booleanKey = DanaBooleanKey.DanaRUseExtended, title = app.aaps.pump.dana.R.string.danar_useextended_title)) + addPreference( + AdaptiveListIntPreference( + ctx = context, + intKey = DanaIntKey.BolusSpeed, + title = app.aaps.pump.dana.R.string.bolusspeed, + dialogTitle = app.aaps.pump.dana.R.string.bolusspeed, + entries = speedEntries, + entryValues = speedValues + ) + ) + addPreference(AdaptiveSwitchPreference(ctx = context, booleanKey = DanaBooleanKey.UseExtended, title = app.aaps.pump.dana.R.string.danar_useextended_title)) } } } diff --git a/pump/danar/src/main/kotlin/app/aaps/pump/danar/services/AbstractDanaRExecutionService.kt b/pump/danar/src/main/kotlin/app/aaps/pump/danar/services/AbstractDanaRExecutionService.kt index 12e0a8162dc..dff0e1f7ded 100644 --- a/pump/danar/src/main/kotlin/app/aaps/pump/danar/services/AbstractDanaRExecutionService.kt +++ b/pump/danar/src/main/kotlin/app/aaps/pump/danar/services/AbstractDanaRExecutionService.kt @@ -30,7 +30,7 @@ import app.aaps.core.interfaces.rx.events.EventPumpStatusChanged import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.fabric.FabricPrivacy -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.ui.toast.ToastUtils.errorToast import app.aaps.pump.dana.DanaPump import app.aaps.pump.dana.R @@ -163,7 +163,7 @@ abstract class AbstractDanaRExecutionService : DaggerService() { } protected fun getBTSocketForSelectedPump() { - mDevName = preferences.get(DanaStringKey.DanaRName) + mDevName = preferences.get(DanaStringKey.RName) if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S || ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) { val bluetoothAdapter = (context.getSystemService(BLUETOOTH_SERVICE) as BluetoothManager).adapter if (bluetoothAdapter != null) { diff --git a/pump/danar/src/main/kotlin/app/aaps/pump/danar/services/DanaRExecutionService.kt b/pump/danar/src/main/kotlin/app/aaps/pump/danar/services/DanaRExecutionService.kt index db276d74fc2..18d1ecfe2cd 100644 --- a/pump/danar/src/main/kotlin/app/aaps/pump/danar/services/DanaRExecutionService.kt +++ b/pump/danar/src/main/kotlin/app/aaps/pump/danar/services/DanaRExecutionService.kt @@ -230,7 +230,7 @@ class DanaRExecutionService : AbstractDanaRExecutionService() { if (stopPressed) return false danaPump.bolusingTreatment = t danaPump.bolusDone = false - val preferencesSpeed = preferences.get(DanaIntKey.DanaBolusSpeed) + val preferencesSpeed = preferences.get(DanaIntKey.BolusSpeed) val start: MessageBase = if (preferencesSpeed == 0) MsgBolusStart(injector, amount) else MsgBolusStartWithSpeed(injector, amount, preferencesSpeed) danaPump.bolusStopped = false danaPump.bolusStopForced = false diff --git a/pump/danar/src/main/kotlin/app/aaps/pump/danarkorean/DanaRKoreanPlugin.kt b/pump/danar/src/main/kotlin/app/aaps/pump/danarkorean/DanaRKoreanPlugin.kt index d3beab7547e..759f295f133 100644 --- a/pump/danar/src/main/kotlin/app/aaps/pump/danarkorean/DanaRKoreanPlugin.kt +++ b/pump/danar/src/main/kotlin/app/aaps/pump/danarkorean/DanaRKoreanPlugin.kt @@ -38,7 +38,7 @@ import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.DecimalFormatter import app.aaps.core.interfaces.utils.Round import app.aaps.core.interfaces.utils.fabric.FabricPrivacy -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.constraints.ConstraintObject import app.aaps.core.ui.toast.ToastUtils import app.aaps.core.validators.DefaultEditTextValidator @@ -81,16 +81,16 @@ class DanaRKoreanPlugin @Inject constructor( instantiator: Instantiator ) : AbstractDanaRPlugin( danaPump, + aapsLogger, rh, + preferences, + commandQueue, constraintChecker, - aapsLogger, aapsSchedulers, - commandQueue, rxBus, activePlugin, dateUtil, pumpSync, - preferences, uiInteraction, danaHistoryDatabase, decimalFormatter, @@ -108,7 +108,7 @@ class DanaRKoreanPlugin @Inject constructor( .toObservable(EventPreferenceChange::class.java) .observeOn(aapsSchedulers.io) .subscribe({ - if (it.isChanged(DanaBooleanKey.DanaRUseExtended.key)) { + if (it.isChanged(DanaBooleanKey.UseExtended.key)) { if (pumpSync.expectedPumpState().extendedBolus != null) { executionService?.extendedBolusStop() } @@ -146,7 +146,7 @@ class DanaRKoreanPlugin @Inject constructor( // Pump interface override val isFakingTempsByExtendedBoluses: Boolean - get() = preferences.get(DanaBooleanKey.DanaRUseExtended) + get() = preferences.get(DanaBooleanKey.UseExtended) override fun isInitialized(): Boolean = danaPump.lastConnection > 0 && danaPump.maxBasal > 0 && !danaPump.isConfigUD && !danaPump.isEasyModeEnabled && danaPump.isExtendedBolusEnabled && danaPump.isPasswordOK @@ -203,8 +203,8 @@ class DanaRKoreanPlugin @Inject constructor( val absoluteRateAfterConstraint = constraintChecker.applyBasalConstraints(ConstraintObject(absoluteRate, aapsLogger), profile).value() var doTempOff = baseBasalRate - absoluteRateAfterConstraint == 0.0 && absoluteRateAfterConstraint >= 0.10 val doLowTemp = absoluteRateAfterConstraint < baseBasalRate || absoluteRateAfterConstraint < 0.10 - val doHighTemp = absoluteRateAfterConstraint > baseBasalRate && !preferences.get(DanaBooleanKey.DanaRUseExtended) - val doExtendedTemp = absoluteRateAfterConstraint > baseBasalRate && preferences.get(DanaBooleanKey.DanaRUseExtended) + val doHighTemp = absoluteRateAfterConstraint > baseBasalRate && !preferences.get(DanaBooleanKey.UseExtended) + val doExtendedTemp = absoluteRateAfterConstraint > baseBasalRate && preferences.get(DanaBooleanKey.UseExtended) var percentRate: Int = java.lang.Double.valueOf(absoluteRateAfterConstraint / baseBasalRate * 100).toInt() // Any basal less than 0.10u/h will be dumped once per hour, not every 4 minutes. So if it's less than .10u/h, set a zero temp. @@ -219,7 +219,7 @@ class DanaRKoreanPlugin @Inject constructor( if (doTempOff) { // If extended in progress - if (danaPump.isExtendedInProgress && preferences.get(DanaBooleanKey.DanaRUseExtended)) { + if (danaPump.isExtendedInProgress && preferences.get(DanaBooleanKey.UseExtended)) { aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: Stopping extended bolus (doTempOff)") return cancelExtendedBolus() } @@ -233,7 +233,7 @@ class DanaRKoreanPlugin @Inject constructor( } if (doLowTemp || doHighTemp) { // If extended in progress - if (danaPump.isExtendedInProgress && preferences.get(DanaBooleanKey.DanaRUseExtended)) { + if (danaPump.isExtendedInProgress && preferences.get(DanaBooleanKey.UseExtended)) { aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: Stopping extended bolus (doLowTemp || doHighTemp)") val result = cancelExtendedBolus() if (!result.success) { @@ -312,7 +312,7 @@ class DanaRKoreanPlugin @Inject constructor( override fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult { if (danaPump.isTempBasalInProgress) return cancelRealTempBasal() - if (danaPump.isExtendedInProgress && preferences.get(DanaBooleanKey.DanaRUseExtended)) { + if (danaPump.isExtendedInProgress && preferences.get(DanaBooleanKey.UseExtended)) { return cancelExtendedBolus() } val result = instantiator.providePumpEnactResult() @@ -364,10 +364,19 @@ class DanaRKoreanPlugin @Inject constructor( key = "danar_korean_settings" title = rh.gs(app.aaps.pump.dana.R.string.danar_pump_settings) initialExpandedChildrenCount = 0 - addPreference(AdaptiveListPreference(ctx = context, stringKey = DanaStringKey.DanaRName, title = app.aaps.pump.dana.R.string.danar_bt_name_title, dialogTitle = app.aaps.pump.dana.R.string.danar_bt_name_title, entries = entries, entryValues = entries)) + addPreference( + AdaptiveListPreference( + ctx = context, + stringKey = DanaStringKey.RName, + title = app.aaps.pump.dana.R.string.danar_bt_name_title, + dialogTitle = app.aaps.pump.dana.R.string.danar_bt_name_title, + entries = entries, + entryValues = entries + ) + ) addPreference( AdaptiveIntPreference( - ctx = context, intKey = DanaIntKey.DanaRPassword, title = app.aaps.pump.dana.R.string.danar_password_title, + ctx = context, intKey = DanaIntKey.Password, title = app.aaps.pump.dana.R.string.danar_password_title, validatorParams = DefaultEditTextValidator.Parameters( testType = EditTextValidator.TEST_REGEXP, customRegexp = rh.gs(app.aaps.core.validators.R.string.fourdigitnumber), @@ -375,7 +384,7 @@ class DanaRKoreanPlugin @Inject constructor( ) ) ) - addPreference(AdaptiveSwitchPreference(ctx = context, booleanKey = DanaBooleanKey.DanaRUseExtended, title = app.aaps.pump.dana.R.string.danar_useextended_title)) + addPreference(AdaptiveSwitchPreference(ctx = context, booleanKey = DanaBooleanKey.UseExtended, title = app.aaps.pump.dana.R.string.danar_useextended_title)) } } } \ No newline at end of file diff --git a/pump/danar/src/main/kotlin/app/aaps/pump/danarv2/DanaRv2Plugin.kt b/pump/danar/src/main/kotlin/app/aaps/pump/danarv2/DanaRv2Plugin.kt index 29a471502f5..4e0eb65745f 100644 --- a/pump/danar/src/main/kotlin/app/aaps/pump/danarv2/DanaRv2Plugin.kt +++ b/pump/danar/src/main/kotlin/app/aaps/pump/danarv2/DanaRv2Plugin.kt @@ -42,7 +42,7 @@ import app.aaps.core.interfaces.utils.Round.ceilTo import app.aaps.core.interfaces.utils.Round.floorTo import app.aaps.core.interfaces.utils.Round.roundTo import app.aaps.core.interfaces.utils.fabric.FabricPrivacy -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.constraints.ConstraintObject import app.aaps.core.ui.toast.ToastUtils import app.aaps.core.validators.DefaultEditTextValidator @@ -88,16 +88,16 @@ class DanaRv2Plugin @Inject constructor( instantiator: Instantiator ) : AbstractDanaRPlugin( danaPump, + aapsLogger, rh, + preferences, + commandQueue, constraintChecker, - aapsLogger, aapsSchedulers, - commandQueue, rxBus, activePlugin, dateUtil, pumpSync, - preferences, uiInteraction, danaHistoryDatabase, decimalFormatter, @@ -163,7 +163,7 @@ class DanaRv2Plugin @Inject constructor( detailedBolusInfo.insulin = constraintChecker.applyBolusConstraints(ConstraintObject(detailedBolusInfo.insulin, aapsLogger)).value() // v2 stores end time for bolus, we need to adjust time // default delivery speed is 12 sec/U - val preferencesSpeed = preferences.get(DanaIntKey.DanaBolusSpeed) + val preferencesSpeed = preferences.get(DanaIntKey.BolusSpeed) var speed = 12 when (preferencesSpeed) { 0 -> speed = 12 @@ -347,7 +347,7 @@ class DanaRv2Plugin @Inject constructor( .duration(pump.extendedBolusRemainingMinutes) .absolute(pump.extendedBolusAbsoluteRate) .isPercent(false) - if (!preferences.get(DanaBooleanKey.DanaRUseExtended)) result.bolusDelivered(pump.extendedBolusAmount) + if (!preferences.get(DanaBooleanKey.UseExtended)) result.bolusDelivered(pump.extendedBolusAmount) aapsLogger.debug(LTag.PUMP, "setExtendedBolus: OK") return result } @@ -400,10 +400,10 @@ class DanaRv2Plugin @Inject constructor( key = "danar_v2_settings" title = rh.gs(R.string.danar_pump_settings) initialExpandedChildrenCount = 0 - addPreference(AdaptiveListPreference(ctx = context, stringKey = DanaStringKey.DanaRName, title = R.string.danar_bt_name_title, dialogTitle = R.string.danar_bt_name_title, entries = entries, entryValues = entries)) + addPreference(AdaptiveListPreference(ctx = context, stringKey = DanaStringKey.RName, title = R.string.danar_bt_name_title, dialogTitle = R.string.danar_bt_name_title, entries = entries, entryValues = entries)) addPreference( AdaptiveIntPreference( - ctx = context, intKey = DanaIntKey.DanaRPassword, title = R.string.danar_password_title, + ctx = context, intKey = DanaIntKey.Password, title = R.string.danar_password_title, validatorParams = DefaultEditTextValidator.Parameters( testType = EditTextValidator.TEST_REGEXP, customRegexp = rh.gs(app.aaps.core.validators.R.string.fourdigitnumber), @@ -411,7 +411,7 @@ class DanaRv2Plugin @Inject constructor( ) ) ) - addPreference(AdaptiveListIntPreference(ctx = context, intKey = DanaIntKey.DanaBolusSpeed, title = R.string.bolusspeed, dialogTitle = R.string.bolusspeed, entries = speedEntries, entryValues = speedValues)) + addPreference(AdaptiveListIntPreference(ctx = context, intKey = DanaIntKey.BolusSpeed, title = R.string.bolusspeed, dialogTitle = R.string.bolusspeed, entries = speedEntries, entryValues = speedValues)) } } } diff --git a/pump/danar/src/main/kotlin/app/aaps/pump/danarv2/services/DanaRv2ExecutionService.kt b/pump/danar/src/main/kotlin/app/aaps/pump/danarv2/services/DanaRv2ExecutionService.kt index c526f813e5d..3df75530669 100644 --- a/pump/danar/src/main/kotlin/app/aaps/pump/danarv2/services/DanaRv2ExecutionService.kt +++ b/pump/danar/src/main/kotlin/app/aaps/pump/danarv2/services/DanaRv2ExecutionService.kt @@ -289,7 +289,7 @@ class DanaRv2ExecutionService : AbstractDanaRExecutionService() { rxBus.send(EventPumpStatusChanged(rh.gs(R.string.startingbolus))) danaPump.bolusingTreatment = t danaPump.bolusDone = false - val preferencesSpeed = preferences.get(DanaIntKey.DanaBolusSpeed) + val preferencesSpeed = preferences.get(DanaIntKey.BolusSpeed) val start: MessageBase = if (preferencesSpeed == 0) MsgBolusStart(injector, amount) else MsgBolusStartWithSpeed(injector, amount, preferencesSpeed) danaPump.bolusStopped = false danaPump.bolusStopForced = false diff --git a/pump/danar/src/test/kotlin/app/aaps/pump/danaR/DanaRPluginTest.kt b/pump/danar/src/test/kotlin/app/aaps/pump/danaR/DanaRPluginTest.kt index 6951b13e451..fe3a0492894 100644 --- a/pump/danar/src/test/kotlin/app/aaps/pump/danaR/DanaRPluginTest.kt +++ b/pump/danar/src/test/kotlin/app/aaps/pump/danaR/DanaRPluginTest.kt @@ -1,21 +1,11 @@ package app.aaps.pump.danaR -import android.content.SharedPreferences import app.aaps.core.data.plugin.PluginType import app.aaps.core.interfaces.constraints.ConstraintsChecker import app.aaps.core.interfaces.pump.PumpSync import app.aaps.core.interfaces.queue.CommandQueue import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.objects.constraints.ConstraintObject -import app.aaps.core.validators.preferences.AdaptiveClickPreference -import app.aaps.core.validators.preferences.AdaptiveDoublePreference -import app.aaps.core.validators.preferences.AdaptiveIntPreference -import app.aaps.core.validators.preferences.AdaptiveIntentPreference -import app.aaps.core.validators.preferences.AdaptiveListIntPreference -import app.aaps.core.validators.preferences.AdaptiveListPreference -import app.aaps.core.validators.preferences.AdaptiveStringPreference -import app.aaps.core.validators.preferences.AdaptiveSwitchPreference -import app.aaps.core.validators.preferences.AdaptiveUnitPreference import app.aaps.pump.dana.DanaPump import app.aaps.pump.dana.database.DanaHistoryDatabase import app.aaps.pump.dana.keys.DanaStringKey @@ -30,76 +20,28 @@ import org.mockito.Mockito.`when` class DanaRPluginTest : TestBaseWithProfile() { - @Mock lateinit var sharedPrefs: SharedPreferences @Mock lateinit var constraintChecker: ConstraintsChecker @Mock lateinit var commandQueue: CommandQueue @Mock lateinit var pumpSync: PumpSync @Mock lateinit var uiInteraction: UiInteraction @Mock lateinit var danaHistoryDatabase: DanaHistoryDatabase - lateinit var danaPump: DanaPump private lateinit var danaRPlugin: DanaRPlugin - init { - addInjector { - if (it is AdaptiveDoublePreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveIntPreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - it.config = config - } - if (it is AdaptiveIntentPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveUnitPreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveSwitchPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - it.config = config - } - if (it is AdaptiveStringPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveListPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveListIntPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveClickPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - } - } - @BeforeEach fun prepareMocks() { - `when`(preferences.get(DanaStringKey.DanaMacAddress)).thenReturn("") - `when`(preferences.get(DanaStringKey.DanaRName)).thenReturn("") + `when`(preferences.get(DanaStringKey.MacAddress)).thenReturn("") + `when`(preferences.get(DanaStringKey.RName)).thenReturn("") `when`(rh.gs(app.aaps.core.ui.R.string.pumplimit)).thenReturn("pump limit") `when`(rh.gs(app.aaps.core.ui.R.string.itmustbepositivevalue)).thenReturn("it must be positive value") `when`(rh.gs(app.aaps.core.ui.R.string.limitingbasalratio)).thenReturn("Limiting max basal rate to %1\$.2f U/h because of %2\$s") `when`(rh.gs(app.aaps.core.ui.R.string.limitingpercentrate)).thenReturn("Limiting max percent rate to %1\$d%% because of %2\$s") danaPump = DanaPump(aapsLogger, preferences, dateUtil, instantiator, decimalFormatter) danaRPlugin = DanaRPlugin( - aapsLogger, aapsSchedulers, rxBus, context, rh, constraintChecker, activePlugin, commandQueue, danaPump, dateUtil, fabricPrivacy, pumpSync, - preferences, uiInteraction, danaHistoryDatabase, decimalFormatter, instantiator + aapsLogger, rh, preferences, commandQueue, aapsSchedulers, rxBus, context, constraintChecker, activePlugin, danaPump, dateUtil, fabricPrivacy, pumpSync, + uiInteraction, danaHistoryDatabase, decimalFormatter, instantiator ) } diff --git a/pump/danar/src/test/kotlin/app/aaps/pump/danaRKorean/DanaRKoreanPluginTest.kt b/pump/danar/src/test/kotlin/app/aaps/pump/danaRKorean/DanaRKoreanPluginTest.kt index 87d7ea39e30..1c300203ce5 100644 --- a/pump/danar/src/test/kotlin/app/aaps/pump/danaRKorean/DanaRKoreanPluginTest.kt +++ b/pump/danar/src/test/kotlin/app/aaps/pump/danaRKorean/DanaRKoreanPluginTest.kt @@ -1,21 +1,11 @@ package app.aaps.pump.danaRKorean -import android.content.SharedPreferences import app.aaps.core.data.plugin.PluginType import app.aaps.core.interfaces.constraints.ConstraintsChecker import app.aaps.core.interfaces.pump.PumpSync import app.aaps.core.interfaces.queue.CommandQueue import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.objects.constraints.ConstraintObject -import app.aaps.core.validators.preferences.AdaptiveClickPreference -import app.aaps.core.validators.preferences.AdaptiveDoublePreference -import app.aaps.core.validators.preferences.AdaptiveIntPreference -import app.aaps.core.validators.preferences.AdaptiveIntentPreference -import app.aaps.core.validators.preferences.AdaptiveListIntPreference -import app.aaps.core.validators.preferences.AdaptiveListPreference -import app.aaps.core.validators.preferences.AdaptiveStringPreference -import app.aaps.core.validators.preferences.AdaptiveSwitchPreference -import app.aaps.core.validators.preferences.AdaptiveUnitPreference import app.aaps.pump.dana.DanaPump import app.aaps.pump.dana.database.DanaHistoryDatabase import app.aaps.pump.dana.keys.DanaStringKey @@ -30,7 +20,6 @@ import org.mockito.Mockito.`when` class DanaRKoreanPluginTest : TestBaseWithProfile() { - @Mock lateinit var sharedPrefs: SharedPreferences @Mock lateinit var constraintChecker: ConstraintsChecker @Mock lateinit var commandQueue: CommandQueue @Mock lateinit var pumpSync: PumpSync @@ -41,56 +30,10 @@ class DanaRKoreanPluginTest : TestBaseWithProfile() { private lateinit var danaRPlugin: DanaRKoreanPlugin - init { - addInjector { - if (it is AdaptiveDoublePreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveIntPreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - it.config = config - } - if (it is AdaptiveIntentPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveUnitPreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveSwitchPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - it.config = config - } - if (it is AdaptiveStringPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveListPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveListIntPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveClickPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - } - } - @BeforeEach fun prepareMocks() { - `when`(preferences.get(DanaStringKey.DanaMacAddress)).thenReturn("") - `when`(preferences.get(DanaStringKey.DanaRName)).thenReturn("") + `when`(preferences.get(DanaStringKey.MacAddress)).thenReturn("") + `when`(preferences.get(DanaStringKey.RName)).thenReturn("") `when`(rh.gs(app.aaps.core.ui.R.string.pumplimit)).thenReturn("pump limit") `when`(rh.gs(app.aaps.core.ui.R.string.itmustbepositivevalue)).thenReturn("it must be positive value") `when`(rh.gs(app.aaps.core.ui.R.string.limitingbasalratio)).thenReturn("Limiting max basal rate to %1\$.2f U/h because of %2\$s") diff --git a/pump/danar/src/test/kotlin/app/aaps/pump/danaRv2/DanaRv2PluginTest.kt b/pump/danar/src/test/kotlin/app/aaps/pump/danaRv2/DanaRv2PluginTest.kt index 101d033c511..8d3c3015703 100644 --- a/pump/danar/src/test/kotlin/app/aaps/pump/danaRv2/DanaRv2PluginTest.kt +++ b/pump/danar/src/test/kotlin/app/aaps/pump/danaRv2/DanaRv2PluginTest.kt @@ -1,6 +1,5 @@ package app.aaps.pump.danaRv2 -import android.content.SharedPreferences import app.aaps.core.data.plugin.PluginType import app.aaps.core.interfaces.constraints.ConstraintsChecker import app.aaps.core.interfaces.pump.DetailedBolusInfoStorage @@ -9,15 +8,6 @@ import app.aaps.core.interfaces.pump.TemporaryBasalStorage import app.aaps.core.interfaces.queue.CommandQueue import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.objects.constraints.ConstraintObject -import app.aaps.core.validators.preferences.AdaptiveClickPreference -import app.aaps.core.validators.preferences.AdaptiveDoublePreference -import app.aaps.core.validators.preferences.AdaptiveIntPreference -import app.aaps.core.validators.preferences.AdaptiveIntentPreference -import app.aaps.core.validators.preferences.AdaptiveListIntPreference -import app.aaps.core.validators.preferences.AdaptiveListPreference -import app.aaps.core.validators.preferences.AdaptiveStringPreference -import app.aaps.core.validators.preferences.AdaptiveSwitchPreference -import app.aaps.core.validators.preferences.AdaptiveUnitPreference import app.aaps.pump.dana.DanaPump import app.aaps.pump.dana.database.DanaHistoryDatabase import app.aaps.pump.dana.keys.DanaStringKey @@ -32,7 +22,6 @@ import org.mockito.Mockito.`when` class DanaRv2PluginTest : TestBaseWithProfile() { - @Mock lateinit var sharedPrefs: SharedPreferences @Mock lateinit var constraintChecker: ConstraintsChecker @Mock lateinit var commandQueue: CommandQueue @Mock lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage @@ -45,56 +34,10 @@ class DanaRv2PluginTest : TestBaseWithProfile() { private lateinit var danaRv2Plugin: DanaRv2Plugin - init { - addInjector { - if (it is AdaptiveDoublePreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveIntPreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - it.config = config - } - if (it is AdaptiveIntentPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveUnitPreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveSwitchPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - it.config = config - } - if (it is AdaptiveStringPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveListPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveListIntPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - if (it is AdaptiveClickPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPrefs - } - } - } - @BeforeEach fun prepareMocks() { - `when`(preferences.get(DanaStringKey.DanaRName)).thenReturn("") - `when`(preferences.get(DanaStringKey.DanaMacAddress)).thenReturn("") + `when`(preferences.get(DanaStringKey.RName)).thenReturn("") + `when`(preferences.get(DanaStringKey.MacAddress)).thenReturn("") `when`(rh.gs(app.aaps.core.ui.R.string.pumplimit)).thenReturn("pump limit") `when`(rh.gs(app.aaps.core.ui.R.string.itmustbepositivevalue)).thenReturn("it must be positive value") `when`(rh.gs(app.aaps.core.ui.R.string.limitingbasalratio)).thenReturn("Limiting max basal rate to %1\$.2f U/h because of %2\$s") diff --git a/pump/danars/src/main/kotlin/app/aaps/pump/danars/DanaRSPlugin.kt b/pump/danars/src/main/kotlin/app/aaps/pump/danars/DanaRSPlugin.kt index 127e4716b30..721d0d42be7 100644 --- a/pump/danars/src/main/kotlin/app/aaps/pump/danars/DanaRSPlugin.kt +++ b/pump/danars/src/main/kotlin/app/aaps/pump/danars/DanaRSPlugin.kt @@ -49,7 +49,7 @@ import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.DecimalFormatter import app.aaps.core.interfaces.utils.Round import app.aaps.core.interfaces.utils.fabric.FabricPrivacy -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.constraints.ConstraintObject import app.aaps.core.ui.toast.ToastUtils import app.aaps.core.validators.DefaultEditTextValidator @@ -66,7 +66,7 @@ import app.aaps.pump.dana.keys.DanaBooleanKey import app.aaps.pump.dana.keys.DanaIntKey import app.aaps.pump.dana.keys.DanaIntentKey import app.aaps.pump.dana.keys.DanaLongKey -import app.aaps.pump.dana.keys.DanaString2Key +import app.aaps.pump.dana.keys.DanaStringComposedKey import app.aaps.pump.dana.keys.DanaStringKey import app.aaps.pump.danars.activities.BLEScanActivity import app.aaps.pump.danars.events.EventDanaRSDeviceChange @@ -83,16 +83,16 @@ import kotlin.math.max @Singleton class DanaRSPlugin @Inject constructor( aapsLogger: AAPSLogger, + rh: ResourceHelper, + preferences: Preferences, + commandQueue: CommandQueue, private val aapsSchedulers: AapsSchedulers, private val rxBus: RxBus, private val context: Context, - rh: ResourceHelper, private val constraintChecker: ConstraintsChecker, private val profileFunction: ProfileFunction, - commandQueue: CommandQueue, private val danaPump: DanaPump, private val pumpSync: PumpSync, - private val preferences: Preferences, private val detailedBolusInfoStorage: DetailedBolusInfoStorage, private val temporaryBasalStorage: TemporaryBasalStorage, private val fabricPrivacy: FabricPrivacy, @@ -102,7 +102,7 @@ class DanaRSPlugin @Inject constructor( private val decimalFormatter: DecimalFormatter, private val instantiator: Instantiator ) : PumpPluginBase( - PluginDescription() + pluginDescription = PluginDescription() .mainType(PluginType.PUMP) .fragmentClass(DanaFragment::class.java.name) .pluginIcon(app.aaps.core.ui.R.drawable.ic_danai_128) @@ -111,7 +111,8 @@ class DanaRSPlugin @Inject constructor( .shortName(app.aaps.pump.dana.R.string.danarspump_shortname) .preferencesId(PluginDescription.PREFERENCE_SCREEN) .description(app.aaps.pump.dana.R.string.description_pump_dana_rs), - aapsLogger, rh, commandQueue + ownPreferences = listOf(DanaStringKey::class.java, DanaIntKey::class.java, DanaBooleanKey::class.java, DanaIntentKey::class.java, DanaStringComposedKey::class.java, DanaLongKey::class.java), + aapsLogger, rh, preferences, commandQueue ), Pump, Dana, PluginConstraints, OwnDatabasePlugin { private val disposable = CompositeDisposable() @@ -119,24 +120,14 @@ class DanaRSPlugin @Inject constructor( private var mDeviceAddress = "" var mDeviceName = "" - // Make plugin preferences available to AAPS - init { - preferences.registerPreferences(DanaStringKey::class.java) - preferences.registerPreferences(DanaIntKey::class.java) - preferences.registerPreferences(DanaBooleanKey::class.java) - preferences.registerPreferences(DanaIntentKey::class.java) - preferences.registerPreferences(DanaString2Key::class.java) - preferences.registerPreferences(DanaLongKey::class.java) - } - override val pumpDescription get() = PumpDescription().fillFor(danaPump.pumpType()) override fun updatePreferenceSummary(pref: Preference) { super.updatePreferenceSummary(pref) - if (pref.key == DanaStringKey.DanaRsName.key) { - val value = preferences.getIfExists(DanaStringKey.DanaRsName) + if (pref.key == DanaStringKey.RsName.key) { + val value = preferences.getIfExists(DanaStringKey.RsName) pref.summary = value ?: rh.gs(app.aaps.core.ui.R.string.not_set_short) } } @@ -183,9 +174,9 @@ class DanaRSPlugin @Inject constructor( } fun changePump() { - mDeviceAddress = preferences.get(DanaStringKey.DanaMacAddress) - mDeviceName = preferences.get(DanaStringKey.DanaRsName) - danaPump.serialNumber = preferences.get(DanaStringKey.DanaRsName) + mDeviceAddress = preferences.get(DanaStringKey.MacAddress) + mDeviceName = preferences.get(DanaStringKey.RsName) + danaPump.serialNumber = preferences.get(DanaStringKey.RsName) danaPump.reset() commandQueue.readStatus(rh.gs(app.aaps.core.ui.R.string.device_changed), null) } @@ -321,7 +312,7 @@ class DanaRSPlugin @Inject constructor( require(detailedBolusInfo.insulin > 0) { detailedBolusInfo.toString() } detailedBolusInfo.insulin = constraintChecker.applyBolusConstraints(ConstraintObject(detailedBolusInfo.insulin, aapsLogger)).value() - val preferencesSpeed = preferences.get(DanaIntKey.DanaBolusSpeed) + val preferencesSpeed = preferences.get(DanaIntKey.BolusSpeed) var speed = 12 when (preferencesSpeed) { 0 -> speed = 12 @@ -665,11 +656,11 @@ class DanaRSPlugin @Inject constructor( override fun canHandleDST(): Boolean = false override fun clearPairing() { aapsLogger.debug(LTag.PUMPCOMM, "Pairing keys cleared") - preferences.remove(DanaString2Key.DanaRsParingKey, mDeviceName) - preferences.remove(DanaString2Key.DanaRsV3RandomParingKey, mDeviceName) - preferences.remove(DanaString2Key.DanaRsV3ParingKey, mDeviceName) - preferences.remove(DanaString2Key.DanaRsV3RandomSyncKey, mDeviceName) - preferences.remove(DanaString2Key.DanaRsBle5PairingKey, mDeviceName) + preferences.remove(DanaStringComposedKey.ParingKey, mDeviceName) + preferences.remove(DanaStringComposedKey.V3RandomParingKey, mDeviceName) + preferences.remove(DanaStringComposedKey.V3ParingKey, mDeviceName) + preferences.remove(DanaStringComposedKey.V3RandomSyncKey, mDeviceName) + preferences.remove(DanaStringComposedKey.Ble5PairingKey, mDeviceName) } override fun clearAllTables() = danaHistoryDatabase.clearAllTables() @@ -688,13 +679,13 @@ class DanaRSPlugin @Inject constructor( initialExpandedChildrenCount = 0 addPreference( AdaptiveIntentPreference( - ctx = context, intentKey = DanaIntentKey.DanaRsBtSelector, title = app.aaps.pump.dana.R.string.selectedpump, + ctx = context, intentKey = DanaIntentKey.BtSelector, title = app.aaps.pump.dana.R.string.selectedpump, intent = Intent(context, BLEScanActivity::class.java) ) ) addPreference( AdaptiveStringPreference( - ctx = context, stringKey = DanaStringKey.DanaRsPassword, title = app.aaps.pump.dana.R.string.danars_password_title, + ctx = context, stringKey = DanaStringKey.Password, title = app.aaps.pump.dana.R.string.danars_password_title, validatorParams = DefaultEditTextValidator.Parameters( testType = EditTextValidator.TEST_REGEXP, customRegexp = rh.gs(app.aaps.core.validators.R.string.fourhexanumber), @@ -705,15 +696,15 @@ class DanaRSPlugin @Inject constructor( addPreference( AdaptiveListIntPreference( ctx = context, - intKey = DanaIntKey.DanaBolusSpeed, + intKey = DanaIntKey.BolusSpeed, title = app.aaps.pump.dana.R.string.bolusspeed, dialogTitle = app.aaps.pump.dana.R.string.bolusspeed, entries = speedEntries, entryValues = speedValues ) ) - addPreference(AdaptiveSwitchPreference(ctx = context, booleanKey = DanaBooleanKey.DanaRsLogInsulinChange, title = app.aaps.pump.dana.R.string.rs_loginsulinchange_title, summary = app.aaps.pump.dana.R.string.rs_loginsulinchange_summary)) - addPreference(AdaptiveSwitchPreference(ctx = context, booleanKey = DanaBooleanKey.DanaRsLogCannulaChange, title = app.aaps.pump.dana.R.string.rs_logcanulachange_title, summary = app.aaps.pump.dana.R.string.rs_logcanulachange_summary)) + addPreference(AdaptiveSwitchPreference(ctx = context, booleanKey = DanaBooleanKey.LogInsulinChange, title = app.aaps.pump.dana.R.string.rs_loginsulinchange_title, summary = app.aaps.pump.dana.R.string.rs_loginsulinchange_summary)) + addPreference(AdaptiveSwitchPreference(ctx = context, booleanKey = DanaBooleanKey.LogCannulaChange, title = app.aaps.pump.dana.R.string.rs_logcanulachange_title, summary = app.aaps.pump.dana.R.string.rs_logcanulachange_summary)) } } } \ No newline at end of file diff --git a/pump/danars/src/main/kotlin/app/aaps/pump/danars/activities/BLEScanActivity.kt b/pump/danars/src/main/kotlin/app/aaps/pump/danars/activities/BLEScanActivity.kt index 3d74495ba3b..ff05f0d2fa9 100644 --- a/pump/danars/src/main/kotlin/app/aaps/pump/danars/activities/BLEScanActivity.kt +++ b/pump/danars/src/main/kotlin/app/aaps/pump/danars/activities/BLEScanActivity.kt @@ -23,7 +23,7 @@ import androidx.core.app.ActivityCompat import app.aaps.core.interfaces.pump.BlePreCheck import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.bus.RxBus -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.ui.activities.TranslatedDaggerAppCompatActivity import app.aaps.core.ui.toast.ToastUtils import app.aaps.core.utils.extensions.safeEnable @@ -149,8 +149,8 @@ class BLEScanActivity : TranslatedDaggerAppCompatActivity() { } override fun onClick(v: View) { - preferences.put(DanaStringKey.DanaMacAddress, item.device.address) - preferences.put(DanaStringKey.DanaRsName, name.text.toString()) + preferences.put(DanaStringKey.MacAddress, item.device.address) + preferences.put(DanaStringKey.RsName, name.text.toString()) if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S || ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) { item.device.createBond() rxBus.send(EventDanaRSDeviceChange()) diff --git a/pump/danars/src/main/kotlin/app/aaps/pump/danars/activities/EnterPinActivity.kt b/pump/danars/src/main/kotlin/app/aaps/pump/danars/activities/EnterPinActivity.kt index 06b3f873b6b..5dbc677dab2 100644 --- a/pump/danars/src/main/kotlin/app/aaps/pump/danars/activities/EnterPinActivity.kt +++ b/pump/danars/src/main/kotlin/app/aaps/pump/danars/activities/EnterPinActivity.kt @@ -7,13 +7,13 @@ import app.aaps.core.interfaces.rx.AapsSchedulers import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventPumpStatusChanged import app.aaps.core.interfaces.utils.fabric.FabricPrivacy -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.ui.activities.TranslatedDaggerAppCompatActivity import app.aaps.core.ui.dialogs.OKDialog import app.aaps.core.utils.hexStringToByteArray import app.aaps.core.validators.DefaultEditTextValidator import app.aaps.core.validators.EditTextValidator -import app.aaps.pump.dana.keys.DanaString2Key +import app.aaps.pump.dana.keys.DanaStringComposedKey import app.aaps.pump.danars.DanaRSPlugin import app.aaps.pump.danars.databinding.DanarsEnterPinActivityBinding import app.aaps.pump.danars.services.BLEComm @@ -89,12 +89,12 @@ class EnterPinActivity : TranslatedDaggerAppCompatActivity() { for (i in pairingKey.indices) pairingKeyCheckSum = pairingKeyCheckSum xor pairingKey[i] - preferences.put(DanaString2Key.DanaRsV3ParingKey, danaRSPlugin.mDeviceName, Base64.encodeToString(pairingKey, Base64.DEFAULT)) + preferences.put(DanaStringComposedKey.V3ParingKey, danaRSPlugin.mDeviceName, value = Base64.encodeToString(pairingKey, Base64.DEFAULT)) for (i in randomPairingKey.indices) pairingKeyCheckSum = pairingKeyCheckSum xor randomPairingKey[i] - preferences.put(DanaString2Key.DanaRsV3RandomParingKey, danaRSPlugin.mDeviceName, Base64.encodeToString(randomPairingKey, Base64.DEFAULT)) + preferences.put(DanaStringComposedKey.V3RandomParingKey, danaRSPlugin.mDeviceName, value = Base64.encodeToString(randomPairingKey, Base64.DEFAULT)) return checksum[0] == pairingKeyCheckSum } diff --git a/pump/danars/src/main/kotlin/app/aaps/pump/danars/comm/DanaRSPacketAPSHistoryEvents.kt b/pump/danars/src/main/kotlin/app/aaps/pump/danars/comm/DanaRSPacketAPSHistoryEvents.kt index b3fe4d20a5e..4cefd5f9f02 100644 --- a/pump/danars/src/main/kotlin/app/aaps/pump/danars/comm/DanaRSPacketAPSHistoryEvents.kt +++ b/pump/danars/src/main/kotlin/app/aaps/pump/danars/comm/DanaRSPacketAPSHistoryEvents.kt @@ -9,7 +9,7 @@ import app.aaps.core.interfaces.pump.TemporaryBasalStorage import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventPumpStatusChanged -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.dana.DanaPump import app.aaps.pump.dana.R import app.aaps.pump.dana.keys.DanaBooleanKey @@ -288,7 +288,7 @@ open class DanaRSPacketAPSHistoryEvents( } DanaPump.HistoryEntry.REFILL -> { - if (preferences.get(DanaBooleanKey.DanaRsLogInsulinChange)) { + if (preferences.get(DanaBooleanKey.LogInsulinChange)) { val newRecord = pumpSync.insertTherapyEventIfNewWithTimestamp( timestamp = datetime, type = TE.Type.INSULIN_CHANGE, @@ -336,7 +336,7 @@ open class DanaRSPacketAPSHistoryEvents( } DanaPump.HistoryEntry.PRIME_CANNULA -> { - if (preferences.get(DanaBooleanKey.DanaRsLogCannulaChange)) { + if (preferences.get(DanaBooleanKey.LogCannulaChange)) { val newRecord = pumpSync.insertTherapyEventIfNewWithTimestamp( timestamp = datetime, type = TE.Type.CANNULA_CHANGE, diff --git a/pump/danars/src/main/kotlin/app/aaps/pump/danars/services/BLEComm.kt b/pump/danars/src/main/kotlin/app/aaps/pump/danars/services/BLEComm.kt index 626dc2d2a63..3f38daf0db9 100644 --- a/pump/danars/src/main/kotlin/app/aaps/pump/danars/services/BLEComm.kt +++ b/pump/danars/src/main/kotlin/app/aaps/pump/danars/services/BLEComm.kt @@ -29,14 +29,14 @@ import app.aaps.core.interfaces.rx.events.EventDismissNotification import app.aaps.core.interfaces.rx.events.EventPumpStatusChanged import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.interfaces.utils.DateUtil -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.ui.toast.ToastUtils import app.aaps.core.utils.notifyAll import app.aaps.core.utils.waitMillis import app.aaps.pump.dana.DanaPump import app.aaps.pump.dana.R import app.aaps.pump.dana.keys.DanaLongKey -import app.aaps.pump.dana.keys.DanaString2Key +import app.aaps.pump.dana.keys.DanaStringComposedKey import app.aaps.pump.dana.keys.DanaStringKey import app.aaps.pump.danars.DanaRSPlugin import app.aaps.pump.danars.activities.EnterPinActivity @@ -168,30 +168,30 @@ class BLEComm @Inject internal constructor( if (!encryptedDataRead && encryptedCommandSent && encryption == EncryptionType.ENCRYPTION_BLE5) { // there was no response from pump after started encryption // assume pairing keys are invalid - val lastClearRequest = preferences.get(DanaLongKey.DanaRsLastClearKeyRequest) + val lastClearRequest = preferences.get(DanaLongKey.LastClearKeyRequest) if (lastClearRequest != 0L && dateUtil.isOlderThan(lastClearRequest, 5)) { ToastUtils.errorToast(context, R.string.invalidpairing) danaRSPlugin.changePump() removeBond() } else if (lastClearRequest == 0L) { aapsLogger.error(LTag.PUMPBTCOMM, "Clearing pairing keys postponed") - preferences.put(DanaLongKey.DanaRsLastClearKeyRequest, dateUtil.now()) + preferences.put(DanaLongKey.LastClearKeyRequest, dateUtil.now()) } } if (!encryptedDataRead && encryptedCommandSent && encryption == EncryptionType.ENCRYPTION_RSv3) { // there was no response from pump after started encryption // assume pairing keys are invalid - val lastClearRequest = preferences.get(DanaLongKey.DanaRsLastClearKeyRequest) + val lastClearRequest = preferences.get(DanaLongKey.LastClearKeyRequest) if (lastClearRequest != 0L && dateUtil.isOlderThan(lastClearRequest, 5)) { aapsLogger.error(LTag.PUMPBTCOMM, "Clearing pairing keys !!!") - preferences.remove(DanaString2Key.DanaRsV3RandomParingKey, danaRSPlugin.mDeviceName) - preferences.remove(DanaString2Key.DanaRsV3ParingKey, danaRSPlugin.mDeviceName) - preferences.remove(DanaString2Key.DanaRsV3RandomSyncKey, danaRSPlugin.mDeviceName) + preferences.remove(DanaStringComposedKey.V3RandomParingKey, danaRSPlugin.mDeviceName) + preferences.remove(DanaStringComposedKey.V3ParingKey, danaRSPlugin.mDeviceName) + preferences.remove(DanaStringComposedKey.V3RandomSyncKey, danaRSPlugin.mDeviceName) ToastUtils.errorToast(context, R.string.invalidpairing) danaRSPlugin.changePump() } else if (lastClearRequest == 0L) { aapsLogger.error(LTag.PUMPBTCOMM, "Clearing pairing keys postponed") - preferences.put(DanaLongKey.DanaRsLastClearKeyRequest, dateUtil.now()) + preferences.put(DanaLongKey.LastClearKeyRequest, dateUtil.now()) } } // cancel previous scheduled disconnection to prevent closing upcoming connection @@ -212,7 +212,7 @@ class BLEComm @Inject internal constructor( } private fun removeBond() { - preferences.getIfExists(DanaStringKey.DanaMacAddress)?.let { address -> + preferences.getIfExists(DanaStringKey.MacAddress)?.let { address -> bluetoothAdapter?.getRemoteDevice(address)?.let { device -> try { device.javaClass.getMethod("removeBond").invoke(device) @@ -404,7 +404,7 @@ class BLEComm @Inject internal constructor( if (isConnected && (encryption == EncryptionType.ENCRYPTION_RSv3 || encryption == EncryptionType.ENCRYPTION_BLE5)) bleEncryption.decryptSecondLevelPacket(receivedData).also { encryptedDataRead = true - preferences.put(DanaLongKey.DanaRsLastClearKeyRequest, 0L) + preferences.put(DanaLongKey.LastClearKeyRequest, 0L) } else receivedData addToReadBuffer(incomingBuffer) @@ -533,7 +533,7 @@ class BLEComm @Inject internal constructor( encryption = EncryptionType.ENCRYPTION_DEFAULT danaPump.ignoreUserPassword = false // Grab pairing key from preferences if exists - val pairingKey = preferences.get(DanaString2Key.DanaRsParingKey, danaRSPlugin.mDeviceName) + val pairingKey = preferences.get(DanaStringComposedKey.ParingKey, danaRSPlugin.mDeviceName) aapsLogger.debug(LTag.PUMPBTCOMM, "Using stored pairing key: $pairingKey") if (pairingKey.isNotEmpty()) { sendPasskeyCheck(pairingKey) @@ -549,7 +549,7 @@ class BLEComm @Inject internal constructor( danaPump.hwModel = decryptedBuffer[5].toInt() danaPump.protocol = decryptedBuffer[7].toInt() // grab randomSyncKey - preferences.put(DanaString2Key.DanaRsV3RandomSyncKey, danaRSPlugin.mDeviceName, String.format("%02x", decryptedBuffer[decryptedBuffer.size - 1])) + preferences.put(DanaStringComposedKey.V3RandomSyncKey, danaRSPlugin.mDeviceName, value = String.format("%02x", decryptedBuffer[decryptedBuffer.size - 1])) if (danaPump.hwModel == 0x05) { aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + "ENCRYPTION__PUMP_CHECK V3 (OK)" + " " + DanaRSPacket.toHexString(decryptedBuffer)) @@ -569,9 +569,9 @@ class BLEComm @Inject internal constructor( danaPump.protocol = decryptedBuffer[7].toInt() val pairingKey = DanaRSPacket.asciiStringFromBuff(decryptedBuffer, 8, 6) // used while bonding if (decryptedBuffer[8] != 0.toByte()) - preferences.put(DanaString2Key.DanaRsBle5PairingKey, danaRSPlugin.mDeviceName, pairingKey) + preferences.put(DanaStringComposedKey.Ble5PairingKey, danaRSPlugin.mDeviceName, value = pairingKey) - val storedPairingKey = preferences.get(DanaString2Key.DanaRsBle5PairingKey, danaRSPlugin.mDeviceName) + val storedPairingKey = preferences.get(DanaStringComposedKey.Ble5PairingKey, danaRSPlugin.mDeviceName) if (storedPairingKey.isBlank()) { removeBond() disconnect("Non existing pairing key") @@ -625,13 +625,13 @@ class BLEComm @Inject internal constructor( // 2nd packet v3 // 0x00 Start encryption, 0x01 Request pairing private fun sendV3PairingInformation() { - val randomPairingKey = preferences.get(DanaString2Key.DanaRsV3RandomParingKey, danaRSPlugin.mDeviceName) - val pairingKey = preferences.get(DanaString2Key.DanaRsV3ParingKey, danaRSPlugin.mDeviceName) + val randomPairingKey = preferences.get(DanaStringComposedKey.V3RandomParingKey, danaRSPlugin.mDeviceName) + val pairingKey = preferences.get(DanaStringComposedKey.V3ParingKey, danaRSPlugin.mDeviceName) if (randomPairingKey.isNotEmpty() && pairingKey.isNotEmpty()) { val tPairingKey = Base64.decode(pairingKey, Base64.DEFAULT) val tRandomPairingKey = Base64.decode(randomPairingKey, Base64.DEFAULT) var tRandomSyncKey: Byte = 0 - val randomSyncKey = preferences.get(DanaString2Key.DanaRsV3RandomSyncKey, danaRSPlugin.mDeviceName) + val randomSyncKey = preferences.get(DanaStringComposedKey.V3RandomSyncKey, danaRSPlugin.mDeviceName) if (randomSyncKey.isNotEmpty()) { tRandomSyncKey = randomSyncKey.toInt(16).toByte() } @@ -667,8 +667,8 @@ class BLEComm @Inject internal constructor( } else if (encryption == EncryptionType.ENCRYPTION_RSv3) { // decryptedBuffer[2] : 0x00 OK 0x01 Error, No pairing if (decryptedBuffer[2] == 0x00.toByte()) { - val randomPairingKey = preferences.get(DanaString2Key.DanaRsV3RandomParingKey, danaRSPlugin.mDeviceName) - val pairingKey = preferences.get(DanaString2Key.DanaRsV3ParingKey, danaRSPlugin.mDeviceName) + val randomPairingKey = preferences.get(DanaStringComposedKey.V3RandomParingKey, danaRSPlugin.mDeviceName) + val pairingKey = preferences.get(DanaStringComposedKey.V3ParingKey, danaRSPlugin.mDeviceName) if (randomPairingKey.isNotEmpty() && pairingKey.isNotEmpty()) { // expecting successful connect isConnected = true @@ -723,8 +723,8 @@ class BLEComm @Inject internal constructor( // 3rd packet v3 : only after entering PIN codes fun finishV3Pairing() { - val randomPairingKey = preferences.get(DanaString2Key.DanaRsV3RandomParingKey, danaRSPlugin.mDeviceName) - val pairingKey = preferences.get(DanaString2Key.DanaRsV3ParingKey, danaRSPlugin.mDeviceName) + val randomPairingKey = preferences.get(DanaStringComposedKey.V3RandomParingKey, danaRSPlugin.mDeviceName) + val pairingKey = preferences.get(DanaStringComposedKey.V3ParingKey, danaRSPlugin.mDeviceName) if (randomPairingKey.isNotEmpty() && pairingKey.isNotEmpty()) { val tPairingKey = Base64.decode(pairingKey, Base64.DEFAULT) val tRandomPairingKey = Base64.decode(randomPairingKey, Base64.DEFAULT) @@ -750,7 +750,7 @@ class BLEComm @Inject internal constructor( sendTimeInfo() val pairingKey = byteArrayOf(decryptedBuffer[2], decryptedBuffer[3]) // store pairing key to preferences - preferences.put(DanaString2Key.DanaRsParingKey, danaRSPlugin.mDeviceName, DanaRSPacket.bytesToHex(pairingKey)) + preferences.put(DanaStringComposedKey.ParingKey, danaRSPlugin.mDeviceName, value = DanaRSPacket.bytesToHex(pairingKey)) aapsLogger.debug(LTag.PUMPBTCOMM, "Got pairing key: " + DanaRSPacket.bytesToHex(pairingKey)) } diff --git a/pump/danars/src/main/kotlin/app/aaps/pump/danars/services/DanaRSService.kt b/pump/danars/src/main/kotlin/app/aaps/pump/danars/services/DanaRSService.kt index 60f8ce00709..1c315ebfe5c 100644 --- a/pump/danars/src/main/kotlin/app/aaps/pump/danars/services/DanaRSService.kt +++ b/pump/danars/src/main/kotlin/app/aaps/pump/danars/services/DanaRSService.kt @@ -32,7 +32,7 @@ import app.aaps.core.interfaces.rx.events.EventPumpStatusChanged import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.fabric.FabricPrivacy -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.dana.DanaPump import app.aaps.pump.dana.R import app.aaps.pump.dana.comm.RecordTypes @@ -289,7 +289,7 @@ class DanaRSService : DaggerService() { if (!isConnected) return false if (BolusProgressData.stopPressed) return false rxBus.send(EventPumpStatusChanged(rh.gs(R.string.startingbolus))) - val preferencesSpeed = preferences.get(DanaIntKey.DanaBolusSpeed) + val preferencesSpeed = preferences.get(DanaIntKey.BolusSpeed) danaPump.bolusDone = false danaPump.bolusingTreatment = t danaPump.bolusAmountToBeDelivered = insulin diff --git a/pump/danars/src/test/kotlin/app/aaps/pump/danars/DanaRSPluginTest.kt b/pump/danars/src/test/kotlin/app/aaps/pump/danars/DanaRSPluginTest.kt index ca0013e6008..d8aa2ef4e32 100644 --- a/pump/danars/src/test/kotlin/app/aaps/pump/danars/DanaRSPluginTest.kt +++ b/pump/danars/src/test/kotlin/app/aaps/pump/danars/DanaRSPluginTest.kt @@ -1,6 +1,5 @@ package app.aaps.pump.danars -import android.content.SharedPreferences import app.aaps.core.data.plugin.PluginType import app.aaps.core.interfaces.constraints.ConstraintsChecker import app.aaps.core.interfaces.pump.DetailedBolusInfoStorage @@ -8,15 +7,6 @@ import app.aaps.core.interfaces.pump.PumpSync import app.aaps.core.interfaces.pump.TemporaryBasalStorage import app.aaps.core.interfaces.queue.CommandQueue import app.aaps.core.objects.constraints.ConstraintObject -import app.aaps.core.validators.preferences.AdaptiveClickPreference -import app.aaps.core.validators.preferences.AdaptiveDoublePreference -import app.aaps.core.validators.preferences.AdaptiveIntPreference -import app.aaps.core.validators.preferences.AdaptiveIntentPreference -import app.aaps.core.validators.preferences.AdaptiveListIntPreference -import app.aaps.core.validators.preferences.AdaptiveListPreference -import app.aaps.core.validators.preferences.AdaptiveStringPreference -import app.aaps.core.validators.preferences.AdaptiveSwitchPreference -import app.aaps.core.validators.preferences.AdaptiveUnitPreference import app.aaps.pump.dana.database.DanaHistoryDatabase import app.aaps.pump.dana.keys.DanaStringKey import com.google.common.truth.Truth.assertThat @@ -30,7 +20,6 @@ import org.mockito.Mockito @Suppress("SpellCheckingInspection") class DanaRSPluginTest : DanaRSTestBase() { - @Mock lateinit var sharedPreferences: SharedPreferences @Mock lateinit var constraintChecker: ConstraintsChecker @Mock lateinit var commandQueue: CommandQueue @Mock lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage @@ -40,53 +29,6 @@ class DanaRSPluginTest : DanaRSTestBase() { private lateinit var danaRSPlugin: DanaRSPlugin - init { - addInjector { - if (it is AdaptiveDoublePreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPreferences - } - if (it is AdaptiveIntPreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPreferences - it.config = config - } - if (it is AdaptiveIntentPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPreferences - } - if (it is AdaptiveUnitPreference) { - it.profileUtil = profileUtil - it.preferences = preferences - it.sharedPrefs = sharedPreferences - } - if (it is AdaptiveSwitchPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPreferences - it.config = config - } - if (it is AdaptiveStringPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPreferences - } - if (it is AdaptiveListPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPreferences - } - if (it is AdaptiveListIntPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPreferences - } - if (it is AdaptiveClickPreference) { - it.preferences = preferences - it.sharedPrefs = sharedPreferences - } - } - } - - @Test fun basalRateShouldBeLimited() { danaRSPlugin.setPluginEnabled(PluginType.PUMP, true) @@ -113,32 +55,15 @@ class DanaRSPluginTest : DanaRSTestBase() { @BeforeEach fun prepareMocks() { - Mockito.`when`(preferences.get(DanaStringKey.DanaRsName)).thenReturn("") - Mockito.`when`(preferences.get(DanaStringKey.DanaMacAddress)).thenReturn("") + Mockito.`when`(preferences.get(DanaStringKey.RsName)).thenReturn("") + Mockito.`when`(preferences.get(DanaStringKey.MacAddress)).thenReturn("") Mockito.`when`(rh.gs(eq(app.aaps.core.ui.R.string.limitingbasalratio), anyObject(), anyObject())).thenReturn("limitingbasalratio") Mockito.`when`(rh.gs(eq(app.aaps.core.ui.R.string.limitingpercentrate), anyObject(), anyObject())).thenReturn("limitingpercentrate") danaRSPlugin = DanaRSPlugin( - aapsLogger, - aapsSchedulers, - rxBus, - context, - rh, - constraintChecker, - profileFunction, - commandQueue, - danaPump, - pumpSync, - preferences, - detailedBolusInfoStorage, - temporaryBasalStorage, - fabricPrivacy, - dateUtil, - uiInteraction, - danaHistoryDatabase, - decimalFormatter, - instantiator + aapsLogger, rh, preferences, commandQueue, aapsSchedulers, rxBus, context, constraintChecker, profileFunction, danaPump, pumpSync, detailedBolusInfoStorage, temporaryBasalStorage, + fabricPrivacy, dateUtil, uiInteraction, danaHistoryDatabase, decimalFormatter, instantiator ) } diff --git a/pump/danars/src/test/kotlin/app/aaps/pump/danars/comm/DanaRsPacketBolusSetStepBolusStartTest.kt b/pump/danars/src/test/kotlin/app/aaps/pump/danars/comm/DanaRsPacketBolusSetStepBolusStartTest.kt index 7a5e46c87e9..f75944ce3e9 100644 --- a/pump/danars/src/test/kotlin/app/aaps/pump/danars/comm/DanaRsPacketBolusSetStepBolusStartTest.kt +++ b/pump/danars/src/test/kotlin/app/aaps/pump/danars/comm/DanaRsPacketBolusSetStepBolusStartTest.kt @@ -56,25 +56,9 @@ class DanaRsPacketBolusSetStepBolusStartTest : DanaRSTestBase() { fun mock() { danaRSPlugin = DanaRSPlugin( - aapsLogger, - aapsSchedulers, - rxBus, - context, - rh, - constraintChecker, - profileFunction, - commandQueue, - danaPump, - pumpSync, - preferences, - detailedBolusInfoStorage, - temporaryBasalStorage, - fabricPrivacy, - dateUtil, - uiInteraction, - danaHistoryDatabase, - decimalFormatter, - instantiator + aapsLogger, rh, preferences, commandQueue, aapsSchedulers, rxBus, context, constraintChecker, profileFunction, danaPump, + pumpSync, detailedBolusInfoStorage, temporaryBasalStorage, fabricPrivacy, dateUtil, uiInteraction, danaHistoryDatabase, + decimalFormatter, instantiator ) Mockito.`when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(ConstraintObject(0.0, aapsLogger)) } diff --git a/pump/danars/src/test/kotlin/app/aaps/pump/danars/comm/DanaRsPacketNotifyDeliveryRateDisplayTest.kt b/pump/danars/src/test/kotlin/app/aaps/pump/danars/comm/DanaRsPacketNotifyDeliveryRateDisplayTest.kt index dffdb12097f..8bb588cce0e 100644 --- a/pump/danars/src/test/kotlin/app/aaps/pump/danars/comm/DanaRsPacketNotifyDeliveryRateDisplayTest.kt +++ b/pump/danars/src/test/kotlin/app/aaps/pump/danars/comm/DanaRsPacketNotifyDeliveryRateDisplayTest.kt @@ -60,25 +60,8 @@ class DanaRsPacketNotifyDeliveryRateDisplayTest : DanaRSTestBase() { fun mock() { danaRSPlugin = DanaRSPlugin( - aapsLogger, - aapsSchedulers, - rxBus, - context, - rh, - constraintChecker, - profileFunction, - commandQueue, - danaPump, - pumpSync, - preferences, - detailedBolusInfoStorage, - temporaryBasalStorage, - fabricPrivacy, - dateUtil, - uiInteraction, - danaHistoryDatabase, - decimalFormatter, - instantiator + aapsLogger, rh, preferences, commandQueue, aapsSchedulers, rxBus, context, constraintChecker, profileFunction, danaPump, pumpSync, + detailedBolusInfoStorage, temporaryBasalStorage, fabricPrivacy, dateUtil, uiInteraction, danaHistoryDatabase, decimalFormatter, instantiator ) danaPump.bolusingTreatment = EventOverviewBolusProgress.Treatment(0.0, 0, true, 0) } diff --git a/pump/diaconn/build.gradle.kts b/pump/diaconn/build.gradle.kts index 86334c16ba6..41c0c200dc1 100644 --- a/pump/diaconn/build.gradle.kts +++ b/pump/diaconn/build.gradle.kts @@ -21,10 +21,12 @@ android { dependencies { implementation(project(":core:data")) implementation(project(":core:interfaces")) + implementation(project(":core:keys")) implementation(project(":core:libraries")) implementation(project(":core:objects")) implementation(project(":core:utils")) implementation(project(":core:ui")) + implementation(project(":core:validators")) implementation(project(":shared:impl")) api(libs.androidx.room) diff --git a/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/DiaconnG8Fragment.kt b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/DiaconnG8Fragment.kt index a168be0e81c..9ff1020fcc9 100644 --- a/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/DiaconnG8Fragment.kt +++ b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/DiaconnG8Fragment.kt @@ -23,7 +23,6 @@ import app.aaps.core.interfaces.rx.events.EventInitializationChanged import app.aaps.core.interfaces.rx.events.EventPumpStatusChanged import app.aaps.core.interfaces.rx.events.EventQueueChanged import app.aaps.core.interfaces.rx.events.EventTempBasalChange -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.fabric.FabricPrivacy @@ -46,7 +45,6 @@ class DiaconnG8Fragment : DaggerFragment() { @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var diaconnG8Pump: DiaconnG8Pump @Inject lateinit var rh: ResourceHelper - @Inject lateinit var sp: SP @Inject lateinit var warnColors: WarnColors @Inject lateinit var dateUtil: DateUtil @Inject lateinit var aapsSchedulers: AapsSchedulers diff --git a/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/DiaconnG8Plugin.kt b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/DiaconnG8Plugin.kt index 9f2972d3a35..4eafcd7b2c5 100644 --- a/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/DiaconnG8Plugin.kt +++ b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/DiaconnG8Plugin.kt @@ -6,8 +6,9 @@ import android.content.Intent import android.content.ServiceConnection import android.os.IBinder import android.text.format.DateFormat -import androidx.preference.Preference -import androidx.preference.PreferenceFragmentCompat +import androidx.preference.PreferenceCategory +import androidx.preference.PreferenceManager +import androidx.preference.PreferenceScreen import app.aaps.core.data.model.BS import app.aaps.core.data.plugin.PluginType import app.aaps.core.data.pump.defs.ManufacturerType @@ -45,16 +46,25 @@ import app.aaps.core.interfaces.rx.events.EventAppExit import app.aaps.core.interfaces.rx.events.EventConfigBuilderChange import app.aaps.core.interfaces.rx.events.EventDismissNotification import app.aaps.core.interfaces.rx.events.EventOverviewBolusProgress -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.DecimalFormatter import app.aaps.core.interfaces.utils.Round import app.aaps.core.interfaces.utils.fabric.FabricPrivacy +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.objects.constraints.ConstraintObject import app.aaps.core.ui.toast.ToastUtils +import app.aaps.core.validators.preferences.AdaptiveIntentPreference +import app.aaps.core.validators.preferences.AdaptiveListIntPreference +import app.aaps.core.validators.preferences.AdaptiveSwitchPreference +import app.aaps.pump.diaconn.activities.DiaconnG8BLEScanActivity import app.aaps.pump.diaconn.database.DiaconnHistoryDatabase import app.aaps.pump.diaconn.events.EventDiaconnG8DeviceChange +import app.aaps.pump.diaconn.keys.DiaconnBooleanKey +import app.aaps.pump.diaconn.keys.DiaconnIntKey +import app.aaps.pump.diaconn.keys.DiaconnIntNonKey +import app.aaps.pump.diaconn.keys.DiaconnIntentKey +import app.aaps.pump.diaconn.keys.DiaconnStringNonKey import app.aaps.pump.diaconn.service.DiaconnG8Service import io.reactivex.rxjava3.disposables.CompositeDisposable import org.json.JSONException @@ -67,13 +77,13 @@ import kotlin.math.max @Singleton class DiaconnG8Plugin @Inject constructor( aapsLogger: AAPSLogger, + rh: ResourceHelper, + preferences: Preferences, + commandQueue: CommandQueue, private val rxBus: RxBus, private val context: Context, - rh: ResourceHelper, private val constraintChecker: ConstraintsChecker, private val profileFunction: ProfileFunction, - private val sp: SP, - commandQueue: CommandQueue, private val diaconnG8Pump: DiaconnG8Pump, private val pumpSync: PumpSync, private val detailedBolusInfoStorage: DetailedBolusInfoStorage, @@ -86,15 +96,19 @@ class DiaconnG8Plugin @Inject constructor( private val decimalFormatter: DecimalFormatter, private val instantiator: Instantiator ) : PumpPluginBase( - PluginDescription() + pluginDescription = PluginDescription() .mainType(PluginType.PUMP) .fragmentClass(DiaconnG8Fragment::class.java.name) .pluginIcon(app.aaps.core.ui.R.drawable.ic_diaconn_g8) .pluginName(R.string.diaconn_g8_pump) .shortName(R.string.diaconn_g8_pump_shortname) - .preferencesId(R.xml.pref_diaconn) + .preferencesId(PluginDescription.PREFERENCE_SCREEN) .description(R.string.description_pump_diaconn_g8), - aapsLogger, rh, commandQueue + ownPreferences = listOf( + DiaconnIntentKey::class.java, DiaconnIntKey::class.java, DiaconnBooleanKey::class.java, + DiaconnStringNonKey::class.java, DiaconnIntNonKey::class.java, + ), + aapsLogger, rh, preferences, commandQueue ), Pump, Diaconn, PluginConstraints, OwnDatabasePlugin { private val disposable = CompositeDisposable() @@ -145,8 +159,8 @@ class DiaconnG8Plugin @Inject constructor( } fun changePump() { - mDeviceAddress = sp.getString(R.string.key_diaconn_g8_address, "") - mDeviceName = sp.getString(R.string.key_diaconn_g8_name, "") + mDeviceAddress = preferences.get(DiaconnStringNonKey.Address) + mDeviceName = preferences.get(DiaconnStringNonKey.Name) diaconnG8Pump.reset() commandQueue.readStatus(rh.gs(app.aaps.core.ui.R.string.device_changed), null) } @@ -561,7 +575,7 @@ class DiaconnG8Plugin @Inject constructor( override fun canHandleDST(): Boolean = false override fun isBatteryChangeLoggingEnabled(): Boolean { - return sp.getBoolean(R.string.key_diaconn_g8_logbatterychange, false) + return preferences.get(DiaconnBooleanKey.LogBatteryChange) } @Synchronized @@ -590,21 +604,27 @@ class DiaconnG8Plugin @Inject constructor( } } - override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) { - - val bolusSpeedPreference: Preference? = preferenceFragment.findPreference(rh.gs(R.string.key_diaconn_g8_bolusspeed)) - bolusSpeedPreference?.setOnPreferenceChangeListener { _, newValue -> - val intBolusSpeed = newValue.toString().toInt() - - diaconnG8Pump.bolusSpeed = intBolusSpeed - diaconnG8Pump.speed = intBolusSpeed - diaconnG8Pump.setUserOptionType = DiaconnG8Pump.BOLUS_SPEED - sp.putBoolean(R.string.key_diaconn_g8_is_bolus_speed_sync, false) + override fun clearAllTables() = diaconnHistoryDatabase.clearAllTables() - true + override fun addPreferenceScreen(preferenceManager: PreferenceManager, parent: PreferenceScreen, context: Context, requiredKey: String?) { + if (requiredKey != null) return + + val speedEntries = arrayOf("1 U/min", "2 U/min", "3 U/min", "4 U/min", "5 U/min", "6 U/min", "7 U/min", "8 U/min") + val speedValues = arrayOf("1", "2", "3", "4", "5", "6", "7", "8") + + val category = PreferenceCategory(context) + parent.addPreference(category) + category.apply { + key = "diaconn_settings" + title = rh.gs(R.string.diaconn_g8_pump) + initialExpandedChildrenCount = 0 + addPreference(AdaptiveIntentPreference(ctx = context, intentKey = DiaconnIntentKey.BtSelector, title = R.string.selectedpump, intent = Intent(context, DiaconnG8BLEScanActivity::class.java))) + addPreference(AdaptiveListIntPreference(ctx = context, intKey = DiaconnIntKey.BolusSpeed, title = R.string.bolusspeed, entries = speedEntries, entryValues = speedValues)) + addPreference(AdaptiveSwitchPreference(ctx = context, booleanKey = DiaconnBooleanKey.LogInsulinChange, title = R.string.diaconn_g8_loginsulinchange_title, summary = R.string.diaconn_g8_loginsulinchange_summary)) + addPreference(AdaptiveSwitchPreference(ctx = context, booleanKey = DiaconnBooleanKey.LogCannulaChange, title = R.string.diaconn_g8_logcanulachange_title, summary = R.string.diaconn_g8_logcanulachange_summary)) + addPreference(AdaptiveSwitchPreference(ctx = context, booleanKey = DiaconnBooleanKey.LogTubeChange, title = R.string.diaconn_g8_logtubechange_title, summary = R.string.diaconn_g8_logtubechange_summary)) + addPreference(AdaptiveSwitchPreference(ctx = context, booleanKey = DiaconnBooleanKey.LogBatteryChange, title = R.string.diaconn_g8_logbatterychange_title, summary = R.string.diaconn_g8_logbatterychange_summary)) + addPreference(AdaptiveSwitchPreference(ctx = context, booleanKey = DiaconnBooleanKey.SendLogsToCloud, title = R.string.diaconn_g8_cloudsend_title, summary = R.string.diaconn_g8_cloudsend_summary)) } } - - override fun clearAllTables() = diaconnHistoryDatabase.clearAllTables() - } diff --git a/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/activities/DiaconnG8BLEScanActivity.kt b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/activities/DiaconnG8BLEScanActivity.kt index c03ba9a0dc0..70bd5fa9697 100644 --- a/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/activities/DiaconnG8BLEScanActivity.kt +++ b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/activities/DiaconnG8BLEScanActivity.kt @@ -25,19 +25,20 @@ import android.widget.TextView import androidx.core.app.ActivityCompat import app.aaps.core.interfaces.pump.BlePreCheck import app.aaps.core.interfaces.rx.bus.RxBus -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.ui.activities.TranslatedDaggerAppCompatActivity import app.aaps.core.ui.toast.ToastUtils import app.aaps.core.utils.extensions.safeEnable import app.aaps.pump.diaconn.R import app.aaps.pump.diaconn.databinding.DiaconnG8BlescannerActivityBinding import app.aaps.pump.diaconn.events.EventDiaconnG8DeviceChange +import app.aaps.pump.diaconn.keys.DiaconnStringNonKey import java.util.UUID import javax.inject.Inject class DiaconnG8BLEScanActivity : TranslatedDaggerAppCompatActivity() { - @Inject lateinit var sp: SP + @Inject lateinit var preferences: Preferences @Inject lateinit var blePreCheck: BlePreCheck @Inject lateinit var context: Context @Inject lateinit var rxBus: RxBus @@ -104,14 +105,14 @@ class DiaconnG8BLEScanActivity : TranslatedDaggerAppCompatActivity() { .build() bluetoothLeScanner?.startScan(filters, settings, mBleScanCallback) - } catch (ignored: IllegalStateException) { + } catch (_: IllegalStateException) { } // ignore BT not on @SuppressLint("MissingPermission") private fun stopScan() = try { bluetoothLeScanner?.stopScan(mBleScanCallback) - } catch (ignored: IllegalStateException) { + } catch (_: IllegalStateException) { } // ignore BT not on private fun addBleDevice(device: BluetoothDevice?) { @@ -172,8 +173,8 @@ class DiaconnG8BLEScanActivity : TranslatedDaggerAppCompatActivity() { @SuppressLint("MissingPermission") override fun onClick(v: View) { - sp.putString(R.string.key_diaconn_g8_address, item.device.address) - sp.putString(R.string.key_diaconn_g8_name, name.text.toString()) + preferences.put(DiaconnStringNonKey.Address, item.device.address) + preferences.put(DiaconnStringNonKey.Name, name.text.toString()) item.device.createBond() rxBus.send(EventDiaconnG8DeviceChange()) finish() @@ -206,7 +207,7 @@ class DiaconnG8BLEScanActivity : TranslatedDaggerAppCompatActivity() { private fun stringEquals(arg1: String, arg2: String): Boolean { return try { arg1 == arg2 - } catch (e: Exception) { + } catch (_: Exception) { false } } diff --git a/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/activities/DiaconnG8UserOptionsActivity.kt b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/activities/DiaconnG8UserOptionsActivity.kt index e33f433a588..42522ebe95f 100644 --- a/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/activities/DiaconnG8UserOptionsActivity.kt +++ b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/activities/DiaconnG8UserOptionsActivity.kt @@ -11,14 +11,15 @@ import app.aaps.core.interfaces.plugin.ActivePlugin import app.aaps.core.interfaces.queue.Callback import app.aaps.core.interfaces.queue.CommandQueue import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.interfaces.utils.fabric.FabricPrivacy +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.ui.activities.TranslatedDaggerAppCompatActivity import app.aaps.core.ui.toast.ToastUtils import app.aaps.pump.diaconn.DiaconnG8Pump import app.aaps.pump.diaconn.R import app.aaps.pump.diaconn.databinding.DiaconnG8UserOptionsActivityBinding +import app.aaps.pump.diaconn.keys.DiaconnIntKey import io.reactivex.rxjava3.disposables.CompositeDisposable import java.text.DecimalFormat import javax.inject.Inject @@ -30,7 +31,7 @@ class DiaconnG8UserOptionsActivity : TranslatedDaggerAppCompatActivity() { @Inject lateinit var diaconnG8Pump: DiaconnG8Pump @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var commandQueue: CommandQueue - @Inject lateinit var sp: SP + @Inject lateinit var preferences: Preferences @Inject lateinit var uiInteraction: UiInteraction @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var rh: ResourceHelper @@ -65,7 +66,7 @@ class DiaconnG8UserOptionsActivity : TranslatedDaggerAppCompatActivity() { binding.saveBolusSpeed.setOnClickListener { onSaveBolusSpeedClick() } - val spBolusSpeed = sp.getString(getString(R.string.key_diaconn_g8_bolusspeed), "5") + val spBolusSpeed = preferences.get(DiaconnIntKey.BolusSpeed) binding.bolusSpeed.setParams(spBolusSpeed.toDouble(), 1.0, 8.0, 1.0, DecimalFormat("1"), true, binding.saveBolusSpeed) @@ -149,9 +150,7 @@ class DiaconnG8UserOptionsActivity : TranslatedDaggerAppCompatActivity() { diaconnG8Pump.bolusSpeed = intSpeed diaconnG8Pump.speed = intSpeed diaconnG8Pump.setUserOptionType = DiaconnG8Pump.BOLUS_SPEED - sp.putString(R.string.key_diaconn_g8_bolusspeed, intSpeed.toString()) - sp.putBoolean(R.string.key_diaconn_g8_is_bolus_speed_sync, false) - + preferences.put(DiaconnIntKey.BolusSpeed, intSpeed) ToastUtils.okToast(context, "Save Success!") } diff --git a/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/keys/DiaconnBooleanKey.kt b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/keys/DiaconnBooleanKey.kt new file mode 100644 index 00000000000..3ebb6b8eebb --- /dev/null +++ b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/keys/DiaconnBooleanKey.kt @@ -0,0 +1,25 @@ +package app.aaps.pump.diaconn.keys + +import app.aaps.core.keys.interfaces.BooleanPreferenceKey + +enum class DiaconnBooleanKey( + override val key: String, + override val defaultValue: Boolean, + override val calculatedDefaultValue: Boolean = false, + override val engineeringModeOnly: Boolean = false, + override val defaultedBySM: Boolean = false, + override val showInApsMode: Boolean = true, + override val showInNsClientMode: Boolean = true, + override val showInPumpControlMode: Boolean = true, + override val dependency: BooleanPreferenceKey? = null, + override val negativeDependency: BooleanPreferenceKey? = null, + override val hideParentScreenIfHidden: Boolean = false, + override val exportable: Boolean = true +) : BooleanPreferenceKey { + + LogInsulinChange("diaconn_g8_loginsulinchange", true), + LogCannulaChange("diaconn_g8_logneedlechange", true), + LogTubeChange("diaconn_g8_logtubechange", true), + LogBatteryChange("diaconn_g8_logbatterychanges", true), + SendLogsToCloud("diaconn_g8_cloudsend", true), +} diff --git a/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/keys/DiaconnIntKey.kt b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/keys/DiaconnIntKey.kt new file mode 100644 index 00000000000..92b95ff9b4a --- /dev/null +++ b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/keys/DiaconnIntKey.kt @@ -0,0 +1,24 @@ +package app.aaps.pump.diaconn.keys + +import app.aaps.core.keys.interfaces.BooleanPreferenceKey +import app.aaps.core.keys.interfaces.IntPreferenceKey + +enum class DiaconnIntKey( + override val key: String, + override val defaultValue: Int, + override val min: Int = Int.MIN_VALUE, + override val max: Int = Int.MAX_VALUE, + override val calculatedDefaultValue: Boolean = false, + override val engineeringModeOnly: Boolean = false, + override val defaultedBySM: Boolean = false, + override val showInApsMode: Boolean = true, + override val showInNsClientMode: Boolean = true, + override val showInPumpControlMode: Boolean = true, + override val dependency: BooleanPreferenceKey? = null, + override val negativeDependency: BooleanPreferenceKey? = null, + override val hideParentScreenIfHidden: Boolean = false, + override val exportable: Boolean = true +) : IntPreferenceKey { + + BolusSpeed("g8_bolusspeed", 5), +} diff --git a/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/keys/DiaconnIntNonKey.kt b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/keys/DiaconnIntNonKey.kt new file mode 100644 index 00000000000..c0bb6f73747 --- /dev/null +++ b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/keys/DiaconnIntNonKey.kt @@ -0,0 +1,13 @@ +package app.aaps.pump.diaconn.keys + +import app.aaps.core.keys.interfaces.IntNonPreferenceKey + +enum class DiaconnIntNonKey( + override val key: String, + override val defaultValue: Int, + override val exportable: Boolean = true +) : IntNonPreferenceKey { + + ApsIncarnationNo("aps_incarnation_no", 65536), + PumpSerialNo("pump_serial_no", 0), +} diff --git a/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/keys/DiaconnIntentKey.kt b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/keys/DiaconnIntentKey.kt new file mode 100644 index 00000000000..c1ca29715fa --- /dev/null +++ b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/keys/DiaconnIntentKey.kt @@ -0,0 +1,19 @@ +package app.aaps.pump.diaconn.keys + +import app.aaps.core.keys.interfaces.BooleanPreferenceKey +import app.aaps.core.keys.interfaces.IntentPreferenceKey + +enum class DiaconnIntentKey( + override val key: String, + override val defaultedBySM: Boolean = false, + override val showInApsMode: Boolean = true, + override val showInNsClientMode: Boolean = true, + override val showInPumpControlMode: Boolean = true, + override val dependency: BooleanPreferenceKey? = null, + override val negativeDependency: BooleanPreferenceKey? = null, + override val hideParentScreenIfHidden: Boolean = false, + override val exportable: Boolean = false +) : IntentPreferenceKey { + + BtSelector(key = "diaconn_bt_selector") +} \ No newline at end of file diff --git a/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/keys/DiaconnStringNonKey.kt b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/keys/DiaconnStringNonKey.kt new file mode 100644 index 00000000000..32d1ac6abfe --- /dev/null +++ b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/keys/DiaconnStringNonKey.kt @@ -0,0 +1,15 @@ +package app.aaps.pump.diaconn.keys + +import app.aaps.core.keys.interfaces.StringNonPreferenceKey + +enum class DiaconnStringNonKey( + override val key: String, + override val defaultValue: String, + override val exportable: Boolean = true +) : StringNonPreferenceKey { + + AppUuid("diaconn_g8_appuid", ""), + PumpVersion("pump_version", ""), + Address("diagonn_g8_address", ""), + Name("Diaconn G8", ""), +} diff --git a/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/packet/BasalLimitInquireResponsePacket.kt b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/packet/BasalLimitInquireResponsePacket.kt index 29c25ce7854..636ea83f7d5 100644 --- a/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/packet/BasalLimitInquireResponsePacket.kt +++ b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/packet/BasalLimitInquireResponsePacket.kt @@ -2,11 +2,11 @@ package app.aaps.pump.diaconn.packet import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.sharedPreferences.SP -import dagger.android.HasAndroidInjector +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.diaconn.DiaconnG8Pump -import app.aaps.pump.diaconn.R +import app.aaps.pump.diaconn.keys.DiaconnStringNonKey import app.aaps.pump.diaconn.pumplog.PumpLogUtil +import dagger.android.HasAndroidInjector import javax.inject.Inject /** @@ -15,7 +15,7 @@ import javax.inject.Inject class BasalLimitInquireResponsePacket(injector: HasAndroidInjector) : DiaconnG8Packet(injector) { @Inject lateinit var diaconnG8Pump: DiaconnG8Pump - @Inject lateinit var sp: SP + @Inject lateinit var preferences: Preferences @Inject lateinit var rh: ResourceHelper init { @@ -38,7 +38,7 @@ class BasalLimitInquireResponsePacket(injector: HasAndroidInjector) : DiaconnG8P return } diaconnG8Pump.maxBasalPerHours = getShortToInt(bufferData).toDouble() / 100.0 // not include tempbasal limit - val pumpFirmwareVersion = sp.getString(rh.gs(R.string.pumpversion), "") + val pumpFirmwareVersion = preferences.get(DiaconnStringNonKey.PumpVersion) if (pumpFirmwareVersion.isNotEmpty() && PumpLogUtil.isPumpVersionGe(pumpFirmwareVersion, 3, 0)) { diaconnG8Pump.maxBasal = diaconnG8Pump.maxBasalPerHours * 2.5 // include tempbasal } else { diff --git a/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/packet/BigAPSMainInfoInquireResponsePacket.kt b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/packet/BigAPSMainInfoInquireResponsePacket.kt index a8b360c3b02..cd630ab0b3b 100644 --- a/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/packet/BigAPSMainInfoInquireResponsePacket.kt +++ b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/packet/BigAPSMainInfoInquireResponsePacket.kt @@ -2,11 +2,11 @@ package app.aaps.pump.diaconn.packet import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.sharedPreferences.SP -import dagger.android.HasAndroidInjector +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.diaconn.DiaconnG8Pump -import app.aaps.pump.diaconn.R +import app.aaps.pump.diaconn.keys.DiaconnStringNonKey import app.aaps.pump.diaconn.pumplog.PumpLogUtil +import dagger.android.HasAndroidInjector import org.joda.time.DateTime import javax.inject.Inject import kotlin.math.floor @@ -20,7 +20,7 @@ class BigAPSMainInfoInquireResponsePacket( ) : DiaconnG8Packet(injector) { @Inject lateinit var diaconnG8Pump: DiaconnG8Pump - @Inject lateinit var sp: SP + @Inject lateinit var preferences: Preferences @Inject lateinit var rh: ResourceHelper init { @@ -75,7 +75,7 @@ class BigAPSMainInfoInquireResponsePacket( diaconnG8Pump.minorVersion = getByteToInt(bufferData) // save current pump firmware version - sp.putString(rh.gs(R.string.pumpversion), diaconnG8Pump.majorVersion.toString() + "." + diaconnG8Pump.minorVersion.toString()) + preferences.put(DiaconnStringNonKey.PumpVersion, diaconnG8Pump.majorVersion.toString() + "." + diaconnG8Pump.minorVersion.toString()) // 5. pump log status diaconnG8Pump.pumpLastLogNum = getShortToInt(bufferData) // last saved log no @@ -215,8 +215,8 @@ class BigAPSMainInfoInquireResponsePacket( diaconnG8Pump.pumpProfiles!![diaconnG8Pump.activeProfile][23] = diaconnG8Pump.baseAmount24 //incarnation no 처리 - diaconnG8Pump.isPumpVersionGe2_63 = PumpLogUtil.isPumpVersionGe(sp.getString(rh.gs(R.string.pumpversion), ""), 2, 63) - diaconnG8Pump.isPumpVersionGe3_53 = PumpLogUtil.isPumpVersionGe(sp.getString(rh.gs(R.string.pumpversion), ""), 3, 53) + diaconnG8Pump.isPumpVersionGe2_63 = PumpLogUtil.isPumpVersionGe(preferences.get(DiaconnStringNonKey.PumpVersion), 2, 63) + diaconnG8Pump.isPumpVersionGe3_53 = PumpLogUtil.isPumpVersionGe(preferences.get(DiaconnStringNonKey.PumpVersion), 3, 53) aapsLogger.debug(LTag.PUMPCOMM, "result > " + diaconnG8Pump.result) aapsLogger.debug(LTag.PUMPCOMM, "systemRemainInsulin > " + diaconnG8Pump.systemRemainInsulin) diff --git a/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/packet/BigLogInquireResponsePacket.kt b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/packet/BigLogInquireResponsePacket.kt index 6ba3851da60..3e657cadc56 100644 --- a/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/packet/BigLogInquireResponsePacket.kt +++ b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/packet/BigLogInquireResponsePacket.kt @@ -15,9 +15,7 @@ import app.aaps.core.interfaces.pump.defs.fillFor import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventPumpStatusChanged -import app.aaps.core.interfaces.sharedPreferences.SP -import app.aaps.shared.impl.extensions.safeGetPackageInfo -import dagger.android.HasAndroidInjector +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.diaconn.DiaconnG8Pump import app.aaps.pump.diaconn.R import app.aaps.pump.diaconn.api.ApiResponse @@ -28,6 +26,8 @@ import app.aaps.pump.diaconn.api.PumpLogDto import app.aaps.pump.diaconn.common.RecordTypes import app.aaps.pump.diaconn.database.DiaconnHistoryRecord import app.aaps.pump.diaconn.database.DiaconnHistoryRecordDao +import app.aaps.pump.diaconn.keys.DiaconnBooleanKey +import app.aaps.pump.diaconn.keys.DiaconnStringNonKey import app.aaps.pump.diaconn.pumplog.LogAlarmBattery import app.aaps.pump.diaconn.pumplog.LogAlarmBlock import app.aaps.pump.diaconn.pumplog.LogAlarmShortAge @@ -54,6 +54,8 @@ import app.aaps.pump.diaconn.pumplog.LogSuspendV2 import app.aaps.pump.diaconn.pumplog.LogTbStartV3 import app.aaps.pump.diaconn.pumplog.LogTbStopV3 import app.aaps.pump.diaconn.pumplog.PumpLogUtil +import app.aaps.shared.impl.extensions.safeGetPackageInfo +import dagger.android.HasAndroidInjector import org.apache.commons.lang3.time.DateUtils import org.joda.time.DateTime import retrofit2.Call @@ -74,7 +76,7 @@ class BigLogInquireResponsePacket( @Inject lateinit var diaconnG8Pump: DiaconnG8Pump @Inject lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage @Inject lateinit var temporaryBasalStorage: TemporaryBasalStorage - @Inject lateinit var sp: SP + @Inject lateinit var preferences: Preferences @Inject lateinit var pumpSync: PumpSync @Inject lateinit var diaconnHistoryRecordDao: DiaconnHistoryRecordDao @Inject lateinit var diaconnLogUploader: DiaconnLogUploader @@ -546,7 +548,7 @@ class BigLogInquireResponsePacket( aapsLogger.debug(LTag.PUMPCOMM, "$logItem ") val logStartDate = DateUtils.parseDate(logItem.dttm, "yyyy-MM-dd HH:mm:ss") val logDateTime = logStartDate.time - if (sp.getBoolean(R.string.key_diaconn_g8_loginsulinchange, true)) { + if (preferences.get(DiaconnBooleanKey.LogInsulinChange)) { val newRecord = pumpSync.insertTherapyEventIfNewWithTimestamp( timestamp = logDateTime, type = TE.Type.INSULIN_CHANGE, @@ -575,7 +577,7 @@ class BigLogInquireResponsePacket( aapsLogger.debug(LTag.PUMPCOMM, "$logItem ") val logStartDate = DateUtils.parseDate(logItem.dttm, "yyyy-MM-dd HH:mm:ss") val logDateTime = logStartDate.time - if (sp.getBoolean(R.string.key_diaconn_g8_logtubechange, true)) { + if (preferences.get(DiaconnBooleanKey.LogTubeChange)) { val newRecord = pumpSync.insertTherapyEventIfNewWithTimestamp( timestamp = logDateTime, type = TE.Type.NOTE, @@ -705,7 +707,7 @@ class BigLogInquireResponsePacket( aapsLogger.debug(LTag.PUMPCOMM, "$logItem ") val logStartDate = DateUtils.parseDate(logItem.dttm, "yyyy-MM-dd HH:mm:ss") val logDateTime = logStartDate.time - if (sp.getBoolean(R.string.key_diaconn_g8_logneedlechange, true)) { + if (preferences.get(DiaconnBooleanKey.LogCannulaChange)) { val newRecord = pumpSync.insertTherapyEventIfNewWithTimestamp( timestamp = logDateTime, type = TE.Type.CANNULA_CHANGE, @@ -872,7 +874,7 @@ class BigLogInquireResponsePacket( diaconnG8HistoryRecord.stringValue = getReasonName(pumpLogKind, logItem.reason) diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) if (logItem.reason == 3.toByte()) { - if (sp.getBoolean(R.string.key_diaconn_g8_logbatterychange, true)) { + if (preferences.get(DiaconnBooleanKey.LogBatteryChange)) { val newRecord = pumpSync.insertTherapyEventIfNewWithTimestamp( timestamp = logDateTime, type = TE.Type.PUMP_BATTERY_CHANGE, @@ -903,10 +905,10 @@ class BigLogInquireResponsePacket( // 플랫폼 동기화이면, if (diaconnG8Pump.isPlatformUploadStarted) { aapsLogger.debug(LTag.PUMPCOMM, "Diaconn api upload start!!") - var appUid: String = sp.getString(R.string.key_diaconn_g8_appuid, "") + var appUid: String = preferences.get(DiaconnStringNonKey.AppUuid) if (appUid.isEmpty()) { appUid = UUID.randomUUID().toString() - sp.putString(R.string.key_diaconn_g8_appuid, appUid) + preferences.put(DiaconnStringNonKey.AppUuid, appUid) } //api send val retrofit = diaconnLogUploader.getRetrofitInstance() diff --git a/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/packet/BigMainInfoInquireResponsePacket.kt b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/packet/BigMainInfoInquireResponsePacket.kt index 39d6e50c85d..ced2d1b2dd4 100644 --- a/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/packet/BigMainInfoInquireResponsePacket.kt +++ b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/packet/BigMainInfoInquireResponsePacket.kt @@ -2,11 +2,11 @@ package app.aaps.pump.diaconn.packet import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.sharedPreferences.SP -import dagger.android.HasAndroidInjector +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.diaconn.DiaconnG8Pump -import app.aaps.pump.diaconn.R +import app.aaps.pump.diaconn.keys.DiaconnStringNonKey import app.aaps.pump.diaconn.pumplog.PumpLogUtil +import dagger.android.HasAndroidInjector import org.joda.time.DateTime import javax.inject.Inject import kotlin.math.floor @@ -20,7 +20,7 @@ class BigMainInfoInquireResponsePacket( ) : DiaconnG8Packet(injector) { @Inject lateinit var diaconnG8Pump: DiaconnG8Pump - @Inject lateinit var sp: SP + @Inject lateinit var preferences: Preferences @Inject lateinit var rh: ResourceHelper init { @@ -74,7 +74,7 @@ class BigMainInfoInquireResponsePacket( diaconnG8Pump.majorVersion = getByteToInt(bufferData) diaconnG8Pump.minorVersion = getByteToInt(bufferData) - sp.putString(rh.gs(R.string.pumpversion), diaconnG8Pump.majorVersion.toString() + "." + diaconnG8Pump.minorVersion.toString()) + preferences.put(DiaconnStringNonKey.PumpVersion, diaconnG8Pump.majorVersion.toString() + "." + diaconnG8Pump.minorVersion.toString()) // 5. pump log status diaconnG8Pump.pumpLastLogNum = getShortToInt(bufferData) // last saved log no @@ -211,8 +211,8 @@ class BigMainInfoInquireResponsePacket( diaconnG8Pump.pumpProfiles!![diaconnG8Pump.activeProfile][23] = diaconnG8Pump.baseAmount24 //incarnation no 처리 - diaconnG8Pump.isPumpVersionGe2_63 = PumpLogUtil.isPumpVersionGe(sp.getString(rh.gs(R.string.pumpversion), ""), 2, 63) - diaconnG8Pump.isPumpVersionGe3_53 = PumpLogUtil.isPumpVersionGe(sp.getString(rh.gs(R.string.pumpversion), ""), 3, 53) + diaconnG8Pump.isPumpVersionGe2_63 = PumpLogUtil.isPumpVersionGe(preferences.get(DiaconnStringNonKey.PumpVersion), 2, 63) + diaconnG8Pump.isPumpVersionGe3_53 = PumpLogUtil.isPumpVersionGe(preferences.get(DiaconnStringNonKey.PumpVersion), 3, 53) aapsLogger.debug(LTag.PUMPCOMM, "result > " + diaconnG8Pump.result) aapsLogger.debug(LTag.PUMPCOMM, "systemRemainInsulin > " + diaconnG8Pump.systemRemainInsulin) diff --git a/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/packet/BolusSpeedInquireResponsePacket.kt b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/packet/BolusSpeedInquireResponsePacket.kt index a609d5b9a0e..d56042bc739 100644 --- a/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/packet/BolusSpeedInquireResponsePacket.kt +++ b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/packet/BolusSpeedInquireResponsePacket.kt @@ -1,9 +1,10 @@ package app.aaps.pump.diaconn.packet import app.aaps.core.interfaces.logging.LTag -import app.aaps.core.interfaces.sharedPreferences.SP -import dagger.android.HasAndroidInjector +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.diaconn.DiaconnG8Pump +import app.aaps.pump.diaconn.keys.DiaconnIntKey +import dagger.android.HasAndroidInjector import javax.inject.Inject /** @@ -13,7 +14,7 @@ import javax.inject.Inject class BolusSpeedInquireResponsePacket(injector: HasAndroidInjector) : DiaconnG8Packet(injector) { @Inject lateinit var diaconnG8Pump: DiaconnG8Pump - @Inject lateinit var sp: SP + @Inject lateinit var preferences: Preferences init { msgType = 0x85.toByte() @@ -37,7 +38,7 @@ class BolusSpeedInquireResponsePacket(injector: HasAndroidInjector) : DiaconnG8P } diaconnG8Pump.speed = getByteToInt(bufferData) //주입속도 - sp.putString("g8_bolusspeed", diaconnG8Pump.speed.toString()) + preferences.put(DiaconnIntKey.BolusSpeed, diaconnG8Pump.speed) aapsLogger.debug(LTag.PUMPCOMM, "Result --> ${diaconnG8Pump.result}") aapsLogger.debug(LTag.PUMPCOMM, "bolusSpeed > " + diaconnG8Pump.speed) diff --git a/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/packet/BolusSpeedSettingReportPacket.kt b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/packet/BolusSpeedSettingReportPacket.kt index 3be14e9687b..660f2a4b497 100644 --- a/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/packet/BolusSpeedSettingReportPacket.kt +++ b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/packet/BolusSpeedSettingReportPacket.kt @@ -1,10 +1,8 @@ package app.aaps.pump.diaconn.packet import app.aaps.core.interfaces.logging.LTag -import app.aaps.core.interfaces.sharedPreferences.SP -import dagger.android.HasAndroidInjector import app.aaps.pump.diaconn.DiaconnG8Pump -import app.aaps.pump.diaconn.R +import dagger.android.HasAndroidInjector import javax.inject.Inject /** @@ -15,7 +13,6 @@ class BolusSpeedSettingReportPacket( ) : DiaconnG8Packet(injector) { @Inject lateinit var diaconnG8Pump: DiaconnG8Pump - @Inject lateinit var sp: SP init { msgType = 0xC5.toByte() @@ -32,7 +29,6 @@ class BolusSpeedSettingReportPacket( val bufferData = prefixDecode(data) diaconnG8Pump.speed = getByteToInt(bufferData) // speed result - sp.putBoolean(R.string.key_diaconn_g8_is_bolus_speed_sync, true) aapsLogger.debug(LTag.PUMPCOMM, "bolusSpeed --> ${diaconnG8Pump.speed}") } diff --git a/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/packet/IncarnationInquireResponsePacket.kt b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/packet/IncarnationInquireResponsePacket.kt index 90b596788b3..bef71ca95c6 100644 --- a/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/packet/IncarnationInquireResponsePacket.kt +++ b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/packet/IncarnationInquireResponsePacket.kt @@ -2,9 +2,8 @@ package app.aaps.pump.diaconn.packet import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.sharedPreferences.SP -import dagger.android.HasAndroidInjector import app.aaps.pump.diaconn.DiaconnG8Pump +import dagger.android.HasAndroidInjector import javax.inject.Inject /** @@ -16,7 +15,6 @@ open class IncarnationInquireResponsePacket( ) : DiaconnG8Packet(injector) { @Inject lateinit var diaconnG8Pump: DiaconnG8Pump - @Inject lateinit var sp: SP @Inject lateinit var rh: ResourceHelper var result = 0 diff --git a/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/packet/SerialNumInquireResponsePacket.kt b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/packet/SerialNumInquireResponsePacket.kt index 2687f2f6b6b..402c36514b3 100644 --- a/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/packet/SerialNumInquireResponsePacket.kt +++ b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/packet/SerialNumInquireResponsePacket.kt @@ -2,10 +2,10 @@ package app.aaps.pump.diaconn.packet import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.sharedPreferences.SP -import dagger.android.HasAndroidInjector +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.diaconn.DiaconnG8Pump -import app.aaps.pump.diaconn.R +import app.aaps.pump.diaconn.keys.DiaconnStringNonKey +import dagger.android.HasAndroidInjector import javax.inject.Inject /** @@ -14,7 +14,7 @@ import javax.inject.Inject class SerialNumInquireResponsePacket(injector: HasAndroidInjector) : DiaconnG8Packet(injector) { @Inject lateinit var diaconnG8Pump: DiaconnG8Pump - @Inject lateinit var sp: SP + @Inject lateinit var preferences: Preferences @Inject lateinit var rh: ResourceHelper init { @@ -59,7 +59,7 @@ class SerialNumInquireResponsePacket(injector: HasAndroidInjector) : DiaconnG8Pa aapsLogger.debug(LTag.PUMPCOMM, "majorVersion --> ${diaconnG8Pump.majorVersion}") aapsLogger.debug(LTag.PUMPCOMM, "minorVersion --> ${diaconnG8Pump.minorVersion}") - sp.putString(rh.gs(R.string.pumpversion), diaconnG8Pump.majorVersion.toString() + "." + diaconnG8Pump.minorVersion.toString()) + preferences.put(DiaconnStringNonKey.PumpVersion, diaconnG8Pump.majorVersion.toString() + "." + diaconnG8Pump.minorVersion.toString()) } override val friendlyName = "PUMP_SERIAL_NUM_INQUIRE_RESPONSE" diff --git a/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/service/DiaconnG8Service.kt b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/service/DiaconnG8Service.kt index 61090a14fd2..d46db23e604 100644 --- a/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/service/DiaconnG8Service.kt +++ b/pump/diaconn/src/main/kotlin/app/aaps/pump/diaconn/service/DiaconnG8Service.kt @@ -26,13 +26,13 @@ import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventAppExit import app.aaps.core.interfaces.rx.events.EventInitializationChanged import app.aaps.core.interfaces.rx.events.EventOverviewBolusProgress +import app.aaps.core.interfaces.rx.events.EventPreferenceChange import app.aaps.core.interfaces.rx.events.EventProfileSwitchChanged import app.aaps.core.interfaces.rx.events.EventPumpStatusChanged -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.fabric.FabricPrivacy -import dagger.android.HasAndroidInjector +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.diaconn.DiaconnG8Plugin import app.aaps.pump.diaconn.DiaconnG8Pump import app.aaps.pump.diaconn.R @@ -40,7 +40,10 @@ import app.aaps.pump.diaconn.api.DiaconnApiService import app.aaps.pump.diaconn.api.DiaconnLogUploader import app.aaps.pump.diaconn.database.DiaconnHistoryRecordDao import app.aaps.pump.diaconn.events.EventDiaconnG8NewStatus -import dagger.android.DaggerService +import app.aaps.pump.diaconn.keys.DiaconnBooleanKey +import app.aaps.pump.diaconn.keys.DiaconnIntKey +import app.aaps.pump.diaconn.keys.DiaconnIntNonKey +import app.aaps.pump.diaconn.keys.DiaconnStringNonKey import app.aaps.pump.diaconn.packet.AppConfirmSettingPacket import app.aaps.pump.diaconn.packet.BasalLimitInquirePacket import app.aaps.pump.diaconn.packet.BasalSettingPacket @@ -70,7 +73,10 @@ import app.aaps.pump.diaconn.packet.TempBasalSettingPacket import app.aaps.pump.diaconn.packet.TimeInquirePacket import app.aaps.pump.diaconn.packet.TimeSettingPacket import app.aaps.pump.diaconn.pumplog.PumpLogUtil +import dagger.android.DaggerService +import dagger.android.HasAndroidInjector import io.reactivex.rxjava3.disposables.CompositeDisposable +import io.reactivex.rxjava3.kotlin.plusAssign import org.joda.time.DateTime import org.joda.time.DateTimeZone import java.util.concurrent.TimeUnit @@ -85,7 +91,7 @@ class DiaconnG8Service : DaggerService() { @Inject lateinit var injector: HasAndroidInjector @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var rxBus: RxBus - @Inject lateinit var sp: SP + @Inject lateinit var preferences: Preferences @Inject lateinit var rh: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var commandQueue: CommandQueue @@ -107,13 +113,24 @@ class DiaconnG8Service : DaggerService() { private val mBinder: IBinder = LocalBinder() private var lastApproachingDailyLimit: Long = 0 + private var updateBolusSpeedInPump = false + override fun onCreate() { super.onCreate() - disposable.add(rxBus - .toObservable(EventAppExit::class.java) - .observeOn(aapsSchedulers.io) - .subscribe({ stopSelf() }) { fabricPrivacy.logException(it) } - ) + disposable += rxBus + .toObservable(EventAppExit::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ stopSelf() }, fabricPrivacy::logException) + disposable += rxBus + .toObservable(EventPreferenceChange::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ + if (it.isChanged(DiaconnIntKey.BolusSpeed.key)) { + diaconnG8Pump.bolusSpeed = preferences.get(DiaconnIntKey.BolusSpeed) + diaconnG8Pump.speed = preferences.get(DiaconnIntKey.BolusSpeed) + updateBolusSpeedInPump = true + } + }, fabricPrivacy::logException) } inner class LocalBinder : Binder() { @@ -167,7 +184,7 @@ class DiaconnG8Service : DaggerService() { rxBus.send(EventPumpStatusChanged(rh.gs(R.string.gettingpumpsettings))) sendMessage(SerialNumInquirePacket(injector)) - val pumpFirmwareVersion = sp.getString(rh.gs(R.string.pumpversion), "") + val pumpFirmwareVersion = preferences.get(DiaconnStringNonKey.PumpVersion) if (pumpFirmwareVersion.isNotEmpty() && PumpLogUtil.isPumpVersionGe(pumpFirmwareVersion, 3, 0)) { sendMessage(BigAPSMainInfoInquirePacket(injector)) // APS Pump Main Info @@ -287,9 +304,9 @@ class DiaconnG8Service : DaggerService() { // pump log status val pumpLastNum = diaconnG8Pump.pumpLastLogNum val pumpWrappingCount = diaconnG8Pump.pumpWrappingCount - val apsIncarnationNum = sp.getInt(rh.gs(R.string.apsIncarnationNo), 65536) + val apsIncarnationNum = preferences.get(DiaconnIntNonKey.ApsIncarnationNo) // aps last log num - val pumpSerialNo = sp.getInt(rh.gs(R.string.pumpserialno), 0) + val pumpSerialNo = preferences.get(DiaconnIntNonKey.PumpSerialNo) // if first install app if (apsWrappingCount == -1 && apsLastLogNum == 9999) { @@ -301,14 +318,14 @@ class DiaconnG8Service : DaggerService() { if (pumpSerialNo != diaconnG8Pump.serialNo) { apsWrappingCount = pumpWrappingCount apsLastLogNum = if (pumpLastNum - 1 < 0) 0 else pumpLastNum - 2 - sp.putInt(rh.gs(R.string.pumpserialno), diaconnG8Pump.serialNo) + preferences.put(DiaconnIntNonKey.PumpSerialNo, diaconnG8Pump.serialNo) aapsLogger.debug(LTag.PUMPCOMM, "Pump serialNo is different apsWrappingCount : $apsWrappingCount, apsLastLogNum : $apsLastLogNum") } // if pump reset if (apsIncarnationNum != diaconnG8Pump.pumpIncarnationNum) { apsWrappingCount = pumpWrappingCount apsLastLogNum = if (pumpLastNum - 1 < 0) 0 else pumpLastNum - 2 - sp.putInt(R.string.apsIncarnationNo, diaconnG8Pump.pumpIncarnationNum) + preferences.put(DiaconnIntNonKey.ApsIncarnationNo, diaconnG8Pump.pumpIncarnationNum) aapsLogger.debug(LTag.PUMPCOMM, "Pump incarnationNum is different apsWrappingCount : $apsWrappingCount, apsLastLogNum : $apsLastLogNum") } aapsLogger.debug(LTag.PUMPCOMM, "apsWrappingCount : $apsWrappingCount, apsLastLogNum : $apsLastLogNum") @@ -330,7 +347,7 @@ class DiaconnG8Service : DaggerService() { diaconnG8Pump.lastConnection = System.currentTimeMillis() } // upload pump log to Diaconn Cloud - if (sp.getBoolean(R.string.key_diaconn_g8_cloudsend, true)) { + if (preferences.get(DiaconnBooleanKey.SendLogsToCloud)) { SystemClock.sleep(1000) try { // getting last uploaded log number @@ -421,11 +438,11 @@ class DiaconnG8Service : DaggerService() { val result = instantiator.providePumpEnactResult() val msg: DiaconnG8Packet = when (diaconnG8Pump.setUserOptionType) { - DiaconnG8Pump.ALARM -> SoundSettingPacket(injector, diaconnG8Pump.beepAndAlarm, diaconnG8Pump.alarmIntensity) - DiaconnG8Pump.LCD -> DisplayTimeoutSettingPacket(injector, diaconnG8Pump.lcdOnTimeSec) - DiaconnG8Pump.LANG -> LanguageSettingPacket(injector, diaconnG8Pump.selectedLanguage) + DiaconnG8Pump.ALARM -> SoundSettingPacket(injector, diaconnG8Pump.beepAndAlarm, diaconnG8Pump.alarmIntensity) + DiaconnG8Pump.LCD -> DisplayTimeoutSettingPacket(injector, diaconnG8Pump.lcdOnTimeSec) + DiaconnG8Pump.LANG -> LanguageSettingPacket(injector, diaconnG8Pump.selectedLanguage) DiaconnG8Pump.BOLUS_SPEED -> BolusSpeedSettingPacket(injector, diaconnG8Pump.bolusSpeed) - else -> null + else -> null } ?: return result.success(false) sendMessage(msg) @@ -447,16 +464,13 @@ class DiaconnG8Service : DaggerService() { if (BolusProgressData.stopPressed) return false rxBus.send(EventPumpStatusChanged(rh.gs(R.string.startingbolus))) - // bolus speed setting - val apsPrefBolusSpeed = sp.getInt(R.string.key_diaconn_g8_bolusspeed, 5) - val isSpeedSyncToPump = sp.getBoolean(R.string.key_diaconn_g8_is_bolus_speed_sync, false) - // aps speed check - if (!isSpeedSyncToPump) { - val msg = BolusSpeedSettingPacket(injector, apsPrefBolusSpeed) + if (updateBolusSpeedInPump) { + val msg = BolusSpeedSettingPacket(injector, preferences.get(DiaconnIntKey.BolusSpeed)) sendMessage(msg) sendMessage(AppConfirmSettingPacket(injector, msg.msgType, diaconnG8Pump.otpNumber)) diaconnG8Pump.otpNumber = 0 + updateBolusSpeedInPump = false } // pump bolus speed inquire diff --git a/pump/diaconn/src/main/res/values/arrays.xml b/pump/diaconn/src/main/res/values/arrays.xml deleted file mode 100644 index f813bedce02..00000000000 --- a/pump/diaconn/src/main/res/values/arrays.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - - - 1 U/min - 2 U/min - 3 U/min - 4 U/min - 5 U/min - 6 U/min - 7 U/min - 8 U/min - - - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - - - - Chiness - Korean - English - - - 1 - 2 - 3 - - - - Small - Medium - Large - - - 1 - 2 - 3 - - - diff --git a/pump/diaconn/src/main/res/values/colors.xml b/pump/diaconn/src/main/res/values/colors.xml deleted file mode 100644 index aa88e1fc900..00000000000 --- a/pump/diaconn/src/main/res/values/colors.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - #FFBB86FC - #FF6200EE - #FF3700B3 - #FF03DAC5 - #FF018786 - \ No newline at end of file diff --git a/pump/diaconn/src/main/res/values/ids.xml b/pump/diaconn/src/main/res/values/ids.xml deleted file mode 100644 index ab4bb053a10..00000000000 --- a/pump/diaconn/src/main/res/values/ids.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/pump/diaconn/src/main/res/values/strings.xml b/pump/diaconn/src/main/res/values/strings.xml index 5dfd29ca25a..65afa99082e 100644 --- a/pump/diaconn/src/main/res/values/strings.xml +++ b/pump/diaconn/src/main/res/values/strings.xml @@ -1,47 +1,36 @@ - diagonn_g8_address - Diaconn G8 - - g8_bolusspeed - diaconn_g8_logbatterychanges - diaconn_g8_loginsulinchange - diaconn_g8_logneedlechange - diaconn_g8_cloudsend - diaconn_g8_appuid - diaconn_g8_isbolusspeedsync - - Reset Pairing + Reset Pairing No Device available - Diaconn Pump Pairing - Pump Error - Alarms - Basal Hours - Boluses - Daily insulin + Diaconn Pump Pairing + Pump Error + Alarms + Basal Hours + Boluses + Daily insulin Refill Suspend - Invalid pairing information. Requesting new pairing - Getting pump settings - Getting pump time - Large time difference:\nTime in pump is off by more than 1.5 hours.\nPlease adjust the time manually on the pump and make sure that reading the history from the pump does not cause unexpected behaviour.\nIf possible, remove the history from the pump before changing the time or disable the closed loop for one DIA after the last wrong history entry but minimum one DIA from now. - Large time difference Title - Approaching insulin daily limit - Starting bolus delivery - Waiting for estimated bolus end - Getting Bolus Status + Invalid pairing information. Requesting new pairing + Getting pump settings + Getting pump time + Large time difference:\nTime in pump is off by more than 1.5 hours.\nPlease adjust the time manually on the pump and make sure that reading the history from the pump does not cause unexpected behaviour.\nIf possible, remove the history from the pump before changing the time or disable the closed loop for one DIA after the last wrong history entry but minimum one DIA from now. + Large time difference Title + Approaching insulin daily limit + Starting bolus delivery + Waiting for estimated bolus end + Getting Bolus Status Stopping temp basal - Setting temp basal - Setting extended bolus - Stopping extended bolus - Updating basal rates + Setting temp basal + Setting extended bolus + Stopping extended bolus + Updating basal rates Pump Integration for Diaconn G8 Pumps Diaconn G8 Diaconn G8 - Max bolus violation - Command error - Speed error - Insulin limit violation - Asked: %1$.2fU Delivered: %2$.2fU Error code: %3$s + Max bolus violation + Command error + Speed error + Insulin limit violation + Asked: %1$.2fU Delivered: %2$.2fU Error code: %3$s Bolus speed Selected pump @@ -75,9 +64,6 @@ Insulin Lack Warning Battery replacement is required Insulin replacement is required - pump_version - aps_incarnation_no - pump_serial_no Log reservoir change Add \"Insulin Change\" event to careportal when detected in history Log needle change @@ -112,9 +98,9 @@ REPLACE TUBE REPLACE NEEDLE REPLACE SYRINGE - Injection Block (%s) - basal release (%s) - basal suspend (%s) + Injection Block (%s) + basal release (%s) + basal suspend (%s) Dual Nomarl Success Dual Square Start Dual Square Success @@ -123,7 +109,6 @@ Meal Failed Success Meal Success - diaconn_g8_logtubechange Can\'t lookup due to packet CRC error. Can\'t be set to an input parameter error. Can\'t be set to a protocol specification error. diff --git a/pump/diaconn/src/main/res/xml/pref_diaconn.xml b/pump/diaconn/src/main/res/xml/pref_diaconn.xml deleted file mode 100644 index ec409e5636e..00000000000 --- a/pump/diaconn/src/main/res/xml/pref_diaconn.xml +++ /dev/null @@ -1,56 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/pump/eopatch/build.gradle.kts b/pump/eopatch/build.gradle.kts index cc2c1a221fd..b483c94e2af 100644 --- a/pump/eopatch/build.gradle.kts +++ b/pump/eopatch/build.gradle.kts @@ -17,6 +17,7 @@ android { dependencies { implementation(project(":core:data")) implementation(project(":core:interfaces")) + implementation(project(":core:keys")) implementation(project(":core:libraries")) implementation(project(":core:utils")) implementation(project(":core:ui")) @@ -28,6 +29,7 @@ dependencies { api(libs.io.reactivex.rxjava3.rxandroid) api(libs.com.polidea.rxandroidble3) api(libs.com.jakewharton.rx3.replaying.share) + implementation(project(":core:validators")) kapt(libs.com.google.dagger.compiler) kapt(libs.com.google.dagger.android.processor) diff --git a/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/EopatchPumpPlugin.kt b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/EopatchPumpPlugin.kt index c4e237a3257..3a746aa04ac 100644 --- a/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/EopatchPumpPlugin.kt +++ b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/EopatchPumpPlugin.kt @@ -1,6 +1,9 @@ package app.aaps.pump.eopatch +import android.content.Context import android.os.SystemClock +import androidx.preference.PreferenceCategory +import androidx.preference.PreferenceScreen import app.aaps.core.data.model.BS import app.aaps.core.data.plugin.PluginType import app.aaps.core.data.pump.defs.ManufacturerType @@ -35,12 +38,17 @@ import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.Round import app.aaps.core.interfaces.utils.fabric.FabricPrivacy +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.core.validators.preferences.AdaptiveListIntPreference +import app.aaps.core.validators.preferences.AdaptiveSwitchPreference import app.aaps.pump.eopatch.alarm.IAlarmManager import app.aaps.pump.eopatch.ble.IPatchManager import app.aaps.pump.eopatch.ble.PatchManagerExecutor import app.aaps.pump.eopatch.ble.PreferenceManager import app.aaps.pump.eopatch.code.BolusExDuration -import app.aaps.pump.eopatch.code.SettingKeys +import app.aaps.pump.eopatch.keys.EopatchBooleanKey +import app.aaps.pump.eopatch.keys.EopatchIntKey +import app.aaps.pump.eopatch.keys.EopatchStringNonKey import app.aaps.pump.eopatch.ui.EopatchOverviewFragment import app.aaps.pump.eopatch.vo.NormalBasalManager import app.aaps.pump.eopatch.vo.PatchConfig @@ -61,6 +69,7 @@ import kotlin.math.roundToInt class EopatchPumpPlugin @Inject constructor( aapsLogger: AAPSLogger, rh: ResourceHelper, + preferences: Preferences, commandQueue: CommandQueue, private val aapsSchedulers: AapsSchedulers, private val rxBus: RxBus, @@ -77,14 +86,18 @@ class EopatchPumpPlugin @Inject constructor( private val patchConfig: PatchConfig, private val normalBasalManager: NormalBasalManager ) : PumpPluginBase( - PluginDescription() + pluginDescription = PluginDescription() .mainType(PluginType.PUMP) .fragmentClass(EopatchOverviewFragment::class.java.name) .pluginIcon(app.aaps.core.ui.R.drawable.ic_eopatch2_128) .pluginName(R.string.eopatch) .shortName(R.string.eopatch_shortname) - .preferencesId(R.xml.pref_eopatch) - .description(R.string.eopatch_pump_description), aapsLogger, rh, commandQueue + .preferencesId(PluginDescription.PREFERENCE_SCREEN) + .description(R.string.eopatch_pump_description), + ownPreferences = listOf( + EopatchIntKey::class.java, EopatchBooleanKey::class.java, EopatchStringNonKey::class.java + ), + aapsLogger, rh, preferences, commandQueue ), Pump { private val mDisposables = CompositeDisposable() @@ -98,10 +111,10 @@ class EopatchPumpPlugin @Inject constructor( mDisposables += rxBus .toObservable(EventPreferenceChange::class.java) .observeOn(aapsSchedulers.io) - .subscribe({ event: EventPreferenceChange -> - if (event.isChanged(rh.gs(SettingKeys.LOW_RESERVOIR_REMINDERS)) || event.isChanged(rh.gs(SettingKeys.EXPIRATION_REMINDERS))) { + .subscribe({ event -> + if (event.isChanged(EopatchIntKey.LowReservoirReminder.key) || event.isChanged(EopatchIntKey.ExpirationReminder.key)) { patchManager.changeReminderSetting() - } else if (event.isChanged(rh.gs(SettingKeys.BUZZER_REMINDERS))) { + } else if (event.isChanged(EopatchBooleanKey.BuzzerReminder.key)) { patchManager.changeBuzzerSetting() } }, fabricPrivacy::logException) @@ -611,4 +624,25 @@ class EopatchPumpPlugin @Inject constructor( private fun readTBR(): PumpSync.PumpState.TemporaryBasal? { return pumpSync.expectedPumpState().temporaryBasal } + + override fun addPreferenceScreen(preferenceManager: androidx.preference.PreferenceManager, parent: PreferenceScreen, context: Context, requiredKey: String?) { + if (requiredKey != null) return + + val lowReservoirEntries = arrayOf("10 U", "15 U", "20 U", "25 U", "30 U", "35 U", "40 U", "45 U", "50 U") + val lowReservoirValues = arrayOf("10", "15", "20", "25", "30", "35", "40", "45", "50") + val expirationRemindersEntries = + arrayOf("1 hr", "2 hr", "3 hr", "4 hr", "5 hr", "6 hr", "7 hr", "8 hr", "9 hr", "10 hr", "11 hr", "12 hr", "13 hr", "14 hr", "15 hr", "16 hr", "17 hr", "18 hr", "19 hr", "20 hr", "21 hr", "22 hr", "23 hr", "24 hr") + val expirationRemindersValues = arrayOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24") + + val category = PreferenceCategory(context) + parent.addPreference(category) + category.apply { + key = "eopatch_settings" + title = rh.gs(R.string.eopatch) + initialExpandedChildrenCount = 0 + addPreference(AdaptiveListIntPreference(ctx = context, intKey = EopatchIntKey.LowReservoirReminder, title = R.string.low_reservoir, entries = lowReservoirEntries, entryValues = lowReservoirValues)) + addPreference(AdaptiveListIntPreference(ctx = context, intKey = EopatchIntKey.ExpirationReminder, title = R.string.patch_expiration_reminders, entries = expirationRemindersEntries, entryValues = expirationRemindersValues)) + addPreference(AdaptiveSwitchPreference(ctx = context, booleanKey = EopatchBooleanKey.BuzzerReminder, title = R.string.patch_buzzer_reminders)) + } + } } \ No newline at end of file diff --git a/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/alarm/AlarmManager.kt b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/alarm/AlarmManager.kt index d6c26e27a8c..8b0a0c7732b 100644 --- a/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/alarm/AlarmManager.kt +++ b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/alarm/AlarmManager.kt @@ -11,7 +11,6 @@ import app.aaps.core.interfaces.pump.PumpSync import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.AapsSchedulers import app.aaps.core.interfaces.rx.bus.RxBus -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.ui.UiInteraction import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.fabric.FabricPrivacy @@ -52,7 +51,6 @@ class AlarmManager @Inject constructor() : IAlarmManager { @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rxBus: RxBus @Inject lateinit var fabricPrivacy: FabricPrivacy - @Inject lateinit var sp: SP @Inject lateinit var context: Context @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var uiInteraction: UiInteraction diff --git a/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/ble/PatchManager.kt b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/ble/PatchManager.kt index 265f8b55cd2..8560f531304 100644 --- a/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/ble/PatchManager.kt +++ b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/ble/PatchManager.kt @@ -12,20 +12,19 @@ import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventCustomActionsChanged import app.aaps.core.interfaces.rx.events.EventPumpStatusChanged import app.aaps.core.interfaces.rx.events.EventRefreshOverview -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.DateUtil +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.eopatch.R import app.aaps.pump.eopatch.RxAction import app.aaps.pump.eopatch.alarm.AlarmCode import app.aaps.pump.eopatch.alarm.IAlarmRegistry -import app.aaps.pump.eopatch.code.SettingKeys.Companion.BUZZER_REMINDERS -import app.aaps.pump.eopatch.code.SettingKeys.Companion.EXPIRATION_REMINDERS -import app.aaps.pump.eopatch.code.SettingKeys.Companion.LOW_RESERVOIR_REMINDERS import app.aaps.pump.eopatch.core.scan.BleConnectionState import app.aaps.pump.eopatch.core.scan.IPatchScanner import app.aaps.pump.eopatch.core.scan.PatchScanner import app.aaps.pump.eopatch.core.scan.ScanList import app.aaps.pump.eopatch.event.EventPatchActivationNotComplete +import app.aaps.pump.eopatch.keys.EopatchBooleanKey +import app.aaps.pump.eopatch.keys.EopatchIntKey import app.aaps.pump.eopatch.ui.DialogHelperActivity import app.aaps.pump.eopatch.vo.Alarms import app.aaps.pump.eopatch.vo.PatchConfig @@ -51,7 +50,7 @@ class PatchManager @Inject constructor( private val rh: ResourceHelper, private val rxBus: RxBus, private val context: Context, - private val sp: SP, + private val preferences: Preferences, private val pumpSync: PumpSync, private val dateUtil: DateUtil, private val rxAction: RxAction, @@ -178,7 +177,7 @@ class PatchManager @Inject constructor( } override fun changeBuzzerSetting() { - val buzzer = sp.getBoolean(BUZZER_REMINDERS, false) + val buzzer = preferences.get(EopatchBooleanKey.BuzzerReminder) if (patchConfig.infoReminder != buzzer) { if (patchConfig.isActivated) { compositeDisposable.add( @@ -197,8 +196,8 @@ class PatchManager @Inject constructor( } override fun changeReminderSetting() { - val doseUnit = sp.getInt(LOW_RESERVOIR_REMINDERS, 0) - val hours = sp.getInt(EXPIRATION_REMINDERS, 0) + val doseUnit = preferences.get(EopatchIntKey.LowReservoirReminder) + val hours = preferences.get(EopatchIntKey.ExpirationReminder) val pc: PatchConfig = patchConfig if (pc.lowReservoirAlertAmount != doseUnit || pc.patchExpireAlertTime != hours) { if (patchConfig.isActivated) { diff --git a/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/ble/PatchManagerExecutor.kt b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/ble/PatchManagerExecutor.kt index bd44331d22e..a43a57e4572 100644 --- a/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/ble/PatchManagerExecutor.kt +++ b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/ble/PatchManagerExecutor.kt @@ -7,7 +7,7 @@ import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.pump.DetailedBolusInfo import app.aaps.core.interfaces.rx.AapsSchedulers -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.eopatch.EoPatchRxBus.listen import app.aaps.pump.eopatch.alarm.AlarmCode import app.aaps.pump.eopatch.ble.task.ActivateTask @@ -35,9 +35,6 @@ import app.aaps.pump.eopatch.ble.task.UpdateConnectionTask import app.aaps.pump.eopatch.code.BolusExDuration import app.aaps.pump.eopatch.code.DeactivationStatus import app.aaps.pump.eopatch.code.PatchLifecycle -import app.aaps.pump.eopatch.code.SettingKeys.Companion.BUZZER_REMINDERS -import app.aaps.pump.eopatch.code.SettingKeys.Companion.EXPIRATION_REMINDERS -import app.aaps.pump.eopatch.code.SettingKeys.Companion.LOW_RESERVOIR_REMINDERS import app.aaps.pump.eopatch.core.Patch import app.aaps.pump.eopatch.core.api.BuzzerStop import app.aaps.pump.eopatch.core.api.GetTemperature @@ -60,6 +57,8 @@ import app.aaps.pump.eopatch.core.scan.BleConnectionState import app.aaps.pump.eopatch.core.scan.IBleDevice import app.aaps.pump.eopatch.core.scan.PatchSelfTestResult import app.aaps.pump.eopatch.event.EventEoPatchAlarm +import app.aaps.pump.eopatch.keys.EopatchBooleanKey +import app.aaps.pump.eopatch.keys.EopatchIntKey import app.aaps.pump.eopatch.ui.receiver.RxBroadcastReceiver import app.aaps.pump.eopatch.vo.Alarms import app.aaps.pump.eopatch.vo.NormalBasal @@ -107,7 +106,7 @@ class PatchManagerExecutor @Inject constructor( private val normalBasalManager: NormalBasalManager, private val alarms: Alarms, private val context: Context, - private val sp: SP, + private val preferences: Preferences, private val aapsLogger: AAPSLogger, private val aapsSchedulers: AapsSchedulers, private val START_BOND: StartBondTask, @@ -121,11 +120,11 @@ class PatchManagerExecutor @Inject constructor( private val compositeDisposable: CompositeDisposable = CompositeDisposable() - private val BUZZER_STOP: BuzzerStop - private val TEMPERATURE_GET: GetTemperature - private val ALARM_ALERT_ERROR_BEEP_STOP: StopAeBeep - private val PUBLIC_KEY_SET: PublicKeySend - private val SEQUENCE_GET: SequenceGet + private val BUZZER_STOP: BuzzerStop = BuzzerStop() + private val TEMPERATURE_GET: GetTemperature = GetTemperature() + private val ALARM_ALERT_ERROR_BEEP_STOP: StopAeBeep = StopAeBeep() + private val PUBLIC_KEY_SET: PublicKeySend = PublicKeySend() + private val SEQUENCE_GET: SequenceGet = SequenceGet() @Inject fun onInit() { patch.init(context) @@ -203,9 +202,9 @@ class PatchManagerExecutor @Inject constructor( private fun onPatchConnected(connected: Boolean) { val activated = patchConfig.isActivated val useEncryption = patchConfig.sharedKey != null - val doseUnit = sp.getInt(LOW_RESERVOIR_REMINDERS, 0) - val hours = sp.getInt(EXPIRATION_REMINDERS, 0) - val buzzer = sp.getBoolean(BUZZER_REMINDERS, false) + val doseUnit = preferences.get(EopatchIntKey.LowReservoirReminder) + val hours = preferences.get(EopatchIntKey.ExpirationReminder) + val buzzer = preferences.get(EopatchBooleanKey.BuzzerReminder) val pc: PatchConfig = patchConfig if (connected && activated && useEncryption) { @@ -606,15 +605,6 @@ class PatchManagerExecutor @Inject constructor( .map(Function { pubKey: ECPublicKey -> encodeECPublicKey(pubKey) }) } - init { - - BUZZER_STOP = BuzzerStop() - TEMPERATURE_GET = GetTemperature() - ALARM_ALERT_ERROR_BEEP_STOP = StopAeBeep() - PUBLIC_KEY_SET = PublicKeySend() - SEQUENCE_GET = SequenceGet() - } - val patchConnectionState get() = patch.connectionState fun observePatchConnectionState(): Observable { diff --git a/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/ble/PreferenceManagerImpl.kt b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/ble/PreferenceManagerImpl.kt index b1d879d737c..7bf1aa161c0 100644 --- a/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/ble/PreferenceManagerImpl.kt +++ b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/ble/PreferenceManagerImpl.kt @@ -3,10 +3,10 @@ package app.aaps.pump.eopatch.ble import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.rx.bus.RxBus -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.eopatch.GsonHelper import app.aaps.pump.eopatch.code.PatchLifecycle -import app.aaps.pump.eopatch.code.SettingKeys +import app.aaps.pump.eopatch.keys.EopatchStringNonKey import app.aaps.pump.eopatch.vo.Alarms import app.aaps.pump.eopatch.vo.BolusCurrent import app.aaps.pump.eopatch.vo.NormalBasalManager @@ -24,7 +24,7 @@ import javax.inject.Singleton @Singleton class PreferenceManagerImpl @Inject constructor() : PreferenceManager { - @Inject lateinit var sp: SP + @Inject lateinit var preferences: Preferences @Inject lateinit var rxBus: RxBus @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var patchConfig: PatchConfig @@ -47,7 +47,7 @@ class PreferenceManagerImpl @Inject constructor() : PreferenceManager { override fun init() { try { - val jsonStr = sp.getString(SettingKeys.PATCH_STATE, "") + val jsonStr = preferences.get(EopatchStringNonKey.PatchState) val savedState = GsonHelper.sharedGson().fromJson(jsonStr, PatchState::class.java) patchState = savedState } catch (ex: Exception) { @@ -56,7 +56,7 @@ class PreferenceManagerImpl @Inject constructor() : PreferenceManager { } try { - val jsonStr = sp.getString(SettingKeys.BOLUS_CURRENT, "") + val jsonStr = preferences.get(EopatchStringNonKey.BolusCurrent) val savedBolusCurrent = GsonHelper.sharedGson().fromJson(jsonStr, BolusCurrent::class.java) bolusCurrent = savedBolusCurrent } catch (ex: Exception) { @@ -65,7 +65,7 @@ class PreferenceManagerImpl @Inject constructor() : PreferenceManager { } try { - val jsonStr = sp.getString(SettingKeys.PATCH_CONFIG, "") + val jsonStr = preferences.get(EopatchStringNonKey.PatchConfig) val savedConfig = GsonHelper.sharedGson().fromJson(jsonStr, PatchConfig::class.java) patchConfig.update(savedConfig) } catch (ex: Exception) { @@ -73,7 +73,7 @@ class PreferenceManagerImpl @Inject constructor() : PreferenceManager { } try { - val jsonStr = sp.getString(SettingKeys.NORMAL_BASAL, "") + val jsonStr = preferences.get(EopatchStringNonKey.NormalBasal) val normalBasalManager = GsonHelper.sharedGson().fromJson(jsonStr, NormalBasalManager::class.java) normalBasalMgr.update(normalBasalManager) } catch (ex: Exception) { @@ -81,7 +81,7 @@ class PreferenceManagerImpl @Inject constructor() : PreferenceManager { } try { - val jsonStr = sp.getString(SettingKeys.TEMP_BASAL, "") + val jsonStr = preferences.get(EopatchStringNonKey.TempBasal) val tempBasalManager = GsonHelper.sharedGson().fromJson(jsonStr, TempBasalManager::class.java) tempBasalManager.update(tempBasalManager) } catch (ex: Exception) { @@ -89,7 +89,7 @@ class PreferenceManagerImpl @Inject constructor() : PreferenceManager { } try { - val jsonStr = sp.getString(SettingKeys.ALARMS, "") + val jsonStr = preferences.get(EopatchStringNonKey.Alarms) val alarms = GsonHelper.sharedGson().fromJson(jsonStr, Alarms::class.java) mAlarms.update(alarms) } catch (ex: Exception) { @@ -107,12 +107,12 @@ class PreferenceManagerImpl @Inject constructor() : PreferenceManager { override fun isInitDone() = initialized - override fun flushPatchConfig() = patchConfig.flush(sp) - override fun flushPatchState() = patchState.flush(sp) - override fun flushBolusCurrent() = bolusCurrent.flush(sp) - override fun flushNormalBasalManager() = normalBasalMgr.flush(sp) - override fun flushTempBasalManager() = tempBasalManager.flush(sp) - override fun flushAlarms() = mAlarms.flush(sp) + override fun flushPatchConfig() = patchConfig.flush(preferences) + override fun flushPatchState() = patchState.flush(preferences) + override fun flushBolusCurrent() = bolusCurrent.flush(preferences) + override fun flushNormalBasalManager() = normalBasalMgr.flush(preferences) + override fun flushTempBasalManager() = tempBasalManager.flush(preferences) + override fun flushAlarms() = mAlarms.flush(preferences) @Synchronized override fun updatePatchLifeCycle(event: PatchLifecycleEvent) { diff --git a/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/code/SettingKeys.kt b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/code/SettingKeys.kt deleted file mode 100644 index f968d165695..00000000000 --- a/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/code/SettingKeys.kt +++ /dev/null @@ -1,19 +0,0 @@ -package app.aaps.pump.eopatch.code - -import app.aaps.pump.eopatch.R - -class SettingKeys { - companion object { - - val LOW_RESERVOIR_REMINDERS: Int = R.string.key_eopatch_low_reservoir_reminders - val EXPIRATION_REMINDERS: Int = R.string.key_eopatch_expiration_reminders - val BUZZER_REMINDERS: Int = R.string.key_eopatch_patch_buzzer_reminders - - val PATCH_CONFIG: Int = R.string.key_eopatch_patch_config - val PATCH_STATE: Int = R.string.key_eopatch_patch_state - val BOLUS_CURRENT: Int = R.string.key_eopatch_bolus_current - val NORMAL_BASAL: Int = R.string.key_eopatch_normal_basal - val TEMP_BASAL: Int = R.string.key_eopatch_temp_basal - val ALARMS: Int = R.string.key_eopatch_bolus_current - } -} \ No newline at end of file diff --git a/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/keys/EopatchBooleanKey.kt b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/keys/EopatchBooleanKey.kt new file mode 100644 index 00000000000..411e0a6d059 --- /dev/null +++ b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/keys/EopatchBooleanKey.kt @@ -0,0 +1,21 @@ +package app.aaps.pump.eopatch.keys + +import app.aaps.core.keys.interfaces.BooleanPreferenceKey + +enum class EopatchBooleanKey( + override val key: String, + override val defaultValue: Boolean, + override val calculatedDefaultValue: Boolean = false, + override val engineeringModeOnly: Boolean = false, + override val defaultedBySM: Boolean = false, + override val showInApsMode: Boolean = true, + override val showInNsClientMode: Boolean = true, + override val showInPumpControlMode: Boolean = true, + override val dependency: BooleanPreferenceKey? = null, + override val negativeDependency: BooleanPreferenceKey? = null, + override val hideParentScreenIfHidden: Boolean = false, + override val exportable: Boolean = true +) : BooleanPreferenceKey { + + BuzzerReminder("eopatch_patch_buzzer_reminders", false), +} diff --git a/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/keys/EopatchIntKey.kt b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/keys/EopatchIntKey.kt new file mode 100644 index 00000000000..8bab5cb97c7 --- /dev/null +++ b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/keys/EopatchIntKey.kt @@ -0,0 +1,25 @@ +package app.aaps.pump.eopatch.keys + +import app.aaps.core.keys.interfaces.BooleanPreferenceKey +import app.aaps.core.keys.interfaces.IntPreferenceKey + +enum class EopatchIntKey( + override val key: String, + override val defaultValue: Int, + override val min: Int = Int.MIN_VALUE, + override val max: Int = Int.MAX_VALUE, + override val calculatedDefaultValue: Boolean = false, + override val engineeringModeOnly: Boolean = false, + override val defaultedBySM: Boolean = false, + override val showInApsMode: Boolean = true, + override val showInNsClientMode: Boolean = true, + override val showInPumpControlMode: Boolean = true, + override val dependency: BooleanPreferenceKey? = null, + override val negativeDependency: BooleanPreferenceKey? = null, + override val hideParentScreenIfHidden: Boolean = false, + override val exportable: Boolean = true +) : IntPreferenceKey { + + LowReservoirReminder("eopatch_low_reservoir_reminders", 10), + ExpirationReminder("eopatch_expiration_reminders", 4), +} diff --git a/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/keys/EopatchStringNonKey.kt b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/keys/EopatchStringNonKey.kt new file mode 100644 index 00000000000..576335152e3 --- /dev/null +++ b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/keys/EopatchStringNonKey.kt @@ -0,0 +1,17 @@ +package app.aaps.pump.eopatch.keys + +import app.aaps.core.keys.interfaces.StringNonPreferenceKey + +enum class EopatchStringNonKey( + override val key: String, + override val defaultValue: String, + override val exportable: Boolean = true +) : StringNonPreferenceKey { + + Alarms("eopatch_alarms", ""), + BolusCurrent("eopatch_bolus_current", ""), + PatchState("eopatch_patch_state", ""), + PatchConfig("eopatch_patch_config", ""), + NormalBasal("eopatch_normal_basal", ""), + TempBasal("eopatch_temp_basal", ""), +} diff --git a/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/ui/AlarmHelperActivity.kt b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/ui/AlarmHelperActivity.kt index 2989028dac3..b41ac41bb42 100644 --- a/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/ui/AlarmHelperActivity.kt +++ b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/ui/AlarmHelperActivity.kt @@ -4,7 +4,6 @@ import android.os.Bundle import androidx.appcompat.app.AlertDialog import app.aaps.core.interfaces.rx.AapsSchedulers import app.aaps.core.interfaces.rx.bus.RxBus -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.ui.R import app.aaps.core.ui.activities.TranslatedDaggerAppCompatActivity import app.aaps.pump.eopatch.alarm.AlarmCode @@ -17,7 +16,6 @@ import javax.inject.Inject class AlarmHelperActivity : TranslatedDaggerAppCompatActivity() { - @Inject lateinit var sp: SP @Inject lateinit var rxBus: RxBus @Inject lateinit var aapsSchedulers: AapsSchedulers @@ -46,22 +44,14 @@ class AlarmHelperActivity : TranslatedDaggerAppCompatActivity() { rxBus .toObservable(EventProgressDialog::class.java) .observeOn(aapsSchedulers.main) - .subscribe({ - if (it.show) { - showProgressDialog(it.resId) - } else { - dismissProgressDialog() - } - }, { }) + .subscribe({ if (it.show) showProgressDialog(it.resId) else dismissProgressDialog() }, { }) ) disposable.add( rxBus .toObservable(EventDialog::class.java) .observeOn(aapsSchedulers.main) - .subscribe({ - if (it.show) it.dialog.show(supportFragmentManager, "") - }, { }) + .subscribe({ if (it.show) it.dialog.show(supportFragmentManager, "") }, { }) ) } diff --git a/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/ui/viewmodel/EopatchViewModel.kt b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/ui/viewmodel/EopatchViewModel.kt index fe54ec62077..8402e6916fb 100644 --- a/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/ui/viewmodel/EopatchViewModel.kt +++ b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/ui/viewmodel/EopatchViewModel.kt @@ -9,7 +9,7 @@ import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.AapsSchedulers -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.eopatch.CommonUtils import app.aaps.pump.eopatch.R import app.aaps.pump.eopatch.RxAction @@ -21,7 +21,6 @@ import app.aaps.pump.eopatch.ble.PreferenceManager import app.aaps.pump.eopatch.code.EventType import app.aaps.pump.eopatch.code.PatchLifecycle import app.aaps.pump.eopatch.code.PatchStep -import app.aaps.pump.eopatch.code.SettingKeys.Companion.EXPIRATION_REMINDERS import app.aaps.pump.eopatch.core.define.IPatchConstant import app.aaps.pump.eopatch.core.scan.BleConnectionState import app.aaps.pump.eopatch.core.scan.PatchSelfTestResult.TEST_SUCCESS @@ -29,6 +28,7 @@ import app.aaps.pump.eopatch.extension.getDiffDays import app.aaps.pump.eopatch.extension.subscribeDefault import app.aaps.pump.eopatch.extension.subscribeEmpty import app.aaps.pump.eopatch.extension.takeOne +import app.aaps.pump.eopatch.keys.EopatchIntKey import app.aaps.pump.eopatch.ui.EoBaseNavigator import app.aaps.pump.eopatch.ui.event.SingleLiveEvent import app.aaps.pump.eopatch.ui.event.UIEvent @@ -74,7 +74,7 @@ class EopatchViewModel @Inject constructor( private val aapsLogger: AAPSLogger, private val aapsSchedulers: AapsSchedulers, private val rxAction: RxAction, - private val sp: SP + private val preferences: Preferences ) : EoBaseViewModel() { companion object { @@ -547,7 +547,7 @@ class EopatchViewModel @Inject constructor( PatchStep.COMPLETE, PatchStep.BASAL_SCHEDULE -> { val now = System.currentTimeMillis() val expireTimeStamp = patchConfig.expireTimestamp - val millisBeforeExpiration = TimeUnit.HOURS.toMillis(sp.getInt(EXPIRATION_REMINDERS, 0).toLong()) + val millisBeforeExpiration = TimeUnit.HOURS.toMillis(preferences.get(EopatchIntKey.ExpirationReminder).toLong()) Maybe.just(AlarmCode.B012) .flatMap { alarmRegistry.remove(it) } diff --git a/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/vo/Alarms.kt b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/vo/Alarms.kt index cd01dcc91ea..75f07f42e83 100644 --- a/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/vo/Alarms.kt +++ b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/vo/Alarms.kt @@ -1,9 +1,9 @@ package app.aaps.pump.eopatch.vo -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.eopatch.GsonHelper import app.aaps.pump.eopatch.alarm.AlarmCode -import app.aaps.pump.eopatch.code.SettingKeys +import app.aaps.pump.eopatch.keys.EopatchStringNonKey import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.subjects.BehaviorSubject @@ -98,9 +98,9 @@ class Alarms : IPreference { return subject.hide() } - override fun flush(sp: SP) { + override fun flush(preferences: Preferences) { val jsonStr = GsonHelper.sharedGson().toJson(this) - sp.putString(SettingKeys.ALARMS, jsonStr) + preferences.put(EopatchStringNonKey.Alarms, jsonStr) subject.onNext(this) } diff --git a/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/vo/BolusCurrent.kt b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/vo/BolusCurrent.kt index 127700b1a73..08494c9d309 100644 --- a/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/vo/BolusCurrent.kt +++ b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/vo/BolusCurrent.kt @@ -1,11 +1,11 @@ package app.aaps.pump.eopatch.vo -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.eopatch.AppConstant import app.aaps.pump.eopatch.GsonHelper -import app.aaps.pump.eopatch.code.SettingKeys import app.aaps.pump.eopatch.core.code.BolusType import app.aaps.pump.eopatch.core.util.FloatAdjusters +import app.aaps.pump.eopatch.keys.EopatchStringNonKey import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.subjects.BehaviorSubject @@ -163,9 +163,9 @@ class BolusCurrent : IPreference { return subject.hide() } - override fun flush(sp: SP) { + override fun flush(preferences: Preferences) { val jsonStr = GsonHelper.sharedGson().toJson(this) - sp.putString(SettingKeys.BOLUS_CURRENT, jsonStr) + preferences.put(EopatchStringNonKey.BolusCurrent, jsonStr) subject.onNext(this) } diff --git a/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/vo/IPreference.kt b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/vo/IPreference.kt index 6cb42e060be..1494cf48ca1 100644 --- a/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/vo/IPreference.kt +++ b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/vo/IPreference.kt @@ -1,10 +1,10 @@ package app.aaps.pump.eopatch.vo -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences import io.reactivex.rxjava3.core.Observable interface IPreference { - fun flush(sp: SP) + fun flush(preferences: Preferences) fun observe(): Observable } \ No newline at end of file diff --git a/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/vo/NormalBasalManager.kt b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/vo/NormalBasalManager.kt index f1c262b2485..c9628487d40 100644 --- a/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/vo/NormalBasalManager.kt +++ b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/vo/NormalBasalManager.kt @@ -1,11 +1,11 @@ package app.aaps.pump.eopatch.vo import app.aaps.core.interfaces.profile.Profile -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.eopatch.CommonUtils import app.aaps.pump.eopatch.GsonHelper import app.aaps.pump.eopatch.code.BasalStatus -import app.aaps.pump.eopatch.code.SettingKeys +import app.aaps.pump.eopatch.keys.EopatchStringNonKey import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.subjects.BehaviorSubject import java.util.concurrent.TimeUnit @@ -115,9 +115,9 @@ class NormalBasalManager : IPreference { return subject.hide() } - override fun flush(sp: SP) { + override fun flush(preferences: Preferences) { val jsonStr = GsonHelper.sharedGson().toJson(this) - sp.putString(SettingKeys.NORMAL_BASAL, jsonStr) + preferences.put(EopatchStringNonKey.NormalBasal, jsonStr) subject.onNext(this) } diff --git a/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/vo/PatchConfig.kt b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/vo/PatchConfig.kt index 6b5c286973e..09c4a654093 100644 --- a/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/vo/PatchConfig.kt +++ b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/vo/PatchConfig.kt @@ -1,13 +1,13 @@ package app.aaps.pump.eopatch.vo -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.eopatch.AppConstant import app.aaps.pump.eopatch.CommonUtils import app.aaps.pump.eopatch.FloatFormatters import app.aaps.pump.eopatch.GsonHelper import app.aaps.pump.eopatch.code.PatchLifecycle -import app.aaps.pump.eopatch.code.SettingKeys import app.aaps.pump.eopatch.core.define.IPatchConstant.WARRANTY_OPERATING_LIFE_MILLI +import app.aaps.pump.eopatch.keys.EopatchStringNonKey import com.google.android.gms.common.internal.Preconditions import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.subjects.BehaviorSubject @@ -301,9 +301,9 @@ class PatchConfig : IPreference { return subject.hide() } - override fun flush(sp: SP) { + override fun flush(preferences: Preferences) { val jsonStr = GsonHelper.sharedGson().toJson(this) - sp.putString(SettingKeys.PATCH_CONFIG, jsonStr) + preferences.put(EopatchStringNonKey.PatchConfig, jsonStr) subject.onNext(this) } diff --git a/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/vo/PatchState.kt b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/vo/PatchState.kt index 5d197170d0e..025c7744dff 100644 --- a/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/vo/PatchState.kt +++ b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/vo/PatchState.kt @@ -1,11 +1,11 @@ package app.aaps.pump.eopatch.vo -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.eopatch.AppConstant import app.aaps.pump.eopatch.GsonHelper -import app.aaps.pump.eopatch.code.SettingKeys import app.aaps.pump.eopatch.core.code.BolusType import app.aaps.pump.eopatch.core.util.FloatAdjusters +import app.aaps.pump.eopatch.keys.EopatchStringNonKey import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.subjects.BehaviorSubject import java.io.Serializable @@ -307,9 +307,9 @@ class PatchState : IPreference { return subject.hide() } - override fun flush(sp: SP) { + override fun flush(preferences: Preferences) { val jsonStr = GsonHelper.sharedGson().toJson(this) - sp.putString(SettingKeys.PATCH_STATE, jsonStr) + preferences.put(EopatchStringNonKey.PatchState, jsonStr) subject.onNext(this) } diff --git a/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/vo/TempBasalManager.kt b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/vo/TempBasalManager.kt index d712b9cb9aa..062300883ef 100644 --- a/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/vo/TempBasalManager.kt +++ b/pump/eopatch/src/main/kotlin/app/aaps/pump/eopatch/vo/TempBasalManager.kt @@ -1,10 +1,10 @@ package app.aaps.pump.eopatch.vo -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.eopatch.CommonUtils import app.aaps.pump.eopatch.GsonHelper -import app.aaps.pump.eopatch.code.SettingKeys import app.aaps.pump.eopatch.code.UnitOrPercent +import app.aaps.pump.eopatch.keys.EopatchStringNonKey import com.google.common.base.Preconditions import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.subjects.BehaviorSubject @@ -52,9 +52,9 @@ class TempBasalManager : IPreference { return subject.hide() } - override fun flush(sp: SP) { + override fun flush(preferences: Preferences) { val jsonStr = GsonHelper.sharedGson().toJson(this) - sp.putString(SettingKeys.TEMP_BASAL, jsonStr) + preferences.put(EopatchStringNonKey.TempBasal, jsonStr) subject.onNext(this) } diff --git a/pump/eopatch/src/main/res/values/arrays.xml b/pump/eopatch/src/main/res/values/arrays.xml index cdc341d68d2..5d3b5a8e81c 100644 --- a/pump/eopatch/src/main/res/values/arrays.xml +++ b/pump/eopatch/src/main/res/values/arrays.xml @@ -1,82 +1,6 @@ - - 10 U - 15 U - 20 U - 25 U - 30 U - 35 U - 40 U - 45 U - 50 U - - - - 10 - 15 - 20 - 25 - 30 - 35 - 40 - 45 - 50 - - - 1 hr - 2 hr - 3 hr - 4 hr - 5 hr - 6 hr - 7 hr - 8 hr - 9 hr - 10 hr - 11 hr - 12 hr - 13 hr - 14 hr - 15 hr - 16 hr - 17 hr - 18 hr - 19 hr - 20 hr - 21 hr - 22 hr - 23 hr - 24 hr - - - - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 - 11 - 12 - 13 - 14 - 15 - 16 - 17 - 18 - 19 - 20 - 21 - 22 - 23 - 24 - @string/time_30min @string/time_1hr diff --git a/pump/eopatch/src/main/res/values/strings.xml b/pump/eopatch/src/main/res/values/strings.xml index c0161a3137b..6f14bd0bfce 100644 --- a/pump/eopatch/src/main/res/values/strings.xml +++ b/pump/eopatch/src/main/res/values/strings.xml @@ -1,12 +1,4 @@ - eopatch_low_reservoir_reminders - eopatch_expiration_reminders - eopatch_patch_buzzer_reminders - eopatch_patch_config - eopatch_patch_state - eopatch_bolus_current - eopatch_normal_basal - eopatch_temp_basal : EOPatch2 diff --git a/pump/eopatch/src/main/res/xml/pref_eopatch.xml b/pump/eopatch/src/main/res/xml/pref_eopatch.xml deleted file mode 100644 index c726b011113..00000000000 --- a/pump/eopatch/src/main/res/xml/pref_eopatch.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/pump/equil/build.gradle.kts b/pump/equil/build.gradle.kts index c310bab4b99..d5d77f44da3 100644 --- a/pump/equil/build.gradle.kts +++ b/pump/equil/build.gradle.kts @@ -22,6 +22,7 @@ android { dependencies { implementation(project(":core:data")) implementation(project(":core:interfaces")) + implementation(project(":core:keys")) implementation(project(":core:libraries")) implementation(project(":core:objects")) implementation(project(":core:utils")) diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/EquilConst.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/EquilConst.kt index 0a33adf2a19..eb615509cb9 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/EquilConst.kt +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/EquilConst.kt @@ -6,18 +6,8 @@ object EquilConst { const val EQUIL_BLE_WRITE_TIME_OUT: Long = 20 const val EQUIL_BLE_NEXT_CMD: Long = 150 const val EQUIL_SUPPORT_LEVEL = 5.3f - const val EQUIL_BLOUS_THRESHOLD_STEP = 1600 + const val EQUIL_BOLUS_THRESHOLD_STEP = 1600 const val EQUIL_STEP_MAX = 32000 const val EQUIL_STEP_FILL = 160 const val EQUIL_STEP_AIR = 120 - object Prefs { - - val EQUIL_DEVICES = R.string.key_equil_devices - val EQUIL_PASSWORD = R.string.key_equil_password - val Equil_ALARM_BATTERY_10 = R.string.key_equil_alarm_battery_10 - val EQUIL_ALARM_INSULIN_10 = R.string.key_equil_alarm_insulin_10 - val EQUIL_ALARM_INSULIN_5 = R.string.key_equil_alarm_insulin_5 - val EQUIL_BASAL_SET = R.string.key_equil_basal_set - val EQUIL_STATE = R.string.key_equil_state - } } diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/EquilFragment.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/EquilFragment.kt index 221933c50c8..0f30be761b9 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/EquilFragment.kt +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/EquilFragment.kt @@ -14,20 +14,18 @@ import androidx.fragment.app.DialogFragment import app.aaps.core.data.time.T import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.logging.LTag -import app.aaps.core.interfaces.logging.UserEntryLogger import app.aaps.core.interfaces.plugin.ActivePlugin import app.aaps.core.interfaces.protection.ProtectionCheck import app.aaps.core.interfaces.pump.BlePreCheck -import app.aaps.core.interfaces.pump.WarnColors import app.aaps.core.interfaces.queue.Callback import app.aaps.core.interfaces.queue.CommandQueue import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.AapsSchedulers import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventPumpStatusChanged -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.fabric.FabricPrivacy +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.ui.UIRunnable import app.aaps.core.ui.extensions.runOnUiThread import app.aaps.core.ui.toast.ToastUtils @@ -54,14 +52,12 @@ class EquilFragment : DaggerFragment() { @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var rh: ResourceHelper - @Inject lateinit var sp: SP - @Inject lateinit var warnColors: WarnColors + @Inject lateinit var preferences: Preferences @Inject lateinit var dateUtil: DateUtil @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var blePreCheck: BlePreCheck @Inject lateinit var equilPumpPlugin: EquilPumpPlugin @Inject lateinit var protectionCheck: ProtectionCheck - @Inject lateinit var uel: UserEntryLogger @Inject lateinit var equilManager: EquilManager private var disposable: CompositeDisposable = CompositeDisposable() @@ -259,7 +255,7 @@ class EquilFragment : DaggerFragment() { tempMode = RunMode.SUSPEND } showLoading() - commandQueue.customCommand(CmdModelSet(tempMode.command, aapsLogger, sp, equilManager), object : Callback() { + commandQueue.customCommand(CmdModelSet(tempMode.command, aapsLogger, preferences, equilManager), object : Callback() { override fun run() { dismissLoading() aapsLogger.debug(LTag.PUMPCOMM, "result====" + result.success) diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/EquilPumpPlugin.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/EquilPumpPlugin.kt index b5b3c79236c..236a46a18fb 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/EquilPumpPlugin.kt +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/EquilPumpPlugin.kt @@ -34,11 +34,10 @@ import app.aaps.core.interfaces.rx.AapsSchedulers import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventDismissNotification import app.aaps.core.interfaces.rx.events.EventPreferenceChange -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.DecimalFormatter import app.aaps.core.interfaces.utils.fabric.FabricPrivacy -import app.aaps.core.keys.Preferences +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.ui.toast.ToastUtils import app.aaps.core.validators.preferences.AdaptiveDoublePreference import app.aaps.core.validators.preferences.AdaptiveListIntPreference @@ -50,8 +49,10 @@ import app.aaps.pump.equil.driver.definition.BasalSchedule import app.aaps.pump.equil.events.EventEquilAlarm import app.aaps.pump.equil.events.EventEquilDataChanged import app.aaps.pump.equil.keys.EquilBooleanKey -import app.aaps.pump.equil.keys.EquilDoubleKey -import app.aaps.pump.equil.keys.EquilIntKey +import app.aaps.pump.equil.keys.EquilBooleanPreferenceKey +import app.aaps.pump.equil.keys.EquilDoublePreferenceKey +import app.aaps.pump.equil.keys.EquilIntPreferenceKey +import app.aaps.pump.equil.keys.EquilStringKey import app.aaps.pump.equil.manager.EquilManager import app.aaps.pump.equil.manager.command.BaseCmd import app.aaps.pump.equil.manager.command.CmdAlarmSet @@ -73,27 +74,31 @@ import javax.inject.Singleton class EquilPumpPlugin @Inject constructor( aapsLogger: AAPSLogger, rh: ResourceHelper, + preferences: Preferences, commandQueue: CommandQueue, private val aapsSchedulers: AapsSchedulers, private val rxBus: RxBus, private val context: Context, - private val sp: SP, private val fabricPrivacy: FabricPrivacy, private val dateUtil: DateUtil, private val pumpSync: PumpSync, private val equilManager: EquilManager, private val decimalFormatter: DecimalFormatter, - private val instantiator: Instantiator, - private val preferences: Preferences + private val instantiator: Instantiator ) : PumpPluginBase( - PluginDescription() + pluginDescription = PluginDescription() .mainType(PluginType.PUMP) .fragmentClass(EquilFragment::class.java.name) .pluginIcon(app.aaps.core.ui.R.drawable.ic_equil_128) .pluginName(R.string.equil_name) .shortName(R.string.equil_name_short) .preferencesId(PluginDescription.PREFERENCE_SCREEN) - .description(R.string.equil_pump_description), aapsLogger, rh, commandQueue + .description(R.string.equil_pump_description), + ownPreferences = listOf( + EquilBooleanKey::class.java, EquilBooleanPreferenceKey::class.java, EquilDoublePreferenceKey::class.java, EquilIntPreferenceKey::class.java, + EquilStringKey::class.java + ), + aapsLogger, rh, preferences, commandQueue ), Pump { override val pumpDescription: PumpDescription @@ -103,12 +108,6 @@ class EquilPumpPlugin @Inject constructor( private val disposable = CompositeDisposable() private var statusChecker: Runnable - init { - preferences.registerPreferences(EquilIntKey::class.java) - preferences.registerPreferences(EquilDoubleKey::class.java) - preferences.registerPreferences(EquilBooleanKey::class.java) - } - override fun onStart() { super.onStart() equilManager.init() @@ -122,56 +121,56 @@ class EquilPumpPlugin @Inject constructor( .toObservable(EventEquilAlarm::class.java) .observeOn(aapsSchedulers.io) .subscribe({ eventEquilError -> - var cmd = commandQueue.performing() - cmd?.let { - if (it.commandType == Command.CommandType.BOLUS) { - aapsLogger.info( - LTag.PUMPCOMM, - "eventEquilError.tips====${eventEquilError.tips}" - ) - rxBus.send(EventDismissNotification(Notification.EQUIL_ALARM)) - equilManager.showNotification( - Notification.EQUIL_ALARM, - eventEquilError.tips, - Notification.URGENT, app.aaps.core.ui.R.raw.alarm - ) - stopBolusDelivering() - } - } - }, fabricPrivacy::logException) + var cmd = commandQueue.performing() + cmd?.let { + if (it.commandType == Command.CommandType.BOLUS) { + aapsLogger.info( + LTag.PUMPCOMM, + "eventEquilError.tips====${eventEquilError.tips}" + ) + rxBus.send(EventDismissNotification(Notification.EQUIL_ALARM)) + equilManager.showNotification( + Notification.EQUIL_ALARM, + eventEquilError.tips, + Notification.URGENT, app.aaps.core.ui.R.raw.alarm + ) + stopBolusDelivering() + } + } + }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventPreferenceChange::class.java) .observeOn(aapsSchedulers.io) .subscribe({ event -> - if (event.isChanged(EquilIntKey.EquilTone.key)) { - val mode = preferences.get(EquilIntKey.EquilTone) - commandQueue.customCommand( - CmdAlarmSet(mode, aapsLogger, sp, equilManager), - object : Callback() { - override fun run() { - if (result.success) ToastUtils.infoToast( - context, - rh.gs(R.string.equil_pump_updated) - ) - else ToastUtils.infoToast(context, rh.gs(R.string.equil_error)) - } - }) - } else if (event.isChanged(EquilDoubleKey.EquilMaxBolus.key)) { - val data = preferences.get(EquilDoubleKey.EquilMaxBolus) - commandQueue.customCommand( - CmdSettingSet(data, aapsLogger, sp, equilManager), - object : Callback() { - override fun run() { - if (result.success) ToastUtils.infoToast( - context, - rh.gs(R.string.equil_pump_updated) - ) - else ToastUtils.infoToast(context, rh.gs(R.string.equil_error)) - } - }) - } - }, fabricPrivacy::logException) + if (event.isChanged(EquilIntPreferenceKey.EquilTone.key)) { + val mode = preferences.get(EquilIntPreferenceKey.EquilTone) + commandQueue.customCommand( + CmdAlarmSet(mode, aapsLogger, preferences, equilManager), + object : Callback() { + override fun run() { + if (result.success) ToastUtils.infoToast( + context, + rh.gs(R.string.equil_pump_updated) + ) + else ToastUtils.infoToast(context, rh.gs(R.string.equil_error)) + } + }) + } else if (event.isChanged(EquilDoublePreferenceKey.EquilMaxBolus.key)) { + val data = preferences.get(EquilDoublePreferenceKey.EquilMaxBolus) + commandQueue.customCommand( + CmdSettingSet(data, aapsLogger, preferences, equilManager), + object : Callback() { + override fun run() { + if (result.success) ToastUtils.infoToast( + context, + rh.gs(R.string.equil_pump_updated) + ) + else ToastUtils.infoToast(context, rh.gs(R.string.equil_error)) + } + }) + } + }, fabricPrivacy::logException) } var tempActivationProgress = ActivationProgress.NONE @@ -234,13 +233,7 @@ class EquilPumpPlugin @Inject constructor( if (mode === RunMode.RUN || mode === RunMode.SUSPEND) { val basalSchedule = BasalSchedule.mapProfileToBasalSchedule(profile) val pumpEnactResult = equilManager.executeCmd( - CmdBasalSet( - basalSchedule, - profile, - aapsLogger, - sp, - equilManager - ) + CmdBasalSet(basalSchedule, profile, aapsLogger, preferences, equilManager) ) if (pumpEnactResult.success) { equilManager.equilState?.basalSchedule = basalSchedule @@ -285,7 +278,7 @@ class EquilPumpPlugin @Inject constructor( return instantiator.providePumpEnactResult().success(false).enacted(false) .bolusDelivered(0.0).comment("Invalid input") } - val maxBolus = preferences.get(EquilDoubleKey.EquilMaxBolus) + val maxBolus = preferences.get(EquilDoublePreferenceKey.EquilMaxBolus) if (detailedBolusInfo.insulin > maxBolus) { val formattedValue = "%.2f".format(maxBolus) val comment = rh.gs(R.string.equil_maxbolus_tips, formattedValue) @@ -471,7 +464,7 @@ class EquilPumpPlugin @Inject constructor( override fun timezoneOrDSTChanged(timeChangeType: TimeChangeType) { aapsLogger.debug(LTag.PUMP, "DST and/or TimeZone changed event will be consumed by driver") - commandQueue.customCommand(CmdTimeSet(aapsLogger, sp, equilManager), null) + commandQueue.customCommand(CmdTimeSet(aapsLogger, preferences, equilManager), null) } override val isFakingTempsByExtendedBoluses: Boolean = false @@ -535,27 +528,26 @@ class EquilPumpPlugin @Inject constructor( } fun resetData() { - sp.putBoolean(EquilConst.Prefs.Equil_ALARM_BATTERY_10, false) - sp.putBoolean(EquilConst.Prefs.EQUIL_ALARM_INSULIN_10, false) - sp.putBoolean(EquilConst.Prefs.EQUIL_ALARM_INSULIN_5, false) - sp.putBoolean(EquilConst.Prefs.EQUIL_ALARM_INSULIN_5, false) - sp.putBoolean(EquilConst.Prefs.EQUIL_BASAL_SET, false) + preferences.put(EquilBooleanKey.AlarmBattery10, false) + preferences.put(EquilBooleanKey.AlarmInsulin10, false) + preferences.put(EquilBooleanKey.AlarmInsulin5, false) + preferences.put(EquilBooleanKey.BasalSet, false) } fun clearData() { resetData() equilManager.clearPodState() - sp.putString(EquilConst.Prefs.EQUIL_DEVICES, "") - sp.putString(EquilConst.Prefs.EQUIL_PASSWORD, "") + preferences.put(EquilStringKey.Devices, "") + preferences.put(EquilStringKey.Password, "") } private fun playAlarm() { val battery = equilManager.equilState?.battery ?: 100 val insulin = equilManager.equilState?.currentInsulin ?: 0 - val alarmBattery = preferences.get(EquilBooleanKey.EquilAlarmBattery) - val alarmInsulin = preferences.get(EquilBooleanKey.EquilAlarmInsulin) + val alarmBattery = preferences.get(EquilBooleanPreferenceKey.EquilAlarmBattery) + val alarmInsulin = preferences.get(EquilBooleanPreferenceKey.EquilAlarmInsulin) if (battery <= 10 && alarmBattery) { - val alarmBattery10 = sp.getBoolean(EquilConst.Prefs.Equil_ALARM_BATTERY_10, false) + val alarmBattery10 = preferences.get(EquilBooleanKey.AlarmBattery10) if (!alarmBattery10) { equilManager.showNotification( Notification.FAILED_UPDATE_PROFILE, @@ -563,7 +555,7 @@ class EquilPumpPlugin @Inject constructor( Notification.NORMAL, app.aaps.core.ui.R.raw.alarm ) - sp.putBoolean(EquilConst.Prefs.Equil_ALARM_BATTERY_10, true) + preferences.put(EquilBooleanKey.AlarmBattery10, true) } else { if (battery < 5) { equilManager.showNotification( @@ -579,7 +571,7 @@ class EquilPumpPlugin @Inject constructor( when { insulin in 6..10 -> { val alarmInsulin10 = - sp.getBoolean(EquilConst.Prefs.EQUIL_ALARM_INSULIN_10, false) + preferences.get(EquilBooleanKey.AlarmInsulin10) if (!alarmInsulin10) { rxBus.send(EventDismissNotification(Notification.EQUIL_ALARM_INSULIN)) equilManager.showNotification( @@ -588,12 +580,12 @@ class EquilPumpPlugin @Inject constructor( Notification.NORMAL, app.aaps.core.ui.R.raw.alarm ) - sp.putBoolean(EquilConst.Prefs.EQUIL_ALARM_INSULIN_10, true) + preferences.put(EquilBooleanKey.AlarmInsulin10, true) } } - insulin in 3..5 -> { - val alarmInsulin5 = sp.getBoolean(EquilConst.Prefs.EQUIL_ALARM_INSULIN_5, false) + insulin in 3..5 -> { + val alarmInsulin5 = preferences.get(EquilBooleanKey.AlarmInsulin5) if (!alarmInsulin5) { rxBus.send(EventDismissNotification(Notification.EQUIL_ALARM_INSULIN)) @@ -603,11 +595,11 @@ class EquilPumpPlugin @Inject constructor( Notification.NORMAL, app.aaps.core.ui.R.raw.alarm ) - sp.putBoolean(EquilConst.Prefs.EQUIL_ALARM_INSULIN_5, true) + preferences.put(EquilBooleanKey.AlarmInsulin5, true) } } - insulin <= 2 -> { + insulin <= 2 -> { rxBus.send(EventDismissNotification(Notification.EQUIL_ALARM_INSULIN)) equilManager.showNotification( Notification.EQUIL_ALARM_INSULIN, @@ -655,21 +647,21 @@ class EquilPumpPlugin @Inject constructor( addPreference( AdaptiveSwitchPreference( ctx = context, - booleanKey = EquilBooleanKey.EquilAlarmBattery, + booleanKey = EquilBooleanPreferenceKey.EquilAlarmBattery, title = R.string.equil_settings_alarm_battery ) ) addPreference( AdaptiveSwitchPreference( ctx = context, - booleanKey = EquilBooleanKey.EquilAlarmInsulin, + booleanKey = EquilBooleanPreferenceKey.EquilAlarmInsulin, title = R.string.equil_settings_alarm_insulin ) ) addPreference( AdaptiveListIntPreference( ctx = context, - intKey = EquilIntKey.EquilTone, + intKey = EquilIntPreferenceKey.EquilTone, title = R.string.equil_tone, entries = toneEntries, entryValues = toneValues @@ -678,7 +670,7 @@ class EquilPumpPlugin @Inject constructor( addPreference( AdaptiveDoublePreference( ctx = context, - doubleKey = EquilDoubleKey.EquilMaxBolus, + doubleKey = EquilDoublePreferenceKey.EquilMaxBolus, title = app.aaps.core.ui.R.string.max_bolus_title ) ) diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/keys/EquilBooleanKey.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/keys/EquilBooleanKey.kt index 101332112a0..814e6a3a784 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/keys/EquilBooleanKey.kt +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/keys/EquilBooleanKey.kt @@ -1,21 +1,15 @@ package app.aaps.pump.equil.keys -import app.aaps.core.keys.BooleanPreferenceKey +import app.aaps.core.keys.interfaces.BooleanNonPreferenceKey enum class EquilBooleanKey( override val key: String, override val defaultValue: Boolean, - override val calculatedDefaultValue: Boolean = false, - override val engineeringModeOnly: Boolean = false, - override val defaultedBySM: Boolean = false, - override val showInApsMode: Boolean = true, - override val showInNsClientMode: Boolean = true, - override val showInPumpControlMode: Boolean = true, - override val dependency: BooleanPreferenceKey? = null, - override val negativeDependency: BooleanPreferenceKey? = null, - override val hideParentScreenIfHidden: Boolean = false -) : BooleanPreferenceKey { + override val exportable: Boolean = true +) : BooleanNonPreferenceKey { - EquilAlarmBattery("key_equil_alarm_battery", true), - EquilAlarmInsulin("key_equil_alarm_insulin", true), + BasalSet("key_equil_basal_set", false), + AlarmBattery10("key_equil_alarm_battery_10", false), + AlarmInsulin10("key_equil_alarm_insulin_10", false), + AlarmInsulin5("key_equil_alarm_insulin_5", false), } diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/keys/EquilBooleanPreferenceKey.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/keys/EquilBooleanPreferenceKey.kt new file mode 100644 index 00000000000..b92a37421fe --- /dev/null +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/keys/EquilBooleanPreferenceKey.kt @@ -0,0 +1,22 @@ +package app.aaps.pump.equil.keys + +import app.aaps.core.keys.interfaces.BooleanPreferenceKey + +enum class EquilBooleanPreferenceKey( + override val key: String, + override val defaultValue: Boolean, + override val calculatedDefaultValue: Boolean = false, + override val engineeringModeOnly: Boolean = false, + override val defaultedBySM: Boolean = false, + override val showInApsMode: Boolean = true, + override val showInNsClientMode: Boolean = true, + override val showInPumpControlMode: Boolean = true, + override val dependency: BooleanPreferenceKey? = null, + override val negativeDependency: BooleanPreferenceKey? = null, + override val hideParentScreenIfHidden: Boolean = false, + override val exportable: Boolean = true +) : BooleanPreferenceKey { + + EquilAlarmBattery("key_equil_alarm_battery", true), + EquilAlarmInsulin("key_equil_alarm_insulin", true), +} diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/keys/EquilDoubleKey.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/keys/EquilDoublePreferenceKey.kt similarity index 70% rename from pump/equil/src/main/kotlin/app/aaps/pump/equil/keys/EquilDoubleKey.kt rename to pump/equil/src/main/kotlin/app/aaps/pump/equil/keys/EquilDoublePreferenceKey.kt index f5d536317e7..15989a0df24 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/keys/EquilDoubleKey.kt +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/keys/EquilDoublePreferenceKey.kt @@ -1,9 +1,9 @@ package app.aaps.pump.equil.keys -import app.aaps.core.keys.BooleanPreferenceKey -import app.aaps.core.keys.DoublePreferenceKey +import app.aaps.core.keys.interfaces.BooleanPreferenceKey +import app.aaps.core.keys.interfaces.DoublePreferenceKey -enum class EquilDoubleKey( +enum class EquilDoublePreferenceKey( override val key: String, override val defaultValue: Double, override val min: Double, @@ -15,7 +15,8 @@ enum class EquilDoubleKey( override val showInPumpControlMode: Boolean = true, override val dependency: BooleanPreferenceKey? = null, override val negativeDependency: BooleanPreferenceKey? = null, - override val hideParentScreenIfHidden: Boolean = false + override val exportable: Boolean = true, + override val hideParentScreenIfHidden: Boolean = false, ) : DoublePreferenceKey { EquilMaxBolus("equil_maxbolus", 10.0, 0.1, 25.0), diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/keys/EquilIntKey.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/keys/EquilIntPreferenceKey.kt similarity index 68% rename from pump/equil/src/main/kotlin/app/aaps/pump/equil/keys/EquilIntKey.kt rename to pump/equil/src/main/kotlin/app/aaps/pump/equil/keys/EquilIntPreferenceKey.kt index 3a7851b607a..44aeba62dd8 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/keys/EquilIntKey.kt +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/keys/EquilIntPreferenceKey.kt @@ -1,9 +1,9 @@ package app.aaps.pump.equil.keys -import app.aaps.core.keys.BooleanPreferenceKey -import app.aaps.core.keys.IntPreferenceKey +import app.aaps.core.keys.interfaces.BooleanPreferenceKey +import app.aaps.core.keys.interfaces.IntPreferenceKey -enum class EquilIntKey( +enum class EquilIntPreferenceKey( override val key: String, override val defaultValue: Int, override val min: Int, @@ -16,8 +16,9 @@ enum class EquilIntKey( override val showInPumpControlMode: Boolean = true, override val dependency: BooleanPreferenceKey? = null, override val negativeDependency: BooleanPreferenceKey? = null, - override val hideParentScreenIfHidden: Boolean = false + override val hideParentScreenIfHidden: Boolean = false, + override val exportable: Boolean = true ) : IntPreferenceKey { - EquilTone("key_equil_tone", 3, 0 ,3), + EquilTone("key_equil_tone", 3, 0, 3), } diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/keys/EquilStringKey.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/keys/EquilStringKey.kt new file mode 100644 index 00000000000..b216238c753 --- /dev/null +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/keys/EquilStringKey.kt @@ -0,0 +1,15 @@ +package app.aaps.pump.equil.keys + +import app.aaps.core.keys.interfaces.StringNonPreferenceKey + +enum class EquilStringKey( + override val key: String, + override val defaultValue: String, + override val exportable: Boolean = true +) : StringNonPreferenceKey { + + Devices("key_equil_devices", ""), + Password("key_equil_password", ""), + PairPassword("key_equil_pair_password", ""), + State("key_equil_state1", ""), +} diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/EquilManager.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/EquilManager.kt index 87d32e2c07f..e3d55e0b8b4 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/EquilManager.kt +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/EquilManager.kt @@ -17,10 +17,9 @@ import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.Event import app.aaps.core.interfaces.rx.events.EventNewNotification import app.aaps.core.interfaces.rx.events.EventOverviewBolusProgress -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.HardLimits +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.equil.EquilConst -import app.aaps.pump.equil.EquilConst.Prefs.EQUIL_STATE import app.aaps.pump.equil.R import app.aaps.pump.equil.ble.EquilBLE import app.aaps.pump.equil.data.AlarmMode @@ -42,6 +41,7 @@ import app.aaps.pump.equil.events.EventEquilAlarm import app.aaps.pump.equil.events.EventEquilDataChanged import app.aaps.pump.equil.events.EventEquilInsulinChanged import app.aaps.pump.equil.events.EventEquilModeChanged +import app.aaps.pump.equil.keys.EquilStringKey import app.aaps.pump.equil.manager.EquilManager.EquilState import app.aaps.pump.equil.manager.Utils.bytesToInt import app.aaps.pump.equil.manager.Utils.internalDecodeSpeedToUH @@ -79,7 +79,7 @@ import javax.inject.Singleton class EquilManager @Inject constructor( private val aapsLogger: AAPSLogger, private val rxBus: RxBus, - private val sp: SP, + private val preferences: Preferences, private val rh: ResourceHelper, private val pumpSync: PumpSync, private val equilBLE: EquilBLE, @@ -118,7 +118,7 @@ class EquilManager @Inject constructor( if (index == -1) { return "" } - return listEvent!!.get(index)!!.comment + return listEvent.get(index).comment } fun closeBleAuto() { @@ -148,7 +148,7 @@ class EquilManager @Inject constructor( fun getTempBasalPump(): PumpEnactResult { val result = instantiator.providePumpEnactResult() try { - val command = CmdTempBasalGet(aapsLogger, sp, this) + val command = CmdTempBasalGet(aapsLogger, preferences, this) equilBLE.writeCmd(command) synchronized(command) { (command as Object).wait(command.timeOut.toLong()) @@ -166,7 +166,7 @@ class EquilManager @Inject constructor( fun setTempBasal(insulin: Double, time: Int, cancel: Boolean): PumpEnactResult { val result = instantiator.providePumpEnactResult() try { - val command = CmdTempBasalSet(insulin, time, aapsLogger, sp, this) + val command = CmdTempBasalSet(insulin, time, aapsLogger, preferences, this) command.cancel = cancel val equilHistoryRecord = addHistory(command) equilBLE.writeCmd(command) @@ -216,7 +216,7 @@ class EquilManager @Inject constructor( fun setExtendedBolus(insulin: Double, time: Int, cancel: Boolean): PumpEnactResult { val result = instantiator.providePumpEnactResult() try { - val command = CmdExtendedBolusSet(insulin, time, cancel, aapsLogger, sp, this) + val command = CmdExtendedBolusSet(insulin, time, cancel, aapsLogger, preferences, this) val equilHistoryRecord = addHistory(command) equilBLE.writeCmd(command) synchronized(command) { @@ -266,7 +266,7 @@ class EquilManager @Inject constructor( ) val result = instantiator.providePumpEnactResult() try { - val command = CmdLargeBasalSet(detailedBolusInfo.insulin, aapsLogger, sp, this) + val command = CmdLargeBasalSet(detailedBolusInfo.insulin, aapsLogger, preferences, this) val equilHistoryRecord = addHistory(command) equilBLE.writeCmd(command) synchronized(command) { @@ -328,7 +328,7 @@ class EquilManager @Inject constructor( fun stopBolus(bolusProfile: BolusProfile): PumpEnactResult { val result = instantiator.providePumpEnactResult() try { - val command: BaseCmd = CmdLargeBasalSet(0.0, aapsLogger, sp, this) + val command: BaseCmd = CmdLargeBasalSet(0.0, aapsLogger, preferences, this) val equilHistoryRecord = addHistory(command) equilBLE.writeCmd(command) synchronized(command) { @@ -351,7 +351,7 @@ class EquilManager @Inject constructor( fun loadEquilHistory(index: Int): Int { try { aapsLogger.debug(LTag.PUMPCOMM, "loadHistory start: ") - val historyGet = CmdHistoryGet(index, aapsLogger, sp, this) + val historyGet = CmdHistoryGet(index, aapsLogger, preferences, this) equilBLE.readHistory(historyGet) synchronized(historyGet) { (historyGet as Object).wait(historyGet.timeOut.toLong()) @@ -432,7 +432,7 @@ class EquilManager @Inject constructor( fun readEquilStatus(): PumpEnactResult { val result = instantiator.providePumpEnactResult() try { - val command: BaseCmd = CmdModelGet(aapsLogger, sp, this) + val command: BaseCmd = CmdModelGet(aapsLogger, preferences, this) equilBLE.writeCmd(command) synchronized(command) { (command as Object).wait(command.timeOut.toLong()) @@ -513,7 +513,7 @@ class EquilManager @Inject constructor( } fun readPodState(): String { - return sp.getString(EQUIL_STATE, "") + return preferences.get(EquilStringKey.State) } fun loadPodState() { @@ -551,7 +551,7 @@ class EquilManager @Inject constructor( } private fun storePodState(podState: String) { - sp.putString(EQUIL_STATE, podState) + preferences.put(EquilStringKey.State, podState) } fun setAddress(address: String) { @@ -764,7 +764,7 @@ class EquilManager @Inject constructor( rxBus.send(EventEquilDataChanged()) } - fun decodeData(data: ByteArray,saveData:Boolean) { + fun decodeData(data: ByteArray, saveData: Boolean) { var year = data[11].toInt() and 0xFF year = year + 2000 val month = data[12].toInt() and 0xff @@ -789,7 +789,7 @@ class EquilManager @Inject constructor( errorTips, Notification.NORMAL, app.aaps.core.ui.R.raw.alarm ) - if(saveData){ + if (saveData) { val time = System.currentTimeMillis() val equilHistoryRecord = EquilHistoryRecord( EquilHistoryRecord.EventType.EQUIL_ALARM, @@ -803,7 +803,7 @@ class EquilManager @Inject constructor( } } - if (!TextUtils.isEmpty(errorTips)){ + if (!TextUtils.isEmpty(errorTips)) { rxBus.send(EventEquilAlarm(errorTips)) } aapsLogger.debug( diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/BaseCmd.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/BaseCmd.kt index b7bc00c1709..b099882b62d 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/BaseCmd.kt +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/BaseCmd.kt @@ -3,11 +3,10 @@ package app.aaps.pump.equil.manager.command import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.queue.CustomCommand -import app.aaps.core.interfaces.sharedPreferences.SP -import app.aaps.pump.equil.EquilConst.Prefs.EQUIL_DEVICES -import app.aaps.pump.equil.EquilConst.Prefs.EQUIL_PASSWORD +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.equil.database.EquilHistoryRecord import app.aaps.pump.equil.database.ResolvedResult +import app.aaps.pump.equil.keys.EquilStringKey import app.aaps.pump.equil.manager.Crc import app.aaps.pump.equil.manager.EquilCmdModel import app.aaps.pump.equil.manager.EquilManager @@ -23,7 +22,7 @@ import java.util.Locale abstract class BaseCmd( val createTime: Long, val aapsLogger: AAPSLogger, - val sp: SP, + val preferences: Preferences, val equilManager: EquilManager ) : CustomCommand { @@ -73,11 +72,11 @@ abstract class BaseCmd( } fun getEquilDevices(): String { - return sp.getString(EQUIL_DEVICES, "") + return preferences.get(EquilStringKey.Devices) } fun getEquilPassWord(): String { - return sp.getString(EQUIL_PASSWORD, "") + return preferences.get(EquilStringKey.Password) } open fun isPairStep(): Boolean { diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/BaseSetting.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/BaseSetting.kt index 79a801cedc8..26de5908a03 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/BaseSetting.kt +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/BaseSetting.kt @@ -2,7 +2,7 @@ package app.aaps.pump.equil.manager.command import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.logging.LTag -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.equil.manager.AESUtil import app.aaps.pump.equil.manager.EquilCmdModel import app.aaps.pump.equil.manager.EquilManager @@ -14,9 +14,9 @@ import java.nio.ByteBuffer abstract class BaseSetting( createTime: Long, aapsLogger: AAPSLogger, - sp: SP, + preferences: Preferences, equilManager: EquilManager -) : BaseCmd(createTime, aapsLogger, sp, equilManager) { +) : BaseCmd(createTime, aapsLogger, preferences, equilManager) { fun getReqData(): ByteArray { val indexByte = Utils.intToBytes(pumpReqIndex) diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdAlarmSet.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdAlarmSet.kt index d6a521750ba..a3168dff60e 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdAlarmSet.kt +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdAlarmSet.kt @@ -1,7 +1,7 @@ package app.aaps.pump.equil.manager.command import app.aaps.core.interfaces.logging.AAPSLogger -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.equil.data.AlarmMode import app.aaps.pump.equil.database.EquilHistoryRecord import app.aaps.pump.equil.manager.EquilManager @@ -10,9 +10,9 @@ import app.aaps.pump.equil.manager.Utils class CmdAlarmSet( var mode: Int, aapsLogger: AAPSLogger, - sp: SP, + preferences: Preferences, equilManager: EquilManager -) : BaseSetting(System.currentTimeMillis(), aapsLogger, sp, equilManager) { +) : BaseSetting(System.currentTimeMillis(), aapsLogger, preferences, equilManager) { override fun getFirstData(): ByteArray { val indexByte = Utils.intToBytes(pumpReqIndex) diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdBasalGet.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdBasalGet.kt index 9785053b763..2dfabd166f3 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdBasalGet.kt +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdBasalGet.kt @@ -3,7 +3,7 @@ package app.aaps.pump.equil.manager.command import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.profile.Profile -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.equil.database.EquilHistoryRecord import app.aaps.pump.equil.manager.EquilManager import app.aaps.pump.equil.manager.Utils @@ -12,9 +12,9 @@ import java.lang.StringBuilder class CmdBasalGet( var profile: Profile, aapsLogger: AAPSLogger, - sp: SP, + preferences: Preferences, equilManager: EquilManager -) : BaseSetting(System.currentTimeMillis(), aapsLogger, sp, equilManager) { +) : BaseSetting(System.currentTimeMillis(), aapsLogger, preferences, equilManager) { override fun getFirstData(): ByteArray { val indexByte = Utils.intToBytes(pumpReqIndex) diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdBasalSet.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdBasalSet.kt index 12c0a12b2d1..3745d3df9cc 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdBasalSet.kt +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdBasalSet.kt @@ -3,10 +3,10 @@ package app.aaps.pump.equil.manager.command import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.profile.Profile -import app.aaps.core.interfaces.sharedPreferences.SP -import app.aaps.pump.equil.EquilConst.Prefs.EQUIL_BASAL_SET +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.equil.database.EquilHistoryRecord import app.aaps.pump.equil.driver.definition.BasalSchedule +import app.aaps.pump.equil.keys.EquilBooleanKey import app.aaps.pump.equil.manager.EquilManager import app.aaps.pump.equil.manager.Utils import java.util.ArrayList @@ -15,9 +15,9 @@ class CmdBasalSet( var basalSchedule: BasalSchedule, var profile: Profile, aapsLogger: AAPSLogger, - sp: SP, + preferences: Preferences, equilManager: EquilManager -) : BaseSetting(System.currentTimeMillis(), aapsLogger, sp, equilManager) { +) : BaseSetting(System.currentTimeMillis(), aapsLogger, preferences, equilManager) { override fun getFirstData(): ByteArray { val indexByte = Utils.intToBytes(pumpReqIndex) @@ -55,7 +55,7 @@ class CmdBasalSet( override fun decodeConfirmData(data: ByteArray) { synchronized(this) { - sp.putBoolean(EQUIL_BASAL_SET, true) + preferences.put(EquilBooleanKey.BasalSet, true) cmdStatus = true (this as Object).notifyAll() } diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdDevicesGet.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdDevicesGet.kt index 3dd75eca16a..33dd81087d4 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdDevicesGet.kt +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdDevicesGet.kt @@ -2,16 +2,16 @@ package app.aaps.pump.equil.manager.command import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.logging.LTag -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.equil.database.EquilHistoryRecord import app.aaps.pump.equil.manager.EquilManager import app.aaps.pump.equil.manager.Utils class CmdDevicesGet( aapsLogger: AAPSLogger, - sp: SP, + preferences: Preferences, equilManager: EquilManager -) : BaseSetting(System.currentTimeMillis(), aapsLogger, sp, equilManager) { +) : BaseSetting(System.currentTimeMillis(), aapsLogger, preferences, equilManager) { init { port = "0000" diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdDevicesOldGet.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdDevicesOldGet.kt index 0a52475b65e..cc122cde84a 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdDevicesOldGet.kt +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdDevicesOldGet.kt @@ -2,7 +2,7 @@ package app.aaps.pump.equil.manager.command import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.logging.LTag -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.equil.EquilConst import app.aaps.pump.equil.database.EquilHistoryRecord import app.aaps.pump.equil.manager.EquilCmdModel @@ -17,9 +17,9 @@ import java.util.Locale class CmdDevicesOldGet( var address: String, aapsLogger: AAPSLogger, - sp: SP, + preferences: Preferences, equilManager: EquilManager -) : BaseSetting(System.currentTimeMillis(), aapsLogger, sp, equilManager) { +) : BaseSetting(System.currentTimeMillis(), aapsLogger, preferences, equilManager) { private var firmwareVersion = 0f @@ -88,7 +88,7 @@ class CmdDevicesOldGet( isEnd = true response = EquilResponse(createTime) rspIndex = intValue - aapsLogger.debug(LTag.PUMPCOMM, "intValue=====" + intValue + "====" + rspIndex) + aapsLogger.debug(LTag.PUMPCOMM, "intValue=====$intValue====$rspIndex") return list } catch (e: Exception) { response = EquilResponse(createTime) @@ -108,7 +108,7 @@ class CmdDevicesOldGet( response = EquilResponse(createTime) config = true rspIndex = intValue - aapsLogger.debug(LTag.PUMPCOMM, "intValue=====" + intValue + "====" + rspIndex) + aapsLogger.debug(LTag.PUMPCOMM, "intValue=====$intValue====$rspIndex") return list } catch (e: Exception) { e.printStackTrace() diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdExtendedBolusSet.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdExtendedBolusSet.kt index c3beb5a7958..9cbbbdbf638 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdExtendedBolusSet.kt +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdExtendedBolusSet.kt @@ -1,7 +1,7 @@ package app.aaps.pump.equil.manager.command import app.aaps.core.interfaces.logging.AAPSLogger -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.equil.database.EquilHistoryRecord import app.aaps.pump.equil.manager.EquilManager import app.aaps.pump.equil.manager.Utils @@ -11,9 +11,9 @@ class CmdExtendedBolusSet( var durationInMinutes: Int, var cancel: Boolean, aapsLogger: AAPSLogger, - sp: SP, + preferences: Preferences, equilManager: EquilManager -) : BaseSetting(System.currentTimeMillis(), aapsLogger, sp, equilManager) { +) : BaseSetting(System.currentTimeMillis(), aapsLogger, preferences, equilManager) { var step: Int = 0 var pumpTime: Int = 0 diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdHistoryGet.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdHistoryGet.kt index d374bc6c7bb..2f8474754f4 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdHistoryGet.kt +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdHistoryGet.kt @@ -2,7 +2,7 @@ package app.aaps.pump.equil.manager.command import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.logging.LTag -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.equil.database.EquilHistoryRecord import app.aaps.pump.equil.manager.EquilManager import app.aaps.pump.equil.manager.Utils @@ -10,9 +10,9 @@ import app.aaps.pump.equil.manager.Utils class CmdHistoryGet( var currentIndex: Int, aapsLogger: AAPSLogger, - sp: SP, + preferences: Preferences, equilManager: EquilManager -) : BaseSetting(System.currentTimeMillis(), aapsLogger, sp, equilManager) { +) : BaseSetting(System.currentTimeMillis(), aapsLogger, preferences, equilManager) { private var battery = 0 private var medicine = 0 diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdInsulinChange.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdInsulinChange.kt index 800bd45ed8c..691a87e798f 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdInsulinChange.kt +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdInsulinChange.kt @@ -2,16 +2,16 @@ package app.aaps.pump.equil.manager.command import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.logging.LTag -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.equil.database.EquilHistoryRecord import app.aaps.pump.equil.manager.EquilManager import app.aaps.pump.equil.manager.Utils class CmdInsulinChange( aapsLogger: AAPSLogger, - sp: SP, + preferences: Preferences, equilManager: EquilManager -) : BaseSetting(System.currentTimeMillis(), aapsLogger, sp, equilManager) { +) : BaseSetting(System.currentTimeMillis(), aapsLogger, preferences, equilManager) { override fun getFirstData(): ByteArray { val indexByte = Utils.intToBytes(pumpReqIndex) diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdInsulinGet.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdInsulinGet.kt index bafa7ee8514..54d53a089ed 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdInsulinGet.kt +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdInsulinGet.kt @@ -1,16 +1,16 @@ package app.aaps.pump.equil.manager.command import app.aaps.core.interfaces.logging.AAPSLogger -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.equil.database.EquilHistoryRecord import app.aaps.pump.equil.manager.EquilManager import app.aaps.pump.equil.manager.Utils class CmdInsulinGet( aapsLogger: AAPSLogger, - sp: SP, + preferences: Preferences, equilManager: EquilManager -) : BaseSetting(System.currentTimeMillis(), aapsLogger, sp, equilManager) { +) : BaseSetting(System.currentTimeMillis(), aapsLogger, preferences, equilManager) { init { this.port = "0505" diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdLargeBasalSet.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdLargeBasalSet.kt index 4cc2ac9d23b..1baad146f81 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdLargeBasalSet.kt +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdLargeBasalSet.kt @@ -2,7 +2,7 @@ package app.aaps.pump.equil.manager.command import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.logging.LTag -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.equil.database.EquilHistoryRecord import app.aaps.pump.equil.manager.EquilManager import app.aaps.pump.equil.manager.Utils @@ -10,9 +10,9 @@ import app.aaps.pump.equil.manager.Utils class CmdLargeBasalSet( var insulin: Double, aapsLogger: AAPSLogger, - sp: SP, + preferences: Preferences, equilManager: EquilManager -) : BaseSetting(System.currentTimeMillis(), aapsLogger, sp, equilManager) { +) : BaseSetting(System.currentTimeMillis(), aapsLogger, preferences, equilManager) { var step: Int = 0 var stepTime: Int = 0 diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdModelGet.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdModelGet.kt index c5409c47e0a..5931739ecab 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdModelGet.kt +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdModelGet.kt @@ -2,16 +2,16 @@ package app.aaps.pump.equil.manager.command import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.logging.LTag -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.equil.database.EquilHistoryRecord import app.aaps.pump.equil.manager.EquilManager import app.aaps.pump.equil.manager.Utils class CmdModelGet( aapsLogger: AAPSLogger, - sp: SP, + preferences: Preferences, equilManager: EquilManager -) : BaseSetting(System.currentTimeMillis(), aapsLogger, sp, equilManager) { +) : BaseSetting(System.currentTimeMillis(), aapsLogger, preferences, equilManager) { override fun getFirstData(): ByteArray { val indexByte = Utils.intToBytes(pumpReqIndex) diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdModelSet.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdModelSet.kt index 81677b15e08..ae2e8b1b6a0 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdModelSet.kt +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdModelSet.kt @@ -1,7 +1,7 @@ package app.aaps.pump.equil.manager.command import app.aaps.core.interfaces.logging.AAPSLogger -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.equil.data.RunMode import app.aaps.pump.equil.database.EquilHistoryRecord import app.aaps.pump.equil.manager.EquilManager @@ -10,9 +10,9 @@ import app.aaps.pump.equil.manager.Utils class CmdModelSet( var mode: Int, aapsLogger: AAPSLogger, - sp: SP, + preferences: Preferences, equilManager: EquilManager -) : BaseSetting(System.currentTimeMillis(), aapsLogger, sp, equilManager) { +) : BaseSetting(System.currentTimeMillis(), aapsLogger, preferences, equilManager) { fun getMode(): RunMode = when (mode) { diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdPair.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdPair.kt index ffaba58701a..1333641d008 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdPair.kt +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdPair.kt @@ -3,10 +3,9 @@ package app.aaps.pump.equil.manager.command import android.util.Log import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.logging.LTag -import app.aaps.core.interfaces.sharedPreferences.SP -import app.aaps.pump.equil.EquilConst.Prefs.EQUIL_DEVICES -import app.aaps.pump.equil.EquilConst.Prefs.EQUIL_PASSWORD +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.equil.database.EquilHistoryRecord +import app.aaps.pump.equil.keys.EquilStringKey import app.aaps.pump.equil.manager.AESUtil import app.aaps.pump.equil.manager.EquilManager import app.aaps.pump.equil.manager.EquilResponse @@ -20,9 +19,9 @@ class CmdPair( var address: String, private var password: String, aapsLogger: AAPSLogger, - sp: SP, + preferences: Preferences, equilManager: EquilManager -) : BaseCmd(System.currentTimeMillis(), aapsLogger, sp, equilManager) { +) : BaseCmd(System.currentTimeMillis(), aapsLogger, preferences, equilManager) { var sn: String? @@ -129,8 +128,8 @@ class CmdPair( return null } - sp.putString(EQUIL_PASSWORD, pwd2) - sp.putString(EQUIL_DEVICES, pwd1) + preferences.put(EquilStringKey.Password, pwd2) + preferences.put(EquilStringKey.Devices, pwd1) runPwd = pwd2 val data1 = Utils.hexStringToBytes(pwd1) val data = Utils.concat(data1, keyBytes) diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdResistanceGet.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdResistanceGet.kt index a5a071747a2..56ed01e69ee 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdResistanceGet.kt +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdResistanceGet.kt @@ -1,7 +1,7 @@ package app.aaps.pump.equil.manager.command import app.aaps.core.interfaces.logging.AAPSLogger -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.equil.database.EquilHistoryRecord import app.aaps.pump.equil.manager.AESUtil import app.aaps.pump.equil.manager.EquilManager @@ -10,9 +10,9 @@ import app.aaps.pump.equil.manager.Utils class CmdResistanceGet( aapsLogger: AAPSLogger, - sp: SP, + preferences: Preferences, equilManager: EquilManager -) : BaseSetting(System.currentTimeMillis(), aapsLogger, sp, equilManager) { +) : BaseSetting(System.currentTimeMillis(), aapsLogger, preferences, equilManager) { init { port = "1515" diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdSettingGet.kt.unused b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdSettingGet.kt.unused index 887284252bd..8870f5445c2 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdSettingGet.kt.unused +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdSettingGet.kt.unused @@ -2,16 +2,15 @@ package app.aaps.pump.equil.manager.command import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.logging.LTag -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.pump.equil.database.EquilHistoryRecord import app.aaps.pump.equil.manager.EquilManager import app.aaps.pump.equil.manager.Utils class CmdSettingGet( aapsLogger: AAPSLogger, - sp: SP, + preferences: Preferences, equilManager: EquilManager -) : BaseSetting(System.currentTimeMillis(), aapsLogger, sp, equilManager) { +) : BaseSetting(System.currentTimeMillis(), aapsLogger, preferences, equilManager) { private var useTime: Long = 0 private var closeTime: Long = 0 diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdSettingSet.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdSettingSet.kt index 2a22717cdf9..d9ddfbf7be0 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdSettingSet.kt +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdSettingSet.kt @@ -2,7 +2,7 @@ package app.aaps.pump.equil.manager.command import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.logging.LTag -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.equil.EquilConst import app.aaps.pump.equil.database.EquilHistoryRecord import app.aaps.pump.equil.manager.EquilManager @@ -11,12 +11,12 @@ import app.aaps.pump.equil.manager.Utils class CmdSettingSet( maxBolus: Double? = null, aapsLogger: AAPSLogger, - sp: SP, + preferences: Preferences, equilManager: EquilManager -) : BaseSetting(System.currentTimeMillis(), aapsLogger, sp, equilManager) { +) : BaseSetting(System.currentTimeMillis(), aapsLogger, preferences, equilManager) { var lowAlarm: Double = 0.0 - var bolusThresholdStep: Int = EquilConst.EQUIL_BLOUS_THRESHOLD_STEP + var bolusThresholdStep: Int = EquilConst.EQUIL_BOLUS_THRESHOLD_STEP init { maxBolus?.let { bolusThresholdStep = Utils.decodeSpeedToUH(maxBolus) } diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdStepSet.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdStepSet.kt index 91b0bf845a9..333853de28d 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdStepSet.kt +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdStepSet.kt @@ -1,7 +1,7 @@ package app.aaps.pump.equil.manager.command import app.aaps.core.interfaces.logging.AAPSLogger -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.equil.database.EquilHistoryRecord import app.aaps.pump.equil.manager.AESUtil import app.aaps.pump.equil.manager.EquilManager @@ -11,9 +11,9 @@ import app.aaps.pump.equil.manager.Utils class CmdStepSet( var sendConfig: Boolean, var step: Int, aapsLogger: AAPSLogger, - sp: SP, + preferences: Preferences, equilManager: EquilManager -) : BaseSetting(System.currentTimeMillis(), aapsLogger, sp, equilManager) { +) : BaseSetting(System.currentTimeMillis(), aapsLogger, preferences, equilManager) { override fun getFirstData(): ByteArray { val indexByte = Utils.intToBytes(pumpReqIndex) diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdTempBasalGet.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdTempBasalGet.kt index 5066e671da8..eca5faf0f78 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdTempBasalGet.kt +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdTempBasalGet.kt @@ -2,16 +2,16 @@ package app.aaps.pump.equil.manager.command import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.logging.LTag -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.equil.database.EquilHistoryRecord import app.aaps.pump.equil.manager.EquilManager import app.aaps.pump.equil.manager.Utils class CmdTempBasalGet( aapsLogger: AAPSLogger, - sp: SP, + preferences: Preferences, equilManager: EquilManager -) : BaseSetting(System.currentTimeMillis(), aapsLogger, sp, equilManager) { +) : BaseSetting(System.currentTimeMillis(), aapsLogger, preferences, equilManager) { var time = 0 private var step = 0 diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdTempBasalSet.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdTempBasalSet.kt index d252a029bc5..92171687bab 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdTempBasalSet.kt +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdTempBasalSet.kt @@ -2,7 +2,7 @@ package app.aaps.pump.equil.manager.command import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.logging.LTag -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.equil.database.EquilHistoryRecord import app.aaps.pump.equil.manager.EquilManager import app.aaps.pump.equil.manager.Utils @@ -10,9 +10,9 @@ import app.aaps.pump.equil.manager.Utils class CmdTempBasalSet( var insulin: Double, var duration: Int, aapsLogger: AAPSLogger, - sp: SP, + preferences: Preferences, equilManager: EquilManager -) : BaseSetting(System.currentTimeMillis(), aapsLogger, sp, equilManager) { +) : BaseSetting(System.currentTimeMillis(), aapsLogger, preferences, equilManager) { var step: Int = 0 var pumpTime: Int diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdTimeGet.kt.unused b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdTimeGet.kt.unused index 6c47237df25..0674d4fd25e 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdTimeGet.kt.unused +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdTimeGet.kt.unused @@ -1,16 +1,15 @@ package app.aaps.pump.equil.manager.command import app.aaps.core.interfaces.logging.AAPSLogger -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.pump.equil.database.EquilHistoryRecord import app.aaps.pump.equil.manager.EquilManager import app.aaps.pump.equil.manager.Utils class CmdTimeGet( aapsLogger: AAPSLogger, - sp: SP, + preferences: Preferences, equilManager: EquilManager -) : BaseSetting(System.currentTimeMillis(), aapsLogger, sp, equilManager) { +) : BaseSetting(System.currentTimeMillis(), aapsLogger, preferences, equilManager) { init { port = "0505" diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdTimeSet.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdTimeSet.kt index 6258ae85add..94b99ad68c7 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdTimeSet.kt +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdTimeSet.kt @@ -1,7 +1,7 @@ package app.aaps.pump.equil.manager.command import app.aaps.core.interfaces.logging.AAPSLogger -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.equil.database.EquilHistoryRecord import app.aaps.pump.equil.manager.EquilManager import app.aaps.pump.equil.manager.Utils @@ -9,9 +9,9 @@ import java.util.Calendar class CmdTimeSet( aapsLogger: AAPSLogger, - sp: SP, + preferences: Preferences, equilManager: EquilManager -) : BaseSetting(System.currentTimeMillis(), aapsLogger, sp, equilManager) { +) : BaseSetting(System.currentTimeMillis(), aapsLogger, preferences, equilManager) { init { port = "0505" diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdTmepBasalGet.kt.unused b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdTmepBasalGet.kt.unused index fe9a24811db..63a6f91cf92 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdTmepBasalGet.kt.unused +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdTmepBasalGet.kt.unused @@ -1,16 +1,15 @@ package app.aaps.pump.equil.manager.command import app.aaps.core.interfaces.logging.AAPSLogger -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.pump.equil.database.EquilHistoryRecord import app.aaps.pump.equil.manager.EquilManager import app.aaps.pump.equil.manager.Utils class CmdTmepBasalGet( aapsLogger: AAPSLogger, - sp: SP, + preferences: Preferences, equilManager: EquilManager -) : BaseSetting(System.currentTimeMillis(), aapsLogger, sp, equilManager) { +) : BaseSetting(System.currentTimeMillis(), aapsLogger, preferences, equilManager) { override fun getFirstData(): ByteArray { val indexByte = Utils.intToBytes(pumpReqIndex) diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdUnPair.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdUnPair.kt index 552afa5217d..4aa06b2c282 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdUnPair.kt +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/CmdUnPair.kt @@ -2,7 +2,7 @@ package app.aaps.pump.equil.manager.command import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.logging.LTag -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.equil.database.EquilHistoryRecord import app.aaps.pump.equil.manager.AESUtil import app.aaps.pump.equil.manager.EquilManager @@ -15,9 +15,9 @@ import java.security.MessageDigest class CmdUnPair( name: String, val password: String, aapsLogger: AAPSLogger, - sp: SP, + preferences: Preferences, equilManager: EquilManager -) : BaseCmd(System.currentTimeMillis(), aapsLogger, sp, equilManager) { +) : BaseCmd(System.currentTimeMillis(), aapsLogger, preferences, equilManager) { var sn: String? var randomPassword: ByteArray? = null diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/SettingCmd.kt.unused b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/SettingCmd.kt.unused index d7ba8f51f16..f8e41b75340 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/SettingCmd.kt.unused +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/manager/command/SettingCmd.kt.unused @@ -1,16 +1,15 @@ package app.aaps.pump.equil.manager.command import app.aaps.core.interfaces.logging.AAPSLogger -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.pump.equil.database.EquilHistoryRecord import app.aaps.pump.equil.manager.EquilManager import app.aaps.pump.equil.manager.Utils class SettingCmd( aapsLogger: AAPSLogger, - sp: SP, + preferences: Preferences, equilManager: EquilManager -) : BaseSetting(System.currentTimeMillis(), aapsLogger, sp, equilManager) { +) : BaseSetting(System.currentTimeMillis(), aapsLogger, preferences, equilManager) { fun getData(): ByteArray { val indexByte = Utils.intToBytes(pumpReqIndex) diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/ui/EquilHistoryRecordActivity.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/ui/EquilHistoryRecordActivity.kt index 3450f6a37a3..01d1375ffa5 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/ui/EquilHistoryRecordActivity.kt +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/ui/EquilHistoryRecordActivity.kt @@ -22,7 +22,6 @@ import app.aaps.core.interfaces.queue.CommandQueue import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.AapsSchedulers import app.aaps.core.interfaces.rx.bus.RxBus -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.fabric.FabricPrivacy import app.aaps.core.ui.activities.TranslatedDaggerAppCompatActivity @@ -51,7 +50,6 @@ import kotlin.math.abs // IMPORTANT: This activity needs to be called from RileyLinkSelectPreference (see pref_medtronic.xml as example) class EquilHistoryRecordActivity : TranslatedDaggerAppCompatActivity() { - @Inject lateinit var sp: SP @Inject lateinit var blePreCheck: BlePreCheck @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var context: Context diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/ui/EquilUnPairActivity.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/ui/EquilUnPairActivity.kt index 71a319b5ac1..5954752c37a 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/ui/EquilUnPairActivity.kt +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/ui/EquilUnPairActivity.kt @@ -15,12 +15,13 @@ import app.aaps.core.interfaces.queue.Callback import app.aaps.core.interfaces.queue.CommandQueue import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.bus.RxBus -import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.ui.activities.TranslatedDaggerAppCompatActivity import app.aaps.pump.equil.EquilPumpPlugin import app.aaps.pump.equil.R import app.aaps.pump.equil.databinding.EquilUnpairActivityBinding import app.aaps.pump.equil.events.EventEquilUnPairChanged +import app.aaps.pump.equil.keys.EquilStringKey import app.aaps.pump.equil.manager.EquilManager import app.aaps.pump.equil.manager.command.CmdUnPair import app.aaps.pump.equil.ui.dlg.LoadingDlg @@ -29,7 +30,7 @@ import javax.inject.Inject // IMPORTANT: This activity needs to be called from RileyLinkSelectPreference (see pref_medtronic.xml as example) class EquilUnPairActivity : TranslatedDaggerAppCompatActivity() { - @Inject lateinit var sp: SP + @Inject lateinit var preferences: Preferences @Inject lateinit var blePreCheck: BlePreCheck @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var context: Context @@ -84,7 +85,7 @@ class EquilUnPairActivity : TranslatedDaggerAppCompatActivity() { private fun unpair(name: String) { showLoading() - commandQueue.customCommand(CmdUnPair(name, sp.getString(rh.gs(R.string.key_equil_pair_password), ""), aapsLogger, sp, equilManager), object : Callback() { + commandQueue.customCommand(CmdUnPair(name, preferences.get(EquilStringKey.PairPassword), aapsLogger, preferences, equilManager), object : Callback() { override fun run() { dismissLoading() if (result.success) { diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/ui/EquilUnPairDetachActivity.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/ui/EquilUnPairDetachActivity.kt index 9504255a761..3bfb0b25b00 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/ui/EquilUnPairDetachActivity.kt +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/ui/EquilUnPairDetachActivity.kt @@ -15,8 +15,8 @@ import app.aaps.core.interfaces.queue.CommandQueue import app.aaps.core.interfaces.resources.ResourceHelper import app.aaps.core.interfaces.rx.AapsSchedulers import app.aaps.core.interfaces.rx.bus.RxBus -import app.aaps.core.interfaces.sharedPreferences.SP import app.aaps.core.interfaces.utils.fabric.FabricPrivacy +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.ui.activities.TranslatedDaggerAppCompatActivity import app.aaps.pump.equil.EquilPumpPlugin import app.aaps.pump.equil.R @@ -35,7 +35,7 @@ import javax.inject.Inject // IMPORTANT: This activity needs to be called from RileyLinkSelectPreference (see pref_medtronic.xml as example) class EquilUnPairDetachActivity : TranslatedDaggerAppCompatActivity() { - @Inject lateinit var sp: SP + @Inject lateinit var preferences: Preferences @Inject lateinit var blePreCheck: BlePreCheck @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var context: Context @@ -93,7 +93,7 @@ class EquilUnPairDetachActivity : TranslatedDaggerAppCompatActivity() { private fun changeInsulin() { showLoading() - commandQueue.customCommand(CmdInsulinChange(aapsLogger, sp, equilManager), object : Callback() { + commandQueue.customCommand(CmdInsulinChange(aapsLogger, preferences, equilManager), object : Callback() { override fun run() { if (!result.success) equilPumpPlugin.showToast(rh.gs(R.string.equil_error)) equilManager.setRunMode(RunMode.STOP) diff --git a/pump/equil/src/main/kotlin/app/aaps/pump/equil/ui/pair/EquilChangeInsulinFragment.kt b/pump/equil/src/main/kotlin/app/aaps/pump/equil/ui/pair/EquilChangeInsulinFragment.kt index dbe67f169cf..8e101339ecb 100644 --- a/pump/equil/src/main/kotlin/app/aaps/pump/equil/ui/pair/EquilChangeInsulinFragment.kt +++ b/pump/equil/src/main/kotlin/app/aaps/pump/equil/ui/pair/EquilChangeInsulinFragment.kt @@ -28,7 +28,7 @@ class EquilChangeInsulinFragment : EquilPairFragmentBase() { view.findViewById