From ca9486fab340170a216e9135bf7bff08357066d6 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sat, 28 Dec 2019 22:51:04 +0100 Subject: [PATCH] TreatmentsPlugin -> dagger --- .../nightscout/androidaps/MainActivity.java | 16 +- .../info/nightscout/androidaps/MainApp.java | 3 +- .../activities/NoSplashAppCompatActivity.kt | 6 +- .../androidaps/activities/StatsActivity.kt | 6 +- .../androidaps/activities/SurveyActivity.kt | 6 +- .../dependencyInjection/ActivitiesModule.kt | 42 +++- .../dependencyInjection/AppModule.kt | 1 + .../dependencyInjection/FragmentsModule.kt | 41 ++-- .../androidaps/dialogs/ProfileSwitchDialog.kt | 5 +- .../interfaces/TreatmentsInterface.java | 10 +- .../androidaps/logging/AAPSLogger.kt | 4 + .../androidaps/logging/AAPSLoggerDebug.kt | 16 ++ .../logging/AAPSLoggerProduction.kt | 21 +- .../plugins/configBuilder/ProfileFunction.kt | 2 - .../ProfileFunctionImplementation.kt | 28 +-- .../configBuilder/ProfileFunctions.java | 26 --- .../actions/ActionProfileSwitch.java | 13 +- .../actions/ActionProfileSwitchPercent.java | 8 +- .../smsCommunicator/SmsCommunicatorPlugin.kt | 3 +- .../general/wear/ActionStringHandler.java | 3 +- .../plugins/profile/ns/NSProfileFragment.kt | 12 +- .../plugins/treatments/TreatmentsPlugin.java | 188 +++++++++++------- .../androidaps/utils/TddCalculator.kt | 31 ++- 23 files changed, 276 insertions(+), 215 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/MainActivity.java b/app/src/main/java/info/nightscout/androidaps/MainActivity.java index 419004a64d..8e6a20dc04 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/MainActivity.java @@ -37,9 +37,6 @@ import com.joanzapata.iconify.fonts.FontAwesomeModule; import javax.inject.Inject; import dagger.android.AndroidInjection; -import dagger.android.AndroidInjector; -import dagger.android.DispatchingAndroidInjector; -import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.activities.HistoryBrowseActivity; import info.nightscout.androidaps.activities.NoSplashAppCompatActivity; import info.nightscout.androidaps.activities.PreferencesActivity; @@ -68,10 +65,7 @@ import info.nightscout.androidaps.utils.SP; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; -public class MainActivity extends NoSplashAppCompatActivity implements HasAndroidInjector { - - @Inject - DispatchingAndroidInjector androidInjector; +public class MainActivity extends NoSplashAppCompatActivity { private CompositeDisposable disposable = new CompositeDisposable(); @@ -354,12 +348,4 @@ public class MainActivity extends NoSplashAppCompatActivity implements HasAndroi return actionBarDrawerToggle.onOptionsItemSelected(item); } - - /** - * Returns an {@link AndroidInjector}. - */ - @Override - public AndroidInjector androidInjector() { - return androidInjector; - } } diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java index 6132ad1c48..ef139464da 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java @@ -136,6 +136,7 @@ public class MainApp extends DaggerApplication { @Inject OpenAPSAMAPlugin openAPSAMAPlugin; @Inject OpenAPSSMBPlugin openAPSSMBPlugin; @Inject StatusLinePlugin statusLinePlugin; + @Inject TreatmentsPlugin treatmentsPlugin; @Override public void onCreate() { @@ -215,7 +216,7 @@ public class MainApp extends DaggerApplication { if (Config.APS) pluginsList.add(openAPSSMBPlugin); pluginsList.add(NSProfilePlugin.getPlugin()); if (!Config.NSCLIENT) pluginsList.add(LocalProfilePlugin.INSTANCE); - pluginsList.add(TreatmentsPlugin.getPlugin()); + pluginsList.add(treatmentsPlugin); if (!Config.NSCLIENT) pluginsList.add(safetyPlugin); if (!Config.NSCLIENT) pluginsList.add(VersionCheckerPlugin.INSTANCE); if (Config.APS) pluginsList.add(StorageConstraintPlugin.getPlugin()); diff --git a/app/src/main/java/info/nightscout/androidaps/activities/NoSplashAppCompatActivity.kt b/app/src/main/java/info/nightscout/androidaps/activities/NoSplashAppCompatActivity.kt index 3f59cd56ef..b4ac7eff51 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/NoSplashAppCompatActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/NoSplashAppCompatActivity.kt @@ -2,11 +2,13 @@ package info.nightscout.androidaps.activities import android.content.Context import android.os.Bundle -import androidx.appcompat.app.AppCompatActivity +import dagger.android.support.DaggerAppCompatActivity import info.nightscout.androidaps.R import info.nightscout.androidaps.utils.LocaleHelper -open class NoSplashAppCompatActivity : AppCompatActivity() { +@Suppress("registered") +open class NoSplashAppCompatActivity : DaggerAppCompatActivity() { + public override fun onCreate(savedInstanceState: Bundle?) { setTheme(R.style.AppTheme_NoActionBar) super.onCreate(savedInstanceState) diff --git a/app/src/main/java/info/nightscout/androidaps/activities/StatsActivity.kt b/app/src/main/java/info/nightscout/androidaps/activities/StatsActivity.kt index d0ac8e3f6f..ef55984f5f 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/StatsActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/StatsActivity.kt @@ -8,14 +8,18 @@ import info.nightscout.androidaps.utils.OKDialog import info.nightscout.androidaps.utils.TddCalculator import info.nightscout.androidaps.utils.TirCalculator import kotlinx.android.synthetic.main.stats_activity.* +import javax.inject.Inject class StatsActivity : NoSplashAppCompatActivity() { + @Inject + lateinit var tddCalculator: TddCalculator + override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.stats_activity) - stats_tdds.text = TddCalculator.stats() + stats_tdds.text = tddCalculator.stats() stats_tir.text = TirCalculator.stats() stats_activity.text = ActivityMonitor.stats() 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 bf07eda9af..df4b8bd242 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/SurveyActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/SurveyActivity.kt @@ -12,10 +12,14 @@ import info.nightscout.androidaps.dialogs.ProfileViewerDialog import info.nightscout.androidaps.utils.* import kotlinx.android.synthetic.main.survey_activity.* import org.slf4j.LoggerFactory +import javax.inject.Inject class SurveyActivity : NoSplashAppCompatActivity() { private val log = LoggerFactory.getLogger(SurveyActivity::class.java) + @Inject + lateinit var tddCalculator: TddCalculator + override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.survey_activity) @@ -26,7 +30,7 @@ class SurveyActivity : NoSplashAppCompatActivity() { val profileList = profileStore?.getProfileList() ?: return survey_spinner.adapter = ArrayAdapter(this, R.layout.spinner_centered, profileList) - survey_tdds.text = TddCalculator.stats() + survey_tdds.text = tddCalculator.stats() survey_tir.text = TirCalculator.stats() survey_activity.text = ActivityMonitor.stats() diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ActivitiesModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ActivitiesModule.kt index cb3d910e5e..64446c54d1 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ActivitiesModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ActivitiesModule.kt @@ -3,14 +3,44 @@ package info.nightscout.androidaps.dependencyInjection import dagger.Module import dagger.android.ContributesAndroidInjector import info.nightscout.androidaps.MainActivity -import info.nightscout.androidaps.activities.PreferencesActivity +import info.nightscout.androidaps.activities.* +import info.nightscout.androidaps.plugins.general.maintenance.activities.LogSettingActivity +import info.nightscout.androidaps.plugins.general.overview.activities.QuickWizardListActivity +import info.nightscout.androidaps.plugins.pump.common.dialog.RileyLinkBLEScanActivity +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.dialog.RileyLinkStatusActivity +import info.nightscout.androidaps.plugins.pump.danaR.activities.DanaRHistoryActivity +import info.nightscout.androidaps.plugins.pump.danaR.activities.DanaRUserOptionsActivity +import info.nightscout.androidaps.plugins.pump.danaRS.activities.BLEScanActivity +import info.nightscout.androidaps.plugins.pump.danaRS.activities.PairingHelperActivity +import info.nightscout.androidaps.plugins.pump.insight.activities.InsightAlertActivity +import info.nightscout.androidaps.plugins.pump.insight.activities.InsightPairingActivity +import info.nightscout.androidaps.plugins.pump.insight.activities.InsightPairingInformationActivity +import info.nightscout.androidaps.plugins.pump.medtronic.dialog.MedtronicHistoryActivity +import info.nightscout.androidaps.setupwizard.SetupWizardActivity @Module abstract class ActivitiesModule { - @ContributesAndroidInjector - abstract fun contributeMainActivity(): MainActivity - - @ContributesAndroidInjector - abstract fun contributesPreferencesActivity(): PreferencesActivity + @ContributesAndroidInjector abstract fun contributesBLEScanActivity(): BLEScanActivity + @ContributesAndroidInjector abstract fun contributeBolusProgressHelperActivity(): BolusProgressHelperActivity + @ContributesAndroidInjector abstract fun contributeDanaRHistoryActivity(): DanaRHistoryActivity + @ContributesAndroidInjector abstract fun contributeDanaRUserOptionsActivity(): DanaRUserOptionsActivity + @ContributesAndroidInjector abstract fun contributeErrorHelperActivity(): ErrorHelperActivity + @ContributesAndroidInjector abstract fun contributesHistoryBrowseActivity(): HistoryBrowseActivity + @ContributesAndroidInjector abstract fun contributesInsightAlertActivity(): InsightAlertActivity + @ContributesAndroidInjector abstract fun contributesInsightPairingActivity(): InsightPairingActivity + @ContributesAndroidInjector abstract fun contributesInsightPairingInformationActivity(): InsightPairingInformationActivity + @ContributesAndroidInjector abstract fun contributesLogSettingActivity(): LogSettingActivity + @ContributesAndroidInjector abstract fun contributeMainActivity(): MainActivity + @ContributesAndroidInjector abstract fun contributesMedtronicHistoryActivity(): MedtronicHistoryActivity + @ContributesAndroidInjector abstract fun contributesPairingHelperActivity(): PairingHelperActivity + @ContributesAndroidInjector abstract fun contributesPreferencesActivity(): PreferencesActivity + @ContributesAndroidInjector abstract fun contributesQuickWizardListActivity(): QuickWizardListActivity + @ContributesAndroidInjector abstract fun contributesRequestDexcomPermissionActivity(): RequestDexcomPermissionActivity + @ContributesAndroidInjector abstract fun contributesRileyLinkStatusActivity(): RileyLinkStatusActivity + @ContributesAndroidInjector abstract fun contributesRileyLinkBLEScanActivity(): RileyLinkBLEScanActivity + @ContributesAndroidInjector abstract fun contributesSetupWizardActivity(): SetupWizardActivity + @ContributesAndroidInjector abstract fun contributesStatsActivity(): StatsActivity + @ContributesAndroidInjector abstract fun contributesSurveyActivity(): SurveyActivity + @ContributesAndroidInjector abstract fun contributesTDDStatsActivity(): TDDStatsActivity } \ No newline at end of file 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 7cee10e9b3..2e520f3a04 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -17,6 +17,7 @@ import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctionImplementation import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective5 import info.nightscout.androidaps.plugins.general.automation.actions.ActionSendSMS +import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.queue.commands.CommandSetProfile import info.nightscout.androidaps.services.DataService import info.nightscout.androidaps.utils.resources.ResourceHelper diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt index b3bf7d47dd..7ac458589a 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt @@ -8,39 +8,22 @@ import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAFragment import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAFragment import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBFragment import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorFragment +import info.nightscout.androidaps.plugins.profile.ns.NSProfileFragment @Module abstract class FragmentsModule { - @ContributesAndroidInjector - abstract fun contributesPreferencesFragment(): MyPreferenceFragment - - @ContributesAndroidInjector - abstract fun contributesOpenAPSAMAFragment(): OpenAPSAMAFragment - - @ContributesAndroidInjector - abstract fun contributesOpenAPSMAFragment(): OpenAPSMAFragment - - @ContributesAndroidInjector - abstract fun contributesOpenAPSSMBFragment(): OpenAPSSMBFragment - - @ContributesAndroidInjector - abstract fun contributesSmsCommunicatorFragment(): SmsCommunicatorFragment - - @ContributesAndroidInjector - abstract fun contributesCalibrationDialog(): CalibrationDialog - - @ContributesAndroidInjector - abstract fun contributesCarbsDialog(): CarbsDialog - - @ContributesAndroidInjector - abstract fun contributesCareDialog(): CareDialog - - @ContributesAndroidInjector - abstract fun contributesExtendedBolusDialog(): ExtendedBolusDialog - - @ContributesAndroidInjector - abstract fun contributesFillDialog(): FillDialog + @ContributesAndroidInjector abstract fun contributesPreferencesFragment(): MyPreferenceFragment + @ContributesAndroidInjector abstract fun contributesOpenAPSAMAFragment(): OpenAPSAMAFragment + @ContributesAndroidInjector abstract fun contributesOpenAPSMAFragment(): OpenAPSMAFragment + @ContributesAndroidInjector abstract fun contributesOpenAPSSMBFragment(): OpenAPSSMBFragment + @ContributesAndroidInjector abstract fun contributesNSProfileFragment(): NSProfileFragment + @ContributesAndroidInjector abstract fun contributesSmsCommunicatorFragment(): SmsCommunicatorFragment + @ContributesAndroidInjector abstract fun contributesCalibrationDialog(): CalibrationDialog + @ContributesAndroidInjector abstract fun contributesCarbsDialog(): CarbsDialog + @ContributesAndroidInjector abstract fun contributesCareDialog(): CareDialog + @ContributesAndroidInjector abstract fun contributesExtendedBolusDialog(): ExtendedBolusDialog + @ContributesAndroidInjector abstract fun contributesFillDialog(): FillDialog @ContributesAndroidInjector abstract fun contributesInsulinDialog(): InsulinDialog diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt index 57aaad0736..22f80c7e73 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt @@ -30,6 +30,9 @@ class ProfileSwitchDialog : DialogFragmentWithDate() { @Inject lateinit var profileFunction: ProfileFunction + @Inject + lateinit var treatmentsPlugin: TreatmentsPlugin + override fun onSaveInstanceState(savedInstanceState: Bundle) { super.onSaveInstanceState(savedInstanceState) savedInstanceState.putDouble("overview_profileswitch_duration", overview_profileswitch_duration.value) @@ -104,7 +107,7 @@ class ProfileSwitchDialog : DialogFragmentWithDate() { activity?.let { activity -> OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal_profileswitch), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { - profileFunction.doProfileSwitch(profileStore, profile, duration.toInt(), percent, timeShift, eventTime) + treatmentsPlugin.doProfileSwitch(profileStore, profile, duration.toInt(), percent, timeShift, eventTime) }) } return true diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java index 43661b117a..917fa1ff66 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java @@ -1,19 +1,21 @@ package info.nightscout.androidaps.interfaces; +import org.jetbrains.annotations.NotNull; + import java.util.List; import info.nightscout.androidaps.data.DetailedBolusInfo; +import info.nightscout.androidaps.data.Intervals; import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.MealData; import info.nightscout.androidaps.data.NonOverlappingIntervals; -import info.nightscout.androidaps.data.Profile; +import info.nightscout.androidaps.data.ProfileIntervals; +import info.nightscout.androidaps.data.ProfileStore; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.ProfileSwitch; import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.plugins.treatments.Treatment; -import info.nightscout.androidaps.data.Intervals; -import info.nightscout.androidaps.data.ProfileIntervals; /** * Created by mike on 14.06.2016. @@ -62,6 +64,8 @@ public interface TreatmentsInterface { ProfileSwitch getProfileSwitchFromHistory(long time); ProfileIntervals getProfileSwitchesFromHistory(); void addToHistoryProfileSwitch(ProfileSwitch profileSwitch); + void doProfileSwitch(@NotNull final ProfileStore profileStore, @NotNull final String profileName, final int duration, final int percentage, final int timeShift, final long date); + void doProfileSwitch(final int duration, final int percentage, final int timeShift); long oldestDataAvailable(); diff --git a/app/src/main/java/info/nightscout/androidaps/logging/AAPSLogger.kt b/app/src/main/java/info/nightscout/androidaps/logging/AAPSLogger.kt index e3f74fdb10..e3bc5eafaa 100644 --- a/app/src/main/java/info/nightscout/androidaps/logging/AAPSLogger.kt +++ b/app/src/main/java/info/nightscout/androidaps/logging/AAPSLogger.kt @@ -6,8 +6,12 @@ package info.nightscout.androidaps.logging interface AAPSLogger { + fun debug(message: String) + fun debug(enable: Boolean, tag: LTag, message: String) fun debug(tag: LTag, message: String) fun info(tag: LTag, message: String) fun error(tag: LTag, message: String) + fun error(message: String) + fun error(message: String, throwable: Throwable) fun error(tag: LTag, message: String, throwable: Throwable) } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerDebug.kt b/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerDebug.kt index d512725176..346f12f749 100644 --- a/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerDebug.kt +++ b/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerDebug.kt @@ -8,6 +8,14 @@ import android.util.Log class AAPSLoggerDebug : AAPSLogger { + override fun debug(message: String) { + Log.d(LTag.CORE.tag, message) + } + + override fun debug(enable: Boolean, tag: LTag, message: String) { + if (enable) Log.d(LTag.CORE.tag, message) + } + override fun debug(tag: LTag, message: String) { Log.d(tag.tag, message) } @@ -21,6 +29,14 @@ class AAPSLoggerDebug : AAPSLogger { } + override fun error(message: String) { + Log.e(LTag.CORE.tag, message) + } + + override fun error(message: String, throwable: Throwable) { + Log.e(LTag.CORE.tag, message, throwable) + } + override fun error(tag: LTag, message: String, throwable: Throwable) { Log.e(tag.tag, message, throwable) diff --git a/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerProduction.kt b/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerProduction.kt index 414fad2859..bcc11634b1 100644 --- a/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerProduction.kt +++ b/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerProduction.kt @@ -8,10 +8,19 @@ import org.slf4j.LoggerFactory class AAPSLoggerProduction : AAPSLogger { + override fun debug(message: String) { + LoggerFactory.getLogger(LTag.CORE.tag).debug(message) + } + + override fun debug(enable: Boolean, tag: LTag, message: String) { + if (enable && L.isEnabled(tag.tag)) { + LoggerFactory.getLogger(tag.tag).debug(message) + } + } + override fun debug(tag: LTag, message: String) { if (L.isEnabled(tag.tag)) { LoggerFactory.getLogger(tag.tag).debug(message) - } } @@ -25,14 +34,20 @@ class AAPSLoggerProduction : AAPSLogger { override fun error(tag: LTag, message: String) { if (L.isEnabled(tag.tag)) { LoggerFactory.getLogger(tag.tag).error(message) - } } + override fun error(message: String) { + LoggerFactory.getLogger(LTag.CORE.tag).error(message) + } + + override fun error(message: String, throwable: Throwable) { + LoggerFactory.getLogger(LTag.CORE.tag).error(message, throwable) + } + override fun error(tag: LTag, message: String, throwable: Throwable) { if (L.isEnabled(tag.tag)) { LoggerFactory.getLogger(tag.tag).error(message, throwable) - } } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunction.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunction.kt index 6faee1c38a..0ad24d8c09 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunction.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunction.kt @@ -14,6 +14,4 @@ interface ProfileFunction { fun getUnits(): String fun getProfile(time: Long): Profile? fun prepareProfileSwitch(profileStore: ProfileStore, profileName: String, duration: Int, percentage: Int, timeShift: Int, date: Long): ProfileSwitch - fun doProfileSwitch(profileStore: ProfileStore, profileName: String, duration: Int, percentage: Int, timeShift: Int, date: Long) - fun doProfileSwitch(duration: Int, percentage: Int, timeShift: Int) } \ No newline at end of file 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 de43cf5519..1e7355e464 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 @@ -6,12 +6,11 @@ import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.ProfileStore import info.nightscout.androidaps.db.ProfileSwitch import info.nightscout.androidaps.db.Source -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.sharedPreferences.SP import java.security.spec.InvalidParameterSpecException -import javax.inject.Inject import javax.inject.Singleton +@Singleton class ProfileFunctionImplementation constructor(private val sp: SP) : ProfileFunction { override fun getProfileName(): String = @@ -34,7 +33,7 @@ class ProfileFunctionImplementation constructor(private val sp: SP) : ProfileFun } override fun getProfile(time: Long): Profile? = - getProfile(System.currentTimeMillis()) + ProfileFunctions.getInstance().getProfile(System.currentTimeMillis()) override fun getUnits(): String = sp.getString(R.string.key_units, Constants.MGDL) @@ -54,27 +53,4 @@ class ProfileFunctionImplementation constructor(private val sp: SP) : ProfileFun profileSwitch.percentage = percentage return profileSwitch } - - override fun doProfileSwitch(profileStore: ProfileStore, profileName: String, duration: Int, percentage: Int, timeShift: Int, date: Long) { - val profileSwitch = prepareProfileSwitch(profileStore, profileName, duration, percentage, timeShift, date) - TreatmentsPlugin.getPlugin().addToHistoryProfileSwitch(profileSwitch) - if (percentage == 90 && duration == 10) - sp.putBoolean(R.string.key_objectiveuseprofileswitch, true) - } - - override fun doProfileSwitch(duration: Int, percentage: Int, timeShift: Int) { - getProfile()?.let { - val profileSwitch = ProfileSwitch() - profileSwitch.date = System.currentTimeMillis() - profileSwitch.source = Source.USER - profileSwitch.profileName = ProfileFunctions.getInstance().getProfileName(System.currentTimeMillis(), customized = false, showRemainingTime = false) - profileSwitch.profileJson = it.data.toString() - profileSwitch.profilePlugin = ConfigBuilderPlugin.getPlugin().activeProfileInterface::class.java.name - profileSwitch.durationInMinutes = duration - profileSwitch.isCPP = percentage != 100 || timeShift != 0 - profileSwitch.timeshift = timeShift - profileSwitch.percentage = percentage - TreatmentsPlugin.getPlugin().addToHistoryProfileSwitch(profileSwitch) - } - } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctions.java b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctions.java index 126fc6c44d..fc58e29940 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctions.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctions.java @@ -182,30 +182,4 @@ public class ProfileFunctions implements ProfileFunction { return profileSwitch; } - public void doProfileSwitch(@NotNull final ProfileStore profileStore, @NotNull final String profileName, final int duration, final int percentage, final int timeShift, final long date) { - ProfileSwitch profileSwitch = prepareProfileSwitch(profileStore, profileName, duration, percentage, timeShift, date); - TreatmentsPlugin.getPlugin().addToHistoryProfileSwitch(profileSwitch); - if (percentage == 90 && duration == 10) - SP.putBoolean(R.string.key_objectiveuseprofileswitch, true); - } - - public void doProfileSwitch(final int duration, final int percentage, final int timeShift) { - ProfileSwitch profileSwitch = TreatmentsPlugin.getPlugin().getProfileSwitchFromHistory(System.currentTimeMillis()); - if (profileSwitch != null) { - profileSwitch = new ProfileSwitch(); - profileSwitch.date = System.currentTimeMillis(); - profileSwitch.source = Source.USER; - profileSwitch.profileName = getInstance().getProfileName(System.currentTimeMillis(), false, false); - profileSwitch.profileJson = getInstance().getProfile().getData().toString(); - profileSwitch.profilePlugin = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getClass().getName(); - profileSwitch.durationInMinutes = duration; - profileSwitch.isCPP = percentage != 100 || timeShift != 0; - profileSwitch.timeshift = timeShift; - profileSwitch.percentage = percentage; - TreatmentsPlugin.getPlugin().addToHistoryProfileSwitch(profileSwitch); - } else { - log.error("No profile switch existing"); - } - } - } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.java index b3741b7271..cb82edf3fc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.java @@ -20,6 +20,7 @@ import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; 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.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.JsonHelper; @@ -33,7 +34,7 @@ public class ActionProfileSwitch extends Action { // Prevent action if active profile is already active // but we don't have a trigger IS_NOT_EQUAL // so check is in the doRun() - ProfileInterface profileInterface = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface(); + ProfileInterface profileInterface = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface(); if (profileInterface != null) { ProfileStore profileStore = profileInterface.getProfile(); if (profileStore != null) { @@ -62,13 +63,13 @@ public class ActionProfileSwitch extends Action { String activeProfileName = ProfileFunctions.getInstance().getProfileName(); //Check for uninitialized profileName - if ( profileName.equals("")){ + if (profileName.equals("")) { log.error("Selected profile not initialized"); if (callback != null) callback.result(new PumpEnactResult().success(false).comment(R.string.error_field_must_not_be_empty)).run(); return; } - if ( ProfileFunctions.getInstance().getProfile() == null){ + if (ProfileFunctions.getInstance().getProfile() == null) { log.error("ProfileFunctions not initialized"); if (callback != null) callback.result(new PumpEnactResult().success(false).comment(R.string.noprofile)).run(); @@ -90,15 +91,15 @@ public class ActionProfileSwitch extends Action { } ProfileStore profileStore = activeProfile.getProfile(); if (profileStore == null) return; - if(profileStore.getSpecificProfile(profileName) == null) { + if (profileStore.getSpecificProfile(profileName) == null) { if (L.isEnabled(L.AUTOMATION)) - log.error("Selected profile does not exist! - "+ profileName); + log.error("Selected profile does not exist! - " + profileName); if (callback != null) callback.result(new PumpEnactResult().success(false).comment(R.string.notexists)).run(); return; } - ProfileFunctions.getInstance().doProfileSwitch(profileStore, profileName, 0, 100, 0, DateUtil.now()); + TreatmentsPlugin.getPlugin().doProfileSwitch(profileStore, profileName, 0, 100, 0, DateUtil.now()); if (callback != null) callback.result(new PumpEnactResult().success(true).comment(R.string.ok)).run(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercent.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercent.java index 71cbed7173..ba62667335 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercent.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercent.java @@ -6,21 +6,21 @@ import com.google.common.base.Optional; import org.json.JSONException; import org.json.JSONObject; +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.plugins.configBuilder.ProfileFunctions; 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; import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithElement; import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder; import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerProfilePercent; +import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.utils.JsonHelper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; public class ActionProfileSwitchPercent extends Action { private static final Logger log = LoggerFactory.getLogger(ActionProfileSwitchPercent.class); @@ -47,7 +47,7 @@ public class ActionProfileSwitchPercent extends Action { @Override public void doAction(Callback callback) { - ProfileFunctions.getInstance().doProfileSwitch((int) duration.getValue(), (int) pct.getValue(), 0); + TreatmentsPlugin.getPlugin().doProfileSwitch((int) duration.getValue(), (int) pct.getValue(), 0); if (callback != null) callback.result(new PumpEnactResult().success(true).comment(R.string.ok)).run(); } 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 46f58a8d2c..dbdd3c52c2 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 @@ -54,6 +54,7 @@ import javax.inject.Singleton @Singleton class SmsCommunicatorPlugin @Inject constructor( val configBuilderPlugin: ConfigBuilderPlugin, + val treatmentsPlugin: TreatmentsPlugin, val resourceHelper: ResourceHelper, val constraintChecker: ConstraintChecker, val aapsLogger: AAPSLogger @@ -467,7 +468,7 @@ class SmsCommunicatorPlugin @Inject constructor( val finalPercentage = percentage messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction(list[pindex - 1] as String, finalPercentage) { override fun run() { - ProfileFunctions.getInstance().doProfileSwitch(store, list[pindex - 1] as String, 0, finalPercentage, 0, DateUtil.now()) + treatmentsPlugin.doProfileSwitch(store, list[pindex - 1] as String, 0, finalPercentage, 0, DateUtil.now()) sendSMS(Sms(receivedSms.phoneNumber, R.string.profileswitchcreated)) } }) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.java index a137def1d4..3a4674938f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.java @@ -679,8 +679,7 @@ public class ActionStringHandler { } //send profile to pumpe - new NewNSTreatmentDialog(); //init - ProfileFunctions.getInstance().doProfileSwitch(0, percentage, timeshift); + TreatmentsPlugin.getPlugin().doProfileSwitch(0, percentage, timeshift); } private static void generateTempTarget(int duration, double low, double high) { 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 5183007a64..c688e332fb 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 @@ -6,12 +6,13 @@ import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.ArrayAdapter -import androidx.fragment.app.Fragment +import dagger.android.support.DaggerFragment import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions import info.nightscout.androidaps.plugins.profile.ns.events.EventNSProfileUpdateGUI +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 @@ -21,8 +22,13 @@ import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.close.* import kotlinx.android.synthetic.main.nsprofile_fragment.* import kotlinx.android.synthetic.main.profileviewer_fragment.* +import javax.inject.Inject + +class NSProfileFragment : DaggerFragment() { + + @Inject + lateinit var treatmentsPlugin: TreatmentsPlugin -class NSProfileFragment : Fragment() { private var disposable: CompositeDisposable = CompositeDisposable() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, @@ -42,7 +48,7 @@ class NSProfileFragment : Fragment() { activity?.let { activity -> OKDialog.showConfirmation(activity, MainApp.gs(R.string.nsprofile), MainApp.gs(R.string.activate_profile) + ": " + name + " ?", Runnable { - ProfileFunctions.getInstance().doProfileSwitch(store, name, 0, 100, 0, DateUtil.now()) + treatmentsPlugin.doProfileSwitch(store, name, 0, 100, 0, DateUtil.now()) }) } } 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 69589a126f..25d0a0e028 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 @@ -7,16 +7,18 @@ import androidx.annotation.Nullable; import com.google.firebase.analytics.FirebaseAnalytics; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.jetbrains.annotations.NotNull; import java.util.ArrayList; -import java.util.Date; import java.util.List; +import javax.inject.Inject; +import javax.inject.Singleton; + 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; import info.nightscout.androidaps.data.Intervals; import info.nightscout.androidaps.data.Iob; @@ -26,8 +28,10 @@ import info.nightscout.androidaps.data.NonOverlappingIntervals; import info.nightscout.androidaps.data.OverlappingIntervals; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.ProfileIntervals; +import info.nightscout.androidaps.data.ProfileStore; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.ProfileSwitch; +import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.EventReloadProfileSwitchData; @@ -40,12 +44,12 @@ import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.TreatmentsInterface; -import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; -import info.nightscout.androidaps.activities.ErrorHelperActivity; import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData; @@ -59,26 +63,33 @@ import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.T; +import info.nightscout.androidaps.utils.resources.ResourceHelper; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.schedulers.Schedulers; -/** - * Created by mike on 05.08.2016. - */ +@Singleton public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface { - private Logger log = LoggerFactory.getLogger(L.DATATREATMENTS); + private final AAPSLogger aapsLogger; + private final MainApp mainApp; + private final ResourceHelper resourceHelper; + private final ProfileFunction profileFunction; + private final ConfigBuilderPlugin configBuilderPlugin; private CompositeDisposable disposable = new CompositeDisposable(); private static TreatmentsPlugin treatmentsPlugin; + /** + * @deprecated Use dagger to get an instance + */ + @Deprecated public static TreatmentsPlugin getPlugin() { if (treatmentsPlugin == null) - treatmentsPlugin = new TreatmentsPlugin(); + throw new IllegalStateException("Accessing TreatmentsPlugin before first instantiation"); return treatmentsPlugin; } - private TreatmentService service; + protected TreatmentService service; private IobTotal lastTreatmentCalculation; private IobTotal lastTempBasalsCalculation; @@ -89,7 +100,13 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface private final Intervals tempTargets = new OverlappingIntervals<>(); private final ProfileIntervals profiles = new ProfileIntervals<>(); - public TreatmentsPlugin() { + @Inject + public TreatmentsPlugin(AAPSLogger aapsLogger, + ResourceHelper resourceHelper, + MainApp mainApp, + ConfigBuilderPlugin configBuilderPlugin, + ProfileFunction profileFunction + ) { super(new PluginDescription() .mainType(PluginType.TREATMENT) .fragmentClass(TreatmentsFragment.class.getName()) @@ -98,19 +115,24 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface .alwaysEnabled(true) .description(R.string.description_treatments) ); - this.service = new TreatmentService(); + this.aapsLogger = aapsLogger; + this.resourceHelper = resourceHelper; + this.mainApp = mainApp; + this.configBuilderPlugin = configBuilderPlugin; + this.profileFunction = profileFunction; + treatmentsPlugin = this; } @Override protected void onStart() { + this.service = new TreatmentService(); initializeData(range()); super.onStart(); disposable.add(RxBus.INSTANCE .toObservable(EventReloadTreatmentData.class) .observeOn(Schedulers.io()) .subscribe(event -> { - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("EventReloadTreatmentData"); + aapsLogger.debug(LTag.DATATREATMENTS, "EventReloadTreatmentData"); initializeTreatmentData(range()); initializeExtendedBolusData(range()); updateTotalIOBTreatments(); @@ -134,8 +156,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface .toObservable(EventReloadTempBasalData.class) .observeOn(Schedulers.io()) .subscribe(event -> { - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("EventReloadTempBasalData"); + aapsLogger.debug(LTag.DATATREATMENTS, "EventReloadTempBasalData"); initializeTempBasalData(range()); updateTotalIOBTempBasals(); }, @@ -155,9 +176,9 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface private long range() { double dia = Constants.defaultDIA; - if (ConfigBuilderPlugin.getPlugin() != null && ProfileFunctions.getInstance().getProfile() != null) - dia = ProfileFunctions.getInstance().getProfile().getDia(); - return (long) (60 * 60 * 1000L * (24 + dia)); + if (profileFunction.getProfile() != null) + dia = profileFunction.getProfile().getDia(); + return (long) (60 * 60 * 1000L * (24 + dia)); } public void initializeData(long range) { @@ -169,8 +190,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface } private void initializeTreatmentData(long range) { - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("initializeTreatmentData"); + aapsLogger.debug(LTag.DATATREATMENTS, "initializeTreatmentData"); synchronized (treatments) { treatments.clear(); treatments.addAll(getService().getTreatmentDataFromTime(DateUtil.now() - range, false)); @@ -178,8 +198,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface } private void initializeTempBasalData(long range) { - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("initializeTempBasalData"); + aapsLogger.debug(LTag.DATATREATMENTS, "initializeTempBasalData"); synchronized (tempBasals) { tempBasals.reset().add(MainApp.getDbHelper().getTemporaryBasalsDataFromTime(DateUtil.now() - range, false)); } @@ -187,8 +206,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface } private void initializeExtendedBolusData(long range) { - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("initializeExtendedBolusData"); + aapsLogger.debug(LTag.DATATREATMENTS, "initializeExtendedBolusData"); synchronized (extendedBoluses) { extendedBoluses.reset().add(MainApp.getDbHelper().getExtendedBolusDataFromTime(DateUtil.now() - range, false)); } @@ -196,16 +214,14 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface } private void initializeTempTargetData(long range) { - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("initializeTempTargetData"); + aapsLogger.debug(LTag.DATATREATMENTS, "initializeTempTargetData"); synchronized (tempTargets) { tempTargets.reset().add(MainApp.getDbHelper().getTemptargetsDataFromTime(DateUtil.now() - range, false)); } } private void initializeProfileSwitchData(long range) { - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("initializeProfileSwitchData"); + aapsLogger.debug(LTag.DATATREATMENTS, "initializeProfileSwitchData"); synchronized (profiles) { profiles.reset().add(MainApp.getDbHelper().getProfileSwitchData(DateUtil.now() - range, false)); } @@ -220,22 +236,22 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface public IobTotal getCalculationToTimeTreatments(long time) { IobTotal total = new IobTotal(time); - Profile profile = ProfileFunctions.getInstance().getProfile(); + Profile profile = profileFunction.getProfile(); if (profile == null) return total; - InsulinInterface insulinInterface = ConfigBuilderPlugin.getPlugin().getActiveInsulin(); + InsulinInterface insulinInterface = configBuilderPlugin.getActiveInsulin(); if (insulinInterface == null) return total; - PumpInterface pumpInterface = ConfigBuilderPlugin.getPlugin().getActivePump(); + PumpInterface pumpInterface = configBuilderPlugin.getActivePump(); if (pumpInterface == null) return total; double dia = profile.getDia(); synchronized (treatments) { - for (Integer pos = 0; pos < treatments.size(); pos++) { + for (int pos = 0; pos < treatments.size(); pos++) { Treatment t = treatments.get(pos); if (!t.isValid) continue; if (t.date > time) continue; @@ -276,7 +292,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface public MealData getMealData() { MealData result = new MealData(); - Profile profile = ProfileFunctions.getInstance().getProfile(); + Profile profile = profileFunction.getProfile(); if (profile == null) return result; long now = System.currentTimeMillis(); @@ -344,17 +360,13 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface long time = System.currentTimeMillis(); synchronized (treatments) { - if (MedtronicHistoryData.doubleBolusDebug) - log.debug("DoubleBolusDebug: AllTreatmentsInDb: {}", MedtronicUtil.getGsonInstanceCore().toJson(treatments)); + aapsLogger.debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: AllTreatmentsInDb: " + MedtronicUtil.getGsonInstanceCore().toJson(treatments)); for (Treatment t : treatments) { if (t.date <= time && t.date >= fromTimestamp) in5minback.add(t); } - - if (MedtronicHistoryData.doubleBolusDebug) - log.debug("DoubleBolusDebug: FilteredTreatments: AfterTime={}, Items={}", fromTimestamp, MedtronicUtil.getGsonInstanceCore().toJson(in5minback)); - + aapsLogger.debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: FilteredTreatments: AfterTime={}, Items={} " + fromTimestamp + " " + MedtronicUtil.getGsonInstanceCore().toJson(in5minback)); return in5minback; } } @@ -364,7 +376,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface public List getTreatments5MinBackFromHistory(long time) { List in5minback = new ArrayList<>(); synchronized (treatments) { - for (Integer pos = 0; pos < treatments.size(); pos++) { + for (int pos = 0; pos < treatments.size(); pos++) { Treatment t = treatments.get(pos); if (!t.isValid) continue; @@ -383,12 +395,11 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface for (Treatment t : treatments) { if (!t.isValid) continue; - if (t.date > last && t.insulin > 0 && t.isValid && t.date <= now) + if (t.date > last && t.insulin > 0 && t.date <= now) last = t.date; } } - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("Last bolus time: " + new Date(last).toLocaleString()); + aapsLogger.debug(LTag.DATATREATMENTS, "Last bolus time: " + DateUtil.dateAndTimeString(last)); return last; } @@ -399,12 +410,11 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface for (Treatment t : treatments) { if (!t.isValid) continue; - if (t.date > last && t.insulin > 0 && t.isValid && t.date <= now && isSMB == t.isSMB) + if (t.date > last && t.insulin > 0 && t.date <= now && isSMB == t.isSMB) last = t.date; } } - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("Last manual bolus time: " + new Date(last).toLocaleString()); + aapsLogger.debug(LTag.DATATREATMENTS, "Last manual bolus time: " + DateUtil.dateAndTimeString(last)); return last; } @@ -443,16 +453,20 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface public IobTotal getCalculationToTimeTempBasals(long time, boolean truncate, long truncateTime) { IobTotal total = new IobTotal(time); - InsulinInterface insulinInterface = ConfigBuilderPlugin.getPlugin().getActiveInsulin(); + InsulinInterface insulinInterface = configBuilderPlugin.getActiveInsulin(); if (insulinInterface == null) return total; + PumpInterface pumpInterface = configBuilderPlugin.getActivePump(); + if (pumpInterface == null) + return total; + synchronized (tempBasals) { for (Integer pos = 0; pos < tempBasals.size(); pos++) { TemporaryBasal t = tempBasals.get(pos); if (t.date > time) continue; IobTotal calc; - Profile profile = ProfileFunctions.getInstance().getProfile(t.date); + Profile profile = profileFunction.getProfile(t.date); if (profile == null) continue; if (truncate && t.end() > truncateTime) { TemporaryBasal dummyTemp = new TemporaryBasal(); @@ -466,14 +480,14 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface total.plus(calc); } } - if (ConfigBuilderPlugin.getPlugin().getActivePump().isFakingTempsByExtendedBoluses()) { + if (pumpInterface.isFakingTempsByExtendedBoluses()) { IobTotal totalExt = new IobTotal(time); synchronized (extendedBoluses) { - for (Integer pos = 0; pos < extendedBoluses.size(); pos++) { + for (int pos = 0; pos < extendedBoluses.size(); pos++) { ExtendedBolus e = extendedBoluses.get(pos); if (e.date > time) continue; IobTotal calc; - Profile profile = ProfileFunctions.getInstance().getProfile(e.date); + Profile profile = profileFunction.getProfile(e.date); if (profile == null) continue; if (truncate && e.end() > truncateTime) { ExtendedBolus dummyExt = new ExtendedBolus(); @@ -499,16 +513,20 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface public IobTotal getCalculationToTimeTempBasals(long time, long truncateTime, AutosensResult lastAutosensResult, boolean exercise_mode, int half_basal_exercise_target, boolean isTempTarget) { IobTotal total = new IobTotal(time); - InsulinInterface insulinInterface = ConfigBuilderPlugin.getPlugin().getActiveInsulin(); + InsulinInterface insulinInterface = configBuilderPlugin.getActiveInsulin(); if (insulinInterface == null) return total; + PumpInterface pumpInterface = configBuilderPlugin.getActivePump(); + if (pumpInterface == null) + return total; + synchronized (tempBasals) { for (int pos = 0; pos < tempBasals.size(); pos++) { TemporaryBasal t = tempBasals.get(pos); if (t.date > time) continue; IobTotal calc; - Profile profile = ProfileFunctions.getInstance().getProfile(t.date); + Profile profile = profileFunction.getProfile(t.date); if (profile == null) continue; if (t.end() > truncateTime) { TemporaryBasal dummyTemp = new TemporaryBasal(); @@ -522,14 +540,14 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface total.plus(calc); } } - if (ConfigBuilderPlugin.getPlugin().getActivePump().isFakingTempsByExtendedBoluses()) { + if (pumpInterface.isFakingTempsByExtendedBoluses()) { IobTotal totalExt = new IobTotal(time); synchronized (extendedBoluses) { for (int pos = 0; pos < extendedBoluses.size(); pos++) { ExtendedBolus e = extendedBoluses.get(pos); if (e.date > time) continue; IobTotal calc; - Profile profile = ProfileFunctions.getInstance().getProfile(e.date); + Profile profile = profileFunction.getProfile(e.date); if (profile == null) continue; if (e.end() > truncateTime) { ExtendedBolus dummyExt = new ExtendedBolus(); @@ -564,7 +582,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface if (tb != null) return tb; ExtendedBolus eb = getExtendedBolusFromHistory(time); - if (eb != null && ConfigBuilderPlugin.getPlugin().getActivePump().isFakingTempsByExtendedBoluses()) + if (eb != null && configBuilderPlugin.getActivePump().isFakingTempsByExtendedBoluses()) return new TemporaryBasal(eb); return null; } @@ -582,11 +600,11 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface boolean newRecordCreated = MainApp.getDbHelper().createOrUpdate(extendedBolus); if (newRecordCreated) { if (extendedBolus.durationInMinutes == 0) { - if (ConfigBuilderPlugin.getPlugin().getActivePump().isFakingTempsByExtendedBoluses()) + if (configBuilderPlugin.getActivePump().isFakingTempsByExtendedBoluses()) NSUpload.uploadTempBasalEnd(extendedBolus.date, true, extendedBolus.pumpId); else NSUpload.uploadExtendedBolusEnd(extendedBolus.date, extendedBolus.pumpId); - } else if (ConfigBuilderPlugin.getPlugin().getActivePump().isFakingTempsByExtendedBoluses()) + } else if (configBuilderPlugin.getActivePump().isFakingTempsByExtendedBoluses()) NSUpload.uploadTempBasalStartAbsolute(new TemporaryBasal(extendedBolus), extendedBolus.insulin); else NSUpload.uploadExtendedBolus(extendedBolus); @@ -628,8 +646,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface public boolean addToHistoryTreatment(DetailedBolusInfo detailedBolusInfo, boolean allowUpdate) { boolean medtronicPump = MedtronicUtil.isMedtronicPump(); - if (MedtronicHistoryData.doubleBolusDebug) - log.debug("DoubleBolusDebug: addToHistoryTreatment::isMedtronicPump={}", medtronicPump); + aapsLogger.debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: addToHistoryTreatment::isMedtronicPump={} " + medtronicPump); Treatment treatment = new Treatment(); treatment.date = detailedBolusInfo.date; @@ -640,13 +657,11 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface treatment.isSMB = detailedBolusInfo.isSMB; if (detailedBolusInfo.carbTime == 0) treatment.carbs = detailedBolusInfo.carbs; - treatment.source = detailedBolusInfo.source; treatment.mealBolus = treatment.carbs > 0; treatment.boluscalc = detailedBolusInfo.boluscalc != null ? detailedBolusInfo.boluscalc.toString() : null; TreatmentService.UpdateReturn creatOrUpdateResult; - if (medtronicPump && MedtronicHistoryData.doubleBolusDebug) - log.debug("DoubleBolusDebug: addToHistoryTreatment::treatment={}", treatment); + aapsLogger.debug(medtronicPump && MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: addToHistoryTreatment::treatment={} " + treatment); if (!medtronicPump) creatOrUpdateResult = getService().createOrUpdate(treatment); @@ -662,10 +677,8 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface carbsTreatment.pumpId = detailedBolusInfo.pumpId; // but this should never happen carbsTreatment.date = detailedBolusInfo.date + detailedBolusInfo.carbTime * 60 * 1000L + 1000L; // add 1 sec to make them different records carbsTreatment.carbs = detailedBolusInfo.carbs; - carbsTreatment.source = detailedBolusInfo.source; - if (medtronicPump && MedtronicHistoryData.doubleBolusDebug) - log.debug("DoubleBolusDebug: carbTime!=0, creating second treatment. CarbsTreatment={}", carbsTreatment); + aapsLogger.debug(medtronicPump && MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: carbTime!=0, creating second treatment. CarbsTreatment={}" + carbsTreatment); if (!medtronicPump) getService().createOrUpdate(carbsTreatment); @@ -677,16 +690,16 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface NSUpload.uploadTreatmentRecord(detailedBolusInfo); if (!allowUpdate && !creatOrUpdateResult.success) { - log.error("Treatment could not be added to DB", new Exception()); + aapsLogger.error("Treatment could not be added to DB", new Exception()); - String status = String.format(MainApp.gs(R.string.error_adding_treatment_message), treatment.insulin, (int) treatment.carbs, DateUtil.dateAndTimeString(treatment.date)); + String status = String.format(resourceHelper.gs(R.string.error_adding_treatment_message), treatment.insulin, (int) treatment.carbs, DateUtil.dateAndTimeString(treatment.date)); - Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class); + Intent i = new Intent(mainApp, ErrorHelperActivity.class); i.putExtra("soundid", R.raw.error); - i.putExtra("title", MainApp.gs(R.string.error_adding_treatment_title)); + i.putExtra("title", resourceHelper.gs(R.string.error_adding_treatment_title)); i.putExtra("status", status); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - MainApp.instance().startActivity(i); + mainApp.startActivity(i); Bundle bundle = new Bundle(); bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "TreatmentClash"); @@ -769,5 +782,32 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface NSUpload.uploadProfileSwitch(profileSwitch); } + @Override + public void doProfileSwitch(@NotNull final ProfileStore profileStore, @NotNull final String profileName, final int duration, final int percentage, final int timeShift, final long date) { + ProfileSwitch profileSwitch = profileFunction.prepareProfileSwitch(profileStore, profileName, duration, percentage, timeShift, date); + TreatmentsPlugin.getPlugin().addToHistoryProfileSwitch(profileSwitch); + if (percentage == 90 && duration == 10) + SP.putBoolean(R.string.key_objectiveuseprofileswitch, true); + } + + @Override + public void doProfileSwitch(final int duration, final int percentage, final int timeShift) { + ProfileSwitch profileSwitch = TreatmentsPlugin.getPlugin().getProfileSwitchFromHistory(System.currentTimeMillis()); + if (profileSwitch != null) { + profileSwitch = new ProfileSwitch(); + profileSwitch.date = System.currentTimeMillis(); + profileSwitch.source = Source.USER; + profileSwitch.profileName = profileFunction.getProfileName(System.currentTimeMillis(), false, false); + profileSwitch.profileJson = profileFunction.getProfile().getData().toString(); + profileSwitch.profilePlugin = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getClass().getName(); + profileSwitch.durationInMinutes = duration; + profileSwitch.isCPP = percentage != 100 || timeShift != 0; + profileSwitch.timeshift = timeShift; + profileSwitch.percentage = percentage; + TreatmentsPlugin.getPlugin().addToHistoryProfileSwitch(profileSwitch); + } else { + aapsLogger.error(LTag.PROFILE, "No profile switch exists"); + } + } } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/TddCalculator.kt b/app/src/main/java/info/nightscout/androidaps/utils/TddCalculator.kt index 0210247eb3..e86e78c5af 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/TddCalculator.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/TddCalculator.kt @@ -5,13 +5,26 @@ import android.util.LongSparseArray import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.db.TDD -import info.nightscout.androidaps.logging.L -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.plugins.treatments.TreatmentService import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin -import org.slf4j.LoggerFactory +import info.nightscout.androidaps.utils.resources.ResourceHelper +import javax.inject.Inject -object TddCalculator : TreatmentsPlugin() { - private val log = LoggerFactory.getLogger(L.DATATREATMENTS) +class TddCalculator @Inject constructor( + val aapsLogger: AAPSLogger, + val resourceHelper: ResourceHelper, + val mainApp: MainApp, + val configBuilderPlugin: ConfigBuilderPlugin, + val profileFunction: ProfileFunction +) : TreatmentsPlugin(aapsLogger, resourceHelper, mainApp, configBuilderPlugin, profileFunction) { + + init { + service = TreatmentService() // plugin is not started + } fun calculate(days: Long): LongSparseArray { val range = T.days(days + 1).msecs() @@ -33,7 +46,7 @@ object TddCalculator : TreatmentsPlugin() { val midnight = MidnightTime.calc(t) val tdd = result[midnight] ?: TDD(midnight, 0.0, 0.0, 0.0) val tbr = getTempBasalFromHistory(t) - val profile = ProfileFunctions.getInstance().getProfile(t) ?: continue + val profile = profileFunction.getProfile(t) ?: continue val absoluteRate = tbr?.tempBasalConvertedToAbsolute(t, profile) ?: profile.getBasal(t) tdd.basal += absoluteRate / 60.0 * 5.0 result.put(midnight, tdd) @@ -42,11 +55,11 @@ object TddCalculator : TreatmentsPlugin() { val tdd = result.valueAt(i) tdd.total = tdd.bolus + tdd.basal } - log.debug(result.toString()) + aapsLogger.debug(LTag.CORE, result.toString()) return result } - fun averageTDD(tdds: LongSparseArray): TDD { + private fun averageTDD(tdds: LongSparseArray): TDD { val totalTdd = TDD() for (i in 0 until tdds.size()) { val tdd = tdds.valueAt(i) @@ -71,7 +84,7 @@ object TddCalculator : TreatmentsPlugin() { ) } - fun toText(tdds: LongSparseArray): String { + private fun toText(tdds: LongSparseArray): String { var t = "" for (i in 0 until tdds.size()) { t += "${tdds.valueAt(i).toText()}
"