diff --git a/app/build.gradle b/app/build.gradle index fe4517d78e..9077e2f9e3 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -63,7 +63,7 @@ android { targetSdkVersion 25 multiDexEnabled true versionCode 1500 - version "2.0a-dev" + version "2.0b-dev" buildConfigField "String", "VERSION", '"' + version + '"' buildConfigField "String", "BUILDVERSION", generateGitBuild() testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" diff --git a/app/src/main/java/com/squareup/otto/LoggingBus.java b/app/src/main/java/com/squareup/otto/LoggingBus.java index 3417e7dd41..13b69c5029 100644 --- a/app/src/main/java/com/squareup/otto/LoggingBus.java +++ b/app/src/main/java/com/squareup/otto/LoggingBus.java @@ -10,6 +10,7 @@ import java.util.HashSet; import java.util.Map; import java.util.Set; +import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.events.Event; /** Logs events has they're being posted to and dispatched from the event bus. @@ -18,7 +19,7 @@ import info.nightscout.androidaps.events.Event; * after 10s (after startup) and then again every 60s. * */ public class LoggingBus extends Bus { - private static Logger log = LoggerFactory.getLogger(LoggingBus.class); + private static Logger log = LoggerFactory.getLogger(Constants.EVENTS); private static long everyMinute = System.currentTimeMillis() + 10 * 1000; private Map> event2Receiver = new HashMap<>(); diff --git a/app/src/main/java/info/nightscout/androidaps/Config.java b/app/src/main/java/info/nightscout/androidaps/Config.java index a12e0a9ea0..04f40669e7 100644 --- a/app/src/main/java/info/nightscout/androidaps/Config.java +++ b/app/src/main/java/info/nightscout/androidaps/Config.java @@ -35,7 +35,10 @@ public class Config { public static final boolean logCongigBuilderActions = true; public static final boolean logAutosensData = false; public static final boolean logEvents = false; - public static final boolean logProfile = false; + public static final boolean logQueue = true; + public static final boolean logBgSource = true; + public static final boolean logOverview = true; + public static final boolean logNotification = true; // DanaR specific public static final boolean logDanaBTComm = true; diff --git a/app/src/main/java/info/nightscout/androidaps/Constants.java b/app/src/main/java/info/nightscout/androidaps/Constants.java index a66d4e77f1..6b2f3d4ac1 100644 --- a/app/src/main/java/info/nightscout/androidaps/Constants.java +++ b/app/src/main/java/info/nightscout/androidaps/Constants.java @@ -67,4 +67,12 @@ public class Constants { //SMS Communicator public static final long SMS_CONFIRM_TIMEOUT = T.mins(5).msecs(); + + // logging + public static final String AUTOSENS = "AUTOSENS"; + public static final String EVENTS = "EVENTS"; + public static final String QUEUE = "QUEUE"; + public static final String BGSOURCE = "BGSOURCE"; + public static final String OVERVIEW = "OVERVIEW"; + public static final String NOTIFICATION = "NOTIFICATION"; } diff --git a/app/src/main/java/info/nightscout/androidaps/HistoryBrowseActivity.java b/app/src/main/java/info/nightscout/androidaps/HistoryBrowseActivity.java index 636db14086..d106fb9985 100644 --- a/app/src/main/java/info/nightscout/androidaps/HistoryBrowseActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/HistoryBrowseActivity.java @@ -1,7 +1,7 @@ package info.nightscout.androidaps; -import android.app.Activity; import android.os.Bundle; +import android.os.SystemClock; import android.support.v4.content.res.ResourcesCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.PopupMenu; @@ -17,11 +17,13 @@ import android.widget.TextView; import com.jjoe64.graphview.GraphView; import com.squareup.otto.Subscribe; +import com.wdullaer.materialdatetimepicker.date.DatePickerDialog; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Calendar; +import java.util.Date; import butterknife.BindView; import butterknife.ButterKnife; @@ -33,11 +35,12 @@ import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished; +import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventIobCalculationProgress; import info.nightscout.androidaps.plugins.Overview.OverviewFragment; import info.nightscout.androidaps.plugins.Overview.OverviewPlugin; import info.nightscout.androidaps.plugins.Overview.graphData.GraphData; import info.nightscout.utils.DateUtil; -import info.nightscout.utils.SP; +import info.nightscout.utils.T; public class HistoryBrowseActivity extends AppCompatActivity { private static Logger log = LoggerFactory.getLogger(HistoryBrowseActivity.class); @@ -61,9 +64,11 @@ public class HistoryBrowseActivity extends AppCompatActivity { SeekBar seekBar; @BindView(R.id.historybrowse_noprofile) TextView noProfile; + @BindView(R.id.overview_iobcalculationprogess) + TextView iobCalculationProgressView; private int rangeToDisplay = 24; // for graph - private long start; + private long start = 0; IobCobCalculatorPlugin iobCobCalculatorPlugin; @@ -90,7 +95,19 @@ public class HistoryBrowseActivity extends AppCompatActivity { iobGraph.getGridLabelRenderer().setNumVerticalLabels(5); setupChartMenu(); + } + @Override + public void onPause() { + super.onPause(); + MainApp.bus().unregister(this); + iobCobCalculatorPlugin.stopCalculation("onPause"); + } + + @Override + public void onResume() { + super.onResume(); + MainApp.bus().register(this); // set start of current day Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); @@ -99,33 +116,23 @@ public class HistoryBrowseActivity extends AppCompatActivity { calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.HOUR_OF_DAY, 0); start = calendar.getTimeInMillis(); - } - - @Override - protected void onResume() { - super.onResume(); + runCalculation("onResume"); + SystemClock.sleep(1000); updateGUI("onResume"); } - - @OnClick(R.id.historybrowse_start) - void onClickStart() { - } - @OnClick(R.id.historybrowse_left) void onClickLeft() { - start -= rangeToDisplay * 60 * 60 * 1000L; - updateGUI("left"); - iobCobCalculatorPlugin.clearCache(); - iobCobCalculatorPlugin.runCalculation("onClickLeft", start, true, eventCustomCalculationFinished); + start -= T.hours(rangeToDisplay).msecs(); + updateGUI("onClickLeft"); + runCalculation("onClickLeft"); } @OnClick(R.id.historybrowse_right) void onClickRight() { - start += rangeToDisplay * 60 * 60 * 1000L; - updateGUI("right"); - iobCobCalculatorPlugin.clearCache(); - iobCobCalculatorPlugin.runCalculation("onClickRight", start, true, eventCustomCalculationFinished); + start += T.hours(rangeToDisplay).msecs(); + updateGUI("onClickRight"); + runCalculation("onClickRight"); } @OnClick(R.id.historybrowse_end) @@ -137,9 +144,8 @@ public class HistoryBrowseActivity extends AppCompatActivity { calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.HOUR_OF_DAY, 0); start = calendar.getTimeInMillis(); - updateGUI("resetToMidnight"); - iobCobCalculatorPlugin.clearCache(); - iobCobCalculatorPlugin.runCalculation("onClickEnd", start, true, eventCustomCalculationFinished); + updateGUI("onClickEnd"); + runCalculation("onClickEnd"); } @OnClick(R.id.historybrowse_zoom) @@ -159,32 +165,63 @@ public class HistoryBrowseActivity extends AppCompatActivity { calendar.set(Calendar.HOUR_OF_DAY, 0); start = calendar.getTimeInMillis(); updateGUI("resetToMidnight"); - iobCobCalculatorPlugin.clearCache(); - iobCobCalculatorPlugin.runCalculation("onLongClickZoom", start, true, eventCustomCalculationFinished); + runCalculation("onLongClickZoom"); return true; } @OnClick(R.id.historybrowse_date) void onClickDate() { + 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(getFragmentManager(), "Datepickerdialog"); + } + + private void runCalculation(String from) { + long end = start + T.hours(rangeToDisplay).msecs(); + iobCobCalculatorPlugin.stopCalculation(from); + iobCobCalculatorPlugin.clearCache(); + iobCobCalculatorPlugin.runCalculation(from, end, true, false, eventCustomCalculationFinished); } @Subscribe public void onStatusEvent(final EventAutosensCalculationFinished e) { - Activity activity = this; - if (activity != null && e.cause == eventCustomCalculationFinished) { + if (e.cause == eventCustomCalculationFinished) { log.debug("EventAutosensCalculationFinished"); - activity.runOnUiThread(new Runnable() { - @Override - public void run() { - synchronized (HistoryBrowseActivity.this) { - updateGUI("EventAutosensCalculationFinished"); - } + runOnUiThread(() -> { + synchronized (HistoryBrowseActivity.this) { + updateGUI("EventAutosensCalculationFinished"); } }); } } + @Subscribe + public void onStatusEvent(final EventIobCalculationProgress e) { + runOnUiThread(() -> { + if (iobCalculationProgressView != null) + iobCalculationProgressView.setText(e.progress); + }); + } + void updateGUI(String from) { + log.debug("updateGUI from: " + from); if (noProfile == null || buttonDate == null || buttonZoom == null || bgGraph == null || iobGraph == null || seekBar == null) return; @@ -200,17 +237,11 @@ public class HistoryBrowseActivity extends AppCompatActivity { } final String units = profile.getUnits(); + final double lowLine = OverviewPlugin.getPlugin().determineLowLine(units); + final double highLine = OverviewPlugin.getPlugin().determineHighLine(units); - double lowLineSetting = SP.getDouble("low_mark", Profile.fromMgdlToUnits(OverviewPlugin.bgTargetLow, units)); - double highLineSetting = SP.getDouble("high_mark", Profile.fromMgdlToUnits(OverviewPlugin.bgTargetHigh, units)); - - if (lowLineSetting < 1) - lowLineSetting = Profile.fromMgdlToUnits(76d, units); - if (highLineSetting < 1) - highLineSetting = Profile.fromMgdlToUnits(180d, units); - - final double lowLine = lowLineSetting; - final double highLine = highLineSetting; + buttonDate.setText(DateUtil.dateAndTimeString(start)); + buttonZoom.setText(String.valueOf(rangeToDisplay)); final boolean showPrediction = false; @@ -226,20 +257,17 @@ public class HistoryBrowseActivity extends AppCompatActivity { //fromTime = toTime - hoursToFetch * 60 * 60 * 1000L; //endTime = toTime + predHours * 60 * 60 * 1000L; //} else { - fromTime = start + 100000; - toTime = start + rangeToDisplay * 60 * 60 * 1000L; + fromTime = start + T.secs(100).msecs(); + toTime = start + T.hours(rangeToDisplay).msecs(); //} - buttonDate.setText(DateUtil.dateAndTimeString(start)); - buttonZoom.setText(String.valueOf(rangeToDisplay)); - log.debug("Period: " + DateUtil.dateAndTimeString(fromTime) + " - " + DateUtil.dateAndTimeString(toTime)); final long pointer = System.currentTimeMillis(); // ------------------ 1st graph - final GraphData graphData = new GraphData(bgGraph, IobCobCalculatorPlugin.getPlugin()); + final GraphData graphData = new GraphData(bgGraph, iobCobCalculatorPlugin); // **** In range Area **** graphData.addInRangeArea(fromTime, toTime, lowLine, highLine); @@ -267,143 +295,137 @@ public class HistoryBrowseActivity extends AppCompatActivity { // ------------------ 2nd graph - final GraphData secondGraphData = new GraphData(iobGraph, iobCobCalculatorPlugin); + new Thread(() -> { + final GraphData secondGraphData = new GraphData(iobGraph, iobCobCalculatorPlugin); - boolean useIobForScale = false; - boolean useCobForScale = false; - boolean useDevForScale = false; - boolean useRatioForScale = false; - boolean useDevSlopeForScale = false; + boolean useIobForScale = false; + boolean useCobForScale = false; + boolean useDevForScale = false; + boolean useRatioForScale = 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 (showDevslope) { - useDevSlopeForScale = true; - } + if (showIob) { + useIobForScale = true; + } else if (showCob) { + useCobForScale = true; + } else if (showDev) { + useDevForScale = true; + } else if (showRat) { + useRatioForScale = true; + } else if (showDevslope) { + useDSForScale = true; + } - if (showIob) - secondGraphData.addIob(fromTime, toTime, useIobForScale, 1d); - 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 (showDevslope) - secondGraphData.addDeviationSlope(fromTime, toTime, useDevSlopeForScale, 1d); + if (showIob) + secondGraphData.addIob(fromTime, toTime, useIobForScale, 1d); + 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 (showDevslope) + secondGraphData.addDeviationSlope(fromTime, toTime, useDSForScale, 1d); - // **** NOW line **** - // set manual x bounds to have nice steps - secondGraphData.formatAxis(fromTime, toTime); - secondGraphData.addNowLine(pointer); + // **** NOW line **** + // set manual x bounds to have nice steps + secondGraphData.formatAxis(fromTime, toTime); + secondGraphData.addNowLine(pointer); - // do GUI update - if (showIob || showCob || showDev || showRat || showDevslope) { - iobGraph.setVisibility(View.VISIBLE); - } else { - iobGraph.setVisibility(View.GONE); - } - // finally enforce drawing of graphs - graphData.performUpdate(); - secondGraphData.performUpdate(); + // do GUI update + runOnUiThread(() -> { + if (showIob || showCob || showDev || showRat || showDevslope) { + iobGraph.setVisibility(View.VISIBLE); + } else { + iobGraph.setVisibility(View.GONE); + } + // finally enforce drawing of graphs + graphData.performUpdate(); + if (showIob || showCob || showDev || showRat || showDevslope) + secondGraphData.performUpdate(); + }); + }).start(); } private void setupChartMenu() { chartButton = (ImageButton) findViewById(R.id.overview_chartMenuButton); - chartButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - MenuItem item; - CharSequence title; - SpannableString s; - PopupMenu popup = new PopupMenu(v.getContext(), v); + chartButton.setOnClickListener(v -> { + MenuItem item; + CharSequence title; + SpannableString s; + PopupMenu popup = new PopupMenu(v.getContext(), v); - item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.BAS.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_basals)); + item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.BAS.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_basals)); + title = item.getTitle(); + s = new SpannableString(title); + s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.basal, null)), 0, s.length(), 0); + item.setTitle(s); + item.setCheckable(true); + item.setChecked(showBasal); + + item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.IOB.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_iob)); + title = item.getTitle(); + s = new SpannableString(title); + s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.iob, null)), 0, s.length(), 0); + item.setTitle(s); + item.setCheckable(true); + item.setChecked(showIob); + + item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.COB.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_cob)); + title = item.getTitle(); + s = new SpannableString(title); + s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.cob, null)), 0, s.length(), 0); + item.setTitle(s); + item.setCheckable(true); + item.setChecked(showCob); + + item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.DEV.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_deviations)); + title = item.getTitle(); + s = new SpannableString(title); + s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.deviations, null)), 0, s.length(), 0); + item.setTitle(s); + item.setCheckable(true); + item.setChecked(showDev); + + item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.SEN.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_sensitivity)); + title = item.getTitle(); + s = new SpannableString(title); + s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.ratio, null)), 0, s.length(), 0); + item.setTitle(s); + item.setCheckable(true); + item.setChecked(showRat); + + if (MainApp.devBranch) { + item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.DEVSLOPE.ordinal(), Menu.NONE, "Deviation slope"); title = item.getTitle(); s = new SpannableString(title); - s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.basal, null)), 0, s.length(), 0); + s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.devslopepos, null)), 0, s.length(), 0); item.setTitle(s); item.setCheckable(true); - item.setChecked(showBasal); - - item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.IOB.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_iob)); - title = item.getTitle(); - s = new SpannableString(title); - s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.iob, null)), 0, s.length(), 0); - item.setTitle(s); - item.setCheckable(true); - item.setChecked(showIob); - - item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.COB.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_cob)); - title = item.getTitle(); - s = new SpannableString(title); - s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.cob, null)), 0, s.length(), 0); - item.setTitle(s); - item.setCheckable(true); - item.setChecked(showCob); - - item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.DEV.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_deviations)); - title = item.getTitle(); - s = new SpannableString(title); - s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.deviations, null)), 0, s.length(), 0); - item.setTitle(s); - item.setCheckable(true); - item.setChecked(showDev); - - item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.SEN.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_sensitivity)); - title = item.getTitle(); - s = new SpannableString(title); - s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.ratio, null)), 0, s.length(), 0); - item.setTitle(s); - item.setCheckable(true); - item.setChecked(showRat); - - if (MainApp.devBranch) { - item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.DEVSLOPE.ordinal(), Menu.NONE, "Deviation slope"); - title = item.getTitle(); - s = new SpannableString(title); - s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.devslopepos, null)), 0, s.length(), 0); - item.setTitle(s); - item.setCheckable(true); - item.setChecked(showDevslope); - } - - popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { - @Override - public boolean onMenuItemClick(MenuItem item) { - if (item.getItemId() == OverviewFragment.CHARTTYPE.BAS.ordinal()) { - showBasal = !item.isChecked(); - } else if (item.getItemId() == OverviewFragment.CHARTTYPE.IOB.ordinal()) { - showIob = !item.isChecked(); - } else if (item.getItemId() == OverviewFragment.CHARTTYPE.COB.ordinal()) { - showCob = !item.isChecked(); - } else if (item.getItemId() == OverviewFragment.CHARTTYPE.DEV.ordinal()) { - showDev = !item.isChecked(); - } else if (item.getItemId() == OverviewFragment.CHARTTYPE.SEN.ordinal()) { - showRat = !item.isChecked(); - } else if (item.getItemId() == OverviewFragment.CHARTTYPE.DEVSLOPE.ordinal()) { - showDevslope = !item.isChecked(); - } - updateGUI("onGraphCheckboxesCheckedChanged"); - return true; - } - }); - chartButton.setImageResource(R.drawable.ic_arrow_drop_up_white_24dp); - popup.setOnDismissListener(new PopupMenu.OnDismissListener() { - @Override - public void onDismiss(PopupMenu menu) { - chartButton.setImageResource(R.drawable.ic_arrow_drop_down_white_24dp); - } - }); - popup.show(); + item.setChecked(showDevslope); } + + popup.setOnMenuItemClickListener(item1 -> { + if (item1.getItemId() == OverviewFragment.CHARTTYPE.BAS.ordinal()) { + showBasal = !item1.isChecked(); + } else if (item1.getItemId() == OverviewFragment.CHARTTYPE.IOB.ordinal()) { + showIob = !item1.isChecked(); + } else if (item1.getItemId() == OverviewFragment.CHARTTYPE.COB.ordinal()) { + showCob = !item1.isChecked(); + } else if (item1.getItemId() == OverviewFragment.CHARTTYPE.DEV.ordinal()) { + showDev = !item1.isChecked(); + } else if (item1.getItemId() == OverviewFragment.CHARTTYPE.SEN.ordinal()) { + showRat = !item1.isChecked(); + } else if (item1.getItemId() == OverviewFragment.CHARTTYPE.DEVSLOPE.ordinal()) { + showDevslope = !item1.isChecked(); + } + updateGUI("onGraphCheckboxesCheckedChanged"); + return true; + }); + chartButton.setImageResource(R.drawable.ic_arrow_drop_up_white_24dp); + popup.setOnDismissListener(menu -> chartButton.setImageResource(R.drawable.ic_arrow_drop_down_white_24dp)); + popup.show(); }); } diff --git a/app/src/main/java/info/nightscout/androidaps/MainActivity.java b/app/src/main/java/info/nightscout/androidaps/MainActivity.java index fe66b95ab0..b22972844c 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/MainActivity.java @@ -352,7 +352,6 @@ public class MainActivity extends AppCompatActivity { public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); pluginPreferencesMenuItem = menu.findItem(R.id.nav_plugin_preferences); - menu.findItem(R.id.nav_historybrowser).setVisible(MainApp.devBranch); checkPluginPreferences(findViewById(R.id.pager)); return true; } diff --git a/app/src/main/java/info/nightscout/androidaps/PreferencesActivity.java b/app/src/main/java/info/nightscout/androidaps/PreferencesActivity.java index a8def0ebf9..349828b7cb 100644 --- a/app/src/main/java/info/nightscout/androidaps/PreferencesActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/PreferencesActivity.java @@ -86,7 +86,7 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre pref.setSummary("******"); } else if (pref.getKey().equals(MainApp.gs(R.string.key_danars_name))) { pref.setSummary(SP.getString(R.string.key_danars_name, "")); - } else if (editTextPref.getText() != null && !editTextPref.getText().equals("")) { + } else if (editTextPref.getText() != null ) { ((EditTextPreference) pref).setDialogMessage(editTextPref.getDialogMessage()); pref.setSummary(editTextPref.getText()); } else if (pref.getKey().contains("smscommunicator_allowednumbers") && TextUtils.isEmpty(editTextPref.getText().trim())) { diff --git a/app/src/main/java/info/nightscout/androidaps/Services/DataService.java b/app/src/main/java/info/nightscout/androidaps/Services/DataService.java index ca7d760cc4..a254f9bf5f 100644 --- a/app/src/main/java/info/nightscout/androidaps/Services/DataService.java +++ b/app/src/main/java/info/nightscout/androidaps/Services/DataService.java @@ -13,11 +13,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import info.nightscout.androidaps.Config; -import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ProfileStore; -import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.events.EventNsFood; import info.nightscout.androidaps.events.EventNsTreatment; @@ -26,15 +23,13 @@ import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin import info.nightscout.androidaps.plugins.NSClientInternal.data.NSDeviceStatus; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSMbg; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSettingsStatus; -import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSgv; import info.nightscout.androidaps.plugins.Overview.OverviewPlugin; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.notifications.Notification; import info.nightscout.androidaps.plugins.ProfileNS.NSProfilePlugin; -import info.nightscout.androidaps.plugins.ProfileNS.events.EventNSProfileUpdateGUI; import info.nightscout.androidaps.plugins.PumpDanaR.activities.DanaRNSHistorySync; -import info.nightscout.androidaps.plugins.SmsCommunicator.events.EventNewSMS; +import info.nightscout.androidaps.plugins.SmsCommunicator.SmsCommunicatorPlugin; import info.nightscout.androidaps.plugins.Source.SourceDexcomG5Plugin; import info.nightscout.androidaps.plugins.Source.SourceGlimpPlugin; import info.nightscout.androidaps.plugins.Source.SourceMM640gPlugin; @@ -44,20 +39,12 @@ import info.nightscout.androidaps.plugins.Source.SourceXdripPlugin; import info.nightscout.androidaps.receivers.DataReceiver; import info.nightscout.utils.BundleLogger; import info.nightscout.utils.JsonHelper; -import info.nightscout.utils.NSUpload; import info.nightscout.utils.SP; public class DataService extends IntentService { private static Logger log = LoggerFactory.getLogger(DataService.class); - boolean xDripEnabled = false; - boolean nsClientEnabled = true; - boolean mm640gEnabled = false; - boolean glimpEnabled = false; - boolean dexcomG5Enabled = false; - boolean poctechEnabled = false; - public DataService() { super("DataService"); registerBus(); @@ -67,58 +54,6 @@ public class DataService extends IntentService { protected void onHandleIntent(final Intent intent) { if (Config.logFunctionCalls) log.debug("onHandleIntent " + BundleLogger.log(intent.getExtras())); - if (ConfigBuilderPlugin.getPlugin().getActiveBgSource() == null) { - xDripEnabled = true; - nsClientEnabled = false; - mm640gEnabled = false; - glimpEnabled = false; - dexcomG5Enabled = false; - poctechEnabled = false; - } else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourceXdripPlugin.class)) { - xDripEnabled = true; - nsClientEnabled = false; - mm640gEnabled = false; - glimpEnabled = false; - dexcomG5Enabled = false; - poctechEnabled = false; - } else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourceNSClientPlugin.class)) { - xDripEnabled = false; - nsClientEnabled = true; - mm640gEnabled = false; - glimpEnabled = false; - dexcomG5Enabled = false; - poctechEnabled = false; - } else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourceMM640gPlugin.class)) { - xDripEnabled = false; - nsClientEnabled = false; - mm640gEnabled = true; - glimpEnabled = false; - dexcomG5Enabled = false; - poctechEnabled = false; - } else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourceGlimpPlugin.class)) { - xDripEnabled = false; - nsClientEnabled = false; - mm640gEnabled = false; - glimpEnabled = true; - dexcomG5Enabled = false; - poctechEnabled = false; - } else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourceDexcomG5Plugin.class)) { - xDripEnabled = false; - nsClientEnabled = false; - mm640gEnabled = false; - glimpEnabled = false; - dexcomG5Enabled = true; - poctechEnabled = false; - } else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourcePoctechPlugin.class)) { - xDripEnabled = false; - nsClientEnabled = false; - mm640gEnabled = false; - glimpEnabled = false; - dexcomG5Enabled = false; - poctechEnabled = true; - } - - boolean isNSProfile = MainApp.getConfigBuilder().getActiveProfileInterface() != null && MainApp.getConfigBuilder().getActiveProfileInterface().getClass().equals(NSProfilePlugin.class); boolean acceptNSData = !SP.getBoolean(R.string.key_ns_upload_only, false); Bundle bundles = intent.getExtras(); @@ -127,71 +62,44 @@ public class DataService extends IntentService { } - if (intent != null) { - final String action = intent.getAction(); - if (Intents.ACTION_NEW_BG_ESTIMATE.equals(action)) { - if (xDripEnabled) { - handleNewDataFromXDrip(intent); - } - } else if (Intents.NS_EMULATOR.equals(action)) { - if (mm640gEnabled) { - handleNewDataFromMM640g(intent); - } - } else if (Intents.GLIMP_BG.equals(action)) { - if (glimpEnabled) { - handleNewDataFromGlimp(intent); - } - } else if (Intents.DEXCOMG5_BG.equals(action)) { - if (dexcomG5Enabled) { - handleNewDataFromDexcomG5(intent); - } - } else if (Intents.POCTECH_BG.equals(action)) { - if (poctechEnabled) { - handleNewDataFromPoctech(intent); - } - } else if (Intents.ACTION_NEW_SGV.equals(action)) { - if (nsClientEnabled || SP.getBoolean(R.string.key_ns_autobackfill, true)) - handleNewDataFromNSClient(intent); - // Objectives 0 - ObjectivesPlugin.bgIsAvailableInNS = true; - ObjectivesPlugin.saveProgress(); - } else if (isNSProfile && Intents.ACTION_NEW_PROFILE.equals(action) || Intents.ACTION_NEW_DEVICESTATUS.equals(action)) { - // always handle Profile if NSProfile is enabled without looking at nsUploadOnly - handleNewDataFromNSClient(intent); - } else if (acceptNSData && - (Intents.ACTION_NEW_TREATMENT.equals(action) || - Intents.ACTION_CHANGED_TREATMENT.equals(action) || - Intents.ACTION_REMOVED_TREATMENT.equals(action) || - Intents.ACTION_NEW_STATUS.equals(action) || - Intents.ACTION_NEW_DEVICESTATUS.equals(action) || - Intents.ACTION_NEW_FOOD.equals(action) || - Intents.ACTION_CHANGED_FOOD.equals(action) || - Intents.ACTION_REMOVED_FOOD.equals(action) || - Intents.ACTION_NEW_CAL.equals(action) || - Intents.ACTION_NEW_MBG.equals(action)) - ) { - handleNewDataFromNSClient(intent); - } else if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(action)) { - handleNewSMS(intent); - } + final String action = intent.getAction(); + if (Intents.ACTION_NEW_BG_ESTIMATE.equals(action)) { + SourceXdripPlugin.getPlugin().handleNewData(intent); + } else if (Intents.NS_EMULATOR.equals(action)) { + SourceMM640gPlugin.getPlugin().handleNewData(intent); + } else if (Intents.GLIMP_BG.equals(action)) { + SourceGlimpPlugin.getPlugin().handleNewData(intent); + } else if (Intents.DEXCOMG5_BG.equals(action)) { + SourceDexcomG5Plugin.getPlugin().handleNewData(intent); + } else if (Intents.POCTECH_BG.equals(action)) { + SourcePoctechPlugin.getPlugin().handleNewData(intent); + } else if (Intents.ACTION_NEW_SGV.equals(action)) { + SourceNSClientPlugin.getPlugin().handleNewData(intent); + } else if (Intents.ACTION_NEW_PROFILE.equals(action)) { + // always handle Profile if NSProfile is enabled without looking at nsUploadOnly + NSProfilePlugin.getPlugin().handleNewData(intent); + } else if (acceptNSData && + (Intents.ACTION_NEW_TREATMENT.equals(action) || + Intents.ACTION_CHANGED_TREATMENT.equals(action) || + Intents.ACTION_REMOVED_TREATMENT.equals(action) || + Intents.ACTION_NEW_STATUS.equals(action) || + Intents.ACTION_NEW_DEVICESTATUS.equals(action) || + Intents.ACTION_NEW_FOOD.equals(action) || + Intents.ACTION_CHANGED_FOOD.equals(action) || + Intents.ACTION_REMOVED_FOOD.equals(action) || + Intents.ACTION_NEW_CAL.equals(action) || + Intents.ACTION_NEW_MBG.equals(action)) + ) { + handleNewDataFromNSClient(intent); + } else if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(action)) { + SmsCommunicatorPlugin.getPlugin().handleNewData(intent); } + if (Config.logFunctionCalls) log.debug("onHandleIntent exit " + intent); DataReceiver.completeWakefulIntent(intent); } -/* - @Override - public int onStartCommand(Intent intent, int flags, int startId) { - super.onStartCommand(intent, flags, startId); - - if (Config.logFunctionCalls) - log.debug("onStartCommand"); - - return START_STICKY; - } -*/ - @Override public void onDestroy() { super.onDestroy(); @@ -207,142 +115,6 @@ public class DataService extends IntentService { MainApp.bus().register(this); } - private void handleNewDataFromXDrip(Intent intent) { - Bundle bundle = intent.getExtras(); - if (bundle == null) return; - - BgReading bgReading = new BgReading(); - - bgReading.value = bundle.getDouble(Intents.EXTRA_BG_ESTIMATE); - bgReading.direction = bundle.getString(Intents.EXTRA_BG_SLOPE_NAME); - bgReading.date = bundle.getLong(Intents.EXTRA_TIMESTAMP); - bgReading.raw = bundle.getDouble(Intents.EXTRA_RAW); - String source = bundle.getString(Intents.XDRIP_DATA_SOURCE_DESCRIPTION, "no Source specified"); - SourceXdripPlugin.getPlugin().setSource(source); - MainApp.getDbHelper().createIfNotExists(bgReading, "XDRIP"); - } - - private void handleNewDataFromGlimp(Intent intent) { - Bundle bundle = intent.getExtras(); - if (bundle == null) return; - - BgReading bgReading = new BgReading(); - - bgReading.value = bundle.getDouble("mySGV"); - bgReading.direction = bundle.getString("myTrend"); - bgReading.date = bundle.getLong("myTimestamp"); - bgReading.raw = 0; - - MainApp.getDbHelper().createIfNotExists(bgReading, "GLIMP"); - } - - private void handleNewDataFromDexcomG5(Intent intent) { - // onHandleIntent Bundle{ data => [{"m_time":1511939180,"m_trend":"NotComputable","m_value":335}]; android.support.content.wakelockid => 95; }Bundle - - Bundle bundle = intent.getExtras(); - if (bundle == null) return; - - BgReading bgReading = new BgReading(); - - String data = bundle.getString("data"); - log.debug("Received Dexcom Data", data); - - try { - JSONArray jsonArray = new JSONArray(data); - log.debug("Received Dexcom Data size:" + jsonArray.length()); - for (int i = 0; i < jsonArray.length(); i++) { - JSONObject json = jsonArray.getJSONObject(i); - bgReading.value = json.getInt("m_value"); - bgReading.direction = json.getString("m_trend"); - bgReading.date = json.getLong("m_time") * 1000L; - bgReading.raw = 0; - boolean isNew = MainApp.getDbHelper().createIfNotExists(bgReading, "DexcomG5"); - if (isNew && SP.getBoolean(R.string.key_dexcomg5_nsupload, false)) { - NSUpload.uploadBg(bgReading); - } - if (isNew && SP.getBoolean(R.string.key_dexcomg5_xdripupload, false)) { - NSUpload.sendToXdrip(bgReading); - } - } - - } catch (JSONException e) { - e.printStackTrace(); - } - } - - private void handleNewDataFromPoctech(Intent intent) { - - Bundle bundle = intent.getExtras(); - if (bundle == null) return; - - BgReading bgReading = new BgReading(); - - String data = bundle.getString("data"); - log.debug("Received Poctech Data", data); - - try { - JSONArray jsonArray = new JSONArray(data); - log.debug("Received Poctech Data size:" + jsonArray.length()); - for (int i = 0; i < jsonArray.length(); i++) { - JSONObject json = jsonArray.getJSONObject(i); - bgReading.value = json.getDouble("current"); - bgReading.direction = json.getString("direction"); - bgReading.date = json.getLong("date"); - bgReading.raw = json.getDouble("raw"); - if (JsonHelper.safeGetString(json, "units", Constants.MGDL).equals("mmol/L")) - bgReading.value = bgReading.value * Constants.MMOLL_TO_MGDL; - boolean isNew = MainApp.getDbHelper().createIfNotExists(bgReading, "Poctech"); - if (isNew && SP.getBoolean(R.string.key_dexcomg5_nsupload, false)) { - NSUpload.uploadBg(bgReading); - } - if (isNew && SP.getBoolean(R.string.key_dexcomg5_xdripupload, false)) { - NSUpload.sendToXdrip(bgReading); - } - } - - } catch (JSONException e) { - e.printStackTrace(); - } - } - - private void handleNewDataFromMM640g(Intent intent) { - Bundle bundle = intent.getExtras(); - if (bundle == null) return; - - final String collection = bundle.getString("collection"); - if (collection == null) return; - - if (collection.equals("entries")) { - final String data = bundle.getString("data"); - - if ((data != null) && (data.length() > 0)) { - try { - final JSONArray json_array = new JSONArray(data); - for (int i = 0; i < json_array.length(); i++) { - final JSONObject json_object = json_array.getJSONObject(i); - final String type = json_object.getString("type"); - switch (type) { - case "sgv": - BgReading bgReading = new BgReading(); - - bgReading.value = json_object.getDouble("sgv"); - bgReading.direction = json_object.getString("direction"); - bgReading.date = json_object.getLong("date"); - bgReading.raw = json_object.getDouble("sgv"); - - MainApp.getDbHelper().createIfNotExists(bgReading, "MM640g"); - break; - default: - log.debug("Unknown entries type: " + type); - } - } - } catch (JSONException e) { - log.error("Got JSON exception: " + e); - } - } - } - } - private void handleNewDataFromNSClient(Intent intent) { Bundle bundles = intent.getExtras(); if (bundles == null) return; @@ -422,20 +194,6 @@ public class DataService extends IntentService { log.error("Unhandled exception", e); } } - // Handle profile - if (intent.getAction().equals(Intents.ACTION_NEW_PROFILE)) { - try { - String activeProfile = bundles.getString("activeprofile"); - String profile = bundles.getString("profile"); - ProfileStore profileStore = new ProfileStore(new JSONObject(profile)); - NSProfilePlugin.getPlugin().storeNewProfile(profileStore); - MainApp.bus().post(new EventNSProfileUpdateGUI()); - if (Config.logIncommingData) - log.debug("Received profileStore: " + activeProfile + " " + profile); - } catch (JSONException e) { - log.error("Unhandled exception", e); - } - } if (intent.getAction().equals(Intents.ACTION_NEW_TREATMENT) || intent.getAction().equals(Intents.ACTION_CHANGED_TREATMENT)) { try { @@ -477,27 +235,6 @@ public class DataService extends IntentService { } } - if (intent.getAction().equals(Intents.ACTION_NEW_SGV)) { - try { - if (bundles.containsKey("sgv")) { - String sgvstring = bundles.getString("sgv"); - JSONObject sgvJson = new JSONObject(sgvstring); - storeSgv(sgvJson); - } - - if (bundles.containsKey("sgvs")) { - String sgvstring = bundles.getString("sgvs"); - JSONArray jsonArray = new JSONArray(sgvstring); - for (int i = 0; i < jsonArray.length(); i++) { - JSONObject sgvJson = jsonArray.getJSONObject(i); - storeSgv(sgvJson); - } - } - } catch (Exception e) { - log.error("Unhandled exception", e); - } - } - if (intent.getAction().equals(Intents.ACTION_NEW_MBG)) { try { if (bundles.containsKey("mbg")) { @@ -580,7 +317,7 @@ public class DataService extends IntentService { } if (eventType.equals(CareportalEvent.ANNOUNCEMENT)) { - long date = JsonHelper.safeGetLong(json,"mills"); + long date = JsonHelper.safeGetLong(json, "mills"); long now = System.currentTimeMillis(); String enteredBy = JsonHelper.safeGetString(json, "enteredBy", ""); String notes = JsonHelper.safeGetString(json, "notes", ""); @@ -600,17 +337,4 @@ public class DataService extends IntentService { log.debug("Adding/Updating new MBG: " + careportalEvent.log()); } - private void storeSgv(JSONObject sgvJson) { - NSSgv nsSgv = new NSSgv(sgvJson); - BgReading bgReading = new BgReading(nsSgv); - MainApp.getDbHelper().createIfNotExists(bgReading, "NS"); - SourceNSClientPlugin.getPlugin().detectSource(JsonHelper.safeGetString(sgvJson, "device"), JsonHelper.safeGetLong(sgvJson, "mills")); - } - - private void handleNewSMS(Intent intent) { - Bundle bundle = intent.getExtras(); - if (bundle == null) return; - MainApp.bus().post(new EventNewSMS(bundle)); - } - } diff --git a/app/src/main/java/info/nightscout/androidaps/data/Profile.java b/app/src/main/java/info/nightscout/androidaps/data/Profile.java index 7412f8ce4c..748710f17a 100644 --- a/app/src/main/java/info/nightscout/androidaps/data/Profile.java +++ b/app/src/main/java/info/nightscout/androidaps/data/Profile.java @@ -52,6 +52,14 @@ public class Profile { protected Profile() { } + @Override + public String toString() { + if (json != null) + return json.toString(); + else + return "Profile has no JSON"; + } + // Constructor from profileStore JSON public Profile(JSONObject json, String units) { init(json, 100, 0); @@ -295,8 +303,6 @@ public class Profile { Integer getShitfTimeSecs(Integer originalTime) { Integer shiftedTime = originalTime + timeshift * 60 * 60; shiftedTime = (shiftedTime + 24 * 60 * 60) % (24 * 60 * 60); - if (timeshift != 0 && Config.logProfile) - log.debug("(Sec) Original time: " + originalTime + " ShiftedTime: " + shiftedTime); return shiftedTime; } diff --git a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java index 5095195872..ba6f2e5dd0 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java @@ -431,6 +431,23 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { return new ArrayList(); } + public List getBgreadingsDataFromTime(long start, long end, boolean ascending) { + try { + Dao daoBgreadings = getDaoBgReadings(); + List bgReadings; + QueryBuilder queryBuilder = daoBgreadings.queryBuilder(); + queryBuilder.orderBy("date", ascending); + Where where = queryBuilder.where(); + where.between("date", start, end).and().gt("value", 38).and().eq("isValid", true); + PreparedQuery preparedQuery = queryBuilder.prepare(); + bgReadings = daoBgreadings.query(preparedQuery); + return bgReadings; + } catch (SQLException e) { + log.error("Unhandled exception", e); + } + return new ArrayList(); + } + public List getAllBgreadingsDataFromTime(long mills, boolean ascending) { try { Dao daoBgreadings = getDaoBgReadings(); @@ -676,7 +693,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { .source(Source.NIGHTSCOUT); createOrUpdate(tempTarget); } catch (JSONException e) { - log.error("Unhandled exception", e); + log.error("Unhandled exception: " + trJson.toString(), e); } } @@ -762,7 +779,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } } } catch (SQLException | JSONException e) { - log.error("Unhandled exception", e); + log.error("Unhandled exception: " + trJson.toString(), e); } } @@ -967,7 +984,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { createOrUpdate(tempBasal); } } catch (JSONException e) { - log.error("Unhandled exception", e); + log.error("Unhandled exception: " + trJson.toString(), e); } } @@ -1345,7 +1362,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { careportalEvent._id = trJson.getString("_id"); createOrUpdate(careportalEvent); } catch (SQLException | JSONException e) { - log.error("Unhandled exception", e); + log.error("Unhandled exception: " + trJson.toString(), e); } } @@ -1520,7 +1537,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { profileSwitch.profilePlugin = trJson.getString("profilePlugin"); createOrUpdate(profileSwitch); } catch (JSONException e) { - log.error("Unhandled exception", e); + log.error("Unhandled exception: " + trJson.toString(), e); } } diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/BgSourceInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/BgSourceInterface.java index a45ab083e7..d42ead7950 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/BgSourceInterface.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/BgSourceInterface.java @@ -1,8 +1,12 @@ package info.nightscout.androidaps.interfaces; +import android.content.Intent; + /** * Created by mike on 20.06.2016. */ public interface BgSourceInterface { boolean advancedFilteringSupported(); + + void handleNewData(Intent intent); } diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/SensitivityInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/SensitivityInterface.java index 81af28eaa4..f4514ad572 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/SensitivityInterface.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/SensitivityInterface.java @@ -1,6 +1,7 @@ package info.nightscout.androidaps.interfaces; import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensResult; +import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; /** * Created by mike on 24.06.2017. @@ -11,6 +12,6 @@ public interface SensitivityInterface { double MIN_HOURS = 1; double MIN_HOURS_FULL_AUTOSENS = 4; - AutosensResult detectSensitivity(long fromTime, long toTime); + AutosensResult detectSensitivity(IobCobCalculatorPlugin plugin, long fromTime, long toTime); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsFragment.java index d45fb10b4e..0fb505bda7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsFragment.java @@ -87,7 +87,6 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL tempBasalCancel.setOnClickListener(this); fill.setOnClickListener(this); history.setOnClickListener(this); - history.setVisibility(MainApp.devBranch ? View.VISIBLE : View.GONE); tddStats.setOnClickListener(this); updateGUI(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/Dialogs/NewNSTreatmentDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/Dialogs/NewNSTreatmentDialog.java index 46c1e3666d..666a4a27a3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/Dialogs/NewNSTreatmentDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/Dialogs/NewNSTreatmentDialog.java @@ -206,8 +206,11 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick public void onItemSelected(AdapterView parent, View view, int position, long id) { double defaultDuration; double defaultTarget = 0; - if (profile != null) { + if (profile != null && editTemptarget.getValue() == bg) { defaultTarget = bg; + } else { + //prevent changes on screen rotate + defaultTarget = editTemptarget.getValue(); } boolean erase = false; @@ -222,6 +225,8 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick } else if (MainApp.gs(R.string.hypo).equals(reasonList.get(position))) { defaultDuration = helper.determineHypoTTDuration(); defaultTarget = helper.determineHypoTT(units); + } else if (editDuration.getValue() != 0) { + defaultDuration = editDuration.getValue(); } else { defaultDuration = 0; erase = true; @@ -258,7 +263,6 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick if (sensorRadioButton.isChecked()) meterRadioButton.setChecked(true); } }; - editBg = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_bginput); editTemptarget = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_temptarget); if (profile == null) { @@ -271,9 +275,14 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick editBg.setParams(bg, 0d, 500d, 1d, new DecimalFormat("0"), false, bgTextWatcher); editTemptarget.setParams(bg, 0d, 500d, 1d, new DecimalFormat("0"), false); } + sensorRadioButton.setOnCheckedChangeListener((buttonView, isChecked) -> { Double bg1 = Profile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData() != null ? GlucoseStatus.getGlucoseStatusData().glucose : 0d, profile.getUnits()); - editBg.setValue(bg1); + if (savedInstanceState != null && savedInstanceState.getDouble("editBg") != bg1) { + editBg.setValue(savedInstanceState.getDouble("editBg")); + } else { + editBg.setValue(bg1); + } }); Integer maxCarbs = MainApp.getConstraintChecker().getMaxCarbsAllowed().value(); @@ -378,6 +387,25 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick setCancelable(true); getDialog().setCanceledOnTouchOutside(false); + //recovering state if there is something + // only numberPickers and editTexts + if (savedInstanceState != null) { + editBg.setValue(savedInstanceState.getDouble("editBg")); + editTemptarget.setValue(savedInstanceState.getDouble("editTemptarget")); + notesEdit.setText(savedInstanceState.getString("notesEdit")); + editCarbs.setValue(savedInstanceState.getDouble("editCarbs")); + editCarbs.setValue(savedInstanceState.getDouble("editCarbs")); + editInsulin.setValue(savedInstanceState.getDouble("editInsulin")); + editDuration.setValue(savedInstanceState.getDouble("editDuration")); + editPercent.setValue(savedInstanceState.getDouble("editPercent")); + editAbsolute.setValue(savedInstanceState.getDouble("editAbsolute")); + editCarbTime.setValue(savedInstanceState.getDouble("editCarbTime")); + editPercentage.setValue(savedInstanceState.getDouble("editPercentage")); + editTimeshift.setValue(savedInstanceState.getDouble("editTimeshift")); + // time and date + dateButton.setText(savedInstanceState.getString("dateButton")); + timeButton.setText(savedInstanceState.getString("timeButton")); + } return view; } @@ -772,4 +800,22 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick } } + @Override + public void onSaveInstanceState(Bundle savedInstanceState) { + savedInstanceState.putString("notesEdit", notesEdit.getText().toString()); + savedInstanceState.putString("dateButton", dateButton.getText().toString()); + savedInstanceState.putString("timeButton", timeButton.getText().toString()); + savedInstanceState.putDouble("editBg", editBg.getValue()); + savedInstanceState.putDouble("editCarbs", editCarbs.getValue()); + savedInstanceState.putDouble("editInsulin", editInsulin.getValue()); + savedInstanceState.putDouble("editDuration", editDuration.getValue()); + savedInstanceState.putDouble("editPercent", editPercent.getValue()); + savedInstanceState.putDouble("editAbsolute", editAbsolute.getValue()); + savedInstanceState.putDouble("editCarbTime", editCarbTime.getValue()); + savedInstanceState.putDouble("editTemptarget", editTemptarget.getValue()); + savedInstanceState.putDouble("editPercentage", editPercentage.getValue()); + savedInstanceState.putDouble("editTimeshift", editTimeshift.getValue()); + super.onSaveInstanceState(savedInstanceState); + } + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/AutosensData.java b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/AutosensData.java index dd2c50d8c9..95a3976155 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/AutosensData.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/AutosensData.java @@ -26,7 +26,7 @@ import info.nightscout.utils.SP; */ public class AutosensData implements DataPointWithLabelInterface { - private static Logger log = LoggerFactory.getLogger("AUTOSENS"); + private static Logger log = LoggerFactory.getLogger(Constants.AUTOSENS); public void setChartTime(long chartTime) { this.chartTime = chartTime; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/AutosensResult.java b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/AutosensResult.java index c83095e620..92a5ad1217 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/AutosensResult.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/AutosensResult.java @@ -5,11 +5,13 @@ import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import info.nightscout.androidaps.Constants; + /** * Created by mike on 06.01.2017. */ public class AutosensResult { - private static Logger log = LoggerFactory.getLogger("AUTOSENS"); + private static Logger log = LoggerFactory.getLogger(Constants.AUTOSENS); //default values to show when autosens algorithm is not called public double ratio = 1d; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobCalculatorPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobCalculatorPlugin.java index 096668b996..daabef245a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobCalculatorPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobCalculatorPlugin.java @@ -1,6 +1,7 @@ package info.nightscout.androidaps.plugins.IobCobCalculator; import android.os.SystemClock; +import android.provider.SyncStateContract; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.util.LongSparseArray; @@ -48,7 +49,7 @@ import static info.nightscout.utils.DateUtil.now; */ public class IobCobCalculatorPlugin extends PluginBase { - private Logger log = LoggerFactory.getLogger("AUTOSENS"); + private Logger log = LoggerFactory.getLogger(Constants.AUTOSENS); private static IobCobCalculatorPlugin plugin = null; @@ -98,6 +99,10 @@ public class IobCobCalculatorPlugin extends PluginBase { return autosensDataTable; } + public List getBgReadings() { + return bgReadings; + } + public List getBucketedData() { return bucketed_data; } @@ -136,13 +141,10 @@ public class IobCobCalculatorPlugin extends PluginBase { return rounded; } - void loadBgData(long start) { - if (start < oldestDataAvailable()) { - start = oldestDataAvailable(); - log.debug("Limiting BG data to oldest data available: " + DateUtil.dateAndTimeString(start)); - } - bgReadings = MainApp.getDbHelper().getBgreadingsDataFromTime((long) (start - 60 * 60 * 1000L * (24 + dia)), false); - log.debug("BG data loaded. Size: " + bgReadings.size() + " Start date: " + DateUtil.dateAndTimeString(start)); + void loadBgData(long now) { + long start = (long) (now - 60 * 60 * 1000L * (24 + dia)); + bgReadings = MainApp.getDbHelper().getBgreadingsDataFromTime(start, now, false); + log.debug("BG data loaded. Size: " + bgReadings.size() + " Start date: " + DateUtil.dateAndTimeString(start) + " End date: " + DateUtil.dateAndTimeString(now)); } private boolean isAbout5minData() { @@ -294,12 +296,19 @@ public class IobCobCalculatorPlugin extends PluginBase { log.debug("Bucketed data created. Size: " + bucketed_data.size()); } - public long oldestDataAvailable() { - long now = System.currentTimeMillis(); + public long calculateDetectionStart(long from, boolean limitDataToOldestAvailable) { + Profile profile = MainApp.getConfigBuilder().getProfile(from); + double dia = Constants.defaultDIA; + if (profile != null) dia = profile.getDia(); long oldestDataAvailable = TreatmentsPlugin.getPlugin().oldestDataAvailable(); - long getBGDataFrom = Math.max(oldestDataAvailable, (long) (now - T.hours(1).msecs() * (24 + MainApp.getConfigBuilder().getProfile().getDia()))); - log.debug("Limiting data to oldest available temps: " + new Date(oldestDataAvailable).toString()); + long getBGDataFrom; + if (limitDataToOldestAvailable) { + getBGDataFrom = Math.max(oldestDataAvailable, (long) (from - T.hours(1).msecs() * (24 + dia))); + if (getBGDataFrom == oldestDataAvailable) + log.debug("Limiting data to oldest available temps: " + new Date(oldestDataAvailable).toString()); + } else + getBGDataFrom = (long) (from - T.hours(1).msecs() * (24 + dia)); return getBGDataFrom; } @@ -403,7 +412,7 @@ public class IobCobCalculatorPlugin extends PluginBase { @Nullable public AutosensData getLastAutosensDataSynchronized(String reason) { - if (thread != null && thread.isAlive()) { + if (thread != null && thread.isAlive()) { log.debug("AUTOSENSDATA is waiting for calculation thread: " + reason); try { thread.join(5000); @@ -510,7 +519,7 @@ public class IobCobCalculatorPlugin extends PluginBase { public AutosensResult detectSensitivityWithLock(long fromTime, long toTime) { synchronized (dataLock) { - return ConfigBuilderPlugin.getActiveSensitivity().detectSensitivity(fromTime, toTime); + return ConfigBuilderPlugin.getActiveSensitivity().detectSensitivity(this, fromTime, toTime); } } @@ -529,7 +538,7 @@ public class IobCobCalculatorPlugin extends PluginBase { log.debug("Ignoring event for non default instance"); return; } - runCalculation("onEventAppInitialized", System.currentTimeMillis(), true, ev); + runCalculation("onEventAppInitialized", System.currentTimeMillis(), true, true, ev); } @Subscribe @@ -540,10 +549,10 @@ public class IobCobCalculatorPlugin extends PluginBase { return; } stopCalculation("onEventNewBG"); - runCalculation("onEventNewBG", System.currentTimeMillis(), true, ev); + runCalculation("onEventNewBG", System.currentTimeMillis(), true, true, ev); } - private void stopCalculation(String from) { + public void stopCalculation(String from) { if (thread != null && thread.getState() != Thread.State.TERMINATED) { stopCalculationTrigger = true; log.debug("Stopping calculation thread: " + from); @@ -554,13 +563,13 @@ public class IobCobCalculatorPlugin extends PluginBase { } } - public void runCalculation(String from, long start, boolean bgDataReload, Event cause) { - log.debug("Starting calculation thread: " + from); + public void runCalculation(String from, long end, boolean bgDataReload, boolean limitDataToOldestAvailable, Event cause) { + log.debug("Starting calculation thread: " + from + " to " + DateUtil.dateAndTimeString(end)); if (thread == null || thread.getState() == Thread.State.TERMINATED) { if (SensitivityOref1Plugin.getPlugin().isEnabled(PluginType.SENSITIVITY)) - thread = new IobCobOref1Thread(this, from, start, bgDataReload, cause); + thread = new IobCobOref1Thread(this, from, end, bgDataReload, limitDataToOldestAvailable, cause); else - thread = new IobCobThread(this, from, start, bgDataReload, cause); + thread = new IobCobThread(this, from, end, bgDataReload, limitDataToOldestAvailable, cause); thread.start(); } } @@ -586,7 +595,7 @@ public class IobCobCalculatorPlugin extends PluginBase { iobTable = new LongSparseArray<>(); autosensDataTable = new LongSparseArray<>(); } - runCalculation("onNewProfile", System.currentTimeMillis(), false, ev); + runCalculation("onNewProfile", System.currentTimeMillis(), false, true, ev); } @Subscribe @@ -609,7 +618,7 @@ public class IobCobCalculatorPlugin extends PluginBase { iobTable = new LongSparseArray<>(); autosensDataTable = new LongSparseArray<>(); } - runCalculation("onEventPreferenceChange", System.currentTimeMillis(), false, ev); + runCalculation("onEventPreferenceChange", System.currentTimeMillis(), false, true, ev); } } @@ -625,7 +634,7 @@ public class IobCobCalculatorPlugin extends PluginBase { iobTable = new LongSparseArray<>(); autosensDataTable = new LongSparseArray<>(); } - runCalculation("onEventConfigBuilderChange", System.currentTimeMillis(), false, ev); + runCalculation("onEventConfigBuilderChange", System.currentTimeMillis(), false, true, ev); } // When historical data is changed (comming from NS etc) finished calculations after this date must be invalidated @@ -669,7 +678,7 @@ public class IobCobCalculatorPlugin extends PluginBase { } } } - runCalculation("onEventNewHistoryData", System.currentTimeMillis(), false, ev); + runCalculation("onEventNewHistoryData", System.currentTimeMillis(), false, true, ev); //log.debug("Releasing onNewHistoryData"); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobOref1Thread.java b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobOref1Thread.java index d10d0ebe29..a51e0e95f4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobOref1Thread.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobOref1Thread.java @@ -43,24 +43,26 @@ import static java.util.Calendar.MINUTE; */ public class IobCobOref1Thread extends Thread { - private static Logger log = LoggerFactory.getLogger("AUTOSENS"); + private static Logger log = LoggerFactory.getLogger(Constants.AUTOSENS); private final Event cause; private IobCobCalculatorPlugin iobCobCalculatorPlugin; private boolean bgDataReload; + private boolean limitDataToOldestAvailable; private String from; - private long start; + private long end; private PowerManager.WakeLock mWakeLock; - public IobCobOref1Thread(IobCobCalculatorPlugin plugin, String from, long start, boolean bgDataReload, Event cause) { + public IobCobOref1Thread(IobCobCalculatorPlugin plugin, String from, long end, boolean bgDataReload, boolean limitDataToOldestAvailable, Event cause) { super(); this.iobCobCalculatorPlugin = plugin; this.bgDataReload = bgDataReload; + this.limitDataToOldestAvailable = limitDataToOldestAvailable; this.from = from; this.cause = cause; - this.start = start; + this.end = end; PowerManager powerManager = (PowerManager) MainApp.instance().getApplicationContext().getSystemService(Context.POWER_SERVICE); mWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "iobCobThread"); @@ -81,15 +83,15 @@ public class IobCobOref1Thread extends Thread { } //log.debug("Locking calculateSensitivityData"); - long oldestTimeWithData = iobCobCalculatorPlugin.oldestDataAvailable(); + long oldestTimeWithData = iobCobCalculatorPlugin.calculateDetectionStart(end, limitDataToOldestAvailable); synchronized (iobCobCalculatorPlugin.dataLock) { if (bgDataReload) { - iobCobCalculatorPlugin.loadBgData(start); + iobCobCalculatorPlugin.loadBgData(end); iobCobCalculatorPlugin.createBucketedData(); } List bucketed_data = iobCobCalculatorPlugin.getBucketedData(); - LongSparseArray autosensDataTable = IobCobCalculatorPlugin.getPlugin().getAutosensDataTable(); + LongSparseArray autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable(); if (bucketed_data == null || bucketed_data.size() < 3) { log.debug("Aborting calculation thread (No bucketed data available): " + from); @@ -166,7 +168,7 @@ public class IobCobOref1Thread extends Thread { // https://github.com/openaps/oref0/blob/master/lib/determine-basal/cob-autosens.js#L169 if (i < bucketed_data.size() - 16) { // we need 1h of data to calculate minDeviationSlope long hourago = bgTime + 10 * 1000 - 60 * 60 * 1000L; - AutosensData hourAgoData = IobCobCalculatorPlugin.getPlugin().getAutosensData(hourago); + AutosensData hourAgoData = iobCobCalculatorPlugin.getAutosensData(hourago); if (hourAgoData != null) { int initialIndex = autosensDataTable.indexOfKey(hourAgoData.time); if (Config.logAutosensData) @@ -339,7 +341,7 @@ public class IobCobOref1Thread extends Thread { if (bgTime < now()) autosensDataTable.put(bgTime, autosensData); if (Config.logAutosensData) - log.debug("Running detectSensitivity from: " + DateUtil.dateAndTimeString(oldestTimeWithData) + " to: " + DateUtil.dateAndTimeString(bgTime) + " lastDataTime:" + IobCobCalculatorPlugin.getPlugin().lastDataTime()); + log.debug("Running detectSensitivity from: " + DateUtil.dateAndTimeString(oldestTimeWithData) + " to: " + DateUtil.dateAndTimeString(bgTime) + " lastDataTime:" + iobCobCalculatorPlugin.lastDataTime()); AutosensResult sensitivity = iobCobCalculatorPlugin.detectSensitivityWithLock(oldestTimeWithData, bgTime); if (Config.logAutosensData) log.debug("Sensitivity result: " + sensitivity.toString()); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobThread.java b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobThread.java index d60efb5bc6..3c072abb99 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobThread.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobThread.java @@ -42,24 +42,26 @@ import static info.nightscout.utils.DateUtil.now; */ public class IobCobThread extends Thread { - private static Logger log = LoggerFactory.getLogger("AUTOSENS"); + private static Logger log = LoggerFactory.getLogger(Constants.AUTOSENS); private final Event cause; private IobCobCalculatorPlugin iobCobCalculatorPlugin; private boolean bgDataReload; + private boolean limitDataToOldestAvailable; private String from; - private long start; + private long end; private PowerManager.WakeLock mWakeLock; - public IobCobThread(IobCobCalculatorPlugin plugin, String from, long start, boolean bgDataReload, Event cause) { + public IobCobThread(IobCobCalculatorPlugin plugin, String from, long end, boolean bgDataReload, boolean limitDataToOldestAvailable, Event cause) { super(); this.iobCobCalculatorPlugin = plugin; this.bgDataReload = bgDataReload; + this.limitDataToOldestAvailable = limitDataToOldestAvailable; this.from = from; this.cause = cause; - this.start = start; + this.end = end; PowerManager powerManager = (PowerManager) MainApp.instance().getApplicationContext().getSystemService(Context.POWER_SERVICE); mWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "iobCobThread"); @@ -80,15 +82,15 @@ public class IobCobThread extends Thread { } //log.debug("Locking calculateSensitivityData"); - long oldestTimeWithData = iobCobCalculatorPlugin.oldestDataAvailable(); + long oldestTimeWithData = iobCobCalculatorPlugin.calculateDetectionStart(end, limitDataToOldestAvailable); synchronized (iobCobCalculatorPlugin.dataLock) { if (bgDataReload) { - iobCobCalculatorPlugin.loadBgData(start); + iobCobCalculatorPlugin.loadBgData(end); iobCobCalculatorPlugin.createBucketedData(); } List bucketed_data = iobCobCalculatorPlugin.getBucketedData(); - LongSparseArray autosensDataTable = IobCobCalculatorPlugin.getPlugin().getAutosensDataTable(); + LongSparseArray autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable(); if (bucketed_data == null || bucketed_data.size() < 3) { log.debug("Aborting calculation thread (No bucketed data available): " + from); @@ -165,7 +167,7 @@ public class IobCobThread extends Thread { // https://github.com/openaps/oref0/blob/master/lib/determine-basal/cob-autosens.js#L169 if (i < bucketed_data.size() - 16) { // we need 1h of data to calculate minDeviationSlope long hourago = bgTime + 10 * 1000 - 60 * 60 * 1000L; - AutosensData hourAgoData = IobCobCalculatorPlugin.getPlugin().getAutosensData(hourago); + AutosensData hourAgoData = iobCobCalculatorPlugin.getAutosensData(hourago); if (hourAgoData != null) { int initialIndex = autosensDataTable.indexOfKey(hourAgoData.time); if (Config.logAutosensData) @@ -266,7 +268,7 @@ public class IobCobThread extends Thread { if (bgTime < now()) autosensDataTable.put(bgTime, autosensData); if (Config.logAutosensData) - log.debug("Running detectSensitivity from: " + DateUtil.dateAndTimeString(oldestTimeWithData) + " to: " + DateUtil.dateAndTimeString(bgTime) + " lastDataTime:" + IobCobCalculatorPlugin.getPlugin().lastDataTime()); + log.debug("Running detectSensitivity from: " + DateUtil.dateAndTimeString(oldestTimeWithData) + " to: " + DateUtil.dateAndTimeString(bgTime) + " lastDataTime:" + iobCobCalculatorPlugin.lastDataTime()); AutosensResult sensitivity = iobCobCalculatorPlugin.detectSensitivityWithLock(oldestTimeWithData, bgTime); if (Config.logAutosensData) log.debug("Sensitivity result: " + sensitivity.toString()); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAPlugin.java index 74d15cd2a4..f73752faa2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAPlugin.java @@ -179,6 +179,7 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface { MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openaps_noasdata))); return; } + lastAutosensResult = autosensData.autosensResult; } else { lastAutosensResult = new AutosensResult(); lastAutosensResult.sensResult = "autosens disabled"; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewCarbsDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewCarbsDialog.java index 26f46081ea..b51270938d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewCarbsDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewCarbsDialog.java @@ -157,13 +157,22 @@ public class NewCarbsDialog extends DialogFragment implements OnClickListener, C BgReading bgReading = DatabaseHelper.actualBg(); if (bgReading != null && bgReading.value < 72) { - startHypoTTCheckbox.setOnCheckedChangeListener(null); startHypoTTCheckbox.setChecked(true); + // see #onCheckedChanged why listeners are registered like this + startHypoTTCheckbox.setOnClickListener(this); + } else { + startHypoTTCheckbox.setOnCheckedChangeListener(this); } - startHypoTTCheckbox.setOnClickListener(this); setCancelable(true); getDialog().setCanceledOnTouchOutside(false); + + //recovering state if there is something + if (savedInstanceState != null) { + editCarbs.setValue(savedInstanceState.getDouble("editCarbs")); + editTime.setValue(savedInstanceState.getDouble("editTime")); + editDuration.setValue(savedInstanceState.getDouble("editDuration")); + } return view; } @@ -171,6 +180,19 @@ public class NewCarbsDialog extends DialogFragment implements OnClickListener, C return value > 0 ? "+" + value : String.valueOf(value); } + + @Override + public void onSaveInstanceState(Bundle carbsDialogState) { + carbsDialogState.putBoolean("startActivityTTCheckbox",startActivityTTCheckbox.isChecked()); + carbsDialogState.putBoolean("startEatingSoonTTCheckbox", startEatingSoonTTCheckbox.isChecked()); + carbsDialogState.putBoolean("startHypoTTCheckbox", startHypoTTCheckbox.isChecked()); + carbsDialogState.putDouble("editTime", editTime.getValue()); + carbsDialogState.putDouble("editDuration", editDuration.getValue()); + carbsDialogState.putDouble("editCarbs", editCarbs.getValue()); + super.onSaveInstanceState(carbsDialogState); + } + + @Override public synchronized void onClick(View view) { switch (view.getId()) { @@ -228,6 +250,8 @@ public class NewCarbsDialog extends DialogFragment implements OnClickListener, C } } + + @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // Logic to disable a selected radio when pressed: when a checked radio diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialog.java index 032104e103..0ad53d99a4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialog.java @@ -147,6 +147,23 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com MainApp.bus().unregister(this); } + @Override + public void onSaveInstanceState(Bundle savedInstanceState) { + savedInstanceState.putBoolean("bgCheckbox", bgCheckbox.isChecked()); + savedInstanceState.putBoolean("ttCheckbox", ttCheckbox.isChecked()); + savedInstanceState.putBoolean("bolusIobCheckbox", bolusIobCheckbox.isChecked()); + savedInstanceState.putBoolean("basalIobCheckbox", basalIobCheckbox.isChecked()); + savedInstanceState.putBoolean("bgtrendCheckbox", bgtrendCheckbox.isChecked()); + savedInstanceState.putBoolean("cobCheckbox", cobCheckbox.isChecked()); + savedInstanceState.putDouble("editBg", editBg.getValue()); + savedInstanceState.putDouble("editCarbs", editCarbs.getValue()); + savedInstanceState.putDouble("editCorr", editCorr.getValue()); + savedInstanceState.putDouble("editCarbTime", editCarbTime.getValue()); + super.onSaveInstanceState(savedInstanceState); + } + + + @Subscribe public void onStatusEvent(final EventNewBG e) { Activity activity = getActivity(); @@ -259,6 +276,13 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com setCancelable(true); getDialog().setCanceledOnTouchOutside(false); + //recovering state if there is something + if (savedInstanceState != null) { + editCarbs.setValue(savedInstanceState.getDouble("editCarbs")); + editBg.setValue(savedInstanceState.getDouble("editBg")); + editCarbTime.setValue(savedInstanceState.getDouble("editCarbTime")); + editCorr.setValue(savedInstanceState.getDouble("editCorr")); + } return view; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java index 2b4ab247b8..b5e97a59d8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java @@ -85,6 +85,7 @@ import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialo import info.nightscout.androidaps.plugins.Careportal.OptionsToShow; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin; +import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.IobCobCalculator.CobInfo; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; @@ -125,7 +126,7 @@ import info.nightscout.utils.ToastUtils; import static info.nightscout.utils.DateUtil.now; public class OverviewFragment extends Fragment implements View.OnClickListener, View.OnLongClickListener { - private static Logger log = LoggerFactory.getLogger(OverviewFragment.class); + private static Logger log = LoggerFactory.getLogger(Constants.OVERVIEW); TextView timeView; TextView bgView; @@ -200,143 +201,136 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - try { - //check screen width - final DisplayMetrics dm = new DisplayMetrics(); - getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm); - int screen_width = dm.widthPixels; - int screen_height = dm.heightPixels; - smallWidth = screen_width <= Constants.SMALL_WIDTH; - smallHeight = screen_height <= Constants.SMALL_HEIGHT; - boolean landscape = screen_height < screen_width; + //check screen width + final DisplayMetrics dm = new DisplayMetrics(); + getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm); + int screen_width = dm.widthPixels; + int screen_height = dm.heightPixels; + smallWidth = screen_width <= Constants.SMALL_WIDTH; + smallHeight = screen_height <= Constants.SMALL_HEIGHT; + boolean landscape = screen_height < screen_width; - View view; + View view; - if (MainApp.sResources.getBoolean(R.bool.isTablet) && (Config.NSCLIENT || Config.G5UPLOADER)) { - view = inflater.inflate(R.layout.overview_fragment_nsclient_tablet, container, false); - } else if (Config.NSCLIENT || Config.G5UPLOADER) { - view = inflater.inflate(R.layout.overview_fragment_nsclient, container, false); - shorttextmode = true; - } else if (smallHeight || landscape) { - view = inflater.inflate(R.layout.overview_fragment_smallheight, container, false); - } else { - view = inflater.inflate(R.layout.overview_fragment, container, false); - } - - timeView = (TextView) view.findViewById(R.id.overview_time); - bgView = (TextView) view.findViewById(R.id.overview_bg); - arrowView = (TextView) view.findViewById(R.id.overview_arrow); - if (smallWidth) { - arrowView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 35); - } - sensitivityView = (TextView) view.findViewById(R.id.overview_sensitivity); - timeAgoView = (TextView) view.findViewById(R.id.overview_timeago); - timeAgoShortView = (TextView) view.findViewById(R.id.overview_timeagoshort); - deltaView = (TextView) view.findViewById(R.id.overview_delta); - deltaShortView = (TextView) view.findViewById(R.id.overview_deltashort); - avgdeltaView = (TextView) view.findViewById(R.id.overview_avgdelta); - baseBasalView = (TextView) view.findViewById(R.id.overview_basebasal); - extendedBolusView = (TextView) view.findViewById(R.id.overview_extendedbolus); - activeProfileView = (TextView) view.findViewById(R.id.overview_activeprofile); - pumpStatusView = (TextView) view.findViewById(R.id.overview_pumpstatus); - pumpDeviceStatusView = (TextView) view.findViewById(R.id.overview_pump); - openapsDeviceStatusView = (TextView) view.findViewById(R.id.overview_openaps); - uploaderDeviceStatusView = (TextView) view.findViewById(R.id.overview_uploader); - iobCalculationProgressView = (TextView) view.findViewById(R.id.overview_iobcalculationprogess); - loopStatusLayout = (LinearLayout) view.findViewById(R.id.overview_looplayout); - pumpStatusLayout = (LinearLayout) view.findViewById(R.id.overview_pumpstatuslayout); - - pumpStatusView.setBackgroundColor(MainApp.gc(R.color.colorInitializingBorder)); - - iobView = (TextView) view.findViewById(R.id.overview_iob); - cobView = (TextView) view.findViewById(R.id.overview_cob); - apsModeView = (TextView) view.findViewById(R.id.overview_apsmode); - tempTargetView = (TextView) view.findViewById(R.id.overview_temptarget); - - iage = (TextView) view.findViewById(R.id.careportal_insulinage); - cage = (TextView) view.findViewById(R.id.careportal_canulaage); - sage = (TextView) view.findViewById(R.id.careportal_sensorage); - pbage = (TextView) view.findViewById(R.id.careportal_pbage); - - bgGraph = (GraphView) view.findViewById(R.id.overview_bggraph); - iobGraph = (GraphView) view.findViewById(R.id.overview_iobgraph); - - treatmentButton = (SingleClickButton) view.findViewById(R.id.overview_treatmentbutton); - treatmentButton.setOnClickListener(this); - wizardButton = (SingleClickButton) view.findViewById(R.id.overview_wizardbutton); - wizardButton.setOnClickListener(this); - insulinButton = (SingleClickButton) view.findViewById(R.id.overview_insulinbutton); - if (insulinButton != null) - insulinButton.setOnClickListener(this); - carbsButton = (SingleClickButton) view.findViewById(R.id.overview_carbsbutton); - if (carbsButton != null) - carbsButton.setOnClickListener(this); - acceptTempButton = (SingleClickButton) view.findViewById(R.id.overview_accepttempbutton); - if (acceptTempButton != null) - acceptTempButton.setOnClickListener(this); - quickWizardButton = (SingleClickButton) view.findViewById(R.id.overview_quickwizardbutton); - quickWizardButton.setOnClickListener(this); - quickWizardButton.setOnLongClickListener(this); - calibrationButton = (SingleClickButton) view.findViewById(R.id.overview_calibrationbutton); - if (calibrationButton != null) - calibrationButton.setOnClickListener(this); - cgmButton = (SingleClickButton) view.findViewById(R.id.overview_cgmbutton); - if (cgmButton != null) - cgmButton.setOnClickListener(this); - - acceptTempLayout = (LinearLayout) view.findViewById(R.id.overview_accepttemplayout); - - notificationsView = (RecyclerView) view.findViewById(R.id.overview_notifications); - notificationsView.setHasFixedSize(false); - llm = new LinearLayoutManager(view.getContext()); - notificationsView.setLayoutManager(llm); - - int axisWidth = 50; - - if (dm.densityDpi <= 120) - axisWidth = 3; - else if (dm.densityDpi <= 160) - axisWidth = 10; - else if (dm.densityDpi <= 320) - axisWidth = 35; - else if (dm.densityDpi <= 420) - axisWidth = 50; - else if (dm.densityDpi <= 560) - axisWidth = 70; - else - axisWidth = 80; - - bgGraph.getGridLabelRenderer().setGridColor(MainApp.gc(R.color.graphgrid)); - bgGraph.getGridLabelRenderer().reloadStyles(); - iobGraph.getGridLabelRenderer().setGridColor(MainApp.gc(R.color.graphgrid)); - iobGraph.getGridLabelRenderer().reloadStyles(); - iobGraph.getGridLabelRenderer().setHorizontalLabelsVisible(false); - bgGraph.getGridLabelRenderer().setLabelVerticalWidth(axisWidth); - iobGraph.getGridLabelRenderer().setLabelVerticalWidth(axisWidth); - iobGraph.getGridLabelRenderer().setNumVerticalLabels(3); - - rangeToDisplay = SP.getInt(R.string.key_rangetodisplay, 6); - - bgGraph.setOnLongClickListener(new View.OnLongClickListener() { - @Override - public boolean onLongClick(View v) { - rangeToDisplay += 6; - rangeToDisplay = rangeToDisplay > 24 ? 6 : rangeToDisplay; - SP.putInt(R.string.key_rangetodisplay, rangeToDisplay); - updateGUI("rangeChange"); - return false; - } - }); - - setupChartMenu(view); - - return view; - } catch (Exception e) { - FabricPrivacy.logException(e); - log.debug("Runtime Exception", e); + if (MainApp.sResources.getBoolean(R.bool.isTablet) && (Config.NSCLIENT || Config.G5UPLOADER)) { + view = inflater.inflate(R.layout.overview_fragment_nsclient_tablet, container, false); + } else if (Config.NSCLIENT || Config.G5UPLOADER) { + view = inflater.inflate(R.layout.overview_fragment_nsclient, container, false); + shorttextmode = true; + } else if (smallHeight || landscape) { + view = inflater.inflate(R.layout.overview_fragment_smallheight, container, false); + } else { + view = inflater.inflate(R.layout.overview_fragment, container, false); } - return null; + timeView = (TextView) view.findViewById(R.id.overview_time); + bgView = (TextView) view.findViewById(R.id.overview_bg); + arrowView = (TextView) view.findViewById(R.id.overview_arrow); + if (smallWidth) { + arrowView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 35); + } + sensitivityView = (TextView) view.findViewById(R.id.overview_sensitivity); + timeAgoView = (TextView) view.findViewById(R.id.overview_timeago); + timeAgoShortView = (TextView) view.findViewById(R.id.overview_timeagoshort); + deltaView = (TextView) view.findViewById(R.id.overview_delta); + deltaShortView = (TextView) view.findViewById(R.id.overview_deltashort); + avgdeltaView = (TextView) view.findViewById(R.id.overview_avgdelta); + baseBasalView = (TextView) view.findViewById(R.id.overview_basebasal); + extendedBolusView = (TextView) view.findViewById(R.id.overview_extendedbolus); + activeProfileView = (TextView) view.findViewById(R.id.overview_activeprofile); + pumpStatusView = (TextView) view.findViewById(R.id.overview_pumpstatus); + pumpDeviceStatusView = (TextView) view.findViewById(R.id.overview_pump); + openapsDeviceStatusView = (TextView) view.findViewById(R.id.overview_openaps); + uploaderDeviceStatusView = (TextView) view.findViewById(R.id.overview_uploader); + iobCalculationProgressView = (TextView) view.findViewById(R.id.overview_iobcalculationprogess); + loopStatusLayout = (LinearLayout) view.findViewById(R.id.overview_looplayout); + pumpStatusLayout = (LinearLayout) view.findViewById(R.id.overview_pumpstatuslayout); + + pumpStatusView.setBackgroundColor(MainApp.gc(R.color.colorInitializingBorder)); + + iobView = (TextView) view.findViewById(R.id.overview_iob); + cobView = (TextView) view.findViewById(R.id.overview_cob); + apsModeView = (TextView) view.findViewById(R.id.overview_apsmode); + tempTargetView = (TextView) view.findViewById(R.id.overview_temptarget); + + iage = (TextView) view.findViewById(R.id.careportal_insulinage); + cage = (TextView) view.findViewById(R.id.careportal_canulaage); + sage = (TextView) view.findViewById(R.id.careportal_sensorage); + pbage = (TextView) view.findViewById(R.id.careportal_pbage); + + bgGraph = (GraphView) view.findViewById(R.id.overview_bggraph); + iobGraph = (GraphView) view.findViewById(R.id.overview_iobgraph); + + treatmentButton = (SingleClickButton) view.findViewById(R.id.overview_treatmentbutton); + treatmentButton.setOnClickListener(this); + wizardButton = (SingleClickButton) view.findViewById(R.id.overview_wizardbutton); + wizardButton.setOnClickListener(this); + insulinButton = (SingleClickButton) view.findViewById(R.id.overview_insulinbutton); + if (insulinButton != null) + insulinButton.setOnClickListener(this); + carbsButton = (SingleClickButton) view.findViewById(R.id.overview_carbsbutton); + if (carbsButton != null) + carbsButton.setOnClickListener(this); + acceptTempButton = (SingleClickButton) view.findViewById(R.id.overview_accepttempbutton); + if (acceptTempButton != null) + acceptTempButton.setOnClickListener(this); + quickWizardButton = (SingleClickButton) view.findViewById(R.id.overview_quickwizardbutton); + quickWizardButton.setOnClickListener(this); + quickWizardButton.setOnLongClickListener(this); + calibrationButton = (SingleClickButton) view.findViewById(R.id.overview_calibrationbutton); + if (calibrationButton != null) + calibrationButton.setOnClickListener(this); + cgmButton = (SingleClickButton) view.findViewById(R.id.overview_cgmbutton); + if (cgmButton != null) + cgmButton.setOnClickListener(this); + + acceptTempLayout = (LinearLayout) view.findViewById(R.id.overview_accepttemplayout); + + notificationsView = (RecyclerView) view.findViewById(R.id.overview_notifications); + notificationsView.setHasFixedSize(false); + llm = new LinearLayoutManager(view.getContext()); + notificationsView.setLayoutManager(llm); + + int axisWidth = 50; + + if (dm.densityDpi <= 120) + axisWidth = 3; + else if (dm.densityDpi <= 160) + axisWidth = 10; + else if (dm.densityDpi <= 320) + axisWidth = 35; + else if (dm.densityDpi <= 420) + axisWidth = 50; + else if (dm.densityDpi <= 560) + axisWidth = 70; + else + axisWidth = 80; + + bgGraph.getGridLabelRenderer().setGridColor(MainApp.gc(R.color.graphgrid)); + bgGraph.getGridLabelRenderer().reloadStyles(); + iobGraph.getGridLabelRenderer().setGridColor(MainApp.gc(R.color.graphgrid)); + iobGraph.getGridLabelRenderer().reloadStyles(); + iobGraph.getGridLabelRenderer().setHorizontalLabelsVisible(false); + bgGraph.getGridLabelRenderer().setLabelVerticalWidth(axisWidth); + iobGraph.getGridLabelRenderer().setLabelVerticalWidth(axisWidth); + iobGraph.getGridLabelRenderer().setNumVerticalLabels(3); + + rangeToDisplay = SP.getInt(R.string.key_rangetodisplay, 6); + + bgGraph.setOnLongClickListener(new View.OnLongClickListener() { + @Override + public boolean onLongClick(View v) { + rangeToDisplay += 6; + rangeToDisplay = rangeToDisplay > 24 ? 6 : rangeToDisplay; + SP.putInt(R.string.key_rangetodisplay, rangeToDisplay); + updateGUI("rangeChange"); + return false; + } + }); + + setupChartMenu(view); + + return view; } private void setupChartMenu(View view) { @@ -589,7 +583,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, pvd.show(manager, "ProfileViewDialog"); } else if (item.getTitle().equals(MainApp.gs(R.string.eatingsoon))) { DefaultValueHelper defHelper = new DefaultValueHelper(); - double target = defHelper.determineEatingSoonTT(profile.getUnits()); + double target = defHelper.determineEatingSoonTT(Constants.MGDL); TempTarget tempTarget = new TempTarget() .date(System.currentTimeMillis()) .duration(defHelper.determineEatingSoonTTDuration()) @@ -600,7 +594,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, TreatmentsPlugin.getPlugin().addToHistoryTempTarget(tempTarget); } else if (item.getTitle().equals(MainApp.gs(R.string.activity))) { DefaultValueHelper defHelper = new DefaultValueHelper(); - double target = defHelper.determineActivityTT(profile.getUnits()); + double target = defHelper.determineActivityTT(Constants.MGDL); TempTarget tempTarget = new TempTarget() .date(now()) .duration(defHelper.determineActivityTTDuration()) @@ -611,7 +605,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, TreatmentsPlugin.getPlugin().addToHistoryTempTarget(tempTarget); } else if (item.getTitle().equals(MainApp.gs(R.string.hypo))) { DefaultValueHelper defHelper = new DefaultValueHelper(); - double target = defHelper.determineHypoTT(profile.getUnits()); + double target = defHelper.determineHypoTT(Constants.MGDL); TempTarget tempTarget = new TempTarget() .date(now()) .duration(defHelper.determineHypoTTDuration()) @@ -832,7 +826,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, builder.setPositiveButton(MainApp.gs(R.string.ok), (dialog, id) -> { synchronized (builder) { if (accepted) { - log.debug("guarding: already accepted"); + if (Config.logOverview) + log.debug("guarding: already accepted"); return; } accepted = true; @@ -1037,7 +1032,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, @SuppressLint("SetTextI18n") public void updateGUI(final String from) { - log.debug("updateGUI entered from: " + from); + if (Config.logOverview) + log.debug("updateGUI entered from: " + from); final Date updateGUIStart = new Date(); if (getActivity() == null) @@ -1384,9 +1380,9 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, // Sensitivity if (sensitivityView != null) { - AutosensResult lastAutosensResult = IobCobCalculatorPlugin.getPlugin().detectSensitivityWithLock(IobCobCalculatorPlugin.getPlugin().oldestDataAvailable(), System.currentTimeMillis()); - if (lastAutosensResult != null) - sensitivityView.setText(String.format("%.0f%%", lastAutosensResult.ratio * 100)); + AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getLastAutosensDataSynchronized("Overview"); + if (autosensData != null) + sensitivityView.setText(String.format("%.0f%%", autosensData.autosensResult.ratio * 100)); else sensitivityView.setText(""); } @@ -1432,7 +1428,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, final long now = System.currentTimeMillis(); // ------------------ 1st graph - Profiler.log(log, from + " - 1st graph - START", updateGUIStart); + if (Config.logOverview) + Profiler.log(log, from + " - 1st graph - START", updateGUIStart); final GraphData graphData = new GraphData(bgGraph, IobCobCalculatorPlugin.getPlugin()); @@ -1464,7 +1461,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, graphData.addNowLine(now); // ------------------ 2nd graph - Profiler.log(log, from + " - 2nd graph - START", updateGUIStart); + if (Config.logOverview) + Profiler.log(log, from + " - 2nd graph - START", updateGUIStart); final GraphData secondGraphData = new GraphData(iobGraph, IobCobCalculatorPlugin.getPlugin()); @@ -1518,12 +1516,14 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, // finally enforce drawing of graphs graphData.performUpdate(); secondGraphData.performUpdate(); - Profiler.log(log, from + " - onDataChanged", updateGUIStart); + if (Config.logOverview) + Profiler.log(log, from + " - onDataChanged", updateGUIStart); }); } }).start(); - Profiler.log(log, from, updateGUIStart); + if (Config.logOverview) + Profiler.log(log, from, updateGUIStart); } //Notifications diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewPlugin.java index 3b787fd768..eea249c2e2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewPlugin.java @@ -7,6 +7,7 @@ import org.json.JSONException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; @@ -24,7 +25,7 @@ import info.nightscout.utils.SP; * Created by mike on 05.08.2016. */ public class OverviewPlugin extends PluginBase { - private static Logger log = LoggerFactory.getLogger(OverviewPlugin.class); + private static Logger log = LoggerFactory.getLogger(Constants.OVERVIEW); private static OverviewPlugin overviewPlugin = new OverviewPlugin(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/events/EventOverviewBolusProgress.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/events/EventOverviewBolusProgress.java index 6f9526369e..18e8ff91bc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/events/EventOverviewBolusProgress.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/events/EventOverviewBolusProgress.java @@ -7,7 +7,6 @@ import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.events.Event; public class EventOverviewBolusProgress extends Event { - private static Logger log = LoggerFactory.getLogger(EventOverviewBolusProgress.class); public String status = ""; public Treatment t = null; public int percent = 0; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/graphData/GraphData.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/graphData/GraphData.java index 20feb76124..d750965d38 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/graphData/GraphData.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/graphData/GraphData.java @@ -11,10 +11,14 @@ import com.jjoe64.graphview.series.DataPoint; import com.jjoe64.graphview.series.LineGraphSeries; import com.jjoe64.graphview.series.Series; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.ArrayList; import java.util.Collections; import java.util.List; +import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -47,6 +51,7 @@ import info.nightscout.utils.Round; */ public class GraphData { + private static Logger log = LoggerFactory.getLogger(Constants.OVERVIEW); private GraphView graph; public double maxY = Double.MIN_VALUE; @@ -65,14 +70,18 @@ public class GraphData { public void addBgReadings(long fromTime, long toTime, double lowLine, double highLine, List predictions) { double maxBgValue = Double.MIN_VALUE; - bgReadingsArray = MainApp.getDbHelper().getBgreadingsDataFromTime(fromTime, true); + //bgReadingsArray = MainApp.getDbHelper().getBgreadingsDataFromTime(fromTime, true); + bgReadingsArray = iobCobCalculatorPlugin.getBgReadings(); List bgListArray = new ArrayList<>(); - if (bgReadingsArray.size() == 0) { + if (bgReadingsArray == null || bgReadingsArray.size() == 0) { + if (Config.logOverview) + log.debug("No BG data."); return; } for (BgReading bg : bgReadingsArray) { + if (bg.date < fromTime || bg.date > toTime) continue; if (bg.value > maxBgValue) maxBgValue = bg.value; bgListArray.add(bg); } @@ -137,7 +146,7 @@ public class GraphData { for (long time = fromTime; time < toTime; time += 60 * 1000L) { Profile profile = MainApp.getConfigBuilder().getProfile(time); if (profile == null) continue; - BasalData basalData = IobCobCalculatorPlugin.getPlugin().getBasalData(profile, time); + BasalData basalData = iobCobCalculatorPlugin.getBasalData(profile, time); double baseBasalValue = basalData.basal; double absoluteLineValue = baseBasalValue; double tempBasalValue = 0; @@ -321,13 +330,13 @@ public class GraphData { } private double getNearestBg(long date) { - for (int r = bgReadingsArray.size() - 1; r >= 0; r--) { + for (int r = 0; r < bgReadingsArray.size(); r++) { BgReading reading = bgReadingsArray.get(r); if (reading.date > date) continue; return Profile.fromMgdlToUnits(reading.value, units); } return bgReadingsArray.size() > 0 - ? Profile.fromMgdlToUnits(bgReadingsArray.get(0).value, units) : 0; + ? Profile.fromMgdlToUnits(bgReadingsArray.get(0).value, units) : Profile.fromMgdlToUnits(100, units); } // scale in % of vertical size (like 0.3) @@ -342,7 +351,7 @@ public class GraphData { Profile profile = MainApp.getConfigBuilder().getProfile(time); double iob = 0d; if (profile != null) - iob = IobCobCalculatorPlugin.getPlugin().calculateFromTreatmentsAndTempsSynchronized(time, profile).iob; + iob = iobCobCalculatorPlugin.calculateFromTreatmentsAndTempsSynchronized(time, profile).iob; if (Math.abs(lastIob - iob) > 0.02) { if (Math.abs(lastIob - iob) > 0.2) iobArray.add(new ScaledDataPoint(time, lastIob, iobScale)); @@ -380,7 +389,7 @@ public class GraphData { Scale cobScale = new Scale(); for (long time = fromTime; time <= toTime; time += 5 * 60 * 1000L) { - AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getAutosensData(time); + AutosensData autosensData = iobCobCalculatorPlugin.getAutosensData(time); if (autosensData != null) { int cob = (int) autosensData.cob; if (cob != lastCob) { @@ -438,7 +447,7 @@ public class GraphData { Scale devScale = new Scale(); for (long time = fromTime; time <= toTime; time += 5 * 60 * 1000L) { - AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getAutosensData(time); + AutosensData autosensData = iobCobCalculatorPlugin.getAutosensData(time); if (autosensData != null) { int color = MainApp.gc(R.color.deviationblack); // "=" if (autosensData.type.equals("") || autosensData.type.equals("non-meal")) { @@ -488,7 +497,7 @@ public class GraphData { Scale ratioScale = new Scale(); for (long time = fromTime; time <= toTime; time += 5 * 60 * 1000L) { - AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getAutosensData(time); + AutosensData autosensData = iobCobCalculatorPlugin.getAutosensData(time); if (autosensData != null) { ratioArray.add(new ScaledDataPoint(time, autosensData.autosensResult.ratio - 1, ratioScale)); maxRatioValueFound = Math.max(maxRatioValueFound, autosensData.autosensResult.ratio - 1); @@ -504,11 +513,11 @@ public class GraphData { ratioSeries.setThickness(3); if (useForScale) { - maxY = maxRatioValueFound; - minY = minRatioValueFound; + maxY = Math.max(maxRatioValueFound, Math.abs(minRatioValueFound)); + minY = -maxY; } - ratioScale.setMultiplier(maxY * scale / maxRatioValueFound); + ratioScale.setMultiplier(maxY * scale / Math.max(maxRatioValueFound, Math.abs(minRatioValueFound))); addSeries(ratioSeries); } @@ -525,7 +534,7 @@ public class GraphData { Scale dsMinScale = new Scale(); for (long time = fromTime; time <= toTime; time += 5 * 60 * 1000L) { - AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getAutosensData(time); + AutosensData autosensData = iobCobCalculatorPlugin.getAutosensData(time); if (autosensData != null) { dsMaxArray.add(new ScaledDataPoint(time, autosensData.slopeFromMaxDeviation, dsMaxScale)); dsMinArray.add(new ScaledDataPoint(time, autosensData.slopeFromMinDeviation, dsMinScale)); @@ -604,8 +613,10 @@ public class GraphData { } } - graph.getViewport().setMaxY(Round.ceilTo(maxY, 1d)); - graph.getViewport().setMinY(Round.floorTo(minY, 1d)); + double step = 1d; + if (maxY < 1) step = 0.1d; + graph.getViewport().setMaxY(Round.ceilTo(maxY, step)); + graph.getViewport().setMinY(Round.floorTo(minY, step)); graph.getViewport().setYAxisBoundsManual(true); // draw it diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/notifications/Notification.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/notifications/Notification.java index 8c91e2896b..57e6b72377 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/notifications/Notification.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/notifications/Notification.java @@ -20,8 +20,6 @@ import info.nightscout.utils.SP; */ public class Notification { - private static Logger log = LoggerFactory.getLogger(Notification.class); - public static final int URGENT = 0; public static final int NORMAL = 1; public static final int LOW = 2; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/notifications/NotificationRecyclerViewAdapter.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/notifications/NotificationRecyclerViewAdapter.java index 895b99a43e..02390154b6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/notifications/NotificationRecyclerViewAdapter.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/notifications/NotificationRecyclerViewAdapter.java @@ -15,6 +15,8 @@ import org.slf4j.LoggerFactory; import java.util.List; import java.util.Objects; +import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastAckAlarm; @@ -24,7 +26,7 @@ import info.nightscout.utils.DateUtil; import info.nightscout.utils.SP; public class NotificationRecyclerViewAdapter extends RecyclerView.Adapter { - private static Logger log = LoggerFactory.getLogger(NotificationRecyclerViewAdapter.class); + private static Logger log = LoggerFactory.getLogger(Constants.NOTIFICATION); private List notificationsList; @@ -96,11 +98,13 @@ public class NotificationRecyclerViewAdapter extends RecyclerView.Adapter store = new ArrayList(); - public long snoozedUntil = 0L; + private static Logger log = LoggerFactory.getLogger(Constants.NOTIFICATION); + public List store = new ArrayList<>(); private boolean usesChannels; public NotificationStore() { @@ -52,7 +52,8 @@ public class NotificationStore { } public synchronized boolean add(Notification n) { - log.info("Notification received: " + n.text); + if (Config.logNotification) + log.debug("Notification received: " + n.text); for (Notification storeNotification : store) { if (storeNotification.id == n.id) { storeNotification.date = n.date; @@ -107,7 +108,8 @@ public class NotificationStore { } public void snoozeTo(long timeToSnooze) { - log.debug("Snoozing alarm until: " + timeToSnooze); + if (Config.logNotification) + log.debug("Snoozing alarm until: " + timeToSnooze); SP.putLong("snoozedTo", timeToSnooze); } @@ -116,7 +118,8 @@ public class NotificationStore { Notification notification = new Notification(Notification.NSALARM, MainApp.gs(R.string.nsalarm_staledata), Notification.URGENT); SP.putLong("snoozedTo", System.currentTimeMillis()); add(notification); - log.debug("Snoozed to current time and added back notification!"); + if (Config.logNotification) + log.debug("Snoozed to current time and added back notification!"); } } @@ -125,7 +128,7 @@ public class NotificationStore { NotificationManager mgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Bitmap largeIcon = BitmapFactory.decodeResource(context.getResources(), R.mipmap.blueowl); int smallIcon = R.drawable.ic_notification; - if (Config.NSCLIENT || Config.G5UPLOADER){ + if (Config.NSCLIENT || Config.G5UPLOADER) { largeIcon = BitmapFactory.decodeResource(MainApp.instance().getResources(), R.mipmap.yellowowl); smallIcon = R.drawable.nsclient_smallicon; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileNS/NSProfilePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileNS/NSProfilePlugin.java index 404aff0608..ec4cc22055 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileNS/NSProfilePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileNS/NSProfilePlugin.java @@ -1,10 +1,9 @@ package info.nightscout.androidaps.plugins.ProfileNS; import android.content.Intent; +import android.os.Bundle; import android.support.annotation.Nullable; -import com.squareup.otto.Subscribe; - import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; @@ -65,12 +64,24 @@ public class NSProfilePlugin extends PluginBase implements ProfileInterface { MainApp.bus().unregister(this); } - @Subscribe - public void storeNewProfile(ProfileStore newProfile) { - profile = new ProfileStore(newProfile.getData()); - storeNSProfile(); - MainApp.bus().post(new EventNSProfileUpdateGUI()); - MainApp.bus().post(new EventProfileStoreChanged()); + public void handleNewData(Intent intent) { + try { + Bundle bundles = intent.getExtras(); + if (bundles == null) return; + + String activeProfile = bundles.getString("activeprofile"); + String profileString = bundles.getString("profile"); + profile = new ProfileStore(new JSONObject(profileString)); + storeNSProfile(); + if (isEnabled(PluginType.PROFILE)) { + MainApp.bus().post(new EventProfileStoreChanged()); + MainApp.bus().post(new EventNSProfileUpdateGUI()); + } + if (Config.logIncommingData) + log.debug("Received profileStore: " + activeProfile + " " + profile); + } catch (JSONException e) { + log.error("Unhandled exception", e); + } } private void storeNSProfile() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/activities/DanaRUserOptionsActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/activities/DanaRUserOptionsActivity.java index b4930a2a1a..bd6a315319 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/activities/DanaRUserOptionsActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/activities/DanaRUserOptionsActivity.java @@ -45,6 +45,10 @@ public class DanaRUserOptionsActivity extends Activity { NumberPicker shutdown; NumberPicker lowReservoir; Button saveToPumpButton; + // This is for Dana pumps only + boolean isRS = MainApp.getSpecificPlugin(DanaRSPlugin.class) != null && MainApp.getSpecificPlugin(DanaRSPlugin.class).isEnabled(PluginType.PUMP); + boolean isDanaR = MainApp.getSpecificPlugin(DanaRPlugin.class) != null && MainApp.getSpecificPlugin(DanaRPlugin.class).isEnabled(PluginType.PUMP); + boolean isDanaRv2 = MainApp.getSpecificPlugin(DanaRv2Plugin.class) != null && MainApp.getSpecificPlugin(DanaRv2Plugin.class).isEnabled(PluginType.PUMP); @Override protected void onResume() { @@ -125,8 +129,8 @@ public class DanaRUserOptionsActivity extends Activity { public void setData() { DanaRPump pump = DanaRPump.getInstance(); - - timeFormat.setChecked(pump.timeDisplayType != 0); + // in DanaRS timeDisplay values are reversed + timeFormat.setChecked((!isRS && pump.timeDisplayType != 0) || (isRS && pump.timeDisplayType == 0)); buttonScroll.setChecked(pump.buttonScrollOnOff != 0); beep.setChecked(pump.beepAndAlarm > 4); screenTimeout.setValue((double) pump.lcdOnTimeSec); @@ -142,19 +146,22 @@ public class DanaRUserOptionsActivity extends Activity { } public void onSaveClick() { - boolean isRS = MainApp.getSpecificPlugin(DanaRSPlugin.class) != null && MainApp.getSpecificPlugin(DanaRSPlugin.class).isEnabled(PluginType.PUMP); - boolean isDanaR = MainApp.getSpecificPlugin(DanaRPlugin.class) != null && MainApp.getSpecificPlugin(DanaRPlugin.class).isEnabled(PluginType.PUMP); - boolean isDanaRv2 = MainApp.getSpecificPlugin(DanaRv2Plugin.class) != null && MainApp.getSpecificPlugin(DanaRv2Plugin.class).isEnabled(PluginType.PUMP); if (!isRS && !isDanaR && !isDanaRv2) { //exit if pump is not DanaRS, Dana!, or DanaR with upgraded firmware return; } DanaRPump pump = DanaRPump.getInstance(); - if (timeFormat.isChecked()) pump.timeDisplayType = 1; else pump.timeDisplayType = 0; + // displayTime on RS is reversed + if (isRS) { + if (timeFormat.isChecked()) + pump.timeDisplayType = 0; + else + pump.timeDisplayType = 1; + } if (buttonScroll.isChecked()) pump.buttonScrollOnOff = 1; else diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/services/BLEComm.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/services/BLEComm.java index 9df2ebc0a1..e15f6f23c0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/services/BLEComm.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/services/BLEComm.java @@ -151,7 +151,7 @@ public class BLEComm { isConnecting = false; } - public void disconnect(String from) { + public synchronized void disconnect(String from) { log.debug("disconnect from: " + from); // cancel previous scheduled disconnection to prevent closing upcomming connection @@ -187,17 +187,7 @@ public class BLEComm { private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() { public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { - log.debug("onConnectionStateChange"); - - if (newState == BluetoothProfile.STATE_CONNECTED) { - mBluetoothGatt.discoverServices(); - } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { - close(); - isConnected = false; - isConnecting = false; - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED)); - log.debug("Device was disconnected " + gatt.getDevice().getName());//Device was disconnected - } + onConnectionStateChangeSynchronized(gatt, status, newState); // call it synchronized } public void onServicesDiscovered(BluetoothGatt gatt, int status) { @@ -325,6 +315,20 @@ public class BLEComm { } } + public synchronized void onConnectionStateChangeSynchronized(BluetoothGatt gatt, int status, int newState) { + log.debug("onConnectionStateChange"); + + if (newState == BluetoothProfile.STATE_CONNECTED) { + mBluetoothGatt.discoverServices(); + } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { + close(); + isConnected = false; + isConnecting = false; + MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED)); + log.debug("Device was disconnected " + gatt.getDevice().getName());//Device was disconnected + } + } + private final byte[] readBuffer = new byte[1024]; private int bufferLength = 0; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/AbstractSensitivityPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/AbstractSensitivityPlugin.java index 1d96eeff6b..3e43b6a3d0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/AbstractSensitivityPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/AbstractSensitivityPlugin.java @@ -3,28 +3,31 @@ package info.nightscout.androidaps.plugins.Sensitivity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.R; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.SensitivityInterface; import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensResult; +import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.utils.Round; import info.nightscout.utils.SP; import info.nightscout.utils.SafeParse; public abstract class AbstractSensitivityPlugin extends PluginBase implements SensitivityInterface { - private static final Logger log = LoggerFactory.getLogger("AUTOSENS"); + private static final Logger log = LoggerFactory.getLogger(Constants.AUTOSENS); public AbstractSensitivityPlugin(PluginDescription pluginDescription) { super(pluginDescription); } @Override - public abstract AutosensResult detectSensitivity(long fromTime, long toTime); + public abstract AutosensResult detectSensitivity(IobCobCalculatorPlugin plugin, long fromTime, long toTime); - public AutosensResult fillResult(double ratio, double carbsAbsorbed, String pastSensitivity, - String ratioLimit, String sensResult, int deviationsArraySize) { + AutosensResult fillResult(double ratio, double carbsAbsorbed, String pastSensitivity, + String ratioLimit, String sensResult, int deviationsArraySize) { return this.fillResult(ratio, carbsAbsorbed, pastSensitivity, ratioLimit, sensResult, deviationsArraySize, SafeParse.stringToDouble(SP.getString(R.string.key_openapsama_autosens_min, "0.7")), @@ -32,8 +35,8 @@ public abstract class AbstractSensitivityPlugin extends PluginBase implements Se } public AutosensResult fillResult(double ratio, double carbsAbsorbed, String pastSensitivity, - String ratioLimit, String sensResult, int deviationsArraySize, - double ratioMin, double ratioMax) { + String ratioLimit, String sensResult, int deviationsArraySize, + double ratioMin, double ratioMax) { double rawRatio = ratio; ratio = Math.max(ratio, ratioMin); ratio = Math.min(ratio, ratioMax); @@ -51,7 +54,8 @@ public abstract class AbstractSensitivityPlugin extends PluginBase implements Se if (ratio != rawRatio) { ratioLimit += "Ratio limited from " + rawRatio + " to " + ratio; - log.debug(ratioLimit); + if (Config.logAutosensData) + log.debug(ratioLimit); } AutosensResult output = new AutosensResult(); @@ -64,5 +68,4 @@ public abstract class AbstractSensitivityPlugin extends PluginBase implements Se } - } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/SensitivityAAPSPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/SensitivityAAPSPlugin.java index e5ca522a51..e5949e7298 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/SensitivityAAPSPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/SensitivityAAPSPlugin.java @@ -11,6 +11,7 @@ import java.util.Date; import java.util.List; import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; @@ -28,7 +29,7 @@ import info.nightscout.utils.SP; */ public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin { - private static Logger log = LoggerFactory.getLogger("AUTOSENS"); + private static Logger log = LoggerFactory.getLogger(Constants.AUTOSENS); static SensitivityAAPSPlugin plugin = null; @@ -49,8 +50,8 @@ public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin { } @Override - public AutosensResult detectSensitivity(long fromTime, long toTime) { - LongSparseArray autosensDataTable = IobCobCalculatorPlugin.getPlugin().getAutosensDataTable(); + public AutosensResult detectSensitivity(IobCobCalculatorPlugin iobCobCalculatorPlugin, long fromTime, long toTime) { + LongSparseArray autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable(); String age = SP.getString(R.string.key_age, ""); int defaultHours = 24; @@ -67,13 +68,13 @@ public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin { } if (autosensDataTable == null || autosensDataTable.size() < 4) { - log.debug("No autosens data available. lastDataTime=" + IobCobCalculatorPlugin.getPlugin().lastDataTime()); + log.debug("No autosens data available. lastDataTime=" + iobCobCalculatorPlugin.lastDataTime()); return new AutosensResult(); } - AutosensData current = IobCobCalculatorPlugin.getPlugin().getAutosensData(toTime); // this is running inside lock already + AutosensData current = iobCobCalculatorPlugin.getAutosensData(toTime); // this is running inside lock already if (current == null) { - log.debug("No autosens data available. toTime: " + DateUtil.dateAndTimeString(toTime) + " lastDataTime: " + IobCobCalculatorPlugin.getPlugin().lastDataTime()); + log.debug("No autosens data available. toTime: " + DateUtil.dateAndTimeString(toTime) + " lastDataTime: " + iobCobCalculatorPlugin.lastDataTime()); return new AutosensResult(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/SensitivityOref0Plugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/SensitivityOref0Plugin.java index c9086dbfbd..142feba8da 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/SensitivityOref0Plugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/SensitivityOref0Plugin.java @@ -11,6 +11,7 @@ import java.util.Date; import java.util.List; import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; @@ -27,7 +28,7 @@ import info.nightscout.utils.DateUtil; */ public class SensitivityOref0Plugin extends AbstractSensitivityPlugin { - private static Logger log = LoggerFactory.getLogger("AUTOSENS"); + private static Logger log = LoggerFactory.getLogger(Constants.AUTOSENS); static SensitivityOref0Plugin plugin = null; @@ -48,8 +49,8 @@ public class SensitivityOref0Plugin extends AbstractSensitivityPlugin { } @Override - public AutosensResult detectSensitivity(long fromTime, long toTime) { - LongSparseArray autosensDataTable = IobCobCalculatorPlugin.getPlugin().getAutosensDataTable(); + public AutosensResult detectSensitivity(IobCobCalculatorPlugin iobCobCalculatorPlugin, long fromTime, long toTime) { + LongSparseArray autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable(); int hoursForDetection = 24; @@ -62,13 +63,13 @@ public class SensitivityOref0Plugin extends AbstractSensitivityPlugin { } if (autosensDataTable == null || autosensDataTable.size() < 4) { - log.debug("No autosens data available. lastDataTime=" + IobCobCalculatorPlugin.getPlugin().lastDataTime()); + log.debug("No autosens data available. lastDataTime=" + iobCobCalculatorPlugin.lastDataTime()); return new AutosensResult(); } - AutosensData current = IobCobCalculatorPlugin.getPlugin().getAutosensData(toTime); // this is running inside lock already + AutosensData current = iobCobCalculatorPlugin.getAutosensData(toTime); // this is running inside lock already if (current == null) { - log.debug("No autosens data available. toTime: " + DateUtil.dateAndTimeString(toTime) + " lastDataTime: " + IobCobCalculatorPlugin.getPlugin().lastDataTime()); + log.debug("No autosens data available. toTime: " + DateUtil.dateAndTimeString(toTime) + " lastDataTime: " + iobCobCalculatorPlugin.lastDataTime()); return new AutosensResult(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/SensitivityOref1Plugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/SensitivityOref1Plugin.java index 29787b14c0..4eb67cc69f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/SensitivityOref1Plugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/SensitivityOref1Plugin.java @@ -11,6 +11,7 @@ import java.util.Date; import java.util.List; import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; @@ -27,7 +28,7 @@ import info.nightscout.utils.DateUtil; */ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { - private static Logger log = LoggerFactory.getLogger("AUTOSENS"); + private static Logger log = LoggerFactory.getLogger(Constants.AUTOSENS); static SensitivityOref1Plugin plugin = null; @@ -48,10 +49,10 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { } @Override - public AutosensResult detectSensitivity(long fromTime, long toTime) { + public AutosensResult detectSensitivity(IobCobCalculatorPlugin iobCobCalculatorPlugin, long fromTime, long toTime) { // todo this method is called from the IobCobCalculatorPlugin, which leads to a circular // dependency, this should be avoided - LongSparseArray autosensDataTable = IobCobCalculatorPlugin.getPlugin().getAutosensDataTable(); + LongSparseArray autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable(); Profile profile = MainApp.getConfigBuilder().getProfile(); @@ -61,14 +62,14 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { } if (autosensDataTable == null || autosensDataTable.size() < 4) { - log.debug("No autosens data available. lastDataTime=" + IobCobCalculatorPlugin.getPlugin().lastDataTime()); + log.debug("No autosens data available. lastDataTime=" + iobCobCalculatorPlugin.lastDataTime()); return new AutosensResult(); } // the current - AutosensData current = IobCobCalculatorPlugin.getPlugin().getAutosensData(toTime); // this is running inside lock already + AutosensData current = iobCobCalculatorPlugin.getAutosensData(toTime); // this is running inside lock already if (current == null) { - log.debug("No autosens data available. toTime: " + DateUtil.dateAndTimeString(toTime) + " lastDataTime: " + IobCobCalculatorPlugin.getPlugin().lastDataTime()); + log.debug("No autosens data available. toTime: " + DateUtil.dateAndTimeString(toTime) + " lastDataTime: " + iobCobCalculatorPlugin.lastDataTime()); return new AutosensResult(); } @@ -120,10 +121,12 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { // when we have less than 8h worth of deviation data, add up to 90m of zero deviations // this dampens any large sensitivity changes detected based on too little data, without ignoring them completely - log.debug("Using most recent " + deviationsArray.size() + " deviations"); + if (Config.logAutosensData) + log.debug("Using most recent " + deviationsArray.size() + " deviations"); if (deviationsArray.size() < 96) { int pad = Math.round((1 - deviationsArray.size() / 96) * 18); - log.debug("Adding " + pad + " more zero deviations"); + if (Config.logAutosensData) + log.debug("Adding " + pad + " more zero deviations"); for (int d = 0; d < pad; d++) { //process.stderr.write("."); deviationsArray.add(0d); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/SensitivityWeightedAveragePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/SensitivityWeightedAveragePlugin.java index 0200838d39..0a98b19289 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/SensitivityWeightedAveragePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/SensitivityWeightedAveragePlugin.java @@ -9,6 +9,7 @@ import java.util.Date; import java.util.List; import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; @@ -26,7 +27,7 @@ import info.nightscout.utils.SP; */ public class SensitivityWeightedAveragePlugin extends AbstractSensitivityPlugin { - private static Logger log = LoggerFactory.getLogger("AUTOSENS"); + private static Logger log = LoggerFactory.getLogger(Constants.AUTOSENS); private static SensitivityWeightedAveragePlugin plugin = null; @@ -47,8 +48,8 @@ public class SensitivityWeightedAveragePlugin extends AbstractSensitivityPlugin } @Override - public AutosensResult detectSensitivity(long fromTime, long toTime) { - LongSparseArray autosensDataTable = IobCobCalculatorPlugin.getPlugin().getAutosensDataTable(); + public AutosensResult detectSensitivity(IobCobCalculatorPlugin iobCobCalculatorPlugin, long fromTime, long toTime) { + LongSparseArray autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable(); String age = SP.getString(R.string.key_age, ""); int defaultHours = 24; @@ -58,14 +59,14 @@ public class SensitivityWeightedAveragePlugin extends AbstractSensitivityPlugin int hoursForDetection = SP.getInt(R.string.key_openapsama_autosens_period, defaultHours); if (autosensDataTable == null || autosensDataTable.size() < 4) { - log.debug("No autosens data available. lastDataTime=" + IobCobCalculatorPlugin.getPlugin().lastDataTime()); + log.debug("No autosens data available. lastDataTime=" + iobCobCalculatorPlugin.lastDataTime()); return new AutosensResult(); } - AutosensData current = IobCobCalculatorPlugin.getPlugin().getAutosensData(toTime); // this is running inside lock already + AutosensData current = iobCobCalculatorPlugin.getAutosensData(toTime); // this is running inside lock already if (current == null) { if (Config.logAutosensData) - log.debug("No autosens data available. toTime: " + DateUtil.dateAndTimeString(toTime) + " lastDataTime: " + IobCobCalculatorPlugin.getPlugin().lastDataTime()); + log.debug("No autosens data available. toTime: " + DateUtil.dateAndTimeString(toTime) + " lastDataTime: " + iobCobCalculatorPlugin.lastDataTime()); return new AutosensResult(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/SmsCommunicatorPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/SmsCommunicatorPlugin.java index 847ead4482..55f7ee9e50 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/SmsCommunicatorPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/SmsCommunicatorPlugin.java @@ -2,6 +2,7 @@ package info.nightscout.androidaps.plugins.SmsCommunicator; import android.content.Intent; import android.content.pm.ResolveInfo; +import android.os.Bundle; import android.os.SystemClock; import android.telephony.SmsManager; import android.telephony.SmsMessage; @@ -39,7 +40,6 @@ import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.Loop.LoopPlugin; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.notifications.Notification; -import info.nightscout.androidaps.plugins.SmsCommunicator.events.EventNewSMS; import info.nightscout.androidaps.plugins.SmsCommunicator.events.EventSmsCommunicatorUpdateGui; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.queue.Callback; @@ -165,10 +165,11 @@ public class SmsCommunicatorPlugin extends PluginBase { return false; } - @Subscribe - public void onStatusEvent(final EventNewSMS ev) { + public void handleNewData(Intent intent) { + Bundle bundle = intent.getExtras(); + if (bundle == null) return; - Object[] pdus = (Object[]) ev.bundle.get("pdus"); + Object[] pdus = (Object[]) bundle.get("pdus"); if (pdus != null) { // For every SMS message received for (Object pdu : pdus) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/events/EventNewSMS.java b/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/events/EventNewSMS.java deleted file mode 100644 index dfaebb3942..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/events/EventNewSMS.java +++ /dev/null @@ -1,15 +0,0 @@ -package info.nightscout.androidaps.plugins.SmsCommunicator.events; - -import android.os.Bundle; - -import info.nightscout.androidaps.events.Event; - -/** - * Created by mike on 13.07.2016. - */ -public class EventNewSMS extends Event { - public Bundle bundle; - public EventNewSMS(Bundle bundle) { - this.bundle = bundle; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceDexcomG5Plugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceDexcomG5Plugin.java index af040c8c90..b47f8ae1e1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceDexcomG5Plugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceDexcomG5Plugin.java @@ -1,17 +1,32 @@ package info.nightscout.androidaps.plugins.Source; +import android.content.Intent; +import android.os.Bundle; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.Constants; +import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.interfaces.BgSourceInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.utils.NSUpload; +import info.nightscout.utils.SP; /** * Created by mike on 28.11.2017. */ public class SourceDexcomG5Plugin extends PluginBase implements BgSourceInterface { + private static Logger log = LoggerFactory.getLogger(Constants.BGSOURCE); private static SourceDexcomG5Plugin plugin = null; @@ -37,4 +52,43 @@ public class SourceDexcomG5Plugin extends PluginBase implements BgSourceInterfac public boolean advancedFilteringSupported() { return true; } + + @Override + public void handleNewData(Intent intent) { + // onHandleIntent Bundle{ data => [{"m_time":1511939180,"m_trend":"NotComputable","m_value":335}]; android.support.content.wakelockid => 95; }Bundle + + if (!isEnabled(PluginType.BGSOURCE)) return; + + Bundle bundle = intent.getExtras(); + if (bundle == null) return; + + BgReading bgReading = new BgReading(); + + String data = bundle.getString("data"); + if (Config.logBgSource) + log.debug("Received Dexcom Data", data); + + try { + JSONArray jsonArray = new JSONArray(data); + if (Config.logBgSource) + log.debug("Received Dexcom Data size:" + jsonArray.length()); + for (int i = 0; i < jsonArray.length(); i++) { + JSONObject json = jsonArray.getJSONObject(i); + bgReading.value = json.getInt("m_value"); + bgReading.direction = json.getString("m_trend"); + bgReading.date = json.getLong("m_time") * 1000L; + bgReading.raw = 0; + boolean isNew = MainApp.getDbHelper().createIfNotExists(bgReading, "DexcomG5"); + if (isNew && SP.getBoolean(R.string.key_dexcomg5_nsupload, false)) { + NSUpload.uploadBg(bgReading); + } + if (isNew && SP.getBoolean(R.string.key_dexcomg5_xdripupload, false)) { + NSUpload.sendToXdrip(bgReading); + } + } + + } catch (JSONException e) { + log.error("Exception: ", e); + } + } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceGlimpPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceGlimpPlugin.java index 38b891ff65..761457d296 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceGlimpPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceGlimpPlugin.java @@ -1,15 +1,27 @@ package info.nightscout.androidaps.plugins.Source; +import android.content.Intent; +import android.os.Bundle; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.Constants; +import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.interfaces.BgSourceInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.utils.BundleLogger; /** * Created by mike on 05.08.2016. */ public class SourceGlimpPlugin extends PluginBase implements BgSourceInterface { + private static Logger log = LoggerFactory.getLogger(Constants.BGSOURCE); private static SourceGlimpPlugin plugin = null; @@ -32,4 +44,25 @@ public class SourceGlimpPlugin extends PluginBase implements BgSourceInterface { public boolean advancedFilteringSupported() { return false; } + + @Override + public void handleNewData(Intent intent) { + + if (!isEnabled(PluginType.BGSOURCE)) return; + + Bundle bundle = intent.getExtras(); + if (bundle == null) return; + + if (Config.logBgSource) + log.debug("Received Glimp Data: " + BundleLogger.log(bundle)); + + BgReading bgReading = new BgReading(); + + bgReading.value = bundle.getDouble("mySGV"); + bgReading.direction = bundle.getString("myTrend"); + bgReading.date = bundle.getLong("myTimestamp"); + bgReading.raw = 0; + + MainApp.getDbHelper().createIfNotExists(bgReading, "GLIMP"); + } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceMM640gPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceMM640gPlugin.java index 041b084efd..e96ea1b318 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceMM640gPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceMM640gPlugin.java @@ -1,6 +1,19 @@ package info.nightscout.androidaps.plugins.Source; +import android.content.Intent; +import android.os.Bundle; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.Constants; +import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.interfaces.BgSourceInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; @@ -10,6 +23,8 @@ import info.nightscout.androidaps.interfaces.PluginType; * Created by mike on 05.08.2016. */ public class SourceMM640gPlugin extends PluginBase implements BgSourceInterface { + private static Logger log = LoggerFactory.getLogger(Constants.BGSOURCE); + private static SourceMM640gPlugin plugin = null; public static SourceMM640gPlugin getPlugin() { @@ -31,4 +46,49 @@ public class SourceMM640gPlugin extends PluginBase implements BgSourceInterface public boolean advancedFilteringSupported() { return false; } + + @Override + public void handleNewData(Intent intent) { + + if (!isEnabled(PluginType.BGSOURCE)) return; + + Bundle bundle = intent.getExtras(); + if (bundle == null) return; + + final String collection = bundle.getString("collection"); + if (collection == null) return; + + if (collection.equals("entries")) { + final String data = bundle.getString("data"); + if (Config.logBgSource) + log.debug("Received MM640g Data: ", data); + + if ((data != null) && (data.length() > 0)) { + try { + final JSONArray json_array = new JSONArray(data); + for (int i = 0; i < json_array.length(); i++) { + final JSONObject json_object = json_array.getJSONObject(i); + final String type = json_object.getString("type"); + switch (type) { + case "sgv": + BgReading bgReading = new BgReading(); + + bgReading.value = json_object.getDouble("sgv"); + bgReading.direction = json_object.getString("direction"); + bgReading.date = json_object.getLong("date"); + bgReading.raw = json_object.getDouble("sgv"); + + MainApp.getDbHelper().createIfNotExists(bgReading, "MM640g"); + break; + default: + if (Config.logBgSource) + log.debug("Unknown entries type: " + type); + } + } + } catch (JSONException e) { + log.error("Exception: ", e); + } + } + } + } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceNSClientPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceNSClientPlugin.java index c99fbcb9bb..89408d3e46 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceNSClientPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceNSClientPlugin.java @@ -1,16 +1,32 @@ package info.nightscout.androidaps.plugins.Source; +import android.content.Intent; +import android.os.Bundle; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.Constants; +import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.interfaces.BgSourceInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSgv; +import info.nightscout.utils.JsonHelper; +import info.nightscout.utils.SP; /** * Created by mike on 05.08.2016. */ public class SourceNSClientPlugin extends PluginBase implements BgSourceInterface { + private static Logger log = LoggerFactory.getLogger(Constants.BGSOURCE); private static SourceNSClientPlugin plugin = null; @@ -39,6 +55,50 @@ public class SourceNSClientPlugin extends PluginBase implements BgSourceInterfac return isAdvancedFilteringEnabled; } + @Override + public void handleNewData(Intent intent) { + + if (!isEnabled(PluginType.BGSOURCE) && !SP.getBoolean(R.string.key_ns_autobackfill, true)) + return; + + Bundle bundles = intent.getExtras(); + + try { + if (bundles.containsKey("sgv")) { + String sgvstring = bundles.getString("sgv"); + if (Config.logBgSource) + log.debug("Received NS Data: " + sgvstring); + + JSONObject sgvJson = new JSONObject(sgvstring); + storeSgv(sgvJson); + } + + if (bundles.containsKey("sgvs")) { + String sgvstring = bundles.getString("sgvs"); + if (Config.logBgSource) + log.debug("Received NS Data: " + sgvstring); + JSONArray jsonArray = new JSONArray(sgvstring); + for (int i = 0; i < jsonArray.length(); i++) { + JSONObject sgvJson = jsonArray.getJSONObject(i); + storeSgv(sgvJson); + } + } + } catch (Exception e) { + log.error("Unhandled exception", e); + } + + // Objectives 0 + ObjectivesPlugin.bgIsAvailableInNS = true; + ObjectivesPlugin.saveProgress(); + } + + private void storeSgv(JSONObject sgvJson) { + NSSgv nsSgv = new NSSgv(sgvJson); + BgReading bgReading = new BgReading(nsSgv); + MainApp.getDbHelper().createIfNotExists(bgReading, "NS"); + SourceNSClientPlugin.getPlugin().detectSource(JsonHelper.safeGetString(sgvJson, "device"), JsonHelper.safeGetLong(sgvJson, "mills")); + } + public void detectSource(String source, long timeStamp) { if (timeStamp > lastBGTimeStamp) { if (source.contains("G5 Native") || source.contains("AndroidAPS-DexcomG5")) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourcePoctechPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourcePoctechPlugin.java index 13cb99d392..071943065d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourcePoctechPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourcePoctechPlugin.java @@ -1,16 +1,32 @@ package info.nightscout.androidaps.plugins.Source; +import android.content.Intent; +import android.os.Bundle; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.Constants; +import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.interfaces.BgSourceInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.utils.JsonHelper; +import info.nightscout.utils.NSUpload; +import info.nightscout.utils.SP; /** * Created by mike on 05.08.2016. */ public class SourcePoctechPlugin extends PluginBase implements BgSourceInterface { + private static Logger log = LoggerFactory.getLogger(Constants.BGSOURCE); private static SourcePoctechPlugin plugin = null; @@ -36,4 +52,44 @@ public class SourcePoctechPlugin extends PluginBase implements BgSourceInterface return false; } + @Override + public void handleNewData(Intent intent) { + + if (!isEnabled(PluginType.BGSOURCE)) return; + + Bundle bundle = intent.getExtras(); + if (bundle == null) return; + + BgReading bgReading = new BgReading(); + + String data = bundle.getString("data"); + if (Config.logBgSource) + log.debug("Received Poctech Data", data); + + try { + JSONArray jsonArray = new JSONArray(data); + if (Config.logBgSource) + log.debug("Received Poctech Data size:" + jsonArray.length()); + for (int i = 0; i < jsonArray.length(); i++) { + JSONObject json = jsonArray.getJSONObject(i); + bgReading.value = json.getDouble("current"); + bgReading.direction = json.getString("direction"); + bgReading.date = json.getLong("date"); + bgReading.raw = json.getDouble("raw"); + if (JsonHelper.safeGetString(json, "units", Constants.MGDL).equals("mmol/L")) + bgReading.value = bgReading.value * Constants.MMOLL_TO_MGDL; + boolean isNew = MainApp.getDbHelper().createIfNotExists(bgReading, "Poctech"); + if (isNew && SP.getBoolean(R.string.key_dexcomg5_nsupload, false)) { + NSUpload.uploadBg(bgReading); + } + if (isNew && SP.getBoolean(R.string.key_dexcomg5_xdripupload, false)) { + NSUpload.sendToXdrip(bgReading); + } + } + + } catch (JSONException e) { + log.error("Exception: ", e); + } + } + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceXdripPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceXdripPlugin.java index fa61c9ea61..77cf5e61d0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceXdripPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceXdripPlugin.java @@ -1,18 +1,31 @@ package info.nightscout.androidaps.plugins.Source; +import android.content.Intent; +import android.os.Bundle; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.Constants; +import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.Services.Intents; +import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.interfaces.BgSourceInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.utils.BundleLogger; /** * Created by mike on 05.08.2016. */ public class SourceXdripPlugin extends PluginBase implements BgSourceInterface { + private static Logger log = LoggerFactory.getLogger(Constants.BGSOURCE); private static SourceXdripPlugin plugin = null; - + boolean advancedFiltering; public static SourceXdripPlugin getPlugin() { @@ -35,6 +48,28 @@ public class SourceXdripPlugin extends PluginBase implements BgSourceInterface { return advancedFiltering; } + @Override + public void handleNewData(Intent intent) { + + if (!isEnabled(PluginType.BGSOURCE)) return; + + Bundle bundle = intent.getExtras(); + if (bundle == null) return; + + if (Config.logBgSource) + log.debug("Received xDrip data: " + BundleLogger.log(intent.getExtras())); + + BgReading bgReading = new BgReading(); + + bgReading.value = bundle.getDouble(Intents.EXTRA_BG_ESTIMATE); + bgReading.direction = bundle.getString(Intents.EXTRA_BG_SLOPE_NAME); + bgReading.date = bundle.getLong(Intents.EXTRA_TIMESTAMP); + bgReading.raw = bundle.getDouble(Intents.EXTRA_RAW); + String source = bundle.getString(Intents.XDRIP_DATA_SOURCE_DESCRIPTION, "no Source specified"); + SourceXdripPlugin.getPlugin().setSource(source); + MainApp.getDbHelper().createIfNotExists(bgReading, "XDRIP"); + } + public void setSource(String source) { this.advancedFiltering = source.contains("G5 Native"); } diff --git a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java index 47fe4acd6a..07ef303dbf 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java @@ -12,6 +12,8 @@ import org.slf4j.LoggerFactory; import java.util.LinkedList; +import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.DetailedBolusInfo; @@ -75,7 +77,7 @@ import info.nightscout.androidaps.queue.commands.CommandTempBasalPercent; */ public class CommandQueue { - private static Logger log = LoggerFactory.getLogger(CommandQueue.class); + private Logger log = LoggerFactory.getLogger(Constants.QUEUE); private final LinkedList queue = new LinkedList<>(); protected Command performing; @@ -109,12 +111,14 @@ public class CommandQueue { private synchronized void inject(Command command) { // inject as a first command - log.debug("QUEUE: Adding as first: " + command.getClass().getSimpleName() + " - " + command.status()); + if (Config.logQueue) + log.debug("Adding as first: " + command.getClass().getSimpleName() + " - " + command.status()); queue.addFirst(command); } private synchronized void add(Command command) { - log.debug("QUEUE: Adding: " + command.getClass().getSimpleName() + " - " + command.status()); + if (Config.logQueue) + log.debug("Adding: " + command.getClass().getSimpleName() + " - " + command.status()); queue.add(command); } @@ -147,15 +151,18 @@ public class CommandQueue { // start thread again if not already running protected synchronized void notifyAboutNewCommand() { while (thread != null && thread.getState() != Thread.State.TERMINATED && thread.waitingForDisconnect) { - log.debug("QUEUE: Waiting for previous thread finish"); + if (Config.logQueue) + log.debug("Waiting for previous thread finish"); SystemClock.sleep(500); } if (thread == null || thread.getState() == Thread.State.TERMINATED) { thread = new QueueThread(this); thread.start(); - log.debug("QUEUE: Starting new thread"); + if (Config.logQueue) + log.debug("Starting new thread"); } else { - log.debug("QUEUE: Thread is already running"); + if (Config.logQueue) + log.debug("Thread is already running"); } } @@ -164,8 +171,8 @@ public class CommandQueue { tempCommandQueue.readStatus(reason, callback); } - public synchronized boolean bolusInQueue(){ - if(isRunning(Command.CommandType.BOLUS)) return true; + public synchronized boolean bolusInQueue() { + if (isRunning(Command.CommandType.BOLUS)) return true; for (int i = 0; i < queue.size(); i++) { if (queue.get(i).commandType == Command.CommandType.BOLUS) { return true; @@ -180,17 +187,19 @@ public class CommandQueue { if (type == Command.CommandType.SMB_BOLUS) { if (isRunning(Command.CommandType.BOLUS) || bolusInQueue()) { - log.debug("Rejecting SMB since a bolus is queue/running"); + if (Config.logQueue) + log.debug("Rejecting SMB since a bolus is queue/running"); return false; } if (detailedBolusInfo.lastKnownBolusTime < TreatmentsPlugin.getPlugin().getLastBolusTime()) { - log.debug("Rejecting bolus, another bolus was issued since request time"); + if (Config.logQueue) + log.debug("Rejecting bolus, another bolus was issued since request time"); return false; } } - if(type.equals(Command.CommandType.BOLUS) && detailedBolusInfo.carbs > 0 && detailedBolusInfo.insulin == 0){ + if (type.equals(Command.CommandType.BOLUS) && detailedBolusInfo.carbs > 0 && detailedBolusInfo.insulin == 0) { type = Command.CommandType.CARBS_ONLY_TREATMENT; //Carbs only can be added in parallel as they can be "in the future". } else { @@ -213,7 +222,7 @@ public class CommandQueue { add(new CommandSMBBolus(detailedBolusInfo, callback)); } else { add(new CommandBolus(detailedBolusInfo, callback, type)); - if(type.equals(Command.CommandType.BOLUS)) { + if (type.equals(Command.CommandType.BOLUS)) { // Bring up bolus progress dialog (start here, so the dialog is shown when the bolus is requested, // not when the Bolus command is starting. The command closes the dialog upon completion). showBolusProgressDialog(detailedBolusInfo.insulin, detailedBolusInfo.context); @@ -337,7 +346,8 @@ public class CommandQueue { // returns true if command is queued public boolean setProfile(Profile profile, Callback callback) { if (isThisProfileSet(profile)) { - log.debug("QUEUE: Correct profile already set"); + if (Config.logQueue) + log.debug("Correct profile already set"); if (callback != null) callback.result(new PumpEnactResult().success(true).enacted(false)).run(); return false; @@ -381,7 +391,8 @@ public class CommandQueue { // returns true if command is queued public boolean readStatus(String reason, Callback callback) { if (isLastScheduled(Command.CommandType.READSTATUS)) { - log.debug("QUEUE: READSTATUS " + reason + " ignored as duplicated"); + if (Config.logQueue) + log.debug("READSTATUS " + reason + " ignored as duplicated"); if (callback != null) callback.result(executingNowError()).run(); return false; @@ -496,8 +507,10 @@ public class CommandQueue { if (activePump != null && current != null) { boolean result = activePump.isThisProfileSet(profile); if (!result) { - log.debug("Current profile: " + current.getData().toString()); - log.debug("New profile: " + profile.getData().toString()); + if (Config.logQueue) { + log.debug("Current profile: " + current.toString()); + log.debug("New profile: " + profile.toString()); + } } return result; } else return true; diff --git a/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java b/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java index a5ad59ca0b..3073ecb950 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java @@ -8,6 +8,7 @@ import android.os.SystemClock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -26,7 +27,7 @@ import info.nightscout.utils.SP; */ public class QueueThread extends Thread { - private static Logger log = LoggerFactory.getLogger(QueueThread.class); + private Logger log = LoggerFactory.getLogger(Constants.QUEUE); private CommandQueue queue; @@ -54,7 +55,8 @@ public class QueueThread extends Thread { while (true) { PumpInterface pump = ConfigBuilderPlugin.getActivePump(); if (pump == null) { - log.debug("QUEUE: pump == null"); + if (Config.logQueue) + log.debug("pump == null"); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.pumpNotInitialized))); SystemClock.sleep(1000); continue; @@ -64,15 +66,17 @@ public class QueueThread extends Thread { if (!pump.isConnected() && secondsElapsed > Constants.PUMP_MAX_CONNECTION_TIME_IN_SECONDS) { MainApp.bus().post(new EventDismissBolusprogressIfRunning(null)); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.connectiontimedout))); - log.debug("QUEUE: timed out"); + if (Config.logQueue) + log.debug("timed out"); pump.stopConnecting(); //BLUETOOTH-WATCHDOG boolean watchdog = SP.getBoolean(R.string.key_btwatchdog, false); long last_watchdog = SP.getLong(R.string.key_btwatchdog_lastbark, 0l); watchdog = watchdog && System.currentTimeMillis() - last_watchdog > (Constants.MIN_WATCHDOG_INTERVAL_IN_SECONDS * 1000); - if(watchdog) { - log.debug("BT watchdog - toggeling the phonest bluetooth"); + if (watchdog) { + if (Config.logQueue) + log.debug("BT watchdog - toggeling the phonest bluetooth"); //write time SP.putLong(R.string.key_btwatchdog_lastbark, System.currentTimeMillis()); //toggle BT @@ -91,7 +95,8 @@ public class QueueThread extends Thread { pump.connect("watchdog"); } else { queue.clear(); - log.debug("QUEUE: no connection possible"); + if (Config.logQueue) + log.debug("no connection possible"); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); pump.disconnect("Queue empty"); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED)); @@ -100,7 +105,8 @@ public class QueueThread extends Thread { } if (pump.isConnecting()) { - log.debug("QUEUE: connecting " + secondsElapsed); + if (Config.logQueue) + log.debug("connecting " + secondsElapsed); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.CONNECTING, (int) secondsElapsed)); SystemClock.sleep(1000); continue; @@ -108,7 +114,8 @@ public class QueueThread extends Thread { if (!pump.isConnected()) { - log.debug("QUEUE: connect"); + if (Config.logQueue) + log.debug("connect"); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.CONNECTING, (int) secondsElapsed)); pump.connect("Connection needed"); SystemClock.sleep(1000); @@ -118,12 +125,14 @@ public class QueueThread extends Thread { if (queue.performing() == null) { if (!connectLogged) { connectLogged = true; - log.debug("QUEUE: connection time " + secondsElapsed + "s"); + if (Config.logQueue) + log.debug("connection time " + secondsElapsed + "s"); } // Pickup 1st command and set performing variable if (queue.size() > 0) { queue.pickup(); - log.debug("QUEUE: performing " + queue.performing().status()); + if (Config.logQueue) + log.debug("performing " + queue.performing().status()); MainApp.bus().post(new EventQueueChanged()); queue.performing().execute(); queue.resetPerforming(); @@ -138,14 +147,17 @@ public class QueueThread extends Thread { long secondsFromLastCommand = (System.currentTimeMillis() - lastCommandTime) / 1000; if (secondsFromLastCommand >= 5) { waitingForDisconnect = true; - log.debug("QUEUE: queue empty. disconnect"); + if (Config.logQueue) + log.debug("queue empty. disconnect"); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); pump.disconnect("Queue empty"); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED)); - log.debug("QUEUE: disconnected"); + if (Config.logQueue) + log.debug("disconnected"); return; } else { - log.debug("QUEUE: waiting for disconnect"); + if (Config.logQueue) + log.debug("waiting for disconnect"); SystemClock.sleep(1000); } } @@ -154,6 +166,4 @@ public class QueueThread extends Thread { mWakeLock.release(); } } - - } diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/Command.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/Command.java index 7156a72f25..13208fb9f1 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/Command.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/Command.java @@ -1,5 +1,10 @@ package info.nightscout.androidaps.queue.commands; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.PumpEnactResult; @@ -9,6 +14,8 @@ import info.nightscout.androidaps.queue.Callback; * Created by mike on 09.11.2017. */ public abstract class Command { + private Logger log = LoggerFactory.getLogger(Constants.QUEUE); + public enum CommandType { BOLUS, SMB_BOLUS, @@ -33,6 +40,8 @@ public abstract class Command { PumpEnactResult result = new PumpEnactResult(); result.success = false; result.comment = MainApp.gs(R.string.connectiontimedout); + if (Config.logQueue) + log.debug("Result cancel"); if (callback != null) callback.result(result).run(); } diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandBolus.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandBolus.java index 2be3831ace..c0c2090177 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandBolus.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandBolus.java @@ -1,5 +1,10 @@ package info.nightscout.androidaps.queue.commands; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.PumpEnactResult; @@ -14,6 +19,8 @@ import info.nightscout.utils.DecimalFormatter; */ public class CommandBolus extends Command { + private Logger log = LoggerFactory.getLogger(Constants.QUEUE); + DetailedBolusInfo detailedBolusInfo; public CommandBolus(DetailedBolusInfo detailedBolusInfo, Callback callback, CommandType type) { @@ -28,6 +35,8 @@ public class CommandBolus extends Command { BolusProgressDialog.bolusEnded = true; MainApp.bus().post(new EventDismissBolusprogressIfRunning(r)); + if (Config.logQueue) + log.debug("Result success: " + r.success + " enacted: " + r.enacted); if (callback != null) callback.result(r).run(); diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandCancelExtendedBolus.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandCancelExtendedBolus.java index 536c2d876c..e5d69e2b6d 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandCancelExtendedBolus.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandCancelExtendedBolus.java @@ -4,7 +4,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import info.nightscout.androidaps.Config; -import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.queue.Callback; @@ -14,7 +14,7 @@ import info.nightscout.androidaps.queue.Callback; */ public class CommandCancelExtendedBolus extends Command { - private static Logger log = LoggerFactory.getLogger(CommandCancelExtendedBolus.class); + private Logger log = LoggerFactory.getLogger(Constants.QUEUE); public CommandCancelExtendedBolus(Callback callback) { commandType = CommandType.EXTENDEDBOLUS; @@ -24,8 +24,8 @@ public class CommandCancelExtendedBolus extends Command { @Override public void execute() { PumpEnactResult r = ConfigBuilderPlugin.getActivePump().cancelExtendedBolus(); - if (Config.logCongigBuilderActions) - log.debug("cancelExtendedBolus success: " + r.success + " enacted: " + r.enacted); + if (Config.logQueue) + log.debug("Result success: " + r.success + " enacted: " + r.enacted); if (callback != null) callback.result(r).run(); } diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandCancelTempBasal.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandCancelTempBasal.java index d2496c871a..a79df63569 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandCancelTempBasal.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandCancelTempBasal.java @@ -1,6 +1,10 @@ package info.nightscout.androidaps.queue.commands; -import info.nightscout.androidaps.MainApp; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.queue.Callback; @@ -10,6 +14,8 @@ import info.nightscout.androidaps.queue.Callback; */ public class CommandCancelTempBasal extends Command { + private Logger log = LoggerFactory.getLogger(Constants.QUEUE); + boolean enforceNew; public CommandCancelTempBasal(boolean enforceNew, Callback callback) { @@ -21,6 +27,8 @@ public class CommandCancelTempBasal extends Command { @Override public void execute() { PumpEnactResult r = ConfigBuilderPlugin.getActivePump().cancelTempBasal(enforceNew); + if (Config.logQueue) + log.debug("Result success: " + r.success + " enacted: " + r.enacted); if (callback != null) callback.result(r).run(); } diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandExtendedBolus.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandExtendedBolus.java index 0641d9139d..b3470e6e48 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandExtendedBolus.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandExtendedBolus.java @@ -4,7 +4,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import info.nightscout.androidaps.Config; -import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.queue.Callback; @@ -14,7 +14,7 @@ import info.nightscout.androidaps.queue.Callback; */ public class CommandExtendedBolus extends Command { - private static Logger log = LoggerFactory.getLogger(CommandExtendedBolus.class); + private Logger log = LoggerFactory.getLogger(Constants.QUEUE); private double insulin; private int durationInMinutes; @@ -29,8 +29,8 @@ public class CommandExtendedBolus extends Command { @Override public void execute() { PumpEnactResult r = ConfigBuilderPlugin.getActivePump().setExtendedBolus(insulin, durationInMinutes); - if (Config.logCongigBuilderActions) - log.debug("setExtendedBolus rate: " + insulin + " durationInMinutes: " + durationInMinutes + " success: " + r.success + " enacted: " + r.enacted); + if (Config.logQueue) + log.debug("Result rate: " + insulin + " durationInMinutes: " + durationInMinutes + " success: " + r.success + " enacted: " + r.enacted); if (callback != null) callback.result(r).run(); } diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadEvents.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadEvents.java index 2d6bc5b5fc..da307b0c21 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadEvents.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadEvents.java @@ -1,5 +1,10 @@ package info.nightscout.androidaps.queue.commands; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.interfaces.DanaRInterface; import info.nightscout.androidaps.interfaces.PumpInterface; @@ -11,6 +16,8 @@ import info.nightscout.androidaps.queue.Callback; */ public class CommandLoadEvents extends Command { + private Logger log = LoggerFactory.getLogger(Constants.QUEUE); + public CommandLoadEvents(Callback callback) { commandType = CommandType.LOADEVENTS; this.callback = callback; @@ -22,6 +29,8 @@ public class CommandLoadEvents extends Command { if (pump instanceof DanaRInterface) { DanaRInterface danaPump = (DanaRInterface) pump; PumpEnactResult r = danaPump.loadEvents(); + if (Config.logQueue) + log.debug("Result success: " + r.success + " enacted: " + r.enacted); if (callback != null) callback.result(r).run(); } diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadHistory.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadHistory.java index 16e9a18048..065e194ef0 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadHistory.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadHistory.java @@ -1,17 +1,23 @@ package info.nightscout.androidaps.queue.commands; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.interfaces.DanaRInterface; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.queue.Callback; -import info.nightscout.androidaps.queue.commands.Command; /** * Created by mike on 10.11.2017. */ public class CommandLoadHistory extends Command { + private Logger log = LoggerFactory.getLogger(Constants.QUEUE); + byte type; public CommandLoadHistory(byte type, Callback callback) { @@ -26,6 +32,8 @@ public class CommandLoadHistory extends Command { if (pump instanceof DanaRInterface) { DanaRInterface danaPump = (DanaRInterface) pump; PumpEnactResult r = danaPump.loadHistory(type); + if (Config.logQueue) + log.debug("Result success: " + r.success + " enacted: " + r.enacted); if (callback != null) callback.result(r).run(); } diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadTDDs.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadTDDs.java index 363781a379..77a74369f2 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadTDDs.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadTDDs.java @@ -1,5 +1,10 @@ package info.nightscout.androidaps.queue.commands; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; @@ -10,6 +15,8 @@ import info.nightscout.androidaps.queue.Callback; */ public class CommandLoadTDDs extends Command { + private Logger log = LoggerFactory.getLogger(Constants.QUEUE); + public CommandLoadTDDs(Callback callback) { commandType = CommandType.LOADHISTORY; //belongs to the history group of commands @@ -20,9 +27,11 @@ public class CommandLoadTDDs extends Command { public void execute() { PumpInterface pump = ConfigBuilderPlugin.getActivePump(); PumpEnactResult r = pump.loadTDDs(); + if (Config.logQueue) + log.debug("Result success: " + r.success + " enacted: " + r.enacted); if (callback != null) callback.result(r).run(); - } + } @Override public String status() { diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandReadStatus.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandReadStatus.java index 44c778c5f7..78e4f3cdf1 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandReadStatus.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandReadStatus.java @@ -1,5 +1,10 @@ package info.nightscout.androidaps.queue.commands; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.queue.Callback; import info.nightscout.utils.LocalAlertUtils; @@ -9,6 +14,8 @@ import info.nightscout.utils.LocalAlertUtils; */ public class CommandReadStatus extends Command { + private Logger log = LoggerFactory.getLogger(Constants.QUEUE); + String reason; public CommandReadStatus(String reason, Callback callback) { @@ -21,6 +28,8 @@ public class CommandReadStatus extends Command { public void execute() { ConfigBuilderPlugin.getActivePump().getPumpStatus(); LocalAlertUtils.notifyPumpStatusRead(); + if (Config.logQueue) + log.debug("CommandReadStatus executed. Reason: " + reason); if (callback != null) callback.result(null).run(); } diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.java index 46336f7d4b..c4e613e04b 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.java @@ -3,6 +3,8 @@ package info.nightscout.androidaps.queue.commands; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.PumpEnactResult; @@ -20,7 +22,8 @@ import info.nightscout.utils.T; */ public class CommandSMBBolus extends Command { - private static Logger log = LoggerFactory.getLogger(CommandSMBBolus.class); + private Logger log = LoggerFactory.getLogger(Constants.QUEUE); + DetailedBolusInfo detailedBolusInfo; public CommandSMBBolus(DetailedBolusInfo detailedBolusInfo, Callback callback) { @@ -34,20 +37,25 @@ public class CommandSMBBolus extends Command { PumpEnactResult r; long lastBolusTime = TreatmentsPlugin.getPlugin().getLastBolusTime(); if (lastBolusTime != 0 && lastBolusTime + T.mins(3).msecs() > DateUtil.now()) { - log.debug("SMB requsted but still in 3 min interval"); + if (Config.logQueue) + log.debug("SMB requsted but still in 3 min interval"); r = new PumpEnactResult().enacted(false).success(false).comment("SMB requsted but still in 3 min interval"); - } else if (detailedBolusInfo.deliverAt != 0 && detailedBolusInfo.deliverAt + T.mins(1).msecs() > System.currentTimeMillis()) + } else if (detailedBolusInfo.deliverAt != 0 && detailedBolusInfo.deliverAt + T.mins(1).msecs() > System.currentTimeMillis()) { r = ConfigBuilderPlugin.getActivePump().deliverTreatment(detailedBolusInfo); - else { + } else { r = new PumpEnactResult().enacted(false).success(false).comment("SMB request too old"); - log.debug("SMB bolus canceled. delivetAt=" + detailedBolusInfo.deliverAt + " now=" + System.currentTimeMillis()); + if (Config.logQueue) + log.debug("SMB bolus canceled. delivetAt: " + DateUtil.dateAndTimeString(detailedBolusInfo.deliverAt)); } + if (Config.logQueue) + log.debug("Result success: " + r.success + " enacted: " + r.enacted); + if (callback != null) callback.result(r).run(); } public String status() { - return "SMBBOLUS " + DecimalFormatter.to1Decimal(detailedBolusInfo.insulin) + "U"; + return "SMBBOLUS " + DecimalFormatter.to2Decimal(detailedBolusInfo.insulin) + "U"; } } diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetProfile.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetProfile.java index 03764dee0b..3fa375cfac 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetProfile.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetProfile.java @@ -3,6 +3,8 @@ package info.nightscout.androidaps.queue.commands; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; @@ -20,7 +22,8 @@ import info.nightscout.androidaps.queue.Callback; */ public class CommandSetProfile extends Command { - private static Logger log = LoggerFactory.getLogger(CommandSetProfile.class); + private Logger log = LoggerFactory.getLogger(Constants.QUEUE); + private Profile profile; public CommandSetProfile(Profile profile, Callback callback) { @@ -32,13 +35,16 @@ public class CommandSetProfile extends Command { @Override public void execute() { if (ConfigBuilderPlugin.getCommandQueue().isThisProfileSet(profile)) { - log.debug("QUEUE: Correct profile already set"); + if (Config.logQueue) + log.debug("Correct profile already set. profile: " + profile.toString()); if (callback != null) callback.result(new PumpEnactResult().success(true).enacted(false)).run(); return; } PumpEnactResult r = ConfigBuilderPlugin.getActivePump().setNewBasalProfile(profile); + if (Config.logQueue) + log.debug("Result success: " + r.success + " enacted: " + r.enacted + " profile: " + profile.toString()); if (callback != null) callback.result(r).run(); diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetUserSettings.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetUserSettings.java index f3d9fe2a4b..59f0fe3ba9 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetUserSettings.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetUserSettings.java @@ -3,13 +3,12 @@ package info.nightscout.androidaps.queue.commands; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.interfaces.DanaRInterface; -import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.plugins.PumpDanaRv2.DanaRv2Plugin; import info.nightscout.androidaps.queue.Callback; /** @@ -17,7 +16,8 @@ import info.nightscout.androidaps.queue.Callback; */ public class CommandSetUserSettings extends Command { - private static Logger log = LoggerFactory.getLogger(CommandSetUserSettings.class); + private Logger log = LoggerFactory.getLogger(Constants.QUEUE); + public CommandSetUserSettings(Callback callback) { commandType = CommandType.SETUSERSETTINGS; this.callback = callback; @@ -28,11 +28,9 @@ public class CommandSetUserSettings extends Command { PumpInterface pump = ConfigBuilderPlugin.getActivePump(); if (pump instanceof DanaRInterface) { DanaRInterface danaPump = (DanaRInterface) pump; - boolean isDanaRv2 = MainApp.getSpecificPlugin(DanaRv2Plugin.class) != null && MainApp.getSpecificPlugin(DanaRv2Plugin.class).isEnabled(PluginType.PUMP); - if(isDanaRv2){ - log.debug("MsgSetUserOptions detected for DanaRv2"); - } PumpEnactResult r = danaPump.setUserOptions(); + if (Config.logQueue) + log.debug("Result success: " + r.success + " enacted: " + r.enacted); if (callback != null) callback.result(r).run(); } diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalAbsolute.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalAbsolute.java index 35c2435558..6e1a174364 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalAbsolute.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalAbsolute.java @@ -4,6 +4,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; @@ -15,7 +16,7 @@ import info.nightscout.androidaps.queue.Callback; */ public class CommandTempBasalAbsolute extends Command { - private static Logger log = LoggerFactory.getLogger(CommandTempBasalAbsolute.class); + private Logger log = LoggerFactory.getLogger(Constants.QUEUE); int durationInMinutes; double absoluteRate; @@ -34,8 +35,8 @@ public class CommandTempBasalAbsolute extends Command { @Override public void execute() { PumpEnactResult r = ConfigBuilderPlugin.getActivePump().setTempBasalAbsolute(absoluteRate, durationInMinutes, profile, enforceNew); - if (Config.logCongigBuilderActions) - log.debug("setTempBasalAbsolute rate: " + absoluteRate + " durationInMinutes: " + durationInMinutes + " success: " + r.success + " enacted: " + r.enacted); + if (Config.logQueue) + log.debug("Result rate: " + absoluteRate + " durationInMinutes: " + durationInMinutes + " success: " + r.success + " enacted: " + r.enacted); if (callback != null) callback.result(r).run(); } diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalPercent.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalPercent.java index bbb421e128..8b210de2c4 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalPercent.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalPercent.java @@ -4,6 +4,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; @@ -14,7 +15,7 @@ import info.nightscout.androidaps.queue.Callback; */ public class CommandTempBasalPercent extends Command { - private static Logger log = LoggerFactory.getLogger(CommandTempBasalPercent.class); + private Logger log = LoggerFactory.getLogger(Constants.QUEUE); int durationInMinutes; int percent; @@ -33,8 +34,8 @@ public class CommandTempBasalPercent extends Command { @Override public void execute() { PumpEnactResult r = ConfigBuilderPlugin.getActivePump().setTempBasalPercent(percent, durationInMinutes, profile, enforceNew); - if (Config.logCongigBuilderActions) - log.debug("setTempBasalPercent percent: " + percent + " durationInMinutes: " + durationInMinutes + " success: " + r.success + " enacted: " + r.enacted); + if (Config.logQueue) + log.debug("Result percent: " + percent + " durationInMinutes: " + durationInMinutes + " success: " + r.success + " enacted: " + r.enacted); if (callback != null) callback.result(r).run(); } diff --git a/app/src/main/res/layout/activity_historybrowse.xml b/app/src/main/res/layout/activity_historybrowse.xml index f05672e765..6f29d671c4 100644 --- a/app/src/main/res/layout/activity_historybrowse.xml +++ b/app/src/main/res/layout/activity_historybrowse.xml @@ -27,41 +27,35 @@ android:layout_height="wrap_content" android:orientation="horizontal"> - -