TreatmentsPlugin -> dagger

This commit is contained in:
Milos Kozak 2019-12-28 22:51:04 +01:00
parent 377b5a9991
commit ca9486fab3
23 changed files with 276 additions and 215 deletions

View file

@ -37,9 +37,6 @@ import com.joanzapata.iconify.fonts.FontAwesomeModule;
import javax.inject.Inject; import javax.inject.Inject;
import dagger.android.AndroidInjection; 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.HistoryBrowseActivity;
import info.nightscout.androidaps.activities.NoSplashAppCompatActivity; import info.nightscout.androidaps.activities.NoSplashAppCompatActivity;
import info.nightscout.androidaps.activities.PreferencesActivity; 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.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.CompositeDisposable;
public class MainActivity extends NoSplashAppCompatActivity implements HasAndroidInjector { public class MainActivity extends NoSplashAppCompatActivity {
@Inject
DispatchingAndroidInjector<Object> androidInjector;
private CompositeDisposable disposable = new CompositeDisposable(); private CompositeDisposable disposable = new CompositeDisposable();
@ -354,12 +348,4 @@ public class MainActivity extends NoSplashAppCompatActivity implements HasAndroi
return actionBarDrawerToggle.onOptionsItemSelected(item); return actionBarDrawerToggle.onOptionsItemSelected(item);
} }
/**
* Returns an {@link AndroidInjector}.
*/
@Override
public AndroidInjector<Object> androidInjector() {
return androidInjector;
}
} }

View file

@ -136,6 +136,7 @@ public class MainApp extends DaggerApplication {
@Inject OpenAPSAMAPlugin openAPSAMAPlugin; @Inject OpenAPSAMAPlugin openAPSAMAPlugin;
@Inject OpenAPSSMBPlugin openAPSSMBPlugin; @Inject OpenAPSSMBPlugin openAPSSMBPlugin;
@Inject StatusLinePlugin statusLinePlugin; @Inject StatusLinePlugin statusLinePlugin;
@Inject TreatmentsPlugin treatmentsPlugin;
@Override @Override
public void onCreate() { public void onCreate() {
@ -215,7 +216,7 @@ public class MainApp extends DaggerApplication {
if (Config.APS) pluginsList.add(openAPSSMBPlugin); if (Config.APS) pluginsList.add(openAPSSMBPlugin);
pluginsList.add(NSProfilePlugin.getPlugin()); pluginsList.add(NSProfilePlugin.getPlugin());
if (!Config.NSCLIENT) pluginsList.add(LocalProfilePlugin.INSTANCE); 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(safetyPlugin);
if (!Config.NSCLIENT) pluginsList.add(VersionCheckerPlugin.INSTANCE); if (!Config.NSCLIENT) pluginsList.add(VersionCheckerPlugin.INSTANCE);
if (Config.APS) pluginsList.add(StorageConstraintPlugin.getPlugin()); if (Config.APS) pluginsList.add(StorageConstraintPlugin.getPlugin());

View file

@ -2,11 +2,13 @@ package info.nightscout.androidaps.activities
import android.content.Context import android.content.Context
import android.os.Bundle import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity import dagger.android.support.DaggerAppCompatActivity
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.utils.LocaleHelper import info.nightscout.androidaps.utils.LocaleHelper
open class NoSplashAppCompatActivity : AppCompatActivity() { @Suppress("registered")
open class NoSplashAppCompatActivity : DaggerAppCompatActivity() {
public override fun onCreate(savedInstanceState: Bundle?) { public override fun onCreate(savedInstanceState: Bundle?) {
setTheme(R.style.AppTheme_NoActionBar) setTheme(R.style.AppTheme_NoActionBar)
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)

View file

@ -8,14 +8,18 @@ import info.nightscout.androidaps.utils.OKDialog
import info.nightscout.androidaps.utils.TddCalculator import info.nightscout.androidaps.utils.TddCalculator
import info.nightscout.androidaps.utils.TirCalculator import info.nightscout.androidaps.utils.TirCalculator
import kotlinx.android.synthetic.main.stats_activity.* import kotlinx.android.synthetic.main.stats_activity.*
import javax.inject.Inject
class StatsActivity : NoSplashAppCompatActivity() { class StatsActivity : NoSplashAppCompatActivity() {
@Inject
lateinit var tddCalculator: TddCalculator
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
setContentView(R.layout.stats_activity) setContentView(R.layout.stats_activity)
stats_tdds.text = TddCalculator.stats() stats_tdds.text = tddCalculator.stats()
stats_tir.text = TirCalculator.stats() stats_tir.text = TirCalculator.stats()
stats_activity.text = ActivityMonitor.stats() stats_activity.text = ActivityMonitor.stats()

View file

@ -12,10 +12,14 @@ import info.nightscout.androidaps.dialogs.ProfileViewerDialog
import info.nightscout.androidaps.utils.* import info.nightscout.androidaps.utils.*
import kotlinx.android.synthetic.main.survey_activity.* import kotlinx.android.synthetic.main.survey_activity.*
import org.slf4j.LoggerFactory import org.slf4j.LoggerFactory
import javax.inject.Inject
class SurveyActivity : NoSplashAppCompatActivity() { class SurveyActivity : NoSplashAppCompatActivity() {
private val log = LoggerFactory.getLogger(SurveyActivity::class.java) private val log = LoggerFactory.getLogger(SurveyActivity::class.java)
@Inject
lateinit var tddCalculator: TddCalculator
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
setContentView(R.layout.survey_activity) setContentView(R.layout.survey_activity)
@ -26,7 +30,7 @@ class SurveyActivity : NoSplashAppCompatActivity() {
val profileList = profileStore?.getProfileList() ?: return val profileList = profileStore?.getProfileList() ?: return
survey_spinner.adapter = ArrayAdapter(this, R.layout.spinner_centered, profileList) 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_tir.text = TirCalculator.stats()
survey_activity.text = ActivityMonitor.stats() survey_activity.text = ActivityMonitor.stats()

View file

@ -3,14 +3,44 @@ package info.nightscout.androidaps.dependencyInjection
import dagger.Module import dagger.Module
import dagger.android.ContributesAndroidInjector import dagger.android.ContributesAndroidInjector
import info.nightscout.androidaps.MainActivity 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 @Module
abstract class ActivitiesModule { abstract class ActivitiesModule {
@ContributesAndroidInjector @ContributesAndroidInjector abstract fun contributesBLEScanActivity(): BLEScanActivity
abstract fun contributeMainActivity(): MainActivity @ContributesAndroidInjector abstract fun contributeBolusProgressHelperActivity(): BolusProgressHelperActivity
@ContributesAndroidInjector abstract fun contributeDanaRHistoryActivity(): DanaRHistoryActivity
@ContributesAndroidInjector @ContributesAndroidInjector abstract fun contributeDanaRUserOptionsActivity(): DanaRUserOptionsActivity
abstract fun contributesPreferencesActivity(): PreferencesActivity @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
} }

View file

@ -17,6 +17,7 @@ import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctionImplementation import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctionImplementation
import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective5 import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective5
import info.nightscout.androidaps.plugins.general.automation.actions.ActionSendSMS 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.queue.commands.CommandSetProfile
import info.nightscout.androidaps.services.DataService import info.nightscout.androidaps.services.DataService
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper

View file

@ -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.openAPSMA.OpenAPSMAFragment
import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBFragment import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBFragment
import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorFragment import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorFragment
import info.nightscout.androidaps.plugins.profile.ns.NSProfileFragment
@Module @Module
abstract class FragmentsModule { abstract class FragmentsModule {
@ContributesAndroidInjector @ContributesAndroidInjector abstract fun contributesPreferencesFragment(): MyPreferenceFragment
abstract fun contributesPreferencesFragment(): MyPreferenceFragment @ContributesAndroidInjector abstract fun contributesOpenAPSAMAFragment(): OpenAPSAMAFragment
@ContributesAndroidInjector abstract fun contributesOpenAPSMAFragment(): OpenAPSMAFragment
@ContributesAndroidInjector @ContributesAndroidInjector abstract fun contributesOpenAPSSMBFragment(): OpenAPSSMBFragment
abstract fun contributesOpenAPSAMAFragment(): OpenAPSAMAFragment @ContributesAndroidInjector abstract fun contributesNSProfileFragment(): NSProfileFragment
@ContributesAndroidInjector abstract fun contributesSmsCommunicatorFragment(): SmsCommunicatorFragment
@ContributesAndroidInjector @ContributesAndroidInjector abstract fun contributesCalibrationDialog(): CalibrationDialog
abstract fun contributesOpenAPSMAFragment(): OpenAPSMAFragment @ContributesAndroidInjector abstract fun contributesCarbsDialog(): CarbsDialog
@ContributesAndroidInjector abstract fun contributesCareDialog(): CareDialog
@ContributesAndroidInjector @ContributesAndroidInjector abstract fun contributesExtendedBolusDialog(): ExtendedBolusDialog
abstract fun contributesOpenAPSSMBFragment(): OpenAPSSMBFragment @ContributesAndroidInjector abstract fun contributesFillDialog(): FillDialog
@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 @ContributesAndroidInjector
abstract fun contributesInsulinDialog(): InsulinDialog abstract fun contributesInsulinDialog(): InsulinDialog

View file

@ -30,6 +30,9 @@ class ProfileSwitchDialog : DialogFragmentWithDate() {
@Inject @Inject
lateinit var profileFunction: ProfileFunction lateinit var profileFunction: ProfileFunction
@Inject
lateinit var treatmentsPlugin: TreatmentsPlugin
override fun onSaveInstanceState(savedInstanceState: Bundle) { override fun onSaveInstanceState(savedInstanceState: Bundle) {
super.onSaveInstanceState(savedInstanceState) super.onSaveInstanceState(savedInstanceState)
savedInstanceState.putDouble("overview_profileswitch_duration", overview_profileswitch_duration.value) savedInstanceState.putDouble("overview_profileswitch_duration", overview_profileswitch_duration.value)
@ -104,7 +107,7 @@ class ProfileSwitchDialog : DialogFragmentWithDate() {
activity?.let { activity -> activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal_profileswitch), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), Runnable { OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal_profileswitch), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), Runnable {
profileFunction.doProfileSwitch(profileStore, profile, duration.toInt(), percent, timeShift, eventTime) treatmentsPlugin.doProfileSwitch(profileStore, profile, duration.toInt(), percent, timeShift, eventTime)
}) })
} }
return true return true

View file

@ -1,19 +1,21 @@
package info.nightscout.androidaps.interfaces; package info.nightscout.androidaps.interfaces;
import org.jetbrains.annotations.NotNull;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Intervals;
import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData; import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.data.NonOverlappingIntervals; 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.ExtendedBolus;
import info.nightscout.androidaps.db.ProfileSwitch; import info.nightscout.androidaps.db.ProfileSwitch;
import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.plugins.treatments.Treatment; 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. * Created by mike on 14.06.2016.
@ -62,6 +64,8 @@ public interface TreatmentsInterface {
ProfileSwitch getProfileSwitchFromHistory(long time); ProfileSwitch getProfileSwitchFromHistory(long time);
ProfileIntervals<ProfileSwitch> getProfileSwitchesFromHistory(); ProfileIntervals<ProfileSwitch> getProfileSwitchesFromHistory();
void addToHistoryProfileSwitch(ProfileSwitch profileSwitch); 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(); long oldestDataAvailable();

View file

@ -6,8 +6,12 @@ package info.nightscout.androidaps.logging
interface AAPSLogger { interface AAPSLogger {
fun debug(message: String)
fun debug(enable: Boolean, tag: LTag, message: String)
fun debug(tag: LTag, message: String) fun debug(tag: LTag, message: String)
fun info(tag: LTag, message: String) fun info(tag: LTag, message: String)
fun error(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) fun error(tag: LTag, message: String, throwable: Throwable)
} }

View file

@ -8,6 +8,14 @@ import android.util.Log
class AAPSLoggerDebug : AAPSLogger { 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) { override fun debug(tag: LTag, message: String) {
Log.d(tag.tag, message) 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) { override fun error(tag: LTag, message: String, throwable: Throwable) {
Log.e(tag.tag, message, throwable) Log.e(tag.tag, message, throwable)

View file

@ -8,10 +8,19 @@ import org.slf4j.LoggerFactory
class AAPSLoggerProduction : AAPSLogger { 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) { override fun debug(tag: LTag, message: String) {
if (L.isEnabled(tag.tag)) { if (L.isEnabled(tag.tag)) {
LoggerFactory.getLogger(tag.tag).debug(message) LoggerFactory.getLogger(tag.tag).debug(message)
} }
} }
@ -25,14 +34,20 @@ class AAPSLoggerProduction : AAPSLogger {
override fun error(tag: LTag, message: String) { override fun error(tag: LTag, message: String) {
if (L.isEnabled(tag.tag)) { if (L.isEnabled(tag.tag)) {
LoggerFactory.getLogger(tag.tag).error(message) 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) { override fun error(tag: LTag, message: String, throwable: Throwable) {
if (L.isEnabled(tag.tag)) { if (L.isEnabled(tag.tag)) {
LoggerFactory.getLogger(tag.tag).error(message, throwable) LoggerFactory.getLogger(tag.tag).error(message, throwable)
} }
} }
} }

View file

@ -14,6 +14,4 @@ interface ProfileFunction {
fun getUnits(): String fun getUnits(): String
fun getProfile(time: Long): Profile? fun getProfile(time: Long): Profile?
fun prepareProfileSwitch(profileStore: ProfileStore, profileName: String, duration: Int, percentage: Int, timeShift: Int, date: Long): ProfileSwitch 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)
} }

View file

@ -6,12 +6,11 @@ import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.data.ProfileStore import info.nightscout.androidaps.data.ProfileStore
import info.nightscout.androidaps.db.ProfileSwitch import info.nightscout.androidaps.db.ProfileSwitch
import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.db.Source
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import java.security.spec.InvalidParameterSpecException import java.security.spec.InvalidParameterSpecException
import javax.inject.Inject
import javax.inject.Singleton import javax.inject.Singleton
@Singleton
class ProfileFunctionImplementation constructor(private val sp: SP) : ProfileFunction { class ProfileFunctionImplementation constructor(private val sp: SP) : ProfileFunction {
override fun getProfileName(): String = override fun getProfileName(): String =
@ -34,7 +33,7 @@ class ProfileFunctionImplementation constructor(private val sp: SP) : ProfileFun
} }
override fun getProfile(time: Long): Profile? = override fun getProfile(time: Long): Profile? =
getProfile(System.currentTimeMillis()) ProfileFunctions.getInstance().getProfile(System.currentTimeMillis())
override fun getUnits(): String = override fun getUnits(): String =
sp.getString(R.string.key_units, Constants.MGDL) sp.getString(R.string.key_units, Constants.MGDL)
@ -54,27 +53,4 @@ class ProfileFunctionImplementation constructor(private val sp: SP) : ProfileFun
profileSwitch.percentage = percentage profileSwitch.percentage = percentage
return profileSwitch 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)
}
}
} }

View file

@ -182,30 +182,4 @@ public class ProfileFunctions implements ProfileFunction {
return profileSwitch; 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");
}
}
} }

View file

@ -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.InputProfileName;
import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithElement; 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.elements.LayoutBuilder;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.JsonHelper; import info.nightscout.androidaps.utils.JsonHelper;
@ -98,7 +99,7 @@ public class ActionProfileSwitch extends Action {
return; return;
} }
ProfileFunctions.getInstance().doProfileSwitch(profileStore, profileName, 0, 100, 0, DateUtil.now()); TreatmentsPlugin.getPlugin().doProfileSwitch(profileStore, profileName, 0, 100, 0, DateUtil.now());
if (callback != null) if (callback != null)
callback.result(new PumpEnactResult().success(true).comment(R.string.ok)).run(); callback.result(new PumpEnactResult().success(true).comment(R.string.ok)).run();
} }

View file

@ -6,21 +6,21 @@ import com.google.common.base.Optional;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.PumpEnactResult; 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.Comparator;
import info.nightscout.androidaps.plugins.general.automation.elements.InputDuration; 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.InputPercent;
import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithElement; 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.elements.LayoutBuilder;
import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerProfilePercent; 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.queue.Callback;
import info.nightscout.androidaps.utils.JsonHelper; import info.nightscout.androidaps.utils.JsonHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ActionProfileSwitchPercent extends Action { public class ActionProfileSwitchPercent extends Action {
private static final Logger log = LoggerFactory.getLogger(ActionProfileSwitchPercent.class); private static final Logger log = LoggerFactory.getLogger(ActionProfileSwitchPercent.class);
@ -47,7 +47,7 @@ public class ActionProfileSwitchPercent extends Action {
@Override @Override
public void doAction(Callback callback) { 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) if (callback != null)
callback.result(new PumpEnactResult().success(true).comment(R.string.ok)).run(); callback.result(new PumpEnactResult().success(true).comment(R.string.ok)).run();
} }

View file

@ -54,6 +54,7 @@ import javax.inject.Singleton
@Singleton @Singleton
class SmsCommunicatorPlugin @Inject constructor( class SmsCommunicatorPlugin @Inject constructor(
val configBuilderPlugin: ConfigBuilderPlugin, val configBuilderPlugin: ConfigBuilderPlugin,
val treatmentsPlugin: TreatmentsPlugin,
val resourceHelper: ResourceHelper, val resourceHelper: ResourceHelper,
val constraintChecker: ConstraintChecker, val constraintChecker: ConstraintChecker,
val aapsLogger: AAPSLogger val aapsLogger: AAPSLogger
@ -467,7 +468,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val finalPercentage = percentage val finalPercentage = percentage
messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction(list[pindex - 1] as String, finalPercentage) { messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction(list[pindex - 1] as String, finalPercentage) {
override fun run() { 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)) sendSMS(Sms(receivedSms.phoneNumber, R.string.profileswitchcreated))
} }
}) })

View file

@ -679,8 +679,7 @@ public class ActionStringHandler {
} }
//send profile to pumpe //send profile to pumpe
new NewNSTreatmentDialog(); //init TreatmentsPlugin.getPlugin().doProfileSwitch(0, percentage, timeshift);
ProfileFunctions.getInstance().doProfileSwitch(0, percentage, timeshift);
} }
private static void generateTempTarget(int duration, double low, double high) { private static void generateTempTarget(int duration, double low, double high) {

View file

@ -6,12 +6,13 @@ import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import android.widget.AdapterView import android.widget.AdapterView
import android.widget.ArrayAdapter import android.widget.ArrayAdapter
import androidx.fragment.app.Fragment import dagger.android.support.DaggerFragment
import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions
import info.nightscout.androidaps.plugins.profile.ns.events.EventNSProfileUpdateGUI 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.DateUtil
import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.DecimalFormatter
import info.nightscout.androidaps.utils.FabricPrivacy 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.close.*
import kotlinx.android.synthetic.main.nsprofile_fragment.* import kotlinx.android.synthetic.main.nsprofile_fragment.*
import kotlinx.android.synthetic.main.profileviewer_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() private var disposable: CompositeDisposable = CompositeDisposable()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
@ -42,7 +48,7 @@ class NSProfileFragment : Fragment() {
activity?.let { activity -> activity?.let { activity ->
OKDialog.showConfirmation(activity, MainApp.gs(R.string.nsprofile), OKDialog.showConfirmation(activity, MainApp.gs(R.string.nsprofile),
MainApp.gs(R.string.activate_profile) + ": " + name + " ?", Runnable { 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())
}) })
} }
} }

View file

@ -7,16 +7,18 @@ import androidx.annotation.Nullable;
import com.google.firebase.analytics.FirebaseAnalytics; import com.google.firebase.analytics.FirebaseAnalytics;
import org.slf4j.Logger; import org.jetbrains.annotations.NotNull;
import org.slf4j.LoggerFactory;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date;
import java.util.List; import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.activities.ErrorHelperActivity;
import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Intervals; import info.nightscout.androidaps.data.Intervals;
import info.nightscout.androidaps.data.Iob; 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.OverlappingIntervals;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.ProfileIntervals; import info.nightscout.androidaps.data.ProfileIntervals;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.ProfileSwitch; import info.nightscout.androidaps.db.ProfileSwitch;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.events.EventReloadProfileSwitchData; 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.PluginType;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface; 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.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; 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.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.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData; 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.FabricPrivacy;
import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.SP;
import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.T;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers; import io.reactivex.schedulers.Schedulers;
/** @Singleton
* Created by mike on 05.08.2016.
*/
public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface { 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 CompositeDisposable disposable = new CompositeDisposable();
private static TreatmentsPlugin treatmentsPlugin; private static TreatmentsPlugin treatmentsPlugin;
/**
* @deprecated Use dagger to get an instance
*/
@Deprecated
public static TreatmentsPlugin getPlugin() { public static TreatmentsPlugin getPlugin() {
if (treatmentsPlugin == null) if (treatmentsPlugin == null)
treatmentsPlugin = new TreatmentsPlugin(); throw new IllegalStateException("Accessing TreatmentsPlugin before first instantiation");
return treatmentsPlugin; return treatmentsPlugin;
} }
private TreatmentService service; protected TreatmentService service;
private IobTotal lastTreatmentCalculation; private IobTotal lastTreatmentCalculation;
private IobTotal lastTempBasalsCalculation; private IobTotal lastTempBasalsCalculation;
@ -89,7 +100,13 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
private final Intervals<TempTarget> tempTargets = new OverlappingIntervals<>(); private final Intervals<TempTarget> tempTargets = new OverlappingIntervals<>();
private final ProfileIntervals<ProfileSwitch> profiles = new ProfileIntervals<>(); private final ProfileIntervals<ProfileSwitch> profiles = new ProfileIntervals<>();
public TreatmentsPlugin() { @Inject
public TreatmentsPlugin(AAPSLogger aapsLogger,
ResourceHelper resourceHelper,
MainApp mainApp,
ConfigBuilderPlugin configBuilderPlugin,
ProfileFunction profileFunction
) {
super(new PluginDescription() super(new PluginDescription()
.mainType(PluginType.TREATMENT) .mainType(PluginType.TREATMENT)
.fragmentClass(TreatmentsFragment.class.getName()) .fragmentClass(TreatmentsFragment.class.getName())
@ -98,19 +115,24 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
.alwaysEnabled(true) .alwaysEnabled(true)
.description(R.string.description_treatments) .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 @Override
protected void onStart() { protected void onStart() {
this.service = new TreatmentService();
initializeData(range()); initializeData(range());
super.onStart(); super.onStart();
disposable.add(RxBus.INSTANCE disposable.add(RxBus.INSTANCE
.toObservable(EventReloadTreatmentData.class) .toObservable(EventReloadTreatmentData.class)
.observeOn(Schedulers.io()) .observeOn(Schedulers.io())
.subscribe(event -> { .subscribe(event -> {
if (L.isEnabled(L.DATATREATMENTS)) aapsLogger.debug(LTag.DATATREATMENTS, "EventReloadTreatmentData");
log.debug("EventReloadTreatmentData");
initializeTreatmentData(range()); initializeTreatmentData(range());
initializeExtendedBolusData(range()); initializeExtendedBolusData(range());
updateTotalIOBTreatments(); updateTotalIOBTreatments();
@ -134,8 +156,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
.toObservable(EventReloadTempBasalData.class) .toObservable(EventReloadTempBasalData.class)
.observeOn(Schedulers.io()) .observeOn(Schedulers.io())
.subscribe(event -> { .subscribe(event -> {
if (L.isEnabled(L.DATATREATMENTS)) aapsLogger.debug(LTag.DATATREATMENTS, "EventReloadTempBasalData");
log.debug("EventReloadTempBasalData");
initializeTempBasalData(range()); initializeTempBasalData(range());
updateTotalIOBTempBasals(); updateTotalIOBTempBasals();
}, },
@ -155,8 +176,8 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
private long range() { private long range() {
double dia = Constants.defaultDIA; double dia = Constants.defaultDIA;
if (ConfigBuilderPlugin.getPlugin() != null && ProfileFunctions.getInstance().getProfile() != null) if (profileFunction.getProfile() != null)
dia = ProfileFunctions.getInstance().getProfile().getDia(); dia = profileFunction.getProfile().getDia();
return (long) (60 * 60 * 1000L * (24 + dia)); return (long) (60 * 60 * 1000L * (24 + dia));
} }
@ -169,8 +190,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
} }
private void initializeTreatmentData(long range) { private void initializeTreatmentData(long range) {
if (L.isEnabled(L.DATATREATMENTS)) aapsLogger.debug(LTag.DATATREATMENTS, "initializeTreatmentData");
log.debug("initializeTreatmentData");
synchronized (treatments) { synchronized (treatments) {
treatments.clear(); treatments.clear();
treatments.addAll(getService().getTreatmentDataFromTime(DateUtil.now() - range, false)); treatments.addAll(getService().getTreatmentDataFromTime(DateUtil.now() - range, false));
@ -178,8 +198,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
} }
private void initializeTempBasalData(long range) { private void initializeTempBasalData(long range) {
if (L.isEnabled(L.DATATREATMENTS)) aapsLogger.debug(LTag.DATATREATMENTS, "initializeTempBasalData");
log.debug("initializeTempBasalData");
synchronized (tempBasals) { synchronized (tempBasals) {
tempBasals.reset().add(MainApp.getDbHelper().getTemporaryBasalsDataFromTime(DateUtil.now() - range, false)); 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) { private void initializeExtendedBolusData(long range) {
if (L.isEnabled(L.DATATREATMENTS)) aapsLogger.debug(LTag.DATATREATMENTS, "initializeExtendedBolusData");
log.debug("initializeExtendedBolusData");
synchronized (extendedBoluses) { synchronized (extendedBoluses) {
extendedBoluses.reset().add(MainApp.getDbHelper().getExtendedBolusDataFromTime(DateUtil.now() - range, false)); 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) { private void initializeTempTargetData(long range) {
if (L.isEnabled(L.DATATREATMENTS)) aapsLogger.debug(LTag.DATATREATMENTS, "initializeTempTargetData");
log.debug("initializeTempTargetData");
synchronized (tempTargets) { synchronized (tempTargets) {
tempTargets.reset().add(MainApp.getDbHelper().getTemptargetsDataFromTime(DateUtil.now() - range, false)); tempTargets.reset().add(MainApp.getDbHelper().getTemptargetsDataFromTime(DateUtil.now() - range, false));
} }
} }
private void initializeProfileSwitchData(long range) { private void initializeProfileSwitchData(long range) {
if (L.isEnabled(L.DATATREATMENTS)) aapsLogger.debug(LTag.DATATREATMENTS, "initializeProfileSwitchData");
log.debug("initializeProfileSwitchData");
synchronized (profiles) { synchronized (profiles) {
profiles.reset().add(MainApp.getDbHelper().getProfileSwitchData(DateUtil.now() - range, false)); 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) { public IobTotal getCalculationToTimeTreatments(long time) {
IobTotal total = new IobTotal(time); IobTotal total = new IobTotal(time);
Profile profile = ProfileFunctions.getInstance().getProfile(); Profile profile = profileFunction.getProfile();
if (profile == null) if (profile == null)
return total; return total;
InsulinInterface insulinInterface = ConfigBuilderPlugin.getPlugin().getActiveInsulin(); InsulinInterface insulinInterface = configBuilderPlugin.getActiveInsulin();
if (insulinInterface == null) if (insulinInterface == null)
return total; return total;
PumpInterface pumpInterface = ConfigBuilderPlugin.getPlugin().getActivePump(); PumpInterface pumpInterface = configBuilderPlugin.getActivePump();
if (pumpInterface == null) if (pumpInterface == null)
return total; return total;
double dia = profile.getDia(); double dia = profile.getDia();
synchronized (treatments) { synchronized (treatments) {
for (Integer pos = 0; pos < treatments.size(); pos++) { for (int pos = 0; pos < treatments.size(); pos++) {
Treatment t = treatments.get(pos); Treatment t = treatments.get(pos);
if (!t.isValid) continue; if (!t.isValid) continue;
if (t.date > time) continue; if (t.date > time) continue;
@ -276,7 +292,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
public MealData getMealData() { public MealData getMealData() {
MealData result = new MealData(); MealData result = new MealData();
Profile profile = ProfileFunctions.getInstance().getProfile(); Profile profile = profileFunction.getProfile();
if (profile == null) return result; if (profile == null) return result;
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
@ -344,17 +360,13 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
long time = System.currentTimeMillis(); long time = System.currentTimeMillis();
synchronized (treatments) { synchronized (treatments) {
if (MedtronicHistoryData.doubleBolusDebug) aapsLogger.debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: AllTreatmentsInDb: " + MedtronicUtil.getGsonInstanceCore().toJson(treatments));
log.debug("DoubleBolusDebug: AllTreatmentsInDb: {}", MedtronicUtil.getGsonInstanceCore().toJson(treatments));
for (Treatment t : treatments) { for (Treatment t : treatments) {
if (t.date <= time && t.date >= fromTimestamp) if (t.date <= time && t.date >= fromTimestamp)
in5minback.add(t); in5minback.add(t);
} }
aapsLogger.debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: FilteredTreatments: AfterTime={}, Items={} " + fromTimestamp + " " + MedtronicUtil.getGsonInstanceCore().toJson(in5minback));
if (MedtronicHistoryData.doubleBolusDebug)
log.debug("DoubleBolusDebug: FilteredTreatments: AfterTime={}, Items={}", fromTimestamp, MedtronicUtil.getGsonInstanceCore().toJson(in5minback));
return in5minback; return in5minback;
} }
} }
@ -364,7 +376,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
public List<Treatment> getTreatments5MinBackFromHistory(long time) { public List<Treatment> getTreatments5MinBackFromHistory(long time) {
List<Treatment> in5minback = new ArrayList<>(); List<Treatment> in5minback = new ArrayList<>();
synchronized (treatments) { synchronized (treatments) {
for (Integer pos = 0; pos < treatments.size(); pos++) { for (int pos = 0; pos < treatments.size(); pos++) {
Treatment t = treatments.get(pos); Treatment t = treatments.get(pos);
if (!t.isValid) if (!t.isValid)
continue; continue;
@ -383,12 +395,11 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
for (Treatment t : treatments) { for (Treatment t : treatments) {
if (!t.isValid) if (!t.isValid)
continue; 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; last = t.date;
} }
} }
if (L.isEnabled(L.DATATREATMENTS)) aapsLogger.debug(LTag.DATATREATMENTS, "Last bolus time: " + DateUtil.dateAndTimeString(last));
log.debug("Last bolus time: " + new Date(last).toLocaleString());
return last; return last;
} }
@ -399,12 +410,11 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
for (Treatment t : treatments) { for (Treatment t : treatments) {
if (!t.isValid) if (!t.isValid)
continue; 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; last = t.date;
} }
} }
if (L.isEnabled(L.DATATREATMENTS)) aapsLogger.debug(LTag.DATATREATMENTS, "Last manual bolus time: " + DateUtil.dateAndTimeString(last));
log.debug("Last manual bolus time: " + new Date(last).toLocaleString());
return last; return last;
} }
@ -443,16 +453,20 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
public IobTotal getCalculationToTimeTempBasals(long time, boolean truncate, long truncateTime) { public IobTotal getCalculationToTimeTempBasals(long time, boolean truncate, long truncateTime) {
IobTotal total = new IobTotal(time); IobTotal total = new IobTotal(time);
InsulinInterface insulinInterface = ConfigBuilderPlugin.getPlugin().getActiveInsulin(); InsulinInterface insulinInterface = configBuilderPlugin.getActiveInsulin();
if (insulinInterface == null) if (insulinInterface == null)
return total; return total;
PumpInterface pumpInterface = configBuilderPlugin.getActivePump();
if (pumpInterface == null)
return total;
synchronized (tempBasals) { synchronized (tempBasals) {
for (Integer pos = 0; pos < tempBasals.size(); pos++) { for (Integer pos = 0; pos < tempBasals.size(); pos++) {
TemporaryBasal t = tempBasals.get(pos); TemporaryBasal t = tempBasals.get(pos);
if (t.date > time) continue; if (t.date > time) continue;
IobTotal calc; IobTotal calc;
Profile profile = ProfileFunctions.getInstance().getProfile(t.date); Profile profile = profileFunction.getProfile(t.date);
if (profile == null) continue; if (profile == null) continue;
if (truncate && t.end() > truncateTime) { if (truncate && t.end() > truncateTime) {
TemporaryBasal dummyTemp = new TemporaryBasal(); TemporaryBasal dummyTemp = new TemporaryBasal();
@ -466,14 +480,14 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
total.plus(calc); total.plus(calc);
} }
} }
if (ConfigBuilderPlugin.getPlugin().getActivePump().isFakingTempsByExtendedBoluses()) { if (pumpInterface.isFakingTempsByExtendedBoluses()) {
IobTotal totalExt = new IobTotal(time); IobTotal totalExt = new IobTotal(time);
synchronized (extendedBoluses) { synchronized (extendedBoluses) {
for (Integer pos = 0; pos < extendedBoluses.size(); pos++) { for (int pos = 0; pos < extendedBoluses.size(); pos++) {
ExtendedBolus e = extendedBoluses.get(pos); ExtendedBolus e = extendedBoluses.get(pos);
if (e.date > time) continue; if (e.date > time) continue;
IobTotal calc; IobTotal calc;
Profile profile = ProfileFunctions.getInstance().getProfile(e.date); Profile profile = profileFunction.getProfile(e.date);
if (profile == null) continue; if (profile == null) continue;
if (truncate && e.end() > truncateTime) { if (truncate && e.end() > truncateTime) {
ExtendedBolus dummyExt = new ExtendedBolus(); 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) { public IobTotal getCalculationToTimeTempBasals(long time, long truncateTime, AutosensResult lastAutosensResult, boolean exercise_mode, int half_basal_exercise_target, boolean isTempTarget) {
IobTotal total = new IobTotal(time); IobTotal total = new IobTotal(time);
InsulinInterface insulinInterface = ConfigBuilderPlugin.getPlugin().getActiveInsulin(); InsulinInterface insulinInterface = configBuilderPlugin.getActiveInsulin();
if (insulinInterface == null) if (insulinInterface == null)
return total; return total;
PumpInterface pumpInterface = configBuilderPlugin.getActivePump();
if (pumpInterface == null)
return total;
synchronized (tempBasals) { synchronized (tempBasals) {
for (int pos = 0; pos < tempBasals.size(); pos++) { for (int pos = 0; pos < tempBasals.size(); pos++) {
TemporaryBasal t = tempBasals.get(pos); TemporaryBasal t = tempBasals.get(pos);
if (t.date > time) continue; if (t.date > time) continue;
IobTotal calc; IobTotal calc;
Profile profile = ProfileFunctions.getInstance().getProfile(t.date); Profile profile = profileFunction.getProfile(t.date);
if (profile == null) continue; if (profile == null) continue;
if (t.end() > truncateTime) { if (t.end() > truncateTime) {
TemporaryBasal dummyTemp = new TemporaryBasal(); TemporaryBasal dummyTemp = new TemporaryBasal();
@ -522,14 +540,14 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
total.plus(calc); total.plus(calc);
} }
} }
if (ConfigBuilderPlugin.getPlugin().getActivePump().isFakingTempsByExtendedBoluses()) { if (pumpInterface.isFakingTempsByExtendedBoluses()) {
IobTotal totalExt = new IobTotal(time); IobTotal totalExt = new IobTotal(time);
synchronized (extendedBoluses) { synchronized (extendedBoluses) {
for (int pos = 0; pos < extendedBoluses.size(); pos++) { for (int pos = 0; pos < extendedBoluses.size(); pos++) {
ExtendedBolus e = extendedBoluses.get(pos); ExtendedBolus e = extendedBoluses.get(pos);
if (e.date > time) continue; if (e.date > time) continue;
IobTotal calc; IobTotal calc;
Profile profile = ProfileFunctions.getInstance().getProfile(e.date); Profile profile = profileFunction.getProfile(e.date);
if (profile == null) continue; if (profile == null) continue;
if (e.end() > truncateTime) { if (e.end() > truncateTime) {
ExtendedBolus dummyExt = new ExtendedBolus(); ExtendedBolus dummyExt = new ExtendedBolus();
@ -564,7 +582,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
if (tb != null) if (tb != null)
return tb; return tb;
ExtendedBolus eb = getExtendedBolusFromHistory(time); ExtendedBolus eb = getExtendedBolusFromHistory(time);
if (eb != null && ConfigBuilderPlugin.getPlugin().getActivePump().isFakingTempsByExtendedBoluses()) if (eb != null && configBuilderPlugin.getActivePump().isFakingTempsByExtendedBoluses())
return new TemporaryBasal(eb); return new TemporaryBasal(eb);
return null; return null;
} }
@ -582,11 +600,11 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
boolean newRecordCreated = MainApp.getDbHelper().createOrUpdate(extendedBolus); boolean newRecordCreated = MainApp.getDbHelper().createOrUpdate(extendedBolus);
if (newRecordCreated) { if (newRecordCreated) {
if (extendedBolus.durationInMinutes == 0) { if (extendedBolus.durationInMinutes == 0) {
if (ConfigBuilderPlugin.getPlugin().getActivePump().isFakingTempsByExtendedBoluses()) if (configBuilderPlugin.getActivePump().isFakingTempsByExtendedBoluses())
NSUpload.uploadTempBasalEnd(extendedBolus.date, true, extendedBolus.pumpId); NSUpload.uploadTempBasalEnd(extendedBolus.date, true, extendedBolus.pumpId);
else else
NSUpload.uploadExtendedBolusEnd(extendedBolus.date, extendedBolus.pumpId); NSUpload.uploadExtendedBolusEnd(extendedBolus.date, extendedBolus.pumpId);
} else if (ConfigBuilderPlugin.getPlugin().getActivePump().isFakingTempsByExtendedBoluses()) } else if (configBuilderPlugin.getActivePump().isFakingTempsByExtendedBoluses())
NSUpload.uploadTempBasalStartAbsolute(new TemporaryBasal(extendedBolus), extendedBolus.insulin); NSUpload.uploadTempBasalStartAbsolute(new TemporaryBasal(extendedBolus), extendedBolus.insulin);
else else
NSUpload.uploadExtendedBolus(extendedBolus); NSUpload.uploadExtendedBolus(extendedBolus);
@ -628,8 +646,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
public boolean addToHistoryTreatment(DetailedBolusInfo detailedBolusInfo, boolean allowUpdate) { public boolean addToHistoryTreatment(DetailedBolusInfo detailedBolusInfo, boolean allowUpdate) {
boolean medtronicPump = MedtronicUtil.isMedtronicPump(); boolean medtronicPump = MedtronicUtil.isMedtronicPump();
if (MedtronicHistoryData.doubleBolusDebug) aapsLogger.debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: addToHistoryTreatment::isMedtronicPump={} " + medtronicPump);
log.debug("DoubleBolusDebug: addToHistoryTreatment::isMedtronicPump={}", medtronicPump);
Treatment treatment = new Treatment(); Treatment treatment = new Treatment();
treatment.date = detailedBolusInfo.date; treatment.date = detailedBolusInfo.date;
@ -640,13 +657,11 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
treatment.isSMB = detailedBolusInfo.isSMB; treatment.isSMB = detailedBolusInfo.isSMB;
if (detailedBolusInfo.carbTime == 0) if (detailedBolusInfo.carbTime == 0)
treatment.carbs = detailedBolusInfo.carbs; treatment.carbs = detailedBolusInfo.carbs;
treatment.source = detailedBolusInfo.source;
treatment.mealBolus = treatment.carbs > 0; treatment.mealBolus = treatment.carbs > 0;
treatment.boluscalc = detailedBolusInfo.boluscalc != null ? detailedBolusInfo.boluscalc.toString() : null; treatment.boluscalc = detailedBolusInfo.boluscalc != null ? detailedBolusInfo.boluscalc.toString() : null;
TreatmentService.UpdateReturn creatOrUpdateResult; TreatmentService.UpdateReturn creatOrUpdateResult;
if (medtronicPump && MedtronicHistoryData.doubleBolusDebug) aapsLogger.debug(medtronicPump && MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: addToHistoryTreatment::treatment={} " + treatment);
log.debug("DoubleBolusDebug: addToHistoryTreatment::treatment={}", treatment);
if (!medtronicPump) if (!medtronicPump)
creatOrUpdateResult = getService().createOrUpdate(treatment); 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.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.date = detailedBolusInfo.date + detailedBolusInfo.carbTime * 60 * 1000L + 1000L; // add 1 sec to make them different records
carbsTreatment.carbs = detailedBolusInfo.carbs; carbsTreatment.carbs = detailedBolusInfo.carbs;
carbsTreatment.source = detailedBolusInfo.source;
if (medtronicPump && MedtronicHistoryData.doubleBolusDebug) aapsLogger.debug(medtronicPump && MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: carbTime!=0, creating second treatment. CarbsTreatment={}" + carbsTreatment);
log.debug("DoubleBolusDebug: carbTime!=0, creating second treatment. CarbsTreatment={}", carbsTreatment);
if (!medtronicPump) if (!medtronicPump)
getService().createOrUpdate(carbsTreatment); getService().createOrUpdate(carbsTreatment);
@ -677,16 +690,16 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
NSUpload.uploadTreatmentRecord(detailedBolusInfo); NSUpload.uploadTreatmentRecord(detailedBolusInfo);
if (!allowUpdate && !creatOrUpdateResult.success) { 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("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.putExtra("status", status);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainApp.instance().startActivity(i); mainApp.startActivity(i);
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "TreatmentClash"); bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "TreatmentClash");
@ -769,5 +782,32 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
NSUpload.uploadProfileSwitch(profileSwitch); 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");
}
}
} }

View file

@ -5,13 +5,26 @@ import android.util.LongSparseArray
import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.db.TDD import info.nightscout.androidaps.db.TDD
import info.nightscout.androidaps.logging.L import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions 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 info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import org.slf4j.LoggerFactory import info.nightscout.androidaps.utils.resources.ResourceHelper
import javax.inject.Inject
object TddCalculator : TreatmentsPlugin() { class TddCalculator @Inject constructor(
private val log = LoggerFactory.getLogger(L.DATATREATMENTS) 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<TDD> { fun calculate(days: Long): LongSparseArray<TDD> {
val range = T.days(days + 1).msecs() val range = T.days(days + 1).msecs()
@ -33,7 +46,7 @@ object TddCalculator : TreatmentsPlugin() {
val midnight = MidnightTime.calc(t) val midnight = MidnightTime.calc(t)
val tdd = result[midnight] ?: TDD(midnight, 0.0, 0.0, 0.0) val tdd = result[midnight] ?: TDD(midnight, 0.0, 0.0, 0.0)
val tbr = getTempBasalFromHistory(t) 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) val absoluteRate = tbr?.tempBasalConvertedToAbsolute(t, profile) ?: profile.getBasal(t)
tdd.basal += absoluteRate / 60.0 * 5.0 tdd.basal += absoluteRate / 60.0 * 5.0
result.put(midnight, tdd) result.put(midnight, tdd)
@ -42,11 +55,11 @@ object TddCalculator : TreatmentsPlugin() {
val tdd = result.valueAt(i) val tdd = result.valueAt(i)
tdd.total = tdd.bolus + tdd.basal tdd.total = tdd.bolus + tdd.basal
} }
log.debug(result.toString()) aapsLogger.debug(LTag.CORE, result.toString())
return result return result
} }
fun averageTDD(tdds: LongSparseArray<TDD>): TDD { private fun averageTDD(tdds: LongSparseArray<TDD>): TDD {
val totalTdd = TDD() val totalTdd = TDD()
for (i in 0 until tdds.size()) { for (i in 0 until tdds.size()) {
val tdd = tdds.valueAt(i) val tdd = tdds.valueAt(i)
@ -71,7 +84,7 @@ object TddCalculator : TreatmentsPlugin() {
) )
} }
fun toText(tdds: LongSparseArray<TDD>): String { private fun toText(tdds: LongSparseArray<TDD>): String {
var t = "" var t = ""
for (i in 0 until tdds.size()) { for (i in 0 until tdds.size()) {
t += "${tdds.valueAt(i).toText()}<br>" t += "${tdds.valueAt(i).toText()}<br>"