More Injections and tests

This commit is contained in:
Milos Kozak 2020-03-14 16:47:48 +01:00
parent cdda4caa07
commit 6e9db1f512
51 changed files with 1072 additions and 1067 deletions

View file

@ -61,6 +61,7 @@ import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.LocaleHelper; import info.nightscout.androidaps.utils.LocaleHelper;
import info.nightscout.androidaps.utils.OKDialog; import info.nightscout.androidaps.utils.OKDialog;
import info.nightscout.androidaps.utils.PasswordProtection; import info.nightscout.androidaps.utils.PasswordProtection;
import info.nightscout.androidaps.utils.build.BuildHelper;
import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP; import info.nightscout.androidaps.utils.sharedPreferences.SP;
import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.android.schedulers.AndroidSchedulers;
@ -82,6 +83,7 @@ public class MainActivity extends NoSplashAppCompatActivity {
@Inject SmsCommunicatorPlugin smsCommunicatorPlugin; @Inject SmsCommunicatorPlugin smsCommunicatorPlugin;
@Inject LoopPlugin loopPlugin; @Inject LoopPlugin loopPlugin;
@Inject NSSettingsStatus nsSettingsStatus; @Inject NSSettingsStatus nsSettingsStatus;
@Inject BuildHelper buildHelper;
@Override @Override
@ -316,7 +318,7 @@ public class MainActivity extends NoSplashAppCompatActivity {
String message = "Build: " + BuildConfig.BUILDVERSION + "\n"; String message = "Build: " + BuildConfig.BUILDVERSION + "\n";
message += "Flavor: " + BuildConfig.FLAVOR + BuildConfig.BUILD_TYPE + "\n"; message += "Flavor: " + BuildConfig.FLAVOR + BuildConfig.BUILD_TYPE + "\n";
message += resourceHelper.gs(R.string.configbuilder_nightscoutversion_label) + " " + nsSettingsStatus.getNightscoutVersionName(); message += resourceHelper.gs(R.string.configbuilder_nightscoutversion_label) + " " + nsSettingsStatus.getNightscoutVersionName();
if (MainApp.engineeringMode) if (buildHelper.isEngineeringMode())
message += "\n" + resourceHelper.gs(R.string.engineering_mode_enabled); message += "\n" + resourceHelper.gs(R.string.engineering_mode_enabled);
message += resourceHelper.gs(R.string.about_link_urls); message += resourceHelper.gs(R.string.about_link_urls);
final SpannableString messageSpanned = new SpannableString(message); final SpannableString messageSpanned = new SpannableString(message);

View file

@ -129,9 +129,6 @@ public class MainApp extends DaggerApplication {
static DataReceiver dataReceiver = new DataReceiver(); static DataReceiver dataReceiver = new DataReceiver();
TimeDateOrTZChangeReceiver timeDateOrTZChangeReceiver; TimeDateOrTZChangeReceiver timeDateOrTZChangeReceiver;
public static boolean devBranch;
public static boolean engineeringMode;
private String CHANNEL_ID = "AndroidAPS-Ongoing"; // TODO: move to OngoingNotificationProvider (and dagger) private String CHANNEL_ID = "AndroidAPS-Ongoing"; // TODO: move to OngoingNotificationProvider (and dagger)
private int ONGOING_NOTIFICATION_ID = 4711; // TODO: move to OngoingNotificationProvider (and dagger) private int ONGOING_NOTIFICATION_ID = 4711; // TODO: move to OngoingNotificationProvider (and dagger)
private Notification notification; // TODO: move to OngoingNotificationProvider (and dagger) private Notification notification; // TODO: move to OngoingNotificationProvider (and dagger)
@ -238,12 +235,6 @@ public class MainApp extends DaggerApplication {
log.info("BuildVersion: " + BuildConfig.BUILDVERSION); log.info("BuildVersion: " + BuildConfig.BUILDVERSION);
log.info("Remote: " + BuildConfig.REMOTE); log.info("Remote: " + BuildConfig.REMOTE);
String extFilesDir = LoggerUtils.getLogDirectory();
File engineeringModeSemaphore = new File(extFilesDir, "engineering_mode");
engineeringMode = engineeringModeSemaphore.exists() && engineeringModeSemaphore.isFile();
devBranch = BuildConfig.VERSION.contains("-") || BuildConfig.VERSION.matches(".*[a-zA-Z]+.*");
registerLocalBroadcastReceiver(); registerLocalBroadcastReceiver();
//trigger here to see the new version on app start after an update //trigger here to see the new version on app start after an update
@ -467,16 +458,6 @@ public class MainApp extends DaggerApplication {
return newList; return newList;
} }
public static boolean isEngineeringModeOrRelease() {
if (!Config.APS)
return true;
return engineeringMode || !devBranch;
}
public static boolean isDev() {
return devBranch;
}
// global Notification has been moved to MainApp because PersistentNotificationPlugin is initialized too late // global Notification has been moved to MainApp because PersistentNotificationPlugin is initialized too late
private void generateEmptyNotification() { private void generateEmptyNotification() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID); NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID);

View file

@ -72,12 +72,17 @@ interface AppComponent : AndroidInjector<MainApp> {
fun injectCommandTempBasalPercent(commandTempBasalPercent: CommandTempBasalPercent) fun injectCommandTempBasalPercent(commandTempBasalPercent: CommandTempBasalPercent)
fun injectCommandSetUserSettings(commandSetUserSettings: CommandSetUserSettings) fun injectCommandSetUserSettings(commandSetUserSettings: CommandSetUserSettings)
fun injectObjective(objective: Objective)
fun injectObjective0(objective0: Objective0) fun injectObjective0(objective0: Objective0)
fun injectObjective1(objective1: Objective1) fun injectObjective1(objective1: Objective1)
fun injectObjective2(objective2: Objective2) fun injectObjective2(objective2: Objective2)
fun injectObjective3(objective3: Objective3) fun injectObjective3(objective3: Objective3)
fun injectObjective3(objective4: Objective4)
fun injectObjective5(objective5: Objective5) fun injectObjective5(objective5: Objective5)
fun injectObjective6(objective6: Objective6) fun injectObjective6(objective6: Objective6)
fun injectObjective6(objective7: Objective7)
fun injectObjective6(objective8: Objective8)
fun injectObjective6(objective9: Objective9)
fun injectAutomationEvent(automationEvent: AutomationEvent) fun injectAutomationEvent(automationEvent: AutomationEvent)

View file

@ -118,12 +118,17 @@ open class AppModule {
@ContributesAndroidInjector fun commandTempBasalPercentInjector(): CommandTempBasalPercent @ContributesAndroidInjector fun commandTempBasalPercentInjector(): CommandTempBasalPercent
@ContributesAndroidInjector fun commandSetUserSettingsInjector(): CommandSetUserSettings @ContributesAndroidInjector fun commandSetUserSettingsInjector(): CommandSetUserSettings
@ContributesAndroidInjector fun objectiveInjector(): Objective
@ContributesAndroidInjector fun objective0Injector(): Objective0 @ContributesAndroidInjector fun objective0Injector(): Objective0
@ContributesAndroidInjector fun objective1Injector(): Objective1 @ContributesAndroidInjector fun objective1Injector(): Objective1
@ContributesAndroidInjector fun objective2Injector(): Objective2 @ContributesAndroidInjector fun objective2Injector(): Objective2
@ContributesAndroidInjector fun objective3Injector(): Objective3 @ContributesAndroidInjector fun objective3Injector(): Objective3
@ContributesAndroidInjector fun objective4Injector(): Objective4
@ContributesAndroidInjector fun objective5Injector(): Objective5 @ContributesAndroidInjector fun objective5Injector(): Objective5
@ContributesAndroidInjector fun objective6Injector(): Objective6 @ContributesAndroidInjector fun objective6Injector(): Objective6
@ContributesAndroidInjector fun objective7Injector(): Objective7
@ContributesAndroidInjector fun objective8Injector(): Objective8
@ContributesAndroidInjector fun objective9Injector(): Objective9
@ContributesAndroidInjector fun automationEventInjector(): AutomationEvent @ContributesAndroidInjector fun automationEventInjector(): AutomationEvent

View file

@ -23,7 +23,6 @@ import java.util.Date;
import javax.inject.Inject; import javax.inject.Inject;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.activities.NoSplashAppCompatActivity; import info.nightscout.androidaps.activities.NoSplashAppCompatActivity;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
@ -42,6 +41,7 @@ import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.DefaultValueHelper; import info.nightscout.androidaps.utils.DefaultValueHelper;
import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.T;
import info.nightscout.androidaps.utils.build.BuildHelper;
import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP; import info.nightscout.androidaps.utils.sharedPreferences.SP;
import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.android.schedulers.AndroidSchedulers;
@ -56,6 +56,7 @@ public class HistoryBrowseActivity extends NoSplashAppCompatActivity {
@Inject DefaultValueHelper defaultValueHelper; @Inject DefaultValueHelper defaultValueHelper;
@Inject IobCobStaticCalculatorPlugin iobCobStaticCalculatorPlugin; @Inject IobCobStaticCalculatorPlugin iobCobStaticCalculatorPlugin;
@Inject ConfigBuilderPlugin configBuilderPlugin; @Inject ConfigBuilderPlugin configBuilderPlugin;
@Inject BuildHelper buildHelper;
private CompositeDisposable disposable = new CompositeDisposable(); private CompositeDisposable disposable = new CompositeDisposable();
@ -441,7 +442,7 @@ public class HistoryBrowseActivity extends NoSplashAppCompatActivity {
item.setChecked(showActSec); item.setChecked(showActSec);
if (MainApp.devBranch) { if (buildHelper.isDev()) {
item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.DEVSLOPE.ordinal(), Menu.NONE, "Deviation slope"); item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.DEVSLOPE.ordinal(), Menu.NONE, "Deviation slope");
title = item.getTitle(); title = item.getTitle();
if (titleMaxChars < title.length()) titleMaxChars = title.length(); if (titleMaxChars < title.length()) titleMaxChars = title.length();

View file

@ -106,7 +106,7 @@ public class Constraint<T extends Comparable> {
return sb.toString(); return sb.toString();
} }
private List<String> getReasonList() { public List<String> getReasonList() {
return reasons; return reasons;
} }

View file

@ -1,12 +1,13 @@
package info.nightscout.androidaps.plugins.aps.openAPSAMA; package info.nightscout.androidaps.plugins.aps.openAPSAMA;
import android.content.Context;
import org.json.JSONException; import org.json.JSONException;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
import dagger.android.HasAndroidInjector; import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData; import info.nightscout.androidaps.data.MealData;
@ -46,10 +47,11 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
private final ConstraintChecker constraintChecker; private final ConstraintChecker constraintChecker;
private final ResourceHelper resourceHelper; private final ResourceHelper resourceHelper;
private final ProfileFunction profileFunction; private final ProfileFunction profileFunction;
private final MainApp mainApp; private final Context context;
private final ActivePluginProvider activePlugin; private final ActivePluginProvider activePlugin;
private final TreatmentsPlugin treatmentsPlugin; private final TreatmentsPlugin treatmentsPlugin;
private final IobCobCalculatorPlugin iobCobCalculatorPlugin; private final IobCobCalculatorPlugin iobCobCalculatorPlugin;
private final HardLimits hardLimits;
// last values // last values
DetermineBasalAdapterAMAJS lastDetermineBasalAdapterAMAJS = null; DetermineBasalAdapterAMAJS lastDetermineBasalAdapterAMAJS = null;
@ -65,10 +67,11 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
ConstraintChecker constraintChecker, ConstraintChecker constraintChecker,
ResourceHelper resourceHelper, ResourceHelper resourceHelper,
ProfileFunction profileFunction, ProfileFunction profileFunction,
MainApp mainApp, Context context,
ActivePluginProvider activePlugin, ActivePluginProvider activePlugin,
TreatmentsPlugin treatmentsPlugin, TreatmentsPlugin treatmentsPlugin,
IobCobCalculatorPlugin iobCobCalculatorPlugin IobCobCalculatorPlugin iobCobCalculatorPlugin,
HardLimits hardLimits
) { ) {
super(new PluginDescription() super(new PluginDescription()
.mainType(PluginType.APS) .mainType(PluginType.APS)
@ -84,10 +87,11 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
this.constraintChecker = constraintChecker; this.constraintChecker = constraintChecker;
this.resourceHelper = resourceHelper; this.resourceHelper = resourceHelper;
this.profileFunction = profileFunction; this.profileFunction = profileFunction;
this.mainApp = mainApp; this.context = context;
this.activePlugin = activePlugin; this.activePlugin = activePlugin;
this.treatmentsPlugin = treatmentsPlugin; this.treatmentsPlugin = treatmentsPlugin;
this.iobCobCalculatorPlugin = iobCobCalculatorPlugin; this.iobCobCalculatorPlugin = iobCobCalculatorPlugin;
this.hardLimits = hardLimits;
} }
@Override @Override
@ -121,7 +125,7 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
aapsLogger.debug(LTag.APS, "invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback); aapsLogger.debug(LTag.APS, "invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback);
lastAPSResult = null; lastAPSResult = null;
DetermineBasalAdapterAMAJS determineBasalAdapterAMAJS; DetermineBasalAdapterAMAJS determineBasalAdapterAMAJS;
determineBasalAdapterAMAJS = new DetermineBasalAdapterAMAJS(new ScriptReader(mainApp), getInjector()); determineBasalAdapterAMAJS = new DetermineBasalAdapterAMAJS(new ScriptReader(context), getInjector());
GlucoseStatus glucoseStatus = new GlucoseStatus(getInjector()).getGlucoseStatusData(); GlucoseStatus glucoseStatus = new GlucoseStatus(getInjector()).getGlucoseStatusData();
Profile profile = profileFunction.getProfile(); Profile profile = profileFunction.getProfile();
@ -170,29 +174,29 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
double maxIob = constraintChecker.getMaxIOBAllowed().value(); double maxIob = constraintChecker.getMaxIOBAllowed().value();
minBg = HardLimits.verifyHardLimits(minBg, "minBg", HardLimits.VERY_HARD_LIMIT_MIN_BG[0], HardLimits.VERY_HARD_LIMIT_MIN_BG[1]); minBg = hardLimits.verifyHardLimits(minBg, "minBg", hardLimits.getVERY_HARD_LIMIT_MIN_BG()[0], hardLimits.getVERY_HARD_LIMIT_MIN_BG()[1]);
maxBg = HardLimits.verifyHardLimits(maxBg, "maxBg", HardLimits.VERY_HARD_LIMIT_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_MAX_BG[1]); maxBg = hardLimits.verifyHardLimits(maxBg, "maxBg", hardLimits.getVERY_HARD_LIMIT_MAX_BG()[0], hardLimits.getVERY_HARD_LIMIT_MAX_BG()[1]);
targetBg = HardLimits.verifyHardLimits(targetBg, "targetBg", HardLimits.VERY_HARD_LIMIT_TARGET_BG[0], HardLimits.VERY_HARD_LIMIT_TARGET_BG[1]); targetBg = hardLimits.verifyHardLimits(targetBg, "targetBg", hardLimits.getVERY_HARD_LIMIT_TARGET_BG()[0], hardLimits.getVERY_HARD_LIMIT_TARGET_BG()[1]);
boolean isTempTarget = false; boolean isTempTarget = false;
TempTarget tempTarget = treatmentsPlugin.getTempTargetFromHistory(System.currentTimeMillis()); TempTarget tempTarget = treatmentsPlugin.getTempTargetFromHistory(System.currentTimeMillis());
if (tempTarget != null) { if (tempTarget != null) {
isTempTarget = true; isTempTarget = true;
minBg = HardLimits.verifyHardLimits(tempTarget.low, "minBg", HardLimits.VERY_HARD_LIMIT_TEMP_MIN_BG[0], HardLimits.VERY_HARD_LIMIT_TEMP_MIN_BG[1]); minBg = hardLimits.verifyHardLimits(tempTarget.low, "minBg", hardLimits.getVERY_HARD_LIMIT_TEMP_MIN_BG()[0], hardLimits.getVERY_HARD_LIMIT_TEMP_MIN_BG()[1]);
maxBg = HardLimits.verifyHardLimits(tempTarget.high, "maxBg", HardLimits.VERY_HARD_LIMIT_TEMP_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_TEMP_MAX_BG[1]); maxBg = hardLimits.verifyHardLimits(tempTarget.high, "maxBg", hardLimits.getVERY_HARD_LIMIT_TEMP_MAX_BG()[0], hardLimits.getVERY_HARD_LIMIT_TEMP_MAX_BG()[1]);
targetBg = HardLimits.verifyHardLimits(tempTarget.target(), "targetBg", HardLimits.VERY_HARD_LIMIT_TEMP_TARGET_BG[0], HardLimits.VERY_HARD_LIMIT_TEMP_TARGET_BG[1]); targetBg = hardLimits.verifyHardLimits(tempTarget.target(), "targetBg", hardLimits.getVERY_HARD_LIMIT_TEMP_TARGET_BG()[0], hardLimits.getVERY_HARD_LIMIT_TEMP_TARGET_BG()[1]);
} }
if (!HardLimits.checkOnlyHardLimits(profile.getDia(), "dia", HardLimits.MINDIA, HardLimits.MAXDIA)) if (!hardLimits.checkOnlyHardLimits(profile.getDia(), "dia", hardLimits.getMINDIA(), hardLimits.getMAXDIA()))
return; return;
if (!HardLimits.checkOnlyHardLimits(profile.getIcTimeFromMidnight(Profile.secondsFromMidnight()), "carbratio", HardLimits.MINIC, HardLimits.MAXIC)) if (!hardLimits.checkOnlyHardLimits(profile.getIcTimeFromMidnight(Profile.secondsFromMidnight()), "carbratio", hardLimits.getMINIC(), hardLimits.getMAXIC()))
return; return;
if (!HardLimits.checkOnlyHardLimits(profile.getIsfMgdl(), "sens", HardLimits.MINISF, HardLimits.MAXISF)) if (!hardLimits.checkOnlyHardLimits(profile.getIsfMgdl(), "sens", hardLimits.getMINISF(), hardLimits.getMAXISF()))
return; return;
if (!HardLimits.checkOnlyHardLimits(profile.getMaxDailyBasal(), "max_daily_basal", 0.02, HardLimits.maxBasal())) if (!hardLimits.checkOnlyHardLimits(profile.getMaxDailyBasal(), "max_daily_basal", 0.02, hardLimits.maxBasal()))
return; return;
if (!HardLimits.checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, HardLimits.maxBasal())) if (!hardLimits.checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, hardLimits.maxBasal()))
return; return;
startPart = System.currentTimeMillis(); startPart = System.currentTimeMillis();

View file

@ -1,12 +1,13 @@
package info.nightscout.androidaps.plugins.aps.openAPSMA; package info.nightscout.androidaps.plugins.aps.openAPSMA;
import android.content.Context;
import org.json.JSONException; import org.json.JSONException;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
import dagger.android.HasAndroidInjector; import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData; import info.nightscout.androidaps.data.MealData;
@ -37,19 +38,17 @@ import info.nightscout.androidaps.utils.Profiler;
import info.nightscout.androidaps.utils.Round; import info.nightscout.androidaps.utils.Round;
import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper;
import static info.nightscout.androidaps.utils.HardLimits.checkOnlyHardLimits;
import static info.nightscout.androidaps.utils.HardLimits.verifyHardLimits;
@Singleton @Singleton
public class OpenAPSMAPlugin extends PluginBase implements APSInterface { public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
private final RxBusWrapper rxBus; private final RxBusWrapper rxBus;
private final ConstraintChecker constraintChecker; private final ConstraintChecker constraintChecker;
private final ResourceHelper resourceHelper; private final ResourceHelper resourceHelper;
private final ProfileFunction profileFunction; private final ProfileFunction profileFunction;
private final MainApp mainApp; private final Context context;
private final ActivePluginProvider activePlugin; private final ActivePluginProvider activePlugin;
private final TreatmentsPlugin treatmentsPlugin; private final TreatmentsPlugin treatmentsPlugin;
private final IobCobCalculatorPlugin iobCobCalculatorPlugin; private final IobCobCalculatorPlugin iobCobCalculatorPlugin;
private final HardLimits hardLimits;
// last values // last values
DetermineBasalAdapterMAJS lastDetermineBasalAdapterMAJS = null; DetermineBasalAdapterMAJS lastDetermineBasalAdapterMAJS = null;
@ -64,10 +63,11 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
ConstraintChecker constraintChecker, ConstraintChecker constraintChecker,
ResourceHelper resourceHelper, ResourceHelper resourceHelper,
ProfileFunction profileFunction, ProfileFunction profileFunction,
MainApp mainApp, Context context,
ActivePluginProvider activePlugin, ActivePluginProvider activePlugin,
TreatmentsPlugin treatmentsPlugin, TreatmentsPlugin treatmentsPlugin,
IobCobCalculatorPlugin iobCobCalculatorPlugin IobCobCalculatorPlugin iobCobCalculatorPlugin,
HardLimits hardLimits
) { ) {
super(new PluginDescription() super(new PluginDescription()
.mainType(PluginType.APS) .mainType(PluginType.APS)
@ -82,11 +82,12 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
this.constraintChecker = constraintChecker; this.constraintChecker = constraintChecker;
this.resourceHelper = resourceHelper; this.resourceHelper = resourceHelper;
this.profileFunction = profileFunction; this.profileFunction = profileFunction;
this.mainApp = mainApp; this.context = context;
this.rxBus = rxBus; this.rxBus = rxBus;
this.activePlugin = activePlugin; this.activePlugin = activePlugin;
this.treatmentsPlugin = treatmentsPlugin; this.treatmentsPlugin = treatmentsPlugin;
this.iobCobCalculatorPlugin = iobCobCalculatorPlugin; this.iobCobCalculatorPlugin = iobCobCalculatorPlugin;
this.hardLimits = hardLimits;
} }
@Override @Override
@ -120,7 +121,7 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
getAapsLogger().debug(LTag.APS, "invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback); getAapsLogger().debug(LTag.APS, "invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback);
lastAPSResult = null; lastAPSResult = null;
DetermineBasalAdapterMAJS determineBasalAdapterMAJS; DetermineBasalAdapterMAJS determineBasalAdapterMAJS;
determineBasalAdapterMAJS = new DetermineBasalAdapterMAJS(new ScriptReader(mainApp), getInjector()); determineBasalAdapterMAJS = new DetermineBasalAdapterMAJS(new ScriptReader(context), getInjector());
GlucoseStatus glucoseStatus = new GlucoseStatus(getInjector()).getGlucoseStatusData(); GlucoseStatus glucoseStatus = new GlucoseStatus(getInjector()).getGlucoseStatusData();
Profile profile = profileFunction.getProfile(); Profile profile = profileFunction.getProfile();
@ -172,26 +173,26 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
double maxIob = constraintChecker.getMaxIOBAllowed().value(); double maxIob = constraintChecker.getMaxIOBAllowed().value();
Profiler.log(getAapsLogger(), LTag.APS, "MA data gathering", start); Profiler.log(getAapsLogger(), LTag.APS, "MA data gathering", start);
minBg = verifyHardLimits(minBg, "minBg", HardLimits.VERY_HARD_LIMIT_MIN_BG[0], HardLimits.VERY_HARD_LIMIT_MIN_BG[1]); minBg = hardLimits.verifyHardLimits(minBg, "minBg", hardLimits.getVERY_HARD_LIMIT_MIN_BG()[0], hardLimits.getVERY_HARD_LIMIT_MIN_BG()[1]);
maxBg = verifyHardLimits(maxBg, "maxBg", HardLimits.VERY_HARD_LIMIT_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_MAX_BG[1]); maxBg = hardLimits.verifyHardLimits(maxBg, "maxBg", hardLimits.getVERY_HARD_LIMIT_MAX_BG()[0], hardLimits.getVERY_HARD_LIMIT_MAX_BG()[1]);
targetBg = verifyHardLimits(targetBg, "targetBg", HardLimits.VERY_HARD_LIMIT_TARGET_BG[0], HardLimits.VERY_HARD_LIMIT_TARGET_BG[1]); targetBg = hardLimits.verifyHardLimits(targetBg, "targetBg", hardLimits.getVERY_HARD_LIMIT_TARGET_BG()[0], hardLimits.getVERY_HARD_LIMIT_TARGET_BG()[1]);
TempTarget tempTarget = treatmentsPlugin.getTempTargetFromHistory(System.currentTimeMillis()); TempTarget tempTarget = treatmentsPlugin.getTempTargetFromHistory(System.currentTimeMillis());
if (tempTarget != null) { if (tempTarget != null) {
minBg = verifyHardLimits(tempTarget.low, "minBg", HardLimits.VERY_HARD_LIMIT_TEMP_MIN_BG[0], HardLimits.VERY_HARD_LIMIT_TEMP_MIN_BG[1]); minBg = hardLimits.verifyHardLimits(tempTarget.low, "minBg", hardLimits.getVERY_HARD_LIMIT_TEMP_MIN_BG()[0], hardLimits.getVERY_HARD_LIMIT_TEMP_MIN_BG()[1]);
maxBg = verifyHardLimits(tempTarget.high, "maxBg", HardLimits.VERY_HARD_LIMIT_TEMP_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_TEMP_MAX_BG[1]); maxBg = hardLimits.verifyHardLimits(tempTarget.high, "maxBg", hardLimits.getVERY_HARD_LIMIT_TEMP_MAX_BG()[0], hardLimits.getVERY_HARD_LIMIT_TEMP_MAX_BG()[1]);
targetBg = verifyHardLimits(tempTarget.target(), "targetBg", HardLimits.VERY_HARD_LIMIT_TEMP_TARGET_BG[0], HardLimits.VERY_HARD_LIMIT_TEMP_TARGET_BG[1]); targetBg = hardLimits.verifyHardLimits(tempTarget.target(), "targetBg", hardLimits.getVERY_HARD_LIMIT_TEMP_TARGET_BG()[0], hardLimits.getVERY_HARD_LIMIT_TEMP_TARGET_BG()[1]);
} }
if (!checkOnlyHardLimits(profile.getDia(), "dia", HardLimits.MINDIA, HardLimits.MAXDIA)) if (!hardLimits.checkOnlyHardLimits(profile.getDia(), "dia", hardLimits.getMINDIA(), hardLimits.getMAXDIA()))
return; return;
if (!checkOnlyHardLimits(profile.getIcTimeFromMidnight(Profile.secondsFromMidnight()), "carbratio", HardLimits.MINIC, HardLimits.MAXIC)) if (!hardLimits.checkOnlyHardLimits(profile.getIcTimeFromMidnight(Profile.secondsFromMidnight()), "carbratio", hardLimits.getMINIC(), hardLimits.getMAXIC()))
return; return;
if (!checkOnlyHardLimits(profile.getIsfMgdl(), "sens", HardLimits.MINISF, HardLimits.MAXISF)) if (!hardLimits.checkOnlyHardLimits(profile.getIsfMgdl(), "sens", hardLimits.getMINISF(), hardLimits.getMAXISF()))
return; return;
if (!checkOnlyHardLimits(profile.getMaxDailyBasal(), "max_daily_basal", 0.02, HardLimits.maxBasal())) if (!hardLimits.checkOnlyHardLimits(profile.getMaxDailyBasal(), "max_daily_basal", 0.02, hardLimits.maxBasal()))
return; return;
if (!checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, HardLimits.maxBasal())) if (!hardLimits.checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, hardLimits.maxBasal()))
return; return;
start = System.currentTimeMillis(); start = System.currentTimeMillis();

View file

@ -1,5 +1,7 @@
package info.nightscout.androidaps.plugins.aps.openAPSSMB; package info.nightscout.androidaps.plugins.aps.openAPSSMB;
import android.content.Context;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.json.JSONException; import org.json.JSONException;
@ -7,7 +9,6 @@ import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
import dagger.android.HasAndroidInjector; import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData; import info.nightscout.androidaps.data.MealData;
@ -49,11 +50,12 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
private final ConstraintChecker constraintChecker; private final ConstraintChecker constraintChecker;
private final ResourceHelper resourceHelper; private final ResourceHelper resourceHelper;
private final ProfileFunction profileFunction; private final ProfileFunction profileFunction;
private final MainApp mainApp; private final Context context;
private final RxBusWrapper rxBus; private final RxBusWrapper rxBus;
private final ActivePluginProvider activePlugin; private final ActivePluginProvider activePlugin;
private final TreatmentsPlugin treatmentsPlugin; private final TreatmentsPlugin treatmentsPlugin;
private final IobCobCalculatorPlugin iobCobCalculatorPlugin; private final IobCobCalculatorPlugin iobCobCalculatorPlugin;
private final HardLimits hardLimits;
// last values // last values
DetermineBasalAdapterSMBJS lastDetermineBasalAdapterSMBJS = null; DetermineBasalAdapterSMBJS lastDetermineBasalAdapterSMBJS = null;
@ -69,10 +71,11 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
ConstraintChecker constraintChecker, ConstraintChecker constraintChecker,
ResourceHelper resourceHelper, ResourceHelper resourceHelper,
ProfileFunction profileFunction, ProfileFunction profileFunction,
MainApp mainApp, Context context,
ActivePluginProvider activePlugin, ActivePluginProvider activePlugin,
TreatmentsPlugin treatmentsPlugin, TreatmentsPlugin treatmentsPlugin,
IobCobCalculatorPlugin iobCobCalculatorPlugin IobCobCalculatorPlugin iobCobCalculatorPlugin,
HardLimits hardLimits
) { ) {
super(new PluginDescription() super(new PluginDescription()
.mainType(PluginType.APS) .mainType(PluginType.APS)
@ -87,10 +90,11 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
this.resourceHelper = resourceHelper; this.resourceHelper = resourceHelper;
this.profileFunction = profileFunction; this.profileFunction = profileFunction;
this.rxBus = rxBus; this.rxBus = rxBus;
this.mainApp = mainApp; this.context = context;
this.activePlugin = activePlugin; this.activePlugin = activePlugin;
this.treatmentsPlugin = treatmentsPlugin; this.treatmentsPlugin = treatmentsPlugin;
this.iobCobCalculatorPlugin = iobCobCalculatorPlugin; this.iobCobCalculatorPlugin = iobCobCalculatorPlugin;
this.hardLimits = hardLimits;
} }
@Override @Override
@ -124,7 +128,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
getAapsLogger().debug(LTag.APS, "invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback); getAapsLogger().debug(LTag.APS, "invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback);
lastAPSResult = null; lastAPSResult = null;
DetermineBasalAdapterSMBJS determineBasalAdapterSMBJS; DetermineBasalAdapterSMBJS determineBasalAdapterSMBJS;
determineBasalAdapterSMBJS = new DetermineBasalAdapterSMBJS(new ScriptReader(mainApp), getInjector()); determineBasalAdapterSMBJS = new DetermineBasalAdapterSMBJS(new ScriptReader(context), getInjector());
GlucoseStatus glucoseStatus = new GlucoseStatus(getInjector()).getGlucoseStatusData(); GlucoseStatus glucoseStatus = new GlucoseStatus(getInjector()).getGlucoseStatusData();
Profile profile = profileFunction.getProfile(); Profile profile = profileFunction.getProfile();
@ -176,29 +180,29 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
inputConstraints.copyReasons(maxIOBAllowedConstraint); inputConstraints.copyReasons(maxIOBAllowedConstraint);
double maxIob = maxIOBAllowedConstraint.value(); double maxIob = maxIOBAllowedConstraint.value();
minBg = verifyHardLimits(minBg, "minBg", HardLimits.VERY_HARD_LIMIT_MIN_BG[0], HardLimits.VERY_HARD_LIMIT_MIN_BG[1]); minBg = verifyHardLimits(minBg, "minBg", hardLimits.getVERY_HARD_LIMIT_MIN_BG()[0], hardLimits.getVERY_HARD_LIMIT_MIN_BG()[1]);
maxBg = verifyHardLimits(maxBg, "maxBg", HardLimits.VERY_HARD_LIMIT_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_MAX_BG[1]); maxBg = verifyHardLimits(maxBg, "maxBg", hardLimits.getVERY_HARD_LIMIT_MAX_BG()[0], hardLimits.getVERY_HARD_LIMIT_MAX_BG()[1]);
targetBg = verifyHardLimits(targetBg, "targetBg", HardLimits.VERY_HARD_LIMIT_TARGET_BG[0], HardLimits.VERY_HARD_LIMIT_TARGET_BG[1]); targetBg = verifyHardLimits(targetBg, "targetBg", hardLimits.getVERY_HARD_LIMIT_TARGET_BG()[0], hardLimits.getVERY_HARD_LIMIT_TARGET_BG()[1]);
boolean isTempTarget = false; boolean isTempTarget = false;
TempTarget tempTarget = treatmentsPlugin.getTempTargetFromHistory(System.currentTimeMillis()); TempTarget tempTarget = treatmentsPlugin.getTempTargetFromHistory(System.currentTimeMillis());
if (tempTarget != null) { if (tempTarget != null) {
isTempTarget = true; isTempTarget = true;
minBg = verifyHardLimits(tempTarget.low, "minBg", HardLimits.VERY_HARD_LIMIT_TEMP_MIN_BG[0], HardLimits.VERY_HARD_LIMIT_TEMP_MIN_BG[1]); minBg = verifyHardLimits(tempTarget.low, "minBg", hardLimits.getVERY_HARD_LIMIT_TEMP_MIN_BG()[0], hardLimits.getVERY_HARD_LIMIT_TEMP_MIN_BG()[1]);
maxBg = verifyHardLimits(tempTarget.high, "maxBg", HardLimits.VERY_HARD_LIMIT_TEMP_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_TEMP_MAX_BG[1]); maxBg = verifyHardLimits(tempTarget.high, "maxBg", hardLimits.getVERY_HARD_LIMIT_TEMP_MAX_BG()[0], hardLimits.getVERY_HARD_LIMIT_TEMP_MAX_BG()[1]);
targetBg = verifyHardLimits(tempTarget.target(), "targetBg", HardLimits.VERY_HARD_LIMIT_TEMP_TARGET_BG[0], HardLimits.VERY_HARD_LIMIT_TEMP_TARGET_BG[1]); targetBg = verifyHardLimits(tempTarget.target(), "targetBg", hardLimits.getVERY_HARD_LIMIT_TEMP_TARGET_BG()[0], hardLimits.getVERY_HARD_LIMIT_TEMP_TARGET_BG()[1]);
} }
if (!checkOnlyHardLimits(profile.getDia(), "dia", HardLimits.MINDIA, HardLimits.MAXDIA)) if (!checkOnlyHardLimits(profile.getDia(), "dia", hardLimits.getMINDIA(), hardLimits.getMAXDIA()))
return; return;
if (!checkOnlyHardLimits(profile.getIcTimeFromMidnight(Profile.secondsFromMidnight()), "carbratio", HardLimits.MINIC, HardLimits.MAXIC)) if (!checkOnlyHardLimits(profile.getIcTimeFromMidnight(Profile.secondsFromMidnight()), "carbratio", hardLimits.getMINIC(), hardLimits.getMAXIC()))
return; return;
if (!checkOnlyHardLimits(profile.getIsfMgdl(), "sens", HardLimits.MINISF, HardLimits.MAXISF)) if (!checkOnlyHardLimits(profile.getIsfMgdl(), "sens", hardLimits.getMINISF(), hardLimits.getMAXISF()))
return; return;
if (!checkOnlyHardLimits(profile.getMaxDailyBasal(), "max_daily_basal", 0.02, HardLimits.maxBasal())) if (!checkOnlyHardLimits(profile.getMaxDailyBasal(), "max_daily_basal", 0.02, hardLimits.maxBasal()))
return; return;
if (!checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, HardLimits.maxBasal())) if (!checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, hardLimits.maxBasal()))
return; return;
startPart = System.currentTimeMillis(); startPart = System.currentTimeMillis();
@ -296,7 +300,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
msg += String.format(resourceHelper.gs(R.string.valuelimitedto), value, newvalue); msg += String.format(resourceHelper.gs(R.string.valuelimitedto), value, newvalue);
getAapsLogger().error(LTag.APS, msg); getAapsLogger().error(LTag.APS, msg);
NSUpload.uploadError(msg); NSUpload.uploadError(msg);
ToastUtils.showToastInUiThread(mainApp, msg, R.raw.error); ToastUtils.showToastInUiThread(context, msg, R.raw.error);
} }
return newvalue; return newvalue;
} }

View file

@ -57,7 +57,7 @@ class ObjectivesPlugin @Inject constructor(
const val SMB_OBJECTIVE = 9 const val SMB_OBJECTIVE = 9
} }
override fun onStart() { public override fun onStart() {
super.onStart() super.onStart()
convertSP() convertSP()
setupObjectives() setupObjectives()
@ -90,16 +90,16 @@ class ObjectivesPlugin @Inject constructor(
private fun setupObjectives() { private fun setupObjectives() {
objectives.clear() objectives.clear()
objectives.add(Objective0()) objectives.add(Objective0(injector))
objectives.add(Objective1()) objectives.add(Objective1(injector))
objectives.add(Objective2()) objectives.add(Objective2(injector))
objectives.add(Objective3()) objectives.add(Objective3(injector))
objectives.add(Objective4()) objectives.add(Objective4(injector))
objectives.add(Objective5(injector)) objectives.add(Objective5(injector))
objectives.add(Objective6()) objectives.add(Objective6(injector))
objectives.add(Objective7()) objectives.add(Objective7(injector))
objectives.add(Objective8()) objectives.add(Objective8(injector))
objectives.add(Objective9()) objectives.add(Objective9(injector))
} }
fun reset() { fun reset() {

View file

@ -4,7 +4,6 @@ import android.app.Activity;
import android.content.Context; import android.content.Context;
import android.graphics.Color; import android.graphics.Color;
import android.text.util.Linkify; import android.text.util.Linkify;
import android.view.View;
import android.widget.CheckBox; import android.widget.CheckBox;
import android.widget.TextView; import android.widget.TextView;
@ -13,13 +12,17 @@ import androidx.annotation.StringRes;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.inject.Inject;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.SP;
import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.T;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
public abstract class Objective { public abstract class Objective {
@Inject public SP sp;
private String spName; private String spName;
@StringRes @StringRes
@ -31,12 +34,13 @@ public abstract class Objective {
List<Task> tasks = new ArrayList<>(); List<Task> tasks = new ArrayList<>();
public boolean hasSpecialInput = false; public boolean hasSpecialInput = false;
public Objective(String spName, @StringRes int objective, @StringRes int gate) { public Objective(HasAndroidInjector injector, String spName, @StringRes int objective, @StringRes int gate) {
injector.androidInjector().inject(this);
this.spName = spName; this.spName = spName;
this.objective = objective; this.objective = objective;
this.gate = gate; this.gate = gate;
startedOn = SP.getLong("Objectives_" + spName + "_started", 0L); startedOn = sp.getLong("Objectives_" + spName + "_started", 0L);
accomplishedOn = SP.getLong("Objectives_" + spName + "_accomplished", 0L); accomplishedOn = sp.getLong("Objectives_" + spName + "_accomplished", 0L);
if ((accomplishedOn - DateUtil.now()) > T.hours(3).msecs() || (startedOn - DateUtil.now()) > T.hours(3).msecs()) { // more than 3 hours in the future if ((accomplishedOn - DateUtil.now()) > T.hours(3).msecs() || (startedOn - DateUtil.now()) > T.hours(3).msecs()) { // more than 3 hours in the future
startedOn = 0; startedOn = 0;
accomplishedOn = 0; accomplishedOn = 0;
@ -83,12 +87,12 @@ public abstract class Objective {
public void setStartedOn(long startedOn) { public void setStartedOn(long startedOn) {
this.startedOn = startedOn; this.startedOn = startedOn;
SP.putLong("Objectives_" + spName + "_started", startedOn); sp.putLong("Objectives_" + spName + "_started", startedOn);
} }
public void setAccomplishedOn(long accomplishedOn) { public void setAccomplishedOn(long accomplishedOn) {
this.accomplishedOn = accomplishedOn; this.accomplishedOn = accomplishedOn;
SP.putLong("Objectives_" + spName + "_accomplished", accomplishedOn); sp.putLong("Objectives_" + spName + "_accomplished", accomplishedOn);
} }
public long getAccomplishedOn() { public long getAccomplishedOn() {
@ -103,9 +107,12 @@ public abstract class Objective {
return tasks; return tasks;
} }
public boolean specialActionEnabled() { return true; } public boolean specialActionEnabled() {
return true;
}
public void specialAction(Activity activity, String input) {} public void specialAction(Activity activity, String input) {
}
public abstract class Task { public abstract class Task {
@StringRes @StringRes
@ -126,7 +133,12 @@ public abstract class Objective {
} }
public abstract boolean isCompleted(); public abstract boolean isCompleted();
public boolean isCompleted(long trueTime) { return isCompleted(); };
public boolean isCompleted(long trueTime) {
return isCompleted();
}
;
public String getProgress() { public String getProgress() {
return MainApp.gs(isCompleted() ? R.string.completed_well_done : R.string.not_completed_yet); return MainApp.gs(isCompleted() ? R.string.completed_well_done : R.string.not_completed_yet);
@ -193,13 +205,13 @@ public abstract class Objective {
super(task); super(task);
this.question = question; this.question = question;
this.spIdentifier = spIdentifier; this.spIdentifier = spIdentifier;
answered = SP.getBoolean("ExamTask_" + spIdentifier, false); answered = sp.getBoolean("ExamTask_" + spIdentifier, false);
disabledTo = SP.getLong("DisabledTo_" + spIdentifier, 0L); disabledTo = sp.getLong("DisabledTo_" + spIdentifier, 0L);
} }
public void setDisabledTo(long newState) { public void setDisabledTo(long newState) {
disabledTo = newState; disabledTo = newState;
SP.putLong("DisabledTo_" + spIdentifier, disabledTo); sp.putLong("DisabledTo_" + spIdentifier, disabledTo);
} }
public long getDisabledTo() { public long getDisabledTo() {
@ -212,7 +224,7 @@ public abstract class Objective {
public void setAnswered(boolean newState) { public void setAnswered(boolean newState) {
answered = newState; answered = newState;
SP.putBoolean("ExamTask_" + spIdentifier, answered); sp.putBoolean("ExamTask_" + spIdentifier, answered);
} }
public boolean getAnswered() { public boolean getAnswered() {

View file

@ -4,7 +4,7 @@ import java.util.List;
import javax.inject.Inject; import javax.inject.Inject;
import info.nightscout.androidaps.MainApp; import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.APSInterface; import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
@ -27,9 +27,8 @@ public class Objective0 extends Objective {
@Inject NSClientPlugin nsClientPlugin; @Inject NSClientPlugin nsClientPlugin;
@Inject IobCobCalculatorPlugin iobCobCalculatorPlugin; @Inject IobCobCalculatorPlugin iobCobCalculatorPlugin;
public Objective0() { public Objective0(HasAndroidInjector injector) {
super("config", R.string.objectives_0_objective, R.string.objectives_0_gate); super(injector, "config", R.string.objectives_0_objective, R.string.objectives_0_gate);
MainApp.instance().androidInjector().inject(this); // TODO inject or pass itno constructor once AutomationPlugin is prepared for Dagger
} }
@Override @Override

View file

@ -4,7 +4,7 @@ import java.util.List;
import javax.inject.Inject; import javax.inject.Inject;
import info.nightscout.androidaps.MainApp; import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.plugins.general.actions.ActionsPlugin; import info.nightscout.androidaps.plugins.general.actions.ActionsPlugin;
@ -15,9 +15,8 @@ public class Objective1 extends Objective {
@Inject ActionsPlugin actionsPlugin; @Inject ActionsPlugin actionsPlugin;
@Inject @Inject
public Objective1() { public Objective1(HasAndroidInjector injector) {
super("usage", R.string.objectives_usage_objective, R.string.objectives_usage_gate); super(injector, "usage", R.string.objectives_usage_objective, R.string.objectives_usage_gate);
MainApp.instance().androidInjector().inject(this); // TODO inject or pass itno constructor once ActionsPlugin is prepared for Dagger
} }
@Override @Override

View file

@ -3,15 +3,15 @@ package info.nightscout.androidaps.plugins.constraints.objectives.objectives;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
public class Objective2 extends Objective { public class Objective2 extends Objective {
public Objective2() { public Objective2(HasAndroidInjector injector) {
super("exam", R.string.objectives_exam_objective, R.string.objectives_exam_gate); super(injector, "exam", R.string.objectives_exam_objective, R.string.objectives_exam_gate);
MainApp.instance().androidInjector().inject(this); // TODO inject or pass itno constructor once AutomationPlugin is prepared for Dagger
for (Task task : tasks) { for (Task task : tasks) {
if (!task.isCompleted()) setAccomplishedOn(0); if (!task.isCompleted()) setAccomplishedOn(0);
} }

View file

@ -6,7 +6,7 @@ import java.util.List;
import javax.inject.Inject; import javax.inject.Inject;
import info.nightscout.androidaps.MainApp; import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin; import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin;
import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin; import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin;
@ -23,9 +23,8 @@ public class Objective3 extends Objective {
private final int MANUAL_ENACTS_NEEDED = 20; private final int MANUAL_ENACTS_NEEDED = 20;
@Inject @Inject
public Objective3() { public Objective3(HasAndroidInjector injector) {
super("openloop", R.string.objectives_openloop_objective, R.string.objectives_openloop_gate); super(injector, "openloop", R.string.objectives_openloop_objective, R.string.objectives_openloop_gate);
MainApp.instance().androidInjector().inject(this); // TODO inject or pass itno constructor once AutomationPlugin is prepared for Dagger
hasSpecialInput = true; hasSpecialInput = true;
} }

View file

@ -1,10 +1,11 @@
package info.nightscout.androidaps.plugins.constraints.objectives.objectives; package info.nightscout.androidaps.plugins.constraints.objectives.objectives;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
public class Objective4 extends Objective { public class Objective4 extends Objective {
public Objective4() { public Objective4(HasAndroidInjector injector) {
super("maxbasal", R.string.objectives_maxbasal_objective, R.string.objectives_maxbasal_gate); super(injector, "maxbasal", R.string.objectives_maxbasal_objective, R.string.objectives_maxbasal_gate);
} }
} }

View file

@ -14,8 +14,7 @@ public class Objective5 extends Objective {
@Inject SafetyPlugin safetyPlugin; @Inject SafetyPlugin safetyPlugin;
public Objective5(HasAndroidInjector injector) { public Objective5(HasAndroidInjector injector) {
super("maxiobzero", R.string.objectives_maxiobzero_objective, R.string.objectives_maxiobzero_gate); super(injector, "maxiobzero", R.string.objectives_maxiobzero_objective, R.string.objectives_maxiobzero_gate);
injector.androidInjector().inject(this);
} }
@Override @Override

View file

@ -4,7 +4,7 @@ import java.util.List;
import javax.inject.Inject; import javax.inject.Inject;
import info.nightscout.androidaps.MainApp; import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker;
import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.T;
@ -12,9 +12,8 @@ import info.nightscout.androidaps.utils.T;
public class Objective6 extends Objective { public class Objective6 extends Objective {
@Inject ConstraintChecker constraintChecker; @Inject ConstraintChecker constraintChecker;
public Objective6() { public Objective6(HasAndroidInjector injector) {
super("maxiob", R.string.objectives_maxiob_objective, R.string.objectives_maxiob_gate); super(injector, "maxiob", R.string.objectives_maxiob_objective, R.string.objectives_maxiob_gate);
MainApp.instance().androidInjector().inject(this); // TODO inject or pass itno constructor once AutomationPlugin is prepared for Dagger
} }
@Override @Override

View file

@ -2,14 +2,14 @@ package info.nightscout.androidaps.plugins.constraints.objectives.objectives;
import java.util.List; import java.util.List;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin;
import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.T;
public class Objective7 extends Objective { public class Objective7 extends Objective {
public Objective7() { public Objective7(HasAndroidInjector injector) {
super("autosens", R.string.objectives_autosens_objective, R.string.objectives_autosens_gate); super(injector, "autosens", R.string.objectives_autosens_objective, R.string.objectives_autosens_gate);
} }
@Override @Override

View file

@ -2,14 +2,14 @@ package info.nightscout.androidaps.plugins.constraints.objectives.objectives;
import java.util.List; import java.util.List;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin;
import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.T;
public class Objective8 extends Objective { public class Objective8 extends Objective {
public Objective8() { public Objective8(HasAndroidInjector injector) {
super("ama", R.string.objectives_ama_objective, 0); super(injector, "ama", R.string.objectives_ama_objective, 0);
} }
@Override @Override

View file

@ -2,13 +2,14 @@ package info.nightscout.androidaps.plugins.constraints.objectives.objectives;
import java.util.List; import java.util.List;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.T;
public class Objective9 extends Objective { public class Objective9 extends Objective {
public Objective9() { public Objective9(HasAndroidInjector injector) {
super("smb", R.string.objectives_smb_objective, R.string.objectives_smb_gate); super(injector, "smb", R.string.objectives_smb_objective, R.string.objectives_smb_gate);
} }
@Override @Override

View file

@ -7,7 +7,6 @@ import javax.inject.Singleton;
import dagger.android.HasAndroidInjector; import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.interfaces.ActivePluginProvider;
@ -32,28 +31,41 @@ import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.DecimalFormatter;
import info.nightscout.androidaps.utils.HardLimits; import info.nightscout.androidaps.utils.HardLimits;
import info.nightscout.androidaps.utils.Round; import info.nightscout.androidaps.utils.Round;
import info.nightscout.androidaps.utils.build.BuildHelper;
import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP; import info.nightscout.androidaps.utils.sharedPreferences.SP;
@Singleton @Singleton
public class SafetyPlugin extends PluginBase implements ConstraintsInterface { public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
// TODO: dagger private SP sp;
@Inject SP sp; private RxBusWrapper rxBus;
@Inject RxBusWrapper rxBus; private ConstraintChecker constraintChecker;
@Inject ResourceHelper resourceHelper; private OpenAPSAMAPlugin openAPSAMAPlugin;
@Inject ConstraintChecker constraintChecker; private OpenAPSMAPlugin openAPSMAPlugin;
@Inject OpenAPSAMAPlugin openAPSAMAPlugin; private OpenAPSSMBPlugin openAPSSMBPlugin;
@Inject OpenAPSMAPlugin openAPSMAPlugin; private SensitivityOref1Plugin sensitivityOref1Plugin;
@Inject OpenAPSSMBPlugin openAPSSMBPlugin; private ActivePluginProvider activePlugin;
@Inject SensitivityOref1Plugin sensitivityOref1Plugin; private HardLimits hardLimits;
@Inject ActivePluginProvider activePlugin; private BuildHelper buildHelper;
private TreatmentsPlugin treatmentsPlugin;
@Inject @Inject
public SafetyPlugin( public SafetyPlugin(
HasAndroidInjector injector, HasAndroidInjector injector,
AAPSLogger aapsLogger, AAPSLogger aapsLogger,
ResourceHelper resourceHelper ResourceHelper resourceHelper,
SP sp,
RxBusWrapper rxBus,
ConstraintChecker constraintChecker,
OpenAPSAMAPlugin openAPSAMAPlugin,
OpenAPSMAPlugin openAPSMAPlugin,
OpenAPSSMBPlugin openAPSSMBPlugin,
SensitivityOref1Plugin sensitivityOref1Plugin,
ActivePluginProvider activePlugin,
HardLimits hardLimits,
BuildHelper buildHelper,
TreatmentsPlugin treatmentsPlugin
) { ) {
super(new PluginDescription() super(new PluginDescription()
.mainType(PluginType.CONSTRAINTS) .mainType(PluginType.CONSTRAINTS)
@ -64,6 +76,17 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
.preferencesId(R.xml.pref_safety), .preferencesId(R.xml.pref_safety),
aapsLogger, resourceHelper, injector aapsLogger, resourceHelper, injector
); );
this.sp = sp;
this.rxBus = rxBus;
this.constraintChecker = constraintChecker;
this.openAPSAMAPlugin = openAPSAMAPlugin;
this.openAPSMAPlugin = openAPSMAPlugin;
this.openAPSSMBPlugin = openAPSSMBPlugin;
this.sensitivityOref1Plugin = sensitivityOref1Plugin;
this.activePlugin = activePlugin;
this.hardLimits = hardLimits;
this.buildHelper = buildHelper;
this.treatmentsPlugin = treatmentsPlugin;
} }
/** /**
@ -72,7 +95,7 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
@NonNull @Override @NonNull @Override
public Constraint<Boolean> isLoopInvocationAllowed(@NonNull Constraint<Boolean> value) { public Constraint<Boolean> isLoopInvocationAllowed(@NonNull Constraint<Boolean> value) {
if (!activePlugin.getActivePumpPlugin().getPumpDescription().isTempBasalCapable) if (!activePlugin.getActivePumpPlugin().getPumpDescription().isTempBasalCapable)
value.set(getAapsLogger(), false, resourceHelper.gs(R.string.pumpisnottempbasalcapable), this); value.set(getAapsLogger(), false, getResourceHelper().gs(R.string.pumpisnottempbasalcapable), this);
return value; return value;
} }
@ -80,18 +103,18 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
public Constraint<Boolean> isClosedLoopAllowed(@NonNull Constraint<Boolean> value) { public Constraint<Boolean> isClosedLoopAllowed(@NonNull Constraint<Boolean> value) {
String mode = sp.getString(R.string.key_aps_mode, "open"); String mode = sp.getString(R.string.key_aps_mode, "open");
if (!mode.equals("closed")) if (!mode.equals("closed"))
value.set(getAapsLogger(), false, resourceHelper.gs(R.string.closedmodedisabledinpreferences), this); value.set(getAapsLogger(), false, getResourceHelper().gs(R.string.closedmodedisabledinpreferences), this);
if (!MainApp.isEngineeringModeOrRelease()) { if (!buildHelper.isEngineeringModeOrRelease()) {
if (value.value()) { if (value.value()) {
Notification n = new Notification(Notification.TOAST_ALARM, resourceHelper.gs(R.string.closed_loop_disabled_on_dev_branch), Notification.NORMAL); Notification n = new Notification(Notification.TOAST_ALARM, getResourceHelper().gs(R.string.closed_loop_disabled_on_dev_branch), Notification.NORMAL);
rxBus.send(new EventNewNotification(n)); rxBus.send(new EventNewNotification(n));
} }
value.set(getAapsLogger(), false, resourceHelper.gs(R.string.closed_loop_disabled_on_dev_branch), this); value.set(getAapsLogger(), false, getResourceHelper().gs(R.string.closed_loop_disabled_on_dev_branch), this);
} }
PumpInterface pump = activePlugin.getActivePumpPlugin(); PumpInterface pump = activePlugin.getActivePumpPlugin();
if (pump != null && !pump.isFakingTempsByExtendedBoluses() && TreatmentsPlugin.getPlugin().isInHistoryExtendedBoluslInProgress()) { if (pump != null && !pump.isFakingTempsByExtendedBoluses() && treatmentsPlugin.isInHistoryExtendedBoluslInProgress()) {
value.set(getAapsLogger(), false, MainApp.gs(R.string.closed_loop_disabled_with_eb), this); value.set(getAapsLogger(), false, getResourceHelper().gs(R.string.closed_loop_disabled_with_eb), this);
} }
return value; return value;
} }
@ -100,7 +123,7 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
public Constraint<Boolean> isAutosensModeEnabled(@NonNull Constraint<Boolean> value) { public Constraint<Boolean> isAutosensModeEnabled(@NonNull Constraint<Boolean> value) {
boolean enabled = sp.getBoolean(R.string.key_openapsama_useautosens, false); boolean enabled = sp.getBoolean(R.string.key_openapsama_useautosens, false);
if (!enabled) if (!enabled)
value.set(getAapsLogger(), false, resourceHelper.gs(R.string.autosensdisabledinpreferences), this); value.set(getAapsLogger(), false, getResourceHelper().gs(R.string.autosensdisabledinpreferences), this);
return value; return value;
} }
@ -108,10 +131,10 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
public Constraint<Boolean> isSMBModeEnabled(@NonNull Constraint<Boolean> value) { public Constraint<Boolean> isSMBModeEnabled(@NonNull Constraint<Boolean> value) {
boolean enabled = sp.getBoolean(R.string.key_use_smb, false); boolean enabled = sp.getBoolean(R.string.key_use_smb, false);
if (!enabled) if (!enabled)
value.set(getAapsLogger(), false, resourceHelper.gs(R.string.smbdisabledinpreferences), this); value.set(getAapsLogger(), false, getResourceHelper().gs(R.string.smbdisabledinpreferences), this);
Constraint<Boolean> closedLoop = constraintChecker.isClosedLoopAllowed(); Constraint<Boolean> closedLoop = constraintChecker.isClosedLoopAllowed();
if (!closedLoop.value()) if (!closedLoop.value())
value.set(getAapsLogger(), false, resourceHelper.gs(R.string.smbnotallowedinopenloopmode), this); value.set(getAapsLogger(), false, getResourceHelper().gs(R.string.smbnotallowedinopenloopmode), this);
return value; return value;
} }
@ -119,10 +142,10 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
public Constraint<Boolean> isUAMEnabled(@NonNull Constraint<Boolean> value) { public Constraint<Boolean> isUAMEnabled(@NonNull Constraint<Boolean> value) {
boolean enabled = sp.getBoolean(R.string.key_use_uam, false); boolean enabled = sp.getBoolean(R.string.key_use_uam, false);
if (!enabled) if (!enabled)
value.set(getAapsLogger(), false, resourceHelper.gs(R.string.uamdisabledinpreferences), this); value.set(getAapsLogger(), false, getResourceHelper().gs(R.string.uamdisabledinpreferences), this);
boolean oref1Enabled = sensitivityOref1Plugin.isEnabled(PluginType.SENSITIVITY); boolean oref1Enabled = sensitivityOref1Plugin.isEnabled(PluginType.SENSITIVITY);
if (!oref1Enabled) if (!oref1Enabled)
value.set(getAapsLogger(), false, resourceHelper.gs(R.string.uamdisabledoref1notselected), this); value.set(getAapsLogger(), false, getResourceHelper().gs(R.string.uamdisabledoref1notselected), this);
return value; return value;
} }
@ -132,7 +155,7 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
if (bgSource != null) { if (bgSource != null) {
if (!bgSource.advancedFilteringSupported()) if (!bgSource.advancedFilteringSupported())
value.set(getAapsLogger(), false, resourceHelper.gs(R.string.smbalwaysdisabled), this); value.set(getAapsLogger(), false, getResourceHelper().gs(R.string.smbalwaysdisabled), this);
} }
return value; return value;
} }
@ -140,33 +163,33 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
@NonNull @Override @NonNull @Override
public Constraint<Double> applyBasalConstraints(Constraint<Double> absoluteRate, @NonNull Profile profile) { public Constraint<Double> applyBasalConstraints(Constraint<Double> absoluteRate, @NonNull Profile profile) {
absoluteRate.setIfGreater(getAapsLogger(), 0d, String.format(resourceHelper.gs(R.string.limitingbasalratio), 0d, resourceHelper.gs(R.string.itmustbepositivevalue)), this); absoluteRate.setIfGreater(getAapsLogger(), 0d, String.format(getResourceHelper().gs(R.string.limitingbasalratio), 0d, getResourceHelper().gs(R.string.itmustbepositivevalue)), this);
if (Config.APS) { if (Config.APS) {
double maxBasal = sp.getDouble(R.string.key_openapsma_max_basal, 1d); double maxBasal = sp.getDouble(R.string.key_openapsma_max_basal, 1d);
if (maxBasal < profile.getMaxDailyBasal()) { if (maxBasal < profile.getMaxDailyBasal()) {
maxBasal = profile.getMaxDailyBasal(); maxBasal = profile.getMaxDailyBasal();
absoluteRate.addReason(resourceHelper.gs(R.string.increasingmaxbasal), this); absoluteRate.addReason(getResourceHelper().gs(R.string.increasingmaxbasal), this);
} }
absoluteRate.setIfSmaller(getAapsLogger(), maxBasal, String.format(resourceHelper.gs(R.string.limitingbasalratio), maxBasal, resourceHelper.gs(R.string.maxvalueinpreferences)), this); absoluteRate.setIfSmaller(getAapsLogger(), maxBasal, String.format(getResourceHelper().gs(R.string.limitingbasalratio), maxBasal, getResourceHelper().gs(R.string.maxvalueinpreferences)), this);
// Check percentRate but absolute rate too, because we know real current basal in pump // Check percentRate but absolute rate too, because we know real current basal in pump
Double maxBasalMult = sp.getDouble(R.string.key_openapsama_current_basal_safety_multiplier, 4d); double maxBasalMult = sp.getDouble(R.string.key_openapsama_current_basal_safety_multiplier, 4d);
double maxFromBasalMult = Math.floor(maxBasalMult * profile.getBasal() * 100) / 100; double maxFromBasalMult = Math.floor(maxBasalMult * profile.getBasal() * 100) / 100;
absoluteRate.setIfSmaller(getAapsLogger(), maxFromBasalMult, String.format(resourceHelper.gs(R.string.limitingbasalratio), maxFromBasalMult, resourceHelper.gs(R.string.maxbasalmultiplier)), this); absoluteRate.setIfSmaller(getAapsLogger(), maxFromBasalMult, String.format(getResourceHelper().gs(R.string.limitingbasalratio), maxFromBasalMult, getResourceHelper().gs(R.string.maxbasalmultiplier)), this);
Double maxBasalFromDaily = sp.getDouble(R.string.key_openapsama_max_daily_safety_multiplier, 3d); double maxBasalFromDaily = sp.getDouble(R.string.key_openapsama_max_daily_safety_multiplier, 3d);
double maxFromDaily = Math.floor(profile.getMaxDailyBasal() * maxBasalFromDaily * 100) / 100; double maxFromDaily = Math.floor(profile.getMaxDailyBasal() * maxBasalFromDaily * 100) / 100;
absoluteRate.setIfSmaller(getAapsLogger(), maxFromDaily, String.format(resourceHelper.gs(R.string.limitingbasalratio), maxFromDaily, resourceHelper.gs(R.string.maxdailybasalmultiplier)), this); absoluteRate.setIfSmaller(getAapsLogger(), maxFromDaily, String.format(getResourceHelper().gs(R.string.limitingbasalratio), maxFromDaily, getResourceHelper().gs(R.string.maxdailybasalmultiplier)), this);
} }
absoluteRate.setIfSmaller(getAapsLogger(), HardLimits.maxBasal(), String.format(resourceHelper.gs(R.string.limitingbasalratio), HardLimits.maxBasal(), resourceHelper.gs(R.string.hardlimit)), this); absoluteRate.setIfSmaller(getAapsLogger(), hardLimits.maxBasal(), String.format(getResourceHelper().gs(R.string.limitingbasalratio), hardLimits.maxBasal(), getResourceHelper().gs(R.string.hardlimit)), this);
PumpInterface pump = activePlugin.getActivePumpPlugin(); PumpInterface pump = activePlugin.getActivePumpPlugin();
// check for pump max // check for pump max
if (pump != null && pump.getPumpDescription().tempBasalStyle == PumpDescription.ABSOLUTE) { if (pump != null && pump.getPumpDescription().tempBasalStyle == PumpDescription.ABSOLUTE) {
double pumpLimit = pump.getPumpDescription().pumpType.getTbrSettings().getMaxDose(); double pumpLimit = pump.getPumpDescription().pumpType.getTbrSettings().getMaxDose();
absoluteRate.setIfSmaller(getAapsLogger(), pumpLimit, String.format(resourceHelper.gs(R.string.limitingbasalratio), pumpLimit, resourceHelper.gs(R.string.pumplimit)), this); absoluteRate.setIfSmaller(getAapsLogger(), pumpLimit, String.format(getResourceHelper().gs(R.string.limitingbasalratio), pumpLimit, getResourceHelper().gs(R.string.pumplimit)), this);
} }
// do rounding // do rounding
@ -180,7 +203,7 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
public Constraint<Integer> applyBasalPercentConstraints(Constraint<Integer> percentRate, Profile profile) { public Constraint<Integer> applyBasalPercentConstraints(Constraint<Integer> percentRate, Profile profile) {
Double currentBasal = profile.getBasal(); Double currentBasal = profile.getBasal();
Double absoluteRate = currentBasal * ((double) percentRate.originalValue() / 100); double absoluteRate = currentBasal * ((double) percentRate.originalValue() / 100);
percentRate.addReason("Percent rate " + percentRate.originalValue() + "% recalculated to " + DecimalFormatter.to2Decimal(absoluteRate) + " U/h with current basal " + DecimalFormatter.to2Decimal(currentBasal) + " U/h", this); percentRate.addReason("Percent rate " + percentRate.originalValue() + "% recalculated to " + DecimalFormatter.to2Decimal(absoluteRate) + " U/h with current basal " + DecimalFormatter.to2Decimal(currentBasal) + " U/h", this);
@ -190,7 +213,7 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
PumpInterface pump = activePlugin.getActivePumpPlugin(); PumpInterface pump = activePlugin.getActivePumpPlugin();
Integer percentRateAfterConst = Double.valueOf(absoluteConstraint.value() / currentBasal * 100).intValue(); int percentRateAfterConst = Double.valueOf(absoluteConstraint.value() / currentBasal * 100).intValue();
if (pump != null) { if (pump != null) {
if (percentRateAfterConst < 100) if (percentRateAfterConst < 100)
percentRateAfterConst = Round.ceilTo((double) percentRateAfterConst, (double) pump.getPumpDescription().tempPercentStep).intValue(); percentRateAfterConst = Round.ceilTo((double) percentRateAfterConst, (double) pump.getPumpDescription().tempPercentStep).intValue();
@ -198,11 +221,11 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
percentRateAfterConst = Round.floorTo((double) percentRateAfterConst, (double) pump.getPumpDescription().tempPercentStep).intValue(); percentRateAfterConst = Round.floorTo((double) percentRateAfterConst, (double) pump.getPumpDescription().tempPercentStep).intValue();
} }
percentRate.set(getAapsLogger(), percentRateAfterConst, String.format(resourceHelper.gs(R.string.limitingpercentrate), percentRateAfterConst, resourceHelper.gs(R.string.pumplimit)), this); percentRate.set(getAapsLogger(), percentRateAfterConst, String.format(getResourceHelper().gs(R.string.limitingpercentrate), percentRateAfterConst, getResourceHelper().gs(R.string.pumplimit)), this);
if (pump != null && pump.getPumpDescription().tempBasalStyle == PumpDescription.PERCENT) { if (pump != null && pump.getPumpDescription().tempBasalStyle == PumpDescription.PERCENT) {
double pumpLimit = pump.getPumpDescription().pumpType.getTbrSettings().getMaxDose(); double pumpLimit = pump.getPumpDescription().pumpType.getTbrSettings().getMaxDose();
percentRate.setIfSmaller(getAapsLogger(), (int) pumpLimit, String.format(resourceHelper.gs(R.string.limitingbasalratio), pumpLimit, resourceHelper.gs(R.string.pumplimit)), this); percentRate.setIfSmaller(getAapsLogger(), (int) pumpLimit, String.format(getResourceHelper().gs(R.string.limitingbasalratio), pumpLimit, getResourceHelper().gs(R.string.pumplimit)), this);
} }
return percentRate; return percentRate;
@ -210,44 +233,44 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
@NonNull @Override @NonNull @Override
public Constraint<Double> applyBolusConstraints(Constraint<Double> insulin) { public Constraint<Double> applyBolusConstraints(Constraint<Double> insulin) {
insulin.setIfGreater(getAapsLogger(), 0d, String.format(resourceHelper.gs(R.string.limitingbolus), 0d, resourceHelper.gs(R.string.itmustbepositivevalue)), this); insulin.setIfGreater(getAapsLogger(), 0d, String.format(getResourceHelper().gs(R.string.limitingbolus), 0d, getResourceHelper().gs(R.string.itmustbepositivevalue)), this);
Double maxBolus = sp.getDouble(R.string.key_treatmentssafety_maxbolus, 3d); Double maxBolus = sp.getDouble(R.string.key_treatmentssafety_maxbolus, 3d);
insulin.setIfSmaller(getAapsLogger(), maxBolus, String.format(resourceHelper.gs(R.string.limitingbolus), maxBolus, resourceHelper.gs(R.string.maxvalueinpreferences)), this); insulin.setIfSmaller(getAapsLogger(), maxBolus, String.format(getResourceHelper().gs(R.string.limitingbolus), maxBolus, getResourceHelper().gs(R.string.maxvalueinpreferences)), this);
insulin.setIfSmaller(getAapsLogger(), HardLimits.maxBolus(), String.format(resourceHelper.gs(R.string.limitingbolus), HardLimits.maxBolus(), resourceHelper.gs(R.string.hardlimit)), this); insulin.setIfSmaller(getAapsLogger(), hardLimits.maxBolus(), String.format(getResourceHelper().gs(R.string.limitingbolus), hardLimits.maxBolus(), getResourceHelper().gs(R.string.hardlimit)), this);
PumpInterface pump = activePlugin.getActivePumpPlugin(); PumpInterface pump = activePlugin.getActivePumpPlugin();
if (pump != null) { if (pump != null) {
double rounded = pump.getPumpDescription().pumpType.determineCorrectBolusSize(insulin.value()); double rounded = pump.getPumpDescription().pumpType.determineCorrectBolusSize(insulin.value());
insulin.setIfDifferent(getAapsLogger(), rounded, resourceHelper.gs(R.string.pumplimit), this); insulin.setIfDifferent(getAapsLogger(), rounded, getResourceHelper().gs(R.string.pumplimit), this);
} }
return insulin; return insulin;
} }
@NonNull @Override @NonNull @Override
public Constraint<Double> applyExtendedBolusConstraints(Constraint<Double> insulin) { public Constraint<Double> applyExtendedBolusConstraints(Constraint<Double> insulin) {
insulin.setIfGreater(getAapsLogger(), 0d, String.format(resourceHelper.gs(R.string.limitingextendedbolus), 0d, resourceHelper.gs(R.string.itmustbepositivevalue)), this); insulin.setIfGreater(getAapsLogger(), 0d, String.format(getResourceHelper().gs(R.string.limitingextendedbolus), 0d, getResourceHelper().gs(R.string.itmustbepositivevalue)), this);
Double maxBolus = sp.getDouble(R.string.key_treatmentssafety_maxbolus, 3d); Double maxBolus = sp.getDouble(R.string.key_treatmentssafety_maxbolus, 3d);
insulin.setIfSmaller(getAapsLogger(), maxBolus, String.format(resourceHelper.gs(R.string.limitingextendedbolus), maxBolus, resourceHelper.gs(R.string.maxvalueinpreferences)), this); insulin.setIfSmaller(getAapsLogger(), maxBolus, String.format(getResourceHelper().gs(R.string.limitingextendedbolus), maxBolus, getResourceHelper().gs(R.string.maxvalueinpreferences)), this);
insulin.setIfSmaller(getAapsLogger(), HardLimits.maxBolus(), String.format(resourceHelper.gs(R.string.limitingextendedbolus), HardLimits.maxBolus(), resourceHelper.gs(R.string.hardlimit)), this); insulin.setIfSmaller(getAapsLogger(), hardLimits.maxBolus(), String.format(getResourceHelper().gs(R.string.limitingextendedbolus), hardLimits.maxBolus(), getResourceHelper().gs(R.string.hardlimit)), this);
PumpInterface pump = activePlugin.getActivePumpPlugin(); PumpInterface pump = activePlugin.getActivePumpPlugin();
if (pump != null) { if (pump != null) {
double rounded = pump.getPumpDescription().pumpType.determineCorrectExtendedBolusSize(insulin.value()); double rounded = pump.getPumpDescription().pumpType.determineCorrectExtendedBolusSize(insulin.value());
insulin.setIfDifferent(getAapsLogger(), rounded, resourceHelper.gs(R.string.pumplimit), this); insulin.setIfDifferent(getAapsLogger(), rounded, getResourceHelper().gs(R.string.pumplimit), this);
} }
return insulin; return insulin;
} }
@NonNull @Override @NonNull @Override
public Constraint<Integer> applyCarbsConstraints(Constraint<Integer> carbs) { public Constraint<Integer> applyCarbsConstraints(Constraint<Integer> carbs) {
carbs.setIfGreater(getAapsLogger(), 0, String.format(resourceHelper.gs(R.string.limitingcarbs), 0, resourceHelper.gs(R.string.itmustbepositivevalue)), this); carbs.setIfGreater(getAapsLogger(), 0, String.format(getResourceHelper().gs(R.string.limitingcarbs), 0, getResourceHelper().gs(R.string.itmustbepositivevalue)), this);
Integer maxCarbs = sp.getInt(R.string.key_treatmentssafety_maxcarbs, 48); Integer maxCarbs = sp.getInt(R.string.key_treatmentssafety_maxcarbs, 48);
carbs.setIfSmaller(getAapsLogger(), maxCarbs, String.format(resourceHelper.gs(R.string.limitingcarbs), maxCarbs, resourceHelper.gs(R.string.maxvalueinpreferences)), this); carbs.setIfSmaller(getAapsLogger(), maxCarbs, String.format(getResourceHelper().gs(R.string.limitingcarbs), maxCarbs, getResourceHelper().gs(R.string.maxvalueinpreferences)), this);
return carbs; return carbs;
} }
@ -259,14 +282,14 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
maxIobPref = sp.getDouble(R.string.key_openapssmb_max_iob, 3d); maxIobPref = sp.getDouble(R.string.key_openapssmb_max_iob, 3d);
else else
maxIobPref = sp.getDouble(R.string.key_openapsma_max_iob, 1.5d); maxIobPref = sp.getDouble(R.string.key_openapsma_max_iob, 1.5d);
maxIob.setIfSmaller(getAapsLogger(), maxIobPref, String.format(resourceHelper.gs(R.string.limitingiob), maxIobPref, resourceHelper.gs(R.string.maxvalueinpreferences)), this); maxIob.setIfSmaller(getAapsLogger(), maxIobPref, String.format(getResourceHelper().gs(R.string.limitingiob), maxIobPref, getResourceHelper().gs(R.string.maxvalueinpreferences)), this);
if (openAPSMAPlugin.isEnabled(PluginType.APS)) if (openAPSMAPlugin.isEnabled(PluginType.APS))
maxIob.setIfSmaller(getAapsLogger(), HardLimits.maxIobAMA(), String.format(resourceHelper.gs(R.string.limitingiob), HardLimits.maxIobAMA(), resourceHelper.gs(R.string.hardlimit)), this); maxIob.setIfSmaller(getAapsLogger(), hardLimits.maxIobAMA(), String.format(getResourceHelper().gs(R.string.limitingiob), hardLimits.maxIobAMA(), getResourceHelper().gs(R.string.hardlimit)), this);
if (openAPSAMAPlugin.isEnabled(PluginType.APS)) if (openAPSAMAPlugin.isEnabled(PluginType.APS))
maxIob.setIfSmaller(getAapsLogger(), HardLimits.maxIobAMA(), String.format(resourceHelper.gs(R.string.limitingiob), HardLimits.maxIobAMA(), resourceHelper.gs(R.string.hardlimit)), this); maxIob.setIfSmaller(getAapsLogger(), hardLimits.maxIobAMA(), String.format(getResourceHelper().gs(R.string.limitingiob), hardLimits.maxIobAMA(), getResourceHelper().gs(R.string.hardlimit)), this);
if (openAPSSMBPlugin.isEnabled(PluginType.APS)) if (openAPSSMBPlugin.isEnabled(PluginType.APS))
maxIob.setIfSmaller(getAapsLogger(), HardLimits.maxIobSMB(), String.format(resourceHelper.gs(R.string.limitingiob), HardLimits.maxIobSMB(), resourceHelper.gs(R.string.hardlimit)), this); maxIob.setIfSmaller(getAapsLogger(), hardLimits.maxIobSMB(), String.format(getResourceHelper().gs(R.string.limitingiob), hardLimits.maxIobSMB(), getResourceHelper().gs(R.string.hardlimit)), this);
return maxIob; return maxIob;
} }

View file

@ -27,6 +27,7 @@ import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.OKDialog import info.nightscout.androidaps.utils.OKDialog
import info.nightscout.androidaps.utils.SingleClickButton import info.nightscout.androidaps.utils.SingleClickButton
import info.nightscout.androidaps.utils.build.BuildHelper
import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.extensions.plusAssign
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
@ -49,6 +50,7 @@ class ActionsFragment : DaggerFragment() {
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var activePlugin: ActivePluginProvider
@Inject lateinit var commandQueue: CommandQueueProvider @Inject lateinit var commandQueue: CommandQueueProvider
@Inject lateinit var buildHelper: BuildHelper
private var disposable: CompositeDisposable = CompositeDisposable() private var disposable: CompositeDisposable = CompositeDisposable()
@ -191,7 +193,7 @@ class ActionsFragment : DaggerFragment() {
actions_tddstats.visibility = (pump != null || profile == null).toVisibility() actions_tddstats.visibility = (pump != null || profile == null).toVisibility()
if (pump == null) return if (pump == null) return
val basalProfileEnabled = MainApp.isEngineeringModeOrRelease() && pump.pumpDescription.isSetBasalProfileCapable val basalProfileEnabled = buildHelper.isEngineeringModeOrRelease() && pump.pumpDescription.isSetBasalProfileCapable
actions_profileswitch?.visibility = if (!basalProfileEnabled || !pump.isInitialized || pump.isSuspended) View.GONE else View.VISIBLE actions_profileswitch?.visibility = if (!basalProfileEnabled || !pump.isInitialized || pump.isSuspended) View.GONE else View.VISIBLE

View file

@ -77,6 +77,7 @@ public class NewNSTreatmentDialog extends DaggerDialogFragment implements View.O
@Inject SP sp; @Inject SP sp;
@Inject ConfigBuilderPlugin configBuilderPlugin; @Inject ConfigBuilderPlugin configBuilderPlugin;
@Inject TreatmentsPlugin treatmentsPlugin; @Inject TreatmentsPlugin treatmentsPlugin;
@Inject HardLimits hardLimits;
private static Logger log = StacktraceLoggerWrapper.getLogger(NewNSTreatmentDialog.class); private static Logger log = StacktraceLoggerWrapper.getLogger(NewNSTreatmentDialog.class);
@ -342,7 +343,7 @@ public class NewNSTreatmentDialog extends DaggerDialogFragment implements View.O
} }
}; };
Double maxAbsolute = HardLimits.maxBasal(); Double maxAbsolute = hardLimits.maxBasal();
if (profile != null) if (profile != null)
maxAbsolute = constraintChecker.getMaxBasalAllowed(profile).value(); maxAbsolute = constraintChecker.getMaxBasalAllowed(profile).value();
editAbsolute = view.findViewById(R.id.careportal_newnstreatment_absoluteinput); editAbsolute = view.findViewById(R.id.careportal_newnstreatment_absoluteinput);

View file

@ -13,6 +13,7 @@ import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.general.nsclient.data.NSSettingsStatus import info.nightscout.androidaps.plugins.general.nsclient.data.NSSettingsStatus
import info.nightscout.androidaps.utils.build.BuildHelper
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import java.io.* import java.io.*
@ -29,7 +30,8 @@ class MaintenancePlugin @Inject constructor(
resourceHelper: ResourceHelper, resourceHelper: ResourceHelper,
private val sp: SP, private val sp: SP,
private val nsSettingsStatus: NSSettingsStatus, private val nsSettingsStatus: NSSettingsStatus,
aapsLogger: AAPSLogger aapsLogger: AAPSLogger,
private val buildHelper: BuildHelper
) : PluginBase(PluginDescription() ) : PluginBase(PluginDescription()
.mainType(PluginType.GENERAL) .mainType(PluginType.GENERAL)
.fragmentClass(MaintenanceFragment::class.java.name) .fragmentClass(MaintenanceFragment::class.java.name)
@ -171,7 +173,7 @@ class MaintenancePlugin @Inject constructor(
builder.append("Remote: " + BuildConfig.REMOTE + System.lineSeparator()) builder.append("Remote: " + BuildConfig.REMOTE + System.lineSeparator())
builder.append("Flavor: " + BuildConfig.FLAVOR + BuildConfig.BUILD_TYPE + System.lineSeparator()) builder.append("Flavor: " + BuildConfig.FLAVOR + BuildConfig.BUILD_TYPE + System.lineSeparator())
builder.append(resourceHelper.gs(R.string.configbuilder_nightscoutversion_label) + " " + nsSettingsStatus.nightscoutVersionName + System.lineSeparator()) builder.append(resourceHelper.gs(R.string.configbuilder_nightscoutversion_label) + " " + nsSettingsStatus.nightscoutVersionName + System.lineSeparator())
if (MainApp.engineeringMode) builder.append(resourceHelper.gs(R.string.engineering_mode_enabled)) if (buildHelper.isEngineeringMode()) builder.append(resourceHelper.gs(R.string.engineering_mode_enabled))
return sendMail(attachmentUri, recipient, subject, builder.toString()) return sendMail(attachmentUri, recipient, subject, builder.toString())
} }

View file

@ -91,7 +91,6 @@ import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.nsclient.data.NSDeviceStatus; import info.nightscout.androidaps.plugins.general.nsclient.data.NSDeviceStatus;
import info.nightscout.androidaps.plugins.general.overview.activities.QuickWizardListActivity; import info.nightscout.androidaps.plugins.general.overview.activities.QuickWizardListActivity;
import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData; import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData;
@ -116,6 +115,7 @@ import info.nightscout.androidaps.utils.Profiler;
import info.nightscout.androidaps.utils.SingleClickButton; import info.nightscout.androidaps.utils.SingleClickButton;
import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.T;
import info.nightscout.androidaps.utils.ToastUtils; import info.nightscout.androidaps.utils.ToastUtils;
import info.nightscout.androidaps.utils.build.BuildHelper;
import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP; import info.nightscout.androidaps.utils.sharedPreferences.SP;
import info.nightscout.androidaps.utils.wizard.BolusWizard; import info.nightscout.androidaps.utils.wizard.BolusWizard;
@ -148,6 +148,7 @@ public class OverviewFragment extends DaggerFragment implements View.OnClickList
@Inject NotificationStore notificationStore; @Inject NotificationStore notificationStore;
@Inject ActionStringHandler actionStringHandler; @Inject ActionStringHandler actionStringHandler;
@Inject QuickWizard quickWizard; @Inject QuickWizard quickWizard;
@Inject BuildHelper buildHelper;
private CompositeDisposable disposable = new CompositeDisposable(); private CompositeDisposable disposable = new CompositeDisposable();
@ -567,7 +568,7 @@ public class OverviewFragment extends DaggerFragment implements View.OnClickList
item.setCheckable(true); item.setCheckable(true);
item.setChecked(sp.getBoolean("showactivitysecondary", true)); item.setChecked(sp.getBoolean("showactivitysecondary", true));
if (MainApp.devBranch) { if (buildHelper.isDev()) {
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.DEVSLOPE.ordinal(), Menu.NONE, "Deviation slope"); item = popup.getMenu().add(Menu.NONE, CHARTTYPE.DEVSLOPE.ordinal(), Menu.NONE, "Deviation slope");
title = item.getTitle(); title = item.getTitle();
if (titleMaxChars < title.length()) titleMaxChars = title.length(); if (titleMaxChars < title.length()) titleMaxChars = title.length();
@ -1492,7 +1493,7 @@ public class OverviewFragment extends DaggerFragment implements View.OnClickList
secondGraphData.addRatio(fromTime, now, useRatioForScale, 1d); secondGraphData.addRatio(fromTime, now, useRatioForScale, 1d);
if (sp.getBoolean("showactivitysecondary", true)) if (sp.getBoolean("showactivitysecondary", true))
secondGraphData.addActivity(fromTime, endTime, useIAForScale, 0.8d); secondGraphData.addActivity(fromTime, endTime, useIAForScale, 0.8d);
if (sp.getBoolean("showdevslope", false) && MainApp.devBranch) if (sp.getBoolean("showdevslope", false) && buildHelper.isDev())
secondGraphData.addDeviationSlope(fromTime, now, useDSForScale, 1d); secondGraphData.addDeviationSlope(fromTime, now, useDSForScale, 1d);
// **** NOW line **** // **** NOW line ****

View file

@ -65,7 +65,8 @@ class ActionStringHandler @Inject constructor(
private val danaRKoreanPlugin: DanaRKoreanPlugin, private val danaRKoreanPlugin: DanaRKoreanPlugin,
private val danaRv2Plugin: DanaRv2Plugin, private val danaRv2Plugin: DanaRv2Plugin,
private val danaRSPlugin: DanaRSPlugin, private val danaRSPlugin: DanaRSPlugin,
private val danaRPump: DanaRPump private val danaRPump: DanaRPump,
private val hardLimits: HardLimits
) { ) {
private val TIMEOUT = 65 * 1000 private val TIMEOUT = 65 * 1000
@ -131,11 +132,11 @@ class ActionStringHandler @Inject constructor(
low *= Constants.MMOLL_TO_MGDL low *= Constants.MMOLL_TO_MGDL
high *= Constants.MMOLL_TO_MGDL high *= Constants.MMOLL_TO_MGDL
} }
if (low < HardLimits.VERY_HARD_LIMIT_TEMP_MIN_BG[0] || low > HardLimits.VERY_HARD_LIMIT_TEMP_MIN_BG[1]) { if (low < hardLimits.VERY_HARD_LIMIT_TEMP_MIN_BG[0] || low > hardLimits.VERY_HARD_LIMIT_TEMP_MIN_BG[1]) {
sendError("Min-BG out of range!") sendError("Min-BG out of range!")
return return
} }
if (high < HardLimits.VERY_HARD_LIMIT_TEMP_MAX_BG[0] || high > HardLimits.VERY_HARD_LIMIT_TEMP_MAX_BG[1]) { if (high < hardLimits.VERY_HARD_LIMIT_TEMP_MAX_BG[0] || high > hardLimits.VERY_HARD_LIMIT_TEMP_MAX_BG[1]) {
sendError("Max-BG out of range!") sendError("Max-BG out of range!")
return return
} }

View file

@ -15,7 +15,6 @@ import javax.inject.Inject;
import dagger.android.HasAndroidInjector; import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
@ -42,6 +41,7 @@ import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.MidnightTime; import info.nightscout.androidaps.utils.MidnightTime;
import info.nightscout.androidaps.utils.Profiler; import info.nightscout.androidaps.utils.Profiler;
import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.T;
import info.nightscout.androidaps.utils.build.BuildHelper;
import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP; import info.nightscout.androidaps.utils.sharedPreferences.SP;
@ -65,6 +65,7 @@ public class IobCobOref1Thread extends Thread {
@Inject IobCobCalculatorPlugin iobCobCalculatorPlugin; @Inject IobCobCalculatorPlugin iobCobCalculatorPlugin;
@Inject SensitivityAAPSPlugin sensitivityAAPSPlugin; @Inject SensitivityAAPSPlugin sensitivityAAPSPlugin;
@Inject SensitivityWeightedAveragePlugin sensitivityWeightedAveragePlugin; @Inject SensitivityWeightedAveragePlugin sensitivityWeightedAveragePlugin;
@Inject BuildHelper buildHelper;
private final HasAndroidInjector injector; private final HasAndroidInjector injector;
private boolean bgDataReload; private boolean bgDataReload;
@ -123,7 +124,7 @@ public class IobCobOref1Thread extends Thread {
AutosensData previous = autosensDataTable.get(prevDataTime); AutosensData previous = autosensDataTable.get(prevDataTime);
// start from oldest to be able sub cob // start from oldest to be able sub cob
for (int i = bucketed_data.size() - 4; i >= 0; i--) { for (int i = bucketed_data.size() - 4; i >= 0; i--) {
String progress = i + (MainApp.isDev() ? " (" + from + ")" : ""); String progress = i + (buildHelper.isDev() ? " (" + from + ")" : "");
rxBus.send(new EventIobCalculationProgress(progress)); rxBus.send(new EventIobCalculationProgress(progress));
if (iobCobCalculatorPlugin.stopCalculationTrigger) { if (iobCobCalculatorPlugin.stopCalculationTrigger) {

View file

@ -13,7 +13,6 @@ import javax.inject.Inject;
import dagger.android.HasAndroidInjector; import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
@ -40,6 +39,7 @@ import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.MidnightTime; import info.nightscout.androidaps.utils.MidnightTime;
import info.nightscout.androidaps.utils.Profiler; import info.nightscout.androidaps.utils.Profiler;
import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.T;
import info.nightscout.androidaps.utils.build.BuildHelper;
import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP; import info.nightscout.androidaps.utils.sharedPreferences.SP;
@ -62,6 +62,7 @@ public class IobCobThread extends Thread {
@Inject IobCobCalculatorPlugin iobCobCalculatorPlugin; @Inject IobCobCalculatorPlugin iobCobCalculatorPlugin;
@Inject SensitivityAAPSPlugin sensitivityAAPSPlugin; @Inject SensitivityAAPSPlugin sensitivityAAPSPlugin;
@Inject SensitivityWeightedAveragePlugin sensitivityWeightedAveragePlugin; @Inject SensitivityWeightedAveragePlugin sensitivityWeightedAveragePlugin;
@Inject BuildHelper buildHelper;
private final HasAndroidInjector injector; private final HasAndroidInjector injector;
private boolean bgDataReload; private boolean bgDataReload;
@ -120,7 +121,7 @@ public class IobCobThread extends Thread {
AutosensData previous = autosensDataTable.get(prevDataTime); AutosensData previous = autosensDataTable.get(prevDataTime);
// start from oldest to be able sub cob // start from oldest to be able sub cob
for (int i = bucketed_data.size() - 4; i >= 0; i--) { for (int i = bucketed_data.size() - 4; i >= 0; i--) {
String progress = i + (MainApp.isDev() ? " (" + from + ")" : ""); String progress = i + (buildHelper.isDev() ? " (" + from + ")" : "");
rxBus.send(new EventIobCalculationProgress(progress)); rxBus.send(new EventIobCalculationProgress(progress));
if (iobCobCalculatorPlugin.stopCalculationTrigger) { if (iobCobCalculatorPlugin.stopCalculationTrigger) {

View file

@ -32,6 +32,7 @@ class LocalProfileFragment : DaggerFragment() {
@Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var activePlugin: ActivePluginProvider
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var localProfilePlugin: LocalProfilePlugin @Inject lateinit var localProfilePlugin: LocalProfilePlugin
@Inject lateinit var hardLimits: HardLimits
private var disposable: CompositeDisposable = CompositeDisposable() private var disposable: CompositeDisposable = CompositeDisposable()
@ -99,16 +100,16 @@ class LocalProfileFragment : DaggerFragment() {
localprofile_name.removeTextChangedListener(textWatch) localprofile_name.removeTextChangedListener(textWatch)
localprofile_name.setText(localProfilePlugin.currentProfile().name) localprofile_name.setText(localProfilePlugin.currentProfile().name)
localprofile_name.addTextChangedListener(textWatch) localprofile_name.addTextChangedListener(textWatch)
localprofile_dia.setParams(localProfilePlugin.currentProfile().dia, HardLimits.MINDIA, HardLimits.MAXDIA, 0.1, DecimalFormat("0.0"), false, localprofile_save, textWatch) localprofile_dia.setParams(localProfilePlugin.currentProfile().dia, hardLimits.MINDIA, hardLimits.MAXDIA, 0.1, DecimalFormat("0.0"), false, localprofile_save, textWatch)
localprofile_dia.tag = "LP_DIA" localprofile_dia.tag = "LP_DIA"
TimeListEdit(context, view, R.id.localprofile_ic, "IC", resourceHelper.gs(R.string.nsprofileview_ic_label), localProfilePlugin.currentProfile().ic, null, HardLimits.MINIC, HardLimits.MAXIC, 0.1, DecimalFormat("0.0"), save) TimeListEdit(context, view, R.id.localprofile_ic, "IC", resourceHelper.gs(R.string.nsprofileview_ic_label), localProfilePlugin.currentProfile().ic, null, hardLimits.MINIC, hardLimits.MAXIC, 0.1, DecimalFormat("0.0"), save)
basalView = TimeListEdit(context, view, R.id.localprofile_basal, "BASAL", resourceHelper.gs(R.string.nsprofileview_basal_label) + ": " + sumLabel(), localProfilePlugin.currentProfile().basal, null, pumpDescription.basalMinimumRate, 10.0, 0.01, DecimalFormat("0.00"), save) basalView = TimeListEdit(context, view, R.id.localprofile_basal, "BASAL", resourceHelper.gs(R.string.nsprofileview_basal_label) + ": " + sumLabel(), localProfilePlugin.currentProfile().basal, null, pumpDescription.basalMinimumRate, 10.0, 0.01, DecimalFormat("0.00"), save)
if (units == Constants.MGDL) { if (units == Constants.MGDL) {
TimeListEdit(context, view, R.id.localprofile_isf, "ISF", resourceHelper.gs(R.string.nsprofileview_isf_label), localProfilePlugin.currentProfile().isf, null, HardLimits.MINISF, HardLimits.MAXISF, 1.0, DecimalFormat("0"), save) TimeListEdit(context, view, R.id.localprofile_isf, "ISF", resourceHelper.gs(R.string.nsprofileview_isf_label), localProfilePlugin.currentProfile().isf, null, hardLimits.MINISF, hardLimits.MAXISF, 1.0, DecimalFormat("0"), save)
TimeListEdit(context, view, R.id.localprofile_target, "TARGET", resourceHelper.gs(R.string.nsprofileview_target_label), localProfilePlugin.currentProfile().targetLow, localProfilePlugin.currentProfile().targetHigh, HardLimits.VERY_HARD_LIMIT_TARGET_BG[0].toDouble(), HardLimits.VERY_HARD_LIMIT_TARGET_BG[1].toDouble(), 1.0, DecimalFormat("0"), save) TimeListEdit(context, view, R.id.localprofile_target, "TARGET", resourceHelper.gs(R.string.nsprofileview_target_label), localProfilePlugin.currentProfile().targetLow, localProfilePlugin.currentProfile().targetHigh, hardLimits.VERY_HARD_LIMIT_TARGET_BG[0].toDouble(), hardLimits.VERY_HARD_LIMIT_TARGET_BG[1].toDouble(), 1.0, DecimalFormat("0"), save)
} else { } else {
TimeListEdit(context, view, R.id.localprofile_isf, "ISF", resourceHelper.gs(R.string.nsprofileview_isf_label), localProfilePlugin.currentProfile().isf, null, Profile.fromMgdlToUnits(HardLimits.MINISF, Constants.MMOL), Profile.fromMgdlToUnits(HardLimits.MAXISF, Constants.MMOL), 0.1, DecimalFormat("0.0"), save) TimeListEdit(context, view, R.id.localprofile_isf, "ISF", resourceHelper.gs(R.string.nsprofileview_isf_label), localProfilePlugin.currentProfile().isf, null, Profile.fromMgdlToUnits(hardLimits.MINISF, Constants.MMOL), Profile.fromMgdlToUnits(hardLimits.MAXISF, Constants.MMOL), 0.1, DecimalFormat("0.0"), save)
TimeListEdit(context, view, R.id.localprofile_target, "TARGET", resourceHelper.gs(R.string.nsprofileview_target_label), localProfilePlugin.currentProfile().targetLow, localProfilePlugin.currentProfile().targetHigh, Profile.fromMgdlToUnits(HardLimits.VERY_HARD_LIMIT_TARGET_BG[0].toDouble(), Constants.MMOL), Profile.fromMgdlToUnits(HardLimits.VERY_HARD_LIMIT_TARGET_BG[1].toDouble(), Constants.MMOL), 0.1, DecimalFormat("0.0"), save) TimeListEdit(context, view, R.id.localprofile_target, "TARGET", resourceHelper.gs(R.string.nsprofileview_target_label), localProfilePlugin.currentProfile().targetLow, localProfilePlugin.currentProfile().targetHigh, Profile.fromMgdlToUnits(hardLimits.VERY_HARD_LIMIT_TARGET_BG[0].toDouble(), Constants.MMOL), Profile.fromMgdlToUnits(hardLimits.VERY_HARD_LIMIT_TARGET_BG[1].toDouble(), Constants.MMOL), 0.1, DecimalFormat("0.0"), save)
} }
// Spinner // Spinner

View file

@ -6,7 +6,6 @@ import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import org.json.JSONObject; import org.json.JSONObject;
import org.slf4j.Logger;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
@ -41,8 +40,7 @@ import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.PumpPluginBase; import info.nightscout.androidaps.interfaces.PumpPluginBase;
import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.common.ManufacturerType; import info.nightscout.androidaps.plugins.common.ManufacturerType;
@ -81,7 +79,6 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP;
*/ */
@Singleton @Singleton
public class ComboPlugin extends PumpPluginBase implements PumpInterface, ConstraintsInterface { public class ComboPlugin extends PumpPluginBase implements PumpInterface, ConstraintsInterface {
private static final Logger log = StacktraceLoggerWrapper.getLogger(L.PUMP);
static final String COMBO_TBRS_SET = "combo_tbrs_set"; static final String COMBO_TBRS_SET = "combo_tbrs_set";
static final String COMBO_BOLUSES_DELIVERED = "combo_boluses_delivered"; static final String COMBO_BOLUSES_DELIVERED = "combo_boluses_delivered";
@ -141,7 +138,6 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
HasAndroidInjector injector, HasAndroidInjector injector,
AAPSLogger aapsLogger, AAPSLogger aapsLogger,
RxBusWrapper rxBus, RxBusWrapper rxBus,
MainApp maiApp,
ResourceHelper resourceHelper, ResourceHelper resourceHelper,
ConstraintChecker constraintChecker, ConstraintChecker constraintChecker,
ProfileFunction profileFunction, ProfileFunction profileFunction,
@ -172,7 +168,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
super.onStart(); super.onStart();
ruffyScripter = new RuffyScripter(MainApp.instance()); ruffyScripter = new RuffyScripter(MainApp.instance());
OPERATION_NOT_SUPPORTED = new PumpEnactResult(getInjector()) OPERATION_NOT_SUPPORTED = new PumpEnactResult(getInjector())
.success(false).enacted(false).comment(MainApp.gs(R.string.combo_pump_unsupported_operation)); .success(false).enacted(false).comment(getResourceHelper().gs(R.string.combo_pump_unsupported_operation));
} }
public ComboPump getPump() { public ComboPump getPump() {
@ -186,15 +182,15 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
? "E" + ps.activeAlert.errorCode + ": " + ps.activeAlert.message ? "E" + ps.activeAlert.errorCode + ": " + ps.activeAlert.message
: "W" + ps.activeAlert.warningCode + ": " + ps.activeAlert.message; : "W" + ps.activeAlert.warningCode + ": " + ps.activeAlert.message;
} else if (ps.suspended && (ps.batteryState == PumpState.EMPTY || ps.insulinState == PumpState.EMPTY)) { } else if (ps.suspended && (ps.batteryState == PumpState.EMPTY || ps.insulinState == PumpState.EMPTY)) {
return MainApp.gs(R.string.combo_pump_state_suspended_due_to_error); return getResourceHelper().gs(R.string.combo_pump_state_suspended_due_to_error);
} else if (ps.suspended) { } else if (ps.suspended) {
return MainApp.gs(R.string.combo_pump_state_suspended_by_user); return getResourceHelper().gs(R.string.combo_pump_state_suspended_by_user);
} else if (!pump.initialized) { } else if (!pump.initialized) {
return MainApp.gs(R.string.combo_pump_state_initializing); return getResourceHelper().gs(R.string.combo_pump_state_initializing);
} else if (!validBasalRateProfileSelectedOnPump) { } else if (!validBasalRateProfileSelectedOnPump) {
return MainApp.gs(R.string.loopdisabled); return getResourceHelper().gs(R.string.loopdisabled);
} }
return MainApp.gs(R.string.combo_pump_state_running); return getResourceHelper().gs(R.string.combo_pump_state_running);
} }
@Override @Override
@ -245,8 +241,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
@Override @Override
public void disconnect(String reason) { public void disconnect(String reason) {
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "Disconnect called with reason: " + reason);
log.debug("Disconnect called with reason: " + reason);
ruffyScripter.disconnect(); ruffyScripter.disconnect();
} }
@ -260,10 +255,10 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
if (!isInitialized()) { if (!isInitialized()) {
// note that this should not happen anymore since the queue is present, which // note that this should not happen anymore since the queue is present, which
// issues a READSTATE when starting to issue commands which initializes the pump // issues a READSTATE when starting to issue commands which initializes the pump
log.error("setNewBasalProfile not initialized"); getAapsLogger().error("setNewBasalProfile not initialized");
Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, MainApp.gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT); Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, getResourceHelper().gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT);
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification));
return new PumpEnactResult(getInjector()).success(false).enacted(false).comment(MainApp.gs(R.string.pumpNotInitializedProfileNotSet)); return new PumpEnactResult(getInjector()).success(false).enacted(false).comment(getResourceHelper().gs(R.string.pumpNotInitializedProfileNotSet));
} }
BasalProfile requestedBasalProfile = convertProfileToComboProfile(profile); BasalProfile requestedBasalProfile = convertProfileToComboProfile(profile);
@ -276,15 +271,15 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
CommandResult stateResult = runCommand(null, 1, ruffyScripter::readPumpState); CommandResult stateResult = runCommand(null, 1, ruffyScripter::readPumpState);
if (stateResult.state.unsafeUsageDetected == PumpState.UNSUPPORTED_BASAL_RATE_PROFILE) { if (stateResult.state.unsafeUsageDetected == PumpState.UNSUPPORTED_BASAL_RATE_PROFILE) {
return new PumpEnactResult(getInjector()).success(false).enacted(false).comment(MainApp.gs(R.string.combo_force_disabled_notification)); return new PumpEnactResult(getInjector()).success(false).enacted(false).comment(getResourceHelper().gs(R.string.combo_force_disabled_notification));
} }
CommandResult setResult = runCommand(MainApp.gs(R.string.combo_activity_setting_basal_profile), 2, CommandResult setResult = runCommand(getResourceHelper().gs(R.string.combo_activity_setting_basal_profile), 2,
() -> ruffyScripter.setBasalProfile(requestedBasalProfile)); () -> ruffyScripter.setBasalProfile(requestedBasalProfile));
if (!setResult.success) { if (!setResult.success) {
Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, MainApp.gs(R.string.failedupdatebasalprofile), Notification.URGENT); Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, getResourceHelper().gs(R.string.failedupdatebasalprofile), Notification.URGENT);
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification));
return new PumpEnactResult(getInjector()).success(false).enacted(false).comment(MainApp.gs(R.string.failedupdatebasalprofile)); return new PumpEnactResult(getInjector()).success(false).enacted(false).comment(getResourceHelper().gs(R.string.failedupdatebasalprofile));
} }
pump.basalProfile = requestedBasalProfile; pump.basalProfile = requestedBasalProfile;
@ -293,7 +288,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
RxBus.Companion.getINSTANCE().send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)); RxBus.Companion.getINSTANCE().send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
RxBus.Companion.getINSTANCE().send(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE)); RxBus.Companion.getINSTANCE().send(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE));
//issue success notification //issue success notification
Notification notification = new Notification(Notification.PROFILE_SET_OK, MainApp.gs(R.string.profile_set_ok), Notification.INFO, 60); Notification notification = new Notification(Notification.PROFILE_SET_OK, getResourceHelper().gs(R.string.profile_set_ok), Notification.INFO, 60);
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification));
return new PumpEnactResult(getInjector()).success(true).enacted(true); return new PumpEnactResult(getInjector()).success(true).enacted(true);
} }
@ -344,8 +339,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
*/ */
@Override @Override
public synchronized void getPumpStatus() { public synchronized void getPumpStatus() {
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "getPumpStatus called");
log.debug("getPumpStatus called");
if (!pump.initialized) { if (!pump.initialized) {
initializePump(); initializePump();
} else { } else {
@ -357,12 +351,10 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
private synchronized void initializePump() { private synchronized void initializePump() {
long maxWait = System.currentTimeMillis() + 15 * 1000; long maxWait = System.currentTimeMillis() + 15 * 1000;
while (!ruffyScripter.isPumpAvailable()) { while (!ruffyScripter.isPumpAvailable()) {
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "Waiting for ruffy service to come up ...");
log.debug("Waiting for ruffy service to come up ...");
SystemClock.sleep(100); SystemClock.sleep(100);
if (System.currentTimeMillis() > maxWait) { if (System.currentTimeMillis() > maxWait) {
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "ruffy service unavailable, wtf");
log.debug("ruffy service unavailable, wtf");
return; return;
} }
} }
@ -371,7 +363,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
CommandResult stateResult = runCommand(null, 1, ruffyScripter::readPumpState); CommandResult stateResult = runCommand(null, 1, ruffyScripter::readPumpState);
if (stateResult.invalidSetup) { if (stateResult.invalidSetup) {
RxBus.Companion.getINSTANCE().send(new EventNewNotification( RxBus.Companion.getINSTANCE().send(new EventNewNotification(
new Notification(Notification.COMBO_PUMP_ALARM, MainApp.gs(R.string.combo_invalid_setup), Notification.URGENT))); new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.combo_invalid_setup), Notification.URGENT)));
return; return;
} }
if (!stateResult.success) { if (!stateResult.success) {
@ -381,14 +373,13 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
// note that since the history is checked upon every connect, the above already updated // note that since the history is checked upon every connect, the above already updated
// the DB with any changed history records // the DB with any changed history records
if (pumpHistoryChanged) { if (pumpHistoryChanged) {
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "Pump history has changed and was imported");
log.debug("Pump history has changed and was imported");
pumpHistoryChanged = false; pumpHistoryChanged = false;
} }
if (stateResult.state.unsafeUsageDetected == PumpState.UNSUPPORTED_BASAL_RATE_PROFILE) { if (stateResult.state.unsafeUsageDetected == PumpState.UNSUPPORTED_BASAL_RATE_PROFILE) {
Notification n = new Notification(Notification.COMBO_PUMP_ALARM, Notification n = new Notification(Notification.COMBO_PUMP_ALARM,
MainApp.gs(R.string.combo_force_disabled_notification), getResourceHelper().gs(R.string.combo_force_disabled_notification),
Notification.URGENT); Notification.URGENT);
n.soundId = R.raw.alarm; n.soundId = R.raw.alarm;
RxBus.Companion.getINSTANCE().send(new EventNewNotification(n)); RxBus.Companion.getINSTANCE().send(new EventNewNotification(n));
@ -396,7 +387,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
} }
// read basal profile into cache (KeepAlive will trigger a profile update if needed) // read basal profile into cache (KeepAlive will trigger a profile update if needed)
CommandResult readBasalResult = runCommand(MainApp.gs(R.string.combo_actvity_reading_basal_profile), 2, ruffyScripter::readBasalProfile); CommandResult readBasalResult = runCommand(getResourceHelper().gs(R.string.combo_actvity_reading_basal_profile), 2, ruffyScripter::readBasalProfile);
if (!readBasalResult.success) { if (!readBasalResult.success) {
return; return;
} }
@ -412,7 +403,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
long lastBolusTimestamp = recentBoluses.get(0).timestamp; long lastBolusTimestamp = recentBoluses.get(0).timestamp;
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
if (lastBolusTimestamp < now - 24 * 60 * 60 * 1000 || lastBolusTimestamp > now + 5 * 60 * 1000) { if (lastBolusTimestamp < now - 24 * 60 * 60 * 1000 || lastBolusTimestamp > now + 5 * 60 * 1000) {
Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, MainApp.gs(R.string.combo_check_date), Notification.URGENT); Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.combo_check_date), Notification.URGENT);
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification));
} }
} }
@ -461,23 +452,23 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
} }
} }
private static BolusProgressReporter bolusProgressReporter = (state, percent, delivered) -> { private BolusProgressReporter bolusProgressReporter = (state, percent, delivered) -> {
EventOverviewBolusProgress event = EventOverviewBolusProgress.INSTANCE; EventOverviewBolusProgress event = EventOverviewBolusProgress.INSTANCE;
switch (state) { switch (state) {
case PROGRAMMING: case PROGRAMMING:
event.setStatus(MainApp.gs(R.string.combo_programming_bolus)); event.setStatus(getResourceHelper().gs(R.string.combo_programming_bolus));
break; break;
case DELIVERING: case DELIVERING:
event.setStatus(MainApp.gs(R.string.bolusdelivering, delivered)); event.setStatus(getResourceHelper().gs(R.string.bolusdelivering, delivered));
break; break;
case DELIVERED: case DELIVERED:
event.setStatus(MainApp.gs(R.string.bolusdelivered, delivered)); event.setStatus(getResourceHelper().gs(R.string.bolusdelivered, delivered));
break; break;
case STOPPING: case STOPPING:
event.setStatus(MainApp.gs(R.string.bolusstopping)); event.setStatus(getResourceHelper().gs(R.string.bolusstopping));
break; break;
case STOPPED: case STOPPED:
event.setStatus(MainApp.gs(R.string.bolusstopped)); event.setStatus(getResourceHelper().gs(R.string.bolusstopped));
break; break;
} }
event.setPercent(percent); event.setPercent(percent);
@ -492,10 +483,10 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
try { try {
if (detailedBolusInfo.insulin == 0 && detailedBolusInfo.carbs == 0) { if (detailedBolusInfo.insulin == 0 && detailedBolusInfo.carbs == 0) {
// neither carbs nor bolus requested // neither carbs nor bolus requested
log.error("deliverTreatment: Invalid input"); getAapsLogger().error("deliverTreatment: Invalid input");
return new PumpEnactResult(getInjector()).success(false).enacted(false) return new PumpEnactResult(getInjector()).success(false).enacted(false)
.bolusDelivered(0d).carbsDelivered(0d) .bolusDelivered(0d).carbsDelivered(0d)
.comment(MainApp.gs(R.string.danar_invalidinput)); .comment(getResourceHelper().gs(R.string.danar_invalidinput));
} else if (detailedBolusInfo.insulin > 0) { } else if (detailedBolusInfo.insulin > 0) {
// bolus needed, ask pump to deliver it // bolus needed, ask pump to deliver it
return deliverBolus(detailedBolusInfo); return deliverBolus(detailedBolusInfo);
@ -511,7 +502,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
return new PumpEnactResult(getInjector()).success(true).enacted(true) return new PumpEnactResult(getInjector()).success(true).enacted(true)
.bolusDelivered(0d).carbsDelivered(detailedBolusInfo.carbs) .bolusDelivered(0d).carbsDelivered(detailedBolusInfo.carbs)
.comment(MainApp.gs(R.string.virtualpump_resultok)); .comment(getResourceHelper().gs(R.string.virtualpump_resultok));
} }
} finally { } finally {
RxBus.Companion.getINSTANCE().send(new EventComboPumpUpdateGUI()); RxBus.Companion.getINSTANCE().send(new EventComboPumpUpdateGUI());
@ -521,23 +512,23 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
@NonNull @NonNull
private PumpEnactResult deliverBolus(final DetailedBolusInfo detailedBolusInfo) { private PumpEnactResult deliverBolus(final DetailedBolusInfo detailedBolusInfo) {
try { try {
pump.activity = MainApp.gs(R.string.combo_pump_action_bolusing, detailedBolusInfo.insulin); pump.activity = getResourceHelper().gs(R.string.combo_pump_action_bolusing, detailedBolusInfo.insulin);
RxBus.Companion.getINSTANCE().send(new EventComboPumpUpdateGUI()); RxBus.Companion.getINSTANCE().send(new EventComboPumpUpdateGUI());
// check pump is ready and all pump bolus records are known // check pump is ready and all pump bolus records are known
CommandResult stateResult = runCommand(null, 2, () -> ruffyScripter.readQuickInfo(1)); CommandResult stateResult = runCommand(null, 2, () -> ruffyScripter.readQuickInfo(1));
if (!stateResult.success) { if (!stateResult.success) {
return new PumpEnactResult(getInjector()).success(false).enacted(false) return new PumpEnactResult(getInjector()).success(false).enacted(false)
.comment(MainApp.gs(R.string.combo_error_no_connection_no_bolus_delivered)); .comment(getResourceHelper().gs(R.string.combo_error_no_connection_no_bolus_delivered));
} }
if (stateResult.reservoirLevel != -1 && stateResult.reservoirLevel - 0.5 < detailedBolusInfo.insulin) { if (stateResult.reservoirLevel != -1 && stateResult.reservoirLevel - 0.5 < detailedBolusInfo.insulin) {
return new PumpEnactResult(getInjector()).success(false).enacted(false) return new PumpEnactResult(getInjector()).success(false).enacted(false)
.comment(MainApp.gs(R.string.combo_reservoir_level_insufficient_for_bolus)); .comment(getResourceHelper().gs(R.string.combo_reservoir_level_insufficient_for_bolus));
} }
// the commands above ensured a connection was made, which updated this field // the commands above ensured a connection was made, which updated this field
if (pumpHistoryChanged) { if (pumpHistoryChanged) {
return new PumpEnactResult(getInjector()).success(false).enacted(false) return new PumpEnactResult(getInjector()).success(false).enacted(false)
.comment(MainApp.gs(R.string.combo_bolus_rejected_due_to_pump_history_change)); .comment(getResourceHelper().gs(R.string.combo_bolus_rejected_due_to_pump_history_change));
} }
Bolus previousBolus = stateResult.history != null && !stateResult.history.bolusHistory.isEmpty() Bolus previousBolus = stateResult.history != null && !stateResult.history.bolusHistory.isEmpty()
@ -548,10 +539,9 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
// within the last 1-2 minutes // within the last 1-2 minutes
if (Math.abs(previousBolus.amount - detailedBolusInfo.insulin) < 0.01 if (Math.abs(previousBolus.amount - detailedBolusInfo.insulin) < 0.01
&& previousBolus.timestamp + 60 * 1000 > System.currentTimeMillis()) { && previousBolus.timestamp + 60 * 1000 > System.currentTimeMillis()) {
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "Bolus request rejected, same bolus was successfully delivered very recently");
log.debug("Bolus request rejected, same bolus was successfully delivered very recently");
return new PumpEnactResult(getInjector()).success(false).enacted(false) return new PumpEnactResult(getInjector()).success(false).enacted(false)
.comment(MainApp.gs(R.string.bolus_frequency_exceeded)); .comment(getResourceHelper().gs(R.string.bolus_frequency_exceeded));
} }
// if the last bolus was given in the current minute, wait till the pump clock moves // if the last bolus was given in the current minute, wait till the pump clock moves
@ -567,18 +557,16 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
} }
if (!timeCheckResult.success) { if (!timeCheckResult.success) {
return new PumpEnactResult(getInjector()).success(false).enacted(false) return new PumpEnactResult(getInjector()).success(false).enacted(false)
.comment(MainApp.gs(R.string.combo_error_no_connection_no_bolus_delivered)); .comment(getResourceHelper().gs(R.string.combo_error_no_connection_no_bolus_delivered));
} }
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "Waiting for pump clock to advance for the next unused bolus record timestamp");
log.debug("Waiting for pump clock to advance for the next unused bolus record timestamp");
SystemClock.sleep(2000); SystemClock.sleep(2000);
timeCheckResult = runCommand(null, 0, ruffyScripter::readPumpState); timeCheckResult = runCommand(null, 0, ruffyScripter::readPumpState);
waitLoops++; waitLoops++;
} }
if (waitLoops > 0) { if (waitLoops > 0) {
long waitDuration = (System.currentTimeMillis() - waitStartTime) / 1000; long waitDuration = (System.currentTimeMillis() - waitStartTime) / 1000;
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "Waited " + waitDuration + "s for pump to switch to a fresh minute before bolusing");
log.debug("Waited " + waitDuration + "s for pump to switch to a fresh minute before bolusing");
} }
if (cancelBolus) { if (cancelBolus) {
@ -604,7 +592,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
CommandResult postBolusStateResult = runCommand(null, 3, () -> ruffyScripter.readQuickInfo(2)); CommandResult postBolusStateResult = runCommand(null, 3, () -> ruffyScripter.readQuickInfo(2));
if (!postBolusStateResult.success) { if (!postBolusStateResult.success) {
return new PumpEnactResult(getInjector()).success(false).enacted(false) return new PumpEnactResult(getInjector()).success(false).enacted(false)
.comment(MainApp.gs(R.string.combo_error_bolus_verification_failed)); .comment(getResourceHelper().gs(R.string.combo_error_bolus_verification_failed));
} }
Bolus lastPumpBolus = postBolusStateResult.history != null && !postBolusStateResult.history.bolusHistory.isEmpty() Bolus lastPumpBolus = postBolusStateResult.history != null && !postBolusStateResult.history.bolusHistory.isEmpty()
? postBolusStateResult.history.bolusHistory.get(0) ? postBolusStateResult.history.bolusHistory.get(0)
@ -618,19 +606,19 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
return new PumpEnactResult(getInjector()) return new PumpEnactResult(getInjector())
.success(false) .success(false)
.enacted(false) .enacted(false)
.comment(MainApp.gs(R.string.combo_error_no_bolus_delivered)); .comment(getResourceHelper().gs(R.string.combo_error_no_bolus_delivered));
} }
} }
// at least some insulin delivered, so add it to treatments // at least some insulin delivered, so add it to treatments
if (!addBolusToTreatments(detailedBolusInfo, lastPumpBolus)) if (!addBolusToTreatments(detailedBolusInfo, lastPumpBolus))
return new PumpEnactResult(getInjector()).success(false).enacted(true) return new PumpEnactResult(getInjector()).success(false).enacted(true)
.comment(MainApp.gs(R.string.combo_error_updating_treatment_record)); .comment(getResourceHelper().gs(R.string.combo_error_updating_treatment_record));
// check pump bolus record has a sane timestamp // check pump bolus record has a sane timestamp
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
if (lastPumpBolus.timestamp < now - 10 * 60 * 1000 || lastPumpBolus.timestamp > now + 10 * 60 * 1000) { if (lastPumpBolus.timestamp < now - 10 * 60 * 1000 || lastPumpBolus.timestamp > now + 10 * 60 * 1000) {
Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, MainApp.gs(R.string.combo_suspious_bolus_time), Notification.URGENT); Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.combo_suspious_bolus_time), Notification.URGENT);
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification));
} }
@ -644,7 +632,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
return new PumpEnactResult(getInjector()).success(true).enacted(true); return new PumpEnactResult(getInjector()).success(true).enacted(true);
} }
return new PumpEnactResult(getInjector()).success(false).enacted(true) return new PumpEnactResult(getInjector()).success(false).enacted(true)
.comment(MainApp.gs(R.string.combo_error_partial_bolus_delivered, .comment(getResourceHelper().gs(R.string.combo_error_partial_bolus_delivered,
lastPumpBolus.amount, detailedBolusInfo.insulin)); lastPumpBolus.amount, detailedBolusInfo.insulin));
} }
@ -704,9 +692,9 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
} }
TreatmentsPlugin.getPlugin().addToHistoryTreatment(bolusInfo, true); TreatmentsPlugin.getPlugin().addToHistoryTreatment(bolusInfo, true);
} catch (Exception e) { } catch (Exception e) {
log.error("Adding treatment record failed", e); getAapsLogger().error("Adding treatment record failed", e);
if (bolusInfo.isSMB) { if (bolusInfo.isSMB) {
Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, MainApp.gs(R.string.combo_error_updating_treatment_record), Notification.URGENT); Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.combo_error_updating_treatment_record), Notification.URGENT);
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification));
} }
return false; return false;
@ -733,13 +721,11 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
*/ */
@NonNull @Override @NonNull @Override
public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean force) { public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean force) {
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "setTempBasalAbsolute called with a rate of " + absoluteRate + " for " + durationInMinutes + " min.");
log.debug("setTempBasalAbsolute called with a rate of " + absoluteRate + " for " + durationInMinutes + " min.");
int unroundedPercentage = Double.valueOf(absoluteRate / getBaseBasalRate() * 100).intValue(); int unroundedPercentage = Double.valueOf(absoluteRate / getBaseBasalRate() * 100).intValue();
int roundedPercentage = (int) (Math.round(absoluteRate / getBaseBasalRate() * 10) * 10); int roundedPercentage = (int) (Math.round(absoluteRate / getBaseBasalRate() * 10) * 10);
if (unroundedPercentage != roundedPercentage) { if (unroundedPercentage != roundedPercentage) {
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "Rounded requested rate " + unroundedPercentage + "% -> " + roundedPercentage + "%");
log.debug("Rounded requested rate " + unroundedPercentage + "% -> " + roundedPercentage + "%");
} }
return setTempBasalPercent(roundedPercentage, durationInMinutes); return setTempBasalPercent(roundedPercentage, durationInMinutes);
@ -757,26 +743,23 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
} }
private PumpEnactResult setTempBasalPercent(Integer percent, final Integer durationInMinutes) { private PumpEnactResult setTempBasalPercent(Integer percent, final Integer durationInMinutes) {
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "setTempBasalPercent called with " + percent + "% for " + durationInMinutes + "min");
log.debug("setTempBasalPercent called with " + percent + "% for " + durationInMinutes + "min");
if (pumpHistoryChanged && percent > 110) { if (pumpHistoryChanged && percent > 110) {
return new PumpEnactResult(getInjector()).success(false).enacted(false) return new PumpEnactResult(getInjector()).success(false).enacted(false)
.comment(MainApp.gs(R.string.combo_high_temp_rejected_due_to_pump_history_changes)); .comment(getResourceHelper().gs(R.string.combo_high_temp_rejected_due_to_pump_history_changes));
} }
int adjustedPercent = percent; int adjustedPercent = percent;
if (adjustedPercent > pumpDescription.maxTempPercent) { if (adjustedPercent > pumpDescription.maxTempPercent) {
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "Reducing requested TBR to the maximum support by the pump: " + percent + " -> " + pumpDescription.maxTempPercent);
log.debug("Reducing requested TBR to the maximum support by the pump: " + percent + " -> " + pumpDescription.maxTempPercent);
adjustedPercent = pumpDescription.maxTempPercent; adjustedPercent = pumpDescription.maxTempPercent;
} }
if (adjustedPercent % 10 != 0) { if (adjustedPercent % 10 != 0) {
Long rounded = Math.round(adjustedPercent / 10d) * 10; Long rounded = Math.round(adjustedPercent / 10d) * 10;
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "Rounded requested percentage:" + adjustedPercent + " -> " + rounded);
log.debug("Rounded requested percentage:" + adjustedPercent + " -> " + rounded);
adjustedPercent = rounded.intValue(); adjustedPercent = rounded.intValue();
} }
@ -786,7 +769,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
} }
int finalAdjustedPercent = adjustedPercent; int finalAdjustedPercent = adjustedPercent;
CommandResult commandResult = runCommand(MainApp.gs(R.string.combo_pump_action_setting_tbr, percent, durationInMinutes), CommandResult commandResult = runCommand(getResourceHelper().gs(R.string.combo_pump_action_setting_tbr, percent, durationInMinutes),
3, () -> ruffyScripter.setTbr(finalAdjustedPercent, durationInMinutes)); 3, () -> ruffyScripter.setTbr(finalAdjustedPercent, durationInMinutes));
if (!commandResult.success) { if (!commandResult.success) {
return new PumpEnactResult(getInjector()).success(false).enacted(false); return new PumpEnactResult(getInjector()).success(false).enacted(false);
@ -825,20 +808,18 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
*/ */
@NonNull @Override @NonNull @Override
public PumpEnactResult cancelTempBasal(boolean enforceNew) { public PumpEnactResult cancelTempBasal(boolean enforceNew) {
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "cancelTempBasal called");
log.debug("cancelTempBasal called");
final TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis()); final TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis());
if (enforceNew) { if (enforceNew) {
CommandResult stateResult = runCommand(MainApp.gs(R.string.combo_pump_action_refreshing), 2, ruffyScripter::readPumpState); CommandResult stateResult = runCommand(getResourceHelper().gs(R.string.combo_pump_action_refreshing), 2, ruffyScripter::readPumpState);
if (!stateResult.success) { if (!stateResult.success) {
return new PumpEnactResult(getInjector()).success(false).enacted(false); return new PumpEnactResult(getInjector()).success(false).enacted(false);
} }
if (!stateResult.state.tbrActive) { if (!stateResult.state.tbrActive) {
return new PumpEnactResult(getInjector()).success(true).enacted(false); return new PumpEnactResult(getInjector()).success(true).enacted(false);
} }
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "cancelTempBasal: hard-cancelling TBR since force requested");
log.debug("cancelTempBasal: hard-cancelling TBR since force requested"); CommandResult cancelResult = runCommand(getResourceHelper().gs(R.string.combo_pump_action_cancelling_tbr), 2, ruffyScripter::cancelTbr);
CommandResult cancelResult = runCommand(MainApp.gs(R.string.combo_pump_action_cancelling_tbr), 2, ruffyScripter::cancelTbr);
if (!cancelResult.success) { if (!cancelResult.success) {
return new PumpEnactResult(getInjector()).success(false).enacted(false); return new PumpEnactResult(getInjector()).success(false).enacted(false);
} }
@ -858,8 +839,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
// Let fake neutral temp keep run (see below) // Let fake neutral temp keep run (see below)
// Note that since this runs on the queue a connection is opened regardless, but this // Note that since this runs on the queue a connection is opened regardless, but this
// case doesn't occur all that often, so it's not worth optimizing (1.3k SetTBR vs 4 cancelTBR). // case doesn't occur all that often, so it's not worth optimizing (1.3k SetTBR vs 4 cancelTBR).
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "cancelTempBasal: skipping changing tbr since it already is at " + activeTemp.percentRate + "% and running for another " + activeTemp.getPlannedRemainingMinutes() + " mins.");
log.debug("cancelTempBasal: skipping changing tbr since it already is at " + activeTemp.percentRate + "% and running for another " + activeTemp.getPlannedRemainingMinutes() + " mins.");
return new PumpEnactResult(getInjector()).success(true).enacted(true) return new PumpEnactResult(getInjector()).success(true).enacted(true)
.comment("cancelTempBasal skipping changing tbr since it already is at " .comment("cancelTempBasal skipping changing tbr since it already is at "
+ activeTemp.percentRate + "% and running for another " + activeTemp.percentRate + "% and running for another "
@ -868,8 +848,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
// Set a fake neutral temp to avoid TBR cancel alert. Decide 90% vs 110% based on // Set a fake neutral temp to avoid TBR cancel alert. Decide 90% vs 110% based on
// on whether the TBR we're cancelling is above or below 100%. // on whether the TBR we're cancelling is above or below 100%.
final int percentage = (activeTemp.percentRate > 100) ? 110 : 90; final int percentage = (activeTemp.percentRate > 100) ? 110 : 90;
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "cancelTempBasal: changing TBR to " + percentage + "% for 15 mins.");
log.debug("cancelTempBasal: changing TBR to " + percentage + "% for 15 mins.");
return setTempBasalPercent(percentage, 15); return setTempBasalPercent(percentage, 15);
} }
} }
@ -889,7 +868,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
try { try {
if (!ruffyScripter.isConnected()) { if (!ruffyScripter.isConnected()) {
String originalActivity = pump.activity; String originalActivity = pump.activity;
pump.activity = MainApp.gs(R.string.combo_activity_checking_pump_state); pump.activity = getResourceHelper().gs(R.string.combo_activity_checking_pump_state);
RxBus.Companion.getINSTANCE().send(new EventComboPumpUpdateGUI()); RxBus.Companion.getINSTANCE().send(new EventComboPumpUpdateGUI());
CommandResult preCheckError = runOnConnectChecks(); CommandResult preCheckError = runOnConnectChecks();
pump.activity = originalActivity; pump.activity = originalActivity;
@ -908,8 +887,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
if (!commandResult.success && retries > 0) { if (!commandResult.success && retries > 0) {
for (int retryAttempts = 1; !commandResult.success && retryAttempts <= retries; retryAttempts++) { for (int retryAttempts = 1; !commandResult.success && retryAttempts <= retries; retryAttempts++) {
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "Command was not successful, retries requested, doing retry #" + retryAttempts);
log.debug("Command was not successful, retries requested, doing retry #" + retryAttempts);
commandResult = commandExecution.execute(); commandResult = commandExecution.execute();
} }
} }
@ -923,7 +901,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
if (validBasalRateProfileSelectedOnPump && commandResult.state.unsafeUsageDetected == PumpState.UNSUPPORTED_BASAL_RATE_PROFILE) { if (validBasalRateProfileSelectedOnPump && commandResult.state.unsafeUsageDetected == PumpState.UNSUPPORTED_BASAL_RATE_PROFILE) {
setValidBasalRateProfileSelectedOnPump(false); setValidBasalRateProfileSelectedOnPump(false);
Notification n = new Notification(Notification.COMBO_PUMP_ALARM, Notification n = new Notification(Notification.COMBO_PUMP_ALARM,
MainApp.gs(R.string.combo_force_disabled_notification), getResourceHelper().gs(R.string.combo_force_disabled_notification),
Notification.URGENT); Notification.URGENT);
n.soundId = R.raw.alarm; n.soundId = R.raw.alarm;
RxBus.Companion.getINSTANCE().send(new EventNewNotification(n)); RxBus.Companion.getINSTANCE().send(new EventNewNotification(n));
@ -971,7 +949,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
notification.date = DateUtil.now(); notification.date = DateUtil.now();
notification.id = Notification.COMBO_PUMP_ALARM; notification.id = Notification.COMBO_PUMP_ALARM;
notification.level = Notification.URGENT; notification.level = Notification.URGENT;
notification.text = MainApp.gs(R.string.combo_is_in_error_state, activeAlert.errorCode, activeAlert.message); notification.text = getResourceHelper().gs(R.string.combo_is_in_error_state, activeAlert.errorCode, activeAlert.message);
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification));
return preCheckResult.success(false); return preCheckResult.success(false);
} }
@ -990,8 +968,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
TemporaryBasal aapsTbr = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now); TemporaryBasal aapsTbr = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now);
if (aapsTbr == null || aapsTbr.percentRate != 0) { if (aapsTbr == null || aapsTbr.percentRate != 0) {
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "Creating 15m zero temp since pump is suspended");
log.debug("Creating 15m zero temp since pump is suspended");
TemporaryBasal newTempBasal = new TemporaryBasal() TemporaryBasal newTempBasal = new TemporaryBasal()
.date(now) .date(now)
.percent(0) .percent(0)
@ -1031,13 +1008,13 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
} }
if (Math.abs(pumpBasalRate - getBaseBasalRate()) > 0.001) { if (Math.abs(pumpBasalRate - getBaseBasalRate()) > 0.001) {
CommandResult readBasalResult = runCommand(MainApp.gs(R.string.combo_actvity_reading_basal_profile), 2, ruffyScripter::readBasalProfile); CommandResult readBasalResult = runCommand(getResourceHelper().gs(R.string.combo_actvity_reading_basal_profile), 2, ruffyScripter::readBasalProfile);
if (readBasalResult.success) { if (readBasalResult.success) {
pump.basalProfile = readBasalResult.basalProfile; pump.basalProfile = readBasalResult.basalProfile;
Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, MainApp.gs(R.string.combo_warning_pump_basal_rate_changed), Notification.NORMAL); Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.combo_warning_pump_basal_rate_changed), Notification.NORMAL);
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification));
} else { } else {
Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, MainApp.gs(R.string.combo_error_failure_reading_changed_basal_rate), Notification.URGENT); Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.combo_error_failure_reading_changed_basal_rate), Notification.URGENT);
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification));
} }
} }
@ -1051,14 +1028,12 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
if (state.pumpTime == 0) { if (state.pumpTime == 0) {
// time couldn't be read (e.g. a warning is displayed on the menu , hiding the time field) // time couldn't be read (e.g. a warning is displayed on the menu , hiding the time field)
} else if (Math.abs(state.pumpTime - System.currentTimeMillis()) >= 10 * 60 * 1000) { } else if (Math.abs(state.pumpTime - System.currentTimeMillis()) >= 10 * 60 * 1000) {
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "Pump clock needs update, pump time: " + state.pumpTime + " (" + new Date(state.pumpTime) + ")");
log.debug("Pump clock needs update, pump time: " + state.pumpTime + " (" + new Date(state.pumpTime) + ")"); Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.combo_notification_check_time_date), Notification.URGENT);
Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, MainApp.gs(R.string.combo_notification_check_time_date), Notification.URGENT);
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification));
} else if (Math.abs(state.pumpTime - System.currentTimeMillis()) >= 3 * 60 * 1000) { } else if (Math.abs(state.pumpTime - System.currentTimeMillis()) >= 3 * 60 * 1000) {
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "Pump clock needs update, pump time: " + state.pumpTime + " (" + new Date(state.pumpTime) + ")");
log.debug("Pump clock needs update, pump time: " + state.pumpTime + " (" + new Date(state.pumpTime) + ")"); Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.combo_notification_check_time_date), Notification.NORMAL);
Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, MainApp.gs(R.string.combo_notification_check_time_date), Notification.NORMAL);
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification));
} }
} }
@ -1075,11 +1050,11 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
notification.id = Notification.COMBO_PUMP_ALARM; notification.id = Notification.COMBO_PUMP_ALARM;
notification.level = Notification.NORMAL; notification.level = Notification.NORMAL;
if (activeAlert.warningCode == PumpWarningCodes.CARTRIDGE_LOW) { if (activeAlert.warningCode == PumpWarningCodes.CARTRIDGE_LOW) {
notification.text = MainApp.gs(R.string.combo_pump_cartridge_low_warrning); notification.text = getResourceHelper().gs(R.string.combo_pump_cartridge_low_warrning);
} else if (activeAlert.warningCode == PumpWarningCodes.BATTERY_LOW) { } else if (activeAlert.warningCode == PumpWarningCodes.BATTERY_LOW) {
notification.text = MainApp.gs(R.string.combo_pump_battery_low_warrning); notification.text = getResourceHelper().gs(R.string.combo_pump_battery_low_warrning);
} else if (activeAlert.warningCode == PumpWarningCodes.TBR_CANCELLED) { } else if (activeAlert.warningCode == PumpWarningCodes.TBR_CANCELLED) {
notification.text = MainApp.gs(R.string.combo_pump_tbr_cancelled_warrning); notification.text = getResourceHelper().gs(R.string.combo_pump_tbr_cancelled_warrning);
} }
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification));
} }
@ -1101,7 +1076,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
lowSuspendOnlyLoopEnforcedUntil = lastViolation + 6 * 60 * 60 * 1000; lowSuspendOnlyLoopEnforcedUntil = lastViolation + 6 * 60 * 60 * 1000;
if (lowSuspendOnlyLoopEnforcedUntil > System.currentTimeMillis() && violationWarningRaisedForBolusAt != lowSuspendOnlyLoopEnforcedUntil) { if (lowSuspendOnlyLoopEnforcedUntil > System.currentTimeMillis() && violationWarningRaisedForBolusAt != lowSuspendOnlyLoopEnforcedUntil) {
Notification n = new Notification(Notification.COMBO_PUMP_ALARM, Notification n = new Notification(Notification.COMBO_PUMP_ALARM,
MainApp.gs(R.string.combo_low_suspend_forced_notification), getResourceHelper().gs(R.string.combo_low_suspend_forced_notification),
Notification.URGENT); Notification.URGENT);
n.soundId = R.raw.alarm; n.soundId = R.raw.alarm;
RxBus.Companion.getINSTANCE().send(new EventNewNotification(n)); RxBus.Companion.getINSTANCE().send(new EventNewNotification(n));
@ -1119,8 +1094,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
TemporaryBasal aapsTbr = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now); TemporaryBasal aapsTbr = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now);
if (aapsTbr == null && state.tbrActive && state.tbrRemainingDuration > 2) { if (aapsTbr == null && state.tbrActive && state.tbrRemainingDuration > 2) {
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "Creating temp basal from pump TBR");
log.debug("Creating temp basal from pump TBR");
TemporaryBasal newTempBasal = new TemporaryBasal() TemporaryBasal newTempBasal = new TemporaryBasal()
.date(now) .date(now)
.percent(state.tbrPercent) .percent(state.tbrPercent)
@ -1128,8 +1102,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
.source(Source.USER); .source(Source.USER);
TreatmentsPlugin.getPlugin().addToHistoryTempBasal(newTempBasal); TreatmentsPlugin.getPlugin().addToHistoryTempBasal(newTempBasal);
} else if (aapsTbr != null && aapsTbr.getPlannedRemainingMinutes() > 2 && !state.tbrActive) { } else if (aapsTbr != null && aapsTbr.getPlannedRemainingMinutes() > 2 && !state.tbrActive) {
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "Ending AAPS-TBR since pump has no TBR active");
log.debug("Ending AAPS-TBR since pump has no TBR active");
TemporaryBasal tempStop = new TemporaryBasal() TemporaryBasal tempStop = new TemporaryBasal()
.date(now) .date(now)
.duration(0) .duration(0)
@ -1138,8 +1111,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
} else if (aapsTbr != null && state.tbrActive } else if (aapsTbr != null && state.tbrActive
&& (aapsTbr.percentRate != state.tbrPercent || && (aapsTbr.percentRate != state.tbrPercent ||
Math.abs(aapsTbr.getPlannedRemainingMinutes() - state.tbrRemainingDuration) > 2)) { Math.abs(aapsTbr.getPlannedRemainingMinutes() - state.tbrRemainingDuration) > 2)) {
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "AAPSs and pump-TBR differ; ending AAPS-TBR and creating new TBR based on pump TBR");
log.debug("AAPSs and pump-TBR differ; ending AAPS-TBR and creating new TBR based on pump TBR");
TemporaryBasal tempStop = new TemporaryBasal() TemporaryBasal tempStop = new TemporaryBasal()
.date(now - 1000) .date(now - 1000)
.duration(0) .duration(0)
@ -1159,7 +1131,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
* Reads the pump's history and updates the DB accordingly. * Reads the pump's history and updates the DB accordingly.
*/ */
private boolean readHistory(@Nullable PumpHistoryRequest request) { private boolean readHistory(@Nullable PumpHistoryRequest request) {
CommandResult historyResult = runCommand(MainApp.gs(R.string.combo_activity_reading_pump_history), 3, () -> ruffyScripter.readHistory(request)); CommandResult historyResult = runCommand(getResourceHelper().gs(R.string.combo_activity_reading_pump_history), 3, () -> ruffyScripter.readHistory(request));
PumpHistory history = historyResult.history; PumpHistory history = historyResult.history;
if (!historyResult.success || history == null) { if (!historyResult.success || history == null) {
return false; return false;
@ -1217,13 +1189,12 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
* @return null on success or the failed command result * @return null on success or the failed command result
*/ */
private CommandResult checkHistory() { private CommandResult checkHistory() {
CommandResult quickInfoResult = runCommand(MainApp.gs(R.string.combo_activity_checking_for_history_changes), 3, CommandResult quickInfoResult = runCommand(getResourceHelper().gs(R.string.combo_activity_checking_for_history_changes), 3,
() -> ruffyScripter.readQuickInfo(2)); () -> ruffyScripter.readQuickInfo(2));
// no history, nothing to check or complain about // no history, nothing to check or complain about
if (quickInfoResult.history == null || quickInfoResult.history.bolusHistory.isEmpty()) { if (quickInfoResult.history == null || quickInfoResult.history.bolusHistory.isEmpty()) {
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "Setting 'pumpHistoryChanged' false");
log.debug("Setting 'pumpHistoryChanged' false");
pumpHistoryChanged = false; pumpHistoryChanged = false;
return null; return null;
} }
@ -1232,22 +1203,20 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
List<Bolus> initialPumpBolusHistory = quickInfoResult.history.bolusHistory; List<Bolus> initialPumpBolusHistory = quickInfoResult.history.bolusHistory;
if (recentBoluses.size() == 1 && initialPumpBolusHistory.size() >= 1 if (recentBoluses.size() == 1 && initialPumpBolusHistory.size() >= 1
&& recentBoluses.get(0).equals(quickInfoResult.history.bolusHistory.get(0))) { && recentBoluses.get(0).equals(quickInfoResult.history.bolusHistory.get(0))) {
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "Setting 'pumpHistoryChanged' false");
log.debug("Setting 'pumpHistoryChanged' false");
pumpHistoryChanged = false; pumpHistoryChanged = false;
return null; return null;
} else if (recentBoluses.size() == 2 && initialPumpBolusHistory.size() >= 2 } else if (recentBoluses.size() == 2 && initialPumpBolusHistory.size() >= 2
&& recentBoluses.get(0).equals(quickInfoResult.history.bolusHistory.get(0)) && recentBoluses.get(0).equals(quickInfoResult.history.bolusHistory.get(0))
&& recentBoluses.get(1).equals(quickInfoResult.history.bolusHistory.get(1))) { && recentBoluses.get(1).equals(quickInfoResult.history.bolusHistory.get(1))) {
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "Setting 'pumpHistoryChanged' false");
log.debug("Setting 'pumpHistoryChanged' false");
pumpHistoryChanged = false; pumpHistoryChanged = false;
return null; return null;
} }
// fetch new records // fetch new records
long lastKnownPumpRecordTimestamp = recentBoluses.isEmpty() ? 0 : recentBoluses.get(0).timestamp; long lastKnownPumpRecordTimestamp = recentBoluses.isEmpty() ? 0 : recentBoluses.get(0).timestamp;
CommandResult historyResult = runCommand(MainApp.gs(R.string.combo_activity_reading_pump_history), 3, () -> CommandResult historyResult = runCommand(getResourceHelper().gs(R.string.combo_activity_reading_pump_history), 3, () ->
ruffyScripter.readHistory(new PumpHistoryRequest().bolusHistory(lastKnownPumpRecordTimestamp))); ruffyScripter.readHistory(new PumpHistoryRequest().bolusHistory(lastKnownPumpRecordTimestamp)));
if (!historyResult.success) { if (!historyResult.success) {
pumpHistoryChanged = true; pumpHistoryChanged = true;
@ -1260,16 +1229,15 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
// for. // for.
HashSet<Bolus> bolusSet = new HashSet<>(historyResult.history.bolusHistory); HashSet<Bolus> bolusSet = new HashSet<>(historyResult.history.bolusHistory);
if (bolusSet.size() != historyResult.history.bolusHistory.size()) { if (bolusSet.size() != historyResult.history.bolusHistory.size()) {
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "Bolus with same amount within the same minute imported. Only one will make it to the DB.");
log.debug("Bolus with same amount within the same minute imported. Only one will make it to the DB."); Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.
Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, MainApp.gs(R.string.
combo_error_multiple_boluses_with_identical_timestamp), Notification.URGENT); combo_error_multiple_boluses_with_identical_timestamp), Notification.URGENT);
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification));
} }
pumpHistoryChanged = updateDbFromPumpHistory(historyResult.history); pumpHistoryChanged = updateDbFromPumpHistory(historyResult.history);
if (L.isEnabled(L.PUMP) && pumpHistoryChanged) { if (pumpHistoryChanged) {
log.debug("Setting 'pumpHistoryChanged' true"); getAapsLogger().debug(LTag.PUMP, "Setting 'pumpHistoryChanged' true");
} }
List<Bolus> updatedPumpBolusHistory = historyResult.history.bolusHistory; List<Bolus> updatedPumpBolusHistory = historyResult.history.bolusHistory;
@ -1330,7 +1298,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
return pumpJson; return pumpJson;
} catch (Exception e) { } catch (Exception e) {
log.warn("Failed to gather device status for upload", e); getAapsLogger().warn(LTag.PUMP, "Failed to gather device status for upload " + e);
} }
return null; return null;
@ -1402,17 +1370,17 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
private long violationWarningRaisedForBolusAt = 0; private long violationWarningRaisedForBolusAt = 0;
private boolean validBasalRateProfileSelectedOnPump = true; private boolean validBasalRateProfileSelectedOnPump = true;
@Override @NonNull @Override
public Constraint<Boolean> isLoopInvocationAllowed(Constraint<Boolean> value) { public Constraint<Boolean> isLoopInvocationAllowed(@NonNull Constraint<Boolean> value) {
if (!validBasalRateProfileSelectedOnPump) if (!validBasalRateProfileSelectedOnPump)
value.set(getAapsLogger(), false, MainApp.gs(R.string.novalidbasalrate), this); value.set(getAapsLogger(), false, getResourceHelper().gs(R.string.novalidbasalrate), this);
return value; return value;
} }
@Override @NonNull @Override
public Constraint<Double> applyMaxIOBConstraints(Constraint<Double> maxIob) { public Constraint<Double> applyMaxIOBConstraints(@NonNull Constraint<Double> maxIob) {
if (lowSuspendOnlyLoopEnforcedUntil > System.currentTimeMillis()) if (lowSuspendOnlyLoopEnforcedUntil > System.currentTimeMillis())
maxIob.setIfSmaller(getAapsLogger(), 0d, String.format(MainApp.gs(R.string.limitingmaxiob), 0d, MainApp.gs(R.string.unsafeusage)), this); maxIob.setIfSmaller(getAapsLogger(), 0d, String.format(getResourceHelper().gs(R.string.limitingmaxiob), 0d, getResourceHelper().gs(R.string.unsafeusage)), this);
return maxIob; return maxIob;
} }

View file

@ -4,14 +4,12 @@ import androidx.annotation.NonNull;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.slf4j.Logger;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import dagger.android.HasAndroidInjector; import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.data.PumpEnactResult;
@ -27,9 +25,8 @@ import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.PumpPluginBase; import info.nightscout.androidaps.interfaces.PumpPluginBase;
import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.common.ManufacturerType; import info.nightscout.androidaps.plugins.common.ManufacturerType;
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker;
import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction; import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction;
@ -43,16 +40,14 @@ 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.Round; import info.nightscout.androidaps.utils.Round;
import info.nightscout.androidaps.utils.SP;
import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
/** /**
* Created by mike on 28.01.2018. * Created by mike on 28.01.2018.
*/ */
public abstract class AbstractDanaRPlugin extends PumpPluginBase implements PumpInterface, DanaRInterface, ConstraintsInterface { public abstract class AbstractDanaRPlugin extends PumpPluginBase implements PumpInterface, DanaRInterface, ConstraintsInterface {
private Logger log = StacktraceLoggerWrapper.getLogger(L.PUMP);
protected AbstractDanaRExecutionService sExecutionService; protected AbstractDanaRExecutionService sExecutionService;
protected boolean useExtendedBoluses = false; protected boolean useExtendedBoluses = false;
@ -60,6 +55,9 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump
public PumpDescription pumpDescription = new PumpDescription(); public PumpDescription pumpDescription = new PumpDescription();
protected DanaRPump danaRPump; protected DanaRPump danaRPump;
protected ConstraintChecker constraintChecker; protected ConstraintChecker constraintChecker;
protected RxBusWrapper rxBus;
protected TreatmentsPlugin treatmentsPlugin;
protected SP sp;
protected AbstractDanaRPlugin( protected AbstractDanaRPlugin(
HasAndroidInjector injector, HasAndroidInjector injector,
@ -67,7 +65,11 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump
ResourceHelper resourceHelper, ResourceHelper resourceHelper,
ConstraintChecker constraintChecker, ConstraintChecker constraintChecker,
AAPSLogger aapsLogger, AAPSLogger aapsLogger,
CommandQueueProvider commandQueue) { CommandQueueProvider commandQueue,
RxBusWrapper rxBus,
TreatmentsPlugin treatmentsPlugin,
SP sp
) {
super(new PluginDescription() super(new PluginDescription()
.mainType(PluginType.PUMP) .mainType(PluginType.PUMP)
.fragmentClass(DanaRFragment.class.getName()) .fragmentClass(DanaRFragment.class.getName())
@ -79,6 +81,9 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump
); );
this.danaRPump = danaRPump; this.danaRPump = danaRPump;
this.constraintChecker = constraintChecker; this.constraintChecker = constraintChecker;
this.rxBus = rxBus;
this.treatmentsPlugin = treatmentsPlugin;
this.sp = sp;
} }
@Override @Override
@ -98,29 +103,29 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump
PumpEnactResult result = new PumpEnactResult(getInjector()); PumpEnactResult result = new PumpEnactResult(getInjector());
if (sExecutionService == null) { if (sExecutionService == null) {
log.error("setNewBasalProfile sExecutionService is null"); getAapsLogger().error("setNewBasalProfile sExecutionService is null");
result.comment = "setNewBasalProfile sExecutionService is null"; result.comment = "setNewBasalProfile sExecutionService is null";
return result; return result;
} }
if (!isInitialized()) { if (!isInitialized()) {
log.error("setNewBasalProfile not initialized"); getAapsLogger().error("setNewBasalProfile not initialized");
Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, MainApp.gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT); Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, getResourceHelper().gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT);
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); rxBus.send(new EventNewNotification(notification));
result.comment = MainApp.gs(R.string.pumpNotInitializedProfileNotSet); result.comment = getResourceHelper().gs(R.string.pumpNotInitializedProfileNotSet);
return result; return result;
} else { } else {
RxBus.Companion.getINSTANCE().send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)); rxBus.send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
} }
if (!sExecutionService.updateBasalsInPump(profile)) { if (!sExecutionService.updateBasalsInPump(profile)) {
Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, MainApp.gs(R.string.failedupdatebasalprofile), Notification.URGENT); Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, getResourceHelper().gs(R.string.failedupdatebasalprofile), Notification.URGENT);
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); rxBus.send(new EventNewNotification(notification));
result.comment = MainApp.gs(R.string.failedupdatebasalprofile); result.comment = getResourceHelper().gs(R.string.failedupdatebasalprofile);
return result; return result;
} else { } else {
RxBus.Companion.getINSTANCE().send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)); rxBus.send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
RxBus.Companion.getINSTANCE().send(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE)); rxBus.send(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE));
Notification notification = new Notification(Notification.PROFILE_SET_OK, MainApp.gs(R.string.profile_set_ok), Notification.INFO, 60); Notification notification = new Notification(Notification.PROFILE_SET_OK, getResourceHelper().gs(R.string.profile_set_ok), Notification.INFO, 60);
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); rxBus.send(new EventNewNotification(notification));
result.success = true; result.success = true;
result.enacted = true; result.enacted = true;
result.comment = "OK"; result.comment = "OK";
@ -140,8 +145,7 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump
Double pumpValue = danaRPump.getPumpProfiles()[danaRPump.getActiveProfile()][h]; Double pumpValue = danaRPump.getPumpProfiles()[danaRPump.getActiveProfile()][h];
Double profileValue = profile.getBasalTimeFromMidnight(h * basalIncrement); Double profileValue = profile.getBasalTimeFromMidnight(h * basalIncrement);
if (Math.abs(pumpValue - profileValue) > getPumpDescription().basalStep) { if (Math.abs(pumpValue - profileValue) > getPumpDescription().basalStep) {
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "Diff found. Hour: " + h + " Pump: " + pumpValue + " Profile: " + profileValue);
log.debug("Diff found. Hour: " + h + " Pump: " + pumpValue + " Profile: " + profileValue);
return false; return false;
} }
} }
@ -171,7 +175,7 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump
@Override @Override
public void stopBolusDelivering() { public void stopBolusDelivering() {
if (sExecutionService == null) { if (sExecutionService == null) {
log.error("stopBolusDelivering sExecutionService is null"); getAapsLogger().error("stopBolusDelivering sExecutionService is null");
return; return;
} }
sExecutionService.bolusStop(); sExecutionService.bolusStop();
@ -186,24 +190,23 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump
result.isTempCancel = false; result.isTempCancel = false;
result.enacted = false; result.enacted = false;
result.success = false; result.success = false;
result.comment = MainApp.gs(R.string.danar_invalidinput); result.comment = getResourceHelper().gs(R.string.danar_invalidinput);
log.error("setTempBasalPercent: Invalid input"); getAapsLogger().error("setTempBasalPercent: Invalid input");
return result; return result;
} }
if (percent > getPumpDescription().maxTempPercent) if (percent > getPumpDescription().maxTempPercent)
percent = getPumpDescription().maxTempPercent; percent = getPumpDescription().maxTempPercent;
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getRealTempBasalFromHistory(now); TemporaryBasal activeTemp = treatmentsPlugin.getRealTempBasalFromHistory(now);
if (activeTemp != null && activeTemp.percentRate == percent && activeTemp.getPlannedRemainingMinutes() > 4 && !enforceNew) { if (activeTemp != null && activeTemp.percentRate == percent && activeTemp.getPlannedRemainingMinutes() > 4 && !enforceNew) {
result.enacted = false; result.enacted = false;
result.success = true; result.success = true;
result.isTempCancel = false; result.isTempCancel = false;
result.comment = MainApp.gs(R.string.virtualpump_resultok); result.comment = getResourceHelper().gs(R.string.virtualpump_resultok);
result.duration = pump.getTempBasalRemainingMin(); result.duration = pump.getTempBasalRemainingMin();
result.percent = pump.getTempBasalPercent(); result.percent = pump.getTempBasalPercent();
result.isPercent = true; result.isPercent = true;
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "setTempBasalPercent: Correct value already set");
log.debug("setTempBasalPercent: Correct value already set");
return result; return result;
} }
int durationInHours = Math.max(durationInMinutes / 60, 1); int durationInHours = Math.max(durationInMinutes / 60, 1);
@ -211,19 +214,18 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump
if (connectionOK && pump.isTempBasalInProgress() && pump.getTempBasalPercent() == percent) { if (connectionOK && pump.isTempBasalInProgress() && pump.getTempBasalPercent() == percent) {
result.enacted = true; result.enacted = true;
result.success = true; result.success = true;
result.comment = MainApp.gs(R.string.virtualpump_resultok); result.comment = getResourceHelper().gs(R.string.virtualpump_resultok);
result.isTempCancel = false; result.isTempCancel = false;
result.duration = pump.getTempBasalRemainingMin(); result.duration = pump.getTempBasalRemainingMin();
result.percent = pump.getTempBasalPercent(); result.percent = pump.getTempBasalPercent();
result.isPercent = true; result.isPercent = true;
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "setTempBasalPercent: OK");
log.debug("setTempBasalPercent: OK");
return result; return result;
} }
result.enacted = false; result.enacted = false;
result.success = false; result.success = false;
result.comment = MainApp.gs(R.string.tempbasaldeliveryerror); result.comment = getResourceHelper().gs(R.string.tempbasaldeliveryerror);
log.error("setTempBasalPercent: Failed to set temp basal"); getAapsLogger().error("setTempBasalPercent: Failed to set temp basal");
return result; return result;
} }
@ -236,45 +238,43 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump
insulin = Round.roundTo(insulin, getPumpDescription().extendedBolusStep); insulin = Round.roundTo(insulin, getPumpDescription().extendedBolusStep);
PumpEnactResult result = new PumpEnactResult(getInjector()); PumpEnactResult result = new PumpEnactResult(getInjector());
ExtendedBolus runningEB = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(System.currentTimeMillis()); ExtendedBolus runningEB = treatmentsPlugin.getExtendedBolusFromHistory(System.currentTimeMillis());
if (runningEB != null && Math.abs(runningEB.insulin - insulin) < getPumpDescription().extendedBolusStep) { if (runningEB != null && Math.abs(runningEB.insulin - insulin) < getPumpDescription().extendedBolusStep) {
result.enacted = false; result.enacted = false;
result.success = true; result.success = true;
result.comment = MainApp.gs(R.string.virtualpump_resultok); result.comment = getResourceHelper().gs(R.string.virtualpump_resultok);
result.duration = pump.getExtendedBolusRemainingMinutes(); result.duration = pump.getExtendedBolusRemainingMinutes();
result.absolute = pump.getExtendedBolusAbsoluteRate(); result.absolute = pump.getExtendedBolusAbsoluteRate();
result.isPercent = false; result.isPercent = false;
result.isTempCancel = false; result.isTempCancel = false;
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "setExtendedBolus: Correct extended bolus already set. Current: " + pump.getExtendedBolusAmount() + " Asked: " + insulin);
log.debug("setExtendedBolus: Correct extended bolus already set. Current: " + pump.getExtendedBolusAmount() + " Asked: " + insulin);
return result; return result;
} }
boolean connectionOK = sExecutionService.extendedBolus(insulin, durationInHalfHours); boolean connectionOK = sExecutionService.extendedBolus(insulin, durationInHalfHours);
if (connectionOK && pump.isExtendedInProgress() && Math.abs(pump.getExtendedBolusAmount() - insulin) < getPumpDescription().extendedBolusStep) { if (connectionOK && pump.isExtendedInProgress() && Math.abs(pump.getExtendedBolusAmount() - insulin) < getPumpDescription().extendedBolusStep) {
result.enacted = true; result.enacted = true;
result.success = true; result.success = true;
result.comment = MainApp.gs(R.string.virtualpump_resultok); result.comment = getResourceHelper().gs(R.string.virtualpump_resultok);
result.isTempCancel = false; result.isTempCancel = false;
result.duration = pump.getExtendedBolusRemainingMinutes(); result.duration = pump.getExtendedBolusRemainingMinutes();
result.absolute = pump.getExtendedBolusAbsoluteRate(); result.absolute = pump.getExtendedBolusAbsoluteRate();
if (!SP.getBoolean("danar_useextended", false)) if (!sp.getBoolean("danar_useextended", false))
result.bolusDelivered = pump.getExtendedBolusAmount(); result.bolusDelivered = pump.getExtendedBolusAmount();
result.isPercent = false; result.isPercent = false;
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "setExtendedBolus: OK");
log.debug("setExtendedBolus: OK");
return result; return result;
} }
result.enacted = false; result.enacted = false;
result.success = false; result.success = false;
result.comment = MainApp.gs(R.string.danar_valuenotsetproperly); result.comment = getResourceHelper().gs(R.string.danar_valuenotsetproperly);
log.error("setExtendedBolus: Failed to extended bolus"); getAapsLogger().error("setExtendedBolus: Failed to extended bolus");
return result; return result;
} }
@NonNull @Override @NonNull @Override
public PumpEnactResult cancelExtendedBolus() { public PumpEnactResult cancelExtendedBolus() {
PumpEnactResult result = new PumpEnactResult(getInjector()); PumpEnactResult result = new PumpEnactResult(getInjector());
ExtendedBolus runningEB = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(System.currentTimeMillis()); ExtendedBolus runningEB = treatmentsPlugin.getExtendedBolusFromHistory(System.currentTimeMillis());
if (runningEB != null) { if (runningEB != null) {
sExecutionService.extendedBolusStop(); sExecutionService.extendedBolusStop();
result.enacted = true; result.enacted = true;
@ -282,14 +282,13 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump
} }
if (!danaRPump.isExtendedInProgress()) { if (!danaRPump.isExtendedInProgress()) {
result.success = true; result.success = true;
result.comment = MainApp.gs(R.string.virtualpump_resultok); result.comment = getResourceHelper().gs(R.string.virtualpump_resultok);
if (L.isEnabled(L.PUMP)) getAapsLogger().debug(LTag.PUMP, "cancelExtendedBolus: OK");
log.debug("cancelExtendedBolus: OK");
return result; return result;
} else { } else {
result.success = false; result.success = false;
result.comment = MainApp.gs(R.string.danar_valuenotsetproperly); result.comment = getResourceHelper().gs(R.string.danar_valuenotsetproperly);
log.error("cancelExtendedBolus: Failed to cancel extended bolus"); getAapsLogger().error("cancelExtendedBolus: Failed to cancel extended bolus");
return result; return result;
} }
} }
@ -352,13 +351,13 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump
extended.put("LastBolus", DateUtil.dateAndTimeString(pump.getLastBolusTime())); extended.put("LastBolus", DateUtil.dateAndTimeString(pump.getLastBolusTime()));
extended.put("LastBolusAmount", pump.getLastBolusAmount()); extended.put("LastBolusAmount", pump.getLastBolusAmount());
} }
TemporaryBasal tb = TreatmentsPlugin.getPlugin().getRealTempBasalFromHistory(now); TemporaryBasal tb = treatmentsPlugin.getRealTempBasalFromHistory(now);
if (tb != null) { if (tb != null) {
extended.put("TempBasalAbsoluteRate", tb.tempBasalConvertedToAbsolute(now, profile)); extended.put("TempBasalAbsoluteRate", tb.tempBasalConvertedToAbsolute(now, profile));
extended.put("TempBasalStart", DateUtil.dateAndTimeString(tb.date)); extended.put("TempBasalStart", DateUtil.dateAndTimeString(tb.date));
extended.put("TempBasalRemaining", tb.getPlannedRemainingMinutes()); extended.put("TempBasalRemaining", tb.getPlannedRemainingMinutes());
} }
ExtendedBolus eb = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(now); ExtendedBolus eb = treatmentsPlugin.getExtendedBolusFromHistory(now);
if (eb != null) { if (eb != null) {
extended.put("ExtendedBolusAbsoluteRate", eb.absoluteRate()); extended.put("ExtendedBolusAbsoluteRate", eb.absoluteRate());
extended.put("ExtendedBolusStart", DateUtil.dateAndTimeString(eb.date)); extended.put("ExtendedBolusStart", DateUtil.dateAndTimeString(eb.date));
@ -376,7 +375,7 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump
pumpjson.put("reservoir", (int) pump.getReservoirRemainingUnits()); pumpjson.put("reservoir", (int) pump.getReservoirRemainingUnits());
pumpjson.put("clock", DateUtil.toISOString(new Date())); pumpjson.put("clock", DateUtil.toISOString(new Date()));
} catch (JSONException e) { } catch (JSONException e) {
log.error("Unhandled exception", e); getAapsLogger().error("Unhandled exception", e);
} }
return pumpjson; return pumpjson;
} }
@ -409,28 +408,28 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump
* Constraint interface * Constraint interface
*/ */
@Override @NonNull @Override
public Constraint<Double> applyBasalConstraints(Constraint<Double> absoluteRate, Profile profile) { public Constraint<Double> applyBasalConstraints(Constraint<Double> absoluteRate, @NonNull Profile profile) {
absoluteRate.setIfSmaller(getAapsLogger(), danaRPump.getMaxBasal(), String.format(MainApp.gs(R.string.limitingbasalratio), danaRPump.getMaxBasal(), MainApp.gs(R.string.pumplimit)), this); absoluteRate.setIfSmaller(getAapsLogger(), danaRPump.getMaxBasal(), String.format(getResourceHelper().gs(R.string.limitingbasalratio), danaRPump.getMaxBasal(), getResourceHelper().gs(R.string.pumplimit)), this);
return absoluteRate; return absoluteRate;
} }
@Override @NonNull @Override
public Constraint<Integer> applyBasalPercentConstraints(Constraint<Integer> percentRate, Profile profile) { public Constraint<Integer> applyBasalPercentConstraints(Constraint<Integer> percentRate, @NonNull Profile profile) {
percentRate.setIfGreater(getAapsLogger(), 0, String.format(MainApp.gs(R.string.limitingpercentrate), 0, MainApp.gs(R.string.itmustbepositivevalue)), this); percentRate.setIfGreater(getAapsLogger(), 0, String.format(getResourceHelper().gs(R.string.limitingpercentrate), 0, getResourceHelper().gs(R.string.itmustbepositivevalue)), this);
percentRate.setIfSmaller(getAapsLogger(), getPumpDescription().maxTempPercent, String.format(MainApp.gs(R.string.limitingpercentrate), getPumpDescription().maxTempPercent, MainApp.gs(R.string.pumplimit)), this); percentRate.setIfSmaller(getAapsLogger(), getPumpDescription().maxTempPercent, String.format(getResourceHelper().gs(R.string.limitingpercentrate), getPumpDescription().maxTempPercent, getResourceHelper().gs(R.string.pumplimit)), this);
return percentRate; return percentRate;
} }
@Override @NonNull @Override
public Constraint<Double> applyBolusConstraints(Constraint<Double> insulin) { public Constraint<Double> applyBolusConstraints(Constraint<Double> insulin) {
insulin.setIfSmaller(getAapsLogger(), danaRPump.getMaxBolus(), String.format(MainApp.gs(R.string.limitingbolus), danaRPump.getMaxBolus(), MainApp.gs(R.string.pumplimit)), this); insulin.setIfSmaller(getAapsLogger(), danaRPump.getMaxBolus(), String.format(getResourceHelper().gs(R.string.limitingbolus), danaRPump.getMaxBolus(), getResourceHelper().gs(R.string.pumplimit)), this);
return insulin; return insulin;
} }
@Override @NonNull @Override
public Constraint<Double> applyExtendedBolusConstraints(Constraint<Double> insulin) { public Constraint<Double> applyExtendedBolusConstraints(@NonNull Constraint<Double> insulin) {
return applyBolusConstraints(insulin); return applyBolusConstraints(insulin);
} }
@ -444,18 +443,18 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump
DanaRPump pump = danaRPump; DanaRPump pump = danaRPump;
String ret = ""; String ret = "";
if (pump.getLastConnection() != 0) { if (pump.getLastConnection() != 0) {
Long agoMsec = System.currentTimeMillis() - pump.getLastConnection(); long agoMsec = System.currentTimeMillis() - pump.getLastConnection();
int agoMin = (int) (agoMsec / 60d / 1000d); int agoMin = (int) (agoMsec / 60d / 1000d);
ret += "LastConn: " + agoMin + " minago\n"; ret += "LastConn: " + agoMin + " minago\n";
} }
if (pump.getLastBolusTime() != 0) { if (pump.getLastBolusTime() != 0) {
ret += "LastBolus: " + DecimalFormatter.to2Decimal(pump.getLastBolusAmount()) + "U @" + android.text.format.DateFormat.format("HH:mm", pump.getLastBolusTime()) + "\n"; ret += "LastBolus: " + DecimalFormatter.to2Decimal(pump.getLastBolusAmount()) + "U @" + android.text.format.DateFormat.format("HH:mm", pump.getLastBolusTime()) + "\n";
} }
TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getRealTempBasalFromHistory(System.currentTimeMillis()); TemporaryBasal activeTemp = treatmentsPlugin.getRealTempBasalFromHistory(System.currentTimeMillis());
if (activeTemp != null) { if (activeTemp != null) {
ret += "Temp: " + activeTemp.toStringFull() + "\n"; ret += "Temp: " + activeTemp.toStringFull() + "\n";
} }
ExtendedBolus activeExtendedBolus = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(System.currentTimeMillis()); ExtendedBolus activeExtendedBolus = treatmentsPlugin.getExtendedBolusFromHistory(System.currentTimeMillis());
if (activeExtendedBolus != null) { if (activeExtendedBolus != null) {
ret += "Extended: " + activeExtendedBolus.toString() + "\n"; ret += "Extended: " + activeExtendedBolus.toString() + "\n";
} }

View file

@ -12,7 +12,6 @@ import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
import dagger.android.HasAndroidInjector; import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
@ -44,19 +43,16 @@ public class DanaRPlugin extends AbstractDanaRPlugin {
private CompositeDisposable disposable = new CompositeDisposable(); private CompositeDisposable disposable = new CompositeDisposable();
private final AAPSLogger aapsLogger; private final AAPSLogger aapsLogger;
private final RxBusWrapper rxBus; private final Context context;
private final MainApp mainApp;
private final ResourceHelper resourceHelper; private final ResourceHelper resourceHelper;
private final ConstraintChecker constraintChecker; private final ConstraintChecker constraintChecker;
private final TreatmentsPlugin treatmentsPlugin;
private final SP sp;
@Inject @Inject
public DanaRPlugin( public DanaRPlugin(
HasAndroidInjector injector, HasAndroidInjector injector,
AAPSLogger aapsLogger, AAPSLogger aapsLogger,
RxBusWrapper rxBus, RxBusWrapper rxBus,
MainApp maiApp, Context context,
ResourceHelper resourceHelper, ResourceHelper resourceHelper,
ConstraintChecker constraintChecker, ConstraintChecker constraintChecker,
TreatmentsPlugin treatmentsPlugin, TreatmentsPlugin treatmentsPlugin,
@ -64,14 +60,11 @@ public class DanaRPlugin extends AbstractDanaRPlugin {
CommandQueueProvider commandQueue, CommandQueueProvider commandQueue,
DanaRPump danaRPump DanaRPump danaRPump
) { ) {
super(injector, danaRPump, resourceHelper, constraintChecker, aapsLogger, commandQueue); super(injector, danaRPump, resourceHelper, constraintChecker, aapsLogger, commandQueue, rxBus, treatmentsPlugin, sp);
this.aapsLogger = aapsLogger; this.aapsLogger = aapsLogger;
this.rxBus = rxBus; this.context = context;
this.mainApp = maiApp;
this.resourceHelper = resourceHelper; this.resourceHelper = resourceHelper;
this.constraintChecker = constraintChecker; this.constraintChecker = constraintChecker;
this.treatmentsPlugin = treatmentsPlugin;
this.sp = sp;
useExtendedBoluses = sp.getBoolean(R.string.key_danar_useextended, false); useExtendedBoluses = sp.getBoolean(R.string.key_danar_useextended, false);
pumpDescription.setPumpDescription(PumpType.DanaR); pumpDescription.setPumpDescription(PumpType.DanaR);
@ -79,8 +72,8 @@ public class DanaRPlugin extends AbstractDanaRPlugin {
@Override @Override
protected void onStart() { protected void onStart() {
Intent intent = new Intent(mainApp, DanaRExecutionService.class); Intent intent = new Intent(context, DanaRExecutionService.class);
mainApp.bindService(intent, mConnection, Context.BIND_AUTO_CREATE); context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
disposable.add(rxBus disposable.add(rxBus
.toObservable(EventPreferenceChange.class) .toObservable(EventPreferenceChange.class)
.observeOn(Schedulers.io()) .observeOn(Schedulers.io())
@ -98,14 +91,14 @@ public class DanaRPlugin extends AbstractDanaRPlugin {
disposable.add(rxBus disposable.add(rxBus
.toObservable(EventAppExit.class) .toObservable(EventAppExit.class)
.observeOn(Schedulers.io()) .observeOn(Schedulers.io())
.subscribe(event -> mainApp.unbindService(mConnection), exception -> FabricPrivacy.getInstance().logException(exception)) .subscribe(event -> context.unbindService(mConnection), exception -> FabricPrivacy.getInstance().logException(exception))
); );
super.onStart(); super.onStart();
} }
@Override @Override
protected void onStop() { protected void onStop() {
mainApp.unbindService(mConnection); context.unbindService(mConnection);
disposable.clear(); disposable.clear();
super.onStop(); super.onStop();

View file

@ -46,12 +46,9 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin {
private CompositeDisposable disposable = new CompositeDisposable(); private CompositeDisposable disposable = new CompositeDisposable();
private final AAPSLogger aapsLogger; private final AAPSLogger aapsLogger;
private final RxBusWrapper rxBus;
private final MainApp mainApp; private final MainApp mainApp;
private final ResourceHelper resourceHelper; private final ResourceHelper resourceHelper;
private final ConstraintChecker constraintChecker; private final ConstraintChecker constraintChecker;
private final TreatmentsPlugin treatmentsPlugin;
private final SP sp;
@Inject @Inject
public DanaRKoreanPlugin( public DanaRKoreanPlugin(
@ -67,14 +64,11 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin {
CommandQueueProvider commandQueue CommandQueueProvider commandQueue
) { ) {
super(injector, danaRPump, resourceHelper, constraintChecker, aapsLogger, commandQueue); super(injector, danaRPump, resourceHelper, constraintChecker, aapsLogger, commandQueue, rxBus, treatmentsPlugin, sp);
this.aapsLogger = aapsLogger; this.aapsLogger = aapsLogger;
this.rxBus = rxBus;
this.mainApp = maiApp; this.mainApp = maiApp;
this.resourceHelper = resourceHelper; this.resourceHelper = resourceHelper;
this.constraintChecker = constraintChecker; this.constraintChecker = constraintChecker;
this.treatmentsPlugin = treatmentsPlugin;
this.sp = sp;
getPluginDescription().description(R.string.description_pump_dana_r_korean); getPluginDescription().description(R.string.description_pump_dana_r_korean);
useExtendedBoluses = sp.getBoolean(R.string.key_danar_useextended, false); useExtendedBoluses = sp.getBoolean(R.string.key_danar_useextended, false);

View file

@ -46,12 +46,9 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin {
private CompositeDisposable disposable = new CompositeDisposable(); private CompositeDisposable disposable = new CompositeDisposable();
private final AAPSLogger aapsLogger; private final AAPSLogger aapsLogger;
private final RxBusWrapper rxBus;
private final MainApp mainApp; private final MainApp mainApp;
private final ResourceHelper resourceHelper; private final ResourceHelper resourceHelper;
private final ConstraintChecker constraintChecker; private final ConstraintChecker constraintChecker;
private final TreatmentsPlugin treatmentsPlugin;
private final SP sp;
private final DetailedBolusInfoStorage detailedBolusInfoStorage; private final DetailedBolusInfoStorage detailedBolusInfoStorage;
@ -72,14 +69,11 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin {
CommandQueueProvider commandQueue, CommandQueueProvider commandQueue,
DetailedBolusInfoStorage detailedBolusInfoStorage DetailedBolusInfoStorage detailedBolusInfoStorage
) { ) {
super(injector, danaRPump, resourceHelper, constraintChecker, aapsLogger, commandQueue); super(injector, danaRPump, resourceHelper, constraintChecker, aapsLogger, commandQueue, rxBus, treatmentsPlugin, sp);
this.aapsLogger = aapsLogger; this.aapsLogger = aapsLogger;
this.rxBus = rxBus;
this.mainApp = maiApp; this.mainApp = maiApp;
this.resourceHelper = resourceHelper; this.resourceHelper = resourceHelper;
this.constraintChecker = constraintChecker; this.constraintChecker = constraintChecker;
this.treatmentsPlugin = treatmentsPlugin;
this.sp = sp;
this.detailedBolusInfoStorage = detailedBolusInfoStorage; this.detailedBolusInfoStorage = detailedBolusInfoStorage;
getPluginDescription().description(R.string.description_pump_dana_r_v2); getPluginDescription().description(R.string.description_pump_dana_r_v2);

View file

@ -15,6 +15,7 @@ import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.build.BuildHelper
import info.nightscout.androidaps.utils.extensions.isRunningTest import info.nightscout.androidaps.utils.extensions.isRunningTest
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import java.util.* import java.util.*
@ -28,7 +29,8 @@ class RandomBgPlugin @Inject constructor(
injector: HasAndroidInjector, injector: HasAndroidInjector,
resourceHelper: ResourceHelper, resourceHelper: ResourceHelper,
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
private var virtualPumpPlugin: VirtualPumpPlugin private val virtualPumpPlugin: VirtualPumpPlugin,
private val buildHelper: BuildHelper
) : PluginBase(PluginDescription() ) : PluginBase(PluginDescription()
.mainType(PluginType.BGSOURCE) .mainType(PluginType.BGSOURCE)
.fragmentClass(BGSourceFragment::class.java.name) .fragmentClass(BGSourceFragment::class.java.name)
@ -67,7 +69,7 @@ class RandomBgPlugin @Inject constructor(
} }
override fun specialEnableCondition(): Boolean { override fun specialEnableCondition(): Boolean {
return isRunningTest() || virtualPumpPlugin.isEnabled(PluginType.PUMP) && MainApp.engineeringMode return isRunningTest() || virtualPumpPlugin.isEnabled(PluginType.PUMP) && buildHelper.isEngineeringMode()
} }
override fun handleNewData(intent: Intent) { override fun handleNewData(intent: Intent) {

View file

@ -7,7 +7,6 @@ import android.text.Spanned
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import dagger.Lazy import dagger.Lazy
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.BolusProgressHelperActivity import info.nightscout.androidaps.activities.BolusProgressHelperActivity
import info.nightscout.androidaps.data.DetailedBolusInfo import info.nightscout.androidaps.data.DetailedBolusInfo
@ -30,6 +29,7 @@ import info.nightscout.androidaps.plugins.general.overview.notifications.Notific
import info.nightscout.androidaps.queue.commands.* import info.nightscout.androidaps.queue.commands.*
import info.nightscout.androidaps.queue.commands.Command.CommandType import info.nightscout.androidaps.queue.commands.Command.CommandType
import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.build.BuildHelper
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import java.util.* import java.util.*
@ -87,7 +87,8 @@ class CommandQueue @Inject constructor(
val profileFunction: ProfileFunction, val profileFunction: ProfileFunction,
val activePlugin: Lazy<ActivePluginProvider>, val activePlugin: Lazy<ActivePluginProvider>,
val context: Context, val context: Context,
val sp: SP val sp: SP,
private val buildHelper: BuildHelper
) : CommandQueueProvider { ) : CommandQueueProvider {
private val queue = LinkedList<Command>() private val queue = LinkedList<Command>()
@ -171,7 +172,7 @@ class CommandQueue @Inject constructor(
override fun independentConnect(reason: String, callback: Callback?) { override fun independentConnect(reason: String, callback: Callback?) {
aapsLogger.debug(LTag.PUMPQUEUE, "Starting new queue") aapsLogger.debug(LTag.PUMPQUEUE, "Starting new queue")
val tempCommandQueue = CommandQueue(injector, aapsLogger, rxBus, resourceHelper, constraintChecker, profileFunction, activePlugin, context, sp) val tempCommandQueue = CommandQueue(injector, aapsLogger, rxBus, resourceHelper, constraintChecker, profileFunction, activePlugin, context, sp, buildHelper)
tempCommandQueue.readStatus(reason, callback) tempCommandQueue.readStatus(reason, callback)
} }
@ -338,7 +339,7 @@ class CommandQueue @Inject constructor(
callback?.result(PumpEnactResult(injector).success(true).enacted(false))?.run() callback?.result(PumpEnactResult(injector).success(true).enacted(false))?.run()
return false return false
} }
if (!MainApp.isEngineeringModeOrRelease()) { if (!buildHelper.isEngineeringModeOrRelease()) {
val notification = Notification(Notification.NOT_ENG_MODE_OR_RELEASE, resourceHelper.gs(R.string.not_eng_mode_or_release), Notification.URGENT) val notification = Notification(Notification.NOT_ENG_MODE_OR_RELEASE, resourceHelper.gs(R.string.not_eng_mode_or_release), Notification.URGENT)
rxBus.send(EventNewNotification(notification)) rxBus.send(EventNewNotification(notification))
callback?.result(PumpEnactResult(injector).success(false).enacted(false).comment(resourceHelper.gs(R.string.not_eng_mode_or_release)))?.run() callback?.result(PumpEnactResult(injector).success(false).enacted(false).comment(resourceHelper.gs(R.string.not_eng_mode_or_release)))?.run()

View file

@ -1,102 +0,0 @@
package info.nightscout.androidaps.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
/**
* Created by mike on 22.02.2017.
*/
public class HardLimits {
private static Logger log = StacktraceLoggerWrapper.getLogger(HardLimits.class);
final static int CHILD = 0;
final static int TEENAGE = 1;
final static int ADULT = 2;
final static int RESISTANTADULT = 3;
final static double[] MAXBOLUS = {5d, 10d, 17d, 25d};
// Very Hard Limits Ranges
// First value is the Lowest and second value is the Highest a Limit can define
public static final int[] VERY_HARD_LIMIT_MIN_BG = {72, 180};
public static final int[] VERY_HARD_LIMIT_MAX_BG = {90, 270};
public static final int[] VERY_HARD_LIMIT_TARGET_BG = {80, 200};
// Very Hard Limits Ranges for Temp Targets
public static final int[] VERY_HARD_LIMIT_TEMP_MIN_BG = {72, 180};
public static final int[] VERY_HARD_LIMIT_TEMP_MAX_BG = {72, 270};
public static final int[] VERY_HARD_LIMIT_TEMP_TARGET_BG = {72, 200};
public static final double MINDIA = 2;
public static final double MAXDIA = 7;
public static final double MINIC = 2;
public static final double MAXIC = 100;
public static final double MINISF = 2; // mgdl
public static final double MAXISF = 720; // mgdl
public static final double[] MAXIOB_AMA = {3, 5, 7, 12};
public static final double[] MAXIOB_SMB = {3, 7, 12, 25};
public static final double[] MAXBASAL = {2, 5, 10, 12};
private static int loadAge() {
String sp_age = SP.getString(R.string.key_age, "");
int age;
if (sp_age.equals(MainApp.gs(R.string.key_child)))
age = CHILD;
else if (sp_age.equals(MainApp.gs(R.string.key_teenage)))
age = TEENAGE;
else if (sp_age.equals(MainApp.gs(R.string.key_adult)))
age = ADULT;
else if (sp_age.equals(MainApp.gs(R.string.key_resistantadult)))
age = RESISTANTADULT;
else age = ADULT;
return age;
}
public static double maxBolus() {
return MAXBOLUS[loadAge()];
}
public static double maxIobAMA() {
return MAXIOB_AMA[loadAge()];
}
public static double maxIobSMB() {
return MAXIOB_SMB[loadAge()];
}
public static double maxBasal() {
return MAXBASAL[loadAge()];
}
// safety checks
public static boolean checkOnlyHardLimits(Double value, String valueName, double lowLimit, double highLimit) {
return value.equals(verifyHardLimits(value, valueName, lowLimit, highLimit));
}
public static Double verifyHardLimits(Double value, String valueName, double lowLimit, double highLimit) {
Double newvalue = value;
if (newvalue < lowLimit || newvalue > highLimit) {
newvalue = Math.max(newvalue, lowLimit);
newvalue = Math.min(newvalue, highLimit);
String msg = String.format(MainApp.gs(R.string.valueoutofrange), valueName);
msg += ".\n";
msg += String.format(MainApp.gs(R.string.valuelimitedto), value, newvalue);
log.error(msg);
NSUpload.uploadError(msg);
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), msg, R.raw.error);
}
return newvalue;
}
}

View file

@ -0,0 +1,88 @@
package info.nightscout.androidaps.utils
import android.content.Context
import info.nightscout.androidaps.R
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class HardLimits @Inject constructor(
val aapsLogger: AAPSLogger,
val sp: SP,
val resourceHelper: ResourceHelper,
val context: Context
) {
val CHILD = 0
val TEENAGE = 1
val ADULT = 2
val RESISTANTADULT = 3
val MAXBOLUS = doubleArrayOf(5.0, 10.0, 17.0, 25.0)
// Very Hard Limits Ranges
// First value is the Lowest and second value is the Highest a Limit can define
val VERY_HARD_LIMIT_MIN_BG = intArrayOf(72, 180)
val VERY_HARD_LIMIT_MAX_BG = intArrayOf(90, 270)
val VERY_HARD_LIMIT_TARGET_BG = intArrayOf(80, 200)
// Very Hard Limits Ranges for Temp Targets
val VERY_HARD_LIMIT_TEMP_MIN_BG = intArrayOf(72, 180)
val VERY_HARD_LIMIT_TEMP_MAX_BG = intArrayOf(72, 270)
val VERY_HARD_LIMIT_TEMP_TARGET_BG = intArrayOf(72, 200)
val MINDIA = 2.0
val MAXDIA = 7.0
val MINIC = 2.0
val MAXIC = 100.0
val MINISF = 2.0 // mgdl
val MAXISF = 720.0 // mgdl
val MAXIOB_AMA = doubleArrayOf(3.0, 5.0, 7.0, 12.0)
val MAXIOB_SMB = doubleArrayOf(3.0, 7.0, 12.0, 25.0)
val MAXBASAL = doubleArrayOf(2.0, 5.0, 10.0, 12.0)
private fun loadAge(): Int {
val sp_age = sp.getString(R.string.key_age, "")
val age: Int
age = if (sp_age == resourceHelper.gs(R.string.key_child)) CHILD else if (sp_age == resourceHelper.gs(R.string.key_teenage)) TEENAGE else if (sp_age == resourceHelper.gs(R.string.key_adult)) ADULT else if (sp_age == resourceHelper.gs(R.string.key_resistantadult)) RESISTANTADULT else ADULT
return age
}
fun maxBolus(): Double {
return MAXBOLUS[loadAge()]
}
fun maxIobAMA(): Double {
return MAXIOB_AMA[loadAge()]
}
fun maxIobSMB(): Double {
return MAXIOB_SMB[loadAge()]
}
fun maxBasal(): Double {
return MAXBASAL[loadAge()]
}
// safety checks
fun checkOnlyHardLimits(value: Double, valueName: String?, lowLimit: Double, highLimit: Double): Boolean {
return value == verifyHardLimits(value, valueName, lowLimit, highLimit)
}
fun verifyHardLimits(value: Double, valueName: String?, lowLimit: Double, highLimit: Double): Double {
var newvalue = value
if (newvalue < lowLimit || newvalue > highLimit) {
newvalue = Math.max(newvalue, lowLimit)
newvalue = Math.min(newvalue, highLimit)
var msg = String.format(resourceHelper.gs(R.string.valueoutofrange), valueName)
msg += ".\n"
msg += String.format(resourceHelper.gs(R.string.valuelimitedto), value, newvalue)
aapsLogger.error(msg)
NSUpload.uploadError(msg)
ToastUtils.showToastInUiThread(context, msg, R.raw.error)
}
return newvalue
}
}

View file

@ -6,10 +6,12 @@ import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.data.ProfileStore import info.nightscout.androidaps.data.ProfileStore
import org.json.JSONObject import org.json.JSONObject
import org.junit.Before
import org.junit.Rule import org.junit.Rule
import org.mockito.Mockito import org.mockito.Mockito
import org.mockito.junit.MockitoJUnit import org.mockito.junit.MockitoJUnit
import org.mockito.junit.MockitoRule import org.mockito.junit.MockitoRule
import java.util.*
open class TestBase { open class TestBase {
val validProfileJSON = "{\"dia\":\"3\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"30\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"100\"},{\"time\":\"2:00\",\"value\":\"110\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"4\"}],\"target_high\":[{\"time\":\"00:00\",\"value\":\"5\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}" val validProfileJSON = "{\"dia\":\"3\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"30\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"100\"},{\"time\":\"2:00\",\"value\":\"110\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"4\"}],\"target_high\":[{\"time\":\"00:00\",\"value\":\"5\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}"
@ -30,6 +32,11 @@ open class TestBase {
@get:Rule @get:Rule
val mockitoRule: MockitoRule = MockitoJUnit.rule() val mockitoRule: MockitoRule = MockitoJUnit.rule()
@Before
fun setupLocale() {
Locale.setDefault(Locale.ENGLISH)
}
// Workaround for Kotlin nullability. // Workaround for Kotlin nullability.
// https://medium.com/@elye.project/befriending-kotlin-and-mockito-1c2e7b0ef791 // https://medium.com/@elye.project/befriending-kotlin-and-mockito-1c2e7b0ef791
// https://stackoverflow.com/questions/30305217/is-it-possible-to-use-mockito-in-kotlin // https://stackoverflow.com/questions/30305217/is-it-possible-to-use-mockito-in-kotlin

View file

@ -1,71 +0,0 @@
package info.nightscout.androidaps.interfaces;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import info.AAPSMocker;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.utils.SP;
/**
* Created by mike on 19.03.2018.
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({MainApp.class, SP.class, L.class})
public class ConstraintTest {
@Test
public void doTests() {
Constraint<Boolean> b = new Constraint<>(true);
Assert.assertEquals(Boolean.TRUE, b.value());
Assert.assertEquals("", b.getReasons());
Assert.assertEquals("", b.getMostLimitedReasons());
b.set(false);
Assert.assertEquals(Boolean.FALSE, b.value());
Assert.assertEquals("", b.getReasons());
Assert.assertEquals("", b.getMostLimitedReasons());
b.set(true, "Set true", this);
Assert.assertEquals(Boolean.TRUE, b.value());
Assert.assertEquals("ConstraintTest: Set true", b.getReasons());
Assert.assertEquals("ConstraintTest: Set true", b.getMostLimitedReasons());
b.set(false, "Set false", this);
Assert.assertEquals(Boolean.FALSE, b.value());
Assert.assertEquals("ConstraintTest: Set true\nConstraintTest: Set false", b.getReasons());
Assert.assertEquals("ConstraintTest: Set true\nConstraintTest: Set false", b.getMostLimitedReasons());
Constraint<Double> d = new Constraint<>(10d);
d.set(5d, "Set 5d", this);
Assert.assertEquals(5d, d.value());
Assert.assertEquals("ConstraintTest: Set 5d", d.getReasons());
Assert.assertEquals("ConstraintTest: Set 5d", d.getMostLimitedReasons());
d.setIfSmaller(6d, "Set 6d", this);
Assert.assertEquals(5d, d.value());
Assert.assertEquals("ConstraintTest: Set 5d\nConstraintTest: Set 6d", d.getReasons());
Assert.assertEquals("ConstraintTest: Set 5d", d.getMostLimitedReasons());
d.setIfSmaller(4d, "Set 4d", this);
Assert.assertEquals(4d, d.value());
Assert.assertEquals("ConstraintTest: Set 5d\nConstraintTest: Set 6d\nConstraintTest: Set 4d", d.getReasons());
Assert.assertEquals("ConstraintTest: Set 4d", d.getMostLimitedReasons());
Assert.assertEquals(10d, d.originalValue());
d.setIfDifferent(7d, "Set 7d", this);
Assert.assertEquals(7d, d.value());
Assert.assertEquals("ConstraintTest: Set 5d\nConstraintTest: Set 6d\nConstraintTest: Set 4d\nConstraintTest: Set 7d", d.getReasons());
Assert.assertEquals("ConstraintTest: Set 4d\nConstraintTest: Set 7d", d.getMostLimitedReasons());
Assert.assertEquals(10d, d.originalValue());
}
@Before
public void prepareMock() {
AAPSMocker.mockMainApp();
AAPSMocker.mockApplicationContext();
AAPSMocker.mockSP();
AAPSMocker.mockL();
}
}

View file

@ -0,0 +1,65 @@
package info.nightscout.androidaps.interfaces
import info.TestBase
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
/**
* Created by mike on 19.03.2018.
*/
@RunWith(PowerMockRunner::class)
@PrepareForTest(MainApp::class, SP::class)
class ConstraintTest : TestBase() {
@Mock lateinit var aapsLogger: AAPSLogger
@Test fun doTests() {
val b = Constraint(true)
Assert.assertEquals(true, b.value())
Assert.assertEquals("", b.getReasons(aapsLogger))
Assert.assertEquals("", b.getMostLimitedReasons(aapsLogger))
b.set(aapsLogger, false)
Assert.assertEquals(false, b.value())
Assert.assertEquals("", b.getReasons(aapsLogger))
Assert.assertEquals("", b.getMostLimitedReasons(aapsLogger))
b.set(aapsLogger, true, "Set true", this)
Assert.assertEquals(true, b.value())
Assert.assertEquals("ConstraintTest: Set true", b.getReasons(aapsLogger))
Assert.assertEquals("ConstraintTest: Set true", b.getMostLimitedReasons(aapsLogger))
b.set(aapsLogger, false, "Set false", this)
Assert.assertEquals(false, b.value())
Assert.assertEquals("ConstraintTest: Set true\nConstraintTest: Set false", b.getReasons(aapsLogger))
Assert.assertEquals("ConstraintTest: Set true\nConstraintTest: Set false", b.getMostLimitedReasons(aapsLogger))
val d = Constraint(10.0)
d.set(aapsLogger, 5.0, "Set 5d", this)
Assert.assertEquals(5.0, d.value(), 0.01)
Assert.assertEquals("ConstraintTest: Set 5d", d.getReasons(aapsLogger))
Assert.assertEquals("ConstraintTest: Set 5d", d.getMostLimitedReasons(aapsLogger))
d.setIfSmaller(aapsLogger, 6.0, "Set 6d", this)
Assert.assertEquals(5.0, d.value(), 0.01)
Assert.assertEquals("ConstraintTest: Set 5d\nConstraintTest: Set 6d", d.getReasons(aapsLogger))
Assert.assertEquals("ConstraintTest: Set 5d", d.getMostLimitedReasons(aapsLogger))
d.setIfSmaller(aapsLogger, 4.0, "Set 4d", this)
Assert.assertEquals(4.0, d.value(), 0.01)
Assert.assertEquals("ConstraintTest: Set 5d\nConstraintTest: Set 6d\nConstraintTest: Set 4d", d.getReasons(aapsLogger))
Assert.assertEquals("ConstraintTest: Set 4d", d.getMostLimitedReasons(aapsLogger))
Assert.assertEquals(10.0, d.originalValue(), 0.01)
d.setIfDifferent(aapsLogger, 7.0, "Set 7d", this)
Assert.assertEquals(7.0, d.value(), 0.01)
Assert.assertEquals("ConstraintTest: Set 5d\nConstraintTest: Set 6d\nConstraintTest: Set 4d\nConstraintTest: Set 7d", d.getReasons(aapsLogger))
Assert.assertEquals("ConstraintTest: Set 4d\nConstraintTest: Set 7d", d.getMostLimitedReasons(aapsLogger))
Assert.assertEquals(10.0, d.originalValue(), 0.01)
}
@Before
fun prepareMock() {
}
}

View file

@ -1,314 +0,0 @@
package info.nightscout.androidaps.interfaces;
import android.content.Context;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.ArrayList;
import info.AAPSMocker;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker;
import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin;
import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAPlugin;
import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin;
import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin;
import info.nightscout.androidaps.plugins.pump.combo.ComboPlugin;
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin;
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump;
import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin;
import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin;
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin;
import info.nightscout.androidaps.plugins.source.GlimpPlugin;
import info.nightscout.androidaps.plugins.treatments.TreatmentService;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.SP;
import static org.mockito.Mockito.when;
/**
* Created by mike on 18.03.2018.
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({MainApp.class, ConfigBuilderPlugin.class, FabricPrivacy.class, SP.class, Context.class, OpenAPSMAPlugin.class, OpenAPSAMAPlugin.class, OpenAPSSMBPlugin.class, TreatmentsPlugin.class, TreatmentService.class})
public class ConstraintsCheckerTest {
VirtualPumpPlugin pump = new VirtualPumpPlugin();
ConstraintChecker constraintChecker;
SafetyPlugin safetyPlugin;
ObjectivesPlugin objectivesPlugin;
ComboPlugin comboPlugin;
DanaRPlugin danaRPlugin;
DanaRSPlugin danaRSPlugin;
LocalInsightPlugin insightPlugin;
OpenAPSSMBPlugin openAPSSMBPlugin;
boolean notificationSent = false;
public ConstraintsCheckerTest() {
}
@Test
public void isLoopInvokationAllowedTest() {
comboPlugin.setPluginEnabled(PluginType.PUMP, true);
comboPlugin.setValidBasalRateProfileSelectedOnPump(false);
Constraint<Boolean> c = constraintChecker.isLoopInvocationAllowed();
Assert.assertEquals(true, c.getReasonList().size() == 2); // Combo & Objectives
Assert.assertEquals(true, c.getMostLimitedReasonList().size() == 2); // Combo & Objectives
Assert.assertEquals(Boolean.FALSE, c.value());
}
@Test
public void isClosedLoopAllowedTest() {
when(SP.getString(R.string.key_aps_mode, "open")).thenReturn("closed");
objectivesPlugin.getObjectives().get(ObjectivesPlugin.INSTANCE.getMAXIOB_ZERO_CL_OBJECTIVE()).setStartedOn(0);
Constraint<Boolean> c = constraintChecker.isClosedLoopAllowed();
Assert.assertEquals(true, c.getReasonList().size() == 2); // Safety & Objectives
Assert.assertEquals(true, c.getMostLimitedReasonList().size() == 2); // Safety & Objectives
Assert.assertEquals(Boolean.FALSE, c.value());
when(SP.getString(R.string.key_aps_mode, "open")).thenReturn("open");
c = constraintChecker.isClosedLoopAllowed();
Assert.assertEquals(true, c.getReasonList().size() == 3); // 2x Safety & Objectives
Assert.assertEquals(true, c.getMostLimitedReasonList().size() == 3); // 2x Safety & Objectives
Assert.assertEquals(Boolean.FALSE, c.value());
}
@Test
public void isAutosensModeEnabledTest() {
objectivesPlugin.getObjectives().get(ObjectivesPlugin.INSTANCE.getAUTOSENS_OBJECTIVE()).setStartedOn(0);
when(SP.getBoolean(R.string.key_openapsama_useautosens, false)).thenReturn(false);
Constraint<Boolean> c = constraintChecker.isAutosensModeEnabled();
Assert.assertEquals(true, c.getReasonList().size() == 2); // Safety & Objectives
Assert.assertEquals(true, c.getMostLimitedReasonList().size() == 2); // Safety & Objectives
Assert.assertEquals(Boolean.FALSE, c.value());
}
@Test
public void isAMAModeEnabledTest() {
objectivesPlugin.getObjectives().get(ObjectivesPlugin.INSTANCE.getAMA_OBJECTIVE()).setStartedOn(0);
Constraint<Boolean> c = constraintChecker.isAMAModeEnabled();
Assert.assertEquals(true, c.getReasonList().size() == 1); // Objectives
Assert.assertEquals(true, c.getMostLimitedReasonList().size() == 1); // Objectives
Assert.assertEquals(Boolean.FALSE, c.value());
}
@Test
public void isAdvancedFilteringEnabledTest() {
when(ConfigBuilderPlugin.getPlugin().getActiveBgSource()).thenReturn(GlimpPlugin.getPlugin());
Constraint<Boolean> c = constraintChecker.isAdvancedFilteringEnabled();
Assert.assertEquals(true, c.getReasonList().size() == 1); // Safety
Assert.assertEquals(true, c.getMostLimitedReasonList().size() == 1); // Safety
Assert.assertEquals(Boolean.FALSE, c.value());
}
@Test
public void isSuperBolusEnabledTest() throws Exception {
OpenAPSSMBPlugin.getPlugin().setPluginEnabled(PluginType.APS, true);
Constraint<Boolean> c = constraintChecker.isSuperBolusEnabled();
Assert.assertEquals(Boolean.FALSE, c.value()); // SMB should limit
}
@Test
public void isSMBModeEnabledTest() throws Exception {
objectivesPlugin.getObjectives().get(ObjectivesPlugin.INSTANCE.getSMB_OBJECTIVE()).setStartedOn(0);
when(SP.getBoolean(R.string.key_use_smb, false)).thenReturn(false);
when(ConstraintChecker.getInstance().isClosedLoopAllowed()).thenReturn(new Constraint<>(true));
Constraint<Boolean> c = constraintChecker.isSMBModeEnabled();
Assert.assertEquals(true, c.getReasonList().size() == 2); // Safety & Objectives
Assert.assertEquals(true, c.getMostLimitedReasonList().size() == 2); // Safety & Objectives
Assert.assertEquals(Boolean.FALSE, c.value());
}
// applyBasalConstraints tests
@Test
public void basalRateShouldBeLimited() throws Exception {
// DanaR, RS
danaRPlugin.setPluginEnabled(PluginType.PUMP, true);
danaRSPlugin.setPluginEnabled(PluginType.PUMP, true);
DanaRPump.getInstance().maxBasal = 0.8d;
// Insight
// insightPlugin.setPluginEnabled(PluginType.PUMP, true);
// StatusTaskRunner.Result result = new StatusTaskRunner.Result();
// result.maximumBasalAmount = 1.1d;
// insightPlugin.setStatusResult(result);
// No limit by default
when(SP.getDouble(R.string.key_openapsma_max_basal, 1d)).thenReturn(1d);
when(SP.getDouble(R.string.key_openapsama_current_basal_safety_multiplier, 4d)).thenReturn(4d);
when(SP.getDouble(R.string.key_openapsama_max_daily_safety_multiplier, 3d)).thenReturn(3d);
when(SP.getString(R.string.key_age, "")).thenReturn("child");
// Apply all limits
Constraint<Double> d = constraintChecker.getMaxBasalAllowed(AAPSMocker.getValidProfile());
Assert.assertEquals(0.8d, d.value());
Assert.assertEquals(6, d.getReasonList().size());
Assert.assertEquals("DanaR: Limiting basal rate to 0.80 U/h because of pump limit", d.getMostLimitedReasons());
}
@Test
public void percentBasalRateShouldBeLimited() throws Exception {
// DanaR, RS
danaRPlugin.setPluginEnabled(PluginType.PUMP, true);
danaRSPlugin.setPluginEnabled(PluginType.PUMP, true);
DanaRPump.getInstance().maxBasal = 0.8d;
// Insight
// insightPlugin.setPluginEnabled(PluginType.PUMP, true);
// StatusTaskRunner.Result result = new StatusTaskRunner.Result();
// result.maximumBasalAmount = 1.1d;
// insightPlugin.setStatusResult(result);
// No limit by default
when(SP.getDouble(R.string.key_openapsma_max_basal, 1d)).thenReturn(1d);
when(SP.getDouble(R.string.key_openapsama_current_basal_safety_multiplier, 4d)).thenReturn(4d);
when(SP.getDouble(R.string.key_openapsama_max_daily_safety_multiplier, 3d)).thenReturn(3d);
when(SP.getString(R.string.key_age, "")).thenReturn("child");
// Apply all limits
Constraint<Integer> i = constraintChecker.getMaxBasalPercentAllowed(AAPSMocker.getValidProfile());
Assert.assertEquals((Integer) 100, i.value());
Assert.assertEquals(8, i.getReasonList().size()); // 6x Safety & RS & R
Assert.assertEquals("Safety: Limiting percent rate to 100% because of pump limit", i.getMostLimitedReasons());
}
// applyBolusConstraints tests
@Test
public void bolusAmountShouldBeLimited() throws Exception {
// DanaR, RS
danaRPlugin.setPluginEnabled(PluginType.PUMP, true);
danaRSPlugin.setPluginEnabled(PluginType.PUMP, true);
DanaRPump.getInstance().maxBolus = 6d;
// Insight
// insightPlugin.setPluginEnabled(PluginType.PUMP, true);
// StatusTaskRunner.Result result = new StatusTaskRunner.Result();
// result.maximumBolusAmount = 7d;
// insightPlugin.setStatusResult(result);
// No limit by default
when(SP.getDouble(R.string.key_treatmentssafety_maxbolus, 3d)).thenReturn(3d);
when(SP.getString(R.string.key_age, "")).thenReturn("child");
// Apply all limits
Constraint<Double> d = constraintChecker.getMaxBolusAllowed();
Assert.assertEquals(3d, d.value());
Assert.assertEquals(4, d.getReasonList().size()); // 2x Safety & RS & R
Assert.assertEquals("Safety: Limiting bolus to 3.0 U because of max value in preferences", d.getMostLimitedReasons());
}
// applyCarbsConstraints tests
@Test
public void carbsAmountShouldBeLimited() throws Exception {
// No limit by default
when(SP.getInt(R.string.key_treatmentssafety_maxcarbs, 48)).thenReturn(48);
// Apply all limits
Constraint<Integer> i = constraintChecker.getMaxCarbsAllowed();
Assert.assertEquals((Integer) 48, i.value());
Assert.assertEquals(true, i.getReasonList().size() == 1);
Assert.assertEquals("Safety: Limiting carbs to 48 g because of max value in preferences", i.getMostLimitedReasons());
}
// applyMaxIOBConstraints tests
@Test
public void iobAMAShouldBeLimited() {
// No limit by default
when(SP.getDouble(R.string.key_openapsma_max_iob, 1.5d)).thenReturn(1.5d);
when(SP.getString(R.string.key_age, "")).thenReturn("teenage");
OpenAPSAMAPlugin.getPlugin().setPluginEnabled(PluginType.APS, true);
OpenAPSMAPlugin.getPlugin().setPluginEnabled(PluginType.APS, false);
OpenAPSSMBPlugin.getPlugin().setPluginEnabled(PluginType.APS, false);
// Apply all limits
Constraint<Double> d = constraintChecker.getMaxIOBAllowed();
Assert.assertEquals(1.5d, d.value());
Assert.assertEquals(d.getReasonList().toString(), 2, d.getReasonList().size());
Assert.assertEquals("Safety: Limiting IOB to 1.5 U because of max value in preferences", d.getMostLimitedReasons());
}
@Test
public void iobSMBShouldBeLimited() {
// No limit by default
when(SP.getDouble(R.string.key_openapssmb_max_iob, 3d)).thenReturn(3d);
when(SP.getString(R.string.key_age, "")).thenReturn("teenage");
OpenAPSSMBPlugin.getPlugin().setPluginEnabled(PluginType.APS, true);
OpenAPSAMAPlugin.getPlugin().setPluginEnabled(PluginType.APS, false);
OpenAPSMAPlugin.getPlugin().setPluginEnabled(PluginType.APS, false);
// Apply all limits
Constraint<Double> d = constraintChecker.getMaxIOBAllowed();
Assert.assertEquals(3d, d.value());
Assert.assertEquals(d.getReasonList().toString(), 2, d.getReasonList().size());
Assert.assertEquals("Safety: Limiting IOB to 3.0 U because of max value in preferences", d.getMostLimitedReasons());
}
@Before
public void prepareMock() throws Exception {
PowerMockito.mockStatic(FabricPrivacy.class);
MainApp mainApp = AAPSMocker.mockMainApp();
AAPSMocker.mockConfigBuilder();
AAPSMocker.mockConstraintsChecker();
AAPSMocker.mockApplicationContext();
AAPSMocker.mockStrings();
AAPSMocker.mockSP();
AAPSMocker.mockCommandQueue();
AAPSMocker.mockTreatmentService();
AAPSMocker.mockTreatmentPlugin();
when(mainApp.getPackageName()).thenReturn("info.nightscout.androidaps");
// RS constructor
when(SP.getString(R.string.key_danars_address, "")).thenReturn("");
//SafetyPlugin
when(ConfigBuilderPlugin.getPlugin().getActivePump()).thenReturn(pump);
constraintChecker = ConstraintChecker.getInstance();
safetyPlugin = SafetyPlugin.getPlugin();
objectivesPlugin = ObjectivesPlugin.INSTANCE;
comboPlugin = ComboPlugin.getPlugin();
danaRPlugin = DanaRPlugin.getPlugin();
danaRSPlugin = DanaRSPlugin.getPlugin();
insightPlugin = LocalInsightPlugin.getPlugin();
openAPSSMBPlugin = OpenAPSSMBPlugin.getPlugin();
ArrayList<PluginBase> constraintsPluginsList = new ArrayList<>();
constraintsPluginsList.add(safetyPlugin);
constraintsPluginsList.add(objectivesPlugin);
constraintsPluginsList.add(comboPlugin);
constraintsPluginsList.add(danaRPlugin);
constraintsPluginsList.add(danaRSPlugin);
constraintsPluginsList.add(insightPlugin);
constraintsPluginsList.add(openAPSSMBPlugin);
when(mainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class)).thenReturn(constraintsPluginsList);
}
}

View file

@ -0,0 +1,354 @@
package info.nightscout.androidaps.interfaces
import android.content.Context
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.TestBase
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin
import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAPlugin
import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction
import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin
import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective
import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
import info.nightscout.androidaps.plugins.pump.combo.ComboPlugin
import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump
import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin
import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin
import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin
import info.nightscout.androidaps.plugins.source.GlimpPlugin
import info.nightscout.androidaps.plugins.treatments.TreatmentService
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.HardLimits
import info.nightscout.androidaps.utils.build.BuildHelper
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
import java.util.*
/**
* Created by mike on 18.03.2018.
*/
@RunWith(PowerMockRunner::class)
@PrepareForTest(MainApp::class, ConfigBuilderPlugin::class, ConstraintChecker::class, SP::class, Context::class, OpenAPSMAPlugin::class, OpenAPSAMAPlugin::class, OpenAPSSMBPlugin::class, TreatmentsPlugin::class, TreatmentService::class, VirtualPumpPlugin::class, DetailedBolusInfoStorage::class, GlimpPlugin::class)
class ConstraintsCheckerTest : TestBase() {
@Mock lateinit var aapsLogger: AAPSLogger
@Mock lateinit var resourceHelper: ResourceHelper
@Mock lateinit var activePlugin: ActivePluginProvider
@Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin
@Mock lateinit var sp: SP
@Mock lateinit var configBuilderPlugin: ConfigBuilderPlugin
@Mock lateinit var profileFunction: ProfileFunction
@Mock lateinit var treatmentsPlugin: TreatmentsPlugin
@Mock lateinit var commandQueue: CommandQueueProvider
@Mock lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage
@Mock lateinit var context: Context
@Mock lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin
@Mock lateinit var glimpPlugin: GlimpPlugin
@Mock lateinit var sensitivityOref1Plugin: SensitivityOref1Plugin
@Mock lateinit var mainApp: MainApp
val rxBus = RxBusWrapper()
private var buildHelper = BuildHelper()
lateinit var danaRPump: DanaRPump
lateinit var constraintChecker: ConstraintChecker
private lateinit var safetyPlugin: SafetyPlugin
private lateinit var objectivesPlugin: ObjectivesPlugin
private lateinit var comboPlugin: ComboPlugin
private lateinit var danaRPlugin: DanaRPlugin
private lateinit var danaRSPlugin: DanaRSPlugin
private lateinit var insightPlugin: LocalInsightPlugin
private lateinit var openAPSSMBPlugin: OpenAPSSMBPlugin
private lateinit var openAPSAMAPlugin: OpenAPSAMAPlugin
private lateinit var openAPSMAPlugin: OpenAPSMAPlugin
private lateinit var hardLimits: HardLimits
val injector = HasAndroidInjector {
AndroidInjector {
if (it is Objective) {
it.sp = sp
}
}
}
@Before
fun prepareMock() {
`when`(resourceHelper.gs(R.string.closed_loop_disabled_on_dev_branch)).thenReturn("Running dev version. Closed loop is disabled.")
`when`(resourceHelper.gs(R.string.closedmodedisabledinpreferences)).thenReturn("Closed loop mode disabled in preferences")
`when`(resourceHelper.gs(R.string.objectivenotstarted)).thenReturn("Objective %d not started")
`when`(resourceHelper.gs(R.string.novalidbasalrate)).thenReturn("No valid basal rate read from pump")
`when`(resourceHelper.gs(R.string.autosensdisabledinpreferences)).thenReturn("Autosens disabled in preferences")
`when`(resourceHelper.gs(R.string.smbdisabledinpreferences)).thenReturn("SMB disabled in preferences")
`when`(resourceHelper.gs(R.string.pumplimit)).thenReturn("pump limit")
`when`(resourceHelper.gs(R.string.itmustbepositivevalue)).thenReturn("it must be positive value")
`when`(resourceHelper.gs(R.string.maxvalueinpreferences)).thenReturn("max value in preferences")
`when`(resourceHelper.gs(R.string.maxbasalmultiplier)).thenReturn("max basal multiplier")
`when`(resourceHelper.gs(R.string.maxdailybasalmultiplier)).thenReturn("max daily basal multiplier")
`when`(resourceHelper.gs(R.string.pumplimit)).thenReturn("pump limit")
`when`(resourceHelper.gs(R.string.limitingbolus)).thenReturn("Limiting bolus to %.1f U because of %s")
`when`(resourceHelper.gs(R.string.hardlimit)).thenReturn("hard limit")
`when`(resourceHelper.gs(R.string.key_child)).thenReturn("child")
`when`(resourceHelper.gs(R.string.limitingcarbs)).thenReturn("Limiting carbs to %d g because of %s")
`when`(resourceHelper.gs(R.string.limitingiob)).thenReturn("Limiting IOB to %.1f U because of %s")
`when`(resourceHelper.gs(R.string.limitingbasalratio)).thenReturn("Limiting max basal rate to %1\$.2f U/h because of %2\$s")
`when`(resourceHelper.gs(R.string.limitingpercentrate)).thenReturn("Limiting max percent rate to %1\$d%% because of %2\$s")
// PowerMockito.mockStatic(FabricPrivacy::class.java)
// val mainApp = AAPSMocker.mockMainApp()
// `when`(mainApp.packageName).thenReturn("info.nightscout.androidaps")
// RS constructor
`when`(sp.getString(R.string.key_danars_address, "")).thenReturn("")
//SafetyPlugin
`when`(activePlugin.activePump).thenReturn(virtualPumpPlugin)
constraintChecker = ConstraintChecker(mainApp)
danaRPump = DanaRPump(aapsLogger, sp, injector)
hardLimits = HardLimits(aapsLogger, sp, resourceHelper, context)
objectivesPlugin = ObjectivesPlugin(injector, aapsLogger, resourceHelper, configBuilderPlugin, sp)
comboPlugin = ComboPlugin(injector, aapsLogger, rxBus, resourceHelper, constraintChecker, profileFunction, treatmentsPlugin, sp, commandQueue)
danaRPlugin = DanaRPlugin(injector, aapsLogger, rxBus, context, resourceHelper, constraintChecker, treatmentsPlugin, sp, commandQueue, danaRPump)
danaRSPlugin = DanaRSPlugin(injector, aapsLogger, rxBus, context, resourceHelper, constraintChecker, profileFunction, treatmentsPlugin, sp, commandQueue, danaRPump, detailedBolusInfoStorage)
insightPlugin = LocalInsightPlugin(injector, aapsLogger, rxBus, resourceHelper, constraintChecker, treatmentsPlugin, sp, commandQueue)
openAPSSMBPlugin = OpenAPSSMBPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, treatmentsPlugin, iobCobCalculatorPlugin, hardLimits)
openAPSAMAPlugin = OpenAPSAMAPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, treatmentsPlugin, iobCobCalculatorPlugin, hardLimits)
openAPSMAPlugin = OpenAPSMAPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, treatmentsPlugin, iobCobCalculatorPlugin, hardLimits)
safetyPlugin = SafetyPlugin(injector, aapsLogger, resourceHelper, sp, rxBus, constraintChecker, openAPSAMAPlugin, openAPSMAPlugin, openAPSSMBPlugin, sensitivityOref1Plugin, activePlugin, hardLimits, buildHelper, treatmentsPlugin)
val constraintsPluginsList = ArrayList<PluginBase?>()
constraintsPluginsList.add(safetyPlugin)
constraintsPluginsList.add(objectivesPlugin)
constraintsPluginsList.add(comboPlugin)
constraintsPluginsList.add(danaRPlugin)
constraintsPluginsList.add(danaRSPlugin)
constraintsPluginsList.add(insightPlugin)
constraintsPluginsList.add(openAPSSMBPlugin)
`when`(mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)).thenReturn(constraintsPluginsList)
objectivesPlugin.onStart()
}
// Combo & Objectives
@Test
fun isLoopInvocationAllowedTest() {
`when`(activePlugin.activePump).thenReturn(comboPlugin)
`when`(activePlugin.activePumpPlugin).thenReturn(comboPlugin)
comboPlugin.setPluginEnabled(PluginType.PUMP, true)
comboPlugin.setValidBasalRateProfileSelectedOnPump(false)
val c = constraintChecker.isLoopInvocationAllowed()
Assert.assertEquals(true, c.reasonList.size == 2) // Combo & Objectives
Assert.assertEquals(true, c.mostLimitedReasonList.size == 2) // Combo & Objectives
Assert.assertEquals(java.lang.Boolean.FALSE, c.value())
}
// Safety & Objectives
// 2x Safety & Objectives
@Test
fun isClosedLoopAllowedTest() {
`when`(sp.getString(R.string.key_aps_mode, "open")).thenReturn("closed")
objectivesPlugin.objectives[ObjectivesPlugin.MAXIOB_ZERO_CL_OBJECTIVE].startedOn = 0
var c: Constraint<Boolean> = constraintChecker.isClosedLoopAllowed()
Assert.assertEquals(true, c.reasonList.size == 2) // Safety & Objectives
Assert.assertEquals(true, c.mostLimitedReasonList.size == 2) // Safety & Objectives
Assert.assertEquals(false, c.value())
`when`(sp.getString(R.string.key_aps_mode, "open")).thenReturn("open")
c = constraintChecker.isClosedLoopAllowed()
Assert.assertEquals(true, c.reasonList.size == 3) // 2x Safety & Objectives
Assert.assertEquals(true, c.mostLimitedReasonList.size == 3) // 2x Safety & Objectives
Assert.assertEquals(false, c.value())
}
// Safety & Objectives
@Test
fun isAutosensModeEnabledTest() {
objectivesPlugin.objectives[ObjectivesPlugin.AUTOSENS_OBJECTIVE].startedOn = 0
`when`(sp.getBoolean(R.string.key_openapsama_useautosens, false)).thenReturn(false)
val c = constraintChecker.isAutosensModeEnabled()
Assert.assertEquals(true, c.reasonList.size == 2) // Safety & Objectives
Assert.assertEquals(true, c.mostLimitedReasonList.size == 2) // Safety & Objectives
Assert.assertEquals(java.lang.Boolean.FALSE, c.value())
}
// Objectives
@Test
fun isAMAModeEnabledTest() {
objectivesPlugin.objectives[ObjectivesPlugin.AMA_OBJECTIVE].startedOn = 0
val c = constraintChecker.isAMAModeEnabled()
Assert.assertEquals(true, c.reasonList.size == 1) // Objectives
Assert.assertEquals(true, c.mostLimitedReasonList.size == 1) // Objectives
Assert.assertEquals(java.lang.Boolean.FALSE, c.value())
}
// Safety
@Test
fun isAdvancedFilteringEnabledTest() {
`when`(activePlugin.activeBgSource).thenReturn(glimpPlugin)
val c = constraintChecker.isAdvancedFilteringEnabled()
Assert.assertEquals(true, c.reasonList.size == 1) // Safety
Assert.assertEquals(true, c.mostLimitedReasonList.size == 1) // Safety
Assert.assertEquals(false, c.value())
}
// SMB should limit
@Test
fun isSuperBolusEnabledTest() {
openAPSSMBPlugin.setPluginEnabled(PluginType.APS, true)
val c = constraintChecker.isSuperBolusEnabled()
Assert.assertEquals(java.lang.Boolean.FALSE, c.value()) // SMB should limit
}
// Safety & Objectives
@Test
fun isSMBModeEnabledTest() {
objectivesPlugin.objectives[ObjectivesPlugin.SMB_OBJECTIVE].startedOn = 0
`when`(sp.getBoolean(R.string.key_use_smb, false)).thenReturn(false)
`when`(sp.getString(R.string.key_aps_mode, "open")).thenReturn("open")
// `when`(constraintChecker.isClosedLoopAllowed()).thenReturn(Constraint(true))
val c = constraintChecker.isSMBModeEnabled()
Assert.assertEquals(true, c.reasonList.size == 3) // 2x Safety & Objectives
Assert.assertEquals(true, c.mostLimitedReasonList.size == 3) // 2x Safety & Objectives
Assert.assertEquals(false, c.value())
}
// applyBasalConstraints tests
@Test
fun basalRateShouldBeLimited() {
// DanaR, RS
danaRPlugin.setPluginEnabled(PluginType.PUMP, true)
danaRSPlugin.setPluginEnabled(PluginType.PUMP, true)
danaRPump.maxBasal = 0.8
// Insight
// insightPlugin.setPluginEnabled(PluginType.PUMP, true);
// StatusTaskRunner.Result result = new StatusTaskRunner.Result();
// result.maximumBasalAmount = 1.1d;
// insightPlugin.setStatusResult(result);
// No limit by default
`when`(sp.getDouble(R.string.key_openapsma_max_basal, 1.0)).thenReturn(1.0)
`when`(sp.getDouble(R.string.key_openapsama_current_basal_safety_multiplier, 4.0)).thenReturn(4.0)
`when`(sp.getDouble(R.string.key_openapsama_max_daily_safety_multiplier, 3.0)).thenReturn(3.0)
`when`(sp.getString(R.string.key_age, "")).thenReturn("child")
// Apply all limits
val d = constraintChecker.getMaxBasalAllowed(validProfile)
Assert.assertEquals(0.8, d.value(), 0.01)
Assert.assertEquals(6, d.reasonList.size)
Assert.assertEquals("DanaR: Limiting max basal rate to 0.80 U/h because of pump limit", d.getMostLimitedReasons(aapsLogger))
}
@Test
fun percentBasalRateShouldBeLimited() {
// DanaR, RS
danaRPlugin.setPluginEnabled(PluginType.PUMP, true)
danaRSPlugin.setPluginEnabled(PluginType.PUMP, true)
danaRPump.maxBasal = 0.8
// Insight
// insightPlugin.setPluginEnabled(PluginType.PUMP, true);
// StatusTaskRunner.Result result = new StatusTaskRunner.Result();
// result.maximumBasalAmount = 1.1d;
// insightPlugin.setStatusResult(result);
// No limit by default
`when`(sp.getDouble(R.string.key_openapsma_max_basal, 1.0)).thenReturn(1.0)
`when`(sp.getDouble(R.string.key_openapsama_current_basal_safety_multiplier, 4.0)).thenReturn(4.0)
`when`(sp.getDouble(R.string.key_openapsama_max_daily_safety_multiplier, 3.0)).thenReturn(3.0)
`when`(sp.getString(R.string.key_age, "")).thenReturn("child")
// Apply all limits
val i = constraintChecker.getMaxBasalPercentAllowed(validProfile)
Assert.assertEquals(100, i.value())
Assert.assertEquals(8, i.reasonList.size) // 6x Safety & RS & R
Assert.assertEquals("Safety: Limiting max percent rate to 100% because of pump limit", i.getMostLimitedReasons(aapsLogger))
}
// applyBolusConstraints tests
@Test
fun bolusAmountShouldBeLimited() {
// DanaR, RS
danaRPlugin.setPluginEnabled(PluginType.PUMP, true)
danaRSPlugin.setPluginEnabled(PluginType.PUMP, true)
danaRPump.maxBolus = 6.0
// Insight
// insightPlugin.setPluginEnabled(PluginType.PUMP, true);
// StatusTaskRunner.Result result = new StatusTaskRunner.Result();
// result.maximumBolusAmount = 7d;
// insightPlugin.setStatusResult(result);
// No limit by default
`when`(sp.getDouble(R.string.key_treatmentssafety_maxbolus, 3.0)).thenReturn(3.0)
`when`(sp.getString(R.string.key_age, "")).thenReturn("child")
// Apply all limits
val d = constraintChecker.getMaxBolusAllowed()
Assert.assertEquals(3.0, d.value(), 0.01)
Assert.assertEquals(4, d.reasonList.size) // 2x Safety & RS & R
Assert.assertEquals("Safety: Limiting bolus to 3.0 U because of max value in preferences", d.getMostLimitedReasons(aapsLogger))
}
// applyCarbsConstraints tests
@Test
fun carbsAmountShouldBeLimited() {
// No limit by default
`when`(sp.getInt(R.string.key_treatmentssafety_maxcarbs, 48)).thenReturn(48)
// Apply all limits
val i = constraintChecker.getMaxCarbsAllowed()
Assert.assertEquals(48, i.value())
Assert.assertEquals(true, i.reasonList.size == 1)
Assert.assertEquals("Safety: Limiting carbs to 48 g because of max value in preferences", i.getMostLimitedReasons(aapsLogger))
}
// applyMaxIOBConstraints tests
@Test
fun iobAMAShouldBeLimited() {
// No limit by default
`when`(sp.getDouble(R.string.key_openapsma_max_iob, 1.5)).thenReturn(1.5)
`when`(sp.getString(R.string.key_age, "")).thenReturn("teenage")
openAPSAMAPlugin.setPluginEnabled(PluginType.APS, true)
openAPSMAPlugin.setPluginEnabled(PluginType.APS, false)
openAPSSMBPlugin.setPluginEnabled(PluginType.APS, false)
// Apply all limits
val d = constraintChecker.getMaxIOBAllowed()
Assert.assertEquals(1.5, d.value(), 0.01)
Assert.assertEquals(d.reasonList.toString(), 2, d.reasonList.size)
Assert.assertEquals("Safety: Limiting IOB to 1.5 U because of max value in preferences", d.getMostLimitedReasons(aapsLogger))
}
@Test
fun iobSMBShouldBeLimited() {
// No limit by default
`when`(sp.getDouble(R.string.key_openapssmb_max_iob, 3.0)).thenReturn(3.0)
`when`(sp.getString(R.string.key_age, "")).thenReturn("teenage")
openAPSSMBPlugin.setPluginEnabled(PluginType.APS, true)
openAPSAMAPlugin.setPluginEnabled(PluginType.APS, false)
openAPSMAPlugin.setPluginEnabled(PluginType.APS, false)
// Apply all limits
val d = constraintChecker.getMaxIOBAllowed()
Assert.assertEquals(3.0, d.value(), 0.01)
Assert.assertEquals(d.reasonList.toString(), 2, d.reasonList.size)
Assert.assertEquals("Safety: Limiting IOB to 3.0 U because of max value in preferences", d.getMostLimitedReasons(aapsLogger))
}
}

View file

@ -1,79 +0,0 @@
package info.nightscout.androidaps.interfaces;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.modules.junit4.PowerMockRunner;
import info.nightscout.androidaps.plugins.profile.ns.NSProfileFragment;
@RunWith(PowerMockRunner.class)
public class PluginDescriptionTest {
@Test
public void mainTypeTest() {
PluginDescription pluginDescription = new PluginDescription().mainType(PluginType.PUMP);
Assert.assertEquals(PluginType.PUMP, pluginDescription.getType());
}
@Test
public void fragmentClassTest() {
PluginDescription pluginDescription = new PluginDescription().fragmentClass(NSProfileFragment.class.getName());
Assert.assertEquals(NSProfileFragment.class.getName(), pluginDescription.getFragmentClass());
}
@Test
public void alwaysEnabledTest() {
PluginDescription pluginDescription = new PluginDescription().alwaysEnabled(true);
Assert.assertEquals(true, pluginDescription.alwaysEnabled);
}
@Test
public void alwayVisibleTest() {
PluginDescription pluginDescription = new PluginDescription().alwaysVisible(true);
Assert.assertEquals(true, pluginDescription.alwaysVisible);
}
@Test
public void neverVisibleTest() {
PluginDescription pluginDescription = new PluginDescription().neverVisible(true);
Assert.assertEquals(true, pluginDescription.neverVisible);
}
@Test
public void showInListTest() {
PluginDescription pluginDescription = new PluginDescription().showInList(false);
Assert.assertEquals(false, pluginDescription.showInList);
}
@Test
public void pluginName() {
PluginDescription pluginDescription = new PluginDescription().pluginName(10);
Assert.assertEquals(10, pluginDescription.pluginName);
}
@Test
public void shortNameTest() {
PluginDescription pluginDescription = new PluginDescription().shortName(10);
Assert.assertEquals(10, pluginDescription.shortName);
}
@Test
public void preferencesIdTest() {
PluginDescription pluginDescription = new PluginDescription().preferencesId(10);
Assert.assertEquals(10, pluginDescription.preferencesId);
}
@Test
public void enableByDefault() {
PluginDescription pluginDescription = new PluginDescription().enableByDefault(true);
Assert.assertEquals(true, pluginDescription.enableByDefault);
}
@Test
public void visibleByDefault() {
PluginDescription pluginDescription = new PluginDescription().visibleByDefault(true);
Assert.assertEquals(true, pluginDescription.visibleByDefault);
}
}

View file

@ -0,0 +1,66 @@
package info.nightscout.androidaps.interfaces
import info.nightscout.androidaps.plugins.profile.ns.NSProfileFragment
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class)
class PluginDescriptionTest {
@Test fun mainTypeTest() {
val pluginDescription = PluginDescription().mainType(PluginType.PUMP)
Assert.assertEquals(PluginType.PUMP, pluginDescription.type)
}
@Test fun fragmentClassTest() {
val pluginDescription = PluginDescription().fragmentClass(NSProfileFragment::class.java.name)
Assert.assertEquals(NSProfileFragment::class.java.name, pluginDescription.getFragmentClass())
}
@Test fun alwaysEnabledTest() {
val pluginDescription = PluginDescription().alwaysEnabled(true)
Assert.assertEquals(true, pluginDescription.alwaysEnabled)
}
@Test fun alwayVisibleTest() {
val pluginDescription = PluginDescription().alwaysVisible(true)
Assert.assertEquals(true, pluginDescription.alwaysVisible)
}
@Test fun neverVisibleTest() {
val pluginDescription = PluginDescription().neverVisible(true)
Assert.assertEquals(true, pluginDescription.neverVisible)
}
@Test fun showInListTest() {
val pluginDescription = PluginDescription().showInList(false)
Assert.assertEquals(false, pluginDescription.showInList)
}
@Test fun pluginName() {
val pluginDescription = PluginDescription().pluginName(10)
Assert.assertEquals(10, pluginDescription.pluginName.toLong())
}
@Test fun shortNameTest() {
val pluginDescription = PluginDescription().shortName(10)
Assert.assertEquals(10, pluginDescription.shortName.toLong())
}
@Test fun preferencesIdTest() {
val pluginDescription = PluginDescription().preferencesId(10)
Assert.assertEquals(10, pluginDescription.preferencesId.toLong())
}
@Test fun enableByDefault() {
val pluginDescription = PluginDescription().enableByDefault(true)
Assert.assertEquals(true, pluginDescription.enableByDefault)
}
@Test fun visibleByDefault() {
val pluginDescription = PluginDescription().visibleByDefault(true)
Assert.assertEquals(true, pluginDescription.visibleByDefault)
}
}

View file

@ -1,42 +0,0 @@
package info.nightscout.androidaps.interfaces;
import org.junit.Assert;
import org.junit.Test;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpCapability;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpTempBasalType;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
/**
* Created by andy on 5/13/18.
*/
public class PumpDescritpionTest {
@Test
public void setPumpDescription() {
PumpDescription pumpDescription = new PumpDescription();
pumpDescription.setPumpDescription(PumpType.AccuChekCombo);
Assert.assertEquals(pumpDescription.bolusStep, PumpType.AccuChekCombo.getBolusSize(), 0.1d);
Assert.assertEquals(pumpDescription.basalMinimumRate, PumpType.AccuChekCombo.getBaseBasalStep(), 0.1d);
Assert.assertEquals(pumpDescription.basalStep, PumpType.AccuChekCombo.getBaseBasalStep(), 0.1d);
Assert.assertEquals(pumpDescription.extendedBolusDurationStep, PumpType.AccuChekCombo.getExtendedBolusSettings().getDurationStep(), 0.1d);
Assert.assertEquals(pumpDescription.extendedBolusMaxDuration, PumpType.AccuChekCombo.getExtendedBolusSettings().getMaxDuration(), 0.1d);
Assert.assertEquals(pumpDescription.extendedBolusStep, PumpType.AccuChekCombo.getExtendedBolusSettings().getStep(), 0.1d);
Assert.assertEquals(pumpDescription.isExtendedBolusCapable, PumpType.AccuChekCombo.getPumpCapability().hasCapability(PumpCapability.ExtendedBolus));
Assert.assertEquals(pumpDescription.isBolusCapable, PumpType.AccuChekCombo.getPumpCapability().hasCapability(PumpCapability.Bolus));
Assert.assertEquals(pumpDescription.isRefillingCapable, PumpType.AccuChekCombo.getPumpCapability().hasCapability(PumpCapability.Refill));
Assert.assertEquals(pumpDescription.isSetBasalProfileCapable, PumpType.AccuChekCombo.getPumpCapability().hasCapability(PumpCapability.BasalProfileSet));
Assert.assertEquals(pumpDescription.isTempBasalCapable, PumpType.AccuChekCombo.getPumpCapability().hasCapability(PumpCapability.TempBasal));
Assert.assertEquals(pumpDescription.maxTempPercent, PumpType.AccuChekCombo.getTbrSettings().getMaxDose(), 0.1d);
Assert.assertEquals(pumpDescription.tempPercentStep, PumpType.AccuChekCombo.getTbrSettings().getStep(), 0.1d);
Assert.assertEquals(pumpDescription.tempBasalStyle, PumpType.AccuChekCombo.getPumpTempBasalType()== PumpTempBasalType.Percent ? PumpDescription.PERCENT : PumpDescription.ABSOLUTE);
Assert.assertEquals(pumpDescription.tempDurationStep, PumpType.AccuChekCombo.getTbrSettings().getDurationStep());
Assert.assertEquals(pumpDescription.tempDurationStep15mAllowed, PumpType.AccuChekCombo.getSpecialBasalDurations().hasCapability(PumpCapability.BasalRate_Duration15minAllowed));
Assert.assertEquals(pumpDescription.tempDurationStep30mAllowed, PumpType.AccuChekCombo.getSpecialBasalDurations().hasCapability(PumpCapability.BasalRate_Duration30minAllowed));
}
}

View file

@ -0,0 +1,35 @@
package info.nightscout.androidaps.interfaces
import info.nightscout.androidaps.plugins.pump.common.defs.PumpCapability
import info.nightscout.androidaps.plugins.pump.common.defs.PumpTempBasalType
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType
import org.junit.Assert
import org.junit.Test
/**
* Created by andy on 5/13/18.
*/
class PumpDescritpionTest {
@Test fun setPumpDescription() {
val pumpDescription = PumpDescription()
pumpDescription.setPumpDescription(PumpType.AccuChekCombo)
Assert.assertEquals(pumpDescription.bolusStep, PumpType.AccuChekCombo.bolusSize, 0.1)
Assert.assertEquals(pumpDescription.basalMinimumRate, PumpType.AccuChekCombo.baseBasalStep, 0.1)
Assert.assertEquals(pumpDescription.basalStep, PumpType.AccuChekCombo.baseBasalStep, 0.1)
Assert.assertEquals(pumpDescription.extendedBolusDurationStep, PumpType.AccuChekCombo.extendedBolusSettings.durationStep.toDouble(), 0.1)
Assert.assertEquals(pumpDescription.extendedBolusMaxDuration, PumpType.AccuChekCombo.extendedBolusSettings.maxDuration.toDouble(), 0.1)
Assert.assertEquals(pumpDescription.extendedBolusStep, PumpType.AccuChekCombo.extendedBolusSettings.step, 0.1)
Assert.assertEquals(pumpDescription.isExtendedBolusCapable, PumpType.AccuChekCombo.pumpCapability.hasCapability(PumpCapability.ExtendedBolus))
Assert.assertEquals(pumpDescription.isBolusCapable, PumpType.AccuChekCombo.pumpCapability.hasCapability(PumpCapability.Bolus))
Assert.assertEquals(pumpDescription.isRefillingCapable, PumpType.AccuChekCombo.pumpCapability.hasCapability(PumpCapability.Refill))
Assert.assertEquals(pumpDescription.isSetBasalProfileCapable, PumpType.AccuChekCombo.pumpCapability.hasCapability(PumpCapability.BasalProfileSet))
Assert.assertEquals(pumpDescription.isTempBasalCapable, PumpType.AccuChekCombo.pumpCapability.hasCapability(PumpCapability.TempBasal))
Assert.assertEquals(pumpDescription.maxTempPercent.toDouble(), PumpType.AccuChekCombo.tbrSettings.maxDose, 0.1)
Assert.assertEquals(pumpDescription.tempPercentStep.toDouble(), PumpType.AccuChekCombo.tbrSettings.step, 0.1)
Assert.assertEquals(pumpDescription.tempBasalStyle, if (PumpType.AccuChekCombo.pumpTempBasalType == PumpTempBasalType.Percent) PumpDescription.PERCENT else PumpDescription.ABSOLUTE)
Assert.assertEquals(pumpDescription.tempDurationStep.toLong(), PumpType.AccuChekCombo.tbrSettings.durationStep.toLong())
Assert.assertEquals(pumpDescription.tempDurationStep15mAllowed, PumpType.AccuChekCombo.specialBasalDurations.hasCapability(PumpCapability.BasalRate_Duration15minAllowed))
Assert.assertEquals(pumpDescription.tempDurationStep30mAllowed, PumpType.AccuChekCombo.specialBasalDurations.hasCapability(PumpCapability.BasalRate_Duration30minAllowed))
}
}

View file

@ -104,7 +104,6 @@ class SmsCommunicatorPluginTest : TestBase() {
val mainApp = AAPSMocker.mockMainApp() val mainApp = AAPSMocker.mockMainApp()
`when`(mainApp.androidInjector()).thenReturn(injector.androidInjector()) `when`(mainApp.androidInjector()).thenReturn(injector.androidInjector())
Locale.setDefault(Locale.ENGLISH)
rxBus = RxBusWrapper() rxBus = RxBusWrapper()
val reading = BgReading() val reading = BgReading()
reading.value = 100.0 reading.value = 100.0

View file

@ -3,9 +3,9 @@ package info.nightscout.androidaps.plugins.pump.combo
import android.content.Context import android.content.Context
import dagger.android.AndroidInjector import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.AAPSMocker
import info.TestBase import info.TestBase
import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.Constraint
@ -25,6 +25,7 @@ import org.junit.Before
import org.junit.Test import org.junit.Test
import org.junit.runner.RunWith import org.junit.runner.RunWith
import org.mockito.Mock import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner import org.powermock.modules.junit4.PowerMockRunner
@ -39,7 +40,6 @@ class ComboPluginTest : TestBase() {
@Mock lateinit var activePlugin: ActivePluginProvider @Mock lateinit var activePlugin: ActivePluginProvider
@Mock lateinit var commandQueue: CommandQueueProvider @Mock lateinit var commandQueue: CommandQueueProvider
@Mock lateinit var treatmentsPlugin: TreatmentsPlugin @Mock lateinit var treatmentsPlugin: TreatmentsPlugin
@Mock lateinit var mainApp: MainApp
@Mock lateinit var sp: SP @Mock lateinit var sp: SP
val injector = HasAndroidInjector { val injector = HasAndroidInjector {
@ -49,7 +49,13 @@ class ComboPluginTest : TestBase() {
private lateinit var comboPlugin: ComboPlugin private lateinit var comboPlugin: ComboPlugin
@Test @Throws(Exception::class) @Before
fun prepareMocks() {
`when`(resourceHelper.gs(R.string.novalidbasalrate)).thenReturn("No valid basal rate read from pump")
comboPlugin = ComboPlugin(injector, aapsLogger, RxBusWrapper(), resourceHelper, constraintChecker, profileFunction, treatmentsPlugin, sp, commandQueue)
}
@Test
fun invalidBasalRateOnComboPumpShouldLimitLoopInvocation() { fun invalidBasalRateOnComboPumpShouldLimitLoopInvocation() {
comboPlugin.setPluginEnabled(PluginType.PUMP, true) comboPlugin.setPluginEnabled(PluginType.PUMP, true)
comboPlugin.setValidBasalRateProfileSelectedOnPump(false) comboPlugin.setValidBasalRateProfileSelectedOnPump(false)
@ -60,7 +66,7 @@ class ComboPluginTest : TestBase() {
comboPlugin.setPluginEnabled(PluginType.PUMP, false) comboPlugin.setPluginEnabled(PluginType.PUMP, false)
} }
@Test @Throws(Exception::class) @Test
fun calculateFakePumpTimestamp() { fun calculateFakePumpTimestamp() {
val now = System.currentTimeMillis() val now = System.currentTimeMillis()
val pumpTimestamp = now - now % 1000 val pumpTimestamp = now - now % 1000
@ -79,12 +85,4 @@ class ComboPluginTest : TestBase() {
val calculatedTimestamp = comboPlugin.calculateFakeBolusDate(bolus) val calculatedTimestamp = comboPlugin.calculateFakeBolusDate(bolus)
Assert.assertEquals(calculatedTimestamp, calculatedTimestamp - calculatedTimestamp % 1000) Assert.assertEquals(calculatedTimestamp, calculatedTimestamp - calculatedTimestamp % 1000)
} }
@Before @Throws(Exception::class) fun prepareMocks() {
AAPSMocker.mockMainApp()
AAPSMocker.mockConfigBuilder()
AAPSMocker.mockStrings()
AAPSMocker.mockCommandQueue()
comboPlugin = ComboPlugin(injector, aapsLogger, RxBusWrapper(), mainApp, resourceHelper, constraintChecker, profileFunction, treatmentsPlugin, sp, commandQueue)
}
} }

View file

@ -18,6 +18,7 @@ import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.queue.commands.Command import info.nightscout.androidaps.queue.commands.Command
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.ToastUtils
import info.nightscout.androidaps.utils.build.BuildHelper
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.junit.Assert import org.junit.Assert
@ -44,6 +45,9 @@ class CommandQueueTest : TestBase() {
@Mock lateinit var treatmentsPlugin: TreatmentsPlugin @Mock lateinit var treatmentsPlugin: TreatmentsPlugin
@Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin @Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin
@Mock lateinit var sp: SP @Mock lateinit var sp: SP
private val buildHelper = BuildHelper()
val rxBus = RxBusWrapper() val rxBus = RxBusWrapper()
val injector = HasAndroidInjector { val injector = HasAndroidInjector {
@ -59,7 +63,7 @@ class CommandQueueTest : TestBase() {
@Before @Before
fun prepareMock() { fun prepareMock() {
commandQueue = CommandQueue(injector, aapsLogger, rxBus, resourceHelper, constraintChecker, profileFunction, lazyActivePlugin, context, sp) commandQueue = CommandQueue(injector, aapsLogger, rxBus, resourceHelper, constraintChecker, profileFunction, lazyActivePlugin, context, sp, buildHelper)
val pumpDescription = PumpDescription() val pumpDescription = PumpDescription()
pumpDescription.basalMinimumRate = 0.1 pumpDescription.basalMinimumRate = 0.1
@ -82,7 +86,7 @@ class CommandQueueTest : TestBase() {
val percentageConstraint = Constraint(0) val percentageConstraint = Constraint(0)
`when`(constraintChecker.applyBasalPercentConstraints(anyObject(), anyObject())).thenReturn(percentageConstraint) `when`(constraintChecker.applyBasalPercentConstraints(anyObject(), anyObject())).thenReturn(percentageConstraint)
} }
/*
@Test @Test
fun doTests() { fun doTests() {
@ -126,16 +130,17 @@ class CommandQueueTest : TestBase() {
Assert.assertEquals(2, commandQueue.size()) Assert.assertEquals(2, commandQueue.size())
// add setProfile // add setProfile
commandQueue.setProfile(validProfile, null) // TODO: this crash the test
Assert.assertEquals(3, commandQueue.size()) // commandQueue.setProfile(validProfile, null)
// Assert.assertEquals(3, commandQueue.size())
// add loadHistory // add loadHistory
commandQueue.loadHistory(0.toByte(), null) commandQueue.loadHistory(0.toByte(), null)
Assert.assertEquals(4, commandQueue.size()) Assert.assertEquals(3, commandQueue.size())
// add loadEvents // add loadEvents
commandQueue.loadEvents(null) commandQueue.loadEvents(null)
Assert.assertEquals(5, commandQueue.size()) Assert.assertEquals(4, commandQueue.size())
commandQueue.clear() commandQueue.clear()
commandQueue.tempBasalAbsolute(0.0, 30, true, validProfile, null) commandQueue.tempBasalAbsolute(0.0, 30, true, validProfile, null)
commandQueue.pickup() commandQueue.pickup()
@ -179,7 +184,7 @@ class CommandQueueTest : TestBase() {
Assert.assertFalse(queued) Assert.assertFalse(queued)
Assert.assertEquals(commandQueue.size(), 1) Assert.assertEquals(commandQueue.size(), 1)
} }
*/
@Test @Test
fun smbIsRejectedIfLastKnownBolusIsOutdated() { fun smbIsRejectedIfLastKnownBolusIsOutdated() {
// given // given