actionStringHandler, // TODO Adrian use RxBus instead of Lazy
+ IobCobCalculatorPlugin iobCobCalculatorPlugin
+ ) {
super(new PluginDescription()
- .mainType(PluginType.LOOP)
- .fragmentClass(LoopFragment.class.getName())
- .pluginName(R.string.loop)
- .shortName(R.string.loop_shortname)
- .preferencesId(R.xml.pref_loop)
- .description(R.string.description_loop)
+ .mainType(PluginType.LOOP)
+ .fragmentClass(LoopFragment.class.getName())
+ .pluginName(R.string.loop)
+ .shortName(R.string.loop_shortname)
+ .preferencesId(R.xml.pref_loop)
+ .description(R.string.description_loop),
+ aapsLogger, resourceHelper, injector
);
- loopSuspendedTill = SP.getLong("loopSuspendedTill", 0L);
- isSuperBolus = SP.getBoolean("isSuperBolus", false);
- isDisconnected = SP.getBoolean("isDisconnected", false);
+ this.injector = injector;
+ this.sp = sp;
+ this.rxBus = rxBus;
+ this.constraintChecker = constraintChecker;
+ this.resourceHelper = resourceHelper;
+ this.profileFunction = profileFunction;
+ this.context = context;
+ this.activePlugin = activePlugin;
+ this.commandQueue = commandQueue;
+ this.treatmentsPlugin = treatmentsPlugin;
+ this.virtualPumpPlugin = virtualPumpPlugin;
+ this.actionStringHandler = actionStringHandler;
+ this.iobCobCalculatorPlugin = iobCobCalculatorPlugin;
+
+ loopSuspendedTill = sp.getLong("loopSuspendedTill", 0L);
+ isSuperBolus = sp.getBoolean("isSuperBolus", false);
+ isDisconnected = sp.getBoolean("isDisconnected", false);
}
@Override
protected void onStart() {
createNotificationChannel();
super.onStart();
- disposable.add(RxBus.INSTANCE
+ disposable.add(rxBus
.toObservable(EventTempTargetChange.class)
.observeOn(Schedulers.io())
- .subscribe(event -> {
- invoke("EventTempTargetChange", true);
- }, FabricPrivacy::logException)
+ .subscribe(event -> invoke("EventTempTargetChange", true), exception -> FabricPrivacy.getInstance().logException(exception))
);
/**
* This method is triggered once autosens calculation has completed, so the LoopPlugin
@@ -139,14 +176,14 @@ public class LoopPlugin extends PluginBase {
* the event causing the calculation is not EventNewBg.
*
*/
- disposable.add(RxBus.INSTANCE
+ disposable.add(rxBus
.toObservable(EventAutosensCalculationFinished.class)
.observeOn(Schedulers.io())
.subscribe(event -> {
// Autosens calculation not triggered by a new BG
if (!(event.getCause() instanceof EventNewBG)) return;
- BgReading bgReading = DatabaseHelper.actualBg();
+ BgReading bgReading = iobCobCalculatorPlugin.actualBg();
// BG outdated
if (bgReading == null) return;
// already looped with that value
@@ -154,7 +191,7 @@ public class LoopPlugin extends PluginBase {
lastBgTriggeredRun = bgReading.date;
invoke("AutosenseCalculation for " + bgReading, true);
- }, FabricPrivacy::logException)
+ }, exception -> FabricPrivacy.getInstance().logException(exception))
);
}
@@ -162,7 +199,7 @@ public class LoopPlugin extends PluginBase {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager mNotificationManager =
- (NotificationManager) MainApp.instance().getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
+ (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
@SuppressLint("WrongConstant") NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
CHANNEL_ID,
NotificationManager.IMPORTANCE_HIGH);
@@ -178,8 +215,13 @@ public class LoopPlugin extends PluginBase {
@Override
public boolean specialEnableCondition() {
- PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
- return pump == null || pump.getPumpDescription().isTempBasalCapable;
+ try {
+ PumpInterface pump = activePlugin.getActivePump();
+ return pump.getPumpDescription().isTempBasalCapable;
+ } catch (Exception ignored) {
+ // may fail during initialization
+ return true;
+ }
}
public long suspendedTo() {
@@ -190,27 +232,27 @@ public class LoopPlugin extends PluginBase {
loopSuspendedTill = endTime;
isSuperBolus = false;
isDisconnected = false;
- SP.putLong("loopSuspendedTill", loopSuspendedTill);
- SP.putBoolean("isSuperBolus", isSuperBolus);
- SP.putBoolean("isDisconnected", isDisconnected);
+ sp.putLong("loopSuspendedTill", loopSuspendedTill);
+ sp.putBoolean("isSuperBolus", isSuperBolus);
+ sp.putBoolean("isDisconnected", isDisconnected);
}
public void superBolusTo(long endTime) {
loopSuspendedTill = endTime;
isSuperBolus = true;
isDisconnected = false;
- SP.putLong("loopSuspendedTill", loopSuspendedTill);
- SP.putBoolean("isSuperBolus", isSuperBolus);
- SP.putBoolean("isDisconnected", isDisconnected);
+ sp.putLong("loopSuspendedTill", loopSuspendedTill);
+ sp.putBoolean("isSuperBolus", isSuperBolus);
+ sp.putBoolean("isDisconnected", isDisconnected);
}
- public void disconnectTo(long endTime) {
+ private void disconnectTo(long endTime) {
loopSuspendedTill = endTime;
isSuperBolus = false;
isDisconnected = true;
- SP.putLong("loopSuspendedTill", loopSuspendedTill);
- SP.putBoolean("isSuperBolus", isSuperBolus);
- SP.putBoolean("isDisconnected", isDisconnected);
+ sp.putLong("loopSuspendedTill", loopSuspendedTill);
+ sp.putBoolean("isSuperBolus", isSuperBolus);
+ sp.putBoolean("isDisconnected", isDisconnected);
}
public int minutesToEndOfSuspend() {
@@ -275,44 +317,41 @@ public class LoopPlugin extends PluginBase {
public synchronized void invoke(String initiator, boolean allowNotification, boolean tempBasalFallback) {
try {
- if (L.isEnabled(L.APS))
- log.debug("invoke from " + initiator);
- Constraint loopEnabled = MainApp.getConstraintChecker().isLoopInvokationAllowed();
+ getAapsLogger().debug(LTag.APS, "invoke from " + initiator);
+ Constraint loopEnabled = constraintChecker.isLoopInvocationAllowed();
if (!loopEnabled.value()) {
- String message = MainApp.gs(R.string.loopdisabled) + "\n" + loopEnabled.getReasons();
- if (L.isEnabled(L.APS))
- log.debug(message);
- RxBus.INSTANCE.send(new EventLoopSetLastRunGui(message));
+ String message = resourceHelper.gs(R.string.loopdisabled) + "\n" + loopEnabled.getReasons(getAapsLogger());
+ getAapsLogger().debug(LTag.APS, message);
+ rxBus.send(new EventLoopSetLastRunGui(message));
return;
}
- final PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
+ final PumpInterface pump = activePlugin.getActivePump();
APSResult result = null;
if (!isEnabled(PluginType.LOOP))
return;
- Profile profile = ProfileFunctions.getInstance().getProfile();
+ Profile profile = profileFunction.getProfile();
- if (profile == null || !ProfileFunctions.getInstance().isProfileValid("Loop")) {
- if (L.isEnabled(L.APS))
- log.debug(MainApp.gs(R.string.noprofileselected));
- RxBus.INSTANCE.send(new EventLoopSetLastRunGui(MainApp.gs(R.string.noprofileselected)));
+ if (profile == null || !profileFunction.isProfileValid("Loop")) {
+ getAapsLogger().debug(LTag.APS, resourceHelper.gs(R.string.noprofileselected));
+ rxBus.send(new EventLoopSetLastRunGui(resourceHelper.gs(R.string.noprofileselected)));
return;
}
// Check if pump info is loaded
if (pump.getBaseBasalRate() < 0.01d) return;
- APSInterface usedAPS = ConfigBuilderPlugin.getPlugin().getActiveAPS();
- if (usedAPS != null && ((PluginBase) usedAPS).isEnabled(PluginType.APS)) {
+ APSInterface usedAPS = activePlugin.getActiveAPS();
+ if (((PluginBase) usedAPS).isEnabled(PluginType.APS)) {
usedAPS.invoke(initiator, tempBasalFallback);
result = usedAPS.getLastAPSResult();
}
// Check if we have any result
if (result == null) {
- RxBus.INSTANCE.send(new EventLoopSetLastRunGui(MainApp.gs(R.string.noapsselected)));
+ rxBus.send(new EventLoopSetLastRunGui(resourceHelper.gs(R.string.noapsselected)));
return;
}
@@ -323,28 +362,27 @@ public class LoopPlugin extends PluginBase {
result.percent = (int) (result.rate / profile.getBasal() * 100);
// check rate for constrais
- final APSResult resultAfterConstraints = result.clone();
+ final APSResult resultAfterConstraints = result.newAndClone(injector);
resultAfterConstraints.rateConstraint = new Constraint<>(resultAfterConstraints.rate);
- resultAfterConstraints.rate = MainApp.getConstraintChecker().applyBasalConstraints(resultAfterConstraints.rateConstraint, profile).value();
+ resultAfterConstraints.rate = constraintChecker.applyBasalConstraints(resultAfterConstraints.rateConstraint, profile).value();
resultAfterConstraints.percentConstraint = new Constraint<>(resultAfterConstraints.percent);
- resultAfterConstraints.percent = MainApp.getConstraintChecker().applyBasalPercentConstraints(resultAfterConstraints.percentConstraint, profile).value();
+ resultAfterConstraints.percent = constraintChecker.applyBasalPercentConstraints(resultAfterConstraints.percentConstraint, profile).value();
resultAfterConstraints.smbConstraint = new Constraint<>(resultAfterConstraints.smb);
- resultAfterConstraints.smb = MainApp.getConstraintChecker().applyBolusConstraints(resultAfterConstraints.smbConstraint).value();
+ resultAfterConstraints.smb = constraintChecker.applyBolusConstraints(resultAfterConstraints.smbConstraint).value();
// safety check for multiple SMBs
- long lastBolusTime = TreatmentsPlugin.getPlugin().getLastBolusTime();
+ long lastBolusTime = treatmentsPlugin.getLastBolusTime();
if (lastBolusTime != 0 && lastBolusTime + T.mins(3).msecs() > System.currentTimeMillis()) {
- if (L.isEnabled(L.APS))
- log.debug("SMB requsted but still in 3 min interval");
+ getAapsLogger().debug(LTag.APS, "SMB requsted but still in 3 min interval");
resultAfterConstraints.smb = 0;
}
if (lastRun == null) lastRun = new LastRun();
lastRun.request = result;
lastRun.constraintsProcessed = resultAfterConstraints;
- lastRun.lastAPSRun = new Date();
+ lastRun.lastAPSRun = DateUtil.now();
lastRun.source = ((PluginBase) usedAPS).getName();
lastRun.tbrSetByPump = null;
lastRun.smbSetByPump = null;
@@ -353,63 +391,61 @@ public class LoopPlugin extends PluginBase {
lastRun.lastSMBEnact = 0;
lastRun.lastSMBRequest = 0;
- NSUpload.uploadDeviceStatus();
+ NSUpload.uploadDeviceStatus(this, iobCobCalculatorPlugin, profileFunction, activePlugin.getActivePump());
if (isSuspended()) {
- if (L.isEnabled(L.APS))
- log.debug(MainApp.gs(R.string.loopsuspended));
- RxBus.INSTANCE.send(new EventLoopSetLastRunGui(MainApp.gs(R.string.loopsuspended)));
+ getAapsLogger().debug(LTag.APS, resourceHelper.gs(R.string.loopsuspended));
+ rxBus.send(new EventLoopSetLastRunGui(resourceHelper.gs(R.string.loopsuspended)));
return;
}
if (pump.isSuspended()) {
- if (L.isEnabled(L.APS))
- log.debug(MainApp.gs(R.string.pumpsuspended));
- RxBus.INSTANCE.send(new EventLoopSetLastRunGui(MainApp.gs(R.string.pumpsuspended)));
+ getAapsLogger().debug(LTag.APS, resourceHelper.gs(R.string.pumpsuspended));
+ rxBus.send(new EventLoopSetLastRunGui(resourceHelper.gs(R.string.pumpsuspended)));
return;
}
- Constraint closedLoopEnabled = MainApp.getConstraintChecker().isClosedLoopAllowed();
+ Constraint closedLoopEnabled = constraintChecker.isClosedLoopAllowed();
if (closedLoopEnabled.value()) {
if (resultAfterConstraints.isChangeRequested()
- && !ConfigBuilderPlugin.getPlugin().getCommandQueue().bolusInQueue()
- && !ConfigBuilderPlugin.getPlugin().getCommandQueue().isRunning(Command.CommandType.BOLUS)) {
- final PumpEnactResult waiting = new PumpEnactResult();
+ && !commandQueue.bolusInQueue()
+ && !commandQueue.isRunning(Command.CommandType.BOLUS)) {
+ final PumpEnactResult waiting = new PumpEnactResult(getInjector());
waiting.queued = true;
if (resultAfterConstraints.tempBasalRequested)
lastRun.tbrSetByPump = waiting;
if (resultAfterConstraints.bolusRequested)
lastRun.smbSetByPump = waiting;
- RxBus.INSTANCE.send(new EventLoopUpdateGui());
+ rxBus.send(new EventLoopUpdateGui());
FabricPrivacy.getInstance().logCustom("APSRequest");
applyTBRRequest(resultAfterConstraints, profile, new Callback() {
@Override
public void run() {
if (result.enacted || result.success) {
lastRun.tbrSetByPump = result;
- lastRun.lastTBRRequest = lastRun.lastAPSRun.getTime();
+ lastRun.lastTBRRequest = lastRun.lastAPSRun;
lastRun.lastTBREnact = DateUtil.now();
- RxBus.INSTANCE.send(new EventLoopUpdateGui());
+ rxBus.send(new EventLoopUpdateGui());
applySMBRequest(resultAfterConstraints, new Callback() {
@Override
public void run() {
//Callback is only called if a bolus was acutally requested
if (result.enacted || result.success) {
lastRun.smbSetByPump = result;
- lastRun.lastSMBRequest = lastRun.lastAPSRun.getTime();
+ lastRun.lastSMBRequest = lastRun.lastAPSRun;
lastRun.lastSMBEnact = DateUtil.now();
} else {
new Thread(() -> {
SystemClock.sleep(1000);
- LoopPlugin.getPlugin().invoke("tempBasalFallback", allowNotification, true);
+ invoke("tempBasalFallback", allowNotification, true);
}).start();
}
- RxBus.INSTANCE.send(new EventLoopUpdateGui());
+ rxBus.send(new EventLoopUpdateGui());
}
});
}
- RxBus.INSTANCE.send(new EventLoopUpdateGui());
+ rxBus.send(new EventLoopUpdateGui());
}
});
} else {
@@ -419,26 +455,26 @@ public class LoopPlugin extends PluginBase {
} else {
if (resultAfterConstraints.isChangeRequested() && allowNotification) {
NotificationCompat.Builder builder =
- new NotificationCompat.Builder(MainApp.instance().getApplicationContext(), CHANNEL_ID);
+ new NotificationCompat.Builder(context, CHANNEL_ID);
builder.setSmallIcon(R.drawable.notif_icon)
- .setContentTitle(MainApp.gs(R.string.openloop_newsuggestion))
+ .setContentTitle(resourceHelper.gs(R.string.openloop_newsuggestion))
.setContentText(resultAfterConstraints.toString())
.setAutoCancel(true)
.setPriority(Notification.PRIORITY_HIGH)
.setCategory(Notification.CATEGORY_ALARM)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
- if (SP.getBoolean("wearcontrol", false)) {
+ if (sp.getBoolean("wearcontrol", false)) {
builder.setLocalOnly(true);
}
// Creates an explicit intent for an Activity in your app
- Intent resultIntent = new Intent(MainApp.instance().getApplicationContext(), MainActivity.class);
+ Intent resultIntent = new Intent(context, MainActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
- TaskStackBuilder stackBuilder = TaskStackBuilder.create(MainApp.instance().getApplicationContext());
+ TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
@@ -447,44 +483,43 @@ public class LoopPlugin extends PluginBase {
builder.setContentIntent(resultPendingIntent);
builder.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
NotificationManager mNotificationManager =
- (NotificationManager) MainApp.instance().getSystemService(Context.NOTIFICATION_SERVICE);
+ (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(Constants.notificationID, builder.build());
- RxBus.INSTANCE.send(new EventNewOpenLoopNotification());
+ rxBus.send(new EventNewOpenLoopNotification());
// Send to Wear
- ActionStringHandler.handleInitiate("changeRequest");
+ actionStringHandler.get().handleInitiate("changeRequest");
} else if (allowNotification) {
// dismiss notifications
NotificationManager notificationManager =
- (NotificationManager) MainApp.instance().getSystemService(Context.NOTIFICATION_SERVICE);
+ (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(Constants.notificationID);
- ActionStringHandler.handleInitiate("cancelChangeRequest");
+ actionStringHandler.get().handleInitiate("cancelChangeRequest");
}
}
- RxBus.INSTANCE.send(new EventLoopUpdateGui());
+ rxBus.send(new EventLoopUpdateGui());
} finally {
- if (L.isEnabled(L.APS))
- log.debug("invoke end");
+ getAapsLogger().debug(LTag.APS, "invoke end");
}
}
public void acceptChangeRequest() {
- Profile profile = ProfileFunctions.getInstance().getProfile();
-
+ Profile profile = profileFunction.getProfile();
+ final LoopPlugin lp = this;
applyTBRRequest(lastRun.constraintsProcessed, profile, new Callback() {
@Override
public void run() {
if (result.enacted) {
lastRun.tbrSetByPump = result;
- lastRun.lastTBRRequest = lastRun.lastAPSRun.getTime();
+ lastRun.lastTBRRequest = lastRun.lastAPSRun;
lastRun.lastTBREnact = DateUtil.now();
lastRun.lastOpenModeAccept = DateUtil.now();
- NSUpload.uploadDeviceStatus();
- SP.incInt(R.string.key_ObjectivesmanualEnacts);
+ NSUpload.uploadDeviceStatus(lp, iobCobCalculatorPlugin, profileFunction, activePlugin.getActivePump());
+ sp.incInt(R.string.key_ObjectivesmanualEnacts);
}
- RxBus.INSTANCE.send(new EventAcceptOpenLoopChange());
+ rxBus.send(new EventAcceptOpenLoopChange());
}
});
FabricPrivacy.getInstance().logCustom("AcceptTemp");
@@ -495,206 +530,187 @@ public class LoopPlugin extends PluginBase {
* TODO: update pump drivers to support APS request in %
*/
- public void applyTBRRequest(APSResult request, Profile profile, Callback callback) {
- boolean allowPercentage = VirtualPumpPlugin.getPlugin().isEnabled(PluginType.PUMP);
+ private void applyTBRRequest(APSResult request, Profile profile, Callback callback) {
+ boolean allowPercentage = virtualPumpPlugin.isEnabled(PluginType.PUMP);
if (!request.tempBasalRequested) {
if (callback != null) {
- callback.result(new PumpEnactResult().enacted(false).success(true).comment(MainApp.gs(R.string.nochangerequested))).run();
+ callback.result(new PumpEnactResult(getInjector()).enacted(false).success(true).comment(resourceHelper.gs(R.string.nochangerequested))).run();
}
return;
}
- PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
- TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin();
+ PumpInterface pump = activePlugin.getActivePump();
if (!pump.isInitialized()) {
- if (L.isEnabled(L.APS))
- log.debug("applyAPSRequest: " + MainApp.gs(R.string.pumpNotInitialized));
+ getAapsLogger().debug(LTag.APS, "applyAPSRequest: " + resourceHelper.gs(R.string.pumpNotInitialized));
if (callback != null) {
- callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpNotInitialized)).enacted(false).success(false)).run();
+ callback.result(new PumpEnactResult(getInjector()).comment(resourceHelper.gs(R.string.pumpNotInitialized)).enacted(false).success(false)).run();
}
return;
}
if (pump.isSuspended()) {
- if (L.isEnabled(L.APS))
- log.debug("applyAPSRequest: " + MainApp.gs(R.string.pumpsuspended));
+ getAapsLogger().debug(LTag.APS, "applyAPSRequest: " + resourceHelper.gs(R.string.pumpsuspended));
if (callback != null) {
- callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpsuspended)).enacted(false).success(false)).run();
+ callback.result(new PumpEnactResult(getInjector()).comment(resourceHelper.gs(R.string.pumpsuspended)).enacted(false).success(false)).run();
}
return;
}
- if (L.isEnabled(L.APS))
- log.debug("applyAPSRequest: " + request.toString());
+ getAapsLogger().debug(LTag.APS, "applyAPSRequest: " + request.toString());
long now = System.currentTimeMillis();
- TemporaryBasal activeTemp = activeTreatments.getTempBasalFromHistory(now);
+ TemporaryBasal activeTemp = treatmentsPlugin.getTempBasalFromHistory(now);
if (request.usePercent && allowPercentage) {
if (request.percent == 100 && request.duration == 0) {
if (activeTemp != null) {
- if (L.isEnabled(L.APS))
- log.debug("applyAPSRequest: cancelTempBasal()");
- ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(false, callback);
+ getAapsLogger().debug(LTag.APS, "applyAPSRequest: cancelTempBasal()");
+ commandQueue.cancelTempBasal(false, callback);
} else {
- if (L.isEnabled(L.APS))
- log.debug("applyAPSRequest: Basal set correctly");
+ getAapsLogger().debug(LTag.APS, "applyAPSRequest: Basal set correctly");
if (callback != null) {
- callback.result(new PumpEnactResult().percent(request.percent).duration(0)
- .enacted(false).success(true).comment(MainApp.gs(R.string.basal_set_correctly))).run();
+ callback.result(new PumpEnactResult(getInjector()).percent(request.percent).duration(0)
+ .enacted(false).success(true).comment(resourceHelper.gs(R.string.basal_set_correctly))).run();
}
}
} else if (activeTemp != null
&& activeTemp.getPlannedRemainingMinutes() > 5
&& request.duration - activeTemp.getPlannedRemainingMinutes() < 30
&& request.percent == activeTemp.percentRate) {
- if (L.isEnabled(L.APS))
- log.debug("applyAPSRequest: Temp basal set correctly");
+ getAapsLogger().debug(LTag.APS, "applyAPSRequest: Temp basal set correctly");
if (callback != null) {
- callback.result(new PumpEnactResult().percent(request.percent)
+ callback.result(new PumpEnactResult(getInjector()).percent(request.percent)
.enacted(false).success(true).duration(activeTemp.getPlannedRemainingMinutes())
- .comment(MainApp.gs(R.string.let_temp_basal_run))).run();
+ .comment(resourceHelper.gs(R.string.let_temp_basal_run))).run();
}
} else {
- if (L.isEnabled(L.APS))
- log.debug("applyAPSRequest: tempBasalPercent()");
- ConfigBuilderPlugin.getPlugin().getCommandQueue().tempBasalPercent(request.percent, request.duration, false, profile, callback);
+ getAapsLogger().debug(LTag.APS, "applyAPSRequest: tempBasalPercent()");
+ commandQueue.tempBasalPercent(request.percent, request.duration, false, profile, callback);
}
} else {
if ((request.rate == 0 && request.duration == 0) || Math.abs(request.rate - pump.getBaseBasalRate()) < pump.getPumpDescription().basalStep) {
if (activeTemp != null) {
- if (L.isEnabled(L.APS))
- log.debug("applyAPSRequest: cancelTempBasal()");
- ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(false, callback);
+ getAapsLogger().debug(LTag.APS, "applyAPSRequest: cancelTempBasal()");
+ commandQueue.cancelTempBasal(false, callback);
} else {
- if (L.isEnabled(L.APS))
- log.debug("applyAPSRequest: Basal set correctly");
+ getAapsLogger().debug(LTag.APS, "applyAPSRequest: Basal set correctly");
if (callback != null) {
- callback.result(new PumpEnactResult().absolute(request.rate).duration(0)
- .enacted(false).success(true).comment(MainApp.gs(R.string.basal_set_correctly))).run();
+ callback.result(new PumpEnactResult(getInjector()).absolute(request.rate).duration(0)
+ .enacted(false).success(true).comment(resourceHelper.gs(R.string.basal_set_correctly))).run();
}
}
} else if (activeTemp != null
&& activeTemp.getPlannedRemainingMinutes() > 5
&& request.duration - activeTemp.getPlannedRemainingMinutes() < 30
&& Math.abs(request.rate - activeTemp.tempBasalConvertedToAbsolute(now, profile)) < pump.getPumpDescription().basalStep) {
- if (L.isEnabled(L.APS))
- log.debug("applyAPSRequest: Temp basal set correctly");
+ getAapsLogger().debug(LTag.APS, "applyAPSRequest: Temp basal set correctly");
if (callback != null) {
- callback.result(new PumpEnactResult().absolute(activeTemp.tempBasalConvertedToAbsolute(now, profile))
+ callback.result(new PumpEnactResult(getInjector()).absolute(activeTemp.tempBasalConvertedToAbsolute(now, profile))
.enacted(false).success(true).duration(activeTemp.getPlannedRemainingMinutes())
- .comment(MainApp.gs(R.string.let_temp_basal_run))).run();
+ .comment(resourceHelper.gs(R.string.let_temp_basal_run))).run();
}
} else {
- if (L.isEnabled(L.APS))
- log.debug("applyAPSRequest: setTempBasalAbsolute()");
- ConfigBuilderPlugin.getPlugin().getCommandQueue().tempBasalAbsolute(request.rate, request.duration, false, profile, callback);
+ getAapsLogger().debug(LTag.APS, "applyAPSRequest: setTempBasalAbsolute()");
+ commandQueue.tempBasalAbsolute(request.rate, request.duration, false, profile, callback);
}
}
}
- public void applySMBRequest(APSResult request, Callback callback) {
+ private void applySMBRequest(APSResult request, Callback callback) {
if (!request.bolusRequested) {
return;
}
- PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
- TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin();
+ PumpInterface pump = activePlugin.getActivePump();
- long lastBolusTime = activeTreatments.getLastBolusTime();
+ long lastBolusTime = treatmentsPlugin.getLastBolusTime();
if (lastBolusTime != 0 && lastBolusTime + 3 * 60 * 1000 > System.currentTimeMillis()) {
- if (L.isEnabled(L.APS))
- log.debug("SMB requested but still in 3 min interval");
+ getAapsLogger().debug(LTag.APS, "SMB requested but still in 3 min interval");
if (callback != null) {
- callback.result(new PumpEnactResult()
- .comment(MainApp.gs(R.string.smb_frequency_exceeded))
+ callback.result(new PumpEnactResult(getInjector())
+ .comment(resourceHelper.gs(R.string.smb_frequency_exceeded))
.enacted(false).success(false)).run();
}
return;
}
if (!pump.isInitialized()) {
- if (L.isEnabled(L.APS))
- log.debug("applySMBRequest: " + MainApp.gs(R.string.pumpNotInitialized));
+ getAapsLogger().debug(LTag.APS, "applySMBRequest: " + resourceHelper.gs(R.string.pumpNotInitialized));
if (callback != null) {
- callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpNotInitialized)).enacted(false).success(false)).run();
+ callback.result(new PumpEnactResult(getInjector()).comment(resourceHelper.gs(R.string.pumpNotInitialized)).enacted(false).success(false)).run();
}
return;
}
if (pump.isSuspended()) {
- if (L.isEnabled(L.APS))
- log.debug("applySMBRequest: " + MainApp.gs(R.string.pumpsuspended));
+ getAapsLogger().debug(LTag.APS, "applySMBRequest: " + resourceHelper.gs(R.string.pumpsuspended));
if (callback != null) {
- callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpsuspended)).enacted(false).success(false)).run();
+ callback.result(new PumpEnactResult(getInjector()).comment(resourceHelper.gs(R.string.pumpsuspended)).enacted(false).success(false)).run();
}
return;
}
- if (L.isEnabled(L.APS))
- log.debug("applySMBRequest: " + request.toString());
+ getAapsLogger().debug(LTag.APS, "applySMBRequest: " + request.toString());
// deliver SMB
DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo();
- detailedBolusInfo.lastKnownBolusTime = activeTreatments.getLastBolusTime();
+ detailedBolusInfo.lastKnownBolusTime = treatmentsPlugin.getLastBolusTime();
detailedBolusInfo.eventType = CareportalEvent.CORRECTIONBOLUS;
detailedBolusInfo.insulin = request.smb;
detailedBolusInfo.isSMB = true;
detailedBolusInfo.source = Source.USER;
detailedBolusInfo.deliverAt = request.deliverAt;
- if (L.isEnabled(L.APS))
- log.debug("applyAPSRequest: bolus()");
- ConfigBuilderPlugin.getPlugin().getCommandQueue().bolus(detailedBolusInfo, callback);
+ getAapsLogger().debug(LTag.APS, "applyAPSRequest: bolus()");
+ commandQueue.bolus(detailedBolusInfo, callback);
}
public void disconnectPump(int durationInMinutes, Profile profile) {
- PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
- TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin();
+ PumpInterface pump = activePlugin.getActivePump();
- LoopPlugin.getPlugin().disconnectTo(System.currentTimeMillis() + durationInMinutes * 60 * 1000L);
+ disconnectTo(System.currentTimeMillis() + durationInMinutes * 60 * 1000L);
if (pump.getPumpDescription().tempBasalStyle == PumpDescription.ABSOLUTE) {
- ConfigBuilderPlugin.getPlugin().getCommandQueue().tempBasalAbsolute(0, durationInMinutes, true, profile, new Callback() {
+ commandQueue.tempBasalAbsolute(0, durationInMinutes, true, profile, new Callback() {
@Override
public void run() {
if (!result.success) {
- Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
+ Intent i = new Intent(context, ErrorHelperActivity.class);
i.putExtra("soundid", R.raw.boluserror);
i.putExtra("status", result.comment);
- i.putExtra("title", MainApp.gs(R.string.tempbasaldeliveryerror));
+ i.putExtra("title", resourceHelper.gs(R.string.tempbasaldeliveryerror));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- MainApp.instance().startActivity(i);
+ context.startActivity(i);
}
}
});
} else {
- ConfigBuilderPlugin.getPlugin().getCommandQueue().tempBasalPercent(0, durationInMinutes, true, profile, new Callback() {
+ commandQueue.tempBasalPercent(0, durationInMinutes, true, profile, new Callback() {
@Override
public void run() {
if (!result.success) {
- Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
+ Intent i = new Intent(context, ErrorHelperActivity.class);
i.putExtra("soundid", R.raw.boluserror);
i.putExtra("status", result.comment);
- i.putExtra("title", MainApp.gs(R.string.tempbasaldeliveryerror));
+ i.putExtra("title", resourceHelper.gs(R.string.tempbasaldeliveryerror));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- MainApp.instance().startActivity(i);
+ context.startActivity(i);
}
}
});
}
- if (pump.getPumpDescription().isExtendedBolusCapable && activeTreatments.isInHistoryExtendedBoluslInProgress()) {
- ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelExtended(new Callback() {
+ if (pump.getPumpDescription().isExtendedBolusCapable && treatmentsPlugin.isInHistoryExtendedBoluslInProgress()) {
+ commandQueue.cancelExtended(new Callback() {
@Override
public void run() {
if (!result.success) {
- Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
+ Intent i = new Intent(context, ErrorHelperActivity.class);
i.putExtra("soundid", R.raw.boluserror);
i.putExtra("status", result.comment);
- i.putExtra("title", MainApp.gs(R.string.extendedbolusdeliveryerror));
+ i.putExtra("title", resourceHelper.gs(R.string.extendedbolusdeliveryerror));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- MainApp.instance().startActivity(i);
+ context.startActivity(i);
}
}
});
@@ -703,17 +719,17 @@ public class LoopPlugin extends PluginBase {
}
public void suspendLoop(int durationInMinutes) {
- LoopPlugin.getPlugin().suspendTo(System.currentTimeMillis() + durationInMinutes * 60 * 1000);
- ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(true, new Callback() {
+ suspendTo(System.currentTimeMillis() + durationInMinutes * 60 * 1000);
+ commandQueue.cancelTempBasal(true, new Callback() {
@Override
public void run() {
if (!result.success) {
- Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
+ Intent i = new Intent(context, ErrorHelperActivity.class);
i.putExtra("soundid", R.raw.boluserror);
i.putExtra("status", result.comment);
- i.putExtra("title", MainApp.gs(R.string.tempbasaldeliveryerror));
+ i.putExtra("title", resourceHelper.gs(R.string.tempbasaldeliveryerror));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- MainApp.instance().startActivity(i);
+ context.startActivity(i);
}
}
});
@@ -726,7 +742,7 @@ public class LoopPlugin extends PluginBase {
data.put("eventType", CareportalEvent.OPENAPSOFFLINE);
data.put("duration", durationInMinutes);
} catch (JSONException e) {
- log.error("Unhandled exception", e);
+ getAapsLogger().error("Unhandled exception", e);
}
CareportalEvent event = new CareportalEvent();
event.date = DateUtil.now();
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.java
index 9ea2d39567..50a6c6e018 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.java
@@ -11,37 +11,42 @@ import org.mozilla.javascript.RhinoException;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.Undefined;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.StandardCharsets;
import javax.annotation.Nullable;
+import javax.inject.Inject;
+import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.Constants;
-import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
-import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.TemporaryBasal;
-import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
+import info.nightscout.androidaps.logging.AAPSLogger;
+import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.aps.loop.ScriptReader;
-import info.nightscout.androidaps.plugins.aps.openAPSMA.LoggerCallback;
+import info.nightscout.androidaps.plugins.aps.logger.LoggerCallback;
import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults;
+import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker;
+import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction;
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus;
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
-import info.nightscout.androidaps.utils.SP;
+import info.nightscout.androidaps.utils.sharedPreferences.SP;
public class DetermineBasalAdapterAMAJS {
- private static Logger log = LoggerFactory.getLogger(L.APS);
+ private HasAndroidInjector injector;
+ @Inject AAPSLogger aapsLogger;
+ @Inject ConstraintChecker constraintChecker;
+ @Inject SP sp;
+ @Inject ProfileFunction profileFunction;
+ @Inject TreatmentsPlugin treatmentsPlugin;
-
- private ScriptReader mScriptReader = null;
+ private ScriptReader mScriptReader;
private JSONObject mProfile;
private JSONObject mGlucoseStatus;
@@ -59,25 +64,26 @@ public class DetermineBasalAdapterAMAJS {
private String scriptDebug = "";
- public DetermineBasalAdapterAMAJS(ScriptReader scriptReader) {
+ DetermineBasalAdapterAMAJS(ScriptReader scriptReader, HasAndroidInjector injector) {
+ injector.androidInjector().inject(this);
mScriptReader = scriptReader;
+ this.injector = injector;
}
@Nullable
public DetermineBasalResultAMA invoke() {
- if (L.isEnabled(L.APS)) {
- log.debug(">>> Invoking detemine_basal <<<");
- log.debug("Glucose status: " + (storedGlucoseStatus = mGlucoseStatus.toString()));
- log.debug("IOB data: " + (storedIobData = mIobData.toString()));
- log.debug("Current temp: " + (storedCurrentTemp = mCurrentTemp.toString()));
- log.debug("Profile: " + (storedProfile = mProfile.toString()));
- log.debug("Meal data: " + (storedMeal_data = mMealData.toString()));
- if (mAutosensData != null)
- log.debug("Autosens data: " + (storedAutosens_data = mAutosensData.toString()));
- else
- log.debug("Autosens data: " + (storedAutosens_data = "undefined"));
- }
+ aapsLogger.debug(LTag.APS, ">>> Invoking detemine_basal <<<");
+ aapsLogger.debug(LTag.APS, "Glucose status: " + (storedGlucoseStatus = mGlucoseStatus.toString()));
+ aapsLogger.debug(LTag.APS, "IOB data: " + (storedIobData = mIobData.toString()));
+ aapsLogger.debug(LTag.APS, "Current temp: " + (storedCurrentTemp = mCurrentTemp.toString()));
+ aapsLogger.debug(LTag.APS, "Profile: " + (storedProfile = mProfile.toString()));
+ aapsLogger.debug(LTag.APS, "Meal data: " + (storedMeal_data = mMealData.toString()));
+ if (mAutosensData != null)
+ aapsLogger.debug(LTag.APS, "Autosens data: " + (storedAutosens_data = mAutosensData.toString()));
+ else
+ aapsLogger.debug(LTag.APS, "Autosens data: " + (storedAutosens_data = "undefined"));
+
DetermineBasalResultAMA determineBasalResultAMA = null;
@@ -124,22 +130,21 @@ public class DetermineBasalAdapterAMAJS {
// Parse the jsResult object to a JSON-String
String result = NativeJSON.stringify(rhino, scope, jsResult, null, null).toString();
- if (L.isEnabled(L.APS))
- log.debug("Result: " + result);
+ aapsLogger.debug(LTag.APS, "Result: " + result);
try {
- determineBasalResultAMA = new DetermineBasalResultAMA(jsResult, new JSONObject(result));
+ determineBasalResultAMA = new DetermineBasalResultAMA(injector, jsResult, new JSONObject(result));
} catch (JSONException e) {
- log.error("Unhandled exception", e);
+ aapsLogger.error(LTag.APS, "Unhandled exception", e);
}
} else {
- log.error("Problem loading JS Functions");
+ aapsLogger.error(LTag.APS, "Problem loading JS Functions");
}
} catch (IOException e) {
- log.error("IOException");
+ aapsLogger.error(LTag.APS, "IOException");
} catch (RhinoException e) {
- log.error("RhinoException: (" + e.lineNumber() + "," + e.columnNumber() + ") " + e.toString());
+ aapsLogger.error(LTag.APS, "RhinoException: (" + e.lineNumber() + "," + e.columnNumber() + ") " + e.toString());
} catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
- log.error(e.toString());
+ aapsLogger.error(LTag.APS, e.toString());
} finally {
Context.exit();
}
@@ -206,25 +211,25 @@ public class DetermineBasalAdapterAMAJS {
mProfile.put("target_bg", targetBg);
mProfile.put("carb_ratio", profile.getIc());
mProfile.put("sens", profile.getIsfMgdl());
- mProfile.put("max_daily_safety_multiplier", SP.getInt(R.string.key_openapsama_max_daily_safety_multiplier, 3));
- mProfile.put("current_basal_safety_multiplier", SP.getDouble(R.string.key_openapsama_current_basal_safety_multiplier, 4d));
+ mProfile.put("max_daily_safety_multiplier", sp.getInt(R.string.key_openapsama_max_daily_safety_multiplier, 3));
+ mProfile.put("current_basal_safety_multiplier", sp.getDouble(R.string.key_openapsama_current_basal_safety_multiplier, 4d));
mProfile.put("skip_neutral_temps", true);
mProfile.put("current_basal", basalrate);
mProfile.put("temptargetSet", tempTargetSet);
- mProfile.put("autosens_adjust_targets", SP.getBoolean(R.string.key_openapsama_autosens_adjusttargets, true));
+ mProfile.put("autosens_adjust_targets", sp.getBoolean(R.string.key_openapsama_autosens_adjusttargets, true));
//align with max-absorption model in AMA sensitivity
if (mealData.usedMinCarbsImpact > 0) {
mProfile.put("min_5m_carbimpact", mealData.usedMinCarbsImpact);
} else {
- mProfile.put("min_5m_carbimpact", SP.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact));
+ mProfile.put("min_5m_carbimpact", sp.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact));
}
- if (ProfileFunctions.getSystemUnits().equals(Constants.MMOL)) {
+ if (profileFunction.getUnits().equals(Constants.MMOL)) {
mProfile.put("out_units", "mmol/L");
}
long now = System.currentTimeMillis();
- TemporaryBasal tb = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now);
+ TemporaryBasal tb = treatmentsPlugin.getTempBasalFromHistory(now);
mCurrentTemp = new JSONObject();
mCurrentTemp.put("temp", "absolute");
@@ -232,7 +237,7 @@ public class DetermineBasalAdapterAMAJS {
mCurrentTemp.put("rate", tb != null ? tb.tempBasalConvertedToAbsolute(now, profile) : 0d);
// as we have non default temps longer than 30 mintues
- TemporaryBasal tempBasal = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis());
+ TemporaryBasal tempBasal = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis());
if (tempBasal != null) {
mCurrentTemp.put("minutesrunning", tempBasal.getRealDuration());
}
@@ -242,7 +247,7 @@ public class DetermineBasalAdapterAMAJS {
mGlucoseStatus = new JSONObject();
mGlucoseStatus.put("glucose", glucoseStatus.glucose);
- if (SP.getBoolean(R.string.key_always_use_shortavg, false)) {
+ if (sp.getBoolean(R.string.key_always_use_shortavg, false)) {
mGlucoseStatus.put("delta", glucoseStatus.short_avgdelta);
} else {
mGlucoseStatus.put("delta", glucoseStatus.delta);
@@ -255,7 +260,7 @@ public class DetermineBasalAdapterAMAJS {
mMealData.put("boluses", mealData.boluses);
mMealData.put("mealCOB", mealData.mealCOB);
- if (MainApp.getConstraintChecker().isAutosensModeEnabled().value()) {
+ if (constraintChecker.isAutosensModeEnabled().value()) {
mAutosensData = new JSONObject();
mAutosensData.put("ratio", autosensDataRatio);
} else {
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalResultAMA.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalResultAMA.java
index 46f1057e27..0bf4839f84 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalResultAMA.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalResultAMA.java
@@ -3,21 +3,21 @@ package info.nightscout.androidaps.plugins.aps.openAPSAMA;
import org.json.JSONException;
import org.json.JSONObject;
import org.mozilla.javascript.NativeObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import info.nightscout.androidaps.logging.L;
+import dagger.android.HasAndroidInjector;
+import info.nightscout.androidaps.logging.AAPSLogger;
+import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.aps.loop.APSResult;
import info.nightscout.androidaps.utils.DateUtil;
public class DetermineBasalResultAMA extends APSResult {
- private static Logger log = LoggerFactory.getLogger(L.APS);
+ private AAPSLogger aapsLogger;
private double eventualBG;
private double snoozeBG;
- DetermineBasalResultAMA(NativeObject result, JSONObject j) {
- this();
+ DetermineBasalResultAMA(HasAndroidInjector injector, NativeObject result, JSONObject j) {
+ this(injector);
date = DateUtil.now();
json = j;
if (result.containsKey("error")) {
@@ -48,13 +48,14 @@ public class DetermineBasalResultAMA extends APSResult {
bolusRequested = false;
}
- private DetermineBasalResultAMA() {
+ private DetermineBasalResultAMA(HasAndroidInjector injector) {
+ super(injector);
hasPredictions = true;
}
@Override
- public DetermineBasalResultAMA clone() {
- DetermineBasalResultAMA newResult = new DetermineBasalResultAMA();
+ public DetermineBasalResultAMA newAndClone(HasAndroidInjector injector) {
+ DetermineBasalResultAMA newResult = new DetermineBasalResultAMA(injector);
doClone(newResult);
newResult.eventualBG = eventualBG;
@@ -68,7 +69,7 @@ public class DetermineBasalResultAMA extends APSResult {
JSONObject ret = new JSONObject(this.json.toString());
return ret;
} catch (JSONException e) {
- log.error("Unhandled exception", e);
+ aapsLogger.error(LTag.APS, "Unhandled exception", e);
}
return null;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAFragment.kt
index 94747a4597..342a1395f5 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAFragment.kt
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAFragment.kt
@@ -5,28 +5,34 @@ import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
-import androidx.fragment.app.Fragment
-import info.nightscout.androidaps.MainApp
+import dagger.android.support.DaggerFragment
import info.nightscout.androidaps.R
-import info.nightscout.androidaps.logging.L
-import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui
-import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateResultGui
-import info.nightscout.androidaps.plugins.bus.RxBus
+import info.nightscout.androidaps.logging.AAPSLogger
+import info.nightscout.androidaps.logging.LTag
+import info.nightscout.androidaps.plugins.aps.events.EventOpenAPSUpdateGui
+import info.nightscout.androidaps.plugins.aps.events.EventOpenAPSUpdateResultGui
+import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.JSONFormatter
-import info.nightscout.androidaps.utils.plusAssign
+import info.nightscout.androidaps.utils.extensions.plusAssign
+import info.nightscout.androidaps.utils.resources.ResourceHelper
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.openapsama_fragment.*
import org.json.JSONArray
import org.json.JSONException
-import org.slf4j.LoggerFactory
+import javax.inject.Inject
-class OpenAPSAMAFragment : Fragment() {
- private val log = LoggerFactory.getLogger(L.APS)
+class OpenAPSAMAFragment : DaggerFragment() {
private var disposable: CompositeDisposable = CompositeDisposable()
+ @Inject lateinit var aapsLogger: AAPSLogger
+ @Inject lateinit var rxBus: RxBusWrapper
+ @Inject lateinit var resourceHelper: ResourceHelper
+ @Inject lateinit var fabricPrivacy: FabricPrivacy
+ @Inject lateinit var openAPSAMAPlugin: OpenAPSAMAPlugin
+
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.openapsama_fragment, container, false)
@@ -36,7 +42,7 @@ class OpenAPSAMAFragment : Fragment() {
super.onViewCreated(view, savedInstanceState)
openapsma_run.setOnClickListener {
- OpenAPSAMAPlugin.getPlugin().invoke("OpenAPSAMA button", false)
+ openAPSAMAPlugin.invoke("OpenAPSAMA button", false)
}
}
@@ -44,22 +50,18 @@ class OpenAPSAMAFragment : Fragment() {
override fun onResume() {
super.onResume()
- disposable += RxBus
- .toObservable(EventOpenAPSUpdateGui::class.java)
- .observeOn(AndroidSchedulers.mainThread())
- .subscribe({
- updateGUI()
- }, {
- FabricPrivacy.logException(it)
- })
- disposable += RxBus
- .toObservable(EventOpenAPSUpdateResultGui::class.java)
- .observeOn(AndroidSchedulers.mainThread())
- .subscribe({
- updateResultGUI(it.text)
- }, {
- FabricPrivacy.logException(it)
- })
+ disposable += rxBus
+ .toObservable(EventOpenAPSUpdateGui::class.java)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe({
+ updateGUI()
+ }, { fabricPrivacy.logException(it) })
+ disposable += rxBus
+ .toObservable(EventOpenAPSUpdateResultGui::class.java)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe({
+ updateResultGUI(it.text)
+ }, { fabricPrivacy.logException(it) })
updateGUI()
}
@@ -73,18 +75,19 @@ class OpenAPSAMAFragment : Fragment() {
@Synchronized
private fun updateGUI() {
if (openapsma_result == null) return
- OpenAPSAMAPlugin.getPlugin().lastAPSResult?.let { lastAPSResult ->
+ openAPSAMAPlugin.lastAPSResult?.let { lastAPSResult ->
openapsma_result.text = JSONFormatter.format(lastAPSResult.json)
openapsma_request.text = lastAPSResult.toSpanned()
}
- OpenAPSAMAPlugin.getPlugin().lastDetermineBasalAdapterAMAJS?.let { determineBasalAdapterAMAJS ->
+ openAPSAMAPlugin.lastDetermineBasalAdapterAMAJS?.let { determineBasalAdapterAMAJS ->
openapsma_glucosestatus.text = JSONFormatter.format(determineBasalAdapterAMAJS.glucoseStatusParam)
openapsma_currenttemp.text = JSONFormatter.format(determineBasalAdapterAMAJS.currentTempParam)
try {
val iobArray = JSONArray(determineBasalAdapterAMAJS.iobDataParam)
- openapsma_iobdata.text = TextUtils.concat(String.format(MainApp.gs(R.string.array_of_elements), iobArray.length()) + "\n", JSONFormatter.format(iobArray.getString(0)))
+ openapsma_iobdata.text = TextUtils.concat(resourceHelper.gs(R.string.array_of_elements, iobArray.length()) + "\n", JSONFormatter.format(iobArray.getString(0)))
} catch (e: JSONException) {
- log.error("Unhandled exception", e)
+ aapsLogger.error(LTag.APS, "Unhandled exception", e)
+ @Suppress("SetTextI18n")
openapsma_iobdata.text = "JSONException see log for details"
}
@@ -92,10 +95,10 @@ class OpenAPSAMAFragment : Fragment() {
openapsma_mealdata.text = JSONFormatter.format(determineBasalAdapterAMAJS.mealDataParam)
openapsma_scriptdebugdata.text = determineBasalAdapterAMAJS.scriptDebug
}
- if (OpenAPSAMAPlugin.getPlugin().lastAPSRun != 0L) {
- openapsma_lastrun.text = DateUtil.dateAndTimeFullString(OpenAPSAMAPlugin.getPlugin().lastAPSRun)
+ if (openAPSAMAPlugin.lastAPSRun != 0L) {
+ openapsma_lastrun.text = DateUtil.dateAndTimeString(openAPSAMAPlugin.lastAPSRun)
}
- OpenAPSAMAPlugin.getPlugin().lastAutosensResult?.let {
+ openAPSAMAPlugin.lastAutosensResult?.let {
openapsma_autosensdata.text = JSONFormatter.format(it.json())
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java
index 49881c5158..cea65a14d9 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java
@@ -1,28 +1,33 @@
package info.nightscout.androidaps.plugins.aps.openAPSAMA;
-import org.json.JSONException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import android.content.Context;
-import info.nightscout.androidaps.MainApp;
+import org.json.JSONException;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.interfaces.APSInterface;
+import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpInterface;
-import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.logging.AAPSLogger;
+import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.aps.loop.APSResult;
import info.nightscout.androidaps.plugins.aps.loop.ScriptReader;
-import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui;
-import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateResultGui;
-import info.nightscout.androidaps.plugins.bus.RxBus;
-import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
-import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
+import info.nightscout.androidaps.plugins.aps.events.EventOpenAPSUpdateGui;
+import info.nightscout.androidaps.plugins.aps.events.EventOpenAPSUpdateResultGui;
+import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
+import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker;
+import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus;
@@ -33,21 +38,20 @@ import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.HardLimits;
import info.nightscout.androidaps.utils.Profiler;
import info.nightscout.androidaps.utils.Round;
+import info.nightscout.androidaps.utils.resources.ResourceHelper;
-/**
- * Created by mike on 05.08.2016.
- */
+@Singleton
public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
- private static Logger log = LoggerFactory.getLogger(L.APS);
-
- private static OpenAPSAMAPlugin openAPSAMAPlugin;
-
- public static OpenAPSAMAPlugin getPlugin() {
- if (openAPSAMAPlugin == null) {
- openAPSAMAPlugin = new OpenAPSAMAPlugin();
- }
- return openAPSAMAPlugin;
- }
+ private final AAPSLogger aapsLogger;
+ private final RxBusWrapper rxBus;
+ private final ConstraintChecker constraintChecker;
+ private final ResourceHelper resourceHelper;
+ private final ProfileFunction profileFunction;
+ private final Context context;
+ private final ActivePluginProvider activePlugin;
+ private final TreatmentsPlugin treatmentsPlugin;
+ private final IobCobCalculatorPlugin iobCobCalculatorPlugin;
+ private final HardLimits hardLimits;
// last values
DetermineBasalAdapterAMAJS lastDetermineBasalAdapterAMAJS = null;
@@ -55,27 +59,56 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
DetermineBasalResultAMA lastAPSResult = null;
AutosensResult lastAutosensResult = null;
- private OpenAPSAMAPlugin() {
+ @Inject
+ public OpenAPSAMAPlugin(
+ HasAndroidInjector injector,
+ AAPSLogger aapsLogger,
+ RxBusWrapper rxBus,
+ ConstraintChecker constraintChecker,
+ ResourceHelper resourceHelper,
+ ProfileFunction profileFunction,
+ Context context,
+ ActivePluginProvider activePlugin,
+ TreatmentsPlugin treatmentsPlugin,
+ IobCobCalculatorPlugin iobCobCalculatorPlugin,
+ HardLimits hardLimits
+ ) {
super(new PluginDescription()
- .mainType(PluginType.APS)
- .fragmentClass(OpenAPSAMAFragment.class.getName())
- .pluginName(R.string.openapsama)
- .shortName(R.string.oaps_shortname)
- .preferencesId(R.xml.pref_openapsama)
- .description(R.string.description_ama)
+ .mainType(PluginType.APS)
+ .fragmentClass(OpenAPSAMAFragment.class.getName())
+ .pluginName(R.string.openapsama)
+ .shortName(R.string.oaps_shortname)
+ .preferencesId(R.xml.pref_openapsama)
+ .description(R.string.description_ama),
+ aapsLogger, resourceHelper, injector
);
+ this.aapsLogger = aapsLogger;
+ this.rxBus = rxBus;
+ this.constraintChecker = constraintChecker;
+ this.resourceHelper = resourceHelper;
+ this.profileFunction = profileFunction;
+ this.context = context;
+ this.activePlugin = activePlugin;
+ this.treatmentsPlugin = treatmentsPlugin;
+ this.iobCobCalculatorPlugin = iobCobCalculatorPlugin;
+ this.hardLimits = hardLimits;
}
@Override
public boolean specialEnableCondition() {
- PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
- return pump == null || pump.getPumpDescription().isTempBasalCapable;
+ try {
+ PumpInterface pump = activePlugin.getActivePump();
+ return pump.getPumpDescription().isTempBasalCapable;
+ } catch (Exception ignored) {
+ // may fail during initialization
+ return true;
+ }
}
@Override
public boolean specialShowInListCondition() {
- PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
- return pump == null || pump.getPumpDescription().isTempBasalCapable;
+ PumpInterface pump = activePlugin.getActivePump();
+ return pump.getPumpDescription().isTempBasalCapable;
}
@Override
@@ -90,45 +123,34 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
@Override
public void invoke(String initiator, boolean tempBasalFallback) {
- if (L.isEnabled(L.APS))
- log.debug("invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback);
+ aapsLogger.debug(LTag.APS, "invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback);
lastAPSResult = null;
DetermineBasalAdapterAMAJS determineBasalAdapterAMAJS;
- determineBasalAdapterAMAJS = new DetermineBasalAdapterAMAJS(new ScriptReader(MainApp.instance().getBaseContext()));
+ determineBasalAdapterAMAJS = new DetermineBasalAdapterAMAJS(new ScriptReader(context), getInjector());
- GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData();
- Profile profile = ProfileFunctions.getInstance().getProfile();
- PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
+ GlucoseStatus glucoseStatus = new GlucoseStatus(getInjector()).getGlucoseStatusData();
+ Profile profile = profileFunction.getProfile();
+ PumpInterface pump = activePlugin.getActivePump();
if (profile == null) {
- RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.noprofileselected)));
- if (L.isEnabled(L.APS))
- log.debug(MainApp.gs(R.string.noprofileselected));
- return;
- }
-
- if (pump == null) {
- RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.nopumpselected)));
- if (L.isEnabled(L.APS))
- log.debug(MainApp.gs(R.string.nopumpselected));
+ rxBus.send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.noprofileselected)));
+ aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.noprofileselected));
return;
}
if (!isEnabled(PluginType.APS)) {
- RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_disabled)));
- if (L.isEnabled(L.APS))
- log.debug(MainApp.gs(R.string.openapsma_disabled));
+ rxBus.send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openapsma_disabled)));
+ aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.openapsma_disabled));
return;
}
if (glucoseStatus == null) {
- RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_noglucosedata)));
- if (L.isEnabled(L.APS))
- log.debug(MainApp.gs(R.string.openapsma_noglucosedata));
+ rxBus.send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openapsma_noglucosedata)));
+ aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.openapsma_noglucosedata));
return;
}
- double maxBasal = MainApp.getConstraintChecker().getMaxBasalAllowed(profile).value();
+ double maxBasal = constraintChecker.getMaxBasalAllowed(profile).value();
double minBg = profile.getTargetLowMgdl();
double maxBg = profile.getTargetHighMgdl();
double targetBg = profile.getTargetMgdl();
@@ -138,47 +160,45 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
long start = System.currentTimeMillis();
long startPart = System.currentTimeMillis();
- IobTotal[] iobArray = IobCobCalculatorPlugin.getPlugin().calculateIobArrayInDia(profile);
- if (L.isEnabled(L.APS))
- Profiler.log(log, "calculateIobArrayInDia()", startPart);
+ IobTotal[] iobArray = iobCobCalculatorPlugin.calculateIobArrayInDia(profile);
+ Profiler.log(aapsLogger, LTag.APS, "calculateIobArrayInDia()", startPart);
startPart = System.currentTimeMillis();
- MealData mealData = TreatmentsPlugin.getPlugin().getMealData();
- if (L.isEnabled(L.APS))
- Profiler.log(log, "getMealData()", startPart);
+ MealData mealData = iobCobCalculatorPlugin.getMealData();
+ Profiler.log(aapsLogger, LTag.APS, "getMealData()", startPart);
- double maxIob = MainApp.getConstraintChecker().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]);
- maxBg = HardLimits.verifyHardLimits(maxBg, "maxBg", HardLimits.VERY_HARD_LIMIT_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_MAX_BG[1]);
- targetBg = HardLimits.verifyHardLimits(targetBg, "targetBg", HardLimits.VERY_HARD_LIMIT_TARGET_BG[0], HardLimits.VERY_HARD_LIMIT_TARGET_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.getVERY_HARD_LIMIT_MAX_BG()[0], hardLimits.getVERY_HARD_LIMIT_MAX_BG()[1]);
+ targetBg = hardLimits.verifyHardLimits(targetBg, "targetBg", hardLimits.getVERY_HARD_LIMIT_TARGET_BG()[0], hardLimits.getVERY_HARD_LIMIT_TARGET_BG()[1]);
boolean isTempTarget = false;
- TempTarget tempTarget = TreatmentsPlugin.getPlugin().getTempTargetFromHistory(System.currentTimeMillis());
+ TempTarget tempTarget = treatmentsPlugin.getTempTargetFromHistory(System.currentTimeMillis());
if (tempTarget != null) {
isTempTarget = true;
- minBg = HardLimits.verifyHardLimits(tempTarget.low, "minBg", HardLimits.VERY_HARD_LIMIT_TEMP_MIN_BG[0], HardLimits.VERY_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]);
- targetBg = HardLimits.verifyHardLimits(tempTarget.target(), "targetBg", HardLimits.VERY_HARD_LIMIT_TEMP_TARGET_BG[0], HardLimits.VERY_HARD_LIMIT_TEMP_TARGET_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.getVERY_HARD_LIMIT_TEMP_MAX_BG()[0], hardLimits.getVERY_HARD_LIMIT_TEMP_MAX_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;
- 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;
- if (!HardLimits.checkOnlyHardLimits(profile.getIsfMgdl(), "sens", HardLimits.MINISF, HardLimits.MAXISF))
+ if (!hardLimits.checkOnlyHardLimits(profile.getIsfMgdl(), "sens", hardLimits.getMINISF(), hardLimits.getMAXISF()))
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;
- if (!HardLimits.checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, HardLimits.maxBasal()))
+ if (!hardLimits.checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, hardLimits.maxBasal()))
return;
startPart = System.currentTimeMillis();
- if (MainApp.getConstraintChecker().isAutosensModeEnabled().value()) {
- AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getLastAutosensDataSynchronized("OpenAPSPlugin");
+ if (constraintChecker.isAutosensModeEnabled().value()) {
+ AutosensData autosensData = iobCobCalculatorPlugin.getLastAutosensDataSynchronized("OpenAPSPlugin");
if (autosensData == null) {
- RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openaps_noasdata)));
+ rxBus.send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openaps_noasdata)));
return;
}
lastAutosensResult = autosensData.autosensResult;
@@ -186,36 +206,32 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
lastAutosensResult = new AutosensResult();
lastAutosensResult.sensResult = "autosens disabled";
}
- if (L.isEnabled(L.APS))
- Profiler.log(log, "detectSensitivityandCarbAbsorption()", startPart);
- if (L.isEnabled(L.APS))
- Profiler.log(log, "AMA data gathering", start);
+ Profiler.log(aapsLogger, LTag.APS, "detectSensitivityandCarbAbsorption()", startPart);
+ Profiler.log(aapsLogger, LTag.APS, "AMA data gathering", start);
start = System.currentTimeMillis();
try {
- determineBasalAdapterAMAJS.setData(profile, maxIob, maxBasal, minBg, maxBg, targetBg, ConfigBuilderPlugin.getPlugin().getActivePump().getBaseBasalRate(), iobArray, glucoseStatus, mealData,
+ determineBasalAdapterAMAJS.setData(profile, maxIob, maxBasal, minBg, maxBg, targetBg, activePlugin.getActivePump().getBaseBasalRate(), iobArray, glucoseStatus, mealData,
lastAutosensResult.ratio, //autosensDataRatio
isTempTarget
);
} catch (JSONException e) {
- FabricPrivacy.logException(e);
+ FabricPrivacy.getInstance().logException(e);
return;
}
DetermineBasalResultAMA determineBasalResultAMA = determineBasalAdapterAMAJS.invoke();
- if (L.isEnabled(L.APS))
- Profiler.log(log, "AMA calculation", start);
+ Profiler.log(aapsLogger, LTag.APS, "AMA calculation", start);
// Fix bug determine basal
if (determineBasalResultAMA == null) {
- if (L.isEnabled(L.APS))
- log.error("SMB calculation returned null");
+ aapsLogger.error(LTag.APS, "SMB calculation returned null");
lastDetermineBasalAdapterAMAJS = null;
lastAPSResult = null;
lastAPSRun = 0;
} else {
- if (determineBasalResultAMA.rate == 0d && determineBasalResultAMA.duration == 0 && !TreatmentsPlugin.getPlugin().isTempBasalInProgress())
+ if (determineBasalResultAMA.rate == 0d && determineBasalResultAMA.duration == 0 && !treatmentsPlugin.isTempBasalInProgress())
determineBasalResultAMA.tempBasalRequested = false;
determineBasalResultAMA.iob = iobArray[0];
@@ -225,14 +241,14 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
try {
determineBasalResultAMA.json.put("timestamp", DateUtil.toISOString(now));
} catch (JSONException e) {
- log.error("Unhandled exception", e);
+ aapsLogger.error(LTag.APS, "Unhandled exception", e);
}
lastDetermineBasalAdapterAMAJS = determineBasalAdapterAMAJS;
lastAPSResult = determineBasalResultAMA;
lastAPSRun = now;
}
- RxBus.INSTANCE.send(new EventOpenAPSUpdateGui());
+ rxBus.send(new EventOpenAPSUpdateGui());
//deviceStatus.suggested = determineBasalResultAMA.json;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/DetermineBasalAdapterMAJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/DetermineBasalAdapterMAJS.java
deleted file mode 100644
index dbc7782ab3..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/DetermineBasalAdapterMAJS.java
+++ /dev/null
@@ -1,225 +0,0 @@
-package info.nightscout.androidaps.plugins.aps.openAPSMA;
-
-import org.json.JSONException;
-import org.json.JSONObject;
-import org.mozilla.javascript.Context;
-import org.mozilla.javascript.Function;
-import org.mozilla.javascript.NativeJSON;
-import org.mozilla.javascript.NativeObject;
-import org.mozilla.javascript.RhinoException;
-import org.mozilla.javascript.Scriptable;
-import org.mozilla.javascript.ScriptableObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.IOException;
-import java.lang.reflect.InvocationTargetException;
-import java.nio.charset.StandardCharsets;
-
-import javax.annotation.Nullable;
-
-import info.nightscout.androidaps.Constants;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
-import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus;
-import info.nightscout.androidaps.data.IobTotal;
-import info.nightscout.androidaps.data.MealData;
-import info.nightscout.androidaps.data.Profile;
-import info.nightscout.androidaps.db.TemporaryBasal;
-import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.aps.loop.ScriptReader;
-import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
-import info.nightscout.androidaps.utils.SP;
-
-public class DetermineBasalAdapterMAJS {
- private static Logger log = LoggerFactory.getLogger(L.APS);
-
- private ScriptReader mScriptReader;
- private JSONObject mProfile;
- private JSONObject mGlucoseStatus;
- private JSONObject mIobData;
- private JSONObject mMealData;
- private JSONObject mCurrentTemp;
-
- private String storedCurrentTemp = null;
- private String storedIobData = null;
- private String storedGlucoseStatus = null;
- private String storedProfile = null;
- private String storedMeal_data = null;
-
- DetermineBasalAdapterMAJS(ScriptReader scriptReader) {
- mScriptReader = scriptReader;
- }
-
- @Nullable
- public DetermineBasalResultMA invoke() {
- DetermineBasalResultMA determineBasalResultMA = null;
-
- Context rhino = Context.enter();
- Scriptable scope = rhino.initStandardObjects();
- // Turn off optimization to make Rhino Android compatible
- rhino.setOptimizationLevel(-1);
-
- try {
-
- //register logger callback for console.log and console.error
- ScriptableObject.defineClass(scope, LoggerCallback.class);
- Scriptable myLogger = rhino.newObject(scope, "LoggerCallback", null);
- scope.put("console", scope, myLogger);
-
- //set module parent
- rhino.evaluateString(scope, "var module = {\"parent\":Boolean(1)};", "JavaScript", 0, null);
-
- //generate functions "determine_basal" and "setTempBasal"
- rhino.evaluateString(scope, readFile("OpenAPSMA/determine-basal.js"), "JavaScript", 0, null);
-
- String setTempBasalCode = "var setTempBasal = function (rate, duration, profile, rT, offline) {" +
- "rT.duration = duration;\n" +
- " rT.rate = rate;" +
- "return rT;" +
- "};";
- rhino.evaluateString(scope, setTempBasalCode, "setTempBasal.js", 0, null);
- Object determineBasalObj = scope.get("determine_basal", scope);
- Object setTempBasalObj = scope.get("setTempBasal", scope);
-
- //call determine-basal
- if (determineBasalObj instanceof Function && setTempBasalObj instanceof Function) {
- Function determineBasalJS = (Function) determineBasalObj;
- Function setTempBasalJS = (Function) setTempBasalObj;
-
- //prepare parameters
- Object[] params = new Object[]{
- makeParam(mGlucoseStatus, rhino, scope),
- makeParam(mCurrentTemp, rhino, scope),
- makeParam(mIobData, rhino, scope),
- makeParam(mProfile, rhino, scope),
- "undefined",
- makeParam(mMealData, rhino, scope),
- setTempBasalJS};
-
- NativeObject jsResult = (NativeObject) determineBasalJS.call(rhino, scope, scope, params);
-
- // Parse the jsResult object to a JSON-String
- String result = NativeJSON.stringify(rhino, scope, jsResult, null, null).toString();
- if (L.isEnabled(L.APS))
- log.debug("Result: " + result);
- try {
- determineBasalResultMA = new DetermineBasalResultMA(jsResult, new JSONObject(result));
- } catch (JSONException e) {
- log.error("Unhandled exception", e);
- }
- } else {
- log.debug("Problem loading JS Functions");
- }
- } catch (IOException e) {
- log.error("IOException");
- } catch (RhinoException e) {
- log.error("RhinoException: (" + e.lineNumber() + "," + e.columnNumber() + ") " + e.toString());
- } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
- log.error(e.toString());
- } finally {
- Context.exit();
- }
-
- storedGlucoseStatus = mGlucoseStatus.toString();
- storedIobData = mIobData.toString();
- storedCurrentTemp = mCurrentTemp.toString();
- storedProfile = mProfile.toString();
- storedMeal_data = mMealData.toString();
-
- return determineBasalResultMA;
- }
-
- String getGlucoseStatusParam() {
- return storedGlucoseStatus;
- }
-
- String getCurrentTempParam() {
- return storedCurrentTemp;
- }
-
- String getIobDataParam() {
- return storedIobData;
- }
-
- String getProfileParam() {
- return storedProfile;
- }
-
- String getMealDataParam() {
- return storedMeal_data;
- }
-
- public void setData(Profile profile,
- double maxIob,
- double maxBasal,
- double minBg,
- double maxBg,
- double targetBg,
- double basalRate,
- IobTotal iobData,
- GlucoseStatus glucoseStatus,
- MealData mealData) throws JSONException {
-
- mProfile = new JSONObject();
- mProfile.put("max_iob", maxIob);
- mProfile.put("dia", Math.min(profile.getDia(), 3d));
- mProfile.put("type", "current");
- mProfile.put("max_daily_basal", profile.getMaxDailyBasal());
- mProfile.put("max_basal", maxBasal);
- mProfile.put("min_bg", minBg);
- mProfile.put("max_bg", maxBg);
- mProfile.put("target_bg", targetBg);
- mProfile.put("carb_ratio", profile.getIc());
- mProfile.put("sens", profile.getIsfMgdl());
-
- mProfile.put("current_basal", basalRate);
-
- if (ProfileFunctions.getSystemUnits().equals(Constants.MMOL)) {
- mProfile.put("out_units", "mmol/L");
- }
-
- long now = System.currentTimeMillis();
- TemporaryBasal tb = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now);
-
- mCurrentTemp = new JSONObject();
- mCurrentTemp.put("duration", tb != null ? tb.getPlannedRemainingMinutes() : 0);
- mCurrentTemp.put("rate", tb != null ? tb.tempBasalConvertedToAbsolute(now, profile) : 0d);
-
- mIobData = new JSONObject();
- mIobData.put("iob", iobData.iob); //netIob
- mIobData.put("activity", iobData.activity); //netActivity
- mIobData.put("bolussnooze", iobData.bolussnooze); //bolusIob
- mIobData.put("basaliob", iobData.basaliob);
- mIobData.put("netbasalinsulin", iobData.netbasalinsulin);
- mIobData.put("hightempinsulin", iobData.hightempinsulin);
-
- mGlucoseStatus = new JSONObject();
- mGlucoseStatus.put("glucose", glucoseStatus.glucose);
- if (SP.getBoolean(R.string.key_always_use_shortavg, false)) {
- mGlucoseStatus.put("delta", glucoseStatus.short_avgdelta);
- } else {
- mGlucoseStatus.put("delta", glucoseStatus.delta);
- }
- mGlucoseStatus.put("avgdelta", glucoseStatus.avgdelta);
-
- mMealData = new JSONObject();
- mMealData.put("carbs", mealData.carbs);
- mMealData.put("boluses", mealData.boluses);
- }
-
- private String readFile(String filename) throws IOException {
- byte[] bytes = mScriptReader.readFile(filename);
- String string = new String(bytes, StandardCharsets.UTF_8);
- if (string.startsWith("#!/usr/bin/env node")) {
- string = string.substring(20);
- }
- return string;
- }
-
- private Object makeParam(JSONObject jsonObject, Context rhino, Scriptable scope) {
- Object param = NativeJSON.parse(rhino, scope, jsonObject.toString(), (context, scriptable, scriptable1, objects) -> objects[1]);
- return param;
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/DetermineBasalResultMA.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/DetermineBasalResultMA.java
deleted file mode 100644
index bbbcf7f893..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/DetermineBasalResultMA.java
+++ /dev/null
@@ -1,77 +0,0 @@
-package info.nightscout.androidaps.plugins.aps.openAPSMA;
-
-import org.json.JSONException;
-import org.json.JSONObject;
-import org.mozilla.javascript.NativeObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.aps.loop.APSResult;
-
-public class DetermineBasalResultMA extends APSResult {
- private static Logger log = LoggerFactory.getLogger(L.APS);
-
- private double eventualBG;
- private double snoozeBG;
- private String mealAssist;
-
- DetermineBasalResultMA(NativeObject result, JSONObject j) {
- json = j;
- if (result.containsKey("error")) {
- reason = (String) result.get("error");
- tempBasalRequested = false;
- rate = -1;
- duration = -1;
- mealAssist = "";
- } else {
- reason = result.get("reason").toString();
- eventualBG = (Double) result.get("eventualBG");
- snoozeBG = (Double) result.get("snoozeBG");
- if (result.containsKey("rate")) {
- rate = (Double) result.get("rate");
- if (rate < 0d) rate = 0d;
- tempBasalRequested = true;
- } else {
- rate = -1;
- tempBasalRequested = false;
- }
- if (result.containsKey("duration")) {
- duration = ((Double) result.get("duration")).intValue();
- //changeRequested as above
- } else {
- duration = -1;
- tempBasalRequested = false;
- }
- if (result.containsKey("mealAssist")) {
- mealAssist = result.get("mealAssist").toString();
- } else mealAssist = "";
- }
- }
-
- private DetermineBasalResultMA() {
- }
-
- @Override
- public DetermineBasalResultMA clone() {
- DetermineBasalResultMA newResult = new DetermineBasalResultMA();
- doClone(newResult);
-
- newResult.eventualBG = eventualBG;
- newResult.snoozeBG = snoozeBG;
- newResult.mealAssist = mealAssist;
- return newResult;
- }
-
- @Override
- public JSONObject json() {
- try {
- JSONObject ret = new JSONObject(this.json.toString());
- return ret;
- } catch (JSONException e) {
- log.error("Unhandled exception", e);
- }
- return null;
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAFragment.kt
deleted file mode 100644
index 1b72f57365..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAFragment.kt
+++ /dev/null
@@ -1,100 +0,0 @@
-package info.nightscout.androidaps.plugins.aps.openAPSMA
-
-import android.os.Bundle
-import android.view.LayoutInflater
-import android.view.View
-import android.view.ViewGroup
-import androidx.fragment.app.Fragment
-import info.nightscout.androidaps.R
-import info.nightscout.androidaps.logging.L
-import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui
-import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateResultGui
-import info.nightscout.androidaps.plugins.bus.RxBus
-import info.nightscout.androidaps.utils.DateUtil
-import info.nightscout.androidaps.utils.FabricPrivacy
-import info.nightscout.androidaps.utils.JSONFormatter
-import info.nightscout.androidaps.utils.plusAssign
-import io.reactivex.android.schedulers.AndroidSchedulers
-import io.reactivex.disposables.CompositeDisposable
-import kotlinx.android.synthetic.main.openapsama_fragment.*
-import org.slf4j.LoggerFactory
-
-class OpenAPSMAFragment : Fragment() {
- private val log = LoggerFactory.getLogger(L.APS)
- private var disposable: CompositeDisposable = CompositeDisposable()
-
- override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
- savedInstanceState: Bundle?): View? {
- return inflater.inflate(R.layout.openapsma_fragment, container, false)
- }
-
- override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
- super.onViewCreated(view, savedInstanceState)
-
- openapsma_run.setOnClickListener {
- OpenAPSMAPlugin.getPlugin().invoke("OpenAPSMA button", false)
- }
-
- }
-
- @Synchronized
- override fun onResume() {
- super.onResume()
-
- disposable += RxBus
- .toObservable(EventOpenAPSUpdateGui::class.java)
- .observeOn(AndroidSchedulers.mainThread())
- .subscribe({
- updateGUI()
- }, {
- FabricPrivacy.logException(it)
- })
- disposable += RxBus
- .toObservable(EventOpenAPSUpdateResultGui::class.java)
- .observeOn(AndroidSchedulers.mainThread())
- .subscribe({
- updateResultGUI(it.text)
- }, {
- FabricPrivacy.logException(it)
- })
- updateGUI()
- }
-
- @Synchronized
- override fun onPause() {
- super.onPause()
- disposable.clear()
- }
-
- @Synchronized
- private fun updateGUI() {
- if (openapsma_result == null) return
- OpenAPSMAPlugin.getPlugin().lastAPSResult?.let { lastAPSResult ->
- openapsma_result.text = JSONFormatter.format(lastAPSResult.json)
- openapsma_request.text = lastAPSResult.toSpanned()
- }
- OpenAPSMAPlugin.getPlugin().lastDetermineBasalAdapterMAJS?.let { determineBasalAdapterMAJS ->
- openapsma_glucosestatus.text = JSONFormatter.format(determineBasalAdapterMAJS.glucoseStatusParam)
- openapsma_currenttemp.text = JSONFormatter.format(determineBasalAdapterMAJS.currentTempParam)
- openapsma_iobdata.text = JSONFormatter.format(determineBasalAdapterMAJS.iobDataParam)
- openapsma_profile.text = JSONFormatter.format(determineBasalAdapterMAJS.profileParam)
- openapsma_mealdata.text = JSONFormatter.format(determineBasalAdapterMAJS.mealDataParam)
- }
- if (OpenAPSMAPlugin.getPlugin().lastAPSRun != 0L) {
- openapsma_lastrun.text = DateUtil.dateAndTimeString(OpenAPSMAPlugin.getPlugin().lastAPSRun)
- }
- }
-
- @Synchronized
- private fun updateResultGUI(text: String) {
- if (openapsma_result == null) return
- openapsma_result.text = text
- openapsma_glucosestatus.text = ""
- openapsma_currenttemp.text = ""
- openapsma_iobdata.text = ""
- openapsma_profile.text = ""
- openapsma_mealdata.text = ""
- openapsma_request.text = ""
- openapsma_lastrun.text = ""
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java
deleted file mode 100644
index 0380156c74..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java
+++ /dev/null
@@ -1,216 +0,0 @@
-package info.nightscout.androidaps.plugins.aps.openAPSMA;
-
-import org.json.JSONException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.IobTotal;
-import info.nightscout.androidaps.data.MealData;
-import info.nightscout.androidaps.data.Profile;
-import info.nightscout.androidaps.db.TempTarget;
-import info.nightscout.androidaps.interfaces.APSInterface;
-import info.nightscout.androidaps.interfaces.PluginBase;
-import info.nightscout.androidaps.interfaces.PluginDescription;
-import info.nightscout.androidaps.interfaces.PluginType;
-import info.nightscout.androidaps.interfaces.PumpInterface;
-import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.aps.loop.APSResult;
-import info.nightscout.androidaps.plugins.aps.loop.ScriptReader;
-import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui;
-import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateResultGui;
-import info.nightscout.androidaps.plugins.bus.RxBus;
-import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
-import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
-import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus;
-import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
-import info.nightscout.androidaps.utils.DateUtil;
-import info.nightscout.androidaps.utils.FabricPrivacy;
-import info.nightscout.androidaps.utils.HardLimits;
-import info.nightscout.androidaps.utils.Profiler;
-import info.nightscout.androidaps.utils.Round;
-
-import static info.nightscout.androidaps.utils.HardLimits.checkOnlyHardLimits;
-import static info.nightscout.androidaps.utils.HardLimits.verifyHardLimits;
-
-/**
- * Created by mike on 05.08.2016.
- */
-public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
- private static Logger log = LoggerFactory.getLogger(L.APS);
-
- private static OpenAPSMAPlugin openAPSMAPlugin;
-
- public static OpenAPSMAPlugin getPlugin() {
- if (openAPSMAPlugin == null) {
- openAPSMAPlugin = new OpenAPSMAPlugin();
- }
- return openAPSMAPlugin;
- }
-
- // last values
- DetermineBasalAdapterMAJS lastDetermineBasalAdapterMAJS = null;
- long lastAPSRun = 0;
- DetermineBasalResultMA lastAPSResult = null;
-
- private OpenAPSMAPlugin() {
- super(new PluginDescription()
- .mainType(PluginType.APS)
- .fragmentClass(OpenAPSMAFragment.class.getName())
- .pluginName(R.string.openapsma)
- .shortName(R.string.oaps_shortname)
- .preferencesId(R.xml.pref_openapsma)
- .description(R.string.description_ma)
- );
- }
-
- @Override
- public boolean specialEnableCondition() {
- PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
- return pump == null || pump.getPumpDescription().isTempBasalCapable;
- }
-
- @Override
- public boolean specialShowInListCondition() {
- PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
- return pump == null || pump.getPumpDescription().isTempBasalCapable;
- }
-
- @Override
- public APSResult getLastAPSResult() {
- return lastAPSResult;
- }
-
- @Override
- public long getLastAPSRun() {
- return lastAPSRun;
- }
-
- @Override
- public void invoke(String initiator, boolean tempBasalFallback) {
- if (L.isEnabled(L.APS))
- log.debug("invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback);
- lastAPSResult = null;
- DetermineBasalAdapterMAJS determineBasalAdapterMAJS;
- determineBasalAdapterMAJS = new DetermineBasalAdapterMAJS(new ScriptReader(MainApp.instance().getBaseContext()));
-
- GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData();
- Profile profile = ProfileFunctions.getInstance().getProfile();
- PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
-
- if (profile == null) {
- RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.noprofileselected)));
- if (L.isEnabled(L.APS))
- log.debug(MainApp.gs(R.string.noprofileselected));
- return;
- }
-
- if (pump == null) {
- RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.nopumpselected)));
- if (L.isEnabled(L.APS))
- log.debug(MainApp.gs(R.string.nopumpselected));
- return;
- }
-
- if (!isEnabled(PluginType.APS)) {
- RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_disabled)));
- if (L.isEnabled(L.APS))
- log.debug(MainApp.gs(R.string.openapsma_disabled));
- return;
- }
-
- if (glucoseStatus == null) {
- RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_noglucosedata)));
- if (L.isEnabled(L.APS))
- log.debug(MainApp.gs(R.string.openapsma_noglucosedata));
- return;
- }
-
- double maxBasal = MainApp.getConstraintChecker().getMaxBasalAllowed(profile).value();
-
- double minBg = profile.getTargetLowMgdl();
- double maxBg = profile.getTargetHighMgdl();
- double targetBg = profile.getTargetMgdl();
-
- minBg = Round.roundTo(minBg, 0.1d);
- maxBg = Round.roundTo(maxBg, 0.1d);
-
- long start = System.currentTimeMillis();
- TreatmentsPlugin.getPlugin().updateTotalIOBTreatments();
- TreatmentsPlugin.getPlugin().updateTotalIOBTempBasals();
- IobTotal bolusIob = TreatmentsPlugin.getPlugin().getLastCalculationTreatments();
- IobTotal basalIob = TreatmentsPlugin.getPlugin().getLastCalculationTempBasals();
-
- IobTotal iobTotal = IobTotal.combine(bolusIob, basalIob).round();
-
- MealData mealData = TreatmentsPlugin.getPlugin().getMealData();
-
- double maxIob = MainApp.getConstraintChecker().getMaxIOBAllowed().value();
- if (L.isEnabled(L.APS))
- Profiler.log(log, "MA data gathering", start);
-
- minBg = verifyHardLimits(minBg, "minBg", HardLimits.VERY_HARD_LIMIT_MIN_BG[0], HardLimits.VERY_HARD_LIMIT_MIN_BG[1]);
- maxBg = verifyHardLimits(maxBg, "maxBg", HardLimits.VERY_HARD_LIMIT_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_MAX_BG[1]);
- targetBg = verifyHardLimits(targetBg, "targetBg", HardLimits.VERY_HARD_LIMIT_TARGET_BG[0], HardLimits.VERY_HARD_LIMIT_TARGET_BG[1]);
-
- TempTarget tempTarget = TreatmentsPlugin.getPlugin().getTempTargetFromHistory(System.currentTimeMillis());
- if (tempTarget != null) {
- minBg = verifyHardLimits(tempTarget.low, "minBg", HardLimits.VERY_HARD_LIMIT_TEMP_MIN_BG[0], HardLimits.VERY_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]);
- targetBg = verifyHardLimits(tempTarget.target(), "targetBg", HardLimits.VERY_HARD_LIMIT_TEMP_TARGET_BG[0], HardLimits.VERY_HARD_LIMIT_TEMP_TARGET_BG[1]);
- }
-
- if (!checkOnlyHardLimits(profile.getDia(), "dia", HardLimits.MINDIA, HardLimits.MAXDIA))
- return;
- if (!checkOnlyHardLimits(profile.getIcTimeFromMidnight(Profile.secondsFromMidnight()), "carbratio", HardLimits.MINIC, HardLimits.MAXIC))
- return;
- if (!checkOnlyHardLimits(profile.getIsfMgdl(), "sens", HardLimits.MINISF, HardLimits.MAXISF))
- return;
- if (!checkOnlyHardLimits(profile.getMaxDailyBasal(), "max_daily_basal", 0.02, HardLimits.maxBasal()))
- return;
- if (!checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, HardLimits.maxBasal()))
- return;
-
- start = System.currentTimeMillis();
- try {
- determineBasalAdapterMAJS.setData(profile, maxIob, maxBasal, minBg, maxBg, targetBg, ConfigBuilderPlugin.getPlugin().getActivePump().getBaseBasalRate(), iobTotal, glucoseStatus, mealData);
- } catch (JSONException e) {
- FabricPrivacy.logException(e);
- return;
- }
- if (L.isEnabled(L.APS))
- Profiler.log(log, "MA calculation", start);
-
-
- long now = System.currentTimeMillis();
-
- DetermineBasalResultMA determineBasalResultMA = determineBasalAdapterMAJS.invoke();
- if (determineBasalResultMA == null) {
- if (L.isEnabled(L.APS))
- log.error("MA calculation returned null");
- lastDetermineBasalAdapterMAJS = null;
- lastAPSResult = null;
- lastAPSRun = 0;
- } else {
- // Fix bug determinef basal
- if (determineBasalResultMA.rate == 0d && determineBasalResultMA.duration == 0 && !TreatmentsPlugin.getPlugin().isTempBasalInProgress())
- determineBasalResultMA.tempBasalRequested = false;
-
- determineBasalResultMA.iob = iobTotal;
-
- try {
- determineBasalResultMA.json.put("timestamp", DateUtil.toISOString(now));
- } catch (JSONException e) {
- log.error("Unhandled exception", e);
- }
-
- lastDetermineBasalAdapterMAJS = determineBasalAdapterMAJS;
- lastAPSResult = determineBasalResultMA;
- lastAPSRun = now;
- }
- RxBus.INSTANCE.send(new EventOpenAPSUpdateGui());
- }
-
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java
index 76571176d3..4d3a0db704 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java
@@ -11,34 +11,46 @@ import org.mozilla.javascript.RhinoException;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.Undefined;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.StandardCharsets;
import javax.annotation.Nullable;
+import javax.inject.Inject;
+import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.Constants;
-import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
-import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.TemporaryBasal;
-import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
+import info.nightscout.androidaps.logging.AAPSLogger;
+import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.aps.loop.ScriptReader;
-import info.nightscout.androidaps.plugins.aps.openAPSMA.LoggerCallback;
+import info.nightscout.androidaps.plugins.aps.logger.LoggerCallback;
+import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker;
+import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction;
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus;
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
+import info.nightscout.androidaps.interfaces.ActivePluginProvider;
+
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
-import info.nightscout.androidaps.utils.SP;
import info.nightscout.androidaps.utils.SafeParse;
+import info.nightscout.androidaps.utils.resources.ResourceHelper;
+import info.nightscout.androidaps.utils.sharedPreferences.SP;
+
public class DetermineBasalAdapterSMBJS {
- private static Logger log = LoggerFactory.getLogger(L.APS);
+ private final HasAndroidInjector injector;
+ @Inject AAPSLogger aapsLogger;
+ @Inject ConstraintChecker constraintChecker;
+ @Inject SP sp;
+ @Inject ResourceHelper resourceHelper;
+ @Inject ProfileFunction profileFunction;
+ @Inject TreatmentsPlugin treatmentsPlugin;
+ @Inject ActivePluginProvider activePluginProvider;
private ScriptReader mScriptReader;
@@ -50,6 +62,7 @@ public class DetermineBasalAdapterSMBJS {
private JSONObject mAutosensData = null;
private boolean mMicrobolusAllowed;
private boolean mSMBAlwaysAllowed;
+ private long mCurrentTime;
private String storedCurrentTemp = null;
private String storedIobData = null;
@@ -60,6 +73,7 @@ public class DetermineBasalAdapterSMBJS {
private String storedAutosens_data = null;
private String storedMicroBolusAllowed = null;
private String storedSMBAlwaysAllowed = null;
+ private String storedCurrentTime = null;
private String scriptDebug = "";
@@ -67,8 +81,10 @@ public class DetermineBasalAdapterSMBJS {
* Main code
*/
- DetermineBasalAdapterSMBJS(ScriptReader scriptReader) {
+ DetermineBasalAdapterSMBJS(ScriptReader scriptReader, HasAndroidInjector injector) {
mScriptReader = scriptReader;
+ this.injector = injector;
+ injector.androidInjector().inject(this);
}
@@ -76,21 +92,21 @@ public class DetermineBasalAdapterSMBJS {
public DetermineBasalResultSMB invoke() {
- if (L.isEnabled(L.APS)) {
- log.debug(">>> Invoking detemine_basal <<<");
- log.debug("Glucose status: " + (storedGlucoseStatus = mGlucoseStatus.toString()));
- log.debug("IOB data: " + (storedIobData = mIobData.toString()));
- log.debug("Current temp: " + (storedCurrentTemp = mCurrentTemp.toString()));
- log.debug("Profile: " + (storedProfile = mProfile.toString()));
- log.debug("Meal data: " + (storedMeal_data = mMealData.toString()));
- if (mAutosensData != null)
- log.debug("Autosens data: " + (storedAutosens_data = mAutosensData.toString()));
- else
- log.debug("Autosens data: " + (storedAutosens_data = "undefined"));
- log.debug("Reservoir data: " + "undefined");
- log.debug("MicroBolusAllowed: " + (storedMicroBolusAllowed = "" + mMicrobolusAllowed));
- log.debug("SMBAlwaysAllowed: " + (storedSMBAlwaysAllowed = "" + mSMBAlwaysAllowed));
- }
+ aapsLogger.debug(LTag.APS, ">>> Invoking detemine_basal <<<");
+ aapsLogger.debug(LTag.APS, "Glucose status: " + (storedGlucoseStatus = mGlucoseStatus.toString()));
+ aapsLogger.debug(LTag.APS, "IOB data: " + (storedIobData = mIobData.toString()));
+ aapsLogger.debug(LTag.APS, "Current temp: " + (storedCurrentTemp = mCurrentTemp.toString()));
+ aapsLogger.debug(LTag.APS, "Profile: " + (storedProfile = mProfile.toString()));
+ aapsLogger.debug(LTag.APS, "Meal data: " + (storedMeal_data = mMealData.toString()));
+ if (mAutosensData != null)
+ aapsLogger.debug(LTag.APS, "Autosens data: " + (storedAutosens_data = mAutosensData.toString()));
+ else
+ aapsLogger.debug(LTag.APS, "Autosens data: " + (storedAutosens_data = "undefined"));
+ aapsLogger.debug(LTag.APS, "Reservoir data: " + "undefined");
+ aapsLogger.debug(LTag.APS, "MicroBolusAllowed: " + (storedMicroBolusAllowed = "" + mMicrobolusAllowed));
+ aapsLogger.debug(LTag.APS, "SMBAlwaysAllowed: " + (storedSMBAlwaysAllowed = "" + mSMBAlwaysAllowed));
+ aapsLogger.debug(LTag.APS, "CurrentTime: " + (storedCurrentTime = "" + mCurrentTime));
+
DetermineBasalResultSMB determineBasalResultSMB = null;
@@ -132,7 +148,8 @@ public class DetermineBasalAdapterSMBJS {
makeParam(mMealData, rhino, scope),
setTempBasalFunctionsObj,
new Boolean(mMicrobolusAllowed),
- makeParam(null, rhino, scope) // reservoir data as undefined
+ makeParam(null, rhino, scope), // reservoir data as undefined
+ new Long(mCurrentTime)
};
@@ -141,22 +158,21 @@ public class DetermineBasalAdapterSMBJS {
// Parse the jsResult object to a JSON-String
String result = NativeJSON.stringify(rhino, scope, jsResult, null, null).toString();
- if (L.isEnabled(L.APS))
- log.debug("Result: " + result);
+ aapsLogger.debug(LTag.APS, "Result: " + result);
try {
- determineBasalResultSMB = new DetermineBasalResultSMB(new JSONObject(result));
+ determineBasalResultSMB = new DetermineBasalResultSMB(injector, new JSONObject(result));
} catch (JSONException e) {
- log.error("Unhandled exception", e);
+ aapsLogger.error(LTag.APS, "Unhandled exception", e);
}
} else {
- log.error("Problem loading JS Functions");
+ aapsLogger.error(LTag.APS, "Problem loading JS Functions");
}
} catch (IOException e) {
- log.error("IOException");
+ aapsLogger.error(LTag.APS, "IOException");
} catch (RhinoException e) {
- log.error("RhinoException: (" + e.lineNumber() + "," + e.columnNumber() + ") " + e.toString());
+ aapsLogger.error(LTag.APS, "RhinoException: (" + e.lineNumber() + "," + e.columnNumber() + ") " + e.toString());
} catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
- log.error(e.toString());
+ aapsLogger.error(LTag.APS, e.toString());
} finally {
Context.exit();
}
@@ -220,6 +236,8 @@ public class DetermineBasalAdapterSMBJS {
boolean advancedFiltering
) throws JSONException {
+ String units = profile.getUnits();
+ Double pumpbolusstep = activePluginProvider.getActivePump().getPumpDescription().bolusStep;
mProfile = new JSONObject();
mProfile.put("max_iob", maxIob);
@@ -232,11 +250,10 @@ public class DetermineBasalAdapterSMBJS {
mProfile.put("target_bg", targetBg);
mProfile.put("carb_ratio", profile.getIc());
mProfile.put("sens", profile.getIsfMgdl());
- mProfile.put("max_daily_safety_multiplier", SP.getInt(R.string.key_openapsama_max_daily_safety_multiplier, 3));
- mProfile.put("current_basal_safety_multiplier", SP.getDouble(R.string.key_openapsama_current_basal_safety_multiplier, 4d));
+ mProfile.put("max_daily_safety_multiplier", sp.getInt(R.string.key_openapsama_max_daily_safety_multiplier, 3));
+ mProfile.put("current_basal_safety_multiplier", sp.getDouble(R.string.key_openapsama_current_basal_safety_multiplier, 4d));
- // TODO AS-FIX
- // mProfile.put("high_temptarget_raises_sensitivity", SP.getBoolean(R.string.key_high_temptarget_raises_sensitivity, SMBDefaults.high_temptarget_raises_sensitivity));
+ //mProfile.put("high_temptarget_raises_sensitivity", SP.getBoolean(R.string.key_high_temptarget_raises_sensitivity, SMBDefaults.high_temptarget_raises_sensitivity));
mProfile.put("high_temptarget_raises_sensitivity", false);
//mProfile.put("low_temptarget_lowers_sensitivity", SP.getBoolean(R.string.key_low_temptarget_lowers_sensitivity, SMBDefaults.low_temptarget_lowers_sensitivity));
mProfile.put("low_temptarget_lowers_sensitivity", false);
@@ -259,26 +276,30 @@ public class DetermineBasalAdapterSMBJS {
mProfile.put("enableUAM", uamAllowed);
mProfile.put("A52_risk_enable", SMBDefaults.A52_risk_enable);
- boolean smbEnabled = SP.getBoolean(MainApp.gs(R.string.key_use_smb), false);
- mProfile.put("enableSMB_with_COB", smbEnabled && SP.getBoolean(R.string.key_enableSMB_with_COB, false));
- mProfile.put("enableSMB_with_temptarget", smbEnabled && SP.getBoolean(R.string.key_enableSMB_with_temptarget, false));
- mProfile.put("allowSMB_with_high_temptarget", smbEnabled && SP.getBoolean(R.string.key_allowSMB_with_high_temptarget, false));
- mProfile.put("enableSMB_always", smbEnabled && SP.getBoolean(R.string.key_enableSMB_always, false) && advancedFiltering);
- mProfile.put("enableSMB_after_carbs", smbEnabled && SP.getBoolean(R.string.key_enableSMB_after_carbs, false) && advancedFiltering);
- mProfile.put("maxSMBBasalMinutes", SP.getInt(R.string.key_smbmaxminutes, SMBDefaults.maxSMBBasalMinutes));
- mProfile.put("carbsReqThreshold", SMBDefaults.carbsReqThreshold);
+ boolean smbEnabled = sp.getBoolean(resourceHelper.gs(R.string.key_use_smb), false);
+ mProfile.put("SMBInterval", sp.getInt("key_smbinterval", SMBDefaults.SMBInterval));
+ mProfile.put("enableSMB_with_COB", smbEnabled && sp.getBoolean(R.string.key_enableSMB_with_COB, false));
+ mProfile.put("enableSMB_with_temptarget", smbEnabled && sp.getBoolean(R.string.key_enableSMB_with_temptarget, false));
+ mProfile.put("allowSMB_with_high_temptarget", smbEnabled && sp.getBoolean(R.string.key_allowSMB_with_high_temptarget, false));
+ mProfile.put("enableSMB_always", smbEnabled && sp.getBoolean(R.string.key_enableSMB_always, false) && advancedFiltering);
+ mProfile.put("enableSMB_after_carbs", smbEnabled && sp.getBoolean(R.string.key_enableSMB_after_carbs, false) && advancedFiltering);
+ mProfile.put("maxSMBBasalMinutes", sp.getInt(R.string.key_smbmaxminutes, SMBDefaults.maxSMBBasalMinutes));
+ mProfile.put("maxUAMSMBBasalMinutes", sp.getInt(R.string.key_uamsmbmaxminutes, SMBDefaults.maxUAMSMBBasalMinutes));
+ //set the min SMB amount to be the amount set by the pump.
+ mProfile.put("bolus_increment", pumpbolusstep);
+ mProfile.put("carbsReqThreshold", sp.getInt(R.string.key_carbsReqThreshold, SMBDefaults.carbsReqThreshold));
mProfile.put("current_basal", basalrate);
mProfile.put("temptargetSet", tempTargetSet);
- mProfile.put("autosens_max", SafeParse.stringToDouble(SP.getString(R.string.key_openapsama_autosens_max, "1.2")));
+ mProfile.put("autosens_max", SafeParse.stringToDouble(sp.getString(R.string.key_openapsama_autosens_max, "1.2")));
- if (ProfileFunctions.getSystemUnits().equals(Constants.MMOL)) {
+ if (profileFunction.getUnits().equals(Constants.MMOL)) {
mProfile.put("out_units", "mmol/L");
}
long now = System.currentTimeMillis();
- TemporaryBasal tb = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now);
+ TemporaryBasal tb = treatmentsPlugin.getTempBasalFromHistory(now);
mCurrentTemp = new JSONObject();
mCurrentTemp.put("temp", "absolute");
@@ -286,7 +307,7 @@ public class DetermineBasalAdapterSMBJS {
mCurrentTemp.put("rate", tb != null ? tb.tempBasalConvertedToAbsolute(now, profile) : 0d);
// as we have non default temps longer than 30 mintues
- TemporaryBasal tempBasal = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis());
+ TemporaryBasal tempBasal = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis());
if (tempBasal != null) {
mCurrentTemp.put("minutesrunning", tempBasal.getRealDuration());
}
@@ -295,8 +316,9 @@ public class DetermineBasalAdapterSMBJS {
mGlucoseStatus = new JSONObject();
mGlucoseStatus.put("glucose", glucoseStatus.glucose);
+ mGlucoseStatus.put("noise", glucoseStatus.noise);
- if (SP.getBoolean(R.string.key_always_use_shortavg, false)) {
+ if (sp.getBoolean(R.string.key_always_use_shortavg, false)) {
mGlucoseStatus.put("delta", glucoseStatus.short_avgdelta);
} else {
mGlucoseStatus.put("delta", glucoseStatus.delta);
@@ -315,7 +337,7 @@ public class DetermineBasalAdapterSMBJS {
mMealData.put("lastCarbTime", mealData.lastCarbTime);
- if (MainApp.getConstraintChecker().isAutosensModeEnabled().value()) {
+ if (constraintChecker.isAutosensModeEnabled().value()) {
mAutosensData = new JSONObject();
mAutosensData.put("ratio", autosensDataRatio);
} else {
@@ -325,6 +347,8 @@ public class DetermineBasalAdapterSMBJS {
mMicrobolusAllowed = microBolusAllowed;
mSMBAlwaysAllowed = advancedFiltering;
+ mCurrentTime = now;
+
}
private Object makeParam(JSONObject jsonObject, Context rhino, Scriptable scope) {
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalResultSMB.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalResultSMB.java
index 9d0bd22557..dae170d5d9 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalResultSMB.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalResultSMB.java
@@ -2,21 +2,25 @@ package info.nightscout.androidaps.plugins.aps.openAPSSMB;
import org.json.JSONException;
import org.json.JSONObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import info.nightscout.androidaps.logging.L;
+import dagger.android.HasAndroidInjector;
+import info.nightscout.androidaps.logging.AAPSLogger;
+import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.aps.loop.APSResult;
import info.nightscout.androidaps.utils.DateUtil;
public class DetermineBasalResultSMB extends APSResult {
- private static final Logger log = LoggerFactory.getLogger(L.APS);
private double eventualBG;
private double snoozeBG;
- DetermineBasalResultSMB(JSONObject result) {
- this();
+ private DetermineBasalResultSMB(HasAndroidInjector injector) {
+ super(injector);
+ hasPredictions = true;
+ }
+
+ DetermineBasalResultSMB(HasAndroidInjector injector, JSONObject result) {
+ this(injector);
date = DateUtil.now();
json = result;
try {
@@ -53,21 +57,17 @@ public class DetermineBasalResultSMB extends APSResult {
try {
deliverAt = DateUtil.fromISODateString(date).getTime();
} catch (Exception e) {
- log.warn("Error parsing 'deliverAt' date: " + date, e);
+ aapsLogger.error(LTag.APS, "Error parsing 'deliverAt' date: " + date, e);
}
}
} catch (JSONException e) {
- log.error("Error parsing determine-basal result JSON", e);
+ aapsLogger.error(LTag.APS, "Error parsing determine-basal result JSON", e);
}
}
- private DetermineBasalResultSMB() {
- hasPredictions = true;
- }
-
@Override
- public DetermineBasalResultSMB clone() {
- DetermineBasalResultSMB newResult = new DetermineBasalResultSMB();
+ public DetermineBasalResultSMB newAndClone(HasAndroidInjector injector) {
+ DetermineBasalResultSMB newResult = new DetermineBasalResultSMB(injector);
doClone(newResult);
newResult.eventualBG = eventualBG;
@@ -80,7 +80,7 @@ public class DetermineBasalResultSMB extends APSResult {
try {
return new JSONObject(this.json.toString());
} catch (JSONException e) {
- log.error("Error converting determine-basal result to JSON", e);
+ aapsLogger.error(LTag.APS, "Error converting determine-basal result to JSON", e);
}
return null;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBFragment.kt
index 06ad0d01fd..95b0f7f7b8 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBFragment.kt
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBFragment.kt
@@ -6,28 +6,34 @@ import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
-import androidx.fragment.app.Fragment
-import info.nightscout.androidaps.MainApp
+import dagger.android.support.DaggerFragment
import info.nightscout.androidaps.R
-import info.nightscout.androidaps.logging.L
-import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui
-import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateResultGui
-import info.nightscout.androidaps.plugins.bus.RxBus
+import info.nightscout.androidaps.logging.AAPSLogger
+import info.nightscout.androidaps.logging.LTag
+import info.nightscout.androidaps.plugins.aps.events.EventOpenAPSUpdateGui
+import info.nightscout.androidaps.plugins.aps.events.EventOpenAPSUpdateResultGui
+import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.JSONFormatter
-import info.nightscout.androidaps.utils.plusAssign
+import info.nightscout.androidaps.utils.extensions.plusAssign
+import info.nightscout.androidaps.utils.resources.ResourceHelper
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.openapsama_fragment.*
import org.json.JSONArray
import org.json.JSONException
-import org.slf4j.LoggerFactory
+import javax.inject.Inject
-class OpenAPSSMBFragment : Fragment() {
- private val log = LoggerFactory.getLogger(L.APS)
+class OpenAPSSMBFragment : DaggerFragment() {
private var disposable: CompositeDisposable = CompositeDisposable()
+ @Inject lateinit var aapsLogger: AAPSLogger
+ @Inject lateinit var rxBus: RxBusWrapper
+ @Inject lateinit var resourceHelper: ResourceHelper
+ @Inject lateinit var fabricPrivacy: FabricPrivacy
+ @Inject lateinit var openAPSSMBPlugin: OpenAPSSMBPlugin
+
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.openapsama_fragment, container, false)
@@ -37,29 +43,25 @@ class OpenAPSSMBFragment : Fragment() {
super.onViewCreated(view, savedInstanceState)
openapsma_run.setOnClickListener {
- OpenAPSSMBPlugin.getPlugin().invoke("OpenAPSSMB button", false)
+ openAPSSMBPlugin.invoke("OpenAPSSMB button", false)
}
}
@Synchronized
override fun onResume() {
super.onResume()
- disposable += RxBus
- .toObservable(EventOpenAPSUpdateGui::class.java)
- .observeOn(AndroidSchedulers.mainThread())
- .subscribe({
- updateGUI()
- }, {
- FabricPrivacy.logException(it)
- })
- disposable += RxBus
- .toObservable(EventOpenAPSUpdateResultGui::class.java)
- .observeOn(AndroidSchedulers.mainThread())
- .subscribe({
- updateResultGUI(it.text)
- }, {
- FabricPrivacy.logException(it)
- })
+ disposable += rxBus
+ .toObservable(EventOpenAPSUpdateGui::class.java)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe({
+ updateGUI()
+ }, { fabricPrivacy.logException(it) })
+ disposable += rxBus
+ .toObservable(EventOpenAPSUpdateResultGui::class.java)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe({
+ updateResultGUI(it.text)
+ }, { fabricPrivacy.logException(it) })
updateGUI()
}
@@ -73,34 +75,33 @@ class OpenAPSSMBFragment : Fragment() {
@Synchronized
fun updateGUI() {
if (openapsma_result == null) return
- val plugin = OpenAPSSMBPlugin.getPlugin()
- plugin.lastAPSResult?.let { lastAPSResult ->
+ openAPSSMBPlugin.lastAPSResult?.let { lastAPSResult ->
openapsma_result.text = JSONFormatter.format(lastAPSResult.json)
openapsma_request.text = lastAPSResult.toSpanned()
}
- plugin.lastDetermineBasalAdapterSMBJS?.let { determineBasalAdapterSMBJS ->
+ openAPSSMBPlugin.lastDetermineBasalAdapterSMBJS?.let { determineBasalAdapterSMBJS ->
openapsma_glucosestatus.text = JSONFormatter.format(determineBasalAdapterSMBJS.glucoseStatusParam)
openapsma_currenttemp.text = JSONFormatter.format(determineBasalAdapterSMBJS.currentTempParam)
try {
val iobArray = JSONArray(determineBasalAdapterSMBJS.iobDataParam)
- openapsma_iobdata.text = TextUtils.concat(String.format(MainApp.gs(R.string.array_of_elements), iobArray.length()) + "\n", JSONFormatter.format(iobArray.getString(0)))
+ openapsma_iobdata.text = TextUtils.concat(resourceHelper.gs(R.string.array_of_elements, iobArray.length()) + "\n", JSONFormatter.format(iobArray.getString(0)))
} catch (e: JSONException) {
- log.error("Unhandled exception", e)
- @SuppressLint("SetTextl18n")
+ aapsLogger.error(LTag.APS, "Unhandled exception", e)
+ @SuppressLint("SetTextI18n")
openapsma_iobdata.text = "JSONException see log for details"
}
openapsma_profile.text = JSONFormatter.format(determineBasalAdapterSMBJS.profileParam)
openapsma_mealdata.text = JSONFormatter.format(determineBasalAdapterSMBJS.mealDataParam)
openapsma_scriptdebugdata.text = determineBasalAdapterSMBJS.scriptDebug
- plugin.lastAPSResult?.inputConstraints?.let {
- openapsma_constraints.text = it.reasons
+ openAPSSMBPlugin.lastAPSResult?.inputConstraints?.let {
+ openapsma_constraints.text = it.getReasons(aapsLogger)
}
}
- if (plugin.lastAPSRun != 0L) {
- openapsma_lastrun.text = DateUtil.dateAndTimeFullString(plugin.lastAPSRun)
+ if (openAPSSMBPlugin.lastAPSRun != 0L) {
+ openapsma_lastrun.text = DateUtil.dateAndTimeString(openAPSSMBPlugin.lastAPSRun)
}
- plugin.lastAutosensResult?.let {
+ openAPSSMBPlugin.lastAutosensResult?.let {
openapsma_autosensdata.text = JSONFormatter.format(it.json())
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java
index 426c04090b..51650891ee 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java
@@ -1,31 +1,36 @@
package info.nightscout.androidaps.plugins.aps.openAPSSMB;
-import org.json.JSONException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import android.content.Context;
-import info.nightscout.androidaps.MainApp;
+import org.jetbrains.annotations.NotNull;
+import org.json.JSONException;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.interfaces.APSInterface;
+import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.ConstraintsInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpInterface;
-import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.logging.AAPSLogger;
+import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.aps.loop.APSResult;
import info.nightscout.androidaps.plugins.aps.loop.ScriptReader;
-import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui;
-import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateResultGui;
-import info.nightscout.androidaps.plugins.bus.RxBus;
-import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
-import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
-import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
+import info.nightscout.androidaps.plugins.aps.events.EventOpenAPSUpdateGui;
+import info.nightscout.androidaps.plugins.aps.events.EventOpenAPSUpdateResultGui;
+import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
+import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker;
+import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus;
@@ -36,22 +41,19 @@ import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.HardLimits;
import info.nightscout.androidaps.utils.Profiler;
import info.nightscout.androidaps.utils.Round;
-import info.nightscout.androidaps.utils.ToastUtils;
+import info.nightscout.androidaps.utils.resources.ResourceHelper;
-/**
- * Created by mike on 05.08.2016.
- */
+@Singleton
public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, ConstraintsInterface {
- private static Logger log = LoggerFactory.getLogger(L.APS);
-
- private static OpenAPSSMBPlugin openAPSSMBPlugin;
-
- public static OpenAPSSMBPlugin getPlugin() {
- if (openAPSSMBPlugin == null) {
- openAPSSMBPlugin = new OpenAPSSMBPlugin();
- }
- return openAPSSMBPlugin;
- }
+ private final ConstraintChecker constraintChecker;
+ private final ResourceHelper resourceHelper;
+ private final ProfileFunction profileFunction;
+ private final Context context;
+ private final RxBusWrapper rxBus;
+ private final ActivePluginProvider activePlugin;
+ private final TreatmentsPlugin treatmentsPlugin;
+ private final IobCobCalculatorPlugin iobCobCalculatorPlugin;
+ private final HardLimits hardLimits;
// last values
DetermineBasalAdapterSMBJS lastDetermineBasalAdapterSMBJS = null;
@@ -59,27 +61,56 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
DetermineBasalResultSMB lastAPSResult = null;
AutosensResult lastAutosensResult = null;
- private OpenAPSSMBPlugin() {
+ @Inject
+ public OpenAPSSMBPlugin(
+ HasAndroidInjector injector,
+ AAPSLogger aapsLogger,
+ RxBusWrapper rxBus,
+ ConstraintChecker constraintChecker,
+ ResourceHelper resourceHelper,
+ ProfileFunction profileFunction,
+ Context context,
+ ActivePluginProvider activePlugin,
+ TreatmentsPlugin treatmentsPlugin,
+ IobCobCalculatorPlugin iobCobCalculatorPlugin,
+ HardLimits hardLimits
+ ) {
super(new PluginDescription()
- .mainType(PluginType.APS)
- .fragmentClass(OpenAPSSMBFragment.class.getName())
- .pluginName(R.string.openapssmb)
- .shortName(R.string.smb_shortname)
- .preferencesId(R.xml.pref_openapssmb)
- .description(R.string.description_smb)
+ .mainType(PluginType.APS)
+ .fragmentClass(OpenAPSSMBFragment.class.getName())
+ .pluginName(R.string.openapssmb)
+ .shortName(R.string.smb_shortname)
+ .preferencesId(R.xml.pref_openapssmb)
+ .description(R.string.description_smb)
+ .setDefault(),
+ aapsLogger, resourceHelper, injector
);
+ this.constraintChecker = constraintChecker;
+ this.resourceHelper = resourceHelper;
+ this.profileFunction = profileFunction;
+ this.rxBus = rxBus;
+ this.context = context;
+ this.activePlugin = activePlugin;
+ this.treatmentsPlugin = treatmentsPlugin;
+ this.iobCobCalculatorPlugin = iobCobCalculatorPlugin;
+ this.hardLimits = hardLimits;
}
@Override
public boolean specialEnableCondition() {
- PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
- return pump == null || pump.getPumpDescription().isTempBasalCapable;
+ try {
+ PumpInterface pump = activePlugin.getActivePump();
+ return pump.getPumpDescription().isTempBasalCapable;
+ } catch (Exception ignored) {
+ // may fail during initialization
+ return true;
+ }
}
@Override
public boolean specialShowInListCondition() {
- PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
- return pump == null || pump.getPumpDescription().isTempBasalCapable;
+ PumpInterface pump = activePlugin.getActivePump();
+ return pump.getPumpDescription().isTempBasalCapable;
}
@Override
@@ -94,47 +125,36 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
@Override
public void invoke(String initiator, boolean tempBasalFallback) {
- if (L.isEnabled(L.APS))
- log.debug("invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback);
+ getAapsLogger().debug(LTag.APS, "invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback);
lastAPSResult = null;
DetermineBasalAdapterSMBJS determineBasalAdapterSMBJS;
- determineBasalAdapterSMBJS = new DetermineBasalAdapterSMBJS(new ScriptReader(MainApp.instance().getBaseContext()));
+ determineBasalAdapterSMBJS = new DetermineBasalAdapterSMBJS(new ScriptReader(context), getInjector());
- GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData();
- Profile profile = ProfileFunctions.getInstance().getProfile();
- PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
+ GlucoseStatus glucoseStatus = new GlucoseStatus(getInjector()).getGlucoseStatusData();
+ Profile profile = profileFunction.getProfile();
+ PumpInterface pump = activePlugin.getActivePump();
if (profile == null) {
- RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.noprofileselected)));
- if (L.isEnabled(L.APS))
- log.debug(MainApp.gs(R.string.noprofileselected));
- return;
- }
-
- if (pump == null) {
- RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.nopumpselected)));
- if (L.isEnabled(L.APS))
- log.debug(MainApp.gs(R.string.nopumpselected));
+ rxBus.send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.noprofileselected)));
+ getAapsLogger().debug(LTag.APS, resourceHelper.gs(R.string.noprofileselected));
return;
}
if (!isEnabled(PluginType.APS)) {
- RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_disabled)));
- if (L.isEnabled(L.APS))
- log.debug(MainApp.gs(R.string.openapsma_disabled));
+ rxBus.send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openapsma_disabled)));
+ getAapsLogger().debug(LTag.APS, resourceHelper.gs(R.string.openapsma_disabled));
return;
}
if (glucoseStatus == null) {
- RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_noglucosedata)));
- if (L.isEnabled(L.APS))
- log.debug(MainApp.gs(R.string.openapsma_noglucosedata));
+ rxBus.send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openapsma_noglucosedata)));
+ getAapsLogger().debug(LTag.APS, resourceHelper.gs(R.string.openapsma_noglucosedata));
return;
}
Constraint inputConstraints = new Constraint<>(0d); // fake. only for collecting all results
- Constraint maxBasalConstraint = MainApp.getConstraintChecker().getMaxBasalAllowed(profile);
+ Constraint maxBasalConstraint = constraintChecker.getMaxBasalAllowed(profile);
inputConstraints.copyReasons(maxBasalConstraint);
double maxBasal = maxBasalConstraint.value();
double minBg = profile.getTargetLowMgdl();
@@ -147,44 +167,43 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
long start = System.currentTimeMillis();
long startPart = System.currentTimeMillis();
- MealData mealData = TreatmentsPlugin.getPlugin().getMealData();
- if (L.isEnabled(L.APS))
- Profiler.log(log, "getMealData()", startPart);
+ MealData mealData = iobCobCalculatorPlugin.getMealData();
+ Profiler.log(getAapsLogger(), LTag.APS, "getMealData()", startPart);
- Constraint maxIOBAllowedConstraint = MainApp.getConstraintChecker().getMaxIOBAllowed();
+ Constraint maxIOBAllowedConstraint = constraintChecker.getMaxIOBAllowed();
inputConstraints.copyReasons(maxIOBAllowedConstraint);
double maxIob = maxIOBAllowedConstraint.value();
- minBg = verifyHardLimits(minBg, "minBg", HardLimits.VERY_HARD_LIMIT_MIN_BG[0], HardLimits.VERY_HARD_LIMIT_MIN_BG[1]);
- maxBg = verifyHardLimits(maxBg, "maxBg", HardLimits.VERY_HARD_LIMIT_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_MAX_BG[1]);
- targetBg = verifyHardLimits(targetBg, "targetBg", HardLimits.VERY_HARD_LIMIT_TARGET_BG[0], HardLimits.VERY_HARD_LIMIT_TARGET_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.getVERY_HARD_LIMIT_MAX_BG()[0], hardLimits.getVERY_HARD_LIMIT_MAX_BG()[1]);
+ targetBg = hardLimits.verifyHardLimits(targetBg, "targetBg", hardLimits.getVERY_HARD_LIMIT_TARGET_BG()[0], hardLimits.getVERY_HARD_LIMIT_TARGET_BG()[1]);
boolean isTempTarget = false;
- TempTarget tempTarget = TreatmentsPlugin.getPlugin().getTempTargetFromHistory(System.currentTimeMillis());
+ TempTarget tempTarget = treatmentsPlugin.getTempTargetFromHistory(System.currentTimeMillis());
if (tempTarget != null) {
isTempTarget = true;
- minBg = verifyHardLimits(tempTarget.low, "minBg", HardLimits.VERY_HARD_LIMIT_TEMP_MIN_BG[0], HardLimits.VERY_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]);
- targetBg = verifyHardLimits(tempTarget.target(), "targetBg", HardLimits.VERY_HARD_LIMIT_TEMP_TARGET_BG[0], HardLimits.VERY_HARD_LIMIT_TEMP_TARGET_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.getVERY_HARD_LIMIT_TEMP_MAX_BG()[0], hardLimits.getVERY_HARD_LIMIT_TEMP_MAX_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;
- if (!checkOnlyHardLimits(profile.getIcTimeFromMidnight(Profile.secondsFromMidnight()), "carbratio", HardLimits.MINIC, HardLimits.MAXIC))
+ if (!hardLimits.checkOnlyHardLimits(profile.getIcTimeFromMidnight(Profile.secondsFromMidnight()), "carbratio", hardLimits.getMINIC(), hardLimits.getMAXIC()))
return;
- if (!checkOnlyHardLimits(profile.getIsfMgdl(), "sens", HardLimits.MINISF, HardLimits.MAXISF))
+ if (!hardLimits.checkOnlyHardLimits(profile.getIsfMgdl(), "sens", hardLimits.getMINISF(), hardLimits.getMAXISF()))
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;
- if (!checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, HardLimits.maxBasal()))
+ if (!hardLimits.checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, hardLimits.maxBasal()))
return;
startPart = System.currentTimeMillis();
- if (MainApp.getConstraintChecker().isAutosensModeEnabled().value()) {
- AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getLastAutosensDataSynchronized("OpenAPSPlugin");
+ if (constraintChecker.isAutosensModeEnabled().value()) {
+ AutosensData autosensData = iobCobCalculatorPlugin.getLastAutosensDataSynchronized("OpenAPSPlugin");
if (autosensData == null) {
- RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openaps_noasdata)));
+ rxBus.send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openaps_noasdata)));
return;
}
lastAutosensResult = autosensData.autosensResult;
@@ -193,31 +212,28 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
lastAutosensResult.sensResult = "autosens disabled";
}
- IobTotal[] iobArray = IobCobCalculatorPlugin.getPlugin().calculateIobArrayForSMB(lastAutosensResult, SMBDefaults.exercise_mode, SMBDefaults.half_basal_exercise_target, isTempTarget);
- if (L.isEnabled(L.APS))
- Profiler.log(log, "calculateIobArrayInDia()", startPart);
+ IobTotal[] iobArray = iobCobCalculatorPlugin.calculateIobArrayForSMB(lastAutosensResult, SMBDefaults.exercise_mode, SMBDefaults.half_basal_exercise_target, isTempTarget);
+ Profiler.log(getAapsLogger(), LTag.APS, "calculateIobArrayInDia()", startPart);
startPart = System.currentTimeMillis();
Constraint smbAllowed = new Constraint<>(!tempBasalFallback);
- MainApp.getConstraintChecker().isSMBModeEnabled(smbAllowed);
+ constraintChecker.isSMBModeEnabled(smbAllowed);
inputConstraints.copyReasons(smbAllowed);
Constraint advancedFiltering = new Constraint<>(!tempBasalFallback);
- MainApp.getConstraintChecker().isAdvancedFilteringEnabled(advancedFiltering);
+ constraintChecker.isAdvancedFilteringEnabled(advancedFiltering);
inputConstraints.copyReasons(advancedFiltering);
Constraint uam = new Constraint<>(true);
- MainApp.getConstraintChecker().isUAMEnabled(uam);
+ constraintChecker.isUAMEnabled(uam);
inputConstraints.copyReasons(uam);
- if (L.isEnabled(L.APS))
- Profiler.log(log, "detectSensitivityandCarbAbsorption()", startPart);
- if (L.isEnabled(L.APS))
- Profiler.log(log, "SMB data gathering", start);
+ Profiler.log(getAapsLogger(), LTag.APS, "detectSensitivityandCarbAbsorption()", startPart);
+ Profiler.log(getAapsLogger(), LTag.APS, "SMB data gathering", start);
start = System.currentTimeMillis();
try {
- determineBasalAdapterSMBJS.setData(profile, maxIob, maxBasal, minBg, maxBg, targetBg, ConfigBuilderPlugin.getPlugin().getActivePump().getBaseBasalRate(), iobArray, glucoseStatus, mealData,
+ determineBasalAdapterSMBJS.setData(profile, maxIob, maxBasal, minBg, maxBg, targetBg, activePlugin.getActivePump().getBaseBasalRate(), iobArray, glucoseStatus, mealData,
lastAutosensResult.ratio, //autosensDataRatio
isTempTarget,
smbAllowed.value(),
@@ -225,25 +241,23 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
advancedFiltering.value()
);
} catch (JSONException e) {
- FabricPrivacy.logException(e);
+ FabricPrivacy.getInstance().logException(e);
return;
}
long now = System.currentTimeMillis();
DetermineBasalResultSMB determineBasalResultSMB = determineBasalAdapterSMBJS.invoke();
- if (L.isEnabled(L.APS))
- Profiler.log(log, "SMB calculation", start);
+ Profiler.log(getAapsLogger(), LTag.APS, "SMB calculation", start);
if (determineBasalResultSMB == null) {
- if (L.isEnabled(L.APS))
- log.error("SMB calculation returned null");
+ getAapsLogger().error(LTag.APS, "SMB calculation returned null");
lastDetermineBasalAdapterSMBJS = null;
lastAPSResult = null;
lastAPSRun = 0;
} else {
// TODO still needed with oref1?
// Fix bug determine basal
- if (determineBasalResultSMB.rate == 0d && determineBasalResultSMB.duration == 0 && !TreatmentsPlugin.getPlugin().isTempBasalInProgress())
+ if (determineBasalResultSMB.rate == 0d && determineBasalResultSMB.duration == 0 && !treatmentsPlugin.isTempBasalInProgress())
determineBasalResultSMB.tempBasalRequested = false;
determineBasalResultSMB.iob = iobArray[0];
@@ -251,7 +265,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
try {
determineBasalResultSMB.json.put("timestamp", DateUtil.toISOString(now));
} catch (JSONException e) {
- log.error("Unhandled exception", e);
+ getAapsLogger().error(LTag.APS, "Unhandled exception", e);
}
determineBasalResultSMB.inputConstraints = inputConstraints;
@@ -260,33 +274,15 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
lastAPSResult = determineBasalResultSMB;
lastAPSRun = now;
}
- RxBus.INSTANCE.send(new EventOpenAPSUpdateGui());
+ rxBus.send(new EventOpenAPSUpdateGui());
//deviceStatus.suggested = determineBasalResultAMA.json;
}
- // safety checks
- private static boolean checkOnlyHardLimits(Double value, String valueName, double lowLimit, double highLimit) {
- return value.equals(verifyHardLimits(value, valueName, lowLimit, highLimit));
- }
-
- private 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;
- }
-
+ @NotNull
+ @Override
public Constraint isSuperBolusEnabled(Constraint value) {
- value.set(false);
+ value.set(getAapsLogger(), false);
return value;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/SMBDefaults.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/SMBDefaults.java
index f6b8f20233..5f2216b5ae 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/SMBDefaults.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/SMBDefaults.java
@@ -55,10 +55,13 @@ public class SMBDefaults {
// *** WARNING *** DO NOT USE enableSMB_always or enableSMB_after_carbs with xDrip+, Libre, or similar
//public final static boolean enableSMB_after_carbs = false; // enable supermicrobolus for 6h after carbs, even with 0 COB
//public final static boolean allowSMB_with_high_temptarget = false; // allow supermicrobolus (if otherwise enabled) even with high temp targets
+ public final static int SMBInterval = 3; // minimum interval between SMBs, in minutes. (limited between 1 and 10 min)
public final static int maxSMBBasalMinutes = 30; // maximum minutes of basal that can be delivered as a single SMB with uncovered COB
+ public final static int maxUAMSMBBasalMinutes = 30; // maximum minutes of basal that can be delivered as a single SMB when IOB exceeds COB
// curve:"rapid-acting" // Supported curves: "bilinear", "rapid-acting" (Novolog, Novorapid, Humalog, Apidra) and "ultra-rapid" (Fiasp)
// useCustomPeakTime:false // allows changing insulinPeakTime
// insulinPeakTime:75 // number of minutes after a bolus activity peaks. defaults to 55m for Fiasp if useCustomPeakTime: false
public final static int carbsReqThreshold = 1; // grams of carbsReq to trigger a pushover
// offline_hotspot:false // enabled an offline-only local wifi hotspot if no Internet available
+ public final static double bolus_increment = 0.1; // minimum bolus that can be delivered as an SMB
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/bus/RxBus.kt b/app/src/main/java/info/nightscout/androidaps/plugins/bus/RxBus.kt
index 1774df1471..0b2960c7d9 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/bus/RxBus.kt
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/bus/RxBus.kt
@@ -5,8 +5,13 @@ import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import io.reactivex.subjects.PublishSubject
-// Use object so we have a singleton instance
-object RxBus {
+class RxBus {
+
+ companion object {
+ @JvmStatic
+ @Deprecated("Get via Dagger. Will be removed once fully transitioned to Dagger")
+ var INSTANCE: RxBus = RxBus()//TODO: remove as soon as Dagger is fully set up
+ }
private val publisher = PublishSubject.create()
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/bus/RxBusWrapper.kt b/app/src/main/java/info/nightscout/androidaps/plugins/bus/RxBusWrapper.kt
new file mode 100644
index 0000000000..66e5324113
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/bus/RxBusWrapper.kt
@@ -0,0 +1,21 @@
+package info.nightscout.androidaps.plugins.bus
+
+import info.nightscout.androidaps.events.Event
+import io.reactivex.Observable
+import javax.inject.Inject
+import javax.inject.Singleton
+
+@Singleton
+open class RxBusWrapper @Inject constructor() {
+
+ private val bus: RxBus = RxBus.INSTANCE
+
+ fun send(event: Event) {
+ bus.send(event)
+ }
+
+ // Listen should return an Observable and not the publisher
+ // Using ofType we filter only events that match that class type
+ fun toObservable(eventType: Class): Observable =
+ bus.toObservable(eventType)
+}
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt
index 059bec1444..57781a090a 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt
@@ -1,26 +1,41 @@
package info.nightscout.androidaps.plugins.configBuilder
-
+import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
+import android.widget.CheckBox
+import android.widget.ImageButton
import android.widget.LinearLayout
+import android.widget.RadioButton
import android.widget.TextView
import androidx.annotation.StringRes
-import androidx.fragment.app.Fragment
-import info.nightscout.androidaps.MainApp
+import dagger.android.support.DaggerFragment
import info.nightscout.androidaps.R
+import info.nightscout.androidaps.activities.PreferencesActivity
+import info.nightscout.androidaps.events.EventRebuildTabs
import info.nightscout.androidaps.interfaces.*
-import info.nightscout.androidaps.plugins.bus.RxBus
+import info.nightscout.androidaps.plugins.bus.RxBusWrapper
+import info.nightscout.androidaps.plugins.configBuilder.events.EventConfigBuilderUpdateGui
import info.nightscout.androidaps.utils.FabricPrivacy
-import info.nightscout.androidaps.utils.PasswordProtection
+import info.nightscout.androidaps.utils.extensions.plusAssign
+import info.nightscout.androidaps.utils.protection.ProtectionCheck
+import info.nightscout.androidaps.utils.resources.ResourceHelper
+import info.nightscout.androidaps.utils.extensions.toVisibility
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.configbuilder_fragment.*
import java.util.*
+import javax.inject.Inject
-class ConfigBuilderFragment : Fragment() {
+class ConfigBuilderFragment : DaggerFragment() {
+ @Inject lateinit var rxBus: RxBusWrapper
+ @Inject lateinit var resourceHelper: ResourceHelper
+ @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin
+ @Inject lateinit var fabricPrivacy: FabricPrivacy
+ @Inject lateinit var activePlugin: ActivePluginProvider
+ @Inject lateinit var protectionCheck: ProtectionCheck
private var disposable: CompositeDisposable = CompositeDisposable()
private val pluginViewHolders = ArrayList()
@@ -33,30 +48,32 @@ class ConfigBuilderFragment : Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
- if (PasswordProtection.isLocked("settings_password"))
+ if (protectionCheck.isLocked(ProtectionCheck.Protection.PREFERENCES))
configbuilder_main_layout.visibility = View.GONE
else
unlock.visibility = View.GONE
unlock.setOnClickListener {
- PasswordProtection.QueryPassword(context, R.string.settings_password, "settings_password", {
- configbuilder_main_layout.visibility = View.VISIBLE
- unlock.visibility = View.GONE
- }, null)
+ activity?.let { activity ->
+ protectionCheck.queryProtection(activity, ProtectionCheck.Protection.PREFERENCES, Runnable {
+ activity.runOnUiThread {
+ configbuilder_main_layout.visibility = View.VISIBLE
+ unlock.visibility = View.GONE
+ }
+ })
+ }
}
}
@Synchronized
override fun onResume() {
super.onResume()
- disposable.add(RxBus
- .toObservable(EventConfigBuilderUpdateGui::class.java)
- .observeOn(AndroidSchedulers.mainThread())
- .subscribe({
- for (pluginViewHolder in pluginViewHolders) pluginViewHolder.update()
- }, {
- FabricPrivacy.logException(it)
- }))
+ disposable += rxBus
+ .toObservable(EventConfigBuilderUpdateGui::class.java)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe({
+ for (pluginViewHolder in pluginViewHolders) pluginViewHolder.update()
+ }, { fabricPrivacy.logException(it) })
updateGUI()
}
@@ -69,23 +86,24 @@ class ConfigBuilderFragment : Fragment() {
@Synchronized
private fun updateGUI() {
configbuilder_categories.removeAllViews()
- createViewsForPlugins(R.string.configbuilder_profile, R.string.configbuilder_profile_description, PluginType.PROFILE, MainApp.getSpecificPluginsVisibleInListByInterface(ProfileInterface::class.java, PluginType.PROFILE))
- createViewsForPlugins(R.string.configbuilder_insulin, R.string.configbuilder_insulin_description, PluginType.INSULIN, MainApp.getSpecificPluginsVisibleInListByInterface(InsulinInterface::class.java, PluginType.INSULIN))
- createViewsForPlugins(R.string.configbuilder_bgsource, R.string.configbuilder_bgsource_description, PluginType.BGSOURCE, MainApp.getSpecificPluginsVisibleInListByInterface(BgSourceInterface::class.java, PluginType.BGSOURCE))
- createViewsForPlugins(R.string.configbuilder_pump, R.string.configbuilder_pump_description, PluginType.PUMP, MainApp.getSpecificPluginsVisibleInList(PluginType.PUMP))
- createViewsForPlugins(R.string.configbuilder_sensitivity, R.string.configbuilder_sensitivity_description, PluginType.SENSITIVITY, MainApp.getSpecificPluginsVisibleInListByInterface(SensitivityInterface::class.java, PluginType.SENSITIVITY))
- createViewsForPlugins(R.string.configbuilder_aps, R.string.configbuilder_aps_description, PluginType.APS, MainApp.getSpecificPluginsVisibleInList(PluginType.APS))
- createViewsForPlugins(R.string.configbuilder_loop, R.string.configbuilder_loop_description, PluginType.LOOP, MainApp.getSpecificPluginsVisibleInList(PluginType.LOOP))
- createViewsForPlugins(R.string.constraints, R.string.configbuilder_constraints_description, PluginType.CONSTRAINTS, MainApp.getSpecificPluginsVisibleInListByInterface(ConstraintsInterface::class.java, PluginType.CONSTRAINTS))
- createViewsForPlugins(R.string.configbuilder_treatments, R.string.configbuilder_treatments_description, PluginType.TREATMENT, MainApp.getSpecificPluginsVisibleInList(PluginType.TREATMENT))
- createViewsForPlugins(R.string.configbuilder_general, R.string.configbuilder_general_description, PluginType.GENERAL, MainApp.getSpecificPluginsVisibleInList(PluginType.GENERAL))
+ createViewsForPlugins(R.string.configbuilder_profile, R.string.configbuilder_profile_description, PluginType.PROFILE, activePlugin.getSpecificPluginsVisibleInListByInterface(ProfileInterface::class.java, PluginType.PROFILE))
+ createViewsForPlugins(R.string.configbuilder_insulin, R.string.configbuilder_insulin_description, PluginType.INSULIN, activePlugin.getSpecificPluginsVisibleInListByInterface(InsulinInterface::class.java, PluginType.INSULIN))
+ createViewsForPlugins(R.string.configbuilder_bgsource, R.string.configbuilder_bgsource_description, PluginType.BGSOURCE, activePlugin.getSpecificPluginsVisibleInListByInterface(BgSourceInterface::class.java, PluginType.BGSOURCE))
+ createViewsForPlugins(R.string.configbuilder_pump, R.string.configbuilder_pump_description, PluginType.PUMP, activePlugin.getSpecificPluginsVisibleInList(PluginType.PUMP))
+ createViewsForPlugins(R.string.configbuilder_sensitivity, R.string.configbuilder_sensitivity_description, PluginType.SENSITIVITY, activePlugin.getSpecificPluginsVisibleInListByInterface(SensitivityInterface::class.java, PluginType.SENSITIVITY))
+ createViewsForPlugins(R.string.configbuilder_aps, R.string.configbuilder_aps_description, PluginType.APS, activePlugin.getSpecificPluginsVisibleInList(PluginType.APS))
+ createViewsForPlugins(R.string.configbuilder_loop, R.string.configbuilder_loop_description, PluginType.LOOP, activePlugin.getSpecificPluginsVisibleInList(PluginType.LOOP))
+ createViewsForPlugins(R.string.constraints, R.string.configbuilder_constraints_description, PluginType.CONSTRAINTS, activePlugin.getSpecificPluginsVisibleInListByInterface(ConstraintsInterface::class.java, PluginType.CONSTRAINTS))
+ createViewsForPlugins(R.string.configbuilder_treatments, R.string.configbuilder_treatments_description, PluginType.TREATMENT, activePlugin.getSpecificPluginsVisibleInList(PluginType.TREATMENT))
+ createViewsForPlugins(R.string.configbuilder_general, R.string.configbuilder_general_description, PluginType.GENERAL, activePlugin.getSpecificPluginsVisibleInList(PluginType.GENERAL))
}
private fun createViewsForPlugins(@StringRes title: Int, @StringRes description: Int, pluginType: PluginType, plugins: List) {
- if (plugins.size == 0) return
+ if (plugins.isEmpty()) return
+ @Suppress("InflateParams")
val parent = layoutInflater.inflate(R.layout.configbuilder_single_category, null) as LinearLayout
- (parent.findViewById(R.id.category_title) as TextView).text = MainApp.gs(title)
- (parent.findViewById(R.id.category_description) as TextView).text = MainApp.gs(description)
+ (parent.findViewById(R.id.category_title) as TextView).text = resourceHelper.gs(title)
+ (parent.findViewById(R.id.category_description) as TextView).text = resourceHelper.gs(description)
val pluginContainer = parent.findViewById(R.id.category_plugins)
for (plugin in plugins) {
val pluginViewHolder = PluginViewHolder(this, pluginType, plugin)
@@ -95,4 +113,77 @@ class ConfigBuilderFragment : Fragment() {
configbuilder_categories.addView(parent)
}
+ inner class PluginViewHolder internal constructor(private val fragment: ConfigBuilderFragment,
+ private val pluginType: PluginType,
+ private val plugin: PluginBase) {
+
+ @Suppress("InflateParams")
+ val baseView: LinearLayout = fragment.layoutInflater.inflate(R.layout.configbuilder_single_plugin, null) as LinearLayout
+ private val enabledExclusive: RadioButton
+ private val enabledInclusive: CheckBox
+ private val pluginName: TextView
+ private val pluginDescription: TextView
+ private val pluginPreferences: ImageButton
+ private val pluginVisibility: CheckBox
+
+ init {
+ enabledExclusive = baseView.findViewById(R.id.plugin_enabled_exclusive)
+ enabledInclusive = baseView.findViewById(R.id.plugin_enabled_inclusive)
+ pluginName = baseView.findViewById(R.id.plugin_name)
+ pluginDescription = baseView.findViewById(R.id.plugin_description)
+ pluginPreferences = baseView.findViewById(R.id.plugin_preferences)
+ pluginVisibility = baseView.findViewById(R.id.plugin_visibility)
+
+ pluginVisibility.setOnClickListener {
+ plugin.setFragmentVisible(pluginType, pluginVisibility.isChecked)
+ configBuilderPlugin.storeSettings("CheckedCheckboxVisible")
+ rxBus.send(EventRebuildTabs())
+ configBuilderPlugin.logPluginStatus()
+ }
+
+ enabledExclusive.setOnClickListener {
+ configBuilderPlugin.switchAllowed(plugin, if (enabledExclusive.visibility == View.VISIBLE) enabledExclusive.isChecked else enabledInclusive.isChecked, fragment.activity, pluginType)
+ }
+ enabledInclusive.setOnClickListener {
+ configBuilderPlugin.switchAllowed(plugin, if (enabledExclusive.visibility == View.VISIBLE) enabledExclusive.isChecked else enabledInclusive.isChecked, fragment.activity, pluginType)
+ }
+
+ pluginPreferences.setOnClickListener {
+ fragment.activity?.let { activity ->
+ protectionCheck.queryProtection(activity, ProtectionCheck.Protection.PREFERENCES, Runnable {
+ val i = Intent(fragment.context, PreferencesActivity::class.java)
+ i.putExtra("id", plugin.preferencesId)
+ fragment.startActivity(i)
+ }, null)
+ }
+ }
+ update()
+ }
+
+ fun update() {
+ enabledExclusive.visibility = areMultipleSelectionsAllowed(pluginType).not().toVisibility()
+ enabledInclusive.visibility = areMultipleSelectionsAllowed(pluginType).toVisibility()
+ enabledExclusive.isChecked = plugin.isEnabled(pluginType)
+ enabledInclusive.isChecked = plugin.isEnabled(pluginType)
+ enabledInclusive.isEnabled = !plugin.pluginDescription.alwaysEnabled
+ enabledExclusive.isEnabled = !plugin.pluginDescription.alwaysEnabled
+ pluginName.text = plugin.name
+ if (plugin.description == null)
+ pluginDescription.visibility = View.GONE
+ else {
+ pluginDescription.visibility = View.VISIBLE
+ pluginDescription.text = plugin.description
+ }
+ pluginPreferences.visibility = if (plugin.preferencesId == -1 || !plugin.isEnabled(pluginType)) View.INVISIBLE else View.VISIBLE
+ pluginVisibility.visibility = plugin.hasFragment().toVisibility()
+ pluginVisibility.isEnabled = !(plugin.pluginDescription.neverVisible || plugin.pluginDescription.alwaysVisible) && plugin.isEnabled(pluginType)
+ pluginVisibility.isChecked = plugin.isFragmentVisible()
+ }
+
+ private fun areMultipleSelectionsAllowed(type: PluginType): Boolean {
+ return type == PluginType.GENERAL || type == PluginType.CONSTRAINTS || type == PluginType.LOOP
+ }
+
+ }
+
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java
index f43513fbf5..e908dfa968 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java
@@ -1,16 +1,21 @@
package info.nightscout.androidaps.plugins.configBuilder;
+import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import androidx.fragment.app.FragmentActivity;
import java.util.ArrayList;
-import info.nightscout.androidaps.MainApp;
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventAppInitialized;
+import info.nightscout.androidaps.events.EventConfigBuilderChange;
+import info.nightscout.androidaps.events.EventRebuildTabs;
import info.nightscout.androidaps.interfaces.APSInterface;
+import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.BgSourceInterface;
import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
@@ -19,98 +24,116 @@ import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.SensitivityInterface;
-import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.bus.RxBus;
-import info.nightscout.androidaps.plugins.insulin.InsulinOrefRapidActingPlugin;
-import info.nightscout.androidaps.plugins.profile.ns.NSProfilePlugin;
-import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin;
-import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref0Plugin;
-import info.nightscout.androidaps.queue.CommandQueue;
-import info.nightscout.androidaps.utils.SP;
+import info.nightscout.androidaps.interfaces.TreatmentsInterface;
+import info.nightscout.androidaps.logging.AAPSLogger;
+import info.nightscout.androidaps.logging.LTag;
+import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
+import info.nightscout.androidaps.plugins.configBuilder.events.EventConfigBuilderUpdateGui;
+import info.nightscout.androidaps.utils.alertDialogs.OKDialog;
+import info.nightscout.androidaps.utils.resources.ResourceHelper;
+import info.nightscout.androidaps.utils.sharedPreferences.SP;
/**
* Created by mike on 05.08.2016.
*/
+@Singleton
public class ConfigBuilderPlugin extends PluginBase {
- private Logger log = LoggerFactory.getLogger(L.CONFIGBUILDER);
-
private static ConfigBuilderPlugin configBuilderPlugin;
+ private final ActivePluginProvider activePlugin;
+ private final SP sp;
+ private final AAPSLogger aapsLogger;
+ private final RxBusWrapper rxBus;
+ private final ResourceHelper resourceHelper;
+ private final ProfileFunction profileFunction;
+
+ /**
+ * @deprecated Use dagger to get an instance
+ */
+
+ @Deprecated
+ public ProfileFunction getProfileFunction() {
+ if (profileFunction == null)
+ throw new IllegalStateException("Accessing profileFunction before first instantiation");
+ return profileFunction;
+ }
+
+ @Deprecated
static public ConfigBuilderPlugin getPlugin() {
if (configBuilderPlugin == null)
- configBuilderPlugin = new ConfigBuilderPlugin();
+ throw new IllegalStateException("Accessing ConfigBuilder before first instantiation");
return configBuilderPlugin;
}
- private BgSourceInterface activeBgSource;
- private PumpInterface activePump;
- private ProfileInterface activeProfile;
- private APSInterface activeAPS;
- private InsulinInterface activeInsulin;
- private SensitivityInterface activeSensitivity;
-
- private ArrayList pluginList;
-
- private CommandQueue commandQueue = new CommandQueue();
-
- public ConfigBuilderPlugin() {
+ /*
+ * Written by Adrian:
+ * The ConfigBuilderPlugin.getPlugin() method is used at 333 places throughout the app.
+ * In order to make the transition to DI, while legacy code is still calling `getPlugin()`,
+ * I'd instantiate this plugin very very early on (first injected dependency in MainApp) and use
+ * Lazy dependencies in this constructor.
+ * */
+ @Inject
+ public ConfigBuilderPlugin(
+ ActivePluginProvider activePlugin,
+ HasAndroidInjector injector,
+ SP sp,
+ RxBusWrapper rxBus,
+ AAPSLogger aapsLogger,
+ ResourceHelper resourceHelper,
+ ProfileFunction profileFunction
+ ) {
super(new PluginDescription()
- .mainType(PluginType.GENERAL)
- .fragmentClass(ConfigBuilderFragment.class.getName())
- .showInList(true)
- .alwaysEnabled(true)
- .alwaysVisible(false)
- .pluginName(R.string.configbuilder)
- .shortName(R.string.configbuilder_shortname)
- .description(R.string.description_config_builder)
+ .mainType(PluginType.GENERAL)
+ .fragmentClass(ConfigBuilderFragment.class.getName())
+ .showInList(true)
+ .alwaysEnabled(true)
+ .alwaysVisible(false)
+ .pluginName(R.string.configbuilder)
+ .shortName(R.string.configbuilder_shortname)
+ .description(R.string.description_config_builder),
+ aapsLogger, resourceHelper, injector
);
+ this.activePlugin = activePlugin;
+ this.sp = sp;
+ this.rxBus = rxBus;
+ this.aapsLogger = aapsLogger;
+ this.resourceHelper = resourceHelper;
+ this.profileFunction = profileFunction;
+ configBuilderPlugin = this; // TODO: only while transitioning to Dagger
}
- @Override
- protected void onStart() {
- super.onStart();
- }
-
- @Override
- protected void onStop() {
- super.onStop();
- }
-
-
public void initialize() {
- pluginList = MainApp.getPluginsList();
upgradeSettings();
+ ((PluginStore) activePlugin).loadDefaults();
loadSettings();
setAlwaysEnabledPluginsEnabled();
- RxBus.INSTANCE.send(new EventAppInitialized());
+ rxBus.send(new EventAppInitialized());
}
private void setAlwaysEnabledPluginsEnabled() {
- for (PluginBase plugin : pluginList) {
- if (plugin.pluginDescription.alwaysEnabled)
+ for (PluginBase plugin : activePlugin.getPluginsList()) {
+ if (plugin.getPluginDescription().alwaysEnabled)
plugin.setPluginEnabled(plugin.getType(), true);
}
storeSettings("setAlwaysEnabledPluginsEnabled");
}
public void storeSettings(String from) {
- if (pluginList != null) {
- if (L.isEnabled(L.CONFIGBUILDER))
- log.debug("Storing settings from: " + from);
+ activePlugin.getPluginsList();
+ getAapsLogger().debug(LTag.CONFIGBUILDER, "Storing settings from: " + from);
- verifySelectionInCategories();
+ activePlugin.verifySelectionInCategories();
- for (PluginBase p : pluginList) {
- PluginType type = p.getType();
- if (p.pluginDescription.alwaysEnabled && p.pluginDescription.alwaysVisible)
- continue;
- if (p.pluginDescription.alwaysEnabled && p.pluginDescription.neverVisible)
- continue;
- savePref(p, type, true);
- if (type == PluginType.PUMP) {
- if (p instanceof ProfileInterface) { // Store state of optional Profile interface
- savePref(p, PluginType.PROFILE, false);
- }
+ for (PluginBase p : activePlugin.getPluginsList()) {
+ PluginType type = p.getType();
+ if (p.getPluginDescription().alwaysEnabled && p.getPluginDescription().alwaysVisible)
+ continue;
+ if (p.getPluginDescription().alwaysEnabled && p.getPluginDescription().neverVisible)
+ continue;
+ savePref(p, type, true);
+ if (type == PluginType.PUMP) {
+ if (p instanceof ProfileInterface) { // Store state of optional Profile interface
+ savePref(p, PluginType.PROFILE, false);
}
}
}
@@ -118,21 +141,18 @@ public class ConfigBuilderPlugin extends PluginBase {
private void savePref(PluginBase p, PluginType type, boolean storeVisible) {
String settingEnabled = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Enabled";
- SP.putBoolean(settingEnabled, p.isEnabled(type));
- if (L.isEnabled(L.CONFIGBUILDER))
- log.debug("Storing: " + settingEnabled + ":" + p.isEnabled(type));
+ sp.putBoolean(settingEnabled, p.isEnabled(type));
+ getAapsLogger().debug(LTag.CONFIGBUILDER, "Storing: " + settingEnabled + ":" + p.isEnabled(type));
if (storeVisible) {
String settingVisible = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Visible";
- SP.putBoolean(settingVisible, p.isFragmentVisible());
- if (L.isEnabled(L.CONFIGBUILDER))
- log.debug("Storing: " + settingVisible + ":" + p.isFragmentVisible());
+ sp.putBoolean(settingVisible, p.isFragmentVisible());
+ getAapsLogger().debug(LTag.CONFIGBUILDER, "Storing: " + settingVisible + ":" + p.isFragmentVisible());
}
}
private void loadSettings() {
- if (L.isEnabled(L.CONFIGBUILDER))
- log.debug("Loading stored settings");
- for (PluginBase p : pluginList) {
+ getAapsLogger().debug(LTag.CONFIGBUILDER, "Loading stored settings");
+ for (PluginBase p : activePlugin.getPluginsList()) {
PluginType type = p.getType();
loadPref(p, type, true);
if (p.getType() == PluginType.PUMP) {
@@ -141,39 +161,35 @@ public class ConfigBuilderPlugin extends PluginBase {
}
}
}
- verifySelectionInCategories();
+ activePlugin.verifySelectionInCategories();
}
private void loadPref(PluginBase p, PluginType type, boolean loadVisible) {
String settingEnabled = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Enabled";
- if (SP.contains(settingEnabled))
- p.setPluginEnabled(type, SP.getBoolean(settingEnabled, false));
- else if (p.getType() == type && (p.pluginDescription.enableByDefault || p.pluginDescription.alwaysEnabled)) {
+ if (sp.contains(settingEnabled))
+ p.setPluginEnabled(type, sp.getBoolean(settingEnabled, false));
+ else if (p.getType() == type && (p.getPluginDescription().enableByDefault || p.getPluginDescription().alwaysEnabled)) {
p.setPluginEnabled(type, true);
}
- if (L.isEnabled(L.CONFIGBUILDER))
- log.debug("Loaded: " + settingEnabled + ":" + p.isEnabled(type));
+ getAapsLogger().debug(LTag.CONFIGBUILDER, "Loaded: " + settingEnabled + ":" + p.isEnabled(type));
if (loadVisible) {
String settingVisible = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Visible";
- if (SP.contains(settingVisible))
- p.setFragmentVisible(type, SP.getBoolean(settingVisible, false) && SP.getBoolean(settingEnabled, false));
- else if (p.getType() == type && p.pluginDescription.visibleByDefault) {
+ if (sp.contains(settingVisible))
+ p.setFragmentVisible(type, sp.getBoolean(settingVisible, false) && sp.getBoolean(settingEnabled, false));
+ else if (p.getType() == type && p.getPluginDescription().visibleByDefault) {
p.setFragmentVisible(type, true);
}
- if (L.isEnabled(L.CONFIGBUILDER))
- log.debug("Loaded: " + settingVisible + ":" + p.isFragmentVisible());
+ getAapsLogger().debug(LTag.CONFIGBUILDER, "Loaded: " + settingVisible + ":" + p.isFragmentVisible());
}
}
// Detect settings prior 1.60
private void upgradeSettings() {
- if (!SP.contains("ConfigBuilder_1_NSProfilePlugin_Enabled"))
+ if (!sp.contains("ConfigBuilder_1_NSProfilePlugin_Enabled"))
return;
- if (L.isEnabled(L.CONFIGBUILDER))
- log.debug("Upgrading stored settings");
- for (PluginBase p : pluginList) {
- if (L.isEnabled(L.CONFIGBUILDER))
- log.debug("Processing " + p.getName());
+ getAapsLogger().debug(LTag.CONFIGBUILDER, "Upgrading stored settings");
+ for (PluginBase p : activePlugin.getPluginsList()) {
+ getAapsLogger().debug(LTag.CONFIGBUILDER, "Processing " + p.getName());
for (int type = 1; type < 11; type++) {
PluginType newType;
switch (type) {
@@ -213,196 +229,69 @@ public class ConfigBuilderPlugin extends PluginBase {
}
String settingEnabled = "ConfigBuilder_" + type + "_" + p.getClass().getSimpleName() + "_Enabled";
String settingVisible = "ConfigBuilder_" + type + "_" + p.getClass().getSimpleName() + "_Visible";
- if (SP.contains(settingEnabled))
- p.setPluginEnabled(newType, SP.getBoolean(settingEnabled, false));
- if (SP.contains(settingVisible))
- p.setFragmentVisible(newType, SP.getBoolean(settingVisible, false) && SP.getBoolean(settingEnabled, false));
- SP.remove(settingEnabled);
- SP.remove(settingVisible);
+ if (sp.contains(settingEnabled))
+ p.setPluginEnabled(newType, sp.getBoolean(settingEnabled, false));
+ if (sp.contains(settingVisible))
+ p.setFragmentVisible(newType, sp.getBoolean(settingVisible, false) && sp.getBoolean(settingEnabled, false));
+ sp.remove(settingEnabled);
+ sp.remove(settingVisible);
if (newType == p.getType()) {
savePref(p, newType, true);
- } else if (p.getType() == PluginType.PUMP && p instanceof ProfileInterface) {
- savePref(p, PluginType.PROFILE, false);
}
}
}
}
- public CommandQueue getCommandQueue() {
- return commandQueue;
- }
-
- @Nullable
- public BgSourceInterface getActiveBgSource() {
- return activeBgSource;
- }
-
- @Nullable
- public ProfileInterface getActiveProfileInterface() {
- return activeProfile;
- }
-
- @Nullable
- public InsulinInterface getActiveInsulin() {
- return activeInsulin;
- }
-
- @Nullable
- public APSInterface getActiveAPS() {
- return activeAPS;
- }
-
- @Nullable
- public PumpInterface getActivePump() {
- return activePump;
- }
-
- @Nullable
- public SensitivityInterface getActiveSensitivity() {
- return activeSensitivity;
- }
-
public void logPluginStatus() {
- if (L.isEnabled(L.CONFIGBUILDER))
- for (PluginBase p : pluginList) {
- log.debug(p.getName() + ":" +
- (p.isEnabled(PluginType.GENERAL) ? " GENERAL" : "") +
- (p.isEnabled(PluginType.TREATMENT) ? " TREATMENT" : "") +
- (p.isEnabled(PluginType.SENSITIVITY) ? " SENSITIVITY" : "") +
- (p.isEnabled(PluginType.PROFILE) ? " PROFILE" : "") +
- (p.isEnabled(PluginType.APS) ? " APS" : "") +
- (p.isEnabled(PluginType.PUMP) ? " PUMP" : "") +
- (p.isEnabled(PluginType.CONSTRAINTS) ? " CONSTRAINTS" : "") +
- (p.isEnabled(PluginType.LOOP) ? " LOOP" : "") +
- (p.isEnabled(PluginType.BGSOURCE) ? " BGSOURCE" : "") +
- (p.isEnabled(PluginType.INSULIN) ? " INSULIN" : "")
- );
- }
- }
-
- private void verifySelectionInCategories() {
- ArrayList pluginsInCategory;
-
- // PluginType.APS
- activeAPS = this.determineActivePlugin(APSInterface.class, PluginType.APS);
-
- // PluginType.INSULIN
- pluginsInCategory = MainApp.getSpecificPluginsList(PluginType.INSULIN);
- activeInsulin = (InsulinInterface) getTheOneEnabledInArray(pluginsInCategory, PluginType.INSULIN);
- if (activeInsulin == null) {
- activeInsulin = InsulinOrefRapidActingPlugin.getPlugin();
- InsulinOrefRapidActingPlugin.getPlugin().setPluginEnabled(PluginType.INSULIN, true);
- if (L.isEnabled(L.CONFIGBUILDER))
- log.debug("Defaulting InsulinOrefRapidActingPlugin");
- }
- this.setFragmentVisiblities(((PluginBase) activeInsulin).getName(), pluginsInCategory, PluginType.INSULIN);
-
- // PluginType.SENSITIVITY
- pluginsInCategory = MainApp.getSpecificPluginsList(PluginType.SENSITIVITY);
- activeSensitivity = (SensitivityInterface) getTheOneEnabledInArray(pluginsInCategory, PluginType.SENSITIVITY);
- if (activeSensitivity == null) {
- activeSensitivity = SensitivityOref0Plugin.getPlugin();
- SensitivityOref0Plugin.getPlugin().setPluginEnabled(PluginType.SENSITIVITY, true);
- if (L.isEnabled(L.CONFIGBUILDER))
- log.debug("Defaulting SensitivityOref0Plugin");
- }
- this.setFragmentVisiblities(((PluginBase) activeSensitivity).getName(), pluginsInCategory, PluginType.SENSITIVITY);
-
- // PluginType.PROFILE
- activeProfile = this.determineActivePlugin(ProfileInterface.class, PluginType.PROFILE);
-
- // PluginType.BGSOURCE
- activeBgSource = this.determineActivePlugin(BgSourceInterface.class, PluginType.BGSOURCE);
-
- // PluginType.PUMP
- pluginsInCategory = MainApp.getSpecificPluginsList(PluginType.PUMP);
- activePump = (PumpInterface) getTheOneEnabledInArray(pluginsInCategory, PluginType.PUMP);
- if (activePump == null) {
- activePump = VirtualPumpPlugin.getPlugin();
- VirtualPumpPlugin.getPlugin().setPluginEnabled(PluginType.PUMP, true);
- if (L.isEnabled(L.CONFIGBUILDER))
- log.debug("Defaulting VirtualPumpPlugin");
- }
- this.setFragmentVisiblities(((PluginBase) activePump).getName(), pluginsInCategory, PluginType.PUMP);
-
- // PluginType.TREATMENT
- }
-
- /**
- * disables the visibility for all fragments of Plugins with the given PluginType
- * which are not equally named to the Plugin implementing the given Plugin Interface.
- *
- * @param pluginInterface
- * @param pluginType
- * @param
- * @return
- */
- private T determineActivePlugin(Class pluginInterface, PluginType pluginType) {
- ArrayList pluginsInCategory;
- pluginsInCategory = MainApp.getSpecificPluginsListByInterface(pluginInterface);
-
- return this.determineActivePlugin(pluginsInCategory, pluginType);
- }
-
- private T determineActivePlugin(PluginType pluginType) {
- ArrayList pluginsInCategory;
- pluginsInCategory = MainApp.getSpecificPluginsList(pluginType);
-
- return this.determineActivePlugin(pluginsInCategory, pluginType);
- }
-
- /**
- * disables the visibility for all fragments of Plugins in the given pluginsInCategory
- * with the given PluginType which are not equally named to the Plugin implementing the
- * given Plugin Interface.
- *
- * TODO we are casting an interface to PluginBase, which seems to be rather odd, since
- * TODO the interface is not implementing PluginBase (this is just avoiding errors through
- * TODO conventions.
- *
- * @param pluginsInCategory
- * @param pluginType
- * @param
- * @return
- */
- private T determineActivePlugin(ArrayList pluginsInCategory,
- PluginType pluginType) {
- T activePlugin = (T) getTheOneEnabledInArray(pluginsInCategory, pluginType);
-
- if (activePlugin != null) {
- this.setFragmentVisiblities(((PluginBase) activePlugin).getName(),
- pluginsInCategory, pluginType);
- }
-
- return activePlugin;
- }
-
- private void setFragmentVisiblities(String activePluginName, ArrayList pluginsInCategory,
- PluginType pluginType) {
- if (L.isEnabled(L.CONFIGBUILDER))
- log.debug("Selected interface: " + activePluginName);
- for (PluginBase p : pluginsInCategory) {
- if (!p.getName().equals(activePluginName)) {
- p.setFragmentVisible(pluginType, false);
- }
+ for (PluginBase p : activePlugin.getPluginsList()) {
+ getAapsLogger().debug(LTag.CONFIGBUILDER, p.getName() + ":" +
+ (p.isEnabled(PluginType.GENERAL) ? " GENERAL" : "") +
+ (p.isEnabled(PluginType.TREATMENT) ? " TREATMENT" : "") +
+ (p.isEnabled(PluginType.SENSITIVITY) ? " SENSITIVITY" : "") +
+ (p.isEnabled(PluginType.PROFILE) ? " PROFILE" : "") +
+ (p.isEnabled(PluginType.APS) ? " APS" : "") +
+ (p.isEnabled(PluginType.PUMP) ? " PUMP" : "") +
+ (p.isEnabled(PluginType.CONSTRAINTS) ? " CONSTRAINTS" : "") +
+ (p.isEnabled(PluginType.LOOP) ? " LOOP" : "") +
+ (p.isEnabled(PluginType.BGSOURCE) ? " BGSOURCE" : "") +
+ (p.isEnabled(PluginType.INSULIN) ? " INSULIN" : "")
+ );
}
}
- @Nullable
- private PluginBase getTheOneEnabledInArray(ArrayList pluginsInCategory, PluginType type) {
- PluginBase found = null;
- for (PluginBase p : pluginsInCategory) {
- if (p.isEnabled(type) && found == null) {
- found = p;
- } else if (p.isEnabled(type)) {
- // set others disabled
- p.setPluginEnabled(type, false);
- }
+ // Ask when switching to physical pump plugin
+ public void switchAllowed(@NonNull PluginBase changedPlugin, boolean newState, @Nullable FragmentActivity activity, @NonNull PluginType type) {
+ if (changedPlugin.getType() == PluginType.PUMP && !changedPlugin.getName().equals(resourceHelper.gs(R.string.virtualpump)))
+ confirmPumpPluginActivation(changedPlugin, newState, activity, type);
+ else
+ performPluginSwitch(changedPlugin, newState, type);
+ }
+
+ private void confirmPumpPluginActivation(@NonNull PluginBase changedPlugin, boolean newState, @Nullable FragmentActivity activity, @NonNull PluginType type) {
+ boolean allowHardwarePump = sp.getBoolean("allow_hardware_pump", false);
+ if (allowHardwarePump || activity == null) {
+ performPluginSwitch(changedPlugin, newState, type);
+ } else {
+ OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.allow_hardware_pump_text), () -> {
+ performPluginSwitch(changedPlugin, newState, type);
+ sp.putBoolean("allow_hardware_pump", true);
+ aapsLogger.debug(LTag.PUMP, "First time HW pump allowed!");
+ }, () -> {
+ rxBus.send(new EventConfigBuilderUpdateGui());
+ aapsLogger.debug(LTag.PUMP, "User does not allow switching to HW pump!");
+ });
}
- // If none enabled, enable first one
- //if (found == null && pluginsInCategory.size() > 0)
- // found = pluginsInCategory.get(0);
- return found;
+ }
+
+ public void performPluginSwitch(PluginBase changedPlugin, boolean enabled, @NonNull PluginType type) {
+ changedPlugin.setPluginEnabled(type, enabled);
+ changedPlugin.setFragmentVisible(type, enabled);
+ processOnEnabledCategoryChanged(changedPlugin, type);
+ storeSettings("CheckedCheckboxEnabled");
+ rxBus.send(new EventRebuildTabs());
+ rxBus.send(new EventConfigBuilderChange());
+ rxBus.send(new EventConfigBuilderUpdateGui());
+ logPluginStatus();
}
public void processOnEnabledCategoryChanged(PluginBase changedPlugin, PluginType type) {
@@ -415,23 +304,25 @@ public class ConfigBuilderPlugin extends PluginBase {
break;
// Single selection allowed
case INSULIN:
- pluginsInCategory = MainApp.getSpecificPluginsListByInterface(InsulinInterface.class);
+ pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(InsulinInterface.class);
break;
case SENSITIVITY:
- pluginsInCategory = MainApp.getSpecificPluginsListByInterface(SensitivityInterface.class);
+ pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(SensitivityInterface.class);
break;
case APS:
- pluginsInCategory = MainApp.getSpecificPluginsListByInterface(APSInterface.class);
+ pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(APSInterface.class);
break;
case PROFILE:
- pluginsInCategory = MainApp.getSpecificPluginsListByInterface(ProfileInterface.class);
+ pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(ProfileInterface.class);
break;
case BGSOURCE:
- pluginsInCategory = MainApp.getSpecificPluginsListByInterface(BgSourceInterface.class);
+ pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(BgSourceInterface.class);
break;
case TREATMENT:
+ pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(TreatmentsInterface.class);
+ break;
case PUMP:
- pluginsInCategory = MainApp.getSpecificPluginsListByInterface(PumpInterface.class);
+ pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(PumpInterface.class);
break;
}
if (pluginsInCategory != null) {
@@ -446,16 +337,7 @@ public class ConfigBuilderPlugin extends PluginBase {
}
}
} else { // enable first plugin in list
- if (type == PluginType.PUMP)
- VirtualPumpPlugin.getPlugin().setPluginEnabled(type, true);
- else if (type == PluginType.INSULIN)
- InsulinOrefRapidActingPlugin.getPlugin().setPluginEnabled(type, true);
- else if (type == PluginType.SENSITIVITY)
- SensitivityOref0Plugin.getPlugin().setPluginEnabled(type, true);
- else if (type == PluginType.PROFILE)
- NSProfilePlugin.getPlugin().setPluginEnabled(type, true);
- else
- pluginsInCategory.get(0).setPluginEnabled(type, true);
+ pluginsInCategory.get(0).setPluginEnabled(type, true);
}
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConstraintChecker.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConstraintChecker.kt
new file mode 100644
index 0000000000..111dcd5b79
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConstraintChecker.kt
@@ -0,0 +1,209 @@
+package info.nightscout.androidaps.plugins.configBuilder
+
+import info.nightscout.androidaps.Constants
+import info.nightscout.androidaps.data.Profile
+import info.nightscout.androidaps.interfaces.ActivePluginProvider
+import info.nightscout.androidaps.interfaces.Constraint
+import info.nightscout.androidaps.interfaces.ConstraintsInterface
+import info.nightscout.androidaps.interfaces.PluginType
+import javax.inject.Inject
+import javax.inject.Singleton
+
+@Singleton
+class ConstraintChecker @Inject constructor(private val activePlugin: ActivePluginProvider) : ConstraintsInterface {
+
+ fun isLoopInvocationAllowed(): Constraint =
+ isLoopInvocationAllowed(Constraint(true))
+
+ fun isClosedLoopAllowed(): Constraint