Merge remote-tracking branch 'origin/dev' into rs

This commit is contained in:
Milos Kozak 2020-04-24 23:03:46 +02:00
commit 29f71f283d
59 changed files with 808 additions and 935 deletions

View file

@ -8,7 +8,6 @@ import com.j256.ormlite.table.DatabaseTable;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.Collections;
@ -18,16 +17,18 @@ import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction;
import info.nightscout.androidaps.plugins.general.nsclient.data.NSMbg;
import info.nightscout.androidaps.plugins.general.overview.OverviewFragment;
import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface;
import info.nightscout.androidaps.plugins.general.overview.graphExtensions.PointsWithLabelGraphSeries;
import info.nightscout.androidaps.utils.DateUtil;
@ -37,7 +38,10 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_CAREPORTALEVENTS)
public class CareportalEvent implements DataPointWithLabelInterface, Interval {
private static Logger log = StacktraceLoggerWrapper.getLogger(L.DATABASE);
@Inject ProfileFunction profileFunction;
@Inject ResourceHelper resourceHelper;
@Inject AAPSLogger aapsLogger;
@DatabaseField(id = true)
public long date;
@ -77,7 +81,13 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval {
public static final String MBG = "Mbg"; // comming from entries
@Deprecated
public CareportalEvent() {
MainApp.instance().androidInjector().inject(this);
}
public CareportalEvent(HasAndroidInjector injector) {
injector.androidInjector().inject(this);
}
public CareportalEvent(NSMbg mbg) {
@ -90,7 +100,7 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval {
return System.currentTimeMillis() - date;
}
public double getHoursFromStart() {
private double getHoursFromStart() {
return (System.currentTimeMillis() - date) / (60 * 60 * 1000.0);
}
@ -125,11 +135,11 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval {
}
//Map:{DAYS=1, HOURS=3, MINUTES=46, SECONDS=40, MILLISECONDS=0, MICROSECONDS=0, NANOSECONDS=0}
public static Map<TimeUnit, Long> computeDiff(long date1, long date2) {
private static Map<TimeUnit, Long> computeDiff(long date1, long date2) {
long diffInMillies = date2 - date1;
List<TimeUnit> units = new ArrayList<TimeUnit>(EnumSet.allOf(TimeUnit.class));
List<TimeUnit> units = new ArrayList<>(EnumSet.allOf(TimeUnit.class));
Collections.reverse(units);
Map<TimeUnit, Long> result = new LinkedHashMap<TimeUnit, Long>();
Map<TimeUnit, Long> result = new LinkedHashMap<>();
long milliesRest = diffInMillies;
for (TimeUnit unit : units) {
long diff = unit.convert(milliesRest, TimeUnit.MILLISECONDS);
@ -141,12 +151,12 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval {
}
public static boolean isEvent5minBack(List<CareportalEvent> list, long time) {
public boolean isEvent5minBack(List<CareportalEvent> list, long time) {
for (int i = 0; i < list.size(); i++) {
CareportalEvent event = list.get(i);
if (event.date <= time && event.date > (time - T.mins(5).msecs())) {
if (L.isEnabled(L.DATABASE))
log.debug("Found event for time: " + DateUtil.dateAndTimeString(time) + " " + event.toString());
aapsLogger.debug("Found event for time: " + DateUtil.dateAndTimeString(time) + " " + event.toString());
return true;
}
}
@ -160,18 +170,18 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval {
return date;
}
double yValue = 0;
private double yValue = 0;
@Override
public double getY() {
String units = ConfigBuilderPlugin.getPlugin().getProfileFunction().getUnits();
String units = profileFunction.getUnits();
if (eventType.equals(MBG)) {
double mbg = 0d;
try {
JSONObject object = new JSONObject(json);
mbg = object.getDouble("mgdl");
} catch (JSONException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
return Profile.fromMgdlToUnits(mbg, units);
}
@ -184,7 +194,7 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval {
units = object.getString("units");
}
} catch (JSONException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
if (glucose != 0d) {
double mmol = 0d;
@ -215,7 +225,7 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval {
if (object.has("notes"))
return StringUtils.abbreviate(object.getString("notes"), 40);
} catch (JSONException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
return Translator.translate(eventType);
}
@ -226,7 +236,7 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval {
if (object.has("notes"))
return object.getString("notes");
} catch (JSONException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
return "";
}
@ -257,14 +267,14 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval {
@Override
public float getSize() {
boolean isTablet = MainApp.resources().getBoolean(R.bool.isTablet);
boolean isTablet = resourceHelper.gb(R.bool.isTablet);
return isTablet ? 12 : 10;
}
@Override
public int getColor() {
if (eventType.equals(ANNOUNCEMENT))
return MainApp.gc(R.color.notificationAnnouncement);
return resourceHelper.gc(R.color.notificationAnnouncement);
if (eventType.equals(MBG))
return Color.RED;
if (eventType.equals(BGCHECK))
@ -277,7 +287,7 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval {
}
// Interval interface
Long cuttedEnd = null;
private Long cuttedEnd = null;
@Override
public long durationInMsec() {
@ -286,7 +296,7 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval {
if (object.has("duration"))
return object.getInt("duration") * 60 * 1000L;
} catch (JSONException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
return 0;
}

View file

@ -7,6 +7,10 @@ import org.slf4j.Logger;
import java.util.Objects;
import javax.inject.Inject;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Iob;
import info.nightscout.androidaps.data.IobTotal;
@ -15,8 +19,8 @@ import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.PluginStore;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult;
import info.nightscout.androidaps.plugins.treatments.Treatment;
import info.nightscout.androidaps.utils.DateUtil;
@ -31,6 +35,9 @@ import info.nightscout.androidaps.utils.SP;
public class TemporaryBasal implements Interval, DbObjectBase {
private static Logger log = StacktraceLoggerWrapper.getLogger(L.DATABASE);
@Inject public ProfileFunction profileFunction;
private HasAndroidInjector injector;
@DatabaseField(id = true)
public long date;
@ -59,7 +66,15 @@ public class TemporaryBasal implements Interval, DbObjectBase {
public double netExtendedRate = 0d;
@Deprecated
public TemporaryBasal() {
injector = MainApp.instance();
injector.androidInjector().inject(this);
}
public TemporaryBasal(HasAndroidInjector injector) {
this.injector = injector;
injector.androidInjector().inject(this);
}
public TemporaryBasal date(long date) {
@ -95,7 +110,7 @@ public class TemporaryBasal implements Interval, DbObjectBase {
}
public TemporaryBasal(ExtendedBolus extendedBolus) {
double basal = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile(extendedBolus.date).getBasal(extendedBolus.date);
double basal = profileFunction.getProfile(extendedBolus.date).getBasal(extendedBolus.date);
this.date = extendedBolus.date;
this.isValid = extendedBolus.isValid;
this.source = extendedBolus.source;
@ -109,7 +124,7 @@ public class TemporaryBasal implements Interval, DbObjectBase {
}
public TemporaryBasal clone() {
TemporaryBasal t = new TemporaryBasal();
TemporaryBasal t = new TemporaryBasal(injector);
t.date = date;
t.isValid = isValid;
t.source = source;
@ -404,7 +419,7 @@ public class TemporaryBasal implements Interval, DbObjectBase {
public String toStringFull() {
if (isFakeExtended) {
Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile();
Profile profile = profileFunction.getProfile();
if (profile == null)
return "null";
Double currentBasalRate = profile.getBasal();
@ -428,7 +443,7 @@ public class TemporaryBasal implements Interval, DbObjectBase {
double rate;
if (isFakeExtended) {
Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile();
Profile profile = profileFunction.getProfile();
if (profile == null)
return "null";
double currentBasalRate = profile.getBasal();
@ -438,7 +453,7 @@ public class TemporaryBasal implements Interval, DbObjectBase {
}
if (SP.getBoolean(R.string.key_danar_visualizeextendedaspercentage, false) && SP.getBoolean(R.string.key_danar_useextended, false)) {
Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile();
Profile profile = profileFunction.getProfile();
if (profile != null) {
double basal = profile.getBasal();
if (basal != 0) {
@ -453,7 +468,7 @@ public class TemporaryBasal implements Interval, DbObjectBase {
}
private String getCalcuatedPercentageIfNeeded() {
Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile();
Profile profile = profileFunction.getProfile();
if (profile == null)
return "null";
@ -479,7 +494,7 @@ public class TemporaryBasal implements Interval, DbObjectBase {
}
public String toStringVeryShort() {
Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile();
Profile profile = profileFunction.getProfile();
if (profile == null)
return "null";

View file

@ -9,10 +9,12 @@ import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.data.ProfileStore
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.db.BgReading
import info.nightscout.androidaps.db.CareportalEvent
import info.nightscout.androidaps.db.ProfileSwitch
import info.nightscout.androidaps.db.TemporaryBasal
import info.nightscout.androidaps.plugins.aps.logger.LoggerCallback
import info.nightscout.androidaps.plugins.aps.loop.APSResult
import info.nightscout.androidaps.plugins.aps.openAPSAMA.DetermineBasalResultAMA
import info.nightscout.androidaps.plugins.aps.logger.LoggerCallback
import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalAdapterSMBJS
import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalResultSMB
import info.nightscout.androidaps.plugins.constraints.objectives.objectives.*
@ -152,6 +154,8 @@ interface AppComponent : AndroidInjector<MainApp> {
fun injectTreatment(treatment: Treatment)
fun injectBgReading(bgReading: BgReading)
fun injectProfileSwitch(profileSwitch: ProfileSwitch)
fun injectTemporaryBasal(temporaryBasal: TemporaryBasal)
fun injectCareportalEvent(careportalEvent: CareportalEvent)
fun injectNotification(notificationWithAction: NotificationWithAction)

View file

@ -14,7 +14,9 @@ import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.data.ProfileStore
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.db.BgReading
import info.nightscout.androidaps.db.CareportalEvent
import info.nightscout.androidaps.db.ProfileSwitch
import info.nightscout.androidaps.db.TemporaryBasal
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.interfaces.PluginBase
@ -37,6 +39,7 @@ import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData
import info.nightscout.androidaps.plugins.general.maintenance.ImportExportPrefs
import info.nightscout.androidaps.plugins.general.maintenance.formats.ClassicPrefsFormat
import info.nightscout.androidaps.plugins.general.maintenance.formats.EncryptedPrefsFormat
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationWithAction
import info.nightscout.androidaps.plugins.general.smsCommunicator.AuthRequest
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData
@ -98,11 +101,14 @@ open class AppModule {
fun providesPlugins(@PluginsModule.AllConfigs allConfigs: Map<@JvmSuppressWildcards Int, @JvmSuppressWildcards PluginBase>,
@PluginsModule.PumpDriver pumpDrivers: Lazy<Map<@JvmSuppressWildcards Int, @JvmSuppressWildcards PluginBase>>,
@PluginsModule.NotNSClient notNsClient: Lazy<Map<@JvmSuppressWildcards Int, @JvmSuppressWildcards PluginBase>>,
@PluginsModule.APS aps: Lazy<Map<@JvmSuppressWildcards Int, @JvmSuppressWildcards PluginBase>>): List<@JvmSuppressWildcards PluginBase> {
@PluginsModule.NSClient nsClient: Lazy<Map<@JvmSuppressWildcards Int, @JvmSuppressWildcards PluginBase>>,
@PluginsModule.APS aps: Lazy<Map<@JvmSuppressWildcards Int, @JvmSuppressWildcards PluginBase>>)
: List<@JvmSuppressWildcards PluginBase> {
val plugins = allConfigs.toMutableMap()
if (Config.PUMPDRIVERS) plugins += pumpDrivers.get()
if (Config.APS) plugins += aps.get()
if (!Config.NSCLIENT) plugins += notNsClient.get()
if (Config.NSCLIENT) plugins += nsClient.get()
return plugins.toList().sortedBy { it.first }.map { it.second }
}
@ -233,6 +239,8 @@ open class AppModule {
@ContributesAndroidInjector fun bgReadingInjector(): BgReading
@ContributesAndroidInjector fun treatmentInjector(): Treatment
@ContributesAndroidInjector fun profileSwitchInjector(): ProfileSwitch
@ContributesAndroidInjector fun temporaryBasalInjector(): TemporaryBasal
@ContributesAndroidInjector fun careportalEventInjector(): CareportalEvent
@ContributesAndroidInjector fun notificationWithActionInjector(): NotificationWithAction

View file

@ -165,7 +165,7 @@ abstract class PluginsModule {
abstract fun bindVirtualPumpPlugin(plugin: VirtualPumpPlugin): PluginBase
@Binds
@NotNSClient
@NSClient
@IntoMap
@IntKey(180)
abstract fun bindCareportalPlugin(plugin: CareportalPlugin): PluginBase
@ -213,7 +213,7 @@ abstract class PluginsModule {
abstract fun bindTreatmentsPlugin(plugin: TreatmentsPlugin): PluginBase
@Binds
@NotNSClient
@AllConfigs
@IntoSet
abstract fun bindSafetyPlugin(plugin: SafetyPlugin): PluginBase
@ -359,6 +359,9 @@ abstract class PluginsModule {
@Qualifier
annotation class NotNSClient
@Qualifier
annotation class NSClient
@Qualifier
annotation class APS

View file

@ -183,7 +183,7 @@ class CareDialog : DialogFragmentWithDate() {
activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(event), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), Runnable {
val careportalEvent = CareportalEvent()
val careportalEvent = CareportalEvent(injector)
careportalEvent.date = eventTime
careportalEvent.source = Source.USER
careportalEvent.eventType = when (options) {

View file

@ -7,6 +7,7 @@ import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.common.base.Joiner
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.ErrorHelperActivity
@ -22,8 +23,8 @@ import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.DecimalFormatter
import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.SafeParse
import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import kotlinx.android.synthetic.main.dialog_fill.*
@ -41,6 +42,7 @@ class FillDialog : DialogFragmentWithDate() {
@Inject lateinit var ctx: Context
@Inject lateinit var commandQueue: CommandQueueProvider
@Inject lateinit var activePlugin: ActivePluginProvider
@Inject lateinit var injector: HasAndroidInjector
override fun onSaveInstanceState(savedInstanceState: Bundle) {
super.onSaveInstanceState(savedInstanceState)
@ -122,12 +124,12 @@ class FillDialog : DialogFragmentWithDate() {
}
if (siteChange) {
aapsLogger.debug("USER ENTRY: SITE CHANGE")
generateCareportalEvent(CareportalEvent.SITECHANGE, eventTime, notes, resourceHelper, sp)
generateCareportalEvent(CareportalEvent.SITECHANGE, eventTime, notes, resourceHelper, sp, injector)
}
if (insulinChange) {
// add a second for case of both checked
aapsLogger.debug("USER ENTRY: INSULIN CHANGE")
generateCareportalEvent(CareportalEvent.INSULINCHANGE, eventTime + 1000, notes, resourceHelper, sp)
generateCareportalEvent(CareportalEvent.INSULINCHANGE, eventTime + 1000, notes, resourceHelper, sp, injector)
}
}, null)
}
@ -162,8 +164,8 @@ class FillDialog : DialogFragmentWithDate() {
}
companion object {
fun generateCareportalEvent(eventType: String, time: Long, notes: String, resourceHelper: ResourceHelper, sp: SP) {
val careportalEvent = CareportalEvent()
fun generateCareportalEvent(eventType: String, time: Long, notes: String, resourceHelper: ResourceHelper, sp: SP, injector: HasAndroidInjector) {
val careportalEvent = CareportalEvent(injector)
careportalEvent.source = Source.USER
careportalEvent.date = time
careportalEvent.json = generateJson(eventType, time, notes, resourceHelper, sp).toString()

View file

@ -1,6 +1,7 @@
package info.nightscout.androidaps.events
class EventBTChange constructor(val state: Change, val deviceName: String) : Event() {
class EventBTChange(val state: Change, val deviceName: String?, val deviceAddress: String? = null) : Event() {
enum class Change {
CONNECT,
DISCONNECT

View file

@ -1,378 +0,0 @@
package info.nightscout.androidaps.historyBrowser;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import androidx.appcompat.widget.PopupMenu;
import androidx.core.content.res.ResourcesCompat;
import com.jjoe64.graphview.GraphView;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import java.util.Calendar;
import java.util.Date;
import javax.inject.Inject;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.activities.NoSplashAppCompatActivity;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.events.EventCustomCalculationFinished;
import info.nightscout.androidaps.events.EventRefreshOverview;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction;
import info.nightscout.androidaps.plugins.general.overview.OverviewFragment;
import info.nightscout.androidaps.plugins.general.overview.OverviewMenus;
import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.DefaultValueHelper;
import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.T;
import info.nightscout.androidaps.utils.buildHelper.BuildHelper;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
public class HistoryBrowseActivity extends NoSplashAppCompatActivity {
@Inject HasAndroidInjector injector;
@Inject AAPSLogger aapsLogger;
@Inject RxBusWrapper rxBus;
@Inject SP sp;
@Inject ResourceHelper resourceHelper;
@Inject ProfileFunction profileFunction;
@Inject DefaultValueHelper defaultValueHelper;
@Inject IobCobStaticCalculatorPlugin iobCobStaticCalculatorPlugin;
@Inject ActivePluginProvider activePlugin;
@Inject BuildHelper buildHelper;
@Inject FabricPrivacy fabricPrivacy;
@Inject OverviewMenus overviewMenus;
private CompositeDisposable disposable = new CompositeDisposable();
ImageButton chartButton;
boolean showBasal = true;
boolean showIob, showCob, showDev, showRat, showActPrim, showActSec, showDevslope;
Button buttonDate;
Button buttonZoom;
GraphView bgGraph;
GraphView iobGraph;
SeekBar seekBar;
TextView noProfile;
TextView iobCalculationProgressView;
private int rangeToDisplay = 24; // for graph
private long start = 0;
EventCustomCalculationFinished eventCustomCalculationFinished = new EventCustomCalculationFinished();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_historybrowse);
buttonDate = findViewById(R.id.historybrowse_date);
buttonZoom = findViewById(R.id.historybrowse_zoom);
bgGraph = findViewById(R.id.historyybrowse_bggraph);
iobGraph = findViewById(R.id.historybrowse_iobgraph);
seekBar = findViewById(R.id.historybrowse_seekBar);
noProfile = findViewById(R.id.historybrowse_noprofile);
iobCalculationProgressView = findViewById(R.id.overview_iobcalculationprogess);
findViewById(R.id.historybrowse_left).setOnClickListener(v -> {
start -= T.hours(rangeToDisplay).msecs();
updateGUI("onClickLeft");
runCalculation("onClickLeft");
});
findViewById(R.id.historybrowse_right).setOnClickListener(v -> {
start += T.hours(rangeToDisplay).msecs();
updateGUI("onClickRight");
runCalculation("onClickRight");
});
findViewById(R.id.historybrowse_end).setOnClickListener(v -> {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR_OF_DAY, 0);
start = calendar.getTimeInMillis();
updateGUI("onClickEnd");
runCalculation("onClickEnd");
});
findViewById(R.id.historybrowse_zoom).setOnClickListener(v -> {
rangeToDisplay += 6;
rangeToDisplay = rangeToDisplay > 24 ? 6 : rangeToDisplay;
updateGUI("rangeChange");
});
findViewById(R.id.historybrowse_zoom).setOnLongClickListener(v -> {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(start);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR_OF_DAY, 0);
start = calendar.getTimeInMillis();
updateGUI("resetToMidnight");
runCalculation("onLongClickZoom");
return true;
});
findViewById(R.id.historybrowse_date).setOnClickListener(v -> {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date(start));
DatePickerDialog dpd = DatePickerDialog.newInstance(
(view, year, monthOfYear, dayOfMonth) -> {
Date date = new Date(0);
date.setYear(year - 1900);
date.setMonth(monthOfYear);
date.setDate(dayOfMonth);
date.setHours(0);
start = date.getTime();
updateGUI("onClickDate");
runCalculation("onClickDate");
},
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH)
);
dpd.setThemeDark(true);
dpd.dismissOnPause(true);
dpd.show(getSupportFragmentManager(), "Datepickerdialog");
});
bgGraph.getGridLabelRenderer().setGridColor(resourceHelper.gc(R.color.graphgrid));
bgGraph.getGridLabelRenderer().reloadStyles();
iobGraph.getGridLabelRenderer().setGridColor(resourceHelper.gc(R.color.graphgrid));
iobGraph.getGridLabelRenderer().reloadStyles();
iobGraph.getGridLabelRenderer().setHorizontalLabelsVisible(false);
bgGraph.getGridLabelRenderer().setLabelVerticalWidth(50);
iobGraph.getGridLabelRenderer().setLabelVerticalWidth(50);
iobGraph.getGridLabelRenderer().setNumVerticalLabels(5);
overviewMenus.setupChartMenu(findViewById(R.id.overview_chartMenuButton));
}
@Override
public void onPause() {
super.onPause();
disposable.clear();
iobCobStaticCalculatorPlugin.stopCalculation("onPause");
}
@Override
public void onResume() {
super.onResume();
disposable.add(rxBus
.toObservable(EventAutosensCalculationFinished.class)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(event -> {
if (event.getCause() == eventCustomCalculationFinished) {
aapsLogger.debug(LTag.AUTOSENS, "EventAutosensCalculationFinished");
synchronized (HistoryBrowseActivity.this) {
updateGUI("EventAutosensCalculationFinished");
}
}
}, fabricPrivacy::logException)
);
disposable.add(rxBus
.toObservable(EventIobCalculationProgress.class)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(event -> {
if (iobCalculationProgressView != null)
iobCalculationProgressView.setText(event.getProgress());
}, exception -> fabricPrivacy.logException(exception))
);
disposable.add(rxBus
.toObservable(EventRefreshOverview.class)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(event -> updateGUI("EventRefreshOverview") , fabricPrivacy::logException)
);
// set start of current day
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR_OF_DAY, 0);
start = calendar.getTimeInMillis();
runCalculation("onResume");
SystemClock.sleep(1000);
updateGUI("onResume");
}
private void runCalculation(String from) {
long end = start + T.hours(rangeToDisplay).msecs();
iobCobStaticCalculatorPlugin.stopCalculation(from);
iobCobStaticCalculatorPlugin.clearCache();
iobCobStaticCalculatorPlugin.runCalculation(from, end, true, false, eventCustomCalculationFinished);
}
void updateGUI(String from) {
aapsLogger.debug(LTag.UI, "updateGUI from: " + from);
if (noProfile == null || buttonDate == null || buttonZoom == null || bgGraph == null || iobGraph == null || seekBar == null)
return;
final PumpInterface pump = activePlugin.getActivePump();
final Profile profile = profileFunction.getProfile();
if (profile == null) {
noProfile.setVisibility(View.VISIBLE);
return;
} else {
noProfile.setVisibility(View.GONE);
}
final double lowLine = defaultValueHelper.determineLowLine();
final double highLine = defaultValueHelper.determineHighLine();
buttonDate.setText(DateUtil.dateAndTimeString(start));
buttonZoom.setText(String.valueOf(rangeToDisplay));
final boolean showPrediction = false;
showBasal = sp.getBoolean("hist_showbasals", true);
showIob = sp.getBoolean("hist_showiob", true);
showCob = sp.getBoolean("hist_showcob", true);
showDev = sp.getBoolean("hist_showdeviations", false);
showRat = sp.getBoolean("hist_showratios", false);
showActPrim = sp.getBoolean("hist_showactivityprimary", false);
showActSec = sp.getBoolean("hist_showactivitysecondary", false);
showDevslope = sp.getBoolean("hist_showdevslope", false);
//int hoursToFetch;
final long toTime;
final long fromTime;
//if (showPrediction) {
//int predHours = (int) (Math.ceil(((DetermineBasalResultAMA) finalLastRun.constraintsProcessed).getLatestPredictionsTime() - System.currentTimeMillis()) / (60 * 60 * 1000));
//predHours = Math.min(2, predHours);
//predHours = Math.max(0, predHours);
//hoursToFetch = rangeToDisplay - predHours;
//toTime = calendar.getTimeInMillis() + 100000; // little bit more to avoid wrong rounding - Graphview specific
//fromTime = toTime - hoursToFetch * 60 * 60 * 1000L;
//endTime = toTime + predHours * 60 * 60 * 1000L;
//} else {
fromTime = start + T.secs(100).msecs();
toTime = start + T.hours(rangeToDisplay).msecs();
//}
aapsLogger.debug(LTag.UI, "Period: " + DateUtil.dateAndTimeString(fromTime) + " - " + DateUtil.dateAndTimeString(toTime));
final long pointer = System.currentTimeMillis();
// ------------------ 1st graph
final GraphData graphData = new GraphData(injector, bgGraph, iobCobStaticCalculatorPlugin);
// **** In range Area ****
graphData.addInRangeArea(fromTime, toTime, lowLine, highLine);
// **** BG ****
if (showPrediction)
//graphData.addBgReadings(fromTime, toTime, lowLine, highLine, (DetermineBasalResultAMA) finalLastRun.constraintsProcessed);
;
else
graphData.addBgReadings(fromTime, toTime, lowLine, highLine, null);
// set manual x bounds to have nice steps
graphData.formatAxis(fromTime, toTime);
if (showActPrim) {
graphData.addActivity(fromTime, toTime, false, 1d);
}
// Treatments
graphData.addTreatments(fromTime, toTime);
// add basal data
if (pump.getPumpDescription().isTempBasalCapable && showBasal) {
graphData.addBasals(fromTime, toTime, lowLine / graphData.getMaxY() / 1.2d);
}
// **** NOW line ****
graphData.addNowLine(pointer);
// ------------------ 2nd graph
new Thread(() -> {
final GraphData secondGraphData = new GraphData(injector, iobGraph, iobCobStaticCalculatorPlugin);
boolean useIobForScale = false;
boolean useCobForScale = false;
boolean useDevForScale = false;
boolean useRatioForScale = false;
boolean useIAForScale = false;
boolean useDSForScale = false;
if (showIob) {
useIobForScale = true;
} else if (showCob) {
useCobForScale = true;
} else if (showDev) {
useDevForScale = true;
} else if (showRat) {
useRatioForScale = true;
} else if (showActSec) {
useIAForScale = true;
} else if (showDevslope) {
useDSForScale = true;
}
if (showIob)
secondGraphData.addIob(fromTime, toTime, useIobForScale, 1d, showPrediction);
if (showCob)
secondGraphData.addCob(fromTime, toTime, useCobForScale, useCobForScale ? 1d : 0.5d);
if (showDev)
secondGraphData.addDeviations(fromTime, toTime, useDevForScale, 1d);
if (showRat)
secondGraphData.addRatio(fromTime, toTime, useRatioForScale, 1d);
if (showActSec)
secondGraphData.addActivity(fromTime, toTime, useIAForScale, useIAForScale ? 2d : 1d);
if (showDevslope)
secondGraphData.addDeviationSlope(fromTime, toTime, useDSForScale, 1d);
// **** NOW line ****
// set manual x bounds to have nice steps
secondGraphData.formatAxis(fromTime, toTime);
secondGraphData.addNowLine(pointer);
// do GUI update
runOnUiThread(() -> {
if (showIob || showCob || showDev || showRat || showActSec || showDevslope) {
iobGraph.setVisibility(View.VISIBLE);
} else {
iobGraph.setVisibility(View.GONE);
}
// finally enforce drawing of graphs
graphData.performUpdate();
if (showIob || showCob || showDev || showRat || showActSec || showDevslope)
secondGraphData.performUpdate();
});
}).start();
}
}

View file

@ -0,0 +1,330 @@
package info.nightscout.androidaps.historyBrowser
import android.app.DatePickerDialog
import android.graphics.Color
import android.os.Bundle
import android.os.SystemClock
import android.util.DisplayMetrics
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import com.jjoe64.graphview.GraphView
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.NoSplashAppCompatActivity
import info.nightscout.androidaps.events.EventCustomCalculationFinished
import info.nightscout.androidaps.events.EventRefreshOverview
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction
import info.nightscout.androidaps.plugins.general.overview.OverviewMenus
import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.DefaultValueHelper
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.buildHelper.BuildHelper
import info.nightscout.androidaps.utils.extensions.toVisibility
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.activity_historybrowse.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.*
import javax.inject.Inject
class HistoryBrowseActivity : NoSplashAppCompatActivity() {
@Inject lateinit var injector: HasAndroidInjector
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var sp: SP
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var defaultValueHelper: DefaultValueHelper
@Inject lateinit var iobCobStaticCalculatorPlugin: IobCobStaticCalculatorPlugin
@Inject lateinit var activePlugin: ActivePluginProvider
@Inject lateinit var buildHelper: BuildHelper
@Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var overviewMenus: OverviewMenus
private val disposable = CompositeDisposable()
private val secondaryGraphs = ArrayList<GraphView>()
private val secondaryGraphsLabel = ArrayList<TextView>()
private var axisWidth: Int = 0
private var rangeToDisplay = 24 // for graph
private var start: Long = 0
private var eventCustomCalculationFinished = EventCustomCalculationFinished()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_historybrowse)
historybrowse_left.setOnClickListener {
start -= T.hours(rangeToDisplay.toLong()).msecs()
updateGUI("onClickLeft")
runCalculation("onClickLeft")
}
historybrowse_right.setOnClickListener {
start += T.hours(rangeToDisplay.toLong()).msecs()
updateGUI("onClickRight")
runCalculation("onClickRight")
}
historybrowse_end.setOnClickListener {
val calendar = Calendar.getInstance()
calendar.timeInMillis = System.currentTimeMillis()
calendar[Calendar.MILLISECOND] = 0
calendar[Calendar.SECOND] = 0
calendar[Calendar.MINUTE] = 0
calendar[Calendar.HOUR_OF_DAY] = 0
start = calendar.timeInMillis
updateGUI("onClickEnd")
runCalculation("onClickEnd")
}
historybrowse_zoom.setOnClickListener {
rangeToDisplay += 6
rangeToDisplay = if (rangeToDisplay > 24) 6 else rangeToDisplay
updateGUI("rangeChange")
}
historybrowse_zoom.setOnLongClickListener {
val calendar = Calendar.getInstance()
calendar.timeInMillis = start
calendar[Calendar.MILLISECOND] = 0
calendar[Calendar.SECOND] = 0
calendar[Calendar.MINUTE] = 0
calendar[Calendar.HOUR_OF_DAY] = 0
start = calendar.timeInMillis
updateGUI("resetToMidnight")
runCalculation("onLongClickZoom")
true
}
// create an OnDateSetListener
val dateSetListener = DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth ->
val cal = Calendar.getInstance()
cal.timeInMillis = start
cal.set(Calendar.YEAR, year)
cal.set(Calendar.MONTH, monthOfYear)
cal.set(Calendar.DAY_OF_MONTH, dayOfMonth)
start = cal.timeInMillis
historybrowse_date?.text = DateUtil.dateAndTimeString(start)
updateGUI("onClickDate")
runCalculation("onClickDate")
}
historybrowse_date.setOnClickListener {
val cal = Calendar.getInstance()
cal.timeInMillis = start
DatePickerDialog(this, dateSetListener,
cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH)
).show()
}
val dm = DisplayMetrics()
windowManager?.defaultDisplay?.getMetrics(dm)
axisWidth = if (dm.densityDpi <= 120) 3 else if (dm.densityDpi <= 160) 10 else if (dm.densityDpi <= 320) 35 else if (dm.densityDpi <= 420) 50 else if (dm.densityDpi <= 560) 70 else 80
historybrowse_bggraph?.gridLabelRenderer?.gridColor = resourceHelper.gc(R.color.graphgrid)
historybrowse_bggraph?.gridLabelRenderer?.reloadStyles()
historybrowse_bggraph?.gridLabelRenderer?.labelVerticalWidth = axisWidth
overviewMenus.setupChartMenu(overview_chartMenuButton)
prepareGraphs()
}
public override fun onPause() {
super.onPause()
disposable.clear()
iobCobStaticCalculatorPlugin.stopCalculation("onPause")
}
public override fun onResume() {
super.onResume()
disposable.add(rxBus
.toObservable(EventAutosensCalculationFinished::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ event: EventAutosensCalculationFinished ->
// catch only events from iobCobStaticCalculatorPlugin
if (event.cause === eventCustomCalculationFinished) {
aapsLogger.debug(LTag.AUTOSENS, "EventAutosensCalculationFinished")
updateGUI("EventAutosensCalculationFinished")
}
}) { fabricPrivacy::logException }
)
disposable.add(rxBus
.toObservable(EventIobCalculationProgress::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ overview_iobcalculationprogess?.text = it.progress }) { fabricPrivacy::logException }
)
disposable.add(rxBus
.toObservable(EventRefreshOverview::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
prepareGraphs()
updateGUI("EventRefreshOverview")
}) { fabricPrivacy::logException }
)
// set start of current day
val calendar = Calendar.getInstance()
calendar.timeInMillis = System.currentTimeMillis()
calendar[Calendar.MILLISECOND] = 0
calendar[Calendar.SECOND] = 0
calendar[Calendar.MINUTE] = 0
calendar[Calendar.HOUR_OF_DAY] = 0
start = calendar.timeInMillis
runCalculation("onResume")
SystemClock.sleep(1000)
updateGUI("onResume")
}
private fun prepareGraphs() {
val numOfGraphs = overviewMenus.setting.size
if (numOfGraphs != secondaryGraphs.size - 1) {
//aapsLogger.debug("New secondary graph count ${numOfGraphs-1}")
// rebuild needed
secondaryGraphs.clear()
secondaryGraphsLabel.clear()
history_iobgraph.removeAllViews()
for (i in 1 until numOfGraphs) {
val label = TextView(this)
label.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).also { it.setMargins(100, 0, 0, -50) }
history_iobgraph.addView(label)
secondaryGraphsLabel.add(label)
val graph = GraphView(this)
graph.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, resourceHelper.dpToPx(100)).also { it.setMargins(0, 0, 0, resourceHelper.dpToPx(10)) }
graph.gridLabelRenderer?.gridColor = resourceHelper.gc(R.color.graphgrid)
graph.gridLabelRenderer?.reloadStyles()
graph.gridLabelRenderer?.isHorizontalLabelsVisible = false
graph.gridLabelRenderer?.labelVerticalWidth = axisWidth
graph.gridLabelRenderer?.numVerticalLabels = 3
graph.viewport.backgroundColor = Color.argb(20, 255, 255, 255) // 8% of gray
history_iobgraph.addView(graph)
secondaryGraphs.add(graph)
}
}
}
private fun runCalculation(from: String) {
val end = start + T.hours(rangeToDisplay.toLong()).msecs()
iobCobStaticCalculatorPlugin.stopCalculation(from)
iobCobStaticCalculatorPlugin.clearCache()
iobCobStaticCalculatorPlugin.runCalculation(from, end, true, false, eventCustomCalculationFinished)
}
@Synchronized
fun updateGUI(from: String) {
aapsLogger.debug(LTag.UI, "updateGUI from: $from")
val pump = activePlugin.activePump
val profile = profileFunction.getProfile()
historybrowse_noprofile?.visibility = (profile == null).toVisibility()
profile ?: return
val lowLine = defaultValueHelper.determineLowLine()
val highLine = defaultValueHelper.determineHighLine()
historybrowse_date?.text = DateUtil.dateAndTimeString(start)
historybrowse_zoom?.text = rangeToDisplay.toString()
GlobalScope.launch(Dispatchers.Main) {
historybrowse_bggraph ?: return@launch
val graphData = GraphData(injector, historybrowse_bggraph, iobCobStaticCalculatorPlugin)
val secondaryGraphsData: ArrayList<GraphData> = ArrayList()
// do preparation in different thread
withContext(Dispatchers.Default) {
val fromTime: Long = start + T.secs(100).msecs()
val toTime: Long = start + T.hours(rangeToDisplay.toLong()).msecs()
aapsLogger.debug(LTag.UI, "Period: " + DateUtil.dateAndTimeString(fromTime) + " - " + DateUtil.dateAndTimeString(toTime))
val pointer = System.currentTimeMillis()
// **** In range Area ****
graphData.addInRangeArea(fromTime, toTime, lowLine, highLine)
// **** BG ****
graphData.addBgReadings(fromTime, toTime, lowLine, highLine, null)
// set manual x bounds to have nice steps
graphData.formatAxis(fromTime, toTime)
// Treatments
graphData.addTreatments(fromTime, toTime)
if (overviewMenus.setting[0][OverviewMenus.CharType.ACT.ordinal])
graphData.addActivity(fromTime, toTime, false, 0.8)
// add basal data
if (pump.pumpDescription.isTempBasalCapable && overviewMenus.setting[0][OverviewMenus.CharType.BAS.ordinal]) {
graphData.addBasals(fromTime, toTime, lowLine / graphData.maxY / 1.2)
}
// add target line
graphData.addTargetLine(fromTime, toTime, profile, null)
// **** NOW line ****
graphData.addNowLine(pointer)
// ------------------ 2nd graph
for (g in 0 until secondaryGraphs.size) {
val secondGraphData = GraphData(injector, secondaryGraphs[g], iobCobStaticCalculatorPlugin)
var useIobForScale = false
var useCobForScale = false
var useDevForScale = false
var useRatioForScale = false
var useDSForScale = false
var useIAForScale = false
var useABSForScale = false
when {
overviewMenus.setting[g + 1][OverviewMenus.CharType.IOB.ordinal] -> useIobForScale = true
overviewMenus.setting[g + 1][OverviewMenus.CharType.COB.ordinal] -> useCobForScale = true
overviewMenus.setting[g + 1][OverviewMenus.CharType.DEV.ordinal] -> useDevForScale = true
overviewMenus.setting[g + 1][OverviewMenus.CharType.SEN.ordinal] -> useRatioForScale = true
overviewMenus.setting[g + 1][OverviewMenus.CharType.ACT.ordinal] -> useIAForScale = true
overviewMenus.setting[g + 1][OverviewMenus.CharType.ABS.ordinal] -> useABSForScale = true
overviewMenus.setting[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal] -> useDSForScale = true
}
if (overviewMenus.setting[g + 1][OverviewMenus.CharType.IOB.ordinal]) secondGraphData.addIob(fromTime, toTime, useIobForScale, 1.0, overviewMenus.setting[g + 1][OverviewMenus.CharType.PRE.ordinal])
if (overviewMenus.setting[g + 1][OverviewMenus.CharType.COB.ordinal]) secondGraphData.addCob(fromTime, toTime, useCobForScale, if (useCobForScale) 1.0 else 0.5)
if (overviewMenus.setting[g + 1][OverviewMenus.CharType.DEV.ordinal]) secondGraphData.addDeviations(fromTime, toTime, useDevForScale, 1.0)
if (overviewMenus.setting[g + 1][OverviewMenus.CharType.SEN.ordinal]) secondGraphData.addRatio(fromTime, toTime, useRatioForScale, 1.0)
if (overviewMenus.setting[g + 1][OverviewMenus.CharType.ACT.ordinal]) secondGraphData.addActivity(fromTime, toTime, useIAForScale, 0.8)
if (overviewMenus.setting[g + 1][OverviewMenus.CharType.ABS.ordinal]) secondGraphData.addAbsIob(fromTime, toTime, useABSForScale, 1.0)
if (overviewMenus.setting[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal] && buildHelper.isDev()) secondGraphData.addDeviationSlope(fromTime, toTime, useDSForScale, 1.0)
// set manual x bounds to have nice steps
secondGraphData.formatAxis(fromTime, toTime)
secondGraphData.addNowLine(pointer)
secondaryGraphsData.add(secondGraphData)
}
}
// finally enforce drawing of graphs in UI thread
graphData.performUpdate()
for (g in 0 until secondaryGraphs.size) {
secondaryGraphsLabel[g].text = overviewMenus.enabledTypes(g + 1)
secondaryGraphs[g].visibility = (
overviewMenus.setting[g + 1][OverviewMenus.CharType.IOB.ordinal] ||
overviewMenus.setting[g + 1][OverviewMenus.CharType.COB.ordinal] ||
overviewMenus.setting[g + 1][OverviewMenus.CharType.DEV.ordinal] ||
overviewMenus.setting[g + 1][OverviewMenus.CharType.SEN.ordinal] ||
overviewMenus.setting[g + 1][OverviewMenus.CharType.ACT.ordinal] ||
overviewMenus.setting[g + 1][OverviewMenus.CharType.ABS.ordinal] ||
overviewMenus.setting[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal]
).toVisibility()
secondaryGraphsData[g].performUpdate()
}
}
}
}

View file

@ -744,7 +744,7 @@ public class LoopPlugin extends PluginBase {
} catch (JSONException e) {
getAapsLogger().error("Unhandled exception", e);
}
CareportalEvent event = new CareportalEvent();
CareportalEvent event = new CareportalEvent(getInjector());
event.date = DateUtil.now();
event.source = Source.USER;
event.eventType = CareportalEvent.OPENAPSOFFLINE;

View file

@ -1,344 +0,0 @@
package info.nightscout.androidaps.plugins.configBuilder;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import java.util.ArrayList;
import javax.inject.Inject;
import javax.inject.Singleton;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventAppInitialized;
import info.nightscout.androidaps.events.EventConfigBuilderChange;
import info.nightscout.androidaps.events.EventRebuildTabs;
import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.BgSourceInterface;
import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.SensitivityInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.configBuilder.events.EventConfigBuilderUpdateGui;
import info.nightscout.androidaps.utils.alertDialogs.OKDialog;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
/**
* Created by mike on 05.08.2016.
*/
@Singleton
public class ConfigBuilderPlugin extends PluginBase {
private static ConfigBuilderPlugin configBuilderPlugin;
private final ActivePluginProvider activePlugin;
private final SP sp;
private final AAPSLogger aapsLogger;
private final RxBusWrapper rxBus;
private final ResourceHelper resourceHelper;
private final ProfileFunction profileFunction;
/**
* @deprecated Use dagger to get an instance
*/
@Deprecated
public ProfileFunction getProfileFunction() {
if (profileFunction == null)
throw new IllegalStateException("Accessing profileFunction before first instantiation");
return profileFunction;
}
@Deprecated
static public ConfigBuilderPlugin getPlugin() {
if (configBuilderPlugin == null)
throw new IllegalStateException("Accessing ConfigBuilder before first instantiation");
return configBuilderPlugin;
}
/*
* Written by Adrian:
* The ConfigBuilderPlugin.getPlugin() method is used at 333 places throughout the app.
* In order to make the transition to DI, while legacy code is still calling `getPlugin()`,
* I'd instantiate this plugin very very early on (first injected dependency in MainApp) and use
* Lazy dependencies in this constructor.
* */
@Inject
public ConfigBuilderPlugin(
ActivePluginProvider activePlugin,
HasAndroidInjector injector,
SP sp,
RxBusWrapper rxBus,
AAPSLogger aapsLogger,
ResourceHelper resourceHelper,
ProfileFunction profileFunction
) {
super(new PluginDescription()
.mainType(PluginType.GENERAL)
.fragmentClass(ConfigBuilderFragment.class.getName())
.showInList(true)
.alwaysEnabled(true)
.alwaysVisible(false)
.pluginName(R.string.configbuilder)
.shortName(R.string.configbuilder_shortname)
.description(R.string.description_config_builder),
aapsLogger, resourceHelper, injector
);
this.activePlugin = activePlugin;
this.sp = sp;
this.rxBus = rxBus;
this.aapsLogger = aapsLogger;
this.resourceHelper = resourceHelper;
this.profileFunction = profileFunction;
configBuilderPlugin = this; // TODO: only while transitioning to Dagger
}
public void initialize() {
upgradeSettings();
((PluginStore) activePlugin).loadDefaults();
loadSettings();
setAlwaysEnabledPluginsEnabled();
rxBus.send(new EventAppInitialized());
}
private void setAlwaysEnabledPluginsEnabled() {
for (PluginBase plugin : activePlugin.getPluginsList()) {
if (plugin.getPluginDescription().alwaysEnabled)
plugin.setPluginEnabled(plugin.getType(), true);
}
storeSettings("setAlwaysEnabledPluginsEnabled");
}
public void storeSettings(String from) {
activePlugin.getPluginsList();
getAapsLogger().debug(LTag.CONFIGBUILDER, "Storing settings from: " + from);
activePlugin.verifySelectionInCategories();
for (PluginBase p : activePlugin.getPluginsList()) {
PluginType type = p.getType();
if (p.getPluginDescription().alwaysEnabled && p.getPluginDescription().alwaysVisible)
continue;
if (p.getPluginDescription().alwaysEnabled && p.getPluginDescription().neverVisible)
continue;
savePref(p, type, true);
if (type == PluginType.PUMP) {
if (p instanceof ProfileInterface) { // Store state of optional Profile interface
savePref(p, PluginType.PROFILE, false);
}
}
}
}
private void savePref(PluginBase p, PluginType type, boolean storeVisible) {
String settingEnabled = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Enabled";
sp.putBoolean(settingEnabled, p.isEnabled(type));
getAapsLogger().debug(LTag.CONFIGBUILDER, "Storing: " + settingEnabled + ":" + p.isEnabled(type));
if (storeVisible) {
String settingVisible = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Visible";
sp.putBoolean(settingVisible, p.isFragmentVisible());
getAapsLogger().debug(LTag.CONFIGBUILDER, "Storing: " + settingVisible + ":" + p.isFragmentVisible());
}
}
private void loadSettings() {
getAapsLogger().debug(LTag.CONFIGBUILDER, "Loading stored settings");
for (PluginBase p : activePlugin.getPluginsList()) {
PluginType type = p.getType();
loadPref(p, type, true);
if (p.getType() == PluginType.PUMP) {
if (p instanceof ProfileInterface) {
loadPref(p, PluginType.PROFILE, false);
}
}
}
activePlugin.verifySelectionInCategories();
}
private void loadPref(PluginBase p, PluginType type, boolean loadVisible) {
String settingEnabled = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Enabled";
if (sp.contains(settingEnabled))
p.setPluginEnabled(type, sp.getBoolean(settingEnabled, false));
else if (p.getType() == type && (p.getPluginDescription().enableByDefault || p.getPluginDescription().alwaysEnabled)) {
p.setPluginEnabled(type, true);
}
getAapsLogger().debug(LTag.CONFIGBUILDER, "Loaded: " + settingEnabled + ":" + p.isEnabled(type));
if (loadVisible) {
String settingVisible = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Visible";
if (sp.contains(settingVisible))
p.setFragmentVisible(type, sp.getBoolean(settingVisible, false) && sp.getBoolean(settingEnabled, false));
else if (p.getType() == type && p.getPluginDescription().visibleByDefault) {
p.setFragmentVisible(type, true);
}
getAapsLogger().debug(LTag.CONFIGBUILDER, "Loaded: " + settingVisible + ":" + p.isFragmentVisible());
}
}
// Detect settings prior 1.60
private void upgradeSettings() {
if (!sp.contains("ConfigBuilder_1_NSProfilePlugin_Enabled"))
return;
getAapsLogger().debug(LTag.CONFIGBUILDER, "Upgrading stored settings");
for (PluginBase p : activePlugin.getPluginsList()) {
getAapsLogger().debug(LTag.CONFIGBUILDER, "Processing " + p.getName());
for (int type = 1; type < 11; type++) {
PluginType newType;
switch (type) {
case 1:
newType = PluginType.GENERAL;
break;
case 2:
newType = PluginType.TREATMENT;
break;
case 3:
newType = PluginType.SENSITIVITY;
break;
case 4:
newType = PluginType.PROFILE;
break;
case 5:
newType = PluginType.APS;
break;
case 6:
newType = PluginType.PUMP;
break;
case 7:
newType = PluginType.CONSTRAINTS;
break;
case 8:
newType = PluginType.LOOP;
break;
case 9:
newType = PluginType.BGSOURCE;
break;
case 10:
newType = PluginType.INSULIN;
break;
default:
newType = PluginType.GENERAL;
break;
}
String settingEnabled = "ConfigBuilder_" + type + "_" + p.getClass().getSimpleName() + "_Enabled";
String settingVisible = "ConfigBuilder_" + type + "_" + p.getClass().getSimpleName() + "_Visible";
if (sp.contains(settingEnabled))
p.setPluginEnabled(newType, sp.getBoolean(settingEnabled, false));
if (sp.contains(settingVisible))
p.setFragmentVisible(newType, sp.getBoolean(settingVisible, false) && sp.getBoolean(settingEnabled, false));
sp.remove(settingEnabled);
sp.remove(settingVisible);
if (newType == p.getType()) {
savePref(p, newType, true);
}
}
}
}
public void logPluginStatus() {
for (PluginBase p : activePlugin.getPluginsList()) {
getAapsLogger().debug(LTag.CONFIGBUILDER, p.getName() + ":" +
(p.isEnabled(PluginType.GENERAL) ? " GENERAL" : "") +
(p.isEnabled(PluginType.TREATMENT) ? " TREATMENT" : "") +
(p.isEnabled(PluginType.SENSITIVITY) ? " SENSITIVITY" : "") +
(p.isEnabled(PluginType.PROFILE) ? " PROFILE" : "") +
(p.isEnabled(PluginType.APS) ? " APS" : "") +
(p.isEnabled(PluginType.PUMP) ? " PUMP" : "") +
(p.isEnabled(PluginType.CONSTRAINTS) ? " CONSTRAINTS" : "") +
(p.isEnabled(PluginType.LOOP) ? " LOOP" : "") +
(p.isEnabled(PluginType.BGSOURCE) ? " BGSOURCE" : "") +
(p.isEnabled(PluginType.INSULIN) ? " INSULIN" : "")
);
}
}
// Ask when switching to physical pump plugin
public void switchAllowed(@NonNull PluginBase changedPlugin, boolean newState, @Nullable FragmentActivity activity, @NonNull PluginType type) {
if (changedPlugin.getType() == PluginType.PUMP && !changedPlugin.getName().equals(resourceHelper.gs(R.string.virtualpump)))
confirmPumpPluginActivation(changedPlugin, newState, activity, type);
else
performPluginSwitch(changedPlugin, newState, type);
}
private void confirmPumpPluginActivation(@NonNull PluginBase changedPlugin, boolean newState, @Nullable FragmentActivity activity, @NonNull PluginType type) {
boolean allowHardwarePump = sp.getBoolean("allow_hardware_pump", false);
if (allowHardwarePump || activity == null) {
performPluginSwitch(changedPlugin, newState, type);
} else {
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.allow_hardware_pump_text), () -> {
performPluginSwitch(changedPlugin, newState, type);
sp.putBoolean("allow_hardware_pump", true);
aapsLogger.debug(LTag.PUMP, "First time HW pump allowed!");
}, () -> {
rxBus.send(new EventConfigBuilderUpdateGui());
aapsLogger.debug(LTag.PUMP, "User does not allow switching to HW pump!");
});
}
}
public void performPluginSwitch(PluginBase changedPlugin, boolean enabled, @NonNull PluginType type) {
changedPlugin.setPluginEnabled(type, enabled);
changedPlugin.setFragmentVisible(type, enabled);
processOnEnabledCategoryChanged(changedPlugin, type);
storeSettings("CheckedCheckboxEnabled");
rxBus.send(new EventRebuildTabs());
rxBus.send(new EventConfigBuilderChange());
rxBus.send(new EventConfigBuilderUpdateGui());
logPluginStatus();
}
public void processOnEnabledCategoryChanged(PluginBase changedPlugin, PluginType type) {
ArrayList<PluginBase> pluginsInCategory = null;
switch (type) {
// Multiple selection allowed
case GENERAL:
case CONSTRAINTS:
case LOOP:
break;
// Single selection allowed
case INSULIN:
pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(InsulinInterface.class);
break;
case SENSITIVITY:
pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(SensitivityInterface.class);
break;
case APS:
pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(APSInterface.class);
break;
case PROFILE:
pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(ProfileInterface.class);
break;
case BGSOURCE:
pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(BgSourceInterface.class);
break;
case TREATMENT:
pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(TreatmentsInterface.class);
break;
case PUMP:
pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(PumpInterface.class);
break;
}
if (pluginsInCategory != null) {
boolean newSelection = changedPlugin.isEnabled(type);
if (newSelection) { // new plugin selected -> disable others
for (PluginBase p : pluginsInCategory) {
if (p.getName().equals(changedPlugin.getName())) {
// this is new selected
} else {
p.setPluginEnabled(type, false);
p.setFragmentVisible(type, false);
}
}
} else { // enable first plugin in list
pluginsInCategory.get(0).setPluginEnabled(type, true);
}
}
}
}

View file

@ -0,0 +1,191 @@
package info.nightscout.androidaps.plugins.configBuilder
import androidx.fragment.app.FragmentActivity
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.events.EventAppInitialized
import info.nightscout.androidaps.events.EventConfigBuilderChange
import info.nightscout.androidaps.events.EventRebuildTabs
import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.events.EventConfigBuilderUpdateGui
import info.nightscout.androidaps.utils.alertDialogs.OKDialog.showConfirmation
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ConfigBuilderPlugin @Inject constructor(
injector: HasAndroidInjector,
aapsLogger: AAPSLogger,
resourceHelper: ResourceHelper,
private val sp: SP,
private val rxBus: RxBusWrapper,
private val activePlugin: ActivePluginProvider
) : PluginBase(PluginDescription()
.mainType(PluginType.GENERAL)
.fragmentClass(ConfigBuilderFragment::class.java.name)
.showInList(true)
.alwaysEnabled(true)
.alwaysVisible(false)
.pluginName(R.string.configbuilder)
.shortName(R.string.configbuilder_shortname)
.description(R.string.description_config_builder),
aapsLogger, resourceHelper, injector
) {
fun initialize() {
(activePlugin as PluginStore).loadDefaults()
loadSettings()
setAlwaysEnabledPluginsEnabled()
rxBus.send(EventAppInitialized())
}
private fun setAlwaysEnabledPluginsEnabled() {
for (plugin in activePlugin.pluginsList) {
if (plugin.pluginDescription.alwaysEnabled) plugin.setPluginEnabled(plugin.getType(), true)
}
storeSettings("setAlwaysEnabledPluginsEnabled")
}
fun storeSettings(from: String) {
activePlugin.pluginsList
aapsLogger.debug(LTag.CONFIGBUILDER, "Storing settings from: $from")
activePlugin.verifySelectionInCategories()
for (p in activePlugin.pluginsList) {
val type = p.getType()
if (p.pluginDescription.alwaysEnabled && p.pluginDescription.alwaysVisible) continue
if (p.pluginDescription.alwaysEnabled && p.pluginDescription.neverVisible) continue
savePref(p, type, true)
if (type == PluginType.PUMP) {
if (p is ProfileInterface) { // Store state of optional Profile interface
savePref(p, PluginType.PROFILE, false)
}
}
}
}
private fun savePref(p: PluginBase, type: PluginType, storeVisible: Boolean) {
val settingEnabled = "ConfigBuilder_" + type.name + "_" + p.javaClass.simpleName + "_Enabled"
sp.putBoolean(settingEnabled, p.isEnabled(type))
aapsLogger.debug(LTag.CONFIGBUILDER, "Storing: " + settingEnabled + ":" + p.isEnabled(type))
if (storeVisible) {
val settingVisible = "ConfigBuilder_" + type.name + "_" + p.javaClass.simpleName + "_Visible"
sp.putBoolean(settingVisible, p.isFragmentVisible())
aapsLogger.debug(LTag.CONFIGBUILDER, "Storing: " + settingVisible + ":" + p.isFragmentVisible())
}
}
private fun loadSettings() {
aapsLogger.debug(LTag.CONFIGBUILDER, "Loading stored settings")
for (p in activePlugin.pluginsList) {
val type = p.getType()
loadPref(p, type, true)
if (p.getType() == PluginType.PUMP) {
if (p is ProfileInterface) {
loadPref(p, PluginType.PROFILE, false)
}
}
}
activePlugin.verifySelectionInCategories()
}
private fun loadPref(p: PluginBase, type: PluginType, loadVisible: Boolean) {
val settingEnabled = "ConfigBuilder_" + type.name + "_" + p.javaClass.simpleName + "_Enabled"
if (sp.contains(settingEnabled)) p.setPluginEnabled(type, sp.getBoolean(settingEnabled, false)) else if (p.getType() == type && (p.pluginDescription.enableByDefault || p.pluginDescription.alwaysEnabled)) {
p.setPluginEnabled(type, true)
}
aapsLogger.debug(LTag.CONFIGBUILDER, "Loaded: " + settingEnabled + ":" + p.isEnabled(type))
if (loadVisible) {
val settingVisible = "ConfigBuilder_" + type.name + "_" + p.javaClass.simpleName + "_Visible"
if (sp.contains(settingVisible)) p.setFragmentVisible(type, sp.getBoolean(settingVisible, false) && sp.getBoolean(settingEnabled, false)) else if (p.getType() == type && p.pluginDescription.visibleByDefault) {
p.setFragmentVisible(type, true)
}
aapsLogger.debug(LTag.CONFIGBUILDER, "Loaded: " + settingVisible + ":" + p.isFragmentVisible())
}
}
fun logPluginStatus() {
for (p in activePlugin.pluginsList) {
aapsLogger.debug(LTag.CONFIGBUILDER, p.name + ":" +
(if (p.isEnabled(PluginType.GENERAL)) " GENERAL" else "") +
(if (p.isEnabled(PluginType.TREATMENT)) " TREATMENT" else "") +
(if (p.isEnabled(PluginType.SENSITIVITY)) " SENSITIVITY" else "") +
(if (p.isEnabled(PluginType.PROFILE)) " PROFILE" else "") +
(if (p.isEnabled(PluginType.APS)) " APS" else "") +
(if (p.isEnabled(PluginType.PUMP)) " PUMP" else "") +
(if (p.isEnabled(PluginType.CONSTRAINTS)) " CONSTRAINTS" else "") +
(if (p.isEnabled(PluginType.LOOP)) " LOOP" else "") +
(if (p.isEnabled(PluginType.BGSOURCE)) " BGSOURCE" else "") +
if (p.isEnabled(PluginType.INSULIN)) " INSULIN" else ""
)
}
}
// Ask when switching to physical pump plugin
fun switchAllowed(changedPlugin: PluginBase, newState: Boolean, activity: FragmentActivity?, type: PluginType) {
if (changedPlugin.getType() == PluginType.PUMP && changedPlugin.name != resourceHelper.gs(R.string.virtualpump)) confirmPumpPluginActivation(changedPlugin, newState, activity, type) else performPluginSwitch(changedPlugin, newState, type)
}
private fun confirmPumpPluginActivation(changedPlugin: PluginBase, newState: Boolean, activity: FragmentActivity?, type: PluginType) {
val allowHardwarePump = sp.getBoolean("allow_hardware_pump", false)
if (allowHardwarePump || activity == null) {
performPluginSwitch(changedPlugin, newState, type)
} else {
showConfirmation(activity, resourceHelper.gs(R.string.allow_hardware_pump_text), Runnable {
performPluginSwitch(changedPlugin, newState, type)
sp.putBoolean("allow_hardware_pump", true)
aapsLogger.debug(LTag.PUMP, "First time HW pump allowed!")
}, Runnable {
rxBus.send(EventConfigBuilderUpdateGui())
aapsLogger.debug(LTag.PUMP, "User does not allow switching to HW pump!")
})
}
}
fun performPluginSwitch(changedPlugin: PluginBase, enabled: Boolean, type: PluginType) {
changedPlugin.setPluginEnabled(type, enabled)
changedPlugin.setFragmentVisible(type, enabled)
processOnEnabledCategoryChanged(changedPlugin, type)
storeSettings("CheckedCheckboxEnabled")
rxBus.send(EventRebuildTabs())
rxBus.send(EventConfigBuilderChange())
rxBus.send(EventConfigBuilderUpdateGui())
logPluginStatus()
}
fun processOnEnabledCategoryChanged(changedPlugin: PluginBase, type: PluginType?) {
var pluginsInCategory: ArrayList<PluginBase>? = null
when (type) {
PluginType.INSULIN -> pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(InsulinInterface::class.java)
PluginType.SENSITIVITY -> pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(SensitivityInterface::class.java)
PluginType.APS -> pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(APSInterface::class.java)
PluginType.PROFILE -> pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(ProfileInterface::class.java)
PluginType.BGSOURCE -> pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(BgSourceInterface::class.java)
PluginType.TREATMENT -> pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(TreatmentsInterface::class.java)
PluginType.PUMP -> pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(PumpInterface::class.java)
else -> {
}
}
if (pluginsInCategory != null) {
val newSelection = changedPlugin.isEnabled(type!!)
if (newSelection) { // new plugin selected -> disable others
for (p in pluginsInCategory) {
if (p.name == changedPlugin.name) {
// this is new selected
} else {
p.setPluginEnabled(type, false)
p.setFragmentVisible(type, false)
}
}
} else { // enable first plugin in list
pluginsInCategory[0].setPluginEnabled(type, true)
}
}
}
}

View file

@ -73,11 +73,10 @@ public class NSUpload {
}
}
public static void uploadTempBasalStartPercent(TemporaryBasal temporaryBasal) {
public static void uploadTempBasalStartPercent(TemporaryBasal temporaryBasal, Profile profile) {
try {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
boolean useAbsolute = SP.getBoolean("ns_sync_use_absolute", false);
Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile(temporaryBasal.date);
double absoluteRate = 0;
if (profile != null) {
absoluteRate = profile.getBasal(temporaryBasal.date) * temporaryBasal.percentRate / 100d;
@ -264,16 +263,16 @@ public class NSUpload {
}
}
public static void uploadTempTarget(TempTarget tempTarget) {
public static void uploadTempTarget(TempTarget tempTarget, ProfileFunction profileFunction) {
try {
JSONObject data = new JSONObject();
data.put("eventType", CareportalEvent.TEMPORARYTARGET);
data.put("duration", tempTarget.durationInMinutes);
if (tempTarget.low > 0) {
data.put("reason", tempTarget.reason);
data.put("targetBottom", Profile.fromMgdlToUnits(tempTarget.low, ConfigBuilderPlugin.getPlugin().getProfileFunction().getUnits()));
data.put("targetTop", Profile.fromMgdlToUnits(tempTarget.high, ConfigBuilderPlugin.getPlugin().getProfileFunction().getUnits()));
data.put("units", ConfigBuilderPlugin.getPlugin().getProfileFunction().getUnits());
data.put("targetBottom", Profile.fromMgdlToUnits(tempTarget.low, profileFunction.getUnits()));
data.put("targetTop", Profile.fromMgdlToUnits(tempTarget.high, profileFunction.getUnits()));
data.put("units", profileFunction.getUnits());
}
data.put("created_at", DateUtil.toISOString(tempTarget.date));
data.put("enteredBy", MainApp.gs(R.string.app_name));

View file

@ -470,7 +470,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
// OpenAPSSMB only
// Add expected zero temp basal for next 240 mins
IobTotal basalIobWithZeroTemp = basalIob.copy();
TemporaryBasal t = new TemporaryBasal()
TemporaryBasal t = new TemporaryBasal(injector)
.date(now + 60 * 1000L)
.duration(240)
.absolute(0);
@ -517,7 +517,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
// OpenAPSSMB only
// Add expected zero temp basal for next 240 mins
IobTotal basalIobWithZeroTemp = basalIob.copy();
TemporaryBasal t = new TemporaryBasal()
TemporaryBasal t = new TemporaryBasal(injector)
.date(now + 60 * 1000L)
.duration(240)
.absolute(0);

View file

@ -776,7 +776,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
PumpState state = commandResult.state;
if (state.tbrActive && state.tbrPercent == adjustedPercent
&& (state.tbrRemainingDuration == durationInMinutes || state.tbrRemainingDuration == durationInMinutes - 1)) {
TemporaryBasal tempStart = new TemporaryBasal()
TemporaryBasal tempStart = new TemporaryBasal(getInjector())
.date(state.timestamp)
.duration(state.tbrRemainingDuration)
.percent(state.tbrPercent)
@ -822,7 +822,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
return new PumpEnactResult(getInjector()).success(false).enacted(false);
}
if (!cancelResult.state.tbrActive) {
TemporaryBasal tempBasal = new TemporaryBasal()
TemporaryBasal tempBasal = new TemporaryBasal(getInjector())
.date(cancelResult.state.timestamp)
.duration(0)
.source(Source.USER);
@ -973,7 +973,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
TemporaryBasal aapsTbr = treatmentsPlugin.getTempBasalFromHistory(now);
if (aapsTbr == null || aapsTbr.percentRate != 0) {
getAapsLogger().debug(LTag.PUMP, "Creating 15m zero temp since pump is suspended");
TemporaryBasal newTempBasal = new TemporaryBasal()
TemporaryBasal newTempBasal = new TemporaryBasal(getInjector())
.date(now)
.percent(0)
.duration(15)
@ -1099,7 +1099,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
TemporaryBasal aapsTbr = treatmentsPlugin.getTempBasalFromHistory(now);
if (aapsTbr == null && state.tbrActive && state.tbrRemainingDuration > 2) {
getAapsLogger().debug(LTag.PUMP, "Creating temp basal from pump TBR");
TemporaryBasal newTempBasal = new TemporaryBasal()
TemporaryBasal newTempBasal = new TemporaryBasal(getInjector())
.date(now)
.percent(state.tbrPercent)
.duration(state.tbrRemainingDuration)
@ -1107,7 +1107,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
treatmentsPlugin.addToHistoryTempBasal(newTempBasal);
} else if (aapsTbr != null && aapsTbr.getPlannedRemainingMinutes() > 2 && !state.tbrActive) {
getAapsLogger().debug(LTag.PUMP, "Ending AAPS-TBR since pump has no TBR active");
TemporaryBasal tempStop = new TemporaryBasal()
TemporaryBasal tempStop = new TemporaryBasal(getInjector())
.date(now)
.duration(0)
.source(Source.USER);
@ -1116,13 +1116,13 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
&& (aapsTbr.percentRate != state.tbrPercent ||
Math.abs(aapsTbr.getPlannedRemainingMinutes() - state.tbrRemainingDuration) > 2)) {
getAapsLogger().debug(LTag.PUMP, "AAPSs and pump-TBR differ; ending AAPS-TBR and creating new TBR based on pump TBR");
TemporaryBasal tempStop = new TemporaryBasal()
TemporaryBasal tempStop = new TemporaryBasal(getInjector())
.date(now - 1000)
.duration(0)
.source(Source.USER);
treatmentsPlugin.addToHistoryTempBasal(tempStop);
TemporaryBasal newTempBasal = new TemporaryBasal()
TemporaryBasal newTempBasal = new TemporaryBasal(getInjector())
.date(now)
.percent(state.tbrPercent)
.duration(state.tbrRemainingDuration)

View file

@ -33,9 +33,9 @@ import static info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyL
*/
public abstract class RileyLinkService extends DaggerService {
@Inject AAPSLogger aapsLogger;
@Inject SP sp;
@Inject Context context;
@Inject protected AAPSLogger aapsLogger;
@Inject protected SP sp;
@Inject protected Context context;
public RileyLinkBLE rileyLinkBLE; // android-bluetooth management

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.pump.danaR.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.logging.AAPSLogger
@ -25,7 +26,8 @@ class MessageHashTableR @Inject constructor(
danaRKoreanPlugin: DanaRKoreanPlugin,
configBuilderPlugin: ConfigBuilderPlugin,
commandQueue: CommandQueueProvider,
activePlugin: ActivePluginProvider
activePlugin: ActivePluginProvider,
injector: HasAndroidInjector
) : MessageHashTableBase {
var messages: HashMap<Int, MessageBase> = HashMap()
@ -36,7 +38,7 @@ class MessageHashTableR @Inject constructor(
put(MsgBolusStartWithSpeed(aapsLogger, constraintChecker, danaRPump, 0.0, 0)) // 0x0104 CMD_MEALINS_START_DATA_SPEED
put(MsgBolusProgress(aapsLogger, resourceHelper, rxBus, danaRPump)) // 0x0202 CMD_PUMP_THIS_REMAINDER_MEAL_INS
put(MsgStatusProfile(aapsLogger, danaRPump)) // 0x0204 CMD_PUMP_CALCULATION_SETTING
put(MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin)) // 0x0205 CMD_PUMP_EXERCISE_MODE
put(MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin, injector)) // 0x0205 CMD_PUMP_EXERCISE_MODE
put(MsgStatusBolusExtended(aapsLogger, danaRPump, activePlugin)) // 0x0207 CMD_PUMP_EXPANS_INS_I
put(MsgStatusBasic(aapsLogger, danaRPump)) // 0x020A CMD_PUMP_INITVIEW_I
put(MsgStatus(aapsLogger, danaRPump)) // 0x020B CMD_PUMP_STATUS

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.pump.danaR.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.db.Source
import info.nightscout.androidaps.db.TemporaryBasal
import info.nightscout.androidaps.interfaces.ActivePluginProvider
@ -11,7 +12,8 @@ import kotlin.math.ceil
class MsgStatusTempBasal(
private val aapsLogger: AAPSLogger,
private val danaRPump: DanaRPump,
private val activePlugin: ActivePluginProvider
private val activePlugin: ActivePluginProvider,
private val injector: HasAndroidInjector
) : MessageBase() {
init {
@ -52,10 +54,10 @@ class MsgStatusTempBasal(
val tempBasal = activePlugin.activeTreatments.getRealTempBasalFromHistory(System.currentTimeMillis())
if (danaRPump.isTempBasalInProgress) {
if (tempBasal.percentRate != danaRPump.tempBasalPercent) { // Close current temp basal
val tempStop = TemporaryBasal().date(danaRPump.tempBasalStart - 1000).source(Source.USER)
val tempStop = TemporaryBasal(injector).date(danaRPump.tempBasalStart - 1000).source(Source.USER)
activePlugin.activeTreatments.addToHistoryTempBasal(tempStop)
// Create new
val newTempBasal = TemporaryBasal()
val newTempBasal = TemporaryBasal(injector)
.date(danaRPump.tempBasalStart)
.percent(danaRPump.tempBasalPercent)
.duration(danaRPump.tempBasalTotalSec / 60)
@ -63,12 +65,12 @@ class MsgStatusTempBasal(
activePlugin.activeTreatments.addToHistoryTempBasal(newTempBasal)
}
} else { // Close current temp basal
val tempStop = TemporaryBasal().date(now).source(Source.USER)
val tempStop = TemporaryBasal(injector).date(now).source(Source.USER)
activePlugin.activeTreatments.addToHistoryTempBasal(tempStop)
}
} else {
if (danaRPump.isTempBasalInProgress) { // Create new
val newTempBasal = TemporaryBasal()
val newTempBasal = TemporaryBasal(injector)
.date(danaRPump.tempBasalStart)
.percent(danaRPump.tempBasalPercent)
.duration(danaRPump.tempBasalTotalSec / 60)

View file

@ -55,7 +55,7 @@ import io.reactivex.schedulers.Schedulers;
*/
public abstract class AbstractDanaRExecutionService extends DaggerService {
@Inject HasAndroidInjector injector;
@Inject protected HasAndroidInjector injector;
@Inject AAPSLogger aapsLogger;
@Inject RxBusWrapper rxBus;
@Inject SP sp;

View file

@ -11,6 +11,7 @@ import java.util.Date;
import javax.inject.Inject;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile;
@ -91,6 +92,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService {
@Inject ActivePluginProvider activePlugin;
@Inject ProfileFunction profileFunction;
@Inject SP sp;
@Inject HasAndroidInjector injector;
public DanaRExecutionService() {
}
@ -147,7 +149,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService {
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpstatus)));
MsgStatus statusMsg = new MsgStatus(aapsLogger, danaRPump);
MsgStatusBasic statusBasicMsg = new MsgStatusBasic(aapsLogger, danaRPump);
MsgStatusTempBasal tempStatusMsg = new MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin);
MsgStatusTempBasal tempStatusMsg = new MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin, injector);
MsgStatusBolusExtended exStatusMsg = new MsgStatusBolusExtended(aapsLogger, danaRPump, activePlugin);
MsgCheckValue checkValue = new MsgCheckValue(aapsLogger, danaRPump, danaRPlugin);
@ -238,7 +240,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService {
}
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal)));
mSerialIOThread.sendMessage(new MsgSetTempBasalStart(aapsLogger, percent, durationInHours));
mSerialIOThread.sendMessage(new MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin));
mSerialIOThread.sendMessage(new MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin, injector));
rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
@ -247,7 +249,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService {
if (!isConnected()) return false;
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal)));
mSerialIOThread.sendMessage(new MsgSetTempBasalStop(aapsLogger));
mSerialIOThread.sendMessage(new MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin));
mSerialIOThread.sendMessage(new MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin, injector));
rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.pump.danaRKorean.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.logging.AAPSLogger
@ -26,7 +27,8 @@ class MessageHashTableRKorean @Inject constructor(
danaRKoreanPlugin: DanaRKoreanPlugin,
configBuilderPlugin: ConfigBuilderPlugin,
commandQueue: CommandQueueProvider,
activePlugin: ActivePluginProvider
activePlugin: ActivePluginProvider,
injector: HasAndroidInjector
) : MessageHashTableBase {
var messages: HashMap<Int, MessageBase> = HashMap()
@ -36,7 +38,7 @@ class MessageHashTableRKorean @Inject constructor(
put(MsgBolusStart(aapsLogger, constraintChecker, danaRPump, 0.0)) // 0x0102 CMD_MEALINS_START_DATA
put(MsgBolusProgress(aapsLogger, resourceHelper, rxBus, danaRPump)) // 0x0202 CMD_PUMP_THIS_REMAINDER_MEAL_INS
put(MsgStatusProfile(aapsLogger, danaRPump)) // 0x0204 CMD_PUMP_CALCULATION_SETTING
put(MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin)) // 0x0205 CMD_PUMP_EXERCISE_MODE
put(MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin, injector)) // 0x0205 CMD_PUMP_EXERCISE_MODE
put(MsgStatusBolusExtended(aapsLogger, danaRPump, activePlugin)) // 0x0207 CMD_PUMP_EXPANS_INS_I
put(MsgStatusBasic_k(aapsLogger, danaRPump)) // 0x020A CMD_PUMP_INITVIEW_I
put(MsgStatus_k(aapsLogger, danaRPump)) // 0x020B CMD_PUMP_STATUS

View file

@ -138,7 +138,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpstatus)));
//MsgStatus_k statusMsg = new MsgStatus_k();
MsgStatusBasic_k statusBasicMsg = new MsgStatusBasic_k(aapsLogger, danaRPump);
MsgStatusTempBasal tempStatusMsg = new MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin);
MsgStatusTempBasal tempStatusMsg = new MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin, injector);
MsgStatusBolusExtended exStatusMsg = new MsgStatusBolusExtended(aapsLogger, danaRPump, activePlugin);
MsgCheckValue_k checkValue = new MsgCheckValue_k(aapsLogger, danaRPump, danaRKoreanPlugin);
@ -227,7 +227,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
}
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal)));
mSerialIOThread.sendMessage(new MsgSetTempBasalStart(aapsLogger, percent, durationInHours));
mSerialIOThread.sendMessage(new MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin));
mSerialIOThread.sendMessage(new MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin, injector));
rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
@ -236,7 +236,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
if (!isConnected()) return false;
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal)));
mSerialIOThread.sendMessage(new MsgSetTempBasalStop(aapsLogger));
mSerialIOThread.sendMessage(new MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin));
mSerialIOThread.sendMessage(new MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin, injector));
rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.pump.danaRS.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
@ -21,7 +22,8 @@ class DanaRSMessageHashTable @Inject constructor(
activePlugin: ActivePluginProvider,
constraintChecker: ConstraintChecker,
detailedBolusInfoStorage: DetailedBolusInfoStorage,
sp: SP
sp: SP,
injector: HasAndroidInjector
) {
var messages: HashMap<Int, DanaRS_Packet> = HashMap()
@ -99,7 +101,7 @@ class DanaRSMessageHashTable @Inject constructor(
put(DanaRS_Packet_History_Temporary(aapsLogger, rxBus))
// APS
put(DanaRS_Packet_APS_Basal_Set_Temporary_Basal(aapsLogger, 0))
put(DanaRS_Packet_APS_History_Events(aapsLogger, rxBus, resourceHelper, activePlugin, danaRPump, detailedBolusInfoStorage, sp, 0))
put(DanaRS_Packet_APS_History_Events(aapsLogger, rxBus, resourceHelper, activePlugin, danaRPump, detailedBolusInfoStorage, sp, injector, 0))
put(DanaRS_Packet_APS_Set_Event_History(aapsLogger, 0, 0, 0, 0))
// v3
put(DanaRS_Packet_General_Get_Shipping_Version(aapsLogger, danaRPump))

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.pump.danaRS.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.db.CareportalEvent
@ -28,6 +29,7 @@ open class DanaRS_Packet_APS_History_Events(
private val danaRPump: DanaRPump,
private val detailedBolusInfoStorage: DetailedBolusInfoStorage,
private val sp: SP,
private val injector: HasAndroidInjector,
private var from: Long
) : DanaRS_Packet() {
@ -78,7 +80,7 @@ open class DanaRS_Packet_APS_History_Events(
val datetime = dateTimeSecFromBuff(data, 1) // 6 bytes
val param1 = (intFromBuff(data, 7, 1) shl 8 and 0xFF00) + (intFromBuff(data, 8, 1) and 0xFF)
val param2 = (intFromBuff(data, 9, 1) shl 8 and 0xFF00) + (intFromBuff(data, 10, 1) and 0xFF)
val temporaryBasal = TemporaryBasal().date(datetime).source(Source.PUMP).pumpId(datetime)
val temporaryBasal = TemporaryBasal(injector).date(datetime).source(Source.PUMP).pumpId(datetime)
val extendedBolus = ExtendedBolus().date(datetime).source(Source.PUMP).pumpId(datetime)
val status: String
when (recordCode.toInt()) {
@ -161,14 +163,14 @@ open class DanaRS_Packet_APS_History_Events(
DanaRPump.REFILL -> {
aapsLogger.debug(LTag.PUMPCOMM, "EVENT REFILL (" + recordCode + ") " + DateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100.0 + "U")
if (sp.getBoolean(R.string.key_rs_loginsulinchange, true))
FillDialog.generateCareportalEvent(CareportalEvent.INSULINCHANGE, datetime, resourceHelper.gs(R.string.danarspump), resourceHelper, sp)
FillDialog.generateCareportalEvent(CareportalEvent.INSULINCHANGE, datetime, resourceHelper.gs(R.string.danarspump), resourceHelper, sp, injector)
status = "REFILL " + DateUtil.timeString(datetime)
}
DanaRPump.PRIME -> {
aapsLogger.debug(LTag.PUMPCOMM, "EVENT PRIME (" + recordCode + ") " + DateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100.0 + "U")
if (sp.getBoolean(R.string.key_rs_logcanulachange, true))
FillDialog.generateCareportalEvent(CareportalEvent.SITECHANGE, datetime, resourceHelper.gs(R.string.danarspump), resourceHelper, sp)
FillDialog.generateCareportalEvent(CareportalEvent.SITECHANGE, datetime, resourceHelper.gs(R.string.danarspump), resourceHelper, sp, injector)
status = "PRIME " + DateUtil.timeString(datetime)
}

View file

@ -211,10 +211,10 @@ class DanaRSService : DaggerService() {
SystemClock.sleep(1000)
val msg: DanaRS_Packet_APS_History_Events
if (lastHistoryFetched == 0L) {
msg = DanaRS_Packet_APS_History_Events(aapsLogger, rxBus, resourceHelper, activePlugin, danaRPump, detailedBolusInfoStorage, sp, 0)
msg = DanaRS_Packet_APS_History_Events(aapsLogger, rxBus, resourceHelper, activePlugin, danaRPump, detailedBolusInfoStorage, sp, injector, 0)
aapsLogger.debug(LTag.PUMPCOMM, "Loading complete event history")
} else {
msg = DanaRS_Packet_APS_History_Events(aapsLogger, rxBus, resourceHelper, activePlugin, danaRPump, detailedBolusInfoStorage, sp, lastHistoryFetched)
msg = DanaRS_Packet_APS_History_Events(aapsLogger, rxBus, resourceHelper, activePlugin, danaRPump, detailedBolusInfoStorage, sp, injector, lastHistoryFetched)
aapsLogger.debug(LTag.PUMPCOMM, "Loading event history from: " + DateUtil.dateAndTimeString(lastHistoryFetched))
}
sendMessage(msg)

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.pump.danaRv2.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.logging.AAPSLogger
@ -32,7 +33,8 @@ class MessageHashTableRv2 @Inject constructor(
commandQueue: CommandQueueProvider,
activePlugin: ActivePluginProvider,
detailedBolusInfoStorage: DetailedBolusInfoStorage,
treatmentsPlugin: TreatmentsPlugin
treatmentsPlugin: TreatmentsPlugin,
injector: HasAndroidInjector
) : MessageHashTableBase {
var messages: HashMap<Int, MessageBase> = HashMap()
@ -91,7 +93,7 @@ class MessageHashTableRv2 @Inject constructor(
put(MsgCheckValue_v2(aapsLogger, rxBus, resourceHelper, danaRPump, danaRPlugin, danaRKoreanPlugin, danaRv2Plugin, configBuilderPlugin, commandQueue)) // 0xF0F1 CMD_PUMP_CHECK_VALUE
put(MsgStatusAPS_v2(aapsLogger, danaRPump)) // 0xE001 CMD_PUMPSTATUS_APS
put(MsgSetAPSTempBasalStart_v2(aapsLogger, 0, false, false)) // 0xE002 CMD_PUMPSET_APSTEMP
put(MsgHistoryEvents_v2(aapsLogger, resourceHelper, detailedBolusInfoStorage, danaRv2Plugin, rxBus, treatmentsPlugin)) // 0xE003 CMD_GET_HISTORY
put(MsgHistoryEvents_v2(aapsLogger, resourceHelper, detailedBolusInfoStorage, danaRv2Plugin, rxBus, treatmentsPlugin, injector)) // 0xE003 CMD_GET_HISTORY
put(MsgSetHistoryEntry_v2(aapsLogger, 0, 0, 0, 0)) // 0xE004 CMD_SET_HISTORY_ENTRY
}

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.pump.danaRv2.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.db.ExtendedBolus
@ -25,6 +26,7 @@ class MsgHistoryEvents_v2 constructor(
val danaRv2Plugin: DanaRv2Plugin,
val rxBus: RxBusWrapper,
val treatmentsPlugin: TreatmentsPlugin,
private val injector: HasAndroidInjector,
var from: Long = 0
) : MessageBase() {
@ -61,7 +63,7 @@ class MsgHistoryEvents_v2 constructor(
val datetime = dateTimeSecFromBuff(bytes, 1) // 6 bytes
val param1 = intFromBuff(bytes, 7, 2)
val param2 = intFromBuff(bytes, 9, 2)
val temporaryBasal = TemporaryBasal()
val temporaryBasal = TemporaryBasal(injector)
.date(datetime)
.source(Source.PUMP)
.pumpId(datetime)

View file

@ -454,7 +454,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
if (!isConnected())
return new PumpEnactResult(injector).success(false);
SystemClock.sleep(300);
MsgHistoryEvents_v2 msg = new MsgHistoryEvents_v2(aapsLogger, resourceHelper, detailedBolusInfoStorage, danaRv2Plugin, rxBus, treatmentsPlugin, lastHistoryFetched);
MsgHistoryEvents_v2 msg = new MsgHistoryEvents_v2(aapsLogger, resourceHelper, detailedBolusInfoStorage, danaRv2Plugin, rxBus, treatmentsPlugin, injector, lastHistoryFetched);
aapsLogger.debug(LTag.PUMP, "Loading event history from: " + DateUtil.dateAndTimeString(lastHistoryFetched));
mSerialIOThread.sendMessage(msg);

View file

@ -1229,7 +1229,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
InsightPumpID stoppedEvent = MainApp.getDbHelper().getPumpStoppedEvent(pumpID.pumpSerial, pumpID.timestamp);
if (stoppedEvent == null || stoppedEvent.eventType.equals("PumpPaused")) continue;
long tbrStart = stoppedEvent.timestamp + 10000;
TemporaryBasal temporaryBasal = new TemporaryBasal();
TemporaryBasal temporaryBasal = new TemporaryBasal(getInjector());
temporaryBasal.durationInMinutes = (int) ((pumpID.timestamp - tbrStart) / 60000);
temporaryBasal.date = tbrStart;
temporaryBasal.source = Source.PUMP;
@ -1355,7 +1355,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
pumpID.timestamp = timestamp;
pumpID.eventType = "StartOfTBR";
MainApp.getDbHelper().createOrUpdate(pumpID);
TemporaryBasal temporaryBasal = new TemporaryBasal();
TemporaryBasal temporaryBasal = new TemporaryBasal(getInjector());
temporaryBasal.durationInMinutes = event.getDuration();
temporaryBasal.source = Source.PUMP;
temporaryBasal.pumpId = pumpID.id;
@ -1374,7 +1374,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
pumpID.eventType = "EndOfTBR";
pumpID.timestamp = timestamp;
MainApp.getDbHelper().createOrUpdate(pumpID);
TemporaryBasal temporaryBasal = new TemporaryBasal();
TemporaryBasal temporaryBasal = new TemporaryBasal(getInjector());
temporaryBasal.durationInMinutes = 0;
temporaryBasal.source = Source.PUMP;
temporaryBasal.pumpId = pumpID.id;
@ -1572,7 +1572,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
data.put("created_at", DateUtil.toISOString(date));
data.put("eventType", CareportalEvent.NOTE);
data.put("notes", note);
CareportalEvent careportalEvent = new CareportalEvent();
CareportalEvent careportalEvent = new CareportalEvent(getInjector());
careportalEvent.date = date;
careportalEvent.source = Source.USER;
careportalEvent.eventType = CareportalEvent.NOTE;
@ -1606,7 +1606,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
if (!enteredBy.equals("")) data.put("enteredBy", enteredBy);
data.put("created_at", DateUtil.toISOString(date));
data.put("eventType", event);
CareportalEvent careportalEvent = new CareportalEvent();
CareportalEvent careportalEvent = new CareportalEvent(getInjector());
careportalEvent.date = date;
careportalEvent.source = Source.USER;
careportalEvent.eventType = event;

View file

@ -1030,7 +1030,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
pumpStatusLocal.tempBasalAmount = absoluteRate;
pumpStatusLocal.tempBasalLength = durationInMinutes;
TemporaryBasal tempStart = new TemporaryBasal() //
TemporaryBasal tempStart = new TemporaryBasal(getInjector()) //
.date(System.currentTimeMillis()) //
.duration(durationInMinutes) //
.absolute(absoluteRate) //
@ -1371,7 +1371,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
if (response) {
aapsLogger.info(LTag.PUMP, getLogPrefix() + "cancelTempBasal - Cancel TBR successful.");
TemporaryBasal tempBasal = new TemporaryBasal() //
TemporaryBasal tempBasal = new TemporaryBasal(getInjector()) //
.date(System.currentTimeMillis()) //
.duration(0) //
.source(Source.USER);

View file

@ -36,10 +36,10 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP;
*/
public class RileyLinkMedtronicService extends RileyLinkService {
@Inject AAPSLogger aapsLogger;
@Inject Context context;
//@Inject AAPSLogger aapsLogger;
//@Inject Context context;
@Inject MedtronicPumpPlugin medtronicPumpPlugin;
@Inject SP sp;
//@Inject SP sp;
private static RileyLinkMedtronicService instance;
private static ServiceTask currentTask = null;
@ -110,6 +110,11 @@ public class RileyLinkMedtronicService extends RileyLinkService {
// init rileyLinkCommunicationManager
medtronicCommunicationManager = new MedtronicCommunicationManager(context, rfspy);
aapsLogger.debug(LTag.PUMPCOMM, "RileyLinkMedtronicService newly constructed");
MedtronicUtil.setMedtronicService(this);
pumpStatus = (MedtronicPumpStatus) medtronicPumpPlugin.getPumpStatusData();
}

View file

@ -239,7 +239,7 @@ class VirtualPumpPlugin @Inject constructor(
override fun stopBolusDelivering() {}
override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean): PumpEnactResult {
val tempBasal = TemporaryBasal()
val tempBasal = TemporaryBasal(injector)
.date(System.currentTimeMillis())
.absolute(absoluteRate)
.duration(durationInMinutes)
@ -259,7 +259,7 @@ class VirtualPumpPlugin @Inject constructor(
}
override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean): PumpEnactResult {
val tempBasal = TemporaryBasal()
val tempBasal = TemporaryBasal(injector)
.date(System.currentTimeMillis())
.percent(percent)
.duration(durationInMinutes)
@ -307,7 +307,7 @@ class VirtualPumpPlugin @Inject constructor(
result.comment = resourceHelper.gs(R.string.virtualpump_resultok)
if (treatmentsPlugin.isTempBasalInProgress) {
result.enacted = true
val tempStop = TemporaryBasal().date(System.currentTimeMillis()).source(Source.USER)
val tempStop = TemporaryBasal(injector).date(System.currentTimeMillis()).source(Source.USER)
treatmentsPlugin.addToHistoryTempBasal(tempStop)
//tempBasal = null;
aapsLogger.debug(LTag.PUMP, "Canceling temp basal: $result")

View file

@ -109,7 +109,7 @@ public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin {
}
// reset deviations after site change
if (CareportalEvent.isEvent5minBack(siteChanges, autosensData.time)) {
if (new CareportalEvent(getInjector()).isEvent5minBack(siteChanges, autosensData.time)) {
deviationsArray.clear();
pastSensitivity += "(SITECHANGE)";
}

View file

@ -118,7 +118,7 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin {
String pastSensitivity = pastSensitivityArray.get(hoursegment);
// reset deviations after site change
if (CareportalEvent.isEvent5minBack(siteChanges, autosensData.time)) {
if (new CareportalEvent(getInjector()).isEvent5minBack(siteChanges, autosensData.time)) {
deviationsArray.clear();
pastSensitivity += "(SITECHANGE)";
}

View file

@ -111,7 +111,7 @@ public class SensitivityWeightedAveragePlugin extends AbstractSensitivityPlugin
}
// reset deviations after site change
if (CareportalEvent.isEvent5minBack(siteChanges, autosensData.time)) {
if (new CareportalEvent(getInjector()).isEvent5minBack(siteChanges, autosensData.time)) {
data.clear();
pastSensitivity += "(SITECHANGE)";
}

View file

@ -102,7 +102,7 @@ class DexcomPlugin @Inject constructor(
jsonObject.put("glucose", meter.getInt("meterValue"))
jsonObject.put("units", Constants.MGDL)
val careportalEvent = CareportalEvent()
val careportalEvent = CareportalEvent(injector)
careportalEvent.date = timestamp
careportalEvent.source = Source.USER
careportalEvent.eventType = CareportalEvent.BGCHECK
@ -122,7 +122,7 @@ class DexcomPlugin @Inject constructor(
jsonObject.put("enteredBy", "AndroidAPS-Dexcom$sensorType")
jsonObject.put("created_at", DateUtil.toISOString(sensorInsertionTime))
jsonObject.put("eventType", CareportalEvent.SENSORCHANGE)
val careportalEvent = CareportalEvent()
val careportalEvent = CareportalEvent(injector)
careportalEvent.date = sensorInsertionTime
careportalEvent.source = Source.USER
careportalEvent.eventType = CareportalEvent.SENSORCHANGE

View file

@ -402,7 +402,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
Profile profile = profileFunction.getProfile(t.date);
if (profile == null) continue;
if (truncate && t.end() > truncateTime) {
TemporaryBasal dummyTemp = new TemporaryBasal();
TemporaryBasal dummyTemp = new TemporaryBasal(getInjector());
dummyTemp.copyFrom(t);
dummyTemp.cutEndTo(truncateTime);
calc = dummyTemp.iobCalc(time, profile);
@ -477,7 +477,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
Profile profile = profileFunction.getProfile(t.date);
if (profile == null) continue;
if (t.end() > truncateTime) {
TemporaryBasal dummyTemp = new TemporaryBasal();
TemporaryBasal dummyTemp = new TemporaryBasal(getInjector());
dummyTemp.copyFrom(t);
dummyTemp.cutEndTo(truncateTime);
calc = dummyTemp.iobCalc(time, profile, lastAutosensResult, exercise_mode, half_basal_exercise_target, isTempTarget);
@ -586,7 +586,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
else if (tempBasal.isAbsolute)
NSUpload.uploadTempBasalStartAbsolute(tempBasal, null);
else
NSUpload.uploadTempBasalStartPercent(tempBasal);
NSUpload.uploadTempBasalStartPercent(tempBasal, profileFunction.getProfile(tempBasal.date));
}
return newRecordCreated;
}
@ -706,7 +706,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
public void addToHistoryTempTarget(TempTarget tempTarget) {
//log.debug("Adding new TemporaryBasal record" + profileSwitch.log());
MainApp.getDbHelper().createOrUpdate(tempTarget);
NSUpload.uploadTempTarget(tempTarget);
NSUpload.uploadTempTarget(tempTarget, profileFunction);
}
@Override

View file

@ -13,13 +13,13 @@ class BTReceiver : DaggerBroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
super.onReceive(context, intent)
val device : BluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
val device: BluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
when (intent.action) {
BluetoothDevice.ACTION_ACL_CONNECTED ->
rxBus.send(EventBTChange(EventBTChange.Change.CONNECT, device.name))
BluetoothDevice.ACTION_ACL_CONNECTED ->
rxBus.send(EventBTChange(EventBTChange.Change.CONNECT, deviceName = device.name, deviceAddress = device.address))
BluetoothDevice.ACTION_ACL_DISCONNECTED ->
rxBus.send(EventBTChange(EventBTChange.Change.DISCONNECT, device.name))
rxBus.send(EventBTChange(EventBTChange.Change.DISCONNECT, deviceName = device.name, deviceAddress = device.address))
}
}
}

View file

@ -64,65 +64,42 @@
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1">
<com.jjoe64.graphview.GraphView
android:id="@+id/historyybrowse_bggraph"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
<ImageButton
android:id="@+id/overview_chartMenuButton"
android:layout_width="30dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:paddingTop="5dp"
app:srcCompat="@drawable/ic_arrow_drop_down_white_24dp" />
<TextView
android:id="@+id/overview_iobcalculationprogess"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="15sp" />
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1">
<com.jjoe64.graphview.GraphView
android:id="@+id/historybrowse_iobgraph"
android:id="@+id/historybrowse_bggraph"
android:layout_width="wrap_content"
android:layout_height="100dp" />
android:layout_height="match_parent" />
<SeekBar
android:id="@+id/historybrowse_seekBar"
android:layout_width="match_parent"
<ImageButton
android:id="@+id/overview_chartMenuButton"
android:layout_width="30dp"
android:layout_height="wrap_content"
android:visibility="gone"/>
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:paddingTop="5dp"
app:srcCompat="@drawable/ic_arrow_drop_down_white_24dp" />
</LinearLayout>
<TextView
android:id="@+id/overview_iobcalculationprogess"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="15sp" />
<ScrollView
</RelativeLayout>
<LinearLayout
android:id="@+id/history_iobgraph"
android:layout_width="match_parent"
android:layout_height="wrap_content">
android:layout_height="wrap_content"
android:orientation="vertical" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
</FrameLayout>
</ScrollView>
</LinearLayout>
</LinearLayout>

View file

@ -1840,7 +1840,7 @@
<string name="current_master_password">Current master password</string>
<string name="statuslights">Status lights</string>
<string name="statuslights_copy_ns">Copy settings from NS</string>
<string name="key_statuslights_copy_ns">statuslights_copy_ns</string>
<string name="copyexistingvalues">Copy NS settins (if exists)?</string>
<string name="key_statuslights_copy_ns" translatable="false">statuslights_copy_ns</string>
<string name="copyexistingvalues">Copy NS settings (if exists)?</string>
<string name="key_statuslights_overview_advanced" translatable="false">statuslights_overview_advanced</string>
</resources>

View file

@ -1,5 +1,8 @@
package info.nightscout.androidaps.data
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.TestBase
import info.nightscout.androidaps.db.TemporaryBasal
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.T
@ -9,21 +12,23 @@ import org.junit.runner.RunWith
import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class)
class NonOverlappingIntervalsTest {
class NonOverlappingIntervalsTest : TestBase() {
private val startDate = DateUtil.now()
var list = NonOverlappingIntervals<TemporaryBasal>()
val injector = HasAndroidInjector { AndroidInjector {} }
@Test
fun doTests() {
// create one 10h interval and test value in and out
list.add(TemporaryBasal().date(startDate).duration(T.hours(10).mins().toInt()).absolute(1.0))
list.add(TemporaryBasal(injector).date(startDate).duration(T.hours(10).mins().toInt()).absolute(1.0))
Assert.assertEquals(null, list.getValueByInterval(startDate - T.secs(1).msecs()))
Assert.assertEquals(1.0, list.getValueByInterval(startDate)!!.absoluteRate, 0.01)
Assert.assertEquals(null, list.getValueByInterval(startDate + T.hours(10).msecs() + 1))
// stop temp after 5h
list.add(TemporaryBasal().date(startDate + T.hours(5).msecs()).duration(0))
list.add(TemporaryBasal(injector).date(startDate + T.hours(5).msecs()).duration(0))
Assert.assertEquals(null, list.getValueByInterval(startDate - T.secs(1).msecs()))
Assert.assertEquals(1.0, list.getValueByInterval(startDate)!!.absoluteRate, 0.01)
Assert.assertEquals(1.0, list.getValueByInterval(startDate + T.hours(5).msecs() - 1)!!.absoluteRate, 0.01)
@ -31,7 +36,7 @@ class NonOverlappingIntervalsTest {
Assert.assertEquals(null, list.getValueByInterval(startDate + T.hours(10).msecs() + 1))
// insert 1h interval inside
list.add(TemporaryBasal().date(startDate + T.hours(3).msecs()).duration(T.hours(1).mins().toInt()).absolute(2.0))
list.add(TemporaryBasal(injector).date(startDate + T.hours(3).msecs()).duration(T.hours(1).mins().toInt()).absolute(2.0))
Assert.assertEquals(null, list.getValueByInterval(startDate - T.secs(1).msecs()))
Assert.assertEquals(1.0, list.getValueByInterval(startDate)!!.absoluteRate, 0.01)
Assert.assertEquals(null, list.getValueByInterval(startDate + T.hours(5).msecs() - 1))
@ -44,7 +49,7 @@ class NonOverlappingIntervalsTest {
@Test
fun testCopyConstructor() {
list.reset()
list.add(TemporaryBasal().date(startDate).duration(T.hours(10).mins().toInt()).absolute(1.0))
list.add(TemporaryBasal(injector).date(startDate).duration(T.hours(10).mins().toInt()).absolute(1.0))
val list2 = NonOverlappingIntervals(list)
Assert.assertEquals(1, list2.list.size.toLong())
}

View file

@ -2,20 +2,14 @@ package info.nightscout.androidaps.plugins.aps.loop
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.TestBase
import info.nightscout.androidaps.TestBaseWithProfile
import info.nightscout.androidaps.db.TemporaryBasal
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.interfaces.PumpDescription
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.JsonHelper.safeGetDouble
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.junit.Assert
import org.junit.Before
@ -35,6 +29,8 @@ class APSResultTest : TestBaseWithProfile() {
@Mock lateinit var sp: SP
@Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin
private val injector = HasAndroidInjector { AndroidInjector { } }
private var closedLoopEnabled = Constraint(false)
private val pumpDescription = PumpDescription()
@ -79,36 +75,36 @@ class APSResultTest : TestBaseWithProfile() {
Assert.assertEquals(false, apsResult.isChangeRequested)
// request equal temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().percent(70).duration(30))
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).percent(70).duration(30))
apsResult.tempBasalRequested(true).percent(70).duration(30)
Assert.assertEquals(false, apsResult.isChangeRequested)
// request zero temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().percent(10).duration(30))
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).percent(10).duration(30))
apsResult.tempBasalRequested(true).percent(0).duration(30)
Assert.assertEquals(true, apsResult.isChangeRequested)
// request high temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().percent(190).duration(30))
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).percent(190).duration(30))
apsResult.tempBasalRequested(true).percent(200).duration(30)
Assert.assertEquals(true, apsResult.isChangeRequested)
// request slightly different temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().percent(70).duration(30))
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).percent(70).duration(30))
apsResult.tempBasalRequested(true).percent(80).duration(30)
Assert.assertEquals(false, apsResult.isChangeRequested)
// request different temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().percent(70).duration(30))
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).percent(70).duration(30))
apsResult.tempBasalRequested(true).percent(120).duration(30)
Assert.assertEquals(true, apsResult.isChangeRequested)
// it should work with absolute temps too
// request different temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().absolute(1.0).duration(30))
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).absolute(1.0).duration(30))
apsResult.tempBasalRequested(true).percent(100).duration(30)
Assert.assertEquals(false, apsResult.isChangeRequested)
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().absolute(2.0).duration(30))
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).absolute(2.0).duration(30))
apsResult.tempBasalRequested(true).percent(50).duration(30)
Assert.assertEquals(true, apsResult.isChangeRequested)
@ -124,39 +120,39 @@ class APSResultTest : TestBaseWithProfile() {
Assert.assertEquals(false, apsResult.isChangeRequested)
// request equal temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().absolute(2.0).duration(30))
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).absolute(2.0).duration(30))
apsResult.tempBasalRequested(true).rate(2.0).duration(30)
Assert.assertEquals(false, apsResult.isChangeRequested)
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().percent(200).duration(30))
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).percent(200).duration(30))
apsResult.tempBasalRequested(true).rate(2.0).duration(30)
Assert.assertEquals(false, apsResult.isChangeRequested)
// request zero temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().absolute(0.1).duration(30))
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).absolute(0.1).duration(30))
apsResult.tempBasalRequested(true).rate(0.0).duration(30)
Assert.assertEquals(true, apsResult.isChangeRequested)
// request high temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().absolute(34.9).duration(30))
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).absolute(34.9).duration(30))
apsResult.tempBasalRequested(true).rate(35.0).duration(30)
Assert.assertEquals(true, apsResult.isChangeRequested)
// request slightly different temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().absolute(1.1).duration(30))
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).absolute(1.1).duration(30))
apsResult.tempBasalRequested(true).rate(1.2).duration(30)
Assert.assertEquals(false, apsResult.isChangeRequested)
// request different temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().absolute(1.1).duration(30))
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).absolute(1.1).duration(30))
apsResult.tempBasalRequested(true).rate(1.5).duration(30)
Assert.assertEquals(true, apsResult.isChangeRequested)
// it should work with percent temps too
// request different temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().percent(110).duration(30))
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).percent(110).duration(30))
apsResult.tempBasalRequested(true).rate(1.1).duration(30)
Assert.assertEquals(false, apsResult.isChangeRequested)
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().percent(200).duration(30))
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).percent(200).duration(30))
apsResult.tempBasalRequested(true).rate(0.5).duration(30)
Assert.assertEquals(true, apsResult.isChangeRequested)
}
@ -173,7 +169,7 @@ class APSResultTest : TestBaseWithProfile() {
it.resourceHelper = resourceHelper
}
apsResult.rate(10.0)
val apsResult2 = apsResult.newAndClone(HasAndroidInjector { AndroidInjector { Unit } })
val apsResult2 = apsResult.newAndClone(injector)
Assert.assertEquals(apsResult.rate, apsResult2.rate, 0.0)
}

View file

@ -6,7 +6,6 @@ import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.TestBase
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
@ -28,7 +27,6 @@ class ConfigBuilderPluginTest : TestBase() {
@Mock lateinit var resourceHelper: ResourceHelper
@Mock lateinit var commandQueue: CommandQueueProvider
@Mock lateinit var activePlugin: ActivePluginProvider
@Mock lateinit var profileFunction: ProfileFunction
lateinit var configBuilderPlugin: ConfigBuilderPlugin
@ -45,6 +43,6 @@ class ConfigBuilderPluginTest : TestBase() {
@Before
fun prepareMock() {
configBuilderPlugin = ConfigBuilderPlugin(activePlugin, injector, sp, RxBusWrapper(), aapsLogger, resourceHelper, profileFunction)
configBuilderPlugin = ConfigBuilderPlugin(injector, aapsLogger, resourceHelper, sp, RxBusWrapper(), activePlugin)
}
}

View file

@ -16,9 +16,11 @@ import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class)
@PrepareForTest(ConfigBuilderPlugin::class)
class AutomationEventTest : TestBase() {
@Mock lateinit var loopPlugin: LoopPlugin

View file

@ -21,7 +21,7 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.mockito.Mock
import org.powermock.core.classloader.annotations.PrepareForTest
@PrepareForTest(VirtualPumpPlugin::class, RxBusWrapper::class, LocalProfilePlugin::class, SmsCommunicatorPlugin::class)
@PrepareForTest(VirtualPumpPlugin::class, RxBusWrapper::class, LocalProfilePlugin::class, SmsCommunicatorPlugin::class, ConfigBuilderPlugin::class)
open class ActionsTestBase : TestBaseWithProfile() {
@Mock lateinit var sp: SP

View file

@ -1,8 +1,10 @@
package info.nightscout.androidaps.plugins.pump.danaR.comm
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.TestBase
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.db.TemporaryBasal
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump
import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.junit.Before
@ -11,7 +13,15 @@ import org.mockito.Mock
open class DanaRTestBase : TestBase() {
@Mock lateinit var sp: SP
@Mock lateinit var injector: HasAndroidInjector
@Mock lateinit var profileFunction: ProfileFunction
val injector = HasAndroidInjector {
AndroidInjector {
if (it is TemporaryBasal) {
it.profileFunction = profileFunction
}
}
}
lateinit var danaRPump: DanaRPump

View file

@ -20,7 +20,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class)
@PrepareForTest(ConstraintChecker::class, DetailedBolusInfoStorage::class)
@PrepareForTest(ConstraintChecker::class, DetailedBolusInfoStorage::class, ConfigBuilderPlugin::class)
class MessageHashTableRTest : DanaRTestBase() {
@Mock lateinit var rxBus: RxBusWrapper
@ -36,7 +36,7 @@ class MessageHashTableRTest : DanaRTestBase() {
@Test fun runTest() {
Mockito.`when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(0.0))
val messageHashTable = MessageHashTableR(aapsLogger, rxBus, resourceHelper, constraintChecker, danaRPump, danaRPlugin, danaRKoreanPlugin, configBuilderPlugin, commandQueue, activePlugin)
val messageHashTable = MessageHashTableR(aapsLogger, rxBus, resourceHelper, constraintChecker, danaRPump, danaRPlugin, danaRKoreanPlugin, configBuilderPlugin, commandQueue, activePlugin, injector)
val testMessage = messageHashTable.findMessage(0x41f2)
Assert.assertEquals("CMD_HISTORY_ALL", testMessage.messageName)
}

View file

@ -14,7 +14,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class)
@PrepareForTest(DanaRKoreanPlugin::class, DanaRPlugin::class)
@PrepareForTest(DanaRKoreanPlugin::class, DanaRPlugin::class, ConfigBuilderPlugin::class)
class MsgInitConnStatusTimeTest : DanaRTestBase() {
@Mock lateinit var resourceHelper: ResourceHelper

View file

@ -1,15 +1,18 @@
package info.nightscout.androidaps.plugins.pump.danaR.comm
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class)
@PrepareForTest(ConfigBuilderPlugin::class)
class MsgStatusTempBasalTest : DanaRTestBase() {
@Mock lateinit var activePlugin: ActivePluginProvider
@ -17,7 +20,7 @@ class MsgStatusTempBasalTest : DanaRTestBase() {
@Test fun runTest() {
`when`(activePlugin.activeTreatments).thenReturn(treatmentsPlugin)
val packet = MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin)
val packet = MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin, injector)
// test message decoding
// test message decoding
packet.handleMessage(createArray(34, 1.toByte()))

View file

@ -19,7 +19,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class)
@PrepareForTest(ConstraintChecker::class, DetailedBolusInfoStorage::class)
@PrepareForTest(ConstraintChecker::class, DetailedBolusInfoStorage::class, ConfigBuilderPlugin::class)
class MessageHashTableRKoreanTest : DanaRSTestBase() {
@Mock lateinit var constraintChecker: ConstraintChecker
@ -32,7 +32,7 @@ class MessageHashTableRKoreanTest : DanaRSTestBase() {
@Test fun runTest() {
Mockito.`when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(0.0))
val messageHashTable = MessageHashTableRKorean(aapsLogger, rxBus, resourceHelper, constraintChecker, danaRPump, danaRPlugin, danaRKoreanPlugin, configBuilderPlugin, commandQueue, activePlugin)
val messageHashTable = MessageHashTableRKorean(aapsLogger, rxBus, resourceHelper, constraintChecker, danaRPump, danaRPlugin, danaRKoreanPlugin, configBuilderPlugin, commandQueue, activePlugin, injector)
val testMessage = messageHashTable.findMessage(0x41f2)
Assert.assertEquals("CMD_HISTORY_ALL", testMessage.messageName)
}

View file

@ -27,7 +27,7 @@ class DanaRSMessageHashTableTest : DanaRSTestBase() {
fun runTest() {
`when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(0.0))
val danaRSMessageHashTable = DanaRSMessageHashTable(aapsLogger, rxBus, resourceHelper, danaRPump, activePlugin, constraintChecker, detailedBolusInfoStorage, sp)
val danaRSMessageHashTable = DanaRSMessageHashTable(aapsLogger, rxBus, resourceHelper, danaRPump, activePlugin, constraintChecker, detailedBolusInfoStorage, sp, injector)
val forTesting: DanaRS_Packet = DanaRS_Packet_APS_Set_Event_History(aapsLogger, DanaRPump.CARBS, 0, 0, 0)
val testPacket: DanaRS_Packet = danaRSMessageHashTable.findMessage(forTesting.command)
Assert.assertEquals(BleEncryption.DANAR_PACKET__OPCODE__APS_SET_EVENT_HISTORY.toLong(), testPacket.getOpCode().toLong())

View file

@ -1,7 +1,10 @@
package info.nightscout.androidaps.plugins.pump.danaRS.comm
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.TestBaseWithProfile
import info.nightscout.androidaps.db.TemporaryBasal
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump
import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.junit.Before
@ -10,7 +13,14 @@ import org.mockito.Mock
open class DanaRSTestBase : TestBaseWithProfile() {
@Mock lateinit var sp: SP
@Mock lateinit var injector: HasAndroidInjector
val injector = HasAndroidInjector {
AndroidInjector {
if (it is TemporaryBasal) {
it.profileFunction = profileFunction
}
}
}
lateinit var danaRPump: DanaRPump

View file

@ -23,7 +23,7 @@ class DanaRS_Packet_APS_History_EventsTest : DanaRSTestBase() {
@Test fun runTest() {
val now = DateUtil.now()
val testPacket = DanaRS_Packet_APS_History_Events(aapsLogger, rxBus, resourceHelper, activePlugin, danaRPump, detailedBolusInfoStorage, sp, now)
val testPacket = DanaRS_Packet_APS_History_Events(aapsLogger, rxBus, resourceHelper, activePlugin, danaRPump, detailedBolusInfoStorage, sp, injector, now)
// test getRequestedParams
val returnedValues = testPacket.requestParams
val expectedValues = getCalender(now)

View file

@ -23,7 +23,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class)
@PrepareForTest(ConstraintChecker::class, DetailedBolusInfoStorage::class)
@PrepareForTest(ConstraintChecker::class, DetailedBolusInfoStorage::class, ConfigBuilderPlugin::class)
class MessageHashTable_rv2Test : DanaRTestBase() {
@Mock lateinit var rxBus: RxBusWrapper
@ -41,7 +41,7 @@ class MessageHashTable_rv2Test : DanaRTestBase() {
@Test
fun runTest() {
`when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(0.0))
val messageHashTableRv2 = MessageHashTableRv2(aapsLogger, rxBus, resourceHelper, constraintChecker, danaRPump, danaRPlugin, danaRKoreanPlugin, danaRv2Plugin, configBuilderPlugin, commandQueue, activePlugin, detailedBolusInfoStorage, treatmentsPlugin)
val messageHashTableRv2 = MessageHashTableRv2(aapsLogger, rxBus, resourceHelper, constraintChecker, danaRPump, danaRPlugin, danaRKoreanPlugin, danaRv2Plugin, configBuilderPlugin, commandQueue, activePlugin, detailedBolusInfoStorage, treatmentsPlugin, injector)
val forTesting: MessageBase = MsgStatusAPS_v2(aapsLogger, danaRPump)
val testPacket: MessageBase = messageHashTableRv2.findMessage(forTesting.command)
Assert.assertEquals(0xE001, testPacket.command.toLong())

View file

@ -17,7 +17,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class)
@PrepareForTest(DanaRKoreanPlugin::class, DanaRPlugin::class, DanaRv2Plugin::class)
@PrepareForTest(DanaRKoreanPlugin::class, DanaRPlugin::class, DanaRv2Plugin::class, ConfigBuilderPlugin::class)
class MsgCheckValue_v2Test : DanaRTestBase() {
val rxBus = RxBusWrapper()

View file

@ -23,7 +23,7 @@ class MsgHistoryEvents_v2Test : DanaRTestBase() {
@Mock lateinit var treatmentsPlugin: TreatmentsPlugin
@Test @Throws(Exception::class) fun runTest() {
var packet = MsgHistoryEvents_v2(aapsLogger, resourceHelper, detailedBolusInfoStorage, danaRv2Plugin, RxBusWrapper(), treatmentsPlugin, 0)
var packet = MsgHistoryEvents_v2(aapsLogger, resourceHelper, detailedBolusInfoStorage, danaRv2Plugin, RxBusWrapper(), treatmentsPlugin, injector, 0)
// test message decoding
val array = ByteArray(100)

View file

@ -1,6 +1,8 @@
package info.nightscout.androidaps.plugins.treatments
import android.content.Context
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.TestBaseWithProfile
import info.nightscout.androidaps.db.DatabaseHelper
@ -32,6 +34,14 @@ class TreatmentsPluginTest : TestBaseWithProfile() {
@Mock lateinit var databaseHelper: DatabaseHelper
@Mock lateinit var treatmentService: TreatmentService
val injector = HasAndroidInjector {
AndroidInjector {
if (it is TemporaryBasal) {
it.profileFunction = profileFunction
}
}
}
lateinit var insulinOrefRapidActingPlugin: InsulinOrefRapidActingPlugin
lateinit var sot: TreatmentsPlugin
@ -53,7 +63,7 @@ class TreatmentsPluginTest : TestBaseWithProfile() {
fun `zero TBR should produce zero absolute insulin`() {
val now = DateUtil.now()
val tbrs : MutableList<TemporaryBasal> = ArrayList()
tbrs.add(TemporaryBasal().date(now - T.hours(30). msecs()).duration(10000).percent(0))
tbrs.add(TemporaryBasal(injector).date(now - T.hours(30). msecs()).duration(10000).percent(0))
`when`(databaseHelper.getTemporaryBasalsDataFromTime(ArgumentMatchers.anyLong(), ArgumentMatchers.anyBoolean())).thenReturn(tbrs)
sot.initializeData(T.hours(30). msecs())
@ -69,7 +79,7 @@ class TreatmentsPluginTest : TestBaseWithProfile() {
sot.initializeData(T.hours(30). msecs())
val iob100pct = sot.getAbsoluteIOBTempBasals(now)
tbrs.add(TemporaryBasal().date(now - T.hours(30). msecs()).duration(10000).percent(90))
tbrs.add(TemporaryBasal(injector).date(now - T.hours(30). msecs()).duration(10000).percent(90))
sot.initializeData(T.hours(30). msecs())
val iob90pct = sot.getAbsoluteIOBTempBasals(now)
Assert.assertTrue(iob100pct.iob > iob90pct.iob)
@ -83,7 +93,7 @@ class TreatmentsPluginTest : TestBaseWithProfile() {
sot.initializeData(T.hours(30). msecs())
val iob100pct = sot.getAbsoluteIOBTempBasals(now)
tbrs.add(TemporaryBasal().date(now - T.hours(30). msecs()).duration(10000).percent(110))
tbrs.add(TemporaryBasal(injector).date(now - T.hours(30). msecs()).duration(10000).percent(110))
sot.initializeData(T.hours(30). msecs())
val iob110pct = sot.getAbsoluteIOBTempBasals(now)
Assert.assertEquals(1.1, iob110pct.iob / iob100pct.iob, 0.0001)

View file

@ -8,7 +8,7 @@ buildscript {
maven { url 'https://maven.fabric.io/public' }
}
dependencies {
classpath 'com.android.tools.build:gradle:3.6.2'
classpath 'com.android.tools.build:gradle:3.6.3'
classpath 'com.google.gms:google-services:4.3.3'
classpath 'io.fabric.tools:gradle:1.31.2'