This commit is contained in:
Milos Kozak 2020-03-16 22:49:34 +01:00
parent 66bea16bdf
commit 21f8a13098
27 changed files with 337 additions and 389 deletions

View file

@ -11,7 +11,6 @@ import android.net.ConnectivityManager;
import android.net.wifi.WifiManager; import android.net.wifi.WifiManager;
import androidx.annotation.ColorRes; import androidx.annotation.ColorRes;
import androidx.annotation.PluralsRes;
import androidx.annotation.StringRes; import androidx.annotation.StringRes;
import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationCompat;
import androidx.core.app.TaskStackBuilder; import androidx.core.app.TaskStackBuilder;
@ -25,11 +24,6 @@ import com.j256.ormlite.android.apptools.OpenHelperManager;
import net.danlew.android.joda.JodaTimeAndroid; import net.danlew.android.joda.JodaTimeAndroid;
import org.json.JSONException; import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.ArrayList;
import javax.inject.Inject; import javax.inject.Inject;
@ -39,20 +33,15 @@ import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.dependencyInjection.DaggerAppComponent; import info.nightscout.androidaps.dependencyInjection.DaggerAppComponent;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin;
import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin; import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin;
import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAPlugin; import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAPlugin;
import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin; import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.PluginStore; import info.nightscout.androidaps.plugins.configBuilder.PluginStore;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction;
import info.nightscout.androidaps.plugins.constraints.dstHelper.DstHelperPlugin; import info.nightscout.androidaps.plugins.constraints.dstHelper.DstHelperPlugin;
import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin; import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin;
import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin; import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin;
@ -65,7 +54,6 @@ import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin;
import info.nightscout.androidaps.plugins.general.careportal.CareportalPlugin; import info.nightscout.androidaps.plugins.general.careportal.CareportalPlugin;
import info.nightscout.androidaps.plugins.general.dataBroadcaster.DataBroadcastPlugin; import info.nightscout.androidaps.plugins.general.dataBroadcaster.DataBroadcastPlugin;
import info.nightscout.androidaps.plugins.general.food.FoodPlugin; import info.nightscout.androidaps.plugins.general.food.FoodPlugin;
import info.nightscout.androidaps.plugins.general.maintenance.LoggerUtils;
import info.nightscout.androidaps.plugins.general.maintenance.MaintenancePlugin; import info.nightscout.androidaps.plugins.general.maintenance.MaintenancePlugin;
import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin; import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
@ -112,12 +100,11 @@ import info.nightscout.androidaps.services.Intents;
import info.nightscout.androidaps.utils.ActivityMonitor; import info.nightscout.androidaps.utils.ActivityMonitor;
import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.LocaleHelper; import info.nightscout.androidaps.utils.LocaleHelper;
import info.nightscout.androidaps.utils.SP;
import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
import io.fabric.sdk.android.Fabric; import io.fabric.sdk.android.Fabric;
public class MainApp extends DaggerApplication { public class MainApp extends DaggerApplication {
static Logger log = StacktraceLoggerWrapper.getLogger(L.CORE);
static MainApp sInstance; static MainApp sInstance;
private static Resources sResources; private static Resources sResources;
@ -126,7 +113,7 @@ public class MainApp extends DaggerApplication {
static DatabaseHelper sDatabaseHelper = null; static DatabaseHelper sDatabaseHelper = null;
static DataReceiver dataReceiver = new DataReceiver(); DataReceiver dataReceiver = new DataReceiver();
TimeDateOrTZChangeReceiver timeDateOrTZChangeReceiver; TimeDateOrTZChangeReceiver timeDateOrTZChangeReceiver;
private String CHANNEL_ID = "AndroidAPS-Ongoing"; // TODO: move to OngoingNotificationProvider (and dagger) private String CHANNEL_ID = "AndroidAPS-Ongoing"; // TODO: move to OngoingNotificationProvider (and dagger)
@ -140,6 +127,8 @@ public class MainApp extends DaggerApplication {
@Inject FabricPrivacy fabricPrivacy; @Inject FabricPrivacy fabricPrivacy;
@Inject ResourceHelper resourceHelper; @Inject ResourceHelper resourceHelper;
@Inject VersionCheckerUtils versionCheckersUtils; @Inject VersionCheckerUtils versionCheckersUtils;
@Inject SP sp;
@Inject ProfileFunction profileFunction;
@Inject ActionsPlugin actionsPlugin; @Inject ActionsPlugin actionsPlugin;
@Inject AutomationPlugin automationPlugin; @Inject AutomationPlugin automationPlugin;
@ -200,7 +189,7 @@ public class MainApp extends DaggerApplication {
public void onCreate() { public void onCreate() {
super.onCreate(); super.onCreate();
log.debug("onCreate"); aapsLogger.debug("onCreate");
sInstance = this; sInstance = this;
sResources = getResources(); sResources = getResources();
LocaleHelper.INSTANCE.update(this); LocaleHelper.INSTANCE.update(this);
@ -222,7 +211,7 @@ public class MainApp extends DaggerApplication {
Fabric.with(this, new Crashlytics()); Fabric.with(this, new Crashlytics());
} }
} catch (Exception e) { } catch (Exception e) {
log.error("Error with Fabric init! " + e); aapsLogger.error("Error with Fabric init! " + e);
} }
registerActivityLifecycleCallbacks(activityMonitor); registerActivityLifecycleCallbacks(activityMonitor);
@ -232,9 +221,9 @@ public class MainApp extends DaggerApplication {
JodaTimeAndroid.init(this); JodaTimeAndroid.init(this);
log.info("Version: " + BuildConfig.VERSION_NAME); aapsLogger.debug("Version: " + BuildConfig.VERSION_NAME);
log.info("BuildVersion: " + BuildConfig.BUILDVERSION); aapsLogger.debug("BuildVersion: " + BuildConfig.BUILDVERSION);
log.info("Remote: " + BuildConfig.REMOTE); aapsLogger.debug("Remote: " + BuildConfig.REMOTE);
registerLocalBroadcastReceiver(); registerLocalBroadcastReceiver();
@ -311,23 +300,23 @@ public class MainApp extends DaggerApplication {
// guarantee that the unreachable threshold is at least 30 and of type String // guarantee that the unreachable threshold is at least 30 and of type String
// Added in 1.57 at 21.01.2018 // Added in 1.57 at 21.01.2018
int unreachable_threshold = SP.getInt(R.string.key_pump_unreachable_threshold, 30); int unreachable_threshold = sp.getInt(R.string.key_pump_unreachable_threshold, 30);
SP.remove(R.string.key_pump_unreachable_threshold); sp.remove(R.string.key_pump_unreachable_threshold);
if (unreachable_threshold < 30) unreachable_threshold = 30; if (unreachable_threshold < 30) unreachable_threshold = 30;
SP.putString(R.string.key_pump_unreachable_threshold, Integer.toString(unreachable_threshold)); sp.putString(R.string.key_pump_unreachable_threshold, Integer.toString(unreachable_threshold));
// 2.5 -> 2.6 // 2.5 -> 2.6
if (!SP.contains(R.string.key_units)) { if (!sp.contains(R.string.key_units)) {
String newUnits = Constants.MGDL; String newUnits = Constants.MGDL;
Profile p = ProfileFunctions.getInstance().getProfile(); Profile p = profileFunction.getProfile();
if (p != null && p.getData() != null && p.getData().has("units")) { if (p != null && p.getData() != null && p.getData().has("units")) {
try { try {
newUnits = p.getData().getString("units"); newUnits = p.getData().getString("units");
} catch (JSONException e) { } catch (JSONException e) {
log.error("Unhandled exception", e); aapsLogger.error("Unhandled exception", e);
} }
} }
SP.putString(R.string.key_units, newUnits); sp.putString(R.string.key_units, newUnits);
} }
} }
@ -355,7 +344,7 @@ public class MainApp extends DaggerApplication {
IntentFilter intentFilter = new IntentFilter(); IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION ); intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
registerReceiver(new NetworkChangeReceiver(), intentFilter); registerReceiver(new NetworkChangeReceiver(), intentFilter);
} }
@ -369,11 +358,6 @@ public class MainApp extends DaggerApplication {
return sResources.getString(id, args); return sResources.getString(id, args);
} }
@Deprecated
public static String gq(@PluralsRes int id, int quantity, Object... args) {
return sResources.getQuantityString(id, quantity, args);
}
@Deprecated @Deprecated
public static int gc(@ColorRes int id) { public static int gc(@ColorRes int id) {
return ContextCompat.getColor(instance(), id); return ContextCompat.getColor(instance(), id);
@ -444,16 +428,4 @@ public class MainApp extends DaggerApplication {
keepAliveManager.cancelAlarm(this); keepAliveManager.cancelAlarm(this);
super.onTerminate(); super.onTerminate();
} }
@Deprecated
public static int dpToPx(int dp) {
float scale = sResources.getDisplayMetrics().density;
return (int) (dp * scale + 0.5f);
}
@Deprecated
public ResourceHelper getResourceHelper() {
return resourceHelper;
}
} }

View file

@ -41,6 +41,7 @@ import info.nightscout.androidaps.plugins.treatments.TreatmentsFragment
import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsBolusFragment import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsBolusFragment
import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsCareportalFragment import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsCareportalFragment
import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsProfileSwitchFragment import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsProfileSwitchFragment
import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsTempTargetFragment
@Module @Module
@Suppress("unused") @Suppress("unused")
@ -53,6 +54,7 @@ abstract class FragmentsModule {
@ContributesAndroidInjector abstract fun contributesBGSourceFragment(): BGSourceFragment @ContributesAndroidInjector abstract fun contributesBGSourceFragment(): BGSourceFragment
@ContributesAndroidInjector abstract fun contributesCareportalFragment(): CareportalFragment @ContributesAndroidInjector abstract fun contributesCareportalFragment(): CareportalFragment
@ContributesAndroidInjector abstract fun contributesComboFragment(): ComboFragment @ContributesAndroidInjector abstract fun contributesComboFragment(): ComboFragment
@ContributesAndroidInjector @ContributesAndroidInjector
abstract fun contributesConfigBuilderFragment(): ConfigBuilderFragment abstract fun contributesConfigBuilderFragment(): ConfigBuilderFragment
@ -71,6 +73,7 @@ abstract class FragmentsModule {
@ContributesAndroidInjector abstract fun contributesMedtronicFragment(): MedtronicFragment @ContributesAndroidInjector abstract fun contributesMedtronicFragment(): MedtronicFragment
@ContributesAndroidInjector abstract fun contributesNSProfileFragment(): NSProfileFragment @ContributesAndroidInjector abstract fun contributesNSProfileFragment(): NSProfileFragment
@ContributesAndroidInjector abstract fun contributesNSClientFragment(): NSClientFragment @ContributesAndroidInjector abstract fun contributesNSClientFragment(): NSClientFragment
@ContributesAndroidInjector @ContributesAndroidInjector
abstract fun contributesSmsCommunicatorFragment(): SmsCommunicatorFragment abstract fun contributesSmsCommunicatorFragment(): SmsCommunicatorFragment
@ -78,6 +81,8 @@ abstract class FragmentsModule {
@ContributesAndroidInjector abstract fun contributesTreatmentsFragment(): TreatmentsFragment @ContributesAndroidInjector abstract fun contributesTreatmentsFragment(): TreatmentsFragment
@ContributesAndroidInjector @ContributesAndroidInjector
abstract fun contributesTreatmentsBolusFragment(): TreatmentsBolusFragment abstract fun contributesTreatmentsBolusFragment(): TreatmentsBolusFragment
@ContributesAndroidInjector
abstract fun contributesTreatmentsTempTargetFragment(): TreatmentsTempTargetFragment
@ContributesAndroidInjector @ContributesAndroidInjector
abstract fun contributesTreatmentsCareportalFragment(): TreatmentsCareportalFragment abstract fun contributesTreatmentsCareportalFragment(): TreatmentsCareportalFragment
@ -94,6 +99,7 @@ abstract class FragmentsModule {
@ContributesAndroidInjector abstract fun contributesEditActionDialog(): EditActionDialog @ContributesAndroidInjector abstract fun contributesEditActionDialog(): EditActionDialog
@ContributesAndroidInjector abstract fun contributesEditEventDialog(): EditEventDialog @ContributesAndroidInjector abstract fun contributesEditEventDialog(): EditEventDialog
@ContributesAndroidInjector abstract fun contributesEditTriggerDialog(): EditTriggerDialog @ContributesAndroidInjector abstract fun contributesEditTriggerDialog(): EditTriggerDialog
@ContributesAndroidInjector @ContributesAndroidInjector
abstract fun contributesEditQuickWizardDialog(): EditQuickWizardDialog abstract fun contributesEditQuickWizardDialog(): EditQuickWizardDialog

View file

@ -5,6 +5,7 @@ import dagger.android.ContributesAndroidInjector
import info.nightscout.androidaps.plugins.general.nsclient.services.NSClientService import info.nightscout.androidaps.plugins.general.nsclient.services.NSClientService
import info.nightscout.androidaps.plugins.general.persistentNotification.DummyService import info.nightscout.androidaps.plugins.general.persistentNotification.DummyService
import info.nightscout.androidaps.plugins.general.wear.wearintegration.WatchUpdaterService import info.nightscout.androidaps.plugins.general.wear.wearintegration.WatchUpdaterService
import info.nightscout.androidaps.plugins.pump.danaR.services.AbstractDanaRExecutionService
import info.nightscout.androidaps.plugins.pump.danaR.services.DanaRExecutionService import info.nightscout.androidaps.plugins.pump.danaR.services.DanaRExecutionService
import info.nightscout.androidaps.plugins.pump.danaRKorean.services.DanaRKoreanExecutionService import info.nightscout.androidaps.plugins.pump.danaRKorean.services.DanaRKoreanExecutionService
import info.nightscout.androidaps.plugins.pump.danaRS.services.DanaRSService import info.nightscout.androidaps.plugins.pump.danaRS.services.DanaRSService
@ -17,6 +18,7 @@ import info.nightscout.androidaps.services.LocationService
@Suppress("unused") @Suppress("unused")
abstract class ServicesModule { abstract class ServicesModule {
@ContributesAndroidInjector abstract fun contributesAbstractDanaRExecutionService(): AbstractDanaRExecutionService
@ContributesAndroidInjector abstract fun contributesAlarmSoundService(): AlarmSoundService @ContributesAndroidInjector abstract fun contributesAlarmSoundService(): AlarmSoundService
@ContributesAndroidInjector abstract fun contributesDataService(): DataService @ContributesAndroidInjector abstract fun contributesDataService(): DataService
@ContributesAndroidInjector abstract fun contributesDummyService(): DummyService @ContributesAndroidInjector abstract fun contributesDummyService(): DummyService

View file

@ -44,6 +44,7 @@ public class DetermineBasalAdapterAMAJS {
@Inject ConstraintChecker constraintChecker; @Inject ConstraintChecker constraintChecker;
@Inject SP sp; @Inject SP sp;
@Inject ProfileFunction profileFunction; @Inject ProfileFunction profileFunction;
@Inject TreatmentsPlugin treatmentsPlugin;
private ScriptReader mScriptReader; private ScriptReader mScriptReader;
@ -228,7 +229,7 @@ public class DetermineBasalAdapterAMAJS {
} }
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
TemporaryBasal tb = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now); TemporaryBasal tb = treatmentsPlugin.getTempBasalFromHistory(now);
mCurrentTemp = new JSONObject(); mCurrentTemp = new JSONObject();
mCurrentTemp.put("temp", "absolute"); mCurrentTemp.put("temp", "absolute");
@ -236,7 +237,7 @@ public class DetermineBasalAdapterAMAJS {
mCurrentTemp.put("rate", tb != null ? tb.tempBasalConvertedToAbsolute(now, profile) : 0d); mCurrentTemp.put("rate", tb != null ? tb.tempBasalConvertedToAbsolute(now, profile) : 0d);
// as we have non default temps longer than 30 mintues // as we have non default temps longer than 30 mintues
TemporaryBasal tempBasal = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis()); TemporaryBasal tempBasal = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis());
if (tempBasal != null) { if (tempBasal != null) {
mCurrentTemp.put("minutesrunning", tempBasal.getRealDuration()); mCurrentTemp.put("minutesrunning", tempBasal.getRealDuration());
} }

View file

@ -38,6 +38,7 @@ public class DetermineBasalAdapterMAJS {
private HasAndroidInjector injector; private HasAndroidInjector injector;
@Inject AAPSLogger aapsLogger; @Inject AAPSLogger aapsLogger;
@Inject ProfileFunction profileFunction; @Inject ProfileFunction profileFunction;
@Inject TreatmentsPlugin treatmentsPlugin;
private ScriptReader mScriptReader; private ScriptReader mScriptReader;
private JSONObject mProfile; private JSONObject mProfile;
@ -187,7 +188,7 @@ public class DetermineBasalAdapterMAJS {
} }
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
TemporaryBasal tb = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now); TemporaryBasal tb = treatmentsPlugin.getTempBasalFromHistory(now);
mCurrentTemp = new JSONObject(); mCurrentTemp = new JSONObject();
mCurrentTemp.put("duration", tb != null ? tb.getPlannedRemainingMinutes() : 0); mCurrentTemp.put("duration", tb != null ? tb.getPlannedRemainingMinutes() : 0);

View file

@ -45,6 +45,7 @@ public class DetermineBasalAdapterSMBJS {
@Inject ConstraintChecker constraintChecker; @Inject ConstraintChecker constraintChecker;
@Inject SP sp; @Inject SP sp;
@Inject ProfileFunction profileFunction; @Inject ProfileFunction profileFunction;
@Inject TreatmentsPlugin treatmentsPlugin;
private ScriptReader mScriptReader; private ScriptReader mScriptReader;
private JSONObject mProfile; private JSONObject mProfile;
@ -283,7 +284,7 @@ public class DetermineBasalAdapterSMBJS {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
TemporaryBasal tb = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now); TemporaryBasal tb = treatmentsPlugin.getTempBasalFromHistory(now);
mCurrentTemp = new JSONObject(); mCurrentTemp = new JSONObject();
mCurrentTemp.put("temp", "absolute"); mCurrentTemp.put("temp", "absolute");
@ -291,7 +292,7 @@ public class DetermineBasalAdapterSMBJS {
mCurrentTemp.put("rate", tb != null ? tb.tempBasalConvertedToAbsolute(now, profile) : 0d); mCurrentTemp.put("rate", tb != null ? tb.tempBasalConvertedToAbsolute(now, profile) : 0d);
// as we have non default temps longer than 30 mintues // as we have non default temps longer than 30 mintues
TemporaryBasal tempBasal = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis()); TemporaryBasal tempBasal = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis());
if (tempBasal != null) { if (tempBasal != null) {
mCurrentTemp.put("minutesrunning", tempBasal.getRealDuration()); mCurrentTemp.put("minutesrunning", tempBasal.getRealDuration());
} }

View file

@ -24,12 +24,15 @@ import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientR
import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientUpdateGUI; import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientUpdateGUI;
import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.OKDialog; import info.nightscout.androidaps.utils.OKDialog;
import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.CompositeDisposable;
public class NSClientFragment extends DaggerFragment implements View.OnClickListener, CompoundButton.OnCheckedChangeListener { public class NSClientFragment extends DaggerFragment implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
@Inject NSClientPlugin nsClientPlugin; @Inject NSClientPlugin nsClientPlugin;
@Inject SP sp;
@Inject ResourceHelper resourceHelper;
private CompositeDisposable disposable = new CompositeDisposable(); private CompositeDisposable disposable = new CompositeDisposable();
@ -135,7 +138,7 @@ public class NSClientFragment extends DaggerFragment implements View.OnClickList
FabricPrivacy.getInstance().logCustom("NSClientPause"); FabricPrivacy.getInstance().logCustom("NSClientPause");
break; break;
case R.id.nsclientinternal_autoscroll: case R.id.nsclientinternal_autoscroll:
SP.putBoolean(R.string.key_nsclientinternal_autoscroll, isChecked); sp.putBoolean(R.string.key_nsclientinternal_autoscroll, isChecked);
nsClientPlugin.autoscroll = isChecked; nsClientPlugin.autoscroll = isChecked;
updateGui(); updateGui();
break; break;
@ -144,13 +147,13 @@ public class NSClientFragment extends DaggerFragment implements View.OnClickList
protected void updateGui() { protected void updateGui() {
nsClientPlugin.updateLog(); nsClientPlugin.updateLog();
pausedCheckbox.setChecked(SP.getBoolean(R.string.key_nsclientinternal_paused, false)); pausedCheckbox.setChecked(sp.getBoolean(R.string.key_nsclientinternal_paused, false));
logTextView.setText(nsClientPlugin.textLog); logTextView.setText(nsClientPlugin.textLog);
if (nsClientPlugin.autoscroll) { if (nsClientPlugin.autoscroll) {
logScrollview.fullScroll(ScrollView.FOCUS_DOWN); logScrollview.fullScroll(ScrollView.FOCUS_DOWN);
} }
urlTextView.setText(nsClientPlugin.url()); urlTextView.setText(nsClientPlugin.url());
Spanned queuetext = Html.fromHtml(MainApp.gs(R.string.queue) + " <b>" + UploadQueue.size() + "</b>"); Spanned queuetext = Html.fromHtml(resourceHelper.gs(R.string.queue) + " <b>" + UploadQueue.size() + "</b>");
queueTextView.setText(queuetext); queueTextView.setText(queuetext);
statusTextView.setText(nsClientPlugin.status); statusTextView.setText(nsClientPlugin.status);
} }

View file

@ -14,7 +14,6 @@ import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceScreen; import androidx.preference.PreferenceScreen;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -25,7 +24,6 @@ import javax.inject.Singleton;
import dagger.android.HasAndroidInjector; import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.events.EventChargingState; import info.nightscout.androidaps.events.EventChargingState;
@ -35,8 +33,7 @@ import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.general.nsclient.data.AlarmAck; import info.nightscout.androidaps.plugins.general.nsclient.data.AlarmAck;
import info.nightscout.androidaps.plugins.general.nsclient.data.NSAlarm; import info.nightscout.androidaps.plugins.general.nsclient.data.NSAlarm;
@ -46,20 +43,21 @@ import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientS
import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientUpdateGUI; import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientUpdateGUI;
import info.nightscout.androidaps.plugins.general.nsclient.services.NSClientService; import info.nightscout.androidaps.plugins.general.nsclient.services.NSClientService;
import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.SP;
import info.nightscout.androidaps.utils.ToastUtils; import info.nightscout.androidaps.utils.ToastUtils;
import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers; import io.reactivex.schedulers.Schedulers;
@Singleton @Singleton
public class NSClientPlugin extends PluginBase { public class NSClientPlugin extends PluginBase {
private Logger log = StacktraceLoggerWrapper.getLogger(L.NSCLIENT);
private CompositeDisposable disposable = new CompositeDisposable(); private CompositeDisposable disposable = new CompositeDisposable();
private final AAPSLogger aapsLogger; private final AAPSLogger aapsLogger;
private final RxBusWrapper rxBus; private final RxBusWrapper rxBus;
private final ResourceHelper resourceHelper; private final ResourceHelper resourceHelper;
private final Context context;
private final SP sp;
public Handler handler; public Handler handler;
@ -80,7 +78,9 @@ public class NSClientPlugin extends PluginBase {
HasAndroidInjector injector, HasAndroidInjector injector,
AAPSLogger aapsLogger, AAPSLogger aapsLogger,
RxBusWrapper rxBus, RxBusWrapper rxBus,
ResourceHelper resourceHelper ResourceHelper resourceHelper,
Context context,
SP sp
) { ) {
super(new PluginDescription() super(new PluginDescription()
.mainType(PluginType.GENERAL) .mainType(PluginType.GENERAL)
@ -95,6 +95,8 @@ public class NSClientPlugin extends PluginBase {
this.aapsLogger = aapsLogger; this.aapsLogger = aapsLogger;
this.rxBus = rxBus; this.rxBus = rxBus;
this.resourceHelper = resourceHelper; this.resourceHelper = resourceHelper;
this.context = context;
this.sp = sp;
if (Config.NSCLIENT) { if (Config.NSCLIENT) {
getPluginDescription().alwaysEnabled(true).visibleByDefault(true); getPluginDescription().alwaysEnabled(true).visibleByDefault(true);
@ -114,10 +116,9 @@ public class NSClientPlugin extends PluginBase {
@Override @Override
protected void onStart() { protected void onStart() {
paused = SP.getBoolean(R.string.key_nsclientinternal_paused, false); paused = sp.getBoolean(R.string.key_nsclientinternal_paused, false);
autoscroll = SP.getBoolean(R.string.key_nsclientinternal_autoscroll, true); autoscroll = sp.getBoolean(R.string.key_nsclientinternal_autoscroll, true);
Context context = MainApp.instance().getApplicationContext();
Intent intent = new Intent(context, NSClientService.class); Intent intent = new Intent(context, NSClientService.class);
context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE); context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
super.onStart(); super.onStart();
@ -127,7 +128,7 @@ public class NSClientPlugin extends PluginBase {
.toObservable(EventNSClientStatus.class) .toObservable(EventNSClientStatus.class)
.observeOn(Schedulers.io()) .observeOn(Schedulers.io())
.subscribe(event -> { .subscribe(event -> {
status = event.getStatus(MainApp.instance().getResourceHelper()); status = event.getStatus(resourceHelper);
rxBus.send(new EventNSClientUpdateGUI()); rxBus.send(new EventNSClientUpdateGUI());
}, exception -> FabricPrivacy.getInstance().logException(exception)) }, exception -> FabricPrivacy.getInstance().logException(exception))
); );
@ -146,7 +147,7 @@ public class NSClientPlugin extends PluginBase {
.observeOn(Schedulers.io()) .observeOn(Schedulers.io())
.subscribe(event -> { .subscribe(event -> {
if (nsClientService != null) { if (nsClientService != null) {
MainApp.instance().getApplicationContext().unbindService(mConnection); context.unbindService(mConnection);
} }
}, exception -> FabricPrivacy.getInstance().logException(exception)) }, exception -> FabricPrivacy.getInstance().logException(exception))
); );
@ -155,8 +156,7 @@ public class NSClientPlugin extends PluginBase {
.observeOn(Schedulers.io()) .observeOn(Schedulers.io())
.subscribe(event -> { .subscribe(event -> {
addToLog(event); addToLog(event);
if (L.isEnabled(L.NSCLIENT)) aapsLogger.debug(LTag.NSCLIENT, event.getAction() + " " + event.getLogText());
log.debug(event.getAction() + " " + event.getLogText());
}, exception -> FabricPrivacy.getInstance().logException(exception)) }, exception -> FabricPrivacy.getInstance().logException(exception))
); );
disposable.add(rxBus disposable.add(rxBus
@ -173,7 +173,7 @@ public class NSClientPlugin extends PluginBase {
@Override @Override
protected void onStop() { protected void onStop() {
MainApp.instance().getApplicationContext().unbindService(mConnection); context.getApplicationContext().unbindService(mConnection);
disposable.clear(); disposable.clear();
super.onStop(); super.onStop();
} }
@ -183,14 +183,14 @@ public class NSClientPlugin extends PluginBase {
super.preprocessPreferences(preferenceFragment); super.preprocessPreferences(preferenceFragment);
if (Config.NSCLIENT) { if (Config.NSCLIENT) {
PreferenceScreen scrnAdvancedSettings = (PreferenceScreen) preferenceFragment.findPreference(MainApp.gs(R.string.key_advancedsettings)); PreferenceScreen scrnAdvancedSettings = preferenceFragment.findPreference(resourceHelper.gs(R.string.key_advancedsettings));
if (scrnAdvancedSettings != null) { if (scrnAdvancedSettings != null) {
scrnAdvancedSettings.removePreference(preferenceFragment.findPreference(MainApp.gs(R.string.key_statuslights_res_warning))); scrnAdvancedSettings.removePreference(preferenceFragment.findPreference(resourceHelper.gs(R.string.key_statuslights_res_warning)));
scrnAdvancedSettings.removePreference(preferenceFragment.findPreference(MainApp.gs(R.string.key_statuslights_res_critical))); scrnAdvancedSettings.removePreference(preferenceFragment.findPreference(resourceHelper.gs(R.string.key_statuslights_res_critical)));
scrnAdvancedSettings.removePreference(preferenceFragment.findPreference(MainApp.gs(R.string.key_statuslights_bat_warning))); scrnAdvancedSettings.removePreference(preferenceFragment.findPreference(resourceHelper.gs(R.string.key_statuslights_bat_warning)));
scrnAdvancedSettings.removePreference(preferenceFragment.findPreference(MainApp.gs(R.string.key_statuslights_bat_critical))); scrnAdvancedSettings.removePreference(preferenceFragment.findPreference(resourceHelper.gs(R.string.key_statuslights_bat_critical)));
scrnAdvancedSettings.removePreference(preferenceFragment.findPreference(MainApp.gs(R.string.key_show_statuslights))); scrnAdvancedSettings.removePreference(preferenceFragment.findPreference(resourceHelper.gs(R.string.key_show_statuslights)));
scrnAdvancedSettings.removePreference(preferenceFragment.findPreference(MainApp.gs(R.string.key_show_statuslights_extended))); scrnAdvancedSettings.removePreference(preferenceFragment.findPreference(resourceHelper.gs(R.string.key_show_statuslights_extended)));
} }
} }
} }
@ -198,14 +198,12 @@ public class NSClientPlugin extends PluginBase {
private ServiceConnection mConnection = new ServiceConnection() { private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) { public void onServiceDisconnected(ComponentName name) {
if (L.isEnabled(L.NSCLIENT)) aapsLogger.debug(LTag.NSCLIENT, "Service is disconnected");
log.debug("Service is disconnected");
nsClientService = null; nsClientService = null;
} }
public void onServiceConnected(ComponentName name, IBinder service) { public void onServiceConnected(ComponentName name, IBinder service) {
if (L.isEnabled(L.NSCLIENT)) aapsLogger.debug(LTag.NSCLIENT, "Service is connected");
log.debug("Service is connected");
NSClientService.LocalBinder mLocalBinder = (NSClientService.LocalBinder) service; NSClientService.LocalBinder mLocalBinder = (NSClientService.LocalBinder) service;
if (mLocalBinder != null) // is null when running in roboelectric if (mLocalBinder != null) // is null when running in roboelectric
nsClientService = mLocalBinder.getServiceInstance(); nsClientService = mLocalBinder.getServiceInstance();
@ -244,7 +242,7 @@ public class NSClientPlugin extends PluginBase {
} }
textLog = Html.fromHtml(newTextLog.toString()); textLog = Html.fromHtml(newTextLog.toString());
} catch (OutOfMemoryError e) { } catch (OutOfMemoryError e) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), "Out of memory!\nStop using this phone !!!", R.raw.error); ToastUtils.showToastInUiThread(context, "Out of memory!\nStop using this phone !!!", R.raw.error);
} }
} }
@ -254,9 +252,9 @@ public class NSClientPlugin extends PluginBase {
} }
public void pause(boolean newState) { public void pause(boolean newState) {
SP.putBoolean(R.string.key_nsclientinternal_paused, newState); sp.putBoolean(R.string.key_nsclientinternal_paused, newState);
paused = newState; paused = newState;
rxBus.send(new EventPreferenceChange(MainApp.resources(), R.string.key_nsclientinternal_paused)); rxBus.send(new EventPreferenceChange(resourceHelper, R.string.key_nsclientinternal_paused));
} }
public UploadQueue queue() { public UploadQueue queue() {
@ -276,9 +274,8 @@ public class NSClientPlugin extends PluginBase {
if (!isEnabled(PluginType.GENERAL)) { if (!isEnabled(PluginType.GENERAL)) {
return; return;
} }
if (SP.getBoolean(R.string.key_ns_noupload, false)) { if (sp.getBoolean(R.string.key_ns_noupload, false)) {
if (L.isEnabled(L.NSCLIENT)) aapsLogger.debug(LTag.NSCLIENT, "Upload disabled. Message dropped");
log.debug("Upload disabled. Message dropped");
return; return;
} }

View file

@ -512,7 +512,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
} }
} }
} else { } else {
tb2 = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now); //use "now" to express current situation tb2 = treatmentsPlugin.getTempBasalFromHistory(now); //use "now" to express current situation
if (tb2 != null) { if (tb2 != null) {
//onset at the end //onset at the end
Profile profileTB = profileFunction.getProfile(runningTime); Profile profileTB = profileFunction.getProfile(runningTime);

View file

@ -16,10 +16,8 @@ import androidx.annotation.NonNull;
import javax.inject.Inject; import javax.inject.Inject;
import dagger.android.support.DaggerFragment; import dagger.android.support.DaggerFragment;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.pump.combo.events.EventComboPumpUpdateGUI; import info.nightscout.androidaps.plugins.pump.combo.events.EventComboPumpUpdateGUI;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.PumpState; import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.PumpState;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.Bolus; import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.Bolus;
@ -28,13 +26,17 @@ import info.nightscout.androidaps.queue.CommandQueue;
import info.nightscout.androidaps.queue.events.EventQueueChanged; import info.nightscout.androidaps.queue.events.EventQueueChanged;
import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.CompositeDisposable;
public class ComboFragment extends DaggerFragment implements View.OnClickListener { public class ComboFragment extends DaggerFragment implements View.OnClickListener {
@Inject ComboPlugin comboPlugin; @Inject ComboPlugin comboPlugin;
@Inject CommandQueue commandQueue; @Inject CommandQueue commandQueue;
@Inject ResourceHelper resourceHelper;
@Inject RxBusWrapper rxBus;
@Inject SP sp;
private CompositeDisposable disposable = new CompositeDisposable(); private CompositeDisposable disposable = new CompositeDisposable();
@ -75,12 +77,12 @@ public class ComboFragment extends DaggerFragment implements View.OnClickListene
@Override @Override
public synchronized void onResume() { public synchronized void onResume() {
super.onResume(); super.onResume();
disposable.add(RxBus.Companion.getINSTANCE() disposable.add(rxBus
.toObservable(EventComboPumpUpdateGUI.class) .toObservable(EventComboPumpUpdateGUI.class)
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
.subscribe(event -> updateGui(), exception -> FabricPrivacy.getInstance().logException(exception)) .subscribe(event -> updateGui(), exception -> FabricPrivacy.getInstance().logException(exception))
); );
disposable.add(RxBus.Companion.getINSTANCE() disposable.add(rxBus
.toObservable(EventQueueChanged.class) .toObservable(EventQueueChanged.class)
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
.subscribe(event -> updateGui(), exception -> FabricPrivacy.getInstance().logException(exception)) .subscribe(event -> updateGui(), exception -> FabricPrivacy.getInstance().logException(exception))
@ -151,7 +153,7 @@ public class ComboFragment extends DaggerFragment implements View.OnClickListene
} else { } else {
activityView.setTextColor(Color.RED); activityView.setTextColor(Color.RED);
activityView.setTextSize(14); activityView.setTextSize(14);
activityView.setText(MainApp.gs(R.string.pump_unreachable)); activityView.setText(resourceHelper.gs(R.string.pump_unreachable));
} }
if (comboPlugin.isInitialized()) { if (comboPlugin.isInitialized()) {
@ -171,13 +173,13 @@ public class ComboFragment extends DaggerFragment implements View.OnClickListene
// reservoir // reservoir
int reservoirLevel = comboPlugin.getPump().reservoirLevel; int reservoirLevel = comboPlugin.getPump().reservoirLevel;
if (reservoirLevel != -1) { if (reservoirLevel != -1) {
reservoirView.setText(reservoirLevel + " " + MainApp.gs(R.string.insulin_unit_shortname)); reservoirView.setText(reservoirLevel + " " + resourceHelper.gs(R.string.insulin_unit_shortname));
} else if (ps.insulinState == PumpState.LOW) { } else if (ps.insulinState == PumpState.LOW) {
reservoirView.setText(MainApp.gs(R.string.combo_reservoir_low)); reservoirView.setText(resourceHelper.gs(R.string.combo_reservoir_low));
} else if (ps.insulinState == PumpState.EMPTY) { } else if (ps.insulinState == PumpState.EMPTY) {
reservoirView.setText(MainApp.gs(R.string.combo_reservoir_empty)); reservoirView.setText(resourceHelper.gs(R.string.combo_reservoir_empty));
} else { } else {
reservoirView.setText(MainApp.gs(R.string.combo_reservoir_normal)); reservoirView.setText(resourceHelper.gs(R.string.combo_reservoir_normal));
} }
if (ps.insulinState == PumpState.UNKNOWN) { if (ps.insulinState == PumpState.UNKNOWN) {
@ -201,7 +203,7 @@ public class ComboFragment extends DaggerFragment implements View.OnClickListene
lastConnectionView.setText(R.string.combo_pump_connected_now); lastConnectionView.setText(R.string.combo_pump_connected_now);
lastConnectionView.setTextColor(Color.WHITE); lastConnectionView.setTextColor(Color.WHITE);
} else if (comboPlugin.getPump().lastSuccessfulCmdTime + 30 * 60 * 1000 < System.currentTimeMillis()) { } else if (comboPlugin.getPump().lastSuccessfulCmdTime + 30 * 60 * 1000 < System.currentTimeMillis()) {
lastConnectionView.setText(MainApp.gs(R.string.combo_no_pump_connection, min)); lastConnectionView.setText(resourceHelper.gs(R.string.combo_no_pump_connection, min));
lastConnectionView.setTextColor(Color.RED); lastConnectionView.setTextColor(Color.RED);
} else { } else {
lastConnectionView.setText(minAgo); lastConnectionView.setText(minAgo);
@ -213,22 +215,22 @@ public class ComboFragment extends DaggerFragment implements View.OnClickListene
if (bolus != null) { if (bolus != null) {
long agoMsc = System.currentTimeMillis() - bolus.timestamp; long agoMsc = System.currentTimeMillis() - bolus.timestamp;
double bolusMinAgo = agoMsc / 60d / 1000d; double bolusMinAgo = agoMsc / 60d / 1000d;
String unit = MainApp.gs(R.string.insulin_unit_shortname); String unit = resourceHelper.gs(R.string.insulin_unit_shortname);
String ago; String ago;
if ((agoMsc < 60 * 1000)) { if ((agoMsc < 60 * 1000)) {
ago = MainApp.gs(R.string.combo_pump_connected_now); ago = resourceHelper.gs(R.string.combo_pump_connected_now);
} else if (bolusMinAgo < 60) { } else if (bolusMinAgo < 60) {
ago = DateUtil.minAgo(bolus.timestamp); ago = DateUtil.minAgo(bolus.timestamp);
} else { } else {
ago = DateUtil.hourAgo(bolus.timestamp); ago = DateUtil.hourAgo(bolus.timestamp);
} }
lastBolusView.setText(MainApp.gs(R.string.combo_last_bolus, bolus.amount, unit, ago)); lastBolusView.setText(resourceHelper.gs(R.string.combo_last_bolus, bolus.amount, unit, ago));
} else { } else {
lastBolusView.setText(""); lastBolusView.setText("");
} }
// base basal rate // base basal rate
baseBasalRate.setText(MainApp.gs(R.string.pump_basebasalrate, comboPlugin.getBaseBasalRate())); baseBasalRate.setText(resourceHelper.gs(R.string.pump_basebasalrate, comboPlugin.getBaseBasalRate()));
// TBR // TBR
String tbrStr = ""; String tbrStr = "";
@ -236,14 +238,14 @@ public class ComboFragment extends DaggerFragment implements View.OnClickListene
long minSinceRead = (System.currentTimeMillis() - comboPlugin.getPump().state.timestamp) / 1000 / 60; long minSinceRead = (System.currentTimeMillis() - comboPlugin.getPump().state.timestamp) / 1000 / 60;
long remaining = ps.tbrRemainingDuration - minSinceRead; long remaining = ps.tbrRemainingDuration - minSinceRead;
if (remaining >= 0) { if (remaining >= 0) {
tbrStr = MainApp.gs(R.string.combo_tbr_remaining, ps.tbrPercent, remaining); tbrStr = resourceHelper.gs(R.string.combo_tbr_remaining, ps.tbrPercent, remaining);
} }
} }
tempBasalText.setText(tbrStr); tempBasalText.setText(tbrStr);
// stats // stats
bolusCount.setText(String.valueOf(SP.getLong(ComboPlugin.COMBO_BOLUSES_DELIVERED, 0L))); bolusCount.setText(String.valueOf(sp.getLong(ComboPlugin.COMBO_BOLUSES_DELIVERED, 0L)));
tbrCount.setText(String.valueOf(SP.getLong(ComboPlugin.COMBO_TBRS_SET, 0L))); tbrCount.setText(String.valueOf(sp.getLong(ComboPlugin.COMBO_TBRS_SET, 0L)));
} }
} }
} }

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.pump.combo; package info.nightscout.androidaps.plugins.pump.combo;
import android.content.Context;
import android.os.SystemClock; import android.os.SystemClock;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
@ -41,10 +42,8 @@ import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.PumpPluginBase; import info.nightscout.androidaps.interfaces.PumpPluginBase;
import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.common.ManufacturerType; import info.nightscout.androidaps.plugins.common.ManufacturerType;
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction;
import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction; import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction;
import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType; import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType;
@ -82,12 +81,12 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
static final String COMBO_BOLUSES_DELIVERED = "combo_boluses_delivered"; static final String COMBO_BOLUSES_DELIVERED = "combo_boluses_delivered";
private final ResourceHelper resourceHelper; private final ResourceHelper resourceHelper;
private final ConstraintChecker constraintChecker;
private final ProfileFunction profileFunction; private final ProfileFunction profileFunction;
private final TreatmentsPlugin treatmentsPlugin; private final TreatmentsPlugin treatmentsPlugin;
private final info.nightscout.androidaps.utils.sharedPreferences.SP sp; private final info.nightscout.androidaps.utils.sharedPreferences.SP sp;
private final RxBusWrapper rxBus; private RxBusWrapper rxBus;
private final CommandQueueProvider commandQueue; private final CommandQueueProvider commandQueue;
private final Context context;
private final static PumpDescription pumpDescription = new PumpDescription(); private final static PumpDescription pumpDescription = new PumpDescription();
@ -138,11 +137,11 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
AAPSLogger aapsLogger, AAPSLogger aapsLogger,
RxBusWrapper rxBus, RxBusWrapper rxBus,
ResourceHelper resourceHelper, ResourceHelper resourceHelper,
ConstraintChecker constraintChecker,
ProfileFunction profileFunction, ProfileFunction profileFunction,
TreatmentsPlugin treatmentsPlugin, TreatmentsPlugin treatmentsPlugin,
SP sp, SP sp,
CommandQueueProvider commandQueue CommandQueueProvider commandQueue,
Context context
) { ) {
super(new PluginDescription() super(new PluginDescription()
.mainType(PluginType.PUMP) .mainType(PluginType.PUMP)
@ -154,18 +153,18 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
); );
this.rxBus = rxBus; this.rxBus = rxBus;
this.resourceHelper = resourceHelper; this.resourceHelper = resourceHelper;
this.constraintChecker = constraintChecker;
this.profileFunction = profileFunction; this.profileFunction = profileFunction;
this.treatmentsPlugin = treatmentsPlugin; this.treatmentsPlugin = treatmentsPlugin;
this.sp = sp; this.sp = sp;
this.commandQueue = commandQueue; this.commandQueue = commandQueue;
this.context = context;
pumpDescription.setPumpDescription(PumpType.AccuChekCombo); pumpDescription.setPumpDescription(PumpType.AccuChekCombo);
} }
@Override protected void onStart() { @Override protected void onStart() {
super.onStart(); super.onStart();
ruffyScripter = new RuffyScripter(MainApp.instance()); ruffyScripter = new RuffyScripter(context);
OPERATION_NOT_SUPPORTED = new PumpEnactResult(getInjector()) OPERATION_NOT_SUPPORTED = new PumpEnactResult(getInjector())
.success(false).enacted(false).comment(getResourceHelper().gs(R.string.combo_pump_unsupported_operation)); .success(false).enacted(false).comment(getResourceHelper().gs(R.string.combo_pump_unsupported_operation));
} }
@ -256,15 +255,15 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
// issues a READSTATE when starting to issue commands which initializes the pump // issues a READSTATE when starting to issue commands which initializes the pump
getAapsLogger().error("setNewBasalProfile not initialized"); getAapsLogger().error("setNewBasalProfile not initialized");
Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, getResourceHelper().gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT); Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, getResourceHelper().gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT);
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); rxBus.send(new EventNewNotification(notification));
return new PumpEnactResult(getInjector()).success(false).enacted(false).comment(getResourceHelper().gs(R.string.pumpNotInitializedProfileNotSet)); return new PumpEnactResult(getInjector()).success(false).enacted(false).comment(getResourceHelper().gs(R.string.pumpNotInitializedProfileNotSet));
} }
BasalProfile requestedBasalProfile = convertProfileToComboProfile(profile); BasalProfile requestedBasalProfile = convertProfileToComboProfile(profile);
if (pump.basalProfile.equals(requestedBasalProfile)) { if (pump.basalProfile.equals(requestedBasalProfile)) {
//dismiss previously "FAILED" overview notifications //dismiss previously "FAILED" overview notifications
RxBus.Companion.getINSTANCE().send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)); rxBus.send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
RxBus.Companion.getINSTANCE().send(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE)); rxBus.send(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE));
return new PumpEnactResult(getInjector()).success(true).enacted(false); return new PumpEnactResult(getInjector()).success(true).enacted(false);
} }
@ -277,18 +276,18 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
() -> ruffyScripter.setBasalProfile(requestedBasalProfile)); () -> ruffyScripter.setBasalProfile(requestedBasalProfile));
if (!setResult.success) { if (!setResult.success) {
Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, getResourceHelper().gs(R.string.failedupdatebasalprofile), Notification.URGENT); Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, getResourceHelper().gs(R.string.failedupdatebasalprofile), Notification.URGENT);
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); rxBus.send(new EventNewNotification(notification));
return new PumpEnactResult(getInjector()).success(false).enacted(false).comment(getResourceHelper().gs(R.string.failedupdatebasalprofile)); return new PumpEnactResult(getInjector()).success(false).enacted(false).comment(getResourceHelper().gs(R.string.failedupdatebasalprofile));
} }
pump.basalProfile = requestedBasalProfile; pump.basalProfile = requestedBasalProfile;
//dismiss previously "FAILED" overview notifications //dismiss previously "FAILED" overview notifications
RxBus.Companion.getINSTANCE().send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)); rxBus.send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
RxBus.Companion.getINSTANCE().send(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE)); rxBus.send(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE));
//issue success notification //issue success notification
Notification notification = new Notification(Notification.PROFILE_SET_OK, getResourceHelper().gs(R.string.profile_set_ok), Notification.INFO, 60); Notification notification = new Notification(Notification.PROFILE_SET_OK, getResourceHelper().gs(R.string.profile_set_ok), Notification.INFO, 60);
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); rxBus.send(new EventNewNotification(notification));
return new PumpEnactResult(getInjector()).success(true).enacted(true); return new PumpEnactResult(getInjector()).success(true).enacted(true);
} }
@ -361,7 +360,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
// trigger a connect, which will update state and check history // trigger a connect, which will update state and check history
CommandResult stateResult = runCommand(null, 1, ruffyScripter::readPumpState); CommandResult stateResult = runCommand(null, 1, ruffyScripter::readPumpState);
if (stateResult.invalidSetup) { if (stateResult.invalidSetup) {
RxBus.Companion.getINSTANCE().send(new EventNewNotification( rxBus.send(new EventNewNotification(
new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.combo_invalid_setup), Notification.URGENT))); new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.combo_invalid_setup), Notification.URGENT)));
return; return;
} }
@ -381,7 +380,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
getResourceHelper().gs(R.string.combo_force_disabled_notification), getResourceHelper().gs(R.string.combo_force_disabled_notification),
Notification.URGENT); Notification.URGENT);
n.soundId = R.raw.alarm; n.soundId = R.raw.alarm;
RxBus.Companion.getINSTANCE().send(new EventNewNotification(n)); rxBus.send(new EventNewNotification(n));
return; return;
} }
@ -394,7 +393,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
setValidBasalRateProfileSelectedOnPump(true); setValidBasalRateProfileSelectedOnPump(true);
pump.initialized = true; pump.initialized = true;
RxBus.Companion.getINSTANCE().send(new EventInitializationChanged()); rxBus.send(new EventInitializationChanged());
// show notification to check pump date if last bolus is older than 24 hours // show notification to check pump date if last bolus is older than 24 hours
// or is in the future // or is in the future
@ -403,13 +402,13 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
if (lastBolusTimestamp < now - 24 * 60 * 60 * 1000 || lastBolusTimestamp > now + 5 * 60 * 1000) { if (lastBolusTimestamp < now - 24 * 60 * 60 * 1000 || lastBolusTimestamp > now + 5 * 60 * 1000) {
Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.combo_check_date), Notification.URGENT); Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.combo_check_date), Notification.URGENT);
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); rxBus.send(new EventNewNotification(notification));
} }
} }
// ComboFragment updates state fully only after the pump has initialized, // ComboFragment updates state fully only after the pump has initialized,
// so force an update after initialization completed // so force an update after initialization completed
RxBus.Companion.getINSTANCE().send(new EventComboPumpUpdateGUI()); rxBus.send(new EventComboPumpUpdateGUI());
} }
/** /**
@ -425,7 +424,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
if (result.state.menu != null) { if (result.state.menu != null) {
pump.state = result.state; pump.state = result.state;
} }
RxBus.Companion.getINSTANCE().send(new EventComboPumpUpdateGUI()); rxBus.send(new EventComboPumpUpdateGUI());
} }
@Override @Override
@ -471,7 +470,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
break; break;
} }
event.setPercent(percent); event.setPercent(percent);
RxBus.Companion.getINSTANCE().send(event); rxBus.send(event);
}; };
/** /**
@ -491,20 +490,20 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
return deliverBolus(detailedBolusInfo); return deliverBolus(detailedBolusInfo);
} else { } else {
// no bolus required, carb only treatment // no bolus required, carb only treatment
TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, false); treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, false);
EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE; EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE;
bolusingEvent.setT(new Treatment()); bolusingEvent.setT(new Treatment());
bolusingEvent.getT().isSMB = detailedBolusInfo.isSMB; bolusingEvent.getT().isSMB = detailedBolusInfo.isSMB;
bolusingEvent.setPercent(100); bolusingEvent.setPercent(100);
RxBus.Companion.getINSTANCE().send(bolusingEvent); rxBus.send(bolusingEvent);
return new PumpEnactResult(getInjector()).success(true).enacted(true) return new PumpEnactResult(getInjector()).success(true).enacted(true)
.bolusDelivered(0d).carbsDelivered(detailedBolusInfo.carbs) .bolusDelivered(0d).carbsDelivered(detailedBolusInfo.carbs)
.comment(getResourceHelper().gs(R.string.virtualpump_resultok)); .comment(getResourceHelper().gs(R.string.virtualpump_resultok));
} }
} finally { } finally {
RxBus.Companion.getINSTANCE().send(new EventComboPumpUpdateGUI()); rxBus.send(new EventComboPumpUpdateGUI());
} }
} }
@ -512,7 +511,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
private PumpEnactResult deliverBolus(final DetailedBolusInfo detailedBolusInfo) { private PumpEnactResult deliverBolus(final DetailedBolusInfo detailedBolusInfo) {
try { try {
pump.activity = getResourceHelper().gs(R.string.combo_pump_action_bolusing, detailedBolusInfo.insulin); pump.activity = getResourceHelper().gs(R.string.combo_pump_action_bolusing, detailedBolusInfo.insulin);
RxBus.Companion.getINSTANCE().send(new EventComboPumpUpdateGUI()); rxBus.send(new EventComboPumpUpdateGUI());
// check pump is ready and all pump bolus records are known // check pump is ready and all pump bolus records are known
CommandResult stateResult = runCommand(null, 2, () -> ruffyScripter.readQuickInfo(1)); CommandResult stateResult = runCommand(null, 2, () -> ruffyScripter.readQuickInfo(1));
@ -618,7 +617,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
if (lastPumpBolus.timestamp < now - 10 * 60 * 1000 || lastPumpBolus.timestamp > now + 10 * 60 * 1000) { if (lastPumpBolus.timestamp < now - 10 * 60 * 1000 || lastPumpBolus.timestamp > now + 10 * 60 * 1000) {
Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.combo_suspious_bolus_time), Notification.URGENT); Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.combo_suspious_bolus_time), Notification.URGENT);
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); rxBus.send(new EventNewNotification(notification));
} }
// update `recentBoluses` so the bolus was just delivered won't be detected as a new // update `recentBoluses` so the bolus was just delivered won't be detected as a new
@ -644,8 +643,8 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
.carbsDelivered(detailedBolusInfo.carbs); .carbsDelivered(detailedBolusInfo.carbs);
} finally { } finally {
pump.activity = null; pump.activity = null;
RxBus.Companion.getINSTANCE().send(new EventComboPumpUpdateGUI()); rxBus.send(new EventComboPumpUpdateGUI());
RxBus.Companion.getINSTANCE().send(new EventRefreshOverview("Bolus")); rxBus.send(new EventRefreshOverview("Bolus"));
cancelBolus = false; cancelBolus = false;
} }
} }
@ -682,19 +681,19 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
carbInfo.date = bolusInfo.date + bolusInfo.carbTime * 60L * 1000L; carbInfo.date = bolusInfo.date + bolusInfo.carbTime * 60L * 1000L;
carbInfo.carbs = bolusInfo.carbs; carbInfo.carbs = bolusInfo.carbs;
carbInfo.source = Source.USER; carbInfo.source = Source.USER;
TreatmentsPlugin.getPlugin().addToHistoryTreatment(carbInfo, true); treatmentsPlugin.addToHistoryTreatment(carbInfo, true);
// remove carbs from bolusInfo to not trigger any unwanted code paths in // remove carbs from bolusInfo to not trigger any unwanted code paths in
// TreatmentsPlugin.addToHistoryTreatment() method // TreatmentsPlugin.addToHistoryTreatment() method
bolusInfo.carbTime = 0; bolusInfo.carbTime = 0;
bolusInfo.carbs = 0; bolusInfo.carbs = 0;
} }
TreatmentsPlugin.getPlugin().addToHistoryTreatment(bolusInfo, true); treatmentsPlugin.addToHistoryTreatment(bolusInfo, true);
} catch (Exception e) { } catch (Exception e) {
getAapsLogger().error("Adding treatment record failed", e); getAapsLogger().error("Adding treatment record failed", e);
if (bolusInfo.isSMB) { if (bolusInfo.isSMB) {
Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.combo_error_updating_treatment_record), Notification.URGENT); Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.combo_error_updating_treatment_record), Notification.URGENT);
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); rxBus.send(new EventNewNotification(notification));
} }
return false; return false;
} }
@ -782,9 +781,9 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
.duration(state.tbrRemainingDuration) .duration(state.tbrRemainingDuration)
.percent(state.tbrPercent) .percent(state.tbrPercent)
.source(Source.USER); .source(Source.USER);
TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempStart); treatmentsPlugin.addToHistoryTempBasal(tempStart);
RxBus.Companion.getINSTANCE().send(new EventComboPumpUpdateGUI()); rxBus.send(new EventComboPumpUpdateGUI());
} }
incrementTbrCount(); incrementTbrCount();
@ -808,7 +807,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
@NonNull @Override @NonNull @Override
public PumpEnactResult cancelTempBasal(boolean enforceNew) { public PumpEnactResult cancelTempBasal(boolean enforceNew) {
getAapsLogger().debug(LTag.PUMP, "cancelTempBasal called"); getAapsLogger().debug(LTag.PUMP, "cancelTempBasal called");
final TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis()); final TemporaryBasal activeTemp = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis());
if (enforceNew) { if (enforceNew) {
CommandResult stateResult = runCommand(getResourceHelper().gs(R.string.combo_pump_action_refreshing), 2, ruffyScripter::readPumpState); CommandResult stateResult = runCommand(getResourceHelper().gs(R.string.combo_pump_action_refreshing), 2, ruffyScripter::readPumpState);
if (!stateResult.success) { if (!stateResult.success) {
@ -827,7 +826,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
.date(cancelResult.state.timestamp) .date(cancelResult.state.timestamp)
.duration(0) .duration(0)
.source(Source.USER); .source(Source.USER);
TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempBasal); treatmentsPlugin.addToHistoryTempBasal(tempBasal);
return new PumpEnactResult(getInjector()).isTempCancel(true).success(true).enacted(true); return new PumpEnactResult(getInjector()).isTempCancel(true).success(true).enacted(true);
} else { } else {
return new PumpEnactResult(getInjector()).success(false).enacted(false); return new PumpEnactResult(getInjector()).success(false).enacted(false);
@ -868,7 +867,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
if (!ruffyScripter.isConnected()) { if (!ruffyScripter.isConnected()) {
String originalActivity = pump.activity; String originalActivity = pump.activity;
pump.activity = getResourceHelper().gs(R.string.combo_activity_checking_pump_state); pump.activity = getResourceHelper().gs(R.string.combo_activity_checking_pump_state);
RxBus.Companion.getINSTANCE().send(new EventComboPumpUpdateGUI()); rxBus.send(new EventComboPumpUpdateGUI());
CommandResult preCheckError = runOnConnectChecks(); CommandResult preCheckError = runOnConnectChecks();
pump.activity = originalActivity; pump.activity = originalActivity;
if (preCheckError != null) { if (preCheckError != null) {
@ -879,7 +878,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
if (activity != null) { if (activity != null) {
pump.activity = activity; pump.activity = activity;
RxBus.Companion.getINSTANCE().send(new EventComboPumpUpdateGUI()); rxBus.send(new EventComboPumpUpdateGUI());
} }
commandResult = commandExecution.execute(); commandResult = commandExecution.execute();
@ -903,7 +902,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
getResourceHelper().gs(R.string.combo_force_disabled_notification), getResourceHelper().gs(R.string.combo_force_disabled_notification),
Notification.URGENT); Notification.URGENT);
n.soundId = R.raw.alarm; n.soundId = R.raw.alarm;
RxBus.Companion.getINSTANCE().send(new EventNewNotification(n)); rxBus.send(new EventNewNotification(n));
commandQueue.cancelTempBasal(true, null); commandQueue.cancelTempBasal(true, null);
} }
updateLocalData(commandResult); updateLocalData(commandResult);
@ -911,7 +910,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
} finally { } finally {
if (activity != null) { if (activity != null) {
pump.activity = null; pump.activity = null;
RxBus.Companion.getINSTANCE().send(new EventComboPumpUpdateGUI()); rxBus.send(new EventComboPumpUpdateGUI());
} }
} }
@ -949,7 +948,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
notification.id = Notification.COMBO_PUMP_ALARM; notification.id = Notification.COMBO_PUMP_ALARM;
notification.level = Notification.URGENT; notification.level = Notification.URGENT;
notification.text = getResourceHelper().gs(R.string.combo_is_in_error_state, activeAlert.errorCode, activeAlert.message); notification.text = getResourceHelper().gs(R.string.combo_is_in_error_state, activeAlert.errorCode, activeAlert.message);
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); rxBus.send(new EventNewNotification(notification));
return preCheckResult.success(false); return preCheckResult.success(false);
} }
} }
@ -965,7 +964,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
} }
} else { } else {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
TemporaryBasal aapsTbr = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now); TemporaryBasal aapsTbr = treatmentsPlugin.getTempBasalFromHistory(now);
if (aapsTbr == null || aapsTbr.percentRate != 0) { if (aapsTbr == null || aapsTbr.percentRate != 0) {
getAapsLogger().debug(LTag.PUMP, "Creating 15m zero temp since pump is suspended"); getAapsLogger().debug(LTag.PUMP, "Creating 15m zero temp since pump is suspended");
TemporaryBasal newTempBasal = new TemporaryBasal() TemporaryBasal newTempBasal = new TemporaryBasal()
@ -973,7 +972,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
.percent(0) .percent(0)
.duration(15) .duration(15)
.source(Source.USER); .source(Source.USER);
TreatmentsPlugin.getPlugin().addToHistoryTempBasal(newTempBasal); treatmentsPlugin.addToHistoryTempBasal(newTempBasal);
} }
} }
@ -1011,10 +1010,10 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
if (readBasalResult.success) { if (readBasalResult.success) {
pump.basalProfile = readBasalResult.basalProfile; pump.basalProfile = readBasalResult.basalProfile;
Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.combo_warning_pump_basal_rate_changed), Notification.NORMAL); Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.combo_warning_pump_basal_rate_changed), Notification.NORMAL);
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); rxBus.send(new EventNewNotification(notification));
} else { } else {
Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.combo_error_failure_reading_changed_basal_rate), Notification.URGENT); Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.combo_error_failure_reading_changed_basal_rate), Notification.URGENT);
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); rxBus.send(new EventNewNotification(notification));
} }
} }
} }
@ -1029,11 +1028,11 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
} else if (Math.abs(state.pumpTime - System.currentTimeMillis()) >= 10 * 60 * 1000) { } else if (Math.abs(state.pumpTime - System.currentTimeMillis()) >= 10 * 60 * 1000) {
getAapsLogger().debug(LTag.PUMP, "Pump clock needs update, pump time: " + state.pumpTime + " (" + new Date(state.pumpTime) + ")"); getAapsLogger().debug(LTag.PUMP, "Pump clock needs update, pump time: " + state.pumpTime + " (" + new Date(state.pumpTime) + ")");
Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.combo_notification_check_time_date), Notification.URGENT); Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.combo_notification_check_time_date), Notification.URGENT);
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); rxBus.send(new EventNewNotification(notification));
} else if (Math.abs(state.pumpTime - System.currentTimeMillis()) >= 3 * 60 * 1000) { } else if (Math.abs(state.pumpTime - System.currentTimeMillis()) >= 3 * 60 * 1000) {
getAapsLogger().debug(LTag.PUMP, "Pump clock needs update, pump time: " + state.pumpTime + " (" + new Date(state.pumpTime) + ")"); getAapsLogger().debug(LTag.PUMP, "Pump clock needs update, pump time: " + state.pumpTime + " (" + new Date(state.pumpTime) + ")");
Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.combo_notification_check_time_date), Notification.NORMAL); Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.combo_notification_check_time_date), Notification.NORMAL);
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); rxBus.send(new EventNewNotification(notification));
} }
} }
@ -1055,7 +1054,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
} else if (activeAlert.warningCode == PumpWarningCodes.TBR_CANCELLED) { } else if (activeAlert.warningCode == PumpWarningCodes.TBR_CANCELLED) {
notification.text = getResourceHelper().gs(R.string.combo_pump_tbr_cancelled_warrning); notification.text = getResourceHelper().gs(R.string.combo_pump_tbr_cancelled_warrning);
} }
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); rxBus.send(new EventNewNotification(notification));
} }
private void checkForUnsafeUsage(CommandResult commandResult) { private void checkForUnsafeUsage(CommandResult commandResult) {
@ -1078,7 +1077,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
getResourceHelper().gs(R.string.combo_low_suspend_forced_notification), getResourceHelper().gs(R.string.combo_low_suspend_forced_notification),
Notification.URGENT); Notification.URGENT);
n.soundId = R.raw.alarm; n.soundId = R.raw.alarm;
RxBus.Companion.getINSTANCE().send(new EventNewNotification(n)); rxBus.send(new EventNewNotification(n));
violationWarningRaisedForBolusAt = lowSuspendOnlyLoopEnforcedUntil; violationWarningRaisedForBolusAt = lowSuspendOnlyLoopEnforcedUntil;
commandQueue.cancelTempBasal(true, null); commandQueue.cancelTempBasal(true, null);
} }
@ -1091,7 +1090,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
private void checkAndResolveTbrMismatch(PumpState state) { private void checkAndResolveTbrMismatch(PumpState state) {
// compare with: info.nightscout.androidaps.plugins.PumpDanaR.comm.MsgStatusTempBasal.updateTempBasalInDB() // compare with: info.nightscout.androidaps.plugins.PumpDanaR.comm.MsgStatusTempBasal.updateTempBasalInDB()
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
TemporaryBasal aapsTbr = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now); TemporaryBasal aapsTbr = treatmentsPlugin.getTempBasalFromHistory(now);
if (aapsTbr == null && state.tbrActive && state.tbrRemainingDuration > 2) { if (aapsTbr == null && state.tbrActive && state.tbrRemainingDuration > 2) {
getAapsLogger().debug(LTag.PUMP, "Creating temp basal from pump TBR"); getAapsLogger().debug(LTag.PUMP, "Creating temp basal from pump TBR");
TemporaryBasal newTempBasal = new TemporaryBasal() TemporaryBasal newTempBasal = new TemporaryBasal()
@ -1099,14 +1098,14 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
.percent(state.tbrPercent) .percent(state.tbrPercent)
.duration(state.tbrRemainingDuration) .duration(state.tbrRemainingDuration)
.source(Source.USER); .source(Source.USER);
TreatmentsPlugin.getPlugin().addToHistoryTempBasal(newTempBasal); treatmentsPlugin.addToHistoryTempBasal(newTempBasal);
} else if (aapsTbr != null && aapsTbr.getPlannedRemainingMinutes() > 2 && !state.tbrActive) { } else if (aapsTbr != null && aapsTbr.getPlannedRemainingMinutes() > 2 && !state.tbrActive) {
getAapsLogger().debug(LTag.PUMP, "Ending AAPS-TBR since pump has no TBR active"); getAapsLogger().debug(LTag.PUMP, "Ending AAPS-TBR since pump has no TBR active");
TemporaryBasal tempStop = new TemporaryBasal() TemporaryBasal tempStop = new TemporaryBasal()
.date(now) .date(now)
.duration(0) .duration(0)
.source(Source.USER); .source(Source.USER);
TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempStop); treatmentsPlugin.addToHistoryTempBasal(tempStop);
} else if (aapsTbr != null && state.tbrActive } else if (aapsTbr != null && state.tbrActive
&& (aapsTbr.percentRate != state.tbrPercent || && (aapsTbr.percentRate != state.tbrPercent ||
Math.abs(aapsTbr.getPlannedRemainingMinutes() - state.tbrRemainingDuration) > 2)) { Math.abs(aapsTbr.getPlannedRemainingMinutes() - state.tbrRemainingDuration) > 2)) {
@ -1115,14 +1114,14 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
.date(now - 1000) .date(now - 1000)
.duration(0) .duration(0)
.source(Source.USER); .source(Source.USER);
TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempStop); treatmentsPlugin.addToHistoryTempBasal(tempStop);
TemporaryBasal newTempBasal = new TemporaryBasal() TemporaryBasal newTempBasal = new TemporaryBasal()
.date(now) .date(now)
.percent(state.tbrPercent) .percent(state.tbrPercent)
.duration(state.tbrRemainingDuration) .duration(state.tbrRemainingDuration)
.source(Source.USER); .source(Source.USER);
TreatmentsPlugin.getPlugin().addToHistoryTempBasal(newTempBasal); treatmentsPlugin.addToHistoryTempBasal(newTempBasal);
} }
} }
@ -1161,7 +1160,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
dbi.source = Source.PUMP; dbi.source = Source.PUMP;
dbi.insulin = pumpBolus.amount; dbi.insulin = pumpBolus.amount;
dbi.eventType = CareportalEvent.CORRECTIONBOLUS; dbi.eventType = CareportalEvent.CORRECTIONBOLUS;
if (TreatmentsPlugin.getPlugin().addToHistoryTreatment(dbi, true)) { if (treatmentsPlugin.addToHistoryTreatment(dbi, true)) {
updated = true; updated = true;
} }
} }
@ -1231,7 +1230,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
getAapsLogger().debug(LTag.PUMP, "Bolus with same amount within the same minute imported. Only one will make it to the DB."); getAapsLogger().debug(LTag.PUMP, "Bolus with same amount within the same minute imported. Only one will make it to the DB.");
Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string. Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.
combo_error_multiple_boluses_with_identical_timestamp), Notification.URGENT); combo_error_multiple_boluses_with_identical_timestamp), Notification.URGENT);
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); rxBus.send(new EventNewNotification(notification));
} }
pumpHistoryChanged = updateDbFromPumpHistory(historyResult.history); pumpHistoryChanged = updateDbFromPumpHistory(historyResult.history);

View file

@ -73,8 +73,8 @@ import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.queue.commands.Command; import info.nightscout.androidaps.queue.commands.Command;
import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.SP;
import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers; import io.reactivex.schedulers.Schedulers;
@ -92,6 +92,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService {
@Inject MessageHashTableR messageHashTableR; @Inject MessageHashTableR messageHashTableR;
@Inject ActivePluginProvider activePlugin; @Inject ActivePluginProvider activePlugin;
@Inject ProfileFunction profileFunction; @Inject ProfileFunction profileFunction;
@Inject SP sp;
private CompositeDisposable disposable = new CompositeDisposable(); private CompositeDisposable disposable = new CompositeDisposable();
@ -311,7 +312,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService {
if (BolusProgressDialog.stopPressed) return false; if (BolusProgressDialog.stopPressed) return false;
mBolusingTreatment = t; mBolusingTreatment = t;
int preferencesSpeed = SP.getInt(R.string.key_danars_bolusspeed, 0); int preferencesSpeed = sp.getInt(R.string.key_danars_bolusspeed, 0);
MessageBase start; MessageBase start;
if (preferencesSpeed == 0) if (preferencesSpeed == 0)
start = new MsgBolusStart(aapsLogger, constraintChecker, danaRPump, amount); start = new MsgBolusStart(aapsLogger, constraintChecker, danaRPump, amount);

View file

@ -19,9 +19,8 @@ import java.util.List;
import javax.inject.Inject; import javax.inject.Inject;
import dagger.android.support.DaggerFragment; import dagger.android.support.DaggerFragment;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.parameter_blocks.TBROverNotificationBlock; import info.nightscout.androidaps.plugins.pump.insight.app_layer.parameter_blocks.TBROverNotificationBlock;
import info.nightscout.androidaps.plugins.pump.insight.descriptors.ActiveBasalRate; import info.nightscout.androidaps.plugins.pump.insight.descriptors.ActiveBasalRate;
import info.nightscout.androidaps.plugins.pump.insight.descriptors.ActiveBolus; import info.nightscout.androidaps.plugins.pump.insight.descriptors.ActiveBolus;
@ -35,12 +34,15 @@ import info.nightscout.androidaps.queue.CommandQueue;
import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.DecimalFormatter;
import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.CompositeDisposable;
public class LocalInsightFragment extends DaggerFragment implements View.OnClickListener { public class LocalInsightFragment extends DaggerFragment implements View.OnClickListener {
@Inject LocalInsightPlugin localInsightPlugin; @Inject LocalInsightPlugin localInsightPlugin;
@Inject CommandQueue commandQueue; @Inject CommandQueue commandQueue;
@Inject RxBusWrapper rxBus;
@Inject ResourceHelper resourceHelper;
private CompositeDisposable disposable = new CompositeDisposable(); private CompositeDisposable disposable = new CompositeDisposable();
@ -74,7 +76,7 @@ public class LocalInsightFragment extends DaggerFragment implements View.OnClick
@Override @Override
public synchronized void onResume() { public synchronized void onResume() {
super.onResume(); super.onResume();
disposable.add(RxBus.Companion.getINSTANCE() disposable.add(rxBus
.toObservable(EventLocalInsightUpdateGUI.class) .toObservable(EventLocalInsightUpdateGUI.class)
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
.subscribe(event -> updateGUI(), exception -> FabricPrivacy.getInstance().logException(exception)) .subscribe(event -> updateGUI(), exception -> FabricPrivacy.getInstance().logException(exception))
@ -219,9 +221,9 @@ public class LocalInsightFragment extends DaggerFragment implements View.OnClick
string = R.string.recovering; string = R.string.recovering;
break; break;
} }
statusItems.add(getStatusItem(MainApp.gs(R.string.insight_status), MainApp.gs(string))); statusItems.add(getStatusItem(resourceHelper.gs(R.string.insight_status), resourceHelper.gs(string)));
if (state == InsightState.RECOVERING) { if (state == InsightState.RECOVERING) {
statusItems.add(getStatusItem(MainApp.gs(R.string.recovery_duration), localInsightPlugin.getConnectionService().getRecoveryDuration() / 1000 + "s")); statusItems.add(getStatusItem(resourceHelper.gs(R.string.recovery_duration), localInsightPlugin.getConnectionService().getRecoveryDuration() / 1000 + "s"));
} }
} }
@ -234,7 +236,7 @@ public class LocalInsightFragment extends DaggerFragment implements View.OnClick
long lastConnection = localInsightPlugin.getConnectionService().getLastConnected(); long lastConnection = localInsightPlugin.getConnectionService().getLastConnected();
if (lastConnection == 0) return; if (lastConnection == 0) return;
int min = (int) ((System.currentTimeMillis() - lastConnection) / 60000); int min = (int) ((System.currentTimeMillis() - lastConnection) / 60000);
statusItems.add(getStatusItem(MainApp.gs(R.string.last_connected), DateUtil.timeString(lastConnection))); statusItems.add(getStatusItem(resourceHelper.gs(R.string.last_connected), DateUtil.timeString(lastConnection)));
} }
} }
@ -260,12 +262,12 @@ public class LocalInsightFragment extends DaggerFragment implements View.OnClick
string = R.string.paused; string = R.string.paused;
break; break;
} }
statusItems.add(getStatusItem(MainApp.gs(R.string.operating_mode), MainApp.gs(string))); statusItems.add(getStatusItem(resourceHelper.gs(R.string.operating_mode), resourceHelper.gs(string)));
} }
private void getBatteryStatusItem(List<View> statusItems) { private void getBatteryStatusItem(List<View> statusItems) {
if (localInsightPlugin.getBatteryStatus() == null) return; if (localInsightPlugin.getBatteryStatus() == null) return;
statusItems.add(getStatusItem(MainApp.gs(R.string.pump_battery_label), statusItems.add(getStatusItem(resourceHelper.gs(R.string.pump_battery_label),
localInsightPlugin.getBatteryStatus().getBatteryAmount() + "%")); localInsightPlugin.getBatteryStatus().getBatteryAmount() + "%"));
} }
@ -275,30 +277,30 @@ public class LocalInsightFragment extends DaggerFragment implements View.OnClick
String status; String status;
if (cartridgeStatus.isInserted()) if (cartridgeStatus.isInserted())
status = DecimalFormatter.to2Decimal(localInsightPlugin.getCartridgeStatus().getRemainingAmount()) + "U"; status = DecimalFormatter.to2Decimal(localInsightPlugin.getCartridgeStatus().getRemainingAmount()) + "U";
else status = MainApp.gs(R.string.not_inserted); else status = resourceHelper.gs(R.string.not_inserted);
statusItems.add(getStatusItem(MainApp.gs(R.string.pump_reservoir_label), status)); statusItems.add(getStatusItem(resourceHelper.gs(R.string.pump_reservoir_label), status));
} }
private void getTDDItems(List<View> statusItems) { private void getTDDItems(List<View> statusItems) {
if (localInsightPlugin.getTotalDailyDose() == null) return; if (localInsightPlugin.getTotalDailyDose() == null) return;
TotalDailyDose tdd = localInsightPlugin.getTotalDailyDose(); TotalDailyDose tdd = localInsightPlugin.getTotalDailyDose();
statusItems.add(getStatusItem(MainApp.gs(R.string.tdd_bolus), DecimalFormatter.to2Decimal(tdd.getBolus()))); statusItems.add(getStatusItem(resourceHelper.gs(R.string.tdd_bolus), DecimalFormatter.to2Decimal(tdd.getBolus())));
statusItems.add(getStatusItem(MainApp.gs(R.string.tdd_basal), DecimalFormatter.to2Decimal(tdd.getBasal()))); statusItems.add(getStatusItem(resourceHelper.gs(R.string.tdd_basal), DecimalFormatter.to2Decimal(tdd.getBasal())));
statusItems.add(getStatusItem(MainApp.gs(R.string.tdd_total), DecimalFormatter.to2Decimal(tdd.getBolusAndBasal()))); statusItems.add(getStatusItem(resourceHelper.gs(R.string.tdd_total), DecimalFormatter.to2Decimal(tdd.getBolusAndBasal())));
} }
private void getBaseBasalRateItem(List<View> statusItems) { private void getBaseBasalRateItem(List<View> statusItems) {
if (localInsightPlugin.getActiveBasalRate() == null) return; if (localInsightPlugin.getActiveBasalRate() == null) return;
ActiveBasalRate activeBasalRate = localInsightPlugin.getActiveBasalRate(); ActiveBasalRate activeBasalRate = localInsightPlugin.getActiveBasalRate();
statusItems.add(getStatusItem(MainApp.gs(R.string.pump_basebasalrate_label), statusItems.add(getStatusItem(resourceHelper.gs(R.string.pump_basebasalrate_label),
DecimalFormatter.to2Decimal(activeBasalRate.getActiveBasalRate()) + " U/h (" + activeBasalRate.getActiveBasalProfileName() + ")")); DecimalFormatter.to2Decimal(activeBasalRate.getActiveBasalRate()) + " U/h (" + activeBasalRate.getActiveBasalProfileName() + ")"));
} }
private void getTBRItem(List<View> statusItems) { private void getTBRItem(List<View> statusItems) {
if (localInsightPlugin.getActiveTBR() == null) return; if (localInsightPlugin.getActiveTBR() == null) return;
ActiveTBR activeTBR = localInsightPlugin.getActiveTBR(); ActiveTBR activeTBR = localInsightPlugin.getActiveTBR();
statusItems.add(getStatusItem(MainApp.gs(R.string.pump_tempbasal_label), statusItems.add(getStatusItem(resourceHelper.gs(R.string.pump_tempbasal_label),
MainApp.gs(R.string.tbr_formatter, activeTBR.getPercentage(), activeTBR.getInitialDuration() - activeTBR.getRemainingDuration(), activeTBR.getInitialDuration()))); resourceHelper.gs(R.string.tbr_formatter, activeTBR.getPercentage(), activeTBR.getInitialDuration() - activeTBR.getRemainingDuration(), activeTBR.getInitialDuration())));
} }
private void getBolusItems(List<View> statusItems) { private void getBolusItems(List<View> statusItems) {
@ -307,15 +309,15 @@ public class LocalInsightFragment extends DaggerFragment implements View.OnClick
String label; String label;
switch (activeBolus.getBolusType()) { switch (activeBolus.getBolusType()) {
case MULTIWAVE: case MULTIWAVE:
label = MainApp.gs(R.string.multiwave_bolus); label = resourceHelper.gs(R.string.multiwave_bolus);
break; break;
case EXTENDED: case EXTENDED:
label = MainApp.gs(R.string.extended_bolus); label = resourceHelper.gs(R.string.extended_bolus);
break; break;
default: default:
continue; continue;
} }
statusItems.add(getStatusItem(label, MainApp.gs(R.string.eb_formatter, activeBolus.getRemainingAmount(), activeBolus.getInitialAmount(), activeBolus.getRemainingDuration()))); statusItems.add(getStatusItem(label, resourceHelper.gs(R.string.eb_formatter, activeBolus.getRemainingAmount(), activeBolus.getInitialAmount(), activeBolus.getRemainingDuration())));
} }
} }
} }

View file

@ -15,7 +15,6 @@ import androidx.annotation.NonNull;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.slf4j.Logger;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
@ -51,8 +50,7 @@ import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.PumpPluginBase; import info.nightscout.androidaps.interfaces.PumpPluginBase;
import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.common.ManufacturerType; import info.nightscout.androidaps.plugins.common.ManufacturerType;
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker;
@ -147,16 +145,14 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
private final AAPSLogger aapsLogger; private final AAPSLogger aapsLogger;
private final RxBusWrapper rxBus; private final RxBusWrapper rxBus;
private final ResourceHelper resourceHelper; private final ResourceHelper resourceHelper;
private final ConstraintChecker constraintChecker;
private final TreatmentsPlugin treatmentsPlugin; private final TreatmentsPlugin treatmentsPlugin;
private final SP sp; private final SP sp;
private final CommandQueueProvider commandQueue; private final CommandQueueProvider commandQueue;
private final ProfileFunction profileFunction; private final ProfileFunction profileFunction;
private final Context context;
public static final String ALERT_CHANNEL_ID = "AndroidAPS-InsightAlert"; public static final String ALERT_CHANNEL_ID = "AndroidAPS-InsightAlert";
private Logger log = StacktraceLoggerWrapper.getLogger(L.PUMP);
private PumpDescription pumpDescription; private PumpDescription pumpDescription;
private InsightAlertService alertService; private InsightAlertService alertService;
private InsightConnectionService connectionService; private InsightConnectionService connectionService;
@ -208,11 +204,11 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
AAPSLogger aapsLogger, AAPSLogger aapsLogger,
RxBusWrapper rxBus, RxBusWrapper rxBus,
ResourceHelper resourceHelper, ResourceHelper resourceHelper,
ConstraintChecker constraintChecker,
TreatmentsPlugin treatmentsPlugin, TreatmentsPlugin treatmentsPlugin,
SP sp, SP sp,
CommandQueueProvider commandQueue, CommandQueueProvider commandQueue,
ProfileFunction profileFunction ProfileFunction profileFunction,
Context context
) { ) {
super(new PluginDescription() super(new PluginDescription()
.pluginName(R.string.insight_local) .pluginName(R.string.insight_local)
@ -227,11 +223,11 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
this.aapsLogger = aapsLogger; this.aapsLogger = aapsLogger;
this.rxBus = rxBus; this.rxBus = rxBus;
this.resourceHelper = resourceHelper; this.resourceHelper = resourceHelper;
this.constraintChecker = constraintChecker;
this.treatmentsPlugin = treatmentsPlugin; this.treatmentsPlugin = treatmentsPlugin;
this.sp = sp; this.sp = sp;
this.commandQueue = commandQueue; this.commandQueue = commandQueue;
this.profileFunction = profileFunction; this.profileFunction = profileFunction;
this.context = context;
pumpDescription = new PumpDescription(); pumpDescription = new PumpDescription();
pumpDescription.setPumpDescription(PumpType.AccuChekInsightBluetooth); pumpDescription.setPumpDescription(PumpType.AccuChekInsightBluetooth);
@ -280,15 +276,15 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
@Override @Override
protected void onStart() { protected void onStart() {
super.onStart(); super.onStart();
MainApp.instance().bindService(new Intent(MainApp.instance(), InsightConnectionService.class), serviceConnection, Context.BIND_AUTO_CREATE); context.bindService(new Intent(context, InsightConnectionService.class), serviceConnection, Context.BIND_AUTO_CREATE);
MainApp.instance().bindService(new Intent(MainApp.instance(), InsightAlertService.class), serviceConnection, Context.BIND_AUTO_CREATE); context.bindService(new Intent(context, InsightAlertService.class), serviceConnection, Context.BIND_AUTO_CREATE);
createNotificationChannel(); createNotificationChannel();
} }
private void createNotificationChannel() { private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) MainApp.instance().getSystemService(Context.NOTIFICATION_SERVICE); NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel(ALERT_CHANNEL_ID, MainApp.gs(R.string.insight_alert_notification_channel), NotificationManager.IMPORTANCE_HIGH); NotificationChannel channel = new NotificationChannel(ALERT_CHANNEL_ID, resourceHelper.gs(R.string.insight_alert_notification_channel), NotificationManager.IMPORTANCE_HIGH);
channel.setSound(null, null); channel.setSound(null, null);
notificationManager.createNotificationChannel(channel); notificationManager.createNotificationChannel(channel);
} }
@ -297,7 +293,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
@Override @Override
protected void onStop() { protected void onStop() {
super.onStop(); super.onStop();
MainApp.instance().unbindService(serviceConnection); context.unbindService(serviceConnection);
} }
@Override @Override
@ -371,11 +367,11 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
updatePumpTimeIfNeeded(); updatePumpTimeIfNeeded();
fetchStatus(); fetchStatus();
} catch (AppLayerErrorException e) { } catch (AppLayerErrorException e) {
log.info("Exception while fetching status: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); aapsLogger.info(LTag.PUMP, "Exception while fetching status: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
} catch (InsightException e) { } catch (InsightException e) {
log.info("Exception while fetching status: " + e.getClass().getCanonicalName()); aapsLogger.info(LTag.PUMP, "Exception while fetching status: " + e.getClass().getCanonicalName());
} catch (Exception e) { } catch (Exception e) {
log.error("Exception while fetching status", e); aapsLogger.error("Exception while fetching status", e);
} }
} }
@ -518,17 +514,17 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
} catch (Exception ignored) { } catch (Exception ignored) {
} }
} catch (AppLayerErrorException e) { } catch (AppLayerErrorException e) {
log.info("Exception while setting profile: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); aapsLogger.info(LTag.PUMP, "Exception while setting profile: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, resourceHelper.gs(R.string.failedupdatebasalprofile), Notification.URGENT); Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, resourceHelper.gs(R.string.failedupdatebasalprofile), Notification.URGENT);
rxBus.send(new EventNewNotification(notification)); rxBus.send(new EventNewNotification(notification));
result.comment = ExceptionTranslator.getString(e); result.comment = ExceptionTranslator.getString(e);
} catch (InsightException e) { } catch (InsightException e) {
log.info("Exception while setting profile: " + e.getClass().getCanonicalName()); aapsLogger.info(LTag.PUMP, "Exception while setting profile: " + e.getClass().getCanonicalName());
Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, resourceHelper.gs(R.string.failedupdatebasalprofile), Notification.URGENT); Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, resourceHelper.gs(R.string.failedupdatebasalprofile), Notification.URGENT);
rxBus.send(new EventNewNotification(notification)); rxBus.send(new EventNewNotification(notification));
result.comment = ExceptionTranslator.getString(e); result.comment = ExceptionTranslator.getString(e);
} catch (Exception e) { } catch (Exception e) {
log.error("Exception while setting profile", e); aapsLogger.error("Exception while setting profile", e);
Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, resourceHelper.gs(R.string.failedupdatebasalprofile), Notification.URGENT); Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, resourceHelper.gs(R.string.failedupdatebasalprofile), Notification.URGENT);
rxBus.send(new EventNewNotification(notification)); rxBus.send(new EventNewNotification(notification));
result.comment = ExceptionTranslator.getString(e); result.comment = ExceptionTranslator.getString(e);
@ -618,11 +614,11 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
carbInfo.carbs = detailedBolusInfo.carbs; carbInfo.carbs = detailedBolusInfo.carbs;
carbInfo.date = detailedBolusInfo.date + detailedBolusInfo.carbTime * 60L * 1000L; carbInfo.date = detailedBolusInfo.date + detailedBolusInfo.carbTime * 60L * 1000L;
carbInfo.source = Source.USER; carbInfo.source = Source.USER;
TreatmentsPlugin.getPlugin().addToHistoryTreatment(carbInfo, false); treatmentsPlugin.addToHistoryTreatment(carbInfo, false);
detailedBolusInfo.carbTime = 0; detailedBolusInfo.carbTime = 0;
detailedBolusInfo.carbs = 0; detailedBolusInfo.carbs = 0;
} }
TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, true); treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, true);
while (true) { while (true) {
synchronized ($bolusLock) { synchronized ($bolusLock) {
if (bolusCancelled) break; if (bolusCancelled) break;
@ -661,13 +657,13 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
readHistory(); readHistory();
fetchStatus(); fetchStatus();
} catch (AppLayerErrorException e) { } catch (AppLayerErrorException e) {
log.info("Exception while delivering bolus: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); aapsLogger.info(LTag.PUMP, "Exception while delivering bolus: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
result.comment = ExceptionTranslator.getString(e); result.comment = ExceptionTranslator.getString(e);
} catch (InsightException e) { } catch (InsightException e) {
log.info("Exception while delivering bolus: " + e.getClass().getCanonicalName()); aapsLogger.info(LTag.PUMP, "Exception while delivering bolus: " + e.getClass().getCanonicalName());
result.comment = ExceptionTranslator.getString(e); result.comment = ExceptionTranslator.getString(e);
} catch (Exception e) { } catch (Exception e) {
log.error("Exception while delivering bolus", e); aapsLogger.error("Exception while delivering bolus", e);
result.comment = ExceptionTranslator.getString(e); result.comment = ExceptionTranslator.getString(e);
} }
} else if (detailedBolusInfo.carbs > 0) { } else if (detailedBolusInfo.carbs > 0) {
@ -693,11 +689,11 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
alertService.ignore(null); alertService.ignore(null);
} }
} catch (AppLayerErrorException e) { } catch (AppLayerErrorException e) {
log.info("Exception while canceling bolus: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); aapsLogger.info(LTag.PUMP, "Exception while canceling bolus: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
} catch (InsightException e) { } catch (InsightException e) {
log.info("Exception while canceling bolus: " + e.getClass().getCanonicalName()); aapsLogger.info(LTag.PUMP, "Exception while canceling bolus: " + e.getClass().getCanonicalName());
} catch (Exception e) { } catch (Exception e) {
log.error("Exception while canceling bolus", e); aapsLogger.error("Exception while canceling bolus", e);
} }
}).start(); }).start();
} }
@ -742,11 +738,11 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
fetchStatus(); fetchStatus();
readHistory(); readHistory();
} catch (AppLayerErrorException e) { } catch (AppLayerErrorException e) {
log.info("Exception after setting TBR: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); aapsLogger.info(LTag.PUMP, "Exception after setting TBR: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
} catch (InsightException e) { } catch (InsightException e) {
log.info("Exception after setting TBR: " + e.getClass().getCanonicalName()); aapsLogger.info(LTag.PUMP, "Exception after setting TBR: " + e.getClass().getCanonicalName());
} catch (Exception e) { } catch (Exception e) {
log.error("Exception after setting TBR", e); aapsLogger.error("Exception after setting TBR", e);
} }
return result; return result;
} }
@ -778,13 +774,13 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
readHistory(); readHistory();
fetchStatus(); fetchStatus();
} catch (AppLayerErrorException e) { } catch (AppLayerErrorException e) {
log.info("Exception while setting TBR: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); aapsLogger.info(LTag.PUMP, "Exception while setting TBR: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
result.comment = ExceptionTranslator.getString(e); result.comment = ExceptionTranslator.getString(e);
} catch (InsightException e) { } catch (InsightException e) {
log.info("Exception while setting TBR: " + e.getClass().getCanonicalName()); aapsLogger.info(LTag.PUMP, "Exception while setting TBR: " + e.getClass().getCanonicalName());
result.comment = ExceptionTranslator.getString(e); result.comment = ExceptionTranslator.getString(e);
} catch (Exception e) { } catch (Exception e) {
log.error("Exception while setting TBR", e); aapsLogger.error("Exception while setting TBR", e);
result.comment = ExceptionTranslator.getString(e); result.comment = ExceptionTranslator.getString(e);
} }
return result; return result;
@ -798,11 +794,11 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
fetchStatus(); fetchStatus();
readHistory(); readHistory();
} catch (AppLayerErrorException e) { } catch (AppLayerErrorException e) {
log.info("Exception after delivering extended bolus: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); aapsLogger.info(LTag.PUMP, "Exception after delivering extended bolus: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
} catch (InsightException e) { } catch (InsightException e) {
log.info("Exception after delivering extended bolus: " + e.getClass().getCanonicalName()); aapsLogger.info(LTag.PUMP, "Exception after delivering extended bolus: " + e.getClass().getCanonicalName());
} catch (Exception e) { } catch (Exception e) {
log.error("Exception after delivering extended bolus", e); aapsLogger.error("Exception after delivering extended bolus", e);
} }
return result; return result;
} }
@ -827,18 +823,18 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
extendedBolus.durationInMinutes = durationInMinutes; extendedBolus.durationInMinutes = durationInMinutes;
extendedBolus.insulin = insulin; extendedBolus.insulin = insulin;
extendedBolus.pumpId = insightBolusID.id; extendedBolus.pumpId = insightBolusID.id;
TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus); treatmentsPlugin.addToHistoryExtendedBolus(extendedBolus);
result.success = true; result.success = true;
result.enacted = true; result.enacted = true;
result.comment = resourceHelper.gs(R.string.virtualpump_resultok); result.comment = resourceHelper.gs(R.string.virtualpump_resultok);
} catch (AppLayerErrorException e) { } catch (AppLayerErrorException e) {
log.info("Exception while delivering extended bolus: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); aapsLogger.info(LTag.PUMP, "Exception while delivering extended bolus: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
result.comment = ExceptionTranslator.getString(e); result.comment = ExceptionTranslator.getString(e);
} catch (InsightException e) { } catch (InsightException e) {
log.info("Exception while delivering extended bolus: " + e.getClass().getCanonicalName()); aapsLogger.info(LTag.PUMP, "Exception while delivering extended bolus: " + e.getClass().getCanonicalName());
result.comment = ExceptionTranslator.getString(e); result.comment = ExceptionTranslator.getString(e);
} catch (Exception e) { } catch (Exception e) {
log.error("Exception while delivering extended bolus", e); aapsLogger.error("Exception while delivering extended bolus", e);
result.comment = ExceptionTranslator.getString(e); result.comment = ExceptionTranslator.getString(e);
} }
return result; return result;
@ -857,11 +853,11 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
fetchStatus(); fetchStatus();
readHistory(); readHistory();
} catch (AppLayerErrorException e) { } catch (AppLayerErrorException e) {
log.info("Exception after canceling TBR: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); aapsLogger.info(LTag.PUMP, "Exception after canceling TBR: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
} catch (InsightException e) { } catch (InsightException e) {
log.info("Exception after canceling TBR: " + e.getClass().getCanonicalName()); aapsLogger.info(LTag.PUMP, "Exception after canceling TBR: " + e.getClass().getCanonicalName());
} catch (Exception e) { } catch (Exception e) {
log.error("Exception after canceling TBR", e); aapsLogger.error("Exception after canceling TBR", e);
} }
return result; return result;
} }
@ -881,13 +877,13 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
result.success = true; result.success = true;
result.comment = resourceHelper.gs(R.string.virtualpump_resultok); result.comment = resourceHelper.gs(R.string.virtualpump_resultok);
} catch (AppLayerErrorException e) { } catch (AppLayerErrorException e) {
log.info("Exception while canceling TBR: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); aapsLogger.info(LTag.PUMP, "Exception while canceling TBR: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
result.comment = ExceptionTranslator.getString(e); result.comment = ExceptionTranslator.getString(e);
} catch (InsightException e) { } catch (InsightException e) {
log.info("Exception while canceling TBR: " + e.getClass().getCanonicalName()); aapsLogger.info(LTag.PUMP, "Exception while canceling TBR: " + e.getClass().getCanonicalName());
result.comment = ExceptionTranslator.getString(e); result.comment = ExceptionTranslator.getString(e);
} catch (Exception e) { } catch (Exception e) {
log.error("Exception while canceling TBR", e); aapsLogger.error("Exception while canceling TBR", e);
result.comment = ExceptionTranslator.getString(e); result.comment = ExceptionTranslator.getString(e);
} }
return result; return result;
@ -900,11 +896,11 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
fetchStatus(); fetchStatus();
readHistory(); readHistory();
} catch (AppLayerErrorException e) { } catch (AppLayerErrorException e) {
log.info("Exception after canceling extended bolus: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); aapsLogger.info(LTag.PUMP, "Exception after canceling extended bolus: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
} catch (InsightException e) { } catch (InsightException e) {
log.info("Exception after canceling extended bolus: " + e.getClass().getCanonicalName()); aapsLogger.info(LTag.PUMP, "Exception after canceling extended bolus: " + e.getClass().getCanonicalName());
} catch (Exception e) { } catch (Exception e) {
log.error("Exception after canceling extended bolus", e); aapsLogger.error("Exception after canceling extended bolus", e);
} }
return result; return result;
} }
@ -933,7 +929,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
else UploadQueue.removeID("dbAdd", _id); else UploadQueue.removeID("dbAdd", _id);
MainApp.getDbHelper().delete(extendedBolus); MainApp.getDbHelper().delete(extendedBolus);
} else } else
TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus); treatmentsPlugin.addToHistoryExtendedBolus(extendedBolus);
} }
result.enacted = true; result.enacted = true;
result.success = true; result.success = true;
@ -943,13 +939,13 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
result.success = true; result.success = true;
result.comment = resourceHelper.gs(R.string.virtualpump_resultok); result.comment = resourceHelper.gs(R.string.virtualpump_resultok);
} catch (AppLayerErrorException e) { } catch (AppLayerErrorException e) {
log.info("Exception while canceling extended bolus: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); aapsLogger.info(LTag.PUMP, "Exception while canceling extended bolus: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
result.comment = ExceptionTranslator.getString(e); result.comment = ExceptionTranslator.getString(e);
} catch (InsightException e) { } catch (InsightException e) {
log.info("Exception while canceling extended bolus: " + e.getClass().getCanonicalName()); aapsLogger.info(LTag.PUMP, "Exception while canceling extended bolus: " + e.getClass().getCanonicalName());
result.comment = ExceptionTranslator.getString(e); result.comment = ExceptionTranslator.getString(e);
} catch (Exception e) { } catch (Exception e) {
log.error("Exception while canceling extended bolus", e); aapsLogger.error("Exception while canceling extended bolus", e);
result.comment = ExceptionTranslator.getString(e); result.comment = ExceptionTranslator.getString(e);
} }
return result; return result;
@ -969,11 +965,11 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
} }
} }
} catch (AppLayerErrorException e) { } catch (AppLayerErrorException e) {
log.info("Exception while confirming alert: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); aapsLogger.info(LTag.PUMP, "Exception while confirming alert: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
} catch (InsightException e) { } catch (InsightException e) {
log.info("Exception while confirming alert: " + e.getClass().getCanonicalName()); aapsLogger.info(LTag.PUMP, "Exception while confirming alert: " + e.getClass().getCanonicalName());
} catch (Exception e) { } catch (Exception e) {
log.error("Exception while confirming alert", e); aapsLogger.error("Exception while confirming alert", e);
} }
} }
@ -996,13 +992,13 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
extended.put("ActiveProfile", profileFunction.getProfileName()); extended.put("ActiveProfile", profileFunction.getProfileName());
} catch (Exception e) { } catch (Exception e) {
} }
TemporaryBasal tb = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now); TemporaryBasal tb = treatmentsPlugin.getTempBasalFromHistory(now);
if (tb != null) { if (tb != null) {
extended.put("TempBasalAbsoluteRate", tb.tempBasalConvertedToAbsolute(now, profile)); extended.put("TempBasalAbsoluteRate", tb.tempBasalConvertedToAbsolute(now, profile));
extended.put("TempBasalStart", DateUtil.dateAndTimeString(tb.date)); extended.put("TempBasalStart", DateUtil.dateAndTimeString(tb.date));
extended.put("TempBasalRemaining", tb.getPlannedRemainingMinutes()); extended.put("TempBasalRemaining", tb.getPlannedRemainingMinutes());
} }
ExtendedBolus eb = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(now); ExtendedBolus eb = treatmentsPlugin.getExtendedBolusFromHistory(now);
if (eb != null) { if (eb != null) {
extended.put("ExtendedBolusAbsoluteRate", eb.absoluteRate()); extended.put("ExtendedBolusAbsoluteRate", eb.absoluteRate());
extended.put("ExtendedBolusStart", DateUtil.dateAndTimeString(eb.date)); extended.put("ExtendedBolusStart", DateUtil.dateAndTimeString(eb.date));
@ -1021,7 +1017,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
} }
pump.put("clock", DateUtil.toISOString(now)); pump.put("clock", DateUtil.toISOString(now));
} catch (JSONException e) { } catch (JSONException e) {
log.error("Unhandled exception", e); aapsLogger.error("Unhandled exception", e);
} }
return pump; return pump;
} }
@ -1053,13 +1049,13 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
fetchStatus(); fetchStatus();
readHistory(); readHistory();
} catch (AppLayerErrorException e) { } catch (AppLayerErrorException e) {
log.info("Exception while stopping pump: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); aapsLogger.info(LTag.PUMP, "Exception while stopping pump: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
result.comment = ExceptionTranslator.getString(e); result.comment = ExceptionTranslator.getString(e);
} catch (InsightException e) { } catch (InsightException e) {
log.info("Exception while stopping pump: " + e.getClass().getCanonicalName()); aapsLogger.info(LTag.PUMP, "Exception while stopping pump: " + e.getClass().getCanonicalName());
result.comment = ExceptionTranslator.getString(e); result.comment = ExceptionTranslator.getString(e);
} catch (Exception e) { } catch (Exception e) {
log.error("Exception while stopping pump", e); aapsLogger.error("Exception while stopping pump", e);
result.comment = ExceptionTranslator.getString(e); result.comment = ExceptionTranslator.getString(e);
} }
return result; return result;
@ -1076,13 +1072,13 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
fetchStatus(); fetchStatus();
readHistory(); readHistory();
} catch (AppLayerErrorException e) { } catch (AppLayerErrorException e) {
log.info("Exception while starting pump: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); aapsLogger.info(LTag.PUMP, "Exception while starting pump: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
result.comment = ExceptionTranslator.getString(e); result.comment = ExceptionTranslator.getString(e);
} catch (InsightException e) { } catch (InsightException e) {
log.info("Exception while starting pump: " + e.getClass().getCanonicalName()); aapsLogger.info(LTag.PUMP, "Exception while starting pump: " + e.getClass().getCanonicalName());
result.comment = ExceptionTranslator.getString(e); result.comment = ExceptionTranslator.getString(e);
} catch (Exception e) { } catch (Exception e) {
log.error("Exception while starting pump", e); aapsLogger.error("Exception while starting pump", e);
result.comment = ExceptionTranslator.getString(e); result.comment = ExceptionTranslator.getString(e);
} }
return result; return result;
@ -1098,15 +1094,15 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
result.enacted = true; result.enacted = true;
} catch (AppLayerErrorException e) { } catch (AppLayerErrorException e) {
tbrOverNotificationBlock.setEnabled(valueBefore); tbrOverNotificationBlock.setEnabled(valueBefore);
log.info("Exception while updating TBR notification block: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); aapsLogger.info(LTag.PUMP, "Exception while updating TBR notification block: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
result.comment = ExceptionTranslator.getString(e); result.comment = ExceptionTranslator.getString(e);
} catch (InsightException e) { } catch (InsightException e) {
tbrOverNotificationBlock.setEnabled(valueBefore); tbrOverNotificationBlock.setEnabled(valueBefore);
log.info("Exception while updating TBR notification block: " + e.getClass().getSimpleName()); aapsLogger.info(LTag.PUMP, "Exception while updating TBR notification block: " + e.getClass().getSimpleName());
result.comment = ExceptionTranslator.getString(e); result.comment = ExceptionTranslator.getString(e);
} catch (Exception e) { } catch (Exception e) {
tbrOverNotificationBlock.setEnabled(valueBefore); tbrOverNotificationBlock.setEnabled(valueBefore);
log.error("Exception while updating TBR notification block", e); aapsLogger.error("Exception while updating TBR notification block", e);
result.comment = ExceptionTranslator.getString(e); result.comment = ExceptionTranslator.getString(e);
} }
return result; return result;
@ -1202,11 +1198,11 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
MainApp.getDbHelper().createOrUpdate(historyOffset); MainApp.getDbHelper().createOrUpdate(historyOffset);
} }
} catch (AppLayerErrorException e) { } catch (AppLayerErrorException e) {
log.info("Exception while reading history: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); aapsLogger.info(LTag.PUMP, "Exception while reading history: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
} catch (InsightException e) { } catch (InsightException e) {
log.info("Exception while reading history: " + e.getClass().getSimpleName()); aapsLogger.info(LTag.PUMP, "Exception while reading history: " + e.getClass().getSimpleName());
} catch (Exception e) { } catch (Exception e) {
log.error("Exception while reading history", e); aapsLogger.error("Exception while reading history", e);
} finally { } finally {
try { try {
connectionService.requestMessage(new StopReadingHistoryMessage()).await(); connectionService.requestMessage(new StopReadingHistoryMessage()).await();
@ -1214,11 +1210,11 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
} }
} }
} catch (AppLayerErrorException e) { } catch (AppLayerErrorException e) {
log.info("Exception while reading history: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); aapsLogger.info(LTag.PUMP, "Exception while reading history: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
} catch (InsightException e) { } catch (InsightException e) {
log.info("Exception while reading history: " + e.getClass().getSimpleName()); aapsLogger.info(LTag.PUMP, "Exception while reading history: " + e.getClass().getSimpleName());
} catch (Exception e) { } catch (Exception e) {
log.error("Exception while reading history", e); aapsLogger.error("Exception while reading history", e);
} }
new Handler(Looper.getMainLooper()).post(() -> rxBus.send(new EventRefreshOverview("LocalInsightPlugin::readHistory"))); new Handler(Looper.getMainLooper()).post(() -> rxBus.send(new EventRefreshOverview("LocalInsightPlugin::readHistory")));
} }
@ -1245,7 +1241,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
} }
Collections.sort(temporaryBasals, (o1, o2) -> (int) (o1.date - o2.date)); Collections.sort(temporaryBasals, (o1, o2) -> (int) (o1.date - o2.date));
for (TemporaryBasal temporaryBasal : temporaryBasals) for (TemporaryBasal temporaryBasal : temporaryBasals)
TreatmentsPlugin.getPlugin().addToHistoryTempBasal(temporaryBasal); treatmentsPlugin.addToHistoryTempBasal(temporaryBasal);
} }
private boolean processHistoryEvent(String serial, List<TemporaryBasal> temporaryBasals, List<InsightPumpID> pumpStartedEvents, HistoryEvent event) { private boolean processHistoryEvent(String serial, List<TemporaryBasal> temporaryBasals, List<InsightPumpID> pumpStartedEvents, HistoryEvent event) {
@ -1410,7 +1406,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
detailedBolusInfo.source = Source.PUMP; detailedBolusInfo.source = Source.PUMP;
detailedBolusInfo.pumpId = bolusID.id; detailedBolusInfo.pumpId = bolusID.id;
detailedBolusInfo.insulin = event.getImmediateAmount(); detailedBolusInfo.insulin = event.getImmediateAmount();
TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, true); treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, true);
} }
if ((event.getBolusType() == BolusType.EXTENDED || event.getBolusType() == BolusType.MULTIWAVE)) { if ((event.getBolusType() == BolusType.EXTENDED || event.getBolusType() == BolusType.MULTIWAVE)) {
ExtendedBolus extendedBolus = new ExtendedBolus(); ExtendedBolus extendedBolus = new ExtendedBolus();
@ -1420,7 +1416,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
extendedBolus.insulin = event.getExtendedAmount(); extendedBolus.insulin = event.getExtendedAmount();
extendedBolus.pumpId = bolusID.id; extendedBolus.pumpId = bolusID.id;
if (profileFunction.getProfile(extendedBolus.date) != null) if (profileFunction.getProfile(extendedBolus.date) != null)
TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus); treatmentsPlugin.addToHistoryExtendedBolus(extendedBolus);
} }
} }
@ -1444,7 +1440,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
detailedBolusInfo.source = Source.PUMP; detailedBolusInfo.source = Source.PUMP;
detailedBolusInfo.pumpId = bolusID.id; detailedBolusInfo.pumpId = bolusID.id;
detailedBolusInfo.insulin = event.getImmediateAmount(); detailedBolusInfo.insulin = event.getImmediateAmount();
TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, true); treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, true);
} }
if (event.getBolusType() == BolusType.EXTENDED || event.getBolusType() == BolusType.MULTIWAVE) { if (event.getBolusType() == BolusType.EXTENDED || event.getBolusType() == BolusType.MULTIWAVE) {
if (event.getDuration() == 0) { if (event.getDuration() == 0) {
@ -1463,7 +1459,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
extendedBolus.insulin = event.getExtendedAmount(); extendedBolus.insulin = event.getExtendedAmount();
extendedBolus.pumpId = bolusID.id; extendedBolus.pumpId = bolusID.id;
if (profileFunction.getProfile(extendedBolus.date) != null) if (profileFunction.getProfile(extendedBolus.date) != null)
TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus); treatmentsPlugin.addToHistoryExtendedBolus(extendedBolus);
} }
} }
} }
@ -1585,7 +1581,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
MainApp.getDbHelper().createOrUpdate(careportalEvent); MainApp.getDbHelper().createOrUpdate(careportalEvent);
NSUpload.uploadCareportalEntryToNS(data); NSUpload.uploadCareportalEntryToNS(data);
} catch (JSONException e) { } catch (JSONException e) {
log.error("Unhandled exception", e); aapsLogger.error("Unhandled exception", e);
} }
} }
@ -1619,19 +1615,19 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
MainApp.getDbHelper().createOrUpdate(careportalEvent); MainApp.getDbHelper().createOrUpdate(careportalEvent);
NSUpload.uploadCareportalEntryToNS(data); NSUpload.uploadCareportalEntryToNS(data);
} catch (JSONException e) { } catch (JSONException e) {
log.error("Unhandled exception", e); aapsLogger.error("Unhandled exception", e);
} }
} }
@Override @NonNull @Override
public Constraint<Integer> applyBasalPercentConstraints(Constraint<Integer> percentRate, Profile profile) { public Constraint<Integer> applyBasalPercentConstraints(Constraint<Integer> percentRate, @NonNull Profile profile) {
percentRate.setIfGreater(getAapsLogger(), 0, String.format(resourceHelper.gs(R.string.limitingpercentrate), 0, resourceHelper.gs(R.string.itmustbepositivevalue)), this); percentRate.setIfGreater(getAapsLogger(), 0, String.format(resourceHelper.gs(R.string.limitingpercentrate), 0, resourceHelper.gs(R.string.itmustbepositivevalue)), this);
percentRate.setIfSmaller(getAapsLogger(), getPumpDescription().maxTempPercent, String.format(resourceHelper.gs(R.string.limitingpercentrate), getPumpDescription().maxTempPercent, resourceHelper.gs(R.string.pumplimit)), this); percentRate.setIfSmaller(getAapsLogger(), getPumpDescription().maxTempPercent, String.format(resourceHelper.gs(R.string.limitingpercentrate), getPumpDescription().maxTempPercent, resourceHelper.gs(R.string.pumplimit)), this);
return percentRate; return percentRate;
} }
@Override @NonNull @Override
public Constraint<Double> applyBolusConstraints(Constraint<Double> insulin) { public Constraint<Double> applyBolusConstraints(@NonNull Constraint<Double> insulin) {
if (!limitsFetched) return insulin; if (!limitsFetched) return insulin;
insulin.setIfSmaller(getAapsLogger(), maximumBolusAmount, String.format(resourceHelper.gs(R.string.limitingbolus), maximumBolusAmount, resourceHelper.gs(R.string.pumplimit)), this); insulin.setIfSmaller(getAapsLogger(), maximumBolusAmount, String.format(resourceHelper.gs(R.string.limitingbolus), maximumBolusAmount, resourceHelper.gs(R.string.pumplimit)), this);
if (insulin.value() < minimumBolusAmount) { if (insulin.value() < minimumBolusAmount) {
@ -1645,8 +1641,8 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
return insulin; return insulin;
} }
@Override @NonNull @Override
public Constraint<Double> applyExtendedBolusConstraints(Constraint<Double> insulin) { public Constraint<Double> applyExtendedBolusConstraints(@NonNull Constraint<Double> insulin) {
return applyBolusConstraints(insulin); return applyBolusConstraints(insulin);
} }

View file

@ -4,7 +4,6 @@ import androidx.annotation.NonNull;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.slf4j.Logger;
import java.util.List; import java.util.List;
@ -13,7 +12,6 @@ import javax.inject.Singleton;
import dagger.android.HasAndroidInjector; import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
@ -25,8 +23,7 @@ import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.PumpPluginBase; import info.nightscout.androidaps.interfaces.PumpPluginBase;
import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.common.ManufacturerType; import info.nightscout.androidaps.plugins.common.ManufacturerType;
import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction; import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction;
@ -43,8 +40,8 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper;
*/ */
@Singleton @Singleton
public class MDIPlugin extends PumpPluginBase implements PumpInterface { public class MDIPlugin extends PumpPluginBase implements PumpInterface {
private static Logger log = StacktraceLoggerWrapper.getLogger(MDIPlugin.class);
private TreatmentsPlugin treatmentsPlugin;
private PumpDescription pumpDescription = new PumpDescription(); private PumpDescription pumpDescription = new PumpDescription();
@Inject @Inject
@ -53,7 +50,8 @@ public class MDIPlugin extends PumpPluginBase implements PumpInterface {
AAPSLogger aapsLogger, AAPSLogger aapsLogger,
RxBusWrapper rxBus, RxBusWrapper rxBus,
ResourceHelper resourceHelper, ResourceHelper resourceHelper,
CommandQueueProvider commandQueue CommandQueueProvider commandQueue,
TreatmentsPlugin treatmentsPlugin
) { ) {
super(new PluginDescription() super(new PluginDescription()
.mainType(PluginType.PUMP) .mainType(PluginType.PUMP)
@ -61,6 +59,8 @@ public class MDIPlugin extends PumpPluginBase implements PumpInterface {
.description(R.string.description_pump_mdi), .description(R.string.description_pump_mdi),
injector, aapsLogger, resourceHelper, commandQueue injector, aapsLogger, resourceHelper, commandQueue
); );
this.treatmentsPlugin = treatmentsPlugin;
pumpDescription.isBolusCapable = true; pumpDescription.isBolusCapable = true;
pumpDescription.bolusStep = 0.5d; pumpDescription.bolusStep = 0.5d;
@ -171,8 +171,8 @@ public class MDIPlugin extends PumpPluginBase implements PumpInterface {
result.success = true; result.success = true;
result.bolusDelivered = detailedBolusInfo.insulin; result.bolusDelivered = detailedBolusInfo.insulin;
result.carbsDelivered = detailedBolusInfo.carbs; result.carbsDelivered = detailedBolusInfo.carbs;
result.comment = MainApp.gs(R.string.virtualpump_resultok); result.comment = getResourceHelper().gs(R.string.virtualpump_resultok);
TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, false); treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, false);
return result; return result;
} }
@ -184,9 +184,8 @@ public class MDIPlugin extends PumpPluginBase implements PumpInterface {
public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean enforceNew) { public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean enforceNew) {
PumpEnactResult result = new PumpEnactResult(getInjector()); PumpEnactResult result = new PumpEnactResult(getInjector());
result.success = false; result.success = false;
result.comment = MainApp.gs(R.string.pumperror); result.comment = getResourceHelper().gs(R.string.pumperror);
if (L.isEnabled(L.PUMPCOMM)) getAapsLogger().debug(LTag.PUMPBTCOMM, "Setting temp basal absolute: " + result);
log.debug("Setting temp basal absolute: " + result);
return result; return result;
} }
@ -194,9 +193,8 @@ public class MDIPlugin extends PumpPluginBase implements PumpInterface {
public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) { public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) {
PumpEnactResult result = new PumpEnactResult(getInjector()); PumpEnactResult result = new PumpEnactResult(getInjector());
result.success = false; result.success = false;
result.comment = MainApp.gs(R.string.pumperror); result.comment = getResourceHelper().gs(R.string.pumperror);
if (L.isEnabled(L.PUMPCOMM)) getAapsLogger().debug(LTag.PUMPBTCOMM, "Settings temp basal percent: " + result);
log.debug("Settings temp basal percent: " + result);
return result; return result;
} }
@ -204,9 +202,8 @@ public class MDIPlugin extends PumpPluginBase implements PumpInterface {
public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) { public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) {
PumpEnactResult result = new PumpEnactResult(getInjector()); PumpEnactResult result = new PumpEnactResult(getInjector());
result.success = false; result.success = false;
result.comment = MainApp.gs(R.string.pumperror); result.comment = getResourceHelper().gs(R.string.pumperror);
if (L.isEnabled(L.PUMPCOMM)) getAapsLogger().debug(LTag.PUMPBTCOMM, "Setting extended bolus: " + result);
log.debug("Setting extended bolus: " + result);
return result; return result;
} }
@ -214,9 +211,8 @@ public class MDIPlugin extends PumpPluginBase implements PumpInterface {
public PumpEnactResult cancelTempBasal(boolean force) { public PumpEnactResult cancelTempBasal(boolean force) {
PumpEnactResult result = new PumpEnactResult(getInjector()); PumpEnactResult result = new PumpEnactResult(getInjector());
result.success = false; result.success = false;
result.comment = MainApp.gs(R.string.pumperror); result.comment = getResourceHelper().gs(R.string.pumperror);
if (L.isEnabled(L.PUMPCOMM)) getAapsLogger().debug(LTag.PUMPBTCOMM, "Cancel temp basal: " + result);
log.debug("Cancel temp basal: " + result);
return result; return result;
} }
@ -224,9 +220,8 @@ public class MDIPlugin extends PumpPluginBase implements PumpInterface {
public PumpEnactResult cancelExtendedBolus() { public PumpEnactResult cancelExtendedBolus() {
PumpEnactResult result = new PumpEnactResult(getInjector()); PumpEnactResult result = new PumpEnactResult(getInjector());
result.success = false; result.success = false;
result.comment = MainApp.gs(R.string.pumperror); result.comment = getResourceHelper().gs(R.string.pumperror);
if (L.isEnabled(L.PUMPCOMM)) getAapsLogger().debug(LTag.PUMPBTCOMM, "Canceling extended bolus: " + result);
log.debug("Canceling extended bolus: " + result);
return result; return result;
} }

View file

@ -905,7 +905,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
detailedBolusInfo.date = now; detailedBolusInfo.date = now;
detailedBolusInfo.deliverAt = now; // not sure about that one detailedBolusInfo.deliverAt = now; // not sure about that one
TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, true); treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, true);
// we subtract insulin, exact amount will be visible with next remainingInsulin update. // we subtract insulin, exact amount will be visible with next remainingInsulin update.
getMDTPumpStatus().reservoirRemainingUnits -= detailedBolusInfo.insulin; getMDTPumpStatus().reservoirRemainingUnits -= detailedBolusInfo.insulin;
@ -1082,7 +1082,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
.absolute(absoluteRate) // .absolute(absoluteRate) //
.source(Source.USER); .source(Source.USER);
TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempStart); treatmentsPlugin.addToHistoryTempBasal(tempStart);
incrementStatistics(MedtronicConst.Statistics.TBRsSet); incrementStatistics(MedtronicConst.Statistics.TBRsSet);
@ -1437,7 +1437,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
.duration(0) // .duration(0) //
.source(Source.USER); .source(Source.USER);
TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempBasal); treatmentsPlugin.addToHistoryTempBasal(tempBasal);
return new PumpEnactResult(getInjector()).success(true).enacted(true) // return new PumpEnactResult(getInjector()).success(true).enacted(true) //
.isTempCancel(true); .isTempCancel(true);

View file

@ -10,19 +10,20 @@ import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView; import androidx.cardview.widget.CardView;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView;
import javax.inject.Inject;
import dagger.android.support.DaggerFragment;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Intervals; import info.nightscout.androidaps.data.Intervals;
import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.events.EventTempTargetChange; import info.nightscout.androidaps.events.EventTempTargetChange;
import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue; import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue;
import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart; import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart;
@ -31,7 +32,8 @@ import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.DecimalFormatter;
import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.OKDialog; import info.nightscout.androidaps.utils.OKDialog;
import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.CompositeDisposable;
@ -39,7 +41,13 @@ import io.reactivex.disposables.CompositeDisposable;
* Created by mike on 13/01/17. * Created by mike on 13/01/17.
*/ */
public class TreatmentsTempTargetFragment extends Fragment { public class TreatmentsTempTargetFragment extends DaggerFragment {
@Inject TreatmentsPlugin treatmentsPlugin;
@Inject SP sp;
@Inject RxBusWrapper rxBus;
@Inject ProfileFunction profileFunction;
@Inject ResourceHelper resourceHelper;
private CompositeDisposable disposable = new CompositeDisposable(); private CompositeDisposable disposable = new CompositeDisposable();
private RecyclerView recyclerView; private RecyclerView recyclerView;
@ -63,7 +71,7 @@ public class TreatmentsTempTargetFragment extends Fragment {
@Override @Override
public void onBindViewHolder(TempTargetsViewHolder holder, int position) { public void onBindViewHolder(TempTargetsViewHolder holder, int position) {
String units = ProfileFunctions.getSystemUnits(); String units = profileFunction.getUnits();
TempTarget tempTarget = tempTargetList.getReversed(position); TempTarget tempTarget = tempTargetList.getReversed(position);
holder.ph.setVisibility(tempTarget.source == Source.PUMP ? View.VISIBLE : View.GONE); holder.ph.setVisibility(tempTarget.source == Source.PUMP ? View.VISIBLE : View.GONE);
holder.ns.setVisibility(NSUpload.isIdValid(tempTarget._id) ? View.VISIBLE : View.GONE); holder.ns.setVisibility(NSUpload.isIdValid(tempTarget._id) ? View.VISIBLE : View.GONE);
@ -83,9 +91,9 @@ public class TreatmentsTempTargetFragment extends Fragment {
holder.reasonColon.setText(""); holder.reasonColon.setText("");
} }
if (tempTarget.isInProgress() && tempTarget == currentlyActiveTarget) { if (tempTarget.isInProgress() && tempTarget == currentlyActiveTarget) {
holder.date.setTextColor(ContextCompat.getColor(MainApp.instance(), R.color.colorActive)); holder.date.setTextColor(resourceHelper.gc(R.color.colorActive));
} else if (tempTarget.date > DateUtil.now()) { } else if (tempTarget.date > DateUtil.now()) {
holder.date.setTextColor(ContextCompat.getColor(MainApp.instance(), R.color.colorScheduled)); holder.date.setTextColor(resourceHelper.gc(R.color.colorScheduled));
} else { } else {
holder.date.setTextColor(holder.reasonColon.getCurrentTextColor()); holder.date.setTextColor(holder.reasonColon.getCurrentTextColor());
} }
@ -130,8 +138,8 @@ public class TreatmentsTempTargetFragment extends Fragment {
remove = itemView.findViewById(R.id.temptargetrange_remove); remove = itemView.findViewById(R.id.temptargetrange_remove);
remove.setOnClickListener(v -> { remove.setOnClickListener(v -> {
final TempTarget tempTarget = (TempTarget) v.getTag(); final TempTarget tempTarget = (TempTarget) v.getTag();
OKDialog.showConfirmation(getContext(), MainApp.gs(R.string.removerecord), OKDialog.showConfirmation(getContext(), resourceHelper.gs(R.string.removerecord),
MainApp.gs(R.string.careportal_temporarytarget) + ": " + tempTarget.friendlyDescription(ProfileFunctions.getSystemUnits()) + resourceHelper.gs(R.string.careportal_temporarytarget) + ": " + tempTarget.friendlyDescription(profileFunction.getUnits()) +
"\n" + DateUtil.dateAndTimeString(tempTarget.date), "\n" + DateUtil.dateAndTimeString(tempTarget.date),
(dialog, id) -> { (dialog, id) -> {
final String _id = tempTarget._id; final String _id = tempTarget._id;
@ -158,17 +166,17 @@ public class TreatmentsTempTargetFragment extends Fragment {
LinearLayoutManager llm = new LinearLayoutManager(view.getContext()); LinearLayoutManager llm = new LinearLayoutManager(view.getContext());
recyclerView.setLayoutManager(llm); recyclerView.setLayoutManager(llm);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(TreatmentsPlugin.getPlugin().getTempTargetsFromHistory()); RecyclerViewAdapter adapter = new RecyclerViewAdapter(treatmentsPlugin.getTempTargetsFromHistory());
recyclerView.setAdapter(adapter); recyclerView.setAdapter(adapter);
Button refreshFromNS = view.findViewById(R.id.temptargetrange_refreshfromnightscout); Button refreshFromNS = view.findViewById(R.id.temptargetrange_refreshfromnightscout);
refreshFromNS.setOnClickListener(v -> refreshFromNS.setOnClickListener(v ->
OKDialog.showConfirmation(getContext(), MainApp.gs(R.string.refresheventsfromnightscout) + " ?", () -> { OKDialog.showConfirmation(getContext(), resourceHelper.gs(R.string.refresheventsfromnightscout) + " ?", () -> {
MainApp.getDbHelper().resetTempTargets(); MainApp.getDbHelper().resetTempTargets();
RxBus.Companion.getINSTANCE().send(new EventNSClientRestart()); rxBus.send(new EventNSClientRestart());
})); }));
boolean nsUploadOnly = SP.getBoolean(R.string.key_ns_upload_only, true); boolean nsUploadOnly = sp.getBoolean(R.string.key_ns_upload_only, true);
if (nsUploadOnly) if (nsUploadOnly)
refreshFromNS.setVisibility(View.GONE); refreshFromNS.setVisibility(View.GONE);
@ -178,7 +186,7 @@ public class TreatmentsTempTargetFragment extends Fragment {
@Override @Override
public synchronized void onResume() { public synchronized void onResume() {
super.onResume(); super.onResume();
disposable.add(RxBus.Companion.getINSTANCE() disposable.add(rxBus
.toObservable(EventTempTargetChange.class) .toObservable(EventTempTargetChange.class)
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
.subscribe(event -> updateGui(), exception -> FabricPrivacy.getInstance().logException(exception)) .subscribe(event -> updateGui(), exception -> FabricPrivacy.getInstance().logException(exception))
@ -193,6 +201,6 @@ public class TreatmentsTempTargetFragment extends Fragment {
} }
private void updateGui() { private void updateGui() {
recyclerView.swapAdapter(new RecyclerViewAdapter(TreatmentsPlugin.getPlugin().getTempTargetsFromHistory()), false); recyclerView.swapAdapter(new RecyclerViewAdapter(treatmentsPlugin.getTempTargetsFromHistory()), false);
} }
} }

View file

@ -1,6 +1,7 @@
package info.nightscout.androidaps.utils.resources package info.nightscout.androidaps.utils.resources
import android.annotation.SuppressLint import android.annotation.SuppressLint
import android.content.Context
import android.content.res.AssetFileDescriptor import android.content.res.AssetFileDescriptor
import android.graphics.Bitmap import android.graphics.Bitmap
import android.graphics.BitmapFactory import android.graphics.BitmapFactory
@ -10,32 +11,31 @@ import androidx.annotation.PluralsRes
import androidx.annotation.StringRes import androidx.annotation.StringRes
import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat
import info.nightscout.androidaps.Config import info.nightscout.androidaps.Config
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import javax.inject.Inject import javax.inject.Inject
/** /**
* Created by adrian on 2019-12-23. * Created by adrian on 2019-12-23.
*/ */
class ResourceHelperImplementation @Inject constructor(private val mainApp: MainApp) : ResourceHelper { class ResourceHelperImplementation @Inject constructor(private val context: Context) : ResourceHelper {
override fun gs(@StringRes id: Int): String = mainApp.getString(id) override fun gs(@StringRes id: Int): String = context.getString(id)
override fun gs(@StringRes id: Int, vararg args: Any?): String = mainApp.getString(id, *args) override fun gs(@StringRes id: Int, vararg args: Any?): String = context.getString(id, *args)
override fun gq(@PluralsRes id: Int, quantity: Int, vararg args: Any?): String = override fun gq(@PluralsRes id: Int, quantity: Int, vararg args: Any?): String =
mainApp.resources.getQuantityString(id, quantity, *args) context.resources.getQuantityString(id, quantity, *args)
override fun gc(@ColorRes id: Int): Int = ContextCompat.getColor(mainApp, id) override fun gc(@ColorRes id: Int): Int = ContextCompat.getColor(context, id)
override fun gb(@BoolRes id :Int) : Boolean = mainApp.resources.getBoolean(id) override fun gb(@BoolRes id :Int) : Boolean = context.resources.getBoolean(id)
@SuppressLint("ResourceType") @SuppressLint("ResourceType")
override fun gcs(@ColorRes id: Int): String = override fun gcs(@ColorRes id: Int): String =
gs(id).replace("#ff", "#") gs(id).replace("#ff", "#")
override fun openRawResourceFd(id: Int): AssetFileDescriptor = override fun openRawResourceFd(id: Int): AssetFileDescriptor =
mainApp.resources.openRawResourceFd(id) context.resources.openRawResourceFd(id)
override fun getIcon(): Int { override fun getIcon(): Int {
return when { return when {
@ -54,10 +54,10 @@ class ResourceHelperImplementation @Inject constructor(private val mainApp: Main
} }
override fun decodeResource(id: Int): Bitmap = override fun decodeResource(id: Int): Bitmap =
BitmapFactory.decodeResource(mainApp.resources, id) BitmapFactory.decodeResource(context.resources, id)
override fun dpToPx(dp: Int): Int { override fun dpToPx(dp: Int): Int {
val scale = mainApp.resources.displayMetrics.density val scale = context.resources.displayMetrics.density
return (dp * scale + 0.5f).toInt() return (dp * scale + 0.5f).toInt()
} }
} }

View file

@ -1,19 +1,9 @@
package info.nightscout.androidaps.plugins.general.automation.actions package info.nightscout.androidaps.plugins.general.automation.actions
import com.google.common.base.Optional
import info.AAPSMocker
import info.SPMocker
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.db.ProfileSwitch
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions
import info.nightscout.androidaps.plugins.general.automation.elements.InputProfileName import info.nightscout.androidaps.plugins.general.automation.elements.InputProfileName
import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin
import info.nightscout.androidaps.plugins.profile.ns.NSProfilePlugin
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.SP
import org.junit.Assert import org.junit.Assert
import org.junit.Before import org.junit.Before
import org.junit.Test import org.junit.Test
@ -24,8 +14,6 @@ import org.mockito.Mockito
import org.mockito.Mockito.`when` import org.mockito.Mockito.`when`
import org.mockito.Mockito.anyInt import org.mockito.Mockito.anyInt
import org.mockito.Mockito.anyString import org.mockito.Mockito.anyString
import org.mockito.invocation.InvocationOnMock
import org.powermock.api.mockito.PowerMockito
import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner import org.powermock.modules.junit4.PowerMockRunner

View file

@ -1,14 +1,9 @@
package info.nightscout.androidaps.plugins.general.automation.elements package info.nightscout.androidaps.plugins.general.automation.elements
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions
import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerTestBase import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerTestBase
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.SP
import org.junit.Assert import org.junit.Assert
import org.junit.Test import org.junit.Test
import org.junit.runner.RunWith import org.junit.runner.RunWith
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class) @RunWith(PowerMockRunner::class)

View file

@ -1,14 +1,12 @@
package info.nightscout.androidaps.plugins.general.automation.triggers package info.nightscout.androidaps.plugins.general.automation.triggers
import com.google.common.base.Optional import com.google.common.base.Optional
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions
import info.nightscout.androidaps.plugins.general.automation.elements.Comparator import info.nightscout.androidaps.plugins.general.automation.elements.Comparator
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.SP
import org.json.JSONObject import org.json.JSONObject
import org.junit.Assert import org.junit.Assert
import org.junit.Before import org.junit.Before
@ -22,7 +20,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class) @RunWith(PowerMockRunner::class)
@PrepareForTest(ProfileFunctions::class, DateUtil::class, IobCobCalculatorPlugin::class, SP::class) @PrepareForTest(ProfileFunctions::class, DateUtil::class, IobCobCalculatorPlugin::class)
class TriggerAutosensValueTest : TriggerTestBase() { class TriggerAutosensValueTest : TriggerTestBase() {
var now = 1514766900000L var now = 1514766900000L

View file

@ -6,7 +6,6 @@ import info.nightscout.androidaps.plugins.general.automation.elements.Comparator
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.CobInfo import info.nightscout.androidaps.plugins.iob.iobCobCalculator.CobInfo
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.SP
import org.json.JSONObject import org.json.JSONObject
import org.junit.Assert import org.junit.Assert
import org.junit.Before import org.junit.Before
@ -18,7 +17,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class) @RunWith(PowerMockRunner::class)
@PrepareForTest(DateUtil::class, IobCobCalculatorPlugin::class, SP::class) @PrepareForTest(DateUtil::class, IobCobCalculatorPlugin::class)
class TriggerCOBTest : TriggerTestBase() { class TriggerCOBTest : TriggerTestBase() {
var now = 1514766900000L var now = 1514766900000L

View file

@ -5,19 +5,16 @@ import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.AAPSMocker import info.AAPSMocker
import info.nightscout.androidaps.Constants import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.logging.L
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction
import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRSTestBase import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRSTestBase
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.SP
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import org.junit.Assert import org.junit.Assert
import org.junit.Before import org.junit.Before
@ -30,7 +27,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class) @RunWith(PowerMockRunner::class)
@PrepareForTest(ConstraintChecker::class, RxBusWrapper::class, L::class, SP::class, MainApp::class, DetailedBolusInfoStorage::class) @PrepareForTest(ConstraintChecker::class, RxBusWrapper::class, DetailedBolusInfoStorage::class)
class DanaRSPluginTest : DanaRSTestBase() { class DanaRSPluginTest : DanaRSTestBase() {
@Mock lateinit var context: Context @Mock lateinit var context: Context

View file

@ -1,8 +1,5 @@
package info.nightscout.androidaps.plugins.pump.danaRS.comm package info.nightscout.androidaps.plugins.pump.danaRS.comm
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.logging.L
import info.nightscout.androidaps.utils.SP
import org.junit.Assert import org.junit.Assert
import org.junit.Test import org.junit.Test
import org.junit.runner.RunWith import org.junit.runner.RunWith

View file

@ -1,16 +1,11 @@
package info.nightscout.androidaps.plugins.pump.danaRS.comm package info.nightscout.androidaps.plugins.pump.danaRS.comm
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.logging.L
import info.nightscout.androidaps.utils.SP
import org.junit.Assert import org.junit.Assert
import org.junit.Test import org.junit.Test
import org.junit.runner.RunWith import org.junit.runner.RunWith
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class) @RunWith(PowerMockRunner::class)
@PrepareForTest(MainApp::class, SP::class, L::class)
class DanaRS_Packet_General_Get_Shipping_InformationTest : DanaRSTestBase() { class DanaRS_Packet_General_Get_Shipping_InformationTest : DanaRSTestBase() {
@Test fun runTest() { @Test fun runTest() {

View file

@ -15,7 +15,6 @@ import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.SP
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import org.junit.Before import org.junit.Before
import org.junit.Test import org.junit.Test
@ -26,7 +25,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class) @RunWith(PowerMockRunner::class)
@PrepareForTest(ConstraintChecker::class, SP::class, DetailedBolusInfoStorage::class) @PrepareForTest(ConstraintChecker::class, DetailedBolusInfoStorage::class)
class DanaRv2PluginTest : TestBase() { class DanaRv2PluginTest : TestBase() {
@Mock lateinit var aapsLogger: AAPSLogger @Mock lateinit var aapsLogger: AAPSLogger

View file

@ -1,29 +1,23 @@
package info.nightscout.androidaps.plugins.pump.medtronic.data.dto; package info.nightscout.androidaps.plugins.pump.medtronic.data.dto;
import static org.mockito.Mockito.when;
import junit.framework.Assert; import junit.framework.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Ignore; import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito; import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import info.AAPSMocker; import info.AAPSMocker;
import info.SPMocker; import info.SPMocker;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus; import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus;
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil;
import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.SP;
import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.T;
import static org.mockito.Mockito.when;
/** /**
* Created by andy on 6/16/18. * Created by andy on 6/16/18.
*/ */
@ -56,10 +50,10 @@ public class BasalProfileUTest {
BasalProfile basalProfile = new BasalProfile(); BasalProfile basalProfile = new BasalProfile();
byte[] data = { // byte[] data = { //
0x48, 0x00, 0x00, 0x40, 0x00, 0x02, 0x38, 0x00, 0x04, 0x3A, 0x00, 0x06, 0x32, 0x00, 0x0C, 0x26, 0x00, // 0x48, 0x00, 0x00, 0x40, 0x00, 0x02, 0x38, 0x00, 0x04, 0x3A, 0x00, 0x06, 0x32, 0x00, 0x0C, 0x26, 0x00, //
0x10, 0x2E, 0x00, 0x14, 0x32, 0x00, 0x18, 0x26, 0x00, 0x1A, 0x1A, 0x00, 0x20, 0x14, 0x00, 0x2A, 0x00, // 0x10, 0x2E, 0x00, 0x14, 0x32, 0x00, 0x18, 0x26, 0x00, 0x1A, 0x1A, 0x00, 0x20, 0x14, 0x00, 0x2A, 0x00, //
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
basalProfile.setRawData(data); basalProfile.setRawData(data);
@ -91,7 +85,7 @@ public class BasalProfileUTest {
Assert.assertTrue(MedtronicUtil.isSame(0.5d, profilesByHour[23])); Assert.assertTrue(MedtronicUtil.isSame(0.5d, profilesByHour[23]));
System.out.println("Basals by hour: " System.out.println("Basals by hour: "
+ (profilesByHour == null ? "null" : BasalProfile.getProfilesByHourToString(profilesByHour))); + (profilesByHour == null ? "null" : BasalProfile.getProfilesByHourToString(profilesByHour)));
} }
@ -99,17 +93,17 @@ public class BasalProfileUTest {
public void testProfileByDay2() { public void testProfileByDay2() {
BasalProfile basalProfile = new BasalProfile(); BasalProfile basalProfile = new BasalProfile();
byte[] data = { // byte[] data = { //
0x32, 0x00, 0x00, 0x2C, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 0x32, 0x00, 0x00, 0x2C, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
basalProfile.setRawData(data); basalProfile.setRawData(data);
Double[] profilesByHour = basalProfile.getProfilesByHour(); Double[] profilesByHour = basalProfile.getProfilesByHour();
System.out.println("Basals by hour: " System.out.println("Basals by hour: "
+ (profilesByHour == null ? "null" : BasalProfile.getProfilesByHourToString(profilesByHour))); + (profilesByHour == null ? "null" : BasalProfile.getProfilesByHourToString(profilesByHour)));
} }
@ -118,14 +112,14 @@ public class BasalProfileUTest {
public void testProfileByDayZero() { public void testProfileByDayZero() {
BasalProfile basalProfile = new BasalProfile(); BasalProfile basalProfile = new BasalProfile();
byte[] data = { // byte[] data = { //
0x00 }; 0x00};
basalProfile.setRawData(data); basalProfile.setRawData(data);
Double[] profilesByHour = basalProfile.getProfilesByHour(); Double[] profilesByHour = basalProfile.getProfilesByHour();
System.out.println("Basals by hour: " System.out.println("Basals by hour: "
+ (profilesByHour == null ? "null" : BasalProfile.getProfilesByHourToString(profilesByHour))); + (profilesByHour == null ? "null" : BasalProfile.getProfilesByHourToString(profilesByHour)));
} }
@ -134,14 +128,14 @@ public class BasalProfileUTest {
public void testProfileByDayZeroZero3F() { public void testProfileByDayZeroZero3F() {
BasalProfile basalProfile = new BasalProfile(); BasalProfile basalProfile = new BasalProfile();
byte[] data = { // byte[] data = { //
0x00, 0x00, 0x3f }; 0x00, 0x00, 0x3f};
basalProfile.setRawData(data); basalProfile.setRawData(data);
Double[] profilesByHour = basalProfile.getProfilesByHour(); Double[] profilesByHour = basalProfile.getProfilesByHour();
System.out.println("Basals by hour: " System.out.println("Basals by hour: "
+ (profilesByHour == null ? "null" : BasalProfile.getProfilesByHourToString(profilesByHour))); + (profilesByHour == null ? "null" : BasalProfile.getProfilesByHourToString(profilesByHour)));
} }
@ -152,11 +146,11 @@ public class BasalProfileUTest {
MedtronicUtil.getPumpStatus().pumpType = PumpType.Medtronic_522_722; MedtronicUtil.getPumpStatus().pumpType = PumpType.Medtronic_522_722;
byte[] data = { byte[] data = {
0, 72, 0, 2, 64, 0, 4, 56, 0, 6, 58, 0, 8, 58, 0, 10, 58, 0, 12, 50, 0, 14, 50, 0, 16, 38, 0, 18, 38, 0, 0, 72, 0, 2, 64, 0, 4, 56, 0, 6, 58, 0, 8, 58, 0, 10, 58, 0, 12, 50, 0, 14, 50, 0, 16, 38, 0, 18, 38, 0,
20, 46, 0, 22, 46, 0, 24, 50, 0, 26, 38, 0, 28, 38, 0, 30, 38, 0, 32, 26, 0, 34, 26, 0, 36, 26, 0, 38, 26, 20, 46, 0, 22, 46, 0, 24, 50, 0, 26, 38, 0, 28, 38, 0, 30, 38, 0, 32, 26, 0, 34, 26, 0, 36, 26, 0, 38, 26,
0, 40, 26, 0, 42, 20, 0, 44, 20, 0, 46, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 40, 26, 0, 42, 20, 0, 44, 20, 0, 46, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
BasalProfile basalProfile = new BasalProfile(); BasalProfile basalProfile = new BasalProfile();
basalProfile.setRawDataFromHistory(data); basalProfile.setRawDataFromHistory(data);
@ -164,7 +158,7 @@ public class BasalProfileUTest {
Double[] profilesByHour = basalProfile.getProfilesByHour(); Double[] profilesByHour = basalProfile.getProfilesByHour();
System.out.println("Basals by hour: " System.out.println("Basals by hour: "
+ (profilesByHour == null ? "null" : BasalProfile.getProfilesByHourToString(profilesByHour))); + (profilesByHour == null ? "null" : BasalProfile.getProfilesByHourToString(profilesByHour)));
// 1.800 1.600 1.400 1.450 1.450 1.450 1.250 1.250 0.950 0.950 1.150 1.150 1.250 0.950 0.950 0.950 0.650 0.650 // 1.800 1.600 1.400 1.450 1.450 1.450 1.250 1.250 0.950 0.950 1.150 1.150 1.250 0.950 0.950 0.950 0.650 0.650
// 0.650 0.650 0.650 0.500 0.500 0.500 // 0.650 0.650 0.650 0.500 0.500 0.500