eliminate TreatmentsPlugin::getPlugin

This commit is contained in:
Milos Kozak 2020-03-21 22:51:56 +01:00
parent 07a18ef282
commit e63169a94b
8 changed files with 342 additions and 427 deletions

View file

@ -9,10 +9,13 @@ interface AAPSLogger {
fun debug(message: String)
fun debug(enable: Boolean, tag: LTag, message: String)
fun debug(tag: LTag, message: String)
fun debug(tag: LTag, format: String, vararg arguments: Any?)
fun warn(tag: LTag, message: String)
fun info(tag: LTag, message: String)
fun error(tag: LTag, message: String)
fun error(tag: LTag, message: String, throwable: Throwable)
fun error(tag: LTag, format: String, vararg arguments: Any?)
fun error(message: String)
fun error(message: String, throwable: Throwable)
fun error(tag: LTag, message: String, throwable: Throwable)
fun error(format: String, vararg arguments: Any?)
}

View file

@ -20,6 +20,10 @@ class AAPSLoggerDebug : AAPSLogger {
Log.d(tag.tag, message)
}
override fun debug(tag: LTag, format: String, vararg arguments: Any?) {
Log.d(tag.tag, String.format(format, arguments))
}
override fun warn(tag: LTag, message: String) {
Log.w(tag.tag, message)
}
@ -41,8 +45,16 @@ class AAPSLoggerDebug : AAPSLogger {
Log.e(LTag.CORE.tag, message, throwable)
}
override fun error(format: String, vararg arguments: Any?) {
Log.e(LTag.CORE.tag, String.format(format, arguments))
}
override fun error(tag: LTag, message: String, throwable: Throwable) {
Log.e(tag.tag, message, throwable)
}
override fun error(tag: LTag, format: String, vararg arguments: Any?) {
Log.e(tag.tag, String.format(format, arguments))
}
}

View file

@ -24,6 +24,11 @@ class AAPSLoggerProduction : AAPSLogger {
}
}
override fun debug(tag: LTag, format: String, vararg arguments: Any?) {
if (L.isEnabled(tag.tag))
LoggerFactory.getLogger(tag.tag).debug(stackLogMarker() + String.format(format, arguments))
}
override fun warn(tag: LTag, message: String) {
if (L.isEnabled(tag.tag)) {
LoggerFactory.getLogger(tag.tag).warn(stackLogMarker() + message)
@ -51,11 +56,21 @@ class AAPSLoggerProduction : AAPSLogger {
LoggerFactory.getLogger(LTag.CORE.tag).error(stackLogMarker() + message, throwable)
}
override fun error(format: String, vararg arguments: Any?) {
LoggerFactory.getLogger(LTag.CORE.tag).error(stackLogMarker() + String.format(format, arguments))
}
override fun error(tag: LTag, message: String, throwable: Throwable) {
if (L.isEnabled(tag.tag)) {
LoggerFactory.getLogger(tag.tag).error(stackLogMarker() + message, throwable)
}
}
override fun error(tag: LTag, format: String, vararg arguments: Any?) {
if (L.isEnabled(tag.tag)) {
LoggerFactory.getLogger(tag.tag).error(stackLogMarker() + String.format(format, arguments))
}
}
}
fun StackTraceElement.toLogString(): String = "[${this.className.substringAfterLast(".")}.${this.methodName}():${this.lineNumber}]: "

View file

@ -8,14 +8,11 @@ import androidx.annotation.NonNull;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Profile;
@ -23,6 +20,7 @@ import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.CommandQueueProvider;
import info.nightscout.androidaps.interfaces.ConstraintsInterface;
import info.nightscout.androidaps.interfaces.PluginDescription;
@ -30,16 +28,14 @@ import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.PumpPluginBase;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress;
import info.nightscout.androidaps.plugins.pump.common.data.PumpStatus;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpDriverState;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryData;
import info.nightscout.androidaps.plugins.treatments.Treatment;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.DecimalFormatter;
import info.nightscout.androidaps.utils.FabricPrivacy;
@ -56,7 +52,12 @@ import io.reactivex.schedulers.Schedulers;
public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpInterface, ConstraintsInterface {
private CompositeDisposable disposable = new CompositeDisposable();
private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMP);
protected AAPSLogger aapsLogger;
protected RxBusWrapper rxBus;
protected ActivePluginProvider activePlugin;
protected Context context;
protected FabricPrivacy fabricPrivacy;
/*
protected static final PumpEnactResult OPERATION_NOT_SUPPORTED = new PumpEnactResult().success(false)
.enacted(false).comment(MainApp.gs(R.string.pump_operation_not_supported_by_pump_driver));
@ -72,9 +73,25 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI
protected boolean displayConnectionMessages = false;
protected PumpPluginAbstract(PluginDescription pluginDescription, PumpType pumpType, HasAndroidInjector injector, ResourceHelper resourceHelper, AAPSLogger aapsLogger, CommandQueueProvider commandQueue) {
protected PumpPluginAbstract(
PluginDescription pluginDescription,
PumpType pumpType,
HasAndroidInjector injector,
ResourceHelper resourceHelper,
AAPSLogger aapsLogger,
CommandQueueProvider commandQueue,
RxBusWrapper rxBus,
ActivePluginProvider activePlugin,
Context context,
FabricPrivacy fabricPrivacy
) {
super(pluginDescription, injector, aapsLogger, resourceHelper, commandQueue);
this.aapsLogger = aapsLogger;
this.rxBus = rxBus;
this.activePlugin = activePlugin;
this.context = context;
this.fabricPrivacy = fabricPrivacy;
pumpDescription.setPumpDescription(pumpType);
@ -90,18 +107,15 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI
// TODO: moved from constructor .... test if it works
initPumpStatusData();
Context context = MainApp.instance().getApplicationContext();
Intent intent = new Intent(context, getServiceClass());
context.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
serviceRunning = true;
disposable.add(RxBus.Companion.getINSTANCE()
disposable.add(rxBus
.toObservable(EventAppExit.class)
.observeOn(Schedulers.io())
.subscribe(event -> {
MainApp.instance().getApplicationContext().unbindService(serviceConnection);
}, exception -> FabricPrivacy.getInstance().logException(exception))
.subscribe(event -> context.unbindService(serviceConnection), exception -> fabricPrivacy.logException(exception))
);
onStartCustomActions();
}
@ -109,7 +123,6 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI
@Override
protected void onStop() {
Context context = MainApp.instance().getApplicationContext();
context.unbindService(serviceConnection);
serviceRunning = false;
@ -152,98 +165,91 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI
public boolean isConnected() {
if (displayConnectionMessages && isLoggingEnabled())
LOG.warn("isConnected [PumpPluginAbstract].");
if (displayConnectionMessages)
aapsLogger.debug(LTag.PUMP, "isConnected [PumpPluginAbstract].");
return PumpDriverState.isConnected(pumpState);
}
public boolean isConnecting() {
if (displayConnectionMessages && isLoggingEnabled())
LOG.warn("isConnecting [PumpPluginAbstract].");
if (displayConnectionMessages)
aapsLogger.debug(LTag.PUMP, "isConnecting [PumpPluginAbstract].");
return pumpState == PumpDriverState.Connecting;
}
public void connect(String reason) {
if (displayConnectionMessages && isLoggingEnabled())
LOG.warn("connect (reason={}) [PumpPluginAbstract] - default (empty) implementation.", reason);
if (displayConnectionMessages)
aapsLogger.debug(LTag.PUMP, "connect (reason={}) [PumpPluginAbstract] - default (empty) implementation." + reason);
}
public void disconnect(String reason) {
if (displayConnectionMessages && isLoggingEnabled())
LOG.warn("disconnect (reason={}) [PumpPluginAbstract] - default (empty) implementation.", reason);
if (displayConnectionMessages)
aapsLogger.debug(LTag.PUMP, "disconnect (reason={}) [PumpPluginAbstract] - default (empty) implementation." + reason);
}
public void stopConnecting() {
if (displayConnectionMessages && isLoggingEnabled())
LOG.warn("stopConnecting [PumpPluginAbstract] - default (empty) implementation.");
if (displayConnectionMessages)
aapsLogger.debug(LTag.PUMP, "stopConnecting [PumpPluginAbstract] - default (empty) implementation.");
}
@Override
public boolean isHandshakeInProgress() {
if (displayConnectionMessages && isLoggingEnabled())
LOG.warn("isHandshakeInProgress [PumpPluginAbstract] - default (empty) implementation.");
if (displayConnectionMessages)
aapsLogger.debug(LTag.PUMP, "isHandshakeInProgress [PumpPluginAbstract] - default (empty) implementation.");
return false;
}
@Override
public void finishHandshaking() {
if (displayConnectionMessages && isLoggingEnabled())
LOG.warn("finishHandshaking [PumpPluginAbstract] - default (empty) implementation.");
if (displayConnectionMessages)
aapsLogger.debug(LTag.PUMP, "finishHandshaking [PumpPluginAbstract] - default (empty) implementation.");
}
public void getPumpStatus() {
if (isLoggingEnabled())
LOG.warn("getPumpStatus [PumpPluginAbstract] - Not implemented.");
aapsLogger.debug(LTag.PUMP, "getPumpStatus [PumpPluginAbstract] - Not implemented.");
}
// Upload to pump new basal profile
@NonNull public PumpEnactResult setNewBasalProfile(Profile profile) {
if (isLoggingEnabled())
LOG.warn("setNewBasalProfile [PumpPluginAbstract] - Not implemented.");
aapsLogger.debug(LTag.PUMP, "setNewBasalProfile [PumpPluginAbstract] - Not implemented.");
return getOperationNotSupportedWithCustomText(R.string.pump_operation_not_supported_by_pump_driver);
}
public boolean isThisProfileSet(Profile profile) {
if (isLoggingEnabled())
LOG.warn("isThisProfileSet [PumpPluginAbstract] - Not implemented.");
aapsLogger.debug(LTag.PUMP, "isThisProfileSet [PumpPluginAbstract] - Not implemented.");
return true;
}
public long lastDataTime() {
if (isLoggingEnabled())
LOG.warn("lastDataTime [PumpPluginAbstract].");
aapsLogger.debug(LTag.PUMP, "lastDataTime [PumpPluginAbstract].");
return pumpStatus.lastConnection;
}
public double getBaseBasalRate() {
if (isLoggingEnabled())
LOG.warn("getBaseBasalRate [PumpPluginAbstract] - Not implemented.");
aapsLogger.debug(LTag.PUMP, "getBaseBasalRate [PumpPluginAbstract] - Not implemented.");
return 0.0d;
} // base basal rate, not temp basal
public void stopBolusDelivering() {
if (isLoggingEnabled())
LOG.warn("stopBolusDelivering [PumpPluginAbstract] - Not implemented.");
aapsLogger.debug(LTag.PUMP, "stopBolusDelivering [PumpPluginAbstract] - Not implemented.");
}
@NonNull @Override
public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile,
boolean enforceNew) {
if (isLoggingEnabled())
LOG.warn("setTempBasalAbsolute [PumpPluginAbstract] - Not implemented.");
aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute [PumpPluginAbstract] - Not implemented.");
return getOperationNotSupportedWithCustomText(R.string.pump_operation_not_supported_by_pump_driver);
}
@ -251,15 +257,13 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI
@NonNull @Override
public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile,
boolean enforceNew) {
if (isLoggingEnabled())
LOG.warn("setTempBasalPercent [PumpPluginAbstract] - Not implemented.");
aapsLogger.debug(LTag.PUMP, "setTempBasalPercent [PumpPluginAbstract] - Not implemented.");
return getOperationNotSupportedWithCustomText(R.string.pump_operation_not_supported_by_pump_driver);
}
@NonNull public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) {
if (isLoggingEnabled())
LOG.warn("setExtendedBolus [PumpPluginAbstract] - Not implemented.");
aapsLogger.debug(LTag.PUMP, "setExtendedBolus [PumpPluginAbstract] - Not implemented.");
return getOperationNotSupportedWithCustomText(R.string.pump_operation_not_supported_by_pump_driver);
}
@ -268,15 +272,13 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI
// when the cancel request is requested by the user (forced), the pump should always do a real cancel
@NonNull public PumpEnactResult cancelTempBasal(boolean enforceNew) {
if (isLoggingEnabled())
LOG.warn("cancelTempBasal [PumpPluginAbstract] - Not implemented.");
aapsLogger.debug(LTag.PUMP, "cancelTempBasal [PumpPluginAbstract] - Not implemented.");
return getOperationNotSupportedWithCustomText(R.string.pump_operation_not_supported_by_pump_driver);
}
@NonNull public PumpEnactResult cancelExtendedBolus() {
if (isLoggingEnabled())
LOG.warn("cancelExtendedBolus [PumpPluginAbstract] - Not implemented.");
aapsLogger.debug(LTag.PUMP, "cancelExtendedBolus [PumpPluginAbstract] - Not implemented.");
return getOperationNotSupportedWithCustomText(R.string.pump_operation_not_supported_by_pump_driver);
}
@ -288,8 +290,7 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI
// }
public String deviceID() {
if (isLoggingEnabled())
LOG.warn("deviceID [PumpPluginAbstract] - Not implemented.");
aapsLogger.debug(LTag.PUMP, "deviceID [PumpPluginAbstract] - Not implemented.");
return "FakeDevice";
}
@ -304,16 +305,14 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI
// Short info for SMS, Wear etc
public boolean isFakingTempsByExtendedBoluses() {
if (isLoggingEnabled())
LOG.warn("isFakingTempsByExtendedBoluses [PumpPluginAbstract] - Not implemented.");
aapsLogger.debug(LTag.PUMP, "isFakingTempsByExtendedBoluses [PumpPluginAbstract] - Not implemented.");
return false;
}
@NonNull @Override
public PumpEnactResult loadTDDs() {
if (isLoggingEnabled())
LOG.warn("loadTDDs [PumpPluginAbstract] - Not implemented.");
aapsLogger.debug(LTag.PUMP, "loadTDDs [PumpPluginAbstract] - Not implemented.");
return getOperationNotSupportedWithCustomText(R.string.pump_operation_not_supported_by_pump_driver);
}
@ -321,9 +320,8 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI
@NonNull @Override
public JSONObject getJSONStatus(Profile profile, String profileName) {
long now = System.currentTimeMillis();
if ((pumpStatus.lastConnection + 5 * 60 * 1000L) < System.currentTimeMillis()) {
return null;
return new JSONObject();
}
JSONObject pump = new JSONObject();
@ -336,10 +334,10 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI
extended.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION);
try {
extended.put("ActiveProfile", profileName);
} catch (Exception e) {
} catch (Exception ignored) {
}
TemporaryBasal tb = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis());
TemporaryBasal tb = activePlugin.getActiveTreatments().getTempBasalFromHistory(System.currentTimeMillis());
if (tb != null) {
extended.put("TempBasalAbsoluteRate",
tb.tempBasalConvertedToAbsolute(System.currentTimeMillis(), profile));
@ -347,7 +345,7 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI
extended.put("TempBasalRemaining", tb.getPlannedRemainingMinutes());
}
ExtendedBolus eb = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(System.currentTimeMillis());
ExtendedBolus eb = activePlugin.getActiveTreatments().getExtendedBolusFromHistory(System.currentTimeMillis());
if (eb != null) {
extended.put("ExtendedBolusAbsoluteRate", eb.absoluteRate());
extended.put("ExtendedBolusStart", DateUtil.dateAndTimeString(eb.date));
@ -362,7 +360,7 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI
pump.put("reservoir", pumpStatus.reservoirRemainingUnits);
pump.put("clock", DateUtil.toISOString(new Date()));
} catch (JSONException e) {
LOG.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
return pump;
}
@ -373,7 +371,7 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI
public String shortStatus(boolean veryShort) {
String ret = "";
if (pumpStatus.lastConnection != 0) {
Long agoMsec = System.currentTimeMillis() - pumpStatus.lastConnection;
long agoMsec = System.currentTimeMillis() - pumpStatus.lastConnection;
int agoMin = (int) (agoMsec / 60d / 1000d);
ret += "LastConn: " + agoMin + " min ago\n";
}
@ -381,12 +379,11 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI
ret += "LastBolus: " + DecimalFormatter.to2Decimal(pumpStatus.lastBolusAmount) + "U @" + //
android.text.format.DateFormat.format("HH:mm", pumpStatus.lastBolusTime) + "\n";
}
TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin()
.getRealTempBasalFromHistory(System.currentTimeMillis());
TemporaryBasal activeTemp = activePlugin.getActiveTreatments().getRealTempBasalFromHistory(System.currentTimeMillis());
if (activeTemp != null) {
ret += "Temp: " + activeTemp.toStringFull() + "\n";
}
ExtendedBolus activeExtendedBolus = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(
ExtendedBolus activeExtendedBolus = activePlugin.getActiveTreatments().getExtendedBolusFromHistory(
System.currentTimeMillis());
if (activeExtendedBolus != null) {
ret += "Extended: " + activeExtendedBolus.toString() + "\n";
@ -408,31 +405,29 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI
try {
if (detailedBolusInfo.insulin == 0 && detailedBolusInfo.carbs == 0) {
// neither carbs nor bolus requested
if (isLoggingEnabled())
LOG.error("deliverTreatment: Invalid input");
aapsLogger.error("deliverTreatment: Invalid input");
return new PumpEnactResult(getInjector()).success(false).enacted(false).bolusDelivered(0d).carbsDelivered(0d)
.comment(MainApp.gs(R.string.danar_invalidinput));
.comment(getResourceHelper().gs(R.string.danar_invalidinput));
} else if (detailedBolusInfo.insulin > 0) {
// bolus needed, ask pump to deliver it
return deliverBolus(detailedBolusInfo);
} else {
if (MedtronicHistoryData.doubleBolusDebug)
LOG.debug("DoubleBolusDebug: deliverTreatment::(carb only entry)");
aapsLogger.debug("DoubleBolusDebug: deliverTreatment::(carb only entry)");
// no bolus required, carb only treatment
TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, true);
activePlugin.getActiveTreatments().addToHistoryTreatment(detailedBolusInfo, true);
EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE;
bolusingEvent.setT(new Treatment());
bolusingEvent.getT().isSMB = detailedBolusInfo.isSMB;
bolusingEvent.setPercent(100);
RxBus.Companion.getINSTANCE().send(bolusingEvent);
rxBus.send(bolusingEvent);
if (isLoggingEnabled())
LOG.debug("deliverTreatment: Carb only treatment.");
aapsLogger.debug(LTag.PUMP, "deliverTreatment: Carb only treatment.");
return new PumpEnactResult(getInjector()).success(true).enacted(true).bolusDelivered(0d)
.carbsDelivered(detailedBolusInfo.carbs).comment(MainApp.gs(R.string.virtualpump_resultok));
.carbsDelivered(detailedBolusInfo.carbs).comment(getResourceHelper().gs(R.string.virtualpump_resultok));
}
} finally {
triggerUIChange();
@ -440,20 +435,12 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI
}
public boolean isLoggingEnabled() {
return L.isEnabled(L.PUMP);
}
protected abstract PumpEnactResult deliverBolus(DetailedBolusInfo detailedBolusInfo);
protected abstract void triggerUIChange();
public PumpEnactResult getOperationNotSupportedWithCustomText(int resourceId) {
return new PumpEnactResult(getInjector()).success(false).enacted(false).comment(MainApp.gs(resourceId));
private PumpEnactResult getOperationNotSupportedWithCustomText(int resourceId) {
return new PumpEnactResult(getInjector()).success(false).enacted(false).comment(getResourceHelper().gs(resourceId));
}
}

View file

@ -1,6 +1,7 @@
package info.nightscout.androidaps.plugins.pump.medtronic;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
@ -9,7 +10,6 @@ import android.os.SystemClock;
import androidx.annotation.NonNull;
import org.joda.time.LocalDateTime;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.Arrays;
@ -27,7 +27,6 @@ import javax.inject.Inject;
import javax.inject.Singleton;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.activities.ErrorHelperActivity;
import info.nightscout.androidaps.data.DetailedBolusInfo;
@ -37,18 +36,15 @@ import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.events.EventCustomActionsChanged;
import info.nightscout.androidaps.events.EventRefreshOverview;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.CommandQueueProvider;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.common.ManufacturerType;
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction;
import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction;
import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
@ -84,7 +80,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.events.EventRefreshButt
import info.nightscout.androidaps.plugins.pump.medtronic.service.RileyLinkMedtronicService;
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicConst;
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
@ -98,16 +94,7 @@ import static info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUt
@Singleton
public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInterface {
private final MainApp mainApp;
private final ResourceHelper resourceHelper;
private final ConstraintChecker constraintChecker;
private final ProfileFunction profileFunction;
private final TreatmentsPlugin treatmentsPlugin;
private final info.nightscout.androidaps.utils.sharedPreferences.SP sp;
private final RxBusWrapper rxBus;
private final CommandQueueProvider commandQueue;
private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMP);
private final SP sp;
protected static MedtronicPumpPlugin plugin = null;
private RileyLinkMedtronicService medtronicService;
@ -133,13 +120,12 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
HasAndroidInjector injector,
AAPSLogger aapsLogger,
RxBusWrapper rxBus,
MainApp maiApp,
Context context,
ResourceHelper resourceHelper,
ConstraintChecker constraintChecker,
ProfileFunction profileFunction,
TreatmentsPlugin treatmentsPlugin,
ActivePluginProvider activePlugin,
SP sp,
CommandQueueProvider commandQueue
CommandQueueProvider commandQueue,
FabricPrivacy fabricPrivacy
) {
super(new PluginDescription() //
@ -149,33 +135,24 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
.shortName(R.string.medtronic_name_short) //
.preferencesId(R.xml.pref_medtronic).description(R.string.description_pump_medtronic), //
PumpType.Medtronic_522_722, // we default to most basic model, correct model from config is loaded later
injector, resourceHelper, aapsLogger, commandQueue
injector, resourceHelper, aapsLogger, commandQueue, rxBus, activePlugin, context, fabricPrivacy
);
this.plugin = this;
this.mainApp = maiApp;
this.rxBus = rxBus;
this.resourceHelper = resourceHelper;
this.constraintChecker = constraintChecker;
this.profileFunction = profileFunction;
this.treatmentsPlugin = treatmentsPlugin;
this.sp = sp;
this.commandQueue = commandQueue;
displayConnectionMessages = false;
serviceConnection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) {
if (isLoggingEnabled())
LOG.debug("RileyLinkMedtronicService is disconnected");
aapsLogger.debug(LTag.PUMP, "RileyLinkMedtronicService is disconnected");
medtronicService = null;
}
public void onServiceConnected(ComponentName name, IBinder service) {
if (isLoggingEnabled())
LOG.debug("RileyLinkMedtronicService is connected");
aapsLogger.debug(LTag.PUMP, "RileyLinkMedtronicService is connected");
RileyLinkMedtronicService.LocalBinder mLocalBinder = (RileyLinkMedtronicService.LocalBinder) service;
medtronicService = mLocalBinder.getServiceInstance();
@ -185,8 +162,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
SystemClock.sleep(5000);
if (MedtronicUtil.getPumpStatus() != null) {
if (isLoggingEnabled())
LOG.debug("Starting Medtronic-RileyLink service");
aapsLogger.debug(LTag.PUMP, "Starting Medtronic-RileyLink service");
if (MedtronicUtil.getPumpStatus().setNotInPreInit()) {
break;
}
@ -202,7 +178,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
protected void onStart() {
super.onStart();
medtronicUIComm = new MedtronicUIComm();
medtronicHistoryData = new MedtronicHistoryData();
medtronicHistoryData = new MedtronicHistoryData(aapsLogger, sp, activePlugin);
}
@Deprecated
@ -235,8 +211,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
pumpStatusLocal.refreshConfiguration();
if (isLoggingEnabled())
LOG.debug("initPumpStatusData: {}", this.pumpStatusLocal);
aapsLogger.debug(LTag.PUMP, "initPumpStatusData: " + this.pumpStatusLocal);
this.pumpStatus = pumpStatusLocal;
@ -254,18 +229,18 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
private void migrateSettings() {
if ("US (916 MHz)".equals(sp.getString(MedtronicConst.Prefs.PumpFrequency, null))) {
sp.putString(MedtronicConst.Prefs.PumpFrequency, MainApp.gs(R.string.key_medtronic_pump_frequency_us_ca));
if ("US (916 MHz)".equals(sp.getString(MedtronicConst.Prefs.PumpFrequency, "US (916 MHz)"))) {
sp.putString(MedtronicConst.Prefs.PumpFrequency, getResourceHelper().gs(R.string.key_medtronic_pump_frequency_us_ca));
}
String encoding = sp.getString(MedtronicConst.Prefs.Encoding, null);
String encoding = sp.getString(MedtronicConst.Prefs.Encoding, "RileyLink 4b6b Encoding");
if ("RileyLink 4b6b Encoding".equals(encoding)) {
sp.putString(MedtronicConst.Prefs.Encoding, MainApp.gs(R.string.key_medtronic_pump_encoding_4b6b_rileylink));
sp.putString(MedtronicConst.Prefs.Encoding, getResourceHelper().gs(R.string.key_medtronic_pump_encoding_4b6b_rileylink));
}
if ("Local 4b6b Encoding".equals(encoding)) {
sp.putString(MedtronicConst.Prefs.Encoding, MainApp.gs(R.string.key_medtronic_pump_encoding_4b6b_local));
sp.putString(MedtronicConst.Prefs.Encoding, getResourceHelper().gs(R.string.key_medtronic_pump_encoding_4b6b_local));
}
}
@ -284,8 +259,8 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
StatusRefreshAction.GetData, null, null);
if (doWeHaveAnyStatusNeededRefereshing(statusRefresh)) {
if (!commandQueue.statusInQueue()) {
commandQueue.readStatus("Scheduled Status Refresh", null);
if (!getCommandQueue().statusInQueue()) {
getCommandQueue().readStatus("Scheduled Status Refresh", null);
}
}
@ -330,16 +305,16 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
@Override
public boolean isInitialized() {
if (isLoggingEnabled() && displayConnectionMessages)
LOG.debug("MedtronicPumpPlugin::isInitialized");
if (displayConnectionMessages)
aapsLogger.debug(LTag.PUMP, "MedtronicPumpPlugin::isInitialized");
return isServiceSet() && isInitialized;
}
@Override
public boolean isBusy() {
if (isLoggingEnabled() && displayConnectionMessages)
LOG.debug("MedtronicPumpPlugin::isBusy");
if (displayConnectionMessages)
aapsLogger.debug(LTag.PUMP, "MedtronicPumpPlugin::isBusy");
if (isServiceSet()) {
@ -389,16 +364,16 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
@Override
public boolean isConnected() {
if (isLoggingEnabled() && displayConnectionMessages)
LOG.debug("MedtronicPumpPlugin::isConnected");
if (displayConnectionMessages)
aapsLogger.debug(LTag.PUMP, "MedtronicPumpPlugin::isConnected");
return isServiceSet() && medtronicService.isInitialized();
}
@Override
public boolean isConnecting() {
if (isLoggingEnabled() && displayConnectionMessages)
LOG.debug("MedtronicPumpPlugin::isConnecting");
if (displayConnectionMessages)
aapsLogger.debug(LTag.PUMP, "MedtronicPumpPlugin::isConnecting");
return !isServiceSet() || !medtronicService.isInitialized();
}
@ -414,7 +389,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
refreshAnyStatusThatNeedsToBeRefreshed();
}
RxBus.Companion.getINSTANCE().send(new EventMedtronicPumpValuesChanged());
rxBus.send(new EventMedtronicPumpValuesChanged());
}
@ -429,14 +404,14 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
RileyLinkServiceState rileyLinkServiceState = MedtronicUtil.getServiceState();
if (rileyLinkServiceState == null) {
LOG.error("RileyLink unreachable. RileyLinkServiceState is null.");
aapsLogger.debug(LTag.PUMP, "RileyLink unreachable. RileyLinkServiceState is null.");
return false;
}
if (rileyLinkServiceState != RileyLinkServiceState.PumpConnectorReady //
&& rileyLinkServiceState != RileyLinkServiceState.RileyLinkReady //
&& rileyLinkServiceState != RileyLinkServiceState.TuneUpDevice) {
LOG.error("RileyLink unreachable.");
aapsLogger.debug(LTag.PUMP, "RileyLink unreachable.");
return false;
}
@ -456,8 +431,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
boolean resetTime = false;
if (isPumpNotReachable()) {
if (isLoggingEnabled())
LOG.error("Pump unreachable.");
aapsLogger.error("Pump unreachable.");
MedtronicUtil.sendNotification(MedtronicNotificationType.PumpUnreachable);
return;
@ -538,14 +512,13 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
private void setRefreshButtonEnabled(boolean enabled) {
RxBus.Companion.getINSTANCE().send(new EventRefreshButtonState(enabled));
rxBus.send(new EventRefreshButtonState(enabled));
}
private void initializePump(boolean realInit) {
if (isLoggingEnabled())
LOG.info(getLogPrefix() + "initializePump - start");
aapsLogger.info(LTag.PUMP, getLogPrefix() + "initializePump - start");
if (medtronicCommunicationManager == null) {
medtronicCommunicationManager = MedtronicCommunicationManager.getInstance();
@ -558,8 +531,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
if (isRefresh) {
if (isPumpNotReachable()) {
if (isLoggingEnabled())
LOG.error(getLogPrefix() + "initializePump::Pump unreachable.");
aapsLogger.error(getLogPrefix() + "initializePump::Pump unreachable.");
MedtronicUtil.sendNotification(MedtronicNotificationType.PumpUnreachable);
setRefreshButtonEnabled(true);
@ -575,8 +547,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
medtronicUIComm.executeCommand(MedtronicCommandType.PumpModel);
} else {
if (pumpStatusLocal.medtronicDeviceType != MedtronicUtil.getMedtronicPumpModel()) {
if (isLoggingEnabled())
LOG.warn(getLogPrefix() + "Configured pump is not the same as one detected.");
aapsLogger.warn(LTag.PUMP, getLogPrefix() + "Configured pump is not the same as one detected.");
MedtronicUtil.sendNotification(MedtronicNotificationType.PumpTypeNotSame);
}
}
@ -605,8 +576,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
int errorCount = medtronicUIComm.getInvalidResponsesCount();
if (errorCount >= 5) {
if (isLoggingEnabled())
LOG.error("Number of error counts was 5 or more. Starting tunning.");
aapsLogger.error("Number of error counts was 5 or more. Starting tunning.");
setRefreshButtonEnabled(true);
ServiceTaskExecutor.startTask(new WakeAndTuneTask());
return;
@ -638,7 +608,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
@Override
public boolean isThisProfileSet(Profile profile) {
MedtronicPumpStatus mdtPumpStatus = getMDTPumpStatus();
LOG.debug("isThisProfileSet: basalInitalized={}", mdtPumpStatus.basalProfileStatus);
aapsLogger.debug(LTag.PUMP, "isThisProfileSet: basalInitalized=" + mdtPumpStatus.basalProfileStatus);
if (!isInitialized)
return true;
@ -664,9 +634,8 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
Double[] basalsByHour = getMDTPumpStatus().basalsByHour;
PumpType pumpType = getMDTPumpStatus().getPumpType();
if (isLoggingEnabled())
LOG.debug("Current Basals (h): "
+ (basalsByHour == null ? "null" : BasalProfile.getProfilesByHourToString(basalsByHour)));
aapsLogger.debug(LTag.PUMP, "Current Basals (h): "
+ (basalsByHour == null ? "null" : BasalProfile.getProfilesByHourToString(basalsByHour)));
// int index = 0;
@ -689,14 +658,12 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
stringBuilder.append(" ");
}
if (isLoggingEnabled()) {
LOG.debug(stringBuilder.toString());
aapsLogger.debug(LTag.PUMP, stringBuilder.toString());
if (!invalid) {
LOG.debug("Basal profile is same as AAPS one.");
} else {
LOG.debug("Basal profile on Pump is different than the AAPS one.");
}
if (!invalid) {
aapsLogger.debug(LTag.PUMP, "Basal profile is same as AAPS one.");
} else {
aapsLogger.debug(LTag.PUMP, "Basal profile on Pump is different than the AAPS one.");
}
return (!invalid);
@ -736,8 +703,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
private MedtronicPumpStatus getMDTPumpStatus() {
if (pumpStatusLocal == null) {
// FIXME I don't know why this happens
if (isLoggingEnabled())
LOG.warn("!!!! Reset Pump Status Local");
aapsLogger.warn(LTag.PUMP, "!!!! Reset Pump Status Local");
pumpStatusLocal = MedtronicUtil.getPumpStatus();
}
@ -746,7 +712,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
protected void triggerUIChange() {
RxBus.Companion.getINSTANCE().send(new EventMedtronicPumpValuesChanged());
rxBus.send(new EventMedtronicPumpValuesChanged());
}
private BolusDeliveryType bolusDeliveryType = BolusDeliveryType.Idle;
@ -761,13 +727,12 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
private void checkTimeAndOptionallySetTime() {
if (isLoggingEnabled())
LOG.info("MedtronicPumpPlugin::checkTimeAndOptionallySetTime - Start");
aapsLogger.info(LTag.PUMP, "MedtronicPumpPlugin::checkTimeAndOptionallySetTime - Start");
setRefreshButtonEnabled(false);
if (isPumpNotReachable()) {
LOG.debug("MedtronicPumpPlugin::checkTimeAndOptionallySetTime - Pump Unreachable.");
aapsLogger.debug(LTag.PUMP, "MedtronicPumpPlugin::checkTimeAndOptionallySetTime - Pump Unreachable.");
setRefreshButtonEnabled(true);
return;
}
@ -793,25 +758,23 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
if ((clock.localDeviceTime.getYear() <= 2015) || (timeDiff <= 24 * 60 * 60)) {
if (isLoggingEnabled())
LOG.info("MedtronicPumpPlugin::checkTimeAndOptionallySetTime - Time difference is {} s. Set time on pump.", timeDiff);
aapsLogger.info(LTag.PUMP, "MedtronicPumpPlugin::checkTimeAndOptionallySetTime - Time difference is {} s. Set time on pump." + timeDiff);
medtronicUIComm.executeCommand(MedtronicCommandType.SetRealTimeClock);
if (clock.timeDifference == 0) {
Notification notification = new Notification(Notification.INSIGHT_DATE_TIME_UPDATED, MainApp.gs(R.string.pump_time_updated), Notification.INFO, 60);
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification));
Notification notification = new Notification(Notification.INSIGHT_DATE_TIME_UPDATED, getResourceHelper().gs(R.string.pump_time_updated), Notification.INFO, 60);
rxBus.send(new EventNewNotification(notification));
}
} else {
if ((clock.localDeviceTime.getYear() > 2015)) {
LOG.error("MedtronicPumpPlugin::checkTimeAndOptionallySetTime - Time difference over 24h requested [diff={}]. Doing nothing.", timeDiff);
aapsLogger.error("MedtronicPumpPlugin::checkTimeAndOptionallySetTime - Time difference over 24h requested [diff={}]. Doing nothing." + timeDiff);
sendNotification(MedtronicNotificationType.TimeChangeOver24h);
}
}
} else {
if (isLoggingEnabled())
LOG.info("MedtronicPumpPlugin::checkTimeAndOptionallySetTime - Time difference is {} s. Do nothing.", timeDiff);
aapsLogger.info(LTag.PUMP, "MedtronicPumpPlugin::checkTimeAndOptionallySetTime - Time difference is {} s. Do nothing." + timeDiff);
}
scheduleNextRefresh(MedtronicStatusRefreshType.PumpTime, 0);
@ -821,7 +784,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
@NonNull
protected PumpEnactResult deliverBolus(final DetailedBolusInfo detailedBolusInfo) {
LOG.info("MedtronicPumpPlugin::deliverBolus - {}", BolusDeliveryType.DeliveryPrepared);
aapsLogger.info(LTag.PUMP, "MedtronicPumpPlugin::deliverBolus - " + BolusDeliveryType.DeliveryPrepared);
setRefreshButtonEnabled(false);
@ -831,7 +794,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
return new PumpEnactResult(getInjector()) //
.success(false) //
.enacted(false) //
.comment(MainApp.gs(R.string.medtronic_cmd_bolus_could_not_be_delivered_no_insulin,
.comment(getResourceHelper().gs(R.string.medtronic_cmd_bolus_could_not_be_delivered_no_insulin,
mdtPumpStatus.reservoirRemainingUnits,
detailedBolusInfo.insulin));
}
@ -839,7 +802,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
bolusDeliveryType = BolusDeliveryType.DeliveryPrepared;
if (isPumpNotReachable()) {
LOG.debug("MedtronicPumpPlugin::deliverBolus - Pump Unreachable.");
aapsLogger.debug(LTag.PUMP, "MedtronicPumpPlugin::deliverBolus - Pump Unreachable.");
return setNotReachable(true, false);
}
@ -890,12 +853,12 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
// LOG.debug("MedtronicPumpPlugin::deliverBolus - Show dialog. Context: "
// + MainApp.instance().getApplicationContext());
Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
Intent i = new Intent(context, ErrorHelperActivity.class);
i.putExtra("soundid", R.raw.boluserror);
i.putExtra("status", MainApp.gs(R.string.medtronic_cmd_cancel_bolus_not_supported));
i.putExtra("title", MainApp.gs(R.string.combo_warning));
i.putExtra("status", getResourceHelper().gs(R.string.medtronic_cmd_cancel_bolus_not_supported));
i.putExtra("title", getResourceHelper().gs(R.string.combo_warning));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainApp.instance().startActivity(i);
context.startActivity(i);
}).start();
}
@ -905,7 +868,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
detailedBolusInfo.date = now;
detailedBolusInfo.deliverAt = now; // not sure about that one
treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, true);
activePlugin.getActiveTreatments().addToHistoryTreatment(detailedBolusInfo, true);
// we subtract insulin, exact amount will be visible with next remainingInsulin update.
getMDTPumpStatus().reservoirRemainingUnits -= detailedBolusInfo.insulin;
@ -930,7 +893,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
return new PumpEnactResult(getInjector()) //
.success(bolusDeliveryType == BolusDeliveryType.CancelDelivery) //
.enacted(false) //
.comment(MainApp.gs(R.string.medtronic_cmd_bolus_could_not_be_delivered));
.comment(getResourceHelper().gs(R.string.medtronic_cmd_bolus_could_not_be_delivered));
}
} finally {
@ -955,7 +918,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
return new PumpEnactResult(getInjector()) //
.success(false) //
.enacted(false) //
.comment(MainApp.gs(R.string.medtronic_pump_status_pump_unreachable));
.comment(getResourceHelper().gs(R.string.medtronic_pump_status_pump_unreachable));
}
}
@ -991,29 +954,25 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
return new PumpEnactResult(getInjector()) //
.success(false) //
.enacted(false) //
.comment(MainApp.gs(R.string.medtronic_pump_status_pump_unreachable));
.comment(getResourceHelper().gs(R.string.medtronic_pump_status_pump_unreachable));
}
MedtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable);
getMDTPumpStatus();
if (isLoggingEnabled())
LOG.info(getLogPrefix() + "setTempBasalAbsolute: rate: {}, duration={}", absoluteRate, durationInMinutes);
aapsLogger.info(LTag.PUMP, getLogPrefix() + "setTempBasalAbsolute: rate: " + absoluteRate + ", duration=" + durationInMinutes);
// read current TBR
TempBasalPair tbrCurrent = readTBR();
if (tbrCurrent == null) {
if (isLoggingEnabled())
LOG.warn(getLogPrefix() + "setTempBasalAbsolute - Could not read current TBR, canceling operation.");
aapsLogger.warn(LTag.PUMP, getLogPrefix() + "setTempBasalAbsolute - Could not read current TBR, canceling operation.");
finishAction("TBR");
return new PumpEnactResult(getInjector()).success(false).enacted(false)
.comment(MainApp.gs(R.string.medtronic_cmd_cant_read_tbr));
.comment(getResourceHelper().gs(R.string.medtronic_cmd_cant_read_tbr));
} else {
if (isLoggingEnabled())
LOG.info(getLogPrefix() + "setTempBasalAbsolute: Current Basal: duration: {} min, rate={}",
tbrCurrent.getDurationMinutes(), tbrCurrent.getInsulinRate());
aapsLogger.info(LTag.PUMP, getLogPrefix() + "setTempBasalAbsolute: Current Basal: duration: " + tbrCurrent.getDurationMinutes() + " min, rate=" + tbrCurrent.getInsulinRate());
}
if (!enforceNew) {
@ -1027,8 +986,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
}
if (sameRate) {
if (isLoggingEnabled())
LOG.info(getLogPrefix() + "setTempBasalAbsolute - No enforceNew and same rate. Exiting.");
aapsLogger.info(LTag.PUMP, getLogPrefix() + "setTempBasalAbsolute - No enforceNew and same rate. Exiting.");
finishAction("TBR");
return new PumpEnactResult(getInjector()).success(true).enacted(false);
}
@ -1038,8 +996,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
// if TBR is running we will cancel it.
if (tbrCurrent.getInsulinRate() != 0.0f && tbrCurrent.getDurationMinutes() > 0) {
if (isLoggingEnabled())
LOG.info(getLogPrefix() + "setTempBasalAbsolute - TBR running - so canceling it.");
aapsLogger.info(LTag.PUMP, getLogPrefix() + "setTempBasalAbsolute - TBR running - so canceling it.");
// CANCEL
@ -1048,16 +1005,14 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
Boolean response = (Boolean) responseTask2.returnData;
if (response) {
if (isLoggingEnabled())
LOG.info(getLogPrefix() + "setTempBasalAbsolute - Current TBR cancelled.");
aapsLogger.info(LTag.PUMP, getLogPrefix() + "setTempBasalAbsolute - Current TBR cancelled.");
} else {
if (isLoggingEnabled())
LOG.error(getLogPrefix() + "setTempBasalAbsolute - Cancel TBR failed.");
aapsLogger.error(getLogPrefix() + "setTempBasalAbsolute - Cancel TBR failed.");
finishAction("TBR");
return new PumpEnactResult(getInjector()).success(false).enacted(false)
.comment(MainApp.gs(R.string.medtronic_cmd_cant_cancel_tbr_stop_op));
.comment(getResourceHelper().gs(R.string.medtronic_cmd_cant_cancel_tbr_stop_op));
}
}
@ -1067,8 +1022,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
Boolean response = (Boolean) responseTask.returnData;
if (isLoggingEnabled())
LOG.info(getLogPrefix() + "setTempBasalAbsolute - setTBR. Response: " + response);
aapsLogger.info(LTag.PUMP, getLogPrefix() + "setTempBasalAbsolute - setTBR. Response: " + response);
if (response) {
// FIXME put this into UIPostProcessor
@ -1082,7 +1036,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
.absolute(absoluteRate) //
.source(Source.USER);
treatmentsPlugin.addToHistoryTempBasal(tempStart);
activePlugin.getActiveTreatments().addToHistoryTempBasal(tempStart);
incrementStatistics(MedtronicConst.Statistics.TBRsSet);
@ -1095,7 +1049,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
finishAction("TBR");
return new PumpEnactResult(getInjector()).success(false).enacted(false) //
.comment(MainApp.gs(R.string.medtronic_cmd_tbr_could_not_be_delivered));
.comment(getResourceHelper().gs(R.string.medtronic_cmd_tbr_could_not_be_delivered));
}
}
@ -1110,7 +1064,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
double absoluteValue = profile.getBasal() * (percent / 100.0d);
getMDTPumpStatus();
absoluteValue = pumpStatusLocal.pumpType.determineCorrectBasalSize(absoluteValue);
LOG.warn("setTempBasalPercent [MedtronicPumpPlugin] - You are trying to use setTempBasalPercent with percent other then 0% (%d). This will start setTempBasalAbsolute, with calculated value (%.3f). Result might not be 100% correct.", percent, absoluteValue);
aapsLogger.warn(LTag.PUMP, "setTempBasalPercent [MedtronicPumpPlugin] - You are trying to use setTempBasalPercent with percent other then 0% (" + percent + "). This will start setTempBasalAbsolute, with calculated value (" + absoluteValue + "). Result might not be 100% correct.");
return setTempBasalAbsolute(absoluteValue, durationInMinutes, profile, enforceNew);
}
}
@ -1119,7 +1073,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
private void finishAction(String overviewKey) {
if (overviewKey != null)
RxBus.Companion.getINSTANCE().send(new EventRefreshOverview(overviewKey));
rxBus.send(new EventRefreshOverview(overviewKey));
triggerUIChange();
@ -1153,14 +1107,12 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
if (medtronicHistoryData.isPumpSuspended()) {
this.pumpState = PumpDriverState.Suspended;
if (isLoggingEnabled())
LOG.debug(getLogPrefix() + "isPumpSuspended: true");
aapsLogger.debug(LTag.PUMP, getLogPrefix() + "isPumpSuspended: true");
} else {
if (previousState == PumpDriverState.Suspended) {
this.pumpState = PumpDriverState.Ready;
}
if (isLoggingEnabled())
LOG.debug(getLogPrefix() + "isPumpSuspended: false");
aapsLogger.debug(LTag.PUMP, getLogPrefix() + "isPumpSuspended: false");
}
medtronicHistoryData.processNewHistoryData();
@ -1177,8 +1129,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
if (lastPumpHistoryEntry == null) {
if (isLoggingEnabled())
LOG.debug(getLogPrefix() + "readPumpHistoryLogic(): lastPumpHistoryEntry: null");
aapsLogger.debug(LTag.PUMP, getLogPrefix() + "readPumpHistoryLogic(): lastPumpHistoryEntry: null");
Long lastPumpHistoryEntryTime = getLastPumpEntryTime();
@ -1187,16 +1138,13 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
medtronicHistoryData.setIsInInit(true);
if (lastPumpHistoryEntryTime == 0L) {
if (isLoggingEnabled())
LOG.debug(getLogPrefix() + "readPumpHistoryLogic(): lastPumpHistoryEntryTime: 0L - targetDate: "
+ targetDate);
aapsLogger.debug(LTag.PUMP, getLogPrefix() + "readPumpHistoryLogic(): lastPumpHistoryEntryTime: 0L - targetDate: "
+ targetDate);
targetDate = timeMinus36h;
} else {
// LocalDateTime lastHistoryRecordTime = DateTimeUtil.toLocalDateTime(lastPumpHistoryEntryTime);
if (isLoggingEnabled())
LOG.debug(getLogPrefix() + "readPumpHistoryLogic(): lastPumpHistoryEntryTime: {} - targetDate: {}",
lastPumpHistoryEntryTime, targetDate);
aapsLogger.debug(LTag.PUMP, getLogPrefix() + "readPumpHistoryLogic(): lastPumpHistoryEntryTime: " + lastPumpHistoryEntryTime + " - targetDate: " + targetDate);
medtronicHistoryData.setLastHistoryRecordTime(lastPumpHistoryEntryTime);
@ -1212,34 +1160,30 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
targetDate = (timeMinus36h.isAfter(lastHistoryRecordTime) ? timeMinus36h : lastHistoryRecordTime);
if (isLoggingEnabled())
LOG.debug(getLogPrefix() + "readPumpHistoryLogic(): targetDate: " + targetDate);
aapsLogger.debug(LTag.PUMP, getLogPrefix() + "readPumpHistoryLogic(): targetDate: " + targetDate);
}
} else {
if (isLoggingEnabled())
LOG.debug(getLogPrefix() + "readPumpHistoryLogic(): lastPumpHistoryEntry: not null - {}",
MedtronicUtil.gsonInstance.toJson(lastPumpHistoryEntry));
aapsLogger.debug(LTag.PUMP, getLogPrefix() + "readPumpHistoryLogic(): lastPumpHistoryEntry: not null - " + MedtronicUtil.gsonInstance.toJson(lastPumpHistoryEntry));
medtronicHistoryData.setIsInInit(false);
// medtronicHistoryData.setLastHistoryRecordTime(lastPumpHistoryEntry.atechDateTime);
// targetDate = lastPumpHistoryEntry.atechDateTime;
}
LOG.debug("HST: Target Date: {}", targetDate);
aapsLogger.debug(LTag.PUMP, "HST: Target Date: " + targetDate);
MedtronicUITask responseTask2 = medtronicUIComm.executeCommand(MedtronicCommandType.GetHistoryData,
lastPumpHistoryEntry, targetDate);
LOG.debug("HST: After task");
aapsLogger.debug(LTag.PUMP, "HST: After task");
PumpHistoryResult historyResult = (PumpHistoryResult) responseTask2.returnData;
LOG.debug("HST: History Result: {}", historyResult.toString());
aapsLogger.debug(LTag.PUMP, "HST: History Result: " + historyResult.toString());
PumpHistoryEntry latestEntry = historyResult.getLatestEntry();
if (isLoggingEnabled())
LOG.debug(getLogPrefix() + "Last entry: " + latestEntry);
aapsLogger.debug(LTag.PUMP, getLogPrefix() + "Last entry: " + latestEntry);
if (latestEntry == null) // no new history to read
return;
@ -1247,8 +1191,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
this.lastPumpHistoryEntry = latestEntry;
sp.putLong(MedtronicConst.Statistics.LastPumpHistoryEntry, latestEntry.atechDateTime);
LOG.debug("HST: History: valid={}, unprocessed={}", historyResult.validEntries.size(),
historyResult.unprocessedEntries.size());
aapsLogger.debug(LTag.PUMP, "HST: History: valid=" + historyResult.validEntries.size() + ", unprocessed=" + historyResult.unprocessedEntries.size());
this.medtronicHistoryData.addNewHistory(historyResult);
this.medtronicHistoryData.filterNewEntries();
@ -1282,14 +1225,14 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
LocalDateTime localDateTime = DateTimeUtil.toLocalDateTime(lastPumpEntryTime);
if (localDateTime.getYear() != (new GregorianCalendar().get(Calendar.YEAR))) {
LOG.warn("Saved LastPumpHistoryEntry was invalid. Year was not the same.");
aapsLogger.warn(LTag.PUMP, "Saved LastPumpHistoryEntry was invalid. Year was not the same.");
return 0L;
}
return lastPumpEntryTime;
} catch (Exception ex) {
LOG.warn("Saved LastPumpHistoryEntry was invalid.");
aapsLogger.warn(LTag.PUMP, "Saved LastPumpHistoryEntry was invalid.");
return 0L;
}
@ -1389,8 +1332,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
@NonNull @Override
public PumpEnactResult cancelTempBasal(boolean enforceNew) {
if (isLoggingEnabled())
LOG.info(getLogPrefix() + "cancelTempBasal - started");
aapsLogger.info(LTag.PUMP, getLogPrefix() + "cancelTempBasal - started");
if (isPumpNotReachable()) {
@ -1399,7 +1341,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
return new PumpEnactResult(getInjector()) //
.success(false) //
.enacted(false) //
.comment(MainApp.gs(R.string.medtronic_pump_status_pump_unreachable));
.comment(getResourceHelper().gs(R.string.medtronic_pump_status_pump_unreachable));
}
MedtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable);
@ -1409,17 +1351,15 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
if (tbrCurrent != null) {
if (tbrCurrent.getInsulinRate() == 0.0f && tbrCurrent.getDurationMinutes() == 0) {
if (isLoggingEnabled())
LOG.info(getLogPrefix() + "cancelTempBasal - TBR already canceled.");
aapsLogger.info(LTag.PUMP, getLogPrefix() + "cancelTempBasal - TBR already canceled.");
finishAction("TBR");
return new PumpEnactResult(getInjector()).success(true).enacted(false);
}
} else {
if (isLoggingEnabled())
LOG.warn(getLogPrefix() + "cancelTempBasal - Could not read currect TBR, canceling operation.");
aapsLogger.warn(LTag.PUMP, getLogPrefix() + "cancelTempBasal - Could not read currect TBR, canceling operation.");
finishAction("TBR");
return new PumpEnactResult(getInjector()).success(false).enacted(false)
.comment(MainApp.gs(R.string.medtronic_cmd_cant_read_tbr));
.comment(getResourceHelper().gs(R.string.medtronic_cmd_cant_read_tbr));
}
MedtronicUITask responseTask2 = medtronicUIComm.executeCommand(MedtronicCommandType.CancelTBR);
@ -1429,24 +1369,22 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
finishAction("TBR");
if (response) {
if (isLoggingEnabled())
LOG.info(getLogPrefix() + "cancelTempBasal - Cancel TBR successful.");
aapsLogger.info(LTag.PUMP, getLogPrefix() + "cancelTempBasal - Cancel TBR successful.");
TemporaryBasal tempBasal = new TemporaryBasal() //
.date(System.currentTimeMillis()) //
.duration(0) //
.source(Source.USER);
treatmentsPlugin.addToHistoryTempBasal(tempBasal);
activePlugin.getActiveTreatments().addToHistoryTempBasal(tempBasal);
return new PumpEnactResult(getInjector()).success(true).enacted(true) //
.isTempCancel(true);
} else {
if (isLoggingEnabled())
LOG.info(getLogPrefix() + "cancelTempBasal - Cancel TBR failed.");
aapsLogger.info(LTag.PUMP, getLogPrefix() + "cancelTempBasal - Cancel TBR failed.");
return new PumpEnactResult(getInjector()).success(response).enacted(response) //
.comment(MainApp.gs(R.string.medtronic_cmd_cant_cancel_tbr));
.comment(getResourceHelper().gs(R.string.medtronic_cmd_cant_cancel_tbr));
}
}
@ -1467,15 +1405,14 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
@NonNull @Override
public PumpEnactResult setNewBasalProfile(Profile profile) {
if (isLoggingEnabled())
LOG.info(getLogPrefix() + "setNewBasalProfile");
aapsLogger.info(LTag.PUMP, getLogPrefix() + "setNewBasalProfile");
// this shouldn't be needed, but let's do check if profile setting we are setting is same as current one
if (isProfileSame(profile)) {
return new PumpEnactResult(getInjector()) //
.success(true) //
.enacted(false) //
.comment(MainApp.gs(R.string.medtronic_cmd_basal_profile_not_set_is_same));
.comment(getResourceHelper().gs(R.string.medtronic_cmd_basal_profile_not_set_is_same));
}
setRefreshButtonEnabled(false);
@ -1487,7 +1424,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
return new PumpEnactResult(getInjector()) //
.success(false) //
.enacted(false) //
.comment(MainApp.gs(R.string.medtronic_pump_status_pump_unreachable));
.comment(getResourceHelper().gs(R.string.medtronic_pump_status_pump_unreachable));
}
MedtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable);
@ -1500,7 +1437,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
return new PumpEnactResult(getInjector()) //
.success(false) //
.enacted(false) //
.comment(MainApp.gs(R.string.medtronic_cmd_set_profile_pattern_overflow, profileInvalid));
.comment(getResourceHelper().gs(R.string.medtronic_cmd_set_profile_pattern_overflow, profileInvalid));
}
MedtronicUITask responseTask = medtronicUIComm.executeCommand(MedtronicCommandType.SetBasalProfileSTD,
@ -1508,14 +1445,13 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
Boolean response = (Boolean) responseTask.returnData;
if (isLoggingEnabled())
LOG.info(getLogPrefix() + "Basal Profile was set: " + response);
aapsLogger.info(LTag.PUMP, getLogPrefix() + "Basal Profile was set: " + response);
if (response) {
return new PumpEnactResult(getInjector()).success(true).enacted(true);
} else {
return new PumpEnactResult(getInjector()).success(response).enacted(response) //
.comment(MainApp.gs(R.string.medtronic_cmd_basal_profile_could_not_be_set));
.comment(getResourceHelper().gs(R.string.medtronic_cmd_basal_profile_could_not_be_set));
}
}
@ -1604,12 +1540,12 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
if (MedtronicUtil.getPumpStatus().verifyConfiguration()) {
ServiceTaskExecutor.startTask(new WakeAndTuneTask());
} else {
Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
Intent i = new Intent(context, ErrorHelperActivity.class);
i.putExtra("soundid", R.raw.boluserror);
i.putExtra("status", MainApp.gs(R.string.medtronic_error_operation_not_possible_no_configuration));
i.putExtra("title", MainApp.gs(R.string.combo_warning));
i.putExtra("status", getResourceHelper().gs(R.string.medtronic_error_operation_not_possible_no_configuration));
i.putExtra("title", getResourceHelper().gs(R.string.combo_warning));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainApp.instance().startActivity(i);
context.startActivity(i);
}
}
break;
@ -1635,14 +1571,13 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
@Override
public void timeDateOrTimeZoneChanged() {
if (isLoggingEnabled())
LOG.warn(getLogPrefix() + "Time, Date and/or TimeZone changed. ");
aapsLogger.warn(LTag.PUMP, getLogPrefix() + "Time, Date and/or TimeZone changed. ");
this.hasTimeDateOrTimeZoneChanged = true;
}
private void refreshCustomActionsList() {
RxBus.Companion.getINSTANCE().send(new EventCustomActionsChanged());
rxBus.send(new EventCustomActionsChanged());
}

View file

@ -8,8 +8,6 @@ import org.joda.time.LocalDateTime;
import org.joda.time.Minutes;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Calendar;
@ -29,10 +27,10 @@ import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TDD;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil;
import info.nightscout.androidaps.plugins.pump.common.utils.DateTimeUtil;
import info.nightscout.androidaps.plugins.pump.common.utils.StringUtil;
@ -54,7 +52,7 @@ import info.nightscout.androidaps.plugins.treatments.Treatment;
import info.nightscout.androidaps.plugins.treatments.TreatmentService;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.SP;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
/**
@ -70,7 +68,10 @@ import info.nightscout.androidaps.utils.SP;
// All things marked with "TODO: Fix db code" needs to be updated in new 2.5 database code
public class MedtronicHistoryData {
private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMP);
private static AAPSLogger aapsLogger;
private SP sp;
private ActivePluginProvider activePlugin;
private List<PumpHistoryEntry> allHistory = null;
private List<PumpHistoryEntry> newHistory = null;
@ -94,11 +95,15 @@ public class MedtronicHistoryData {
public static boolean doubleBolusDebug = false;
public MedtronicHistoryData() {
public MedtronicHistoryData(AAPSLogger aapsLogger, SP sp, ActivePluginProvider activePlugin) {
this.allHistory = new ArrayList<>();
this.gson = MedtronicUtil.gsonInstance;
this.gsonCore = MedtronicUtil.getGsonInstanceCore();
this.aapsLogger = aapsLogger;
this.sp = sp;
this.activePlugin = activePlugin;
if (this.gson == null) {
this.gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
}
@ -134,20 +139,16 @@ public class MedtronicHistoryData {
private static void showLogs(String header, String data) {
if (!isLogEnabled())
return;
if (header != null) {
LOG.debug(header);
aapsLogger.debug(LTag.PUMP, header);
}
if (StringUtils.isNotBlank(data)) {
for (final String token : StringUtil.splitString(data, 3500)) {
LOG.debug("{}", token);
aapsLogger.debug(LTag.PUMP, "{}", token);
}
} else {
LOG.debug("No data.");
aapsLogger.debug(LTag.PUMP, "No data.");
}
}
@ -164,7 +165,7 @@ public class MedtronicHistoryData {
List<PumpHistoryEntry> bolusEstimates = new ArrayList<>();
long atechDate = DateTimeUtil.toATechDate(new GregorianCalendar());
//LOG.debug("Filter new entries: Before {}", newHistory);
//aapsLogger.debug(LTag.PUMP, "Filter new entries: Before {}", newHistory);
if (!isCollectionEmpty(newHistory)) {
@ -205,8 +206,7 @@ public class MedtronicHistoryData {
sort(this.newHistory);
}
if (isLogEnabled())
LOG.debug("New History entries found: {}", this.newHistory.size());
aapsLogger.debug(LTag.PUMP, "New History entries found: {}", this.newHistory.size());
showLogs("List of history (after filtering): [" + this.newHistory.size() + "]", gson.toJson(this.newHistory));
@ -258,14 +258,14 @@ public class MedtronicHistoryData {
return;
this.setLastHistoryRecordTime(pheLast.atechDateTime);
SP.putLong(MedtronicConst.Statistics.LastPumpHistoryEntry, pheLast.atechDateTime);
sp.putLong(MedtronicConst.Statistics.LastPumpHistoryEntry, pheLast.atechDateTime);
LocalDateTime dt = null;
try {
dt = DateTimeUtil.toLocalDateTime(pheLast.atechDateTime);
} catch (Exception ex) {
LOG.error("Problem decoding date from last record: {}" + pheLast);
aapsLogger.error("Problem decoding date from last record: {}" + pheLast);
}
if (dt != null) {
@ -287,11 +287,10 @@ public class MedtronicHistoryData {
this.sort(this.allHistory);
if (isLogEnabled())
LOG.debug("All History records [afterFilterCount={}, removedItemsCount={}, newItemsCount={}]",
allHistory.size(), removeList.size(), newHistory.size());
aapsLogger.debug(LTag.PUMP, "All History records [afterFilterCount={}, removedItemsCount={}, newItemsCount={}]",
allHistory.size(), removeList.size(), newHistory.size());
} else {
LOG.error("Since we couldn't determine date, we don't clean full history. This is just workaround.");
aapsLogger.error("Since we couldn't determine date, we don't clean full history. This is just workaround.");
}
this.newHistory.clear();
@ -335,8 +334,7 @@ public class MedtronicHistoryData {
pumpHistoryEntryType == PumpHistoryEntryType.BatteryChange || //
pumpHistoryEntryType == PumpHistoryEntryType.Prime);
if (isLogEnabled())
LOG.debug("isPumpSuspended. Last entry type={}, isSuspended={}", pumpHistoryEntryType, isSuspended);
aapsLogger.debug(LTag.PUMP, "isPumpSuspended. Last entry type={}, isSuspended={}", pumpHistoryEntryType, isSuspended);
return isSuspended;
} else
@ -409,14 +407,13 @@ public class MedtronicHistoryData {
// Prime (for reseting autosense)
List<PumpHistoryEntry> primeRecords = getFilteredItems(PumpHistoryEntryType.Prime);
if (isLogEnabled())
LOG.debug("ProcessHistoryData: Prime [count={}, items={}]", primeRecords.size(), gson.toJson(primeRecords));
aapsLogger.debug(LTag.PUMP, "ProcessHistoryData: Prime [count={}, items={}]", primeRecords.size(), gson.toJson(primeRecords));
if (isCollectionNotEmpty(primeRecords)) {
try {
processPrime(primeRecords);
} catch (Exception ex) {
LOG.error("ProcessHistoryData: Error processing Prime entries: " + ex.getMessage(), ex);
aapsLogger.error("ProcessHistoryData: Error processing Prime entries: " + ex.getMessage(), ex);
throw ex;
}
}
@ -424,14 +421,13 @@ public class MedtronicHistoryData {
// TDD
List<PumpHistoryEntry> tdds = getFilteredItems(PumpHistoryEntryType.EndResultTotals, getTDDType());
if (isLogEnabled())
LOG.debug("ProcessHistoryData: TDD [count={}, items={}]", tdds.size(), gson.toJson(tdds));
aapsLogger.debug(LTag.PUMP, "ProcessHistoryData: TDD [count={}, items={}]", tdds.size(), gson.toJson(tdds));
if (isCollectionNotEmpty(tdds)) {
try {
processTDDs(tdds);
} catch (Exception ex) {
LOG.error("ProcessHistoryData: Error processing TDD entries: " + ex.getMessage(), ex);
aapsLogger.error("ProcessHistoryData: Error processing TDD entries: " + ex.getMessage(), ex);
throw ex;
}
}
@ -441,14 +437,13 @@ public class MedtronicHistoryData {
// Bolus
List<PumpHistoryEntry> treatments = getFilteredItems(PumpHistoryEntryType.Bolus);
if (isLogEnabled())
LOG.debug("ProcessHistoryData: Bolus [count={}, items={}]", treatments.size(), gson.toJson(treatments));
aapsLogger.debug(LTag.PUMP, "ProcessHistoryData: Bolus [count={}, items={}]", treatments.size(), gson.toJson(treatments));
if (treatments.size() > 0) {
try {
processBolusEntries(treatments);
} catch (Exception ex) {
LOG.error("ProcessHistoryData: Error processing Bolus entries: " + ex.getMessage(), ex);
aapsLogger.error("ProcessHistoryData: Error processing Bolus entries: " + ex.getMessage(), ex);
throw ex;
}
}
@ -456,14 +451,13 @@ public class MedtronicHistoryData {
// TBR
List<PumpHistoryEntry> tbrs = getFilteredItems(PumpHistoryEntryType.TempBasalCombined);
if (isLogEnabled())
LOG.debug("ProcessHistoryData: TBRs Processed [count={}, items={}]", tbrs.size(), gson.toJson(tbrs));
aapsLogger.debug(LTag.PUMP, "ProcessHistoryData: TBRs Processed [count={}, items={}]", tbrs.size(), gson.toJson(tbrs));
if (tbrs.size() > 0) {
try {
processTBREntries(tbrs);
} catch (Exception ex) {
LOG.error("ProcessHistoryData: Error processing TBR entries: " + ex.getMessage(), ex);
aapsLogger.error("ProcessHistoryData: Error processing TBR entries: " + ex.getMessage(), ex);
throw ex;
}
}
@ -474,19 +468,18 @@ public class MedtronicHistoryData {
try {
suspends = getSuspends();
} catch (Exception ex) {
LOG.error("ProcessHistoryData: Error getting Suspend entries: " + ex.getMessage(), ex);
aapsLogger.error("ProcessHistoryData: Error getting Suspend entries: " + ex.getMessage(), ex);
throw ex;
}
if (isLogEnabled())
LOG.debug("ProcessHistoryData: 'Delivery Suspend' Processed [count={}, items={}]", suspends.size(),
gson.toJson(suspends));
aapsLogger.debug(LTag.PUMP, "ProcessHistoryData: 'Delivery Suspend' Processed [count={}, items={}]", suspends.size(),
gson.toJson(suspends));
if (isCollectionNotEmpty(suspends)) {
try {
processSuspends(suspends);
} catch (Exception ex) {
LOG.error("ProcessHistoryData: Error processing Suspends entries: " + ex.getMessage(), ex);
aapsLogger.error("ProcessHistoryData: Error processing Suspends entries: " + ex.getMessage(), ex);
throw ex;
}
}
@ -509,12 +502,12 @@ public class MedtronicHistoryData {
}
if (lastPrimeRecord != 0L) {
long lastPrimeFromAAPS = SP.getLong(MedtronicConst.Statistics.LastPrime, 0L);
long lastPrimeFromAAPS = sp.getLong(MedtronicConst.Statistics.LastPrime, 0L);
if (lastPrimeRecord != lastPrimeFromAAPS) {
uploadCareportalEvent(DateTimeUtil.toMillisFromATD(lastPrimeRecord), CareportalEvent.SITECHANGE);
SP.putLong(MedtronicConst.Statistics.LastPrime, lastPrimeRecord);
sp.putLong(MedtronicConst.Statistics.LastPrime, lastPrimeRecord);
}
}
}
@ -525,7 +518,7 @@ public class MedtronicHistoryData {
return;
try {
JSONObject data = new JSONObject();
String enteredBy = SP.getString("careportal_enteredby", "");
String enteredBy = sp.getString("careportal_enteredby", "");
if (!enteredBy.equals("")) data.put("enteredBy", enteredBy);
data.put("created_at", DateUtil.toISOString(date));
data.put("eventType", event);
@ -537,7 +530,7 @@ public class MedtronicHistoryData {
MainApp.getDbHelper().createOrUpdate(careportalEvent);
NSUpload.uploadCareportalEntryToNS(data);
} catch (JSONException e) {
LOG.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
}
@ -546,8 +539,7 @@ public class MedtronicHistoryData {
List<PumpHistoryEntry> tdds = filterTDDs(tddsIn);
if (isLogEnabled())
LOG.debug(getLogPrefix() + "TDDs found: {}.\n{}", tdds.size(), gson.toJson(tdds));
aapsLogger.debug(LTag.PUMP, getLogPrefix() + "TDDs found: {}.\n{}", tdds.size(), gson.toJson(tdds));
List<TDD> tddsDb = databaseHelper.getTDDsForLastXDays(3);
@ -557,14 +549,13 @@ public class MedtronicHistoryData {
DailyTotalsDTO totalsDTO = (DailyTotalsDTO) tdd.getDecodedData().get("Object");
//LOG.debug("DailyTotals: {}", totalsDTO);
//aapsLogger.debug(LTag.PUMP, "DailyTotals: {}", totalsDTO);
if (tddDbEntry == null) {
TDD tddNew = new TDD();
totalsDTO.setTDD(tddNew);
if (isLogEnabled())
LOG.debug("TDD Add: {}", tddNew);
aapsLogger.debug(LTag.PUMP, "TDD Add: {}", tddNew);
databaseHelper.createOrUpdateTDD(tddNew);
@ -573,8 +564,7 @@ public class MedtronicHistoryData {
if (!totalsDTO.doesEqual(tddDbEntry)) {
totalsDTO.setTDD(tddDbEntry);
if (isLogEnabled())
LOG.debug("TDD Edit: {}", tddDbEntry);
aapsLogger.debug(LTag.PUMP, "TDD Edit: {}", tddDbEntry);
databaseHelper.createOrUpdateTDD(tddDbEntry);
}
@ -610,39 +600,37 @@ public class MedtronicHistoryData {
List<? extends DbObjectBase> entriesFromHistory = getDatabaseEntriesByLastTimestamp(oldestTimestamp, ProcessHistoryRecord.Bolus);
if (doubleBolusDebug)
LOG.debug("DoubleBolusDebug: List (before filter): {}, FromDb={}", gson.toJson(entryList),
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: List (before filter): {}, FromDb={}", gson.toJson(entryList),
gsonCore.toJson(entriesFromHistory));
filterOutAlreadyAddedEntries(entryList, entriesFromHistory);
if (entryList.isEmpty()) {
if (doubleBolusDebug)
LOG.debug("DoubleBolusDebug: EntryList was filtered out.");
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: EntryList was filtered out.");
return;
}
filterOutNonInsulinEntries(entriesFromHistory);
if (doubleBolusDebug)
LOG.debug("DoubleBolusDebug: List (after filter): {}, FromDb={}", gson.toJson(entryList),
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: List (after filter): {}, FromDb={}", gson.toJson(entryList),
gsonCore.toJson(entriesFromHistory));
if (isCollectionEmpty(entriesFromHistory)) {
for (PumpHistoryEntry treatment : entryList) {
if (isLogEnabled())
LOG.debug("Add Bolus (no db entry): " + treatment);
aapsLogger.debug(LTag.PUMP, "Add Bolus (no db entry): " + treatment);
if (doubleBolusDebug)
LOG.debug("DoubleBolusDebug: Add Bolus: FromDb=null, Treatment={}", treatment);
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: Add Bolus: FromDb=null, Treatment={}", treatment);
addBolus(treatment, null);
}
} else {
for (PumpHistoryEntry treatment : entryList) {
DbObjectBase treatmentDb = findDbEntry(treatment, entriesFromHistory);
if (isLogEnabled())
LOG.debug("Add Bolus {} - (entryFromDb={}) ", treatment, treatmentDb);
aapsLogger.debug(LTag.PUMP, "Add Bolus {} - (entryFromDb={}) ", treatment, treatmentDb);
if (doubleBolusDebug)
LOG.debug("DoubleBolusDebug: Add Bolus: FromDb={}, Treatment={}", treatmentDb, treatment);
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: Add Bolus: FromDb={}, Treatment={}", treatmentDb, treatment);
addBolus(treatment, (Treatment) treatmentDb);
}
@ -656,7 +644,7 @@ public class MedtronicHistoryData {
for (DbObjectBase dbObjectBase : entriesFromHistory) {
Treatment treatment = (Treatment)dbObjectBase;
Treatment treatment = (Treatment) dbObjectBase;
if (RileyLinkUtil.isSame(treatment.insulin, 0d)) {
removeList.add(dbObjectBase);
@ -690,9 +678,8 @@ public class MedtronicHistoryData {
List<? extends DbObjectBase> entriesFromHistory = getDatabaseEntriesByLastTimestamp(oldestTimestamp, ProcessHistoryRecord.TBR);
if (isLogEnabled())
LOG.debug(ProcessHistoryRecord.TBR.getDescription() + " List (before filter): {}, FromDb={}", gson.toJson(entryList),
gson.toJson(entriesFromHistory));
aapsLogger.debug(LTag.PUMP, ProcessHistoryRecord.TBR.getDescription() + " List (before filter): {}, FromDb={}", gson.toJson(entryList),
gson.toJson(entriesFromHistory));
TempBasalProcessDTO processDTO = null;
@ -712,7 +699,7 @@ public class MedtronicHistoryData {
readOldItem = false;
}
} else {
LOG.error("processDTO was null - shouldn't happen. ItemTwo={}", treatment);
aapsLogger.error("processDTO was null - shouldn't happen. ItemTwo={}", treatment);
}
} else {
if (processDTO != null) {
@ -744,10 +731,9 @@ public class MedtronicHistoryData {
databaseHelper.createOrUpdate(tempBasal);
if (isLogEnabled())
LOG.debug("Edit " + ProcessHistoryRecord.TBR.getDescription() + " - (entryFromDb={}) ", tempBasal);
aapsLogger.debug(LTag.PUMP, "Edit " + ProcessHistoryRecord.TBR.getDescription() + " - (entryFromDb={}) ", tempBasal);
} else {
LOG.error("TempBasal not found. Item: {}", tempBasalProcessDTO.itemOne);
aapsLogger.error("TempBasal not found. Item: {}", tempBasalProcessDTO.itemOne);
}
} else {
@ -763,14 +749,13 @@ public class MedtronicHistoryData {
if (tempBasal == null) {
DbObjectBase treatmentDb = findDbEntry(treatment, entriesFromHistory);
if (isLogEnabled())
LOG.debug("Add " + ProcessHistoryRecord.TBR.getDescription() + " {} - (entryFromDb={}) ", treatment, treatmentDb);
aapsLogger.debug(LTag.PUMP, "Add " + ProcessHistoryRecord.TBR.getDescription() + " {} - (entryFromDb={}) ", treatment, treatmentDb);
addTBR(treatment, (TemporaryBasal) treatmentDb);
} else {
// this shouldn't happen
if (tempBasal.durationInMinutes != tempBasalProcessDTO.getDuration()) {
LOG.debug("Found entry with wrong duration (shouldn't happen)... updating");
aapsLogger.debug(LTag.PUMP, "Found entry with wrong duration (shouldn't happen)... updating");
tempBasal.durationInMinutes = tempBasalProcessDTO.getDuration();
}
@ -813,26 +798,26 @@ public class MedtronicHistoryData {
//proposedTime += (this.pumpTime.timeDifference * 1000);
if (doubleBolusDebug)
LOG.debug("DoubleBolusDebug: findDbEntry Treatment={}, FromDb={}", treatment, gson.toJson(entriesFromHistory));
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: findDbEntry Treatment={}, FromDb={}", treatment, gson.toJson(entriesFromHistory));
if (entriesFromHistory.size() == 0) {
if (doubleBolusDebug)
LOG.debug("DoubleBolusDebug: findDbEntry Treatment={}, FromDb=null", treatment);
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: findDbEntry Treatment={}, FromDb=null", treatment);
return null;
} else if (entriesFromHistory.size() == 1) {
if (doubleBolusDebug)
LOG.debug("DoubleBolusDebug: findDbEntry Treatment={}, FromDb={}. Type=SingleEntry", treatment, entriesFromHistory.get(0));
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: findDbEntry Treatment={}, FromDb={}. Type=SingleEntry", treatment, entriesFromHistory.get(0));
// TODO: Fix db code
// if difference is bigger than 2 minutes we discard entry
long maxMillisAllowed = DateTimeUtil.getMillisFromATDWithAddedMinutes(treatment.atechDateTime, 2);
if (doubleBolusDebug)
LOG.debug("DoubleBolusDebug: findDbEntry maxMillisAllowed={}, AtechDateTime={} (add 2 minutes). ", maxMillisAllowed, treatment.atechDateTime);
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: findDbEntry maxMillisAllowed={}, AtechDateTime={} (add 2 minutes). ", maxMillisAllowed, treatment.atechDateTime);
if (entriesFromHistory.get(0).getDate() > maxMillisAllowed) {
if (doubleBolusDebug)
LOG.debug("DoubleBolusDebug: findDbEntry entry filtered out, returning null. ");
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: findDbEntry entry filtered out, returning null. ");
return null;
}
@ -860,17 +845,16 @@ public class MedtronicHistoryData {
if (outList.size() == 1) {
if (doubleBolusDebug)
LOG.debug("DoubleBolusDebug: findDbEntry Treatment={}, FromDb={}. Type=EntrySelected, AtTimeMin={}, AtTimeSec={}", treatment, entriesFromHistory.get(0), min, sec);
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: findDbEntry Treatment={}, FromDb={}. Type=EntrySelected, AtTimeMin={}, AtTimeSec={}", treatment, entriesFromHistory.get(0), min, sec);
return outList.get(0);
}
if (min == 0 && sec == 10 && outList.size() > 1) {
if (isLogEnabled())
LOG.error("Too many entries (with too small diff): (timeDiff=[min={},sec={}],count={},list={})",
min, sec, outList.size(), gson.toJson(outList));
aapsLogger.error("Too many entries (with too small diff): (timeDiff=[min={},sec={}],count={},list={})",
min, sec, outList.size(), gson.toJson(outList));
if (doubleBolusDebug)
LOG.debug("DoubleBolusDebug: findDbEntry Error - Too many entries (with too small diff): (timeDiff=[min={},sec={}],count={},list={})",
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: findDbEntry Error - Too many entries (with too small diff): (timeDiff=[min={},sec={}],count={},list={})",
min, sec, outList.size(), gson.toJson(outList));
}
}
@ -882,7 +866,7 @@ public class MedtronicHistoryData {
private List<? extends DbObjectBase> getDatabaseEntriesByLastTimestamp(long startTimestamp, ProcessHistoryRecord processHistoryRecord) {
if (processHistoryRecord == ProcessHistoryRecord.Bolus) {
return TreatmentsPlugin.getPlugin().getTreatmentsFromHistoryAfterTimestamp(startTimestamp);
return activePlugin.getActiveTreatments().getTreatmentsFromHistoryAfterTimestamp(startTimestamp);
} else {
return databaseHelper.getTemporaryBasalsDataFromTime(startTimestamp, true);
}
@ -920,7 +904,7 @@ public class MedtronicHistoryData {
}
if (doubleBolusDebug)
LOG.debug("DoubleBolusDebug: filterOutAlreadyAddedEntries: PumpHistory={}, Treatments={}",
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: filterOutAlreadyAddedEntries: PumpHistory={}, Treatments={}",
gson.toJson(removeTreatmentsFromPH),
gsonCore.toJson(removeTreatmentsFromHistory));
@ -934,7 +918,7 @@ public class MedtronicHistoryData {
if (treatment == null) {
if (doubleBolusDebug)
LOG.debug("DoubleBolusDebug: addBolus(tretament==null): Bolus={}", bolusDTO);
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: addBolus(tretament==null): Bolus={}", bolusDTO);
switch (bolusDTO.getBolusType()) {
case Normal: {
@ -948,15 +932,14 @@ public class MedtronicHistoryData {
addCarbsFromEstimate(detailedBolusInfo, bolus);
if (doubleBolusDebug)
LOG.debug("DoubleBolusDebug: addBolus(tretament==null): DetailedBolusInfo={}", detailedBolusInfo);
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: addBolus(tretament==null): DetailedBolusInfo={}", detailedBolusInfo);
boolean newRecord = TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, false);
boolean newRecord = activePlugin.getActiveTreatments().addToHistoryTreatment(detailedBolusInfo, false);
bolus.setLinkedObject(detailedBolusInfo);
if (isLogEnabled())
LOG.debug("addBolus - [date={},pumpId={}, insulin={}, newRecord={}]", detailedBolusInfo.date,
detailedBolusInfo.pumpId, detailedBolusInfo.insulin, newRecord);
aapsLogger.debug(LTag.PUMP, "addBolus - [date={},pumpId={}, insulin={}, newRecord={}]", detailedBolusInfo.date,
detailedBolusInfo.pumpId, detailedBolusInfo.insulin, newRecord);
}
break;
@ -973,13 +956,12 @@ public class MedtronicHistoryData {
bolus.setLinkedObject(extendedBolus);
if (doubleBolusDebug)
LOG.debug("DoubleBolusDebug: addBolus(tretament==null): ExtendedBolus={}", extendedBolus);
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: addBolus(tretament==null): ExtendedBolus={}", extendedBolus);
TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus);
activePlugin.getActiveTreatments().addToHistoryExtendedBolus(extendedBolus);
if (isLogEnabled())
LOG.debug("addBolus - Extended [date={},pumpId={}, insulin={}, duration={}]", extendedBolus.date,
extendedBolus.pumpId, extendedBolus.insulin, extendedBolus.durationInMinutes);
aapsLogger.debug(LTag.PUMP, "addBolus - Extended [date={},pumpId={}, insulin={}, duration={}]", extendedBolus.date,
extendedBolus.pumpId, extendedBolus.insulin, extendedBolus.durationInMinutes);
}
break;
@ -988,20 +970,19 @@ public class MedtronicHistoryData {
} else {
if (doubleBolusDebug)
LOG.debug("DoubleBolusDebug: addBolus(OldTreatment={}): Bolus={}", treatment, bolusDTO);
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: addBolus(OldTreatment={}): Bolus={}", treatment, bolusDTO);
treatment.source = Source.PUMP;
treatment.pumpId = bolus.getPumpId();
treatment.insulin = bolusDTO.getDeliveredAmount();
TreatmentService.UpdateReturn updateReturn = TreatmentsPlugin.getPlugin().getService().createOrUpdateMedtronic(treatment, false);
TreatmentService.UpdateReturn updateReturn = ((TreatmentsPlugin)activePlugin.getActiveTreatments()).getService().createOrUpdateMedtronic(treatment, false);
if (doubleBolusDebug)
LOG.debug("DoubleBolusDebug: addBolus(tretament!=null): NewTreatment={}, UpdateReturn={}", treatment, updateReturn);
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: addBolus(tretament!=null): NewTreatment={}, UpdateReturn={}", treatment, updateReturn);
if (isLogEnabled())
LOG.debug("editBolus - [date={},pumpId={}, insulin={}, newRecord={}]", treatment.date,
treatment.pumpId, treatment.insulin, updateReturn.toString());
aapsLogger.debug(LTag.PUMP, "editBolus - [date={},pumpId={}, insulin={}, newRecord={}]", treatment.date,
treatment.pumpId, treatment.insulin, updateReturn.toString());
bolus.setLinkedObject(treatment);
@ -1016,7 +997,7 @@ public class MedtronicHistoryData {
BolusWizardDTO bolusWizard = (BolusWizardDTO) bolus.getDecodedData().get("Estimate");
if (doubleBolusDebug)
LOG.debug("DoubleBolusDebug: addCarbsFromEstimate: Bolus={}, BolusWizardDTO={}", bolus, bolusWizard);
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: addCarbsFromEstimate: Bolus={}, BolusWizardDTO={}", bolus, bolusWizard);
detailedBolusInfo.carbs = bolusWizard.carbs;
}
@ -1047,14 +1028,13 @@ public class MedtronicHistoryData {
databaseHelper.createOrUpdate(temporaryBasalDb);
if (isLogEnabled())
LOG.debug(operation + " - [date={},pumpId={}, rate={} {}, duration={}]", //
temporaryBasalDb.date, //
temporaryBasalDb.pumpId, //
temporaryBasalDb.isAbsolute ? String.format(Locale.ENGLISH, "%.2f", temporaryBasalDb.absoluteRate) :
String.format(Locale.ENGLISH, "%d", temporaryBasalDb.percentRate), //
temporaryBasalDb.isAbsolute ? "U/h" : "%", //
temporaryBasalDb.durationInMinutes);
aapsLogger.debug(LTag.PUMP, operation + " - [date={},pumpId={}, rate={} {}, duration={}]", //
temporaryBasalDb.date, //
temporaryBasalDb.pumpId, //
temporaryBasalDb.isAbsolute ? String.format(Locale.ENGLISH, "%.2f", temporaryBasalDb.absoluteRate) :
String.format(Locale.ENGLISH, "%d", temporaryBasalDb.percentRate), //
temporaryBasalDb.isAbsolute ? "U/h" : "%", //
temporaryBasalDb.durationInMinutes);
}
@ -1336,7 +1316,7 @@ public class MedtronicHistoryData {
// oldestEntryTime = oldestEntryTime.plusSeconds(this.pumpTime.timeDifference);
// }
} catch (Exception ex) {
LOG.error("Problem decoding date from last record: {}" + currentTreatment);
aapsLogger.error("Problem decoding date from last record: {}" + currentTreatment);
return 8; // default return of 6 minutes
}
@ -1345,9 +1325,8 @@ public class MedtronicHistoryData {
Minutes minutes = Minutes.minutesBetween(oldestEntryTime, now);
// returns oldest time in history, with calculated time difference between pump and phone, minus 5 minutes
if (isLogEnabled())
LOG.debug("Oldest entry: {}, pumpTimeDifference={}, newDt={}, currentTime={}, differenceMin={}", dt,
this.pumpTime.timeDifference, oldestEntryTime, now, minutes.getMinutes());
aapsLogger.debug(LTag.PUMP, "Oldest entry: {}, pumpTimeDifference={}, newDt={}, currentTime={}, differenceMin={}", dt,
this.pumpTime.timeDifference, oldestEntryTime, now, minutes.getMinutes());
return minutes.getMinutes();
}
@ -1367,22 +1346,22 @@ public class MedtronicHistoryData {
}
if (doubleBolusDebug)
LOG.debug("DoubleBolusDebug: getOldestTimestamp. Oldest entry found: time={}, object={}", dt, currentTreatment);
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: getOldestTimestamp. Oldest entry found: time={}, object={}", dt, currentTreatment);
try {
GregorianCalendar oldestEntryTime = DateTimeUtil.toGregorianCalendar(dt);
if (doubleBolusDebug)
LOG.debug("DoubleBolusDebug: getOldestTimestamp. oldestEntryTime: {}", DateTimeUtil.toString(oldestEntryTime));
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: getOldestTimestamp. oldestEntryTime: {}", DateTimeUtil.toString(oldestEntryTime));
oldestEntryTime.add(Calendar.MINUTE, -2);
if (doubleBolusDebug)
LOG.debug("DoubleBolusDebug: getOldestTimestamp. oldestEntryTime (-2m): {}, timeInMillis={}", DateTimeUtil.toString(oldestEntryTime), oldestEntryTime.getTimeInMillis());
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: getOldestTimestamp. oldestEntryTime (-2m): {}, timeInMillis={}", DateTimeUtil.toString(oldestEntryTime), oldestEntryTime.getTimeInMillis());
return oldestEntryTime.getTimeInMillis();
} catch (Exception ex) {
LOG.error("Problem decoding date from last record: {}", currentTreatment);
aapsLogger.error("Problem decoding date from last record: {}", currentTreatment);
return 8; // default return of 6 minutes
}
@ -1422,8 +1401,7 @@ public class MedtronicHistoryData {
List<PumpHistoryEntry> filteredItems = getFilteredItems(PumpHistoryEntryType.ChangeBasalProfile_NewProfile);
if (isLogEnabled())
LOG.debug("hasBasalProfileChanged. Items: " + gson.toJson(filteredItems));
aapsLogger.debug(LTag.PUMP, "hasBasalProfileChanged. Items: " + gson.toJson(filteredItems));
return (filteredItems.size() > 0);
}
@ -1433,8 +1411,7 @@ public class MedtronicHistoryData {
List<PumpHistoryEntry> filteredItems = getFilteredItems(PumpHistoryEntryType.ChangeBasalProfile_NewProfile);
if (isLogEnabled())
LOG.debug("processLastBasalProfileChange. Items: " + filteredItems);
aapsLogger.debug(LTag.PUMP, "processLastBasalProfileChange. Items: " + filteredItems);
PumpHistoryEntry newProfile = null;
Long lastDate = null;
@ -1453,8 +1430,7 @@ public class MedtronicHistoryData {
}
if (newProfile != null) {
if (isLogEnabled())
LOG.debug("processLastBasalProfileChange. item found, setting new basalProfileLocally: " + newProfile);
aapsLogger.debug(LTag.PUMP, "processLastBasalProfileChange. item found, setting new basalProfileLocally: " + newProfile);
BasalProfile basalProfile = (BasalProfile) newProfile.getDecodedData().get("Object");
mdtPumpStatus.basalsByHour = basalProfile.getProfilesByHour();
@ -1518,8 +1494,7 @@ public class MedtronicHistoryData {
} else {
List<PumpHistoryEntry> filteredItems = getFilteredItems(entryTypes);
if (isLogEnabled())
LOG.debug("Items: " + filteredItems);
aapsLogger.debug(LTag.PUMP, "Items: " + filteredItems);
return filteredItems.size() > 0;
}
@ -1528,7 +1503,7 @@ public class MedtronicHistoryData {
private List<PumpHistoryEntry> getFilteredItems(List<PumpHistoryEntry> inList, PumpHistoryEntryType... entryTypes) {
// LOG.debug("InList: " + inList.size());
// aapsLogger.debug(LTag.PUMP, "InList: " + inList.size());
List<PumpHistoryEntry> outList = new ArrayList<>();
if (inList != null && inList.size() > 0) {
@ -1548,7 +1523,7 @@ public class MedtronicHistoryData {
}
}
// LOG.debug("OutList: " + outList.size());
// aapsLogger.debug(LTag.PUMP, "OutList: " + outList.size());
return outList;
}
@ -1563,8 +1538,4 @@ public class MedtronicHistoryData {
return "MedtronicHistoryData::";
}
private static boolean isLogEnabled() {
return (L.isEnabled(L.PUMP));
}
}

View file

@ -72,21 +72,10 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
private final ResourceHelper resourceHelper;
private final ProfileFunction profileFunction;
private final ActivePluginProvider activePlugin;
private final FabricPrivacy fabricPrivacy;
private CompositeDisposable disposable = new CompositeDisposable();
private static TreatmentsPlugin treatmentsPlugin;
/**
* @deprecated Use dagger to get an instance
*/
@Deprecated
public static TreatmentsPlugin getPlugin() {
if (treatmentsPlugin == null)
throw new IllegalStateException("Accessing TreatmentsPlugin before first instantiation");
return treatmentsPlugin;
}
protected TreatmentService service;
private IobTotal lastTreatmentCalculation;
@ -107,7 +96,8 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
Context context,
SP sp,
ProfileFunction profileFunction,
ActivePluginProvider activePlugin
ActivePluginProvider activePlugin,
FabricPrivacy fabricPrivacy
) {
super(new PluginDescription()
.mainType(PluginType.TREATMENT)
@ -125,7 +115,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
this.sp = sp;
this.profileFunction = profileFunction;
this.activePlugin = activePlugin;
treatmentsPlugin = this;
this.fabricPrivacy = fabricPrivacy;
}
@Override
@ -143,19 +133,19 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
updateTotalIOBTreatments();
rxBus.send(event.getNext());
},
exception -> FabricPrivacy.getInstance().logException(exception)
fabricPrivacy::logException
));
disposable.add(rxBus
.toObservable(EventReloadProfileSwitchData.class)
.observeOn(Schedulers.io())
.subscribe(event -> initializeProfileSwitchData(range()),
exception -> FabricPrivacy.getInstance().logException(exception)
fabricPrivacy::logException
));
disposable.add(rxBus
.toObservable(EventTempTargetChange.class)
.observeOn(Schedulers.io())
.subscribe(event -> initializeTempTargetData(range()),
exception -> FabricPrivacy.getInstance().logException(exception)
fabricPrivacy::logException
));
disposable.add(rxBus
.toObservable(EventReloadTempBasalData.class)
@ -165,7 +155,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
initializeTempBasalData(range());
updateTotalIOBTempBasals();
},
exception -> FabricPrivacy.getInstance().logException(exception)
fabricPrivacy::logException
));
}
@ -641,7 +631,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
Bundle bundle = new Bundle();
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "TreatmentClash");
bundle.putString(FirebaseAnalytics.Param.VALUE, status);
FabricPrivacy.getInstance().logCustom(bundle);
fabricPrivacy.logCustom(bundle);
}
return newRecordCreated;
@ -722,14 +712,14 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
@Override
public void doProfileSwitch(@NotNull final ProfileStore profileStore, @NotNull final String profileName, final int duration, final int percentage, final int timeShift, final long date) {
ProfileSwitch profileSwitch = profileFunction.prepareProfileSwitch(profileStore, profileName, duration, percentage, timeShift, date);
treatmentsPlugin.addToHistoryProfileSwitch(profileSwitch);
addToHistoryProfileSwitch(profileSwitch);
if (percentage == 90 && duration == 10)
sp.putBoolean(R.string.key_objectiveuseprofileswitch, true);
}
@Override
public void doProfileSwitch(final int duration, final int percentage, final int timeShift) {
ProfileSwitch profileSwitch = treatmentsPlugin.getProfileSwitchFromHistory(System.currentTimeMillis());
ProfileSwitch profileSwitch = getProfileSwitchFromHistory(System.currentTimeMillis());
if (profileSwitch != null) {
profileSwitch = new ProfileSwitch(getInjector());
profileSwitch.date = System.currentTimeMillis();
@ -741,7 +731,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
profileSwitch.isCPP = percentage != 100 || timeShift != 0;
profileSwitch.timeshift = timeShift;
profileSwitch.percentage = percentage;
treatmentsPlugin.addToHistoryProfileSwitch(profileSwitch);
addToHistoryProfileSwitch(profileSwitch);
} else {
getAapsLogger().error(LTag.PROFILE, "No profile switch exists");
}

View file

@ -14,6 +14,7 @@ import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction
import info.nightscout.androidaps.plugins.treatments.TreatmentService
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.MidnightTime
import info.nightscout.androidaps.utils.T
@ -29,8 +30,9 @@ class TddCalculator @Inject constructor(
val mainApp: MainApp,
val sp: SP,
val activePlugin: ActivePluginProvider,
val profileFunction: ProfileFunction
) : TreatmentsPlugin(injector, aapsLogger, rxBus, resourceHelper, mainApp, sp, profileFunction, activePlugin) {
val profileFunction: ProfileFunction,
fabricPrivacy: FabricPrivacy
) : TreatmentsPlugin(injector, aapsLogger, rxBus, resourceHelper, mainApp, sp, profileFunction, activePlugin, fabricPrivacy) {
init {
service = TreatmentService() // plugin is not started