From ac5ea83d38d60c8ba78c435d696efe6652d0a44f Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Fri, 10 Jan 2020 23:14:58 +0100 Subject: [PATCH] more of dagger --- .../info/nightscout/androidaps/MainApp.java | 138 ++-- .../activities/MyPreferenceFragment.kt | 42 +- .../RequestDexcomPermissionActivity.kt | 2 +- .../androidaps/activities/SurveyActivity.kt | 10 +- .../activities/TDDStatsActivity.java | 13 +- .../nightscout/androidaps/data/Profile.java | 2 +- .../androidaps/data/PumpEnactResult.java | 4 + .../androidaps/db/DatabaseHelper.java | 37 +- .../dependencyInjection/AppComponent.kt | 26 +- .../dependencyInjection/AppModule.kt | 41 +- .../dependencyInjection/FragmentsModule.kt | 39 +- .../androidaps/dialogs/BolusProgressDialog.kt | 8 +- .../androidaps/dialogs/CarbsDialog.kt | 5 +- .../androidaps/dialogs/ExtendedBolusDialog.kt | 10 +- .../androidaps/dialogs/FillDialog.kt | 19 +- .../androidaps/dialogs/InsulinDialog.kt | 30 +- .../androidaps/dialogs/TempBasalDialog.kt | 24 +- .../androidaps/dialogs/TreatmentDialog.kt | 26 +- .../androidaps/dialogs/WizardDialog.kt | 6 +- .../IobCobStaticCalculatorPlugin.kt | 14 +- .../interfaces/ActivePluginProvider.java | 20 +- .../interfaces/CommandQueueProvider.java | 11 - .../interfaces/CommandQueueProvider.kt | 38 ++ .../androidaps/interfaces/PluginBase.kt | 91 +-- .../androidaps/interfaces/PumpInterface.java | 16 +- .../androidaps/interfaces/PumpPluginBase.kt | 23 + .../plugins/aps/loop/LoopPlugin.java | 89 +-- .../aps/openAPSAMA/OpenAPSAMAPlugin.java | 36 +- .../aps/openAPSMA/OpenAPSMAPlugin.java | 38 +- .../aps/openAPSSMB/OpenAPSSMBPlugin.java | 42 +- .../configBuilder/ConfigBuilderFragment.kt | 4 +- .../configBuilder/ConfigBuilderPlugin.java | 150 ++++- .../ProfileFunctionImplementation.kt | 4 +- .../constraints/dstHelper/DstHelperPlugin.kt | 43 +- .../objectives/ObjectivesPlugin.kt | 40 +- .../objectives/objectives/Objective0.java | 8 +- .../objectives/objectives/Objective3.java | 3 +- .../objectives/objectives/Objective5.java | 6 +- .../constraints/safety/SafetyPlugin.java | 180 +++--- .../SignatureVerifierPlugin.kt | 19 +- .../storage/StorageConstraintPlugin.java | 83 --- .../storage/StorageConstraintPlugin.kt | 58 ++ .../versionChecker/VersionCheckerPlugin.kt | 7 +- .../general/actions/ActionsFragment.kt | 51 +- .../plugins/general/actions/ActionsPlugin.kt | 6 +- .../general/automation/AutomationEvent.kt | 18 +- .../general/automation/AutomationPlugin.kt | 77 +-- .../general/automation/actions/Action.kt | 24 +- .../general/automation/actions/ActionDummy.kt | 4 +- .../automation/actions/ActionLoopDisable.kt | 17 +- .../automation/actions/ActionLoopEnable.kt | 13 +- .../automation/actions/ActionLoopResume.kt | 13 +- .../automation/actions/ActionLoopSuspend.kt | 16 +- .../automation/actions/ActionNotification.kt | 14 +- .../automation/actions/ActionProfileSwitch.kt | 20 +- .../actions/ActionProfileSwitchPercent.kt | 22 +- .../automation/actions/ActionSendSMS.kt | 14 +- .../actions/ActionStartTempTarget.kt | 22 +- .../actions/ActionStopTempTarget.kt | 11 +- .../general/automation/elements/Comparator.kt | 9 +- .../automation/elements/ComparatorExists.kt | 9 +- .../general/automation/elements/Element.kt | 13 +- .../general/automation/elements/InputBg.kt | 12 +- .../automation/elements/InputButton.kt | 6 +- .../automation/elements/InputDateTime.kt | 17 +- .../general/automation/elements/InputDelta.kt | 11 +- .../automation/elements/InputDouble.kt | 8 +- .../automation/elements/InputDuration.kt | 8 +- .../automation/elements/InputInsulin.kt | 6 +- .../automation/elements/InputLocationMode.kt | 9 +- .../automation/elements/InputPercent.kt | 6 +- .../automation/elements/InputProfileName.kt | 15 +- .../automation/elements/InputString.kt | 6 +- .../automation/elements/InputTempTarget.kt | 6 +- .../general/automation/elements/InputTime.kt | 12 +- .../automation/elements/InputTimeRange.kt | 14 +- .../automation/elements/InputWeekDay.kt | 4 +- .../automation/elements/LabelWithElement.kt | 10 +- .../automation/elements/StaticLabel.kt | 12 +- .../general/automation/triggers/Trigger.kt | 12 +- .../triggers/TriggerAutosensValue.kt | 20 +- .../general/automation/triggers/TriggerBg.kt | 26 +- .../automation/triggers/TriggerBolusAgo.kt | 20 +- .../general/automation/triggers/TriggerCOB.kt | 20 +- .../automation/triggers/TriggerConnector.kt | 10 +- .../automation/triggers/TriggerDelta.kt | 28 +- .../automation/triggers/TriggerDummy.kt | 4 +- .../general/automation/triggers/TriggerIob.kt | 20 +- .../automation/triggers/TriggerLocation.kt | 40 +- .../triggers/TriggerProfilePercent.kt | 26 +- .../triggers/TriggerPumpLastConnection.kt | 28 +- .../triggers/TriggerRecurringTime.kt | 14 +- .../automation/triggers/TriggerTempTarget.kt | 18 +- .../automation/triggers/TriggerTime.kt | 14 +- .../automation/triggers/TriggerTimeRange.kt | 14 +- .../automation/triggers/TriggerWifiSsid.kt | 26 +- .../general/careportal/CareportalPlugin.kt | 13 +- .../plugins/general/food/FoodPlugin.kt | 6 +- .../general/maintenance/MaintenancePlugin.kt | 7 +- .../general/nsclient/NSClientFragment.java | 33 +- .../general/nsclient/NSClientPlugin.java | 69 +- .../plugins/general/nsclient/UploadQueue.java | 7 +- .../nsclient/events/EventNSClientResend.kt | 5 + .../nsclient/services/NSClientService.java | 13 +- .../general/overview/OverviewFragment.java | 18 +- .../general/overview/OverviewPlugin.kt | 7 +- .../general/overview/StatusLightHandler.kt | 8 +- .../notifications/NotificationWithAction.kt | 13 +- .../PersistentNotificationPlugin.kt | 57 +- .../smsCommunicator/SmsCommunicatorPlugin.kt | 140 +++-- .../general/tidepool/TidepoolPlugin.kt | 14 +- .../general/tidepool/comm/TidepoolUploader.kt | 2 +- .../general/tidepool/comm/UploadChunk.kt | 4 +- .../general/wear/ActionStringHandler.kt | 69 +- .../plugins/general/wear/WearPlugin.kt | 10 +- .../wearintegration/WatchUpdaterService.java | 6 +- .../xdripStatusline/StatusLinePlugin.kt | 29 +- .../plugins/insulin/InsulinOrefBasePlugin.kt | 6 +- .../InsulinOrefUltraRapidActingPlugin.kt | 14 +- .../iob/iobCobCalculator/AutosensData.java | 56 +- .../IobCobCalculatorPlugin.java | 85 ++- .../iobCobCalculator/IobCobOref1Thread.java | 146 +++-- .../iob/iobCobCalculator/IobCobThread.java | 141 ++--- .../profile/local/LocalProfileFragment.kt | 5 +- .../profile/local/LocalProfilePlugin.kt | 9 +- .../plugins/profile/ns/NSProfileFragment.kt | 7 +- .../plugins/profile/ns/NSProfilePlugin.java | 128 ---- .../plugins/profile/ns/NSProfilePlugin.kt | 88 +++ .../plugins/pump/combo/ComboFragment.java | 41 +- .../plugins/pump/combo/ComboPlugin.java | 123 ++-- .../pump/common/PumpPluginAbstract.java | 53 +- .../pump/danaR/AbstractDanaRPlugin.java | 59 +- .../plugins/pump/danaR/DanaRFragment.kt | 22 +- .../plugins/pump/danaR/DanaRPlugin.java | 14 +- .../danaR/activities/DanaRHistoryActivity.kt | 6 +- .../activities/DanaRUserOptionsActivity.kt | 6 +- .../danaR/services/DanaRExecutionService.java | 6 +- .../pump/danaRKorean/DanaRKoreanPlugin.java | 15 +- .../services/DanaRKoreanExecutionService.java | 4 +- .../plugins/pump/danaRS/DanaRSPlugin.java | 92 ++- .../pump/danaRS/services/DanaRSService.java | 6 +- .../plugins/pump/danaRv2/DanaRv2Plugin.java | 19 +- .../services/DanaRv2ExecutionService.java | 6 +- .../pump/insight/LocalInsightFragment.java | 54 +- .../pump/insight/LocalInsightPlugin.java | 223 ++++--- .../plugins/pump/mdi/MDIPlugin.java | 70 ++- .../pump/medtronic/MedtronicFragment.kt | 20 +- .../pump/medtronic/MedtronicPumpPlugin.java | 108 +++- .../plugins/pump/virtual/VirtualPumpPlugin.kt | 21 +- .../AbstractSensitivityPlugin.java | 6 +- .../sensitivity/SensitivityAAPSPlugin.java | 37 +- .../sensitivity/SensitivityOref0Plugin.java | 39 +- .../sensitivity/SensitivityOref1Plugin.java | 37 +- .../SensitivityWeightedAveragePlugin.java | 38 +- .../androidaps/plugins/source/DexcomPlugin.kt | 23 +- .../plugins/source/EversensePlugin.kt | 9 +- .../androidaps/plugins/source/GlimpPlugin.kt | 9 +- .../androidaps/plugins/source/MM640gPlugin.kt | 22 +- .../plugins/source/NSClientSourcePlugin.kt | 23 +- .../plugins/source/PoctechPlugin.kt | 9 +- .../plugins/source/RandomBgPlugin.kt | 10 +- .../androidaps/plugins/source/TomatoPlugin.kt | 9 +- .../androidaps/plugins/source/XdripPlugin.kt | 13 +- .../plugins/treatments/TreatmentsFragment.kt | 2 +- .../plugins/treatments/TreatmentsPlugin.java | 44 +- .../androidaps/queue/CommandQueue.java | 594 ------------------ .../androidaps/queue/CommandQueue.kt | 495 +++++++++++++++ .../androidaps/queue/commands/Command.java | 50 -- .../androidaps/queue/commands/Command.kt | 51 ++ .../queue/commands/CommandBolus.java | 48 -- .../androidaps/queue/commands/CommandBolus.kt | 36 ++ .../commands/CommandCancelExtendedBolus.java | 36 -- .../commands/CommandCancelExtendedBolus.kt | 23 + .../commands/CommandCancelTempBasal.java | 39 -- .../queue/commands/CommandCancelTempBasal.kt | 24 + .../queue/commands/CommandExtendedBolus.java | 41 -- .../queue/commands/CommandExtendedBolus.kt | 25 + .../CommandInsightSetTBROverNotification.java | 32 - .../CommandInsightSetTBROverNotification.kt | 27 + .../queue/commands/CommandLoadEvents.java | 42 -- .../queue/commands/CommandLoadEvents.kt | 28 + .../queue/commands/CommandLoadHistory.java | 45 -- .../queue/commands/CommandLoadHistory.kt | 29 + .../queue/commands/CommandLoadTDDs.java | 39 -- .../queue/commands/CommandLoadTDDs.kt | 24 + .../queue/commands/CommandReadStatus.java | 50 -- .../queue/commands/CommandReadStatus.kt | 33 + .../queue/commands/CommandSMBBolus.java | 57 -- .../queue/commands/CommandSMBBolus.kt | 39 ++ .../queue/commands/CommandSetProfile.java | 69 -- .../queue/commands/CommandSetProfile.kt | 45 ++ .../commands/CommandSetUserSettings.java | 42 -- .../queue/commands/CommandSetUserSettings.kt | 27 + .../queue/commands/CommandStartPump.java | 29 - .../queue/commands/CommandStartPump.kt | 25 + .../queue/commands/CommandStopPump.java | 29 - .../queue/commands/CommandStopPump.kt | 25 + .../commands/CommandTempBasalAbsolute.java | 46 -- .../commands/CommandTempBasalAbsolute.kt | 28 + .../commands/CommandTempBasalPercent.java | 46 -- .../queue/commands/CommandTempBasalPercent.kt | 28 + .../androidaps/receivers/KeepAliveReceiver.kt | 40 +- .../androidaps/services/DataService.java | 3 +- .../androidaps/setupwizard/SWDefinition.kt | 66 +- .../androidaps/utils/FabricPrivacy.kt | 6 +- .../androidaps/utils/LocalAlertUtils.java | 107 ---- .../androidaps/utils/LocalAlertUtils.kt | 106 ++++ .../androidaps/utils/sharedPreferences/SP.kt | 1 + .../sharedPreferences/SPImplementation.kt | 3 + .../androidaps/utils/stats/TddCalculator.kt | 2 +- .../androidaps/utils/wizard/BolusWizard.kt | 50 +- app/src/main/res/values/exam.xml | 2 +- app/src/main/res/values/strings.xml | 2 +- 213 files changed, 3829 insertions(+), 3798 deletions(-) delete mode 100644 app/src/main/java/info/nightscout/androidaps/interfaces/CommandQueueProvider.java create mode 100644 app/src/main/java/info/nightscout/androidaps/interfaces/CommandQueueProvider.kt create mode 100644 app/src/main/java/info/nightscout/androidaps/interfaces/PumpPluginBase.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPlugin.java create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPlugin.kt create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientResend.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.java create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java create mode 100644 app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/Command.java create mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/Command.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/CommandBolus.java create mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/CommandBolus.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/CommandCancelExtendedBolus.java create mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/CommandCancelExtendedBolus.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/CommandCancelTempBasal.java create mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/CommandCancelTempBasal.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/CommandExtendedBolus.java create mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/CommandExtendedBolus.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/CommandInsightSetTBROverNotification.java create mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/CommandInsightSetTBROverNotification.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadEvents.java create mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadEvents.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadHistory.java create mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadHistory.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadTDDs.java create mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadTDDs.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/CommandReadStatus.java create mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/CommandReadStatus.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.java create mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetProfile.java create mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetProfile.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetUserSettings.java create mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetUserSettings.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/CommandStartPump.java create mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/CommandStartPump.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/CommandStopPump.java create mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/CommandStopPump.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalAbsolute.java create mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalAbsolute.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalPercent.java create mode 100644 app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalPercent.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/utils/LocalAlertUtils.java create mode 100644 app/src/main/java/info/nightscout/androidaps/utils/LocalAlertUtils.kt diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java index ceb90250e3..aaf6767a62 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java @@ -7,7 +7,6 @@ import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Resources; -import android.os.SystemClock; import androidx.annotation.ColorRes; import androidx.annotation.PluralsRes; @@ -39,7 +38,6 @@ import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.dependencyInjection.DaggerAppComponent; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginType; -import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.LTag; @@ -89,13 +87,13 @@ import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin; import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref0Plugin; import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin; import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin; -import info.nightscout.androidaps.plugins.source.NSClientSourcePlugin; -import info.nightscout.androidaps.plugins.source.RandomBgPlugin; import info.nightscout.androidaps.plugins.source.DexcomPlugin; import info.nightscout.androidaps.plugins.source.EversensePlugin; import info.nightscout.androidaps.plugins.source.GlimpPlugin; import info.nightscout.androidaps.plugins.source.MM640gPlugin; +import info.nightscout.androidaps.plugins.source.NSClientSourcePlugin; import info.nightscout.androidaps.plugins.source.PoctechPlugin; +import info.nightscout.androidaps.plugins.source.RandomBgPlugin; import info.nightscout.androidaps.plugins.source.TomatoPlugin; import info.nightscout.androidaps.plugins.source.XdripPlugin; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; @@ -120,7 +118,7 @@ public class MainApp extends DaggerApplication { static DatabaseHelper sDatabaseHelper = null; - static ArrayList pluginsList = null; + static ArrayList pluginsList = new ArrayList<>(); static DataReceiver dataReceiver = new DataReceiver(); TimeDateOrTZChangeReceiver timeDateOrTZChangeReceiver; @@ -140,6 +138,7 @@ public class MainApp extends DaggerApplication { @Inject ActionsPlugin actionsPlugin; @Inject AutomationPlugin automationPlugin; + @Inject ComboPlugin comboPlugin; @Inject CareportalPlugin careportalPlugin; @Inject ConfigBuilderPlugin configBuilderPlugin; @Inject DanaRPlugin danaRPlugin; @@ -152,8 +151,12 @@ public class MainApp extends DaggerApplication { @Inject InsulinOrefRapidActingPlugin insulinOrefRapidActingPlugin; @Inject InsulinOrefUltraRapidActingPlugin insulinOrefUltraRapidActingPlugin; @Inject IobCobCalculatorPlugin iobCobCalculatorPlugin; + @Inject LocalInsightPlugin localInsightPlugin; @Inject LocalProfilePlugin localProfilePlugin; @Inject LoopPlugin loopPlugin; + @Inject MedtronicPumpPlugin medtronicPumpPlugin; + @Inject MDIPlugin mdiPlugin; + @Inject NSProfilePlugin nsProfilePlugin; @Inject ObjectivesPlugin objectivesPlugin; @Inject SafetyPlugin safetyPlugin; @Inject SmsCommunicatorPlugin smsCommunicatorPlugin; @@ -163,12 +166,18 @@ public class MainApp extends DaggerApplication { @Inject OverviewPlugin overviewPlugin; @Inject PersistentNotificationPlugin persistentNotificationPlugin; @Inject RandomBgPlugin randomBgPlugin; + @Inject SensitivityOref1Plugin sensitivityOref1Plugin; + @Inject SensitivityAAPSPlugin sensitivityAAPSPlugin; + @Inject SensitivityOref0Plugin sensitivityOref0Plugin; + @Inject SensitivityWeightedAveragePlugin sensitivityWeightedAveragePlugin; @Inject SignatureVerifierPlugin signatureVerifierPlugin; + @Inject StorageConstraintPlugin storageConstraintPlugin; @Inject DexcomPlugin dexcomPlugin; @Inject EversensePlugin eversensePlugin; @Inject GlimpPlugin glimpPlugin; @Inject MaintenancePlugin maintenancePlugin; @Inject MM640gPlugin mM640GPlugin; + @Inject NSClientPlugin nsClientPlugin; @Inject NSClientSourcePlugin nSClientSourcePlugin; @Inject PoctechPlugin poctechPlugin; @Inject TomatoPlugin tomatoPlugin; @@ -232,77 +241,66 @@ public class MainApp extends DaggerApplication { //trigger here to see the new version on app start after an update versionCheckersUtils.triggerCheckVersion(); - if (pluginsList == null) { - pluginsList = new ArrayList<>(); - // Register all tabs in app here - pluginsList.add(overviewPlugin); - pluginsList.add(iobCobCalculatorPlugin); - if (!Config.NSCLIENT) pluginsList.add(actionsPlugin); - pluginsList.add(insulinOrefRapidActingPlugin); - pluginsList.add(insulinOrefUltraRapidActingPlugin); - pluginsList.add(insulinOrefFreePeakPlugin); - pluginsList.add(SensitivityOref0Plugin.getPlugin()); - pluginsList.add(SensitivityAAPSPlugin.getPlugin()); - pluginsList.add(SensitivityWeightedAveragePlugin.getPlugin()); - pluginsList.add(SensitivityOref1Plugin.getPlugin()); - if (Config.PUMPDRIVERS) pluginsList.add(danaRPlugin); - if (Config.PUMPDRIVERS) pluginsList.add(danaRKoreanPlugin); - if (Config.PUMPDRIVERS) pluginsList.add(danaRv2Plugin); - if (Config.PUMPDRIVERS) pluginsList.add(danaRSPlugin); - if (Config.PUMPDRIVERS) pluginsList.add(LocalInsightPlugin.getPlugin()); - if (Config.PUMPDRIVERS) pluginsList.add(ComboPlugin.getPlugin()); - if (Config.PUMPDRIVERS) pluginsList.add(MedtronicPumpPlugin.getPlugin()); - if (!Config.NSCLIENT) pluginsList.add(MDIPlugin.getPlugin()); - pluginsList.add(virtualPumpPlugin); - pluginsList.add(careportalPlugin); - if (Config.APS) pluginsList.add(loopPlugin); - if (Config.APS) pluginsList.add(openAPSMAPlugin); - if (Config.APS) pluginsList.add(openAPSAMAPlugin); - if (Config.APS) pluginsList.add(openAPSSMBPlugin); - pluginsList.add(NSProfilePlugin.getPlugin()); - if (!Config.NSCLIENT) pluginsList.add(localProfilePlugin); - pluginsList.add(treatmentsPlugin); - if (!Config.NSCLIENT) pluginsList.add(safetyPlugin); - if (!Config.NSCLIENT) pluginsList.add(versionCheckerPlugin); - if (Config.APS) pluginsList.add(StorageConstraintPlugin.getPlugin()); - if (Config.APS) pluginsList.add(signatureVerifierPlugin); - if (Config.APS) pluginsList.add(objectivesPlugin); - pluginsList.add(xdripPlugin); - pluginsList.add(nSClientSourcePlugin); - pluginsList.add(mM640GPlugin); - pluginsList.add(glimpPlugin); - pluginsList.add(dexcomPlugin); - pluginsList.add(poctechPlugin); - pluginsList.add(tomatoPlugin); - pluginsList.add(eversensePlugin); - pluginsList.add(randomBgPlugin); - if (!Config.NSCLIENT) pluginsList.add(smsCommunicatorPlugin); - pluginsList.add(foodPlugin); + // Register all tabs in app here + pluginsList.add(overviewPlugin); + pluginsList.add(iobCobCalculatorPlugin); + if (!Config.NSCLIENT) pluginsList.add(actionsPlugin); + pluginsList.add(insulinOrefRapidActingPlugin); + pluginsList.add(insulinOrefUltraRapidActingPlugin); + pluginsList.add(insulinOrefFreePeakPlugin); + pluginsList.add(sensitivityOref0Plugin); + pluginsList.add(sensitivityAAPSPlugin); + pluginsList.add(sensitivityWeightedAveragePlugin); + pluginsList.add(sensitivityOref1Plugin); + if (Config.PUMPDRIVERS) pluginsList.add(danaRPlugin); + if (Config.PUMPDRIVERS) pluginsList.add(danaRKoreanPlugin); + if (Config.PUMPDRIVERS) pluginsList.add(danaRv2Plugin); + if (Config.PUMPDRIVERS) pluginsList.add(danaRSPlugin); + if (Config.PUMPDRIVERS) pluginsList.add(localInsightPlugin); + if (Config.PUMPDRIVERS) pluginsList.add(comboPlugin); + if (Config.PUMPDRIVERS) pluginsList.add(medtronicPumpPlugin); + if (!Config.NSCLIENT) pluginsList.add(mdiPlugin); + if (!Config.NSCLIENT) pluginsList.add(virtualPumpPlugin); + pluginsList.add(careportalPlugin); + if (Config.APS) pluginsList.add(loopPlugin); + if (Config.APS) pluginsList.add(openAPSMAPlugin); + if (Config.APS) pluginsList.add(openAPSAMAPlugin); + if (Config.APS) pluginsList.add(openAPSSMBPlugin); + pluginsList.add(nsProfilePlugin); + if (!Config.NSCLIENT) pluginsList.add(localProfilePlugin); + pluginsList.add(treatmentsPlugin); + if (!Config.NSCLIENT) pluginsList.add(safetyPlugin); + if (!Config.NSCLIENT) pluginsList.add(versionCheckerPlugin); + if (Config.APS) pluginsList.add(storageConstraintPlugin); + if (Config.APS) pluginsList.add(signatureVerifierPlugin); + if (Config.APS) pluginsList.add(objectivesPlugin); + pluginsList.add(xdripPlugin); + pluginsList.add(nSClientSourcePlugin); + pluginsList.add(mM640GPlugin); + pluginsList.add(glimpPlugin); + pluginsList.add(dexcomPlugin); + pluginsList.add(poctechPlugin); + pluginsList.add(tomatoPlugin); + pluginsList.add(eversensePlugin); + pluginsList.add(randomBgPlugin); + if (!Config.NSCLIENT) pluginsList.add(smsCommunicatorPlugin); + pluginsList.add(foodPlugin); - pluginsList.add(wearPlugin); - pluginsList.add(statusLinePlugin); - pluginsList.add(persistentNotificationPlugin); - pluginsList.add(NSClientPlugin.getPlugin()); + pluginsList.add(wearPlugin); + pluginsList.add(statusLinePlugin); + pluginsList.add(persistentNotificationPlugin); + pluginsList.add(nsClientPlugin); // if (engineeringMode) pluginsList.add(tidepoolPlugin); - pluginsList.add(maintenancePlugin); - pluginsList.add(automationPlugin); - pluginsList.add(dstHelperPlugin); + pluginsList.add(maintenancePlugin); + pluginsList.add(automationPlugin); + pluginsList.add(dstHelperPlugin); - pluginsList.add(configBuilderPlugin); + pluginsList.add(configBuilderPlugin); - configBuilderPlugin.initialize(); - } + configBuilderPlugin.initialize(); NSUpload.uploadAppStart(); - final PumpInterface pump = configBuilderPlugin.getActivePump(); - if (pump != null) { - new Thread(() -> { - SystemClock.sleep(5000); - configBuilderPlugin.getCommandQueue().readStatus("Initialization", null); - }).start(); - } - new Thread(() -> keepAliveManager.setAlarm(this)).start(); doMigrations(); } @@ -498,7 +496,7 @@ public class MainApp extends DaggerApplication { } public Notification getNotification() { - return notification; + return notification; } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt b/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt index 77cf60f4e7..70d8520182 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt @@ -41,7 +41,6 @@ import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin -import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref0Plugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin import info.nightscout.androidaps.plugins.source.DexcomPlugin @@ -53,7 +52,6 @@ import info.nightscout.androidaps.utils.OKDialog.show import info.nightscout.androidaps.utils.SafeParse import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP -import java.util.* import javax.inject.Inject class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChangeListener, HasAndroidInjector { @@ -69,12 +67,20 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang @Inject lateinit var danaRv2Plugin: DanaRv2Plugin @Inject lateinit var danaRSPlugin: DanaRSPlugin @Inject lateinit var careportalPlugin: CareportalPlugin + @Inject lateinit var comboPlugin: ComboPlugin @Inject lateinit var insulinOrefFreePeakPlugin: InsulinOrefFreePeakPlugin @Inject lateinit var loopPlugin: LoopPlugin + @Inject lateinit var localInsightPlugin: LocalInsightPlugin + @Inject lateinit var medtronicPumpPlugin: MedtronicPumpPlugin + @Inject lateinit var nsClientPlugin: NSClientPlugin @Inject lateinit var openAPSAMAPlugin: OpenAPSAMAPlugin @Inject lateinit var openAPSMAPlugin: OpenAPSMAPlugin @Inject lateinit var openAPSSMBPlugin: OpenAPSSMBPlugin @Inject lateinit var safetyPlugin: SafetyPlugin + @Inject lateinit var sensitivityAAPSPlugin: SensitivityAAPSPlugin + @Inject lateinit var sensitivityOref0Plugin: SensitivityOref1Plugin + @Inject lateinit var sensitivityOref1Plugin: SensitivityOref1Plugin + @Inject lateinit var sensitivityWeightedAveragePlugin: SensitivityWeightedAveragePlugin @Inject lateinit var dexcomPlugin: DexcomPlugin @Inject lateinit var eversensePlugin: EversensePlugin @Inject lateinit var glimpPlugin: GlimpPlugin @@ -144,20 +150,20 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang addPreferencesFromResourceIfEnabled(openAPSMAPlugin, rootKey, Config.APS) addPreferencesFromResourceIfEnabled(openAPSAMAPlugin, rootKey, Config.APS) addPreferencesFromResourceIfEnabled(openAPSSMBPlugin, rootKey, Config.APS) - addPreferencesFromResourceIfEnabled(SensitivityAAPSPlugin.getPlugin(), rootKey) - addPreferencesFromResourceIfEnabled(SensitivityWeightedAveragePlugin.getPlugin(), rootKey) - addPreferencesFromResourceIfEnabled(SensitivityOref0Plugin.getPlugin(), rootKey) - addPreferencesFromResourceIfEnabled(SensitivityOref1Plugin.getPlugin(), rootKey) + addPreferencesFromResourceIfEnabled(sensitivityAAPSPlugin, rootKey) + addPreferencesFromResourceIfEnabled(sensitivityWeightedAveragePlugin, rootKey) + addPreferencesFromResourceIfEnabled(sensitivityOref0Plugin, rootKey) + addPreferencesFromResourceIfEnabled(sensitivityOref1Plugin, rootKey) addPreferencesFromResourceIfEnabled(danaRPlugin, rootKey, Config.PUMPDRIVERS) addPreferencesFromResourceIfEnabled(danaRKoreanPlugin, rootKey, Config.PUMPDRIVERS) addPreferencesFromResourceIfEnabled(danaRv2Plugin, rootKey, Config.PUMPDRIVERS) addPreferencesFromResourceIfEnabled(danaRSPlugin, rootKey, Config.PUMPDRIVERS) - addPreferencesFromResourceIfEnabled(LocalInsightPlugin.getPlugin(), rootKey, Config.PUMPDRIVERS) - addPreferencesFromResourceIfEnabled(ComboPlugin.getPlugin(), rootKey, Config.PUMPDRIVERS) - addPreferencesFromResourceIfEnabled(MedtronicPumpPlugin.getPlugin(), rootKey, Config.PUMPDRIVERS) + addPreferencesFromResourceIfEnabled(localInsightPlugin, rootKey, Config.PUMPDRIVERS) + addPreferencesFromResourceIfEnabled(comboPlugin, rootKey, Config.PUMPDRIVERS) + addPreferencesFromResourceIfEnabled(medtronicPumpPlugin, rootKey, Config.PUMPDRIVERS) addPreferencesFromResourceIfEnabled(virtualPumpPlugin, rootKey, !Config.NSCLIENT) addPreferencesFromResourceIfEnabled(insulinOrefFreePeakPlugin, rootKey) - addPreferencesFromResourceIfEnabled(NSClientPlugin.getPlugin(), rootKey) + addPreferencesFromResourceIfEnabled(nsClientPlugin, rootKey) addPreferencesFromResourceIfEnabled(tidepoolPlugin, rootKey) addPreferencesFromResourceIfEnabled(smsCommunicatorPlugin, rootKey) addPreferencesFromResourceIfEnabled(automationPlugin, rootKey) @@ -195,7 +201,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang updatePrefSummary(findPreference(key)) } - fun addPreferencesFromResource(@XmlRes preferencesResId: Int, key: String?) { + private fun addPreferencesFromResource(@XmlRes preferencesResId: Int, key: String?) { val xmlRoot = preferenceManager.inflateFromResource(context, preferencesResId, null) val root: Preference? @@ -220,7 +226,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang resourceHelper.gs(R.string.key_high_mark), resourceHelper.gs(R.string.key_low_mark) ) - if (Arrays.asList(*unitDependent).contains(pref.key)) { + if (listOf(*unitDependent).contains(pref.key)) { val editTextPref = pref as EditTextPreference val converted = Profile.toCurrentUnitsString(SafeParse.stringToDouble(editTextPref.text)) editTextPref.summary = converted @@ -233,12 +239,11 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang pref.setSummary(pref.entry) } if (pref is EditTextPreference) { - val editTextPref = pref if (pref.getKey().contains("password") || pref.getKey().contains("secret")) { pref.setSummary("******") - } else if (editTextPref.text != null) { - pref.dialogMessage = editTextPref.dialogMessage - pref.setSummary(editTextPref.text) + } else if (pref.text != null) { + pref.dialogMessage = pref.dialogMessage + pref.setSummary(pref.text) } else { for (plugin in MainApp.getPluginsList()) { plugin.updatePreferenceSummary(pref) @@ -251,9 +256,8 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang private fun initSummary(p: Preference) { p.isIconSpaceReserved = false // remove extra spacing on left after migration to androidx if (p is PreferenceGroup) { - val pGrp = p - for (i in 0 until pGrp.preferenceCount) { - initSummary(pGrp.getPreference(i)) + for (i in 0 until p.preferenceCount) { + initSummary(p.getPreference(i)) } } else { updatePrefSummary(p) diff --git a/app/src/main/java/info/nightscout/androidaps/activities/RequestDexcomPermissionActivity.kt b/app/src/main/java/info/nightscout/androidaps/activities/RequestDexcomPermissionActivity.kt index 3fa2e761f0..e4a5bddf63 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/RequestDexcomPermissionActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/RequestDexcomPermissionActivity.kt @@ -11,7 +11,7 @@ class RequestDexcomPermissionActivity : NoSplashAppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) - requestPermissions(arrayOf(dexcomPlugin.PERMISSION), requestCode) + requestPermissions(arrayOf(DexcomPlugin.PERMISSION), requestCode) } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) { diff --git a/app/src/main/java/info/nightscout/androidaps/activities/SurveyActivity.kt b/app/src/main/java/info/nightscout/androidaps/activities/SurveyActivity.kt index 8f1738f73b..7ccbe7dcf7 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/SurveyActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/SurveyActivity.kt @@ -11,7 +11,11 @@ import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction -import info.nightscout.androidaps.utils.* +import info.nightscout.androidaps.utils.ActivityMonitor +import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.androidaps.utils.InstanceId +import info.nightscout.androidaps.utils.SafeParse +import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.stats.TddCalculator import info.nightscout.androidaps.utils.stats.TirCalculator @@ -21,7 +25,7 @@ import javax.inject.Inject class SurveyActivity : NoSplashAppCompatActivity() { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var resourceHelper: ResourceHelper - @Inject lateinit var activePluginProvider: ActivePluginProvider + @Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var tddCalculator: TddCalculator @Inject lateinit var tirCalculator: TirCalculator @Inject lateinit var profileFunction: ProfileFunction @@ -33,7 +37,7 @@ class SurveyActivity : NoSplashAppCompatActivity() { survey_id.text = InstanceId.instanceId() - val profileStore = activePluginProvider.activeProfileInterface.profile + val profileStore = activePlugin.activeProfileInterface.profile val profileList = profileStore?.getProfileList() ?: return survey_spinner.adapter = ArrayAdapter(this, R.layout.spinner_centered, profileList) diff --git a/app/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.java b/app/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.java index 9bfc387578..9ea091cda5 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.java @@ -38,6 +38,7 @@ import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.TDD; import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.interfaces.ActivePluginProvider; +import info.nightscout.androidaps.interfaces.CommandQueueProvider; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; @@ -60,12 +61,14 @@ public class TDDStatsActivity extends NoSplashAppCompatActivity { @Inject RxBusWrapper rxBus; @Inject SP sp; @Inject ProfileFunction profileFunction; - @Inject ActivePluginProvider activePluginProvider; + @Inject ActivePluginProvider activePlugin; @Inject DanaRSPlugin danaRSPlugin; @Inject DanaRPlugin danaRPlugin; @Inject DanaRv2Plugin danaRv2Plugin; @Inject DanaRKoreanPlugin danaRKoreanPlugin; + @Inject LocalInsightPlugin localInsightPlugin; @Inject ConfigBuilderPlugin configBuilderPlugin; + @Inject CommandQueueProvider commandQueue; private static Logger log = LoggerFactory.getLogger(TDDStatsActivity.class); private CompositeDisposable disposable = new CompositeDisposable(); @@ -157,7 +160,7 @@ public class TDDStatsActivity extends NoSplashAppCompatActivity { } totalBaseBasal.setText(TBB); - if (!activePluginProvider.getActivePump().getPumpDescription().needsManualTDDLoad) + if (!activePlugin.getActivePump().getPumpDescription().needsManualTDDLoad) reloadButton.setVisibility(View.GONE); // stats table @@ -261,7 +264,7 @@ public class TDDStatsActivity extends NoSplashAppCompatActivity { statsMessage.setVisibility(View.VISIBLE); statsMessage.setText(resourceHelper.gs(R.string.danar_stats_warning_Message)); }); - configBuilderPlugin.getCommandQueue().loadTDDs(new Callback() { + commandQueue.loadTDDs(new Callback() { @Override public void run() { loadDataFromDB(); @@ -445,7 +448,7 @@ public class TDDStatsActivity extends NoSplashAppCompatActivity { TableLayout.LayoutParams.WRAP_CONTENT)); } - if (isOldData(historyList) && activePluginProvider.getActivePump().getPumpDescription().needsManualTDDLoad) { + if (isOldData(historyList) && activePlugin.getActivePump().getPumpDescription().needsManualTDDLoad) { statsMessage.setVisibility(View.VISIBLE); statsMessage.setText(resourceHelper.gs(R.string.danar_stats_olddata_Message)); @@ -525,7 +528,7 @@ public class TDDStatsActivity extends NoSplashAppCompatActivity { public boolean isOldData(List historyList) { - boolean startsYesterday = danaRPlugin.isEnabled() || danaRSPlugin.isEnabled() || danaRv2Plugin.isEnabled() || danaRKoreanPlugin.isEnabled() || LocalInsightPlugin.getPlugin().isEnabled(); + boolean startsYesterday = danaRPlugin.isEnabled() || danaRSPlugin.isEnabled() || danaRv2Plugin.isEnabled() || danaRKoreanPlugin.isEnabled() || localInsightPlugin.isEnabled(); DateFormat df = new SimpleDateFormat("dd.MM.", Locale.getDefault()); return (historyList.size() < 3 || !(df.format(new Date(historyList.get(0).date)).equals(df.format(new Date(System.currentTimeMillis() - (startsYesterday ? 1000 * 60 * 60 * 24 : 0)))))); diff --git a/app/src/main/java/info/nightscout/androidaps/data/Profile.java b/app/src/main/java/info/nightscout/androidaps/data/Profile.java index fdc840f2ee..8df6d81acd 100644 --- a/app/src/main/java/info/nightscout/androidaps/data/Profile.java +++ b/app/src/main/java/info/nightscout/androidaps/data/Profile.java @@ -228,7 +228,7 @@ public class Profile { if (isValid) { // Check for hours alignment - PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump(); + PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePumpPlugin(); if (pump != null && !pump.getPumpDescription().is30minBasalRatesCapable) { for (int index = 0; index < basal_v.size(); index++) { long secondsFromMidnight = basal_v.keyAt(index); diff --git a/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java b/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java index 461d8faa7b..b7811b6eaa 100644 --- a/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java +++ b/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java @@ -191,4 +191,8 @@ public class PumpEnactResult { } return result; } + + public static PumpEnactResult error(String message) { + return new PumpEnactResult().enacted(false).success(false).comment(message); + } } diff --git a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java index e035dcd1a6..3f491432e9 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java @@ -32,7 +32,6 @@ import java.util.concurrent.TimeUnit; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.data.OverlappingIntervals; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.ProfileStore; @@ -48,9 +47,9 @@ import info.nightscout.androidaps.events.EventTempBasalChange; import info.nightscout.androidaps.events.EventTempTargetChange; import info.nightscout.androidaps.interfaces.ProfileInterface; 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.general.nsclient.NSUpload; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData; import info.nightscout.androidaps.plugins.pump.danaR.activities.DanaRNSHistorySync; import info.nightscout.androidaps.plugins.pump.danaR.comm.RecordTypes; @@ -418,40 +417,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } - /* - * Return last BgReading from database or null if db is empty - */ - @Nullable - public static BgReading lastBg() { - List bgList = IobCobCalculatorPlugin.getPlugin().getBgReadings(); - - if (bgList == null) - return null; - - for (int i = 0; i < bgList.size(); i++) - if (bgList.get(i).value >= 39) - return bgList.get(i); - return null; - } - - /* - * Return bg reading if not old ( <9 min ) - * or null if older - */ - @Nullable - public static BgReading actualBg() { - BgReading lastBg = lastBg(); - - if (lastBg == null) - return null; - - if (lastBg.date > System.currentTimeMillis() - 9 * 60 * 1000) - return lastBg; - - return null; - } - - public List getBgreadingsDataFromTime(long mills, boolean ascending) { try { Dao daoBgreadings = getDaoBgReadings(); diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt index fe1cb67178..97914a1af9 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt @@ -13,8 +13,12 @@ import info.nightscout.androidaps.plugins.general.automation.actions.* import info.nightscout.androidaps.plugins.general.automation.elements.* import info.nightscout.androidaps.plugins.general.automation.triggers.* import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationWithAction +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobOref1Thread +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobThread import info.nightscout.androidaps.plugins.treatments.Treatment -import info.nightscout.androidaps.queue.commands.CommandSetProfile +import info.nightscout.androidaps.queue.CommandQueue +import info.nightscout.androidaps.queue.commands.* import info.nightscout.androidaps.utils.wizard.BolusWizard import info.nightscout.androidaps.utils.wizard.QuickWizardEntry import javax.inject.Singleton @@ -32,7 +36,21 @@ import javax.inject.Singleton ) interface AppComponent : AndroidInjector { + fun injectCommandQueue(commandQueue: CommandQueue) + fun injectCommandBolus(commandBolus: CommandBolus) + fun injectCommandCancelExtendedBolus(commandCancelExtendedBolus: CommandCancelExtendedBolus) + fun injectCommandCancelTempBasal(commandCancelTempBasal: CommandCancelTempBasal) + fun injectCommandExtendedBolus(commandExtendedBolus: CommandExtendedBolus) + fun injectCommandInsightSetTBROverNotification(commandInsightSetTBROverNotification: CommandInsightSetTBROverNotification) + fun injectCommandLoadEvents(commandLoadEvents: CommandLoadEvents) + fun injectCommandLoadHistory(commandLoadHistory: CommandLoadHistory) + fun injectCommandReadStatus(commandReadStatus: CommandReadStatus) fun injectCommandSetProfile(commandSetProfile: CommandSetProfile) + fun injectCommandCommandSMBBolus(commandSMBBolus: CommandSMBBolus) + fun injectCommandStartPump(commandStartPump: CommandStartPump) + fun injectCommandStopPump(commandStopPump: CommandStopPump) + fun injectCommandTempBasalAbsolute(commandTempBasalAbsolute: CommandTempBasalAbsolute) + fun injectCommandTempBasalPercent(commandTempBasalPercent: CommandTempBasalPercent) fun injectObjective0(objective0: Objective0) fun injectObjective1(objective1: Objective1) @@ -58,7 +76,7 @@ interface AppComponent : AndroidInjector { fun injectTrigger(triggerRecurringTime: TriggerRecurringTime) fun injectTrigger(triggerTempTarget: TriggerTempTarget) fun injectTrigger(triggerTime: TriggerTime) - fun injectTrigger(triggerTimeRange : TriggerTimeRange) + fun injectTrigger(triggerTimeRange: TriggerTimeRange) fun injectTrigger(triggerWifiSsid: TriggerWifiSsid) fun injectAction(action: Action) @@ -95,6 +113,10 @@ interface AppComponent : AndroidInjector { fun injectElement(labelWithElement: LabelWithElement) fun injectElement(staticLabel: StaticLabel) + fun injectAutosensDate(autosensData: AutosensData) + fun injectIobCobThread(iobCobThread: IobCobThread) + fun injectIobCobOref1Thread(iobCobOref1Thread: IobCobOref1Thread) + fun injectTreatment(treatment: Treatment) fun injectBgReading(bgReading: BgReading) 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 314c195b19..c78fc33def 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -25,8 +25,12 @@ import info.nightscout.androidaps.plugins.general.automation.actions.* import info.nightscout.androidaps.plugins.general.automation.elements.* import info.nightscout.androidaps.plugins.general.automation.triggers.* import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationWithAction +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobOref1Thread +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobThread import info.nightscout.androidaps.plugins.treatments.Treatment -import info.nightscout.androidaps.queue.commands.CommandSetProfile +import info.nightscout.androidaps.queue.CommandQueue +import info.nightscout.androidaps.queue.commands.* import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelperImplementation import info.nightscout.androidaps.utils.sharedPreferences.SP @@ -46,8 +50,8 @@ open class AppModule { @Provides @Singleton - fun provideProfileFunction(sp: SP, configBuilderPlugin: ConfigBuilderPlugin): ProfileFunction { - return ProfileFunctionImplementation(sp, configBuilderPlugin) + fun provideProfileFunction(sp: SP): ProfileFunction { + return ProfileFunctionImplementation(sp) } @Provides @@ -69,7 +73,25 @@ open class AppModule { @Module interface AppBindings { + @ContributesAndroidInjector fun commandQueueInjector(): CommandQueue + @ContributesAndroidInjector fun commandBolusInjector(): CommandBolus + @ContributesAndroidInjector + fun commandCancelExtendedBolusInjector(): CommandCancelExtendedBolus + + @ContributesAndroidInjector fun commandCancelTempBasalInjector(): CommandCancelTempBasal + @ContributesAndroidInjector fun commandExtendedBolusInjector(): CommandExtendedBolus + @ContributesAndroidInjector + fun commandInsightSetTBROverNotificationInjector(): CommandInsightSetTBROverNotification + + @ContributesAndroidInjector fun commandLoadEventsInjector(): CommandLoadEvents + @ContributesAndroidInjector fun commandLoadHistoryInjector(): CommandLoadHistory + @ContributesAndroidInjector fun commandReadStatusInjector(): CommandReadStatus @ContributesAndroidInjector fun commandSetProfileInjector(): CommandSetProfile + @ContributesAndroidInjector fun commandCommandSMBBolusInjector(): CommandSMBBolus + @ContributesAndroidInjector fun commandStartPumpInjector(): CommandStartPump + @ContributesAndroidInjector fun commandStopPumpInjector(): CommandStopPump + @ContributesAndroidInjector fun commandTempBasalAbsoluteInjector(): CommandTempBasalAbsolute + @ContributesAndroidInjector fun commandTempBasalPercentInjector(): CommandTempBasalPercent @ContributesAndroidInjector fun objective0Injector(): Objective0 @ContributesAndroidInjector fun objective1Injector(): Objective1 @@ -107,7 +129,9 @@ open class AppModule { @ContributesAndroidInjector fun actionLoopSuspendInjector(): ActionLoopSuspend @ContributesAndroidInjector fun actionNotificationInjector(): ActionNotification @ContributesAndroidInjector fun actionProfileSwitchInjector(): ActionProfileSwitch - @ContributesAndroidInjector fun actionProfileSwitchPercentInjector(): ActionProfileSwitchPercent + @ContributesAndroidInjector + fun actionProfileSwitchPercentInjector(): ActionProfileSwitchPercent + @ContributesAndroidInjector fun actionSendSMSInjector(): ActionSendSMS @ContributesAndroidInjector fun actionStartTempTargetInjector(): ActionStartTempTarget @ContributesAndroidInjector fun actionStopTempTargetInjector(): ActionStopTempTarget @@ -134,6 +158,10 @@ open class AppModule { @ContributesAndroidInjector fun labelWithElementInjector(): LabelWithElement @ContributesAndroidInjector fun staticLabelInjector(): StaticLabel + @ContributesAndroidInjector fun autosensDataInjector(): AutosensData + @ContributesAndroidInjector fun iobCobThreadInjector(): IobCobThread + @ContributesAndroidInjector fun iobCobOref1ThreadInjector(): IobCobOref1Thread + @ContributesAndroidInjector fun bgReadingInjector(): BgReading @ContributesAndroidInjector fun treatmentInjector(): Treatment @@ -146,9 +174,10 @@ open class AppModule { @Binds fun bindContext(mainApp: MainApp): Context @Binds fun bindInjector(mainApp: MainApp): HasAndroidInjector - @Binds fun bindActivePluginProvider(configBuilderPlugin: ConfigBuilderPlugin): ActivePluginProvider + @Binds + fun bindActivePluginProvider(configBuilderPlugin: ConfigBuilderPlugin): ActivePluginProvider - @Binds fun bindCommandQueueProvider(configBuilderPlugin: ConfigBuilderPlugin): CommandQueueProvider + @Binds fun commandQueueProvider(commandQueue: CommandQueue): CommandQueueProvider } } 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 1922eed5a0..b5d7c34848 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt @@ -19,22 +19,24 @@ import info.nightscout.androidaps.plugins.general.automation.dialogs.ChooseTrigg import info.nightscout.androidaps.plugins.general.automation.dialogs.EditActionDialog import info.nightscout.androidaps.plugins.general.automation.dialogs.EditEventDialog import info.nightscout.androidaps.plugins.general.automation.dialogs.EditTriggerDialog +import info.nightscout.androidaps.plugins.general.careportal.CareportalFragment +import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog +import info.nightscout.androidaps.plugins.general.food.FoodFragment +import info.nightscout.androidaps.plugins.general.maintenance.MaintenanceFragment +import info.nightscout.androidaps.plugins.general.nsclient.NSClientFragment import info.nightscout.androidaps.plugins.general.overview.OverviewFragment import info.nightscout.androidaps.plugins.general.overview.dialogs.EditQuickWizardDialog import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorFragment import info.nightscout.androidaps.plugins.general.tidepool.TidepoolFragment import info.nightscout.androidaps.plugins.profile.local.LocalProfileFragment import info.nightscout.androidaps.plugins.profile.ns.NSProfileFragment +import info.nightscout.androidaps.plugins.pump.combo.ComboFragment import info.nightscout.androidaps.plugins.pump.danaR.DanaRFragment +import info.nightscout.androidaps.plugins.pump.insight.LocalInsightFragment import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicFragment import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpFragment import info.nightscout.androidaps.plugins.source.BGSourceFragment import info.nightscout.androidaps.plugins.treatments.TreatmentsFragment -import info.nightscout.androidaps.dialogs.WizardInfoDialog -import info.nightscout.androidaps.plugins.general.careportal.CareportalFragment -import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog -import info.nightscout.androidaps.plugins.general.food.FoodFragment -import info.nightscout.androidaps.plugins.general.maintenance.MaintenanceFragment import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsBolusFragment import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsCareportalFragment import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsProfileSwitchFragment @@ -49,7 +51,10 @@ abstract class FragmentsModule { @ContributesAndroidInjector abstract fun contributesAutomationFragment(): AutomationFragment @ContributesAndroidInjector abstract fun contributesBGSourceFragment(): BGSourceFragment @ContributesAndroidInjector abstract fun contributesCareportalFragment(): CareportalFragment - @ContributesAndroidInjector abstract fun contributesConfigBuilderFragment(): ConfigBuilderFragment + @ContributesAndroidInjector abstract fun contributesComboFragment(): ComboFragment + @ContributesAndroidInjector + abstract fun contributesConfigBuilderFragment(): ConfigBuilderFragment + @ContributesAndroidInjector abstract fun contributesDanaRFragment(): DanaRFragment @ContributesAndroidInjector abstract fun contributesFoodFragment(): FoodFragment @ContributesAndroidInjector abstract fun contributesLocalProfileFragment(): LocalProfileFragment @@ -58,16 +63,26 @@ abstract class FragmentsModule { @ContributesAndroidInjector abstract fun contributesOpenAPSMAFragment(): OpenAPSMAFragment @ContributesAndroidInjector abstract fun contributesOpenAPSSMBFragment(): OpenAPSSMBFragment @ContributesAndroidInjector abstract fun contributesOverviewFragment(): OverviewFragment + @ContributesAndroidInjector abstract fun contributesLocalInsightFragment(): LocalInsightFragment @ContributesAndroidInjector abstract fun contributesLoopFragment(): LoopFragment @ContributesAndroidInjector abstract fun contributesMaintenanceFragment(): MaintenanceFragment @ContributesAndroidInjector abstract fun contributesMedtronicFragment(): MedtronicFragment @ContributesAndroidInjector abstract fun contributesNSProfileFragment(): NSProfileFragment - @ContributesAndroidInjector abstract fun contributesSmsCommunicatorFragment(): SmsCommunicatorFragment + @ContributesAndroidInjector abstract fun contributesNSClientFragment(): NSClientFragment + @ContributesAndroidInjector + abstract fun contributesSmsCommunicatorFragment(): SmsCommunicatorFragment + @ContributesAndroidInjector abstract fun contributesTidepoolFragment(): TidepoolFragment @ContributesAndroidInjector abstract fun contributesTreatmentsFragment(): TreatmentsFragment - @ContributesAndroidInjector abstract fun contributesTreatmentsBolusFragment(): TreatmentsBolusFragment - @ContributesAndroidInjector abstract fun contributesTreatmentsCareportalFragment(): TreatmentsCareportalFragment - @ContributesAndroidInjector abstract fun contributesTreatmentsProfileSwitchFragment(): TreatmentsProfileSwitchFragment + @ContributesAndroidInjector + abstract fun contributesTreatmentsBolusFragment(): TreatmentsBolusFragment + + @ContributesAndroidInjector + abstract fun contributesTreatmentsCareportalFragment(): TreatmentsCareportalFragment + + @ContributesAndroidInjector + abstract fun contributesTreatmentsProfileSwitchFragment(): TreatmentsProfileSwitchFragment + @ContributesAndroidInjector abstract fun contributesVirtualPumpFragment(): VirtualPumpFragment @ContributesAndroidInjector abstract fun contributesBolusProgressDialog(): BolusProgressDialog @@ -77,7 +92,9 @@ abstract class FragmentsModule { @ContributesAndroidInjector abstract fun contributesEditActionDialog(): EditActionDialog @ContributesAndroidInjector abstract fun contributesEditEventDialog(): EditEventDialog @ContributesAndroidInjector abstract fun contributesEditTriggerDialog(): EditTriggerDialog - @ContributesAndroidInjector abstract fun contributesEditQuickWizardDialog(): EditQuickWizardDialog + @ContributesAndroidInjector + abstract fun contributesEditQuickWizardDialog(): EditQuickWizardDialog + @ContributesAndroidInjector abstract fun contributesErrorDialog(): ErrorDialog @ContributesAndroidInjector abstract fun contributesExtendedBolusDialog(): ExtendedBolusDialog @ContributesAndroidInjector abstract fun contributesFillDialog(): FillDialog diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/BolusProgressDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/BolusProgressDialog.kt index a8e8ba3195..25b4b6573c 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/BolusProgressDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/BolusProgressDialog.kt @@ -12,10 +12,10 @@ import dagger.android.support.DaggerDialogFragment import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.BolusProgressHelperActivity import info.nightscout.androidaps.events.EventPumpStatusChanged +import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.general.overview.events.EventDismissBolusProgressIfRunning import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress import info.nightscout.androidaps.utils.FabricPrivacy @@ -29,7 +29,7 @@ class BolusProgressDialog : DaggerDialogFragment() { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var resourceHelper: ResourceHelper - @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin + @Inject lateinit var commandQueue: CommandQueueProvider @Inject lateinit var fabricPrivacy: FabricPrivacy private val disposable = CompositeDisposable() @@ -73,7 +73,7 @@ class BolusProgressDialog : DaggerDialogFragment() { stopPressed = true overview_bolusprogress_stoppressed.visibility = View.VISIBLE overview_bolusprogress_stop.visibility = View.INVISIBLE - configBuilderPlugin.commandQueue.cancelAllBoluses() + commandQueue.cancelAllBoluses() } val defaultState = resourceHelper.gs(R.string.waitingforpump) overview_bolusprogress_progressbar.max = 100 @@ -90,7 +90,7 @@ class BolusProgressDialog : DaggerDialogFragment() { override fun onResume() { super.onResume() aapsLogger.debug(LTag.UI, "onResume") - if (!configBuilderPlugin.commandQueue.bolusInQueue()) + if (!commandQueue.bolusInQueue()) bolusEnded = true if (bolusEnded) dismiss() 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 d0295eeccb..010c97d3ae 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt @@ -12,13 +12,13 @@ import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.db.CareportalEvent -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.ProfileFunction import info.nightscout.androidaps.plugins.general.nsclient.NSUpload +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.treatments.CarbsGenerator import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.* @@ -38,6 +38,7 @@ class CarbsDialog : DialogFragmentWithDate() { @Inject lateinit var defaultValueHelper: DefaultValueHelper @Inject lateinit var treatmentsPlugin: TreatmentsPlugin @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin; companion object { private const val FAV1_DEFAULT = 5 @@ -118,7 +119,7 @@ class CarbsDialog : DialogFragmentWithDate() { validateInputs() } - DatabaseHelper.actualBg()?.let { bgReading -> + iobCobCalculatorPlugin.actualBg()?.let { bgReading -> if (bgReading.value < 72) overview_carbs_hypo_tt.isChecked = true } 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 9becd0a30e..a40b415114 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/ExtendedBolusDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/ExtendedBolusDialog.kt @@ -9,8 +9,9 @@ import com.google.common.base.Joiner import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.ErrorHelperActivity +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.interfaces.CommandQueueProvider 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 @@ -28,7 +29,8 @@ class ExtendedBolusDialog : DialogFragmentWithDate() { @Inject lateinit var mainApp: MainApp @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var constraintChecker: ConstraintChecker - @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin + @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var activePlugin: ActivePluginProvider override fun onSaveInstanceState(savedInstanceState: Bundle) { super.onSaveInstanceState(savedInstanceState) @@ -45,7 +47,7 @@ class ExtendedBolusDialog : DialogFragmentWithDate() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) - val pumpDescription = configBuilderPlugin.activePump?.pumpDescription ?: return + val pumpDescription = activePlugin.activePump.pumpDescription val maxInsulin = constraintChecker.getMaxExtendedBolusAllowed().value() val extendedStep = pumpDescription.extendedBolusStep @@ -70,7 +72,7 @@ class ExtendedBolusDialog : DialogFragmentWithDate() { activity?.let { activity -> OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.extended_bolus), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { - configBuilderPlugin.commandQueue.extendedBolus(insulinAfterConstraint, durationInMinutes, object : Callback() { + commandQueue.extendedBolus(insulinAfterConstraint, durationInMinutes, object : Callback() { override fun run() { if (!result.success) { val i = Intent(mainApp, ErrorHelperActivity::class.java) 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 864a7e8ee3..b6d0e7ce05 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt @@ -1,5 +1,6 @@ package info.nightscout.androidaps.dialogs +import android.content.Context import android.content.Intent import android.os.Bundle import android.view.LayoutInflater @@ -12,8 +13,9 @@ import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.data.DetailedBolusInfo import info.nightscout.androidaps.db.CareportalEvent import info.nightscout.androidaps.db.Source +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.interfaces.CommandQueueProvider 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 @@ -35,8 +37,9 @@ import kotlin.math.abs class FillDialog : DialogFragmentWithDate() { @Inject lateinit var constraintChecker: ConstraintChecker @Inject lateinit var resourceHelper: ResourceHelper - @Inject lateinit var mainApp: MainApp - @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin + @Inject lateinit var ctx: Context + @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var activePlugin: ActivePluginProvider override fun onSaveInstanceState(savedInstanceState: Bundle) { super.onSaveInstanceState(savedInstanceState) @@ -53,7 +56,7 @@ class FillDialog : DialogFragmentWithDate() { super.onViewCreated(view, savedInstanceState) val maxInsulin = constraintChecker.getMaxBolusAllowed().value() - val bolusStep = configBuilderPlugin.activePump!!.pumpDescription.bolusStep + val bolusStep = activePlugin.activePump.pumpDescription.bolusStep fill_insulinamount.setParams(savedInstanceState?.getDouble("fill_insulin_amount") ?: 0.0, 0.0, maxInsulin, bolusStep, DecimalFormatter.pumpSupportedBolusFormat(), true, ok) val amount1 = sp.getDouble("fill_button1", 0.3) @@ -119,15 +122,15 @@ class FillDialog : DialogFragmentWithDate() { detailedBolusInfo.source = Source.USER detailedBolusInfo.isValid = false // do not count it in IOB (for pump history) detailedBolusInfo.notes = notes - configBuilderPlugin.commandQueue.bolus(detailedBolusInfo, object : Callback() { + commandQueue.bolus(detailedBolusInfo, object : Callback() { override fun run() { if (!result.success) { - val i = Intent(mainApp, ErrorHelperActivity::class.java) + val i = Intent(ctx, ErrorHelperActivity::class.java) i.putExtra("soundid", R.raw.boluserror) i.putExtra("status", result.comment) i.putExtra("title", resourceHelper.gs(R.string.treatmentdeliveryerror)) i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - mainApp.startActivity(i) + ctx.startActivity(i) } } }) @@ -158,7 +161,7 @@ class FillDialog : DialogFragmentWithDate() { return true } - fun generateJson(careportalEvent: String, time: Long, notes: String): JSONObject { + private fun generateJson(careportalEvent: String, time: Long, notes: String): JSONObject { val data = JSONObject() try { data.put("eventType", careportalEvent) 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 78dc6ee440..d4ce7712d9 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt @@ -9,7 +9,6 @@ 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.activities.ErrorHelperActivity import info.nightscout.androidaps.data.DetailedBolusInfo @@ -17,11 +16,11 @@ import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.db.CareportalEvent import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.db.TempTarget +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.interfaces.CommandQueueProvider 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.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.extensions.toSignedString @@ -37,12 +36,11 @@ 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 defaultValueHelper: DefaultValueHelper @Inject lateinit var profileFunction: ProfileFunction - @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin - @Inject lateinit var treatmentsPlugin: TreatmentsPlugin + @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var activePlugin: ActivePluginProvider companion object { private const val PLUS1_DEFAULT = 0.5 @@ -63,11 +61,11 @@ class InsulinDialog : DialogFragmentWithDate() { val maxInsulin = constraintChecker.getMaxBolusAllowed().value() if (abs(overview_insulin_time.value.toInt()) > 12 * 60) { overview_insulin_time.value = 0.0 - ToastUtils.showToastInUiThread(mainApp, resourceHelper.gs(R.string.constraintapllied)) + ToastUtils.showToastInUiThread(context, resourceHelper.gs(R.string.constraintapllied)) } if (overview_insulin_amount.value > maxInsulin) { overview_insulin_amount.value = 0.0 - ToastUtils.showToastInUiThread(mainApp, resourceHelper.gs(R.string.bolusconstraintapplied)) + ToastUtils.showToastInUiThread(context, resourceHelper.gs(R.string.bolusconstraintapplied)) } } @@ -91,7 +89,7 @@ class InsulinDialog : DialogFragmentWithDate() { 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.activePump!!.pumpDescription.bolusStep, DecimalFormatter.pumpSupportedBolusFormat(), false, ok, textWatcher) + ?: 0.0, 0.0, maxInsulin, activePlugin.activePump.pumpDescription.bolusStep, DecimalFormatter.pumpSupportedBolusFormat(), false, ok, textWatcher) overview_insulin_plus05.text = sp.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_1), PLUS1_DEFAULT).toSignedString() overview_insulin_plus05.setOnClickListener { @@ -107,7 +105,7 @@ class InsulinDialog : DialogFragmentWithDate() { } overview_insulin_plus20.text = sp.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_3), PLUS3_DEFAULT).toSignedString() overview_insulin_plus20.setOnClickListener { - overview_insulin_amount.value = Math.max(0.0, overview_insulin_amount.value + overview_insulin_amount.value = max(0.0, overview_insulin_amount.value + sp.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_3), PLUS3_DEFAULT)) validateInputs() } @@ -119,7 +117,7 @@ class InsulinDialog : DialogFragmentWithDate() { } override fun submit(): Boolean { - val pumpDescription = configBuilderPlugin.activePump?.pumpDescription + val pumpDescription = activePlugin.activePumpPlugin?.pumpDescription ?: return false val insulin = SafeParse.stringToDouble(overview_insulin_amount.text) val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(insulin)).value() @@ -161,7 +159,7 @@ class InsulinDialog : DialogFragmentWithDate() { .source(Source.USER) .low(Profile.toMgdl(eatingSoonTT, profileFunction.getUnits())) .high(Profile.toMgdl(eatingSoonTT, profileFunction.getUnits())) - treatmentsPlugin.addToHistoryTempTarget(tempTarget) + activePlugin.activeTreatments.addToHistoryTempTarget(tempTarget) } if (insulinAfterConstraints > 0) { val detailedBolusInfo = DetailedBolusInfo() @@ -172,18 +170,18 @@ class InsulinDialog : DialogFragmentWithDate() { detailedBolusInfo.notes = notes if (recordOnlyChecked) { detailedBolusInfo.date = time - treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, false) + activePlugin.activeTreatments.addToHistoryTreatment(detailedBolusInfo, false) } else { detailedBolusInfo.date = DateUtil.now() - configBuilderPlugin.commandQueue.bolus(detailedBolusInfo, object : Callback() { + commandQueue.bolus(detailedBolusInfo, object : Callback() { override fun run() { if (!result.success) { - val i = Intent(mainApp, ErrorHelperActivity::class.java) + val i = Intent(context, ErrorHelperActivity::class.java) i.putExtra("soundid", R.raw.boluserror) i.putExtra("status", result.comment) i.putExtra("title", resourceHelper.gs(R.string.treatmentdeliveryerror)) i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - mainApp.startActivity(i) + context?.startActivity(i) } } }) 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 9370bf795d..b32f5634dd 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/TempBasalDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/TempBasalDialog.kt @@ -6,15 +6,14 @@ import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.google.common.base.Joiner -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.ErrorHelperActivity +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.interfaces.CommandQueueProvider 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.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.HtmlHelper import info.nightscout.androidaps.utils.OKDialog @@ -29,10 +28,10 @@ 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 - @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin + @Inject lateinit var activePlugin: ActivePluginProvider + @Inject lateinit var commandQueue: CommandQueueProvider private var isPercentPump = true @@ -52,7 +51,7 @@ class TempBasalDialog : DialogFragmentWithDate() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) - val pumpDescription = configBuilderPlugin.activePump?.pumpDescription ?: return + val pumpDescription = activePlugin.activePumpPlugin?.pumpDescription ?: return val profile = profileFunction.getProfile() ?: return val maxTempPercent = pumpDescription.maxTempPercent.toDouble() @@ -104,20 +103,19 @@ class TempBasalDialog : DialogFragmentWithDate() { val callback: Callback = object : Callback() { override fun run() { if (!result.success) { - val i = Intent(mainApp, ErrorHelperActivity::class.java) + val i = Intent(context, ErrorHelperActivity::class.java) i.putExtra("soundid", R.raw.boluserror) i.putExtra("status", result.comment) i.putExtra("title", resourceHelper.gs(R.string.tempbasaldeliveryerror)) i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - mainApp.startActivity(i) + context?.startActivity(i) } } } - if (isPercentPump) { - configBuilderPlugin.commandQueue.tempBasalPercent(percent, durationInMinutes, true, profile, callback) - } else { - configBuilderPlugin.commandQueue.tempBasalAbsolute(absolute, durationInMinutes, true, profile, callback) - } + if (isPercentPump) + commandQueue.tempBasalPercent(percent, durationInMinutes, true, profile, callback) + else + commandQueue.tempBasalAbsolute(absolute, durationInMinutes, true, profile, callback) }) } 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 7f2c20224a..c1e43b286d 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt @@ -8,16 +8,15 @@ import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.google.common.base.Joiner -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.data.DetailedBolusInfo import info.nightscout.androidaps.db.CareportalEvent import info.nightscout.androidaps.db.Source +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.interfaces.CommandQueueProvider 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 import info.nightscout.androidaps.utils.HtmlHelper @@ -34,10 +33,9 @@ import kotlin.math.abs class TreatmentDialog : DialogFragmentWithDate() { @Inject lateinit var constraintChecker: ConstraintChecker - @Inject lateinit var mainApp: MainApp @Inject lateinit var resourceHelper: ResourceHelper - @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin - @Inject lateinit var treatmentsPlugin: TreatmentsPlugin + @Inject lateinit var activePlugin: ActivePluginProvider + @Inject lateinit var commandQueue: CommandQueueProvider private val textWatcher: TextWatcher = object : TextWatcher { override fun afterTextChanged(s: Editable) {} @@ -52,11 +50,11 @@ class TreatmentDialog : DialogFragmentWithDate() { val maxInsulin = constraintChecker.getMaxBolusAllowed().value() if (SafeParse.stringToInt(overview_treatment_carbs.text) > maxCarbs) { overview_treatment_carbs.value = 0.0 - ToastUtils.showToastInUiThread(mainApp, resourceHelper.gs(R.string.carbsconstraintapplied)) + ToastUtils.showToastInUiThread(context, resourceHelper.gs(R.string.carbsconstraintapplied)) } if (SafeParse.stringToDouble(overview_treatment_insulin.text) > maxInsulin) { overview_treatment_insulin.value = 0.0 - ToastUtils.showToastInUiThread(mainApp, resourceHelper.gs(R.string.bolusconstraintapplied)) + ToastUtils.showToastInUiThread(context, resourceHelper.gs(R.string.bolusconstraintapplied)) } } @@ -77,7 +75,7 @@ class TreatmentDialog : DialogFragmentWithDate() { val maxCarbs = constraintChecker.getMaxCarbsAllowed().value().toDouble() val maxInsulin = constraintChecker.getMaxBolusAllowed().value() - val pumpDescription = configBuilderPlugin.activePump?.pumpDescription ?: return + val pumpDescription = activePlugin.activePumpPlugin?.pumpDescription ?: return overview_treatment_carbs.setParams(savedInstanceState?.getDouble("overview_treatment_carbs") ?: 0.0, 0.0, maxCarbs, 1.0, DecimalFormat("0"), false, ok, textWatcher) overview_treatment_insulin.setParams(savedInstanceState?.getDouble("overview_treatment_insulin") @@ -85,7 +83,7 @@ class TreatmentDialog : DialogFragmentWithDate() { } override fun submit(): Boolean { - val pumpDescription = configBuilderPlugin.activePump?.pumpDescription + val pumpDescription = activePlugin.activePumpPlugin?.pumpDescription ?: return false val insulin = SafeParse.stringToDouble(overview_treatment_insulin.text) val carbs = SafeParse.stringToInt(overview_treatment_carbs.text) @@ -117,20 +115,20 @@ class TreatmentDialog : DialogFragmentWithDate() { detailedBolusInfo.context = context detailedBolusInfo.source = Source.USER if (!(recordOnlyChecked && (detailedBolusInfo.insulin > 0 || pumpDescription.storesCarbInfo))) { - configBuilderPlugin.commandQueue.bolus(detailedBolusInfo, object : Callback() { + commandQueue.bolus(detailedBolusInfo, object : Callback() { override fun run() { if (!result.success) { - val i = Intent(mainApp, ErrorHelperActivity::class.java) + val i = Intent(context, ErrorHelperActivity::class.java) i.putExtra("soundid", R.raw.boluserror) i.putExtra("status", result.comment) i.putExtra("title", resourceHelper.gs(R.string.treatmentdeliveryerror)) i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - mainApp.startActivity(i) + context?.startActivity(i) } } }) } else - treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, false) + activePlugin.activeTreatments.addToHistoryTreatment(detailedBolusInfo, false) }) } } else 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 8c5f3b0f99..64a35b07cd 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt @@ -18,7 +18,6 @@ import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.db.BgReading -import info.nightscout.androidaps.db.DatabaseHelper import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag @@ -110,8 +109,7 @@ class WizardDialog : DaggerDialogFragment() { ?: 0.0, 0.0, 500.0, 0.1, DecimalFormat("0.0"), false, ok, textWatcher) treatments_wizard_carbs_input.setParams(savedInstanceState?.getDouble("treatments_wizard_carbs_input") ?: 0.0, 0.0, maxCarbs.toDouble(), 1.0, DecimalFormat("0"), false, ok, textWatcher) - val bolusStep = configBuilderPlugin.activePump?.pumpDescription?.bolusStep - ?: 0.1 + val bolusStep = configBuilderPlugin.activePump.pumpDescription.bolusStep treatments_wizard_correction_input.setParams(savedInstanceState?.getDouble("treatments_wizard_correction_input") ?: 0.0, -maxCorrection, maxCorrection, bolusStep, DecimalFormatter.pumpSupportedBolusFormat(), false, ok, textWatcher) treatments_wizard_carb_time_input.setParams(savedInstanceState?.getDouble("treatments_wizard_carb_time_input") @@ -238,7 +236,7 @@ class WizardDialog : DaggerDialogFragment() { treatments_wizard_bg_input.setStep(0.1) // Set BG if not old - val lastBg = DatabaseHelper.actualBg() + val lastBg = iobCobCalculatorPlugin.actualBg() if (lastBg != null) { treatments_wizard_bg_input.value = lastBg.valueToUnits(units) diff --git a/app/src/main/java/info/nightscout/androidaps/historyBrowser/IobCobStaticCalculatorPlugin.kt b/app/src/main/java/info/nightscout/androidaps/historyBrowser/IobCobStaticCalculatorPlugin.kt index 4eb7248460..24a4bc6739 100644 --- a/app/src/main/java/info/nightscout/androidaps/historyBrowser/IobCobStaticCalculatorPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/historyBrowser/IobCobStaticCalculatorPlugin.kt @@ -1,24 +1,34 @@ package info.nightscout.androidaps.historyBrowser +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin +import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin +import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin +import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import javax.inject.Inject class IobCobStaticCalculatorPlugin @Inject constructor( + injector: HasAndroidInjector, aapsLogger: AAPSLogger, rxBus: RxBusWrapper, sp: SP, resourceHelper: ResourceHelper, profileFunction: ProfileFunction, configBuilderPlugin: ConfigBuilderPlugin, - treatmentsPlugin: TreatmentsPlugin -) : IobCobCalculatorPlugin(aapsLogger, rxBus, sp, resourceHelper, profileFunction, configBuilderPlugin, treatmentsPlugin) { + treatmentsPlugin: TreatmentsPlugin, + sensitivityOref1Plugin: SensitivityOref1Plugin, + sensitivityAAPSPlugin: SensitivityAAPSPlugin, + sensitivityWeightedAveragePlugin: SensitivityWeightedAveragePlugin +) : IobCobCalculatorPlugin(injector, aapsLogger, rxBus, sp, resourceHelper, profileFunction, + configBuilderPlugin, treatmentsPlugin, sensitivityOref1Plugin, sensitivityAAPSPlugin, sensitivityWeightedAveragePlugin) { + override fun onStart() { // do not attach to rxbus } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/ActivePluginProvider.java b/app/src/main/java/info/nightscout/androidaps/interfaces/ActivePluginProvider.java index f8f4edd5f1..9eff25fb53 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/ActivePluginProvider.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/ActivePluginProvider.java @@ -1,23 +1,25 @@ package info.nightscout.androidaps.interfaces; +import androidx.annotation.NonNull; import androidx.annotation.Nullable; import org.jetbrains.annotations.NotNull; -/** - * Created by adrian on 2020-01-07. - */ - public interface ActivePluginProvider { + @Nullable BgSourceInterface getActiveBgSource(); - @NotNull ProfileInterface getActiveProfileInterface(); + @NotNull ProfileInterface getActiveProfileInterface(); // Forced to LocalProfile if not changed - @Nullable InsulinInterface getActiveInsulin(); + @NonNull InsulinInterface getActiveInsulin(); // Forced to RapidActing if not changed @Nullable APSInterface getActiveAPS(); - @Nullable PumpInterface getActivePump(); + @Nullable PumpInterface getActivePumpPlugin(); // Use in UI to disable buttons or check if pump is selected - @Nullable SensitivityInterface getActiveSensitivity(); -} + @NotNull PumpInterface getActivePump(); // Use in places not reachable without active pump. Otherwise IllegalStateException is thrown + + @NotNull SensitivityInterface getActiveSensitivity(); // Forced to oref1 if not changed + + @NotNull TreatmentsInterface getActiveTreatments(); +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/CommandQueueProvider.java b/app/src/main/java/info/nightscout/androidaps/interfaces/CommandQueueProvider.java deleted file mode 100644 index eae24fce70..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/CommandQueueProvider.java +++ /dev/null @@ -1,11 +0,0 @@ -package info.nightscout.androidaps.interfaces; - -import info.nightscout.androidaps.queue.CommandQueue; - -/** - * Created by adrian on 2020-01-07. - */ - -public interface CommandQueueProvider { - CommandQueue getCommandQueue(); -} diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/CommandQueueProvider.kt b/app/src/main/java/info/nightscout/androidaps/interfaces/CommandQueueProvider.kt new file mode 100644 index 0000000000..a5f9bf21df --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/CommandQueueProvider.kt @@ -0,0 +1,38 @@ +package info.nightscout.androidaps.interfaces + +import android.text.Spanned +import info.nightscout.androidaps.data.DetailedBolusInfo +import info.nightscout.androidaps.data.Profile +import info.nightscout.androidaps.queue.Callback +import info.nightscout.androidaps.queue.commands.Command + +interface CommandQueueProvider { + + fun isRunning(type: Command.CommandType): Boolean + fun pickup() + fun clear() + fun size(): Int + fun performing(): Command? + fun resetPerforming() + fun independentConnect(reason: String, callback: Callback?) + fun bolusInQueue(): Boolean + fun bolus(detailedBolusInfo: DetailedBolusInfo, callback: Callback?): Boolean + fun cancelAllBoluses() + fun stopPump(callback: Callback?) + fun startPump(callback: Callback?) + fun setTBROverNotification(callback: Callback?, enable: Boolean) + fun tempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, enforceNew: Boolean, profile: Profile, callback: Callback?): Boolean + fun tempBasalPercent(percent: Int, durationInMinutes: Int, enforceNew: Boolean, profile: Profile, callback: Callback?): Boolean + fun extendedBolus(insulin: Double, durationInMinutes: Int, callback: Callback?): Boolean + fun cancelTempBasal(enforceNew: Boolean, callback: Callback?): Boolean + fun cancelExtended(callback: Callback?): Boolean + fun setProfile(profile: Profile, callback: Callback?): Boolean + fun readStatus(reason: String, callback: Callback?): Boolean + fun statusInQueue(): Boolean + fun loadHistory(type: Byte, callback: Callback?): Boolean + fun setUserOptions(callback: Callback?): Boolean + fun loadTDDs(callback: Callback?): Boolean + fun loadEvents(callback: Callback?): Boolean + fun spannedStatus(): Spanned + fun isThisProfileSet(profile: Profile): Boolean +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.kt b/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.kt index 1d52ab4d90..384d3731c3 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.kt +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.kt @@ -1,32 +1,19 @@ package info.nightscout.androidaps.interfaces -import android.os.SystemClock -import androidx.fragment.app.FragmentActivity import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat -import info.nightscout.androidaps.MainApp -import info.nightscout.androidaps.R -import info.nightscout.androidaps.events.EventConfigBuilderChange -import info.nightscout.androidaps.events.EventRebuildTabs import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.L -import info.nightscout.androidaps.logging.L.isEnabled -import info.nightscout.androidaps.plugins.bus.RxBus -import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin -import info.nightscout.androidaps.plugins.configBuilder.EventConfigBuilderUpdateGui -import info.nightscout.androidaps.utils.OKDialog.showConfirmation -import info.nightscout.androidaps.utils.SP -import org.slf4j.LoggerFactory +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.utils.resources.ResourceHelper /** * Created by mike on 09.06.2016. */ -abstract class PluginBase(val pluginDescription: PluginDescription, val rxBus: RxBusWrapper, val aapsLogger: AAPSLogger) { - - companion object { - private val log = LoggerFactory.getLogger(L.CORE) - } +abstract class PluginBase( + val pluginDescription: PluginDescription, + val aapsLogger: AAPSLogger, + val resourceHelper: ResourceHelper +) { enum class State { NOT_INITIALIZED, ENABLED, DISABLED @@ -34,61 +21,22 @@ abstract class PluginBase(val pluginDescription: PluginDescription, val rxBus: R private var state = State.NOT_INITIALIZED private var fragmentVisible = false - // Specific plugin with more Interfaces - protected var isProfileInterfaceEnabled = false - - // Default always calls invoke - // Plugins that have special constraints if they get switched to may override this method - open fun switchAllowed(newState: Boolean, activity: FragmentActivity?, type: PluginType) { - performPluginSwitch(newState, type) - } - - protected fun confirmPumpPluginActivation(newState: Boolean, activity: FragmentActivity?, type: PluginType) { - if (type == PluginType.PUMP) { - val allowHardwarePump = SP.getBoolean("allow_hardware_pump", false) - if (allowHardwarePump || activity == null) { - performPluginSwitch(newState, type) - } else { - showConfirmation(activity, MainApp.gs(R.string.allow_hardware_pump_text), Runnable { - performPluginSwitch(newState, type) - SP.putBoolean("allow_hardware_pump", true) - if (isEnabled(L.PUMP)) log.debug("First time HW pump allowed!") - }, Runnable { - RxBus.INSTANCE.send(EventConfigBuilderUpdateGui()) - if (isEnabled(L.PUMP)) log.debug("User does not allow switching to HW pump!") - }) - } - } else { - performPluginSwitch(newState, type) - } - } - - private fun performPluginSwitch(enabled: Boolean, type: PluginType) { - setPluginEnabled(type, enabled) - setFragmentVisible(type, enabled) - ConfigBuilderPlugin.getPlugin().processOnEnabledCategoryChanged(this, type) - ConfigBuilderPlugin.getPlugin().storeSettings("CheckedCheckboxEnabled") - RxBus.INSTANCE.send(EventRebuildTabs()) - RxBus.INSTANCE.send(EventConfigBuilderChange()) - RxBus.INSTANCE.send(EventConfigBuilderUpdateGui()) - ConfigBuilderPlugin.getPlugin().logPluginStatus() - } open val name: String - get() = if (pluginDescription.pluginName == -1) "UNKNOWN" else MainApp.gs(pluginDescription.pluginName) + get() = if (pluginDescription.pluginName == -1) "UNKNOWN" else resourceHelper.gs(pluginDescription.pluginName) //only if translation exists // use long name as fallback val nameShort: String get() { if (pluginDescription.shortName == -1) return name - val translatedName = MainApp.gs(pluginDescription.shortName) + val translatedName = resourceHelper.gs(pluginDescription.shortName) return if (!translatedName.trim { it <= ' ' }.isEmpty()) translatedName else name // use long name as fallback } val description: String? - get() = if (pluginDescription.description == -1) null else MainApp.gs(pluginDescription.description) + get() = if (pluginDescription.description == -1) null else resourceHelper.gs(pluginDescription.description) fun getType(): PluginType = pluginDescription.mainType @@ -103,7 +51,7 @@ abstract class PluginBase(val pluginDescription: PluginDescription, val rxBus: R if (type == pluginDescription.mainType) return state == State.ENABLED && specialEnableCondition() if (type == PluginType.CONSTRAINTS && pluginDescription.mainType == PluginType.PUMP && isEnabled(PluginType.PUMP)) return true if (type == PluginType.CONSTRAINTS && pluginDescription.mainType == PluginType.APS && isEnabled(PluginType.APS)) return true - return if (type == PluginType.PROFILE && pluginDescription.mainType == PluginType.PUMP) isProfileInterfaceEnabled else false + return false } fun hasFragment(): Boolean { @@ -121,7 +69,7 @@ abstract class PluginBase(val pluginDescription: PluginDescription, val rxBus: R if (state != State.ENABLED) { onStateChange(type, state, State.ENABLED) state = State.ENABLED - if (isEnabled(L.CORE)) log.debug("Starting: $name") + aapsLogger.debug(LTag.CORE, "Starting: $name") onStart() } } else { // disabling plugin @@ -129,11 +77,9 @@ abstract class PluginBase(val pluginDescription: PluginDescription, val rxBus: R onStateChange(type, state, State.DISABLED) state = State.DISABLED onStop() - if (isEnabled(L.CORE)) log.debug("Stopping: $name") + aapsLogger.debug(LTag.CORE, "Stopping: $name") } } - } else if (type == PluginType.PROFILE) { - isProfileInterfaceEnabled = newState } } @@ -161,16 +107,7 @@ abstract class PluginBase(val pluginDescription: PluginDescription, val rxBus: R return true } - protected open fun onStart() { - if (getType() == PluginType.PUMP) { - Thread(Runnable { - SystemClock.sleep(3000) - val commandQueue = ConfigBuilderPlugin.getPlugin().commandQueue - commandQueue?.readStatus("Pump driver changed.", null) - }).start() - } - } - + protected open fun onStart() {} protected open fun onStop() {} protected open fun onStateChange(type: PluginType?, oldState: State?, newState: State?) {} open fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) {} diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/PumpInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/PumpInterface.java index 2ca2bca0d1..aab6d4089a 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/PumpInterface.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/PumpInterface.java @@ -1,5 +1,6 @@ package info.nightscout.androidaps.interfaces; +import org.jetbrains.annotations.NotNull; import org.json.JSONObject; import java.util.List; @@ -42,6 +43,7 @@ public interface PumpInterface { void getPumpStatus(); // Upload to pump new basal profile + @NotNull PumpEnactResult setNewBasalProfile(Profile profile); boolean isThisProfileSet(Profile profile); @@ -54,39 +56,52 @@ public interface PumpInterface { int getBatteryLevel(); // in percent as integer + @NotNull PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo); void stopBolusDelivering(); + @NotNull PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean enforceNew); + @NotNull PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew); + @NotNull PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes); //some pumps might set a very short temp close to 100% as cancelling a temp can be noisy //when the cancel request is requested by the user (forced), the pump should always do a real cancel + @NotNull PumpEnactResult cancelTempBasal(boolean enforceNew); + @NotNull PumpEnactResult cancelExtendedBolus(); // Status to be passed to NS + @NotNull JSONObject getJSONStatus(Profile profile, String profileName); + @NotNull ManufacturerType manufacturer(); + @NotNull PumpType model(); + @NotNull String serialNumber(); // Pump capabilities + @NotNull PumpDescription getPumpDescription(); // Short info for SMS, Wear etc + @NotNull String shortStatus(boolean veryShort); boolean isFakingTempsByExtendedBoluses(); + @NotNull PumpEnactResult loadTDDs(); boolean canHandleDST(); @@ -101,5 +116,4 @@ public interface PumpInterface { * example update clock on pump). */ void timeDateOrTimeZoneChanged(); - } diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/PumpPluginBase.kt b/app/src/main/java/info/nightscout/androidaps/interfaces/PumpPluginBase.kt new file mode 100644 index 0000000000..b72667f19b --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/PumpPluginBase.kt @@ -0,0 +1,23 @@ +package info.nightscout.androidaps.interfaces + +import android.os.SystemClock +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.utils.resources.ResourceHelper + +abstract class PumpPluginBase( + pluginDescription: PluginDescription, + aapsLogger: AAPSLogger, + resourceHelper: ResourceHelper, + val commandQueue: CommandQueueProvider +) : PluginBase(pluginDescription, aapsLogger, resourceHelper) { + + override fun onStart() { + super.onStart() + if (getType() == PluginType.PUMP) { + Thread(Runnable { + SystemClock.sleep(3000) + commandQueue.readStatus("Pump driver changed.", null) + }).start() + } + } +} \ No newline at end of file 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 0bd57e4647..abb55c90ee 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 @@ -29,13 +29,13 @@ import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.CareportalEvent; -import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.EventAcceptOpenLoopChange; import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.events.EventTempTargetChange; import info.nightscout.androidaps.interfaces.APSInterface; +import info.nightscout.androidaps.interfaces.CommandQueueProvider; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; @@ -54,6 +54,7 @@ import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.wear.ActionStringHandler; +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; @@ -69,14 +70,17 @@ import io.reactivex.schedulers.Schedulers; @Singleton public class LoopPlugin extends PluginBase { private final SP sp; + private final RxBusWrapper rxBus; private final ConstraintChecker constraintChecker; private final ResourceHelper resourceHelper; private final ProfileFunction profileFunction; private final MainApp mainApp; + private final CommandQueueProvider commandQueue; private final ConfigBuilderPlugin configBuilderPlugin; private final TreatmentsPlugin treatmentsPlugin; private final VirtualPumpPlugin virtualPumpPlugin; private final Lazy actionStringHandler; + private final IobCobCalculatorPlugin iobCobCalculatorPlugin; private CompositeDisposable disposable = new CompositeDisposable(); @@ -104,35 +108,40 @@ public class LoopPlugin extends PluginBase { @Inject public LoopPlugin( AAPSLogger aapsLogger, - RxBusWrapper rxBusWrapper, + RxBusWrapper rxBus, SP sp, ConstraintChecker constraintChecker, ResourceHelper resourceHelper, ProfileFunction profileFunction, MainApp mainApp, + CommandQueueProvider commandQueue, ConfigBuilderPlugin configBuilderPlugin, TreatmentsPlugin treatmentsPlugin, VirtualPumpPlugin virtualPumpPlugin, - Lazy actionStringHandler // TODO Adrian use RxBus instead of Lazy + Lazy actionStringHandler, // TODO Adrian use RxBus instead of Lazy + IobCobCalculatorPlugin iobCobCalculatorPlugin ) { super(new PluginDescription() - .mainType(PluginType.LOOP) - .fragmentClass(LoopFragment.class.getName()) - .pluginName(R.string.loop) - .shortName(R.string.loop_shortname) - .preferencesId(R.xml.pref_loop) - .description(R.string.description_loop), - rxBusWrapper, aapsLogger + .mainType(PluginType.LOOP) + .fragmentClass(LoopFragment.class.getName()) + .pluginName(R.string.loop) + .shortName(R.string.loop_shortname) + .preferencesId(R.xml.pref_loop) + .description(R.string.description_loop), + aapsLogger, resourceHelper ); this.sp = sp; + this.rxBus = rxBus; this.constraintChecker = constraintChecker; this.resourceHelper = resourceHelper; this.profileFunction = profileFunction; this.mainApp = mainApp; this.configBuilderPlugin = configBuilderPlugin; + this.commandQueue = commandQueue; this.treatmentsPlugin = treatmentsPlugin; this.virtualPumpPlugin = virtualPumpPlugin; this.actionStringHandler = actionStringHandler; + this.iobCobCalculatorPlugin = iobCobCalculatorPlugin; loopSuspendedTill = sp.getLong("loopSuspendedTill", 0L); isSuperBolus = sp.getBoolean("isSuperBolus", false); @@ -143,7 +152,7 @@ public class LoopPlugin extends PluginBase { protected void onStart() { createNotificationChannel(); super.onStart(); - disposable.add(getRxBus() + disposable.add(rxBus .toObservable(EventTempTargetChange.class) .observeOn(Schedulers.io()) .subscribe(event -> invoke("EventTempTargetChange", true), exception -> FabricPrivacy.getInstance().logException(exception)) @@ -155,14 +164,14 @@ public class LoopPlugin extends PluginBase { * the event causing the calculation is not EventNewBg. *

*/ - disposable.add(getRxBus() + disposable.add(rxBus .toObservable(EventAutosensCalculationFinished.class) .observeOn(Schedulers.io()) .subscribe(event -> { // Autosens calculation not triggered by a new BG if (!(event.getCause() instanceof EventNewBG)) return; - BgReading bgReading = DatabaseHelper.actualBg(); + BgReading bgReading = iobCobCalculatorPlugin.actualBg(); // BG outdated if (bgReading == null) return; // already looped with that value @@ -194,7 +203,7 @@ public class LoopPlugin extends PluginBase { @Override public boolean specialEnableCondition() { - PumpInterface pump = configBuilderPlugin.getActivePump(); + PumpInterface pump = configBuilderPlugin.getActivePumpPlugin(); return pump == null || pump.getPumpDescription().isTempBasalCapable; } @@ -297,10 +306,10 @@ public class LoopPlugin extends PluginBase { if (!loopEnabled.value()) { String message = resourceHelper.gs(R.string.loopdisabled) + "\n" + loopEnabled.getReasons(); getAapsLogger().debug(LTag.APS, message); - getRxBus().send(new EventLoopSetLastRunGui(message)); + rxBus.send(new EventLoopSetLastRunGui(message)); return; } - final PumpInterface pump = configBuilderPlugin.getActivePump(); + final PumpInterface pump = configBuilderPlugin.getActivePumpPlugin(); if (pump == null) return; APSResult result = null; @@ -313,7 +322,7 @@ public class LoopPlugin extends PluginBase { if (profile == null || !profileFunction.isProfileValid("Loop")) { if (L.isEnabled(L.APS)) getAapsLogger().debug(LTag.APS, resourceHelper.gs(R.string.noprofileselected)); - getRxBus().send(new EventLoopSetLastRunGui(resourceHelper.gs(R.string.noprofileselected))); + rxBus.send(new EventLoopSetLastRunGui(resourceHelper.gs(R.string.noprofileselected))); return; } @@ -328,7 +337,7 @@ public class LoopPlugin extends PluginBase { // Check if we have any result if (result == null) { - getRxBus().send(new EventLoopSetLastRunGui(resourceHelper.gs(R.string.noapsselected))); + rxBus.send(new EventLoopSetLastRunGui(resourceHelper.gs(R.string.noapsselected))); return; } @@ -368,13 +377,13 @@ public class LoopPlugin extends PluginBase { if (isSuspended()) { getAapsLogger().debug(LTag.APS, resourceHelper.gs(R.string.loopsuspended)); - getRxBus().send(new EventLoopSetLastRunGui(resourceHelper.gs(R.string.loopsuspended))); + rxBus.send(new EventLoopSetLastRunGui(resourceHelper.gs(R.string.loopsuspended))); return; } if (pump.isSuspended()) { getAapsLogger().debug(LTag.APS, resourceHelper.gs(R.string.pumpsuspended)); - getRxBus().send(new EventLoopSetLastRunGui(resourceHelper.gs(R.string.pumpsuspended))); + rxBus.send(new EventLoopSetLastRunGui(resourceHelper.gs(R.string.pumpsuspended))); return; } @@ -382,15 +391,15 @@ public class LoopPlugin extends PluginBase { if (closedLoopEnabled.value()) { if (resultAfterConstraints.isChangeRequested() - && !configBuilderPlugin.getCommandQueue().bolusInQueue() - && !configBuilderPlugin.getCommandQueue().isRunning(Command.CommandType.BOLUS)) { + && !commandQueue.bolusInQueue() + && !commandQueue.isRunning(Command.CommandType.BOLUS)) { final PumpEnactResult waiting = new PumpEnactResult(); waiting.queued = true; if (resultAfterConstraints.tempBasalRequested) lastRun.tbrSetByPump = waiting; if (resultAfterConstraints.bolusRequested) lastRun.smbSetByPump = waiting; - getRxBus().send(new EventLoopUpdateGui()); + rxBus.send(new EventLoopUpdateGui()); FabricPrivacy.getInstance().logCustom("APSRequest"); applyTBRRequest(resultAfterConstraints, profile, new Callback() { @Override @@ -411,11 +420,11 @@ public class LoopPlugin extends PluginBase { invoke("tempBasalFallback", allowNotification, true); }).start(); } - getRxBus().send(new EventLoopUpdateGui()); + rxBus.send(new EventLoopUpdateGui()); } }); } - getRxBus().send(new EventLoopUpdateGui()); + rxBus.send(new EventLoopUpdateGui()); } }); } else { @@ -456,7 +465,7 @@ public class LoopPlugin extends PluginBase { (NotificationManager) mainApp.getSystemService(Context.NOTIFICATION_SERVICE); // mId allows you to update the notification later on. mNotificationManager.notify(Constants.notificationID, builder.build()); - getRxBus().send(new EventNewOpenLoopNotification()); + rxBus.send(new EventNewOpenLoopNotification()); // Send to Wear actionStringHandler.get().handleInitiate("changeRequest"); @@ -469,7 +478,7 @@ public class LoopPlugin extends PluginBase { } } - getRxBus().send(new EventLoopUpdateGui()); + rxBus.send(new EventLoopUpdateGui()); } finally { getAapsLogger().debug(LTag.APS, "invoke end"); } @@ -488,7 +497,7 @@ public class LoopPlugin extends PluginBase { NSUpload.uploadDeviceStatus(lp); sp.incInt(R.string.key_ObjectivesmanualEnacts); } - getRxBus().send(new EventAcceptOpenLoopChange()); + rxBus.send(new EventAcceptOpenLoopChange()); } }); FabricPrivacy.getInstance().logCustom("AcceptTemp"); @@ -509,7 +518,7 @@ public class LoopPlugin extends PluginBase { return; } - PumpInterface pump = configBuilderPlugin.getActivePump(); + PumpInterface pump = configBuilderPlugin.getActivePumpPlugin(); if (pump == null) { if (callback != null) callback.result(new PumpEnactResult().enacted(false).success(false).comment(resourceHelper.gs(R.string.nopumpselected))).run(); @@ -540,7 +549,7 @@ public class LoopPlugin extends PluginBase { if (request.percent == 100 && request.duration == 0) { if (activeTemp != null) { getAapsLogger().debug(LTag.APS, "applyAPSRequest: cancelTempBasal()"); - configBuilderPlugin.getCommandQueue().cancelTempBasal(false, callback); + commandQueue.cancelTempBasal(false, callback); } else { getAapsLogger().debug(LTag.APS, "applyAPSRequest: Basal set correctly"); if (callback != null) { @@ -560,13 +569,13 @@ public class LoopPlugin extends PluginBase { } } else { getAapsLogger().debug(LTag.APS, "applyAPSRequest: tempBasalPercent()"); - configBuilderPlugin.getCommandQueue().tempBasalPercent(request.percent, request.duration, false, profile, callback); + commandQueue.tempBasalPercent(request.percent, request.duration, false, profile, callback); } } else { if ((request.rate == 0 && request.duration == 0) || Math.abs(request.rate - pump.getBaseBasalRate()) < pump.getPumpDescription().basalStep) { if (activeTemp != null) { getAapsLogger().debug(LTag.APS, "applyAPSRequest: cancelTempBasal()"); - configBuilderPlugin.getCommandQueue().cancelTempBasal(false, callback); + commandQueue.cancelTempBasal(false, callback); } else { getAapsLogger().debug(LTag.APS, "applyAPSRequest: Basal set correctly"); if (callback != null) { @@ -586,7 +595,7 @@ public class LoopPlugin extends PluginBase { } } else { getAapsLogger().debug(LTag.APS, "applyAPSRequest: setTempBasalAbsolute()"); - configBuilderPlugin.getCommandQueue().tempBasalAbsolute(request.rate, request.duration, false, profile, callback); + commandQueue.tempBasalAbsolute(request.rate, request.duration, false, profile, callback); } } } @@ -596,7 +605,7 @@ public class LoopPlugin extends PluginBase { return; } - PumpInterface pump = configBuilderPlugin.getActivePump(); + PumpInterface pump = configBuilderPlugin.getActivePumpPlugin(); if (pump == null) { if (callback != null) callback.result(new PumpEnactResult().enacted(false).success(false).comment(resourceHelper.gs(R.string.nopumpselected))).run(); @@ -641,18 +650,18 @@ public class LoopPlugin extends PluginBase { detailedBolusInfo.source = Source.USER; detailedBolusInfo.deliverAt = request.deliverAt; getAapsLogger().debug(LTag.APS, "applyAPSRequest: bolus()"); - configBuilderPlugin.getCommandQueue().bolus(detailedBolusInfo, callback); + commandQueue.bolus(detailedBolusInfo, callback); } public void disconnectPump(int durationInMinutes, Profile profile) { - PumpInterface pump = configBuilderPlugin.getActivePump(); + PumpInterface pump = configBuilderPlugin.getActivePumpPlugin(); if (pump == null) return; disconnectTo(System.currentTimeMillis() + durationInMinutes * 60 * 1000L); if (pump.getPumpDescription().tempBasalStyle == PumpDescription.ABSOLUTE) { - configBuilderPlugin.getCommandQueue().tempBasalAbsolute(0, durationInMinutes, true, profile, new Callback() { + commandQueue.tempBasalAbsolute(0, durationInMinutes, true, profile, new Callback() { @Override public void run() { if (!result.success) { @@ -666,7 +675,7 @@ public class LoopPlugin extends PluginBase { } }); } else { - configBuilderPlugin.getCommandQueue().tempBasalPercent(0, durationInMinutes, true, profile, new Callback() { + commandQueue.tempBasalPercent(0, durationInMinutes, true, profile, new Callback() { @Override public void run() { if (!result.success) { @@ -682,7 +691,7 @@ public class LoopPlugin extends PluginBase { } if (pump.getPumpDescription().isExtendedBolusCapable && treatmentsPlugin.isInHistoryExtendedBoluslInProgress()) { - configBuilderPlugin.getCommandQueue().cancelExtended(new Callback() { + commandQueue.cancelExtended(new Callback() { @Override public void run() { if (!result.success) { @@ -701,7 +710,7 @@ public class LoopPlugin extends PluginBase { public void suspendLoop(int durationInMinutes) { suspendTo(System.currentTimeMillis() + durationInMinutes * 60 * 1000); - configBuilderPlugin.getCommandQueue().cancelTempBasal(true, new Callback() { + commandQueue.cancelTempBasal(true, new Callback() { @Override public void run() { if (!result.success) { 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 2b8f4fd984..a59f5f4eb7 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 @@ -12,6 +12,7 @@ import info.nightscout.androidaps.data.MealData; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.interfaces.APSInterface; +import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; @@ -23,7 +24,6 @@ import info.nightscout.androidaps.plugins.aps.loop.ScriptReader; import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui; import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateResultGui; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData; @@ -46,7 +46,7 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface { private final ResourceHelper resourceHelper; private final ProfileFunction profileFunction; private final MainApp mainApp; - private final ConfigBuilderPlugin configBuilderPlugin; + private final ActivePluginProvider activePlugin; private final TreatmentsPlugin treatmentsPlugin; private final IobCobCalculatorPlugin iobCobCalculatorPlugin; @@ -64,18 +64,18 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface { ResourceHelper resourceHelper, ProfileFunction profileFunction, MainApp mainApp, - ConfigBuilderPlugin configBuilderPlugin, + ActivePluginProvider activePlugin, TreatmentsPlugin treatmentsPlugin, IobCobCalculatorPlugin iobCobCalculatorPlugin ) { super(new PluginDescription() - .mainType(PluginType.APS) - .fragmentClass(OpenAPSAMAFragment.class.getName()) - .pluginName(R.string.openapsama) - .shortName(R.string.oaps_shortname) - .preferencesId(R.xml.pref_openapsama) - .description(R.string.description_ama), - rxBus, aapsLogger + .mainType(PluginType.APS) + .fragmentClass(OpenAPSAMAFragment.class.getName()) + .pluginName(R.string.openapsama) + .shortName(R.string.oaps_shortname) + .preferencesId(R.xml.pref_openapsama) + .description(R.string.description_ama), + aapsLogger, resourceHelper ); this.aapsLogger = aapsLogger; this.rxBus = rxBus; @@ -83,20 +83,24 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface { this.resourceHelper = resourceHelper; this.profileFunction = profileFunction; this.mainApp = mainApp; - this.configBuilderPlugin = configBuilderPlugin; + this.activePlugin = activePlugin; this.treatmentsPlugin = treatmentsPlugin; this.iobCobCalculatorPlugin = iobCobCalculatorPlugin; } @Override public boolean specialEnableCondition() { - PumpInterface pump = configBuilderPlugin.getActivePump(); - return pump == null || pump.getPumpDescription().isTempBasalCapable; + // main fail during init + if (activePlugin != null) { + PumpInterface pump = activePlugin.getActivePumpPlugin(); + return pump == null || pump.getPumpDescription().isTempBasalCapable; + } + return true; } @Override public boolean specialShowInListCondition() { - PumpInterface pump = configBuilderPlugin.getActivePump(); + PumpInterface pump = activePlugin.getActivePumpPlugin(); return pump == null || pump.getPumpDescription().isTempBasalCapable; } @@ -119,7 +123,7 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface { GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(); Profile profile = profileFunction.getProfile(); - PumpInterface pump = configBuilderPlugin.getActivePump(); + PumpInterface pump = activePlugin.getActivePump(); if (profile == null) { rxBus.send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.noprofileselected))); @@ -207,7 +211,7 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface { start = System.currentTimeMillis(); try { - determineBasalAdapterAMAJS.setData(profile, maxIob, maxBasal, minBg, maxBg, targetBg, configBuilderPlugin.getActivePump().getBaseBasalRate(), iobArray, glucoseStatus, mealData, + determineBasalAdapterAMAJS.setData(profile, maxIob, maxBasal, minBg, maxBg, targetBg, activePlugin.getActivePump().getBaseBasalRate(), iobArray, glucoseStatus, mealData, lastAutosensResult.ratio, //autosensDataRatio isTempTarget ); 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 c18c80a6db..0d5a6e2612 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 @@ -12,6 +12,7 @@ import info.nightscout.androidaps.data.MealData; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.interfaces.APSInterface; +import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; @@ -23,7 +24,6 @@ import info.nightscout.androidaps.plugins.aps.loop.ScriptReader; import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui; import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateResultGui; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; @@ -41,11 +41,12 @@ import static info.nightscout.androidaps.utils.HardLimits.verifyHardLimits; @Singleton public class OpenAPSMAPlugin extends PluginBase implements APSInterface { + private final RxBusWrapper rxBus; private final ConstraintChecker constraintChecker; private final ResourceHelper resourceHelper; private final ProfileFunction profileFunction; private final MainApp mainApp; - private final ConfigBuilderPlugin configBuilderPlugin; + private final ActivePluginProvider activePlugin; private final TreatmentsPlugin treatmentsPlugin; private final IobCobCalculatorPlugin iobCobCalculatorPlugin; @@ -57,12 +58,12 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface { @Inject public OpenAPSMAPlugin( AAPSLogger aapsLogger, - RxBusWrapper rxBusWrapper, + RxBusWrapper rxBus, ConstraintChecker constraintChecker, ResourceHelper resourceHelper, ProfileFunction profileFunction, MainApp mainApp, - ConfigBuilderPlugin configBuilderPlugin, + ActivePluginProvider activePlugin, TreatmentsPlugin treatmentsPlugin, IobCobCalculatorPlugin iobCobCalculatorPlugin ) { @@ -73,27 +74,32 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface { .shortName(R.string.oaps_shortname) .preferencesId(R.xml.pref_openapsma) .description(R.string.description_ma), - rxBusWrapper, aapsLogger + aapsLogger, resourceHelper ); this.constraintChecker = constraintChecker; this.resourceHelper = resourceHelper; this.profileFunction = profileFunction; this.mainApp = mainApp; - this.configBuilderPlugin = configBuilderPlugin; + this.rxBus = rxBus; + this.activePlugin = activePlugin; this.treatmentsPlugin = treatmentsPlugin; this.iobCobCalculatorPlugin = iobCobCalculatorPlugin; } @Override public boolean specialEnableCondition() { - PumpInterface pump = configBuilderPlugin.getActivePump(); - return pump == null || pump.getPumpDescription().isTempBasalCapable; + // main fail during init + if (activePlugin != null) { + PumpInterface pump = activePlugin.getActivePumpPlugin(); + return pump == null || pump.getPumpDescription().isTempBasalCapable; + } + return true; } @Override public boolean specialShowInListCondition() { - PumpInterface pump = configBuilderPlugin.getActivePump(); + PumpInterface pump = activePlugin.getActivePumpPlugin(); return pump == null || pump.getPumpDescription().isTempBasalCapable; } @@ -116,28 +122,28 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface { GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(); Profile profile = profileFunction.getProfile(); - PumpInterface pump = configBuilderPlugin.getActivePump(); + PumpInterface pump = activePlugin.getActivePumpPlugin(); if (profile == null) { - getRxBus().send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.noprofileselected))); + rxBus.send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.noprofileselected))); getAapsLogger().debug(LTag.APS, resourceHelper.gs(R.string.noprofileselected)); return; } if (pump == null) { - getRxBus().send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.nopumpselected))); + rxBus.send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.nopumpselected))); getAapsLogger().debug(LTag.APS, resourceHelper.gs(R.string.nopumpselected)); return; } if (!isEnabled(PluginType.APS)) { - getRxBus().send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openapsma_disabled))); + rxBus.send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openapsma_disabled))); getAapsLogger().debug(LTag.APS, resourceHelper.gs(R.string.openapsma_disabled)); return; } if (glucoseStatus == null) { - getRxBus().send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openapsma_noglucosedata))); + rxBus.send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openapsma_noglucosedata))); getAapsLogger().debug(LTag.APS, resourceHelper.gs(R.string.openapsma_noglucosedata)); return; } @@ -188,7 +194,7 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface { start = System.currentTimeMillis(); try { - determineBasalAdapterMAJS.setData(profile, maxIob, maxBasal, minBg, maxBg, targetBg, configBuilderPlugin.getActivePump().getBaseBasalRate(), iobTotal, glucoseStatus, mealData); + determineBasalAdapterMAJS.setData(profile, maxIob, maxBasal, minBg, maxBg, targetBg, activePlugin.getActivePump().getBaseBasalRate(), iobTotal, glucoseStatus, mealData); } catch (JSONException e) { FabricPrivacy.getInstance().logException(e); return; @@ -221,7 +227,7 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface { lastAPSResult = determineBasalResultMA; lastAPSRun = now; } - getRxBus().send(new EventOpenAPSUpdateGui()); + rxBus.send(new EventOpenAPSUpdateGui()); } 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 6b8034a038..f64ceca7c9 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 @@ -13,6 +13,7 @@ import info.nightscout.androidaps.data.MealData; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.interfaces.APSInterface; +import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.ConstraintsInterface; import info.nightscout.androidaps.interfaces.PluginBase; @@ -26,7 +27,6 @@ import info.nightscout.androidaps.plugins.aps.loop.ScriptReader; import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui; import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateResultGui; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; @@ -49,7 +49,8 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr private final ResourceHelper resourceHelper; private final ProfileFunction profileFunction; private final MainApp mainApp; - private final ConfigBuilderPlugin configBuilderPlugin; + private final RxBusWrapper rxBus; + private final ActivePluginProvider activePlugin; private final TreatmentsPlugin treatmentsPlugin; private final IobCobCalculatorPlugin iobCobCalculatorPlugin; @@ -62,15 +63,15 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr @Inject public OpenAPSSMBPlugin( AAPSLogger aapsLogger, - RxBusWrapper rxBusWrapper, + RxBusWrapper rxBus, ConstraintChecker constraintChecker, ResourceHelper resourceHelper, ProfileFunction profileFunction, MainApp mainApp, - ConfigBuilderPlugin configBuilderPlugin, + ActivePluginProvider activePlugin, TreatmentsPlugin treatmentsPlugin, IobCobCalculatorPlugin iobCobCalculatorPlugin - ) { + ) { super(new PluginDescription() .mainType(PluginType.APS) .fragmentClass(OpenAPSSMBFragment.class.getName()) @@ -78,27 +79,32 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr .shortName(R.string.smb_shortname) .preferencesId(R.xml.pref_openapssmb) .description(R.string.description_smb), - rxBusWrapper, aapsLogger + aapsLogger, resourceHelper ); this.constraintChecker = constraintChecker; this.resourceHelper = resourceHelper; this.profileFunction = profileFunction; + this.rxBus = rxBus; this.mainApp = mainApp; - this.configBuilderPlugin = configBuilderPlugin; + this.activePlugin = activePlugin; this.treatmentsPlugin = treatmentsPlugin; this.iobCobCalculatorPlugin = iobCobCalculatorPlugin; } @Override public boolean specialEnableCondition() { - PumpInterface pump = configBuilderPlugin.getActivePump(); - return pump == null || pump.getPumpDescription().isTempBasalCapable; + // main fail during init + if (activePlugin != null) { + PumpInterface pump = activePlugin.getActivePumpPlugin(); + return pump == null || pump.getPumpDescription().isTempBasalCapable; + } + return true; } @Override public boolean specialShowInListCondition() { - PumpInterface pump = configBuilderPlugin.getActivePump(); + PumpInterface pump = activePlugin.getActivePumpPlugin(); return pump == null || pump.getPumpDescription().isTempBasalCapable; } @@ -121,28 +127,28 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(); Profile profile = profileFunction.getProfile(); - PumpInterface pump = configBuilderPlugin.getActivePump(); + PumpInterface pump = activePlugin.getActivePump(); if (profile == null) { - getRxBus().send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.noprofileselected))); + rxBus.send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.noprofileselected))); getAapsLogger().debug(LTag.APS, resourceHelper.gs(R.string.noprofileselected)); return; } if (pump == null) { - getRxBus().send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.nopumpselected))); + rxBus.send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.nopumpselected))); getAapsLogger().debug(LTag.APS, resourceHelper.gs(R.string.nopumpselected)); return; } if (!isEnabled(PluginType.APS)) { - getRxBus().send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openapsma_disabled))); + rxBus.send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openapsma_disabled))); getAapsLogger().debug(LTag.APS, resourceHelper.gs(R.string.openapsma_disabled)); return; } if (glucoseStatus == null) { - getRxBus().send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openapsma_noglucosedata))); + rxBus.send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openapsma_noglucosedata))); getAapsLogger().debug(LTag.APS, resourceHelper.gs(R.string.openapsma_noglucosedata)); return; } @@ -198,7 +204,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr if (constraintChecker.isAutosensModeEnabled().value()) { AutosensData autosensData = iobCobCalculatorPlugin.getLastAutosensDataSynchronized("OpenAPSPlugin"); if (autosensData == null) { - getRxBus().send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openaps_noasdata))); + rxBus.send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openaps_noasdata))); return; } lastAutosensResult = autosensData.autosensResult; @@ -228,7 +234,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr start = System.currentTimeMillis(); try { - determineBasalAdapterSMBJS.setData(profile, maxIob, maxBasal, minBg, maxBg, targetBg, configBuilderPlugin.getActivePump().getBaseBasalRate(), iobArray, glucoseStatus, mealData, + determineBasalAdapterSMBJS.setData(profile, maxIob, maxBasal, minBg, maxBg, targetBg, activePlugin.getActivePump().getBaseBasalRate(), iobArray, glucoseStatus, mealData, lastAutosensResult.ratio, //autosensDataRatio isTempTarget, smbAllowed.value(), @@ -269,7 +275,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr lastAPSResult = determineBasalResultSMB; lastAPSRun = now; } - getRxBus().send(new EventOpenAPSUpdateGui()); + rxBus.send(new EventOpenAPSUpdateGui()); //deviceStatus.suggested = determineBasalResultAMA.json; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt index 8ca8162e7d..10abea34cf 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt @@ -136,10 +136,10 @@ class ConfigBuilderFragment : DaggerFragment() { } enabledExclusive.setOnClickListener { - plugin.switchAllowed(if (enabledExclusive.visibility == View.VISIBLE) enabledExclusive.isChecked else enabledInclusive.isChecked, fragment.activity, pluginType) + configBuilderPlugin.switchAllowed(plugin, if (enabledExclusive.visibility == View.VISIBLE) enabledExclusive.isChecked else enabledInclusive.isChecked, fragment.activity, pluginType) } enabledInclusive.setOnClickListener { - plugin.switchAllowed(if (enabledExclusive.visibility == View.VISIBLE) enabledExclusive.isChecked else enabledInclusive.isChecked, fragment.activity, pluginType) + configBuilderPlugin.switchAllowed(plugin, if (enabledExclusive.visibility == View.VISIBLE) enabledExclusive.isChecked else enabledInclusive.isChecked, fragment.activity, pluginType) } pluginPreferences.setOnClickListener { 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 bb2ae49bb6..8f4c66ac98 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 @@ -1,6 +1,8 @@ package info.nightscout.androidaps.plugins.configBuilder; +import androidx.annotation.NonNull; import androidx.annotation.Nullable; +import androidx.fragment.app.FragmentActivity; import org.jetbrains.annotations.NotNull; @@ -13,6 +15,8 @@ import dagger.Lazy; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.events.EventAppInitialized; +import info.nightscout.androidaps.events.EventConfigBuilderChange; +import info.nightscout.androidaps.events.EventRebuildTabs; import info.nightscout.androidaps.interfaces.APSInterface; import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.interfaces.BgSourceInterface; @@ -24,30 +28,45 @@ import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.SensitivityInterface; +import info.nightscout.androidaps.interfaces.TreatmentsInterface; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.insulin.InsulinOrefRapidActingPlugin; import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin; import info.nightscout.androidaps.plugins.profile.ns.NSProfilePlugin; import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin; import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref0Plugin; -import info.nightscout.androidaps.queue.CommandQueue; +import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin; +import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; +import info.nightscout.androidaps.utils.OKDialog; +import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.sharedPreferences.SP; /** * Created by mike on 05.08.2016. */ @Singleton -public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvider, CommandQueueProvider { +public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvider { private static ConfigBuilderPlugin configBuilderPlugin; private final SP sp; - + private final AAPSLogger aapsLogger; + private final RxBusWrapper rxBus; + private final ResourceHelper resourceHelper; + private final CommandQueueProvider commandQueue; + private final NSProfilePlugin nsProfilePlugin; /** * @deprecated Use dagger to get an instance */ + + @Deprecated + public CommandQueueProvider getCommandQueue() { + if (commandQueue == null) + throw new IllegalStateException("Accessing commandQueue before first instantiation"); + return commandQueue; + } + @Deprecated static public ConfigBuilderPlugin getPlugin() { if (configBuilderPlugin == null) @@ -61,11 +80,12 @@ public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvi private APSInterface activeAPS; private InsulinInterface activeInsulin; private SensitivityInterface activeSensitivity; + private Lazy treatmentsPlugin; + private Lazy sensitivityOref0Plugin; + private Lazy sensitivityOref1Plugin; private ArrayList pluginList; - private CommandQueue commandQueue = new CommandQueue(); - private final Lazy insulinOrefRapidActingPlugin; private final Lazy localProfilePlugin; private final Lazy virtualPumpPlugin; @@ -82,9 +102,16 @@ public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvi Lazy insulinOrefRapidActingPlugin, Lazy localProfilePlugin, Lazy virtualPumpPlugin, + Lazy treatmentsPlugin, + Lazy sensitivityOref0Plugin, + Lazy sensitivityOref1Plugin, SP sp, RxBusWrapper rxBus, - AAPSLogger aapsLogger) { + AAPSLogger aapsLogger, + ResourceHelper resourceHelper, + CommandQueueProvider commandQueue, + NSProfilePlugin nsProfilePlugin + ) { super(new PluginDescription() .mainType(PluginType.GENERAL) .fragmentClass(ConfigBuilderFragment.class.getName()) @@ -94,12 +121,20 @@ public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvi .pluginName(R.string.configbuilder) .shortName(R.string.configbuilder_shortname) .description(R.string.description_config_builder), - rxBus, aapsLogger + aapsLogger, resourceHelper ); this.insulinOrefRapidActingPlugin = insulinOrefRapidActingPlugin; this.localProfilePlugin = localProfilePlugin; this.virtualPumpPlugin = virtualPumpPlugin; + this.treatmentsPlugin = treatmentsPlugin; + this.sensitivityOref0Plugin = sensitivityOref0Plugin; + this.sensitivityOref1Plugin = sensitivityOref1Plugin; this.sp = sp; + this.rxBus = rxBus; + this.aapsLogger = aapsLogger; + this.resourceHelper = resourceHelper; + this.commandQueue = commandQueue; + this.nsProfilePlugin = nsProfilePlugin; configBuilderPlugin = this; // TODO: only while transitioning to Dagger } @@ -108,7 +143,7 @@ public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvi upgradeSettings(); loadSettings(); setAlwaysEnabledPluginsEnabled(); - RxBus.Companion.getINSTANCE().send(new EventAppInitialized()); + rxBus.send(new EventAppInitialized()); } private void setAlwaysEnabledPluginsEnabled() { @@ -246,39 +281,58 @@ public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvi } } - @Override public CommandQueue getCommandQueue() { - return commandQueue; - } - - @Override @Nullable + @Override + @Nullable public BgSourceInterface getActiveBgSource() { return activeBgSource; } - @Override @NotNull + @Override + @NotNull public ProfileInterface getActiveProfileInterface() { if (activeProfile != null) return activeProfile; else return localProfilePlugin.get(); } - @Override @Nullable + @Override + @NotNull public InsulinInterface getActiveInsulin() { + if (activeInsulin == null) + return insulinOrefRapidActingPlugin.get(); return activeInsulin; } - @Override @Nullable + @Override + @Nullable public APSInterface getActiveAPS() { return activeAPS; } - @Override @Nullable + @Override + @NotNull public PumpInterface getActivePump() { + if (activePump == null) + throw new IllegalStateException("No pump selected"); return activePump; } - @Override @Nullable + @Override + @Nullable + public PumpInterface getActivePumpPlugin() { + return activePump; + } + + @Override + @NotNull public SensitivityInterface getActiveSensitivity() { - return activeSensitivity; + if (activeSensitivity == null) + return sensitivityOref1Plugin.get(); + else + return activeSensitivity; + } + + @NonNull @Override public TreatmentsInterface getActiveTreatments() { + return treatmentsPlugin.get(); } public void logPluginStatus() { @@ -318,8 +372,8 @@ public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvi pluginsInCategory = MainApp.getSpecificPluginsList(PluginType.SENSITIVITY); activeSensitivity = (SensitivityInterface) getTheOneEnabledInArray(pluginsInCategory, PluginType.SENSITIVITY); if (activeSensitivity == null) { - activeSensitivity = SensitivityOref0Plugin.getPlugin(); - SensitivityOref0Plugin.getPlugin().setPluginEnabled(PluginType.SENSITIVITY, true); + activeSensitivity = sensitivityOref0Plugin.get(); + sensitivityOref0Plugin.get().setPluginEnabled(PluginType.SENSITIVITY, true); getAapsLogger().debug(LTag.CONFIGBUILDER, "Defaulting SensitivityOref0Plugin"); } this.setFragmentVisiblities(((PluginBase) activeSensitivity).getName(), pluginsInCategory, PluginType.SENSITIVITY); @@ -359,13 +413,6 @@ public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvi return this.determineActivePlugin(pluginsInCategory, pluginType); } - private T determineActivePlugin(PluginType pluginType) { - ArrayList pluginsInCategory; - pluginsInCategory = MainApp.getSpecificPluginsList(pluginType); - - return this.determineActivePlugin(pluginsInCategory, pluginType); - } - /** * disables the visibility for all fragments of Plugins in the given pluginsInCategory * with the given PluginType which are not equally named to the Plugin implementing the @@ -419,6 +466,45 @@ public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvi return found; } + // Ask when switching to physical pump plugin + public void switchAllowed(@NonNull PluginBase changedPlugin, boolean newState, @Nullable FragmentActivity activity, @NonNull PluginType type) { + if (changedPlugin.getType() == PluginType.PUMP && !changedPlugin.getName().equals(resourceHelper.gs(R.string.virtualpump))) + confirmPumpPluginActivation(changedPlugin, newState, activity, type); + else + performPluginSwitch(changedPlugin, newState, type); + } + + private void confirmPumpPluginActivation(@NonNull PluginBase changedPlugin, boolean newState, @Nullable FragmentActivity activity, @NonNull PluginType type) { + if (type == PluginType.PUMP) { + boolean allowHardwarePump = sp.getBoolean("allow_hardware_pump", false); + if (allowHardwarePump || activity == null) { + performPluginSwitch(changedPlugin, newState, type); + } else { + OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.allow_hardware_pump_text), () -> { + performPluginSwitch(changedPlugin, newState, type); + sp.putBoolean("allow_hardware_pump", true); + aapsLogger.debug(LTag.PUMP, "First time HW pump allowed!"); + }, () -> { + rxBus.send(new EventConfigBuilderUpdateGui()); + aapsLogger.debug(LTag.PUMP, "User does not allow switching to HW pump!"); + }); + } + } else { + performPluginSwitch(changedPlugin, newState, type); + } + } + + private void performPluginSwitch(PluginBase changedPlugin, boolean enabled, @NonNull PluginType type) { + setPluginEnabled(type, enabled); + setFragmentVisible(type, enabled); + processOnEnabledCategoryChanged(changedPlugin, type); + storeSettings("CheckedCheckboxEnabled"); + rxBus.send(new EventRebuildTabs()); + rxBus.send(new EventConfigBuilderChange()); + rxBus.send(new EventConfigBuilderUpdateGui()); + logPluginStatus(); + } + public void processOnEnabledCategoryChanged(PluginBase changedPlugin, PluginType type) { ArrayList pluginsInCategory = null; switch (type) { @@ -461,13 +547,13 @@ public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvi } } else { // enable first plugin in list if (type == PluginType.PUMP) - VirtualPumpPlugin.Companion.getPlugin().setPluginEnabled(type, true); + virtualPumpPlugin.get().setPluginEnabled(type, true); else if (type == PluginType.INSULIN) insulinOrefRapidActingPlugin.get().setPluginEnabled(type, true); else if (type == PluginType.SENSITIVITY) - SensitivityOref0Plugin.getPlugin().setPluginEnabled(type, true); + sensitivityOref0Plugin.get().setPluginEnabled(type, true); else if (type == PluginType.PROFILE) - NSProfilePlugin.getPlugin().setPluginEnabled(type, true); + nsProfilePlugin.setPluginEnabled(type, true); else pluginsInCategory.get(0).setPluginEnabled(type, true); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctionImplementation.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctionImplementation.kt index 68d8cfef50..dbc9d29e79 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctionImplementation.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctionImplementation.kt @@ -13,8 +13,7 @@ import javax.inject.Singleton @Singleton class ProfileFunctionImplementation @Inject constructor( - private val sp: SP, - private val configBuilderPlugin: ConfigBuilderPlugin + private val sp: SP ) : ProfileFunction { override fun getProfileName(): String = @@ -50,7 +49,6 @@ class ProfileFunctionImplementation @Inject constructor( profileSwitch.source = Source.USER profileSwitch.profileName = profileName profileSwitch.profileJson = profile.data.toString() - profileSwitch.profilePlugin = configBuilderPlugin.activeProfileInterface::class.java.name profileSwitch.durationInMinutes = duration profileSwitch.isCPP = percentage != 100 || timeShift != 0 profileSwitch.timeshift = timeShift diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPlugin.kt index 90d3be398f..197bb1a1f8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPlugin.kt @@ -1,17 +1,12 @@ package info.nightscout.androidaps.plugins.constraints.dstHelper -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R -import info.nightscout.androidaps.interfaces.Constraint -import info.nightscout.androidaps.interfaces.ConstraintsInterface -import info.nightscout.androidaps.interfaces.PluginBase -import info.nightscout.androidaps.interfaces.PluginDescription -import info.nightscout.androidaps.interfaces.PluginType +import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationWithAction @@ -24,29 +19,31 @@ import javax.inject.Singleton @Singleton class DstHelperPlugin @Inject constructor( + private var injector: HasAndroidInjector, aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, - var resourceHelper: ResourceHelper, - var mainApp: MainApp, - var sp: SP, - var configBuilderPlugin: ConfigBuilderPlugin, - var loopPlugin: LoopPlugin - ) : PluginBase(PluginDescription() + private var rxBus: RxBusWrapper, + resourceHelper: ResourceHelper, + private var sp: SP, + private var activePlugin: ActivePluginProvider, + private var loopPlugin: LoopPlugin +) : PluginBase(PluginDescription() .mainType(PluginType.CONSTRAINTS) .neverVisible(true) .alwaysEnabled(true) .showInList(false) .pluginName(R.string.dst_plugin_name), - rxBus, aapsLogger + aapsLogger, resourceHelper ), ConstraintsInterface { - private val DISABLE_TIMEFRAME_HOURS = -3 - private val WARN_PRIOR_TIMEFRAME_HOURS = 12 + companion object { + private const val DISABLE_TIME_FRAME_HOURS = -3 + private const val WARN_PRIOR_TIME_FRAME_HOURS = 12 + } //Return false if time to DST change happened in the last 3 hours. override fun isLoopInvocationAllowed(value: Constraint): Constraint { - val pump = configBuilderPlugin.activePump - if (pump == null || pump.canHandleDST()) { + val pump = activePlugin.activePumpPlugin ?: return value + if (pump.canHandleDST()) { aapsLogger.debug(LTag.CONSTRAINTS, "Pump can handle DST") return value } @@ -54,7 +51,7 @@ class DstHelperPlugin @Inject constructor( if (willBeDST(cal)) { val snoozedTo: Long = sp.getLong(R.string.key_snooze_dst_in24h, 0L) if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo) { - val notification = NotificationWithAction(mainApp, Notification.DST_IN_24H, resourceHelper.gs(R.string.dst_in_24h_warning), Notification.LOW) + val notification = NotificationWithAction(injector, Notification.DST_IN_24H, resourceHelper.gs(R.string.dst_in_24h_warning), Notification.LOW) notification.action(R.string.snooze, Runnable { sp.putLong(R.string.key_snooze_dst_in24h, System.currentTimeMillis() + T.hours(24).msecs()) }) @@ -69,7 +66,7 @@ class DstHelperPlugin @Inject constructor( if (!loopPlugin.isSuspended) { val snoozedTo: Long = sp.getLong(R.string.key_snooze_loopdisabled, 0L) if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo) { - val notification = NotificationWithAction(mainApp, Notification.DST_LOOP_DISABLED, resourceHelper.gs(R.string.dst_loop_disabled_warning), Notification.LOW) + val notification = NotificationWithAction(injector, Notification.DST_LOOP_DISABLED, resourceHelper.gs(R.string.dst_loop_disabled_warning), Notification.LOW) notification.action(R.string.snooze, Runnable { sp.putLong(R.string.key_snooze_loopdisabled, System.currentTimeMillis() + T.hours(24).msecs()) }) @@ -85,13 +82,13 @@ class DstHelperPlugin @Inject constructor( fun wasDST(now: Calendar): Boolean { val ago = now.clone() as Calendar - ago.add(Calendar.HOUR, DISABLE_TIMEFRAME_HOURS) + ago.add(Calendar.HOUR, DISABLE_TIME_FRAME_HOURS) return now[Calendar.DST_OFFSET] != ago[Calendar.DST_OFFSET] } fun willBeDST(now: Calendar): Boolean { val ago = now.clone() as Calendar - ago.add(Calendar.HOUR, WARN_PRIOR_TIMEFRAME_HOURS) + ago.add(Calendar.HOUR, WARN_PRIOR_TIME_FRAME_HOURS) return now[Calendar.DST_OFFSET] != ago[Calendar.DST_OFFSET] } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPlugin.kt index 5ea50555c0..4c62bfc319 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPlugin.kt @@ -3,6 +3,7 @@ package info.nightscout.androidaps.plugins.constraints.objectives import android.app.Activity import com.google.common.base.Charsets import com.google.common.hash.Hashing +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.BuildConfig import info.nightscout.androidaps.Config import info.nightscout.androidaps.R @@ -12,7 +13,6 @@ import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.constraints.objectives.objectives.* import info.nightscout.androidaps.utils.DateUtil @@ -25,10 +25,11 @@ import javax.inject.Singleton @Singleton class ObjectivesPlugin @Inject constructor( - private val sp: SP, - private val resourceHelper: ResourceHelper, + private val injector: HasAndroidInjector, + aapsLogger: AAPSLogger, + resourceHelper: ResourceHelper, private val configBuilderPlugin: ConfigBuilderPlugin, - rxBus: RxBusWrapper, aapsLogger: AAPSLogger + private val sp: SP ) : PluginBase(PluginDescription() .mainType(PluginType.CONSTRAINTS) @@ -38,21 +39,23 @@ class ObjectivesPlugin @Inject constructor( .pluginName(R.string.objectives) .shortName(R.string.objectives_shortname) .description(R.string.description_objectives), - rxBus, aapsLogger + aapsLogger, resourceHelper ), ConstraintsInterface { var objectives: MutableList = ArrayList() - val FIRST_OBJECTIVE = 0 - val USAGE_OBJECTIVE = 1 - val EXAM_OBJECTIVE = 2 - val OPENLOOP_OBJECTIVE = 3 - val MAXBASAL_OBJECTIVE = 4 - val MAXIOB_ZERO_CL_OBJECTIVE = 5 - val MAXIOB_OBJECTIVE = 6 - val AUTOSENS_OBJECTIVE = 7 - val AMA_OBJECTIVE = 8 - val SMB_OBJECTIVE = 9 + companion object { + const val FIRST_OBJECTIVE = 0 + @Suppress("unused") const val USAGE_OBJECTIVE = 1 + @Suppress("unused") const val EXAM_OBJECTIVE = 2 + @Suppress("unused") const val OPENLOOP_OBJECTIVE = 3 + @Suppress("unused") const val MAXBASAL_OBJECTIVE = 4 + const val MAXIOB_ZERO_CL_OBJECTIVE = 5 + @Suppress("unused") const val MAXIOB_OBJECTIVE = 6 + const val AUTOSENS_OBJECTIVE = 7 + const val AMA_OBJECTIVE = 8 + const val SMB_OBJECTIVE = 9 + } override fun onStart() { super.onStart() @@ -61,7 +64,7 @@ class ObjectivesPlugin @Inject constructor( } override fun specialEnableCondition(): Boolean { - val pump = configBuilderPlugin.activePump + val pump = configBuilderPlugin.activePumpPlugin return pump == null || pump.pumpDescription.isTempBasalCapable } @@ -92,7 +95,7 @@ class ObjectivesPlugin @Inject constructor( objectives.add(Objective2()) objectives.add(Objective3()) objectives.add(Objective4()) - objectives.add(Objective5()) + objectives.add(Objective5(injector)) objectives.add(Objective6()) objectives.add(Objective7()) objectives.add(Objective8()) @@ -118,7 +121,7 @@ class ObjectivesPlugin @Inject constructor( fun completeObjectives(activity: Activity, request: String) { val requestCode = sp.getString(R.string.key_objectives_request_code, "") - var url = sp.getString(R.string.key_nsclientinternal_url, "").toLowerCase() + var url = sp.getString(R.string.key_nsclientinternal_url, "").toLowerCase(Locale.getDefault()) if (!url.endsWith("/")) url = "$url/" @Suppress("DEPRECATION") val hashNS = Hashing.sha1().hashString(url + BuildConfig.APPLICATION_ID + "/" + requestCode, Charsets.UTF_8).toString() if (request.equals(hashNS.substring(0, 10), ignoreCase = true)) { @@ -181,5 +184,4 @@ class ObjectivesPlugin @Inject constructor( maxIob.set(0.0, resourceHelper.gs(R.string.objectivenotfinished, MAXIOB_ZERO_CL_OBJECTIVE + 1), this) return maxIob } - } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective0.java b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective0.java index 0b30ea650d..b17f6dc9cb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective0.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective0.java @@ -6,13 +6,13 @@ import javax.inject.Inject; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.interfaces.APSInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin; +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DateUtil; @@ -24,6 +24,8 @@ public class Objective0 extends Objective { @Inject VirtualPumpPlugin virtualPumpPlugin; @Inject TreatmentsPlugin treatmentsPlugin; @Inject LoopPlugin loopPlugin; + @Inject NSClientPlugin nsClientPlugin; + @Inject IobCobCalculatorPlugin iobCobCalculatorPlugin; public Objective0() { super("config", R.string.objectives_0_objective, R.string.objectives_0_gate); @@ -41,7 +43,7 @@ public class Objective0 extends Objective { tasks.add(new Task(R.string.nsclienthaswritepermission) { @Override public boolean isCompleted() { - return NSClientPlugin.getPlugin().hasWritePermission(); + return nsClientPlugin.hasWritePermission(); } }); tasks.add(new Task(R.string.virtualpump_uploadstatus_title) { @@ -64,7 +66,7 @@ public class Objective0 extends Objective { tasks.add(new Task(R.string.hasbgdata) { @Override public boolean isCompleted() { - return DatabaseHelper.lastBg() != null; + return iobCobCalculatorPlugin.lastBg() != null; } }); tasks.add(new Task(R.string.loopenabled) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective3.java b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective3.java index 720afea51f..6dca69d88f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective3.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective3.java @@ -18,6 +18,7 @@ public class Objective3 extends Objective { @Inject SP sp; @Inject ObjectivesPlugin objectivesPlugin; @Inject ResourceHelper resourceHelper; + @Inject NSClientPlugin nsClientPlugin; private final int MANUAL_ENACTS_NEEDED = 20; @@ -49,7 +50,7 @@ public class Objective3 extends Objective { @Override public boolean specialActionEnabled() { - return NSClientPlugin.getPlugin().nsClientService.isConnected && NSClientPlugin.getPlugin().nsClientService.hasWriteAuth; + return nsClientPlugin.nsClientService.isConnected && nsClientPlugin.nsClientService.hasWriteAuth; } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective5.java b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective5.java index 9a55ca077f..ca4e389da2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective5.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective5.java @@ -4,7 +4,7 @@ import java.util.List; import javax.inject.Inject; -import info.nightscout.androidaps.MainApp; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.R; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin; @@ -13,9 +13,9 @@ import info.nightscout.androidaps.utils.T; public class Objective5 extends Objective { @Inject SafetyPlugin safetyPlugin; - public Objective5() { + public Objective5(HasAndroidInjector injector) { super("maxiobzero", R.string.objectives_maxiobzero_objective, R.string.objectives_maxiobzero_gate); - MainApp.instance().androidInjector().inject(this); // TODO inject or pass itno constructor once AutomationPlugin is prepared for Dagger + injector.androidInjector().inject(this); } @Override 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 16006bd40b..5701e32abf 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 @@ -1,5 +1,7 @@ package info.nightscout.androidaps.plugins.constraints.safety; +import androidx.annotation.NonNull; + import javax.inject.Inject; import javax.inject.Singleton; @@ -7,6 +9,7 @@ import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; +import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.interfaces.BgSourceInterface; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.ConstraintsInterface; @@ -19,9 +22,7 @@ import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin; 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.bus.RxBusWrapper; -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; @@ -29,132 +30,133 @@ import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin; import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.HardLimits; import info.nightscout.androidaps.utils.Round; -import info.nightscout.androidaps.utils.SP; +import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.sharedPreferences.SP; @Singleton public class SafetyPlugin extends PluginBase implements ConstraintsInterface { - //TODO: dagger + // TODO: dagger + @Inject SP sp; + @Inject RxBusWrapper rxBus; + @Inject ResourceHelper resourceHelper; + @Inject ConstraintChecker constraintChecker; + @Inject OpenAPSAMAPlugin openAPSAMAPlugin; + @Inject OpenAPSMAPlugin openAPSMAPlugin; + @Inject OpenAPSSMBPlugin openAPSSMBPlugin; + @Inject SensitivityOref1Plugin sensitivityOref1Plugin; + @Inject ActivePluginProvider activePlugin; @Inject - OpenAPSAMAPlugin openAPSAMAPlugin; - - @Inject - OpenAPSMAPlugin openAPSMAPlugin; - - @Inject - OpenAPSSMBPlugin openAPSSMBPlugin; - - @Inject - public SafetyPlugin(RxBusWrapper rxBusWrapper, AAPSLogger aapsLogger) { + public SafetyPlugin(AAPSLogger aapsLogger, ResourceHelper resourceHelper) { super(new PluginDescription() .mainType(PluginType.CONSTRAINTS) .neverVisible(true) .alwaysEnabled(true) .showInList(false) .pluginName(R.string.safety) - .preferencesId(R.xml.pref_safety), rxBusWrapper, aapsLogger + .preferencesId(R.xml.pref_safety), aapsLogger, resourceHelper ); } /** * Constraints interface **/ - @Override - public Constraint isLoopInvocationAllowed(Constraint value) { - if (!ConfigBuilderPlugin.getPlugin().getActivePump().getPumpDescription().isTempBasalCapable) - value.set(false, MainApp.gs(R.string.pumpisnottempbasalcapable), this); + @NonNull @Override + public Constraint isLoopInvocationAllowed(@NonNull Constraint value) { + if (!activePlugin.getActivePumpPlugin().getPumpDescription().isTempBasalCapable) + value.set(false, resourceHelper.gs(R.string.pumpisnottempbasalcapable), this); return value; } - @Override - public Constraint isClosedLoopAllowed(Constraint value) { - String mode = SP.getString(R.string.key_aps_mode, "open"); + @NonNull @Override + public Constraint isClosedLoopAllowed(@NonNull Constraint value) { + String mode = sp.getString(R.string.key_aps_mode, "open"); if (!mode.equals("closed")) - value.set(false, MainApp.gs(R.string.closedmodedisabledinpreferences), this); + value.set(false, resourceHelper.gs(R.string.closedmodedisabledinpreferences), this); if (!MainApp.isEngineeringModeOrRelease()) { if (value.value()) { - Notification n = new Notification(Notification.TOAST_ALARM, MainApp.gs(R.string.closed_loop_disabled_on_dev_branch), Notification.NORMAL); - RxBus.Companion.getINSTANCE().send(new EventNewNotification(n)); + Notification n = new Notification(Notification.TOAST_ALARM, resourceHelper.gs(R.string.closed_loop_disabled_on_dev_branch), Notification.NORMAL); + rxBus.send(new EventNewNotification(n)); } - value.set(false, MainApp.gs(R.string.closed_loop_disabled_on_dev_branch), this); + value.set(false, resourceHelper.gs(R.string.closed_loop_disabled_on_dev_branch), this); } return value; } - @Override - public Constraint isAutosensModeEnabled(Constraint value) { - boolean enabled = SP.getBoolean(R.string.key_openapsama_useautosens, false); + @NonNull @Override + public Constraint isAutosensModeEnabled(@NonNull Constraint value) { + boolean enabled = sp.getBoolean(R.string.key_openapsama_useautosens, false); if (!enabled) - value.set(false, MainApp.gs(R.string.autosensdisabledinpreferences), this); + value.set(false, resourceHelper.gs(R.string.autosensdisabledinpreferences), this); return value; } - @Override - public Constraint isSMBModeEnabled(Constraint value) { - boolean enabled = SP.getBoolean(R.string.key_use_smb, false); + @NonNull @Override + public Constraint isSMBModeEnabled(@NonNull Constraint value) { + boolean enabled = sp.getBoolean(R.string.key_use_smb, false); if (!enabled) - value.set(false, MainApp.gs(R.string.smbdisabledinpreferences), this); - Constraint closedLoop = ConstraintChecker.getInstance().isClosedLoopAllowed(); + value.set(false, resourceHelper.gs(R.string.smbdisabledinpreferences), this); + Constraint closedLoop = constraintChecker.isClosedLoopAllowed(); if (!closedLoop.value()) - value.set(false, MainApp.gs(R.string.smbnotallowedinopenloopmode), this); + value.set(false, resourceHelper.gs(R.string.smbnotallowedinopenloopmode), this); return value; } - @Override - public Constraint isUAMEnabled(Constraint value) { - boolean enabled = SP.getBoolean(R.string.key_use_uam, false); + @NonNull @Override + public Constraint isUAMEnabled(@NonNull Constraint value) { + boolean enabled = sp.getBoolean(R.string.key_use_uam, false); if (!enabled) - value.set(false, MainApp.gs(R.string.uamdisabledinpreferences), this); - boolean oref1Enabled = SensitivityOref1Plugin.getPlugin().isEnabled(PluginType.SENSITIVITY); + value.set(false, resourceHelper.gs(R.string.uamdisabledinpreferences), this); + boolean oref1Enabled = sensitivityOref1Plugin.isEnabled(PluginType.SENSITIVITY); if (!oref1Enabled) - value.set(false, MainApp.gs(R.string.uamdisabledoref1notselected), this); + value.set(false, resourceHelper.gs(R.string.uamdisabledoref1notselected), this); return value; } - @Override - public Constraint isAdvancedFilteringEnabled(Constraint value) { - BgSourceInterface bgSource = ConfigBuilderPlugin.getPlugin().getActiveBgSource(); + @NonNull @Override + public Constraint isAdvancedFilteringEnabled(@NonNull Constraint value) { + BgSourceInterface bgSource = activePlugin.getActiveBgSource(); if (bgSource != null) { if (!bgSource.advancedFilteringSupported()) - value.set(false, MainApp.gs(R.string.smbalwaysdisabled), this); + value.set(false, resourceHelper.gs(R.string.smbalwaysdisabled), this); } return value; } - @Override - public Constraint applyBasalConstraints(Constraint absoluteRate, Profile profile) { + @NonNull @Override + public Constraint applyBasalConstraints(Constraint absoluteRate, @NonNull Profile profile) { - absoluteRate.setIfGreater(0d, String.format(MainApp.gs(R.string.limitingbasalratio), 0d, MainApp.gs(R.string.itmustbepositivevalue)), this); + absoluteRate.setIfGreater(0d, String.format(resourceHelper.gs(R.string.limitingbasalratio), 0d, resourceHelper.gs(R.string.itmustbepositivevalue)), this); if (Config.APS) { - double maxBasal = SP.getDouble(R.string.key_openapsma_max_basal, 1d); + double maxBasal = sp.getDouble(R.string.key_openapsma_max_basal, 1d); if (maxBasal < profile.getMaxDailyBasal()) { maxBasal = profile.getMaxDailyBasal(); - absoluteRate.addReason(MainApp.gs(R.string.increasingmaxbasal), this); + absoluteRate.addReason(resourceHelper.gs(R.string.increasingmaxbasal), this); } - absoluteRate.setIfSmaller(maxBasal, String.format(MainApp.gs(R.string.limitingbasalratio), maxBasal, MainApp.gs(R.string.maxvalueinpreferences)), this); + absoluteRate.setIfSmaller(maxBasal, String.format(resourceHelper.gs(R.string.limitingbasalratio), maxBasal, resourceHelper.gs(R.string.maxvalueinpreferences)), this); // Check percentRate but absolute rate too, because we know real current basal in pump - Double maxBasalMult = SP.getDouble(R.string.key_openapsama_current_basal_safety_multiplier, 4d); + Double maxBasalMult = sp.getDouble(R.string.key_openapsama_current_basal_safety_multiplier, 4d); double maxFromBasalMult = Math.floor(maxBasalMult * profile.getBasal() * 100) / 100; - absoluteRate.setIfSmaller(maxFromBasalMult, String.format(MainApp.gs(R.string.limitingbasalratio), maxFromBasalMult, MainApp.gs(R.string.maxbasalmultiplier)), this); + absoluteRate.setIfSmaller(maxFromBasalMult, String.format(resourceHelper.gs(R.string.limitingbasalratio), maxFromBasalMult, resourceHelper.gs(R.string.maxbasalmultiplier)), this); - Double maxBasalFromDaily = SP.getDouble(R.string.key_openapsama_max_daily_safety_multiplier, 3d); + Double maxBasalFromDaily = sp.getDouble(R.string.key_openapsama_max_daily_safety_multiplier, 3d); double maxFromDaily = Math.floor(profile.getMaxDailyBasal() * maxBasalFromDaily * 100) / 100; - absoluteRate.setIfSmaller(maxFromDaily, String.format(MainApp.gs(R.string.limitingbasalratio), maxFromDaily, MainApp.gs(R.string.maxdailybasalmultiplier)), this); + absoluteRate.setIfSmaller(maxFromDaily, String.format(resourceHelper.gs(R.string.limitingbasalratio), maxFromDaily, resourceHelper.gs(R.string.maxdailybasalmultiplier)), this); } - absoluteRate.setIfSmaller(HardLimits.maxBasal(), String.format(MainApp.gs(R.string.limitingbasalratio), HardLimits.maxBasal(), MainApp.gs(R.string.hardlimit)), this); + absoluteRate.setIfSmaller(HardLimits.maxBasal(), String.format(resourceHelper.gs(R.string.limitingbasalratio), HardLimits.maxBasal(), resourceHelper.gs(R.string.hardlimit)), this); - PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump(); + PumpInterface pump = activePlugin.getActivePumpPlugin(); // check for pump max if (pump != null && pump.getPumpDescription().tempBasalStyle == PumpDescription.ABSOLUTE) { double pumpLimit = pump.getPumpDescription().pumpType.getTbrSettings().getMaxDose(); - absoluteRate.setIfSmaller(pumpLimit, String.format(MainApp.gs(R.string.limitingbasalratio), pumpLimit, MainApp.gs(R.string.pumplimit)), this); + absoluteRate.setIfSmaller(pumpLimit, String.format(resourceHelper.gs(R.string.limitingbasalratio), pumpLimit, resourceHelper.gs(R.string.pumplimit)), this); } // do rounding @@ -164,7 +166,7 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface { return absoluteRate; } - @Override + @NonNull @Override public Constraint applyBasalPercentConstraints(Constraint percentRate, Profile profile) { Double currentBasal = profile.getBasal(); @@ -176,7 +178,7 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface { applyBasalConstraints(absoluteConstraint, profile); percentRate.copyReasons(absoluteConstraint); - PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump(); + PumpInterface pump = activePlugin.getActivePumpPlugin(); Integer percentRateAfterConst = Double.valueOf(absoluteConstraint.value() / currentBasal * 100).intValue(); if (pump != null) { @@ -186,75 +188,75 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface { percentRateAfterConst = Round.floorTo((double) percentRateAfterConst, (double) pump.getPumpDescription().tempPercentStep).intValue(); } - percentRate.set(percentRateAfterConst, String.format(MainApp.gs(R.string.limitingpercentrate), percentRateAfterConst, MainApp.gs(R.string.pumplimit)), this); + percentRate.set(percentRateAfterConst, String.format(resourceHelper.gs(R.string.limitingpercentrate), percentRateAfterConst, resourceHelper.gs(R.string.pumplimit)), this); if (pump != null && pump.getPumpDescription().tempBasalStyle == PumpDescription.PERCENT) { double pumpLimit = pump.getPumpDescription().pumpType.getTbrSettings().getMaxDose(); - percentRate.setIfSmaller((int) pumpLimit, String.format(MainApp.gs(R.string.limitingbasalratio), pumpLimit, MainApp.gs(R.string.pumplimit)), this); + percentRate.setIfSmaller((int) pumpLimit, String.format(resourceHelper.gs(R.string.limitingbasalratio), pumpLimit, resourceHelper.gs(R.string.pumplimit)), this); } return percentRate; } - @Override + @NonNull @Override public Constraint applyBolusConstraints(Constraint insulin) { - insulin.setIfGreater(0d, String.format(MainApp.gs(R.string.limitingbolus), 0d, MainApp.gs(R.string.itmustbepositivevalue)), this); + insulin.setIfGreater(0d, String.format(resourceHelper.gs(R.string.limitingbolus), 0d, resourceHelper.gs(R.string.itmustbepositivevalue)), this); - Double maxBolus = SP.getDouble(R.string.key_treatmentssafety_maxbolus, 3d); - insulin.setIfSmaller(maxBolus, String.format(MainApp.gs(R.string.limitingbolus), maxBolus, MainApp.gs(R.string.maxvalueinpreferences)), this); + Double maxBolus = sp.getDouble(R.string.key_treatmentssafety_maxbolus, 3d); + insulin.setIfSmaller(maxBolus, String.format(resourceHelper.gs(R.string.limitingbolus), maxBolus, resourceHelper.gs(R.string.maxvalueinpreferences)), this); - insulin.setIfSmaller(HardLimits.maxBolus(), String.format(MainApp.gs(R.string.limitingbolus), HardLimits.maxBolus(), MainApp.gs(R.string.hardlimit)), this); + insulin.setIfSmaller(HardLimits.maxBolus(), String.format(resourceHelper.gs(R.string.limitingbolus), HardLimits.maxBolus(), resourceHelper.gs(R.string.hardlimit)), this); - PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump(); + PumpInterface pump = activePlugin.getActivePumpPlugin(); if (pump != null) { double rounded = pump.getPumpDescription().pumpType.determineCorrectBolusSize(insulin.value()); - insulin.setIfDifferent(rounded, MainApp.gs(R.string.pumplimit), this); + insulin.setIfDifferent(rounded, resourceHelper.gs(R.string.pumplimit), this); } return insulin; } - @Override + @NonNull @Override public Constraint applyExtendedBolusConstraints(Constraint insulin) { - insulin.setIfGreater(0d, String.format(MainApp.gs(R.string.limitingextendedbolus), 0d, MainApp.gs(R.string.itmustbepositivevalue)), this); + insulin.setIfGreater(0d, String.format(resourceHelper.gs(R.string.limitingextendedbolus), 0d, resourceHelper.gs(R.string.itmustbepositivevalue)), this); - Double maxBolus = SP.getDouble(R.string.key_treatmentssafety_maxbolus, 3d); - insulin.setIfSmaller(maxBolus, String.format(MainApp.gs(R.string.limitingextendedbolus), maxBolus, MainApp.gs(R.string.maxvalueinpreferences)), this); + Double maxBolus = sp.getDouble(R.string.key_treatmentssafety_maxbolus, 3d); + insulin.setIfSmaller(maxBolus, String.format(resourceHelper.gs(R.string.limitingextendedbolus), maxBolus, resourceHelper.gs(R.string.maxvalueinpreferences)), this); - insulin.setIfSmaller(HardLimits.maxBolus(), String.format(MainApp.gs(R.string.limitingextendedbolus), HardLimits.maxBolus(), MainApp.gs(R.string.hardlimit)), this); + insulin.setIfSmaller(HardLimits.maxBolus(), String.format(resourceHelper.gs(R.string.limitingextendedbolus), HardLimits.maxBolus(), resourceHelper.gs(R.string.hardlimit)), this); - PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump(); + PumpInterface pump = activePlugin.getActivePumpPlugin(); if (pump != null) { double rounded = pump.getPumpDescription().pumpType.determineCorrectExtendedBolusSize(insulin.value()); - insulin.setIfDifferent(rounded, MainApp.gs(R.string.pumplimit), this); + insulin.setIfDifferent(rounded, resourceHelper.gs(R.string.pumplimit), this); } return insulin; } - @Override + @NonNull @Override public Constraint applyCarbsConstraints(Constraint carbs) { - carbs.setIfGreater(0, String.format(MainApp.gs(R.string.limitingcarbs), 0, MainApp.gs(R.string.itmustbepositivevalue)), this); + carbs.setIfGreater(0, String.format(resourceHelper.gs(R.string.limitingcarbs), 0, resourceHelper.gs(R.string.itmustbepositivevalue)), this); - Integer maxCarbs = SP.getInt(R.string.key_treatmentssafety_maxcarbs, 48); - carbs.setIfSmaller(maxCarbs, String.format(MainApp.gs(R.string.limitingcarbs), maxCarbs, MainApp.gs(R.string.maxvalueinpreferences)), this); + Integer maxCarbs = sp.getInt(R.string.key_treatmentssafety_maxcarbs, 48); + carbs.setIfSmaller(maxCarbs, String.format(resourceHelper.gs(R.string.limitingcarbs), maxCarbs, resourceHelper.gs(R.string.maxvalueinpreferences)), this); return carbs; } - @Override - public Constraint applyMaxIOBConstraints(Constraint maxIob) { + @NonNull @Override + public Constraint applyMaxIOBConstraints(@NonNull Constraint maxIob) { double maxIobPref; if (openAPSSMBPlugin.isEnabled(PluginType.APS)) - maxIobPref = SP.getDouble(R.string.key_openapssmb_max_iob, 3d); + maxIobPref = sp.getDouble(R.string.key_openapssmb_max_iob, 3d); else - maxIobPref = SP.getDouble(R.string.key_openapsma_max_iob, 1.5d); - maxIob.setIfSmaller(maxIobPref, String.format(MainApp.gs(R.string.limitingiob), maxIobPref, MainApp.gs(R.string.maxvalueinpreferences)), this); + maxIobPref = sp.getDouble(R.string.key_openapsma_max_iob, 1.5d); + maxIob.setIfSmaller(maxIobPref, String.format(resourceHelper.gs(R.string.limitingiob), maxIobPref, resourceHelper.gs(R.string.maxvalueinpreferences)), this); if (openAPSMAPlugin.isEnabled(PluginType.APS)) - maxIob.setIfSmaller(HardLimits.maxIobAMA(), String.format(MainApp.gs(R.string.limitingiob), HardLimits.maxIobAMA(), MainApp.gs(R.string.hardlimit)), this); + maxIob.setIfSmaller(HardLimits.maxIobAMA(), String.format(resourceHelper.gs(R.string.limitingiob), HardLimits.maxIobAMA(), resourceHelper.gs(R.string.hardlimit)), this); if (openAPSAMAPlugin.isEnabled(PluginType.APS)) - maxIob.setIfSmaller(HardLimits.maxIobAMA(), String.format(MainApp.gs(R.string.limitingiob), HardLimits.maxIobAMA(), MainApp.gs(R.string.hardlimit)), this); + maxIob.setIfSmaller(HardLimits.maxIobAMA(), String.format(resourceHelper.gs(R.string.limitingiob), HardLimits.maxIobAMA(), resourceHelper.gs(R.string.hardlimit)), this); if (openAPSSMBPlugin.isEnabled(PluginType.APS)) - maxIob.setIfSmaller(HardLimits.maxIobSMB(), String.format(MainApp.gs(R.string.limitingiob), HardLimits.maxIobSMB(), MainApp.gs(R.string.hardlimit)), this); + maxIob.setIfSmaller(HardLimits.maxIobSMB(), String.format(resourceHelper.gs(R.string.limitingiob), HardLimits.maxIobSMB(), resourceHelper.gs(R.string.hardlimit)), this); return maxIob; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPlugin.kt index 7ff7e36f01..2e5db61e97 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPlugin.kt @@ -1,7 +1,7 @@ package info.nightscout.androidaps.plugins.constraints.signatureVerifier +import android.content.Context import android.content.pm.PackageManager -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.ConstraintsInterface @@ -34,17 +34,18 @@ import javax.inject.Singleton */ @Singleton class SignatureVerifierPlugin @Inject constructor( + aapsLogger: AAPSLogger, + resourceHelper: ResourceHelper, private val sp: SP, - private val resourceHelper: ResourceHelper, - private val mainApp: MainApp, - rxBus: RxBusWrapper, aapsLogger: AAPSLogger + private val rxBus: RxBusWrapper, + private val context: Context ) : PluginBase(PluginDescription() .mainType(PluginType.CONSTRAINTS) .neverVisible(true) .alwaysEnabled(true) .showInList(false) .pluginName(R.string.signature_verifier), - rxBus, aapsLogger + aapsLogger, resourceHelper ), ConstraintsInterface { private val REVOKED_CERTS_URL = "https://raw.githubusercontent.com/MilosKozak/AndroidAPS/master/app/src/main/assets/revoked_certs.txt" @@ -56,7 +57,7 @@ class SignatureVerifierPlugin @Inject constructor( private var revokedCerts: List? = null override fun onStart() { super.onStart() - revokedCertsFile = File(mainApp.filesDir, "revoked_certs.txt") + revokedCertsFile = File(context.filesDir, "revoked_certs.txt") Thread(Runnable { loadLocalRevokedCerts() if (shouldDownloadCerts()) { @@ -98,7 +99,7 @@ class SignatureVerifierPlugin @Inject constructor( if (revokedCerts == null) return false // TODO Change after raising min API to 28 @Suppress("DEPRECATION", "PackageManagerGetSignatures") - val signatures = mainApp.packageManager.getPackageInfo(mainApp.packageName, PackageManager.GET_SIGNATURES).signatures + val signatures = context.packageManager.getPackageInfo(context.packageName, PackageManager.GET_SIGNATURES).signatures if (signatures != null) { for (signature in signatures) { val digest = MessageDigest.getInstance("SHA256") @@ -124,7 +125,7 @@ class SignatureVerifierPlugin @Inject constructor( try { // TODO Change after raising min API to 28 @Suppress("DEPRECATION", "PackageManagerGetSignatures") - val signatures = mainApp.packageManager.getPackageInfo(mainApp.packageName, PackageManager.GET_SIGNATURES).signatures + val signatures = context.packageManager.getPackageInfo(context.packageName, PackageManager.GET_SIGNATURES).signatures if (signatures != null) { for (signature in signatures) { val digest = MessageDigest.getInstance("SHA256") @@ -212,7 +213,7 @@ class SignatureVerifierPlugin @Inject constructor( } @Throws(IOException::class) private fun readRevokedCertsInAssets(): String { - val inputStream = mainApp.assets.open("revoked_certs.txt") + val inputStream = context.assets.open("revoked_certs.txt") return readInputStream(inputStream) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPlugin.java deleted file mode 100644 index 0d1c2bab68..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPlugin.java +++ /dev/null @@ -1,83 +0,0 @@ -package info.nightscout.androidaps.plugins.constraints.storage; - -import android.os.Environment; -import android.os.StatFs; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; - -import info.nightscout.androidaps.Constants; -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.interfaces.Constraint; -import info.nightscout.androidaps.interfaces.ConstraintsInterface; -import info.nightscout.androidaps.interfaces.PluginBase; -import info.nightscout.androidaps.interfaces.PluginDescription; -import info.nightscout.androidaps.interfaces.PluginType; -import info.nightscout.androidaps.logging.AAPSLoggerProduction; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.bus.RxBus; -import info.nightscout.androidaps.plugins.bus.RxBusWrapper; -import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification; -import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; -import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; - -/** - * Created by Rumen on 06.03.2019. - */ -public class StorageConstraintPlugin extends PluginBase implements ConstraintsInterface { - private static Logger log = LoggerFactory.getLogger(L.CONSTRAINTS); - static StorageConstraintPlugin plugin = null; - - @Deprecated - public static StorageConstraintPlugin getPlugin() { - if (plugin == null) - plugin = new StorageConstraintPlugin(); - return plugin; - } - - // TODO: dagger - - public StorageConstraintPlugin() { - super(new PluginDescription() - .mainType(PluginType.CONSTRAINTS) - .neverVisible(true) - .alwaysEnabled(true) - .showInList(false) - .pluginName(R.string.storage), - new RxBusWrapper(), new AAPSLoggerProduction() // TODO: dagger - ); - } - - /** - * Constraints interface - **/ - - @Override - public Constraint isClosedLoopAllowed(Constraint value) { - long diskfree = getAvailableInternalMemorySize(); - if (L.isEnabled(L.CONSTRAINTS)) - log.debug("Internal storage free (Mb):" + diskfree); - if (diskfree < Constants.MINIMUM_FREE_SPACE) { - value.set(false, MainApp.gs(R.string.diskfull, Constants.MINIMUM_FREE_SPACE), this); - Notification notification = new Notification(Notification.DISKFULL, MainApp.gs(R.string.diskfull, Constants.MINIMUM_FREE_SPACE), Notification.NORMAL); - RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); - } else { - RxBus.Companion.getINSTANCE().send(new EventDismissNotification(Notification.DISKFULL)); - } - - return value; - } - - public static long getAvailableInternalMemorySize() { - File path = Environment.getDataDirectory(); - StatFs stat = new StatFs(path.getPath()); - long blockSize = stat.getBlockSizeLong(); - long blocksAvailable = stat.getAvailableBlocksLong(); - int size = 1048576; // blocksize of 1 Mb - return ((blocksAvailable * blockSize) / size); - } - -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPlugin.kt new file mode 100644 index 0000000000..9dc8e11a48 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPlugin.kt @@ -0,0 +1,58 @@ +package info.nightscout.androidaps.plugins.constraints.storage + +import android.os.Environment +import android.os.StatFs +import info.nightscout.androidaps.Constants +import info.nightscout.androidaps.R +import info.nightscout.androidaps.interfaces.Constraint +import info.nightscout.androidaps.interfaces.ConstraintsInterface +import info.nightscout.androidaps.interfaces.PluginBase +import info.nightscout.androidaps.interfaces.PluginDescription +import info.nightscout.androidaps.interfaces.PluginType +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification +import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification +import info.nightscout.androidaps.plugins.general.overview.notifications.Notification +import info.nightscout.androidaps.utils.resources.ResourceHelper +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +open class StorageConstraintPlugin @Inject constructor( + aapsLogger: AAPSLogger, + resourceHelper: ResourceHelper, + private val rxBus: RxBusWrapper +) : PluginBase(PluginDescription() + .mainType(PluginType.CONSTRAINTS) + .neverVisible(true) + .alwaysEnabled(true) + .showInList(false) + .pluginName(R.string.storage), + aapsLogger, resourceHelper +), ConstraintsInterface { + + override fun isClosedLoopAllowed(value: Constraint): Constraint { + val diskFree = availableInternalMemorySize + aapsLogger.debug(LTag.CONSTRAINTS, "Internal storage free (Mb):$diskFree") + if (diskFree < Constants.MINIMUM_FREE_SPACE) { + value[false, resourceHelper.gs(R.string.diskfull, Constants.MINIMUM_FREE_SPACE)] = this + val notification = Notification(Notification.DISKFULL, resourceHelper.gs(R.string.diskfull, Constants.MINIMUM_FREE_SPACE), Notification.NORMAL) + rxBus.send(EventNewNotification(notification)) + } else { + rxBus.send(EventDismissNotification(Notification.DISKFULL)) + } + return value + } + + val availableInternalMemorySize: Long + get() { + val path = Environment.getDataDirectory() + val stat = StatFs(path.path) + val blockSize = stat.blockSizeLong + val blocksAvailable = stat.availableBlocksLong + val size = 1048576 // block size of 1 Mb + return blocksAvailable * blockSize / size + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerPlugin.kt index f4ff61319f..e068dfb25d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerPlugin.kt @@ -22,16 +22,17 @@ import kotlin.math.roundToInt @Singleton class VersionCheckerPlugin @Inject constructor( private val sp: SP, - private val resourceHelper: ResourceHelper, + resourceHelper: ResourceHelper, private val versionCheckerUtils: VersionCheckerUtils, - rxBus: RxBusWrapper, aapsLogger: AAPSLogger + val rxBus: RxBusWrapper, + aapsLogger: AAPSLogger ) : PluginBase(PluginDescription() .mainType(PluginType.CONSTRAINTS) .neverVisible(true) .alwaysEnabled(true) .showInList(false) .pluginName(R.string.versionChecker), - rxBus, aapsLogger + aapsLogger, resourceHelper ), ConstraintsInterface { enum class GracePeriod(val warning: Long, val old: Long, val veryOld: Long) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt index c83e780049..5e8d3b8a3f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt @@ -16,12 +16,12 @@ import info.nightscout.androidaps.activities.TDDStatsActivity import info.nightscout.androidaps.dialogs.* import info.nightscout.androidaps.events.* import info.nightscout.androidaps.historyBrowser.HistoryBrowseActivity +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction import info.nightscout.androidaps.plugins.general.overview.StatusLightHandler -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.SingleClickButton @@ -44,8 +44,8 @@ class ActionsFragment : DaggerFragment() { @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var statusLightHandler: StatusLightHandler @Inject lateinit var fabricPrivacy: FabricPrivacy - @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin - @Inject lateinit var treatmentsPlugin: TreatmentsPlugin + @Inject lateinit var activePlugin: ActivePluginProvider + @Inject lateinit var commandQueue: CommandQueueProvider private var disposable: CompositeDisposable = CompositeDisposable() @@ -70,8 +70,8 @@ class ActionsFragment : DaggerFragment() { fragmentManager?.let { ExtendedBolusDialog().show(it, "Actions") } } actions_extendedbolus_cancel.setOnClickListener { - if (treatmentsPlugin.isInHistoryExtendedBoluslInProgress) { - configBuilderPlugin.commandQueue.cancelExtended(object : Callback() { + if (activePlugin.activeTreatments.isInHistoryExtendedBoluslInProgress) { + commandQueue.cancelExtended(object : Callback() { override fun run() { if (!result.success) { val i = Intent(mainApp, ErrorHelperActivity::class.java) @@ -89,8 +89,8 @@ class ActionsFragment : DaggerFragment() { fragmentManager?.let { TempBasalDialog().show(it, "Actions") } } actions_canceltempbasal.setOnClickListener { - if (treatmentsPlugin.isTempBasalInProgress) { - configBuilderPlugin.commandQueue.cancelTempBasal(true, object : Callback() { + if (activePlugin.activeTreatments.isTempBasalInProgress) { + commandQueue.cancelTempBasal(true, object : Callback() { override fun run() { if (!result.success) { val i = Intent(mainApp, ErrorHelperActivity::class.java) @@ -159,20 +159,22 @@ class ActionsFragment : DaggerFragment() { @Synchronized fun updateGui() { actions_profileswitch?.visibility = - if (configBuilderPlugin.activeProfileInterface.profile != null) View.VISIBLE + if (activePlugin.activeProfileInterface.profile != null) View.VISIBLE else View.GONE - if (profileFunction.getProfile() == null) { - actions_temptarget?.visibility = View.GONE - actions_extendedbolus?.visibility = View.GONE - actions_extendedbolus_cancel?.visibility = View.GONE - actions_settempbasal?.visibility = View.GONE - actions_canceltempbasal?.visibility = View.GONE - actions_fill?.visibility = View.GONE - return - } + val profile = profileFunction.getProfile() + val pump = activePlugin.activePumpPlugin + + actions_temptarget?.visibility = (profile != null).toVisibility() + actions_canceltempbasal.visibility = (pump != null || profile == null).toVisibility() + actions_settempbasal.visibility = (pump != null || profile == null).toVisibility() + actions_fill.visibility = (pump != null || profile == null).toVisibility() + actions_extendedbolus.visibility = (pump != null || profile == null).toVisibility() + actions_extendedbolus_cancel.visibility = (pump != null || profile == null).toVisibility() + actions_historybrowser.visibility = (pump != null || profile == null).toVisibility() + actions_tddstats.visibility = (pump != null || profile == null).toVisibility() + if (pump == null) return - val pump = configBuilderPlugin.activePump ?: return val basalProfileEnabled = MainApp.isEngineeringModeOrRelease() && pump.pumpDescription.isSetBasalProfileCapable actions_profileswitch?.visibility = if (!basalProfileEnabled || !pump.isInitialized || pump.isSuspended) View.GONE else View.VISIBLE @@ -181,7 +183,7 @@ class ActionsFragment : DaggerFragment() { actions_extendedbolus?.visibility = View.GONE actions_extendedbolus_cancel?.visibility = View.GONE } else { - val activeExtendedBolus = treatmentsPlugin.getExtendedBolusFromHistory(System.currentTimeMillis()) + val activeExtendedBolus = activePlugin.activeTreatments.getExtendedBolusFromHistory(System.currentTimeMillis()) if (activeExtendedBolus != null) { actions_extendedbolus?.visibility = View.GONE actions_extendedbolus_cancel?.visibility = View.VISIBLE @@ -197,7 +199,7 @@ class ActionsFragment : DaggerFragment() { actions_settempbasal?.visibility = View.GONE actions_canceltempbasal?.visibility = View.GONE } else { - val activeTemp = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis()) + val activeTemp = activePlugin.activeTreatments.getTempBasalFromHistory(System.currentTimeMillis()) if (activeTemp != null) { actions_settempbasal?.visibility = View.GONE actions_canceltempbasal?.visibility = View.VISIBLE @@ -220,7 +222,7 @@ class ActionsFragment : DaggerFragment() { } private fun checkPumpCustomActions() { - val activePump = configBuilderPlugin.activePump ?: return + val activePump = activePlugin.activePumpPlugin ?: return val customActions = activePump.customActions ?: return removePumpCustomActions() @@ -237,8 +239,9 @@ class ActionsFragment : DaggerFragment() { btn.layoutParams = layoutParams btn.setOnClickListener { v -> val b = v as SingleClickButton - val action = this.pumpCustomActions[b.text.toString()] - configBuilderPlugin.activePump!!.executeCustomAction(action!!.customActionType) + this.pumpCustomActions[b.text.toString()]?.let { + activePlugin.activePump.executeCustomAction(it.customActionType) + } } val top = activity?.let { ContextCompat.getDrawable(it, customAction.iconResourceId) } btn.setCompoundDrawablesWithIntrinsicBounds(null, top, null, null) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsPlugin.kt index ab0f0c0ef0..f266040520 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsPlugin.kt @@ -6,12 +6,12 @@ import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.utils.resources.ResourceHelper import javax.inject.Inject import javax.inject.Singleton @Singleton -class ActionsPlugin @Inject constructor(rxBus: RxBusWrapper, aapsLogger: AAPSLogger +class ActionsPlugin @Inject constructor(aapsLogger: AAPSLogger, resourceHelper: ResourceHelper ) : PluginBase(PluginDescription() .mainType(PluginType.GENERAL) .fragmentClass(ActionsFragment::class.qualifiedName) @@ -20,5 +20,5 @@ class ActionsPlugin @Inject constructor(rxBus: RxBusWrapper, aapsLogger: AAPSLog .pluginName(R.string.actions) .shortName(R.string.actions_shortname) .description(R.string.description_actions), - rxBus, aapsLogger + aapsLogger, resourceHelper ) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationEvent.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationEvent.kt index 9dada7980d..d0106e7646 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationEvent.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationEvent.kt @@ -1,6 +1,6 @@ package info.nightscout.androidaps.plugins.general.automation -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.general.automation.actions.Action import info.nightscout.androidaps.plugins.general.automation.actions.ActionDummy @@ -14,21 +14,21 @@ import org.json.JSONObject import java.util.* import javax.inject.Inject -class AutomationEvent(private val mainApp: MainApp) { +class AutomationEvent(private val injector: HasAndroidInjector) { @Inject lateinit var aapsLogger: AAPSLogger - var trigger: Trigger = TriggerConnector(mainApp) + var trigger: Trigger = TriggerConnector(injector) val actions: MutableList = ArrayList() var title: String? = null var isEnabled = true var lastRun: Long = 0 init { - mainApp.androidInjector().inject(this) + injector.androidInjector().inject(this) } fun getPreconditions(): TriggerConnector { - val trigger = TriggerConnector(mainApp, TriggerConnector.Type.AND) + val trigger = TriggerConnector(injector, TriggerConnector.Type.AND) for (action in actions) { action.precondition?.let { trigger.list.add(it) } } @@ -52,19 +52,19 @@ class AutomationEvent(private val mainApp: MainApp) { val d = JSONObject(data) title = d.optString("title", "") isEnabled = d.optBoolean("enabled", true) - trigger = TriggerDummy(mainApp).instantiate(JSONObject(d.getString("trigger"))) - ?: TriggerConnector(mainApp) + trigger = TriggerDummy(injector).instantiate(JSONObject(d.getString("trigger"))) + ?: TriggerConnector(injector) val array = d.getJSONArray("actions") actions.clear() for (i in 0 until array.length()) { - ActionDummy(mainApp).instantiate(JSONObject(array.getString(i)))?.let { + ActionDummy(injector).instantiate(JSONObject(array.getString(i)))?.let { actions.add(it) } } return this } - fun shouldRun() : Boolean{ + fun shouldRun(): Boolean { return lastRun <= DateUtil.now() - T.mins(5).msecs() } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationPlugin.kt index dc56d305b9..320314462c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationPlugin.kt @@ -1,9 +1,10 @@ package info.nightscout.androidaps.plugins.general.automation +import android.content.Context import android.content.Intent import android.os.Build import android.os.Handler -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.events.EventChargingState import info.nightscout.androidaps.events.EventLocationChange @@ -40,19 +41,21 @@ import javax.inject.Singleton @Singleton class AutomationPlugin @Inject constructor( - private val resourceHelper: ResourceHelper, - private val mainApp: MainApp, + private val injector: HasAndroidInjector, + resourceHelper: ResourceHelper, + private val context: Context, private val sp: SP, private val fabricPrivacy: FabricPrivacy, private val loopPlugin: LoopPlugin, - rxBus: RxBusWrapper, aapsLogger: AAPSLogger + private val rxBus: RxBusWrapper, + aapsLogger: AAPSLogger ) : PluginBase(PluginDescription() .mainType(PluginType.GENERAL) .fragmentClass(AutomationFragment::class.qualifiedName) .pluginName(R.string.automation) .shortName(R.string.automation_short) .preferencesId(R.xml.pref_automation) - .description(R.string.automation_description), rxBus, aapsLogger + .description(R.string.automation_description), aapsLogger, resourceHelper ) { private var disposable: CompositeDisposable = CompositeDisposable() @@ -74,9 +77,9 @@ class AutomationPlugin @Inject constructor( override fun onStart() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) - mainApp.startForegroundService(Intent(mainApp, LocationService::class.java)) + context.startForegroundService(Intent(context, LocationService::class.java)) else - mainApp.startService(Intent(mainApp, LocationService::class.java)) + context.startService(Intent(context, LocationService::class.java)) super.onStart() loadFromSP() @@ -87,11 +90,11 @@ class AutomationPlugin @Inject constructor( .observeOn(Schedulers.io()) .subscribe({ e -> if (e.isChanged(resourceHelper, R.string.key_location)) { - mainApp.stopService(Intent(mainApp, LocationService::class.java)) + context.stopService(Intent(context, LocationService::class.java)) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) - mainApp.startForegroundService(Intent(mainApp, LocationService::class.java)) + context.startForegroundService(Intent(context, LocationService::class.java)) else - mainApp.startService(Intent(mainApp, LocationService::class.java)) + context.startService(Intent(context, LocationService::class.java)) } }, { fabricPrivacy.logException(it) }) disposable += rxBus @@ -124,7 +127,7 @@ class AutomationPlugin @Inject constructor( override fun onStop() { disposable.clear() loopHandler.removeCallbacks(refreshLoop) - mainApp.stopService(Intent(mainApp, LocationService::class.java)) + context.stopService(Intent(context, LocationService::class.java)) super.onStop() } @@ -149,7 +152,7 @@ class AutomationPlugin @Inject constructor( val array = JSONArray(data) for (i in 0 until array.length()) { val o = array.getJSONObject(i) - val event = AutomationEvent(mainApp).fromJSON(o.toString()) + val event = AutomationEvent(injector).fromJSON(o.toString()) automationEvents.add(event) } } catch (e: JSONException) { @@ -198,36 +201,36 @@ class AutomationPlugin @Inject constructor( fun getActionDummyObjects(): List { return listOf( - //ActionLoopDisable(mainApp), - //ActionLoopEnable(mainApp), - //ActionLoopResume(mainApp), - //ActionLoopSuspend(mainApp), - ActionStartTempTarget(mainApp), - ActionStopTempTarget(mainApp), - ActionNotification(mainApp), - ActionProfileSwitchPercent(mainApp), - ActionProfileSwitch(mainApp), - ActionSendSMS(mainApp) + //ActionLoopDisable(injector), + //ActionLoopEnable(injector), + //ActionLoopResume(injector), + //ActionLoopSuspend(injector), + ActionStartTempTarget(injector), + ActionStopTempTarget(injector), + ActionNotification(injector), + ActionProfileSwitchPercent(injector), + ActionProfileSwitch(injector), + ActionSendSMS(injector) ) } fun getTriggerDummyObjects(): List { return listOf( - TriggerConnector(mainApp), - TriggerTime(mainApp), - TriggerRecurringTime(mainApp), - TriggerTimeRange(mainApp), - TriggerBg(mainApp), - TriggerDelta(mainApp), - TriggerIob(mainApp), - TriggerCOB(mainApp), - TriggerProfilePercent(mainApp), - TriggerTempTarget(mainApp), - TriggerWifiSsid(mainApp), - TriggerLocation(mainApp), - TriggerAutosensValue(mainApp), - TriggerBolusAgo(mainApp), - TriggerPumpLastConnection(mainApp) + TriggerConnector(injector), + TriggerTime(injector), + TriggerRecurringTime(injector), + TriggerTimeRange(injector), + TriggerBg(injector), + TriggerDelta(injector), + TriggerIob(injector), + TriggerCOB(injector), + TriggerProfilePercent(injector), + TriggerTempTarget(injector), + TriggerWifiSsid(injector), + TriggerLocation(injector), + TriggerAutosensValue(injector), + TriggerBolusAgo(injector), + TriggerPumpLastConnection(injector) ) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/Action.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/Action.kt index 590638f86e..98c8d27c60 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/Action.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/Action.kt @@ -2,33 +2,17 @@ package info.nightscout.androidaps.plugins.general.automation.actions import android.widget.LinearLayout import androidx.annotation.DrawableRes -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin -import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.general.automation.triggers.Trigger -import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.queue.Callback -import info.nightscout.androidaps.utils.resources.ResourceHelper -import info.nightscout.androidaps.utils.sharedPreferences.SP import org.json.JSONException import org.json.JSONObject import javax.inject.Inject import kotlin.reflect.full.primaryConstructor -abstract class Action(val mainApp: MainApp) { +abstract class Action(val injector: HasAndroidInjector) { @Inject lateinit var aapsLogger: AAPSLogger - @Inject lateinit var sp: SP - @Inject lateinit var rxBus: RxBusWrapper - @Inject lateinit var profileFunction: ProfileFunction - @Inject lateinit var resourceHelper: ResourceHelper - @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin - @Inject lateinit var loopPlugin: LoopPlugin - @Inject lateinit var treatmentsPlugin: TreatmentsPlugin - @Inject lateinit var smsCommunicatorPlugin: SmsCommunicatorPlugin var precondition: Trigger? = null @@ -38,7 +22,7 @@ abstract class Action(val mainApp: MainApp) { @DrawableRes abstract fun icon(): Int init { - mainApp.androidInjector().inject(this) + injector.androidInjector().inject(this) } open fun generateDialog(root: LinearLayout) {} @@ -62,7 +46,7 @@ abstract class Action(val mainApp: MainApp) { val type = obj.getString("type") val data = obj.optJSONObject("data") val clazz = Class.forName(type).kotlin - return (clazz.primaryConstructor?.call(mainApp) as Action).fromJSON(data?.toString() + return (clazz.primaryConstructor?.call(injector) as Action).fromJSON(data?.toString() ?: "") //return (clazz.newInstance() as Action).fromJSON(data?.toString() ?: "") } catch (e: ClassNotFoundException) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionDummy.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionDummy.kt index 23c4fa5fdb..c7d1fec9b1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionDummy.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionDummy.kt @@ -1,10 +1,10 @@ package info.nightscout.androidaps.plugins.general.automation.actions -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.queue.Callback // Used for instantiation of other actions only -class ActionDummy(mainApp: MainApp) : Action(mainApp) { +class ActionDummy(injector: HasAndroidInjector) : Action(injector) { override fun friendlyName(): Int { throw NotImplementedError("An operation is not implemented") diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopDisable.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopDisable.kt index 25109ad535..b55ce9c177 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopDisable.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopDisable.kt @@ -1,14 +1,25 @@ package info.nightscout.androidaps.plugins.general.automation.actions import androidx.annotation.DrawableRes -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.events.EventRefreshOverview +import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.PluginType +import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin +import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.queue.Callback +import info.nightscout.androidaps.utils.resources.ResourceHelper +import javax.inject.Inject -class ActionLoopDisable(mainApp: MainApp) : Action(mainApp) { +class ActionLoopDisable(injector: HasAndroidInjector) : Action(injector) { + @Inject lateinit var loopPlugin: LoopPlugin + @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin + @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var rxBus: RxBusWrapper override fun friendlyName(): Int = R.string.disableloop override fun shortDescription(): String = resourceHelper.gs(R.string.disableloop) @@ -18,7 +29,7 @@ class ActionLoopDisable(mainApp: MainApp) : Action(mainApp) { if (loopPlugin.isEnabled(PluginType.LOOP)) { loopPlugin.setPluginEnabled(PluginType.LOOP, false) configBuilderPlugin.storeSettings("ActionLoopDisable") - configBuilderPlugin.commandQueue.cancelTempBasal(true, object : Callback() { + commandQueue.cancelTempBasal(true, object : Callback() { override fun run() { rxBus.send(EventRefreshOverview("ActionLoopDisable")) callback.result(result).run() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopEnable.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopEnable.kt index 7ba42f140e..eb40388b44 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopEnable.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopEnable.kt @@ -1,14 +1,23 @@ package info.nightscout.androidaps.plugins.general.automation.actions import androidx.annotation.DrawableRes -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.events.EventRefreshOverview import info.nightscout.androidaps.interfaces.PluginType +import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin +import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.queue.Callback +import info.nightscout.androidaps.utils.resources.ResourceHelper +import javax.inject.Inject -class ActionLoopEnable(mainApp: MainApp) : Action(mainApp) { +class ActionLoopEnable(injector: HasAndroidInjector) : Action(injector) { + @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var loopPlugin: LoopPlugin + @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin + @Inject lateinit var rxBus: RxBusWrapper override fun friendlyName(): Int = R.string.enableloop override fun shortDescription(): String = resourceHelper.gs(R.string.enableloop) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopResume.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopResume.kt index 0764566616..813060345e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopResume.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopResume.kt @@ -1,14 +1,23 @@ package info.nightscout.androidaps.plugins.general.automation.actions import androidx.annotation.DrawableRes -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.events.EventRefreshOverview +import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin +import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.queue.Callback +import info.nightscout.androidaps.utils.resources.ResourceHelper +import javax.inject.Inject -class ActionLoopResume(mainApp: MainApp) : Action(mainApp) { +class ActionLoopResume(injector: HasAndroidInjector) : Action(injector) { + @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var loopPlugin: LoopPlugin + @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin + @Inject lateinit var rxBus: RxBusWrapper override fun friendlyName(): Int = R.string.resumeloop override fun shortDescription(): String = resourceHelper.gs(R.string.resumeloop) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopSuspend.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopSuspend.kt index 5cad5f333d..3e503a4dd3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopSuspend.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopSuspend.kt @@ -2,19 +2,27 @@ package info.nightscout.androidaps.plugins.general.automation.actions import android.widget.LinearLayout import androidx.annotation.DrawableRes -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.events.EventRefreshOverview +import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin +import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.automation.elements.InputDuration import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithElement import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.JsonHelper +import info.nightscout.androidaps.utils.resources.ResourceHelper import org.json.JSONObject +import javax.inject.Inject -class ActionLoopSuspend(mainApp: MainApp) : Action(mainApp) { - var minutes = InputDuration(mainApp, 0, InputDuration.TimeUnit.MINUTES) +class ActionLoopSuspend(injector: HasAndroidInjector) : Action(injector) { + @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var loopPlugin: LoopPlugin + @Inject lateinit var rxBus: RxBusWrapper + + var minutes = InputDuration(injector, 0, InputDuration.TimeUnit.MINUTES) override fun friendlyName(): Int = R.string.suspendloop override fun shortDescription(): String = resourceHelper.gs(R.string.suspendloopforXmin, minutes.getMinutes()) @@ -48,7 +56,7 @@ class ActionLoopSuspend(mainApp: MainApp) : Action(mainApp) { override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(LabelWithElement(mainApp, resourceHelper.gs(R.string.careportal_newnstreatment_duration_min_label), "", minutes)) + .add(LabelWithElement(injector, resourceHelper.gs(R.string.careportal_newnstreatment_duration_min_label), "", minutes)) .build(root) } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotification.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotification.kt index eee0ab86c2..8a5c5c0aeb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotification.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotification.kt @@ -2,10 +2,11 @@ package info.nightscout.androidaps.plugins.general.automation.actions import android.widget.LinearLayout import androidx.annotation.DrawableRes -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.events.EventRefreshOverview +import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.automation.elements.InputString import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithElement import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder @@ -14,10 +15,15 @@ import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotifi import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.JsonHelper +import info.nightscout.androidaps.utils.resources.ResourceHelper import org.json.JSONObject +import javax.inject.Inject -class ActionNotification(mainApp: MainApp) : Action(mainApp) { - var text = InputString(mainApp) +class ActionNotification(injector: HasAndroidInjector) : Action(injector) { + @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rxBus: RxBusWrapper + + var text = InputString(injector) override fun friendlyName(): Int = R.string.notification override fun shortDescription(): String = resourceHelper.gs(R.string.notification_message, text.value) @@ -49,7 +55,7 @@ class ActionNotification(mainApp: MainApp) : Action(mainApp) { override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(LabelWithElement(mainApp,resourceHelper.gs(R.string.message_short), "", text)) + .add(LabelWithElement(injector, resourceHelper.gs(R.string.message_short), "", text)) .build(root) } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.kt index 1c797cdc19..7bc47c4cba 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.kt @@ -2,20 +2,28 @@ package info.nightscout.androidaps.plugins.general.automation.actions import android.widget.LinearLayout import androidx.annotation.DrawableRes -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.data.PumpEnactResult +import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.general.automation.elements.InputProfileName import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithElement import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.JsonHelper +import info.nightscout.androidaps.utils.resources.ResourceHelper import org.json.JSONObject +import javax.inject.Inject -class ActionProfileSwitch(mainApp: MainApp) : Action(mainApp) { - var inputProfileName: InputProfileName = InputProfileName(mainApp, "") +class ActionProfileSwitch(injector: HasAndroidInjector) : Action(injector) { + @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var activePlugin: ActivePluginProvider + @Inject lateinit var profileFunction: ProfileFunction + + var inputProfileName: InputProfileName = InputProfileName(injector, "") override fun friendlyName(): Int = R.string.profilename override fun shortDescription(): String = resourceHelper.gs(R.string.changengetoprofilename, inputProfileName.value) @@ -39,19 +47,19 @@ class ActionProfileSwitch(mainApp: MainApp) : Action(mainApp) { callback.result(PumpEnactResult().success(true).comment(R.string.alreadyset))?.run() return } - val profileStore = configBuilderPlugin.activeProfileInterface.profile ?: return + val profileStore = activePlugin.activeProfileInterface.profile ?: return if (profileStore.getSpecificProfile(inputProfileName.value) == null) { aapsLogger.error(LTag.AUTOMATION, "Selected profile does not exist! - ${inputProfileName.value}") callback.result(PumpEnactResult().success(false).comment(R.string.notexists))?.run() return } - treatmentsPlugin.doProfileSwitch(profileStore, inputProfileName.value, 0, 100, 0, DateUtil.now()) + activePlugin.activeTreatments.doProfileSwitch(profileStore, inputProfileName.value, 0, 100, 0, DateUtil.now()) callback.result(PumpEnactResult().success(true).comment(R.string.ok))?.run() } override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(LabelWithElement(mainApp, resourceHelper.gs(R.string.profilename), "", inputProfileName)) + .add(LabelWithElement(injector, resourceHelper.gs(R.string.profilename), "", inputProfileName)) .build(root) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercent.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercent.kt index 3882da1906..561dd167fa 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercent.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercent.kt @@ -2,9 +2,10 @@ package info.nightscout.androidaps.plugins.general.automation.actions import android.widget.LinearLayout import androidx.annotation.DrawableRes -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.data.PumpEnactResult +import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.plugins.general.automation.elements.Comparator import info.nightscout.androidaps.plugins.general.automation.elements.InputDuration import info.nightscout.androidaps.plugins.general.automation.elements.InputPercent @@ -13,11 +14,16 @@ import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuil import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerProfilePercent import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.JsonHelper +import info.nightscout.androidaps.utils.resources.ResourceHelper import org.json.JSONObject +import javax.inject.Inject -class ActionProfileSwitchPercent(mainApp: MainApp) : Action(mainApp) { - var pct = InputPercent(mainApp) - var duration = InputDuration(mainApp, 0, InputDuration.TimeUnit.MINUTES) +class ActionProfileSwitchPercent(injector: HasAndroidInjector) : Action(injector) { + @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var activePlugin: ActivePluginProvider + + var pct = InputPercent(injector) + var duration = InputDuration(injector, 0, InputDuration.TimeUnit.MINUTES) override fun friendlyName(): Int = R.string.profilepercentage override fun shortDescription(): String = @@ -27,18 +33,18 @@ class ActionProfileSwitchPercent(mainApp: MainApp) : Action(mainApp) { @DrawableRes override fun icon(): Int = R.drawable.icon_actions_profileswitch init { - precondition = TriggerProfilePercent(mainApp, 100.0, Comparator.Compare.IS_EQUAL) + precondition = TriggerProfilePercent(injector, 100.0, Comparator.Compare.IS_EQUAL) } override fun doAction(callback: Callback) { - treatmentsPlugin.doProfileSwitch(duration.value, pct.value.toInt(), 0) + activePlugin.activeTreatments.doProfileSwitch(duration.value, pct.value.toInt(), 0) callback.result(PumpEnactResult().success(true).comment(R.string.ok))?.run() } override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(LabelWithElement(mainApp, resourceHelper.gs(R.string.percent_u), "", pct)) - .add(LabelWithElement(mainApp, resourceHelper.gs(R.string.careportal_newnstreatment_duration_min_label), "", duration)) + .add(LabelWithElement(injector, resourceHelper.gs(R.string.percent_u), "", pct)) + .add(LabelWithElement(injector, resourceHelper.gs(R.string.careportal_newnstreatment_duration_min_label), "", duration)) .build(root) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMS.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMS.kt index 84b10feb65..ac92e93d98 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMS.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMS.kt @@ -1,18 +1,24 @@ package info.nightscout.androidaps.plugins.general.automation.actions import android.widget.LinearLayout -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.plugins.general.automation.elements.InputString import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithElement import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder +import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.JsonHelper +import info.nightscout.androidaps.utils.resources.ResourceHelper import org.json.JSONObject +import javax.inject.Inject -class ActionSendSMS(mainApp: MainApp) : Action(mainApp) { - var text = InputString(mainApp) +class ActionSendSMS(injector: HasAndroidInjector) : Action(injector) { + @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var smsCommunicatorPlugin: SmsCommunicatorPlugin + + var text = InputString(injector) override fun friendlyName(): Int = R.string.sendsmsactiondescription override fun shortDescription(): String = resourceHelper.gs(R.string.sendsmsactionlabel, text.value) @@ -41,7 +47,7 @@ class ActionSendSMS(mainApp: MainApp) : Action(mainApp) { override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(LabelWithElement(mainApp, resourceHelper.gs(R.string.sendsmsactiontext), "", text)) + .add(LabelWithElement(injector, resourceHelper.gs(R.string.sendsmsactiontext), "", text)) .build(root) } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTarget.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTarget.kt index d497fb9bd1..370678fcee 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTarget.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTarget.kt @@ -2,13 +2,14 @@ package info.nightscout.androidaps.plugins.general.automation.actions import android.widget.LinearLayout import androidx.annotation.DrawableRes +import dagger.android.HasAndroidInjector 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.data.PumpEnactResult import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.db.TempTarget +import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.plugins.general.automation.elements.ComparatorExists import info.nightscout.androidaps.plugins.general.automation.elements.InputDuration import info.nightscout.androidaps.plugins.general.automation.elements.InputTempTarget @@ -19,14 +20,19 @@ import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.androidaps.utils.JsonHelper.safeGetDouble +import info.nightscout.androidaps.utils.resources.ResourceHelper import org.json.JSONObject +import javax.inject.Inject -class ActionStartTempTarget(mainApp: MainApp) : Action(mainApp) { - var value = InputTempTarget(mainApp) - var duration = InputDuration(mainApp, 0, InputDuration.TimeUnit.MINUTES) +class ActionStartTempTarget(injector: HasAndroidInjector) : Action(injector) { + @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var activePlugin: ActivePluginProvider + + var value = InputTempTarget(injector) + var duration = InputDuration(injector, 0, InputDuration.TimeUnit.MINUTES) init { - precondition = TriggerTempTarget(mainApp, ComparatorExists.Compare.NOT_EXISTS) + precondition = TriggerTempTarget(injector, ComparatorExists.Compare.NOT_EXISTS) } override fun friendlyName(): Int = R.string.starttemptarget @@ -34,15 +40,15 @@ class ActionStartTempTarget(mainApp: MainApp) : Action(mainApp) { @DrawableRes override fun icon(): Int = R.drawable.icon_cp_cgm_target override fun doAction(callback: Callback) { - treatmentsPlugin.addToHistoryTempTarget(tt()) + activePlugin.activeTreatments.addToHistoryTempTarget(tt()) callback.result(PumpEnactResult().success(true).comment(R.string.ok))?.run() } override fun generateDialog(root: LinearLayout) { val unitResId = if (value.units == Constants.MGDL) R.string.mgdl else R.string.mmol LayoutBuilder() - .add(LabelWithElement(mainApp, resourceHelper.gs(R.string.careportal_temporarytarget) + "\n[" + resourceHelper.gs(unitResId) + "]", "", value)) - .add(LabelWithElement(mainApp, resourceHelper.gs(R.string.careportal_newnstreatment_duration_min_label), "", duration)) + .add(LabelWithElement(injector, resourceHelper.gs(R.string.careportal_temporarytarget) + "\n[" + resourceHelper.gs(unitResId) + "]", "", value)) + .add(LabelWithElement(injector, resourceHelper.gs(R.string.careportal_newnstreatment_duration_min_label), "", duration)) .build(root) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStopTempTarget.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStopTempTarget.kt index 8ba5622a21..18118110d0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStopTempTarget.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStopTempTarget.kt @@ -1,14 +1,19 @@ package info.nightscout.androidaps.plugins.general.automation.actions -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.db.TempTarget +import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.androidaps.utils.resources.ResourceHelper +import javax.inject.Inject -class ActionStopTempTarget(mainApp: MainApp) : Action(mainApp) { +class ActionStopTempTarget(injector: HasAndroidInjector) : Action(injector) { + @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var activePlugin: ActivePluginProvider override fun friendlyName(): Int = R.string.stoptemptarget override fun shortDescription(): String = resourceHelper.gs(R.string.stoptemptarget) @@ -21,7 +26,7 @@ class ActionStopTempTarget(mainApp: MainApp) : Action(mainApp) { .reason("Automation") .source(Source.USER) .low(0.0).high(0.0) - treatmentsPlugin.addToHistoryTempTarget(tempTarget) + activePlugin.activeTreatments.addToHistoryTempTarget(tempTarget) callback.result(PumpEnactResult().success(true).comment(R.string.ok))?.run() } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/Comparator.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/Comparator.kt index f965224281..86fd8dc73e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/Comparator.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/Comparator.kt @@ -6,12 +6,15 @@ import android.widget.ArrayAdapter import android.widget.LinearLayout import android.widget.Spinner import androidx.annotation.StringRes -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.utils.resources.ResourceHelper import java.util.* +import javax.inject.Inject + +class Comparator(injector: HasAndroidInjector) : Element(injector) { + @Inject lateinit var resourceHelper: ResourceHelper -class Comparator(mainApp: MainApp) : Element(mainApp) { enum class Compare { IS_LESSER, IS_EQUAL_OR_LESSER, @@ -53,7 +56,7 @@ class Comparator(mainApp: MainApp) : Element(mainApp) { } } - constructor(mainApp: MainApp, value : Compare) : this(mainApp) { + constructor(injector: HasAndroidInjector, value: Compare) : this(injector) { this.value = value } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorExists.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorExists.kt index 1fa8ec1b6a..2e7e437bd9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorExists.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorExists.kt @@ -6,12 +6,15 @@ import android.widget.ArrayAdapter import android.widget.LinearLayout import android.widget.Spinner import androidx.annotation.StringRes -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.utils.resources.ResourceHelper import java.util.* +import javax.inject.Inject + +class ComparatorExists(injector: HasAndroidInjector) : Element(injector) { + @Inject lateinit var resourceHelper: ResourceHelper -class ComparatorExists(mainApp: MainApp) : Element(mainApp) { enum class Compare { EXISTS, NOT_EXISTS; @@ -30,7 +33,7 @@ class ComparatorExists(mainApp: MainApp) : Element(mainApp) { } } - constructor(mainApp: MainApp, value: Compare) : this(mainApp) { + constructor(injector: HasAndroidInjector, value: Compare) : this(injector) { this.value = value } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/Element.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/Element.kt index 7a9f74289f..e8c3e6580c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/Element.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/Element.kt @@ -1,20 +1,13 @@ package info.nightscout.androidaps.plugins.general.automation.elements import android.widget.LinearLayout -import info.nightscout.androidaps.MainApp -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction -import info.nightscout.androidaps.utils.resources.ResourceHelper -import javax.inject.Inject +import dagger.android.HasAndroidInjector -abstract class Element(val mainApp: MainApp) { - @Inject lateinit var resourceHelper: ResourceHelper - @Inject lateinit var profileFunction: ProfileFunction - @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin +abstract class Element(val injector: HasAndroidInjector) { abstract fun addToLayout(root: LinearLayout) init { - mainApp.androidInjector().inject(this) + injector.androidInjector().inject(this) } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputBg.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputBg.kt index fb8b45f83d..896a2181b5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputBg.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputBg.kt @@ -1,13 +1,17 @@ package info.nightscout.androidaps.plugins.general.automation.elements import android.widget.LinearLayout +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.utils.NumberPicker import java.text.DecimalFormat +import javax.inject.Inject + +class InputBg(injector: HasAndroidInjector) : Element(injector) { + @Inject lateinit var profileFunction: ProfileFunction -class InputBg(mainApp: MainApp) : Element(mainApp) { var units = Constants.MGDL var value = 0.0 private var minValue = 0.0 @@ -15,9 +19,7 @@ class InputBg(mainApp: MainApp) : Element(mainApp) { private var step = 0.0 private var decimalFormat: DecimalFormat? = null - - - constructor(mainApp: MainApp, value : Double, units: String) : this(mainApp) { + constructor(injector: HasAndroidInjector, value: Double, units: String) : this(injector) { setUnits(units) this.value = value } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputButton.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputButton.kt index 866e9c4423..dd4bd9b5d6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputButton.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputButton.kt @@ -2,13 +2,13 @@ package info.nightscout.androidaps.plugins.general.automation.elements import android.widget.Button import android.widget.LinearLayout -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector -class InputButton(mainApp: MainApp) : Element(mainApp) { +class InputButton(injector: HasAndroidInjector) : Element(injector) { var text: String? = null var runnable: Runnable? = null - constructor(mainApp: MainApp, text: String, runnable: Runnable) : this(mainApp) { + constructor(injector: HasAndroidInjector, text: String, runnable: Runnable) : this(injector) { this.text = text this.runnable = runnable } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDateTime.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDateTime.kt index 59324aa0c5..f61d1d5719 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDateTime.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDateTime.kt @@ -2,22 +2,29 @@ package info.nightscout.androidaps.plugins.general.automation.elements import android.app.DatePickerDialog import android.app.TimePickerDialog +import android.content.Context import android.graphics.Typeface import android.text.format.DateFormat import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.androidaps.utils.resources.ResourceHelper import java.util.* +import javax.inject.Inject -class InputDateTime(mainApp: MainApp) : Element(mainApp) { - var value : Long = DateUtil.now() +class InputDateTime(injector: HasAndroidInjector) : Element(injector) { + @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var context: Context - constructor(mainApp: MainApp, value : Long) : this(mainApp) { + var value: Long = DateUtil.now() + + constructor(injector: HasAndroidInjector, value: Long) : this(injector) { this.value = value } + override fun addToLayout(root: LinearLayout) { val label = TextView(root.context) val dateButton = TextView(root.context) @@ -66,7 +73,7 @@ class InputDateTime(mainApp: MainApp) : Element(mainApp) { TimePickerDialog(it, timeSetListener, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), - DateFormat.is24HourFormat(mainApp) + DateFormat.is24HourFormat(context) ).show() } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDelta.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDelta.kt index d1bf5dfbf8..a667b51099 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDelta.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDelta.kt @@ -7,14 +7,17 @@ import android.widget.ArrayAdapter import android.widget.LinearLayout import android.widget.Spinner import androidx.annotation.StringRes -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.utils.NumberPicker import info.nightscout.androidaps.utils.resources.ResourceHelper import java.text.DecimalFormat import java.util.* +import javax.inject.Inject + +class InputDelta(injector: HasAndroidInjector) : Element(injector) { + @Inject lateinit var resourceHelper: ResourceHelper -class InputDelta(mainApp: MainApp) : Element(mainApp) { enum class DeltaType { DELTA, SHORT_AVERAGE, LONG_AVERAGE; @@ -43,7 +46,7 @@ class InputDelta(mainApp: MainApp) : Element(mainApp) { private var decimalFormat: DecimalFormat? = null var deltaType: DeltaType = DeltaType.DELTA - constructor(mainApp: MainApp, value: Double, minValue: Double, maxValue: Double, step: Double, decimalFormat: DecimalFormat, deltaType: DeltaType) : this(mainApp) { + constructor(injector: HasAndroidInjector, value: Double, minValue: Double, maxValue: Double, step: Double, decimalFormat: DecimalFormat, deltaType: DeltaType) : this(injector) { this.value = value this.minValue = minValue this.maxValue = maxValue @@ -52,7 +55,7 @@ class InputDelta(mainApp: MainApp) : Element(mainApp) { this.deltaType = deltaType } - constructor(mainApp: MainApp, inputDelta: InputDelta) : this(mainApp) { + constructor(injector: HasAndroidInjector, inputDelta: InputDelta) : this(injector) { value = inputDelta.value minValue = inputDelta.minValue maxValue = inputDelta.maxValue diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDouble.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDouble.kt index 5a63cddcfb..7824b51960 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDouble.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDouble.kt @@ -1,12 +1,12 @@ package info.nightscout.androidaps.plugins.general.automation.elements import android.widget.LinearLayout -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.utils.NumberPicker import java.text.DecimalFormat -class InputDouble(mainApp: MainApp) : Element(mainApp) { +class InputDouble(injector: HasAndroidInjector) : Element(injector) { var value = 0.0 private var minValue = 0.0 private var maxValue = 0.0 @@ -14,7 +14,7 @@ class InputDouble(mainApp: MainApp) : Element(mainApp) { private var decimalFormat: DecimalFormat? = null private var numberPicker: NumberPicker? = null - constructor(mainApp: MainApp, value: Double, minValue: Double, maxValue: Double, step: Double, decimalFormat: DecimalFormat) : this(mainApp) { + constructor(injector: HasAndroidInjector, value: Double, minValue: Double, maxValue: Double, step: Double, decimalFormat: DecimalFormat) : this(injector) { this.value = value this.minValue = minValue this.maxValue = maxValue @@ -22,7 +22,7 @@ class InputDouble(mainApp: MainApp) : Element(mainApp) { this.decimalFormat = decimalFormat } - constructor(mainApp: MainApp, inputDouble: InputDouble) : this(mainApp) { + constructor(injector: HasAndroidInjector, inputDouble: InputDouble) : this(injector) { this.value = inputDouble.value this.minValue = inputDouble.minValue this.maxValue = inputDouble.maxValue diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDuration.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDuration.kt index 777137316c..cab16d2502 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDuration.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDuration.kt @@ -1,17 +1,17 @@ package info.nightscout.androidaps.plugins.general.automation.elements import android.widget.LinearLayout -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.utils.NumberPicker import java.text.DecimalFormat -class InputDuration(mainApp: MainApp) : Element(mainApp) { +class InputDuration(injector: HasAndroidInjector) : Element(injector) { enum class TimeUnit { MINUTES, HOURS } - constructor(mainApp: MainApp, value: Int, unit: TimeUnit) : this(mainApp) { + constructor(injector: HasAndroidInjector, value: Int, unit: TimeUnit) : this(injector) { this.unit = unit this.value = value } @@ -31,7 +31,7 @@ class InputDuration(mainApp: MainApp) : Element(mainApp) { } fun duplicate(): InputDuration { - val i = InputDuration(mainApp) + val i = InputDuration(injector) i.unit = unit i.value = value return i diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputInsulin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputInsulin.kt index 01651dc780..f822a971f4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputInsulin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputInsulin.kt @@ -1,15 +1,15 @@ package info.nightscout.androidaps.plugins.general.automation.elements import android.widget.LinearLayout -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.utils.NumberPicker import java.text.DecimalFormat -class InputInsulin(mainApp: MainApp) : Element(mainApp) { +class InputInsulin(injector: HasAndroidInjector) : Element(injector) { var value = 0.0 - constructor(mainApp: MainApp, another: InputInsulin) : this(mainApp) { + constructor(injector: HasAndroidInjector, another: InputInsulin) : this(injector) { value = another.value } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputLocationMode.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputLocationMode.kt index 9571e9da83..9e3f7280cc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputLocationMode.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputLocationMode.kt @@ -6,12 +6,15 @@ import android.widget.ArrayAdapter import android.widget.LinearLayout import android.widget.Spinner import androidx.annotation.StringRes -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.utils.resources.ResourceHelper import java.util.* +import javax.inject.Inject + +class InputLocationMode(injector: HasAndroidInjector) : Element(injector) { + @Inject lateinit var resourceHelper: ResourceHelper -class InputLocationMode(mainApp: MainApp) : Element(mainApp) { enum class Mode { INSIDE, OUTSIDE, GOING_IN, GOING_OUT; @@ -43,7 +46,7 @@ class InputLocationMode(mainApp: MainApp) : Element(mainApp) { var value: Mode = Mode.INSIDE - constructor(mainApp: MainApp, value: InputLocationMode.Mode) : this(mainApp) { + constructor(injector: HasAndroidInjector, value: InputLocationMode.Mode) : this(injector) { this.value = value } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputPercent.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputPercent.kt index 6412bfb6cd..7b1f739ed7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputPercent.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputPercent.kt @@ -1,15 +1,15 @@ package info.nightscout.androidaps.plugins.general.automation.elements import android.widget.LinearLayout -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.utils.NumberPicker import java.text.DecimalFormat -class InputPercent(mainApp: MainApp) : Element(mainApp) { +class InputPercent(injector: HasAndroidInjector) : Element(injector) { var value: Double = 100.0 - constructor(mainApp: MainApp, value: Double) : this(mainApp) { + constructor(injector: HasAndroidInjector, value: Double) : this(injector) { this.value = value } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputProfileName.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputProfileName.kt index 04daea5c66..57e010eabe 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputProfileName.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputProfileName.kt @@ -6,19 +6,24 @@ import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.LinearLayout import android.widget.Spinner -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.utils.resources.ResourceHelper +import javax.inject.Inject + +class InputProfileName(injector: HasAndroidInjector) : Element(injector) { + @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var activePlugin: ActivePluginProvider -class InputProfileName(mainApp: MainApp) : Element(mainApp) { var value: String = "" - constructor(mainApp: MainApp, name: String) : this(mainApp) { + constructor(injector: HasAndroidInjector, name: String) : this(injector) { value = name } override fun addToLayout(root: LinearLayout) { - val profileStore = configBuilderPlugin.activeProfileInterface.profile ?: return + val profileStore = activePlugin.activeProfileInterface.profile ?: return val profileList = profileStore.getProfileList() val adapter = ArrayAdapter(root.context, R.layout.spinner_centered, profileList) adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputString.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputString.kt index a857fb2ecb..0af3e88318 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputString.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputString.kt @@ -5,9 +5,9 @@ import android.text.TextWatcher import android.view.ViewGroup import android.widget.EditText import android.widget.LinearLayout -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector -class InputString(mainApp: MainApp) : Element(mainApp) { +class InputString(injector: HasAndroidInjector) : Element(injector) { var textWatcher: TextWatcher = object : TextWatcher { override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {} @@ -17,7 +17,7 @@ class InputString(mainApp: MainApp) : Element(mainApp) { } var value = "" - constructor(mainApp: MainApp, value: String) : this(mainApp) { + constructor(injector: HasAndroidInjector, value: String) : this(injector) { this.value = value } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTempTarget.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTempTarget.kt index 0b8d2a1a15..fa1939e951 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTempTarget.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTempTarget.kt @@ -1,13 +1,13 @@ package info.nightscout.androidaps.plugins.general.automation.elements import android.widget.LinearLayout +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.utils.NumberPicker import java.text.DecimalFormat -class InputTempTarget(mainApp: MainApp) : Element(mainApp) { +class InputTempTarget(injector: HasAndroidInjector) : Element(injector) { var units = Constants.MGDL var value = 0.0 @@ -15,7 +15,7 @@ class InputTempTarget(mainApp: MainApp) : Element(mainApp) { value = if (units == Constants.MMOL) 6.0 else 110.0 } - constructor(mainApp: MainApp, inputTempTarget: InputTempTarget) : this(mainApp) { + constructor(injector: HasAndroidInjector, inputTempTarget: InputTempTarget) : this(injector) { value = inputTempTarget.value units = inputTempTarget.units } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTime.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTime.kt index 00a66a5916..34bc74560c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTime.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTime.kt @@ -1,20 +1,26 @@ package info.nightscout.androidaps.plugins.general.automation.elements import android.app.TimePickerDialog +import android.content.Context import android.graphics.Typeface import android.text.format.DateFormat import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.MidnightTime import info.nightscout.androidaps.utils.T +import info.nightscout.androidaps.utils.resources.ResourceHelper import java.util.* +import javax.inject.Inject + +class InputTime(injector: HasAndroidInjector) : Element(injector) { + @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var context: Context -class InputTime(mainApp: MainApp) : Element(mainApp) { var value: Int = getMinSinceMidnight(DateUtil.now()) override fun addToLayout(root: LinearLayout) { @@ -34,7 +40,7 @@ class InputTime(mainApp: MainApp) : Element(mainApp) { TimePickerDialog(it, startTimeSetListener, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), - DateFormat.is24HourFormat(mainApp) + DateFormat.is24HourFormat(context) ).show() } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTimeRange.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTimeRange.kt index b97ed8a1b7..18cf98fc73 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTimeRange.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTimeRange.kt @@ -1,20 +1,26 @@ package info.nightscout.androidaps.plugins.general.automation.elements import android.app.TimePickerDialog +import android.content.Context import android.graphics.Typeface import android.text.format.DateFormat import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.MidnightTime import info.nightscout.androidaps.utils.T +import info.nightscout.androidaps.utils.resources.ResourceHelper import java.util.* +import javax.inject.Inject + +class InputTimeRange(injector: HasAndroidInjector) : Element(injector) { + @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var context: Context -class InputTimeRange(mainApp: MainApp) : Element(mainApp) { var start: Int = getMinSinceMidnight(DateUtil.now()) var end: Int = getMinSinceMidnight(DateUtil.now()) @@ -38,7 +44,7 @@ class InputTimeRange(mainApp: MainApp) : Element(mainApp) { TimePickerDialog(it, startTimeSetListener, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), - DateFormat.is24HourFormat(mainApp) + DateFormat.is24HourFormat(context) ).show() } } @@ -55,7 +61,7 @@ class InputTimeRange(mainApp: MainApp) : Element(mainApp) { TimePickerDialog(it, endTimeSetListener, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), - DateFormat.is24HourFormat(mainApp) + DateFormat.is24HourFormat(context) ).show() } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputWeekDay.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputWeekDay.kt index 4f4d11787b..df46890d50 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputWeekDay.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputWeekDay.kt @@ -5,11 +5,11 @@ import android.view.ViewGroup import android.widget.LinearLayout import androidx.annotation.StringRes import com.dpro.widgets.WeekdaysPicker -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import java.util.* -class InputWeekDay(mainApp: MainApp) : Element(mainApp) { +class InputWeekDay(injector: HasAndroidInjector) : Element(injector) { enum class DayOfWeek { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/LabelWithElement.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/LabelWithElement.kt index 5666e0e9f9..cb2a3ffc0a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/LabelWithElement.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/LabelWithElement.kt @@ -5,14 +5,18 @@ import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TableLayout import android.widget.TextView -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.utils.resources.ResourceHelper +import javax.inject.Inject + +class LabelWithElement(injector: HasAndroidInjector) : Element(injector) { + @Inject lateinit var resourceHelper: ResourceHelper -class LabelWithElement(mainApp: MainApp) : Element(mainApp) { var element: Element? = null var textPre: String = "" var textPost: String = "" - constructor(mainApp: MainApp, textPre: String, textPost: String, element: Element) : this(mainApp) { + constructor(injector: HasAndroidInjector, textPre: String, textPost: String, element: Element) : this(injector) { this.textPre = textPre this.textPost = textPost this.element = element diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/StaticLabel.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/StaticLabel.kt index f949a16722..2f7b4bcc25 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/StaticLabel.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/StaticLabel.kt @@ -4,19 +4,23 @@ import android.graphics.Typeface import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.plugins.general.automation.triggers.Trigger +import info.nightscout.androidaps.utils.resources.ResourceHelper +import javax.inject.Inject + +class StaticLabel(injector: HasAndroidInjector) : Element(injector) { + @Inject lateinit var resourceHelper: ResourceHelper -class StaticLabel(mainApp: MainApp) : Element(mainApp) { var label = "" var trigger: Trigger? = null - constructor(mainApp: MainApp, label: String, trigger: Trigger) : this(mainApp) { + constructor(injector: HasAndroidInjector, label: String, trigger: Trigger) : this(injector) { this.label = label this.trigger = trigger } - constructor(mainApp: MainApp, resourceId: Int, trigger: Trigger) : this(mainApp) { + constructor(injector: HasAndroidInjector, resourceId: Int, trigger: Trigger) : this(injector) { label = resourceHelper.gs(resourceId) this.trigger = trigger } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/Trigger.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/Trigger.kt index ad21334bd5..3890deb60d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/Trigger.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/Trigger.kt @@ -8,12 +8,11 @@ import android.widget.LinearLayout import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.google.common.base.Optional -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.general.automation.dialogs.ChooseTriggerDialog import info.nightscout.androidaps.plugins.general.automation.events.EventTriggerChanged @@ -22,7 +21,6 @@ import info.nightscout.androidaps.plugins.general.automation.events.EventTrigger import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.services.LastLocationDataContainer -import info.nightscout.androidaps.services.LocationService import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import org.json.JSONException @@ -30,7 +28,7 @@ import org.json.JSONObject import javax.inject.Inject import kotlin.reflect.full.primaryConstructor -abstract class Trigger(val mainApp: MainApp) { +abstract class Trigger(val injector: HasAndroidInjector) { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var resourceHelper: ResourceHelper @@ -38,11 +36,11 @@ abstract class Trigger(val mainApp: MainApp) { @Inject lateinit var sp: SP @Inject lateinit var locationDataContainer: LastLocationDataContainer @Inject lateinit var treatmentsPlugin: TreatmentsPlugin - @Inject lateinit var activePluginProvider: ActivePluginProvider + @Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin init { - mainApp.androidInjector().inject(this) + injector.androidInjector().inject(this) } abstract fun shouldRun(): Boolean @@ -77,7 +75,7 @@ abstract class Trigger(val mainApp: MainApp) { val type = obj.getString("type") val data = obj.getJSONObject("data") val clazz = Class.forName(type).kotlin - return (clazz.primaryConstructor?.call(mainApp) as Trigger).fromJSON(data?.toString() + return (clazz.primaryConstructor?.call(injector) as Trigger).fromJSON(data?.toString() ?: "") } catch (e: ClassNotFoundException) { aapsLogger.error("Unhandled exception", e) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerAutosensValue.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerAutosensValue.kt index 3ce4d72950..7fb9aaa560 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerAutosensValue.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerAutosensValue.kt @@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.general.automation.triggers import android.widget.LinearLayout import com.google.common.base.Optional -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.general.automation.elements.Comparator @@ -15,18 +15,18 @@ import info.nightscout.androidaps.utils.JsonHelper.safeGetString import org.json.JSONObject import java.text.DecimalFormat -class TriggerAutosensValue(mainApp: MainApp) : Trigger(mainApp) { +class TriggerAutosensValue(injector: HasAndroidInjector) : Trigger(injector) { private val minValue = (sp.getDouble(R.string.key_openapsama_autosens_min, 0.7) * 100).toInt() private val maxValue = (sp.getDouble(R.string.key_openapsama_autosens_max, 1.2) * 100).toInt() private val step = 1.0 private val decimalFormat = DecimalFormat("1") - private var autosens: InputDouble = InputDouble(mainApp, 100.0, minValue.toDouble(), maxValue.toDouble(), step, decimalFormat) + private var autosens: InputDouble = InputDouble(injector, 100.0, minValue.toDouble(), maxValue.toDouble(), step, decimalFormat) - var comparator: Comparator = Comparator(mainApp) + var comparator: Comparator = Comparator(injector) - private constructor(mainApp: MainApp, triggerAutosensValue: TriggerAutosensValue) : this(mainApp) { - autosens = InputDouble(mainApp, triggerAutosensValue.autosens) - comparator = Comparator(mainApp, triggerAutosensValue.comparator.value) + private constructor(injector: HasAndroidInjector, triggerAutosensValue: TriggerAutosensValue) : this(injector) { + autosens = InputDouble(injector, triggerAutosensValue.autosens) + comparator = Comparator(injector, triggerAutosensValue.comparator.value) } override fun shouldRun(): Boolean { @@ -70,13 +70,13 @@ class TriggerAutosensValue(mainApp: MainApp) : Trigger(mainApp) { override fun icon(): Optional = Optional.of(R.drawable.`as`) - override fun duplicate(): Trigger = TriggerAutosensValue(mainApp, this) + override fun duplicate(): Trigger = TriggerAutosensValue(injector, this) override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(StaticLabel(mainApp, R.string.autosenslabel, this)) + .add(StaticLabel(injector, R.string.autosenslabel, this)) .add(comparator) - .add(LabelWithElement(mainApp, resourceHelper.gs(R.string.autosenslabel) + ": ", "", autosens)) + .add(LabelWithElement(injector, resourceHelper.gs(R.string.autosenslabel) + ": ", "", autosens)) .build(root) } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBg.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBg.kt index f5e3e17d04..0be8e9a510 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBg.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBg.kt @@ -2,8 +2,8 @@ package info.nightscout.androidaps.plugins.general.automation.triggers import android.widget.LinearLayout import com.google.common.base.Optional +import dagger.android.HasAndroidInjector 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.logging.LTag @@ -16,18 +16,18 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.utils.JsonHelper import org.json.JSONObject -class TriggerBg(mainApp: MainApp) : Trigger(mainApp) { - private var bg = InputBg(mainApp) - var comparator = Comparator(mainApp) +class TriggerBg(injector: HasAndroidInjector) : Trigger(injector) { + private var bg = InputBg(injector) + var comparator = Comparator(injector) - constructor(mainApp: MainApp, value: Double, units: String, compare: Comparator.Compare) : this(mainApp) { - bg = InputBg(mainApp, value, units) - comparator = Comparator(mainApp, compare) + constructor(injector: HasAndroidInjector, value: Double, units: String, compare: Comparator.Compare) : this(injector) { + bg = InputBg(injector, value, units) + comparator = Comparator(injector, compare) } - constructor(mainApp: MainApp, triggerBg: TriggerBg) : this(mainApp) { - bg = InputBg(mainApp, triggerBg.bg.value, triggerBg.bg.units) - comparator = Comparator(mainApp, triggerBg.comparator.value) + constructor(injector: HasAndroidInjector, triggerBg: TriggerBg) : this(injector) { + bg = InputBg(injector, triggerBg.bg.value, triggerBg.bg.units) + comparator = Comparator(injector, triggerBg.comparator.value) } override fun shouldRun(): Boolean { @@ -78,13 +78,13 @@ class TriggerBg(mainApp: MainApp) : Trigger(mainApp) { override fun icon(): Optional = Optional.of(R.drawable.icon_cp_bgcheck) - override fun duplicate(): Trigger = TriggerBg(mainApp, this) + override fun duplicate(): Trigger = TriggerBg(injector, this) override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(StaticLabel(mainApp, R.string.glucose, this)) + .add(StaticLabel(injector, R.string.glucose, this)) .add(comparator) - .add(LabelWithElement(mainApp, resourceHelper.gs(R.string.glucose_u, bg.units), "", bg)) + .add(LabelWithElement(injector, resourceHelper.gs(R.string.glucose_u, bg.units), "", bg)) .build(root) } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgo.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgo.kt index fc1888a0f6..9a7b6e9563 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgo.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgo.kt @@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.general.automation.triggers import android.widget.LinearLayout import com.google.common.base.Optional -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.general.automation.elements.Comparator @@ -15,13 +15,13 @@ import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.androidaps.utils.JsonHelper.safeGetString import org.json.JSONObject -class TriggerBolusAgo(mainApp: MainApp) : Trigger(mainApp) { - private var minutesAgo: InputDuration = InputDuration(mainApp, 0, InputDuration.TimeUnit.MINUTES) - var comparator: Comparator = Comparator(mainApp) +class TriggerBolusAgo(injector: HasAndroidInjector) : Trigger(injector) { + private var minutesAgo: InputDuration = InputDuration(injector, 0, InputDuration.TimeUnit.MINUTES) + var comparator: Comparator = Comparator(injector) - private constructor(mainApp: MainApp, triggerBolusAgo: TriggerBolusAgo) : this(mainApp) { - minutesAgo = InputDuration(mainApp, triggerBolusAgo.minutesAgo.value, InputDuration.TimeUnit.MINUTES) - comparator = Comparator(mainApp, triggerBolusAgo.comparator.value) + private constructor(injector: HasAndroidInjector, triggerBolusAgo: TriggerBolusAgo) : this(injector) { + minutesAgo = InputDuration(injector, triggerBolusAgo.minutesAgo.value, InputDuration.TimeUnit.MINUTES) + comparator = Comparator(injector, triggerBolusAgo.comparator.value) } override fun shouldRun(): Boolean { @@ -69,13 +69,13 @@ class TriggerBolusAgo(mainApp: MainApp) : Trigger(mainApp) { override fun icon(): Optional = Optional.of(R.drawable.icon_bolus) - override fun duplicate(): Trigger = TriggerBolusAgo(mainApp, this) + override fun duplicate(): Trigger = TriggerBolusAgo(injector, this) override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(StaticLabel(mainApp, R.string.lastboluslabel, this)) + .add(StaticLabel(injector, R.string.lastboluslabel, this)) .add(comparator) - .add(LabelWithElement(mainApp, resourceHelper.gs(R.string.lastboluslabel) + ": ", "", minutesAgo)) + .add(LabelWithElement(injector, resourceHelper.gs(R.string.lastboluslabel) + ": ", "", minutesAgo)) .build(root) } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerCOB.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerCOB.kt index 58ae143167..1d1299c93b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerCOB.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerCOB.kt @@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.general.automation.triggers import android.widget.LinearLayout import com.google.common.base.Optional -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.general.automation.elements.Comparator @@ -15,15 +15,15 @@ import info.nightscout.androidaps.utils.JsonHelper.safeGetDouble import org.json.JSONObject import java.text.DecimalFormat -class TriggerCOB(mainApp: MainApp) : Trigger(mainApp) { +class TriggerCOB(injector: HasAndroidInjector) : Trigger(injector) { private val minValue = 0 private val maxValue = sp.getInt(R.string.key_treatmentssafety_maxcarbs, 48) - private var cob: InputDouble = InputDouble(mainApp, 0.0, minValue.toDouble(), maxValue.toDouble(), 1.0, DecimalFormat("1")) - var comparator: Comparator = Comparator(mainApp) + private var cob: InputDouble = InputDouble(injector, 0.0, minValue.toDouble(), maxValue.toDouble(), 1.0, DecimalFormat("1")) + var comparator: Comparator = Comparator(injector) - private constructor(mainApp: MainApp, triggerCOB: TriggerCOB) : this(mainApp) { - cob = InputDouble(mainApp, triggerCOB.cob) - comparator = Comparator(mainApp, triggerCOB.comparator.value) + private constructor(injector: HasAndroidInjector, triggerCOB: TriggerCOB) : this(injector) { + cob = InputDouble(injector, triggerCOB.cob) + comparator = Comparator(injector, triggerCOB.comparator.value) } override fun shouldRun(): Boolean { @@ -69,13 +69,13 @@ class TriggerCOB(mainApp: MainApp) : Trigger(mainApp) { override fun icon(): Optional = Optional.of(R.drawable.icon_cp_bolus_carbs) - override fun duplicate(): Trigger = TriggerCOB(mainApp, this) + override fun duplicate(): Trigger = TriggerCOB(injector, this) override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(StaticLabel(mainApp, R.string.triggercoblabel, this)) + .add(StaticLabel(injector, R.string.triggercoblabel, this)) .add(comparator) - .add(LabelWithElement(mainApp, resourceHelper.gs(R.string.triggercoblabel) + ": ", "", cob)) + .add(LabelWithElement(injector, resourceHelper.gs(R.string.triggercoblabel) + ": ", "", cob)) .build(root) } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerConnector.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerConnector.kt index 612916b522..7358eaa7ff 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerConnector.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerConnector.kt @@ -9,7 +9,7 @@ import android.widget.LinearLayout import android.widget.Spinner import androidx.annotation.StringRes import com.google.common.base.Optional -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.utils.JsonHelper.safeGetString @@ -18,11 +18,11 @@ import org.json.JSONArray import org.json.JSONObject import java.util.* -class TriggerConnector(mainApp: MainApp) : Trigger(mainApp) { +class TriggerConnector(injector: HasAndroidInjector) : Trigger(injector) { var list: MutableList = ArrayList() private var connectorType: Type = Type.AND // TODO move to TriggerConnector - //var connector: TriggerConnector = TriggerConnector(mainApp, TriggerConnector.Type.AND) + //var connector: TriggerConnector = TriggerConnector(injector, TriggerConnector.Type.AND) enum class Type { AND, OR, XOR; @@ -52,7 +52,7 @@ class TriggerConnector(mainApp: MainApp) : Trigger(mainApp) { } } - constructor(mainApp: MainApp, connectorType: Type) : this(mainApp) { + constructor(injector: HasAndroidInjector, connectorType: Type) : this(injector) { this.connectorType = connectorType } @@ -120,7 +120,7 @@ class TriggerConnector(mainApp: MainApp) : Trigger(mainApp) { override fun icon(): Optional = Optional.absent() - override fun duplicate(): Trigger = TriggerConnector(mainApp, connectorType) + override fun duplicate(): Trigger = TriggerConnector(injector, connectorType) override fun generateDialog(root: LinearLayout) { val padding = resourceHelper.dpToPx(5) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDelta.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDelta.kt index 4470f94fe3..61f5bd3ef5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDelta.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDelta.kt @@ -2,8 +2,8 @@ package info.nightscout.androidaps.plugins.general.automation.triggers import android.widget.LinearLayout import com.google.common.base.Optional +import dagger.android.HasAndroidInjector 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.logging.LTag @@ -18,11 +18,11 @@ import info.nightscout.androidaps.utils.JsonHelper import org.json.JSONObject import java.text.DecimalFormat -class TriggerDelta(mainApp: MainApp) : Trigger(mainApp) { +class TriggerDelta(injector: HasAndroidInjector) : Trigger(injector) { var units: String = Constants.MGDL - private var delta: InputDelta = InputDelta(mainApp) - var comparator: Comparator = Comparator(mainApp) + private var delta: InputDelta = InputDelta(injector) + var comparator: Comparator = Comparator(injector) companion object { private const val MMOL_MAX = 4.0 @@ -31,14 +31,14 @@ class TriggerDelta(mainApp: MainApp) : Trigger(mainApp) { init { units = profileFunction.getUnits() - delta = if (units == Constants.MMOL) InputDelta(mainApp, 0.0, (-MMOL_MAX), MMOL_MAX, 0.1, DecimalFormat("0.1"), DeltaType.DELTA) - else InputDelta(mainApp, 0.0, (-MGDL_MAX), MGDL_MAX, 1.0, DecimalFormat("1"), DeltaType.DELTA) + delta = if (units == Constants.MMOL) InputDelta(injector, 0.0, (-MMOL_MAX), MMOL_MAX, 0.1, DecimalFormat("0.1"), DeltaType.DELTA) + else InputDelta(injector, 0.0, (-MGDL_MAX), MGDL_MAX, 1.0, DecimalFormat("1"), DeltaType.DELTA) } - private constructor(mainApp: MainApp, triggerDelta: TriggerDelta) : this(mainApp) { + private constructor(injector: HasAndroidInjector, triggerDelta: TriggerDelta) : this(injector) { units = triggerDelta.units - delta = InputDelta(mainApp, triggerDelta.delta) - comparator = Comparator(mainApp, triggerDelta.comparator.value) + delta = InputDelta(injector, triggerDelta.delta) + comparator = Comparator(injector, triggerDelta.comparator.value) } override fun shouldRun(): Boolean { @@ -81,8 +81,8 @@ class TriggerDelta(mainApp: MainApp) : Trigger(mainApp) { val type = DeltaType.valueOf(JsonHelper.safeGetString(d, "deltaType", "")) val value = JsonHelper.safeGetDouble(d, "value") delta = - if (units == Constants.MMOL) InputDelta(mainApp, value, (-MMOL_MAX), MMOL_MAX, 0.1, DecimalFormat("0.1"), type) - else InputDelta(mainApp, value, (-MGDL_MAX), MGDL_MAX, 1.0, DecimalFormat("1"), type) + if (units == Constants.MMOL) InputDelta(injector, value, (-MMOL_MAX), MMOL_MAX, 0.1, DecimalFormat("0.1"), type) + else InputDelta(injector, value, (-MGDL_MAX), MGDL_MAX, 1.0, DecimalFormat("1"), type) comparator.setValue(Comparator.Compare.valueOf(JsonHelper.safeGetString(d, "comparator")!!)) return this } @@ -94,13 +94,13 @@ class TriggerDelta(mainApp: MainApp) : Trigger(mainApp) { override fun icon(): Optional = Optional.of(R.drawable.icon_auto_delta) - override fun duplicate(): Trigger = TriggerDelta(mainApp, this) + override fun duplicate(): Trigger = TriggerDelta(injector, this) override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(StaticLabel(mainApp, R.string.deltalabel, this)) + .add(StaticLabel(injector, R.string.deltalabel, this)) .add(comparator) - .add(LabelWithElement(mainApp, resourceHelper.gs(R.string.deltalabel_u, units) + ": ", "", delta)) + .add(LabelWithElement(injector, resourceHelper.gs(R.string.deltalabel_u, units) + ": ", "", delta)) .build(root) } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDummy.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDummy.kt index 8f7982db52..c98b78d32a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDummy.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDummy.kt @@ -1,10 +1,10 @@ package info.nightscout.androidaps.plugins.general.automation.triggers import com.google.common.base.Optional -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector // Used for instantiation of other triggers only -class TriggerDummy(mainApp: MainApp) : Trigger(mainApp) { +class TriggerDummy(injector: HasAndroidInjector) : Trigger(injector) { override fun shouldRun(): Boolean { throw NotImplementedError("An operation is not implemented") diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerIob.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerIob.kt index 04c4b49ed4..09d4a49892 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerIob.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerIob.kt @@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.general.automation.triggers import android.widget.LinearLayout import com.google.common.base.Optional -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.general.automation.elements.Comparator @@ -14,13 +14,13 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.JsonHelper import org.json.JSONObject -class TriggerIob(mainApp: MainApp) : Trigger(mainApp) { - private var insulin = InputInsulin(mainApp) - var comparator: Comparator = Comparator(mainApp) +class TriggerIob(injector: HasAndroidInjector) : Trigger(injector) { + private var insulin = InputInsulin(injector) + var comparator: Comparator = Comparator(injector) - constructor(mainApp: MainApp, triggerIob: TriggerIob) : this(mainApp) { - insulin = InputInsulin(mainApp, triggerIob.insulin) - comparator = Comparator(mainApp, triggerIob.comparator.value) + constructor(injector: HasAndroidInjector, triggerIob: TriggerIob) : this(injector) { + insulin = InputInsulin(injector, triggerIob.insulin) + comparator = Comparator(injector, triggerIob.comparator.value) } val value: Double = 0.0 @@ -60,13 +60,13 @@ class TriggerIob(mainApp: MainApp) : Trigger(mainApp) { override fun icon(): Optional = Optional.of(R.drawable.ic_keyboard_capslock) - override fun duplicate(): Trigger = TriggerIob(mainApp, this) + override fun duplicate(): Trigger = TriggerIob(injector, this) override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(StaticLabel(mainApp, R.string.iob, this)) + .add(StaticLabel(injector, R.string.iob, this)) .add(comparator) - .add(LabelWithElement(mainApp, resourceHelper.gs(R.string.iob_u), "", insulin)) + .add(LabelWithElement(injector, resourceHelper.gs(R.string.iob_u), "", insulin)) .build(root) } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocation.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocation.kt index 75c12389b8..a9f3c936d9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocation.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocation.kt @@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.general.automation.triggers import android.location.Location import android.widget.LinearLayout import com.google.common.base.Optional -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.general.automation.elements.* @@ -11,12 +11,12 @@ import info.nightscout.androidaps.utils.JsonHelper import org.json.JSONObject import java.text.DecimalFormat -class TriggerLocation(mainApp: MainApp) : Trigger(mainApp) { - var latitude = InputDouble(mainApp, 0.0, -90.0, +90.0, 0.000001, DecimalFormat("0.000000")) - var longitude = InputDouble(mainApp, 0.0, -180.0, +180.0, 0.000001, DecimalFormat("0.000000")) - var distance = InputDouble(mainApp, 200.0, 0.0, 100000.0, 10.0, DecimalFormat("0")) - var modeSelected = InputLocationMode(mainApp) - var name: InputString = InputString(mainApp) +class TriggerLocation(injector: HasAndroidInjector) : Trigger(injector) { + var latitude = InputDouble(injector, 0.0, -90.0, +90.0, 0.000001, DecimalFormat("0.000000")) + var longitude = InputDouble(injector, 0.0, -180.0, +180.0, 0.000001, DecimalFormat("0.000000")) + var distance = InputDouble(injector, 200.0, 0.0, 100000.0, 10.0, DecimalFormat("0")) + var modeSelected = InputLocationMode(injector) + var name: InputString = InputString(injector) var lastMode = InputLocationMode.Mode.INSIDE private val buttonAction = Runnable { @@ -27,11 +27,11 @@ class TriggerLocation(mainApp: MainApp) : Trigger(mainApp) { } } - private constructor(mainApp: MainApp, triggerLocation: TriggerLocation) : this(mainApp) { - latitude = InputDouble(mainApp, triggerLocation.latitude) - longitude = InputDouble(mainApp, triggerLocation.longitude) - distance = InputDouble(mainApp, triggerLocation.distance) - modeSelected = InputLocationMode(mainApp, triggerLocation.modeSelected.value) + private constructor(injector: HasAndroidInjector, triggerLocation: TriggerLocation) : this(injector) { + latitude = InputDouble(injector, triggerLocation.latitude) + longitude = InputDouble(injector, triggerLocation.longitude) + distance = InputDouble(injector, triggerLocation.distance) + modeSelected = InputLocationMode(injector, triggerLocation.modeSelected.value) if (modeSelected.value == InputLocationMode.Mode.GOING_OUT) lastMode = InputLocationMode.Mode.OUTSIDE name = triggerLocation.name @@ -87,17 +87,17 @@ class TriggerLocation(mainApp: MainApp) : Trigger(mainApp) { override fun icon(): Optional = Optional.of(R.drawable.ic_location_on) - override fun duplicate(): Trigger = TriggerLocation(mainApp, this) + override fun duplicate(): Trigger = TriggerLocation(injector, this) override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(StaticLabel(mainApp, R.string.location, this)) - .add(LabelWithElement(mainApp, resourceHelper.gs(R.string.name_short), "", name)) - .add(LabelWithElement(mainApp, resourceHelper.gs(R.string.latitude_short), "", latitude)) - .add(LabelWithElement(mainApp, resourceHelper.gs(R.string.longitude_short), "", longitude)) - .add(LabelWithElement(mainApp, resourceHelper.gs(R.string.distance_short), "", distance)) - .add(LabelWithElement(mainApp, resourceHelper.gs(R.string.location_mode), "", modeSelected)) - .add(InputButton(mainApp, resourceHelper.gs(R.string.currentlocation), buttonAction), locationDataContainer.lastLocation != null) + .add(StaticLabel(injector, R.string.location, this)) + .add(LabelWithElement(injector, resourceHelper.gs(R.string.name_short), "", name)) + .add(LabelWithElement(injector, resourceHelper.gs(R.string.latitude_short), "", latitude)) + .add(LabelWithElement(injector, resourceHelper.gs(R.string.longitude_short), "", longitude)) + .add(LabelWithElement(injector, resourceHelper.gs(R.string.distance_short), "", distance)) + .add(LabelWithElement(injector, resourceHelper.gs(R.string.location_mode), "", modeSelected)) + .add(InputButton(injector, resourceHelper.gs(R.string.currentlocation), buttonAction), locationDataContainer.lastLocation != null) .build(root) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerProfilePercent.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerProfilePercent.kt index 9de445e790..67bcb4196f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerProfilePercent.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerProfilePercent.kt @@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.general.automation.triggers import android.widget.LinearLayout import com.google.common.base.Optional -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.general.automation.elements.Comparator @@ -13,18 +13,18 @@ import info.nightscout.androidaps.plugins.general.automation.elements.StaticLabe import info.nightscout.androidaps.utils.JsonHelper import org.json.JSONObject -class TriggerProfilePercent(mainApp: MainApp) : Trigger(mainApp) { - private var pct = InputPercent(mainApp) - var comparator = Comparator(mainApp) +class TriggerProfilePercent(injector: HasAndroidInjector) : Trigger(injector) { + private var pct = InputPercent(injector) + var comparator = Comparator(injector) - constructor(mainApp: MainApp, value: Double, compare: Comparator.Compare) : this(mainApp) { - pct = InputPercent(mainApp, value) - comparator = Comparator(mainApp, compare) + constructor(injector: HasAndroidInjector, value: Double, compare: Comparator.Compare) : this(injector) { + pct = InputPercent(injector, value) + comparator = Comparator(injector, compare) } - constructor(mainApp: MainApp, triggerProfilePercent: TriggerProfilePercent) : this(mainApp) { - pct = InputPercent(mainApp, triggerProfilePercent.pct.value) - comparator = Comparator(mainApp, triggerProfilePercent.comparator.value) + constructor(injector: HasAndroidInjector, triggerProfilePercent: TriggerProfilePercent) : this(injector) { + pct = InputPercent(injector, triggerProfilePercent.pct.value) + comparator = Comparator(injector, triggerProfilePercent.comparator.value) } override fun shouldRun(): Boolean { @@ -69,13 +69,13 @@ class TriggerProfilePercent(mainApp: MainApp) : Trigger(mainApp) { override fun icon(): Optional = Optional.of(R.drawable.icon_actions_profileswitch) - override fun duplicate(): Trigger = TriggerProfilePercent(mainApp, this) + override fun duplicate(): Trigger = TriggerProfilePercent(injector, this) override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(StaticLabel(mainApp, R.string.profilepercentage, this)) + .add(StaticLabel(injector, R.string.profilepercentage, this)) .add(comparator) - .add(LabelWithElement(mainApp, resourceHelper.gs(R.string.percent_u), "", pct)) + .add(LabelWithElement(injector, resourceHelper.gs(R.string.percent_u), "", pct)) .build(root) } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnection.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnection.kt index 05ba096001..235f14d6a1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnection.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnection.kt @@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.general.automation.triggers import android.widget.LinearLayout import com.google.common.base.Optional -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.general.automation.elements.Comparator @@ -15,22 +15,22 @@ import info.nightscout.androidaps.utils.JsonHelper.safeGetInt import info.nightscout.androidaps.utils.JsonHelper.safeGetString import org.json.JSONObject -class TriggerPumpLastConnection(mainApp: MainApp) : Trigger(mainApp) { - private var minutesAgo = InputDuration(mainApp) - private var comparator = Comparator(mainApp) +class TriggerPumpLastConnection(injector: HasAndroidInjector) : Trigger(injector) { + private var minutesAgo = InputDuration(injector) + private var comparator = Comparator(injector) - constructor(mainApp: MainApp, value: Int, unit: InputDuration.TimeUnit, compare: Comparator.Compare) : this(mainApp) { - minutesAgo = InputDuration(mainApp, value, unit) - comparator = Comparator(mainApp, compare) + constructor(injector: HasAndroidInjector, value: Int, unit: InputDuration.TimeUnit, compare: Comparator.Compare) : this(injector) { + minutesAgo = InputDuration(injector, value, unit) + comparator = Comparator(injector, compare) } - constructor(mainApp: MainApp, triggerPumpLastConnection: TriggerPumpLastConnection) : this(mainApp) { - minutesAgo = InputDuration(mainApp, triggerPumpLastConnection.minutesAgo.value, triggerPumpLastConnection.minutesAgo.unit) - comparator = Comparator(mainApp, triggerPumpLastConnection.comparator.value) + constructor(injector: HasAndroidInjector, triggerPumpLastConnection: TriggerPumpLastConnection) : this(injector) { + minutesAgo = InputDuration(injector, triggerPumpLastConnection.minutesAgo.value, triggerPumpLastConnection.minutesAgo.unit) + comparator = Comparator(injector, triggerPumpLastConnection.comparator.value) } override fun shouldRun(): Boolean { - val lastConnection = activePluginProvider.activePump?.lastDataTime() ?: return false + val lastConnection = activePlugin.activePumpPlugin?.lastDataTime() ?: return false if (lastConnection == 0L && comparator.value === Comparator.Compare.IS_NOT_AVAILABLE) { aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription()) return true @@ -69,13 +69,13 @@ class TriggerPumpLastConnection(mainApp: MainApp) : Trigger(mainApp) { override fun icon(): Optional = Optional.of(R.drawable.remove) - override fun duplicate(): Trigger = TriggerPumpLastConnection(mainApp, this) + override fun duplicate(): Trigger = TriggerPumpLastConnection(injector, this) override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(StaticLabel(mainApp, R.string.automation_trigger_pump_last_connection_label, this)) + .add(StaticLabel(injector, R.string.automation_trigger_pump_last_connection_label, this)) .add(comparator) - .add(LabelWithElement(mainApp, resourceHelper.gs(R.string.automation_trigger_pump_last_connection_description) + ": ", "", minutesAgo)) + .add(LabelWithElement(injector, resourceHelper.gs(R.string.automation_trigger_pump_last_connection_description) + ": ", "", minutesAgo)) .build(root) } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTime.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTime.kt index e3f1029af9..459bef5e43 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTime.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTime.kt @@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.general.automation.triggers import android.widget.LinearLayout import com.google.common.base.Optional -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.logging.LTag @@ -17,11 +17,11 @@ import info.nightscout.androidaps.utils.T import org.json.JSONObject import java.util.* -class TriggerRecurringTime(mainApp: MainApp) : Trigger(mainApp) { - private val days = InputWeekDay(mainApp) - private val time = InputTime(mainApp) +class TriggerRecurringTime(injector: HasAndroidInjector) : Trigger(injector) { + private val days = InputWeekDay(injector) + private val time = InputTime(injector) - constructor(mainApp: MainApp, triggerRecurringTime: TriggerRecurringTime) : this(mainApp) { + constructor(injector: HasAndroidInjector, triggerRecurringTime: TriggerRecurringTime) : this(injector) { this.time.value = triggerRecurringTime.time.value if (days.weekdays.size >= 0) System.arraycopy(triggerRecurringTime.days.weekdays, 0, days.weekdays, 0, triggerRecurringTime.days.weekdays.size) @@ -86,7 +86,7 @@ class TriggerRecurringTime(mainApp: MainApp) : Trigger(mainApp) { override fun icon(): Optional = Optional.of(R.drawable.ic_access_alarm_24dp) - override fun duplicate(): Trigger = TriggerRecurringTime(mainApp, this) + override fun duplicate(): Trigger = TriggerRecurringTime(injector, this) private fun toMills(minutesSinceMidnight: Int): Long = MidnightTime.calc() + T.mins(minutesSinceMidnight.toLong()).msecs() @@ -94,7 +94,7 @@ class TriggerRecurringTime(mainApp: MainApp) : Trigger(mainApp) { override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(StaticLabel(mainApp, R.string.recurringTime, this)) + .add(StaticLabel(injector, R.string.recurringTime, this)) .add(days) .add(time) .build(root) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTarget.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTarget.kt index 1a4d5593c8..56cd9ab527 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTarget.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTarget.kt @@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.general.automation.triggers import android.widget.LinearLayout import com.google.common.base.Optional -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.general.automation.elements.ComparatorExists @@ -11,15 +11,15 @@ import info.nightscout.androidaps.plugins.general.automation.elements.StaticLabe import info.nightscout.androidaps.utils.JsonHelper import org.json.JSONObject -class TriggerTempTarget(mainApp: MainApp) : Trigger(mainApp) { - var comparator = ComparatorExists(mainApp) +class TriggerTempTarget(injector: HasAndroidInjector) : Trigger(injector) { + var comparator = ComparatorExists(injector) - constructor(mainApp: MainApp, compare: ComparatorExists.Compare) : this(mainApp) { - comparator = ComparatorExists(mainApp, compare) + constructor(injector: HasAndroidInjector, compare: ComparatorExists.Compare) : this(injector) { + comparator = ComparatorExists(injector, compare) } - constructor(mainApp: MainApp, triggerTempTarget: TriggerTempTarget) : this(mainApp) { - comparator = ComparatorExists(mainApp, triggerTempTarget.comparator.value) + constructor(injector: HasAndroidInjector, triggerTempTarget: TriggerTempTarget) : this(injector) { + comparator = ComparatorExists(injector, triggerTempTarget.comparator.value) } override fun shouldRun(): Boolean { @@ -58,11 +58,11 @@ class TriggerTempTarget(mainApp: MainApp) : Trigger(mainApp) { override fun icon(): Optional = Optional.of(R.drawable.ic_keyboard_tab) - override fun duplicate(): Trigger = TriggerTempTarget(mainApp, this) + override fun duplicate(): Trigger = TriggerTempTarget(injector, this) override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(StaticLabel(mainApp, R.string.careportal_temporarytarget, this)) + .add(StaticLabel(injector, R.string.careportal_temporarytarget, this)) .add(comparator) .build(root) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTime.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTime.kt index a4fa0dce0e..6404387af8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTime.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTime.kt @@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.general.automation.triggers import android.widget.LinearLayout import com.google.common.base.Optional -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.general.automation.elements.InputDateTime @@ -13,14 +13,14 @@ import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.androidaps.utils.T import org.json.JSONObject -class TriggerTime(mainApp: MainApp) : Trigger(mainApp) { - var time = InputDateTime(mainApp) +class TriggerTime(injector: HasAndroidInjector) : Trigger(injector) { + var time = InputDateTime(injector) - constructor(mainApp: MainApp, runAt: Long) : this(mainApp) { + constructor(injector: HasAndroidInjector, runAt: Long) : this(injector) { this.time.value = runAt } - constructor(mainApp: MainApp, triggerTime: TriggerTime) : this(mainApp) { + constructor(injector: HasAndroidInjector, triggerTime: TriggerTime) : this(injector) { this.time.value = triggerTime.time.value } @@ -56,11 +56,11 @@ class TriggerTime(mainApp: MainApp) : Trigger(mainApp) { override fun icon(): Optional = Optional.of(R.drawable.ic_access_alarm_24dp) - override fun duplicate(): Trigger = TriggerTime(mainApp, time.value) + override fun duplicate(): Trigger = TriggerTime(injector, time.value) override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(StaticLabel(mainApp, R.string.time, this)) + .add(StaticLabel(injector, R.string.time, this)) .add(time) .build(root) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRange.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRange.kt index 543c4096d4..82d749752e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRange.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRange.kt @@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.general.automation.triggers import android.widget.LinearLayout import com.google.common.base.Optional -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.logging.LTag @@ -16,17 +16,17 @@ import info.nightscout.androidaps.utils.T import org.json.JSONObject // Trigger for time range ( from 10:00AM till 13:00PM ) -class TriggerTimeRange(mainApp: MainApp) : Trigger(mainApp) { +class TriggerTimeRange(injector: HasAndroidInjector) : Trigger(injector) { // in minutes since midnight 60 means 1AM - var range = InputTimeRange(mainApp) + var range = InputTimeRange(injector) - constructor(mainApp: MainApp, start: Int, end: Int) : this(mainApp) { + constructor(injector: HasAndroidInjector, start: Int, end: Int) : this(injector) { range.start = start range.end = end } - constructor(mainApp: MainApp, triggerTimeRange: TriggerTimeRange) : this(mainApp) { + constructor(injector: HasAndroidInjector, triggerTimeRange: TriggerTimeRange) : this(injector) { range.start = triggerTimeRange.range.start range.end = triggerTimeRange.range.end } @@ -68,7 +68,7 @@ class TriggerTimeRange(mainApp: MainApp) : Trigger(mainApp) { override fun icon(): Optional = Optional.of(R.drawable.ic_access_alarm_24dp) - override fun duplicate(): Trigger = TriggerTimeRange(mainApp, range.start, range.end) + override fun duplicate(): Trigger = TriggerTimeRange(injector, range.start, range.end) private fun toMills(minutesSinceMidnight: Int): Long = MidnightTime.calc() + T.mins(minutesSinceMidnight.toLong()).msecs() @@ -76,7 +76,7 @@ class TriggerTimeRange(mainApp: MainApp) : Trigger(mainApp) { override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(StaticLabel(mainApp, R.string.time_range, this)) + .add(StaticLabel(injector, R.string.time_range, this)) .add(range) .build(root) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsid.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsid.kt index 54aacf8199..3c1ac20375 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsid.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsid.kt @@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.general.automation.triggers import android.widget.LinearLayout import com.google.common.base.Optional -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.general.automation.elements.Comparator @@ -14,18 +14,18 @@ import info.nightscout.androidaps.receivers.NetworkChangeReceiver import info.nightscout.androidaps.utils.JsonHelper import org.json.JSONObject -class TriggerWifiSsid(mainApp: MainApp) : Trigger(mainApp) { - private var ssid = InputString(mainApp) - var comparator = Comparator(mainApp) +class TriggerWifiSsid(injector: HasAndroidInjector) : Trigger(injector) { + private var ssid = InputString(injector) + var comparator = Comparator(injector) - constructor(mainApp: MainApp, ssid: String, compare: Comparator.Compare) : this(mainApp) { - this.ssid = InputString(mainApp, ssid) - comparator = Comparator(mainApp, compare) + constructor(injector: HasAndroidInjector, ssid: String, compare: Comparator.Compare) : this(injector) { + this.ssid = InputString(injector, ssid) + comparator = Comparator(injector, compare) } - constructor(mainApp: MainApp, triggerWifiSsid: TriggerWifiSsid) : this(mainApp) { - this.ssid = InputString(mainApp, triggerWifiSsid.ssid.value) - comparator = Comparator(mainApp, triggerWifiSsid.comparator.value) + constructor(injector: HasAndroidInjector, triggerWifiSsid: TriggerWifiSsid) : this(injector) { + this.ssid = InputString(injector, triggerWifiSsid.ssid.value) + comparator = Comparator(injector, triggerWifiSsid.comparator.value) } override fun shouldRun(): Boolean { @@ -66,13 +66,13 @@ class TriggerWifiSsid(mainApp: MainApp) : Trigger(mainApp) { override fun icon(): Optional = Optional.of(R.drawable.ic_network_wifi) - override fun duplicate(): Trigger = TriggerWifiSsid(mainApp, this) + override fun duplicate(): Trigger = TriggerWifiSsid(injector, this) override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(StaticLabel(mainApp, R.string.ns_wifi_ssids, this)) + .add(StaticLabel(injector, R.string.ns_wifi_ssids, this)) .add(comparator) - .add(LabelWithElement(mainApp, resourceHelper.gs(R.string.ns_wifi_ssids) + ": ", "", ssid)) + .add(LabelWithElement(injector, resourceHelper.gs(R.string.ns_wifi_ssids) + ": ", "", ssid)) .build(root) } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalPlugin.kt index c7e921e36d..b79dc7157b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalPlugin.kt @@ -6,12 +6,12 @@ import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.utils.resources.ResourceHelper import javax.inject.Inject import javax.inject.Singleton @Singleton -class CareportalPlugin @Inject constructor(rxBus: RxBusWrapper, aapsLogger: AAPSLogger +class CareportalPlugin @Inject constructor(aapsLogger: AAPSLogger, resourceHelper: ResourceHelper ) : PluginBase(PluginDescription() .mainType(PluginType.GENERAL) .fragmentClass(CareportalFragment::class.java.name) @@ -20,11 +20,6 @@ class CareportalPlugin @Inject constructor(rxBus: RxBusWrapper, aapsLogger: AAPS .visibleByDefault(Config.NSCLIENT) .enableByDefault(Config.NSCLIENT) .description(R.string.description_careportal), - rxBus, aapsLogger + aapsLogger, resourceHelper -) { - - override fun specialEnableCondition(): Boolean { - return Config.NSCLIENT - } -} \ No newline at end of file +) \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodPlugin.kt index 3758090cbf..7928fca509 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodPlugin.kt @@ -5,19 +5,19 @@ import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.utils.resources.ResourceHelper import javax.inject.Inject import javax.inject.Singleton @Singleton -class FoodPlugin @Inject constructor(rxBus: RxBusWrapper, aapsLogger: AAPSLogger +class FoodPlugin @Inject constructor(aapsLogger: AAPSLogger, resourceHelper: ResourceHelper ) : PluginBase(PluginDescription() .mainType(PluginType.GENERAL) .fragmentClass(FoodFragment::class.java.name) .pluginName(R.string.food) .shortName(R.string.food_short) .description(R.string.description_food), - rxBus, aapsLogger + aapsLogger, resourceHelper ) { var service: FoodService? = null diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt index 082c1aa581..08a7275fb4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt @@ -11,7 +11,6 @@ import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.nsclient.data.NSSettingsStatus import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP @@ -25,10 +24,10 @@ import javax.inject.Singleton @Singleton class MaintenancePlugin @Inject constructor( private val mainApp: MainApp, - private val resourceHelper: ResourceHelper, + resourceHelper: ResourceHelper, private val sp: SP, private val nsSettingsStatus: NSSettingsStatus, - rxBus: RxBusWrapper, aapsLogger: AAPSLogger + aapsLogger: AAPSLogger ) : PluginBase(PluginDescription() .mainType(PluginType.GENERAL) .fragmentClass(MaintenanceFragment::class.java.name) @@ -38,7 +37,7 @@ class MaintenancePlugin @Inject constructor( .shortName(R.string.maintenance_shortname) .preferencesId(R.xml.pref_maintenance) .description(R.string.description_maintenance), - rxBus, aapsLogger + aapsLogger, resourceHelper ) { fun sendLogs() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.java index c832219eed..174a3c47c6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.java @@ -13,8 +13,9 @@ import android.widget.CompoundButton; import android.widget.ScrollView; import android.widget.TextView; -import androidx.fragment.app.Fragment; +import javax.inject.Inject; +import dagger.android.support.DaggerFragment; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.plugins.bus.RxBus; @@ -27,7 +28,9 @@ import info.nightscout.androidaps.utils.SP; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; -public class NSClientFragment extends Fragment implements View.OnClickListener, CompoundButton.OnCheckedChangeListener { +public class NSClientFragment extends DaggerFragment implements View.OnClickListener, CompoundButton.OnCheckedChangeListener { + @Inject NSClientPlugin nsClientPlugin; + private CompositeDisposable disposable = new CompositeDisposable(); private TextView logTextView; @@ -50,10 +53,10 @@ public class NSClientFragment extends Fragment implements View.OnClickListener, logScrollview = (ScrollView) view.findViewById(R.id.nsclientinternal_logscrollview); autoscrollCheckbox = (CheckBox) view.findViewById(R.id.nsclientinternal_autoscroll); - autoscrollCheckbox.setChecked(NSClientPlugin.getPlugin().autoscroll); + autoscrollCheckbox.setChecked(nsClientPlugin.autoscroll); autoscrollCheckbox.setOnCheckedChangeListener(this); pausedCheckbox = (CheckBox) view.findViewById(R.id.nsclientinternal_paused); - pausedCheckbox.setChecked(NSClientPlugin.getPlugin().paused); + pausedCheckbox.setChecked(nsClientPlugin.paused); pausedCheckbox.setOnCheckedChangeListener(this); logTextView = (TextView) view.findViewById(R.id.nsclientinternal_log); queueTextView = (TextView) view.findViewById(R.id.nsclientinternal_queue); @@ -104,21 +107,21 @@ public class NSClientFragment extends Fragment implements View.OnClickListener, FabricPrivacy.getInstance().logCustom("NSClientRestart"); break; case R.id.nsclientinternal_delivernow: - NSClientPlugin.getPlugin().resend("GUI"); + nsClientPlugin.resend("GUI"); FabricPrivacy.getInstance().logCustom("NSClientDeliverNow"); break; case R.id.nsclientinternal_clearlog: - NSClientPlugin.getPlugin().clearLog(); + nsClientPlugin.clearLog(); break; case R.id.nsclientinternal_clearqueue: - OKDialog.showConfirmation(getContext(),MainApp.gs(R.string.nsclientinternal), MainApp.gs(R.string.clearqueueconfirm), () -> { + OKDialog.showConfirmation(getContext(), MainApp.gs(R.string.nsclientinternal), MainApp.gs(R.string.clearqueueconfirm), () -> { UploadQueue.clearQueue(); updateGui(); FabricPrivacy.getInstance().logCustom("NSClientClearQueue"); }); break; case R.id.nsclientinternal_showqueue: - RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("QUEUE", NSClientPlugin.getPlugin().queue().textList())); + RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("QUEUE", nsClientPlugin.queue().textList())); break; } } @@ -127,29 +130,29 @@ public class NSClientFragment extends Fragment implements View.OnClickListener, public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { switch (buttonView.getId()) { case R.id.nsclientinternal_paused: - NSClientPlugin.getPlugin().pause(isChecked); + nsClientPlugin.pause(isChecked); updateGui(); FabricPrivacy.getInstance().logCustom("NSClientPause"); break; case R.id.nsclientinternal_autoscroll: SP.putBoolean(R.string.key_nsclientinternal_autoscroll, isChecked); - NSClientPlugin.getPlugin().autoscroll = isChecked; + nsClientPlugin.autoscroll = isChecked; updateGui(); break; } } protected void updateGui() { - NSClientPlugin.getPlugin().updateLog(); + nsClientPlugin.updateLog(); pausedCheckbox.setChecked(SP.getBoolean(R.string.key_nsclientinternal_paused, false)); - logTextView.setText(NSClientPlugin.getPlugin().textLog); - if (NSClientPlugin.getPlugin().autoscroll) { + logTextView.setText(nsClientPlugin.textLog); + if (nsClientPlugin.autoscroll) { logScrollview.fullScroll(ScrollView.FOCUS_DOWN); } - urlTextView.setText(NSClientPlugin.getPlugin().url()); + urlTextView.setText(nsClientPlugin.url()); Spanned queuetext = Html.fromHtml(MainApp.gs(R.string.queue) + " " + UploadQueue.size() + ""); queueTextView.setText(queuetext); - statusTextView.setText(NSClientPlugin.getPlugin().status); + statusTextView.setText(nsClientPlugin.status); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java index c510052c12..f3f799ddb1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java @@ -20,6 +20,9 @@ import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; +import javax.inject.Inject; +import javax.inject.Singleton; + import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; @@ -31,34 +34,31 @@ import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; -import info.nightscout.androidaps.logging.AAPSLoggerProduction; +import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.general.nsclient.data.AlarmAck; import info.nightscout.androidaps.plugins.general.nsclient.data.NSAlarm; import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientNewLog; +import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientResend; import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientStatus; import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientUpdateGUI; import info.nightscout.androidaps.plugins.general.nsclient.services.NSClientService; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.ToastUtils; +import info.nightscout.androidaps.utils.resources.ResourceHelper; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.schedulers.Schedulers; +@Singleton public class NSClientPlugin extends PluginBase { private Logger log = LoggerFactory.getLogger(L.NSCLIENT); private CompositeDisposable disposable = new CompositeDisposable(); - static NSClientPlugin nsClientPlugin; - - static public NSClientPlugin getPlugin() { - if (nsClientPlugin == null) { - nsClientPlugin = new NSClientPlugin(); - } - return nsClientPlugin; - } + private final AAPSLogger aapsLogger; + private final RxBusWrapper rxBus; + private final ResourceHelper resourceHelper; public Handler handler; @@ -74,9 +74,12 @@ public class NSClientPlugin extends PluginBase { private NsClientReceiverDelegate nsClientReceiverDelegate; - // TODO: dagger - - private NSClientPlugin() { + @Inject + public NSClientPlugin( + AAPSLogger aapsLogger, + RxBusWrapper rxBus, + ResourceHelper resourceHelper + ) { super(new PluginDescription() .mainType(PluginType.GENERAL) .fragmentClass(NSClientFragment.class.getName()) @@ -84,23 +87,22 @@ public class NSClientPlugin extends PluginBase { .shortName(R.string.nsclientinternal_shortname) .preferencesId(R.xml.pref_nsclientinternal) .description(R.string.description_ns_client), - new RxBusWrapper(), new AAPSLoggerProduction() // TODO: dagger + aapsLogger, resourceHelper ); + this.aapsLogger = aapsLogger; + this.rxBus = rxBus; + this.resourceHelper = resourceHelper; + if (Config.NSCLIENT) { getPluginDescription().alwaysEnabled(true).visibleByDefault(true); } - paused = SP.getBoolean(R.string.key_nsclientinternal_paused, false); - autoscroll = SP.getBoolean(R.string.key_nsclientinternal_autoscroll, true); - if (handler == null) { HandlerThread handlerThread = new HandlerThread(NSClientPlugin.class.getSimpleName() + "Handler"); handlerThread.start(); handler = new Handler(handlerThread.getLooper()); } - nsClientReceiverDelegate = - new NsClientReceiverDelegate(); } public boolean isAllowed() { @@ -110,31 +112,35 @@ public class NSClientPlugin extends PluginBase { @Override protected void onStart() { + paused = SP.getBoolean(R.string.key_nsclientinternal_paused, false); + autoscroll = SP.getBoolean(R.string.key_nsclientinternal_autoscroll, true); + nsClientReceiverDelegate = new NsClientReceiverDelegate(); + Context context = MainApp.instance().getApplicationContext(); Intent intent = new Intent(context, NSClientService.class); context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE); super.onStart(); nsClientReceiverDelegate.grabReceiversState(); - disposable.add(RxBus.Companion.getINSTANCE() + disposable.add(rxBus .toObservable(EventNSClientStatus.class) .observeOn(Schedulers.io()) .subscribe(event -> { status = event.getStatus(MainApp.instance().getResourceHelper()); - RxBus.Companion.getINSTANCE().send(new EventNSClientUpdateGUI()); + rxBus.send(new EventNSClientUpdateGUI()); }, exception -> FabricPrivacy.getInstance().logException(exception)) ); - disposable.add(RxBus.Companion.getINSTANCE() + disposable.add(rxBus .toObservable(EventNetworkChange.class) .observeOn(Schedulers.io()) .subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), exception -> FabricPrivacy.getInstance().logException(exception)) ); - disposable.add(RxBus.Companion.getINSTANCE() + disposable.add(rxBus .toObservable(EventPreferenceChange.class) .observeOn(Schedulers.io()) .subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), exception -> FabricPrivacy.getInstance().logException(exception)) ); - disposable.add(RxBus.Companion.getINSTANCE() + disposable.add(rxBus .toObservable(EventAppExit.class) .observeOn(Schedulers.io()) .subscribe(event -> { @@ -143,7 +149,7 @@ public class NSClientPlugin extends PluginBase { } }, exception -> FabricPrivacy.getInstance().logException(exception)) ); - disposable.add(RxBus.Companion.getINSTANCE() + disposable.add(rxBus .toObservable(EventNSClientNewLog.class) .observeOn(Schedulers.io()) .subscribe(event -> { @@ -152,11 +158,16 @@ public class NSClientPlugin extends PluginBase { log.debug(event.getAction() + " " + event.getLogText()); }, exception -> FabricPrivacy.getInstance().logException(exception)) ); - disposable.add(RxBus.Companion.getINSTANCE() + disposable.add(rxBus .toObservable(EventChargingState.class) .observeOn(Schedulers.io()) .subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), exception -> FabricPrivacy.getInstance().logException(exception)) ); + disposable.add(rxBus + .toObservable(EventNSClientResend.class) + .observeOn(Schedulers.io()) + .subscribe(event -> resend(event.getReason()), exception -> FabricPrivacy.getInstance().logException(exception)) + ); } @Override @@ -205,7 +216,7 @@ public class NSClientPlugin extends PluginBase { synchronized (listLog) { listLog.clear(); } - RxBus.Companion.getINSTANCE().send(new EventNSClientUpdateGUI()); + rxBus.send(new EventNSClientUpdateGUI()); }); } @@ -218,7 +229,7 @@ public class NSClientPlugin extends PluginBase { listLog.remove(0); } } - RxBus.Companion.getINSTANCE().send(new EventNSClientUpdateGUI()); + rxBus.send(new EventNSClientUpdateGUI()); }); } @@ -244,7 +255,7 @@ public class NSClientPlugin extends PluginBase { public void pause(boolean newState) { SP.putBoolean(R.string.key_nsclientinternal_paused, newState); paused = newState; - RxBus.Companion.getINSTANCE().send(new EventPreferenceChange(MainApp.resources(), R.string.key_nsclientinternal_paused)); + rxBus.send(new EventPreferenceChange(MainApp.resources(), R.string.key_nsclientinternal_paused)); } public UploadQueue queue() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/UploadQueue.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/UploadQueue.java index c2bb0d21ab..f2ff8bd196 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/UploadQueue.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/UploadQueue.java @@ -17,6 +17,8 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.DbRequest; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; +import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientResend; import info.nightscout.androidaps.plugins.general.nsclient.services.NSClientService; /** @@ -48,10 +50,7 @@ public class UploadQueue { if (L.isEnabled(L.NSCLIENT)) log.debug("Adding to queue: " + dbr.data); MainApp.getDbHelper().create(dbr); - NSClientPlugin plugin = NSClientPlugin.getPlugin(); - if (plugin != null) { - plugin.resend("newdata"); - } + RxBus.getINSTANCE().send(new EventNSClientResend("newdata")); }); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientResend.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientResend.kt new file mode 100644 index 0000000000..26f70b8a82 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientResend.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.general.nsclient.events + +import info.nightscout.androidaps.events.Event + +class EventNSClientResend(val reason: String) : Event() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java index a4c8d5af1b..c9659cfcbc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java @@ -84,6 +84,7 @@ public class NSClientService extends DaggerService { @Inject RxBusWrapper rxBus; @Inject ResourceHelper resourceHelper; @Inject SP sp; + @Inject NSClientPlugin nsClientPlugin; private static Logger log = LoggerFactory.getLogger(L.NSCLIENT); private CompositeDisposable disposable = new CompositeDisposable(); @@ -146,7 +147,7 @@ public class NSClientService extends DaggerService { .toObservable(EventConfigBuilderChange.class) .observeOn(Schedulers.io()) .subscribe(event -> { - if (nsEnabled != NSClientPlugin.getPlugin().isEnabled(PluginType.GENERAL)) { + if (nsEnabled != nsClientPlugin.isEnabled(PluginType.GENERAL)) { latestDateInReceivedData = 0; destroy(); initialize(); @@ -277,10 +278,10 @@ public class NSClientService extends DaggerService { nsAPIhashCode = Hashing.sha1().hashString(nsAPISecret, Charsets.UTF_8).toString(); rxBus.send(new EventNSClientStatus("Initializing")); - if (!NSClientPlugin.getPlugin().isAllowed()) { + if (!nsClientPlugin.isAllowed()) { rxBus.send(new EventNSClientNewLog("NSCLIENT", "not allowed")); rxBus.send(new EventNSClientStatus("Not allowed")); - } else if (NSClientPlugin.getPlugin().paused) { + } else if (nsClientPlugin.paused) { rxBus.send(new EventNSClientNewLog("NSCLIENT", "paused")); rxBus.send(new EventNSClientStatus("Paused")); } else if (!nsEnabled) { @@ -340,12 +341,12 @@ public class NSClientService extends DaggerService { Notification n = new Notification(Notification.NSMALFUNCTION, resourceHelper.gs(R.string.nsmalfunction), Notification.URGENT); rxBus.send(new EventNewNotification(n)); rxBus.send(new EventNSClientNewLog("WATCHDOG", "pausing for " + WATCHDOG_RECONNECT_IN + " mins")); - NSClientPlugin.getPlugin().pause(true); + nsClientPlugin.pause(true); rxBus.send(new EventNSClientUpdateGUI()); new Thread(() -> { SystemClock.sleep(T.mins(WATCHDOG_RECONNECT_IN).msecs()); rxBus.send(new EventNSClientNewLog("WATCHDOG", "reenabling NSClient")); - NSClientPlugin.getPlugin().pause(false); + nsClientPlugin.pause(false); }).start(); } } @@ -398,7 +399,7 @@ public class NSClientService extends DaggerService { } public void readPreferences() { - nsEnabled = NSClientPlugin.getPlugin().isEnabled(PluginType.GENERAL); + nsEnabled = nsClientPlugin.isEnabled(PluginType.GENERAL); nsURL = sp.getString(R.string.key_nsclientinternal_url, ""); nsAPISecret = sp.getString(R.string.key_nsclientinternal_api_secret, ""); nsDevice = sp.getString("careportal_enteredby", ""); 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 98a516c0b1..6ef4f5d88b 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 @@ -52,7 +52,6 @@ import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.BgReading; -import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.TempTarget; @@ -933,7 +932,7 @@ public class OverviewFragment extends DaggerFragment implements View.OnClickList } private void onClickQuickwizard() { - final BgReading actualBg = DatabaseHelper.actualBg(); + final BgReading actualBg = iobCobCalculatorPlugin.actualBg(); final Profile profile = profileFunction.getProfile(); final String profileName = profileFunction.getProfileName(); final PumpInterface pump = configBuilderPlugin.getActivePump(); @@ -1029,8 +1028,8 @@ public class OverviewFragment extends DaggerFragment implements View.OnClickList loopStatusLayout.setVisibility(View.VISIBLE); statusLightHandler.updateAge(sage, iage, cage, pbage); - BgReading actualBG = DatabaseHelper.actualBg(); - BgReading lastBG = DatabaseHelper.lastBg(); + BgReading actualBG = iobCobCalculatorPlugin.actualBg(); + BgReading lastBG = iobCobCalculatorPlugin.lastBg(); final PumpInterface pump = configBuilderPlugin.getActivePump(); @@ -1143,9 +1142,8 @@ public class OverviewFragment extends DaggerFragment implements View.OnClickList // **** Calibration & CGM buttons **** boolean xDripIsBgSource = xdripPlugin.isEnabled(PluginType.BGSOURCE); boolean dexcomIsSource = dexcomPlugin.isEnabled(PluginType.BGSOURCE); - boolean bgAvailable = DatabaseHelper.actualBg() != null; if (calibrationButton != null) { - if ((xDripIsBgSource || dexcomIsSource) && bgAvailable && sp.getBoolean(R.string.key_show_calibration_button, true)) { + if ((xDripIsBgSource || dexcomIsSource) && actualBG != null && sp.getBoolean(R.string.key_show_calibration_button, true)) { calibrationButton.setVisibility(View.VISIBLE); } else { calibrationButton.setVisibility(View.GONE); @@ -1167,10 +1165,10 @@ public class OverviewFragment extends DaggerFragment implements View.OnClickList if (activeTemp != null) { basalText = "T: " + activeTemp.toStringVeryShort(); } else { - basalText = MainApp.gs(R.string.pump_basebasalrate,profile.getBasal()); + basalText = MainApp.gs(R.string.pump_basebasalrate, profile.getBasal()); } baseBasalView.setOnClickListener(v -> { - String fullText = resourceHelper.gs(R.string.pump_basebasalrate_label) + ": " + resourceHelper.gs(R.string.pump_basebasalrate,profile.getBasal()) + "\n"; + String fullText = resourceHelper.gs(R.string.pump_basebasalrate_label) + ": " + resourceHelper.gs(R.string.pump_basebasalrate, profile.getBasal()) + "\n"; if (activeTemp != null) { fullText += resourceHelper.gs(R.string.pump_tempbasal_label) + ": " + activeTemp.toStringFull(); } @@ -1181,14 +1179,14 @@ public class OverviewFragment extends DaggerFragment implements View.OnClickList if (activeTemp != null) { basalText = activeTemp.toStringFull(); } else { - basalText = resourceHelper.gs(R.string.pump_basebasalrate,profile.getBasal()); + basalText = resourceHelper.gs(R.string.pump_basebasalrate, profile.getBasal()); } } baseBasalView.setText(basalText); if (activeTemp != null) { baseBasalView.setTextColor(resourceHelper.gc(R.color.basal)); } else { - baseBasalView.setTextColor(MainApp.gc(R.color.defaulttextcolor)); + baseBasalView.setTextColor(MainApp.gc(R.color.defaulttextcolor)); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewPlugin.kt index 8e30734dba..90dd1279be 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewPlugin.kt @@ -12,6 +12,7 @@ import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotifi import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationStore import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.extensions.plusAssign +import info.nightscout.androidaps.utils.resources.ResourceHelper import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import javax.inject.Inject @@ -21,7 +22,9 @@ import javax.inject.Singleton class OverviewPlugin @Inject constructor( private val notificationStore: NotificationStore, private val fabricPrivacy: FabricPrivacy, - rxBus: RxBusWrapper, aapsLogger: AAPSLogger + private val rxBus: RxBusWrapper, + aapsLogger: AAPSLogger, + resourceHelper: ResourceHelper ) : PluginBase(PluginDescription() .mainType(PluginType.GENERAL) .fragmentClass(OverviewFragment::class.qualifiedName) @@ -30,7 +33,7 @@ class OverviewPlugin @Inject constructor( .pluginName(R.string.overview) .shortName(R.string.overview_shortname) .preferencesId(R.xml.pref_overview) - .description(R.string.description_overview), rxBus, aapsLogger + .description(R.string.description_overview), aapsLogger, resourceHelper ) { private var disposable: CompositeDisposable = CompositeDisposable() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/StatusLightHandler.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/StatusLightHandler.kt index 8e33444108..0e6fa04a18 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/StatusLightHandler.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/StatusLightHandler.kt @@ -30,10 +30,10 @@ class StatusLightHandler @Inject constructor( */ fun statusLight(cageView: TextView?, iAgeView: TextView?, reservoirView: TextView?, sageView: TextView?, batteryView: TextView?) { - val pump = configBuilderPlugin.activePump + val pump = configBuilderPlugin.activePumpPlugin ?: return applyStatusLight("cage", CareportalEvent.SITECHANGE, cageView, "CAN", 48, 72) applyStatusLight("iage", CareportalEvent.INSULINCHANGE, iAgeView, "INS", 72, 96) - val reservoirLevel = if (pump!!.isInitialized) pump.reservoirLevel else (-1).toDouble() + val reservoirLevel = if (pump.isInitialized) pump.reservoirLevel else (-1).toDouble() applyStatusLightLevel(R.string.key_statuslights_res_critical, 10.0, R.string.key_statuslights_res_warning, 80.0, reservoirView, "RES", reservoirLevel) applyStatusLight("sage", CareportalEvent.SENSORCHANGE, sageView, "SEN", 164, 166) @@ -92,14 +92,14 @@ class StatusLightHandler @Inject constructor( fun extendedStatusLight(cageView: TextView, iAgeView: TextView, reservoirView: TextView, sageView: TextView, batteryView: TextView) { - val pump = configBuilderPlugin.activePump + val pump = configBuilderPlugin.activePumpPlugin ?: return handleAge("cage", CareportalEvent.SITECHANGE, cageView, "CAN ", 48, 72) handleAge("iage", CareportalEvent.INSULINCHANGE, iAgeView, "INS ", 72, 96) handleLevel(R.string.key_statuslights_res_critical, 10.0, R.string.key_statuslights_res_warning, 80.0, - reservoirView, "RES ", pump!!.reservoirLevel) + reservoirView, "RES ", pump.reservoirLevel) handleAge("sage", CareportalEvent.SENSORCHANGE, sageView, "SEN ", 164, 166) if (pump.model() != PumpType.AccuChekCombo) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationWithAction.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationWithAction.kt index 2836b2f516..c5670699c9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationWithAction.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationWithAction.kt @@ -1,6 +1,6 @@ package info.nightscout.androidaps.plugins.general.overview.notifications -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag @@ -14,7 +14,7 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP import javax.inject.Inject class NotificationWithAction constructor( - mainApp: MainApp + injector: HasAndroidInjector ) : Notification() { @Inject lateinit var aapsLogger: AAPSLogger @@ -22,21 +22,22 @@ class NotificationWithAction constructor( @Inject lateinit var sp: SP @Inject lateinit var defaultValueHelper: DefaultValueHelper @Inject lateinit var nsSettingsStatus: NSSettingsStatus + @Inject lateinit var nsClientPlugin: NSClientPlugin private var nsAlarm: NSAlarm? = null init { - mainApp.androidInjector().inject(this) + injector.androidInjector().inject(this) } - constructor(mainApp: MainApp, id: Int, text: String, level: Int) : this(mainApp) { + constructor(injector: HasAndroidInjector, id: Int, text: String, level: Int) : this(injector) { this.id = id date = System.currentTimeMillis() this.text = text this.level = level } - constructor (mainApp: MainApp, nsAlarm: NSAlarm) : this(mainApp) { + constructor (injector: HasAndroidInjector, nsAlarm: NSAlarm) : this(injector) { this.nsAlarm = nsAlarm date = System.currentTimeMillis() when (nsAlarm.level()) { @@ -63,7 +64,7 @@ class NotificationWithAction constructor( } buttonText = R.string.snooze action = Runnable { - NSClientPlugin.getPlugin().handleClearAlarm(nsAlarm, 60 * 60 * 1000L) + nsClientPlugin.handleClearAlarm(nsAlarm, 60 * 60 * 1000L) // Adding current time to snooze if we got staleData aapsLogger.debug(LTag.NOTIFICATION, "Notification text is: $text") val msToSnooze = sp.getInt(R.string.key_nsalarm_staledatavalue, 15) * 60 * 1000L diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt index b1ab314df7..8e7b8f6bbc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt @@ -14,7 +14,6 @@ import info.nightscout.androidaps.MainActivity import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile -import info.nightscout.androidaps.db.DatabaseHelper import info.nightscout.androidaps.events.* import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.PluginBase @@ -22,12 +21,10 @@ import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus 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.DecimalFormatter import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.resources.ResourceHelper @@ -38,15 +35,15 @@ import javax.inject.Singleton @Singleton class PersistentNotificationPlugin @Inject constructor( - var mainApp: MainApp, - var resourceHelper: ResourceHelper, - var profileFunction: ProfileFunction, - var fabricPrivacy: FabricPrivacy, - var activePlugins: ActivePluginProvider, - var treatmentsPlugin: TreatmentsPlugin, - var iobCobCalculatorPlugin: IobCobCalculatorPlugin, - rxBus: RxBusWrapper, - aapsLogger: AAPSLogger + aapsLogger: AAPSLogger, + resourceHelper: ResourceHelper, + private var profileFunction: ProfileFunction, + private var fabricPrivacy: FabricPrivacy, + private var activePlugins: ActivePluginProvider, + private var iobCobCalculatorPlugin: IobCobCalculatorPlugin, + private var rxBus: RxBusWrapper, + private var context: Context, + private var mainApp: MainApp ) : PluginBase(PluginDescription() .mainType(PluginType.GENERAL) .neverVisible(true) @@ -55,7 +52,7 @@ class PersistentNotificationPlugin @Inject constructor( .alwaysEnabled(true) .showInList(false) .description(R.string.description_persistent_notification), - rxBus, aapsLogger + aapsLogger, resourceHelper ) { // For Android Auto @@ -109,7 +106,7 @@ class PersistentNotificationPlugin @Inject constructor( private fun createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - val mNotificationManager = mainApp.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + val mNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val channel = NotificationChannel(mainApp.channelId(), mainApp.channelId() as CharSequence, NotificationManager.IMPORTANCE_HIGH) mNotificationManager.createNotificationChannel(channel) } @@ -117,20 +114,20 @@ class PersistentNotificationPlugin @Inject constructor( override fun onStop() { disposable.clear() - mainApp.stopService(Intent(mainApp, DummyService::class.java)) + context.stopService(Intent(context, DummyService::class.java)) super.onStop() } private fun triggerNotificationUpdate() { updateNotification() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) - mainApp.startForegroundService(Intent(mainApp, DummyService::class.java)) + context.startForegroundService(Intent(context, DummyService::class.java)) else - mainApp.startService(Intent(mainApp, DummyService::class.java)) + context.startService(Intent(context, DummyService::class.java)) } private fun updateNotification() { - val pump = activePlugins.activePump ?: return + val pump = activePlugins.activePumpPlugin ?: return var line1: String? var line2: String? = null var line3: String? = null @@ -138,7 +135,7 @@ class PersistentNotificationPlugin @Inject constructor( if (profileFunction.isProfileValid("Notification")) { var line1_aa: String val units = profileFunction.getUnits() - val lastBG = DatabaseHelper.lastBg() + val lastBG = iobCobCalculatorPlugin.lastBg() val glucoseStatus = GlucoseStatus.getGlucoseStatusData() if (lastBG != null) { line1_aa = lastBG.valueToUnitsToString(units) @@ -157,16 +154,16 @@ class PersistentNotificationPlugin @Inject constructor( line1_aa = resourceHelper.gs(R.string.missed_bg_readings) line1 = line1_aa } - val activeTemp = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis()) + val activeTemp = activePlugins.activeTreatments.getTempBasalFromHistory(System.currentTimeMillis()) if (activeTemp != null) { line1 += " " + activeTemp.toStringShort() line1_aa += " " + activeTemp.toStringShort() + "." } //IOB - treatmentsPlugin.updateTotalIOBTreatments() - treatmentsPlugin.updateTotalIOBTempBasals() - val bolusIob = treatmentsPlugin.lastCalculationTreatments.round() - val basalIob = treatmentsPlugin.lastCalculationTempBasals.round() + activePlugins.activeTreatments.updateTotalIOBTreatments() + activePlugins.activeTreatments.updateTotalIOBTempBasals() + val bolusIob = activePlugins.activeTreatments.lastCalculationTreatments.round() + val basalIob = activePlugins.activeTreatments.lastCalculationTempBasals.round() line2 = resourceHelper.gs(R.string.treatments_iob_label_string) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U " + resourceHelper.gs(R.string.cob) + ": " + iobCobCalculatorPlugin.getCobInfo(false, "PersistentNotificationPlugin").generateCOBString() val line2_aa = resourceHelper.gs(R.string.treatments_iob_label_string) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U. " + resourceHelper.gs(R.string.cob) + ": " + iobCobCalculatorPlugin.getCobInfo(false, "PersistentNotificationPlugin").generateCOBString() + "." line3 = DecimalFormatter.to2Decimal(pump.baseBasalRate) + " U/h" @@ -179,7 +176,7 @@ class PersistentNotificationPlugin @Inject constructor( .setAction(READ_ACTION) .putExtra(CONVERSATION_ID, mainApp.notificationId()) .setPackage(PACKAGE) - val msgReadPendingIntent = PendingIntent.getBroadcast(mainApp, + val msgReadPendingIntent = PendingIntent.getBroadcast(context, mainApp.notificationId(), msgReadIntent, PendingIntent.FLAG_UPDATE_CURRENT) @@ -189,7 +186,7 @@ class PersistentNotificationPlugin @Inject constructor( .putExtra(CONVERSATION_ID, mainApp.notificationId()) .setPackage(PACKAGE) val msgReplyPendingIntent = PendingIntent.getBroadcast( - mainApp, + context, mainApp.notificationId(), msgReplyIntent, PendingIntent.FLAG_UPDATE_CURRENT) @@ -206,7 +203,7 @@ class PersistentNotificationPlugin @Inject constructor( } else { line1 = resourceHelper.gs(R.string.noprofileset) } - val builder = NotificationCompat.Builder(mainApp, mainApp.channelId()) + val builder = NotificationCompat.Builder(context, mainApp.channelId()) builder.setOngoing(true) builder.setOnlyAlertOnce(true) builder.setCategory(NotificationCompat.CATEGORY_STATUS) @@ -221,8 +218,8 @@ class PersistentNotificationPlugin @Inject constructor( .setUnreadConversation(unreadConversationBuilder.build())) } /// End Android Auto - val resultIntent = Intent(mainApp, MainActivity::class.java) - val stackBuilder = TaskStackBuilder.create(mainApp) + val resultIntent = Intent(context, MainActivity::class.java) + val stackBuilder = TaskStackBuilder.create(context) stackBuilder.addParentStack(MainActivity::class.java) stackBuilder.addNextIntent(resultIntent) val resultPendingIntent = stackBuilder.getPendingIntent( @@ -230,7 +227,7 @@ class PersistentNotificationPlugin @Inject constructor( PendingIntent.FLAG_UPDATE_CURRENT ) builder.setContentIntent(resultPendingIntent) - val mNotificationManager = mainApp.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + val mNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val notification = builder.build() mNotificationManager.notify(mainApp.notificationId(), notification) mainApp.notification = notification 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 90c0e5f4a6..5495b9f362 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 @@ -11,7 +11,6 @@ import info.nightscout.androidaps.Constants import info.nightscout.androidaps.R import info.nightscout.androidaps.data.DetailedBolusInfo import info.nightscout.androidaps.data.Profile -import info.nightscout.androidaps.db.DatabaseHelper import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.db.TempTarget import info.nightscout.androidaps.events.EventPreferenceChange @@ -47,16 +46,15 @@ import javax.inject.Singleton @Singleton class SmsCommunicatorPlugin @Inject constructor( - private val sp: SP, - private val resourceHelper: ResourceHelper, - private val constraintChecker: ConstraintChecker, aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, + resourceHelper: ResourceHelper, + private val sp: SP, + private val constraintChecker: ConstraintChecker, + private val rxBus: RxBusWrapper, private val profileFunction: ProfileFunction, private val fabricPrivacy: FabricPrivacy, - private val activePluginProvider: ActivePluginProvider, - private val commandQueueProvider: CommandQueueProvider, - private val treatmentsPlugin: TreatmentsPlugin, + private val activePlugin: ActivePluginProvider, + private val commandQueue: CommandQueueProvider, private val loopPlugin: LoopPlugin, private val iobCobCalculatorPlugin: IobCobCalculatorPlugin ) : PluginBase(PluginDescription() @@ -66,7 +64,7 @@ class SmsCommunicatorPlugin @Inject constructor( .shortName(R.string.smscommunicator_shortname) .preferencesId(R.xml.pref_smscommunicator) .description(R.string.description_sms_communicator), - rxBus, aapsLogger + aapsLogger, resourceHelper ) { private val disposable = CompositeDisposable() @@ -196,7 +194,7 @@ class SmsCommunicatorPlugin @Inject constructor( rxBus.send(EventSmsCommunicatorUpdateGui()) return } - val pump = activePluginProvider.activePump ?: return + val pump = activePlugin.activePumpPlugin ?: return messages.add(receivedSms) aapsLogger.debug(LTag.SMS, receivedSms.toString()) val splitted = receivedSms.text.split(Regex("\\s+")).toTypedArray() @@ -267,8 +265,8 @@ class SmsCommunicatorPlugin @Inject constructor( } private fun processBG(receivedSms: Sms) { - val actualBG = DatabaseHelper.actualBg() - val lastBG = DatabaseHelper.lastBg() + val actualBG = iobCobCalculatorPlugin.actualBg() + val lastBG = iobCobCalculatorPlugin.lastBg() var reply = "" val units = profileFunction.getUnits() if (actualBG != null) { @@ -280,10 +278,10 @@ class SmsCommunicatorPlugin @Inject constructor( } val glucoseStatus = GlucoseStatus.getGlucoseStatusData() if (glucoseStatus != null) reply += resourceHelper.gs(R.string.sms_delta) + " " + Profile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + " " + units + ", " - treatmentsPlugin.updateTotalIOBTreatments() - val bolusIob = treatmentsPlugin.lastCalculationTreatments.round() - treatmentsPlugin.updateTotalIOBTempBasals() - val basalIob = treatmentsPlugin.lastCalculationTempBasals.round() + activePlugin.activeTreatments.updateTotalIOBTreatments() + val bolusIob = activePlugin.activeTreatments.lastCalculationTreatments.round() + activePlugin.activeTreatments.updateTotalIOBTempBasals() + val basalIob = activePlugin.activeTreatments.lastCalculationTempBasals.round() val cobInfo = iobCobCalculatorPlugin.getCobInfo(false, "SMS COB") reply += (resourceHelper.gs(R.string.sms_iob) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U (" + resourceHelper.gs(R.string.sms_bolus) + " " + DecimalFormatter.to2Decimal(bolusIob.iob) + "U " @@ -298,7 +296,7 @@ class SmsCommunicatorPlugin @Inject constructor( "DISABLE", "STOP" -> { if (loopPlugin.isEnabled(PluginType.LOOP)) { loopPlugin.setPluginEnabled(PluginType.LOOP, false) - commandQueueProvider.commandQueue.cancelTempBasal(true, object : Callback() { + commandQueue.cancelTempBasal(true, object : Callback() { override fun run() { rxBus.send(EventRefreshOverview("SMS_LOOP_STOP")) val replyText = resourceHelper.gs(R.string.smscommunicator_loophasbeendisabled) + " " + @@ -352,7 +350,7 @@ class SmsCommunicatorPlugin @Inject constructor( receivedSms.processed = true messageToConfirm = AuthRequest(this, resourceHelper, receivedSms, reply, passCode, object : SmsAction(duration) { override fun run() { - commandQueueProvider.commandQueue.cancelTempBasal(true, object : Callback() { + commandQueue.cancelTempBasal(true, object : Callback() { override fun run() { if (result.success) { loopPlugin.suspendTo(System.currentTimeMillis() + anInteger() * 60L * 1000) @@ -363,7 +361,7 @@ class SmsCommunicatorPlugin @Inject constructor( sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) } else { var replyText = resourceHelper.gs(R.string.smscommunicator_tempbasalcancelfailed) - replyText += "\n" + activePluginProvider.activePump?.shortStatus(true) + replyText += "\n" + activePlugin.activePumpPlugin?.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, replyText)) } } @@ -379,7 +377,7 @@ class SmsCommunicatorPlugin @Inject constructor( private fun processTREATMENTS(splitted: Array, receivedSms: Sms) { if (splitted[1].toUpperCase(Locale.getDefault()) == "REFRESH") { - treatmentsPlugin.service.resetTreatments() + (activePlugin.activeTreatments as TreatmentsPlugin).service.resetTreatments() rxBus.send(EventNSClientRestart()) sendSMS(Sms(receivedSms.phoneNumber, "TREATMENTS REFRESH SENT")) receivedSms.processed = true @@ -410,9 +408,9 @@ class SmsCommunicatorPlugin @Inject constructor( } private fun processPUMP(receivedSms: Sms) { - commandQueueProvider.commandQueue.readStatus("SMS", object : Callback() { + commandQueue.readStatus("SMS", object : Callback() { override fun run() { - val pump = activePluginProvider.activePump + val pump = activePlugin.activePumpPlugin if (result.success) { if (pump != null) { val reply = pump.shortStatus(true) @@ -428,7 +426,7 @@ class SmsCommunicatorPlugin @Inject constructor( } private fun processPROFILE(splitted: Array, receivedSms: Sms) { // load profiles - val anInterface = activePluginProvider.activeProfileInterface + val anInterface = activePlugin.activeProfileInterface val store = anInterface.profile if (store == null) { sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.notconfigured))) @@ -467,7 +465,7 @@ class SmsCommunicatorPlugin @Inject constructor( val finalPercentage = percentage messageToConfirm = AuthRequest(this, resourceHelper, receivedSms, reply, passCode, object : SmsAction(list[pindex - 1] as String, finalPercentage) { override fun run() { - treatmentsPlugin.doProfileSwitch(store, list[pindex - 1] as String, 0, finalPercentage, 0, DateUtil.now()) + activePlugin.activeTreatments.doProfileSwitch(store, list[pindex - 1] as String, 0, finalPercentage, 0, DateUtil.now()) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.profileswitchcreated))) } }) @@ -484,15 +482,15 @@ class SmsCommunicatorPlugin @Inject constructor( receivedSms.processed = true messageToConfirm = AuthRequest(this, resourceHelper, receivedSms, reply, passCode, object : SmsAction() { override fun run() { - commandQueueProvider.commandQueue.cancelTempBasal(true, object : Callback() { + commandQueue.cancelTempBasal(true, object : Callback() { override fun run() { if (result.success) { var replyText = resourceHelper.gs(R.string.smscommunicator_tempbasalcanceled) - replyText += "\n" + activePluginProvider.activePump?.shortStatus(true) + replyText += "\n" + activePlugin.activePumpPlugin?.shortStatus(true) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) } else { var replyText = resourceHelper.gs(R.string.smscommunicator_tempbasalcancelfailed) - replyText += "\n" + activePluginProvider.activePump?.shortStatus(true) + replyText += "\n" + activePlugin.activePumpPlugin?.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, replyText)) } } @@ -514,16 +512,16 @@ class SmsCommunicatorPlugin @Inject constructor( receivedSms.processed = true messageToConfirm = AuthRequest(this, resourceHelper, receivedSms, reply, passCode, object : SmsAction(tempBasalPct, duration) { override fun run() { - commandQueueProvider.commandQueue.tempBasalPercent(anInteger(), secondInteger(), true, profile, object : Callback() { + commandQueue.tempBasalPercent(anInteger(), secondInteger(), true, profile, object : Callback() { override fun run() { if (result.success) { var replyText: String replyText = if (result.isPercent) String.format(resourceHelper.gs(R.string.smscommunicator_tempbasalset_percent), result.percent, result.duration) else String.format(resourceHelper.gs(R.string.smscommunicator_tempbasalset), result.absolute, result.duration) - replyText += "\n" + activePluginProvider.activePump?.shortStatus(true) + replyText += "\n" + activePlugin.activePumpPlugin?.shortStatus(true) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) } else { var replyText = resourceHelper.gs(R.string.smscommunicator_tempbasalfailed) - replyText += "\n" + activePluginProvider.activePump?.shortStatus(true) + replyText += "\n" + activePlugin.activePumpPlugin?.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, replyText)) } } @@ -546,16 +544,16 @@ class SmsCommunicatorPlugin @Inject constructor( receivedSms.processed = true messageToConfirm = AuthRequest(this, resourceHelper, receivedSms, reply, passCode, object : SmsAction(tempBasal, duration) { override fun run() { - commandQueueProvider.commandQueue.tempBasalAbsolute(aDouble(), secondInteger(), true, profile, object : Callback() { + commandQueue.tempBasalAbsolute(aDouble(), secondInteger(), true, profile, object : Callback() { override fun run() { if (result.success) { var replyText = if (result.isPercent) String.format(resourceHelper.gs(R.string.smscommunicator_tempbasalset_percent), result.percent, result.duration) else String.format(resourceHelper.gs(R.string.smscommunicator_tempbasalset), result.absolute, result.duration) - replyText += "\n" + activePluginProvider.activePump?.shortStatus(true) + replyText += "\n" + activePlugin.activePumpPlugin?.shortStatus(true) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) } else { var replyText = resourceHelper.gs(R.string.smscommunicator_tempbasalfailed) - replyText += "\n" + activePluginProvider.activePump?.shortStatus(true) + replyText += "\n" + activePlugin.activePumpPlugin?.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, replyText)) } } @@ -573,15 +571,15 @@ class SmsCommunicatorPlugin @Inject constructor( receivedSms.processed = true messageToConfirm = AuthRequest(this, resourceHelper, receivedSms, reply, passCode, object : SmsAction() { override fun run() { - commandQueueProvider.commandQueue.cancelExtended(object : Callback() { + commandQueue.cancelExtended(object : Callback() { override fun run() { if (result.success) { var replyText = resourceHelper.gs(R.string.smscommunicator_extendedcanceled) - replyText += "\n" + activePluginProvider.activePump?.shortStatus(true) + replyText += "\n" + activePlugin.activePumpPlugin?.shortStatus(true) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) } else { var replyText = resourceHelper.gs(R.string.smscommunicator_extendedcancelfailed) - replyText += "\n" + activePluginProvider.activePump?.shortStatus(true) + replyText += "\n" + activePlugin.activePumpPlugin?.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, replyText)) } } @@ -601,15 +599,15 @@ class SmsCommunicatorPlugin @Inject constructor( receivedSms.processed = true messageToConfirm = AuthRequest(this, resourceHelper, receivedSms, reply, passCode, object : SmsAction(extended, duration) { override fun run() { - commandQueueProvider.commandQueue.extendedBolus(aDouble(), secondInteger(), object : Callback() { + commandQueue.extendedBolus(aDouble(), secondInteger(), object : Callback() { override fun run() { if (result.success) { var replyText = String.format(resourceHelper.gs(R.string.smscommunicator_extendedset), aDouble, duration) - replyText += "\n" + activePluginProvider.activePump?.shortStatus(true) + replyText += "\n" + activePlugin.activePumpPlugin?.shortStatus(true) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) } else { var replyText = resourceHelper.gs(R.string.smscommunicator_extendedfailed) - replyText += "\n" + activePluginProvider.activePump?.shortStatus(true) + replyText += "\n" + activePlugin.activePumpPlugin?.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, replyText)) } } @@ -638,18 +636,18 @@ class SmsCommunicatorPlugin @Inject constructor( val detailedBolusInfo = DetailedBolusInfo() detailedBolusInfo.insulin = aDouble() detailedBolusInfo.source = Source.USER - commandQueueProvider.commandQueue.bolus(detailedBolusInfo, object : Callback() { + commandQueue.bolus(detailedBolusInfo, object : Callback() { override fun run() { val resultSuccess = result.success val resultBolusDelivered = result.bolusDelivered - commandQueueProvider.commandQueue.readStatus("SMS", object : Callback() { + commandQueue.readStatus("SMS", object : Callback() { override fun run() { if (resultSuccess) { var replyText = if (isMeal) String.format(resourceHelper.gs(R.string.smscommunicator_mealbolusdelivered), resultBolusDelivered) else String.format(resourceHelper.gs(R.string.smscommunicator_bolusdelivered), resultBolusDelivered) - replyText += "\n" + activePluginProvider.activePump?.shortStatus(true) + replyText += "\n" + activePlugin.activePumpPlugin?.shortStatus(true) lastRemoteBolusTime = DateUtil.now() if (isMeal) { profileFunction.getProfile()?.let { currentProfile -> @@ -669,7 +667,7 @@ class SmsCommunicatorPlugin @Inject constructor( .source(Source.USER) .low(Profile.toMgdl(eatingSoonTT, currentProfile.units)) .high(Profile.toMgdl(eatingSoonTT, currentProfile.units)) - treatmentsPlugin.addToHistoryTempTarget(tempTarget) + activePlugin.activeTreatments.addToHistoryTempTarget(tempTarget) val tt = if (currentProfile.units == Constants.MMOL) { DecimalFormatter.to1Decimal(eatingSoonTT) } else DecimalFormatter.to0Decimal(eatingSoonTT) @@ -679,7 +677,7 @@ class SmsCommunicatorPlugin @Inject constructor( sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) } else { var replyText = resourceHelper.gs(R.string.smscommunicator_bolusfailed) - replyText += "\n" + activePluginProvider.activePump?.shortStatus(true) + replyText += "\n" + activePlugin.activePumpPlugin?.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, replyText)) } } @@ -714,15 +712,15 @@ class SmsCommunicatorPlugin @Inject constructor( val detailedBolusInfo = DetailedBolusInfo() detailedBolusInfo.carbs = anInteger().toDouble() detailedBolusInfo.date = secondLong() - commandQueueProvider.commandQueue.bolus(detailedBolusInfo, object : Callback() { + commandQueue.bolus(detailedBolusInfo, object : Callback() { override fun run() { if (result.success) { var replyText = String.format(resourceHelper.gs(R.string.smscommunicator_carbsset), anInteger) - replyText += "\n" + activePluginProvider.activePump?.shortStatus(true) + replyText += "\n" + activePlugin.activePumpPlugin?.shortStatus(true) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) } else { var replyText = resourceHelper.gs(R.string.smscommunicator_carbsfailed) - replyText += "\n" + activePluginProvider.activePump?.shortStatus(true) + replyText += "\n" + activePlugin.activePumpPlugin?.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, replyText)) } } @@ -749,24 +747,30 @@ class SmsCommunicatorPlugin @Inject constructor( var keyTarget = 0 var defaultTargetMMOL = 0.0 var defaultTargetMGDL = 0.0 - if (isMeal) { - keyDuration = R.string.key_eatingsoon_duration - defaultTargetDuration = Constants.defaultEatingSoonTTDuration - keyTarget = R.string.key_eatingsoon_target - defaultTargetMMOL = Constants.defaultEatingSoonTTmmol - defaultTargetMGDL = Constants.defaultEatingSoonTTmgdl - } else if (isActivity) { - keyDuration = R.string.key_activity_duration - defaultTargetDuration = Constants.defaultActivityTTDuration - keyTarget = R.string.key_activity_target - defaultTargetMMOL = Constants.defaultActivityTTmmol - defaultTargetMGDL = Constants.defaultActivityTTmgdl - } else if (isHypo) { - keyDuration = R.string.key_hypo_duration - defaultTargetDuration = Constants.defaultHypoTTDuration - keyTarget = R.string.key_hypo_target - defaultTargetMMOL = Constants.defaultHypoTTmmol - defaultTargetMGDL = Constants.defaultHypoTTmgdl + when { + isMeal -> { + keyDuration = R.string.key_eatingsoon_duration + defaultTargetDuration = Constants.defaultEatingSoonTTDuration + keyTarget = R.string.key_eatingsoon_target + defaultTargetMMOL = Constants.defaultEatingSoonTTmmol + defaultTargetMGDL = Constants.defaultEatingSoonTTmgdl + } + + isActivity -> { + keyDuration = R.string.key_activity_duration + defaultTargetDuration = Constants.defaultActivityTTDuration + keyTarget = R.string.key_activity_target + defaultTargetMMOL = Constants.defaultActivityTTmmol + defaultTargetMGDL = Constants.defaultActivityTTmgdl + } + + isHypo -> { + keyDuration = R.string.key_hypo_duration + defaultTargetDuration = Constants.defaultHypoTTDuration + keyTarget = R.string.key_hypo_target + defaultTargetMMOL = Constants.defaultHypoTTmmol + defaultTargetMGDL = Constants.defaultHypoTTmgdl + } } var ttDuration = sp.getInt(keyDuration, defaultTargetDuration) ttDuration = if (ttDuration > 0) ttDuration else defaultTargetDuration @@ -780,7 +784,7 @@ class SmsCommunicatorPlugin @Inject constructor( .source(Source.USER) .low(Profile.toMgdl(tt, units)) .high(Profile.toMgdl(tt, units)) - treatmentsPlugin.addToHistoryTempTarget(tempTarget) + activePlugin.activeTreatments.addToHistoryTempTarget(tempTarget) val ttString = if (units == Constants.MMOL) DecimalFormatter.to1Decimal(tt) else DecimalFormatter.to0Decimal(tt) val replyText = String.format(resourceHelper.gs(R.string.smscommunicator_tt_set), ttString, ttDuration) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) @@ -798,7 +802,7 @@ class SmsCommunicatorPlugin @Inject constructor( .duration(0) .low(0.0) .high(0.0) - treatmentsPlugin.addToHistoryTempTarget(tempTarget) + activePlugin.activeTreatments.addToHistoryTempTarget(tempTarget) val replyText = String.format(resourceHelper.gs(R.string.smscommunicator_tt_canceled)) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) } @@ -904,7 +908,7 @@ class SmsCommunicatorPlugin @Inject constructor( return s } - fun areMoreNumbers(allowednumbers: String?): Boolean { + private fun areMoreNumbers(allowednumbers: String?): Boolean { return allowednumbers?.let { var countNumbers = 0 val substrings = it.split(";").toTypedArray() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/TidepoolPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/TidepoolPlugin.kt index 63670fbab8..572c309c94 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/TidepoolPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/TidepoolPlugin.kt @@ -1,10 +1,10 @@ package info.nightscout.androidaps.plugins.general.tidepool +import android.content.Context import android.text.Spanned import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import info.nightscout.androidaps.Constants -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.events.EventNetworkChange import info.nightscout.androidaps.events.EventNewBG @@ -42,9 +42,9 @@ import javax.inject.Singleton @Singleton class TidepoolPlugin @Inject constructor( aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, - private val mainApp: MainApp, - private val resourceHelper: ResourceHelper, + resourceHelper: ResourceHelper, + private val rxBus: RxBusWrapper, + private val context: Context, private val fabricPrivacy: FabricPrivacy, private val tidepoolUploader: TidepoolUploader, private val uploadChunk: UploadChunk, @@ -56,7 +56,7 @@ class TidepoolPlugin @Inject constructor( .fragmentClass(TidepoolFragment::class.qualifiedName) .preferencesId(R.xml.pref_tidepool) .description(R.string.description_tidepool), - rxBus, aapsLogger + aapsLogger, resourceHelper ) { private var disposable: CompositeDisposable = CompositeDisposable() @@ -135,7 +135,7 @@ class TidepoolPlugin @Inject constructor( override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) { super.preprocessPreferences(preferenceFragment) - val tidepoolTestLogin : Preference? = preferenceFragment.findPreference(resourceHelper.gs(R.string.key_tidepool_test_login)) + val tidepoolTestLogin: Preference? = preferenceFragment.findPreference(resourceHelper.gs(R.string.key_tidepool_test_login)) tidepoolTestLogin?.setOnPreferenceClickListener { preferenceFragment.context?.let { tidepoolUploader.testLogin(it) @@ -176,7 +176,7 @@ class TidepoolPlugin @Inject constructor( } textLog = HtmlHelper.fromHtml(newTextLog.toString()) } catch (e: OutOfMemoryError) { - ToastUtils.showToastInUiThread(mainApp, "Out of memory!\nStop using this phone !!!", R.raw.error) + ToastUtils.showToastInUiThread(context, "Out of memory!\nStop using this phone !!!", R.raw.error) } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/TidepoolUploader.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/TidepoolUploader.kt index 45b957de1b..5e859e1847 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/TidepoolUploader.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/TidepoolUploader.kt @@ -151,7 +151,7 @@ class TidepoolUploader @Inject constructor( if (session.datasetReply == null) { rxBus.send(EventTidepoolStatus(("Creating new dataset"))) val call = session.service.openDataSet(session.token!!, session.authReply!!.userid!!, - OpenDatasetRequestMessage((configBuilderPlugin.activePump?.serialNumber() + OpenDatasetRequestMessage((configBuilderPlugin.activePumpPlugin?.serialNumber() ?: InstanceId.instanceId())).getBody()) call.enqueue(TidepoolCallback(rxBus, session, "Open New Dataset", { connectionStatus = ConnectionStatus.CONNECTED diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/UploadChunk.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/UploadChunk.kt index b2cdc05699..919e15941e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/UploadChunk.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/UploadChunk.kt @@ -150,6 +150,7 @@ class UploadChunk @Inject constructor( } return results } + private fun getBasals(start: Long, end: Long): List { val tbrs = treatmentsPlugin.temporaryBasalsFromHistory tbrs.merge() @@ -160,7 +161,8 @@ class UploadChunk @Inject constructor( } fun newInstanceOrNull(ps: ProfileSwitch): ProfileElement? = try { - ProfileElement(ps, configBuilderPlugin.activePump?.serialNumber() ?: InstanceId.instanceId()) + ProfileElement(ps, configBuilderPlugin.activePumpPlugin?.serialNumber() + ?: InstanceId.instanceId()) } catch (e: Throwable) { null } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt index a412305c0b..1592c7b2f6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt @@ -2,6 +2,7 @@ package info.nightscout.androidaps.plugins.general.wear import android.app.NotificationManager import android.content.Context +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Config import info.nightscout.androidaps.Constants import info.nightscout.androidaps.MainApp @@ -9,16 +10,15 @@ import info.nightscout.androidaps.R import info.nightscout.androidaps.data.DetailedBolusInfo import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.db.CareportalEvent -import info.nightscout.androidaps.db.DatabaseHelper import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.db.TDD import info.nightscout.androidaps.db.TempTarget +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.PluginBase -import info.nightscout.androidaps.interfaces.PumpInterface import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification @@ -30,7 +30,6 @@ import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin import info.nightscout.androidaps.plugins.pump.danaRv2.DanaRv2Plugin import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin import info.nightscout.androidaps.plugins.treatments.CarbsGenerator -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DecimalFormatter @@ -52,14 +51,16 @@ class ActionStringHandler @Inject constructor( private val sp: SP, private val rxBus: RxBusWrapper, private val resourceHelper: ResourceHelper, + private val injector: HasAndroidInjector, + private val context: Context, private val constraintChecker: ConstraintChecker, private val profileFunction: ProfileFunction, - private val mainApp: MainApp, private val loopPlugin: LoopPlugin, private val wearPlugin: WearPlugin, - private val treatmentsPlugin: TreatmentsPlugin, - private val configBuilderPlugin: ConfigBuilderPlugin, + private val commandQueue: CommandQueueProvider, + private val activePlugin: ActivePluginProvider, private val iobCobCalculatorPlugin: IobCobCalculatorPlugin, + private val localInsightPlugin: LocalInsightPlugin, private val danaRPlugin: DanaRPlugin, private val danaRKoreanPlugin: DanaRKoreanPlugin, private val danaRv2Plugin: DanaRv2Plugin, @@ -175,7 +176,7 @@ class ActionStringHandler @Inject constructor( sendError("No profile found!") return } - val bgReading = DatabaseHelper.actualBg() + val bgReading = iobCobCalculatorPlugin.actualBg() if (bgReading == null && useBG) { sendError("No recent BG to base calculation on!") return @@ -187,7 +188,7 @@ class ActionStringHandler @Inject constructor( } val format = DecimalFormat("0.00") val formatInt = DecimalFormat("0") - val bolusWizard = BolusWizard(mainApp).doCalc(profile, profileName, treatmentsPlugin.tempTargetFromHistory, + val bolusWizard = BolusWizard(injector).doCalc(profile, profileName, activePlugin.activeTreatments.tempTargetFromHistory, carbsAfterConstraints, cobInfo.displayCob!!, bgReading!!.valueToUnits(profileFunction.getUnits()), 0.0, percentage.toDouble(), useBG, useCOB, useBolusIOB, useBasalIOB, false, useTT, useTrend) if (Math.abs(bolusWizard.insulinAfterConstraints - bolusWizard.calculatedTotalInsulin) >= 0.01) { @@ -216,7 +217,7 @@ class ActionStringHandler @Inject constructor( } lastBolusWizard = bolusWizard } else if ("opencpp" == act[0]) { - val activeProfileSwitch = treatmentsPlugin.getProfileSwitchFromHistory(System.currentTimeMillis()) + val activeProfileSwitch = activePlugin.activeTreatments.getProfileSwitchFromHistory(System.currentTimeMillis()) if (activeProfileSwitch == null) { sendError("No active profile switch!") return @@ -226,7 +227,7 @@ class ActionStringHandler @Inject constructor( rAction = "opencpp" + " " + activeProfileSwitch.percentage + " " + activeProfileSwitch.timeshift } } else if ("cppset" == act[0]) { - val activeProfileSwitch = treatmentsPlugin.getProfileSwitchFromHistory(System.currentTimeMillis()) + val activeProfileSwitch = activePlugin.activeTreatments.getProfileSwitchFromHistory(System.currentTimeMillis()) if (activeProfileSwitch == null) { sendError("No active profile switch!") return @@ -237,7 +238,7 @@ class ActionStringHandler @Inject constructor( rAction = actionString } } else if ("tddstats" == act[0]) { - val activePump: Any? = configBuilderPlugin.activePump + val activePump = activePlugin.activePumpPlugin if (activePump != null) { // check if DB up to date val dummies: MutableList = LinkedList() val historyList = getTDDList(dummies) @@ -246,12 +247,11 @@ class ActionStringHandler @Inject constructor( rAction = "statusmessage" rMessage = "OLD DATA - " //if pump is not busy: try to fetch data - val pump = configBuilderPlugin.activePump - if (pump!!.isBusy) { + if (activePump.isBusy) { rMessage += resourceHelper.gs(R.string.pumpbusy) } else { rMessage += "trying to fetch data from pump." - configBuilderPlugin.commandQueue.loadTDDs(object : Callback() { + commandQueue.loadTDDs(object : Callback() { override fun run() { val dummies1: MutableList = LinkedList() val historyList1 = getTDDList(dummies1) @@ -314,7 +314,7 @@ class ActionStringHandler @Inject constructor( val df: DateFormat = SimpleDateFormat("dd.MM.", Locale.getDefault()) var message = "" val refTDD = profile.baseBasalSum() * 2 - val pump = configBuilderPlugin.activePump + val pump = activePlugin.activePumpPlugin if (df.format(Date(historyList[0].date)) == df.format(Date())) { val tdd = historyList[0].getTotal() historyList.removeAt(0) @@ -358,9 +358,8 @@ class ActionStringHandler @Inject constructor( } private fun isOldData(historyList: List): Boolean { - val activePump: Any? = configBuilderPlugin.activePump - val insight: PumpInterface = LocalInsightPlugin.getPlugin() - val startsYesterday = activePump === danaRPlugin || activePump === danaRSPlugin || activePump === danaRv2Plugin || activePump === danaRKoreanPlugin || activePump === insight + val activePump = activePlugin.activePumpPlugin ?: return false + val startsYesterday = activePump === danaRPlugin || activePump === danaRSPlugin || activePump === danaRv2Plugin || activePump === danaRKoreanPlugin || activePump === localInsightPlugin val df: DateFormat = SimpleDateFormat("dd.MM.", Locale.getDefault()) return historyList.size < 3 || df.format(Date(historyList[0].date)) != df.format(Date(System.currentTimeMillis() - if (startsYesterday) 1000 * 60 * 60 * 24 else 0)) } @@ -390,7 +389,7 @@ class ActionStringHandler @Inject constructor( } private val pumpStatus: String - get() = configBuilderPlugin.activePump?.shortStatus(false) ?: "" + get() = activePlugin.activePumpPlugin?.shortStatus(false) ?: "" // decide if enabled/disabled closed/open; what Plugin as APS? private val loopStatus: String @@ -403,7 +402,7 @@ class ActionStringHandler @Inject constructor( } else { "OPEN LOOP\n" } - val aps = configBuilderPlugin.activeAPS + val aps = activePlugin.activeAPS ret += "APS: " + if (aps == null) "NO APS SELECTED!" else (aps as PluginBase).name if (loopPlugin.lastRun != null) { if (loopPlugin.lastRun.lastAPSRun != null) ret += "\nLast Run: " + DateUtil.timeString(loopPlugin.lastRun.lastAPSRun) @@ -424,7 +423,7 @@ class ActionStringHandler @Inject constructor( } val profile = profileFunction.getProfile() ?: return "No profile set :(" //Check for Temp-Target: - val tempTarget = treatmentsPlugin.tempTargetFromHistory + val tempTarget = activePlugin.activeTreatments.tempTargetFromHistory if (tempTarget != null) { ret += "Temp Target: " + Profile.toTargetRangeString(tempTarget.low, tempTarget.low, Constants.MGDL, profileFunction.getUnits()) ret += "\nuntil: " + DateUtil.timeString(tempTarget.originalEnd()) @@ -439,10 +438,11 @@ class ActionStringHandler @Inject constructor( private val oAPSResultStatus: String get() { var ret = "" - if (!Config.APS) { + if (!Config.APS) return "Only apply in APS mode!" - } - val usedAPS = configBuilderPlugin.activeAPS ?: return "No active APS :(!" + if (activePlugin.activePumpPlugin == null) + return resourceHelper.gs((R.string.nopumpselected)) + val usedAPS = activePlugin.activeAPS ?: return "No active APS :(!" val result = usedAPS.lastAPSResult ?: return "Last result not available!" ret += if (!result.isChangeRequested) { resourceHelper.gs(R.string.nochangerequested) + "\n" @@ -450,7 +450,7 @@ class ActionStringHandler @Inject constructor( resourceHelper.gs(R.string.canceltemp) + "\n" } else { resourceHelper.gs(R.string.rate) + ": " + DecimalFormatter.to2Decimal(result.rate) + " U/h " + - "(" + DecimalFormatter.to2Decimal(result.rate / configBuilderPlugin.activePump!!.baseBasalRate * 100) + "%)\n" + + "(" + DecimalFormatter.to2Decimal(result.rate / activePlugin.activePump.baseBasalRate * 100) + "%)\n" + resourceHelper.gs(R.string.duration) + ": " + DecimalFormatter.to0Decimal(result.duration.toDouble()) + " min\n" } ret += "\n" + resourceHelper.gs(R.string.reason) + ": " + result.reason @@ -471,7 +471,7 @@ class ActionStringHandler @Inject constructor( val amount = SafeParse.stringToDouble(act[1]) val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(amount)).value() if (amount - insulinAfterConstraints != 0.0) { - ToastUtils.showToastInUiThread(mainApp, "aborting: previously applied constraint changed") + ToastUtils.showToastInUiThread(context, "aborting: previously applied constraint changed") sendError("aborting: previously applied constraint changed") return } @@ -508,7 +508,7 @@ class ActionStringHandler @Inject constructor( rxBus.send(EventDismissNotification(SafeParse.stringToInt(act[1]))) } else if ("changeRequest" == act[0]) { loopPlugin.acceptChangeRequest() - val notificationManager = mainApp.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.cancel(Constants.notificationID) } lastBolusWizard = null @@ -547,7 +547,7 @@ class ActionStringHandler @Inject constructor( return } //send profile to pumpe - treatmentsPlugin.doProfileSwitch(0, percentage, timeshift) + activePlugin.activeTreatments.doProfileSwitch(0, percentage, timeshift) } private fun generateTempTarget(duration: Int, low: Double, high: Double) { @@ -561,7 +561,7 @@ class ActionStringHandler @Inject constructor( } else { tempTarget.low(0.0).high(0.0) } - treatmentsPlugin.addToHistoryTempTarget(tempTarget) + activePlugin.activeTreatments.addToHistoryTempTarget(tempTarget) } private fun doFillBolus(amount: Double) { @@ -569,7 +569,7 @@ class ActionStringHandler @Inject constructor( detailedBolusInfo.insulin = amount detailedBolusInfo.isValid = false detailedBolusInfo.source = Source.USER - configBuilderPlugin.commandQueue.bolus(detailedBolusInfo, object : Callback() { + commandQueue.bolus(detailedBolusInfo, object : Callback() { override fun run() { if (!result.success) { sendError(resourceHelper.gs(R.string.treatmentdeliveryerror) + @@ -585,8 +585,9 @@ class ActionStringHandler @Inject constructor( detailedBolusInfo.insulin = amount detailedBolusInfo.carbs = carbs.toDouble() detailedBolusInfo.source = Source.USER - if (detailedBolusInfo.insulin > 0 || configBuilderPlugin.activePump!!.pumpDescription.storesCarbInfo) { - configBuilderPlugin.commandQueue.bolus(detailedBolusInfo, object : Callback() { + val storesCarbs = activePlugin.activePumpPlugin?.pumpDescription?.storesCarbInfo ?: return + if (detailedBolusInfo.insulin > 0 || storesCarbs) { + commandQueue.bolus(detailedBolusInfo, object : Callback() { override fun run() { if (!result.success) { sendError(resourceHelper.gs(R.string.treatmentdeliveryerror) + @@ -596,7 +597,7 @@ class ActionStringHandler @Inject constructor( } }) } else { - treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, false) + activePlugin.activeTreatments.addToHistoryTreatment(detailedBolusInfo, false) } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt index c19aacc054..ba8be65201 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt @@ -26,12 +26,13 @@ import javax.inject.Singleton @Singleton class WearPlugin @Inject constructor( - private val resourceHelper: ResourceHelper, + aapsLogger: AAPSLogger, + resourceHelper: ResourceHelper, private val sp: SP, private val mainApp: MainApp, private val fabricPrivacy: FabricPrivacy, private val loopPlugin: Lazy, - rxBus: RxBusWrapper, aapsLogger: AAPSLogger + private val rxBus: RxBusWrapper ) : PluginBase(PluginDescription() .mainType(PluginType.GENERAL) @@ -40,7 +41,7 @@ class WearPlugin @Inject constructor( .shortName(R.string.wear_shortname) .preferencesId(R.xml.pref_wear) .description(R.string.description_wear), - rxBus, aapsLogger + aapsLogger, resourceHelper ) { private val disposable = CompositeDisposable() @@ -84,7 +85,8 @@ class WearPlugin @Inject constructor( .observeOn(Schedulers.io()) .subscribe({ if (WatchUpdaterService.shouldReportLoopStatus(loopPlugin.get().isEnabled(PluginType.LOOP))) - sendDataToWatch(status = true, basals = false, bgValue = false) }) { fabricPrivacy.logException(it) }) + sendDataToWatch(status = true, basals = false, bgValue = false) + }) { fabricPrivacy.logException(it) }) disposable.add(rxBus .toObservable(EventBolusRequested::class.java) .observeOn(Schedulers.io()) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java index 5329b8abd3..bdb920c6b0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java @@ -38,7 +38,6 @@ import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.BgReading; -import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.logging.AAPSLogger; @@ -48,7 +47,6 @@ import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.nsclient.data.NSDeviceStatus; -import info.nightscout.androidaps.plugins.general.overview.OverviewPlugin; import info.nightscout.androidaps.plugins.general.wear.ActionStringHandler; import info.nightscout.androidaps.plugins.general.wear.WearPlugin; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; @@ -275,7 +273,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog private void sendData() { - BgReading lastBG = DatabaseHelper.lastBg(); + BgReading lastBG = iobCobCalculatorPlugin.lastBg(); // Log.d(TAG, logPrefix + "LastBg=" + lastBG); if (lastBG != null) { GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(); @@ -379,7 +377,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog googleApiConnect(); } long startTime = System.currentTimeMillis() - (long) (60000 * 60 * 5.5); - BgReading last_bg = DatabaseHelper.lastBg(); + BgReading last_bg = iobCobCalculatorPlugin.lastBg(); if (last_bg == null) return; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatusLinePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatusLinePlugin.kt index f0f3b920fe..14f862c12b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatusLinePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatusLinePlugin.kt @@ -1,8 +1,8 @@ package info.nightscout.androidaps.plugins.general.xdripStatusline +import android.content.Context import android.content.Intent import android.os.Bundle -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.events.* @@ -16,7 +16,6 @@ import info.nightscout.androidaps.plugins.bus.RxBusWrapper 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.DecimalFormatter import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.extensions.plusAssign @@ -31,14 +30,14 @@ import javax.inject.Singleton class StatusLinePlugin @Inject constructor( private val sp: SP, private val profileFunction: ProfileFunction, - private val resourceHelper: ResourceHelper, - private val mainApp: MainApp, + resourceHelper: ResourceHelper, + private val context: Context, private val fabricPrivacy: FabricPrivacy, - private val activePluginProvider: ActivePluginProvider, - private val treatmentsPlugin: TreatmentsPlugin, + private val activePlugin: ActivePluginProvider, private val loopPlugin: LoopPlugin, private val iobCobCalculatorPlugin: IobCobCalculatorPlugin, - rxBus: RxBusWrapper, aapsLogger: AAPSLogger + private val rxBus: RxBusWrapper, + aapsLogger: AAPSLogger ) : PluginBase( PluginDescription() .mainType(PluginType.GENERAL) @@ -46,7 +45,7 @@ class StatusLinePlugin @Inject constructor( .shortName(R.string.xdripstatus_shortname) .neverVisible(true) .preferencesId(R.xml.pref_xdripstatus) - .description(R.string.description_xdrip_status_line), rxBus, aapsLogger) { + .description(R.string.description_xdrip_status_line), aapsLogger, resourceHelper) { private val disposable = CompositeDisposable() private var lastLoopStatus = false @@ -107,12 +106,12 @@ class StatusLinePlugin @Inject constructor( val intent = Intent(ACTION_NEW_EXTERNAL_STATUSLINE) intent.putExtras(bundle) intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) - mainApp.sendBroadcast(intent, null) + context.sendBroadcast(intent, null) } private fun buildStatusString(profile: Profile): String { var status = "" - if (activePluginProvider.activePump == null) return "" + if (activePlugin.activePumpPlugin == null) return "" if (!loopPlugin.isEnabled(PluginType.LOOP)) { status += resourceHelper.gs(R.string.disabledloop) + "\n" lastLoopStatus = false @@ -120,15 +119,15 @@ class StatusLinePlugin @Inject constructor( lastLoopStatus = true } //Temp basal - val activeTemp = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis()) + val activeTemp = activePlugin.activeTreatments.getTempBasalFromHistory(System.currentTimeMillis()) if (activeTemp != null) { status += activeTemp.toStringShort() + " " } //IOB - treatmentsPlugin.updateTotalIOBTreatments() - val bolusIob = treatmentsPlugin.lastCalculationTreatments.round() - treatmentsPlugin.updateTotalIOBTempBasals() - val basalIob = treatmentsPlugin.lastCalculationTempBasals.round() + activePlugin.activeTreatments.updateTotalIOBTreatments() + val bolusIob = activePlugin.activeTreatments.lastCalculationTreatments.round() + activePlugin.activeTreatments.updateTotalIOBTempBasals() + val basalIob = activePlugin.activeTreatments.lastCalculationTempBasals.round() status += DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U" if (sp.getBoolean(R.string.key_xdripstatus_detailediob, true)) { status += ("(" diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePlugin.kt index 39a66246d3..4cefb53116 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePlugin.kt @@ -21,15 +21,15 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper * */ abstract class InsulinOrefBasePlugin( - val resourceHelper: ResourceHelper, + resourceHelper: ResourceHelper, val profileFunction: ProfileFunction, - rxBus: RxBusWrapper, aapsLogger: AAPSLogger + val rxBus: RxBusWrapper, aapsLogger: AAPSLogger ) : PluginBase(PluginDescription() .mainType(PluginType.INSULIN) .fragmentClass(InsulinFragment::class.java.name) .shortName(R.string.insulin_shortname) .visibleByDefault(false), - rxBus, aapsLogger + aapsLogger, resourceHelper ), InsulinInterface { private var lastWarned: Long = 0 diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPlugin.kt index f5c26e9eda..8e33910983 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPlugin.kt @@ -6,7 +6,6 @@ import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.utils.resources.ResourceHelper -import info.nightscout.androidaps.utils.sharedPreferences.SP import javax.inject.Inject import javax.inject.Singleton @@ -21,17 +20,11 @@ class InsulinOrefUltraRapidActingPlugin @Inject constructor( ) : InsulinOrefBasePlugin(resourceHelper, profileFunction, rxBus, aapsLogger) { - override fun getId(): Int { - return InsulinInterface.OREF_ULTRA_RAPID_ACTING - } + override fun getId(): Int = InsulinInterface.OREF_ULTRA_RAPID_ACTING - override fun getFriendlyName(): String { - return resourceHelper.gs(R.string.ultrarapid_oref) - } + override fun getFriendlyName(): String = resourceHelper.gs(R.string.ultrarapid_oref) - override fun commentStandardText(): String { - return resourceHelper.gs(R.string.ultrafastactinginsulincomment) - } + override fun commentStandardText(): String = resourceHelper.gs(R.string.ultrafastactinginsulincomment) override val peak = 55 @@ -39,5 +32,6 @@ class InsulinOrefUltraRapidActingPlugin @Inject constructor( pluginDescription .pluginName(R.string.ultrarapid_oref) .description(R.string.description_insulin_ultra_rapid) + .enableByDefault(true) } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/AutosensData.java b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/AutosensData.java index 0c93e0266f..eee999ff4f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/AutosensData.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/AutosensData.java @@ -4,38 +4,46 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; -import java.util.Date; import java.util.List; import java.util.Locale; +import javax.inject.Inject; + +import dagger.android.HasAndroidInjector; 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.interfaces.PluginType; import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults; +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface; import info.nightscout.androidaps.plugins.general.overview.graphExtensions.PointsWithLabelGraphSeries; import info.nightscout.androidaps.plugins.general.overview.graphExtensions.Scale; import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin; import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin; import info.nightscout.androidaps.plugins.treatments.Treatment; -import info.nightscout.androidaps.utils.SP; - -/** - * Created by mike on 25.04.2017. - */ +import info.nightscout.androidaps.utils.DateUtil; +import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.sharedPreferences.SP; public class AutosensData implements DataPointWithLabelInterface { private static Logger log = LoggerFactory.getLogger(L.AUTOSENS); + @Inject SP sp; + @Inject ResourceHelper resourceHelper; + @Inject SensitivityWeightedAveragePlugin sensitivityWeightedAveragePlugin; + @Inject SensitivityAAPSPlugin sensitivityAAPSPlugin; + @Inject ProfileFunction profileFunction; + + AutosensData(HasAndroidInjector injector) { + injector.androidInjector().inject(this); + } + public void setChartTime(long chartTime) { this.chartTime = chartTime; } - static class CarbsInPast { + class CarbsInPast { long time = 0L; double carbs = 0d; double min5minCarbImpact = 0d; @@ -45,20 +53,20 @@ public class AutosensData implements DataPointWithLabelInterface { time = t.date; carbs = t.carbs; remaining = t.carbs; - if (SensitivityAAPSPlugin.getPlugin().isEnabled(PluginType.SENSITIVITY) || SensitivityWeightedAveragePlugin.getPlugin().isEnabled(PluginType.SENSITIVITY)) { - double maxAbsorptionHours = SP.getDouble(R.string.key_absorption_maxtime, Constants.DEFAULT_MAX_ABSORPTION_TIME); - Profile profile = ProfileFunctions.getInstance().getProfile(t.date); + if (sensitivityAAPSPlugin.isEnabled() || sensitivityWeightedAveragePlugin.isEnabled()) { + double maxAbsorptionHours = sp.getDouble(R.string.key_absorption_maxtime, Constants.DEFAULT_MAX_ABSORPTION_TIME); + Profile profile = profileFunction.getProfile(t.date); double sens = profile.getIsfMgdl(t.date); double ic = profile.getIc(t.date); min5minCarbImpact = t.carbs / (maxAbsorptionHours * 60 / 5) * sens / ic; if (L.isEnabled(L.AUTOSENS)) - log.debug("Min 5m carbs impact for " + carbs + "g @" + new Date(t.date).toLocaleString() + " for " + maxAbsorptionHours + "h calculated to " + min5minCarbImpact + " ISF: " + sens + " IC: " + ic); + log.debug("Min 5m carbs impact for " + carbs + "g @" + DateUtil.dateAndTimeString(t.date) + " for " + maxAbsorptionHours + "h calculated to " + min5minCarbImpact + " ISF: " + sens + " IC: " + ic); } else { - min5minCarbImpact = SP.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact); + min5minCarbImpact = sp.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact); } } - CarbsInPast (CarbsInPast other) { + CarbsInPast(CarbsInPast other) { this.time = other.time; this.carbs = other.carbs; this.min5minCarbImpact = other.min5minCarbImpact; @@ -67,7 +75,7 @@ public class AutosensData implements DataPointWithLabelInterface { @Override public String toString() { - return String.format(Locale.ENGLISH, "CarbsInPast: time: %s carbs: %.02f min5minCI: %.02f remaining: %.2f", new Date(time).toLocaleString(), carbs, min5minCarbImpact, remaining); + return String.format(Locale.ENGLISH, "CarbsInPast: time: %s carbs: %.02f min5minCI: %.02f remaining: %.2f", DateUtil.dateAndTimeString(time), carbs, min5minCarbImpact, remaining); } } @@ -103,13 +111,13 @@ public class AutosensData implements DataPointWithLabelInterface { @Override public String toString() { return String.format(Locale.ENGLISH, "AutosensData: %s pastSensitivity=%s delta=%.02f avgDelta=%.02f bgi=%.02f deviation=%.02f avgDeviation=%.02f absorbed=%.02f carbsFromBolus=%.02f cob=%.02f autosensRatio=%.02f slopeFromMaxDeviation=%.02f slopeFromMinDeviation=%.02f activeCarbsList=%s", - new Date(time).toLocaleString(), pastSensitivity, delta, avgDelta, bgi, deviation, avgDeviation, absorbed, carbsFromBolus, cob, autosensResult.ratio, slopeFromMaxDeviation, slopeFromMinDeviation, activeCarbsList.toString()); + DateUtil.dateAndTimeString(time), pastSensitivity, delta, avgDelta, bgi, deviation, avgDeviation, absorbed, carbsFromBolus, cob, autosensResult.ratio, slopeFromMaxDeviation, slopeFromMinDeviation, activeCarbsList.toString()); } public List cloneCarbsList() { List newActiveCarbsList = new ArrayList<>(); - for(CarbsInPast c: activeCarbsList) { + for (CarbsInPast c : activeCarbsList) { newActiveCarbsList.add(new CarbsInPast(c)); } @@ -119,10 +127,10 @@ public class AutosensData implements DataPointWithLabelInterface { // remove carbs older than timeframe public void removeOldCarbs(long toTime) { double maxAbsorptionHours = Constants.DEFAULT_MAX_ABSORPTION_TIME; - if (SensitivityAAPSPlugin.getPlugin().isEnabled(PluginType.SENSITIVITY) || SensitivityWeightedAveragePlugin.getPlugin().isEnabled(PluginType.SENSITIVITY)) { - maxAbsorptionHours = SP.getDouble(R.string.key_absorption_maxtime, Constants.DEFAULT_MAX_ABSORPTION_TIME); + if (sensitivityAAPSPlugin.isEnabled() || sensitivityWeightedAveragePlugin.isEnabled()) { + maxAbsorptionHours = sp.getDouble(R.string.key_absorption_maxtime, Constants.DEFAULT_MAX_ABSORPTION_TIME); } else { - maxAbsorptionHours = SP.getDouble(R.string.key_absorption_cutoff, Constants.DEFAULT_MAX_ABSORPTION_TIME); + maxAbsorptionHours = sp.getDouble(R.string.key_absorption_cutoff, Constants.DEFAULT_MAX_ABSORPTION_TIME); } for (int i = 0; i < activeCarbsList.size(); i++) { CarbsInPast c = activeCarbsList.get(i); @@ -131,7 +139,7 @@ public class AutosensData implements DataPointWithLabelInterface { if (c.remaining > 0) cob -= c.remaining; if (L.isEnabled(L.AUTOSENS)) - log.debug("Removing carbs at " + new Date(toTime).toLocaleString() + " after " + maxAbsorptionHours + "h > " + c.toString()); + log.debug("Removing carbs at " + DateUtil.dateAndTimeString(toTime) + " after " + maxAbsorptionHours + "h > " + c.toString()); } } } @@ -193,7 +201,7 @@ public class AutosensData implements DataPointWithLabelInterface { @Override public int getColor() { - return MainApp.gc(R.color.cob); + return resourceHelper.gc(R.color.cob); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java index d618ed64f4..86c46b77df 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java @@ -14,6 +14,7 @@ import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -55,11 +56,16 @@ import static info.nightscout.androidaps.utils.DateUtil.now; @Singleton public class IobCobCalculatorPlugin extends PluginBase { + private final HasAndroidInjector injector; private final SP sp; + private final RxBusWrapper rxBus; private final ResourceHelper resourceHelper; private final ProfileFunction profileFunction; private final ConfigBuilderPlugin configBuilderPlugin; private final TreatmentsPlugin treatmentsPlugin; + private final SensitivityOref1Plugin sensitivityOref1Plugin; + private final SensitivityAAPSPlugin sensitivityAAPSPlugin; + private final SensitivityWeightedAveragePlugin sensitivityWeightedAveragePlugin; private CompositeDisposable disposable = new CompositeDisposable(); @@ -86,35 +92,44 @@ public class IobCobCalculatorPlugin extends PluginBase { @Inject public IobCobCalculatorPlugin( + HasAndroidInjector injector, AAPSLogger aapsLogger, RxBusWrapper rxBus, SP sp, ResourceHelper resourceHelper, ProfileFunction profileFunction, ConfigBuilderPlugin configBuilderPlugin, - TreatmentsPlugin treatmentsPlugin + TreatmentsPlugin treatmentsPlugin, + SensitivityOref1Plugin sensitivityOref1Plugin, + SensitivityAAPSPlugin sensitivityAAPSPlugin, + SensitivityWeightedAveragePlugin sensitivityWeightedAveragePlugin ) { super(new PluginDescription() - .mainType(PluginType.GENERAL) - .pluginName(R.string.iobcobcalculator) - .showInList(false) - .neverVisible(true) - .alwaysEnabled(true), - rxBus, aapsLogger + .mainType(PluginType.GENERAL) + .pluginName(R.string.iobcobcalculator) + .showInList(false) + .neverVisible(true) + .alwaysEnabled(true), + aapsLogger, resourceHelper ); this.plugin = this; + this.injector = injector; this.sp = sp; + this.rxBus = rxBus; this.resourceHelper = resourceHelper; this.profileFunction = profileFunction; this.configBuilderPlugin = configBuilderPlugin; this.treatmentsPlugin = treatmentsPlugin; + this.sensitivityOref1Plugin = sensitivityOref1Plugin; + this.sensitivityAAPSPlugin = sensitivityAAPSPlugin; + this.sensitivityWeightedAveragePlugin = sensitivityWeightedAveragePlugin; } @Override protected void onStart() { super.onStart(); // EventConfigBuilderChange - disposable.add(getRxBus() + disposable.add(rxBus .toObservable(EventConfigBuilderChange.class) .observeOn(Schedulers.io()) .subscribe(event -> { @@ -128,7 +143,7 @@ public class IobCobCalculatorPlugin extends PluginBase { }, exception -> FabricPrivacy.getInstance().logException(exception)) ); // EventNewBasalProfile - disposable.add(getRxBus() + disposable.add(rxBus .toObservable(EventNewBasalProfile.class) .observeOn(Schedulers.io()) .subscribe(event -> { @@ -146,7 +161,7 @@ public class IobCobCalculatorPlugin extends PluginBase { }, exception -> FabricPrivacy.getInstance().logException(exception)) ); // EventNewBG - disposable.add(getRxBus() + disposable.add(rxBus .toObservable(EventNewBG.class) .observeOn(Schedulers.io()) .subscribe(event -> { @@ -155,7 +170,7 @@ public class IobCobCalculatorPlugin extends PluginBase { }, exception -> FabricPrivacy.getInstance().logException(exception)) ); // EventPreferenceChange - disposable.add(getRxBus() + disposable.add(rxBus .toObservable(EventPreferenceChange.class) .observeOn(Schedulers.io()) .subscribe(event -> { @@ -180,16 +195,16 @@ public class IobCobCalculatorPlugin extends PluginBase { }, exception -> FabricPrivacy.getInstance().logException(exception)) ); // EventAppInitialized - disposable.add(getRxBus() + disposable.add(rxBus .toObservable(EventAppInitialized.class) .observeOn(Schedulers.io()) .subscribe(event -> runCalculation("onEventAppInitialized", System.currentTimeMillis(), true, true, event), exception -> FabricPrivacy.getInstance().logException(exception)) ); // EventNewHistoryData - disposable.add(getRxBus() + disposable.add(rxBus .toObservable(EventNewHistoryData.class) .observeOn(Schedulers.io()) - .subscribe(event -> newHistoryData(event), exception -> FabricPrivacy.getInstance().logException(exception)) + .subscribe(this::newHistoryData, exception -> FabricPrivacy.getInstance().logException(exception)) ); } @@ -668,7 +683,7 @@ public class IobCobCalculatorPlugin extends PluginBase { long dia_ago = now - (Double.valueOf(profile.getDia() * T.hours(1).msecs())).longValue(); double maxAbsorptionHours = Constants.DEFAULT_MAX_ABSORPTION_TIME; - if (SensitivityAAPSPlugin.getPlugin().isEnabled(PluginType.SENSITIVITY) || SensitivityWeightedAveragePlugin.getPlugin().isEnabled(PluginType.SENSITIVITY)) { + if (sensitivityAAPSPlugin.isEnabled() || sensitivityWeightedAveragePlugin.isEnabled()) { maxAbsorptionHours = sp.getDouble(R.string.key_absorption_maxtime, Constants.DEFAULT_MAX_ABSORPTION_TIME); } else { maxAbsorptionHours = sp.getDouble(R.string.key_absorption_cutoff, Constants.DEFAULT_MAX_ABSORPTION_TIME); @@ -777,10 +792,10 @@ public class IobCobCalculatorPlugin extends PluginBase { public void runCalculation(String from, long end, boolean bgDataReload, boolean limitDataToOldestAvailable, Event cause) { getAapsLogger().debug(LTag.AUTOSENS, "Starting calculation thread: " + from + " to " + DateUtil.dateAndTimeString(end)); if (thread == null || thread.getState() == Thread.State.TERMINATED) { - if (SensitivityOref1Plugin.getPlugin().isEnabled(PluginType.SENSITIVITY)) - thread = new IobCobOref1Thread(this, from, end, bgDataReload, limitDataToOldestAvailable, cause); + if (sensitivityOref1Plugin.isEnabled()) + thread = new IobCobOref1Thread(injector, from, end, bgDataReload, limitDataToOldestAvailable, cause); else - thread = new IobCobThread(this, from, end, bgDataReload, limitDataToOldestAvailable, cause); + thread = new IobCobThread(injector, from, end, bgDataReload, limitDataToOldestAvailable, cause); thread.start(); } } @@ -831,6 +846,40 @@ public class IobCobCalculatorPlugin extends PluginBase { } } + /* + * Return last BgReading from database or null if db is empty + */ + @Nullable + public BgReading lastBg() { + List bgList = getBgReadings(); + + if (bgList == null) + return null; + + for (int i = 0; i < bgList.size(); i++) + if (bgList.get(i).value >= 39) + return bgList.get(i); + return null; + } + + /* + * Return bg reading if not old ( <9 min ) + * or null if older + */ + @Nullable + public BgReading actualBg() { + BgReading lastBg = lastBg(); + + if (lastBg == null) + return null; + + if (lastBg.date > System.currentTimeMillis() - 9 * 60 * 1000) + return lastBg; + + return null; + } + + // From https://gist.github.com/IceCreamYou/6ffa1b18c4c8f6aeaad2 // Returns the value at a given percentile in a sorted numeric array. // "Linear interpolation between closest ranks" method diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.java b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.java index 97c8cbb6db..04539a16a4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.java @@ -6,15 +6,14 @@ import android.os.SystemClock; import androidx.collection.LongSparseArray; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.ArrayList; import java.util.Calendar; -import java.util.Date; import java.util.GregorianCalendar; import java.util.List; +import javax.inject.Inject; + +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -23,24 +22,28 @@ import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.events.Event; +import info.nightscout.androidaps.interfaces.ActivePluginProvider; +import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults; -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.bus.RxBusWrapper; +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress; +import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin; +import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin; import info.nightscout.androidaps.plugins.treatments.Treatment; -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.MidnightTime; import info.nightscout.androidaps.utils.Profiler; -import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.T; +import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.sharedPreferences.SP; import static info.nightscout.androidaps.utils.DateUtil.now; import static java.util.Calendar.MINUTE; @@ -50,10 +53,20 @@ import static java.util.Calendar.MINUTE; */ public class IobCobOref1Thread extends Thread { - private static Logger log = LoggerFactory.getLogger(L.AUTOSENS); private final Event cause; - private IobCobCalculatorPlugin iobCobCalculatorPlugin; + @Inject AAPSLogger aapsLogger; + @Inject SP sp; + @Inject RxBusWrapper rxBus; + @Inject ResourceHelper resourceHelper; + @Inject ProfileFunction profileFunction; + @Inject Context context; + @Inject ActivePluginProvider activePluginProvider; + @Inject IobCobCalculatorPlugin iobCobCalculatorPlugin; + @Inject SensitivityAAPSPlugin sensitivityAAPSPlugin; + @Inject SensitivityWeightedAveragePlugin sensitivityWeightedAveragePlugin; + + private final HasAndroidInjector injector; private boolean bgDataReload; private boolean limitDataToOldestAvailable; private String from; @@ -61,19 +74,20 @@ public class IobCobOref1Thread extends Thread { private PowerManager.WakeLock mWakeLock; - IobCobOref1Thread(IobCobCalculatorPlugin plugin, String from, long end, boolean bgDataReload, boolean limitDataToOldestAvailable, Event cause) { + IobCobOref1Thread(HasAndroidInjector injector, String from, long end, boolean bgDataReload, boolean limitDataToOldestAvailable, Event cause) { super(); + injector.androidInjector().inject(this); + this.injector = injector; - this.iobCobCalculatorPlugin = plugin; this.bgDataReload = bgDataReload; this.limitDataToOldestAvailable = limitDataToOldestAvailable; this.from = from; this.cause = cause; this.end = end; - PowerManager powerManager = (PowerManager) MainApp.instance().getApplicationContext().getSystemService(Context.POWER_SERVICE); + PowerManager powerManager = (PowerManager) context.getApplicationContext().getSystemService(Context.POWER_SERVICE); if (powerManager != null) - mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, MainApp.gs(R.string.app_name) + ":iobCobThread"); + mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, resourceHelper.gs(R.string.app_name) + ":iobCobThread"); } @Override @@ -82,16 +96,9 @@ public class IobCobOref1Thread extends Thread { if (mWakeLock != null) mWakeLock.acquire(T.mins(10).msecs()); try { - if (L.isEnabled(L.AUTOSENS)) - log.debug("AUTOSENSDATA thread started: " + from); - if (ConfigBuilderPlugin.getPlugin() == null) { - if (L.isEnabled(L.AUTOSENS)) - log.debug("Aborting calculation thread (ConfigBuilder not ready): " + from); - return; // app still initializing - } - if (!ProfileFunctions.getInstance().isProfileValid("IobCobThread")) { - if (L.isEnabled(L.AUTOSENS)) - log.debug("Aborting calculation thread (No profile): " + from); + aapsLogger.debug(LTag.AUTOSENS, "AUTOSENSDATA thread started: " + from); + if (!profileFunction.isProfileValid("IobCobThread")) { + aapsLogger.debug(LTag.AUTOSENS, "Aborting calculation thread (No profile): " + from); return; // app still initializing } //log.debug("Locking calculateSensitivityData"); @@ -107,24 +114,21 @@ public class IobCobOref1Thread extends Thread { LongSparseArray autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable(); if (bucketed_data == null || bucketed_data.size() < 3) { - if (L.isEnabled(L.AUTOSENS)) - log.debug("Aborting calculation thread (No bucketed data available): " + from); + aapsLogger.debug(LTag.AUTOSENS, "Aborting calculation thread (No bucketed data available): " + from); return; } long prevDataTime = IobCobCalculatorPlugin.roundUpTime(bucketed_data.get(bucketed_data.size() - 3).date); - if (L.isEnabled(L.AUTOSENS)) - log.debug("Prev data time: " + new Date(prevDataTime).toLocaleString()); + aapsLogger.debug(LTag.AUTOSENS, "Prev data time: " + DateUtil.dateAndTimeString(prevDataTime)); AutosensData previous = autosensDataTable.get(prevDataTime); // start from oldest to be able sub cob for (int i = bucketed_data.size() - 4; i >= 0; i--) { String progress = i + (MainApp.isDev() ? " (" + from + ")" : ""); - RxBus.Companion.getINSTANCE().send(new EventIobCalculationProgress(progress)); + rxBus.send(new EventIobCalculationProgress(progress)); if (iobCobCalculatorPlugin.stopCalculationTrigger) { iobCobCalculatorPlugin.stopCalculationTrigger = false; - if (L.isEnabled(L.AUTOSENS)) - log.debug("Aborting calculation thread (trigger): " + from); + aapsLogger.debug(LTag.AUTOSENS, "Aborting calculation thread (trigger): " + from); return; } // check if data already exists @@ -139,19 +143,17 @@ public class IobCobOref1Thread extends Thread { continue; } - Profile profile = ProfileFunctions.getInstance().getProfile(bgTime); + Profile profile = profileFunction.getProfile(bgTime); if (profile == null) { - if (L.isEnabled(L.AUTOSENS)) - log.debug("Aborting calculation thread (no profile): " + from); + aapsLogger.debug(LTag.AUTOSENS, "Aborting calculation thread (no profile): " + from); return; // profile not set yet } - if (L.isEnabled(L.AUTOSENS)) - log.debug("Processing calculation thread: " + from + " (" + i + "/" + bucketed_data.size() + ")"); + aapsLogger.debug(LTag.AUTOSENS, "Processing calculation thread: " + from + " (" + i + "/" + bucketed_data.size() + ")"); double sens = profile.getIsfMgdl(bgTime); - AutosensData autosensData = new AutosensData(); + AutosensData autosensData = new AutosensData(injector); autosensData.time = bgTime; if (previous != null) autosensData.activeCarbsList = previous.cloneCarbsList(); @@ -164,7 +166,7 @@ public class IobCobOref1Thread extends Thread { double delta; bg = bucketed_data.get(i).value; if (bg < 39 || bucketed_data.get(i + 3).value < 39) { - log.error("! value < 39"); + aapsLogger.error("! value < 39"); continue; } autosensData.bg = bg; @@ -188,21 +190,20 @@ public class IobCobOref1Thread extends Thread { AutosensData hourAgoData = iobCobCalculatorPlugin.getAutosensData(hourago); if (hourAgoData != null) { int initialIndex = autosensDataTable.indexOfKey(hourAgoData.time); - if (L.isEnabled(L.AUTOSENS)) - log.debug(">>>>> bucketed_data.size()=" + bucketed_data.size() + " i=" + i + " hourAgoData=" + hourAgoData.toString()); + aapsLogger.debug(LTag.AUTOSENS, ">>>>> bucketed_data.size()=" + bucketed_data.size() + " i=" + i + " hourAgoData=" + hourAgoData.toString()); int past = 1; try { for (; past < 12; past++) { AutosensData ad = autosensDataTable.valueAt(initialIndex + past); if (L.isEnabled(L.AUTOSENS)) { - log.debug(">>>>> past=" + past + " ad=" + (ad != null ? ad.toString() : null)); + aapsLogger.debug(">>>>> past=" + past + " ad=" + (ad != null ? ad.toString() : null)); if (ad == null) { - log.debug(autosensDataTable.toString()); - log.debug(bucketed_data.toString()); - log.debug(IobCobCalculatorPlugin.getPlugin().getBgReadings().toString()); - Notification notification = new Notification(Notification.SENDLOGFILES, MainApp.gs(R.string.sendlogfiles), Notification.LOW); - RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); - SP.putBoolean("log_AUTOSENS", true); + aapsLogger.debug(autosensDataTable.toString()); + aapsLogger.debug(bucketed_data.toString()); + aapsLogger.debug(iobCobCalculatorPlugin.getBgReadings().toString()); + Notification notification = new Notification(Notification.SENDLOGFILES, resourceHelper.gs(R.string.sendlogfiles), Notification.LOW); + rxBus.send(new EventNewNotification(notification)); + sp.putBoolean("log_AUTOSENS", true); break; } } @@ -221,26 +222,25 @@ public class IobCobOref1Thread extends Thread { // log.debug("Deviations: " + new Date(bgTime) + new Date(ad.time) + " avgDeviation=" + avgDeviation + " deviationSlope=" + deviationSlope + " slopeFromMaxDeviation=" + slopeFromMaxDeviation + " slopeFromMinDeviation=" + slopeFromMinDeviation); } } catch (Exception e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); FabricPrivacy.getInstance().logException(e); - log.debug(autosensDataTable.toString()); - log.debug(bucketed_data.toString()); - log.debug(IobCobCalculatorPlugin.getPlugin().getBgReadings().toString()); - Notification notification = new Notification(Notification.SENDLOGFILES, MainApp.gs(R.string.sendlogfiles), Notification.LOW); - RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); - SP.putBoolean("log_AUTOSENS", true); + aapsLogger.debug(autosensDataTable.toString()); + aapsLogger.debug(bucketed_data.toString()); + aapsLogger.debug(iobCobCalculatorPlugin.getBgReadings().toString()); + Notification notification = new Notification(Notification.SENDLOGFILES, resourceHelper.gs(R.string.sendlogfiles), Notification.LOW); + rxBus.send(new EventNewNotification(notification)); + sp.putBoolean("log_AUTOSENS", true); break; } } else { - if (L.isEnabled(L.AUTOSENS)) - log.debug(">>>>> bucketed_data.size()=" + bucketed_data.size() + " i=" + i + " hourAgoData=" + "null"); + aapsLogger.debug(LTag.AUTOSENS, ">>>>> bucketed_data.size()=" + bucketed_data.size() + " i=" + i + " hourAgoData=" + "null"); } } - List recentCarbTreatments = TreatmentsPlugin.getPlugin().getCarbTreatments5MinBackFromHistory(bgTime); + List recentCarbTreatments = activePluginProvider.getActiveTreatments().getCarbTreatments5MinBackFromHistory(bgTime); for (Treatment recentCarbTreatment : recentCarbTreatments) { autosensData.carbsFromBolus += recentCarbTreatment.carbs; - autosensData.activeCarbsList.add(new AutosensData.CarbsInPast(recentCarbTreatment)); + autosensData.activeCarbsList.add(autosensData.new CarbsInPast(recentCarbTreatment)); autosensData.pastSensitivity += "[" + DecimalFormatter.to0Decimal(recentCarbTreatment.carbs) + "g]"; } @@ -257,7 +257,7 @@ public class IobCobOref1Thread extends Thread { // } // } else { //Oref sensitivity - totalMinCarbsImpact = SP.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact); + totalMinCarbsImpact = sp.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact); // } // figure out how many carbs that represents @@ -357,8 +357,8 @@ public class IobCobOref1Thread extends Thread { // add an extra negative deviation if a high temptarget is running and exercise mode is set // TODO AS-FIX - if (false && SP.getBoolean(R.string.key_high_temptarget_raises_sensitivity, SMBDefaults.high_temptarget_raises_sensitivity)) { - TempTarget tempTarget = TreatmentsPlugin.getPlugin().getTempTargetFromHistory(bgTime); + if (false && sp.getBoolean(R.string.key_high_temptarget_raises_sensitivity, SMBDefaults.high_temptarget_raises_sensitivity)) { + TempTarget tempTarget = activePluginProvider.getActiveTreatments().getTempTargetFromHistory(bgTime); if (tempTarget != null && tempTarget.target() >= 100) { autosensData.extraDeviation.add(-(tempTarget.target() - 100) / 20); } @@ -375,30 +375,24 @@ public class IobCobOref1Thread extends Thread { previous = autosensData; if (bgTime < now()) autosensDataTable.put(bgTime, autosensData); - if (L.isEnabled(L.AUTOSENS)) - log.debug("Running detectSensitivity from: " + DateUtil.dateAndTimeString(oldestTimeWithData) + " to: " + DateUtil.dateAndTimeString(bgTime) + " lastDataTime:" + iobCobCalculatorPlugin.lastDataTime()); + aapsLogger.debug(LTag.AUTOSENS, "Running detectSensitivity from: " + DateUtil.dateAndTimeString(oldestTimeWithData) + " to: " + DateUtil.dateAndTimeString(bgTime) + " lastDataTime:" + iobCobCalculatorPlugin.lastDataTime()); AutosensResult sensitivity = iobCobCalculatorPlugin.detectSensitivityWithLock(oldestTimeWithData, bgTime); - if (L.isEnabled(L.AUTOSENS)) - log.debug("Sensitivity result: " + sensitivity.toString()); + aapsLogger.debug(LTag.AUTOSENS, "Sensitivity result: " + sensitivity.toString()); autosensData.autosensResult = sensitivity; - if (L.isEnabled(L.AUTOSENS)) - log.debug(autosensData.toString()); + aapsLogger.debug(LTag.AUTOSENS, autosensData.toString()); } } new Thread(() -> { SystemClock.sleep(1000); - RxBus.Companion.getINSTANCE().send(new EventAutosensCalculationFinished(cause)); + rxBus.send(new EventAutosensCalculationFinished(cause)); }).start(); } finally { if (mWakeLock != null) mWakeLock.release(); - RxBus.Companion.getINSTANCE().send(new EventIobCalculationProgress("")); - if (L.isEnabled(L.AUTOSENS)) { - log.debug("AUTOSENSDATA thread ended: " + from); - log.debug("Midnights: " + MidnightTime.log()); - } - Profiler.log(log, "IobCobOref1Thread", start); + rxBus.send(new EventIobCalculationProgress("")); + aapsLogger.debug(LTag.AUTOSENS, "AUTOSENSDATA thread ended: " + from); + aapsLogger.debug(LTag.AUTOSENS, "Midnights: " + MidnightTime.log()); + Profiler.log(aapsLogger, LTag.AUTOSENS, "IobCobOref1Thread", start); } } - } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.java b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.java index 07d9d3c142..929011fab2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.java @@ -6,13 +6,12 @@ import android.os.SystemClock; import androidx.collection.LongSparseArray; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.ArrayList; -import java.util.Date; import java.util.List; +import javax.inject.Inject; + +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -20,12 +19,14 @@ import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.events.Event; +import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults; -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.bus.RxBusWrapper; +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished; @@ -33,14 +34,14 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCa import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin; import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin; import info.nightscout.androidaps.plugins.treatments.Treatment; -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.MidnightTime; import info.nightscout.androidaps.utils.Profiler; -import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.T; +import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.sharedPreferences.SP; import static info.nightscout.androidaps.utils.DateUtil.now; @@ -49,10 +50,20 @@ import static info.nightscout.androidaps.utils.DateUtil.now; */ public class IobCobThread extends Thread { - private static Logger log = LoggerFactory.getLogger(L.AUTOSENS); private final Event cause; - private IobCobCalculatorPlugin iobCobCalculatorPlugin; + @Inject AAPSLogger aapsLogger; + @Inject SP sp; + @Inject RxBusWrapper rxBus; + @Inject ResourceHelper resourceHelper; + @Inject ProfileFunction profileFunction; + @Inject Context context; + @Inject ActivePluginProvider activePluginProvider; + @Inject IobCobCalculatorPlugin iobCobCalculatorPlugin; + @Inject SensitivityAAPSPlugin sensitivityAAPSPlugin; + @Inject SensitivityWeightedAveragePlugin sensitivityWeightedAveragePlugin; + + private final HasAndroidInjector injector; private boolean bgDataReload; private boolean limitDataToOldestAvailable; private String from; @@ -60,19 +71,20 @@ public class IobCobThread extends Thread { private PowerManager.WakeLock mWakeLock; - IobCobThread(IobCobCalculatorPlugin plugin, String from, long end, boolean bgDataReload, boolean limitDataToOldestAvailable, Event cause) { + @Inject IobCobThread(HasAndroidInjector injector, String from, long end, boolean bgDataReload, boolean limitDataToOldestAvailable, Event cause) { super(); + injector.androidInjector().inject(this); + this.injector = injector; - this.iobCobCalculatorPlugin = plugin; this.bgDataReload = bgDataReload; this.limitDataToOldestAvailable = limitDataToOldestAvailable; this.from = from; this.cause = cause; this.end = end; - PowerManager powerManager = (PowerManager) MainApp.instance().getApplicationContext().getSystemService(Context.POWER_SERVICE); + PowerManager powerManager = (PowerManager) context.getApplicationContext().getSystemService(Context.POWER_SERVICE); if (powerManager != null) - mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, MainApp.gs(R.string.app_name) + ":iobCobThread"); + mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, resourceHelper.gs(R.string.app_name) + ":iobCobThread"); } @Override @@ -81,16 +93,9 @@ public class IobCobThread extends Thread { if (mWakeLock != null) mWakeLock.acquire(T.mins(10).msecs()); try { - if (L.isEnabled(L.AUTOSENS)) - log.debug("AUTOSENSDATA thread started: " + from); - if (ConfigBuilderPlugin.getPlugin() == null) { - if (L.isEnabled(L.AUTOSENS)) - log.debug("Aborting calculation thread (ConfigBuilder not ready): " + from); - return; // app still initializing - } - if (!ProfileFunctions.getInstance().isProfileValid("IobCobThread")) { - if (L.isEnabled(L.AUTOSENS)) - log.debug("Aborting calculation thread (No profile): " + from); + aapsLogger.debug(LTag.AUTOSENS, "AUTOSENSDATA thread started: " + from); + if (!profileFunction.isProfileValid("IobCobThread")) { + aapsLogger.debug(LTag.AUTOSENS, "Aborting calculation thread (No profile): " + from); return; // app still initializing } //log.debug("Locking calculateSensitivityData"); @@ -106,24 +111,21 @@ public class IobCobThread extends Thread { LongSparseArray autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable(); if (bucketed_data == null || bucketed_data.size() < 3) { - if (L.isEnabled(L.AUTOSENS)) - log.debug("Aborting calculation thread (No bucketed data available): " + from); + aapsLogger.debug(LTag.AUTOSENS, "Aborting calculation thread (No bucketed data available): " + from); return; } long prevDataTime = IobCobCalculatorPlugin.roundUpTime(bucketed_data.get(bucketed_data.size() - 3).date); - if (L.isEnabled(L.AUTOSENS)) - log.debug("Prev data time: " + new Date(prevDataTime).toLocaleString()); + aapsLogger.debug(LTag.AUTOSENS, "Prev data time: " + DateUtil.dateAndTimeString(prevDataTime)); AutosensData previous = autosensDataTable.get(prevDataTime); // start from oldest to be able sub cob for (int i = bucketed_data.size() - 4; i >= 0; i--) { String progress = i + (MainApp.isDev() ? " (" + from + ")" : ""); - RxBus.Companion.getINSTANCE().send(new EventIobCalculationProgress(progress)); + rxBus.send(new EventIobCalculationProgress(progress)); if (iobCobCalculatorPlugin.stopCalculationTrigger) { iobCobCalculatorPlugin.stopCalculationTrigger = false; - if (L.isEnabled(L.AUTOSENS)) - log.debug("Aborting calculation thread (trigger): " + from); + aapsLogger.debug(LTag.AUTOSENS, "Aborting calculation thread (trigger): " + from); return; } // check if data already exists @@ -138,19 +140,17 @@ public class IobCobThread extends Thread { continue; } - Profile profile = ProfileFunctions.getInstance().getProfile(bgTime); + Profile profile = profileFunction.getProfile(bgTime); if (profile == null) { - if (L.isEnabled(L.AUTOSENS)) - log.debug("Aborting calculation thread (no profile): " + from); + aapsLogger.debug(LTag.AUTOSENS, "Aborting calculation thread (no profile): " + from); return; // profile not set yet } - if (L.isEnabled(L.AUTOSENS)) - log.debug("Processing calculation thread: " + from + " (" + i + "/" + bucketed_data.size() + ")"); + aapsLogger.debug(LTag.AUTOSENS, "Processing calculation thread: " + from + " (" + i + "/" + bucketed_data.size() + ")"); double sens = profile.getIsfMgdl(bgTime); - AutosensData autosensData = new AutosensData(); + AutosensData autosensData = new AutosensData(injector); autosensData.time = bgTime; if (previous != null) autosensData.activeCarbsList = previous.cloneCarbsList(); @@ -163,7 +163,7 @@ public class IobCobThread extends Thread { double delta; bg = bucketed_data.get(i).value; if (bg < 39 || bucketed_data.get(i + 3).value < 39) { - log.error("! value < 39"); + aapsLogger.error("! value < 39"); continue; } autosensData.bg = bg; @@ -187,21 +187,20 @@ public class IobCobThread extends Thread { AutosensData hourAgoData = iobCobCalculatorPlugin.getAutosensData(hourago); if (hourAgoData != null) { int initialIndex = autosensDataTable.indexOfKey(hourAgoData.time); - if (L.isEnabled(L.AUTOSENS)) - log.debug(">>>>> bucketed_data.size()=" + bucketed_data.size() + " i=" + i + " hourAgoData=" + hourAgoData.toString()); + aapsLogger.debug(LTag.AUTOSENS, ">>>>> bucketed_data.size()=" + bucketed_data.size() + " i=" + i + " hourAgoData=" + hourAgoData.toString()); int past = 1; try { for (; past < 12; past++) { AutosensData ad = autosensDataTable.valueAt(initialIndex + past); if (L.isEnabled(L.AUTOSENS)) { - log.debug(">>>>> past=" + past + " ad=" + (ad != null ? ad.toString() : null)); + aapsLogger.debug(">>>>> past=" + past + " ad=" + (ad != null ? ad.toString() : null)); if (ad == null) { - log.debug(autosensDataTable.toString()); - log.debug(bucketed_data.toString()); - log.debug(IobCobCalculatorPlugin.getPlugin().getBgReadings().toString()); - Notification notification = new Notification(Notification.SENDLOGFILES, MainApp.gs(R.string.sendlogfiles), Notification.LOW); - RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); - SP.putBoolean("log_AUTOSENS", true); + aapsLogger.debug(autosensDataTable.toString()); + aapsLogger.debug(bucketed_data.toString()); + aapsLogger.debug(iobCobCalculatorPlugin.getBgReadings().toString()); + Notification notification = new Notification(Notification.SENDLOGFILES, resourceHelper.gs(R.string.sendlogfiles), Notification.LOW); + rxBus.send(new EventNewNotification(notification)); + sp.putBoolean("log_AUTOSENS", true); break; } } @@ -220,26 +219,25 @@ public class IobCobThread extends Thread { // log.debug("Deviations: " + new Date(bgTime) + new Date(ad.time) + " avgDeviation=" + avgDeviation + " deviationSlope=" + deviationSlope + " slopeFromMaxDeviation=" + slopeFromMaxDeviation + " slopeFromMinDeviation=" + slopeFromMinDeviation); } } catch (Exception e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); FabricPrivacy.getInstance().logException(e); - log.debug(autosensDataTable.toString()); - log.debug(bucketed_data.toString()); - log.debug(IobCobCalculatorPlugin.getPlugin().getBgReadings().toString()); - Notification notification = new Notification(Notification.SENDLOGFILES, MainApp.gs(R.string.sendlogfiles), Notification.LOW); - RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); - SP.putBoolean("log_AUTOSENS", true); + aapsLogger.debug(autosensDataTable.toString()); + aapsLogger.debug(bucketed_data.toString()); + aapsLogger.debug(iobCobCalculatorPlugin.getBgReadings().toString()); + Notification notification = new Notification(Notification.SENDLOGFILES, resourceHelper.gs(R.string.sendlogfiles), Notification.LOW); + rxBus.send(new EventNewNotification(notification)); + sp.putBoolean("log_AUTOSENS", true); break; } } else { - if (L.isEnabled(L.AUTOSENS)) - log.debug(">>>>> bucketed_data.size()=" + bucketed_data.size() + " i=" + i + " hourAgoData=" + "null"); + aapsLogger.debug(LTag.AUTOSENS, ">>>>> bucketed_data.size()=" + bucketed_data.size() + " i=" + i + " hourAgoData=" + "null"); } } - List recentCarbTreatments = TreatmentsPlugin.getPlugin().getCarbTreatments5MinBackFromHistory(bgTime); + List recentCarbTreatments = activePluginProvider.getActiveTreatments().getCarbTreatments5MinBackFromHistory(bgTime); for (Treatment recentCarbTreatment : recentCarbTreatments) { autosensData.carbsFromBolus += recentCarbTreatment.carbs; - autosensData.activeCarbsList.add(new AutosensData.CarbsInPast(recentCarbTreatment)); + autosensData.activeCarbsList.add(autosensData.new CarbsInPast(recentCarbTreatment)); autosensData.pastSensitivity += "[" + DecimalFormatter.to0Decimal(recentCarbTreatment.carbs) + "g]"; } @@ -248,7 +246,7 @@ public class IobCobThread extends Thread { if (previous != null && previous.cob > 0) { // calculate sum of min carb impact from all active treatments double totalMinCarbsImpact = 0d; - if (SensitivityAAPSPlugin.getPlugin().isEnabled(PluginType.SENSITIVITY) || SensitivityWeightedAveragePlugin.getPlugin().isEnabled(PluginType.SENSITIVITY)) { + if (sensitivityAAPSPlugin.isEnabled(PluginType.SENSITIVITY) || sensitivityWeightedAveragePlugin.isEnabled(PluginType.SENSITIVITY)) { //when the impact depends on a max time, sum them up as smaller carb sizes make them smaller for (int ii = 0; ii < autosensData.activeCarbsList.size(); ++ii) { AutosensData.CarbsInPast c = autosensData.activeCarbsList.get(ii); @@ -256,7 +254,7 @@ public class IobCobThread extends Thread { } } else { //Oref sensitivity - totalMinCarbsImpact = SP.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact); + totalMinCarbsImpact = sp.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact); } // figure out how many carbs that represents @@ -301,29 +299,24 @@ public class IobCobThread extends Thread { previous = autosensData; if (bgTime < now()) autosensDataTable.put(bgTime, autosensData); - if (L.isEnabled(L.AUTOSENS)) - log.debug("Running detectSensitivity from: " + DateUtil.dateAndTimeString(oldestTimeWithData) + " to: " + DateUtil.dateAndTimeString(bgTime) + " lastDataTime:" + iobCobCalculatorPlugin.lastDataTime()); + aapsLogger.debug(LTag.AUTOSENS, "Running detectSensitivity from: " + DateUtil.dateAndTimeString(oldestTimeWithData) + " to: " + DateUtil.dateAndTimeString(bgTime) + " lastDataTime:" + iobCobCalculatorPlugin.lastDataTime()); AutosensResult sensitivity = iobCobCalculatorPlugin.detectSensitivityWithLock(oldestTimeWithData, bgTime); - if (L.isEnabled(L.AUTOSENS)) - log.debug("Sensitivity result: " + sensitivity.toString()); + aapsLogger.debug(LTag.AUTOSENS, "Sensitivity result: " + sensitivity.toString()); autosensData.autosensResult = sensitivity; - if (L.isEnabled(L.AUTOSENS)) - log.debug(autosensData.toString()); + aapsLogger.debug(LTag.AUTOSENS, autosensData.toString()); } } new Thread(() -> { SystemClock.sleep(1000); - RxBus.Companion.getINSTANCE().send(new EventAutosensCalculationFinished(cause)); + rxBus.send(new EventAutosensCalculationFinished(cause)); }).start(); } finally { if (mWakeLock != null) mWakeLock.release(); - RxBus.Companion.getINSTANCE().send(new EventIobCalculationProgress("")); - if (L.isEnabled(L.AUTOSENS)) { - log.debug("AUTOSENSDATA thread ended: " + from); - log.debug("Midnights: " + MidnightTime.log()); - } - Profiler.log(log, "IobCobThread", start); + rxBus.send(new EventIobCalculationProgress("")); + aapsLogger.debug(LTag.AUTOSENS, "AUTOSENSDATA thread ended: " + from); + aapsLogger.debug(LTag.AUTOSENS, "Midnights: " + MidnightTime.log()); + Profiler.log(aapsLogger, LTag.AUTOSENS, "IobCobThread", start); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.kt index 2753619418..c05de709ff 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.kt @@ -15,7 +15,6 @@ import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.dialogs.ProfileSwitchDialog import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.insulin.InsulinOrefBasePlugin.Companion.MIN_DIA import info.nightscout.androidaps.plugins.profile.local.events.EventLocalProfileChanged import info.nightscout.androidaps.utils.* @@ -30,7 +29,7 @@ import javax.inject.Inject class LocalProfileFragment : DaggerFragment() { @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var resourceHelper: ResourceHelper - @Inject lateinit var activePluginProvider: ActivePluginProvider + @Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var localProfilePlugin: LocalProfilePlugin @@ -94,7 +93,7 @@ class LocalProfileFragment : DaggerFragment() { } fun build() { - val pumpDescription = activePluginProvider.activePump?.pumpDescription ?: return + val pumpDescription = activePlugin.activePumpPlugin?.pumpDescription ?: return val units = if (localProfilePlugin.currentProfile().mgdl) Constants.MGDL else Constants.MMOL localprofile_name.removeTextChangedListener(textWatch) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt index c76dc47af4..d8498f6944 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt @@ -27,12 +27,13 @@ import java.util.* import javax.inject.Inject import javax.inject.Singleton import kotlin.collections.ArrayList +import kotlin.math.max @Singleton class LocalProfilePlugin @Inject constructor( aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, - private val resourceHelper: ResourceHelper, + private val rxBus: RxBusWrapper, + resourceHelper: ResourceHelper, private val sp: SP, private val profileFunction: ProfileFunction ) : PluginBase(PluginDescription() @@ -41,7 +42,7 @@ class LocalProfilePlugin @Inject constructor( .enableByDefault(true) .pluginName(R.string.localprofile) .shortName(R.string.localprofile_shortname) - .description(R.string.description_profile_local), rxBus, aapsLogger), ProfileInterface { + .description(R.string.description_profile_local), aapsLogger, resourceHelper), ProfileInterface { var rawProfile: ProfileStore? = null @@ -155,7 +156,7 @@ class LocalProfilePlugin @Inject constructor( numOfProfiles = sp.getInt(LOCAL_PROFILE + "_profiles", 0) profiles.clear() - numOfProfiles = Math.max(numOfProfiles, 1) // create at least one default profile if none exists + numOfProfiles = max(numOfProfiles, 1) // create at least one default profile if none exists for (i in 0 until numOfProfiles) { val p = SingleProfile() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfileFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfileFragment.kt index 17c9d37c99..cb6f9c9178 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfileFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfileFragment.kt @@ -32,6 +32,7 @@ class NSProfileFragment : DaggerFragment() { @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var nsProfilePlugin: NSProfilePlugin private var disposable: CompositeDisposable = CompositeDisposable() @@ -47,7 +48,7 @@ class NSProfileFragment : DaggerFragment() { nsprofile_profileswitch.setOnClickListener { val name = nsprofile_spinner.selectedItem?.toString() ?: "" - NSProfilePlugin.getPlugin().profile?.let { store -> + nsProfilePlugin.profile?.let { store -> store.getSpecificProfile(name)?.let { activity?.let { activity -> OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.nsprofile), @@ -79,7 +80,7 @@ class NSProfileFragment : DaggerFragment() { nsprofile_profileswitch.visibility = View.GONE - NSProfilePlugin.getPlugin().profile?.let { store -> + nsProfilePlugin.profile?.let { store -> store.getSpecificProfile(name)?.let { profile -> profileview_units.text = profile.units profileview_dia.text = resourceHelper.gs(R.string.format_hours, profile.dia) @@ -124,7 +125,7 @@ class NSProfileFragment : DaggerFragment() { if (profileview_noprofile == null) return profileview_noprofile.visibility = View.VISIBLE - NSProfilePlugin.getPlugin().profile?.let { profileStore -> + nsProfilePlugin.profile?.let { profileStore -> val profileList = profileStore.getProfileList() val adapter = ArrayAdapter(context!!, R.layout.spinner_centered, profileList) nsprofile_spinner.adapter = adapter diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.java deleted file mode 100644 index 934dc34b44..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.java +++ /dev/null @@ -1,128 +0,0 @@ -package info.nightscout.androidaps.plugins.profile.ns; - -import android.content.Intent; -import android.os.Bundle; - -import androidx.annotation.Nullable; - -import org.json.JSONException; -import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import info.nightscout.androidaps.Config; -import info.nightscout.androidaps.Constants; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ProfileStore; -import info.nightscout.androidaps.events.EventProfileStoreChanged; -import info.nightscout.androidaps.interfaces.PluginBase; -import info.nightscout.androidaps.interfaces.PluginDescription; -import info.nightscout.androidaps.interfaces.PluginType; -import info.nightscout.androidaps.interfaces.ProfileInterface; -import info.nightscout.androidaps.logging.AAPSLoggerProduction; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.bus.RxBus; -import info.nightscout.androidaps.plugins.bus.RxBusWrapper; -import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart; -import info.nightscout.androidaps.plugins.profile.ns.events.EventNSProfileUpdateGUI; -import info.nightscout.androidaps.utils.SP; - -/** - * Created by mike on 05.08.2016. - */ -public class NSProfilePlugin extends PluginBase implements ProfileInterface { - private static Logger log = LoggerFactory.getLogger(L.PROFILE); - - private static NSProfilePlugin nsProfilePlugin; - - public static NSProfilePlugin getPlugin() { - if (nsProfilePlugin == null) - nsProfilePlugin = new NSProfilePlugin(); - return nsProfilePlugin; - } - - private ProfileStore profile = null; - - private NSProfilePlugin() { - super(new PluginDescription() - .mainType(PluginType.PROFILE) - .fragmentClass(NSProfileFragment.class.getName()) - .pluginName(R.string.nsprofile) - .shortName(R.string.profileviewer_shortname) - .alwaysEnabled(Config.NSCLIENT) - .alwaysVisible(Config.NSCLIENT) - .showInList(!Config.NSCLIENT) - .description(R.string.description_profile_nightscout), - new RxBusWrapper(), new AAPSLoggerProduction() // TODO: dagger - ); - loadNSProfile(); - } - - @Override - protected void onStart() { - super.onStart(); - } - - @Override - protected void onStop() { - super.onStop(); - } - - public void handleNewData(Intent intent) { - try { - Bundle bundles = intent.getExtras(); - if (bundles == null) return; - - String activeProfile = bundles.getString("activeprofile"); - String profileString = bundles.getString("profile"); - profile = new ProfileStore(new JSONObject(profileString)); - storeNSProfile(); - if (isEnabled(PluginType.PROFILE)) { - RxBus.Companion.getINSTANCE().send(new EventProfileStoreChanged()); - RxBus.Companion.getINSTANCE().send(new EventNSProfileUpdateGUI()); - } - if (L.isEnabled(L.PROFILE)) - log.debug("Received profileStore: " + activeProfile + " " + profile); - } catch (JSONException e) { - log.error("Unhandled exception", e); - } - } - - private void storeNSProfile() { - SP.putString("profile", profile.getData().toString()); - if (L.isEnabled(L.PROFILE)) - log.debug("Storing profile"); - } - - private void loadNSProfile() { - if (L.isEnabled(L.PROFILE)) - log.debug("Loading stored profile"); - String profileString = SP.getString("profile", null); - if (profileString != null) { - if (L.isEnabled(L.PROFILE)) - log.debug("Loaded profile: " + profileString); - try { - profile = new ProfileStore(new JSONObject(profileString)); - } catch (JSONException e) { - log.error("Unhandled exception", e); - profile = null; - } - } else { - if (L.isEnabled(L.PROFILE)) - log.debug("Stored profile not found"); - // force restart of nsclient to fetch profile - RxBus.Companion.getINSTANCE().send(new EventNSClientRestart()); - } - } - - @Nullable - @Override - public ProfileStore getProfile() { - return profile; - } - - @Override - public String getProfileName() { - return profile.getDefaultProfileName(); - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.kt new file mode 100644 index 0000000000..848ea2d1d8 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.kt @@ -0,0 +1,88 @@ +package info.nightscout.androidaps.plugins.profile.ns + +import android.content.Intent +import info.nightscout.androidaps.Config +import info.nightscout.androidaps.R +import info.nightscout.androidaps.data.ProfileStore +import info.nightscout.androidaps.events.EventProfileStoreChanged +import info.nightscout.androidaps.interfaces.PluginBase +import info.nightscout.androidaps.interfaces.PluginDescription +import info.nightscout.androidaps.interfaces.PluginType +import info.nightscout.androidaps.interfaces.ProfileInterface +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart +import info.nightscout.androidaps.plugins.profile.ns.events.EventNSProfileUpdateGUI +import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.sharedPreferences.SP +import org.json.JSONObject +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class NSProfilePlugin @Inject constructor( + aapsLogger: AAPSLogger, + private val rxBus: RxBusWrapper, + resourceHelper: ResourceHelper, + private val sp: SP +) : PluginBase(PluginDescription() + .mainType(PluginType.PROFILE) + .fragmentClass(NSProfileFragment::class.java.name) + .pluginName(R.string.nsprofile) + .shortName(R.string.profileviewer_shortname) + .alwaysEnabled(Config.NSCLIENT) + .alwaysVisible(Config.NSCLIENT) + .showInList(!Config.NSCLIENT) + .description(R.string.description_profile_nightscout), + aapsLogger, resourceHelper +), ProfileInterface { + + private var profile: ProfileStore? = null + + override fun onStart() { + super.onStart() + loadNSProfile() + } + + fun handleNewData(intent: Intent) { + val bundles = intent.extras ?: return + @Suppress("SpellCheckingInspection") + val activeProfile = bundles.getString("activeprofile") + val profileString = bundles.getString("profile") + profile = ProfileStore(JSONObject(profileString)) + storeNSProfile() + if (isEnabled()) { + rxBus.send(EventProfileStoreChanged()) + rxBus.send(EventNSProfileUpdateGUI()) + } + aapsLogger.debug(LTag.PROFILE, "Received profileStore: $activeProfile $profile") + } + + private fun storeNSProfile() { + sp.putString("profile", profile!!.data.toString()) + aapsLogger.debug(LTag.PROFILE, "Storing profile") + } + + private fun loadNSProfile() { + aapsLogger.debug(LTag.PROFILE, "Loading stored profile") + val profileString = sp.getStringOrNull("profile", null) + if (profileString != null) { + aapsLogger.debug(LTag.PROFILE, "Loaded profile: $profileString") + profile = ProfileStore(JSONObject(profileString)) + } else { + aapsLogger.debug(LTag.PROFILE, "Stored profile not found") + // force restart of nsclient to fetch profile + rxBus.send(EventNSClientRestart()) + } + } + + override fun getProfile(): ProfileStore? { + return profile + } + + override fun getProfileName(): String { + return profile!!.getDefaultProfileName()!! + } + +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboFragment.java index 5f77c5ebf4..6e2fc0c848 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboFragment.java @@ -12,8 +12,10 @@ import android.widget.Button; import android.widget.TextView; import androidx.annotation.NonNull; -import androidx.fragment.app.Fragment; +import javax.inject.Inject; + +import dagger.android.support.DaggerFragment; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.plugins.bus.RxBus; @@ -22,6 +24,7 @@ import info.nightscout.androidaps.plugins.pump.combo.events.EventComboPumpUpdate import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.PumpState; import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.Bolus; import info.nightscout.androidaps.queue.Callback; +import info.nightscout.androidaps.queue.CommandQueue; import info.nightscout.androidaps.queue.events.EventQueueChanged; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.FabricPrivacy; @@ -29,7 +32,10 @@ import info.nightscout.androidaps.utils.SP; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; -public class ComboFragment extends Fragment implements View.OnClickListener { +public class ComboFragment extends DaggerFragment implements View.OnClickListener { + @Inject ComboPlugin comboPlugin; + @Inject CommandQueue commandQueue; + private CompositeDisposable disposable = new CompositeDisposable(); private TextView stateView; @@ -111,16 +117,15 @@ public class ComboFragment extends Fragment implements View.OnClickListener { } public void updateGui() { - ComboPlugin plugin = ComboPlugin.getPlugin(); // state - stateView.setText(plugin.getStateSummary()); - PumpState ps = plugin.getPump().state; + stateView.setText(comboPlugin.getStateSummary()); + PumpState ps = comboPlugin.getPump().state; if (ps.insulinState == PumpState.EMPTY || ps.batteryState == PumpState.EMPTY || ps.activeAlert != null && ps.activeAlert.errorCode != null) { stateView.setTextColor(Color.RED); stateView.setTypeface(null, Typeface.BOLD); - } else if (plugin.getPump().state.suspended + } else if (comboPlugin.getPump().state.suspended || ps.activeAlert != null && ps.activeAlert.warningCode != null) { stateView.setTextColor(Color.YELLOW); stateView.setTypeface(null, Typeface.BOLD); @@ -130,16 +135,16 @@ public class ComboFragment extends Fragment implements View.OnClickListener { } // activity - String activity = plugin.getPump().activity; + String activity = comboPlugin.getPump().activity; if (activity != null) { activityView.setTextColor(Color.WHITE); activityView.setTextSize(14); activityView.setText(activity); - } else if (ConfigBuilderPlugin.getPlugin().getCommandQueue().size() > 0) { + } else if (commandQueue.size() > 0) { activityView.setTextColor(Color.WHITE); activityView.setTextSize(14); activityView.setText(""); - } else if (plugin.isInitialized()) { + } else if (comboPlugin.isInitialized()) { activityView.setTextColor(Color.WHITE); activityView.setTextSize(20); activityView.setText("{fa-bed}"); @@ -149,7 +154,7 @@ public class ComboFragment extends Fragment implements View.OnClickListener { activityView.setText(MainApp.gs(R.string.pump_unreachable)); } - if (plugin.isInitialized()) { + if (comboPlugin.isInitialized()) { // battery batteryView.setTextSize(20); if (ps.batteryState == PumpState.EMPTY) { @@ -164,7 +169,7 @@ public class ComboFragment extends Fragment implements View.OnClickListener { } // reservoir - int reservoirLevel = plugin.getPump().reservoirLevel; + int reservoirLevel = comboPlugin.getPump().reservoirLevel; if (reservoirLevel != -1) { reservoirView.setText(reservoirLevel + " " + MainApp.gs(R.string.insulin_unit_shortname)); } else if (ps.insulinState == PumpState.LOW) { @@ -190,12 +195,12 @@ public class ComboFragment extends Fragment implements View.OnClickListener { } // last connection - String minAgo = DateUtil.minAgo(plugin.getPump().lastSuccessfulCmdTime); - long min = (System.currentTimeMillis() - plugin.getPump().lastSuccessfulCmdTime) / 1000 / 60; - if (plugin.getPump().lastSuccessfulCmdTime + 60 * 1000 > System.currentTimeMillis()) { + String minAgo = DateUtil.minAgo(comboPlugin.getPump().lastSuccessfulCmdTime); + long min = (System.currentTimeMillis() - comboPlugin.getPump().lastSuccessfulCmdTime) / 1000 / 60; + if (comboPlugin.getPump().lastSuccessfulCmdTime + 60 * 1000 > System.currentTimeMillis()) { lastConnectionView.setText(R.string.combo_pump_connected_now); lastConnectionView.setTextColor(Color.WHITE); - } else if (plugin.getPump().lastSuccessfulCmdTime + 30 * 60 * 1000 < System.currentTimeMillis()) { + } else if (comboPlugin.getPump().lastSuccessfulCmdTime + 30 * 60 * 1000 < System.currentTimeMillis()) { lastConnectionView.setText(MainApp.gs(R.string.combo_no_pump_connection, min)); lastConnectionView.setTextColor(Color.RED); } else { @@ -204,7 +209,7 @@ public class ComboFragment extends Fragment implements View.OnClickListener { } // last bolus - Bolus bolus = plugin.getPump().lastBolus; + Bolus bolus = comboPlugin.getPump().lastBolus; if (bolus != null) { long agoMsc = System.currentTimeMillis() - bolus.timestamp; double bolusMinAgo = agoMsc / 60d / 1000d; @@ -223,12 +228,12 @@ public class ComboFragment extends Fragment implements View.OnClickListener { } // base basal rate - baseBasalRate.setText(MainApp.gs(R.string.pump_basebasalrate, plugin.getBaseBasalRate())); + baseBasalRate.setText(MainApp.gs(R.string.pump_basebasalrate, comboPlugin.getBaseBasalRate())); // TBR String tbrStr = ""; if (ps.tbrPercent != -1 && ps.tbrPercent != 100) { - long minSinceRead = (System.currentTimeMillis() - plugin.getPump().state.timestamp) / 1000 / 60; + long minSinceRead = (System.currentTimeMillis() - comboPlugin.getPump().state.timestamp) / 1000 / 60; long remaining = ps.tbrRemainingDuration - minSinceRead; if (remaining >= 0) { tbrStr = MainApp.gs(R.string.combo_tbr_remaining, ps.tbrPercent, remaining); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java index 91cba80fbe..d7fdc2fc6a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java @@ -4,7 +4,6 @@ import android.os.SystemClock; import androidx.annotation.NonNull; import androidx.annotation.Nullable; -import androidx.fragment.app.FragmentActivity; import org.json.JSONObject; import org.slf4j.Logger; @@ -18,6 +17,9 @@ import java.util.HashMap; import java.util.HashSet; import java.util.List; +import javax.inject.Inject; +import javax.inject.Singleton; + import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -30,19 +32,21 @@ import info.nightscout.androidaps.db.TDD; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventRefreshOverview; +import info.nightscout.androidaps.interfaces.CommandQueueProvider; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.ConstraintsInterface; -import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpInterface; -import info.nightscout.androidaps.logging.AAPSLoggerProduction; +import info.nightscout.androidaps.interfaces.PumpPluginBase; +import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.common.ManufacturerType; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; 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; @@ -68,29 +72,29 @@ import info.nightscout.androidaps.plugins.treatments.Treatment; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.InstanceId; -import info.nightscout.androidaps.utils.SP; +import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.sharedPreferences.SP; /** * Created by mike on 05.08.2016. */ -public class ComboPlugin extends PluginBase implements PumpInterface, ConstraintsInterface { +@Singleton +public class ComboPlugin extends PumpPluginBase implements PumpInterface, ConstraintsInterface { private static final Logger log = LoggerFactory.getLogger(L.PUMP); static final String COMBO_TBRS_SET = "combo_tbrs_set"; static final String COMBO_BOLUSES_DELIVERED = "combo_boluses_delivered"; - private static ComboPlugin plugin = null; - - @Deprecated - public static ComboPlugin getPlugin() { - if (plugin == null) - plugin = new ComboPlugin(); - return plugin; - } + private final ResourceHelper resourceHelper; + private final ConstraintChecker constraintChecker; + private final ProfileFunction profileFunction; + private final TreatmentsPlugin treatmentsPlugin; + private final info.nightscout.androidaps.utils.sharedPreferences.SP sp; + private final RxBusWrapper rxBus; + private final CommandQueueProvider commandQueue; private final static PumpDescription pumpDescription = new PumpDescription(); - @NonNull - private final RuffyCommands ruffyScripter; + private RuffyCommands ruffyScripter; @NonNull private static final ComboPump pump = new ComboPump(); @@ -129,24 +133,46 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint */ private volatile List recentBoluses = new ArrayList<>(0); - private static final PumpEnactResult OPERATION_NOT_SUPPORTED = new PumpEnactResult() - .success(false).enacted(false).comment(MainApp.gs(R.string.combo_pump_unsupported_operation)); + private PumpEnactResult OPERATION_NOT_SUPPORTED; - // TODO: dagger - - private ComboPlugin() { + @Inject + public ComboPlugin( + AAPSLogger aapsLogger, + RxBusWrapper rxBus, + MainApp maiApp, + ResourceHelper resourceHelper, + ConstraintChecker constraintChecker, + ProfileFunction profileFunction, + TreatmentsPlugin treatmentsPlugin, + SP sp, + CommandQueueProvider commandQueue + ) { super(new PluginDescription() - .mainType(PluginType.PUMP) - .fragmentClass(ComboFragment.class.getName()) - .pluginName(R.string.combopump) - .shortName(R.string.combopump_shortname) - .description(R.string.description_pump_combo), - new RxBusWrapper(), new AAPSLoggerProduction() // TODO: dagger + .mainType(PluginType.PUMP) + .fragmentClass(ComboFragment.class.getName()) + .pluginName(R.string.combopump) + .shortName(R.string.combopump_shortname) + .description(R.string.description_pump_combo), + aapsLogger, resourceHelper, commandQueue ); - ruffyScripter = new RuffyScripter(MainApp.instance().getApplicationContext()); + this.rxBus = rxBus; + this.resourceHelper = resourceHelper; + this.constraintChecker = constraintChecker; + this.profileFunction = profileFunction; + this.treatmentsPlugin = treatmentsPlugin; + this.sp = sp; + this.commandQueue = commandQueue; + pumpDescription.setPumpDescription(PumpType.AccuChekCombo); } + @Override protected void onStart() { + super.onStart(); + ruffyScripter = new RuffyScripter(MainApp.instance()); + OPERATION_NOT_SUPPORTED = new PumpEnactResult() + .success(false).enacted(false).comment(MainApp.gs(R.string.combo_pump_unsupported_operation)); + } + public ComboPump getPump() { return pump; } @@ -169,11 +195,6 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint return MainApp.gs(R.string.combo_pump_state_running); } - @Override - public void switchAllowed(boolean newState, FragmentActivity activity, PluginType type) { - confirmPumpPluginActivation(newState, activity, type); - } - @Override public boolean isInitialized() { return pump.initialized; @@ -232,7 +253,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint // we're not doing that } - @Override + @NonNull @Override public synchronized PumpEnactResult setNewBasalProfile(Profile profile) { if (!isInitialized()) { // note that this should not happen anymore since the queue is present, which @@ -464,7 +485,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint /** * Updates Treatment records with carbs and boluses and delivers a bolus if needed */ - @Override + @NonNull @Override public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { try { if (detailedBolusInfo.insulin == 0 && detailedBolusInfo.carbs == 0) { @@ -642,7 +663,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint private void incrementTbrCount() { try { - SP.putLong(COMBO_TBRS_SET, SP.getLong(COMBO_TBRS_SET, 0L) + 1); + sp.putLong(COMBO_TBRS_SET, sp.getLong(COMBO_TBRS_SET, 0L) + 1); } catch (Exception e) { // ignore } @@ -650,7 +671,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint private void incrementBolusCount() { try { - SP.putLong(COMBO_BOLUSES_DELIVERED, SP.getLong(COMBO_BOLUSES_DELIVERED, 0L) + 1); + sp.putLong(COMBO_BOLUSES_DELIVERED, sp.getLong(COMBO_BOLUSES_DELIVERED, 0L) + 1); } catch (Exception e) { // ignore } @@ -695,7 +716,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint * might have other issues though (what happens if the tbr which wasn't re-set to * the new value (and thus still has the old duration of e.g. 1 min) expires?) */ - @Override + @NonNull @Override public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean force) { if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute called with a rate of " + absoluteRate + " for " + durationInMinutes + " min."); @@ -715,7 +736,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint * @param forceNew Driver always applies the requested TBR and simply overrides whatever TBR * is or isn't running at the moment */ - @Override + @NonNull @Override public PumpEnactResult setTempBasalPercent(Integer percent, final Integer durationInMinutes, Profile profile, boolean forceNew) { return setTempBasalPercent(percent, durationInMinutes); } @@ -774,7 +795,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint .percent(state.tbrPercent).duration(state.tbrRemainingDuration); } - @Override + @NonNull @Override public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) { return OPERATION_NOT_SUPPORTED; } @@ -787,7 +808,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint * make absolutely sure no TBR is running (such a request is also made when resuming the * loop, irregardless of whether a TBR is running or not). */ - @Override + @NonNull @Override public PumpEnactResult cancelTempBasal(boolean enforceNew) { if (L.isEnabled(L.PUMP)) log.debug("cancelTempBasal called"); @@ -891,7 +912,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint Notification.URGENT); n.soundId = R.raw.alarm; RxBus.Companion.getINSTANCE().send(new EventNewNotification(n)); - ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(true, null); + commandQueue.cancelTempBasal(true, null); } updateLocalData(commandResult); } @@ -1070,7 +1091,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint n.soundId = R.raw.alarm; RxBus.Companion.getINSTANCE().send(new EventNewNotification(n)); violationWarningRaisedForBolusAt = lowSuspendOnlyLoopEnforcedUntil; - ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(true, null); + commandQueue.cancelTempBasal(true, null); } } } @@ -1244,12 +1265,12 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint return null; } - @Override + @NonNull @Override public PumpEnactResult cancelExtendedBolus() { return OPERATION_NOT_SUPPORTED; } - @Override + @NonNull @Override public JSONObject getJSONStatus(Profile profile, String profileName) { if (!pump.initialized) { return null; @@ -1300,27 +1321,27 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint return null; } - @Override + @NonNull @Override public ManufacturerType manufacturer() { return ManufacturerType.Roche; } - @Override + @NonNull @Override public PumpType model() { return PumpType.AccuChekCombo; } - @Override + @NonNull @Override public String serialNumber() { return InstanceId.INSTANCE.instanceId(); // TODO replace by real serial } - @Override + @NonNull @Override public PumpDescription getPumpDescription() { return pumpDescription; } - @Override + @NonNull @Override public String shortStatus(boolean veryShort) { return getStateSummary(); } @@ -1330,7 +1351,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint return false; } - @Override + @NonNull @Override public PumpEnactResult loadTDDs() { PumpEnactResult result = new PumpEnactResult(); result.success = readHistory(new PumpHistoryRequest().tddHistory(PumpHistoryRequest.FULL)); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java index f1d8ad8294..5b25a8f6a9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java @@ -4,7 +4,7 @@ import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; -import androidx.fragment.app.FragmentActivity; +import androidx.annotation.NonNull; import org.json.JSONException; import org.json.JSONObject; @@ -22,16 +22,15 @@ import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.EventAppExit; +import info.nightscout.androidaps.interfaces.CommandQueueProvider; import info.nightscout.androidaps.interfaces.ConstraintsInterface; -import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; -import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpInterface; +import info.nightscout.androidaps.interfaces.PumpPluginBase; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.bus.RxBus; -import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress; import info.nightscout.androidaps.plugins.pump.common.data.PumpStatus; import info.nightscout.androidaps.plugins.pump.common.defs.PumpDriverState; @@ -42,6 +41,7 @@ import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.FabricPrivacy; +import info.nightscout.androidaps.utils.resources.ResourceHelper; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.schedulers.Schedulers; @@ -51,16 +51,16 @@ import io.reactivex.schedulers.Schedulers; // When using this class, make sure that your first step is to create mConnection (see MedtronicPumpPlugin) -public abstract class PumpPluginAbstract extends PluginBase implements PumpInterface, ConstraintsInterface { +public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpInterface, ConstraintsInterface { private CompositeDisposable disposable = new CompositeDisposable(); private static final Logger LOG = LoggerFactory.getLogger(L.PUMP); -/* - protected static final PumpEnactResult OPERATION_NOT_SUPPORTED = new PumpEnactResult().success(false) - .enacted(false).comment(MainApp.gs(R.string.pump_operation_not_supported_by_pump_driver)); - protected static final PumpEnactResult OPERATION_NOT_YET_SUPPORTED = new PumpEnactResult().success(false) - .enacted(false).comment(MainApp.gs(R.string.pump_operation_not_yet_supported_by_pump)); -*/ + /* + protected static final PumpEnactResult OPERATION_NOT_SUPPORTED = new PumpEnactResult().success(false) + .enacted(false).comment(MainApp.gs(R.string.pump_operation_not_supported_by_pump_driver)); + protected static final PumpEnactResult OPERATION_NOT_YET_SUPPORTED = new PumpEnactResult().success(false) + .enacted(false).comment(MainApp.gs(R.string.pump_operation_not_yet_supported_by_pump)); + */ protected PumpDescription pumpDescription = new PumpDescription(); protected PumpStatus pumpStatus; protected ServiceConnection serviceConnection = null; @@ -70,9 +70,9 @@ public abstract class PumpPluginAbstract extends PluginBase implements PumpInter protected boolean displayConnectionMessages = false; - protected PumpPluginAbstract(PluginDescription pluginDescription, PumpType pumpType, RxBusWrapper rxBusWrapper, AAPSLogger aapsLogger) { + protected PumpPluginAbstract(PluginDescription pluginDescription, PumpType pumpType, ResourceHelper resourceHelper, AAPSLogger aapsLogger, CommandQueueProvider commandQueue) { - super(pluginDescription, rxBusWrapper, aapsLogger); + super(pluginDescription, aapsLogger, resourceHelper, commandQueue); pumpDescription.setPumpDescription(pumpType); @@ -122,11 +122,6 @@ public abstract class PumpPluginAbstract extends PluginBase implements PumpInter */ public abstract void onStartCustomActions(); - @Override - public void switchAllowed(boolean newState, FragmentActivity activity, PluginType type) { - confirmPumpPluginActivation(newState, activity, type); - } - /** * Service class (same one you did serviceConnection for) * @@ -208,7 +203,7 @@ public abstract class PumpPluginAbstract extends PluginBase implements PumpInter // Upload to pump new basal profile - public PumpEnactResult setNewBasalProfile(Profile profile) { + @NonNull public PumpEnactResult setNewBasalProfile(Profile profile) { if (isLoggingEnabled()) LOG.warn("setNewBasalProfile [PumpPluginAbstract] - Not implemented."); return getOperationNotSupportedWithCustomText(R.string.pump_operation_not_supported_by_pump_driver); @@ -242,7 +237,7 @@ public abstract class PumpPluginAbstract extends PluginBase implements PumpInter } - @Override + @NonNull @Override public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean enforceNew) { if (isLoggingEnabled()) @@ -251,7 +246,7 @@ public abstract class PumpPluginAbstract extends PluginBase implements PumpInter } - @Override + @NonNull @Override public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) { if (isLoggingEnabled()) @@ -260,7 +255,7 @@ public abstract class PumpPluginAbstract extends PluginBase implements PumpInter } - public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) { + @NonNull public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) { if (isLoggingEnabled()) LOG.warn("setExtendedBolus [PumpPluginAbstract] - Not implemented."); return getOperationNotSupportedWithCustomText(R.string.pump_operation_not_supported_by_pump_driver); @@ -270,14 +265,14 @@ public abstract class PumpPluginAbstract extends PluginBase implements PumpInter // some pumps might set a very short temp close to 100% as cancelling a temp can be noisy // when the cancel request is requested by the user (forced), the pump should always do a real cancel - public PumpEnactResult cancelTempBasal(boolean enforceNew) { + @NonNull public PumpEnactResult cancelTempBasal(boolean enforceNew) { if (isLoggingEnabled()) LOG.warn("cancelTempBasal [PumpPluginAbstract] - Not implemented."); return getOperationNotSupportedWithCustomText(R.string.pump_operation_not_supported_by_pump_driver); } - public PumpEnactResult cancelExtendedBolus() { + @NonNull public PumpEnactResult cancelExtendedBolus() { if (isLoggingEnabled()) LOG.warn("cancelExtendedBolus [PumpPluginAbstract] - Not implemented."); return getOperationNotSupportedWithCustomText(R.string.pump_operation_not_supported_by_pump_driver); @@ -299,7 +294,7 @@ public abstract class PumpPluginAbstract extends PluginBase implements PumpInter // Pump capabilities - public PumpDescription getPumpDescription() { + @NonNull public PumpDescription getPumpDescription() { return pumpDescription; } @@ -313,7 +308,7 @@ public abstract class PumpPluginAbstract extends PluginBase implements PumpInter } - @Override + @NonNull @Override public PumpEnactResult loadTDDs() { if (isLoggingEnabled()) LOG.warn("loadTDDs [PumpPluginAbstract] - Not implemented."); @@ -321,7 +316,7 @@ public abstract class PumpPluginAbstract extends PluginBase implements PumpInter } - @Override + @NonNull @Override public JSONObject getJSONStatus(Profile profile, String profileName) { long now = System.currentTimeMillis(); @@ -372,7 +367,7 @@ public abstract class PumpPluginAbstract extends PluginBase implements PumpInter // FIXME i18n, null checks: iob, TDD - @Override + @NonNull @Override public String shortStatus(boolean veryShort) { String ret = ""; if (pumpStatus.lastConnection != 0) { @@ -405,7 +400,7 @@ public abstract class PumpPluginAbstract extends PluginBase implements PumpInter } - @Override + @NonNull @Override public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { try { 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 e053132977..394979a0f4 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 @@ -1,6 +1,6 @@ package info.nightscout.androidaps.plugins.pump.danaR; -import androidx.fragment.app.FragmentActivity; +import androidx.annotation.NonNull; import org.json.JSONException; import org.json.JSONObject; @@ -17,18 +17,18 @@ import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.TemporaryBasal; +import info.nightscout.androidaps.interfaces.CommandQueueProvider; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.ConstraintsInterface; import info.nightscout.androidaps.interfaces.DanaRInterface; -import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpInterface; +import info.nightscout.androidaps.interfaces.PumpPluginBase; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.bus.RxBus; -import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.common.ManufacturerType; import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction; @@ -36,7 +36,6 @@ import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType; import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; -import info.nightscout.androidaps.plugins.profile.ns.NSProfilePlugin; import info.nightscout.androidaps.plugins.pump.danaR.comm.RecordTypes; import info.nightscout.androidaps.plugins.pump.danaR.services.AbstractDanaRExecutionService; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; @@ -44,12 +43,13 @@ import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.Round; import info.nightscout.androidaps.utils.SP; +import info.nightscout.androidaps.utils.resources.ResourceHelper; /** * Created by mike on 28.01.2018. */ -public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInterface, DanaRInterface, ConstraintsInterface { +public abstract class AbstractDanaRPlugin extends PumpPluginBase implements PumpInterface, DanaRInterface, ConstraintsInterface { private Logger log = LoggerFactory.getLogger(L.PUMP); protected AbstractDanaRExecutionService sExecutionService; @@ -58,23 +58,18 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte public PumpDescription pumpDescription = new PumpDescription(); - protected AbstractDanaRPlugin(RxBusWrapper rxBus, AAPSLogger aapsLogger) { + protected AbstractDanaRPlugin(ResourceHelper resourceHelper, AAPSLogger aapsLogger, CommandQueueProvider commandQueue) { super(new PluginDescription() - .mainType(PluginType.PUMP) - .fragmentClass(DanaRFragment.class.getName()) - .pluginName(R.string.danarspump) - .shortName(R.string.danarpump_shortname) - .preferencesId(R.xml.pref_danars) - .description(R.string.description_pump_dana_r), - rxBus, aapsLogger + .mainType(PluginType.PUMP) + .fragmentClass(DanaRFragment.class.getName()) + .pluginName(R.string.danarspump) + .shortName(R.string.danarpump_shortname) + .preferencesId(R.xml.pref_danars) + .description(R.string.description_pump_dana_r), + aapsLogger, resourceHelper, commandQueue ); } - @Override - public void switchAllowed(boolean newState, FragmentActivity activity, PluginType type) { - confirmPumpPluginActivation(newState, activity, type); - } - @Override public boolean isSuspended() { return DanaRPump.getInstance().pumpSuspended; @@ -87,7 +82,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte } // Pump interface - @Override + @NonNull @Override public PumpEnactResult setNewBasalProfile(Profile profile) { PumpEnactResult result = new PumpEnactResult(); @@ -154,10 +149,14 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte } @Override - public double getReservoirLevel() { return DanaRPump.getInstance().reservoirRemainingUnits; } + public double getReservoirLevel() { + return DanaRPump.getInstance().reservoirRemainingUnits; + } @Override - public int getBatteryLevel() { return DanaRPump.getInstance().batteryRemaining; } + public int getBatteryLevel() { + return DanaRPump.getInstance().batteryRemaining; + } @Override public void stopBolusDelivering() { @@ -168,7 +167,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte sExecutionService.bolusStop(); } - @Override + @NonNull @Override public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) { DanaRPump pump = DanaRPump.getInstance(); PumpEnactResult result = new PumpEnactResult(); @@ -218,7 +217,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte return result; } - @Override + @NonNull @Override public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) { DanaRPump pump = DanaRPump.getInstance(); insulin = ConstraintChecker.getInstance().applyExtendedBolusConstraints(new Constraint<>(insulin)).value(); @@ -262,7 +261,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte return result; } - @Override + @NonNull @Override public PumpEnactResult cancelExtendedBolus() { PumpEnactResult result = new PumpEnactResult(); ExtendedBolus runningEB = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(System.currentTimeMillis()); @@ -323,7 +322,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte } } - @Override + @NonNull @Override public JSONObject getJSONStatus(Profile profile, String profilename) { DanaRPump pump = DanaRPump.getInstance(); long now = System.currentTimeMillis(); @@ -373,17 +372,17 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte return pumpjson; } - @Override + @NonNull @Override public ManufacturerType manufacturer() { return ManufacturerType.Sooil; } - @Override + @NonNull @Override public String serialNumber() { return DanaRPump.getInstance().serialNumber; } - @Override + @NonNull @Override public PumpDescription getPumpDescription() { return pumpDescription; } @@ -426,13 +425,13 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte return applyBolusConstraints(insulin); } - @Override + @NonNull @Override public PumpEnactResult loadTDDs() { return loadHistory(RecordTypes.RECORD_TYPE_DAILY); } // Reply for sms communicator - public String shortStatus(boolean veryShort) { + @NonNull public String shortStatus(boolean veryShort) { DanaRPump pump = DanaRPump.getInstance(); String ret = ""; if (pump.lastConnection != 0) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRFragment.kt index d7078511b2..584a0e6390 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRFragment.kt @@ -13,17 +13,17 @@ import info.nightscout.androidaps.dialogs.ProfileViewerDialog import info.nightscout.androidaps.events.EventExtendedBolusChange import info.nightscout.androidaps.events.EventPumpStatusChanged import info.nightscout.androidaps.events.EventTempBasalChange +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.interfaces.PumpInterface import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.pump.danaR.activities.DanaRHistoryActivity import info.nightscout.androidaps.plugins.pump.danaR.activities.DanaRUserOptionsActivity import info.nightscout.androidaps.plugins.pump.danaR.events.EventDanaRNewStatus import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.queue.events.EventQueueChanged import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy @@ -40,8 +40,8 @@ class DanaRFragment : DaggerFragment() { @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var fabricPrivacy: FabricPrivacy - @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin - @Inject lateinit var treatmentsPlugin: TreatmentsPlugin + @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var danaRKoreanPlugin: DanaRKoreanPlugin @Inject lateinit var resourceHelper: ResourceHelper @@ -90,7 +90,7 @@ class DanaRFragment : DaggerFragment() { danar_btconnection.setOnClickListener { aapsLogger.debug(LTag.PUMP, "Clicked connect to pump") DanaRPump.getInstance().lastConnection = 0 - configBuilderPlugin.commandQueue.readStatus("Clicked connect to pump", null) + commandQueue.readStatus("Clicked connect to pump", null) } } @@ -151,7 +151,7 @@ class DanaRFragment : DaggerFragment() { internal fun updateGUI() { if (danar_dailyunits == null) return val pump = DanaRPump.getInstance() - val plugin: PumpInterface = configBuilderPlugin.activePump ?: return + val plugin: PumpInterface = activePlugin.activePump if (pump.lastConnection != 0L) { val agoMsec = System.currentTimeMillis() - pump.lastConnection val agoMin = (agoMsec.toDouble() / 60.0 / 1000.0).toInt() @@ -172,15 +172,15 @@ class DanaRFragment : DaggerFragment() { SetWarnColor.setColor(danar_dailyunits, pump.dailyTotalUnits, pump.maxDailyTotalUnits * 0.75, pump.maxDailyTotalUnits * 0.9) danar_basabasalrate.text = "( " + (pump.activeProfile + 1) + " ) " + resourceHelper.gs(R.string.pump_basebasalrate, plugin.baseBasalRate) // DanaRPlugin, DanaRKoreanPlugin - if (configBuilderPlugin.activePump?.isFakingTempsByExtendedBoluses == true) { - danar_tempbasal.text = treatmentsPlugin.getRealTempBasalFromHistory(System.currentTimeMillis())?.toStringFull() + if (activePlugin.activePump.isFakingTempsByExtendedBoluses == true) { + danar_tempbasal.text = activePlugin.activeTreatments.getRealTempBasalFromHistory(System.currentTimeMillis())?.toStringFull() ?: "" } else { // v2 plugin - danar_tempbasal.text = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis())?.toStringFull() + danar_tempbasal.text = activePlugin.activeTreatments.getTempBasalFromHistory(System.currentTimeMillis())?.toStringFull() ?: "" } - danar_extendedbolus.text = treatmentsPlugin.getExtendedBolusFromHistory(System.currentTimeMillis())?.toString() + danar_extendedbolus.text = activePlugin.activeTreatments.getExtendedBolusFromHistory(System.currentTimeMillis())?.toString() ?: "" danar_reservoir.text = resourceHelper.gs(R.string.reservoirvalue, pump.reservoirRemainingUnits, 300) SetWarnColor.setColorInverse(danar_reservoir, pump.reservoirRemainingUnits, 50.0, 20.0) @@ -196,7 +196,7 @@ class DanaRFragment : DaggerFragment() { danar_basalstep.text = pump.basalStep.toString() danar_bolusstep.text = pump.bolusStep.toString() danar_serialnumber.text = pump.serialNumber - val status = configBuilderPlugin.commandQueue.spannedStatus() + val status = commandQueue.spannedStatus() if (status.toString() == "") { danar_queue.visibility = View.GONE } else { 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 9599013240..0acb651c51 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 @@ -20,6 +20,7 @@ import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventPreferenceChange; +import info.nightscout.androidaps.interfaces.CommandQueueProvider; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.logging.AAPSLogger; @@ -67,9 +68,10 @@ public class DanaRPlugin extends AbstractDanaRPlugin { ResourceHelper resourceHelper, ConstraintChecker constraintChecker, TreatmentsPlugin treatmentsPlugin, - SP sp + SP sp, + CommandQueueProvider commandQueue ) { - super(rxBus, aapsLogger); + super(resourceHelper, aapsLogger, commandQueue); plugin = this; this.aapsLogger = aapsLogger; this.rxBus = rxBus; @@ -165,7 +167,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { sExecutionService.finishHandshaking(); } - @Override + @NonNull @Override public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { detailedBolusInfo.insulin = constraintChecker.applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) { @@ -199,7 +201,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { } // This is called from APS - @Override + @NonNull @Override public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean enforceNew) { // Recheck pump status if older than 30 min //This should not be needed while using queue because connection should be done before calling this @@ -338,7 +340,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { return result; } - @Override + @NonNull @Override public PumpEnactResult cancelTempBasal(boolean force) { if (treatmentsPlugin.isInHistoryRealTempBasalInProgress()) return cancelRealTempBasal(); @@ -353,7 +355,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { return result; } - @Override + @NonNull @Override public PumpType model() { return PumpType.DanaR; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRHistoryActivity.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRHistoryActivity.kt index 6a84a5e4c2..03cd3ffacf 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRHistoryActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRHistoryActivity.kt @@ -16,11 +16,11 @@ import info.nightscout.androidaps.activities.NoSplashAppCompatActivity import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.db.DanaRHistoryRecord import info.nightscout.androidaps.events.EventPumpStatusChanged +import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.pump.danaR.comm.RecordTypes import info.nightscout.androidaps.plugins.pump.danaR.events.EventDanaRSyncStatus @@ -46,7 +46,7 @@ class DanaRHistoryActivity : NoSplashAppCompatActivity() { @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var danaRKoreanPlugin: DanaRKoreanPlugin @Inject lateinit var danaRSPlugin: DanaRSPlugin - @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin + @Inject lateinit var commandQueue: CommandQueueProvider private val disposable = CompositeDisposable() @@ -114,7 +114,7 @@ class DanaRHistoryActivity : NoSplashAppCompatActivity() { danar_history_status.visibility = View.VISIBLE } clearCardView() - configBuilderPlugin.commandQueue.loadHistory(selected.type, object : Callback() { + commandQueue.loadHistory(selected.type, object : Callback() { override fun run() { loadDataFromDB(selected.type) runOnUiThread { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRUserOptionsActivity.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRUserOptionsActivity.kt index b271370f39..4ceaacdfe1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRUserOptionsActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRUserOptionsActivity.kt @@ -8,12 +8,12 @@ import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.activities.NoSplashAppCompatActivity import info.nightscout.androidaps.events.EventInitializationChanged +import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.L import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin @@ -39,7 +39,7 @@ class DanaRUserOptionsActivity : NoSplashAppCompatActivity() { @Inject lateinit var danaRSPlugin: DanaRSPlugin @Inject lateinit var danaRPlugin: DanaRPlugin @Inject lateinit var danaRv2Plugin: DanaRv2Plugin - @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin + @Inject lateinit var commandQueue: CommandQueueProvider private val disposable = CompositeDisposable() @@ -155,7 +155,7 @@ class DanaRUserOptionsActivity : NoSplashAppCompatActivity() { // 10 to 50 pump.lowReservoirRate = min(max(danar_lowreservoir.value.toInt() * 10 / 10, 10), 50) - configBuilderPlugin.commandQueue.setUserOptions(object : Callback() { + commandQueue.setUserOptions(object : Callback() { override fun run() { if (!result.success) { val i = Intent(mainApp, ErrorHelperActivity::class.java) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java index c43bac04e0..77dacbe5f7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java @@ -13,6 +13,7 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; +import info.nightscout.androidaps.dialogs.BolusProgressDialog; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventPreferenceChange; @@ -24,7 +25,6 @@ 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.general.nsclient.NSUpload; -import info.nightscout.androidaps.dialogs.BolusProgressDialog; import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress; import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; @@ -77,7 +77,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { mBinder = new LocalBinder(); MainApp.instance().getApplicationContext().registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED)); - } + } @Override public void onCreate() { @@ -185,7 +185,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { if (profile != null && Math.abs(danaRPump.currentBasal - profile.getBasal()) >= pump.getPumpDescription().basalStep) { RxBus.Companion.getINSTANCE().send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings))); mSerialIOThread.sendMessage(new MsgSettingBasal()); - if (!pump.isThisProfileSet(profile) && !ConfigBuilderPlugin.getPlugin().getCommandQueue().isRunning(Command.CommandType.BASALPROFILE)) { + if (!pump.isThisProfileSet(profile) && !ConfigBuilderPlugin.getPlugin().getCommandQueue().isRunning(Command.CommandType.BASAL_PROFILE)) { RxBus.Companion.getINSTANCE().send(new EventProfileNeedsUpdate()); } } 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 7427c55590..91ab8b8361 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 @@ -20,6 +20,7 @@ import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventPreferenceChange; +import info.nightscout.androidaps.interfaces.CommandQueueProvider; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.logging.AAPSLogger; @@ -69,9 +70,11 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { ResourceHelper resourceHelper, ConstraintChecker constraintChecker, TreatmentsPlugin treatmentsPlugin, - SP sp + SP sp, + CommandQueueProvider commandQueue + ) { - super(rxBus, aapsLogger); + super(resourceHelper, aapsLogger, commandQueue); plugin = this; this.aapsLogger = aapsLogger; this.rxBus = rxBus; @@ -167,7 +170,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { sExecutionService.finishHandshaking(); } - @Override + @NonNull @Override public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { detailedBolusInfo.insulin = constraintChecker.applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) { @@ -201,7 +204,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { } // This is called from APS - @Override + @NonNull @Override public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean enforceNew) { // Recheck pump status if older than 30 min //This should not be needed while using queue because connection should be done before calling this @@ -340,7 +343,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { return result; } - @Override + @NonNull @Override public PumpEnactResult cancelTempBasal(boolean force) { if (treatmentsPlugin.isInHistoryRealTempBasalInProgress()) return cancelRealTempBasal(); @@ -355,7 +358,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { return result; } - @Override + @NonNull @Override public PumpType model() { return PumpType.DanaRKorean; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java index 1b59e18a0b..923183d115 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java @@ -13,6 +13,7 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; +import info.nightscout.androidaps.dialogs.BolusProgressDialog; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventPreferenceChange; @@ -24,7 +25,6 @@ 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.general.nsclient.NSUpload; -import info.nightscout.androidaps.dialogs.BolusProgressDialog; import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump; @@ -177,7 +177,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { if (profile != null && Math.abs(danaRPump.currentBasal - profile.getBasal()) >= pump.getPumpDescription().basalStep) { RxBus.Companion.getINSTANCE().send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings))); mSerialIOThread.sendMessage(new MsgSettingBasal()); - if (!pump.isThisProfileSet(profile) && !ConfigBuilderPlugin.getPlugin().getCommandQueue().isRunning(Command.CommandType.BASALPROFILE)) { + if (!pump.isThisProfileSet(profile) && !ConfigBuilderPlugin.getPlugin().getCommandQueue().isRunning(Command.CommandType.BASAL_PROFILE)) { RxBus.Companion.getINSTANCE().send(new EventProfileNeedsUpdate()); } } 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 6b189a4e65..87fc1f712a 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 @@ -5,10 +5,9 @@ import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; -import androidx.preference.Preference; import androidx.annotation.NonNull; -import androidx.fragment.app.FragmentActivity; +import androidx.preference.Preference; import org.jetbrains.annotations.NotNull; import org.json.JSONException; @@ -28,14 +27,15 @@ import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.EventAppExit; +import info.nightscout.androidaps.interfaces.CommandQueueProvider; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.ConstraintsInterface; import info.nightscout.androidaps.interfaces.DanaRInterface; -import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpInterface; +import info.nightscout.androidaps.interfaces.PumpPluginBase; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; @@ -68,24 +68,17 @@ import io.reactivex.disposables.CompositeDisposable; import io.reactivex.schedulers.Schedulers; @Singleton -public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInterface, ConstraintsInterface { +public class DanaRSPlugin extends PumpPluginBase implements PumpInterface, DanaRInterface, ConstraintsInterface { private CompositeDisposable disposable = new CompositeDisposable(); - + private final MainApp mainApp; private final ResourceHelper resourceHelper; private final ConstraintChecker constraintChecker; private final ProfileFunction profileFunction; private final TreatmentsPlugin treatmentsPlugin; private final SP sp; - - private static DanaRSPlugin plugin = null; - - @Deprecated - public static DanaRSPlugin getPlugin() { - if (plugin == null) - throw new IllegalStateException("Accessing DanaRSPlugin before first instantiation"); - return plugin; - } + private final RxBusWrapper rxBus; + private final CommandQueueProvider commandQueue; private static DanaRSService danaRSService; @@ -103,24 +96,26 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte ConstraintChecker constraintChecker, ProfileFunction profileFunction, TreatmentsPlugin treatmentsPlugin, - info.nightscout.androidaps.utils.sharedPreferences.SP sp + SP sp, + CommandQueueProvider commandQueue ) { super(new PluginDescription() - .mainType(PluginType.PUMP) - .fragmentClass(DanaRFragment.class.getName()) - .pluginName(R.string.danarspump) - .shortName(R.string.danarspump_shortname) - .preferencesId(R.xml.pref_danars) - .description(R.string.description_pump_dana_rs), - rxBus, aapsLogger + .mainType(PluginType.PUMP) + .fragmentClass(DanaRFragment.class.getName()) + .pluginName(R.string.danarspump) + .shortName(R.string.danarspump_shortname) + .preferencesId(R.xml.pref_danars) + .description(R.string.description_pump_dana_rs), + aapsLogger, resourceHelper, commandQueue ); - plugin = this; this.mainApp = maiApp; + this.rxBus = rxBus; this.resourceHelper = resourceHelper; this.constraintChecker = constraintChecker; this.profileFunction = profileFunction; this.treatmentsPlugin = treatmentsPlugin; this.sp = sp; + this.commandQueue = commandQueue; pumpDescription.setPumpDescription(PumpType.DanaRS); } @@ -138,12 +133,12 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte Intent intent = new Intent(mainApp, DanaRSService.class); mainApp.bindService(intent, mConnection, Context.BIND_AUTO_CREATE); - disposable.add(getRxBus() + disposable.add(rxBus .toObservable(EventAppExit.class) .observeOn(Schedulers.io()) .subscribe(event -> mainApp.unbindService(mConnection), exception -> FabricPrivacy.getInstance().logException(exception)) ); - disposable.add(getRxBus() + disposable.add(rxBus .toObservable(EventDanaRSDeviceChange.class) .observeOn(Schedulers.io()) .subscribe(event -> loadAddress(), exception -> FabricPrivacy.getInstance().logException(exception)) @@ -160,11 +155,6 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte super.onStop(); } - @Override - public void switchAllowed(boolean newState, FragmentActivity activity, @NonNull PluginType type) { - confirmPumpPluginActivation(newState, activity, type); - } - private ServiceConnection mConnection = new ServiceConnection() { public void onServiceDisconnected(ComponentName name) { @@ -300,7 +290,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte return danaRSService.isConnected() || danaRSService.isConnecting(); } - @Override + @NonNull @Override public PumpEnactResult setNewBasalProfile(Profile profile) { PumpEnactResult result = new PumpEnactResult(); @@ -312,22 +302,22 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte if (!isInitialized()) { getAapsLogger().error("setNewBasalProfile not initialized"); Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, resourceHelper.gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT); - getRxBus().send(new EventNewNotification(notification)); + rxBus.send(new EventNewNotification(notification)); result.comment = resourceHelper.gs(R.string.pumpNotInitializedProfileNotSet); return result; } else { - getRxBus().send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)); + rxBus.send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)); } if (!danaRSService.updateBasalsInPump(profile)) { Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, resourceHelper.gs(R.string.failedupdatebasalprofile), Notification.URGENT); - getRxBus().send(new EventNewNotification(notification)); + rxBus.send(new EventNewNotification(notification)); result.comment = resourceHelper.gs(R.string.failedupdatebasalprofile); return result; } else { - getRxBus().send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)); - getRxBus().send(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE)); + rxBus.send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)); + rxBus.send(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE)); Notification notification = new Notification(Notification.PROFILE_SET_OK, resourceHelper.gs(R.string.profile_set_ok), Notification.INFO, 60); - getRxBus().send(new EventNewNotification(notification)); + rxBus.send(new EventNewNotification(notification)); result.success = true; result.enacted = true; result.comment = "OK"; @@ -375,7 +365,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte return DanaRPump.getInstance().batteryRemaining; } - @Override + @NonNull @Override public synchronized PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { detailedBolusInfo.insulin = constraintChecker.applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) { @@ -457,7 +447,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte } // This is called from APS - @Override + @NonNull @Override public synchronized PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean enforceNew) { // Recheck pump status if older than 30 min @@ -535,7 +525,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte return result; } - @Override + @NonNull @Override public synchronized PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) { DanaRPump pump = DanaRPump.getInstance(); PumpEnactResult result = new PumpEnactResult(); @@ -610,7 +600,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte return result; } - @Override + @NonNull @Override public synchronized PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) { DanaRPump pump = DanaRPump.getInstance(); insulin = constraintChecker.applyExtendedBolusConstraints(new Constraint<>(insulin)).value(); @@ -650,7 +640,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte return result; } - @Override + @NonNull @Override public synchronized PumpEnactResult cancelTempBasal(boolean force) { PumpEnactResult result = new PumpEnactResult(); TemporaryBasal runningTB = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis()); @@ -674,7 +664,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte } } - @Override + @NonNull @Override public synchronized PumpEnactResult cancelExtendedBolus() { PumpEnactResult result = new PumpEnactResult(); ExtendedBolus runningEB = treatmentsPlugin.getExtendedBolusFromHistory(System.currentTimeMillis()); @@ -696,12 +686,12 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte } } - @Override + @NonNull @Override public JSONObject getJSONStatus(Profile profile, String profileName) { DanaRPump pump = DanaRPump.getInstance(); long now = System.currentTimeMillis(); if (pump.lastConnection + 5 * 60 * 1000L < System.currentTimeMillis()) { - return null; + return new JSONObject(); } JSONObject pumpjson = new JSONObject(); JSONObject battery = new JSONObject(); @@ -747,27 +737,27 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte return pumpjson; } - @Override + @NonNull @Override public ManufacturerType manufacturer() { return ManufacturerType.Sooil; } - @Override + @NonNull @Override public PumpType model() { return PumpType.DanaRS; } - @Override + @NonNull @Override public String serialNumber() { return DanaRPump.getInstance().serialNumber; } - @Override + @NonNull @Override public PumpDescription getPumpDescription() { return pumpDescription; } - @Override + @NonNull @Override public String shortStatus(boolean veryShort) { DanaRPump pump = DanaRPump.getInstance(); String ret = ""; @@ -800,7 +790,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte return false; } - @Override + @NonNull @Override public PumpEnactResult loadTDDs() { return loadHistory(RecordTypes.RECORD_TYPE_DAILY); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java index a20b403247..bcee1e33e7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java @@ -21,6 +21,7 @@ import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventProfileNeedsUpdate; import info.nightscout.androidaps.events.EventPumpStatusChanged; +import info.nightscout.androidaps.interfaces.CommandQueueProvider; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; @@ -92,6 +93,7 @@ public class DanaRSService extends DaggerService { @Inject SP sp; @Inject ResourceHelper resourceHelper; @Inject ProfileFunction profileFunction; + @Inject CommandQueueProvider commandQueue; @Inject MainApp mainApp; @Inject ConfigBuilderPlugin configBuilderPlugin; @Inject DanaRSPlugin danaRSPlugin; @@ -171,7 +173,7 @@ public class DanaRSService extends DaggerService { if (profile != null && Math.abs(danaRPump.currentBasal - profile.getBasal()) >= pump.getPumpDescription().basalStep) { rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpsettings))); bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Basal_Rate()); // basal profile, basalStep, maxBasal - if (!pump.isThisProfileSet(profile) && !configBuilderPlugin.getCommandQueue().isRunning(Command.CommandType.BASALPROFILE)) { + if (!pump.isThisProfileSet(profile) && !commandQueue.isRunning(Command.CommandType.BASAL_PROFILE)) { rxBus.send(new EventProfileNeedsUpdate()); } } @@ -357,7 +359,7 @@ public class DanaRSService extends DaggerService { SystemClock.sleep(1000); } // do not call loadEvents() directly, reconnection may be needed - configBuilderPlugin.getCommandQueue().loadEvents(new Callback() { + commandQueue.loadEvents(new Callback() { @Override public void run() { // reread bolus status 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 aa03757b80..4ecae5579a 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 @@ -18,6 +18,7 @@ import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.EventAppExit; +import info.nightscout.androidaps.interfaces.CommandQueueProvider; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; @@ -58,7 +59,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { public static DanaRv2Plugin getPlugin() { if (plugin == null) throw new IllegalStateException("Accessing DanaRv2Plugin before first instantiation"); - return plugin; + return plugin; } @Inject @@ -69,9 +70,11 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { ResourceHelper resourceHelper, ConstraintChecker constraintChecker, TreatmentsPlugin treatmentsPlugin, - SP sp + SP sp, + CommandQueueProvider commandQueue + ) { - super(rxBus, aapsLogger); + super(resourceHelper, aapsLogger, commandQueue); plugin = this; this.aapsLogger = aapsLogger; this.rxBus = rxBus; @@ -154,7 +157,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { } // Pump interface - @Override + @NonNull @Override public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { detailedBolusInfo.insulin = constraintChecker.applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) { @@ -221,7 +224,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { } // This is called from APS - @Override + @NonNull @Override public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean enforceNew) { // Recheck pump status if older than 30 min //This should not be needed while using queue because connection should be done before calling this @@ -297,7 +300,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { return result; } - @Override + @NonNull @Override public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) { DanaRPump pump = DanaRPump.getInstance(); PumpEnactResult result = new PumpEnactResult(); @@ -372,7 +375,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { return result; } - @Override + @NonNull @Override public PumpEnactResult cancelTempBasal(boolean force) { PumpEnactResult result = new PumpEnactResult(); TemporaryBasal runningTB = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis()); @@ -396,7 +399,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { } } - @Override + @NonNull @Override public PumpType model() { return PumpType.DanaRv2; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java index 6700804e10..c8647bee48 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java @@ -12,8 +12,10 @@ import java.util.Date; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.activities.ErrorHelperActivity; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; +import info.nightscout.androidaps.dialogs.BolusProgressDialog; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventPreferenceChange; @@ -25,8 +27,6 @@ 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.general.nsclient.NSUpload; -import info.nightscout.androidaps.dialogs.BolusProgressDialog; -import info.nightscout.androidaps.activities.ErrorHelperActivity; import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress; import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; @@ -194,7 +194,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { if (profile != null && Math.abs(danaRPump.currentBasal - profile.getBasal()) >= pump.getPumpDescription().basalStep) { RxBus.Companion.getINSTANCE().send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings))); mSerialIOThread.sendMessage(new MsgSettingBasal()); - if (!pump.isThisProfileSet(profile) && !ConfigBuilderPlugin.getPlugin().getCommandQueue().isRunning(Command.CommandType.BASALPROFILE)) { + if (!pump.isThisProfileSet(profile) && !ConfigBuilderPlugin.getPlugin().getCommandQueue().isRunning(Command.CommandType.BASAL_PROFILE)) { RxBus.Companion.getINSTANCE().send(new EventProfileNeedsUpdate()); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java index 9fe491419b..18212581fb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java @@ -12,11 +12,13 @@ import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; -import androidx.fragment.app.Fragment; import java.util.ArrayList; import java.util.List; +import javax.inject.Inject; + +import dagger.android.support.DaggerFragment; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.plugins.bus.RxBus; @@ -36,7 +38,9 @@ import info.nightscout.androidaps.utils.FabricPrivacy; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; -public class LocalInsightFragment extends Fragment implements View.OnClickListener { +public class LocalInsightFragment extends DaggerFragment implements View.OnClickListener { + @Inject LocalInsightPlugin localInsightPlugin; + private CompositeDisposable disposable = new CompositeDisposable(); private static final boolean ENABLE_OPERATING_MODE_BUTTON = false; @@ -92,7 +96,7 @@ public class LocalInsightFragment extends Fragment implements View.OnClickListen @Override public void onClick(View v) { if (v == operatingMode) { - if (LocalInsightPlugin.getPlugin().getOperatingMode() != null) { + if (localInsightPlugin.getOperatingMode() != null) { operatingMode.setEnabled(false); operatingModeCallback = new Callback() { @Override @@ -103,7 +107,7 @@ public class LocalInsightFragment extends Fragment implements View.OnClickListen }); } }; - switch (LocalInsightPlugin.getPlugin().getOperatingMode()) { + switch (localInsightPlugin.getOperatingMode()) { case PAUSED: case STOPPED: ConfigBuilderPlugin.getPlugin().getCommandQueue().startPump(operatingModeCallback); @@ -113,7 +117,7 @@ public class LocalInsightFragment extends Fragment implements View.OnClickListen } } } else if (v == tbrOverNotification) { - TBROverNotificationBlock notificationBlock = LocalInsightPlugin.getPlugin().getTBROverNotificationBlock(); + TBROverNotificationBlock notificationBlock = localInsightPlugin.getTBROverNotificationBlock(); if (notificationBlock != null) { tbrOverNotification.setEnabled(false); tbrOverNotificationCallback = new Callback() { @@ -146,7 +150,7 @@ public class LocalInsightFragment extends Fragment implements View.OnClickListen protected void updateGUI() { if (!viewsCreated) return; statusItemContainer.removeAllViews(); - if (!LocalInsightPlugin.getPlugin().isInitialized()) { + if (!localInsightPlugin.isInitialized()) { operatingMode.setVisibility(View.GONE); tbrOverNotification.setVisibility(View.GONE); refresh.setVisibility(View.GONE); @@ -154,7 +158,7 @@ public class LocalInsightFragment extends Fragment implements View.OnClickListen } refresh.setVisibility(View.VISIBLE); refresh.setEnabled(refreshCallback == null); - TBROverNotificationBlock notificationBlock = LocalInsightPlugin.getPlugin().getTBROverNotificationBlock(); + TBROverNotificationBlock notificationBlock = localInsightPlugin.getTBROverNotificationBlock(); tbrOverNotification.setVisibility(notificationBlock == null ? View.GONE : View.VISIBLE); if (notificationBlock != null) tbrOverNotification.setText(notificationBlock.isEnabled() ? R.string.disable_tbr_over_notification : R.string.enable_tbr_over_notification); @@ -185,7 +189,7 @@ public class LocalInsightFragment extends Fragment implements View.OnClickListen private void getConnectionStatusItem(List statusItems) { int string = 0; - InsightState state = LocalInsightPlugin.getPlugin().getConnectionService().getState(); + InsightState state = localInsightPlugin.getConnectionService().getState(); switch (state) { case NOT_PAIRED: string = R.string.not_paired; @@ -217,17 +221,17 @@ public class LocalInsightFragment extends Fragment implements View.OnClickListen } statusItems.add(getStatusItem(MainApp.gs(R.string.insight_status), MainApp.gs(string))); if (state == InsightState.RECOVERING) { - statusItems.add(getStatusItem(MainApp.gs(R.string.recovery_duration), LocalInsightPlugin.getPlugin().getConnectionService().getRecoveryDuration() / 1000 + "s")); + statusItems.add(getStatusItem(MainApp.gs(R.string.recovery_duration), localInsightPlugin.getConnectionService().getRecoveryDuration() / 1000 + "s")); } } private void getLastConnectedItem(List statusItems) { - switch (LocalInsightPlugin.getPlugin().getConnectionService().getState()) { + switch (localInsightPlugin.getConnectionService().getState()) { case CONNECTED: case NOT_PAIRED: return; default: - long lastConnection = LocalInsightPlugin.getPlugin().getConnectionService().getLastConnected(); + long lastConnection = localInsightPlugin.getConnectionService().getLastConnected(); if (lastConnection == 0) return; int min = (int) ((System.currentTimeMillis() - lastConnection) / 60000); statusItems.add(getStatusItem(MainApp.gs(R.string.last_connected), DateUtil.timeString(lastConnection))); @@ -235,14 +239,14 @@ public class LocalInsightFragment extends Fragment implements View.OnClickListen } private void getOperatingModeItem(List statusItems) { - if (LocalInsightPlugin.getPlugin().getOperatingMode() == null) { + if (localInsightPlugin.getOperatingMode() == null) { operatingMode.setVisibility(View.GONE); return; } int string = 0; if (ENABLE_OPERATING_MODE_BUTTON) operatingMode.setVisibility(View.VISIBLE); operatingMode.setEnabled(operatingModeCallback == null); - switch (LocalInsightPlugin.getPlugin().getOperatingMode()) { + switch (localInsightPlugin.getOperatingMode()) { case STARTED: operatingMode.setText(R.string.stop_pump); string = R.string.started; @@ -260,46 +264,46 @@ public class LocalInsightFragment extends Fragment implements View.OnClickListen } private void getBatteryStatusItem(List statusItems) { - if (LocalInsightPlugin.getPlugin().getBatteryStatus() == null) return; + if (localInsightPlugin.getBatteryStatus() == null) return; statusItems.add(getStatusItem(MainApp.gs(R.string.pump_battery_label), - LocalInsightPlugin.getPlugin().getBatteryStatus().getBatteryAmount() + "%")); + localInsightPlugin.getBatteryStatus().getBatteryAmount() + "%")); } private void getCartridgeStatusItem(List statusItems) { - CartridgeStatus cartridgeStatus = LocalInsightPlugin.getPlugin().getCartridgeStatus(); + CartridgeStatus cartridgeStatus = localInsightPlugin.getCartridgeStatus(); if (cartridgeStatus == null) return; String status; if (cartridgeStatus.isInserted()) - status = DecimalFormatter.to2Decimal(LocalInsightPlugin.getPlugin().getCartridgeStatus().getRemainingAmount()) + "U"; + status = DecimalFormatter.to2Decimal(localInsightPlugin.getCartridgeStatus().getRemainingAmount()) + "U"; else status = MainApp.gs(R.string.not_inserted); statusItems.add(getStatusItem(MainApp.gs(R.string.pump_reservoir_label), status)); } private void getTDDItems(List statusItems) { - if (LocalInsightPlugin.getPlugin().getTotalDailyDose() == null) return; - TotalDailyDose tdd = LocalInsightPlugin.getPlugin().getTotalDailyDose(); + if (localInsightPlugin.getTotalDailyDose() == null) return; + TotalDailyDose tdd = localInsightPlugin.getTotalDailyDose(); statusItems.add(getStatusItem(MainApp.gs(R.string.tdd_bolus), DecimalFormatter.to2Decimal(tdd.getBolus()))); statusItems.add(getStatusItem(MainApp.gs(R.string.tdd_basal), DecimalFormatter.to2Decimal(tdd.getBasal()))); statusItems.add(getStatusItem(MainApp.gs(R.string.tdd_total), DecimalFormatter.to2Decimal(tdd.getBolusAndBasal()))); } private void getBaseBasalRateItem(List statusItems) { - if (LocalInsightPlugin.getPlugin().getActiveBasalRate() == null) return; - ActiveBasalRate activeBasalRate = LocalInsightPlugin.getPlugin().getActiveBasalRate(); + if (localInsightPlugin.getActiveBasalRate() == null) return; + ActiveBasalRate activeBasalRate = localInsightPlugin.getActiveBasalRate(); statusItems.add(getStatusItem(MainApp.gs(R.string.pump_basebasalrate_label), DecimalFormatter.to2Decimal(activeBasalRate.getActiveBasalRate()) + " U/h (" + activeBasalRate.getActiveBasalProfileName() + ")")); } private void getTBRItem(List statusItems) { - if (LocalInsightPlugin.getPlugin().getActiveTBR() == null) return; - ActiveTBR activeTBR = LocalInsightPlugin.getPlugin().getActiveTBR(); + if (localInsightPlugin.getActiveTBR() == null) return; + ActiveTBR activeTBR = localInsightPlugin.getActiveTBR(); statusItems.add(getStatusItem(MainApp.gs(R.string.pump_tempbasal_label), MainApp.gs(R.string.tbr_formatter, activeTBR.getPercentage(), activeTBR.getInitialDuration() - activeTBR.getRemainingDuration(), activeTBR.getInitialDuration()))); } private void getBolusItems(List statusItems) { - if (LocalInsightPlugin.getPlugin().getActiveBoluses() == null) return; - for (ActiveBolus activeBolus : LocalInsightPlugin.getPlugin().getActiveBoluses()) { + if (localInsightPlugin.getActiveBoluses() == null) return; + for (ActiveBolus activeBolus : localInsightPlugin.getActiveBoluses()) { String label; switch (activeBolus.getBolusType()) { case MULTIWAVE: diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java index df3ec733df..81c03f9e34 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java @@ -8,7 +8,7 @@ import android.os.Handler; import android.os.IBinder; import android.os.Looper; -import androidx.fragment.app.FragmentActivity; +import androidx.annotation.NonNull; import org.json.JSONException; import org.json.JSONObject; @@ -22,7 +22,11 @@ import java.util.Date; import java.util.List; import java.util.TimeZone; +import javax.inject.Inject; +import javax.inject.Singleton; + import info.nightscout.androidaps.BuildConfig; +import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.DetailedBolusInfo; @@ -35,19 +39,19 @@ import info.nightscout.androidaps.db.TDD; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventRefreshOverview; +import info.nightscout.androidaps.interfaces.CommandQueueProvider; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.ConstraintsInterface; -import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpInterface; -import info.nightscout.androidaps.logging.AAPSLoggerProduction; +import info.nightscout.androidaps.interfaces.PumpPluginBase; +import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.common.ManufacturerType; -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.actions.defs.CustomAction; import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType; @@ -130,11 +134,19 @@ import info.nightscout.androidaps.plugins.pump.insight.utils.ParameterBlockUtil; import info.nightscout.androidaps.plugins.treatments.Treatment; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DateUtil; -import info.nightscout.androidaps.utils.SP; +import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.sharedPreferences.SP; -public class LocalInsightPlugin extends PluginBase implements PumpInterface, ConstraintsInterface, InsightConnectionService.StateCallback { +@Singleton +public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, ConstraintsInterface, InsightConnectionService.StateCallback { - private static LocalInsightPlugin instance = null; + private final AAPSLogger aapsLogger; + private final RxBusWrapper rxBus; + private final ResourceHelper resourceHelper; + private final ConstraintChecker constraintChecker; + private final TreatmentsPlugin treatmentsPlugin; + private final SP sp; + private final CommandQueueProvider commandQueue; private Logger log = LoggerFactory.getLogger(L.PUMP); @@ -152,7 +164,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con alertService = ((InsightAlertService.LocalBinder) binder).getService(); } if (connectionService != null && alertService != null) { - RxBus.Companion.getINSTANCE().send(new EventInitializationChanged()); + rxBus.send(new EventInitializationChanged()); } } @@ -183,25 +195,35 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con private boolean statusLoaded; private TBROverNotificationBlock tbrOverNotificationBlock; - @Deprecated - public static LocalInsightPlugin getPlugin() { - if (instance == null) instance = new LocalInsightPlugin(); - return instance; - } - - public LocalInsightPlugin() { + @Inject + public LocalInsightPlugin( + AAPSLogger aapsLogger, + RxBusWrapper rxBus, + ResourceHelper resourceHelper, + ConstraintChecker constraintChecker, + TreatmentsPlugin treatmentsPlugin, + info.nightscout.androidaps.utils.sharedPreferences.SP sp, + CommandQueueProvider commandQueue + ) { super(new PluginDescription() - .pluginName(R.string.insight_local) - .shortName(R.string.insightpump_shortname) - .mainType(PluginType.PUMP) - .description(R.string.description_pump_insight_local) - .fragmentClass(LocalInsightFragment.class.getName()) - .preferencesId(MainApp.instance().getPackageName().equals("info.nightscout.androidaps") - ? R.xml.pref_insight_local_full : R.xml.pref_insight_local_pumpcontrol), - new RxBusWrapper(), new AAPSLoggerProduction() // TODO: dagger + .pluginName(R.string.insight_local) + .shortName(R.string.insightpump_shortname) + .mainType(PluginType.PUMP) + .description(R.string.description_pump_insight_local) + .fragmentClass(LocalInsightFragment.class.getName()) + .preferencesId(Config.APS ? R.xml.pref_insight_local_full : R.xml.pref_insight_local_pumpcontrol), + aapsLogger, resourceHelper, commandQueue ); + this.aapsLogger = aapsLogger; + this.rxBus = rxBus; + this.resourceHelper = resourceHelper; + this.constraintChecker = constraintChecker; + this.treatmentsPlugin = treatmentsPlugin; + this.sp = sp; + this.commandQueue = commandQueue; + pumpDescription = new PumpDescription(); pumpDescription.setPumpDescription(PumpType.AccuChekInsightBluetooth); } @@ -259,11 +281,6 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con MainApp.instance().unbindService(serviceConnection); } - @Override - public void switchAllowed(boolean newState, FragmentActivity activity, PluginType type) { - confirmPumpPluginActivation(newState, activity, type); - } - @Override public boolean isInitialized() { return connectionService != null && alertService != null && connectionService.isPaired(); @@ -363,8 +380,8 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con SetDateTimeMessage setDateTimeMessage = new SetDateTimeMessage(); setDateTimeMessage.setPumpTime(pumpTime); connectionService.requestMessage(setDateTimeMessage).await(); - Notification notification = new Notification(Notification.INSIGHT_DATE_TIME_UPDATED, MainApp.gs(R.string.pump_time_updated), Notification.INFO, 60); - RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); + Notification notification = new Notification(Notification.INSIGHT_DATE_TIME_UPDATED, resourceHelper.gs(R.string.pump_time_updated), Notification.INFO, 60); + rxBus.send(new EventNewNotification(notification)); } } @@ -432,8 +449,8 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con } lastUpdated = System.currentTimeMillis(); new Handler(Looper.getMainLooper()).post(() -> { - RxBus.Companion.getINSTANCE().send(new EventLocalInsightUpdateGUI()); - RxBus.Companion.getINSTANCE().send(new EventRefreshOverview("LocalInsightPlugin::fetchStatus")); + rxBus.send(new EventLocalInsightUpdateGUI()); + rxBus.send(new EventRefreshOverview("LocalInsightPlugin::fetchStatus")); }); } @@ -447,10 +464,10 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con limitsFetched = true; } - @Override + @NonNull @Override public PumpEnactResult setNewBasalProfile(Profile profile) { PumpEnactResult result = new PumpEnactResult(); - RxBus.Companion.getINSTANCE().send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)); + rxBus.send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)); List profileBlocks = new ArrayList<>(); for (int i = 0; i < profile.getBasalValues().length; i++) { Profile.ProfileValue basalValue = profile.getBasalValues()[i]; @@ -470,12 +487,12 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con BRProfileBlock profileBlock = new BRProfile1Block(); profileBlock.setProfileBlocks(profileBlocks); ParameterBlockUtil.writeConfigurationBlock(connectionService, profileBlock); - RxBus.Companion.getINSTANCE().send(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE)); - Notification notification = new Notification(Notification.PROFILE_SET_OK, MainApp.gs(R.string.profile_set_ok), Notification.INFO, 60); - RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); + rxBus.send(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE)); + Notification notification = new Notification(Notification.PROFILE_SET_OK, resourceHelper.gs(R.string.profile_set_ok), Notification.INFO, 60); + rxBus.send(new EventNewNotification(notification)); result.success = true; result.enacted = true; - result.comment = MainApp.gs(R.string.virtualpump_resultok); + result.comment = resourceHelper.gs(R.string.virtualpump_resultok); this.profileBlocks = profileBlocks; try { fetchStatus(); @@ -483,18 +500,18 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con } } catch (AppLayerErrorException e) { log.info("Exception while setting profile: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); - Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, MainApp.gs(R.string.failedupdatebasalprofile), Notification.URGENT); - RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); + Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, resourceHelper.gs(R.string.failedupdatebasalprofile), Notification.URGENT); + rxBus.send(new EventNewNotification(notification)); result.comment = ExceptionTranslator.getString(e); } catch (InsightException e) { log.info("Exception while setting profile: " + e.getClass().getCanonicalName()); - Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, MainApp.gs(R.string.failedupdatebasalprofile), Notification.URGENT); - RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); + Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, resourceHelper.gs(R.string.failedupdatebasalprofile), Notification.URGENT); + rxBus.send(new EventNewNotification(notification)); result.comment = ExceptionTranslator.getString(e); } catch (Exception e) { log.error("Exception while setting profile", e); - Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, MainApp.gs(R.string.failedupdatebasalprofile), Notification.URGENT); - RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); + Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, resourceHelper.gs(R.string.failedupdatebasalprofile), Notification.URGENT); + rxBus.send(new EventNewNotification(notification)); result.comment = ExceptionTranslator.getString(e); } return result; @@ -544,7 +561,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con return batteryStatus.getBatteryAmount(); } - @Override + @NonNull @Override public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { PumpEnactResult result = new PumpEnactResult(); double insulin = Math.round(detailedBolusInfo.insulin / 0.01) * 0.01; @@ -565,9 +582,9 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con t.isSMB = detailedBolusInfo.isSMB; final EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE; bolusingEvent.setT(t); - bolusingEvent.setStatus(MainApp.gs(R.string.insight_delivered, 0d, insulin)); + bolusingEvent.setStatus(resourceHelper.gs(R.string.insight_delivered, 0d, insulin)); bolusingEvent.setPercent(0); - RxBus.Companion.getINSTANCE().send(bolusingEvent); + rxBus.send(bolusingEvent); int trials = 0; InsightBolusID insightBolusID = new InsightBolusID(); insightBolusID.bolusID = bolusID; @@ -596,16 +613,16 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con trials = -1; int percentBefore = bolusingEvent.getPercent(); bolusingEvent.setPercent((int) (100D / activeBolus.getInitialAmount() * (activeBolus.getInitialAmount() - activeBolus.getRemainingAmount()))); - bolusingEvent.setStatus(MainApp.gs(R.string.insight_delivered, activeBolus.getInitialAmount() - activeBolus.getRemainingAmount(), activeBolus.getInitialAmount())); + bolusingEvent.setStatus(resourceHelper.gs(R.string.insight_delivered, activeBolus.getInitialAmount() - activeBolus.getRemainingAmount(), activeBolus.getInitialAmount())); if (percentBefore != bolusingEvent.getPercent()) - RxBus.Companion.getINSTANCE().send(bolusingEvent); + rxBus.send(bolusingEvent); } else { synchronized ($bolusLock) { if (bolusCancelled || trials == -1 || trials++ >= 5) { if (!bolusCancelled) { - bolusingEvent.setStatus(MainApp.gs(R.string.insight_delivered, insulin, insulin)); + bolusingEvent.setStatus(resourceHelper.gs(R.string.insight_delivered, insulin, insulin)); bolusingEvent.setPercent(100); - RxBus.Companion.getINSTANCE().send(bolusingEvent); + rxBus.send(bolusingEvent); } break; } @@ -656,7 +673,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con }).start(); } - @Override + @NonNull @Override public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean enforceNew) { PumpEnactResult result = new PumpEnactResult(); if (activeBasalRate == null) return result; @@ -676,7 +693,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con result.isPercent = false; result.absolute = absoluteRate; result.duration = durationInMinutes; - result.comment = MainApp.gs(R.string.virtualpump_resultok); + result.comment = resourceHelper.gs(R.string.virtualpump_resultok); } else { result.comment = ebResult.comment; } @@ -705,7 +722,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con return result; } - @Override + @NonNull @Override public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) { PumpEnactResult result = new PumpEnactResult(); percent = (int) Math.round(((double) percent) / 10d) * 10; @@ -728,7 +745,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con result.duration = durationInMinutes; result.success = true; result.enacted = true; - result.comment = MainApp.gs(R.string.virtualpump_resultok); + result.comment = resourceHelper.gs(R.string.virtualpump_resultok); readHistory(); fetchStatus(); } catch (AppLayerErrorException e) { @@ -744,7 +761,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con return result; } - @Override + @NonNull @Override public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) { PumpEnactResult result = cancelExtendedBolusOnly(); if (result.success) result = setExtendedBolusOnly(insulin, durationInMinutes); @@ -784,7 +801,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus); result.success = true; result.enacted = true; - result.comment = MainApp.gs(R.string.virtualpump_resultok); + result.comment = resourceHelper.gs(R.string.virtualpump_resultok); } catch (AppLayerErrorException e) { log.info("Exception while delivering extended bolus: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); result.comment = ExceptionTranslator.getString(e); @@ -798,7 +815,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con return result; } - @Override + @NonNull @Override public PumpEnactResult cancelTempBasal(boolean enforceNew) { PumpEnactResult result = new PumpEnactResult(); PumpEnactResult cancelEBResult = null; @@ -830,10 +847,10 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con result.isTempCancel = true; confirmAlert(AlertType.WARNING_36); alertService.ignore(null); - result.comment = MainApp.gs(R.string.virtualpump_resultok); + result.comment = resourceHelper.gs(R.string.virtualpump_resultok); } catch (NoActiveTBRToCanceLException e) { result.success = true; - result.comment = MainApp.gs(R.string.virtualpump_resultok); + result.comment = resourceHelper.gs(R.string.virtualpump_resultok); } catch (AppLayerErrorException e) { log.info("Exception while canceling TBR: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); result.comment = ExceptionTranslator.getString(e); @@ -847,7 +864,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con return result; } - @Override + @NonNull @Override public PumpEnactResult cancelExtendedBolus() { PumpEnactResult result = cancelExtendedBolusOnly(); try { @@ -895,7 +912,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con } } result.success = true; - result.comment = MainApp.gs(R.string.virtualpump_resultok); + result.comment = resourceHelper.gs(R.string.virtualpump_resultok); } catch (AppLayerErrorException e) { log.info("Exception while canceling extended bolus: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); result.comment = ExceptionTranslator.getString(e); @@ -931,7 +948,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con } } - @Override + @NonNull @Override public JSONObject getJSONStatus(Profile profile, String profileName) { long now = System.currentTimeMillis(); if (System.currentTimeMillis() - connectionService.getLastConnected() > (60 * 60 * 1000)) { @@ -979,17 +996,17 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con return pump; } - @Override + @NonNull @Override public ManufacturerType manufacturer() { return ManufacturerType.Roche; } - @Override + @NonNull @Override public PumpType model() { return PumpType.AccuChekInsightBluetooth; } - @Override + @NonNull @Override public String serialNumber() { if (connectionService == null || alertService == null) return "Unknown"; return connectionService.getPumpSystemIdentification().getSerialNumber(); @@ -1065,46 +1082,46 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con return result; } - @Override + @NonNull @Override public PumpDescription getPumpDescription() { return pumpDescription; } - @Override + @NonNull @Override public String shortStatus(boolean veryShort) { StringBuilder ret = new StringBuilder(); if (connectionService.getLastConnected() != 0) { Long agoMsec = System.currentTimeMillis() - connectionService.getLastConnected(); int agoMin = (int) (agoMsec / 60d / 1000d); - ret.append(MainApp.gs(R.string.short_status_last_connected, agoMin) + "\n"); + ret.append(resourceHelper.gs(R.string.short_status_last_connected, agoMin) + "\n"); } if (activeTBR != null) { - ret.append(MainApp.gs(R.string.short_status_tbr, activeTBR.getPercentage(), + ret.append(resourceHelper.gs(R.string.short_status_tbr, activeTBR.getPercentage(), activeTBR.getInitialDuration() - activeTBR.getRemainingDuration(), activeTBR.getInitialDuration()) + "\n"); } if (activeBoluses != null) for (ActiveBolus activeBolus : activeBoluses) { if (activeBolus.getBolusType() == BolusType.STANDARD) continue; - ret.append(MainApp.gs(activeBolus.getBolusType() == BolusType.MULTIWAVE ? R.string.short_status_multiwave : R.string.short_status_extended, + ret.append(resourceHelper.gs(activeBolus.getBolusType() == BolusType.MULTIWAVE ? R.string.short_status_multiwave : R.string.short_status_extended, activeBolus.getRemainingAmount(), activeBolus.getInitialAmount(), activeBolus.getRemainingDuration()) + "\n"); } if (!veryShort && totalDailyDose != null) { - ret.append(MainApp.gs(R.string.short_status_tdd, totalDailyDose.getBolusAndBasal()) + "\n"); + ret.append(resourceHelper.gs(R.string.short_status_tdd, totalDailyDose.getBolusAndBasal()) + "\n"); } if (cartridgeStatus != null) { - ret.append(MainApp.gs(R.string.short_status_reservoir, cartridgeStatus.getRemainingAmount()) + "\n"); + ret.append(resourceHelper.gs(R.string.short_status_reservoir, cartridgeStatus.getRemainingAmount()) + "\n"); } if (batteryStatus != null) { - ret.append(MainApp.gs(R.string.short_status_battery, batteryStatus.getBatteryAmount()) + "\n"); + ret.append(resourceHelper.gs(R.string.short_status_battery, batteryStatus.getBatteryAmount()) + "\n"); } return ret.toString(); } @Override public boolean isFakingTempsByExtendedBoluses() { - return SP.getBoolean("insight_enable_tbr_emulation", false); + return sp.getBoolean("insight_enable_tbr_emulation", false); } - @Override + @NonNull @Override public PumpEnactResult loadTDDs() { return new PumpEnactResult().success(true); } @@ -1173,7 +1190,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con } catch (Exception e) { log.error("Exception while reading history", e); } - new Handler(Looper.getMainLooper()).post(() -> RxBus.Companion.getINSTANCE().send(new EventRefreshOverview("LocalInsightPlugin::readHistory"))); + new Handler(Looper.getMainLooper()).post(() -> rxBus.send(new EventRefreshOverview("LocalInsightPlugin::readHistory"))); } private void processHistoryEvents(String serial, List historyEvents) { @@ -1235,7 +1252,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con } private void processCannulaFilledEvent(CannulaFilledEvent event) { - if (!SP.getBoolean("insight_log_site_changes", false)) return; + if (!sp.getBoolean("insight_log_site_changes", false)) return; long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; uploadCareportalEvent(timestamp, CareportalEvent.SITECHANGE); @@ -1256,21 +1273,21 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con } private void processTubeFilledEvent(TubeFilledEvent event) { - if (!SP.getBoolean("insight_log_tube_changes", false)) return; + if (!sp.getBoolean("insight_log_tube_changes", false)) return; long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; - logNote(timestamp, MainApp.gs(R.string.tube_changed)); + logNote(timestamp, resourceHelper.gs(R.string.tube_changed)); } private void processSniffingDoneEvent(SniffingDoneEvent event) { - if (!SP.getBoolean("insight_log_reservoir_changes", false)) return; + if (!sp.getBoolean("insight_log_reservoir_changes", false)) return; long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; uploadCareportalEvent(timestamp, CareportalEvent.INSULINCHANGE); } private void processPowerUpEvent(PowerUpEvent event) { - if (!SP.getBoolean("insight_log_battery_changes", false)) return; + if (!sp.getBoolean("insight_log_battery_changes", false)) return; long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; uploadCareportalEvent(timestamp, CareportalEvent.PUMPBATTERYCHANGE); @@ -1287,18 +1304,18 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con case STARTED: pumpID.eventType = "PumpStarted"; pumpStartedEvents.add(pumpID); - if (SP.getBoolean("insight_log_operating_mode_changes", false)) - logNote(timestamp, MainApp.gs(R.string.pump_started)); + if (sp.getBoolean("insight_log_operating_mode_changes", false)) + logNote(timestamp, resourceHelper.gs(R.string.pump_started)); break; case STOPPED: pumpID.eventType = "PumpStopped"; - if (SP.getBoolean("insight_log_operating_mode_changes", false)) - logNote(timestamp, MainApp.gs(R.string.pump_stopped)); + if (sp.getBoolean("insight_log_operating_mode_changes", false)) + logNote(timestamp, resourceHelper.gs(R.string.pump_stopped)); break; case PAUSED: pumpID.eventType = "PumpPaused"; - if (SP.getBoolean("insight_log_operating_mode_changes", false)) - logNote(timestamp, MainApp.gs(R.string.pump_paused)); + if (sp.getBoolean("insight_log_operating_mode_changes", false)) + logNote(timestamp, resourceHelper.gs(R.string.pump_paused)); break; } MainApp.getDbHelper().createOrUpdate(pumpID); @@ -1422,7 +1439,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con } private void processOccurrenceOfAlertEvent(OccurrenceOfAlertEvent event) { - if (!SP.getBoolean("insight_log_alerts", false)) return; + if (!sp.getBoolean("insight_log_alerts", false)) return; long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; Integer code = null; @@ -1506,7 +1523,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con break; } if (code != null) - logNote(timestamp, MainApp.gs(R.string.insight_alert_formatter, MainApp.gs(code), MainApp.gs(title))); + logNote(timestamp, resourceHelper.gs(R.string.insight_alert_formatter, resourceHelper.gs(code), resourceHelper.gs(title))); } private long parseDate(int year, int month, int day, int hour, int minute, int second) { @@ -1525,7 +1542,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con if (MainApp.getDbHelper().getCareportalEventFromTimestamp(date) != null) return; JSONObject data = new JSONObject(); - String enteredBy = SP.getString("careportal_enteredby", ""); + String enteredBy = sp.getString("careportal_enteredby", ""); if (!enteredBy.equals("")) data.put("enteredBy", enteredBy); data.put("created_at", DateUtil.toISOString(date)); data.put("eventType", CareportalEvent.NOTE); @@ -1554,7 +1571,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con return; try { JSONObject data = new JSONObject(); - String enteredBy = SP.getString("careportal_enteredby", ""); + String enteredBy = sp.getString("careportal_enteredby", ""); if (!enteredBy.equals("")) data.put("enteredBy", enteredBy); data.put("created_at", DateUtil.toISOString(date)); data.put("eventType", event); @@ -1566,22 +1583,22 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con @Override public Constraint applyBasalPercentConstraints(Constraint percentRate, Profile profile) { - percentRate.setIfGreater(0, String.format(MainApp.gs(R.string.limitingpercentrate), 0, MainApp.gs(R.string.itmustbepositivevalue)), this); - percentRate.setIfSmaller(getPumpDescription().maxTempPercent, String.format(MainApp.gs(R.string.limitingpercentrate), getPumpDescription().maxTempPercent, MainApp.gs(R.string.pumplimit)), this); + percentRate.setIfGreater(0, String.format(resourceHelper.gs(R.string.limitingpercentrate), 0, resourceHelper.gs(R.string.itmustbepositivevalue)), this); + percentRate.setIfSmaller(getPumpDescription().maxTempPercent, String.format(resourceHelper.gs(R.string.limitingpercentrate), getPumpDescription().maxTempPercent, resourceHelper.gs(R.string.pumplimit)), this); return percentRate; } @Override public Constraint applyBolusConstraints(Constraint insulin) { if (!limitsFetched) return insulin; - insulin.setIfSmaller(maximumBolusAmount, String.format(MainApp.gs(R.string.limitingbolus), maximumBolusAmount, MainApp.gs(R.string.pumplimit)), this); + insulin.setIfSmaller(maximumBolusAmount, String.format(resourceHelper.gs(R.string.limitingbolus), maximumBolusAmount, resourceHelper.gs(R.string.pumplimit)), this); if (insulin.value() < minimumBolusAmount) { //TODO: Add function to Constraints or use different approach // This only works if the interface of the InsightPlugin is called last. // If not, another constraint could theoretically set the value between 0 and minimumBolusAmount - insulin.set(0d, String.format(MainApp.gs(R.string.limitingbolus), minimumBolusAmount, MainApp.gs(R.string.pumplimit)), this); + insulin.set(0d, String.format(resourceHelper.gs(R.string.limitingbolus), minimumBolusAmount, resourceHelper.gs(R.string.pumplimit)), this); } return insulin; } @@ -1595,7 +1612,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con public void onStateChanged(InsightState state) { if (state == InsightState.CONNECTED) { statusLoaded = false; - new Handler(Looper.getMainLooper()).post(() -> RxBus.Companion.getINSTANCE().send(new EventDismissNotification(Notification.INSIGHT_TIMEOUT_DURING_HANDSHAKE))); + new Handler(Looper.getMainLooper()).post(() -> rxBus.send(new EventDismissNotification(Notification.INSIGHT_TIMEOUT_DURING_HANDSHAKE))); } else if (state == InsightState.NOT_PAIRED) { connectionService.withdrawConnectionRequest(this); statusLoaded = false; @@ -1608,20 +1625,20 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con activeTBR = null; activeBoluses = null; tbrOverNotificationBlock = null; - new Handler(Looper.getMainLooper()).post(() -> RxBus.Companion.getINSTANCE().send(new EventRefreshOverview("LocalInsightPlugin::onStateChanged"))); + new Handler(Looper.getMainLooper()).post(() -> rxBus.send(new EventRefreshOverview("LocalInsightPlugin::onStateChanged"))); } - new Handler(Looper.getMainLooper()).post(() -> RxBus.Companion.getINSTANCE().send(new EventLocalInsightUpdateGUI())); + new Handler(Looper.getMainLooper()).post(() -> rxBus.send(new EventLocalInsightUpdateGUI())); } @Override public void onPumpPaired() { - ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("Pump paired", null); + commandQueue.readStatus("Pump paired", null); } @Override public void onTimeoutDuringHandshake() { - Notification notification = new Notification(Notification.INSIGHT_TIMEOUT_DURING_HANDSHAKE, MainApp.gs(R.string.timeout_during_handshake), Notification.URGENT); - new Handler(Looper.getMainLooper()).post(() -> RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification))); + Notification notification = new Notification(Notification.INSIGHT_TIMEOUT_DURING_HANDSHAKE, resourceHelper.gs(R.string.timeout_during_handshake), Notification.URGENT); + new Handler(Looper.getMainLooper()).post(() -> rxBus.send(new EventNewNotification(notification))); } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.java index 8113734335..6e0319f35d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.java @@ -1,5 +1,7 @@ package info.nightscout.androidaps.plugins.pump.mdi; +import androidx.annotation.NonNull; + import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; @@ -7,19 +9,22 @@ import org.slf4j.LoggerFactory; import java.util.List; +import javax.inject.Inject; +import javax.inject.Singleton; + import info.nightscout.androidaps.BuildConfig; 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.PumpEnactResult; -import info.nightscout.androidaps.interfaces.PluginBase; +import info.nightscout.androidaps.interfaces.CommandQueueProvider; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpInterface; +import info.nightscout.androidaps.interfaces.PumpPluginBase; import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.logging.AAPSLoggerProduction; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.common.ManufacturerType; @@ -29,33 +34,30 @@ import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.InstanceId; +import info.nightscout.androidaps.utils.resources.ResourceHelper; /** * Created by mike on 05.08.2016. */ -public class MDIPlugin extends PluginBase implements PumpInterface { +@Singleton +public class MDIPlugin extends PumpPluginBase implements PumpInterface { private static Logger log = LoggerFactory.getLogger(MDIPlugin.class); - private static MDIPlugin plugin = null; - - @Deprecated - public static MDIPlugin getPlugin() { - if (plugin == null) - plugin = new MDIPlugin(); - return plugin; - } - private PumpDescription pumpDescription = new PumpDescription(); - //TODO dagger - - private MDIPlugin() { + @Inject + public MDIPlugin( + AAPSLogger aapsLogger, + RxBusWrapper rxBus, + ResourceHelper resourceHelper, + CommandQueueProvider commandQueue + ) { super(new PluginDescription() .mainType(PluginType.PUMP) .pluginName(R.string.mdi) .description(R.string.description_pump_mdi), - new RxBusWrapper(), new AAPSLoggerProduction() // TODO: dagger + aapsLogger, resourceHelper, commandQueue ); pumpDescription.isBolusCapable = true; pumpDescription.bolusStep = 0.5d; @@ -71,7 +73,7 @@ public class MDIPlugin extends PluginBase implements PumpInterface { return false; } - @Override + @NonNull @Override public PumpEnactResult loadTDDs() { //no result, could read DB in the future? PumpEnactResult result = new PumpEnactResult(); @@ -128,7 +130,7 @@ public class MDIPlugin extends PluginBase implements PumpInterface { public void getPumpStatus() { } - @Override + @NonNull @Override public PumpEnactResult setNewBasalProfile(Profile profile) { // Do nothing here. we are using ConfigBuilderPlugin.getPlugin().getActiveProfile().getProfile(); PumpEnactResult result = new PumpEnactResult(); @@ -152,12 +154,16 @@ public class MDIPlugin extends PluginBase implements PumpInterface { } @Override - public double getReservoirLevel() { return -1; } + public double getReservoirLevel() { + return -1; + } @Override - public int getBatteryLevel() { return -1; } + public int getBatteryLevel() { + return -1; + } - @Override + @NonNull @Override public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { PumpEnactResult result = new PumpEnactResult(); result.success = true; @@ -172,7 +178,7 @@ public class MDIPlugin extends PluginBase implements PumpInterface { public void stopBolusDelivering() { } - @Override + @NonNull @Override public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean enforceNew) { PumpEnactResult result = new PumpEnactResult(); result.success = false; @@ -182,7 +188,7 @@ public class MDIPlugin extends PluginBase implements PumpInterface { return result; } - @Override + @NonNull @Override public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) { PumpEnactResult result = new PumpEnactResult(); result.success = false; @@ -192,7 +198,7 @@ public class MDIPlugin extends PluginBase implements PumpInterface { return result; } - @Override + @NonNull @Override public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) { PumpEnactResult result = new PumpEnactResult(); result.success = false; @@ -202,7 +208,7 @@ public class MDIPlugin extends PluginBase implements PumpInterface { return result; } - @Override + @NonNull @Override public PumpEnactResult cancelTempBasal(boolean force) { PumpEnactResult result = new PumpEnactResult(); result.success = false; @@ -212,7 +218,7 @@ public class MDIPlugin extends PluginBase implements PumpInterface { return result; } - @Override + @NonNull @Override public PumpEnactResult cancelExtendedBolus() { PumpEnactResult result = new PumpEnactResult(); result.success = false; @@ -222,7 +228,7 @@ public class MDIPlugin extends PluginBase implements PumpInterface { return result; } - @Override + @NonNull @Override public JSONObject getJSONStatus(Profile profile, String profileName) { long now = System.currentTimeMillis(); JSONObject pump = new JSONObject(); @@ -245,27 +251,27 @@ public class MDIPlugin extends PluginBase implements PumpInterface { return pump; } - @Override + @NonNull @Override public ManufacturerType manufacturer() { return ManufacturerType.AndroidAPS; } - @Override + @NonNull @Override public PumpType model() { return PumpType.MDI; } - @Override + @NonNull @Override public String serialNumber() { return InstanceId.INSTANCE.instanceId(); } - @Override + @NonNull @Override public PumpDescription getPumpDescription() { return pumpDescription; } - @Override + @NonNull @Override public String shortStatus(boolean veryShort) { return model().getModel(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt index c5ab4a3e4a..8768596f50 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt @@ -13,10 +13,11 @@ import info.nightscout.androidaps.R import info.nightscout.androidaps.events.EventExtendedBolusChange import info.nightscout.androidaps.events.EventPumpStatusChanged import info.nightscout.androidaps.events.EventTempBasalChange +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState @@ -32,7 +33,6 @@ import info.nightscout.androidaps.plugins.pump.medtronic.events.EventMedtronicPu import info.nightscout.androidaps.plugins.pump.medtronic.events.EventMedtronicPumpValuesChanged import info.nightscout.androidaps.plugins.pump.medtronic.events.EventRefreshButtonState import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.queue.events.EventQueueChanged import info.nightscout.androidaps.utils.DateUtil @@ -52,8 +52,9 @@ class MedtronicFragment : DaggerFragment() { @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rxBus: RxBusWrapper - @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin - @Inject lateinit var treatmnetsPlugin: TreatmentsPlugin + @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var activePlugin: ActivePluginProvider + @Inject lateinit var medtronicPumpPlugin: MedtronicPumpPlugin private var disposable: CompositeDisposable = CompositeDisposable() @@ -94,8 +95,8 @@ class MedtronicFragment : DaggerFragment() { MedtronicUtil.displayNotConfiguredDialog(context) } else { medtronic_refresh.isEnabled = false - MedtronicPumpPlugin.getPlugin().resetStatusState() - configBuilderPlugin.commandQueue.readStatus("Clicked refresh", object : Callback() { + medtronicPumpPlugin.resetStatusState() + commandQueue.readStatus("Clicked refresh", object : Callback() { override fun run() { activity?.runOnUiThread { medtronic_refresh?.isEnabled = true } } @@ -226,7 +227,7 @@ class MedtronicFragment : DaggerFragment() { else -> aapsLogger.warn(LTag.PUMP, "Unknown pump state: " + pumpStatus.pumpDeviceState) } - val status = configBuilderPlugin.commandQueue.spannedStatus() + val status = commandQueue.spannedStatus() if (status.toString() == "") { medtronic_queue.visibility = View.GONE } else { @@ -250,7 +251,6 @@ class MedtronicFragment : DaggerFragment() { @Synchronized fun updateGUI() { if (medtronic_rl_status == null) return - val plugin = MedtronicPumpPlugin.getPlugin() val pumpStatus = MedtronicUtil.getPumpStatus() setDeviceStatus() @@ -306,9 +306,9 @@ class MedtronicFragment : DaggerFragment() { // base basal rate medtronic_basabasalrate.text = ("(" + pumpStatus.activeProfileName + ") " - + resourceHelper.gs(R.string.pump_basebasalrate, plugin.baseBasalRate)) + + resourceHelper.gs(R.string.pump_basebasalrate, medtronicPumpPlugin.baseBasalRate)) - medtronic_tempbasal.text = treatmnetsPlugin.getTempBasalFromHistory(System.currentTimeMillis())?.toStringFull() + medtronic_tempbasal.text = activePlugin.activeTreatments.getTempBasalFromHistory(System.currentTimeMillis())?.toStringFull() ?: "" // battery diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java index ccd28fecc4..e3ad0abfb8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java @@ -24,6 +24,9 @@ import java.util.Locale; import java.util.Map; import java.util.Set; +import javax.inject.Inject; +import javax.inject.Singleton; + import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.activities.ErrorHelperActivity; @@ -34,15 +37,17 @@ import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.EventCustomActionsChanged; import info.nightscout.androidaps.events.EventRefreshOverview; +import info.nightscout.androidaps.interfaces.CommandQueueProvider; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PumpInterface; -import info.nightscout.androidaps.logging.AAPSLoggerProduction; +import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.common.ManufacturerType; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; 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.EventNewNotification; @@ -79,7 +84,8 @@ import info.nightscout.androidaps.plugins.pump.medtronic.service.RileyLinkMedtro import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicConst; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; -import info.nightscout.androidaps.utils.SP; +import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.sharedPreferences.SP; import static info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil.sendNotification; @@ -88,14 +94,24 @@ import static info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUt * * @author Andy Rozman (andy.rozman@gmail.com) */ +@Singleton public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInterface { + private final MainApp mainApp; + private final ResourceHelper resourceHelper; + private final ConstraintChecker constraintChecker; + private final ProfileFunction profileFunction; + private final TreatmentsPlugin treatmentsPlugin; + private final info.nightscout.androidaps.utils.sharedPreferences.SP sp; + private final RxBusWrapper rxBus; + private final CommandQueueProvider commandQueue; + private static final Logger LOG = LoggerFactory.getLogger(L.PUMP); protected static MedtronicPumpPlugin plugin = null; private RileyLinkMedtronicService medtronicService; private MedtronicPumpStatus pumpStatusLocal = null; - private MedtronicUIComm medtronicUIComm = new MedtronicUIComm(); + private MedtronicUIComm medtronicUIComm; // variables for handling statuses and history private boolean firstRun = true; @@ -111,7 +127,18 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter private boolean hasTimeDateOrTimeZoneChanged = false; - private MedtronicPumpPlugin() { + @Inject + public MedtronicPumpPlugin( + AAPSLogger aapsLogger, + RxBusWrapper rxBus, + MainApp maiApp, + ResourceHelper resourceHelper, + ConstraintChecker constraintChecker, + ProfileFunction profileFunction, + TreatmentsPlugin treatmentsPlugin, + SP sp, + CommandQueueProvider commandQueue + ) { super(new PluginDescription() // .mainType(PluginType.PUMP) // @@ -120,13 +147,22 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter .shortName(R.string.medtronic_name_short) // .preferencesId(R.xml.pref_medtronic).description(R.string.description_pump_medtronic), // PumpType.Medtronic_522_722, // we default to most basic model, correct model from config is loaded later - new RxBusWrapper(), new AAPSLoggerProduction() // TODO: dagger + resourceHelper, aapsLogger, commandQueue + ); + this.plugin = this; + + this.mainApp = maiApp; + this.rxBus = rxBus; + this.resourceHelper = resourceHelper; + this.constraintChecker = constraintChecker; + this.profileFunction = profileFunction; + this.treatmentsPlugin = treatmentsPlugin; + this.sp = sp; + this.commandQueue = commandQueue; displayConnectionMessages = false; - medtronicHistoryData = new MedtronicHistoryData(); - serviceConnection = new ServiceConnection() { public void onServiceDisconnected(ComponentName name) { @@ -160,9 +196,17 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter } + @Override + protected void onStart() { + super.onStart(); + medtronicUIComm = new MedtronicUIComm(); + medtronicHistoryData = new MedtronicHistoryData(); + } + + @Deprecated public static MedtronicPumpPlugin getPlugin() { if (plugin == null) - plugin = new MedtronicPumpPlugin(); + throw new IllegalStateException("Plugin not injected jet"); return plugin; } @@ -183,7 +227,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter this.pumpStatusLocal = new MedtronicPumpStatus(pumpDescription); MedtronicUtil.setPumpStatus(pumpStatusLocal); - pumpStatusLocal.lastConnection = SP.getLong(RileyLinkConst.Prefs.LastGoodDeviceCommunicationTime, 0L); + pumpStatusLocal.lastConnection = sp.getLong(RileyLinkConst.Prefs.LastGoodDeviceCommunicationTime, 0L); pumpStatusLocal.lastDataTime = new LocalDateTime(pumpStatusLocal.lastConnection); pumpStatusLocal.previousConnection = pumpStatusLocal.lastConnection; @@ -198,29 +242,28 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter pumpDescription.maxTempAbsolute = (pumpStatusLocal.maxBasal != null) ? pumpStatusLocal.maxBasal : 35.0d; // set first Medtronic Pump Start - if (!SP.contains(MedtronicConst.Statistics.FirstPumpStart)) { - SP.putLong(MedtronicConst.Statistics.FirstPumpStart, System.currentTimeMillis()); + if (!sp.contains(MedtronicConst.Statistics.FirstPumpStart)) { + sp.putLong(MedtronicConst.Statistics.FirstPumpStart, System.currentTimeMillis()); } migrateSettings(); } - private void migrateSettings() { - if ("US (916 MHz)".equals(SP.getString(MedtronicConst.Prefs.PumpFrequency, null))) { - SP.putString(MedtronicConst.Prefs.PumpFrequency, MainApp.gs(R.string.key_medtronic_pump_frequency_us_ca)); + if ("US (916 MHz)".equals(sp.getString(MedtronicConst.Prefs.PumpFrequency, null))) { + sp.putString(MedtronicConst.Prefs.PumpFrequency, MainApp.gs(R.string.key_medtronic_pump_frequency_us_ca)); } - String encoding = SP.getString(MedtronicConst.Prefs.Encoding, null); + String encoding = sp.getString(MedtronicConst.Prefs.Encoding, null); if ("RileyLink 4b6b Encoding".equals(encoding)) { - SP.putString(MedtronicConst.Prefs.Encoding, MainApp.gs(R.string.key_medtronic_pump_encoding_4b6b_rileylink)); + sp.putString(MedtronicConst.Prefs.Encoding, MainApp.gs(R.string.key_medtronic_pump_encoding_4b6b_rileylink)); } if ("Local 4b6b Encoding".equals(encoding)) { - SP.putString(MedtronicConst.Prefs.Encoding, MainApp.gs(R.string.key_medtronic_pump_encoding_4b6b_local)); + sp.putString(MedtronicConst.Prefs.Encoding, MainApp.gs(R.string.key_medtronic_pump_encoding_4b6b_local)); } } @@ -239,9 +282,8 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter StatusRefreshAction.GetData, null, null); if (doWeHaveAnyStatusNeededRefereshing(statusRefresh)) { - if (!ConfigBuilderPlugin.getPlugin().getCommandQueue().statusInQueue()) { - ConfigBuilderPlugin.getPlugin().getCommandQueue() - .readStatus("Scheduled Status Refresh", null); + if (!commandQueue.statusInQueue()) { + commandQueue.readStatus("Scheduled Status Refresh", null); } } @@ -808,7 +850,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter // LOG.debug("MedtronicPumpPlugin::deliverBolus - Starting wait period."); - int sleepTime = SP.getInt(MedtronicConst.Prefs.BolusDelay, 10) * 1000; + int sleepTime = sp.getInt(MedtronicConst.Prefs.BolusDelay, 10) * 1000; SystemClock.sleep(sleepTime); @@ -926,15 +968,15 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter private void incrementStatistics(String statsKey) { - long currentCount = SP.getLong(statsKey, 0L); + long currentCount = sp.getLong(statsKey, 0L); currentCount++; - SP.putLong(statsKey, currentCount); + sp.putLong(statsKey, currentCount); } // if enforceNew===true current temp basal is canceled and new TBR set (duration is prolonged), // if false and the same rate is requested enacted=false and success=true is returned and TBR is not changed - @Override + @NonNull @Override public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean enforceNew) { @@ -1057,7 +1099,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter } - @Override + @NonNull @Override public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) { if (percent == 0) { @@ -1201,7 +1243,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter return; this.lastPumpHistoryEntry = latestEntry; - SP.putLong(MedtronicConst.Statistics.LastPumpHistoryEntry, latestEntry.atechDateTime); + sp.putLong(MedtronicConst.Statistics.LastPumpHistoryEntry, latestEntry.atechDateTime); LOG.debug("HST: History: valid={}, unprocessed={}", historyResult.validEntries.size(), historyResult.unprocessedEntries.size()); @@ -1232,7 +1274,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter } private Long getLastPumpEntryTime() { - Long lastPumpEntryTime = SP.getLong(MedtronicConst.Statistics.LastPumpHistoryEntry, 0L); + Long lastPumpEntryTime = sp.getLong(MedtronicConst.Statistics.LastPumpHistoryEntry, 0L); try { LocalDateTime localDateTime = DateTimeUtil.toLocalDateTime(lastPumpEntryTime); @@ -1342,7 +1384,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter } - @Override + @NonNull @Override public PumpEnactResult cancelTempBasal(boolean enforceNew) { if (isLoggingEnabled()) @@ -1406,22 +1448,22 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter } } - @Override + @NonNull @Override public ManufacturerType manufacturer() { return getMDTPumpStatus().pumpType.getManufacturer(); } - @Override + @NonNull @Override public PumpType model() { return getMDTPumpStatus().pumpType; } - @Override + @NonNull @Override public String serialNumber() { return getMDTPumpStatus().serialNumber; } - @Override + @NonNull @Override public PumpEnactResult setNewBasalProfile(Profile profile) { if (isLoggingEnabled()) LOG.info(getLogPrefix() + "setNewBasalProfile"); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt index 84ce57ced1..ced9a618b0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt @@ -11,11 +11,7 @@ import info.nightscout.androidaps.db.ExtendedBolus import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.db.TemporaryBasal import info.nightscout.androidaps.events.EventPreferenceChange -import info.nightscout.androidaps.interfaces.PluginBase -import info.nightscout.androidaps.interfaces.PluginDescription -import info.nightscout.androidaps.interfaces.PluginType -import info.nightscout.androidaps.interfaces.PumpDescription -import info.nightscout.androidaps.interfaces.PumpInterface +import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBusWrapper @@ -23,7 +19,6 @@ import info.nightscout.androidaps.plugins.common.ManufacturerType import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType -import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress import info.nightscout.androidaps.plugins.general.overview.notifications.Notification @@ -42,17 +37,19 @@ import org.json.JSONException import org.json.JSONObject import javax.inject.Inject import javax.inject.Singleton +import kotlin.math.min @Singleton class VirtualPumpPlugin @Inject constructor( aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, + private val rxBus: RxBusWrapper, private var fabricPrivacy: FabricPrivacy, - private val resourceHelper: ResourceHelper, + resourceHelper: ResourceHelper, private val sp: SP, private val profileFunction: ProfileFunction, - private val treatmentsPlugin: TreatmentsPlugin -) : PluginBase(PluginDescription() + private val treatmentsPlugin: TreatmentsPlugin, + commandQueue: CommandQueueProvider +) : PumpPluginBase(PluginDescription() .mainType(PluginType.PUMP) .fragmentClass(VirtualPumpFragment::class.java.name) .pluginName(R.string.virtualpump) @@ -60,7 +57,7 @@ class VirtualPumpPlugin @Inject constructor( .preferencesId(R.xml.pref_virtualpump) .neverVisible(Config.NSCLIENT) .description(R.string.description_pump_virtual), - rxBus, aapsLogger + aapsLogger, resourceHelper, commandQueue ), PumpInterface { @@ -219,7 +216,7 @@ class VirtualPumpPlugin @Inject constructor( SystemClock.sleep(200) val bolusingEvent = EventOverviewBolusProgress bolusingEvent.status = resourceHelper.gs(R.string.bolusdelivering, delivering) - bolusingEvent.percent = Math.min((delivering / detailedBolusInfo.insulin * 100).toInt(), 100) + bolusingEvent.percent = min((delivering / detailedBolusInfo.insulin * 100).toInt(), 100) rxBus.send(bolusingEvent) delivering += 0.1 } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPlugin.java index b860694473..37abd8238f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPlugin.java @@ -9,19 +9,19 @@ import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.SensitivityInterface; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.utils.Round; import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.SafeParse; +import info.nightscout.androidaps.utils.resources.ResourceHelper; public abstract class AbstractSensitivityPlugin extends PluginBase implements SensitivityInterface { private static final Logger log = LoggerFactory.getLogger(L.AUTOSENS); - public AbstractSensitivityPlugin(PluginDescription pluginDescription, RxBusWrapper rxBusWrapper, AAPSLogger aapsLogger) { - super(pluginDescription, rxBusWrapper, aapsLogger); + public AbstractSensitivityPlugin(PluginDescription pluginDescription, AAPSLogger aapsLogger, ResourceHelper resourceHelper) { + super(pluginDescription, aapsLogger, resourceHelper); } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.java index 30b1e57c68..0065f72f4c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.java @@ -10,6 +10,9 @@ import java.util.Arrays; import java.util.Date; import java.util.List; +import javax.inject.Inject; +import javax.inject.Singleton; + import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; @@ -17,42 +20,36 @@ import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.db.ProfileSwitch; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; -import info.nightscout.androidaps.logging.AAPSLoggerProduction; +import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.SP; +import info.nightscout.androidaps.utils.resources.ResourceHelper; /** * Created by mike on 24.06.2017. */ +@Singleton public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin { private static Logger log = LoggerFactory.getLogger(L.AUTOSENS); - static SensitivityAAPSPlugin plugin = null; - - @Deprecated - public static SensitivityAAPSPlugin getPlugin() { - if (plugin == null) - plugin = new SensitivityAAPSPlugin(); - return plugin; - } - - // TODO: dagger - - public SensitivityAAPSPlugin() { + @Inject + public SensitivityAAPSPlugin( + AAPSLogger aapsLogger, + ResourceHelper resourceHelper + ) { super(new PluginDescription() - .mainType(PluginType.SENSITIVITY) - .pluginName(R.string.sensitivityaaps) - .shortName(R.string.sensitivity_shortname) - .preferencesId(R.xml.pref_absorption_aaps) - .description(R.string.description_sensitivity_aaps), - new RxBusWrapper(), new AAPSLoggerProduction() // TODO: dagger + .mainType(PluginType.SENSITIVITY) + .pluginName(R.string.sensitivityaaps) + .shortName(R.string.sensitivity_shortname) + .preferencesId(R.xml.pref_absorption_aaps) + .description(R.string.description_sensitivity_aaps), + aapsLogger, resourceHelper ); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref0Plugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref0Plugin.java index 9beb9578db..16a20a740a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref0Plugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref0Plugin.java @@ -10,6 +10,9 @@ import java.util.Arrays; import java.util.Date; import java.util.List; +import javax.inject.Inject; +import javax.inject.Singleton; + import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; @@ -17,41 +20,34 @@ import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.db.ProfileSwitch; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; -import info.nightscout.androidaps.logging.AAPSLoggerProduction; +import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.utils.DateUtil; +import info.nightscout.androidaps.utils.resources.ResourceHelper; /** * Created by mike on 24.06.2017. */ - +@Singleton public class SensitivityOref0Plugin extends AbstractSensitivityPlugin { private static Logger log = LoggerFactory.getLogger(L.AUTOSENS); - static SensitivityOref0Plugin plugin = null; - - @Deprecated - public static SensitivityOref0Plugin getPlugin() { - if (plugin == null) - plugin = new SensitivityOref0Plugin(); - return plugin; - } - - // TODO: dagger - - public SensitivityOref0Plugin() { + @Inject + public SensitivityOref0Plugin( + AAPSLogger aapsLogger, + ResourceHelper resourceHelper + ) { super(new PluginDescription() - .mainType(PluginType.SENSITIVITY) - .pluginName(R.string.sensitivityoref0) - .shortName(R.string.sensitivity_shortname) - .preferencesId(R.xml.pref_absorption_oref0) - .description(R.string.description_sensitivity_oref0), - new RxBusWrapper(), new AAPSLoggerProduction() // TODO: dagger + .mainType(PluginType.SENSITIVITY) + .pluginName(R.string.sensitivityoref0) + .shortName(R.string.sensitivity_shortname) + .preferencesId(R.xml.pref_absorption_oref0) + .description(R.string.description_sensitivity_oref0), + aapsLogger, resourceHelper ); } @@ -61,7 +57,6 @@ public class SensitivityOref0Plugin extends AbstractSensitivityPlugin { int hoursForDetection = 24; - long now = System.currentTimeMillis(); Profile profile = ProfileFunctions.getInstance().getProfile(); if (profile == null) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.java index 334f785549..31ff8afae1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.java @@ -10,6 +10,9 @@ import java.util.Arrays; import java.util.Date; import java.util.List; +import javax.inject.Inject; +import javax.inject.Singleton; + import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; @@ -17,39 +20,35 @@ import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.db.ProfileSwitch; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; -import info.nightscout.androidaps.logging.AAPSLoggerProduction; +import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.utils.DateUtil; +import info.nightscout.androidaps.utils.resources.ResourceHelper; /** * Created by mike on 19.06.2018. */ - +@Singleton public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { private static Logger log = LoggerFactory.getLogger(L.AUTOSENS); - static SensitivityOref1Plugin plugin = null; - - @Deprecated - public static SensitivityOref1Plugin getPlugin() { - if (plugin == null) - plugin = new SensitivityOref1Plugin(); - return plugin; - } - - public SensitivityOref1Plugin() { + @Inject + public SensitivityOref1Plugin( + AAPSLogger aapsLogger, + ResourceHelper resourceHelper + ) { super(new PluginDescription() - .mainType(PluginType.SENSITIVITY) - .pluginName(R.string.sensitivityoref1) - .shortName(R.string.sensitivity_shortname) - .preferencesId(R.xml.pref_absorption_oref1) - .description(R.string.description_sensitivity_oref1), - new RxBusWrapper(), new AAPSLoggerProduction() // TODO: Dagger + .mainType(PluginType.SENSITIVITY) + .pluginName(R.string.sensitivityoref1) + .shortName(R.string.sensitivity_shortname) + .enableByDefault(true) + .preferencesId(R.xml.pref_absorption_oref1) + .description(R.string.description_sensitivity_oref1), + aapsLogger, resourceHelper ); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.java index 00005eda57..219ce2a159 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.java @@ -8,6 +8,9 @@ import org.slf4j.LoggerFactory; import java.util.Date; import java.util.List; +import javax.inject.Inject; +import javax.inject.Singleton; + import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; @@ -15,42 +18,35 @@ import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.db.ProfileSwitch; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; -import info.nightscout.androidaps.logging.AAPSLoggerProduction; +import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.SP; +import info.nightscout.androidaps.utils.resources.ResourceHelper; /** * Created by mike on 24.06.2017. */ - +@Singleton public class SensitivityWeightedAveragePlugin extends AbstractSensitivityPlugin { private static Logger log = LoggerFactory.getLogger(L.AUTOSENS); - private static SensitivityWeightedAveragePlugin plugin = null; - - @Deprecated - public static SensitivityWeightedAveragePlugin getPlugin() { - if (plugin == null) - plugin = new SensitivityWeightedAveragePlugin(); - return plugin; - } - - // TODO: dagger - - public SensitivityWeightedAveragePlugin() { + @Inject + public SensitivityWeightedAveragePlugin( + AAPSLogger aapsLogger, + ResourceHelper resourceHelper + ) { super(new PluginDescription() - .mainType(PluginType.SENSITIVITY) - .pluginName(R.string.sensitivityweightedaverage) - .shortName(R.string.sensitivity_shortname) - .preferencesId(R.xml.pref_absorption_aaps) - .description(R.string.description_sensitivity_weighted_average), - new RxBusWrapper(), new AAPSLoggerProduction() // TODO: dagger + .mainType(PluginType.SENSITIVITY) + .pluginName(R.string.sensitivityweightedaverage) + .shortName(R.string.sensitivity_shortname) + .preferencesId(R.xml.pref_absorption_aaps) + .description(R.string.description_sensitivity_weighted_average), + aapsLogger, resourceHelper ); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt index d58ed8b428..7aa9567ac1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt @@ -14,10 +14,10 @@ import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.T +import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import org.json.JSONObject import javax.inject.Inject @@ -27,7 +27,8 @@ import javax.inject.Singleton class DexcomPlugin @Inject constructor( private val sp: SP, private val mainApp: MainApp, - rxBus: RxBusWrapper, aapsLogger: AAPSLogger + resourceHelper: ResourceHelper, + aapsLogger: AAPSLogger ) : PluginBase(PluginDescription() .mainType(PluginType.BGSOURCE) .fragmentClass(BGSourceFragment::class.java.name) @@ -35,15 +36,7 @@ class DexcomPlugin @Inject constructor( .shortName(R.string.dexcom_short) .preferencesId(R.xml.pref_bgsourcedexcom) .description(R.string.description_source_dexcom), - rxBus, - aapsLogger), BgSourceInterface { - - private val PACKAGE_NAMES = arrayOf("com.dexcom.cgm.region1.mgdl", "com.dexcom.cgm.region1.mmol", - "com.dexcom.cgm.region2.mgdl", "com.dexcom.cgm.region2.mmol", - "com.dexcom.g6.region1.mmol", "com.dexcom.g6.region2.mgdl", - "com.dexcom.g6.region3.mgdl", "com.dexcom.g6.region3.mmol") - - val PERMISSION = "com.dexcom.cgm.EXTERNAL_PERMISSION" + aapsLogger, resourceHelper), BgSourceInterface { override fun advancedFilteringSupported(): Boolean { return true @@ -125,4 +118,12 @@ class DexcomPlugin @Inject constructor( aapsLogger.error("Error while processing intent from Dexcom App", e) } } + + companion object { + private val PACKAGE_NAMES = arrayOf("com.dexcom.cgm.region1.mgdl", "com.dexcom.cgm.region1.mmol", + "com.dexcom.cgm.region2.mgdl", "com.dexcom.cgm.region2.mmol", + "com.dexcom.g6.region1.mmol", "com.dexcom.g6.region2.mgdl", + "com.dexcom.g6.region3.mgdl", "com.dexcom.g6.region3.mmol") + const val PERMISSION = "com.dexcom.cgm.EXTERNAL_PERMISSION" + } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/EversensePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/EversensePlugin.kt index 2d45e20396..b25ab7b3e4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/EversensePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/EversensePlugin.kt @@ -14,9 +14,9 @@ import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.L import info.nightscout.androidaps.logging.L.isEnabled import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import org.json.JSONException import org.json.JSONObject @@ -27,7 +27,8 @@ import javax.inject.Singleton @Singleton class EversensePlugin @Inject constructor( private val sp: SP, - rxBus: RxBusWrapper, aapsLogger: AAPSLogger + resourceHelper: ResourceHelper, + aapsLogger: AAPSLogger ) : PluginBase(PluginDescription() .mainType(PluginType.BGSOURCE) .fragmentClass(BGSourceFragment::class.java.name) @@ -35,8 +36,8 @@ class EversensePlugin @Inject constructor( .shortName(R.string.eversense_shortname) .preferencesId(R.xml.pref_bgsource) .description(R.string.description_source_eversense), - rxBus, - aapsLogger + aapsLogger, + resourceHelper ), BgSourceInterface { override fun advancedFilteringSupported(): Boolean { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/GlimpPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/GlimpPlugin.kt index ecae346008..8810dc1e31 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/GlimpPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/GlimpPlugin.kt @@ -11,21 +11,22 @@ import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.BundleLogger import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.utils.resources.ResourceHelper import javax.inject.Inject import javax.inject.Singleton @Singleton class GlimpPlugin @Inject constructor( - rxBus: RxBusWrapper, aapsLogger: AAPSLogger + resourceHelper: ResourceHelper, + aapsLogger: AAPSLogger ) : PluginBase(PluginDescription() .mainType(PluginType.BGSOURCE) .fragmentClass(BGSourceFragment::class.java.name) .pluginName(R.string.Glimp) .preferencesId(R.xml.pref_bgsource) .description(R.string.description_source_glimp), - rxBus, - aapsLogger + aapsLogger, + resourceHelper ), BgSourceInterface { override fun advancedFilteringSupported(): Boolean { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/MM640gPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/MM640gPlugin.kt index 517901b0c4..1a79c9a333 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/MM640gPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/MM640gPlugin.kt @@ -10,7 +10,7 @@ import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.utils.resources.ResourceHelper import org.json.JSONArray import org.json.JSONException import javax.inject.Inject @@ -18,14 +18,15 @@ import javax.inject.Singleton @Singleton class MM640gPlugin @Inject constructor( - rxBus: RxBusWrapper, aapsLogger: AAPSLogger + resourceHelper: ResourceHelper, + aapsLogger: AAPSLogger ) : PluginBase(PluginDescription() .mainType(PluginType.BGSOURCE) .fragmentClass(BGSourceFragment::class.java.name) .pluginName(R.string.MM640g) .description(R.string.description_source_mm640g), - rxBus, - aapsLogger + aapsLogger, + resourceHelper ), BgSourceInterface { override fun advancedFilteringSupported(): Boolean { @@ -43,15 +44,14 @@ class MM640gPlugin @Inject constructor( try { val jsonArray = JSONArray(data) for (i in 0 until jsonArray.length()) { - val json_object = jsonArray.getJSONObject(i) - val type = json_object.getString("type") - when (type) { + val jsonObject = jsonArray.getJSONObject(i) + when (val type = jsonObject.getString("type")) { "sgv" -> { val bgReading = BgReading() - bgReading.value = json_object.getDouble("sgv") - bgReading.direction = json_object.getString("direction") - bgReading.date = json_object.getLong("date") - bgReading.raw = json_object.getDouble("sgv") + bgReading.value = jsonObject.getDouble("sgv") + bgReading.direction = jsonObject.getString("direction") + bgReading.date = jsonObject.getLong("date") + bgReading.raw = jsonObject.getDouble("sgv") MainApp.getDbHelper().createIfNotExists(bgReading, "MM640g") } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/NSClientSourcePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/NSClientSourcePlugin.kt index cdf579d09e..c3159b97e9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/NSClientSourcePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/NSClientSourcePlugin.kt @@ -10,10 +10,10 @@ import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.nsclient.data.NSSgv import info.nightscout.androidaps.utils.JsonHelper.safeGetLong import info.nightscout.androidaps.utils.JsonHelper.safeGetString +import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import org.json.JSONArray import org.json.JSONObject @@ -22,15 +22,16 @@ import javax.inject.Singleton @Singleton class NSClientSourcePlugin @Inject constructor( - rxBus: RxBusWrapper, aapsLogger: AAPSLogger, + resourceHelper: ResourceHelper, + aapsLogger: AAPSLogger, private val sp: SP ) : PluginBase(PluginDescription() .mainType(PluginType.BGSOURCE) .fragmentClass(BGSourceFragment::class.java.name) .pluginName(R.string.nsclientbg) .description(R.string.description_source_ns_client), - rxBus, - aapsLogger + aapsLogger, + resourceHelper ), BgSourceInterface { private var lastBGTimeStamp: Long = 0 @@ -45,15 +46,15 @@ class NSClientSourcePlugin @Inject constructor( val bundles = intent.extras ?: return try { if (bundles.containsKey("sgv")) { - val sgvstring = bundles.getString("sgv") - aapsLogger.debug(LTag.BGSOURCE, "Received NS Data: $sgvstring") - val sgvJson = JSONObject(sgvstring) + val sgvString = bundles.getString("sgv") + aapsLogger.debug(LTag.BGSOURCE, "Received NS Data: $sgvString") + val sgvJson = JSONObject(sgvString) storeSgv(sgvJson) } if (bundles.containsKey("sgvs")) { - val sgvstring = bundles.getString("sgvs") - aapsLogger.debug(LTag.BGSOURCE, "Received NS Data: $sgvstring") - val jsonArray = JSONArray(sgvstring) + val sgvString = bundles.getString("sgvs") + aapsLogger.debug(LTag.BGSOURCE, "Received NS Data: $sgvString") + val jsonArray = JSONArray(sgvString) for (i in 0 until jsonArray.length()) { val sgvJson = jsonArray.getJSONObject(i) storeSgv(sgvJson) @@ -73,7 +74,7 @@ class NSClientSourcePlugin @Inject constructor( detectSource(safeGetString(sgvJson, "device", "none"), safeGetLong(sgvJson, "mills")) } - fun detectSource(source: String, timeStamp: Long) { + private fun detectSource(source: String, timeStamp: Long) { if (timeStamp > lastBGTimeStamp) { isAdvancedFilteringEnabled = source.contains("G5 Native") || source.contains("G6 Native") || source.contains("AndroidAPS-DexcomG5") || source.contains("AndroidAPS-DexcomG6") lastBGTimeStamp = timeStamp diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/PoctechPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/PoctechPlugin.kt index 07587e8fb3..fb61989e10 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/PoctechPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/PoctechPlugin.kt @@ -11,9 +11,9 @@ import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.utils.JsonHelper.safeGetString +import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import org.json.JSONArray import org.json.JSONException @@ -22,7 +22,8 @@ import javax.inject.Singleton @Singleton class PoctechPlugin @Inject constructor( - rxBus: RxBusWrapper, aapsLogger: AAPSLogger, + resourceHelper: ResourceHelper, + aapsLogger: AAPSLogger, private val sp: SP ) : PluginBase(PluginDescription() .mainType(PluginType.BGSOURCE) @@ -30,8 +31,8 @@ class PoctechPlugin @Inject constructor( .pluginName(R.string.poctech) .preferencesId(R.xml.pref_bgsource) .description(R.string.description_source_poctech), - rxBus, - aapsLogger + aapsLogger, + resourceHelper ), BgSourceInterface { override fun advancedFilteringSupported(): Boolean { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt index 78a1970a4d..8074920d56 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt @@ -11,11 +11,11 @@ import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.extensions.isRunningTest +import info.nightscout.androidaps.utils.resources.ResourceHelper import java.util.* import javax.inject.Inject import javax.inject.Singleton @@ -24,7 +24,8 @@ import kotlin.math.sin @Singleton class RandomBgPlugin @Inject constructor( - rxBus: RxBusWrapper, aapsLogger: AAPSLogger, + resourceHelper: ResourceHelper, + aapsLogger: AAPSLogger, private var virtualPumpPlugin: VirtualPumpPlugin ) : PluginBase(PluginDescription() .mainType(PluginType.BGSOURCE) @@ -32,8 +33,9 @@ class RandomBgPlugin @Inject constructor( .pluginName(R.string.randombg) .shortName(R.string.randombg_short) .description(R.string.description_source_randombg), - rxBus, - aapsLogger), BgSourceInterface { + aapsLogger, + resourceHelper +), BgSourceInterface { private val loopHandler = Handler() private lateinit var refreshLoop: Runnable diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/TomatoPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/TomatoPlugin.kt index 018fbcd9e2..de10ce0ebf 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/TomatoPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/TomatoPlugin.kt @@ -10,15 +10,16 @@ import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.nsclient.NSUpload +import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import javax.inject.Inject import javax.inject.Singleton @Singleton class TomatoPlugin @Inject constructor( - rxBus: RxBusWrapper, aapsLogger: AAPSLogger, + resourceHelper: ResourceHelper, + aapsLogger: AAPSLogger, private val sp: SP ) : PluginBase(PluginDescription() .mainType(PluginType.BGSOURCE) @@ -27,8 +28,8 @@ class TomatoPlugin @Inject constructor( .preferencesId(R.xml.pref_bgsource) .shortName(R.string.tomato_short) .description(R.string.description_source_tomato), - rxBus, - aapsLogger + aapsLogger, + resourceHelper ), BgSourceInterface { override fun advancedFilteringSupported(): Boolean { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/XdripPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/XdripPlugin.kt index a198bc75de..47fe68a2fc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/XdripPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/XdripPlugin.kt @@ -11,24 +11,25 @@ import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.BundleLogger import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.services.Intents +import info.nightscout.androidaps.utils.resources.ResourceHelper import javax.inject.Inject import javax.inject.Singleton @Singleton class XdripPlugin @Inject constructor( - rxBus: RxBusWrapper, aapsLogger: AAPSLogger + resourceHelper: ResourceHelper, + aapsLogger: AAPSLogger ) : PluginBase(PluginDescription() .mainType(PluginType.BGSOURCE) .fragmentClass(BGSourceFragment::class.java.name) .pluginName(R.string.xdrip) .description(R.string.description_source_xdrip), - rxBus, - aapsLogger + aapsLogger, + resourceHelper ), BgSourceInterface { - var advancedFiltering = false + private var advancedFiltering = false override fun advancedFilteringSupported(): Boolean { return advancedFiltering @@ -48,7 +49,7 @@ class XdripPlugin @Inject constructor( MainApp.getDbHelper().createIfNotExists(bgReading, "XDRIP") } - fun setSource(source: String) { + private fun setSource(source: String) { advancedFiltering = source.contains("G5 Native") || source.contains("G6 Native") } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsFragment.kt index 8020dedd04..048b0e82aa 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsFragment.kt @@ -103,7 +103,7 @@ class TreatmentsFragment : DaggerFragment() { } private fun updateGui() { - if (configBuilderPlugin.activePump?.pumpDescription?.isExtendedBolusCapable == true + if (configBuilderPlugin.activePumpPlugin?.pumpDescription?.isExtendedBolusCapable == true || treatmentsPlugin.extendedBolusesFromHistory.size() > 0) treatments_extendedboluses?.visibility = View.VISIBLE else diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java index 1dfaa12729..0c6832fdbc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java @@ -67,6 +67,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface private final MainApp mainApp; private final SP sp; + private final RxBusWrapper rxBus; private final ResourceHelper resourceHelper; private final ProfileFunction profileFunction; private final ConfigBuilderPlugin configBuilderPlugin; @@ -106,17 +107,18 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface ConfigBuilderPlugin configBuilderPlugin ) { super(new PluginDescription() - .mainType(PluginType.TREATMENT) - .fragmentClass(TreatmentsFragment.class.getName()) - .pluginName(R.string.treatments) - .shortName(R.string.treatments_shortname) - .alwaysEnabled(true) - .description(R.string.description_treatments), - rxBus, - aapsLogger + .mainType(PluginType.TREATMENT) + .fragmentClass(TreatmentsFragment.class.getName()) + .pluginName(R.string.treatments) + .shortName(R.string.treatments_shortname) + .alwaysEnabled(true) + .description(R.string.description_treatments), + aapsLogger, + resourceHelper ); this.resourceHelper = resourceHelper; this.mainApp = mainApp; + this.rxBus = rxBus; this.sp = sp; this.profileFunction = profileFunction; this.configBuilderPlugin = configBuilderPlugin; @@ -128,7 +130,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface this.service = new TreatmentService(); initializeData(range()); super.onStart(); - disposable.add(getRxBus() + disposable.add(rxBus .toObservable(EventReloadTreatmentData.class) .observeOn(Schedulers.io()) .subscribe(event -> { @@ -136,23 +138,23 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface initializeTreatmentData(range()); initializeExtendedBolusData(range()); updateTotalIOBTreatments(); - getRxBus().send(event.getNext()); + rxBus.send(event.getNext()); }, exception -> FabricPrivacy.getInstance().logException(exception) )); - disposable.add(getRxBus() + disposable.add(rxBus .toObservable(EventReloadProfileSwitchData.class) .observeOn(Schedulers.io()) .subscribe(event -> initializeProfileSwitchData(range()), exception -> FabricPrivacy.getInstance().logException(exception) )); - disposable.add(getRxBus() + disposable.add(rxBus .toObservable(EventTempTargetChange.class) .observeOn(Schedulers.io()) .subscribe(event -> initializeTempTargetData(range()), exception -> FabricPrivacy.getInstance().logException(exception) )); - disposable.add(getRxBus() + disposable.add(rxBus .toObservable(EventReloadTempBasalData.class) .observeOn(Schedulers.io()) .subscribe(event -> { @@ -240,11 +242,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface if (profile == null) return total; - InsulinInterface insulinInterface = configBuilderPlugin.getActiveInsulin(); - if (insulinInterface == null) - return total; - - PumpInterface pumpInterface = configBuilderPlugin.getActivePump(); + PumpInterface pumpInterface = configBuilderPlugin.getActivePumpPlugin(); if (pumpInterface == null) return total; @@ -402,10 +400,8 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface IobTotal total = new IobTotal(time); InsulinInterface insulinInterface = configBuilderPlugin.getActiveInsulin(); - if (insulinInterface == null) - return total; - PumpInterface pumpInterface = configBuilderPlugin.getActivePump(); + PumpInterface pumpInterface = configBuilderPlugin.getActivePumpPlugin(); if (pumpInterface == null) return total; @@ -462,10 +458,8 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface IobTotal total = new IobTotal(time); InsulinInterface insulinInterface = configBuilderPlugin.getActiveInsulin(); - if (insulinInterface == null) - return total; - PumpInterface pumpInterface = configBuilderPlugin.getActivePump(); + PumpInterface pumpInterface = configBuilderPlugin.getActivePumpPlugin(); if (pumpInterface == null) return total; @@ -727,7 +721,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface @Override public void addToHistoryProfileSwitch(ProfileSwitch profileSwitch) { //log.debug("Adding new TemporaryBasal record" + profileSwitch.log()); - getRxBus().send(new EventDismissNotification(Notification.PROFILE_SWITCH_MISSING)); + rxBus.send(new EventDismissNotification(Notification.PROFILE_SWITCH_MISSING)); MainApp.getDbHelper().createOrUpdate(profileSwitch); NSUpload.uploadProfileSwitch(profileSwitch); } diff --git a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java deleted file mode 100644 index d6babb4033..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java +++ /dev/null @@ -1,594 +0,0 @@ -package info.nightscout.androidaps.queue; - -import android.content.Context; -import android.content.Intent; -import android.os.SystemClock; -import android.text.Html; -import android.text.Spanned; - -import androidx.appcompat.app.AppCompatActivity; - -import org.slf4j.Logger; -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.plugins.general.overview.events.EventDismissBolusProgressIfRunning; -import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification; -import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; -import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; -import info.nightscout.androidaps.queue.commands.Command; -import info.nightscout.androidaps.queue.commands.CommandBolus; -import info.nightscout.androidaps.queue.commands.CommandCancelExtendedBolus; -import info.nightscout.androidaps.queue.commands.CommandCancelTempBasal; -import info.nightscout.androidaps.queue.commands.CommandExtendedBolus; -import info.nightscout.androidaps.queue.commands.CommandInsightSetTBROverNotification; -import info.nightscout.androidaps.queue.commands.CommandLoadEvents; -import info.nightscout.androidaps.queue.commands.CommandLoadHistory; -import info.nightscout.androidaps.queue.commands.CommandLoadTDDs; -import info.nightscout.androidaps.queue.commands.CommandReadStatus; -import info.nightscout.androidaps.queue.commands.CommandSMBBolus; -import info.nightscout.androidaps.queue.commands.CommandSetProfile; -import info.nightscout.androidaps.queue.commands.CommandSetUserSettings; -import info.nightscout.androidaps.queue.commands.CommandStartPump; -import info.nightscout.androidaps.queue.commands.CommandStopPump; -import info.nightscout.androidaps.queue.commands.CommandTempBasalAbsolute; -import info.nightscout.androidaps.queue.commands.CommandTempBasalPercent; - -/** - * Created by mike on 08.11.2017. - *

- * DATA FLOW: - * --------- - *

- * (request) - > ConfigBuilder.getCommandQueue().bolus(...) - *

- * app no longer waits for result but passes Callback - *

- * request is added to queue, if another request of the same type already exists in queue, it's removed prior adding - * but if request of the same type is currently executed (probably important only for bolus which is running long time), new request is declined - * new QueueThread is created and started if current if finished - * CommandReadStatus is added automatically before command if queue is empty - *

- * biggest change is we don't need exec pump commands in Handler because it's finished immediately - * command queueing if not realized by stacking in different Handlers and threads anymore but by internal queue with better control - *

- * QueueThread calls ConfigBuilder#connect which is passed to getActivePump().connect - * connect should be executed on background and return immediately. afterwards isConnecting() is expected to be true - *

- * while isConnecting() == true GUI is updated by posting connection progress - *

- * if connect is successful: isConnected() becomes true, isConnecting() becomes false - * CommandQueue starts calling execute() of commands. execute() is expected to be blocking (return after finish). - * callback with result is called after finish automatically - * if connect failed: isConnected() becomes false, isConnecting() becomes false - * connect() is called again - *

- * when queue is empty, disconnect is called - */ - -public class CommandQueue { - private Logger log = LoggerFactory.getLogger(L.PUMPQUEUE); - - private final LinkedList queue = new LinkedList<>(); - Command performing; - - private QueueThread thread = null; - - private PumpEnactResult executingNowError() { - return new PumpEnactResult().success(false).enacted(false).comment(MainApp.gs(R.string.executingrightnow)); - } - - public boolean isRunning(Command.CommandType type) { - if (performing != null && performing.commandType == type) - return true; - return false; - } - - private synchronized void removeAll(Command.CommandType type) { - synchronized (queue) { - for (int i = queue.size() - 1; i >= 0; i--) { - if (queue.get(i).commandType == type) { - queue.remove(i); - } - } - } - } - - private synchronized boolean isLastScheduled(Command.CommandType type) { - synchronized (queue) { - if (queue.size() > 0 && queue.get(queue.size() - 1).commandType == type) { - return true; - } - } - return false; - } - - private synchronized void inject(Command command) { - // inject as a first command - if (L.isEnabled(L.PUMPQUEUE)) - log.debug("Adding as first: " + command.getClass().getSimpleName() + " - " + command.status()); - synchronized (queue) { - queue.addFirst(command); - } - } - - private synchronized void add(Command command) { - if (L.isEnabled(L.PUMPQUEUE)) - log.debug("Adding: " + command.getClass().getSimpleName() + " - " + command.status()); - synchronized (queue) { - queue.add(command); - } - } - - synchronized void pickup() { - synchronized (queue) { - performing = queue.poll(); - } - } - - synchronized void clear() { - performing = null; - synchronized (queue) { - for (int i = 0; i < queue.size(); i++) { - queue.get(i).cancel(); - } - queue.clear(); - } - } - - public int size() { - return queue.size(); - } - - Command performing() { - return performing; - } - - void resetPerforming() { - performing = null; - } - - // After new command added to the queue - // start thread again if not already running - protected synchronized void notifyAboutNewCommand() { - while (thread != null && thread.getState() != Thread.State.TERMINATED && thread.waitingForDisconnect) { - if (L.isEnabled(L.PUMPQUEUE)) - log.debug("Waiting for previous thread finish"); - SystemClock.sleep(500); - } - if (thread == null || thread.getState() == Thread.State.TERMINATED) { - thread = new QueueThread(this); - thread.start(); - if (L.isEnabled(L.PUMPQUEUE)) - log.debug("Starting new thread"); - } else { - if (L.isEnabled(L.PUMPQUEUE)) - log.debug("Thread is already running"); - } - } - - public void independentConnect(String reason, Callback callback) { - if (L.isEnabled(L.PUMPQUEUE)) - log.debug("Starting new queue"); - CommandQueue tempCommandQueue = new CommandQueue(); - tempCommandQueue.readStatus(reason, callback); - } - - public synchronized boolean bolusInQueue() { - if (isRunning(Command.CommandType.BOLUS)) return true; - synchronized (queue) { - for (int i = 0; i < queue.size(); i++) { - if (queue.get(i).commandType == Command.CommandType.BOLUS) { - return true; - } - } - } - return false; - } - - // returns true if command is queued - public synchronized boolean bolus(DetailedBolusInfo detailedBolusInfo, Callback callback) { - Command.CommandType type = detailedBolusInfo.isSMB ? Command.CommandType.SMB_BOLUS : Command.CommandType.BOLUS; - - if (type == Command.CommandType.SMB_BOLUS) { - if (isRunning(Command.CommandType.BOLUS) || isRunning(Command.CommandType.SMB_BOLUS) || bolusInQueue()) { - if (L.isEnabled(L.PUMPQUEUE)) - log.debug("Rejecting SMB since a bolus is queue/running"); - return false; - } - if (detailedBolusInfo.lastKnownBolusTime < TreatmentsPlugin.getPlugin().getLastBolusTime()) { - if (L.isEnabled(L.PUMPQUEUE)) - log.debug("Rejecting bolus, another bolus was issued since request time"); - return false; - } - removeAll(Command.CommandType.SMB_BOLUS); - } - - - if (type.equals(Command.CommandType.BOLUS) && detailedBolusInfo.carbs > 0 && detailedBolusInfo.insulin == 0) { - type = Command.CommandType.CARBS_ONLY_TREATMENT; - //Carbs only can be added in parallel as they can be "in the future". - } else { - if (isRunning(type)) { - if (callback != null) - callback.result(executingNowError()).run(); - return false; - } - - // remove all unfinished boluses - removeAll(type); - } - - // apply constraints - 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) { - add(new CommandSMBBolus(detailedBolusInfo, callback)); - } else { - add(new CommandBolus(detailedBolusInfo, callback, type)); - if (type.equals(Command.CommandType.BOLUS)) { - // Bring up bolus progress dialog (start here, so the dialog is shown when the bolus is requested, - // not when the Bolus command is starting. The command closes the dialog upon completion). - showBolusProgressDialog(detailedBolusInfo.insulin, detailedBolusInfo.context); - // Notify Wear about upcoming bolus - RxBus.Companion.getINSTANCE().send(new EventBolusRequested(detailedBolusInfo.insulin)); - } - } - - notifyAboutNewCommand(); - - return true; - } - - public void stopPump(Callback callback) { - add(new CommandStopPump(callback)); - notifyAboutNewCommand(); - } - - public void startPump(Callback callback) { - add(new CommandStartPump(callback)); - notifyAboutNewCommand(); - } - - public void setTBROverNotification(Callback callback, boolean enable) { - add(new CommandInsightSetTBROverNotification(callback, enable)); - notifyAboutNewCommand(); - } - - public synchronized void cancelAllBoluses() { - if (!isRunning(Command.CommandType.BOLUS)) { - RxBus.Companion.getINSTANCE().send(new EventDismissBolusProgressIfRunning(new PumpEnactResult().success(true).enacted(false))); - } - removeAll(Command.CommandType.BOLUS); - removeAll(Command.CommandType.SMB_BOLUS); - new Thread(() -> ConfigBuilderPlugin.getPlugin().getActivePump().stopBolusDelivering()).run(); - } - - // returns true if command is queued - public boolean tempBasalAbsolute(double absoluteRate, int durationInMinutes, boolean enforceNew, Profile profile, Callback callback) { - if (!enforceNew && isRunning(Command.CommandType.TEMPBASAL)) { - if (callback != null) - callback.result(executingNowError()).run(); - return false; - } - - // remove all unfinished - removeAll(Command.CommandType.TEMPBASAL); - - Double rateAfterConstraints = ConstraintChecker.getInstance().applyBasalConstraints(new Constraint<>(absoluteRate), profile).value(); - - // add new command to queue - add(new CommandTempBasalAbsolute(rateAfterConstraints, durationInMinutes, enforceNew, profile, callback)); - - notifyAboutNewCommand(); - - return true; - } - - // returns true if command is queued - public boolean tempBasalPercent(Integer percent, int durationInMinutes, boolean enforceNew, Profile profile, Callback callback) { - if (!enforceNew && isRunning(Command.CommandType.TEMPBASAL)) { - if (callback != null) - callback.result(executingNowError()).run(); - return false; - } - - // remove all unfinished - removeAll(Command.CommandType.TEMPBASAL); - - Integer percentAfterConstraints = ConstraintChecker.getInstance().applyBasalPercentConstraints(new Constraint<>(percent), profile).value(); - - // add new command to queue - add(new CommandTempBasalPercent(percentAfterConstraints, durationInMinutes, enforceNew, profile, callback)); - - notifyAboutNewCommand(); - - return true; - } - - // returns true if command is queued - public boolean extendedBolus(double insulin, int durationInMinutes, Callback callback) { - if (isRunning(Command.CommandType.EXTENDEDBOLUS)) { - if (callback != null) - callback.result(executingNowError()).run(); - return false; - } - - Double rateAfterConstraints = ConstraintChecker.getInstance().applyExtendedBolusConstraints(new Constraint<>(insulin)).value(); - - // remove all unfinished - removeAll(Command.CommandType.EXTENDEDBOLUS); - - // add new command to queue - add(new CommandExtendedBolus(rateAfterConstraints, durationInMinutes, callback)); - - notifyAboutNewCommand(); - - return true; - } - - // returns true if command is queued - public boolean cancelTempBasal(boolean enforceNew, Callback callback) { - if (!enforceNew && isRunning(Command.CommandType.TEMPBASAL)) { - if (callback != null) - callback.result(executingNowError()).run(); - return false; - } - - // remove all unfinished - removeAll(Command.CommandType.TEMPBASAL); - - // add new command to queue - add(new CommandCancelTempBasal(enforceNew, callback)); - - notifyAboutNewCommand(); - - return true; - } - - // returns true if command is queued - public boolean cancelExtended(Callback callback) { - if (isRunning(Command.CommandType.EXTENDEDBOLUS)) { - if (callback != null) - callback.result(executingNowError()).run(); - return false; - } - - // remove all unfinished - removeAll(Command.CommandType.EXTENDEDBOLUS); - - // add new command to queue - add(new CommandCancelExtendedBolus(callback)); - - notifyAboutNewCommand(); - - return true; - } - - // returns true if command is queued - public boolean setProfile(Profile profile, Callback callback) { - if (isThisProfileSet(profile)) { - if (L.isEnabled(L.PUMPQUEUE)) - log.debug("Correct profile already set"); - if (callback != null) - callback.result(new PumpEnactResult().success(true).enacted(false)).run(); - return false; - } - - if (!MainApp.isEngineeringModeOrRelease()) { - Notification notification = new Notification(Notification.NOT_ENG_MODE_OR_RELEASE, MainApp.gs(R.string.not_eng_mode_or_release), Notification.URGENT); - RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); - if (callback != null) - callback.result(new PumpEnactResult().success(false).enacted(false).comment(MainApp.gs(R.string.not_eng_mode_or_release))).run(); - return false; - } - - // Compare with pump limits - Profile.ProfileValue[] basalValues = profile.getBasalValues(); - PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump(); - - for (Profile.ProfileValue basalValue : basalValues) { - if (basalValue.value < pump.getPumpDescription().basalMinimumRate) { - Notification notification = new Notification(Notification.BASAL_VALUE_BELOW_MINIMUM, MainApp.gs(R.string.basalvaluebelowminimum), Notification.URGENT); - RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); - if (callback != null) - callback.result(new PumpEnactResult().success(false).enacted(false).comment(MainApp.gs(R.string.basalvaluebelowminimum))).run(); - return false; - } - } - - RxBus.Companion.getINSTANCE().send(new EventDismissNotification(Notification.BASAL_VALUE_BELOW_MINIMUM)); - - // remove all unfinished - removeAll(Command.CommandType.BASALPROFILE); - - // add new command to queue - add(new CommandSetProfile(profile, callback)); - - notifyAboutNewCommand(); - - return true; - } - - // returns true if command is queued - public boolean readStatus(String reason, Callback callback) { - if (isLastScheduled(Command.CommandType.READSTATUS)) { - if (L.isEnabled(L.PUMPQUEUE)) - log.debug("READSTATUS " + reason + " ignored as duplicated"); - if (callback != null) - callback.result(executingNowError()).run(); - return false; - } - - // remove all unfinished - //removeAll(Command.CommandType.READSTATUS); - - // add new command to queue - add(new CommandReadStatus(reason, callback)); - - notifyAboutNewCommand(); - - return true; - } - - - public synchronized boolean statusInQueue() { - if (isRunning(Command.CommandType.READSTATUS)) - return true; - synchronized (queue) { - for (int i = 0; i < queue.size(); i++) { - if (queue.get(i).commandType == Command.CommandType.READSTATUS) { - return true; - } - } - } - return false; - } - - - // returns true if command is queued - public boolean loadHistory(byte type, Callback callback) { - if (isRunning(Command.CommandType.LOADHISTORY)) { - if (callback != null) - callback.result(executingNowError()).run(); - return false; - } - - // remove all unfinished - removeAll(Command.CommandType.LOADHISTORY); - - // add new command to queue - add(new CommandLoadHistory(type, callback)); - - notifyAboutNewCommand(); - - return true; - } - - // returns true if command is queued - public boolean setUserOptions(Callback callback) { - if (isRunning(Command.CommandType.SETUSERSETTINGS)) { - if (callback != null) - callback.result(executingNowError()).run(); - return false; - } - - // remove all unfinished - removeAll(Command.CommandType.SETUSERSETTINGS); - - // add new command to queue - add(new CommandSetUserSettings(callback)); - - notifyAboutNewCommand(); - - return true; - } - - // returns true if command is queued - public boolean loadTDDs(Callback callback) { - if (isRunning(Command.CommandType.LOADHISTORY)) { - if (callback != null) - callback.result(executingNowError()).run(); - return false; - } - - // remove all unfinished - removeAll(Command.CommandType.LOADHISTORY); - - // add new command to queue - add(new CommandLoadTDDs(callback)); - - notifyAboutNewCommand(); - - return true; - } - - // returns true if command is queued - public boolean loadEvents(Callback callback) { - if (isRunning(Command.CommandType.LOADEVENTS)) { - if (callback != null) - callback.result(executingNowError()).run(); - return false; - } - - // remove all unfinished - removeAll(Command.CommandType.LOADEVENTS); - - // add new command to queue - add(new CommandLoadEvents(callback)); - - notifyAboutNewCommand(); - - return true; - } - - public Spanned spannedStatus() { - String s = ""; - int line = 0; - Command perf = performing; - if (perf != null) { - s += "" + perf.status() + ""; - line++; - } - synchronized (queue) { - for (int i = 0; i < queue.size(); i++) { - if (line != 0) - s += "
"; - s += queue.get(i).status(); - line++; - } - } - return Html.fromHtml(s); - } - - public boolean isThisProfileSet(Profile profile) { - PumpInterface activePump = ConfigBuilderPlugin.getPlugin().getActivePump(); - Profile current = ProfileFunctions.getInstance().getProfile(); - if (activePump != null && current != null) { - boolean result = activePump.isThisProfileSet(profile); - if (!result) { - if (L.isEnabled(L.PUMPQUEUE)) { - log.debug("Current profile: " + current.toString()); - log.debug("New profile: " + profile.toString()); - } - } - return result; - } else return true; - } - - protected void showBolusProgressDialog(Double insulin, Context context) { - if (context != null) { - BolusProgressDialog bolusProgressDialog = new BolusProgressDialog(); - bolusProgressDialog.setInsulin(insulin); - bolusProgressDialog.show(((AppCompatActivity) context).getSupportFragmentManager(), "BolusProgress"); - } else { - Intent i = new Intent(); - i.putExtra("insulin", insulin); - i.setClass(MainApp.instance(), BolusProgressHelperActivity.class); - i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - MainApp.instance().startActivity(i); - } - } - -} diff --git a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt new file mode 100644 index 0000000000..1192d6ddcc --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt @@ -0,0 +1,495 @@ +package info.nightscout.androidaps.queue + +import android.content.Context +import android.content.Intent +import android.os.SystemClock +import android.text.Spanned +import androidx.appcompat.app.AppCompatActivity +import dagger.Lazy +import dagger.android.HasAndroidInjector +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.ActivePluginProvider +import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.Constraint +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.L +import info.nightscout.androidaps.logging.L.isEnabled +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +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 +import info.nightscout.androidaps.plugins.general.overview.notifications.Notification +import info.nightscout.androidaps.queue.commands.* +import info.nightscout.androidaps.queue.commands.Command.CommandType +import info.nightscout.androidaps.utils.HtmlHelper +import info.nightscout.androidaps.utils.resources.ResourceHelper +import java.util.* +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Created by mike on 08.11.2017. + * + * + * DATA FLOW: + * --------- + * + * + * (request) - > ConfigBuilder.getCommandQueue().bolus(...) + * + * + * app no longer waits for result but passes Callback + * + * + * request is added to queue, if another request of the same type already exists in queue, it's removed prior adding + * but if request of the same type is currently executed (probably important only for bolus which is running long time), new request is declined + * new QueueThread is created and started if current if finished + * CommandReadStatus is added automatically before command if queue is empty + * + * + * biggest change is we don't need exec pump commands in Handler because it's finished immediately + * command queueing if not realized by stacking in different Handlers and threads anymore but by internal queue with better control + * + * + * QueueThread calls ConfigBuilder#connect which is passed to getActivePump().connect + * connect should be executed on background and return immediately. afterwards isConnecting() is expected to be true + * + * + * while isConnecting() == true GUI is updated by posting connection progress + * + * + * if connect is successful: isConnected() becomes true, isConnecting() becomes false + * CommandQueue starts calling execute() of commands. execute() is expected to be blocking (return after finish). + * callback with result is called after finish automatically + * if connect failed: isConnected() becomes false, isConnecting() becomes false + * connect() is called again + * + * + * when queue is empty, disconnect is called + */ + +@Singleton +class CommandQueue @Inject constructor( + private val injector: HasAndroidInjector, + val aapsLogger: AAPSLogger, + val rxBus: RxBusWrapper, + val resourceHelper: ResourceHelper, + val constraintChecker: ConstraintChecker, + val profileFunction: ProfileFunction, + val activePlugin: Lazy, + val mainApp: MainApp +) : CommandQueueProvider { + + private val queue = LinkedList() + private var thread: QueueThread? = null + + var performing: Command? = null + + private fun executingNowError(): PumpEnactResult = + PumpEnactResult().success(false).enacted(false).comment(resourceHelper.gs(R.string.executingrightnow)) + + override fun isRunning(type: CommandType): Boolean = performing?.commandType == type + + @Synchronized + private fun removeAll(type: CommandType) { + synchronized(queue) { + for (i in queue.indices.reversed()) { + if (queue[i].commandType == type) { + queue.removeAt(i) + } + } + } + } + + @Suppress("SameParameterValue") + @Synchronized + private fun isLastScheduled(type: CommandType): Boolean { + synchronized(queue) { + if (queue.size > 0 && queue[queue.size - 1].commandType == type) { + return true + } + } + return false + } + + @Synchronized + private fun add(command: Command) { + aapsLogger.debug(LTag.PUMPQUEUE, "Adding: " + command.javaClass.simpleName + " - " + command.status()) + synchronized(queue) { queue.add(command) } + } + + @Synchronized + override fun pickup() { + synchronized(queue) { performing = queue.poll() } + } + + @Synchronized + override fun clear() { + performing = null + synchronized(queue) { + for (i in queue.indices) { + queue[i].cancel() + } + queue.clear() + } + } + + override fun size(): Int = queue.size + + override fun performing(): Command? = performing + + override fun resetPerforming() { + performing = null + } + + // After new command added to the queue + // start thread again if not already running + @Synchronized + private fun notifyAboutNewCommand() { + while (thread != null && thread!!.state != Thread.State.TERMINATED && thread!!.waitingForDisconnect) { + aapsLogger.debug(LTag.PUMPQUEUE, "Waiting for previous thread finish") + SystemClock.sleep(500) + } + if (thread == null || thread!!.state == Thread.State.TERMINATED) { + thread = QueueThread(this) + thread!!.start() + aapsLogger.debug(LTag.PUMPQUEUE, "Starting new thread") + } else { + aapsLogger.debug(LTag.PUMPQUEUE, "Thread is already running") + } + } + + override fun independentConnect(reason: String, callback: Callback?) { + aapsLogger.debug(LTag.PUMPQUEUE, "Starting new queue") + val tempCommandQueue = CommandQueue(injector, aapsLogger, rxBus, resourceHelper, constraintChecker, profileFunction, activePlugin, mainApp) + tempCommandQueue.readStatus(reason, callback) + } + + @Synchronized + override fun bolusInQueue(): Boolean { + if (isRunning(CommandType.BOLUS)) return true + synchronized(queue) { + for (i in queue.indices) { + if (queue[i].commandType == CommandType.BOLUS) { + return true + } + } + } + return false + } + + // returns true if command is queued + @Synchronized + override fun bolus(detailedBolusInfo: DetailedBolusInfo, callback: Callback?): Boolean { + var type = if (detailedBolusInfo.isSMB) CommandType.SMB_BOLUS else CommandType.BOLUS + if (type == CommandType.SMB_BOLUS) { + if (isRunning(CommandType.BOLUS) || isRunning(CommandType.SMB_BOLUS) || bolusInQueue()) { + aapsLogger.debug(LTag.PUMPQUEUE, "Rejecting SMB since a bolus is queue/running") + return false + } + if (detailedBolusInfo.lastKnownBolusTime < activePlugin.get().activeTreatments.lastBolusTime) { + aapsLogger.debug(LTag.PUMPQUEUE, "Rejecting bolus, another bolus was issued since request time") + return false + } + removeAll(CommandType.SMB_BOLUS) + } + if (type == CommandType.BOLUS && detailedBolusInfo.carbs > 0 && detailedBolusInfo.insulin == 0.0) { + type = CommandType.CARBS_ONLY_TREATMENT + //Carbs only can be added in parallel as they can be "in the future". + } else { + if (isRunning(type)) { + callback?.result(executingNowError())?.run() + return false + } + // remove all unfinished boluses + removeAll(type) + } + // apply constraints + detailedBolusInfo.insulin = constraintChecker.applyBolusConstraints(Constraint(detailedBolusInfo.insulin)).value() + detailedBolusInfo.carbs = constraintChecker.applyCarbsConstraints(Constraint(detailedBolusInfo.carbs.toInt())).value().toDouble() + // add new command to queue + if (detailedBolusInfo.isSMB) { + add(CommandSMBBolus(injector, detailedBolusInfo, callback)) + } else { + add(CommandBolus(injector, detailedBolusInfo, callback, type)) + if (type == CommandType.BOLUS) { // Bring up bolus progress dialog (start here, so the dialog is shown when the bolus is requested, +// not when the Bolus command is starting. The command closes the dialog upon completion). + showBolusProgressDialog(detailedBolusInfo.insulin, detailedBolusInfo.context) + // Notify Wear about upcoming bolus + rxBus.send(EventBolusRequested(detailedBolusInfo.insulin)) + } + } + notifyAboutNewCommand() + return true + } + + override fun stopPump(callback: Callback?) { + add(CommandStopPump(injector, callback)) + notifyAboutNewCommand() + } + + override fun startPump(callback: Callback?) { + add(CommandStartPump(injector, callback)) + notifyAboutNewCommand() + } + + override fun setTBROverNotification(callback: Callback?, enable: Boolean) { + add(CommandInsightSetTBROverNotification(injector, enable, callback)) + notifyAboutNewCommand() + } + + @Synchronized + override fun cancelAllBoluses() { + if (!isRunning(CommandType.BOLUS)) { + rxBus.send(EventDismissBolusProgressIfRunning(PumpEnactResult().success(true).enacted(false))) + } + removeAll(CommandType.BOLUS) + removeAll(CommandType.SMB_BOLUS) + Thread(Runnable { activePlugin.get().activePump.stopBolusDelivering() }).run() + } + + // returns true if command is queued + override fun tempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, enforceNew: Boolean, profile: Profile, callback: Callback?): Boolean { + if (!enforceNew && isRunning(CommandType.TEMPBASAL)) { + callback?.result(executingNowError())?.run() + return false + } + // remove all unfinished + removeAll(CommandType.TEMPBASAL) + val rateAfterConstraints = constraintChecker.applyBasalConstraints(Constraint(absoluteRate), profile).value() + // add new command to queue + add(CommandTempBasalAbsolute(injector, rateAfterConstraints, durationInMinutes, enforceNew, profile, callback)) + notifyAboutNewCommand() + return true + } + + // returns true if command is queued + override fun tempBasalPercent(percent: Int, durationInMinutes: Int, enforceNew: Boolean, profile: Profile, callback: Callback?): Boolean { + if (!enforceNew && isRunning(CommandType.TEMPBASAL)) { + callback?.result(executingNowError())?.run() + return false + } + // remove all unfinished + removeAll(CommandType.TEMPBASAL) + val percentAfterConstraints = constraintChecker.applyBasalPercentConstraints(Constraint(percent), profile).value() + // add new command to queue + add(CommandTempBasalPercent(injector, percentAfterConstraints, durationInMinutes, enforceNew, profile, callback)) + notifyAboutNewCommand() + return true + } + + // returns true if command is queued + override fun extendedBolus(insulin: Double, durationInMinutes: Int, callback: Callback?): Boolean { + if (isRunning(CommandType.EXTENDEDBOLUS)) { + callback?.result(executingNowError())?.run() + return false + } + val rateAfterConstraints = constraintChecker.applyExtendedBolusConstraints(Constraint(insulin)).value() + // remove all unfinished + removeAll(CommandType.EXTENDEDBOLUS) + // add new command to queue + add(CommandExtendedBolus(injector, rateAfterConstraints, durationInMinutes, callback)) + notifyAboutNewCommand() + return true + } + + // returns true if command is queued + override fun cancelTempBasal(enforceNew: Boolean, callback: Callback?): Boolean { + if (!enforceNew && isRunning(CommandType.TEMPBASAL)) { + callback?.result(executingNowError())?.run() + return false + } + // remove all unfinished + removeAll(CommandType.TEMPBASAL) + // add new command to queue + add(CommandCancelTempBasal(injector, enforceNew, callback)) + notifyAboutNewCommand() + return true + } + + // returns true if command is queued + override fun cancelExtended(callback: Callback?): Boolean { + if (isRunning(CommandType.EXTENDEDBOLUS)) { + callback?.result(executingNowError())?.run() + return false + } + // remove all unfinished + removeAll(CommandType.EXTENDEDBOLUS) + // add new command to queue + add(CommandCancelExtendedBolus(injector, callback)) + notifyAboutNewCommand() + return true + } + + // returns true if command is queued + override fun setProfile(profile: Profile, callback: Callback?): Boolean { + if (isThisProfileSet(profile)) { + aapsLogger.debug(LTag.PUMPQUEUE, "Correct profile already set") + callback?.result(PumpEnactResult().success(true).enacted(false))?.run() + return false + } + if (!MainApp.isEngineeringModeOrRelease()) { + val notification = Notification(Notification.NOT_ENG_MODE_OR_RELEASE, resourceHelper.gs(R.string.not_eng_mode_or_release), Notification.URGENT) + rxBus.send(EventNewNotification(notification)) + callback?.result(PumpEnactResult().success(false).enacted(false).comment(resourceHelper.gs(R.string.not_eng_mode_or_release)))?.run() + return false + } + // Compare with pump limits + val basalValues = profile.basalValues + for (basalValue in basalValues) { + if (basalValue.value < activePlugin.get().activePump.pumpDescription.basalMinimumRate) { + val notification = Notification(Notification.BASAL_VALUE_BELOW_MINIMUM, resourceHelper.gs(R.string.basalvaluebelowminimum), Notification.URGENT) + rxBus.send(EventNewNotification(notification)) + callback?.result(PumpEnactResult().success(false).enacted(false).comment(resourceHelper.gs(R.string.basalvaluebelowminimum)))?.run() + return false + } + } + rxBus.send(EventDismissNotification(Notification.BASAL_VALUE_BELOW_MINIMUM)) + // remove all unfinished + removeAll(CommandType.BASAL_PROFILE) + // add new command to queue + add(CommandSetProfile(injector, profile, callback)) + notifyAboutNewCommand() + return true + } + + // returns true if command is queued + override fun readStatus(reason: String, callback: Callback?): Boolean { + if (isLastScheduled(CommandType.READSTATUS)) { + aapsLogger.debug(LTag.PUMPQUEUE, "READSTATUS $reason ignored as duplicated") + callback?.result(executingNowError())?.run() + return false + } + + // add new command to queue + add(CommandReadStatus(injector, reason, callback)) + notifyAboutNewCommand() + return true + } + + @Synchronized + override fun statusInQueue(): Boolean { + if (isRunning(CommandType.READSTATUS)) return true + synchronized(queue) { + for (i in queue.indices) { + if (queue[i].commandType == CommandType.READSTATUS) { + return true + } + } + } + return false + } + + // returns true if command is queued + override fun loadHistory(type: Byte, callback: Callback?): Boolean { + if (isRunning(CommandType.LOAD_HISTORY)) { + callback?.result(executingNowError())?.run() + return false + } + // remove all unfinished + removeAll(CommandType.LOAD_HISTORY) + // add new command to queue + add(CommandLoadHistory(injector, type, callback)) + notifyAboutNewCommand() + return true + } + + // returns true if command is queued + override fun setUserOptions(callback: Callback?): Boolean { + if (isRunning(CommandType.SET_USER_SETTINGS)) { + callback?.result(executingNowError())?.run() + return false + } + // remove all unfinished + removeAll(CommandType.SET_USER_SETTINGS) + // add new command to queue + add(CommandSetUserSettings(injector, callback)) + notifyAboutNewCommand() + return true + } + + // returns true if command is queued + override fun loadTDDs(callback: Callback?): Boolean { + if (isRunning(CommandType.LOAD_HISTORY)) { + callback?.result(executingNowError())?.run() + return false + } + // remove all unfinished + removeAll(CommandType.LOAD_HISTORY) + // add new command to queue + add(CommandLoadTDDs(injector, callback)) + notifyAboutNewCommand() + return true + } + + // returns true if command is queued + override fun loadEvents(callback: Callback?): Boolean { + if (isRunning(CommandType.LOAD_EVENTS)) { + callback?.result(executingNowError())?.run() + return false + } + // remove all unfinished + removeAll(CommandType.LOAD_EVENTS) + // add new command to queue + add(CommandLoadEvents(injector, callback)) + notifyAboutNewCommand() + return true + } + + override fun spannedStatus(): Spanned { + var s = "" + var line = 0 + val perf = performing + if (perf != null) { + s += "" + perf.status() + "" + line++ + } + synchronized(queue) { + for (i in queue.indices) { + if (line != 0) s += "
" + s += queue[i].status() + line++ + } + } + return HtmlHelper.fromHtml(s) + } + + override fun isThisProfileSet(profile: Profile): Boolean { + val activePump = activePlugin.get().activePump + val current = profileFunction.getProfile() + return if (current != null) { + val result = activePump.isThisProfileSet(profile) + if (!result) { + if (isEnabled(L.PUMPQUEUE)) { + aapsLogger.debug(LTag.PUMPQUEUE, "Current profile: $current") + aapsLogger.debug(LTag.PUMPQUEUE, "New profile: $profile") + } + } + result + } else true + } + + private fun showBolusProgressDialog(insulin: Double, context: Context?) { + if (context != null) { + val bolusProgressDialog = BolusProgressDialog() + bolusProgressDialog.setInsulin(insulin) + bolusProgressDialog.show((context as AppCompatActivity).supportFragmentManager, "BolusProgress") + } else { + val i = Intent() + i.putExtra("insulin", insulin) + i.setClass(mainApp, BolusProgressHelperActivity::class.java) + i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + mainApp.startActivity(i) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/Command.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/Command.java deleted file mode 100644 index 97a7e68521..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/Command.java +++ /dev/null @@ -1,50 +0,0 @@ -package info.nightscout.androidaps.queue.commands; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.queue.Callback; - -/** - * Created by mike on 09.11.2017. - */ -public abstract class Command { - private Logger log = LoggerFactory.getLogger(L.PUMPQUEUE); - - public enum CommandType { - BOLUS, - SMB_BOLUS, - CARBS_ONLY_TREATMENT, - TEMPBASAL, - EXTENDEDBOLUS, - BASALPROFILE, - READSTATUS, - LOADHISTORY, // TDDs and so far only Dana specific - LOADEVENTS, // so far only Dana specific - SETUSERSETTINGS, // so far only Dana specific, - START_PUMP, - STOP_PUMP, - INSIGHT_SET_TBR_OVER_ALARM - } - - public CommandType commandType; - protected Callback callback; - - public abstract void execute(); - - public abstract String status(); - - public void cancel() { - PumpEnactResult result = new PumpEnactResult(); - result.success = false; - result.comment = MainApp.gs(R.string.connectiontimedout); - if (L.isEnabled(L.PUMPQUEUE)) - log.debug("Result cancel"); - if (callback != null) - callback.result(result).run(); - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/Command.kt b/app/src/main/java/info/nightscout/androidaps/queue/commands/Command.kt new file mode 100644 index 0000000000..b0d5558f67 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/Command.kt @@ -0,0 +1,51 @@ +package info.nightscout.androidaps.queue.commands + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.R +import info.nightscout.androidaps.data.PumpEnactResult +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.queue.Callback +import info.nightscout.androidaps.utils.resources.ResourceHelper +import javax.inject.Inject + +abstract class Command( + injector: HasAndroidInjector, + val commandType: CommandType, + val callback: Callback? = null +) { + + @Inject lateinit var aapsLogger: AAPSLogger + @Inject lateinit var resourceHelper: ResourceHelper + + enum class CommandType { + BOLUS, + SMB_BOLUS, + CARBS_ONLY_TREATMENT, + TEMPBASAL, + EXTENDEDBOLUS, + BASAL_PROFILE, + READSTATUS, + LOAD_HISTORY, // TDDs and so far only Dana specific + LOAD_EVENTS, // so far only Dana specific + SET_USER_SETTINGS, // so far only Dana specific, + START_PUMP, + STOP_PUMP, + INSIGHT_SET_TBR_OVER_ALARM // insight only + } + + init { + injector.androidInjector().inject(this) + } + + abstract fun execute() + abstract fun status(): String + + fun cancel() { + val result = PumpEnactResult() + result.success = false + result.comment = resourceHelper.gs(R.string.connectiontimedout) + aapsLogger.debug(LTag.PUMPQUEUE, "Result cancel") + callback?.result(result)?.run() + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandBolus.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandBolus.java deleted file mode 100644 index 55642f6e7b..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandBolus.java +++ /dev/null @@ -1,48 +0,0 @@ -package info.nightscout.androidaps.queue.commands; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import info.nightscout.androidaps.data.DetailedBolusInfo; -import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.bus.RxBus; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.dialogs.BolusProgressDialog; -import info.nightscout.androidaps.plugins.general.overview.events.EventDismissBolusProgressIfRunning; -import info.nightscout.androidaps.queue.Callback; -import info.nightscout.androidaps.utils.DecimalFormatter; - -/** - * Created by mike on 09.11.2017. - */ - -public class CommandBolus extends Command { - private Logger log = LoggerFactory.getLogger(L.PUMPQUEUE); - - private DetailedBolusInfo detailedBolusInfo; - - public CommandBolus(DetailedBolusInfo detailedBolusInfo, Callback callback, CommandType type) { - commandType = type; - this.detailedBolusInfo = detailedBolusInfo; - this.callback = callback; - } - - @Override - public void execute() { - PumpEnactResult r = ConfigBuilderPlugin.getPlugin().getActivePump().deliverTreatment(detailedBolusInfo); - - BolusProgressDialog.bolusEnded = true; - RxBus.Companion.getINSTANCE().send(new EventDismissBolusProgressIfRunning(r)); - if (L.isEnabled(L.PUMPQUEUE)) - log.debug("Result success: " + r.success + " enacted: " + r.enacted); - - if (callback != null) - callback.result(r).run(); - } - - public String status() { - return (detailedBolusInfo.insulin > 0 ? "BOLUS " + DecimalFormatter.to1Decimal(detailedBolusInfo.insulin) + "U " : "") + - (detailedBolusInfo.carbs > 0 ? "CARBS " + DecimalFormatter.to0Decimal(detailedBolusInfo.carbs) + "g" : "" ); - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandBolus.kt b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandBolus.kt new file mode 100644 index 0000000000..084eb12609 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandBolus.kt @@ -0,0 +1,36 @@ +package info.nightscout.androidaps.queue.commands + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.R +import info.nightscout.androidaps.data.DetailedBolusInfo +import info.nightscout.androidaps.dialogs.BolusProgressDialog +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.plugins.general.overview.events.EventDismissBolusProgressIfRunning +import info.nightscout.androidaps.queue.Callback +import javax.inject.Inject + +class CommandBolus( + injector: HasAndroidInjector, + private val detailedBolusInfo: DetailedBolusInfo, + callback: Callback?, + type: CommandType +) : Command(injector, type, callback) { + + @Inject lateinit var rxBus: RxBusWrapper + @Inject lateinit var activePlugin: ActivePluginProvider + + override fun execute() { + val r = activePlugin.activePump.deliverTreatment(detailedBolusInfo) + BolusProgressDialog.bolusEnded = true + rxBus.send(EventDismissBolusProgressIfRunning(r)) + aapsLogger.debug(LTag.PUMPQUEUE, "Result success: ${r.success} enacted: ${r.enacted}") + callback?.result(r)?.run() + } + + override fun status(): String { + return (if (detailedBolusInfo.insulin > 0) "BOLUS " + resourceHelper.gs(R.string.formatinsulinunits, detailedBolusInfo.insulin) else "") + + if (detailedBolusInfo.carbs > 0) "CARBS " + resourceHelper.gs(R.string.format_carbs, detailedBolusInfo.carbs.toInt()) else "" + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandCancelExtendedBolus.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandCancelExtendedBolus.java deleted file mode 100644 index 84ff1942a5..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandCancelExtendedBolus.java +++ /dev/null @@ -1,36 +0,0 @@ -package info.nightscout.androidaps.queue.commands; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.queue.Callback; - -/** - * Created by mike on 09.11.2017. - */ - -public class CommandCancelExtendedBolus extends Command { - private Logger log = LoggerFactory.getLogger(L.PUMPQUEUE); - - public CommandCancelExtendedBolus(Callback callback) { - commandType = CommandType.EXTENDEDBOLUS; - this.callback = callback; - } - - @Override - public void execute() { - PumpEnactResult r = ConfigBuilderPlugin.getPlugin().getActivePump().cancelExtendedBolus(); - if (L.isEnabled(L.PUMPQUEUE)) - log.debug("Result success: " + r.success + " enacted: " + r.enacted); - if (callback != null) - callback.result(r).run(); - } - - @Override - public String status() { - return "CANCEL EXTENDEDBOLUS"; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandCancelExtendedBolus.kt b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandCancelExtendedBolus.kt new file mode 100644 index 0000000000..40f9dfb972 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandCancelExtendedBolus.kt @@ -0,0 +1,23 @@ +package info.nightscout.androidaps.queue.commands + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.queue.Callback +import javax.inject.Inject + +class CommandCancelExtendedBolus constructor( + injector: HasAndroidInjector, + callback: Callback? +) : Command(injector, CommandType.EXTENDEDBOLUS, callback) { + + @Inject lateinit var activePlugin: ActivePluginProvider + + override fun execute() { + val r = activePlugin.activePump.cancelExtendedBolus() + aapsLogger.debug(LTag.PUMPQUEUE, "Result success: ${r.success} enacted: ${r.enacted}") + callback?.result(r)?.run() + } + + override fun status(): String = "CANCEL EXTENDEDBOLUS" +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandCancelTempBasal.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandCancelTempBasal.java deleted file mode 100644 index d6ef30ed36..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandCancelTempBasal.java +++ /dev/null @@ -1,39 +0,0 @@ -package info.nightscout.androidaps.queue.commands; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.queue.Callback; - -/** - * Created by mike on 09.11.2017. - */ - -public class CommandCancelTempBasal extends Command { - private Logger log = LoggerFactory.getLogger(L.PUMPQUEUE); - - private boolean enforceNew; - - public CommandCancelTempBasal(boolean enforceNew, Callback callback) { - commandType = CommandType.TEMPBASAL; - this.enforceNew = enforceNew; - this.callback = callback; - } - - @Override - public void execute() { - PumpEnactResult r = ConfigBuilderPlugin.getPlugin().getActivePump().cancelTempBasal(enforceNew); - if (L.isEnabled(L.PUMPQUEUE)) - log.debug("Result success: " + r.success + " enacted: " + r.enacted); - if (callback != null) - callback.result(r).run(); - } - - @Override - public String status() { - return "CANCEL TEMPBASAL"; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandCancelTempBasal.kt b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandCancelTempBasal.kt new file mode 100644 index 0000000000..ff7182df9a --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandCancelTempBasal.kt @@ -0,0 +1,24 @@ +package info.nightscout.androidaps.queue.commands + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.queue.Callback +import javax.inject.Inject + +class CommandCancelTempBasal( + injector: HasAndroidInjector, + private val enforceNew: Boolean, + callback: Callback? +) : Command(injector, CommandType.TEMPBASAL, callback) { + + @Inject lateinit var activePlugin: ActivePluginProvider + + override fun execute() { + val r = activePlugin.activePump.cancelTempBasal(enforceNew) + aapsLogger.debug(LTag.PUMPQUEUE, "Result success: ${r.success} enacted: ${r.enacted}") + callback?.result(r)?.run() + } + + override fun status(): String = "CANCEL TEMPBASAL" +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandExtendedBolus.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandExtendedBolus.java deleted file mode 100644 index 7609973cf0..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandExtendedBolus.java +++ /dev/null @@ -1,41 +0,0 @@ -package info.nightscout.androidaps.queue.commands; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.queue.Callback; - -/** - * Created by mike on 09.11.2017. - */ - -public class CommandExtendedBolus extends Command { - private Logger log = LoggerFactory.getLogger(L.PUMPQUEUE); - - private double insulin; - private int durationInMinutes; - - public CommandExtendedBolus(double insulin, int durationInMinutes, Callback callback) { - commandType = CommandType.EXTENDEDBOLUS; - this.insulin = insulin; - this.durationInMinutes = durationInMinutes; - this.callback = callback; - } - - @Override - public void execute() { - PumpEnactResult r = ConfigBuilderPlugin.getPlugin().getActivePump().setExtendedBolus(insulin, durationInMinutes); - if (L.isEnabled(L.PUMPQUEUE)) - log.debug("Result rate: " + insulin + " durationInMinutes: " + durationInMinutes + " success: " + r.success + " enacted: " + r.enacted); - if (callback != null) - callback.result(r).run(); - } - - @Override - public String status() { - return "EXTENDEDBOLUS " + insulin + " U " + durationInMinutes + " min"; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandExtendedBolus.kt b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandExtendedBolus.kt new file mode 100644 index 0000000000..2e81520ee4 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandExtendedBolus.kt @@ -0,0 +1,25 @@ +package info.nightscout.androidaps.queue.commands + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.queue.Callback +import javax.inject.Inject + +class CommandExtendedBolus constructor( + injector: HasAndroidInjector, + private val insulin: Double, + private val durationInMinutes: Int, + callback: Callback? +) : Command(injector, CommandType.EXTENDEDBOLUS, callback) { + + @Inject lateinit var activePlugin: ActivePluginProvider + + override fun execute() { + val r = activePlugin.activePump.setExtendedBolus(insulin, durationInMinutes) + aapsLogger.debug(LTag.PUMPQUEUE, "Result rate: $insulin durationInMinutes: $durationInMinutes success: ${r.success} enacted: ${r.enacted}") + callback?.result(r)?.run() + } + + override fun status(): String = "EXTENDEDBOLUS $insulin U $durationInMinutes min" +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandInsightSetTBROverNotification.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandInsightSetTBROverNotification.java deleted file mode 100644 index e65aa31a29..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandInsightSetTBROverNotification.java +++ /dev/null @@ -1,32 +0,0 @@ -package info.nightscout.androidaps.queue.commands; - -import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.interfaces.PumpInterface; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin; -import info.nightscout.androidaps.queue.Callback; - -public class CommandInsightSetTBROverNotification extends Command { - - private boolean enabled; - - public CommandInsightSetTBROverNotification(Callback callback, boolean enabled) { - commandType = CommandType.INSIGHT_SET_TBR_OVER_ALARM; - this.callback = callback; - this.enabled = enabled; - } - - @Override - public void execute() { - PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump(); - if (pump instanceof LocalInsightPlugin) { - PumpEnactResult result = ((LocalInsightPlugin) pump).setTBROverNotification(enabled); - if (callback != null) callback.result(result).run(); - } - } - - @Override - public String status() { - return "INSIGHTSETTBROVERNOTIFICATION"; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandInsightSetTBROverNotification.kt b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandInsightSetTBROverNotification.kt new file mode 100644 index 0000000000..7cf02fed74 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandInsightSetTBROverNotification.kt @@ -0,0 +1,27 @@ +package info.nightscout.androidaps.queue.commands + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin +import info.nightscout.androidaps.queue.Callback +import javax.inject.Inject + +class CommandInsightSetTBROverNotification constructor( + injector: HasAndroidInjector, + private val enabled: Boolean, + callback: Callback? +) : Command(injector, CommandType.INSIGHT_SET_TBR_OVER_ALARM, callback) { + + @Inject lateinit var activePlugin: ActivePluginProvider + + override fun execute() { + val pump = activePlugin.activePump + if (pump is LocalInsightPlugin) { + val result = pump.setTBROverNotification(enabled) + callback?.result(result)?.run() + } + } + + @Suppress("SpellCheckingInspection") + override fun status(): String = "INSIGHTSETTBROVERNOTIFICATION" +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadEvents.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadEvents.java deleted file mode 100644 index 30791a1831..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadEvents.java +++ /dev/null @@ -1,42 +0,0 @@ -package info.nightscout.androidaps.queue.commands; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.interfaces.DanaRInterface; -import info.nightscout.androidaps.interfaces.PumpInterface; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.queue.Callback; - -/** - * Created by mike on 10.11.2017. - */ - -public class CommandLoadEvents extends Command { - private Logger log = LoggerFactory.getLogger(L.PUMPQUEUE); - - public CommandLoadEvents(Callback callback) { - commandType = CommandType.LOADEVENTS; - this.callback = callback; - } - - @Override - public void execute() { - PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump(); - if (pump instanceof DanaRInterface) { - DanaRInterface danaPump = (DanaRInterface) pump; - PumpEnactResult r = danaPump.loadEvents(); - if (L.isEnabled(L.PUMPQUEUE)) - log.debug("Result success: " + r.success + " enacted: " + r.enacted); - if (callback != null) - callback.result(r).run(); - } - } - - @Override - public String status() { - return "LOADEVENTS"; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadEvents.kt b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadEvents.kt new file mode 100644 index 0000000000..7f09441ecc --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadEvents.kt @@ -0,0 +1,28 @@ +package info.nightscout.androidaps.queue.commands + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.interfaces.DanaRInterface +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.queue.Callback +import javax.inject.Inject + +class CommandLoadEvents( + injector: HasAndroidInjector, + callback: Callback? +) : Command(injector, CommandType.LOAD_EVENTS, callback) { + + @Inject lateinit var activePlugin: ActivePluginProvider + + override fun execute() { + val pump = activePlugin.activePump + if (pump is DanaRInterface) { + val danaPump = pump as DanaRInterface + val r = danaPump.loadEvents() + aapsLogger.debug(LTag.PUMPQUEUE, "Result success: ${r.success} enacted: ${r.enacted}") + callback?.result(r)?.run() + } + } + + override fun status(): String = "LOAD EVENTS" +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadHistory.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadHistory.java deleted file mode 100644 index fc6fd49d8f..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadHistory.java +++ /dev/null @@ -1,45 +0,0 @@ -package info.nightscout.androidaps.queue.commands; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.interfaces.DanaRInterface; -import info.nightscout.androidaps.interfaces.PumpInterface; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.queue.Callback; - -/** - * Created by mike on 10.11.2017. - */ - -public class CommandLoadHistory extends Command { - private Logger log = LoggerFactory.getLogger(L.PUMPQUEUE); - - private byte type; - - public CommandLoadHistory(byte type, Callback callback) { - commandType = CommandType.LOADHISTORY; - this.type = type; - this.callback = callback; - } - - @Override - public void execute() { - PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump(); - if (pump instanceof DanaRInterface) { - DanaRInterface danaPump = (DanaRInterface) pump; - PumpEnactResult r = danaPump.loadHistory(type); - if (L.isEnabled(L.PUMPQUEUE)) - log.debug("Result success: " + r.success + " enacted: " + r.enacted); - if (callback != null) - callback.result(r).run(); - } - } - - @Override - public String status() { - return "LOADHISTORY " + type; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadHistory.kt b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadHistory.kt new file mode 100644 index 0000000000..fb7f455ed4 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadHistory.kt @@ -0,0 +1,29 @@ +package info.nightscout.androidaps.queue.commands + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.interfaces.DanaRInterface +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.queue.Callback +import javax.inject.Inject + +class CommandLoadHistory( + injector: HasAndroidInjector, + private val type: Byte, + callback: Callback? +) : Command(injector, CommandType.LOAD_HISTORY, callback) { + + @Inject lateinit var activePlugin: ActivePluginProvider + + override fun execute() { + val pump = activePlugin.activePump + if (pump is DanaRInterface) { + val danaPump = pump as DanaRInterface + val r = danaPump.loadHistory(type) + aapsLogger.debug(LTag.PUMPQUEUE, "Result success: " + r.success + " enacted: " + r.enacted) + callback?.result(r)?.run() + } + } + + override fun status(): String = "LOAD HISTORY $type" +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadTDDs.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadTDDs.java deleted file mode 100644 index e70b5f2261..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadTDDs.java +++ /dev/null @@ -1,39 +0,0 @@ -package info.nightscout.androidaps.queue.commands; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.interfaces.PumpInterface; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.queue.Callback; - -/** - * Created by mike on 10.11.2017. - */ - -public class CommandLoadTDDs extends Command { - private Logger log = LoggerFactory.getLogger(L.PUMPQUEUE); - - - public CommandLoadTDDs(Callback callback) { - commandType = CommandType.LOADHISTORY; //belongs to the history group of commands - this.callback = callback; - } - - @Override - public void execute() { - PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump(); - PumpEnactResult r = pump.loadTDDs(); - if (L.isEnabled(L.PUMPQUEUE)) - log.debug("Result success: " + r.success + " enacted: " + r.enacted); - if (callback != null) - callback.result(r).run(); - } - - @Override - public String status() { - return "LOADTDDS"; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadTDDs.kt b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadTDDs.kt new file mode 100644 index 0000000000..96f1834c35 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadTDDs.kt @@ -0,0 +1,24 @@ +package info.nightscout.androidaps.queue.commands + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.queue.Callback +import javax.inject.Inject + +class CommandLoadTDDs( + injector: HasAndroidInjector, + callback: Callback? +) : Command(injector, CommandType.LOAD_HISTORY, callback) { + + @Inject lateinit var activePlugin: ActivePluginProvider + + override fun execute() { + val pump = activePlugin.activePump + val r = pump.loadTDDs() + aapsLogger.debug(LTag.PUMPQUEUE, "Result success: " + r.success + " enacted: " + r.enacted) + callback?.result(r)?.run() + } + + override fun status(): String = "LOAD TDDs" +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandReadStatus.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandReadStatus.java deleted file mode 100644 index 070aec809e..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandReadStatus.java +++ /dev/null @@ -1,50 +0,0 @@ -package info.nightscout.androidaps.queue.commands; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.interfaces.PumpInterface; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.queue.Callback; -import info.nightscout.androidaps.utils.LocalAlertUtils; -import info.nightscout.androidaps.utils.T; - -/** - * Created by mike on 09.11.2017. - */ - -public class CommandReadStatus extends Command { - private Logger log = LoggerFactory.getLogger(L.PUMPQUEUE); - - private String reason; - - public CommandReadStatus(String reason, Callback callback) { - commandType = CommandType.READSTATUS; - this.reason = reason; - this.callback = callback; - } - - @Override - public void execute() { - ConfigBuilderPlugin.getPlugin().getActivePump().getPumpStatus(); - LocalAlertUtils.notifyPumpStatusRead(); - if (L.isEnabled(L.PUMPQUEUE)) - log.debug("CommandReadStatus executed. Reason: " + reason); - final PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump(); - PumpEnactResult result = new PumpEnactResult().success(false); - if (pump != null) { - long lastConnection = pump.lastDataTime(); - if (lastConnection > System.currentTimeMillis() - T.mins(1).msecs()) - result.success(true); - } - if (callback != null) - callback.result(result).run(); - } - - @Override - public String status() { - return "READSTATUS " + reason; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandReadStatus.kt b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandReadStatus.kt new file mode 100644 index 0000000000..f4b9dd59cf --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandReadStatus.kt @@ -0,0 +1,33 @@ +package info.nightscout.androidaps.queue.commands + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.data.PumpEnactResult +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.queue.Callback +import info.nightscout.androidaps.utils.LocalAlertUtils +import info.nightscout.androidaps.utils.T +import javax.inject.Inject + +class CommandReadStatus( + injector: HasAndroidInjector, + private val reason: String, + callback: Callback? +) : Command(injector, CommandType.READSTATUS, callback) { + + @Inject lateinit var activePlugin: ActivePluginProvider + @Inject lateinit var localAlertUtils: LocalAlertUtils + + override fun execute() { + activePlugin.activePump.getPumpStatus() + localAlertUtils.notifyPumpStatusRead() + aapsLogger.debug(LTag.PUMPQUEUE, "CommandReadStatus executed. Reason: $reason") + val pump = activePlugin.activePump + val result = PumpEnactResult().success(false) + val lastConnection = pump.lastDataTime() + if (lastConnection > System.currentTimeMillis() - T.mins(1).msecs()) result.success(true) + callback?.result(result)?.run() + } + + override fun status(): String = "READSTATUS $reason" +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.java deleted file mode 100644 index 4586389dc1..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.java +++ /dev/null @@ -1,57 +0,0 @@ -package info.nightscout.androidaps.queue.commands; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import info.nightscout.androidaps.data.DetailedBolusInfo; -import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; -import info.nightscout.androidaps.queue.Callback; -import info.nightscout.androidaps.utils.DateUtil; -import info.nightscout.androidaps.utils.DecimalFormatter; -import info.nightscout.androidaps.utils.T; - -/** - * Created by mike on 09.11.2017. - */ - -public class CommandSMBBolus extends Command { - private Logger log = LoggerFactory.getLogger(L.PUMPQUEUE); - - private DetailedBolusInfo detailedBolusInfo; - - public CommandSMBBolus(DetailedBolusInfo detailedBolusInfo, Callback callback) { - commandType = CommandType.SMB_BOLUS; - this.detailedBolusInfo = detailedBolusInfo; - this.callback = callback; - } - - @Override - public void execute() { - PumpEnactResult r; - long lastBolusTime = TreatmentsPlugin.getPlugin().getLastBolusTime(); - if (lastBolusTime != 0 && lastBolusTime + T.mins(3).msecs() > DateUtil.now()) { - if (L.isEnabled(L.PUMPQUEUE)) - log.debug("SMB requsted but still in 3 min interval"); - r = new PumpEnactResult().enacted(false).success(false).comment("SMB requsted but still in 3 min interval"); - } else if (detailedBolusInfo.deliverAt != 0 && detailedBolusInfo.deliverAt + T.mins(1).msecs() > System.currentTimeMillis()) { - r = ConfigBuilderPlugin.getPlugin().getActivePump().deliverTreatment(detailedBolusInfo); - } else { - r = new PumpEnactResult().enacted(false).success(false).comment("SMB request too old"); - if (L.isEnabled(L.PUMPQUEUE)) - log.debug("SMB bolus canceled. delivetAt: " + DateUtil.dateAndTimeString(detailedBolusInfo.deliverAt)); - } - - if (L.isEnabled(L.PUMPQUEUE)) - log.debug("Result success: " + r.success + " enacted: " + r.enacted); - - if (callback != null) - callback.result(r).run(); - } - - public String status() { - return "SMBBOLUS " + DecimalFormatter.to2Decimal(detailedBolusInfo.insulin) + "U"; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.kt b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.kt new file mode 100644 index 0000000000..098244cc61 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.kt @@ -0,0 +1,39 @@ +package info.nightscout.androidaps.queue.commands + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.R +import info.nightscout.androidaps.data.DetailedBolusInfo +import info.nightscout.androidaps.data.PumpEnactResult +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.queue.Callback +import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.androidaps.utils.T +import javax.inject.Inject + +class CommandSMBBolus( + injector: HasAndroidInjector, + private val detailedBolusInfo: DetailedBolusInfo, + callback: Callback? +) : Command(injector, CommandType.SMB_BOLUS, callback) { + + @Inject lateinit var activePlugin: ActivePluginProvider + + override fun execute() { + val r: PumpEnactResult + val lastBolusTime = activePlugin.activeTreatments.lastBolusTime + if (lastBolusTime != 0L && lastBolusTime + T.mins(3).msecs() > DateUtil.now()) { + aapsLogger.debug(LTag.PUMPQUEUE, "SMB requested but still in 3 min interval") + r = PumpEnactResult().enacted(false).success(false).comment("SMB requested but still in 3 min interval") + } else if (detailedBolusInfo.deliverAt != 0L && detailedBolusInfo.deliverAt + T.mins(1).msecs() > System.currentTimeMillis()) { + r = activePlugin.activePump.deliverTreatment(detailedBolusInfo) + } else { + r = PumpEnactResult().enacted(false).success(false).comment("SMB request too old") + aapsLogger.debug(LTag.PUMPQUEUE, "SMB bolus canceled. deliverAt: " + DateUtil.dateAndTimeString(detailedBolusInfo.deliverAt)) + } + aapsLogger.debug(LTag.PUMPQUEUE, "Result success: ${r.success} enacted: ${r.enacted}") + callback?.result(r)?.run() + } + + override fun status(): String = "SMB BOLUS ${resourceHelper.gs(R.string.formatinsulinunits, detailedBolusInfo.insulin)}" +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetProfile.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetProfile.java deleted file mode 100644 index 49acf3e2a9..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetProfile.java +++ /dev/null @@ -1,69 +0,0 @@ -package info.nightscout.androidaps.queue.commands; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.inject.Inject; - -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.Profile; -import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.db.ProfileSwitch; -import info.nightscout.androidaps.db.Source; -import info.nightscout.androidaps.interfaces.PluginType; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin; -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; -import info.nightscout.androidaps.queue.Callback; - -/** - * Created by mike on 09.11.2017. - */ - -public class CommandSetProfile extends Command { - private Logger log = LoggerFactory.getLogger(L.PUMPQUEUE); - - private Profile profile; - - @Inject - SmsCommunicatorPlugin smsCommunicatorPlugin; - - public CommandSetProfile(Profile profile, Callback callback) { - commandType = CommandType.BASALPROFILE; - this.profile = profile; - this.callback = callback; - MainApp.instance().androidInjector().inject(this); // TODO: Inject via constructor - } - - @Override - public void execute() { - if (ConfigBuilderPlugin.getPlugin().getCommandQueue().isThisProfileSet(profile)) { - if (L.isEnabled(L.PUMPQUEUE)) - log.debug("Correct profile already set. profile: " + profile.toString()); - if (callback != null) - callback.result(new PumpEnactResult().success(true).enacted(false)).run(); - return; - } - - PumpEnactResult r = ConfigBuilderPlugin.getPlugin().getActivePump().setNewBasalProfile(profile); - if (L.isEnabled(L.PUMPQUEUE)) - log.debug("Result success: " + r.success + " enacted: " + r.enacted + " profile: " + profile.toString()); - if (callback != null) - callback.result(r).run(); - - // Send SMS notification if ProfileSwitch is comming from NS - ProfileSwitch profileSwitch = TreatmentsPlugin.getPlugin().getProfileSwitchFromHistory(System.currentTimeMillis()); - if (profileSwitch != null && r.enacted && profileSwitch.source == Source.NIGHTSCOUT) { - if (smsCommunicatorPlugin.isEnabled(PluginType.GENERAL)) { - smsCommunicatorPlugin.sendNotificationToAllNumbers(MainApp.gs(R.string.profile_set_ok)); - } - } - } - - @Override - public String status() { - return "SETPROFILE"; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetProfile.kt b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetProfile.kt new file mode 100644 index 0000000000..75f8d60369 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetProfile.kt @@ -0,0 +1,45 @@ +package info.nightscout.androidaps.queue.commands + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.R +import info.nightscout.androidaps.data.Profile +import info.nightscout.androidaps.data.PumpEnactResult +import info.nightscout.androidaps.db.Source +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.PluginType +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin +import info.nightscout.androidaps.queue.Callback +import javax.inject.Inject + +class CommandSetProfile constructor( + injector: HasAndroidInjector, + private val profile: Profile, + callback: Callback? +) : Command(injector, CommandType.BASAL_PROFILE, callback) { + + @Inject lateinit var smsCommunicatorPlugin: SmsCommunicatorPlugin + @Inject lateinit var activePlugin: ActivePluginProvider + @Inject lateinit var commandQueue: CommandQueueProvider + + override fun execute() { + if (commandQueue.isThisProfileSet(profile)) { + aapsLogger.debug(LTag.PUMPQUEUE, "Correct profile already set. profile: $profile") + callback?.result(PumpEnactResult().success(true).enacted(false))?.run() + return + } + val r = activePlugin.activePump.setNewBasalProfile(profile) + aapsLogger.debug(LTag.PUMPQUEUE, "Result success: ${r.success} enacted: ${r.enacted} profile: $profile") + callback?.result(r)?.run() + // Send SMS notification if ProfileSwitch is coming from NS + val profileSwitch = activePlugin.activeTreatments.getProfileSwitchFromHistory(System.currentTimeMillis()) + if (profileSwitch != null && r.enacted && profileSwitch.source == Source.NIGHTSCOUT) { + if (smsCommunicatorPlugin.isEnabled(PluginType.GENERAL)) { + smsCommunicatorPlugin.sendNotificationToAllNumbers(resourceHelper.gs(R.string.profile_set_ok)) + } + } + } + + override fun status(): String = "SET PROFILE" +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetUserSettings.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetUserSettings.java deleted file mode 100644 index 643dbed3ab..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetUserSettings.java +++ /dev/null @@ -1,42 +0,0 @@ -package info.nightscout.androidaps.queue.commands; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.interfaces.DanaRInterface; -import info.nightscout.androidaps.interfaces.PumpInterface; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.queue.Callback; - -/** - * Created by mike on 10.11.2017. - */ - -public class CommandSetUserSettings extends Command { - private Logger log = LoggerFactory.getLogger(L.PUMPQUEUE); - - public CommandSetUserSettings(Callback callback) { - commandType = CommandType.SETUSERSETTINGS; - this.callback = callback; - } - - @Override - public void execute() { - PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump(); - if (pump instanceof DanaRInterface) { - DanaRInterface danaPump = (DanaRInterface) pump; - PumpEnactResult r = danaPump.setUserOptions(); - if (L.isEnabled(L.PUMPQUEUE)) - log.debug("Result success: " + r.success + " enacted: " + r.enacted); - if (callback != null) - callback.result(r).run(); - } - } - - @Override - public String status() { - return "SETUSERSETTINGS"; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetUserSettings.kt b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetUserSettings.kt new file mode 100644 index 0000000000..c63d32fc1c --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetUserSettings.kt @@ -0,0 +1,27 @@ +package info.nightscout.androidaps.queue.commands + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.interfaces.DanaRInterface +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.queue.Callback +import javax.inject.Inject + +class CommandSetUserSettings( + injector: HasAndroidInjector, + callback: Callback? +) : Command(injector, CommandType.SET_USER_SETTINGS, callback) { + + @Inject lateinit var activePlugin: ActivePluginProvider + + override fun execute() { + val pump = activePlugin.activePump + if (pump is DanaRInterface) { + val r = pump.setUserOptions() + aapsLogger.debug(LTag.PUMPQUEUE, "Result success: ${r.success} enacted: ${r.enacted}") + callback?.result(r)?.run() + } + } + + override fun status(): String = "SET USER SETTINGS" +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandStartPump.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandStartPump.java deleted file mode 100644 index 24694a1778..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandStartPump.java +++ /dev/null @@ -1,29 +0,0 @@ -package info.nightscout.androidaps.queue.commands; - -import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.interfaces.PumpInterface; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin; -import info.nightscout.androidaps.queue.Callback; - -public class CommandStartPump extends Command { - - public CommandStartPump(Callback callback) { - commandType = CommandType.START_PUMP; - this.callback = callback; - } - - @Override - public void execute() { - PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump(); - if (pump instanceof LocalInsightPlugin) { - PumpEnactResult result = ((LocalInsightPlugin) pump).startPump(); - if (callback != null) callback.result(result).run(); - } - } - - @Override - public String status() { - return "STARTPUMP"; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandStartPump.kt b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandStartPump.kt new file mode 100644 index 0000000000..da911775bf --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandStartPump.kt @@ -0,0 +1,25 @@ +package info.nightscout.androidaps.queue.commands + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin +import info.nightscout.androidaps.queue.Callback +import javax.inject.Inject + +class CommandStartPump( + injector: HasAndroidInjector, + callback: Callback? +) : Command(injector, CommandType.START_PUMP, callback) { + + @Inject lateinit var activePlugin: ActivePluginProvider + + override fun execute() { + val pump = activePlugin.activePump + if (pump is LocalInsightPlugin) { + val result = pump.startPump() + callback?.result(result)?.run() + } + } + + override fun status(): String = "START PUMP" +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandStopPump.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandStopPump.java deleted file mode 100644 index 6f1cd8ec77..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandStopPump.java +++ /dev/null @@ -1,29 +0,0 @@ -package info.nightscout.androidaps.queue.commands; - -import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.interfaces.PumpInterface; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin; -import info.nightscout.androidaps.queue.Callback; - -public class CommandStopPump extends Command { - - public CommandStopPump(Callback callback) { - commandType = CommandType.STOP_PUMP; - this.callback = callback; - } - - @Override - public void execute() { - PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump(); - if (pump instanceof LocalInsightPlugin) { - PumpEnactResult result = ((LocalInsightPlugin) pump).stopPump(); - if (callback != null) callback.result(result).run(); - } - } - - @Override - public String status() { - return "STOPPUMP"; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandStopPump.kt b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandStopPump.kt new file mode 100644 index 0000000000..1f0390e97f --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandStopPump.kt @@ -0,0 +1,25 @@ +package info.nightscout.androidaps.queue.commands + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin +import info.nightscout.androidaps.queue.Callback +import javax.inject.Inject + +class CommandStopPump( + injector: HasAndroidInjector, + callback: Callback? +) : Command(injector, CommandType.STOP_PUMP, callback) { + + @Inject lateinit var activePlugin: ActivePluginProvider + + override fun execute() { + val pump = activePlugin.activePump + if (pump is LocalInsightPlugin) { + val result = pump.stopPump() + callback?.result(result)?.run() + } + } + + override fun status(): String = "STOP PUMP" +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalAbsolute.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalAbsolute.java deleted file mode 100644 index 1e36a1ab04..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalAbsolute.java +++ /dev/null @@ -1,46 +0,0 @@ -package info.nightscout.androidaps.queue.commands; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import info.nightscout.androidaps.data.Profile; -import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.queue.Callback; - -/** - * Created by mike on 09.11.2017. - */ - -public class CommandTempBasalAbsolute extends Command { - private Logger log = LoggerFactory.getLogger(L.PUMPQUEUE); - - private int durationInMinutes; - private double absoluteRate; - private boolean enforceNew; - private Profile profile; - - public CommandTempBasalAbsolute(double absoluteRate, int durationInMinutes, boolean enforceNew, Profile profile, Callback callback) { - commandType = CommandType.TEMPBASAL; - this.absoluteRate = absoluteRate; - this.durationInMinutes = durationInMinutes; - this.enforceNew = enforceNew; - this.profile = profile; - this.callback = callback; - } - - @Override - public void execute() { - PumpEnactResult r = ConfigBuilderPlugin.getPlugin().getActivePump().setTempBasalAbsolute(absoluteRate, durationInMinutes, profile, enforceNew); - if (L.isEnabled(L.PUMPQUEUE)) - log.debug("Result rate: " + absoluteRate + " durationInMinutes: " + durationInMinutes + " success: " + r.success + " enacted: " + r.enacted); - if (callback != null) - callback.result(r).run(); - } - - @Override - public String status() { - return "TEMPBASAL " + absoluteRate + " U/h " + durationInMinutes + " min"; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalAbsolute.kt b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalAbsolute.kt new file mode 100644 index 0000000000..488aa3bb7f --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalAbsolute.kt @@ -0,0 +1,28 @@ +package info.nightscout.androidaps.queue.commands + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.data.Profile +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.queue.Callback +import javax.inject.Inject + +class CommandTempBasalAbsolute( + injector: HasAndroidInjector, + private val absoluteRate: Double, + private val durationInMinutes: Int, + private val enforceNew: Boolean, + private val profile: Profile, + callback: Callback? +) : Command(injector, CommandType.TEMPBASAL, callback) { + + @Inject lateinit var activePlugin: ActivePluginProvider + + override fun execute() { + val r = activePlugin.activePump.setTempBasalAbsolute(absoluteRate, durationInMinutes, profile, enforceNew) + aapsLogger.debug(LTag.PUMPQUEUE, "Result rate: $absoluteRate durationInMinutes: $durationInMinutes success: ${r.success} enacted: ${r.enacted}") + callback?.result(r)?.run() + } + + override fun status(): String = "TEMP BASAL $absoluteRate U/h $durationInMinutes min" +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalPercent.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalPercent.java deleted file mode 100644 index 68da3b9865..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalPercent.java +++ /dev/null @@ -1,46 +0,0 @@ -package info.nightscout.androidaps.queue.commands; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import info.nightscout.androidaps.data.Profile; -import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.queue.Callback; - -/** - * Created by mike on 09.11.2017. - */ - -public class CommandTempBasalPercent extends Command { - private Logger log = LoggerFactory.getLogger(L.PUMPQUEUE); - - private int durationInMinutes; - private int percent; - private boolean enforceNew; - private Profile profile; - - public CommandTempBasalPercent(int percent, int durationInMinutes, boolean enforceNew, Profile profile, Callback callback) { - commandType = CommandType.TEMPBASAL; - this.percent = percent; - this.durationInMinutes = durationInMinutes; - this.enforceNew = enforceNew; - this.profile = profile; - this.callback = callback; - } - - @Override - public void execute() { - PumpEnactResult r = ConfigBuilderPlugin.getPlugin().getActivePump().setTempBasalPercent(percent, durationInMinutes, profile, enforceNew); - if (L.isEnabled(L.PUMPQUEUE)) - log.debug("Result percent: " + percent + " durationInMinutes: " + durationInMinutes + " success: " + r.success + " enacted: " + r.enacted); - if (callback != null) - callback.result(r).run(); - } - - @Override - public String status() { - return "TEMPBASAL " + percent + "% " + durationInMinutes + " min"; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalPercent.kt b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalPercent.kt new file mode 100644 index 0000000000..2c5fd55041 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalPercent.kt @@ -0,0 +1,28 @@ +package info.nightscout.androidaps.queue.commands + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.data.Profile +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.queue.Callback +import javax.inject.Inject + +class CommandTempBasalPercent( + injector: HasAndroidInjector, + private val percent: Int, + private val durationInMinutes: Int, + private val enforceNew: Boolean, + private val profile: Profile, + callback: Callback? +) : Command(injector, CommandType.BASAL_PROFILE, callback) { + + @Inject lateinit var activePlugin: ActivePluginProvider + + override fun execute() { + val r = activePlugin.activePump.setTempBasalPercent(percent, durationInMinutes, profile, enforceNew) + aapsLogger.debug(LTag.PUMPQUEUE, "Result percent: $percent durationInMinutes: $durationInMinutes success: ${r.success} enacted: ${r.enacted}") + callback?.result(r)?.run() + } + + override fun status(): String = "TEMP BASAL $percent% $durationInMinutes min" +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.kt b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.kt index 7e0052b5ac..d845b773c2 100644 --- a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.kt +++ b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.kt @@ -9,7 +9,6 @@ import android.os.PowerManager import android.os.SystemClock import dagger.android.DaggerBroadcastReceiver import info.nightscout.androidaps.Config -import info.nightscout.androidaps.db.DatabaseHelper import info.nightscout.androidaps.events.EventProfileNeedsUpdate import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.CommandQueueProvider @@ -19,6 +18,7 @@ import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.general.nsclient.NSUpload +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.queue.commands.Command import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy @@ -30,10 +30,12 @@ import kotlin.math.abs class KeepAliveReceiver : DaggerBroadcastReceiver() { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var rxBus: RxBusWrapper - @Inject lateinit var activePluginProvider: ActivePluginProvider - @Inject lateinit var commandQueueProvider: CommandQueueProvider + @Inject lateinit var activePlugin: ActivePluginProvider + @Inject lateinit var commandQueue: CommandQueueProvider @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var loopPlugin: LoopPlugin + @Inject lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin + @Inject lateinit var localAlertUtils: LocalAlertUtils private var lastReadStatus: Long = 0 private var lastRun: Long = 0 @@ -41,24 +43,28 @@ class KeepAliveReceiver : DaggerBroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { super.onReceive(context, intent) - aapsLogger.debug(LTag.CORE, "KeepAlive received"); + aapsLogger.debug(LTag.CORE, "KeepAlive received") val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager val wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AndroidAPS:KeepAliveReceiver") wl.acquire(T.mins(2).msecs()) - LocalAlertUtils.shortenSnoozeInterval() - LocalAlertUtils.checkStaleBGAlert() + localAlertUtils.shortenSnoozeInterval() + localAlertUtils.checkStaleBGAlert() checkPump() checkAPS() wl.release() } - class KeepAliveManager @Inject constructor(val aapsLogger: AAPSLogger) { + class KeepAliveManager @Inject constructor( + private val aapsLogger: AAPSLogger, + private val localAlertUtils: LocalAlertUtils + ) { + //called by MainApp at first app start fun setAlarm(context: Context) { aapsLogger.debug(LTag.CORE, "KeepAlive scheduled") SystemClock.sleep(5000) // wait for app initialization - LocalAlertUtils.shortenSnoozeInterval() - LocalAlertUtils.presnoozeAlarms() + localAlertUtils.shortenSnoozeInterval() + localAlertUtils.presnoozeAlarms() val am = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager val i = Intent(context, KeepAliveReceiver::class.java) val pi = PendingIntent.getBroadcast(context, 0, i, 0) @@ -86,15 +92,15 @@ class KeepAliveReceiver : DaggerBroadcastReceiver() { } - // Usually devicestatus is uploaded through LoopPlugin after every loop cycle. + // Usually deviceStatus is uploaded through LoopPlugin after every loop cycle. // if there is no BG available, we have to upload anyway to have correct // IOB displayed in NS private fun checkAPS() { - val usedAPS = activePluginProvider.activeAPS + val usedAPS = activePlugin.activeAPS var shouldUploadStatus = false if (Config.NSCLIENT) return if (Config.PUMPCONTROL) shouldUploadStatus = true - if (usedAPS == null || !loopPlugin.isEnabled() || DatabaseHelper.actualBg() == null) + if (usedAPS == null || !loopPlugin.isEnabled() || iobCobCalculatorPlugin.actualBg() == null) shouldUploadStatus = true else if (DateUtil.isOlderThan(usedAPS.lastAPSRun, 5)) shouldUploadStatus = true if (DateUtil.isOlderThan(lastIobUpload, IOB_UPDATE_FREQUENCY) && shouldUploadStatus) { @@ -104,7 +110,7 @@ class KeepAliveReceiver : DaggerBroadcastReceiver() { } private fun checkPump() { - val pump = activePluginProvider.activePump ?: return + val pump = activePlugin.activePumpPlugin ?: return val profile = profileFunction.getProfile() ?: return val lastConnection = pump.lastDataTime() val isStatusOutdated = lastConnection + STATUS_UPDATE_FREQUENCY < System.currentTimeMillis() @@ -113,16 +119,16 @@ class KeepAliveReceiver : DaggerBroadcastReceiver() { // sometimes keep alive broadcast stops // as as workaround test if readStatus was requested before an alarm is generated if (lastReadStatus != 0L && lastReadStatus > System.currentTimeMillis() - T.mins(5).msecs()) { - LocalAlertUtils.checkPumpUnreachableAlarm(lastConnection, isStatusOutdated, loopPlugin.isDisconnected) + localAlertUtils.checkPumpUnreachableAlarm(lastConnection, isStatusOutdated, loopPlugin.isDisconnected) } - if (!pump.isThisProfileSet(profile) && !commandQueueProvider.commandQueue.isRunning(Command.CommandType.BASALPROFILE)) { + if (!pump.isThisProfileSet(profile) && !commandQueue.isRunning(Command.CommandType.BASAL_PROFILE)) { rxBus.send(EventProfileNeedsUpdate()) } else if (isStatusOutdated && !pump.isBusy) { lastReadStatus = System.currentTimeMillis() - commandQueueProvider.commandQueue.readStatus("KeepAlive. Status outdated.", null) + commandQueue.readStatus("KeepAlive. Status outdated.", null) } else if (isBasalOutdated && !pump.isBusy) { lastReadStatus = System.currentTimeMillis() - commandQueueProvider.commandQueue.readStatus("KeepAlive. Basal outdated.", null) + commandQueue.readStatus("KeepAlive. Basal outdated.", null) } if (lastRun != 0L && System.currentTimeMillis() - lastRun > T.mins(10).msecs()) { aapsLogger.error(LTag.CORE, "KeepAlive fail") diff --git a/app/src/main/java/info/nightscout/androidaps/services/DataService.java b/app/src/main/java/info/nightscout/androidaps/services/DataService.java index 42324b3b9d..348f213b85 100644 --- a/app/src/main/java/info/nightscout/androidaps/services/DataService.java +++ b/app/src/main/java/info/nightscout/androidaps/services/DataService.java @@ -51,6 +51,7 @@ public class DataService extends DaggerIntentService { @Inject PoctechPlugin poctechPlugin; @Inject TomatoPlugin tomatoPlugin; @Inject XdripPlugin xdripPlugin; + @Inject NSProfilePlugin nsProfilePlugin; public DataService() { super("DataService"); @@ -85,7 +86,7 @@ public class DataService extends DaggerIntentService { nsClientSourcePlugin.handleNewData(intent); } else if (Intents.ACTION_NEW_PROFILE.equals(action)) { // always handle Profile if NSProfile is enabled without looking at nsUploadOnly - NSProfilePlugin.getPlugin().handleNewData(intent); + nsProfilePlugin.handleNewData(intent); } else if (acceptNSData && (Intents.ACTION_NEW_TREATMENT.equals(action) || Intents.ACTION_CHANGED_TREATMENT.equals(action) || diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.kt b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.kt index 293d46545a..22e22d0af9 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.kt +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.kt @@ -11,6 +11,8 @@ import info.nightscout.androidaps.activities.PreferencesActivity import info.nightscout.androidaps.dialogs.ProfileSwitchDialog import info.nightscout.androidaps.events.EventConfigBuilderChange import info.nightscout.androidaps.events.EventPumpStatusChanged +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin @@ -43,13 +45,17 @@ import javax.inject.Singleton class SWDefinition @Inject constructor( private val rxBus: RxBusWrapper, private val mainApp: MainApp, - private val resourceHelper: ResourceHelper, + resourceHelper: ResourceHelper, private val sp: SP, private val profileFunction: ProfileFunction, private val localProfilePlugin: LocalProfilePlugin, - private val configBuilderPlugin: ConfigBuilderPlugin, + private val activePlugin: ActivePluginProvider, + private val commandQueue: CommandQueueProvider, private val objectivesPlugin: ObjectivesPlugin, - private val loopPlugin: LoopPlugin + private val configBuilderPlugin: ConfigBuilderPlugin, + private val loopPlugin: LoopPlugin, + private val nsClientPlugin: NSClientPlugin, + private val nsProfilePlugin: NSProfilePlugin ) { var activity: AppCompatActivity? = null @@ -160,14 +166,14 @@ class SWDefinition @Inject constructor( .add(SWButton() .text(R.string.enable_nsclient) .action { - NSClientPlugin.getPlugin().setPluginEnabled(PluginType.GENERAL, true) - NSClientPlugin.getPlugin().setFragmentVisible(PluginType.GENERAL, true) - configBuilderPlugin.processOnEnabledCategoryChanged(NSClientPlugin.getPlugin(), PluginType.GENERAL) + nsClientPlugin.setPluginEnabled(PluginType.GENERAL, true) + nsClientPlugin.setFragmentVisible(PluginType.GENERAL, true) + configBuilderPlugin.processOnEnabledCategoryChanged(nsClientPlugin, PluginType.GENERAL) configBuilderPlugin.storeSettings("SetupWizard") rxBus.send(EventConfigBuilderChange()) rxBus.send(EventSWUpdate(true)) } - .visibility { !NSClientPlugin.getPlugin().isEnabled(PluginType.GENERAL) }) + .visibility { !nsClientPlugin.isEnabled(PluginType.GENERAL) }) .add(SWEditUrl() .preferenceId(R.string.key_nsclientinternal_url) .updateDelay(5) @@ -182,11 +188,11 @@ class SWDefinition @Inject constructor( .add(SWBreak()) .add(SWEventListener(resourceHelper, rxBus, EventNSClientStatus::class.java) .label(R.string.status) - .initialStatus(NSClientPlugin.getPlugin().status) + .initialStatus(nsClientPlugin.status) ) .add(SWBreak()) - .validator { NSClientPlugin.getPlugin().nsClientService != null && NSClientService.isConnected && NSClientService.hasWriteAuth } - .visibility { !(NSClientPlugin.getPlugin().nsClientService != null && NSClientService.isConnected && NSClientService.hasWriteAuth) } + .validator { nsClientPlugin.nsClientService != null && NSClientService.isConnected && NSClientService.hasWriteAuth } + .visibility { !(nsClientPlugin.nsClientService != null && NSClientService.isConnected && NSClientService.hasWriteAuth) } private val screenAge = SWScreen(R.string.patientage) .skippable(false) .add(SWBreak()) @@ -209,7 +215,7 @@ class SWDefinition @Inject constructor( .add(SWButton() .text(R.string.insulinsourcesetup) .action { - val plugin = configBuilderPlugin.activeInsulin as PluginBase? + val plugin = activePlugin.activeInsulin as PluginBase? if (plugin != null) { PasswordProtection.QueryPassword(activity, R.string.settings_password, "settings_password", Runnable { val i = Intent(activity, PreferencesActivity::class.java) @@ -218,8 +224,7 @@ class SWDefinition @Inject constructor( }, null) } } - .visibility { configBuilderPlugin.activeInsulin != null && (configBuilderPlugin.activeInsulin as PluginBase?)!!.preferencesId > 0 }) - .validator { configBuilderPlugin.activeInsulin != null } + .visibility { (activePlugin.activeInsulin as PluginBase).preferencesId > 0 }) private val screenBgSource = SWScreen(R.string.configbuilder_bgsource) .skippable(false) .add(SWPlugin() @@ -229,7 +234,7 @@ class SWDefinition @Inject constructor( .add(SWButton() .text(R.string.bgsourcesetup) .action { - val plugin = configBuilderPlugin.activeBgSource as PluginBase? + val plugin = activePlugin.activeBgSource as PluginBase? if (plugin != null) { PasswordProtection.QueryPassword(activity, R.string.settings_password, "settings_password", Runnable { val i = Intent(activity, PreferencesActivity::class.java) @@ -238,8 +243,8 @@ class SWDefinition @Inject constructor( }, null) } } - .visibility { configBuilderPlugin.activeBgSource != null && (configBuilderPlugin.activeBgSource as PluginBase?)!!.preferencesId > 0 }) - .validator { configBuilderPlugin.activeBgSource != null } + .visibility { activePlugin.activeBgSource != null && (activePlugin.activeBgSource as PluginBase).preferencesId > 0 }) + .validator { activePlugin.activeBgSource != null } private val screenProfile = SWScreen(R.string.configbuilder_profile) .skippable(false) .add(SWInfotext() @@ -254,8 +259,8 @@ class SWDefinition @Inject constructor( .label(R.string.adjustprofileinns)) .add(SWFragment(this) .add(NSProfileFragment())) - .validator { NSProfilePlugin.getPlugin().profile != null && NSProfilePlugin.getPlugin().profile!!.getDefaultProfile() != null && NSProfilePlugin.getPlugin().profile!!.getDefaultProfile()!!.isValid("StartupWizard") } - .visibility { NSProfilePlugin.getPlugin().isEnabled(PluginType.PROFILE) } + .validator { nsProfilePlugin.profile != null && nsProfilePlugin.profile!!.getDefaultProfile() != null && nsProfilePlugin.profile!!.getDefaultProfile()!!.isValid("StartupWizard") } + .visibility { nsProfilePlugin.isEnabled(PluginType.PROFILE) } private val screenLocalProfile = SWScreen(R.string.localprofile) .skippable(false) .add(SWFragment(this) @@ -280,7 +285,7 @@ class SWDefinition @Inject constructor( .add(SWButton() .text(R.string.pumpsetup) .action { - val plugin = configBuilderPlugin.activePump as PluginBase? + val plugin = activePlugin.activePump as PluginBase? if (plugin != null) { PasswordProtection.QueryPassword(activity, R.string.settings_password, "settings_password", Runnable { val i = Intent(activity, PreferencesActivity::class.java) @@ -289,13 +294,13 @@ class SWDefinition @Inject constructor( }, null) } } - .visibility { configBuilderPlugin.activePump != null && (configBuilderPlugin.activePump as PluginBase?)!!.preferencesId > 0 }) + .visibility { activePlugin.activePumpPlugin != null && (activePlugin.activePump as PluginBase?)!!.preferencesId > 0 }) .add(SWButton() .text(R.string.readstatus) - .action { configBuilderPlugin.commandQueue.readStatus("Clicked connect to pump", null) } - .visibility { configBuilderPlugin.activePump != null }) + .action { commandQueue.readStatus("Clicked connect to pump", null) } + .visibility { activePlugin.activePumpPlugin != null }) .add(SWEventListener(resourceHelper, rxBus, EventPumpStatusChanged::class.java)) - .validator { configBuilderPlugin.activePump != null && configBuilderPlugin.activePump!!.isInitialized } + .validator { activePlugin.activePumpPlugin != null && activePlugin.getActivePumpPlugin()!!.isInitialized() } private val screenAps = SWScreen(R.string.configbuilder_aps) .skippable(false) .add(SWInfotext() @@ -310,7 +315,7 @@ class SWDefinition @Inject constructor( .add(SWButton() .text(R.string.apssetup) .action { - val plugin = configBuilderPlugin.activeAPS as PluginBase? + val plugin = activePlugin.activeAPS as PluginBase? if (plugin != null) { PasswordProtection.QueryPassword(activity, R.string.settings_password, "settings_password", Runnable { val i = Intent(activity, PreferencesActivity::class.java) @@ -319,8 +324,8 @@ class SWDefinition @Inject constructor( }, null) } } - .visibility { configBuilderPlugin.activeAPS != null && (configBuilderPlugin.activeAPS as PluginBase?)!!.preferencesId > 0 }) - .validator { configBuilderPlugin.activeAPS != null } + .visibility { activePlugin.activeAPS != null && (activePlugin.activeAPS as PluginBase?)!!.preferencesId > 0 }) + .validator { activePlugin.activeAPS != null } .visibility { Config.APS } private val screenApsMode = SWScreen(R.string.apsmode_title) .skippable(false) @@ -361,7 +366,7 @@ class SWDefinition @Inject constructor( .add(SWButton() .text(R.string.sensitivitysetup) .action { - val plugin = configBuilderPlugin.activeSensitivity as PluginBase? + val plugin = activePlugin.activeSensitivity as PluginBase? if (plugin != null) { PasswordProtection.QueryPassword(activity, R.string.settings_password, "settings_password", Runnable { val i = Intent(activity, PreferencesActivity::class.java) @@ -370,8 +375,7 @@ class SWDefinition @Inject constructor( }, null) } } - .visibility { configBuilderPlugin.activeSensitivity != null && (configBuilderPlugin.activeSensitivity as PluginBase?)!!.preferencesId > 0 }) - .validator { configBuilderPlugin.activeSensitivity != null } + .visibility { (activePlugin.activeSensitivity as PluginBase).preferencesId > 0 }) private val getScreenObjectives = SWScreen(R.string.objectives) .skippable(false) .add(SWInfotext() @@ -379,8 +383,8 @@ class SWDefinition @Inject constructor( .add(SWBreak()) .add(SWFragment(this) .add(ObjectivesFragment())) - .validator { objectivesPlugin.objectives[objectivesPlugin.FIRST_OBJECTIVE].isStarted } - .visibility { !objectivesPlugin.objectives[objectivesPlugin.FIRST_OBJECTIVE].isStarted && Config.APS } + .validator { objectivesPlugin.objectives[ObjectivesPlugin.FIRST_OBJECTIVE].isStarted } + .visibility { !objectivesPlugin.objectives[ObjectivesPlugin.FIRST_OBJECTIVE].isStarted && Config.APS } private fun SWDefinitionFull() { // List all the screens here add(screenSetupWizard) diff --git a/app/src/main/java/info/nightscout/androidaps/utils/FabricPrivacy.kt b/app/src/main/java/info/nightscout/androidaps/utils/FabricPrivacy.kt index 4fa91cc7c9..31fcd2c528 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/FabricPrivacy.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/FabricPrivacy.kt @@ -129,11 +129,11 @@ class FabricPrivacy @Inject constructor( mainApp.firebaseAnalytics.setUserProperty("Remote", remote) val hashes: List = signatureVerifierPlugin.shortHashes() if (hashes.isNotEmpty()) mainApp.firebaseAnalytics.setUserProperty("Hash", hashes[0]) - configBuilderPlugin.activePump?.let { mainApp.firebaseAnalytics.setUserProperty("Pump", it::class.java.simpleName) } + configBuilderPlugin.activePumpPlugin?.let { mainApp.firebaseAnalytics.setUserProperty("Pump", it::class.java.simpleName) } configBuilderPlugin.activeAPS?.let { mainApp.firebaseAnalytics.setUserProperty("Aps", it::class.java.simpleName) } configBuilderPlugin.activeBgSource?.let { mainApp.firebaseAnalytics.setUserProperty("BgSource", it::class.java.simpleName) } mainApp.firebaseAnalytics.setUserProperty("Profile", configBuilderPlugin.activeProfileInterface.javaClass.simpleName) - configBuilderPlugin.activeSensitivity?.let { mainApp.firebaseAnalytics.setUserProperty("Sensitivity", it::class.java.simpleName) } - configBuilderPlugin.activeInsulin?.let { mainApp.firebaseAnalytics.setUserProperty("Insulin", it::class.java.simpleName) } + configBuilderPlugin.activeSensitivity.let { mainApp.firebaseAnalytics.setUserProperty("Sensitivity", it::class.java.simpleName) } + configBuilderPlugin.activeInsulin.let { mainApp.firebaseAnalytics.setUserProperty("Insulin", it::class.java.simpleName) } } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/utils/LocalAlertUtils.java b/app/src/main/java/info/nightscout/androidaps/utils/LocalAlertUtils.java deleted file mode 100644 index 077d890e46..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/utils/LocalAlertUtils.java +++ /dev/null @@ -1,107 +0,0 @@ -package info.nightscout.androidaps.utils; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import info.nightscout.androidaps.Config; -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.Profile; -import info.nightscout.androidaps.db.BgReading; -import info.nightscout.androidaps.db.DatabaseHelper; -import info.nightscout.androidaps.interfaces.PumpInterface; -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.ProfileFunctions; -import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; -import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification; -import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; -import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; - -/** - * Created by adrian on 17/12/17. - */ - -public class LocalAlertUtils { - private static Logger log = LoggerFactory.getLogger(LocalAlertUtils.class); - - public static long missedReadingsThreshold() { - return T.mins(SP.getInt(MainApp.gs(R.string.key_missed_bg_readings_threshold), 30)).msecs(); - } - - private static long pumpUnreachableThreshold() { - return T.mins(SP.getInt(MainApp.gs(R.string.key_pump_unreachable_threshold), 30)).msecs(); - } - - public static void checkPumpUnreachableAlarm(long lastConnection, boolean isStatusOutdated, boolean isDisconnected) { - boolean alarmTimeoutExpired = lastConnection + pumpUnreachableThreshold() < System.currentTimeMillis(); - boolean nextAlarmOccurrenceReached = SP.getLong("nextPumpDisconnectedAlarm", 0L) < System.currentTimeMillis(); - - if (Config.APS && SP.getBoolean(MainApp.gs(R.string.key_enable_pump_unreachable_alert), true) - && isStatusOutdated && alarmTimeoutExpired && nextAlarmOccurrenceReached && !isDisconnected) { - log.debug("Generating pump unreachable alarm. lastConnection: " + DateUtil.dateAndTimeString(lastConnection) + " isStatusOutdated: " + isStatusOutdated); - Notification n = new Notification(Notification.PUMP_UNREACHABLE, MainApp.gs(R.string.pump_unreachable), Notification.URGENT); - n.soundId = R.raw.alarm; - SP.putLong("nextPumpDisconnectedAlarm", System.currentTimeMillis() + pumpUnreachableThreshold()); - RxBus.Companion.getINSTANCE().send(new EventNewNotification(n)); - if (SP.getBoolean(R.string.key_ns_create_announcements_from_errors, true)) { - NSUpload.uploadError(n.text); - } - } - if (!isStatusOutdated && !alarmTimeoutExpired) - RxBus.Companion.getINSTANCE().send(new EventDismissNotification(Notification.PUMP_UNREACHABLE)); - } - - /*Presnoozes the alarms with 5 minutes if no snooze exists. - * Call only at startup! - */ - public static void presnoozeAlarms() { - if (SP.getLong("nextMissedReadingsAlarm", 0l) < System.currentTimeMillis()) { - SP.putLong("nextMissedReadingsAlarm", System.currentTimeMillis() + 5 * 60 * 1000); - } - if (SP.getLong("nextPumpDisconnectedAlarm", 0l) < System.currentTimeMillis()) { - SP.putLong("nextPumpDisconnectedAlarm", System.currentTimeMillis() + 5 * 60 * 1000); - } - } - - public static void shortenSnoozeInterval() { - //shortens alarm times in case of setting changes or future data - long nextMissedReadingsAlarm = SP.getLong("nextMissedReadingsAlarm", 0L); - nextMissedReadingsAlarm = Math.min(System.currentTimeMillis() + missedReadingsThreshold(), nextMissedReadingsAlarm); - SP.putLong("nextMissedReadingsAlarm", nextMissedReadingsAlarm); - - long nextPumpDisconnectedAlarm = SP.getLong("nextPumpDisconnectedAlarm", 0L); - nextPumpDisconnectedAlarm = Math.min(System.currentTimeMillis() + pumpUnreachableThreshold(), nextPumpDisconnectedAlarm); - SP.putLong("nextPumpDisconnectedAlarm", nextPumpDisconnectedAlarm); - } - - public static void notifyPumpStatusRead() { - //TODO: persist the actual time the pump is read and simplify the whole logic when to alarm - - final PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump(); - final Profile profile = ProfileFunctions.getInstance().getProfile(); - if (pump != null && profile != null) { - long lastConnection = pump.lastDataTime(); - long earliestAlarmTime = lastConnection + pumpUnreachableThreshold(); - if (SP.getLong("nextPumpDisconnectedAlarm", 0l) < earliestAlarmTime) { - SP.putLong("nextPumpDisconnectedAlarm", earliestAlarmTime); - } - } - } - - public static void checkStaleBGAlert() { - BgReading bgReading = DatabaseHelper.lastBg(); - if (SP.getBoolean(MainApp.gs(R.string.key_enable_missed_bg_readings_alert), false) - && bgReading != null && bgReading.date + missedReadingsThreshold() < System.currentTimeMillis() - && SP.getLong("nextMissedReadingsAlarm", 0l) < System.currentTimeMillis()) { - Notification n = new Notification(Notification.BG_READINGS_MISSED, MainApp.gs(R.string.missed_bg_readings), Notification.URGENT); - n.soundId = R.raw.alarm; - SP.putLong("nextMissedReadingsAlarm", System.currentTimeMillis() + missedReadingsThreshold()); - RxBus.Companion.getINSTANCE().send(new EventNewNotification(n)); - if (SP.getBoolean(R.string.key_ns_create_announcements_from_errors, true)) { - NSUpload.uploadError(n.text); - } - } - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/utils/LocalAlertUtils.kt b/app/src/main/java/info/nightscout/androidaps/utils/LocalAlertUtils.kt new file mode 100644 index 0000000000..431dc9daac --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/utils/LocalAlertUtils.kt @@ -0,0 +1,106 @@ +package info.nightscout.androidaps.utils + +import info.nightscout.androidaps.Config +import info.nightscout.androidaps.R +import info.nightscout.androidaps.db.BgReading +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.plugins.general.nsclient.NSUpload +import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification +import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification +import info.nightscout.androidaps.plugins.general.overview.notifications.Notification +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin +import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.sharedPreferences.SP +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Created by adrian on 17/12/17. + */ +@Singleton +class LocalAlertUtils @Inject constructor( + private val aapsLogger: AAPSLogger, + private val sp: SP, + private val rxBus: RxBusWrapper, + private val resourceHelper: ResourceHelper, + private val activePlugin: ActivePluginProvider, + private val profileFunction: ProfileFunction, + private val iobCobCalculatorPlugin: IobCobCalculatorPlugin +) { + + fun missedReadingsThreshold(): Long { + return T.mins(sp.getInt(resourceHelper.gs(R.string.key_missed_bg_readings_threshold), 30).toLong()).msecs() + } + + private fun pumpUnreachableThreshold(): Long { + return T.mins(sp.getInt(resourceHelper.gs(R.string.key_pump_unreachable_threshold), 30).toLong()).msecs() + } + + fun checkPumpUnreachableAlarm(lastConnection: Long, isStatusOutdated: Boolean, isDisconnected: Boolean) { + val alarmTimeoutExpired = lastConnection + pumpUnreachableThreshold() < System.currentTimeMillis() + val nextAlarmOccurrenceReached = sp.getLong("nextPumpDisconnectedAlarm", 0L) < System.currentTimeMillis() + if (Config.APS && sp.getBoolean(resourceHelper.gs(R.string.key_enable_pump_unreachable_alert), true) + && isStatusOutdated && alarmTimeoutExpired && nextAlarmOccurrenceReached && !isDisconnected) { + aapsLogger.debug(LTag.CORE, "Generating pump unreachable alarm. lastConnection: " + DateUtil.dateAndTimeString(lastConnection) + " isStatusOutdated: " + isStatusOutdated) + val n = Notification(Notification.PUMP_UNREACHABLE, resourceHelper.gs(R.string.pump_unreachable), Notification.URGENT) + n.soundId = R.raw.alarm + sp.putLong("nextPumpDisconnectedAlarm", System.currentTimeMillis() + pumpUnreachableThreshold()) + rxBus.send(EventNewNotification(n)) + if (sp.getBoolean(R.string.key_ns_create_announcements_from_errors, true)) { + NSUpload.uploadError(n.text) + } + } + if (!isStatusOutdated && !alarmTimeoutExpired) rxBus.send(EventDismissNotification(Notification.PUMP_UNREACHABLE)) + } + + /*Presnoozes the alarms with 5 minutes if no snooze exists. + * Call only at startup! + */ + fun presnoozeAlarms() { + if (sp.getLong("nextMissedReadingsAlarm", 0L) < System.currentTimeMillis()) { + sp.putLong("nextMissedReadingsAlarm", System.currentTimeMillis() + 5 * 60 * 1000) + } + if (sp.getLong("nextPumpDisconnectedAlarm", 0L) < System.currentTimeMillis()) { + sp.putLong("nextPumpDisconnectedAlarm", System.currentTimeMillis() + 5 * 60 * 1000) + } + } + + fun shortenSnoozeInterval() { //shortens alarm times in case of setting changes or future data + var nextMissedReadingsAlarm = sp.getLong("nextMissedReadingsAlarm", 0L) + nextMissedReadingsAlarm = Math.min(System.currentTimeMillis() + missedReadingsThreshold(), nextMissedReadingsAlarm) + sp.putLong("nextMissedReadingsAlarm", nextMissedReadingsAlarm) + var nextPumpDisconnectedAlarm = sp.getLong("nextPumpDisconnectedAlarm", 0L) + nextPumpDisconnectedAlarm = Math.min(System.currentTimeMillis() + pumpUnreachableThreshold(), nextPumpDisconnectedAlarm) + sp.putLong("nextPumpDisconnectedAlarm", nextPumpDisconnectedAlarm) + } + + fun notifyPumpStatusRead() { //TODO: persist the actual time the pump is read and simplify the whole logic when to alarm + val pump = activePlugin.activePumpPlugin + val profile = profileFunction.getProfile() + if (pump != null && profile != null) { + val lastConnection = pump.lastDataTime() + val earliestAlarmTime = lastConnection + pumpUnreachableThreshold() + if (sp.getLong("nextPumpDisconnectedAlarm", 0L) < earliestAlarmTime) { + sp.putLong("nextPumpDisconnectedAlarm", earliestAlarmTime) + } + } + } + + fun checkStaleBGAlert() { + val bgReading: BgReading? = iobCobCalculatorPlugin.lastBg() + if (sp.getBoolean(resourceHelper.gs(R.string.key_enable_missed_bg_readings_alert), false) + && bgReading != null && bgReading.date + missedReadingsThreshold() < System.currentTimeMillis() && sp.getLong("nextMissedReadingsAlarm", 0L) < System.currentTimeMillis()) { + val n = Notification(Notification.BG_READINGS_MISSED, resourceHelper.gs(R.string.missed_bg_readings), Notification.URGENT) + n.soundId = R.raw.alarm + sp.putLong("nextMissedReadingsAlarm", System.currentTimeMillis() + missedReadingsThreshold()) + rxBus.send(EventNewNotification(n)) + if (sp.getBoolean(R.string.key_ns_create_announcements_from_errors, true)) { + NSUpload.uploadError(n.text) + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SP.kt b/app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SP.kt index f407820197..de7b20f403 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SP.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SP.kt @@ -16,6 +16,7 @@ interface SP { fun remove(key: String) fun getString(@StringRes resourceID: Int, defaultValue: String): String fun getStringOrNull(@StringRes resourceID: Int, defaultValue: String?): String? + fun getStringOrNull(key: String, defaultValue: String?): String? fun getString(key: String, defaultValue: String): String fun getBoolean(@StringRes resourceID: Int, defaultValue: Boolean): Boolean fun getBoolean(key: String, defaultValue: Boolean): Boolean diff --git a/app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SPImplementation.kt b/app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SPImplementation.kt index 3eec951a3f..f05582ab5b 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SPImplementation.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SPImplementation.kt @@ -34,6 +34,9 @@ class SPImplementation @Inject constructor( override fun getStringOrNull(resourceID: Int, defaultValue: String?): String? = sharedPreferences.getString(resourceHelper.gs(resourceID), defaultValue) ?: defaultValue + override fun getStringOrNull(key: String, defaultValue: String?): String? = + sharedPreferences.getString(key, defaultValue) + override fun getString(key: String, defaultValue: String): String = sharedPreferences.getString(key, defaultValue) ?: defaultValue diff --git a/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt b/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt index 585055175f..2553c1a816 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt @@ -23,7 +23,7 @@ import javax.inject.Inject class TddCalculator @Inject constructor( aapsLogger: AAPSLogger, rxBus: RxBusWrapper, - val resourceHelper: ResourceHelper, + resourceHelper: ResourceHelper, val mainApp: MainApp, val sp: SP, val configBuilderPlugin: ConfigBuilderPlugin, diff --git a/app/src/main/java/info/nightscout/androidaps/utils/wizard/BolusWizard.kt b/app/src/main/java/info/nightscout/androidaps/utils/wizard/BolusWizard.kt index 8ee6c0c347..55a17d6ede 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/wizard/BolusWizard.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/wizard/BolusWizard.kt @@ -4,7 +4,7 @@ import android.content.Context import android.content.Intent import android.text.Spanned import com.google.common.base.Joiner -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.data.DetailedBolusInfo @@ -22,7 +22,6 @@ import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction 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.queue.Callback import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.HtmlHelper @@ -37,7 +36,7 @@ import javax.inject.Inject import kotlin.math.abs class BolusWizard @Inject constructor( - private val mainApp: MainApp + injector: HasAndroidInjector ) { @Inject lateinit var aapsLogger: AAPSLogger @@ -45,14 +44,14 @@ class BolusWizard @Inject constructor( @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var constraintChecker: ConstraintChecker - @Inject lateinit var treatmentsPlugin: TreatmentsPlugin - @Inject lateinit var activePluginProvider: ActivePluginProvider - @Inject lateinit var commandQueueProvider: CommandQueueProvider + @Inject lateinit var context: Context + @Inject lateinit var activePlugin: ActivePluginProvider + @Inject lateinit var commandQueue: CommandQueueProvider @Inject lateinit var loopPlugin: LoopPlugin @Inject lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin init { - mainApp.androidInjector().inject(this) + injector.androidInjector().inject(this) } // Intermediate @@ -186,10 +185,10 @@ class BolusWizard @Inject constructor( // Insulin from IOB // IOB calculation - treatmentsPlugin.updateTotalIOBTreatments() - val bolusIob = treatmentsPlugin.lastCalculationTreatments.round() - treatmentsPlugin.updateTotalIOBTempBasals() - val basalIob = treatmentsPlugin.lastCalculationTempBasals.round() + activePlugin.activeTreatments.updateTotalIOBTreatments() + val bolusIob = activePlugin.activeTreatments.lastCalculationTreatments.round() + activePlugin.activeTreatments.updateTotalIOBTempBasals() + val basalIob = activePlugin.activeTreatments.lastCalculationTempBasals.round() insulinFromBolusIOB = if (includeBolusIOB) -bolusIob.iob else 0.0 insulinFromBasalsIOB = if (includeBasalIOB) -basalIob.basaliob else 0.0 @@ -219,8 +218,7 @@ class BolusWizard @Inject constructor( calculatedTotalInsulin = 0.0 } - val bolusStep = activePluginProvider.activePump?.pumpDescription?.bolusStep - ?: 0.1 + val bolusStep = activePlugin.activePump.pumpDescription.bolusStep calculatedTotalInsulin = Round.roundTo(calculatedTotalInsulin, bolusStep) insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(calculatedTotalInsulin)).value() @@ -301,7 +299,7 @@ class BolusWizard @Inject constructor( fun confirmAndExecute(context: Context) { val profile = profileFunction.getProfile() ?: return - val pump = activePluginProvider.activePump ?: return + val pump = activePlugin.activePump if (calculatedTotalInsulin > 0.0 || carbs > 0.0) { if (accepted) { @@ -320,30 +318,30 @@ class BolusWizard @Inject constructor( rxBus.send(EventRefreshOverview("WizardDialog")) } - if (pump.pumpDescription?.tempBasalStyle == PumpDescription.ABSOLUTE) { - commandQueueProvider.commandQueue.tempBasalAbsolute(0.0, 120, true, profile, object : Callback() { + if (pump.pumpDescription.tempBasalStyle == PumpDescription.ABSOLUTE) { + commandQueue.tempBasalAbsolute(0.0, 120, true, profile, object : Callback() { override fun run() { if (!result.success) { - val i = Intent(mainApp, ErrorHelperActivity::class.java) + val i = Intent(context, ErrorHelperActivity::class.java) i.putExtra("soundid", R.raw.boluserror) i.putExtra("status", result.comment) i.putExtra("title", resourceHelper.gs(R.string.tempbasaldeliveryerror)) i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - mainApp.startActivity(i) + context.startActivity(i) } } }) } else { - commandQueueProvider.commandQueue.tempBasalPercent(0, 120, true, profile, object : Callback() { + commandQueue.tempBasalPercent(0, 120, true, profile, object : Callback() { override fun run() { if (!result.success) { - val i = Intent(mainApp, ErrorHelperActivity::class.java) + val i = Intent(context, ErrorHelperActivity::class.java) i.putExtra("soundid", R.raw.boluserror) i.putExtra("status", result.comment) i.putExtra("title", resourceHelper.gs(R.string.tempbasaldeliveryerror)) i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - mainApp.startActivity(i) + context.startActivity(i) } } }) @@ -360,21 +358,21 @@ class BolusWizard @Inject constructor( detailedBolusInfo.boluscalc = nsJSON() detailedBolusInfo.source = Source.USER detailedBolusInfo.notes = notes - if (detailedBolusInfo.insulin > 0 || pump.pumpDescription?.storesCarbInfo == true) { - commandQueueProvider.commandQueue.bolus(detailedBolusInfo, object : Callback() { + if (detailedBolusInfo.insulin > 0 || pump.pumpDescription.storesCarbInfo == true) { + commandQueue.bolus(detailedBolusInfo, object : Callback() { override fun run() { if (!result.success) { - val i = Intent(mainApp, ErrorHelperActivity::class.java) + val i = Intent(context, ErrorHelperActivity::class.java) i.putExtra("soundid", R.raw.boluserror) i.putExtra("status", result.comment) i.putExtra("title", resourceHelper.gs(R.string.treatmentdeliveryerror)) i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - mainApp.startActivity(i) + context.startActivity(i) } } }) } else { - treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, false) + activePlugin.activeTreatments.addToHistoryTreatment(detailedBolusInfo, false) } } }) diff --git a/app/src/main/res/values/exam.xml b/app/src/main/res/values/exam.xml index e9063fd2b1..356f97a00f 100644 --- a/app/src/main/res/values/exam.xml +++ b/app/src/main/res/values/exam.xml @@ -149,7 +149,7 @@ Target wiil be 10% higher. Target will be 10% lower. Only bottom target will be 10% lower. - https://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html?highlight=profile%20switch#profile-switch + https://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html?highlight=profile%20switch#profile-switch If you wake up 1h earlier than usual, how should you notify AAPS of the change in your schedule? Initiate a profile switch with a timeshift of 1 Initiate a profile switch with a timeshift of -1 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 0f576f13a3..dcf6232fcc 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1173,7 +1173,7 @@ Insulin limit violation loop_openmode_min_change Minimal request change [%] - Open Loop will popup new change request only if change is bigger than this value in %. Default value is 20% + Open Loop will popup new change request only if change is bigger than this value in %. Default value is 20% short_tabtitles Please pair your pump with your phone! Searching for devices…