historybrowser, rendering optimizations

This commit is contained in:
Milos Kozak 2018-07-24 00:46:08 +02:00
parent 130fca4c2a
commit 7e2d3fd8be
17 changed files with 319 additions and 266 deletions

View file

@ -1,7 +1,7 @@
package info.nightscout.androidaps; package info.nightscout.androidaps;
import android.app.Activity;
import android.os.Bundle; import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.content.res.ResourcesCompat; import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AppCompatActivity; import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.PopupMenu; import android.support.v7.widget.PopupMenu;
@ -17,11 +17,13 @@ import android.widget.TextView;
import com.jjoe64.graphview.GraphView; import com.jjoe64.graphview.GraphView;
import com.squareup.otto.Subscribe; import com.squareup.otto.Subscribe;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date;
import butterknife.BindView; import butterknife.BindView;
import butterknife.ButterKnife; 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.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished; 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.OverviewFragment;
import info.nightscout.androidaps.plugins.Overview.OverviewPlugin; import info.nightscout.androidaps.plugins.Overview.OverviewPlugin;
import info.nightscout.androidaps.plugins.Overview.graphData.GraphData; import info.nightscout.androidaps.plugins.Overview.graphData.GraphData;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.SP; import info.nightscout.utils.T;
public class HistoryBrowseActivity extends AppCompatActivity { public class HistoryBrowseActivity extends AppCompatActivity {
private static Logger log = LoggerFactory.getLogger(HistoryBrowseActivity.class); private static Logger log = LoggerFactory.getLogger(HistoryBrowseActivity.class);
@ -61,9 +64,11 @@ public class HistoryBrowseActivity extends AppCompatActivity {
SeekBar seekBar; SeekBar seekBar;
@BindView(R.id.historybrowse_noprofile) @BindView(R.id.historybrowse_noprofile)
TextView noProfile; TextView noProfile;
@BindView(R.id.overview_iobcalculationprogess)
TextView iobCalculationProgressView;
private int rangeToDisplay = 24; // for graph private int rangeToDisplay = 24; // for graph
private long start; private long start = 0;
IobCobCalculatorPlugin iobCobCalculatorPlugin; IobCobCalculatorPlugin iobCobCalculatorPlugin;
@ -90,7 +95,19 @@ public class HistoryBrowseActivity extends AppCompatActivity {
iobGraph.getGridLabelRenderer().setNumVerticalLabels(5); iobGraph.getGridLabelRenderer().setNumVerticalLabels(5);
setupChartMenu(); 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 // set start of current day
Calendar calendar = Calendar.getInstance(); Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis()); calendar.setTimeInMillis(System.currentTimeMillis());
@ -99,33 +116,23 @@ public class HistoryBrowseActivity extends AppCompatActivity {
calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.HOUR_OF_DAY, 0);
start = calendar.getTimeInMillis(); start = calendar.getTimeInMillis();
} runCalculation("onResume");
SystemClock.sleep(1000);
@Override
protected void onResume() {
super.onResume();
updateGUI("onResume"); updateGUI("onResume");
} }
@OnClick(R.id.historybrowse_start)
void onClickStart() {
}
@OnClick(R.id.historybrowse_left) @OnClick(R.id.historybrowse_left)
void onClickLeft() { void onClickLeft() {
start -= rangeToDisplay * 60 * 60 * 1000L; start -= T.hours(rangeToDisplay).msecs();
updateGUI("left"); updateGUI("onClickLeft");
iobCobCalculatorPlugin.clearCache(); runCalculation("onClickLeft");
iobCobCalculatorPlugin.runCalculation("onClickLeft", start, true, eventCustomCalculationFinished);
} }
@OnClick(R.id.historybrowse_right) @OnClick(R.id.historybrowse_right)
void onClickRight() { void onClickRight() {
start += rangeToDisplay * 60 * 60 * 1000L; start += T.hours(rangeToDisplay).msecs();
updateGUI("right"); updateGUI("onClickRight");
iobCobCalculatorPlugin.clearCache(); runCalculation("onClickRight");
iobCobCalculatorPlugin.runCalculation("onClickRight", start, true, eventCustomCalculationFinished);
} }
@OnClick(R.id.historybrowse_end) @OnClick(R.id.historybrowse_end)
@ -137,9 +144,8 @@ public class HistoryBrowseActivity extends AppCompatActivity {
calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.HOUR_OF_DAY, 0);
start = calendar.getTimeInMillis(); start = calendar.getTimeInMillis();
updateGUI("resetToMidnight"); updateGUI("onClickEnd");
iobCobCalculatorPlugin.clearCache(); runCalculation("onClickEnd");
iobCobCalculatorPlugin.runCalculation("onClickEnd", start, true, eventCustomCalculationFinished);
} }
@OnClick(R.id.historybrowse_zoom) @OnClick(R.id.historybrowse_zoom)
@ -159,32 +165,63 @@ public class HistoryBrowseActivity extends AppCompatActivity {
calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.HOUR_OF_DAY, 0);
start = calendar.getTimeInMillis(); start = calendar.getTimeInMillis();
updateGUI("resetToMidnight"); updateGUI("resetToMidnight");
iobCobCalculatorPlugin.clearCache(); runCalculation("onLongClickZoom");
iobCobCalculatorPlugin.runCalculation("onLongClickZoom", start, true, eventCustomCalculationFinished);
return true; return true;
} }
@OnClick(R.id.historybrowse_date) @OnClick(R.id.historybrowse_date)
void onClickDate() { 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 @Subscribe
public void onStatusEvent(final EventAutosensCalculationFinished e) { public void onStatusEvent(final EventAutosensCalculationFinished e) {
Activity activity = this; if (e.cause == eventCustomCalculationFinished) {
if (activity != null && e.cause == eventCustomCalculationFinished) {
log.debug("EventAutosensCalculationFinished"); log.debug("EventAutosensCalculationFinished");
activity.runOnUiThread(new Runnable() { runOnUiThread(() -> {
@Override synchronized (HistoryBrowseActivity.this) {
public void run() { updateGUI("EventAutosensCalculationFinished");
synchronized (HistoryBrowseActivity.this) {
updateGUI("EventAutosensCalculationFinished");
}
} }
}); });
} }
} }
@Subscribe
public void onStatusEvent(final EventIobCalculationProgress e) {
runOnUiThread(() -> {
if (iobCalculationProgressView != null)
iobCalculationProgressView.setText(e.progress);
});
}
void updateGUI(String from) { void updateGUI(String from) {
log.debug("updateGUI from: " + from);
if (noProfile == null || buttonDate == null || buttonZoom == null || bgGraph == null || iobGraph == null || seekBar == null) if (noProfile == null || buttonDate == null || buttonZoom == null || bgGraph == null || iobGraph == null || seekBar == null)
return; return;
@ -200,17 +237,11 @@ public class HistoryBrowseActivity extends AppCompatActivity {
} }
final String units = profile.getUnits(); 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)); buttonDate.setText(DateUtil.dateAndTimeString(start));
double highLineSetting = SP.getDouble("high_mark", Profile.fromMgdlToUnits(OverviewPlugin.bgTargetHigh, units)); buttonZoom.setText(String.valueOf(rangeToDisplay));
if (lowLineSetting < 1)
lowLineSetting = Profile.fromMgdlToUnits(76d, units);
if (highLineSetting < 1)
highLineSetting = Profile.fromMgdlToUnits(180d, units);
final double lowLine = lowLineSetting;
final double highLine = highLineSetting;
final boolean showPrediction = false; final boolean showPrediction = false;
@ -226,20 +257,17 @@ public class HistoryBrowseActivity extends AppCompatActivity {
//fromTime = toTime - hoursToFetch * 60 * 60 * 1000L; //fromTime = toTime - hoursToFetch * 60 * 60 * 1000L;
//endTime = toTime + predHours * 60 * 60 * 1000L; //endTime = toTime + predHours * 60 * 60 * 1000L;
//} else { //} else {
fromTime = start + 100000; fromTime = start + T.secs(100).msecs();
toTime = start + rangeToDisplay * 60 * 60 * 1000L; 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)); log.debug("Period: " + DateUtil.dateAndTimeString(fromTime) + " - " + DateUtil.dateAndTimeString(toTime));
final long pointer = System.currentTimeMillis(); final long pointer = System.currentTimeMillis();
// ------------------ 1st graph // ------------------ 1st graph
final GraphData graphData = new GraphData(bgGraph, IobCobCalculatorPlugin.getPlugin()); final GraphData graphData = new GraphData(bgGraph, iobCobCalculatorPlugin);
// **** In range Area **** // **** In range Area ****
graphData.addInRangeArea(fromTime, toTime, lowLine, highLine); graphData.addInRangeArea(fromTime, toTime, lowLine, highLine);
@ -267,143 +295,137 @@ public class HistoryBrowseActivity extends AppCompatActivity {
// ------------------ 2nd graph // ------------------ 2nd graph
final GraphData secondGraphData = new GraphData(iobGraph, iobCobCalculatorPlugin); new Thread(() -> {
final GraphData secondGraphData = new GraphData(iobGraph, iobCobCalculatorPlugin);
boolean useIobForScale = false; boolean useIobForScale = false;
boolean useCobForScale = false; boolean useCobForScale = false;
boolean useDevForScale = false; boolean useDevForScale = false;
boolean useRatioForScale = false; boolean useRatioForScale = false;
boolean useDevSlopeForScale = false; boolean useDSForScale = false;
if (showIob) { if (showIob) {
useIobForScale = true; useIobForScale = true;
} else if (showCob) { } else if (showCob) {
useCobForScale = true; useCobForScale = true;
} else if (showDev) { } else if (showDev) {
useDevForScale = true; useDevForScale = true;
} else if (showRat) { } else if (showRat) {
useRatioForScale = true; useRatioForScale = true;
} else if (showDevslope) { } else if (showDevslope) {
useDevSlopeForScale = true; useDSForScale = true;
} }
if (showIob) if (showIob)
secondGraphData.addIob(fromTime, toTime, useIobForScale, 1d); secondGraphData.addIob(fromTime, toTime, useIobForScale, 1d);
if (showCob) if (showCob)
secondGraphData.addCob(fromTime, toTime, useCobForScale, useCobForScale ? 1d : 0.5d); secondGraphData.addCob(fromTime, toTime, useCobForScale, useCobForScale ? 1d : 0.5d);
if (showDev) if (showDev)
secondGraphData.addDeviations(fromTime, toTime, useDevForScale, 1d); secondGraphData.addDeviations(fromTime, toTime, useDevForScale, 1d);
if (showRat) if (showRat)
secondGraphData.addRatio(fromTime, toTime, useRatioForScale, 1d); secondGraphData.addRatio(fromTime, toTime, useRatioForScale, 1d);
if (showDevslope) if (showDevslope)
secondGraphData.addDeviationSlope(fromTime, toTime, useDevSlopeForScale, 1d); secondGraphData.addDeviationSlope(fromTime, toTime, useDSForScale, 1d);
// **** NOW line **** // **** NOW line ****
// set manual x bounds to have nice steps // set manual x bounds to have nice steps
secondGraphData.formatAxis(fromTime, toTime); secondGraphData.formatAxis(fromTime, toTime);
secondGraphData.addNowLine(pointer); secondGraphData.addNowLine(pointer);
// do GUI update // do GUI update
if (showIob || showCob || showDev || showRat || showDevslope) { runOnUiThread(() -> {
iobGraph.setVisibility(View.VISIBLE); if (showIob || showCob || showDev || showRat || showDevslope) {
} else { iobGraph.setVisibility(View.VISIBLE);
iobGraph.setVisibility(View.GONE); } else {
} iobGraph.setVisibility(View.GONE);
// finally enforce drawing of graphs }
graphData.performUpdate(); // finally enforce drawing of graphs
secondGraphData.performUpdate(); graphData.performUpdate();
if (showIob || showCob || showDev || showRat || showDevslope)
secondGraphData.performUpdate();
});
}).start();
} }
private void setupChartMenu() { private void setupChartMenu() {
chartButton = (ImageButton) findViewById(R.id.overview_chartMenuButton); chartButton = (ImageButton) findViewById(R.id.overview_chartMenuButton);
chartButton.setOnClickListener(new View.OnClickListener() { chartButton.setOnClickListener(v -> {
@Override MenuItem item;
public void onClick(View v) { CharSequence title;
MenuItem item; SpannableString s;
CharSequence title; PopupMenu popup = new PopupMenu(v.getContext(), v);
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(); title = item.getTitle();
s = new SpannableString(title); 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.setTitle(s);
item.setCheckable(true); item.setCheckable(true);
item.setChecked(showBasal); item.setChecked(showDevslope);
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();
} }
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();
}); });
} }

View file

@ -344,7 +344,6 @@ public class MainActivity extends AppCompatActivity {
public boolean onCreateOptionsMenu(Menu menu) { public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu); getMenuInflater().inflate(R.menu.menu_main, menu);
pluginPreferencesMenuItem = menu.findItem(R.id.nav_plugin_preferences); pluginPreferencesMenuItem = menu.findItem(R.id.nav_plugin_preferences);
menu.findItem(R.id.nav_historybrowser).setVisible(MainApp.devBranch);
checkPluginPreferences(findViewById(R.id.pager)); checkPluginPreferences(findViewById(R.id.pager));
return true; return true;
} }

View file

@ -431,6 +431,23 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return new ArrayList<BgReading>(); return new ArrayList<BgReading>();
} }
public List<BgReading> getBgreadingsDataFromTime(long start, long end, boolean ascending) {
try {
Dao<BgReading, Long> daoBgreadings = getDaoBgReadings();
List<BgReading> bgReadings;
QueryBuilder<BgReading, Long> 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<BgReading> preparedQuery = queryBuilder.prepare();
bgReadings = daoBgreadings.query(preparedQuery);
return bgReadings;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<BgReading>();
}
public List<BgReading> getAllBgreadingsDataFromTime(long mills, boolean ascending) { public List<BgReading> getAllBgreadingsDataFromTime(long mills, boolean ascending) {
try { try {
Dao<BgReading, Long> daoBgreadings = getDaoBgReadings(); Dao<BgReading, Long> daoBgreadings = getDaoBgReadings();

View file

@ -1,6 +1,7 @@
package info.nightscout.androidaps.interfaces; package info.nightscout.androidaps.interfaces;
import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensResult;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
/** /**
* Created by mike on 24.06.2017. * Created by mike on 24.06.2017.
@ -11,6 +12,6 @@ public interface SensitivityInterface {
double MIN_HOURS = 1; double MIN_HOURS = 1;
double MIN_HOURS_FULL_AUTOSENS = 4; double MIN_HOURS_FULL_AUTOSENS = 4;
AutosensResult detectSensitivity(long fromTime, long toTime); AutosensResult detectSensitivity(IobCobCalculatorPlugin plugin, long fromTime, long toTime);
} }

View file

@ -87,7 +87,6 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
tempBasalCancel.setOnClickListener(this); tempBasalCancel.setOnClickListener(this);
fill.setOnClickListener(this); fill.setOnClickListener(this);
history.setOnClickListener(this); history.setOnClickListener(this);
history.setVisibility(MainApp.devBranch ? View.VISIBLE : View.GONE);
tddStats.setOnClickListener(this); tddStats.setOnClickListener(this);
updateGUI(); updateGUI();

View file

@ -1,6 +1,7 @@
package info.nightscout.androidaps.plugins.IobCobCalculator; package info.nightscout.androidaps.plugins.IobCobCalculator;
import android.os.SystemClock; import android.os.SystemClock;
import android.provider.SyncStateContract;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import android.support.v4.util.LongSparseArray; import android.support.v4.util.LongSparseArray;
@ -98,6 +99,10 @@ public class IobCobCalculatorPlugin extends PluginBase {
return autosensDataTable; return autosensDataTable;
} }
public List<BgReading> getBgReadings() {
return bgReadings;
}
public List<BgReading> getBucketedData() { public List<BgReading> getBucketedData() {
return bucketed_data; return bucketed_data;
} }
@ -136,13 +141,10 @@ public class IobCobCalculatorPlugin extends PluginBase {
return rounded; return rounded;
} }
void loadBgData(long start) { void loadBgData(long now) {
if (start < oldestDataAvailable()) { long start = (long) (now - 60 * 60 * 1000L * (24 + dia));
start = oldestDataAvailable(); bgReadings = MainApp.getDbHelper().getBgreadingsDataFromTime(start, now, false);
log.debug("Limiting BG data to oldest data available: " + DateUtil.dateAndTimeString(start)); log.debug("BG data loaded. Size: " + bgReadings.size() + " Start date: " + DateUtil.dateAndTimeString(start) + " End date: " + DateUtil.dateAndTimeString(now));
}
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));
} }
private boolean isAbout5minData() { private boolean isAbout5minData() {
@ -294,12 +296,19 @@ public class IobCobCalculatorPlugin extends PluginBase {
log.debug("Bucketed data created. Size: " + bucketed_data.size()); log.debug("Bucketed data created. Size: " + bucketed_data.size());
} }
public long oldestDataAvailable() { public long calculateDetectionStart(long from, boolean limitDataToOldestAvailable) {
long now = System.currentTimeMillis(); Profile profile = MainApp.getConfigBuilder().getProfile(from);
double dia = Constants.defaultDIA;
if (profile != null) dia = profile.getDia();
long oldestDataAvailable = TreatmentsPlugin.getPlugin().oldestDataAvailable(); long oldestDataAvailable = TreatmentsPlugin.getPlugin().oldestDataAvailable();
long getBGDataFrom = Math.max(oldestDataAvailable, (long) (now - T.hours(1).msecs() * (24 + MainApp.getConfigBuilder().getProfile().getDia()))); long getBGDataFrom;
log.debug("Limiting data to oldest available temps: " + new Date(oldestDataAvailable).toString()); 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; return getBGDataFrom;
} }
@ -403,7 +412,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
@Nullable @Nullable
public AutosensData getLastAutosensDataSynchronized(String reason) { public AutosensData getLastAutosensDataSynchronized(String reason) {
if (thread != null && thread.isAlive()) { if (thread != null && thread.isAlive()) {
log.debug("AUTOSENSDATA is waiting for calculation thread: " + reason); log.debug("AUTOSENSDATA is waiting for calculation thread: " + reason);
try { try {
thread.join(5000); thread.join(5000);
@ -510,7 +519,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
public AutosensResult detectSensitivityWithLock(long fromTime, long toTime) { public AutosensResult detectSensitivityWithLock(long fromTime, long toTime) {
synchronized (dataLock) { 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"); log.debug("Ignoring event for non default instance");
return; return;
} }
runCalculation("onEventAppInitialized", System.currentTimeMillis(), true, ev); runCalculation("onEventAppInitialized", System.currentTimeMillis(), true, true, ev);
} }
@Subscribe @Subscribe
@ -540,10 +549,10 @@ public class IobCobCalculatorPlugin extends PluginBase {
return; return;
} }
stopCalculation("onEventNewBG"); 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) { if (thread != null && thread.getState() != Thread.State.TERMINATED) {
stopCalculationTrigger = true; stopCalculationTrigger = true;
log.debug("Stopping calculation thread: " + from); 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) { public void runCalculation(String from, long end, boolean bgDataReload, boolean limitDataToOldestAvailable, Event cause) {
log.debug("Starting calculation thread: " + from); log.debug("Starting calculation thread: " + from + " to " + DateUtil.dateAndTimeString(end));
if (thread == null || thread.getState() == Thread.State.TERMINATED) { if (thread == null || thread.getState() == Thread.State.TERMINATED) {
if (SensitivityOref1Plugin.getPlugin().isEnabled(PluginType.SENSITIVITY)) if (SensitivityOref1Plugin.getPlugin().isEnabled(PluginType.SENSITIVITY))
thread = new IobCobOref1Thread(this, from, start, bgDataReload, cause); thread = new IobCobOref1Thread(this, from, end, bgDataReload, limitDataToOldestAvailable, cause);
else else
thread = new IobCobThread(this, from, start, bgDataReload, cause); thread = new IobCobThread(this, from, end, bgDataReload, limitDataToOldestAvailable, cause);
thread.start(); thread.start();
} }
} }
@ -586,7 +595,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
iobTable = new LongSparseArray<>(); iobTable = new LongSparseArray<>();
autosensDataTable = new LongSparseArray<>(); autosensDataTable = new LongSparseArray<>();
} }
runCalculation("onNewProfile", System.currentTimeMillis(), false, ev); runCalculation("onNewProfile", System.currentTimeMillis(), false, true, ev);
} }
@Subscribe @Subscribe
@ -609,7 +618,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
iobTable = new LongSparseArray<>(); iobTable = new LongSparseArray<>();
autosensDataTable = 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<>(); iobTable = new LongSparseArray<>();
autosensDataTable = 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 // 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"); //log.debug("Releasing onNewHistoryData");
} }

View file

@ -48,19 +48,21 @@ public class IobCobOref1Thread extends Thread {
private IobCobCalculatorPlugin iobCobCalculatorPlugin; private IobCobCalculatorPlugin iobCobCalculatorPlugin;
private boolean bgDataReload; private boolean bgDataReload;
private boolean limitDataToOldestAvailable;
private String from; private String from;
private long start; private long end;
private PowerManager.WakeLock mWakeLock; 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(); super();
this.iobCobCalculatorPlugin = plugin; this.iobCobCalculatorPlugin = plugin;
this.bgDataReload = bgDataReload; this.bgDataReload = bgDataReload;
this.limitDataToOldestAvailable = limitDataToOldestAvailable;
this.from = from; this.from = from;
this.cause = cause; this.cause = cause;
this.start = start; this.end = end;
PowerManager powerManager = (PowerManager) MainApp.instance().getApplicationContext().getSystemService(Context.POWER_SERVICE); PowerManager powerManager = (PowerManager) MainApp.instance().getApplicationContext().getSystemService(Context.POWER_SERVICE);
mWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "iobCobThread"); mWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "iobCobThread");
@ -81,15 +83,15 @@ public class IobCobOref1Thread extends Thread {
} }
//log.debug("Locking calculateSensitivityData"); //log.debug("Locking calculateSensitivityData");
long oldestTimeWithData = iobCobCalculatorPlugin.oldestDataAvailable(); long oldestTimeWithData = iobCobCalculatorPlugin.calculateDetectionStart(end, limitDataToOldestAvailable);
synchronized (iobCobCalculatorPlugin.dataLock) { synchronized (iobCobCalculatorPlugin.dataLock) {
if (bgDataReload) { if (bgDataReload) {
iobCobCalculatorPlugin.loadBgData(start); iobCobCalculatorPlugin.loadBgData(end);
iobCobCalculatorPlugin.createBucketedData(); iobCobCalculatorPlugin.createBucketedData();
} }
List<BgReading> bucketed_data = iobCobCalculatorPlugin.getBucketedData(); List<BgReading> bucketed_data = iobCobCalculatorPlugin.getBucketedData();
LongSparseArray<AutosensData> autosensDataTable = IobCobCalculatorPlugin.getPlugin().getAutosensDataTable(); LongSparseArray<AutosensData> autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable();
if (bucketed_data == null || bucketed_data.size() < 3) { if (bucketed_data == null || bucketed_data.size() < 3) {
log.debug("Aborting calculation thread (No bucketed data available): " + from); 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 // 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 if (i < bucketed_data.size() - 16) { // we need 1h of data to calculate minDeviationSlope
long hourago = bgTime + 10 * 1000 - 60 * 60 * 1000L; long hourago = bgTime + 10 * 1000 - 60 * 60 * 1000L;
AutosensData hourAgoData = IobCobCalculatorPlugin.getPlugin().getAutosensData(hourago); AutosensData hourAgoData = iobCobCalculatorPlugin.getAutosensData(hourago);
if (hourAgoData != null) { if (hourAgoData != null) {
int initialIndex = autosensDataTable.indexOfKey(hourAgoData.time); int initialIndex = autosensDataTable.indexOfKey(hourAgoData.time);
if (Config.logAutosensData) if (Config.logAutosensData)
@ -339,7 +341,7 @@ public class IobCobOref1Thread extends Thread {
if (bgTime < now()) if (bgTime < now())
autosensDataTable.put(bgTime, autosensData); autosensDataTable.put(bgTime, autosensData);
if (Config.logAutosensData) 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); AutosensResult sensitivity = iobCobCalculatorPlugin.detectSensitivityWithLock(oldestTimeWithData, bgTime);
if (Config.logAutosensData) if (Config.logAutosensData)
log.debug("Sensitivity result: " + sensitivity.toString()); log.debug("Sensitivity result: " + sensitivity.toString());

View file

@ -47,19 +47,21 @@ public class IobCobThread extends Thread {
private IobCobCalculatorPlugin iobCobCalculatorPlugin; private IobCobCalculatorPlugin iobCobCalculatorPlugin;
private boolean bgDataReload; private boolean bgDataReload;
private boolean limitDataToOldestAvailable;
private String from; private String from;
private long start; private long end;
private PowerManager.WakeLock mWakeLock; 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(); super();
this.iobCobCalculatorPlugin = plugin; this.iobCobCalculatorPlugin = plugin;
this.bgDataReload = bgDataReload; this.bgDataReload = bgDataReload;
this.limitDataToOldestAvailable = limitDataToOldestAvailable;
this.from = from; this.from = from;
this.cause = cause; this.cause = cause;
this.start = start; this.end = end;
PowerManager powerManager = (PowerManager) MainApp.instance().getApplicationContext().getSystemService(Context.POWER_SERVICE); PowerManager powerManager = (PowerManager) MainApp.instance().getApplicationContext().getSystemService(Context.POWER_SERVICE);
mWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "iobCobThread"); mWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "iobCobThread");
@ -80,15 +82,15 @@ public class IobCobThread extends Thread {
} }
//log.debug("Locking calculateSensitivityData"); //log.debug("Locking calculateSensitivityData");
long oldestTimeWithData = iobCobCalculatorPlugin.oldestDataAvailable(); long oldestTimeWithData = iobCobCalculatorPlugin.calculateDetectionStart(end, limitDataToOldestAvailable);
synchronized (iobCobCalculatorPlugin.dataLock) { synchronized (iobCobCalculatorPlugin.dataLock) {
if (bgDataReload) { if (bgDataReload) {
iobCobCalculatorPlugin.loadBgData(start); iobCobCalculatorPlugin.loadBgData(end);
iobCobCalculatorPlugin.createBucketedData(); iobCobCalculatorPlugin.createBucketedData();
} }
List<BgReading> bucketed_data = iobCobCalculatorPlugin.getBucketedData(); List<BgReading> bucketed_data = iobCobCalculatorPlugin.getBucketedData();
LongSparseArray<AutosensData> autosensDataTable = IobCobCalculatorPlugin.getPlugin().getAutosensDataTable(); LongSparseArray<AutosensData> autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable();
if (bucketed_data == null || bucketed_data.size() < 3) { if (bucketed_data == null || bucketed_data.size() < 3) {
log.debug("Aborting calculation thread (No bucketed data available): " + from); 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 // 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 if (i < bucketed_data.size() - 16) { // we need 1h of data to calculate minDeviationSlope
long hourago = bgTime + 10 * 1000 - 60 * 60 * 1000L; long hourago = bgTime + 10 * 1000 - 60 * 60 * 1000L;
AutosensData hourAgoData = IobCobCalculatorPlugin.getPlugin().getAutosensData(hourago); AutosensData hourAgoData = iobCobCalculatorPlugin.getAutosensData(hourago);
if (hourAgoData != null) { if (hourAgoData != null) {
int initialIndex = autosensDataTable.indexOfKey(hourAgoData.time); int initialIndex = autosensDataTable.indexOfKey(hourAgoData.time);
if (Config.logAutosensData) if (Config.logAutosensData)
@ -266,7 +268,7 @@ public class IobCobThread extends Thread {
if (bgTime < now()) if (bgTime < now())
autosensDataTable.put(bgTime, autosensData); autosensDataTable.put(bgTime, autosensData);
if (Config.logAutosensData) 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); AutosensResult sensitivity = iobCobCalculatorPlugin.detectSensitivityWithLock(oldestTimeWithData, bgTime);
if (Config.logAutosensData) if (Config.logAutosensData)
log.debug("Sensitivity result: " + sensitivity.toString()); log.debug("Sensitivity result: " + sensitivity.toString());

View file

@ -85,6 +85,7 @@ import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialo
import info.nightscout.androidaps.plugins.Careportal.OptionsToShow; import info.nightscout.androidaps.plugins.Careportal.OptionsToShow;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin; 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.AutosensResult;
import info.nightscout.androidaps.plugins.IobCobCalculator.CobInfo; import info.nightscout.androidaps.plugins.IobCobCalculator.CobInfo;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
@ -1384,9 +1385,9 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
// Sensitivity // Sensitivity
if (sensitivityView != null) { if (sensitivityView != null) {
AutosensResult lastAutosensResult = IobCobCalculatorPlugin.getPlugin().detectSensitivityWithLock(IobCobCalculatorPlugin.getPlugin().oldestDataAvailable(), System.currentTimeMillis()); AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getLastAutosensDataSynchronized("Overview");
if (lastAutosensResult != null) if (autosensData != null)
sensitivityView.setText(String.format("%.0f%%", lastAutosensResult.ratio * 100)); sensitivityView.setText(String.format("%.0f%%", autosensData.autosensResult.ratio * 100));
else else
sensitivityView.setText(""); sensitivityView.setText("");
} }

View file

@ -11,6 +11,9 @@ import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries; import com.jjoe64.graphview.series.LineGraphSeries;
import com.jjoe64.graphview.series.Series; import com.jjoe64.graphview.series.Series;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@ -47,6 +50,7 @@ import info.nightscout.utils.Round;
*/ */
public class GraphData { public class GraphData {
private static Logger log = LoggerFactory.getLogger(GraphData.class);
private GraphView graph; private GraphView graph;
public double maxY = Double.MIN_VALUE; public double maxY = Double.MIN_VALUE;
@ -65,14 +69,17 @@ public class GraphData {
public void addBgReadings(long fromTime, long toTime, double lowLine, double highLine, List<BgReading> predictions) { public void addBgReadings(long fromTime, long toTime, double lowLine, double highLine, List<BgReading> predictions) {
double maxBgValue = Double.MIN_VALUE; double maxBgValue = Double.MIN_VALUE;
bgReadingsArray = MainApp.getDbHelper().getBgreadingsDataFromTime(fromTime, true); //bgReadingsArray = MainApp.getDbHelper().getBgreadingsDataFromTime(fromTime, true);
bgReadingsArray = iobCobCalculatorPlugin.getBgReadings();
List<DataPointWithLabelInterface> bgListArray = new ArrayList<>(); List<DataPointWithLabelInterface> bgListArray = new ArrayList<>();
if (bgReadingsArray.size() == 0) { if (bgReadingsArray == null || bgReadingsArray.size() == 0) {
log.debug("No BG data.");
return; return;
} }
for (BgReading bg : bgReadingsArray) { for (BgReading bg : bgReadingsArray) {
if (bg.date < fromTime || bg.date > toTime) continue;
if (bg.value > maxBgValue) maxBgValue = bg.value; if (bg.value > maxBgValue) maxBgValue = bg.value;
bgListArray.add(bg); bgListArray.add(bg);
} }
@ -137,7 +144,7 @@ public class GraphData {
for (long time = fromTime; time < toTime; time += 60 * 1000L) { for (long time = fromTime; time < toTime; time += 60 * 1000L) {
Profile profile = MainApp.getConfigBuilder().getProfile(time); Profile profile = MainApp.getConfigBuilder().getProfile(time);
if (profile == null) continue; if (profile == null) continue;
BasalData basalData = IobCobCalculatorPlugin.getPlugin().getBasalData(profile, time); BasalData basalData = iobCobCalculatorPlugin.getBasalData(profile, time);
double baseBasalValue = basalData.basal; double baseBasalValue = basalData.basal;
double absoluteLineValue = baseBasalValue; double absoluteLineValue = baseBasalValue;
double tempBasalValue = 0; double tempBasalValue = 0;
@ -321,13 +328,13 @@ public class GraphData {
} }
private double getNearestBg(long date) { 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); BgReading reading = bgReadingsArray.get(r);
if (reading.date > date) continue; if (reading.date > date) continue;
return Profile.fromMgdlToUnits(reading.value, units); return Profile.fromMgdlToUnits(reading.value, units);
} }
return bgReadingsArray.size() > 0 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) // scale in % of vertical size (like 0.3)
@ -342,7 +349,7 @@ public class GraphData {
Profile profile = MainApp.getConfigBuilder().getProfile(time); Profile profile = MainApp.getConfigBuilder().getProfile(time);
double iob = 0d; double iob = 0d;
if (profile != null) 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.02) {
if (Math.abs(lastIob - iob) > 0.2) if (Math.abs(lastIob - iob) > 0.2)
iobArray.add(new ScaledDataPoint(time, lastIob, iobScale)); iobArray.add(new ScaledDataPoint(time, lastIob, iobScale));
@ -380,7 +387,7 @@ public class GraphData {
Scale cobScale = new Scale(); Scale cobScale = new Scale();
for (long time = fromTime; time <= toTime; time += 5 * 60 * 1000L) { for (long time = fromTime; time <= toTime; time += 5 * 60 * 1000L) {
AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getAutosensData(time); AutosensData autosensData = iobCobCalculatorPlugin.getAutosensData(time);
if (autosensData != null) { if (autosensData != null) {
int cob = (int) autosensData.cob; int cob = (int) autosensData.cob;
if (cob != lastCob) { if (cob != lastCob) {
@ -438,7 +445,7 @@ public class GraphData {
Scale devScale = new Scale(); Scale devScale = new Scale();
for (long time = fromTime; time <= toTime; time += 5 * 60 * 1000L) { for (long time = fromTime; time <= toTime; time += 5 * 60 * 1000L) {
AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getAutosensData(time); AutosensData autosensData = iobCobCalculatorPlugin.getAutosensData(time);
if (autosensData != null) { if (autosensData != null) {
int color = MainApp.gc(R.color.deviationblack); // "=" int color = MainApp.gc(R.color.deviationblack); // "="
if (autosensData.type.equals("") || autosensData.type.equals("non-meal")) { if (autosensData.type.equals("") || autosensData.type.equals("non-meal")) {
@ -488,7 +495,7 @@ public class GraphData {
Scale ratioScale = new Scale(); Scale ratioScale = new Scale();
for (long time = fromTime; time <= toTime; time += 5 * 60 * 1000L) { for (long time = fromTime; time <= toTime; time += 5 * 60 * 1000L) {
AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getAutosensData(time); AutosensData autosensData = iobCobCalculatorPlugin.getAutosensData(time);
if (autosensData != null) { if (autosensData != null) {
ratioArray.add(new ScaledDataPoint(time, autosensData.autosensResult.ratio - 1, ratioScale)); ratioArray.add(new ScaledDataPoint(time, autosensData.autosensResult.ratio - 1, ratioScale));
maxRatioValueFound = Math.max(maxRatioValueFound, autosensData.autosensResult.ratio - 1); maxRatioValueFound = Math.max(maxRatioValueFound, autosensData.autosensResult.ratio - 1);
@ -525,7 +532,7 @@ public class GraphData {
Scale dsMinScale = new Scale(); Scale dsMinScale = new Scale();
for (long time = fromTime; time <= toTime; time += 5 * 60 * 1000L) { for (long time = fromTime; time <= toTime; time += 5 * 60 * 1000L) {
AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getAutosensData(time); AutosensData autosensData = iobCobCalculatorPlugin.getAutosensData(time);
if (autosensData != null) { if (autosensData != null) {
dsMaxArray.add(new ScaledDataPoint(time, autosensData.slopeFromMaxDeviation, dsMaxScale)); dsMaxArray.add(new ScaledDataPoint(time, autosensData.slopeFromMaxDeviation, dsMaxScale));
dsMinArray.add(new ScaledDataPoint(time, autosensData.slopeFromMinDeviation, dsMinScale)); dsMinArray.add(new ScaledDataPoint(time, autosensData.slopeFromMinDeviation, dsMinScale));

View file

@ -8,6 +8,7 @@ import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.SensitivityInterface; import info.nightscout.androidaps.interfaces.SensitivityInterface;
import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensResult;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.utils.Round; import info.nightscout.utils.Round;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse; import info.nightscout.utils.SafeParse;
@ -21,10 +22,10 @@ public abstract class AbstractSensitivityPlugin extends PluginBase implements Se
} }
@Override @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, AutosensResult fillResult(double ratio, double carbsAbsorbed, String pastSensitivity,
String ratioLimit, String sensResult, int deviationsArraySize) { String ratioLimit, String sensResult, int deviationsArraySize) {
return this.fillResult(ratio, carbsAbsorbed, pastSensitivity, ratioLimit, sensResult, return this.fillResult(ratio, carbsAbsorbed, pastSensitivity, ratioLimit, sensResult,
deviationsArraySize, deviationsArraySize,
SafeParse.stringToDouble(SP.getString(R.string.key_openapsama_autosens_min, "0.7")), SafeParse.stringToDouble(SP.getString(R.string.key_openapsama_autosens_min, "0.7")),
@ -32,8 +33,8 @@ public abstract class AbstractSensitivityPlugin extends PluginBase implements Se
} }
public AutosensResult fillResult(double ratio, double carbsAbsorbed, String pastSensitivity, public AutosensResult fillResult(double ratio, double carbsAbsorbed, String pastSensitivity,
String ratioLimit, String sensResult, int deviationsArraySize, String ratioLimit, String sensResult, int deviationsArraySize,
double ratioMin, double ratioMax) { double ratioMin, double ratioMax) {
double rawRatio = ratio; double rawRatio = ratio;
ratio = Math.max(ratio, ratioMin); ratio = Math.max(ratio, ratioMin);
ratio = Math.min(ratio, ratioMax); ratio = Math.min(ratio, ratioMax);
@ -64,5 +65,4 @@ public abstract class AbstractSensitivityPlugin extends PluginBase implements Se
} }
} }

View file

@ -49,8 +49,8 @@ public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin {
} }
@Override @Override
public AutosensResult detectSensitivity(long fromTime, long toTime) { public AutosensResult detectSensitivity(IobCobCalculatorPlugin iobCobCalculatorPlugin, long fromTime, long toTime) {
LongSparseArray<AutosensData> autosensDataTable = IobCobCalculatorPlugin.getPlugin().getAutosensDataTable(); LongSparseArray<AutosensData> autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable();
String age = SP.getString(R.string.key_age, ""); String age = SP.getString(R.string.key_age, "");
int defaultHours = 24; int defaultHours = 24;
@ -67,13 +67,13 @@ public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin {
} }
if (autosensDataTable == null || autosensDataTable.size() < 4) { 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(); 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 (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(); return new AutosensResult();
} }

View file

@ -48,8 +48,8 @@ public class SensitivityOref0Plugin extends AbstractSensitivityPlugin {
} }
@Override @Override
public AutosensResult detectSensitivity(long fromTime, long toTime) { public AutosensResult detectSensitivity(IobCobCalculatorPlugin iobCobCalculatorPlugin, long fromTime, long toTime) {
LongSparseArray<AutosensData> autosensDataTable = IobCobCalculatorPlugin.getPlugin().getAutosensDataTable(); LongSparseArray<AutosensData> autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable();
int hoursForDetection = 24; int hoursForDetection = 24;
@ -62,13 +62,13 @@ public class SensitivityOref0Plugin extends AbstractSensitivityPlugin {
} }
if (autosensDataTable == null || autosensDataTable.size() < 4) { 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(); 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 (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(); return new AutosensResult();
} }

View file

@ -48,10 +48,10 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin {
} }
@Override @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 // todo this method is called from the IobCobCalculatorPlugin, which leads to a circular
// dependency, this should be avoided // dependency, this should be avoided
LongSparseArray<AutosensData> autosensDataTable = IobCobCalculatorPlugin.getPlugin().getAutosensDataTable(); LongSparseArray<AutosensData> autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable();
Profile profile = MainApp.getConfigBuilder().getProfile(); Profile profile = MainApp.getConfigBuilder().getProfile();
@ -61,14 +61,14 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin {
} }
if (autosensDataTable == null || autosensDataTable.size() < 4) { 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(); return new AutosensResult();
} }
// the current // 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) { 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(); return new AutosensResult();
} }

View file

@ -47,8 +47,8 @@ public class SensitivityWeightedAveragePlugin extends AbstractSensitivityPlugin
} }
@Override @Override
public AutosensResult detectSensitivity(long fromTime, long toTime) { public AutosensResult detectSensitivity(IobCobCalculatorPlugin iobCobCalculatorPlugin, long fromTime, long toTime) {
LongSparseArray<AutosensData> autosensDataTable = IobCobCalculatorPlugin.getPlugin().getAutosensDataTable(); LongSparseArray<AutosensData> autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable();
String age = SP.getString(R.string.key_age, ""); String age = SP.getString(R.string.key_age, "");
int defaultHours = 24; int defaultHours = 24;
@ -58,14 +58,14 @@ public class SensitivityWeightedAveragePlugin extends AbstractSensitivityPlugin
int hoursForDetection = SP.getInt(R.string.key_openapsama_autosens_period, defaultHours); int hoursForDetection = SP.getInt(R.string.key_openapsama_autosens_period, defaultHours);
if (autosensDataTable == null || autosensDataTable.size() < 4) { 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(); 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 (current == null) {
if (Config.logAutosensData) 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(); return new AutosensResult();
} }

View file

@ -27,41 +27,35 @@
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:orientation="horizontal"> android:orientation="horizontal">
<ImageButton
android:id="@+id/historybrowse_start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/ic_first_page_black_24dp" />
<ImageButton <ImageButton
android:id="@+id/historybrowse_left" android:id="@+id/historybrowse_left"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="match_parent"
app:srcCompat="@drawable/ic_chevron_left_black_24dp" /> app:srcCompat="@drawable/ic_chevron_left_black_24dp" />
<Button <Button
android:id="@+id/historybrowse_date" android:id="@+id/historybrowse_date"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="match_parent"
android:layout_weight="1" android:layout_weight="1"
android:text="Button" /> android:text="Button" />
<ImageButton <ImageButton
android:id="@+id/historybrowse_right" android:id="@+id/historybrowse_right"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="match_parent"
app:srcCompat="@drawable/ic_chevron_right_black_24dp" /> app:srcCompat="@drawable/ic_chevron_right_black_24dp" />
<ImageButton <ImageButton
android:id="@+id/historybrowse_end" android:id="@+id/historybrowse_end"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="match_parent"
app:srcCompat="@drawable/ic_last_page_black_24dp" /> app:srcCompat="@drawable/ic_last_page_black_24dp" />
<Button <Button
android:id="@+id/historybrowse_zoom" android:id="@+id/historybrowse_zoom"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="match_parent"
android:layout_weight="1" android:layout_weight="1"
android:text="24" /> android:text="24" />

View file

@ -3,8 +3,8 @@ package info.nightscout.androidaps.plugins.Sensitivity;
import org.junit.Test; import org.junit.Test;
import info.nightscout.androidaps.interfaces.PluginDescription; 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.AutosensResult;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
@ -21,7 +21,7 @@ public class AbstractSensitivityPluginTest {
} }
@Override @Override
public AutosensResult detectSensitivity(long fromTime, long toTime) { public AutosensResult detectSensitivity(IobCobCalculatorPlugin plugin, long fromTime, long toTime) {
return null; return null;
} }
} }