From 7f8abcf591d969bc4d393b9d3f149932539bc502 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Fri, 27 Dec 2019 19:20:38 +0100 Subject: [PATCH] Constraints, Dialogs daggerize --- .../info/nightscout/androidaps/MainApp.java | 10 +- .../androidaps/data/ConstraintChecker.java | 237 ------------------ .../dependencyInjection/AppModule.kt | 7 + .../dependencyInjection/FragmentsModule.kt | 38 +++ .../androidaps/dialogs/CalibrationDialog.kt | 27 +- .../androidaps/dialogs/CarbsDialog.kt | 54 ++-- .../androidaps/dialogs/CareDialog.kt | 24 +- .../dialogs/DialogFragmentWithDate.kt | 4 +- .../androidaps/dialogs/ExtendedBolusDialog.kt | 30 ++- .../androidaps/dialogs/FillDialog.kt | 56 +++-- .../androidaps/dialogs/InsulinDialog.kt | 72 +++--- .../androidaps/dialogs/ProfileSwitchDialog.kt | 31 ++- .../androidaps/dialogs/ProfileViewerDialog.kt | 13 +- .../androidaps/dialogs/TempBasalDialog.kt | 44 ++-- .../androidaps/dialogs/TempTargetDialog.kt | 66 +++-- .../androidaps/dialogs/TreatmentDialog.kt | 46 ++-- .../androidaps/dialogs/WizardDialog.kt | 95 ++++--- .../interfaces/ConstraintsInterface.kt.ignore | 62 +++++ .../plugins/aps/loop/APSResult.java | 3 +- .../plugins/aps/loop/LoopPlugin.java | 13 +- .../DetermineBasalAdapterAMAJS.java | 10 +- .../aps/openAPSAMA/OpenAPSAMAPlugin.java | 7 +- .../aps/openAPSMA/OpenAPSMAPlugin.java | 5 +- .../DetermineBasalAdapterSMBJS.java | 9 +- .../aps/openAPSSMB/OpenAPSSMBPlugin.java | 16 +- .../configBuilder/ConfigBuilderPlugin.java | 14 +- .../configBuilder/ConstraintChecker.kt | 205 +++++++++++++++ .../objectives/objectives/Objective6.java | 4 +- .../constraints/safety/SafetyPlugin.java | 5 +- .../Dialogs/NewNSTreatmentDialog.java | 9 +- .../general/overview/OverviewFragment.java | 6 +- .../smsCommunicator/SmsCommunicatorPlugin.kt | 15 +- .../general/wear/ActionStringHandler.java | 17 +- .../pump/danaR/AbstractDanaRPlugin.java | 5 +- .../plugins/pump/danaR/DanaRPlugin.java | 7 +- .../pump/danaR/comm/MsgBolusStart.java | 4 +- .../danaR/comm/MsgBolusStartWithSpeed.java | 4 +- .../danaR/comm/MsgSetExtendedBolusStart.java | 11 +- .../pump/danaRKorean/DanaRKoreanPlugin.java | 7 +- .../plugins/pump/danaRS/DanaRSPlugin.java | 11 +- ...aRS_Packet_Bolus_Set_Step_Bolus_Start.java | 4 +- .../plugins/pump/danaRv2/DanaRv2Plugin.java | 7 +- .../androidaps/queue/CommandQueue.java | 15 +- .../androidaps/utils/BolusWizard.kt | 3 +- .../androidaps/utils/FabricPrivacy.java | 3 +- app/src/test/java/info/AAPSMocker.java | 6 +- .../interfaces/ConstraintsCheckerTest.java | 6 +- .../plugins/aps/loop/APSResultTest.java | 2 +- .../constraints/safety/SafetyPluginTest.java | 4 +- .../SmsCommunicatorPluginTest.java | 19 +- .../androidaps/queue/CommandQueueTest.java | 12 +- .../androidaps/utils/BolusWizardTest.java | 2 +- 52 files changed, 808 insertions(+), 578 deletions(-) delete mode 100644 app/src/main/java/info/nightscout/androidaps/data/ConstraintChecker.java create mode 100644 app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.kt.ignore create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConstraintChecker.kt diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java index 9e5ccb7879..5ff629fb9a 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java @@ -27,7 +27,6 @@ import javax.inject.Inject; import dagger.android.AndroidInjector; import dagger.android.DaggerApplication; -import info.nightscout.androidaps.data.ConstraintChecker; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.dependencyInjection.DaggerAppComponent; @@ -112,7 +111,6 @@ public class MainApp extends DaggerApplication { static FirebaseAnalytics mFirebaseAnalytics; static DatabaseHelper sDatabaseHelper = null; - static ConstraintChecker sConstraintsChecker = null; static ArrayList pluginsList = null; @@ -138,7 +136,6 @@ public class MainApp extends DaggerApplication { sInstance = this; sResources = getResources(); LocaleHelper.INSTANCE.update(this); - sConstraintsChecker = new ConstraintChecker(); sDatabaseHelper = OpenHelperManager.getHelper(sInstance, DatabaseHelper.class); Thread.setDefaultUncaughtExceptionHandler((thread, ex) -> { @@ -258,7 +255,6 @@ public class MainApp extends DaggerApplication { } - private void doMigrations() { // guarantee that the unreachable threshold is at least 30 and of type String @@ -345,10 +341,6 @@ public class MainApp extends DaggerApplication { return mFirebaseAnalytics; } - public static ConstraintChecker getConstraintChecker() { - return sConstraintsChecker; - } - public static ArrayList getPluginsList() { return pluginsList; } @@ -382,7 +374,7 @@ public class MainApp extends DaggerApplication { return newList; } - public static ArrayList getSpecificPluginsListByInterface(Class interfaceClass) { + public ArrayList getSpecificPluginsListByInterface(Class interfaceClass) { ArrayList newList = new ArrayList<>(); if (pluginsList != null) { diff --git a/app/src/main/java/info/nightscout/androidaps/data/ConstraintChecker.java b/app/src/main/java/info/nightscout/androidaps/data/ConstraintChecker.java deleted file mode 100644 index 9d7a49493b..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/data/ConstraintChecker.java +++ /dev/null @@ -1,237 +0,0 @@ -package info.nightscout.androidaps.data; - -import androidx.annotation.NonNull; - -import java.util.ArrayList; - -import info.nightscout.androidaps.Constants; -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.interfaces.Constraint; -import info.nightscout.androidaps.interfaces.ConstraintsInterface; -import info.nightscout.androidaps.interfaces.PluginBase; -import info.nightscout.androidaps.interfaces.PluginType; - -/** - * Created by mike on 19.03.2018. - */ - -public class ConstraintChecker implements ConstraintsInterface { - - public Constraint isLoopInvokationAllowed() { - return isLoopInvocationAllowed(new Constraint<>(true)); - } - - public Constraint isClosedLoopAllowed() { - return isClosedLoopAllowed(new Constraint<>(true)); - } - - public Constraint isAutosensModeEnabled() { - return isAutosensModeEnabled(new Constraint<>(true)); - } - - public Constraint isAMAModeEnabled() { - return isAMAModeEnabled(new Constraint<>(true)); - } - - public Constraint isSMBModeEnabled() { - return isSMBModeEnabled(new Constraint<>(true)); - } - - public Constraint isUAMEnabled() { - return isUAMEnabled(new Constraint<>(true)); - } - - public Constraint isAdvancedFilteringEnabled() { - return isAdvancedFilteringEnabled(new Constraint<>(true)); - } - - public Constraint isSuperBolusEnabled() { - return isSuperBolusEnabled(new Constraint<>(true)); - } - - public Constraint getMaxBasalAllowed(Profile profile) { - return applyBasalConstraints(new Constraint<>(Constants.REALLYHIGHBASALRATE), profile); - } - - public Constraint getMaxBasalPercentAllowed(Profile profile) { - return applyBasalPercentConstraints(new Constraint<>(Constants.REALLYHIGHPERCENTBASALRATE), profile); - } - - public Constraint getMaxBolusAllowed() { - return applyBolusConstraints(new Constraint<>(Constants.REALLYHIGHBOLUS)); - } - - public Constraint getMaxExtendedBolusAllowed() { - return applyExtendedBolusConstraints(new Constraint<>(Constants.REALLYHIGHBOLUS)); - } - - public Constraint getMaxCarbsAllowed() { - return applyCarbsConstraints(new Constraint<>(Constants.REALLYHIGHCARBS)); - } - - public Constraint getMaxIOBAllowed() { - return applyMaxIOBConstraints(new Constraint<>(Constants.REALLYHIGHIOB)); - } - - @Override - public Constraint isLoopInvocationAllowed(@NonNull Constraint value) { - - ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); - for (PluginBase p : constraintsPlugins) { - ConstraintsInterface constraint = (ConstraintsInterface) p; - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue; - constraint.isLoopInvocationAllowed(value); - } - return value; - } - - @Override - public Constraint isClosedLoopAllowed(@NonNull Constraint value) { - - ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); - for (PluginBase p : constraintsPlugins) { - ConstraintsInterface constraint = (ConstraintsInterface) p; - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue; - constraint.isClosedLoopAllowed(value); - } - return value; - } - - @Override - public Constraint isAutosensModeEnabled(@NonNull Constraint value) { - - ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); - for (PluginBase p : constraintsPlugins) { - ConstraintsInterface constraint = (ConstraintsInterface) p; - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue; - constraint.isAutosensModeEnabled(value); - } - return value; - } - - @Override - public Constraint isAMAModeEnabled(@NonNull Constraint value) { - - ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); - for (PluginBase p : constraintsPlugins) { - ConstraintsInterface constrain = (ConstraintsInterface) p; - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue; - constrain.isAMAModeEnabled(value); - } - return value; - } - - @Override - public Constraint isSMBModeEnabled(@NonNull Constraint value) { - - ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); - for (PluginBase p : constraintsPlugins) { - ConstraintsInterface constraint = (ConstraintsInterface) p; - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue; - constraint.isSMBModeEnabled(value); - } - return value; - } - - @Override - public Constraint isUAMEnabled(@NonNull Constraint value) { - - ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); - for (PluginBase p : constraintsPlugins) { - ConstraintsInterface constraint = (ConstraintsInterface) p; - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue; - constraint.isUAMEnabled(value); - } - return value; - } - - @Override - public Constraint isAdvancedFilteringEnabled(@NonNull Constraint value) { - ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); - for (PluginBase p : constraintsPlugins) { - ConstraintsInterface constraint = (ConstraintsInterface) p; - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue; - constraint.isAdvancedFilteringEnabled(value); - } - return value; - } - - @Override - public Constraint isSuperBolusEnabled(@NonNull Constraint value) { - ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); - for (PluginBase p : constraintsPlugins) { - ConstraintsInterface constraint = (ConstraintsInterface) p; - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue; - constraint.isSuperBolusEnabled(value); - } - return value; - } - - @Override - public Constraint applyBasalConstraints(@NonNull Constraint absoluteRate, Profile profile) { - ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); - for (PluginBase p : constraintsPlugins) { - ConstraintsInterface constraint = (ConstraintsInterface) p; - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue; - constraint.applyBasalConstraints(absoluteRate, profile); - } - return absoluteRate; - } - - @Override - public Constraint applyBasalPercentConstraints(@NonNull Constraint percentRate, Profile profile) { - ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); - for (PluginBase p : constraintsPlugins) { - ConstraintsInterface constrain = (ConstraintsInterface) p; - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue; - constrain.applyBasalPercentConstraints(percentRate, profile); - } - return percentRate; - } - - @Override - public Constraint applyBolusConstraints(@NonNull Constraint insulin) { - ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); - for (PluginBase p : constraintsPlugins) { - ConstraintsInterface constrain = (ConstraintsInterface) p; - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue; - constrain.applyBolusConstraints(insulin); - } - return insulin; - } - - @Override - public Constraint applyExtendedBolusConstraints(@NonNull Constraint insulin) { - ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); - for (PluginBase p : constraintsPlugins) { - ConstraintsInterface constrain = (ConstraintsInterface) p; - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue; - constrain.applyExtendedBolusConstraints(insulin); - } - return insulin; - } - - @Override - public Constraint applyCarbsConstraints(@NonNull Constraint carbs) { - ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); - for (PluginBase p : constraintsPlugins) { - ConstraintsInterface constrain = (ConstraintsInterface) p; - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue; - constrain.applyCarbsConstraints(carbs); - } - return carbs; - } - - @Override - public Constraint applyMaxIOBConstraints(@NonNull Constraint maxIob) { - ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); - for (PluginBase p : constraintsPlugins) { - ConstraintsInterface constrain = (ConstraintsInterface) p; - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue; - constrain.applyMaxIOBConstraints(maxIob); - } - return maxIob; - } - - -} diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt index d031bf7267..9d51eda0a5 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -7,6 +7,7 @@ import dagger.Module import dagger.Provides import dagger.android.ContributesAndroidInjector import info.nightscout.androidaps.MainApp +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctionImplementation import info.nightscout.androidaps.plugins.general.automation.actions.ActionSendSMS @@ -33,6 +34,12 @@ class AppModule { return ProfileFunctionImplementation(sp) } + @Provides + @Singleton + fun provideConstraintChecker(mainApp: MainApp): ConstraintChecker { + return ConstraintChecker(mainApp) + } + @Provides @Singleton fun provideResources(mainApp: MainApp): ResourceHelper { diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt index 162f156fe3..ea7ba7e9e2 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt @@ -3,13 +3,51 @@ package info.nightscout.androidaps.dependencyInjection import dagger.Module import dagger.android.ContributesAndroidInjector import info.nightscout.androidaps.activities.MyPreferenceFragment +import info.nightscout.androidaps.dialogs.* import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorFragment @Module abstract class FragmentsModule { + @ContributesAndroidInjector abstract fun contributesPreferencesFragment(): MyPreferenceFragment @ContributesAndroidInjector abstract fun contributesSmsCommunicatorFragment(): SmsCommunicatorFragment + + @ContributesAndroidInjector + abstract fun contributesCalibrationDialog(): CalibrationDialog + + @ContributesAndroidInjector + abstract fun contributesCarbsDialog(): CarbsDialog + + @ContributesAndroidInjector + abstract fun contributesCareDialog(): CareDialog + + @ContributesAndroidInjector + abstract fun contributesExtendedBolusDialog(): ExtendedBolusDialog + + @ContributesAndroidInjector + abstract fun contributesFillDialog(): FillDialog + + @ContributesAndroidInjector + abstract fun contributesInsulinDialog(): InsulinDialog + + @ContributesAndroidInjector + abstract fun contributesProfileSwitchDialog(): ProfileSwitchDialog + + @ContributesAndroidInjector + abstract fun contributesProfileViewerDialog(): ProfileViewerDialog + + @ContributesAndroidInjector + abstract fun contributesTempBasalDialog(): TempBasalDialog + + @ContributesAndroidInjector + abstract fun contributesTempTargetDialog(): TempTargetDialog + + @ContributesAndroidInjector + abstract fun contributesTreatmentDialog(): TreatmentDialog + + @ContributesAndroidInjector + abstract fun contributesWizardDialog(): WizardDialog } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/CalibrationDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/CalibrationDialog.kt index 949e4e5fef..39b0b8a0f5 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/CalibrationDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/CalibrationDialog.kt @@ -6,21 +6,28 @@ import android.view.View import android.view.ViewGroup import com.google.common.base.Joiner import info.nightscout.androidaps.Constants -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.OKDialog import info.nightscout.androidaps.utils.XdripCalibrations +import info.nightscout.androidaps.utils.resources.ResourceHelper import kotlinx.android.synthetic.main.dialog_calibration.* import kotlinx.android.synthetic.main.okcancel.* import java.text.DecimalFormat import java.util.* +import javax.inject.Inject class CalibrationDialog : DialogFragmentWithDate() { + @Inject + lateinit var resourceHelper: ResourceHelper + + @Inject + lateinit var profileFunction: ProfileFunction + override fun onSaveInstanceState(savedInstanceState: Bundle) { super.onSaveInstanceState(savedInstanceState) savedInstanceState.putDouble("overview_calibration_bg", overview_calibration_bg.value) @@ -35,7 +42,7 @@ class CalibrationDialog : DialogFragmentWithDate() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) - val units = ProfileFunctions.getSystemUnits() + val units = profileFunction.getUnits() val bg = Profile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData()?.glucose ?: 0.0, units) if (units == Constants.MMOL) @@ -44,24 +51,24 @@ class CalibrationDialog : DialogFragmentWithDate() { else overview_calibration_bg.setParams(savedInstanceState?.getDouble("overview_calibration_bg") ?: bg, 36.0, 500.0, 1.0, DecimalFormat("0"), false, ok) - overview_calibration_units.text = if (units == Constants.MMOL) MainApp.gs(R.string.mmol) else MainApp.gs(R.string.mgdl) + overview_calibration_units.text = if (units == Constants.MMOL) resourceHelper.gs(R.string.mmol) else resourceHelper.gs(R.string.mgdl) } - override fun submit() :Boolean { - val units = ProfileFunctions.getSystemUnits() - val unitLabel = if (units == Constants.MMOL) MainApp.gs(R.string.mmol) else MainApp.gs(R.string.mgdl) + override fun submit(): Boolean { + val units = profileFunction.getUnits() + val unitLabel = if (units == Constants.MMOL) resourceHelper.gs(R.string.mmol) else resourceHelper.gs(R.string.mgdl) val actions: LinkedList = LinkedList() val bg = overview_calibration_bg.value - actions.add(MainApp.gs(R.string.treatments_wizard_bg_label) + ": " + Profile.toCurrentUnitsString(bg) + " " + unitLabel) + actions.add(resourceHelper.gs(R.string.treatments_wizard_bg_label) + ": " + Profile.toCurrentUnitsString(bg) + " " + unitLabel) if (bg > 0) { activity?.let { activity -> - OKDialog.showConfirmation(activity, MainApp.gs(R.string.overview_calibration), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { + OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.overview_calibration), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { XdripCalibrations.confirmAndSendCalibration(bg, context) }) } } else activity?.let { activity -> - OKDialog.show(activity, MainApp.gs(R.string.overview_calibration), MainApp.gs(R.string.no_action_selected)) + OKDialog.show(activity, resourceHelper.gs(R.string.overview_calibration), resourceHelper.gs(R.string.no_action_selected)) } return true } diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt index 4e0e2980e8..b7acc5cc58 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt @@ -16,28 +16,38 @@ import info.nightscout.androidaps.db.DatabaseHelper import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.db.TempTarget import info.nightscout.androidaps.interfaces.Constraint +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.treatments.CarbsGenerator import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.* +import info.nightscout.androidaps.utils.resources.ResourceHelper import kotlinx.android.synthetic.main.dialog_carbs.* import kotlinx.android.synthetic.main.notes.* import kotlinx.android.synthetic.main.okcancel.* import java.text.DecimalFormat import java.util.* +import javax.inject.Inject import kotlin.math.max class CarbsDialog : DialogFragmentWithDate() { + @Inject + lateinit var mainApp: MainApp + + @Inject + lateinit var resourceHelper: ResourceHelper + + @Inject + lateinit var constraintChecker: ConstraintChecker + companion object { private const val FAV1_DEFAULT = 5 private const val FAV2_DEFAULT = 10 private const val FAV3_DEFAULT = 20 } - private val maxCarbs = MainApp.getConstraintChecker().maxCarbsAllowed.value().toDouble() - private val textWatcher: TextWatcher = object : TextWatcher { override fun afterTextChanged(s: Editable) { validateInputs() @@ -48,18 +58,19 @@ class CarbsDialog : DialogFragmentWithDate() { } private fun validateInputs() { + val maxCarbs = constraintChecker.getMaxCarbsAllowed().value().toDouble() val time = overview_carbs_time.value.toInt() if (time > 12 * 60 || time < -12 * 60) { overview_carbs_time.value = 0.0 - ToastUtils.showToastInUiThread(MainApp.instance().applicationContext, MainApp.gs(R.string.constraintapllied)) + ToastUtils.showToastInUiThread(mainApp, resourceHelper.gs(R.string.constraintapllied)) } if (overview_carbs_duration.value > 10) { overview_carbs_duration.value = 0.0 - ToastUtils.showToastInUiThread(MainApp.instance().applicationContext, MainApp.gs(R.string.constraintapllied)) + ToastUtils.showToastInUiThread(mainApp, resourceHelper.gs(R.string.constraintapllied)) } if (overview_carbs_carbs.value.toInt() > maxCarbs) { overview_carbs_carbs.value = 0.0 - ToastUtils.showToastInUiThread(MainApp.instance().applicationContext, MainApp.gs(R.string.carbsconstraintapplied)) + ToastUtils.showToastInUiThread(mainApp, resourceHelper.gs(R.string.carbsconstraintapplied)) } } @@ -79,6 +90,7 @@ class CarbsDialog : DialogFragmentWithDate() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) + val maxCarbs = constraintChecker.getMaxCarbsAllowed().value().toDouble() overview_carbs_time.setParams(savedInstanceState?.getDouble("overview_carbs_time") ?: 0.0, -12 * 60.0, 12 * 60.0, 5.0, DecimalFormat("0"), false, ok, textWatcher) @@ -133,7 +145,7 @@ class CarbsDialog : DialogFragmentWithDate() { override fun submit(): Boolean { val carbs = overview_carbs_carbs.value.toInt() - val carbsAfterConstraints = MainApp.getConstraintChecker().applyCarbsConstraints(Constraint(carbs)).value() + val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(carbs)).value() val units = ProfileFunctions.getSystemUnits() val activityTTDuration = DefaultValueHelper.determineActivityTTDuration() val activityTT = DefaultValueHelper.determineActivityTT() @@ -142,42 +154,42 @@ class CarbsDialog : DialogFragmentWithDate() { val hypoTTDuration = DefaultValueHelper.determineHypoTTDuration() val hypoTT = DefaultValueHelper.determineHypoTT() val actions: LinkedList = LinkedList() - val unitLabel = if (units == Constants.MMOL) MainApp.gs(R.string.mmol) else MainApp.gs(R.string.mgdl) + val unitLabel = if (units == Constants.MMOL) resourceHelper.gs(R.string.mmol) else resourceHelper.gs(R.string.mgdl) val activitySelected = overview_carbs_activity_tt.isChecked if (activitySelected) - actions.add(MainApp.gs(R.string.temptargetshort) + ": " + "" + DecimalFormatter.to1Decimal(activityTT) + " " + unitLabel + " (" + activityTTDuration + " " + MainApp.gs(R.string.unit_minute_short) + ")") + actions.add(resourceHelper.gs(R.string.temptargetshort) + ": " + "" + DecimalFormatter.to1Decimal(activityTT) + " " + unitLabel + " (" + activityTTDuration + " " + resourceHelper.gs(R.string.unit_minute_short) + ")") val eatingSoonSelected = overview_carbs_eating_soon_tt.isChecked if (eatingSoonSelected) - actions.add(MainApp.gs(R.string.temptargetshort) + ": " + "" + DecimalFormatter.to1Decimal(eatingSoonTT) + " " + unitLabel + " (" + eatingSoonTTDuration + " " + MainApp.gs(R.string.unit_minute_short) + ")") + actions.add(resourceHelper.gs(R.string.temptargetshort) + ": " + "" + DecimalFormatter.to1Decimal(eatingSoonTT) + " " + unitLabel + " (" + eatingSoonTTDuration + " " + resourceHelper.gs(R.string.unit_minute_short) + ")") val hypoSelected = overview_carbs_hypo_tt.isChecked if (hypoSelected) - actions.add(MainApp.gs(R.string.temptargetshort) + ": " + "" + DecimalFormatter.to1Decimal(hypoTT) + " " + unitLabel + " (" + hypoTTDuration + " " + MainApp.gs(R.string.unit_minute_short) + ")") + actions.add(resourceHelper.gs(R.string.temptargetshort) + ": " + "" + DecimalFormatter.to1Decimal(hypoTT) + " " + unitLabel + " (" + hypoTTDuration + " " + resourceHelper.gs(R.string.unit_minute_short) + ")") val timeOffset = overview_carbs_time.value.toInt() val time = DateUtil.now() + timeOffset * 1000 * 60 if (timeOffset != 0) - actions.add(MainApp.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(time)) + actions.add(resourceHelper.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(time)) val duration = overview_carbs_duration.value.toInt() if (duration > 0) - actions.add(MainApp.gs(R.string.duration) + ": " + duration + MainApp.gs(R.string.shorthour)) + actions.add(resourceHelper.gs(R.string.duration) + ": " + duration + resourceHelper.gs(R.string.shorthour)) if (carbsAfterConstraints > 0) { - actions.add(MainApp.gs(R.string.carbs) + ": " + "" + MainApp.gs(R.string.format_carbs, carbsAfterConstraints) + "") + actions.add(resourceHelper.gs(R.string.carbs) + ": " + "" + resourceHelper.gs(R.string.format_carbs, carbsAfterConstraints) + "") if (carbsAfterConstraints != carbs) - actions.add("" + MainApp.gs(R.string.carbsconstraintapplied) + "") + actions.add("" + resourceHelper.gs(R.string.carbsconstraintapplied) + "") } val notes = notes.text.toString() if (notes.isNotEmpty()) - actions.add(MainApp.gs(R.string.careportal_newnstreatment_notes_label) + ": " + notes) + actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_notes_label) + ": " + notes) if (carbsAfterConstraints > 0 || activitySelected || eatingSoonSelected || hypoSelected) { activity?.let { activity -> - OKDialog.showConfirmation(activity, MainApp.gs(R.string.carbs), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { + OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.carbs), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { if (activitySelected) { val tempTarget = TempTarget() .date(System.currentTimeMillis()) .duration(activityTTDuration) - .reason(MainApp.gs(R.string.activity)) + .reason(resourceHelper.gs(R.string.activity)) .source(Source.USER) .low(Profile.toMgdl(activityTT, ProfileFunctions.getSystemUnits())) .high(Profile.toMgdl(activityTT, ProfileFunctions.getSystemUnits())) @@ -186,7 +198,7 @@ class CarbsDialog : DialogFragmentWithDate() { val tempTarget = TempTarget() .date(System.currentTimeMillis()) .duration(eatingSoonTTDuration) - .reason(MainApp.gs(R.string.eatingsoon)) + .reason(resourceHelper.gs(R.string.eatingsoon)) .source(Source.USER) .low(Profile.toMgdl(eatingSoonTT, ProfileFunctions.getSystemUnits())) .high(Profile.toMgdl(eatingSoonTT, ProfileFunctions.getSystemUnits())) @@ -195,7 +207,7 @@ class CarbsDialog : DialogFragmentWithDate() { val tempTarget = TempTarget() .date(System.currentTimeMillis()) .duration(hypoTTDuration) - .reason(MainApp.gs(R.string.hypo)) + .reason(resourceHelper.gs(R.string.hypo)) .source(Source.USER) .low(Profile.toMgdl(hypoTT, ProfileFunctions.getSystemUnits())) .high(Profile.toMgdl(hypoTT, ProfileFunctions.getSystemUnits())) @@ -206,14 +218,14 @@ class CarbsDialog : DialogFragmentWithDate() { CarbsGenerator.createCarb(carbsAfterConstraints, time, CareportalEvent.CARBCORRECTION, notes) } else { CarbsGenerator.generateCarbs(carbsAfterConstraints, time, duration, notes) - NSUpload.uploadEvent(CareportalEvent.NOTE, DateUtil.now() - 2000, MainApp.gs(R.string.generated_ecarbs_note, carbsAfterConstraints, duration, timeOffset)) + NSUpload.uploadEvent(CareportalEvent.NOTE, DateUtil.now() - 2000, resourceHelper.gs(R.string.generated_ecarbs_note, carbsAfterConstraints, duration, timeOffset)) } } }, null) } } else activity?.let { activity -> - OKDialog.show(activity, MainApp.gs(R.string.carbs), MainApp.gs(R.string.no_action_selected)) + OKDialog.show(activity, resourceHelper.gs(R.string.carbs), resourceHelper.gs(R.string.no_action_selected)) } return true } diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt index 946a3fec5b..39329a94e8 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt @@ -21,15 +21,23 @@ import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.OKDialog import info.nightscout.androidaps.utils.SP import info.nightscout.androidaps.utils.Translator +import info.nightscout.androidaps.utils.resources.ResourceHelper import kotlinx.android.synthetic.main.dialog_care.* import kotlinx.android.synthetic.main.notes.* import kotlinx.android.synthetic.main.okcancel.* import org.json.JSONObject import java.text.DecimalFormat import java.util.* +import javax.inject.Inject class CareDialog : DialogFragmentWithDate() { + @Inject + lateinit var mainApp: MainApp + + @Inject + lateinit var resourceHelper: ResourceHelper + enum class EventType { BGCHECK, SENSOR_INSERT, @@ -65,7 +73,7 @@ class CareDialog : DialogFragmentWithDate() { EventType.SENSOR_INSERT -> R.drawable.icon_cp_cgm_insert EventType.BATTERY_CHANGE -> R.drawable.icon_cp_pump_battery }) - actions_care_title.text = MainApp.gs(when (options) { + actions_care_title.text = resourceHelper.gs(when (options) { EventType.BGCHECK -> R.string.careportal_bgcheck EventType.SENSOR_INSERT -> R.string.careportal_cgmsensorinsert EventType.BATTERY_CHANGE -> R.string.careportal_pumpbatterychange @@ -93,11 +101,11 @@ class CareDialog : DialogFragmentWithDate() { } if (ProfileFunctions.getSystemUnits() == Constants.MMOL) { - actions_care_bgunits.text = MainApp.gs(R.string.mmol) + actions_care_bgunits.text = resourceHelper.gs(R.string.mmol) actions_care_bg.setParams(savedInstanceState?.getDouble("actions_care_bg") ?: bg, 2.0, 30.0, 0.1, DecimalFormat("0.0"), false, ok, bgTextWatcher) } else { - actions_care_bgunits.text = MainApp.gs(R.string.mgdl) + actions_care_bgunits.text = resourceHelper.gs(R.string.mgdl) actions_care_bg.setParams(savedInstanceState?.getDouble("actions_care_bg") ?: bg, 36.0, 500.0, 1.0, DecimalFormat("0"), false, ok, bgTextWatcher) } @@ -116,18 +124,18 @@ class CareDialog : DialogFragmentWithDate() { actions_care_sensor.isChecked -> "Sensor" else -> "Manual" } - actions.add(MainApp.gs(R.string.careportal_newnstreatment_glucosetype) + ": " + Translator.translate(type)) - actions.add(MainApp.gs(R.string.treatments_wizard_bg_label) + ": " + Profile.toCurrentUnitsString(actions_care_bg.value) + " " + MainApp.gs(unitResId)) + actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_glucosetype) + ": " + Translator.translate(type)) + actions.add(resourceHelper.gs(R.string.treatments_wizard_bg_label) + ": " + Profile.toCurrentUnitsString(actions_care_bg.value) + " " + resourceHelper.gs(unitResId)) json.put("glucose", actions_care_bg.value) json.put("glucoseType", type) } val notes = notes.text.toString() if (notes.isNotEmpty()) { - actions.add(MainApp.gs(R.string.careportal_newnstreatment_notes_label) + ": " + notes) + actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_notes_label) + ": " + notes) json.put("notes", notes) } if (eventTimeChanged) - actions.add(MainApp.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(eventTime)) + actions.add(resourceHelper.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(eventTime)) json.put("created_at", DateUtil.toISOString(eventTime)) json.put("eventType", when (options) { @@ -140,7 +148,7 @@ class CareDialog : DialogFragmentWithDate() { json.put("enteredBy", enteredBy) activity?.let { activity -> - OKDialog.showConfirmation(activity, MainApp.gs(event), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { + OKDialog.showConfirmation(activity, resourceHelper.gs(event), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { MainApp.getDbHelper().createCareportalEventFromJsonIfNotExists(json) NSUpload.uploadCareportalEntryToNS(json) }, null) diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/DialogFragmentWithDate.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/DialogFragmentWithDate.kt index da45e77990..407689a53d 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/DialogFragmentWithDate.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/DialogFragmentWithDate.kt @@ -8,7 +8,7 @@ import android.view.View import android.view.ViewGroup import android.view.Window import android.view.WindowManager -import androidx.fragment.app.DialogFragment +import dagger.android.support.DaggerDialogFragment import info.nightscout.androidaps.R import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.SP @@ -19,7 +19,7 @@ import kotlinx.android.synthetic.main.okcancel.* import org.slf4j.LoggerFactory import java.util.* -abstract class DialogFragmentWithDate : DialogFragment() { +abstract class DialogFragmentWithDate : DaggerDialogFragment() { private val log = LoggerFactory.getLogger(DialogFragmentWithDate::class.java) var eventTime = DateUtil.now() diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/ExtendedBolusDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/ExtendedBolusDialog.kt index a717e79b49..e730e513fb 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/ExtendedBolusDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/ExtendedBolusDialog.kt @@ -11,18 +11,30 @@ import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.OKDialog import info.nightscout.androidaps.utils.SafeParse +import info.nightscout.androidaps.utils.resources.ResourceHelper import kotlinx.android.synthetic.main.dialog_extendedbolus.* import kotlinx.android.synthetic.main.okcancel.* import java.text.DecimalFormat import java.util.* +import javax.inject.Inject import kotlin.math.abs class ExtendedBolusDialog : DialogFragmentWithDate() { + @Inject + lateinit var mainApp: MainApp + + @Inject + lateinit var resourceHelper: ResourceHelper + + @Inject + lateinit var constraintChecker: ConstraintChecker + override fun onSaveInstanceState(savedInstanceState: Bundle) { super.onSaveInstanceState(savedInstanceState) savedInstanceState.putDouble("actions_extendedbolus_insulin", actions_extendedbolus_insulin.value) @@ -40,7 +52,7 @@ class ExtendedBolusDialog : DialogFragmentWithDate() { val pumpDescription = ConfigBuilderPlugin.getPlugin().activePump?.pumpDescription ?: return - val maxInsulin = MainApp.getConstraintChecker().maxExtendedBolusAllowed.value() + val maxInsulin = constraintChecker.getMaxExtendedBolusAllowed().value() val extendedStep = pumpDescription.extendedBolusStep actions_extendedbolus_insulin.setParams(savedInstanceState?.getDouble("actions_extendedbolus_insulin") ?: extendedStep, extendedStep, maxInsulin, extendedStep, DecimalFormat("0.00"), false, ok) @@ -55,23 +67,23 @@ class ExtendedBolusDialog : DialogFragmentWithDate() { val insulin = SafeParse.stringToDouble(actions_extendedbolus_insulin.text) val durationInMinutes = SafeParse.stringToInt(actions_extendedbolus_duration.text) val actions: LinkedList = LinkedList() - val insulinAfterConstraint = MainApp.getConstraintChecker().applyExtendedBolusConstraints(Constraint(insulin)).value() - actions.add(MainApp.gs(R.string.formatinsulinunits, insulinAfterConstraint)) - actions.add(MainApp.gs(R.string.duration) + ": " + MainApp.gs(R.string.format_mins, durationInMinutes)) + val insulinAfterConstraint = constraintChecker.applyExtendedBolusConstraints(Constraint(insulin)).value() + actions.add(resourceHelper.gs(R.string.formatinsulinunits, insulinAfterConstraint)) + actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_mins, durationInMinutes)) if (abs(insulinAfterConstraint - insulin) > 0.01) - actions.add("" + MainApp.gs(R.string.constraintapllied) + "") + actions.add("" + resourceHelper.gs(R.string.constraintapllied) + "") activity?.let { activity -> - OKDialog.showConfirmation(activity, MainApp.gs(R.string.extended_bolus), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { + OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.extended_bolus), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { ConfigBuilderPlugin.getPlugin().commandQueue.extendedBolus(insulinAfterConstraint, durationInMinutes, object : Callback() { override fun run() { if (!result.success) { - val i = Intent(MainApp.instance(), ErrorHelperActivity::class.java) + val i = Intent(mainApp, ErrorHelperActivity::class.java) i.putExtra("soundid", R.raw.boluserror) i.putExtra("status", result.comment) - i.putExtra("title", MainApp.gs(R.string.treatmentdeliveryerror)) + i.putExtra("title", resourceHelper.gs(R.string.treatmentdeliveryerror)) i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - MainApp.instance().startActivity(i) + mainApp.startActivity(i) } } }) diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt index 8d55df9bc1..b865f76745 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt @@ -14,17 +14,37 @@ import info.nightscout.androidaps.db.CareportalEvent import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.queue.Callback -import info.nightscout.androidaps.utils.* +import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.androidaps.utils.DecimalFormatter +import info.nightscout.androidaps.utils.HtmlHelper +import info.nightscout.androidaps.utils.OKDialog +import info.nightscout.androidaps.utils.SafeParse +import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.sharedPreferences.SP import kotlinx.android.synthetic.main.dialog_fill.* import kotlinx.android.synthetic.main.notes.* import kotlinx.android.synthetic.main.okcancel.* import java.util.* +import javax.inject.Inject import kotlin.math.abs class FillDialog : DialogFragmentWithDate() { + @Inject + lateinit var constraintChecker: ConstraintChecker + + @Inject + lateinit var resourceHelper: ResourceHelper + + @Inject + lateinit var sp: SP + + @Inject + lateinit var mainApp: MainApp + override fun onSaveInstanceState(savedInstanceState: Bundle) { super.onSaveInstanceState(savedInstanceState) savedInstanceState.putDouble("fill_insulinamount", fill_insulinamount.value) @@ -39,11 +59,11 @@ class FillDialog : DialogFragmentWithDate() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) - val maxInsulin = MainApp.getConstraintChecker().maxBolusAllowed.value() + val maxInsulin = constraintChecker.getMaxBolusAllowed().value() val bolusStep = ConfigBuilderPlugin.getPlugin().activePump!!.pumpDescription.bolusStep fill_insulinamount.setParams(savedInstanceState?.getDouble("fill_insulinamount") ?: 0.0, 0.0, maxInsulin, bolusStep, DecimalFormatter.pumpSupportedBolusFormat(), true, ok) - val amount1 = SP.getDouble("fill_button1", 0.3) + val amount1 = sp.getDouble("fill_button1", 0.3) if (amount1 > 0) { fill_preset_button1.visibility = View.VISIBLE fill_preset_button1.text = DecimalFormatter.toPumpSupportedBolus(amount1) // + "U"); @@ -51,7 +71,7 @@ class FillDialog : DialogFragmentWithDate() { } else { fill_preset_button1.visibility = View.GONE } - val amount2 = SP.getDouble("fill_button2", 0.0) + val amount2 = sp.getDouble("fill_button2", 0.0) if (amount2 > 0) { fill_preset_button2.visibility = View.VISIBLE fill_preset_button2.text = DecimalFormatter.toPumpSupportedBolus(amount2) // + "U"); @@ -59,7 +79,7 @@ class FillDialog : DialogFragmentWithDate() { } else { fill_preset_button2.visibility = View.GONE } - val amount3 = SP.getDouble("fill_button3", 0.0) + val amount3 = sp.getDouble("fill_button3", 0.0) if (amount3 > 0) { fill_preset_button3.visibility = View.VISIBLE fill_preset_button3.text = DecimalFormatter.toPumpSupportedBolus(amount3) // + "U"); @@ -74,29 +94,29 @@ class FillDialog : DialogFragmentWithDate() { val insulin = SafeParse.stringToDouble(fill_insulinamount.text) val actions: LinkedList = LinkedList() - val insulinAfterConstraints = MainApp.getConstraintChecker().applyBolusConstraints(Constraint(insulin)).value() + val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(insulin)).value() if (insulinAfterConstraints > 0) { - actions.add(MainApp.gs(R.string.fillwarning)) + actions.add(resourceHelper.gs(R.string.fillwarning)) actions.add("") - actions.add(MainApp.gs(R.string.bolus) + ": " + "" + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints) + MainApp.gs(R.string.insulin_unit_shortname) + "") + actions.add(resourceHelper.gs(R.string.bolus) + ": " + "" + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints) + MainApp.gs(R.string.insulin_unit_shortname) + "") if (abs(insulinAfterConstraints - insulin) > 0.01) - actions.add(MainApp.gs(R.string.bolusconstraintappliedwarning, MainApp.gc(R.color.warning), insulin, insulinAfterConstraints)) + actions.add(resourceHelper.gs(R.string.bolusconstraintappliedwarning, resourceHelper.gc(R.color.warning), insulin, insulinAfterConstraints)) } val siteChange = fill_catheter_change.isChecked if (siteChange) - actions.add("" + "" + MainApp.gs(R.string.record_pump_site_change) + "") + actions.add("" + "" + resourceHelper.gs(R.string.record_pump_site_change) + "") val insulinChange = fill_cartridge_change.isChecked if (insulinChange) - actions.add("" + "" + MainApp.gs(R.string.record_insulin_cartridge_change) + "") + actions.add("" + "" + resourceHelper.gs(R.string.record_insulin_cartridge_change) + "") val notes = notes.text.toString() if (notes.isNotEmpty()) - actions.add(MainApp.gs(R.string.careportal_newnstreatment_notes_label) + ": " + notes) + actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_notes_label) + ": " + notes) if (eventTimeChanged) - actions.add(MainApp.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(eventTime)) + actions.add(resourceHelper.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(eventTime)) if (insulinAfterConstraints > 0 || fill_catheter_change.isChecked || fill_cartridge_change.isChecked) { activity?.let { activity -> - OKDialog.showConfirmation(activity, MainApp.gs(R.string.primefill), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { + OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.primefill), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { if (insulinAfterConstraints > 0) { val detailedBolusInfo = DetailedBolusInfo() detailedBolusInfo.insulin = insulinAfterConstraints @@ -107,12 +127,12 @@ class FillDialog : DialogFragmentWithDate() { ConfigBuilderPlugin.getPlugin().commandQueue.bolus(detailedBolusInfo, object : Callback() { override fun run() { if (!result.success) { - val i = Intent(MainApp.instance(), ErrorHelperActivity::class.java) + val i = Intent(mainApp, ErrorHelperActivity::class.java) i.putExtra("soundid", R.raw.boluserror) i.putExtra("status", result.comment) - i.putExtra("title", MainApp.gs(R.string.treatmentdeliveryerror)) + i.putExtra("title", resourceHelper.gs(R.string.treatmentdeliveryerror)) i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - MainApp.instance().startActivity(i) + mainApp.startActivity(i) } } }) @@ -123,7 +143,7 @@ class FillDialog : DialogFragmentWithDate() { } } else { activity?.let { activity -> - OKDialog.show(activity, MainApp.gs(R.string.primefill), MainApp.gs(R.string.no_action_selected)) + OKDialog.show(activity, resourceHelper.gs(R.string.primefill), resourceHelper.gs(R.string.no_action_selected)) } } dismiss() diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt index d6f64d87f1..ca48a3f748 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt @@ -19,28 +19,41 @@ import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.db.TempTarget import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.* +import info.nightscout.androidaps.utils.resources.ResourceHelper import kotlinx.android.synthetic.main.dialog_insulin.* import kotlinx.android.synthetic.main.notes.* import kotlinx.android.synthetic.main.okcancel.* import java.text.DecimalFormat import java.util.* +import javax.inject.Inject import kotlin.math.abs import kotlin.math.max class InsulinDialog : DialogFragmentWithDate() { + @Inject + lateinit var constraintChecker: ConstraintChecker + + @Inject + lateinit var mainApp: MainApp + + @Inject + lateinit var resourceHelper: ResourceHelper + + @Inject + lateinit var profileFunction: ProfileFunction + companion object { private const val PLUS1_DEFAULT = 0.5 private const val PLUS2_DEFAULT = 1.0 private const val PLUS3_DEFAULT = 2.0 } - private val maxInsulin = MainApp.getConstraintChecker().maxBolusAllowed.value() - private val textWatcher: TextWatcher = object : TextWatcher { override fun afterTextChanged(s: Editable) { validateInputs() @@ -51,13 +64,14 @@ class InsulinDialog : DialogFragmentWithDate() { } private fun validateInputs() { + val maxInsulin = constraintChecker.getMaxBolusAllowed().value() if (abs(overview_insulin_time.value.toInt()) > 12 * 60) { overview_insulin_time.value = 0.0 - ToastUtils.showToastInUiThread(MainApp.instance().applicationContext, MainApp.gs(R.string.constraintapllied)) + ToastUtils.showToastInUiThread(mainApp, resourceHelper.gs(R.string.constraintapllied)) } if (overview_insulin_amount.value > maxInsulin) { overview_insulin_amount.value = 0.0 - ToastUtils.showToastInUiThread(MainApp.instance().applicationContext, MainApp.gs(R.string.bolusconstraintapplied)) + ToastUtils.showToastInUiThread(mainApp, resourceHelper.gs(R.string.bolusconstraintapplied)) } } @@ -76,27 +90,29 @@ class InsulinDialog : DialogFragmentWithDate() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) + val maxInsulin = constraintChecker.getMaxBolusAllowed().value() + overview_insulin_time.setParams(savedInstanceState?.getDouble("overview_insulin_time") ?: 0.0, -12 * 60.0, 12 * 60.0, 5.0, DecimalFormat("0"), false, ok, textWatcher) overview_insulin_amount.setParams(savedInstanceState?.getDouble("overview_insulin_amount") ?: 0.0, 0.0, maxInsulin, ConfigBuilderPlugin.getPlugin().activePump!!.pumpDescription.bolusStep, DecimalFormatter.pumpSupportedBolusFormat(), false, ok, textWatcher) - overview_insulin_plus05.text = toSignedString(SP.getDouble(MainApp.gs(R.string.key_insulin_button_increment_1), PLUS1_DEFAULT)) + overview_insulin_plus05.text = toSignedString(SP.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_1), PLUS1_DEFAULT)) overview_insulin_plus05.setOnClickListener { overview_insulin_amount.value = max(0.0, overview_insulin_amount.value - + SP.getDouble(MainApp.gs(R.string.key_insulin_button_increment_1), PLUS1_DEFAULT)) + + SP.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_1), PLUS1_DEFAULT)) validateInputs() } - overview_insulin_plus10.text = toSignedString(SP.getDouble(MainApp.gs(R.string.key_insulin_button_increment_2), PLUS2_DEFAULT)) + overview_insulin_plus10.text = toSignedString(SP.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_2), PLUS2_DEFAULT)) overview_insulin_plus10.setOnClickListener { overview_insulin_amount.value = max(0.0, overview_insulin_amount.value - + SP.getDouble(MainApp.gs(R.string.key_insulin_button_increment_2), PLUS2_DEFAULT)) + + SP.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_2), PLUS2_DEFAULT)) validateInputs() } - overview_insulin_plus20.text = toSignedString(SP.getDouble(MainApp.gs(R.string.key_insulin_button_increment_3), PLUS3_DEFAULT)) + overview_insulin_plus20.text = toSignedString(SP.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_3), PLUS3_DEFAULT)) overview_insulin_plus20.setOnClickListener { overview_insulin_amount.value = Math.max(0.0, overview_insulin_amount.value - + SP.getDouble(MainApp.gs(R.string.key_insulin_button_increment_3), PLUS3_DEFAULT)) + + SP.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_3), PLUS3_DEFAULT)) validateInputs() } @@ -115,45 +131,45 @@ class InsulinDialog : DialogFragmentWithDate() { val pumpDescription = ConfigBuilderPlugin.getPlugin().activePump?.pumpDescription ?: return false val insulin = SafeParse.stringToDouble(overview_insulin_amount.text) - val insulinAfterConstraints = MainApp.getConstraintChecker().applyBolusConstraints(Constraint(insulin)).value() + val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(insulin)).value() val actions: LinkedList = LinkedList() - val units = ProfileFunctions.getSystemUnits() - val unitLabel = if (units == Constants.MMOL) MainApp.gs(R.string.mmol) else MainApp.gs(R.string.mgdl) + val units = profileFunction.getUnits() + val unitLabel = if (units == Constants.MMOL) resourceHelper.gs(R.string.mmol) else resourceHelper.gs(R.string.mgdl) val recordOnlyChecked = overview_insulin_record_only.isChecked val eatingSoonChecked = overview_insulin_start_eating_soon_tt.isChecked if (insulinAfterConstraints > 0) { - actions.add(MainApp.gs(R.string.bolus) + ": " + "" + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints) + MainApp.gs(R.string.insulin_unit_shortname) + "") + actions.add(resourceHelper.gs(R.string.bolus) + ": " + "" + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints) + resourceHelper.gs(R.string.insulin_unit_shortname) + "") if (recordOnlyChecked) - actions.add("" + MainApp.gs(R.string.bolusrecordedonly) + "") + actions.add("" + resourceHelper.gs(R.string.bolusrecordedonly) + "") if (abs(insulinAfterConstraints - insulin) > pumpDescription.pumpType.determineCorrectBolusStepSize(insulinAfterConstraints)) - actions.add(MainApp.gs(R.string.bolusconstraintappliedwarning, MainApp.gc(R.color.warning), insulin, insulinAfterConstraints)) + actions.add(resourceHelper.gs(R.string.bolusconstraintappliedwarning, resourceHelper.gc(R.color.warning), insulin, insulinAfterConstraints)) } val eatingSoonTTDuration = DefaultValueHelper.determineEatingSoonTTDuration() val eatingSoonTT = DefaultValueHelper.determineEatingSoonTT() if (eatingSoonChecked) - actions.add(MainApp.gs(R.string.temptargetshort) + ": " + "" + DecimalFormatter.to1Decimal(eatingSoonTT) + " " + unitLabel + " (" + eatingSoonTTDuration + " " + MainApp.gs(R.string.unit_minute_short) + ")") + actions.add(resourceHelper.gs(R.string.temptargetshort) + ": " + "" + DecimalFormatter.to1Decimal(eatingSoonTT) + " " + unitLabel + " (" + eatingSoonTTDuration + " " + resourceHelper.gs(R.string.unit_minute_short) + ")") val timeOffset = overview_insulin_time.value.toInt() val time = DateUtil.now() + T.mins(timeOffset.toLong()).msecs() if (timeOffset != 0) - actions.add(MainApp.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(time)) + actions.add(resourceHelper.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(time)) val notes = notes.text.toString() if (notes.isNotEmpty()) - actions.add(MainApp.gs(R.string.careportal_newnstreatment_notes_label) + ": " + notes) + actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_notes_label) + ": " + notes) if (insulinAfterConstraints > 0 || eatingSoonChecked) { activity?.let { activity -> - OKDialog.showConfirmation(activity, MainApp.gs(R.string.bolus), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { + OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.bolus), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { if (eatingSoonChecked) { val tempTarget = TempTarget() .date(System.currentTimeMillis()) .duration(eatingSoonTTDuration) - .reason(MainApp.gs(R.string.eatingsoon)) + .reason(resourceHelper.gs(R.string.eatingsoon)) .source(Source.USER) - .low(Profile.toMgdl(eatingSoonTT, ProfileFunctions.getSystemUnits())) - .high(Profile.toMgdl(eatingSoonTT, ProfileFunctions.getSystemUnits())) + .low(Profile.toMgdl(eatingSoonTT, profileFunction.getUnits())) + .high(Profile.toMgdl(eatingSoonTT, profileFunction.getUnits())) TreatmentsPlugin.getPlugin().addToHistoryTempTarget(tempTarget) } if (insulinAfterConstraints > 0) { @@ -171,12 +187,12 @@ class InsulinDialog : DialogFragmentWithDate() { ConfigBuilderPlugin.getPlugin().commandQueue.bolus(detailedBolusInfo, object : Callback() { override fun run() { if (!result.success) { - val i = Intent(MainApp.instance(), ErrorHelperActivity::class.java) + val i = Intent(mainApp, ErrorHelperActivity::class.java) i.putExtra("soundid", R.raw.boluserror) i.putExtra("status", result.comment) - i.putExtra("title", MainApp.gs(R.string.treatmentdeliveryerror)) + i.putExtra("title", resourceHelper.gs(R.string.treatmentdeliveryerror)) i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - MainApp.instance().startActivity(i) + mainApp.startActivity(i) } } }) @@ -186,7 +202,7 @@ class InsulinDialog : DialogFragmentWithDate() { } } else activity?.let { activity -> - OKDialog.show(activity, MainApp.gs(R.string.bolus), MainApp.gs(R.string.no_action_selected)) + OKDialog.show(activity, resourceHelper.gs(R.string.bolus), resourceHelper.gs(R.string.no_action_selected)) } return true } diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt index 172cd24195..57aaad0736 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt @@ -7,22 +7,29 @@ import android.view.ViewGroup import android.widget.ArrayAdapter import com.google.common.base.Joiner import info.nightscout.androidaps.Constants -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.OKDialog +import info.nightscout.androidaps.utils.resources.ResourceHelper import kotlinx.android.synthetic.main.dialog_profileswitch.* import kotlinx.android.synthetic.main.notes.* import kotlinx.android.synthetic.main.okcancel.* import java.text.DecimalFormat import java.util.* +import javax.inject.Inject class ProfileSwitchDialog : DialogFragmentWithDate() { + @Inject + lateinit var resourceHelper: ResourceHelper + + @Inject + lateinit var profileFunction: ProfileFunction + override fun onSaveInstanceState(savedInstanceState: Bundle) { super.onSaveInstanceState(savedInstanceState) savedInstanceState.putDouble("overview_profileswitch_duration", overview_profileswitch_duration.value) @@ -55,14 +62,14 @@ class ProfileSwitchDialog : DialogFragmentWithDate() { overview_profileswitch_profile.adapter = adapter // set selected to actual profile for (p in profileList.indices) - if (profileList[p] == ProfileFunctions.getInstance().getProfileName(false)) + if (profileList[p] == profileFunction.getProfileName(false)) overview_profileswitch_profile.setSelection(p) } ?: return TreatmentsPlugin.getPlugin().getProfileSwitchFromHistory(DateUtil.now())?.let { ps -> if (ps.isCPP) { overview_profileswitch_reuselayout.visibility = View.VISIBLE - overview_profileswitch_reusebutton.text = MainApp.gs(R.string.reuse) + " " + ps.percentage + "% " + ps.timeshift + "h" + overview_profileswitch_reusebutton.text = resourceHelper.gs(R.string.reuse) + " " + ps.percentage + "% " + ps.timeshift + "h" overview_profileswitch_reusebutton.setOnClickListener { overview_profileswitch_percentage.value = ps.percentage.toDouble() overview_profileswitch_timeshift.value = ps.timeshift.toDouble() @@ -80,24 +87,24 @@ class ProfileSwitchDialog : DialogFragmentWithDate() { val actions: LinkedList = LinkedList() val duration = overview_profileswitch_duration.value if (duration > 0) - actions.add(MainApp.gs(R.string.duration) + ": " + MainApp.gs(R.string.format_hours, duration)) + actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_hours, duration)) val profile = overview_profileswitch_profile.selectedItem.toString() - actions.add(MainApp.gs(R.string.profile) + ": " + profile) + actions.add(resourceHelper.gs(R.string.profile) + ": " + profile) val percent = overview_profileswitch_percentage.value.toInt() if (percent != 100) - actions.add(MainApp.gs(R.string.percent) + ": " + percent + "%") + actions.add(resourceHelper.gs(R.string.percent) + ": " + percent + "%") val timeShift = overview_profileswitch_timeshift.value.toInt() if (timeShift != 0) - actions.add(MainApp.gs(R.string.careportal_newnstreatment_timeshift_label) + ": " + MainApp.gs(R.string.format_hours, timeShift.toDouble())) + actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_timeshift_label) + ": " + resourceHelper.gs(R.string.format_hours, timeShift.toDouble())) val notes = notes.text.toString() if (notes.isNotEmpty()) - actions.add(MainApp.gs(R.string.careportal_newnstreatment_notes_label) + ": " + notes) + actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_notes_label) + ": " + notes) if (eventTimeChanged) - actions.add(MainApp.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(eventTime)) + actions.add(resourceHelper.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(eventTime)) activity?.let { activity -> - OKDialog.showConfirmation(activity, MainApp.gs(R.string.careportal_profileswitch), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { - ProfileFunctions.getInstance().doProfileSwitch(profileStore, profile, duration.toInt(), percent, timeShift, eventTime) + OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal_profileswitch), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { + profileFunction.doProfileSwitch(profileStore, profile, duration.toInt(), percent, timeShift, eventTime) }) } return true diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileViewerDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileViewerDialog.kt index ef3b19d4d8..a295e3dafa 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileViewerDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileViewerDialog.kt @@ -6,18 +6,23 @@ import android.view.View import android.view.ViewGroup import android.view.Window import android.view.WindowManager -import androidx.fragment.app.DialogFragment +import dagger.android.support.DaggerDialogFragment import info.nightscout.androidaps.Constants -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.androidaps.utils.resources.ResourceHelper import kotlinx.android.synthetic.main.close.* import kotlinx.android.synthetic.main.dialog_profileviewer.* import org.json.JSONObject +import javax.inject.Inject + +class ProfileViewerDialog : DaggerDialogFragment() { + + @Inject + lateinit var resourceHelper: ResourceHelper -class ProfileViewerDialog : DialogFragment() { private var time: Long = 0 enum class Mode(val i: Int) { @@ -77,7 +82,7 @@ class ProfileViewerDialog : DialogFragment() { profile?.let { profileview_units.text = it.units - profileview_dia.text = MainApp.gs(R.string.format_hours, it.dia) + profileview_dia.text = resourceHelper.gs(R.string.format_hours, it.dia) profileview_activeprofile.text = profileName profileview_date.text = date profileview_ic.text = it.icList diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/TempBasalDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/TempBasalDialog.kt index 77c7df319f..32f54a3083 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/TempBasalDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/TempBasalDialog.kt @@ -12,18 +12,34 @@ import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.PumpDescription import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.OKDialog import info.nightscout.androidaps.utils.SafeParse +import info.nightscout.androidaps.utils.resources.ResourceHelper import kotlinx.android.synthetic.main.dialog_tempbasal.* import kotlinx.android.synthetic.main.okcancel.* import java.text.DecimalFormat import java.util.* +import javax.inject.Inject import kotlin.math.abs class TempBasalDialog : DialogFragmentWithDate() { + + @Inject + lateinit var constraintChecker: ConstraintChecker + + @Inject + lateinit var mainApp: MainApp + + @Inject + lateinit var resourceHelper: ResourceHelper + + @Inject + lateinit var profileFunction: ProfileFunction + private var isPercentPump = true override fun onSaveInstanceState(savedInstanceState: Bundle) { @@ -43,7 +59,7 @@ class TempBasalDialog : DialogFragmentWithDate() { super.onViewCreated(view, savedInstanceState) val pumpDescription = ConfigBuilderPlugin.getPlugin().activePump?.pumpDescription ?: return - val profile = ProfileFunctions.getInstance().getProfile() ?: return + val profile = profileFunction.getProfile() ?: return val maxTempPercent = pumpDescription.maxTempPercent.toDouble() val tempPercentStep = pumpDescription.tempPercentStep.toDouble() @@ -73,33 +89,33 @@ class TempBasalDialog : DialogFragmentWithDate() { var percent = 0 var absolute = 0.0 val durationInMinutes = SafeParse.stringToInt(actions_tempbasal_duration.text) - val profile = ProfileFunctions.getInstance().getProfile() ?: return false + val profile = profileFunction.getProfile() ?: return false val actions: LinkedList = LinkedList() if (isPercentPump) { val basalPercentInput = SafeParse.stringToInt(actions_tempbasal_basalpercentinput.text) - percent = MainApp.getConstraintChecker().applyBasalPercentConstraints(Constraint(basalPercentInput), profile).value() - actions.add(MainApp.gs(R.string.pump_tempbasal_label)+ ": $percent%") - actions.add(MainApp.gs(R.string.duration) + ": " + MainApp.gs(R.string.format_mins, durationInMinutes)) - if (percent != basalPercentInput) actions.add(MainApp.gs(R.string.constraintapllied)) + percent = constraintChecker.applyBasalPercentConstraints(Constraint(basalPercentInput), profile).value() + actions.add(resourceHelper.gs(R.string.pump_tempbasal_label) + ": $percent%") + actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_mins, durationInMinutes)) + if (percent != basalPercentInput) actions.add(resourceHelper.gs(R.string.constraintapllied)) } else { val basalAbsoluteInput = SafeParse.stringToDouble(actions_tempbasal_basalabsoluteinput.text) - absolute = MainApp.getConstraintChecker().applyBasalConstraints(Constraint(basalAbsoluteInput), profile).value() - actions.add(MainApp.gs(R.string.pump_tempbasal_label)+ ": " + MainApp.gs(R.string.pump_basebasalrate, absolute)) - actions.add(MainApp.gs(R.string.duration) + ": " + MainApp.gs(R.string.format_mins, durationInMinutes)) + absolute = constraintChecker.applyBasalConstraints(Constraint(basalAbsoluteInput), profile).value() + actions.add(resourceHelper.gs(R.string.pump_tempbasal_label) + ": " + resourceHelper.gs(R.string.pump_basebasalrate, absolute)) + actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_mins, durationInMinutes)) if (abs(absolute - basalAbsoluteInput) > 0.01) - actions.add("" + MainApp.gs(R.string.constraintapllied) + "") + actions.add("" + resourceHelper.gs(R.string.constraintapllied) + "") } activity?.let { activity -> OKDialog.showConfirmation(activity, MainApp.gs(R.string.pump_tempbasal_label), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { val callback: Callback = object : Callback() { override fun run() { if (!result.success) { - val i = Intent(MainApp.instance(), ErrorHelperActivity::class.java) + val i = Intent(mainApp, ErrorHelperActivity::class.java) i.putExtra("soundid", R.raw.boluserror) i.putExtra("status", result.comment) - i.putExtra("title", MainApp.gs(R.string.tempbasaldeliveryerror)) + i.putExtra("title", resourceHelper.gs(R.string.tempbasaldeliveryerror)) i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - MainApp.instance().startActivity(i) + mainApp.startActivity(i) } } } diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt index 5408105a71..e4ef20554b 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt @@ -9,25 +9,39 @@ import android.widget.ArrayAdapter import com.google.common.base.Joiner import com.google.common.collect.Lists import info.nightscout.androidaps.Constants -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.db.TempTarget -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DefaultValueHelper import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.OKDialog -import info.nightscout.androidaps.utils.SP +import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.sharedPreferences.SP import kotlinx.android.synthetic.main.dialog_temptarget.* import kotlinx.android.synthetic.main.okcancel.* import java.text.DecimalFormat import java.util.* +import javax.inject.Inject class TempTargetDialog : DialogFragmentWithDate() { + @Inject + lateinit var constraintChecker: ConstraintChecker + + @Inject + lateinit var sp: SP + + @Inject + lateinit var resourceHelper: ResourceHelper + + @Inject + lateinit var profileFunction: ProfileFunction + override fun onSaveInstanceState(savedInstanceState: Bundle) { super.onSaveInstanceState(savedInstanceState) savedInstanceState.putDouble("overview_temptarget_duration", overview_temptarget_duration.value) @@ -46,7 +60,7 @@ class TempTargetDialog : DialogFragmentWithDate() { overview_temptarget_duration.setParams(savedInstanceState?.getDouble("overview_temptarget_duration") ?: 0.0, 0.0, Constants.MAX_PROFILE_SWITCH_DURATION, 10.0, DecimalFormat("0"), false, ok) - if (ProfileFunctions.getSystemUnits() == Constants.MMOL) + if (profileFunction.getUnits() == Constants.MMOL) overview_temptarget_temptarget.setParams( savedInstanceState?.getDouble("overview_temptarget_temptarget") ?: Constants.MIN_TT_MMOL, @@ -57,16 +71,16 @@ class TempTargetDialog : DialogFragmentWithDate() { ?: Constants.MIN_TT_MGDL, Constants.MIN_TT_MGDL, Constants.MAX_TT_MGDL, 1.0, DecimalFormat("0"), false, ok) - val units = ProfileFunctions.getSystemUnits() - overview_temptarget_units.text = if (units == Constants.MMOL) MainApp.gs(R.string.mmol) else MainApp.gs(R.string.mgdl) + val units = profileFunction.getUnits() + overview_temptarget_units.text = if (units == Constants.MMOL) resourceHelper.gs(R.string.mmol) else resourceHelper.gs(R.string.mgdl) // temp target context?.let { context -> val reasonList: List = Lists.newArrayList( - MainApp.gs(R.string.manual), - MainApp.gs(R.string.cancel), - MainApp.gs(R.string.eatingsoon), - MainApp.gs(R.string.activity), - MainApp.gs(R.string.hypo) + resourceHelper.gs(R.string.manual), + resourceHelper.gs(R.string.cancel), + resourceHelper.gs(R.string.eatingsoon), + resourceHelper.gs(R.string.activity), + resourceHelper.gs(R.string.hypo) ) val adapterReason = ArrayAdapter(context, R.layout.spinner_centered, reasonList) overview_temptarget_reason.adapter = adapterReason @@ -75,27 +89,27 @@ class TempTargetDialog : DialogFragmentWithDate() { val defaultDuration: Double val defaultTarget: Double when (reasonList[position]) { - MainApp.gs(R.string.eatingsoon) -> { + resourceHelper.gs(R.string.eatingsoon) -> { defaultDuration = DefaultValueHelper.determineEatingSoonTTDuration().toDouble() defaultTarget = DefaultValueHelper.determineEatingSoonTT() } - MainApp.gs(R.string.activity) -> { + resourceHelper.gs(R.string.activity) -> { defaultDuration = DefaultValueHelper.determineActivityTTDuration().toDouble() defaultTarget = DefaultValueHelper.determineActivityTT() } - MainApp.gs(R.string.hypo) -> { + resourceHelper.gs(R.string.hypo) -> { defaultDuration = DefaultValueHelper.determineHypoTTDuration().toDouble() defaultTarget = DefaultValueHelper.determineHypoTT() } - MainApp.gs(R.string.cancel) -> { + resourceHelper.gs(R.string.cancel) -> { defaultDuration = 0.0 defaultTarget = 0.0 } - else -> { + else -> { defaultDuration = overview_temptarget_duration.value defaultTarget = overview_temptarget_temptarget.value } @@ -112,21 +126,21 @@ class TempTargetDialog : DialogFragmentWithDate() { override fun submit(): Boolean { val actions: LinkedList = LinkedList() val reason = overview_temptarget_reason.selectedItem.toString() - val unitResId = if (ProfileFunctions.getSystemUnits() == Constants.MGDL) R.string.mgdl else R.string.mmol + val unitResId = if (profileFunction.getUnits() == Constants.MGDL) R.string.mgdl else R.string.mmol val target = overview_temptarget_temptarget.value val duration = overview_temptarget_duration.value if (target != 0.0 && duration != 0.0) { - actions.add(MainApp.gs(R.string.reason) + ": " + reason) - actions.add(MainApp.gs(R.string.nsprofileview_target_label) + ": " + Profile.toCurrentUnitsString(target) + " " + MainApp.gs(unitResId)) - actions.add(MainApp.gs(R.string.duration) + ": " + MainApp.gs(R.string.format_hours, duration)) + actions.add(resourceHelper.gs(R.string.reason) + ": " + reason) + actions.add(resourceHelper.gs(R.string.nsprofileview_target_label) + ": " + Profile.toCurrentUnitsString(target) + " " + resourceHelper.gs(unitResId)) + actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_hours, duration)) } else { - actions.add(MainApp.gs(R.string.stoptemptarget)) + actions.add(resourceHelper.gs(R.string.stoptemptarget)) } if (eventTimeChanged) - actions.add(MainApp.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(eventTime)) + actions.add(resourceHelper.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(eventTime)) activity?.let { activity -> - OKDialog.showConfirmation(activity, MainApp.gs(R.string.careportal_temporarytarget), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { + OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal_temporarytarget), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { if (target == 0.0 || duration == 0.0) { val tempTarget = TempTarget() .date(eventTime) @@ -140,11 +154,11 @@ class TempTargetDialog : DialogFragmentWithDate() { .duration(duration.toInt()) .reason(reason) .source(Source.USER) - .low(Profile.toMgdl(target, ProfileFunctions.getSystemUnits())) - .high(Profile.toMgdl(target, ProfileFunctions.getSystemUnits())) + .low(Profile.toMgdl(target, profileFunction.getUnits())) + .high(Profile.toMgdl(target, profileFunction.getUnits())) TreatmentsPlugin.getPlugin().addToHistoryTempTarget(tempTarget) } - if (duration == 10.0) SP.putBoolean(R.string.key_objectiveusetemptarget, true) + if (duration == 10.0) sp.putBoolean(R.string.key_objectiveusetemptarget, true) }) } return true diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt index 8667befaf2..15006a1371 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt @@ -16,6 +16,7 @@ import info.nightscout.androidaps.db.CareportalEvent import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.DecimalFormatter @@ -23,15 +24,24 @@ import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.OKDialog import info.nightscout.androidaps.utils.SafeParse import info.nightscout.androidaps.utils.ToastUtils +import info.nightscout.androidaps.utils.resources.ResourceHelper import kotlinx.android.synthetic.main.dialog_treatment.* import kotlinx.android.synthetic.main.okcancel.* import java.text.DecimalFormat import java.util.* +import javax.inject.Inject import kotlin.math.abs class TreatmentDialog : DialogFragmentWithDate() { - private var maxCarbs = MainApp.getConstraintChecker().maxCarbsAllowed.value().toDouble() - private var maxInsulin = MainApp.getConstraintChecker().maxBolusAllowed.value() + + @Inject + lateinit var constraintChecker: ConstraintChecker + + @Inject + lateinit var mainApp: MainApp + + @Inject + lateinit var resourceHelper: ResourceHelper private val textWatcher: TextWatcher = object : TextWatcher { override fun afterTextChanged(s: Editable) {} @@ -42,13 +52,15 @@ class TreatmentDialog : DialogFragmentWithDate() { } private fun validateInputs() { + val maxCarbs = constraintChecker.getMaxCarbsAllowed().value().toDouble() + val maxInsulin = constraintChecker.getMaxBolusAllowed().value() if (SafeParse.stringToInt(overview_treatment_carbs.text) > maxCarbs) { overview_treatment_carbs.value = 0.0 - ToastUtils.showToastInUiThread(MainApp.instance().applicationContext, MainApp.gs(R.string.carbsconstraintapplied)) + ToastUtils.showToastInUiThread(mainApp, resourceHelper.gs(R.string.carbsconstraintapplied)) } if (SafeParse.stringToDouble(overview_treatment_insulin.text) > maxInsulin) { overview_treatment_insulin.value = 0.0 - ToastUtils.showToastInUiThread(MainApp.instance().applicationContext, MainApp.gs(R.string.bolusconstraintapplied)) + ToastUtils.showToastInUiThread(mainApp, resourceHelper.gs(R.string.bolusconstraintapplied)) } } @@ -67,6 +79,8 @@ class TreatmentDialog : DialogFragmentWithDate() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) + val maxCarbs = constraintChecker.getMaxCarbsAllowed().value().toDouble() + val maxInsulin = constraintChecker.getMaxBolusAllowed().value() val pumpDescription = ConfigBuilderPlugin.getPlugin().activePump?.pumpDescription ?: return overview_treatment_carbs.setParams(savedInstanceState?.getDouble("overview_treatment_carbs") ?: 0.0, 0.0, maxCarbs, 1.0, DecimalFormat("0"), false, ok, textWatcher) @@ -81,24 +95,24 @@ class TreatmentDialog : DialogFragmentWithDate() { val carbs = SafeParse.stringToInt(overview_treatment_carbs.text) val recordOnlyChecked = overview_treatment_record_only.isChecked val actions: LinkedList = LinkedList() - val insulinAfterConstraints = MainApp.getConstraintChecker().applyBolusConstraints(Constraint(insulin)).value() - val carbsAfterConstraints = MainApp.getConstraintChecker().applyCarbsConstraints(Constraint(carbs)).value() + val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(insulin)).value() + val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(carbs)).value() if (insulinAfterConstraints > 0) { - actions.add(MainApp.gs(R.string.bolus) + ": " + "" + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints) + MainApp.gs(R.string.insulin_unit_shortname) + "") + actions.add(resourceHelper.gs(R.string.bolus) + ": " + "" + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints) + resourceHelper.gs(R.string.insulin_unit_shortname) + "") if (recordOnlyChecked) - actions.add("" + MainApp.gs(R.string.bolusrecordedonly) + "") + actions.add("" + resourceHelper.gs(R.string.bolusrecordedonly) + "") if (abs(insulinAfterConstraints - insulin) > pumpDescription.pumpType.determineCorrectBolusStepSize(insulinAfterConstraints)) - actions.add(MainApp.gs(R.string.bolusconstraintappliedwarning, MainApp.gc(R.color.warning), insulin, insulinAfterConstraints)) + actions.add(resourceHelper.gs(R.string.bolusconstraintappliedwarning, resourceHelper.gc(R.color.warning), insulin, insulinAfterConstraints)) } if (carbsAfterConstraints > 0) { - actions.add(MainApp.gs(R.string.carbs) + ": " + "" + MainApp.gs(R.string.format_carbs, carbsAfterConstraints) + "") + actions.add(resourceHelper.gs(R.string.carbs) + ": " + "" + resourceHelper.gs(R.string.format_carbs, carbsAfterConstraints) + "") if (carbsAfterConstraints != carbs) - actions.add("" + MainApp.gs(R.string.carbsconstraintapplied) + "") + actions.add("" + resourceHelper.gs(R.string.carbsconstraintapplied) + "") } if (insulinAfterConstraints > 0 || carbsAfterConstraints > 0) { activity?.let { activity -> - OKDialog.showConfirmation(activity, MainApp.gs(R.string.overview_treatment_label), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { + OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.overview_treatment_label), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { val detailedBolusInfo = DetailedBolusInfo() if (insulinAfterConstraints == 0.0) detailedBolusInfo.eventType = CareportalEvent.CARBCORRECTION if (carbsAfterConstraints == 0) detailedBolusInfo.eventType = CareportalEvent.CORRECTIONBOLUS @@ -110,12 +124,12 @@ class TreatmentDialog : DialogFragmentWithDate() { ConfigBuilderPlugin.getPlugin().commandQueue.bolus(detailedBolusInfo, object : Callback() { override fun run() { if (!result.success) { - val i = Intent(MainApp.instance(), ErrorHelperActivity::class.java) + val i = Intent(mainApp, ErrorHelperActivity::class.java) i.putExtra("soundid", R.raw.boluserror) i.putExtra("status", result.comment) - i.putExtra("title", MainApp.gs(R.string.treatmentdeliveryerror)) + i.putExtra("title", resourceHelper.gs(R.string.treatmentdeliveryerror)) i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - MainApp.instance().startActivity(i) + mainApp.startActivity(i) } } }) @@ -125,7 +139,7 @@ class TreatmentDialog : DialogFragmentWithDate() { } } else activity?.let { activity -> - OKDialog.show(activity, MainApp.gs(R.string.overview_treatment_label), MainApp.gs(R.string.no_action_selected)) + OKDialog.show(activity, resourceHelper.gs(R.string.overview_treatment_label), resourceHelper.gs(R.string.no_action_selected)) } return true } diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt index d48c28337b..a0fbd28f36 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt @@ -12,7 +12,7 @@ import android.widget.AdapterView import android.widget.AdapterView.OnItemSelectedListener import android.widget.ArrayAdapter import android.widget.CompoundButton -import androidx.fragment.app.DialogFragment +import dagger.android.support.DaggerDialogFragment import info.nightscout.androidaps.Constants import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R @@ -22,22 +22,41 @@ import info.nightscout.androidaps.db.DatabaseHelper import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.* +import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.sharedPreferences.SP import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.dialog_wizard.* import org.slf4j.LoggerFactory import java.text.DecimalFormat import java.util.* +import javax.inject.Inject import kotlin.math.abs -class WizardDialog : DialogFragment() { +class WizardDialog : DaggerDialogFragment() { private val log = LoggerFactory.getLogger(WizardDialog::class.java) + @Inject + lateinit var constraintChecker: ConstraintChecker + + @Inject + lateinit var mainApp: MainApp + + @Inject + lateinit var resourceHelper: ResourceHelper + + @Inject + lateinit var profileFunction: ProfileFunction + + @Inject + lateinit var sp: SP + private var wizard: BolusWizard? = null //one shot guards @@ -79,11 +98,11 @@ class WizardDialog : DialogFragment() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { loadCheckedStates() processCobCheckBox() - treatments_wizard_sbcheckbox.visibility = SP.getBoolean(R.string.key_usesuperbolus, false).toVisibility() - treatments_wizard_notes_layout.visibility = SP.getBoolean(R.string.key_show_notes_entry_dialogs, false).toVisibility() + treatments_wizard_sbcheckbox.visibility = sp.getBoolean(R.string.key_usesuperbolus, false).toVisibility() + treatments_wizard_notes_layout.visibility = sp.getBoolean(R.string.key_show_notes_entry_dialogs, false).toVisibility() - val maxCarbs = MainApp.getConstraintChecker().maxCarbsAllowed.value() - val maxCorrection = MainApp.getConstraintChecker().maxBolusAllowed.value() + val maxCarbs = constraintChecker.getMaxCarbsAllowed().value() + val maxCorrection = constraintChecker.getMaxBolusAllowed().value() treatments_wizard_bg_input.setParams(savedInstanceState?.getDouble("treatments_wizard_bg_input") ?: 0.0, 0.0, 500.0, 0.1, DecimalFormat("0.0"), false, ok, textWatcher) @@ -97,7 +116,7 @@ class WizardDialog : DialogFragment() { ?: 0.0, -60.0, 60.0, 5.0, DecimalFormat("0"), false, ok, textWatcher) initDialog() - treatments_wizard_percent_used.text = MainApp.gs(R.string.format_percent, SP.getInt(R.string.key_boluswizard_percentage, 100)) + treatments_wizard_percent_used.text = resourceHelper.gs(R.string.format_percent, sp.getInt(R.string.key_boluswizard_percentage, 100)) // ok button ok.setOnClickListener { if (okClicked) { @@ -122,13 +141,13 @@ class WizardDialog : DialogFragment() { treatments_wizard_bgtrendcheckbox.setOnCheckedChangeListener(::onCheckedChanged) treatments_wizard_sbcheckbox.setOnCheckedChangeListener(::onCheckedChanged) - val showCalc = SP.getBoolean(MainApp.gs(R.string.key_wizard_calculation_visible), false) + val showCalc = sp.getBoolean(resourceHelper.gs(R.string.key_wizard_calculation_visible), false) treatments_wizard_delimiter.visibility = showCalc.toVisibility() treatments_wizard_resulttable.visibility = showCalc.toVisibility() treatments_wizard_calculationcheckbox.isChecked = showCalc treatments_wizard_calculationcheckbox.setOnCheckedChangeListener { _, isChecked -> run { - SP.putBoolean(MainApp.gs(R.string.key_wizard_calculation_visible), isChecked) + sp.putBoolean(resourceHelper.gs(R.string.key_wizard_calculation_visible), isChecked) treatments_wizard_delimiter.visibility = isChecked.toVisibility() treatments_wizard_resulttable.visibility = isChecked.toVisibility() } @@ -136,7 +155,7 @@ class WizardDialog : DialogFragment() { // profile spinner treatments_wizard_profile.onItemSelectedListener = object : OnItemSelectedListener { override fun onNothingSelected(parent: AdapterView<*>?) { - ToastUtils.showToastInUiThread(MainApp.instance().applicationContext, MainApp.gs(R.string.noprofileselected)) + ToastUtils.showToastInUiThread(mainApp, resourceHelper.gs(R.string.noprofileselected)) ok.visibility = View.GONE } @@ -184,34 +203,34 @@ class WizardDialog : DialogFragment() { } private fun saveCheckedStates() { - SP.putBoolean(MainApp.gs(R.string.key_wizard_include_cob), treatments_wizard_cobcheckbox.isChecked) - SP.putBoolean(MainApp.gs(R.string.key_wizard_include_trend_bg), treatments_wizard_bgtrendcheckbox.isChecked) + sp.putBoolean(resourceHelper.gs(R.string.key_wizard_include_cob), treatments_wizard_cobcheckbox.isChecked) + sp.putBoolean(resourceHelper.gs(R.string.key_wizard_include_trend_bg), treatments_wizard_bgtrendcheckbox.isChecked) } private fun loadCheckedStates() { - treatments_wizard_bgtrendcheckbox.isChecked = SP.getBoolean(MainApp.gs(R.string.key_wizard_include_trend_bg), false) - treatments_wizard_cobcheckbox.isChecked = SP.getBoolean(MainApp.gs(R.string.key_wizard_include_cob), false) + treatments_wizard_bgtrendcheckbox.isChecked = sp.getBoolean(resourceHelper.gs(R.string.key_wizard_include_trend_bg), false) + treatments_wizard_cobcheckbox.isChecked = sp.getBoolean(resourceHelper.gs(R.string.key_wizard_include_cob), false) } private fun initDialog() { - val profile = ProfileFunctions.getInstance().getProfile() - val profileStore = ConfigBuilderPlugin.getPlugin().activeProfileInterface?.profile + val profile = profileFunction.getProfile() + val profileStore = ConfigBuilderPlugin.getPlugin().activeProfileInterface.profile if (profile == null || profileStore == null) { - ToastUtils.showToastInUiThread(MainApp.instance().applicationContext, MainApp.gs(R.string.noprofile)) + ToastUtils.showToastInUiThread(mainApp, resourceHelper.gs(R.string.noprofile)) dismiss() return } val profileList: ArrayList profileList = profileStore.getProfileList() - profileList.add(0, MainApp.gs(R.string.active)) + profileList.add(0, resourceHelper.gs(R.string.active)) context?.let { context -> val adapter = ArrayAdapter(context, R.layout.spinner_centered, profileList) treatments_wizard_profile.adapter = adapter } ?: return - val units = ProfileFunctions.getSystemUnits() + val units = profileFunction.getUnits() treatments_wizard_bgunits.text = units if (units == Constants.MGDL) treatments_wizard_bg_input.setStep(1.0) @@ -239,18 +258,18 @@ class WizardDialog : DialogFragment() { calculateInsulin() - treatments_wizard_percent_used.visibility = (SP.getInt(R.string.key_boluswizard_percentage, 100) != 100).toVisibility() + treatments_wizard_percent_used.visibility = (sp.getInt(R.string.key_boluswizard_percentage, 100) != 100).toVisibility() } private fun calculateInsulin() { - val profileStore = ConfigBuilderPlugin.getPlugin().activeProfileInterface?.profile + val profileStore = ConfigBuilderPlugin.getPlugin().activeProfileInterface.profile if (treatments_wizard_profile.selectedItem == null || profileStore == null) return // not initialized yet var profileName = treatments_wizard_profile.selectedItem.toString() val specificProfile: Profile? - if (profileName == MainApp.gs(R.string.active)) { - specificProfile = ProfileFunctions.getInstance().getProfile() - profileName = ProfileFunctions.getInstance().getProfileName() ?: return + if (profileName == resourceHelper.gs(R.string.active)) { + specificProfile = profileFunction.getProfile() + profileName = profileFunction.getProfileName() ?: return } else specificProfile = profileStore.getSpecificProfile(profileName) @@ -260,10 +279,10 @@ class WizardDialog : DialogFragment() { var bg = SafeParse.stringToDouble(treatments_wizard_bg_input.text) val carbs = SafeParse.stringToInt(treatments_wizard_carbs_input.text) val correction = SafeParse.stringToDouble(treatments_wizard_correction_input.text) - val carbsAfterConstraint = MainApp.getConstraintChecker().applyCarbsConstraints(Constraint(carbs)).value() + val carbsAfterConstraint = constraintChecker.applyCarbsConstraints(Constraint(carbs)).value() if (abs(carbs - carbsAfterConstraint) > 0.01) { treatments_wizard_carbs_input.value = 0.0 - ToastUtils.showToastInUiThread(MainApp.instance().applicationContext, MainApp.gs(R.string.carbsconstraintapplied)) + ToastUtils.showToastInUiThread(mainApp, resourceHelper.gs(R.string.carbsconstraintapplied)) return } @@ -280,7 +299,7 @@ class WizardDialog : DialogFragment() { val carbTime = SafeParse.stringToInt(treatments_wizard_carb_time_input.text) wizard = BolusWizard(specificProfile, profileName, tempTarget, carbsAfterConstraint, cob, bg, correction, - SP.getInt(R.string.key_boluswizard_percentage, 100).toDouble(), + sp.getInt(R.string.key_boluswizard_percentage, 100).toDouble(), treatments_wizard_bgcheckbox.isChecked, treatments_wizard_cobcheckbox.isChecked, treatments_wizard_bolusiobcheckbox.isChecked, @@ -291,10 +310,10 @@ class WizardDialog : DialogFragment() { treatment_wizard_notes.text.toString(), carbTime) wizard?.let { wizard -> - treatments_wizard_bg.text = String.format(MainApp.gs(R.string.format_bg_isf), BgReading().value(Profile.toMgdl(bg, ProfileFunctions.getSystemUnits())).valueToUnitsToString(ProfileFunctions.getSystemUnits()), wizard.sens) + treatments_wizard_bg.text = String.format(resourceHelper.gs(R.string.format_bg_isf), BgReading().value(Profile.toMgdl(bg, profileFunction.getUnits())).valueToUnitsToString(profileFunction.getUnits()), wizard.sens) treatments_wizard_bginsulin.text = StringUtils.formatInsulin(wizard.insulinFromBG) - treatments_wizard_carbs.text = String.format(MainApp.gs(R.string.format_carbs_ic), carbs.toDouble(), wizard.ic) + treatments_wizard_carbs.text = String.format(resourceHelper.gs(R.string.format_carbs_ic), carbs.toDouble(), wizard.ic) treatments_wizard_carbsinsulin.text = StringUtils.formatInsulin(wizard.insulinFromCarbs) treatments_wizard_bolusiobinsulin.text = StringUtils.formatInsulin(wizard.insulinFromBolusIOB) @@ -303,14 +322,14 @@ class WizardDialog : DialogFragment() { treatments_wizard_correctioninsulin.text = StringUtils.formatInsulin(wizard.insulinFromCorrection) // Superbolus - treatments_wizard_sb.text = if (treatments_wizard_sbcheckbox.isChecked) MainApp.gs(R.string.twohours) else "" + treatments_wizard_sb.text = if (treatments_wizard_sbcheckbox.isChecked) resourceHelper.gs(R.string.twohours) else "" treatments_wizard_sbinsulin.text = StringUtils.formatInsulin(wizard.insulinFromSuperBolus) // Trend if (treatments_wizard_bgtrendcheckbox.isChecked && wizard.glucoseStatus != null) { treatments_wizard_bgtrend.text = ((if (wizard.trend > 0) "+" else "") - + Profile.toUnitsString(wizard.trend * 3, wizard.trend * 3 / Constants.MMOLL_TO_MGDL, ProfileFunctions.getSystemUnits()) - + " " + ProfileFunctions.getSystemUnits()) + + Profile.toUnitsString(wizard.trend * 3, wizard.trend * 3 / Constants.MMOLL_TO_MGDL, profileFunction.getUnits()) + + " " + profileFunction.getUnits()) } else { treatments_wizard_bgtrend.text = "" } @@ -318,7 +337,7 @@ class WizardDialog : DialogFragment() { // COB if (treatments_wizard_cobcheckbox.isChecked) { - treatments_wizard_cob.text = String.format(MainApp.gs(R.string.format_cob_ic), cob, wizard.ic) + treatments_wizard_cob.text = String.format(resourceHelper.gs(R.string.format_cob_ic), cob, wizard.ic) treatments_wizard_cobinsulin.text = StringUtils.formatInsulin(wizard.insulinFromCOB) } else { treatments_wizard_cob.text = "" @@ -326,12 +345,12 @@ class WizardDialog : DialogFragment() { } if (wizard.calculatedTotalInsulin > 0.0 || carbsAfterConstraint > 0.0) { - val insulinText = if (wizard.calculatedTotalInsulin > 0.0) MainApp.gs(R.string.formatinsulinunits, wizard.calculatedTotalInsulin) else "" - val carbsText = if (carbsAfterConstraint > 0.0) MainApp.gs(R.string.format_carbs, carbsAfterConstraint) else "" - treatments_wizard_total.text = MainApp.gs(R.string.result_insulin_carbs, insulinText, carbsText) + val insulinText = if (wizard.calculatedTotalInsulin > 0.0) resourceHelper.gs(R.string.formatinsulinunits, wizard.calculatedTotalInsulin) else "" + val carbsText = if (carbsAfterConstraint > 0.0) resourceHelper.gs(R.string.format_carbs, carbsAfterConstraint) else "" + treatments_wizard_total.text = resourceHelper.gs(R.string.result_insulin_carbs, insulinText, carbsText) ok.visibility = View.VISIBLE } else { - treatments_wizard_total.text = MainApp.gs(R.string.missing_carbs, wizard.carbsEquivalent.toInt()) + treatments_wizard_total.text = resourceHelper.gs(R.string.missing_carbs, wizard.carbsEquivalent.toInt()) ok.visibility = View.INVISIBLE } } diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.kt.ignore b/app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.kt.ignore new file mode 100644 index 0000000000..93af086b7a --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.kt.ignore @@ -0,0 +1,62 @@ +package info.nightscout.androidaps.interfaces + +import info.nightscout.androidaps.data.Profile + +interface ConstraintsInterface { + + fun isLoopInvocationAllowed(value: Constraint): Constraint { + return value + } + + fun isClosedLoopAllowed(value: Constraint): Constraint { + return value + } + + fun isAutosensModeEnabled(value: Constraint): Constraint { + return value + } + + fun isAMAModeEnabled(value: Constraint): Constraint { + return value + } + + fun isSMBModeEnabled(value: Constraint): Constraint { + return value + } + + fun isUAMEnabled(value: Constraint): Constraint { + return value + } + + fun isAdvancedFilteringEnabled(value: Constraint): Constraint { + return value + } + + fun isSuperBolusEnabled(value: Constraint): Constraint { + return value + } + + fun applyBasalConstraints(absoluteRate: Constraint, profile: Profile): Constraint { + return absoluteRate + } + + fun applyBasalPercentConstraints(percentRate: Constraint, profile: Profile): Constraint { + return percentRate + } + + fun applyBolusConstraints(insulin: Constraint): Constraint { + return insulin + } + + fun applyExtendedBolusConstraints(insulin: Constraint): Constraint { + return insulin + } + + fun applyCarbsConstraints(carbs: Constraint): Constraint { + return carbs + } + + fun applyMaxIOBConstraints(maxIob: Constraint): Constraint { + return maxIob + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.java index 7e568af2d9..9f2142771a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.java @@ -23,6 +23,7 @@ import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DecimalFormatter; @@ -287,7 +288,7 @@ public class APSResult { } public boolean isChangeRequested() { - Constraint closedLoopEnabled = MainApp.getConstraintChecker().isClosedLoopAllowed(); + Constraint closedLoopEnabled = ConstraintChecker.getInstance().isClosedLoopAllowed(); // closed loop mode: handle change at driver level if (closedLoopEnabled.value()) { if (L.isEnabled(L.APS)) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java index 7492dc64dd..e85bccbc2e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java @@ -19,6 +19,8 @@ import org.slf4j.LoggerFactory; import java.util.Date; +import javax.inject.Inject; + import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainActivity; import info.nightscout.androidaps.MainApp; @@ -48,6 +50,7 @@ import info.nightscout.androidaps.plugins.aps.loop.events.EventLoopUpdateGui; import info.nightscout.androidaps.plugins.aps.loop.events.EventNewOpenLoopNotification; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.activities.ErrorHelperActivity; @@ -271,7 +274,7 @@ public class LoopPlugin extends PluginBase { try { if (L.isEnabled(L.APS)) log.debug("invoke from " + initiator); - Constraint loopEnabled = MainApp.getConstraintChecker().isLoopInvokationAllowed(); + Constraint loopEnabled = ConstraintChecker.getInstance().isLoopInvocationAllowed(); if (!loopEnabled.value()) { String message = MainApp.gs(R.string.loopdisabled) + "\n" + loopEnabled.getReasons(); @@ -319,13 +322,13 @@ public class LoopPlugin extends PluginBase { // check rate for constrais final APSResult resultAfterConstraints = result.clone(); resultAfterConstraints.rateConstraint = new Constraint<>(resultAfterConstraints.rate); - resultAfterConstraints.rate = MainApp.getConstraintChecker().applyBasalConstraints(resultAfterConstraints.rateConstraint, profile).value(); + resultAfterConstraints.rate = ConstraintChecker.getInstance().applyBasalConstraints(resultAfterConstraints.rateConstraint, profile).value(); resultAfterConstraints.percentConstraint = new Constraint<>(resultAfterConstraints.percent); - resultAfterConstraints.percent = MainApp.getConstraintChecker().applyBasalPercentConstraints(resultAfterConstraints.percentConstraint, profile).value(); + resultAfterConstraints.percent = ConstraintChecker.getInstance().applyBasalPercentConstraints(resultAfterConstraints.percentConstraint, profile).value(); resultAfterConstraints.smbConstraint = new Constraint<>(resultAfterConstraints.smb); - resultAfterConstraints.smb = MainApp.getConstraintChecker().applyBolusConstraints(resultAfterConstraints.smbConstraint).value(); + resultAfterConstraints.smb = ConstraintChecker.getInstance().applyBolusConstraints(resultAfterConstraints.smbConstraint).value(); // safety check for multiple SMBs long lastBolusTime = TreatmentsPlugin.getPlugin().getLastBolusTime(); @@ -359,7 +362,7 @@ public class LoopPlugin extends PluginBase { return; } - Constraint closedLoopEnabled = MainApp.getConstraintChecker().isClosedLoopAllowed(); + Constraint closedLoopEnabled = ConstraintChecker.getInstance().isClosedLoopAllowed(); if (closedLoopEnabled.value()) { if (resultAfterConstraints.isChangeRequested() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.java index 9ea2d39567..a0cf096055 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.java @@ -21,19 +21,19 @@ import java.nio.charset.StandardCharsets; import javax.annotation.Nullable; import info.nightscout.androidaps.Constants; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.MealData; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.aps.loop.ScriptReader; import info.nightscout.androidaps.plugins.aps.openAPSMA.LoggerCallback; import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.SP; @@ -255,7 +255,7 @@ public class DetermineBasalAdapterAMAJS { mMealData.put("boluses", mealData.boluses); mMealData.put("mealCOB", mealData.mealCOB); - if (MainApp.getConstraintChecker().isAutosensModeEnabled().value()) { + if (ConstraintChecker.getInstance().isAutosensModeEnabled().value()) { mAutosensData = new JSONObject(); mAutosensData.put("ratio", autosensDataRatio); } else { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java index 49881c5158..b4385e3599 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java @@ -4,6 +4,7 @@ import org.json.JSONException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.IobTotal; @@ -128,7 +129,7 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface { return; } - double maxBasal = MainApp.getConstraintChecker().getMaxBasalAllowed(profile).value(); + double maxBasal = ConstraintChecker.getInstance().getMaxBasalAllowed(profile).value(); double minBg = profile.getTargetLowMgdl(); double maxBg = profile.getTargetHighMgdl(); double targetBg = profile.getTargetMgdl(); @@ -147,7 +148,7 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface { if (L.isEnabled(L.APS)) Profiler.log(log, "getMealData()", startPart); - double maxIob = MainApp.getConstraintChecker().getMaxIOBAllowed().value(); + double maxIob = ConstraintChecker.getInstance().getMaxIOBAllowed().value(); minBg = HardLimits.verifyHardLimits(minBg, "minBg", HardLimits.VERY_HARD_LIMIT_MIN_BG[0], HardLimits.VERY_HARD_LIMIT_MIN_BG[1]); maxBg = HardLimits.verifyHardLimits(maxBg, "maxBg", HardLimits.VERY_HARD_LIMIT_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_MAX_BG[1]); @@ -175,7 +176,7 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface { return; startPart = System.currentTimeMillis(); - if (MainApp.getConstraintChecker().isAutosensModeEnabled().value()) { + if (ConstraintChecker.getInstance().isAutosensModeEnabled().value()) { AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getLastAutosensDataSynchronized("OpenAPSPlugin"); if (autosensData == null) { RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openaps_noasdata))); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java index 0380156c74..ec80acfc8f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java @@ -22,6 +22,7 @@ import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdat import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateResultGui; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; @@ -127,7 +128,7 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface { return; } - double maxBasal = MainApp.getConstraintChecker().getMaxBasalAllowed(profile).value(); + double maxBasal = ConstraintChecker.getInstance().getMaxBasalAllowed(profile).value(); double minBg = profile.getTargetLowMgdl(); double maxBg = profile.getTargetHighMgdl(); @@ -146,7 +147,7 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface { MealData mealData = TreatmentsPlugin.getPlugin().getMealData(); - double maxIob = MainApp.getConstraintChecker().getMaxIOBAllowed().value(); + double maxIob = ConstraintChecker.getInstance().getMaxIOBAllowed().value(); if (L.isEnabled(L.APS)) Profiler.log(log, "MA data gathering", start); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java index 76571176d3..7429bebeec 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java @@ -23,16 +23,17 @@ import javax.annotation.Nullable; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.MealData; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.aps.loop.ScriptReader; import info.nightscout.androidaps.plugins.aps.openAPSMA.LoggerCallback; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.SafeParse; @@ -315,7 +316,7 @@ public class DetermineBasalAdapterSMBJS { mMealData.put("lastCarbTime", mealData.lastCarbTime); - if (MainApp.getConstraintChecker().isAutosensModeEnabled().value()) { + if (ConstraintChecker.getInstance().isAutosensModeEnabled().value()) { mAutosensData = new JSONObject(); mAutosensData.put("ratio", autosensDataRatio); } else { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java index 426c04090b..7ee3866a9a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java @@ -1,5 +1,6 @@ package info.nightscout.androidaps.plugins.aps.openAPSSMB; +import org.jetbrains.annotations.NotNull; import org.json.JSONException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -24,6 +25,7 @@ import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdat import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateResultGui; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData; @@ -134,7 +136,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr Constraint inputConstraints = new Constraint<>(0d); // fake. only for collecting all results - Constraint maxBasalConstraint = MainApp.getConstraintChecker().getMaxBasalAllowed(profile); + Constraint maxBasalConstraint = ConstraintChecker.getInstance().getMaxBasalAllowed(profile); inputConstraints.copyReasons(maxBasalConstraint); double maxBasal = maxBasalConstraint.value(); double minBg = profile.getTargetLowMgdl(); @@ -151,7 +153,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr if (L.isEnabled(L.APS)) Profiler.log(log, "getMealData()", startPart); - Constraint maxIOBAllowedConstraint = MainApp.getConstraintChecker().getMaxIOBAllowed(); + Constraint maxIOBAllowedConstraint = ConstraintChecker.getInstance().getMaxIOBAllowed(); inputConstraints.copyReasons(maxIOBAllowedConstraint); double maxIob = maxIOBAllowedConstraint.value(); @@ -181,7 +183,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr return; startPart = System.currentTimeMillis(); - if (MainApp.getConstraintChecker().isAutosensModeEnabled().value()) { + if (ConstraintChecker.getInstance().isAutosensModeEnabled().value()) { AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getLastAutosensDataSynchronized("OpenAPSPlugin"); if (autosensData == null) { RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openaps_noasdata))); @@ -199,15 +201,15 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr startPart = System.currentTimeMillis(); Constraint smbAllowed = new Constraint<>(!tempBasalFallback); - MainApp.getConstraintChecker().isSMBModeEnabled(smbAllowed); + ConstraintChecker.getInstance().isSMBModeEnabled(smbAllowed); inputConstraints.copyReasons(smbAllowed); Constraint advancedFiltering = new Constraint<>(!tempBasalFallback); - MainApp.getConstraintChecker().isAdvancedFilteringEnabled(advancedFiltering); + ConstraintChecker.getInstance().isAdvancedFilteringEnabled(advancedFiltering); inputConstraints.copyReasons(advancedFiltering); Constraint uam = new Constraint<>(true); - MainApp.getConstraintChecker().isUAMEnabled(uam); + ConstraintChecker.getInstance().isUAMEnabled(uam); inputConstraints.copyReasons(uam); if (L.isEnabled(L.APS)) @@ -285,6 +287,8 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr return newvalue; } + @NotNull + @Override public Constraint isSuperBolusEnabled(Constraint value) { value.set(false); return value; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java index 02508769dd..04fad732b4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java @@ -367,7 +367,7 @@ public class ConfigBuilderPlugin extends PluginBase { */ private T determineActivePlugin(Class pluginInterface, PluginType pluginType) { ArrayList pluginsInCategory; - pluginsInCategory = MainApp.getSpecificPluginsListByInterface(pluginInterface); + pluginsInCategory = MainApp.instance().getSpecificPluginsListByInterface(pluginInterface); return this.determineActivePlugin(pluginsInCategory, pluginType); } @@ -443,23 +443,23 @@ public class ConfigBuilderPlugin extends PluginBase { break; // Single selection allowed case INSULIN: - pluginsInCategory = MainApp.getSpecificPluginsListByInterface(InsulinInterface.class); + pluginsInCategory = MainApp.instance().getSpecificPluginsListByInterface(InsulinInterface.class); break; case SENSITIVITY: - pluginsInCategory = MainApp.getSpecificPluginsListByInterface(SensitivityInterface.class); + pluginsInCategory = MainApp.instance().getSpecificPluginsListByInterface(SensitivityInterface.class); break; case APS: - pluginsInCategory = MainApp.getSpecificPluginsListByInterface(APSInterface.class); + pluginsInCategory = MainApp.instance().getSpecificPluginsListByInterface(APSInterface.class); break; case PROFILE: - pluginsInCategory = MainApp.getSpecificPluginsListByInterface(ProfileInterface.class); + pluginsInCategory = MainApp.instance().getSpecificPluginsListByInterface(ProfileInterface.class); break; case BGSOURCE: - pluginsInCategory = MainApp.getSpecificPluginsListByInterface(BgSourceInterface.class); + pluginsInCategory = MainApp.instance().getSpecificPluginsListByInterface(BgSourceInterface.class); break; case TREATMENT: case PUMP: - pluginsInCategory = MainApp.getSpecificPluginsListByInterface(PumpInterface.class); + pluginsInCategory = MainApp.instance().getSpecificPluginsListByInterface(PumpInterface.class); break; } if (pluginsInCategory != null) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConstraintChecker.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConstraintChecker.kt new file mode 100644 index 0000000000..a3a1e6e2ef --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConstraintChecker.kt @@ -0,0 +1,205 @@ +package info.nightscout.androidaps.plugins.configBuilder + +import info.nightscout.androidaps.Constants +import info.nightscout.androidaps.MainApp +import info.nightscout.androidaps.data.Profile +import info.nightscout.androidaps.interfaces.Constraint +import info.nightscout.androidaps.interfaces.ConstraintsInterface +import info.nightscout.androidaps.interfaces.PluginType +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class ConstraintChecker @Inject constructor(private val mainApp: MainApp) : ConstraintsInterface { + + init { + instance = this + } + + companion object { + @JvmStatic + lateinit var instance: ConstraintChecker + } + + fun isLoopInvocationAllowed(): Constraint = + isLoopInvocationAllowed(Constraint(true)) + + fun isClosedLoopAllowed(): Constraint = + isClosedLoopAllowed(Constraint(true)) + + fun isAutosensModeEnabled(): Constraint = + isAutosensModeEnabled(Constraint(true)) + + fun isAMAModeEnabled(): Constraint = + isAMAModeEnabled(Constraint(true)) + + fun isSMBModeEnabled(): Constraint = + isSMBModeEnabled(Constraint(true)) + + fun isUAMEnabled(): Constraint = + isUAMEnabled(Constraint(true)) + + fun isAdvancedFilteringEnabled(): Constraint = + isAdvancedFilteringEnabled(Constraint(true)) + + fun isSuperBolusEnabled(): Constraint = + isSuperBolusEnabled(Constraint(true)) + + fun getMaxBasalAllowed(profile: Profile): Constraint = + applyBasalConstraints(Constraint(Constants.REALLYHIGHBASALRATE), profile) + + fun getMaxBasalPercentAllowed(profile: Profile): Constraint = + applyBasalPercentConstraints(Constraint(Constants.REALLYHIGHPERCENTBASALRATE), profile) + + fun getMaxBolusAllowed(): Constraint = + applyBolusConstraints(Constraint(Constants.REALLYHIGHBOLUS)) + + fun getMaxExtendedBolusAllowed(): Constraint = + applyExtendedBolusConstraints(Constraint(Constants.REALLYHIGHBOLUS)) + + fun getMaxCarbsAllowed(): Constraint = + applyCarbsConstraints(Constraint(Constants.REALLYHIGHCARBS)) + + fun getMaxIOBAllowed(): Constraint = + applyMaxIOBConstraints(Constraint(Constants.REALLYHIGHIOB)) + + override fun isLoopInvocationAllowed(value: Constraint): Constraint { + val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java) + for (p in constraintsPlugins) { + val constraint = p as ConstraintsInterface + if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + constraint.isLoopInvocationAllowed(value) + } + return value + } + + override fun isClosedLoopAllowed(value: Constraint): Constraint { + val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java) + for (p in constraintsPlugins) { + val constraint = p as ConstraintsInterface + if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + constraint.isClosedLoopAllowed(value) + } + return value + } + + override fun isAutosensModeEnabled(value: Constraint): Constraint { + val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java) + for (p in constraintsPlugins) { + val constraint = p as ConstraintsInterface + if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + constraint.isAutosensModeEnabled(value) + } + return value + } + + override fun isAMAModeEnabled(value: Constraint): Constraint { + val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java) + for (p in constraintsPlugins) { + val constrain = p as ConstraintsInterface + if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + constrain.isAMAModeEnabled(value) + } + return value + } + + override fun isSMBModeEnabled(value: Constraint): Constraint { + val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java) + for (p in constraintsPlugins) { + val constraint = p as ConstraintsInterface + if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + constraint.isSMBModeEnabled(value) + } + return value + } + + override fun isUAMEnabled(value: Constraint): Constraint { + val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java) + for (p in constraintsPlugins) { + val constraint = p as ConstraintsInterface + if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + constraint.isUAMEnabled(value) + } + return value + } + + override fun isAdvancedFilteringEnabled(value: Constraint): Constraint { + val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java) + for (p in constraintsPlugins) { + val constraint = p as ConstraintsInterface + if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + constraint.isAdvancedFilteringEnabled(value) + } + return value + } + + override fun isSuperBolusEnabled(value: Constraint): Constraint { + val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java) + for (p in constraintsPlugins) { + val constraint = p as ConstraintsInterface + if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + constraint.isSuperBolusEnabled(value) + } + return value + } + + override fun applyBasalConstraints(absoluteRate: Constraint, profile: Profile): Constraint { + val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java) + for (p in constraintsPlugins) { + val constraint = p as ConstraintsInterface + if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + constraint.applyBasalConstraints(absoluteRate, profile) + } + return absoluteRate + } + + override fun applyBasalPercentConstraints(percentRate: Constraint, profile: Profile): Constraint { + val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java) + for (p in constraintsPlugins) { + val constrain = p as ConstraintsInterface + if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + constrain.applyBasalPercentConstraints(percentRate, profile) + } + return percentRate + } + + override fun applyBolusConstraints(insulin: Constraint): Constraint { + val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java) + for (p in constraintsPlugins) { + val constrain = p as ConstraintsInterface + if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + constrain.applyBolusConstraints(insulin) + } + return insulin + } + + override fun applyExtendedBolusConstraints(insulin: Constraint): Constraint { + val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java) + for (p in constraintsPlugins) { + val constrain = p as ConstraintsInterface + if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + constrain.applyExtendedBolusConstraints(insulin) + } + return insulin + } + + override fun applyCarbsConstraints(carbs: Constraint): Constraint { + val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java) + for (p in constraintsPlugins) { + val constrain = p as ConstraintsInterface + if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + constrain.applyCarbsConstraints(carbs) + } + return carbs + } + + override fun applyMaxIOBConstraints(maxIob: Constraint): Constraint { + val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java) + for (p in constraintsPlugins) { + val constrain = p as ConstraintsInterface + if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + constrain.applyMaxIOBConstraints(maxIob) + } + return maxIob + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective6.java b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective6.java index 1b224bd40c..d0c8452d4e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective6.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective6.java @@ -2,8 +2,8 @@ package info.nightscout.androidaps.plugins.constraints.objectives.objectives; import java.util.List; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.utils.T; public class Objective6 extends Objective { @@ -18,7 +18,7 @@ public class Objective6 extends Objective { tasks.add(new Task(R.string.maxiobset) { @Override public boolean isCompleted() { - double maxIOB = MainApp.getConstraintChecker().getMaxIOBAllowed().value(); + double maxIOB = ConstraintChecker.getInstance().getMaxIOBAllowed().value(); return maxIOB > 0; } }); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.java index 4d66f36194..9e31635f92 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.java @@ -3,7 +3,6 @@ package info.nightscout.androidaps.plugins.constraints.safety; import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ConstraintChecker; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.interfaces.BgSourceInterface; import info.nightscout.androidaps.interfaces.Constraint; @@ -18,6 +17,7 @@ import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAPlugin; import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin; @@ -90,8 +90,7 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface { boolean enabled = SP.getBoolean(R.string.key_use_smb, false); if (!enabled) value.set(false, MainApp.gs(R.string.smbdisabledinpreferences), this); - ConstraintChecker constraintChecker = MainApp.getConstraintChecker(); - Constraint closedLoop = constraintChecker.isClosedLoopAllowed(); + Constraint closedLoop = ConstraintChecker.getInstance().isClosedLoopAllowed(); if (!closedLoop.value()) value.set(false, MainApp.gs(R.string.smbnotallowedinopenloopmode), this); return value; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialog.java index c4f70f40bf..1236600c10 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialog.java @@ -46,6 +46,7 @@ import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.db.ProfileSwitch; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.careportal.OptionsToShow; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; @@ -272,11 +273,11 @@ public class NewNSTreatmentDialog extends AppCompatDialogFragment implements Vie } }); - Integer maxCarbs = MainApp.getConstraintChecker().getMaxCarbsAllowed().value(); + Integer maxCarbs = ConstraintChecker.getInstance().getMaxCarbsAllowed().value(); editCarbs = view.findViewById(R.id.careportal_newnstreatment_carbsinput); editCarbs.setParams(0d, 0d, (double) maxCarbs, 1d, new DecimalFormat("0"), false, view.findViewById(R.id.ok)); - Double maxInsulin = MainApp.getConstraintChecker().getMaxBolusAllowed().value(); + Double maxInsulin = ConstraintChecker.getInstance().getMaxBolusAllowed().value(); editInsulin = view.findViewById(R.id.careportal_newnstreatment_insulininput); editInsulin.setParams(0d, 0d, maxInsulin, 0.05d, new DecimalFormat("0.00"), false, view.findViewById(R.id.ok)); @@ -305,7 +306,7 @@ public class NewNSTreatmentDialog extends AppCompatDialogFragment implements Vie Integer maxPercent = 200; if (profile != null) - maxPercent = MainApp.getConstraintChecker().getMaxBasalPercentAllowed(profile).value(); + maxPercent = ConstraintChecker.getInstance().getMaxBasalPercentAllowed(profile).value(); editPercent = view.findViewById(R.id.careportal_newnstreatment_percentinput); editPercent.setParams(0d, -100d, (double) maxPercent, 5d, new DecimalFormat("0"), true, view.findViewById(R.id.ok), percentTextWatcher); @@ -329,7 +330,7 @@ public class NewNSTreatmentDialog extends AppCompatDialogFragment implements Vie Double maxAbsolute = HardLimits.maxBasal(); if (profile != null) - maxAbsolute = MainApp.getConstraintChecker().getMaxBasalAllowed(profile).value(); + maxAbsolute = ConstraintChecker.getInstance().getMaxBasalAllowed(profile).value(); editAbsolute = view.findViewById(R.id.careportal_newnstreatment_absoluteinput); editAbsolute.setParams(0d, 0d, maxAbsolute, 0.05d, new DecimalFormat("0.00"), true, view.findViewById(R.id.ok), absoluteTextWatcher); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java index 21a3e1b271..b4c3825452 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java @@ -25,7 +25,6 @@ import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; -import androidx.appcompat.app.AlertDialog; import androidx.appcompat.widget.PopupMenu; import androidx.core.content.res.ResourcesCompat; import androidx.fragment.app.Fragment; @@ -90,6 +89,7 @@ import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; import info.nightscout.androidaps.plugins.aps.loop.events.EventNewOpenLoopNotification; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.careportal.CareportalFragment; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; @@ -930,7 +930,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, final BolusWizard wizard = quickWizardEntry.doCalc(profile, profileName, actualBg, true); if (wizard.getCalculatedTotalInsulin() > 0d && quickWizardEntry.carbs() > 0d) { - Integer carbsAfterConstraints = MainApp.getConstraintChecker().applyCarbsConstraints(new Constraint<>(quickWizardEntry.carbs())).value(); + Integer carbsAfterConstraints = ConstraintChecker.getInstance().applyCarbsConstraints(new Constraint<>(quickWizardEntry.carbs())).value(); if (Math.abs(wizard.getInsulinAfterConstraints() - wizard.getCalculatedTotalInsulin()) >= pump.getPumpDescription().pumpType.determineCorrectBolusStepSize(wizard.getInsulinAfterConstraints()) || !carbsAfterConstraints.equals(quickWizardEntry.carbs())) { OKDialog.show(getContext(), MainApp.gs(R.string.treatmentdeliveryerror), MainApp.gs(R.string.constraints_violation) + "\n" + MainApp.gs(R.string.changeyourinput)); @@ -1059,7 +1059,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, } } - Constraint closedLoopEnabled = MainApp.getConstraintChecker().isClosedLoopAllowed(); + Constraint closedLoopEnabled = ConstraintChecker.getInstance().isClosedLoopAllowed(); // open loop mode final LoopPlugin.LastRun finalLastRun = LoopPlugin.lastRun; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt index 158864bb74..b2b6515b7d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt @@ -10,7 +10,6 @@ import android.telephony.SmsMessage import android.text.TextUtils import com.andreabaccega.widget.ValidatingEditTextPreference import info.nightscout.androidaps.Constants -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.data.DetailedBolusInfo import info.nightscout.androidaps.data.Profile @@ -28,6 +27,7 @@ import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBus.send import info.nightscout.androidaps.plugins.bus.RxBus.toObservable import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart @@ -52,7 +52,8 @@ import javax.inject.Singleton @Singleton class SmsCommunicatorPlugin @Inject constructor( val configBuilderPlugin: ConfigBuilderPlugin, - val resourceHelper: ResourceHelper + val resourceHelper: ResourceHelper, + val constraintChecker: ConstraintChecker ) : PluginBase(PluginDescription() .mainType(PluginType.GENERAL) .fragmentClass(SmsCommunicatorFragment::class.java.name) @@ -506,7 +507,7 @@ class SmsCommunicatorPlugin @Inject constructor( else if (tempBasalPct == 0 && splitted[1] != "0%") sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) else if (duration == 0) sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) else { - tempBasalPct = MainApp.getConstraintChecker().applyBasalPercentConstraints(Constraint(tempBasalPct), profile).value() + tempBasalPct = constraintChecker.applyBasalPercentConstraints(Constraint(tempBasalPct), profile).value() val passCode = generatePasscode() val reply = String.format(resourceHelper.gs(R.string.smscommunicator_basalpctreplywithcode), tempBasalPct, duration, passCode) receivedSms.processed = true @@ -538,7 +539,7 @@ class SmsCommunicatorPlugin @Inject constructor( else if (tempBasal == 0.0 && splitted[1] != "0") sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) else if (duration == 0) sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) else { - tempBasal = MainApp.getConstraintChecker().applyBasalConstraints(Constraint(tempBasal), profile).value() + tempBasal = constraintChecker.applyBasalConstraints(Constraint(tempBasal), profile).value() val passCode = generatePasscode() val reply = String.format(resourceHelper.gs(R.string.smscommunicator_basalreplywithcode), tempBasal, duration, passCode) receivedSms.processed = true @@ -591,7 +592,7 @@ class SmsCommunicatorPlugin @Inject constructor( } else { var extended = SafeParse.stringToDouble(splitted[1]) val duration = SafeParse.stringToInt(splitted[2]) - extended = MainApp.getConstraintChecker().applyExtendedBolusConstraints(Constraint(extended)).value() + extended = constraintChecker.applyExtendedBolusConstraints(Constraint(extended)).value() if (extended == 0.0 || duration == 0) sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) else { val passCode = generatePasscode() @@ -621,7 +622,7 @@ class SmsCommunicatorPlugin @Inject constructor( private fun processBOLUS(splitted: Array, receivedSms: Sms) { var bolus = SafeParse.stringToDouble(splitted[1]) val isMeal = splitted.size > 2 && splitted[2].equals("MEAL", ignoreCase = true) - bolus = MainApp.getConstraintChecker().applyBolusConstraints(Constraint(bolus)).value() + bolus = constraintChecker.applyBolusConstraints(Constraint(bolus)).value() if (splitted.size == 3 && !isMeal) { sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) } else if (bolus > 0.0) { @@ -701,7 +702,7 @@ class SmsCommunicatorPlugin @Inject constructor( } time = midnight + T.secs(seconds.toLong()).msecs() } - grams = MainApp.getConstraintChecker().applyCarbsConstraints(Constraint(grams)).value() + grams = constraintChecker.applyCarbsConstraints(Constraint(grams)).value() if (grams == 0) sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) else { val passCode = generatePasscode() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.java index d25d42bbe2..a137def1d4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.java @@ -35,6 +35,7 @@ import info.nightscout.androidaps.plugins.aps.loop.APSResult; import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog; import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification; @@ -95,7 +96,7 @@ public class ActionStringHandler { } else { return; } - Double insulinAfterConstraints = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(amount)).value(); + Double insulinAfterConstraints = ConstraintChecker.getInstance().applyBolusConstraints(new Constraint<>(amount)).value(); rMessage += MainApp.gs(R.string.primefill) + ": " + insulinAfterConstraints + "U"; if (insulinAfterConstraints - amount != 0) rMessage += "\n" + MainApp.gs(R.string.constraintapllied); @@ -106,7 +107,7 @@ public class ActionStringHandler { ////////////////////////////////////////////// PRIME/FILL double amount = SafeParse.stringToDouble(act[1]); - Double insulinAfterConstraints = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(amount)).value(); + Double insulinAfterConstraints = ConstraintChecker.getInstance().applyBolusConstraints(new Constraint<>(amount)).value(); rMessage += MainApp.gs(R.string.primefill) + ": " + insulinAfterConstraints + "U"; if (insulinAfterConstraints - amount != 0) rMessage += "\n" + MainApp.gs(R.string.constraintapllied); @@ -117,8 +118,8 @@ public class ActionStringHandler { ////////////////////////////////////////////// BOLUS double insulin = SafeParse.stringToDouble(act[1]); int carbs = SafeParse.stringToInt(act[2]); - Double insulinAfterConstraints = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(insulin)).value(); - Integer carbsAfterConstraints = MainApp.getConstraintChecker().applyCarbsConstraints(new Constraint<>(carbs)).value(); + Double insulinAfterConstraints = ConstraintChecker.getInstance().applyBolusConstraints(new Constraint<>(insulin)).value(); + Integer carbsAfterConstraints = ConstraintChecker.getInstance().applyCarbsConstraints(new Constraint<>(carbs)).value(); rMessage += MainApp.gs(R.string.bolus) + ": " + insulinAfterConstraints + "U\n"; rMessage += MainApp.gs(R.string.carbs) + ": " + carbsAfterConstraints + "g"; @@ -180,7 +181,7 @@ public class ActionStringHandler { } else if ("wizard2".equals(act[0])) { ////////////////////////////////////////////// WIZARD Integer carbsBeforeConstraints = SafeParse.stringToInt(act[1]); - Integer carbsAfterConstraints = MainApp.getConstraintChecker().applyCarbsConstraints(new Constraint<>(carbsBeforeConstraints)).value(); + Integer carbsAfterConstraints = ConstraintChecker.getInstance().applyCarbsConstraints(new Constraint<>(carbsBeforeConstraints)).value(); if (carbsAfterConstraints - carbsBeforeConstraints != 0) { sendError("Carb constraint violation!"); @@ -324,7 +325,7 @@ public class ActionStringHandler { int starttime = SafeParse.stringToInt(act[2]); int duration = SafeParse.stringToInt(act[3]); long starttimestamp = System.currentTimeMillis() + starttime * 60 * 1000; - Integer carbsAfterConstraints = MainApp.getConstraintChecker().applyCarbsConstraints(new Constraint<>(carbs)).value(); + Integer carbsAfterConstraints = ConstraintChecker.getInstance().applyCarbsConstraints(new Constraint<>(carbs)).value(); rMessage += MainApp.gs(R.string.carbs) + ": " + carbsAfterConstraints + "g"; rMessage += "\n" + MainApp.gs(R.string.time) + ": " + DateUtil.timeString(starttimestamp); rMessage += "\n" + MainApp.gs(R.string.duration) + ": " + duration + "h"; @@ -491,7 +492,7 @@ public class ActionStringHandler { // decide if enabled/disabled closed/open; what Plugin as APS? final LoopPlugin loopPlugin = LoopPlugin.getPlugin(); if (loopPlugin.isEnabled(loopPlugin.getType())) { - if (MainApp.getConstraintChecker().isClosedLoopAllowed().value()) { + if (ConstraintChecker.getInstance().isClosedLoopAllowed().value()) { ret += "CLOSED LOOP\n"; } else { ret += "OPEN LOOP\n"; @@ -591,7 +592,7 @@ public class ActionStringHandler { if ("fill".equals(act[0])) { Double amount = SafeParse.stringToDouble(act[1]); - Double insulinAfterConstraints = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(amount)).value(); + Double insulinAfterConstraints = ConstraintChecker.getInstance().applyBolusConstraints(new Constraint<>(amount)).value(); if (amount - insulinAfterConstraints != 0) { ToastUtils.showToastInUiThread(MainApp.instance(), "aborting: previously applied constraint changed"); sendError("aborting: previously applied constraint changed"); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/AbstractDanaRPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/AbstractDanaRPlugin.java index 57dadbdc55..cd25f80ba2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/AbstractDanaRPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/AbstractDanaRPlugin.java @@ -28,6 +28,7 @@ import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.common.ManufacturerType; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction; import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType; import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification; @@ -178,7 +179,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) { DanaRPump pump = DanaRPump.getInstance(); PumpEnactResult result = new PumpEnactResult(); - percent = MainApp.getConstraintChecker().applyBasalPercentConstraints(new Constraint<>(percent), profile).value(); + percent = ConstraintChecker.getInstance().applyBasalPercentConstraints(new Constraint<>(percent), profile).value(); if (percent < 0) { result.isTempCancel = false; result.enacted = false; @@ -227,7 +228,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte @Override public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) { DanaRPump pump = DanaRPump.getInstance(); - insulin = MainApp.getConstraintChecker().applyExtendedBolusConstraints(new Constraint<>(insulin)).value(); + insulin = ConstraintChecker.getInstance().applyExtendedBolusConstraints(new Constraint<>(insulin)).value(); // needs to be rounded int durationInHalfHours = Math.max(durationInMinutes / 30, 1); insulin = Round.roundTo(insulin, getPumpDescription().extendedBolusStep); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPlugin.java index e9293b39a6..0d0205b734 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPlugin.java @@ -19,6 +19,7 @@ import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.bus.RxBus; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.danaR.comm.MsgBolusStartWithSpeed; import info.nightscout.androidaps.plugins.pump.danaR.services.DanaRExecutionService; @@ -139,7 +140,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { @Override public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { - detailedBolusInfo.insulin = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); + detailedBolusInfo.insulin = ConstraintChecker.getInstance().applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) { Treatment t = new Treatment(); t.isSMB = detailedBolusInfo.isSMB; @@ -183,7 +184,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { PumpEnactResult result = new PumpEnactResult(); - absoluteRate = MainApp.getConstraintChecker().applyBasalConstraints(new Constraint<>(absoluteRate), profile).value(); + absoluteRate = ConstraintChecker.getInstance().applyBasalConstraints(new Constraint<>(absoluteRate), profile).value(); final boolean doTempOff = getBaseBasalRate() - absoluteRate == 0d; final boolean doLowTemp = absoluteRate < getBaseBasalRate(); @@ -280,7 +281,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { Integer durationInHalfHours = Math.max(durationInMinutes / 30, 1); // We keep current basal running so need to sub current basal Double extendedRateToSet = absoluteRate - getBaseBasalRate(); - extendedRateToSet = MainApp.getConstraintChecker().applyBasalConstraints(new Constraint<>(extendedRateToSet), profile).value(); + extendedRateToSet = ConstraintChecker.getInstance().applyBasalConstraints(new Constraint<>(extendedRateToSet), profile).value(); // needs to be rounded to 0.1 extendedRateToSet = Round.roundTo(extendedRateToSet, pumpDescription.extendedBolusStep * 2); // *2 because of halfhours diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStart.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStart.java index 4b7cd2ff41..f3cd33478d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStart.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStart.java @@ -3,9 +3,9 @@ package info.nightscout.androidaps.plugins.pump.danaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; public class MsgBolusStart extends MessageBase { private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); @@ -20,7 +20,7 @@ public class MsgBolusStart extends MessageBase { this(); // HARDCODED LIMIT - amount = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(amount)).value(); + amount = ConstraintChecker.getInstance().applyBolusConstraints(new Constraint<>(amount)).value(); AddParamInt((int) (amount * 100)); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStartWithSpeed.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStartWithSpeed.java index 0c174807b3..de73ff0491 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStartWithSpeed.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStartWithSpeed.java @@ -3,9 +3,9 @@ package info.nightscout.androidaps.plugins.pump.danaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; public class MsgBolusStartWithSpeed extends MessageBase { private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); @@ -20,7 +20,7 @@ public class MsgBolusStartWithSpeed extends MessageBase { this(); // HARDCODED LIMIT - amount = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(amount)).value(); + amount = ConstraintChecker.getInstance().applyBolusConstraints(new Constraint<>(amount)).value(); AddParamInt((int) (amount * 100)); AddParamByte((byte) speed); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetExtendedBolusStart.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetExtendedBolusStart.java index dad437ac72..f6b3d85aa5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetExtendedBolusStart.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetExtendedBolusStart.java @@ -3,9 +3,9 @@ package info.nightscout.androidaps.plugins.pump.danaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; public class MsgSetExtendedBolusStart extends MessageBase { private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); @@ -22,13 +22,8 @@ public class MsgSetExtendedBolusStart extends MessageBase { // HARDCODED LIMITS if (halfhours < 1) halfhours = 1; if (halfhours > 16) halfhours = 16; - Constraint constrainedAmount = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(amount)); - if (constrainedAmount != null) { - AddParamInt((int) (constrainedAmount.value() * 100)); - } else { - log.error("constrainedAmount of insulin is null!!"); - AddParamInt(0); - } + Constraint constrainedAmount = ConstraintChecker.getInstance().applyBolusConstraints(new Constraint<>(amount)); + AddParamInt((int) (constrainedAmount.value() * 100)); AddParamByte(halfhours); if (L.isEnabled(L.PUMPCOMM)) log.debug("Set extended bolus start: " + (((int) (amount * 100)) / 100d) + "U halfhours: " + (int) halfhours); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPlugin.java index 2645e25ade..ba39c52d9b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPlugin.java @@ -19,6 +19,7 @@ import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.bus.RxBus; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.danaR.AbstractDanaRPlugin; import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump; @@ -142,7 +143,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { @Override public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { - detailedBolusInfo.insulin = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); + detailedBolusInfo.insulin = ConstraintChecker.getInstance().applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) { Treatment t = new Treatment(); t.isSMB = detailedBolusInfo.isSMB; @@ -186,7 +187,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { PumpEnactResult result = new PumpEnactResult(); - absoluteRate = MainApp.getConstraintChecker().applyBasalConstraints(new Constraint<>(absoluteRate), profile).value(); + absoluteRate = ConstraintChecker.getInstance().applyBasalConstraints(new Constraint<>(absoluteRate), profile).value(); final boolean doTempOff = getBaseBasalRate() - absoluteRate == 0d; final boolean doLowTemp = absoluteRate < getBaseBasalRate(); @@ -283,7 +284,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { Integer durationInHalfHours = Math.max(durationInMinutes / 30, 1); // We keep current basal running so need to sub current basal Double extendedRateToSet = absoluteRate - getBaseBasalRate(); - extendedRateToSet = MainApp.getConstraintChecker().applyBasalConstraints(new Constraint<>(extendedRateToSet), profile).value(); + extendedRateToSet = ConstraintChecker.getInstance().applyBasalConstraints(new Constraint<>(extendedRateToSet), profile).value(); // needs to be rounded to 0.1 extendedRateToSet = Round.roundTo(extendedRateToSet, pumpDescription.extendedBolusStep * 2); // *2 because of halfhours diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java index 8c8780d021..5dcbfb9057 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java @@ -7,7 +7,6 @@ import android.content.ServiceConnection; import android.os.IBinder; import android.preference.Preference; -import androidx.annotation.Nullable; import androidx.fragment.app.FragmentActivity; import org.jetbrains.annotations.NotNull; @@ -23,7 +22,6 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.Profile; -import info.nightscout.androidaps.data.ProfileStore; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.TemporaryBasal; @@ -39,6 +37,7 @@ import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.common.ManufacturerType; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction; import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType; @@ -370,7 +369,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte @Override public synchronized PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { - detailedBolusInfo.insulin = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); + detailedBolusInfo.insulin = ConstraintChecker.getInstance().applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) { int preferencesSpeed = SP.getInt(R.string.key_danars_bolusspeed, 0); int speed = 12; @@ -462,7 +461,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte PumpEnactResult result = new PumpEnactResult(); - absoluteRate = MainApp.getConstraintChecker().applyBasalConstraints(new Constraint<>(absoluteRate), profile).value(); + absoluteRate = ConstraintChecker.getInstance().applyBasalConstraints(new Constraint<>(absoluteRate), profile).value(); final boolean doTempOff = getBaseBasalRate() - absoluteRate == 0d; final boolean doLowTemp = absoluteRate < getBaseBasalRate(); @@ -539,7 +538,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte public synchronized PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) { DanaRPump pump = DanaRPump.getInstance(); PumpEnactResult result = new PumpEnactResult(); - percent = MainApp.getConstraintChecker().applyBasalPercentConstraints(new Constraint<>(percent), profile).value(); + percent = ConstraintChecker.getInstance().applyBasalPercentConstraints(new Constraint<>(percent), profile).value(); if (percent < 0) { result.isTempCancel = false; result.enacted = false; @@ -616,7 +615,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte @Override public synchronized PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) { DanaRPump pump = DanaRPump.getInstance(); - insulin = MainApp.getConstraintChecker().applyExtendedBolusConstraints(new Constraint<>(insulin)).value(); + insulin = ConstraintChecker.getInstance().applyExtendedBolusConstraints(new Constraint<>(insulin)).value(); // needs to be rounded int durationInHalfHours = Math.max(durationInMinutes / 30, 1); insulin = Round.roundTo(insulin, getPumpDescription().extendedBolusStep); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Start.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Start.java index 7ff91fa9ef..f2a2f1e783 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Start.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Start.java @@ -5,9 +5,9 @@ import com.cozmo.danar.util.BleCommandUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; public class DanaRS_Packet_Bolus_Set_Step_Bolus_Start extends DanaRS_Packet { private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); @@ -28,7 +28,7 @@ public class DanaRS_Packet_Bolus_Set_Step_Bolus_Start extends DanaRS_Packet { this(); // HARDCODED LIMIT - if there is one that could be created - amount = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(amount)).value(); + amount = ConstraintChecker.getInstance().applyBolusConstraints(new Constraint<>(amount)).value(); this.amount = amount; this.speed = speed; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2Plugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2Plugin.java index 3437d37656..e6fac58b9a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2Plugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2Plugin.java @@ -16,6 +16,7 @@ import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.bus.RxBus; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.danaR.AbstractDanaRPlugin; @@ -128,7 +129,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { // Pump interface @Override public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { - detailedBolusInfo.insulin = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); + detailedBolusInfo.insulin = ConstraintChecker.getInstance().applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) { // v2 stores end time for bolus, we need to adjust time // default delivery speed is 12 sec/U @@ -204,7 +205,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { PumpEnactResult result = new PumpEnactResult(); - absoluteRate = MainApp.getConstraintChecker().applyBasalConstraints(new Constraint<>(absoluteRate), profile).value(); + absoluteRate = ConstraintChecker.getInstance().applyBasalConstraints(new Constraint<>(absoluteRate), profile).value(); final boolean doTempOff = getBaseBasalRate() - absoluteRate == 0d; final boolean doLowTemp = absoluteRate < getBaseBasalRate(); @@ -279,7 +280,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) { DanaRPump pump = DanaRPump.getInstance(); PumpEnactResult result = new PumpEnactResult(); - percent = MainApp.getConstraintChecker().applyBasalPercentConstraints(new Constraint<>(percent), profile).value(); + percent = ConstraintChecker.getInstance().applyBasalPercentConstraints(new Constraint<>(percent), profile).value(); if (percent < 0) { result.isTempCancel = false; result.enacted = false; diff --git a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java index 05efc63aa3..489163eb5a 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java @@ -13,20 +13,23 @@ import org.slf4j.LoggerFactory; import java.util.LinkedList; +import javax.inject.Inject; + import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.activities.BolusProgressHelperActivity; import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; +import info.nightscout.androidaps.dialogs.BolusProgressDialog; import info.nightscout.androidaps.events.EventBolusRequested; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; -import info.nightscout.androidaps.dialogs.BolusProgressDialog; import info.nightscout.androidaps.plugins.general.overview.events.EventDismissBolusProgressIfRunning; import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; @@ -236,8 +239,8 @@ public class CommandQueue { } // apply constraints - detailedBolusInfo.insulin = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); - detailedBolusInfo.carbs = MainApp.getConstraintChecker().applyCarbsConstraints(new Constraint<>((int) detailedBolusInfo.carbs)).value(); + detailedBolusInfo.insulin = ConstraintChecker.getInstance().applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); + detailedBolusInfo.carbs = ConstraintChecker.getInstance().applyCarbsConstraints(new Constraint<>((int) detailedBolusInfo.carbs)).value(); // add new command to queue if (detailedBolusInfo.isSMB) { @@ -293,7 +296,7 @@ public class CommandQueue { // remove all unfinished removeAll(Command.CommandType.TEMPBASAL); - Double rateAfterConstraints = MainApp.getConstraintChecker().applyBasalConstraints(new Constraint<>(absoluteRate), profile).value(); + Double rateAfterConstraints = ConstraintChecker.getInstance().applyBasalConstraints(new Constraint<>(absoluteRate), profile).value(); // add new command to queue add(new CommandTempBasalAbsolute(rateAfterConstraints, durationInMinutes, enforceNew, profile, callback)); @@ -314,7 +317,7 @@ public class CommandQueue { // remove all unfinished removeAll(Command.CommandType.TEMPBASAL); - Integer percentAfterConstraints = MainApp.getConstraintChecker().applyBasalPercentConstraints(new Constraint<>(percent), profile).value(); + Integer percentAfterConstraints = ConstraintChecker.getInstance().applyBasalPercentConstraints(new Constraint<>(percent), profile).value(); // add new command to queue add(new CommandTempBasalPercent(percentAfterConstraints, durationInMinutes, enforceNew, profile, callback)); @@ -332,7 +335,7 @@ public class CommandQueue { return false; } - Double rateAfterConstraints = MainApp.getConstraintChecker().applyExtendedBolusConstraints(new Constraint<>(insulin)).value(); + Double rateAfterConstraints = ConstraintChecker.getInstance().applyExtendedBolusConstraints(new Constraint<>(insulin)).value(); // remove all unfinished removeAll(Command.CommandType.EXTENDEDBOLUS); diff --git a/app/src/main/java/info/nightscout/androidaps/utils/BolusWizard.kt b/app/src/main/java/info/nightscout/androidaps/utils/BolusWizard.kt index df1a0586de..dc5c6b3fc8 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/BolusWizard.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/BolusWizard.kt @@ -19,6 +19,7 @@ import info.nightscout.androidaps.logging.L import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin @@ -186,7 +187,7 @@ class BolusWizard @JvmOverloads constructor(val profile: Profile, ?: 0.1 calculatedTotalInsulin = Round.roundTo(calculatedTotalInsulin, bolusStep) - insulinAfterConstraints = MainApp.getConstraintChecker().applyBolusConstraints(Constraint(calculatedTotalInsulin)).value() + insulinAfterConstraints = ConstraintChecker.instance.applyBolusConstraints(Constraint(calculatedTotalInsulin)).value() log.debug(this.toString()) } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/FabricPrivacy.java b/app/src/main/java/info/nightscout/androidaps/utils/FabricPrivacy.java index 355623f38d..560c44c84e 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/FabricPrivacy.java +++ b/app/src/main/java/info/nightscout/androidaps/utils/FabricPrivacy.java @@ -14,6 +14,7 @@ import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.constraints.signatureVerifier.SignatureVerifierPlugin; /** @@ -113,7 +114,7 @@ public class FabricPrivacy { public static void setUserStats() { if (!fabricEnabled()) return; - String closedLoopEnabled = MainApp.getConstraintChecker().isClosedLoopAllowed().value() ? "CLOSED_LOOP_ENABLED" : "CLOSED_LOOP_DISABLED"; + String closedLoopEnabled = ConstraintChecker.getInstance().isClosedLoopAllowed().value() ? "CLOSED_LOOP_ENABLED" : "CLOSED_LOOP_DISABLED"; // Size is limited to 36 chars String remote = BuildConfig.REMOTE.toLowerCase() .replace("https://", "") diff --git a/app/src/test/java/info/AAPSMocker.java b/app/src/test/java/info/AAPSMocker.java index b48942fbc4..2fe8c77c9f 100644 --- a/app/src/test/java/info/AAPSMocker.java +++ b/app/src/test/java/info/AAPSMocker.java @@ -1,7 +1,6 @@ package info; import android.content.Context; -import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.Resources; @@ -15,7 +14,7 @@ import java.util.Locale; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ConstraintChecker; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.ProfileStore; @@ -25,9 +24,6 @@ import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin; -import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin; -import info.nightscout.androidaps.plugins.pump.danaRv2.DanaRv2Plugin; import info.nightscout.androidaps.plugins.treatments.TreatmentService; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.queue.CommandQueue; diff --git a/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.java b/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.java index f3577e35c8..a5112579ff 100644 --- a/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.java +++ b/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.java @@ -16,7 +16,7 @@ import java.util.ArrayList; import info.AAPSMocker; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ConstraintChecker; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin; import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAPlugin; import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin; @@ -63,7 +63,7 @@ public class ConstraintsCheckerTest { comboPlugin.setPluginEnabled(PluginType.PUMP, true); comboPlugin.setValidBasalRateProfileSelectedOnPump(false); - Constraint c = constraintChecker.isLoopInvokationAllowed(); + Constraint c = constraintChecker.isLoopInvocationAllowed(); Assert.assertEquals(true, c.getReasonList().size() == 2); // Combo & Objectives Assert.assertEquals(true, c.getMostLimitedReasonList().size() == 2); // Combo & Objectives Assert.assertEquals(Boolean.FALSE, c.value()); @@ -129,7 +129,7 @@ public class ConstraintsCheckerTest { public void isSMBModeEnabledTest() throws Exception { objectivesPlugin.getObjectives().get(ObjectivesPlugin.INSTANCE.getSMB_OBJECTIVE()).setStartedOn(0); when(SP.getBoolean(R.string.key_use_smb, false)).thenReturn(false); - when(MainApp.getConstraintChecker().isClosedLoopAllowed()).thenReturn(new Constraint<>(true)); + when(ConstraintChecker.getInstance().isClosedLoopAllowed()).thenReturn(new Constraint<>(true)); Constraint c = constraintChecker.isSMBModeEnabled(); Assert.assertEquals(true, c.getReasonList().size() == 2); // Safety & Objectives diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.java index 1db142af2c..70cbbf5bac 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.java @@ -12,7 +12,7 @@ import org.powermock.modules.junit4.PowerMockRunner; import info.AAPSMocker; import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.data.ConstraintChecker; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.logging.L; diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.java index 1dabf0ff30..959e1620cd 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.java @@ -69,7 +69,7 @@ public class SafetyPluginTest { @Test public void notEnabledSMBInPreferencesDisablesSMB() { when(SP.getBoolean(R.string.key_use_smb, false)).thenReturn(false); - when(MainApp.getConstraintChecker().isClosedLoopAllowed()).thenReturn(new Constraint<>(true)); + when(ConstraintChecker.getInstance().isClosedLoopAllowed()).thenReturn(new Constraint<>(true)); Constraint c = new Constraint<>(true); c = safetyPlugin.isSMBModeEnabled(c); @@ -80,7 +80,7 @@ public class SafetyPluginTest { @Test public void openLoopPreventsSMB() { when(SP.getBoolean(R.string.key_use_smb, false)).thenReturn(true); - when(MainApp.getConstraintChecker().isClosedLoopAllowed()).thenReturn(new Constraint<>(false)); + when(ConstraintChecker.getInstance().isClosedLoopAllowed()).thenReturn(new Constraint<>(false)); Constraint c = new Constraint<>(true); c = safetyPlugin.isSMBModeEnabled(c); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.java index a00c029ce9..641f11bed3 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.java @@ -29,6 +29,7 @@ import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.insulin.InsulinOrefRapidActingPlugin; @@ -552,7 +553,7 @@ public class SmsCommunicatorPluginTest { Assert.assertEquals("BASAL 10% 0", smsCommunicatorPlugin.getMessages().get(0).getText()); Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - when(MainApp.getConstraintChecker().applyBasalPercentConstraints(any(), any())).thenReturn(new Constraint<>(20)); + when(ConstraintChecker.getInstance().applyBasalPercentConstraints(any(), any())).thenReturn(new Constraint<>(20)); //BASAL 20% 20 smsCommunicatorPlugin.setMessages(new ArrayList<>()); @@ -579,7 +580,7 @@ public class SmsCommunicatorPluginTest { Assert.assertEquals("BASAL 1 0", smsCommunicatorPlugin.getMessages().get(0).getText()); Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - when(MainApp.getConstraintChecker().applyBasalConstraints(any(), any())).thenReturn(new Constraint<>(1d)); + when(ConstraintChecker.getInstance().applyBasalConstraints(any(), any())).thenReturn(new Constraint<>(1d)); //BASAL 1 20 smsCommunicatorPlugin.setMessages(new ArrayList<>()); @@ -632,7 +633,7 @@ public class SmsCommunicatorPluginTest { Assert.assertEquals("EXTENDED a%", smsCommunicatorPlugin.getMessages().get(0).getText()); Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - when(MainApp.getConstraintChecker().applyExtendedBolusConstraints(any())).thenReturn(new Constraint<>(1d)); + when(ConstraintChecker.getInstance().applyExtendedBolusConstraints(any())).thenReturn(new Constraint<>(1d)); //EXTENDED 1 0 smsCommunicatorPlugin.setMessages(new ArrayList<>()); @@ -673,7 +674,7 @@ public class SmsCommunicatorPluginTest { Assert.assertEquals("BOLUS", smsCommunicatorPlugin.getMessages().get(0).getText()); Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - when(MainApp.getConstraintChecker().applyBolusConstraints(any())).thenReturn(new Constraint<>(1d)); + when(ConstraintChecker.getInstance().applyBolusConstraints(any())).thenReturn(new Constraint<>(1d)); when(DateUtil.now()).thenReturn(1000L); //BOLUS 1 @@ -683,7 +684,7 @@ public class SmsCommunicatorPluginTest { Assert.assertEquals("BOLUS 1", smsCommunicatorPlugin.getMessages().get(0).getText()); Assert.assertEquals("Remote bolus not available. Try again later.", smsCommunicatorPlugin.getMessages().get(1).getText()); - when(MainApp.getConstraintChecker().applyBolusConstraints(any())).thenReturn(new Constraint<>(0d)); + when(ConstraintChecker.getInstance().applyBolusConstraints(any())).thenReturn(new Constraint<>(0d)); when(DateUtil.now()).thenReturn(Constants.remoteBolusMinDistance + 1002L); @@ -701,9 +702,9 @@ public class SmsCommunicatorPluginTest { Assert.assertEquals("BOLUS a", smsCommunicatorPlugin.getMessages().get(0).getText()); Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - when(MainApp.getConstraintChecker().applyExtendedBolusConstraints(any())).thenReturn(new Constraint<>(1d)); + when(ConstraintChecker.getInstance().applyExtendedBolusConstraints(any())).thenReturn(new Constraint<>(1d)); - when(MainApp.getConstraintChecker().applyBolusConstraints(any())).thenReturn(new Constraint<>(1d)); + when(ConstraintChecker.getInstance().applyBolusConstraints(any())).thenReturn(new Constraint<>(1d)); //BOLUS 1 smsCommunicatorPlugin.setMessages(new ArrayList<>()); @@ -807,7 +808,7 @@ public class SmsCommunicatorPluginTest { Assert.assertEquals("CARBS", smsCommunicatorPlugin.getMessages().get(0).getText()); Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - when(MainApp.getConstraintChecker().applyCarbsConstraints(any())).thenReturn(new Constraint<>(0)); + when(ConstraintChecker.getInstance().applyCarbsConstraints(any())).thenReturn(new Constraint<>(0)); //CARBS 0 smsCommunicatorPlugin.setMessages(new ArrayList<>()); @@ -816,7 +817,7 @@ public class SmsCommunicatorPluginTest { Assert.assertEquals("CARBS 0", smsCommunicatorPlugin.getMessages().get(0).getText()); Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - when(MainApp.getConstraintChecker().applyCarbsConstraints(any())).thenReturn(new Constraint<>(1)); + when(ConstraintChecker.getInstance().applyCarbsConstraints(any())).thenReturn(new Constraint<>(1)); //CARBS 1 smsCommunicatorPlugin.setMessages(new ArrayList<>()); diff --git a/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.java b/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.java index baaccd95b3..57be6e1f24 100644 --- a/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.java +++ b/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.java @@ -17,7 +17,7 @@ import java.util.Date; import info.AAPSMocker; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.data.ConstraintChecker; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.interfaces.Constraint; @@ -123,14 +123,14 @@ public class CommandQueueTest extends CommandQueue { when(MainApp.getConstraintChecker()).thenReturn(constraintChecker); when(MainApp.isEngineeringModeOrRelease()).thenReturn(true); Constraint bolusConstraint = new Constraint<>(0d); - when(MainApp.getConstraintChecker().applyBolusConstraints(any())).thenReturn(bolusConstraint); - when(MainApp.getConstraintChecker().applyExtendedBolusConstraints(any())).thenReturn(bolusConstraint); + when(ConstraintChecker.getInstance().applyBolusConstraints(any())).thenReturn(bolusConstraint); + when(ConstraintChecker.getInstance().applyExtendedBolusConstraints(any())).thenReturn(bolusConstraint); Constraint carbsConstraint = new Constraint<>(0); - when(MainApp.getConstraintChecker().applyCarbsConstraints(any())).thenReturn(carbsConstraint); + when(ConstraintChecker.getInstance().applyCarbsConstraints(any())).thenReturn(carbsConstraint); Constraint rateConstraint = new Constraint<>(0d); - when(MainApp.getConstraintChecker().applyBasalConstraints(any(), any())).thenReturn(rateConstraint); + when(ConstraintChecker.getInstance().applyBasalConstraints(any(), any())).thenReturn(rateConstraint); Constraint percentageConstraint = new Constraint<>(0); - when(MainApp.getConstraintChecker().applyBasalPercentConstraints(any(), any())).thenReturn(percentageConstraint); + when(ConstraintChecker.getInstance().applyBasalPercentConstraints(any(), any())).thenReturn(percentageConstraint); PowerMockito.mockStatic(ToastUtils.class); Context context = mock(Context.class); diff --git a/app/src/test/java/info/nightscout/androidaps/utils/BolusWizardTest.java b/app/src/test/java/info/nightscout/androidaps/utils/BolusWizardTest.java index 43bdbc48b7..4788b39a27 100644 --- a/app/src/test/java/info/nightscout/androidaps/utils/BolusWizardTest.java +++ b/app/src/test/java/info/nightscout/androidaps/utils/BolusWizardTest.java @@ -10,7 +10,7 @@ import org.powermock.modules.junit4.PowerMockRunner; import info.AAPSMocker; import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.data.ConstraintChecker; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus;