temp basal rendering

This commit is contained in:
Milos Kozak 2016-06-23 17:07:38 +02:00
parent 91b36a8528
commit a57409c388
17 changed files with 233 additions and 87 deletions

View file

@ -20,6 +20,7 @@ public class Config {
public static final boolean logPrefsChange = true; public static final boolean logPrefsChange = true;
public static final boolean logConfigBuilder = true; public static final boolean logConfigBuilder = true;
public static final boolean logConstraintsChanges = true; public static final boolean logConstraintsChanges = true;
public static final boolean logTempBasalsCut = true;
// Developing mode only - never turn on // Developing mode only - never turn on
// TODO: remove fakeGlucoseData // TODO: remove fakeGlucoseData

View file

@ -13,6 +13,7 @@ public class Result extends Object implements Parcelable{
public Double absolute = -1d; // absolute rate [U/h] , isPercent = false public Double absolute = -1d; // absolute rate [U/h] , isPercent = false
public Integer percent = -1; // percent of current basal [%] (100% = current basal), isPercent = true public Integer percent = -1; // percent of current basal [%] (100% = current basal), isPercent = true
public boolean isPercent = false; // if true percent is used, otherwise absolute public boolean isPercent = false; // if true percent is used, otherwise absolute
public boolean isTempCancel = false; // if true we are caceling temp basal
// Result of treatment delivery // Result of treatment delivery
public Double bolusDelivered = 0d; // real value of delivered insulin public Double bolusDelivered = 0d; // real value of delivered insulin
public Integer carbsDelivered = 0; // real value of delivered carbs public Integer carbsDelivered = 0; // real value of delivered carbs
@ -24,7 +25,10 @@ public class Result extends Object implements Parcelable{
public String toString() { public String toString() {
String ret = "Success: " + success; String ret = "Success: " + success;
if (enacted) { if (enacted) {
if (isPercent) { if (isTempCancel) {
ret += "\nEnacted: " + enacted + "\nComment: " + comment + "\n" +
"Temp cancel";
} else if (isPercent) {
ret += "\nEnacted: " + enacted + "\nComment: " + comment + "\nDuration: " + duration + " min\nPercent: " + percent + "%"; ret += "\nEnacted: " + enacted + "\nComment: " + comment + "\nDuration: " + duration + " min\nPercent: " + percent + "%";
} else { } else {
ret += "\nEnacted: " + enacted + "\nComment: " + comment + "\nDuration: " + duration + " min\nAbsolute: " + absolute + " U/h"; ret += "\nEnacted: " + enacted + "\nComment: " + comment + "\nDuration: " + duration + " min\nAbsolute: " + absolute + " U/h";

View file

@ -181,7 +181,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
Dao<BgReading, Long> daoBgreadings = getDaoBgReadings(); Dao<BgReading, Long> daoBgreadings = getDaoBgReadings();
List<BgReading> bgReadings; List<BgReading> bgReadings;
QueryBuilder<BgReading, Long> queryBuilder = daoBgreadings.queryBuilder(); QueryBuilder<BgReading, Long> queryBuilder = daoBgreadings.queryBuilder();
queryBuilder.orderBy("timeIndex", false); queryBuilder.orderBy("timeIndex", true);
Where where = queryBuilder.where(); Where where = queryBuilder.where();
where.ge("timeIndex", (long) Math.ceil(mills / 60000d)); where.ge("timeIndex", (long) Math.ceil(mills / 60000d));
PreparedQuery<BgReading> preparedQuery = queryBuilder.prepare(); PreparedQuery<BgReading> preparedQuery = queryBuilder.prepare();

View file

@ -145,15 +145,27 @@ public class TempBasal {
} }
public boolean isInProgress() { public boolean isInProgress() {
long now = new Date().getTime(); return isInProgress(new Date());
if (timeStart.getTime() > now) return false; // in the future }
public double tempBasalConvertedToAbsolute() {
if (isAbsolute) return absolute;
else {
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
double absval = profile.getBasal(NSProfile.secondsFromMidnight()) * percent / 100;
return absval;
}
}
public boolean isInProgress(Date time) {
if (timeStart.getTime() > time.getTime()) return false; // in the future
if (timeEnd == null) { // open end if (timeEnd == null) { // open end
if (timeStart.getTime() < now && getPlannedTimeEnd().getTime() > now) if (timeStart.getTime() < time.getTime() && getPlannedTimeEnd().getTime() > time.getTime())
return true; // in interval return true; // in interval
return false; return false;
} }
// closed end // closed end
if (timeStart.getTime() < now && timeEnd.getTime() > now) return true; // in interval if (timeStart.getTime() < time.getTime() && timeEnd.getTime() > time.getTime()) return true; // in interval
return false; return false;
} }

View file

@ -1,5 +1,8 @@
package info.nightscout.androidaps.interfaces; package info.nightscout.androidaps.interfaces;
import java.util.Date;
import info.nightscout.androidaps.db.TempBasal;
import info.nightscout.androidaps.plugins.OpenAPSMA.IobTotal; import info.nightscout.androidaps.plugins.OpenAPSMA.IobTotal;
/** /**
@ -8,4 +11,6 @@ import info.nightscout.androidaps.plugins.OpenAPSMA.IobTotal;
public interface TempBasalsInterface { public interface TempBasalsInterface {
void updateTotalIOB(); void updateTotalIOB();
IobTotal getLastCalculation(); IobTotal getLastCalculation();
TempBasal getTempBasal (Date time);
} }

View file

@ -30,6 +30,7 @@ import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.plugins.APSResult; import info.nightscout.androidaps.plugins.APSResult;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.client.data.NSProfile; import info.nightscout.client.data.NSProfile;
import info.nightscout.utils.SafeParse;
/** /**
* LOW SUSPEND ALGORITHM * LOW SUSPEND ALGORITHM
@ -251,7 +252,7 @@ public class LowSuspendFragment extends Fragment implements View.OnClickListener
minBgDefault = "5"; minBgDefault = "5";
} }
double minBg = NSProfile.toMgdl(Double.parseDouble(SP.getString("lowsuspend_lowthreshold", minBgDefault).replace(",", ".")), profile.getUnits()); double minBg = NSProfile.toMgdl(SafeParse.stringToDouble(SP.getString("lowsuspend_lowthreshold", minBgDefault)), profile.getUnits());
boolean lowProjected = (glucoseStatus.glucose + 6.0 * glucoseStatus.avgdelta) < minBg; boolean lowProjected = (glucoseStatus.glucose + 6.0 * glucoseStatus.avgdelta) < minBg;
boolean low = glucoseStatus.glucose < minBg; boolean low = glucoseStatus.glucose < minBg;

View file

@ -37,6 +37,7 @@ import info.nightscout.androidaps.plugins.Treatments.TreatmentsFragment;
import info.nightscout.client.data.NSProfile; import info.nightscout.client.data.NSProfile;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.Round; import info.nightscout.utils.Round;
import info.nightscout.utils.SafeParse;
public class OpenAPSMAFragment extends Fragment implements View.OnClickListener, PluginBase, APSInterface { public class OpenAPSMAFragment extends Fragment implements View.OnClickListener, PluginBase, APSInterface {
private static Logger log = LoggerFactory.getLogger(OpenAPSMAFragment.class); private static Logger log = LoggerFactory.getLogger(OpenAPSMAFragment.class);
@ -254,10 +255,10 @@ public class OpenAPSMAFragment extends Fragment implements View.OnClickListener,
Date now = new Date(); Date now = new Date();
double maxIob = Double.parseDouble(SP.getString("openapsma_max_iob", "1.5").replace(",", ".")); double maxIob = SafeParse.stringToDouble(SP.getString("openapsma_max_iob", "1.5"));
double maxBasal = Double.parseDouble(SP.getString("openapsma_max_basal", "1").replace(",", ".")); double maxBasal = SafeParse.stringToDouble(SP.getString("openapsma_max_basal", "1"));
double minBg = NSProfile.toMgdl(Double.parseDouble(SP.getString("openapsma_min_bg", minBgDefault).replace(",", ".")), units); double minBg = NSProfile.toMgdl(SafeParse.stringToDouble(SP.getString("openapsma_min_bg", minBgDefault)), units);
double maxBg = NSProfile.toMgdl(Double.parseDouble(SP.getString("openapsma_max_bg", maxBgDefault).replace(",", ".")), units); double maxBg = NSProfile.toMgdl(SafeParse.stringToDouble(SP.getString("openapsma_max_bg", minBgDefault)), units);
minBg = Round.roundTo(minBg, 1d); minBg = Round.roundTo(minBg, 1d);
maxBg = Round.roundTo(maxBg, 1d); maxBg = Round.roundTo(maxBg, 1d);

View file

@ -16,6 +16,7 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Result; import info.nightscout.androidaps.data.Result;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.utils.SafeParse;
public class NewExtendedBolusDialog extends DialogFragment implements View.OnClickListener { public class NewExtendedBolusDialog extends DialogFragment implements View.OnClickListener {
@ -48,9 +49,7 @@ public class NewExtendedBolusDialog extends DialogFragment implements View.OnCli
switch (view.getId()) { switch (view.getId()) {
case R.id.overview_newextendedbolus_okbutton: case R.id.overview_newextendedbolus_okbutton:
try { try {
int basalPercent = 100; Double insulin = SafeParse.stringToDouble(insulinEdit.getText().toString());
String insulinText = insulinEdit.getText().toString().replace(",", ".");
Double insulin = Double.parseDouble(!insulinText.equals("") ? insulinText : "0");
int durationInMinutes = 30; int durationInMinutes = 30;
if (h10Radio.isChecked()) durationInMinutes = 60; if (h10Radio.isChecked()) durationInMinutes = 60;
if (h20Radio.isChecked()) durationInMinutes = 120; if (h20Radio.isChecked()) durationInMinutes = 120;

View file

@ -16,6 +16,7 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Result; import info.nightscout.androidaps.data.Result;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.utils.SafeParse;
public class NewTempBasalDialog extends DialogFragment implements View.OnClickListener { public class NewTempBasalDialog extends DialogFragment implements View.OnClickListener {
@ -53,8 +54,7 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi
case R.id.overview_newtempbasal_okbutton: case R.id.overview_newtempbasal_okbutton:
try { try {
int basalPercent = 100; int basalPercent = 100;
String basalText = basalEdit.getText().toString().replace(",", "."); Double basal = SafeParse.stringToDouble(basalEdit.getText().toString());
Double basal = Double.parseDouble(!basalText.equals("") ? basalText : "0");
final boolean setAsPercent = percentRadio.isChecked(); final boolean setAsPercent = percentRadio.isChecked();
int durationInMinutes = 30; int durationInMinutes = 30;
if (h10Radio.isChecked()) durationInMinutes = 60; if (h10Radio.isChecked()) durationInMinutes = 60;

View file

@ -17,6 +17,7 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Result; import info.nightscout.androidaps.data.Result;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.utils.SafeParse;
public class NewTreatmentDialog extends DialogFragment implements OnClickListener { public class NewTreatmentDialog extends DialogFragment implements OnClickListener {
@ -46,10 +47,8 @@ public class NewTreatmentDialog extends DialogFragment implements OnClickListene
case R.id.treatments_newtreatment_deliverbutton: case R.id.treatments_newtreatment_deliverbutton:
try { try {
String insulinText = this.insulin.getText().toString().replace(",", "."); Double insulin = SafeParse.stringToDouble(this.insulin.getText().toString());
String carbsText = this.carbs.getText().toString().replace(",", "."); Integer carbs = SafeParse.stringToInt(this.carbs.getText().toString());
Double insulin = Double.parseDouble(!insulinText.equals("") ? insulinText : "0");
Integer carbs = Integer.parseInt(!carbsText.equals("") ? carbsText : "0");
String confirmMessage = getString(R.string.entertreatmentquestion); String confirmMessage = getString(R.string.entertreatmentquestion);

View file

@ -216,16 +216,9 @@ public class WizardDialog extends DialogFragment implements OnClickListener {
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile(); NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
// Entered values // Entered values
String i_bg = this.bgInput.getText().toString().replace("," , "."); Double c_bg = SafeParse.stringToDouble(this.bgInput.getText().toString());
String i_carbs = this.carbsInput.getText().toString().replace(",", "."); Integer c_carbs = SafeParse.stringToInt(this.carbsInput.getText().toString());
String i_correction = this.correctionInput.getText().toString().replace(",", "."); Double c_correction = SafeParse.stringToDouble(this.correctionInput.getText().toString());
Double c_bg = 0d;
try { c_bg = Double.parseDouble(i_bg.equals("") ? "0" : i_bg); } catch (Exception e) {}
Integer c_carbs = 0;
try { c_carbs = Integer.parseInt(i_carbs.equals("") ? "0" : i_carbs); } catch (Exception e) {}
c_carbs = (Integer) Math.round(c_carbs);
Double c_correction = 0d;
try { c_correction = Double.parseDouble(i_correction.equals("") ? "0" : i_correction); } catch (Exception e) {}
if(c_correction != MainApp.getConfigBuilder().applyBolusConstraints(c_correction)) { if(c_correction != MainApp.getConfigBuilder().applyBolusConstraints(c_correction)) {
this.correctionInput.setText(""); this.correctionInput.setText("");
wizardDialogDeliverButton.setVisibility(Button.GONE); wizardDialogDeliverButton.setVisibility(Button.GONE);

View file

@ -2,9 +2,11 @@ package info.nightscout.androidaps.plugins.Overview;
import android.app.Activity; import android.app.Activity;
import android.graphics.Color; import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint; import android.graphics.Paint;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler; import android.os.Handler;
import android.provider.ContactsContract;
import android.support.v4.app.Fragment; import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater; import android.view.LayoutInflater;
@ -15,6 +17,8 @@ import android.widget.LinearLayout;
import android.widget.TextView; import android.widget.TextView;
import com.jjoe64.graphview.GraphView; import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.ValueDependentColor;
import com.jjoe64.graphview.series.BarGraphSeries;
import com.jjoe64.graphview.series.DataPoint; import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries; import com.jjoe64.graphview.series.LineGraphSeries;
import com.jjoe64.graphview.series.PointsGraphSeries; import com.jjoe64.graphview.series.PointsGraphSeries;
@ -317,7 +321,8 @@ public class OverviewFragment extends Fragment implements PluginBase {
int agoMin = (int) (agoMsec / 60d / 1000d); int agoMin = (int) (agoMsec / 60d / 1000d);
timeAgoView.setText(agoMin + " " + getString(R.string.minago)); timeAgoView.setText(agoMin + " " + getString(R.string.minago));
// **** BG graph **** // ****** GRAPH *******
// allign to hours // allign to hours
Calendar calendar = Calendar.getInstance(); Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(new Date().getTime()); calendar.setTimeInMillis(new Date().getTime());
@ -333,6 +338,56 @@ public class OverviewFragment extends Fragment implements PluginBase {
Double highLine = NSProfile.toUnits(180d, 10d, units); Double highLine = NSProfile.toUnits(180d, 10d, units);
Double maxY = NSProfile.toUnits(400d, 20d, units); // TODO: add some scale support Double maxY = NSProfile.toUnits(400d, 20d, units); // TODO: add some scale support
BarGraphSeries<DataPoint> basalsSeries = null;
LineGraphSeries<DataPoint> seriesLow = null;
LineGraphSeries<DataPoint> seriesHigh = null;
LineGraphSeries<DataPoint> seriesNow = null;
PointsGraphSeries<BgReading> seriesInRage = null;
PointsGraphSeries<BgReading> seriesOutOfRange = null;
bgGraph.removeAllSeries();
// **** TEMP BASALS graph ****
class BarDataPoint extends DataPoint {
public BarDataPoint(double x, double y, boolean isTempBasal) {
super(x, y);
this.isTempBasal = isTempBasal;
}
public boolean isTempBasal = false;
}
Double maxAllowedBasal = MainApp.getConfigBuilder().applyBasalConstraints(1000d);
long now = new Date().getTime();
List<BarDataPoint> basalArray = new ArrayList<BarDataPoint>();
for (long time = fromTime; time < now; time += 5 * 60 * 1000l) {
TempBasal tb = MainApp.getConfigBuilder().getActiveTempBasals().getTempBasal(new Date(time));
if (tb != null)
basalArray.add(new BarDataPoint(time, tb.tempBasalConvertedToAbsolute(), true));
else
basalArray.add(new BarDataPoint(time, profile.getBasal(NSProfile.secondsFromMidnight(new Date(time))), false));
}
BarDataPoint[] basal = new BarDataPoint[basalArray.size()];
log.debug("Bars: " + basalArray.size());
basal = basalArray.toArray(basal);
bgGraph.addSeries(basalsSeries = new BarGraphSeries<DataPoint>(basal));
basalsSeries.setValueDependentColor(new ValueDependentColor<DataPoint>() {
@Override
public int get(DataPoint data) {
BarDataPoint point = (BarDataPoint) data;
if (point.isTempBasal) return Color.CYAN;
else return Color.BLUE;
}
});
// set second scale
bgGraph.getSecondScale().addSeries(basalsSeries);
bgGraph.getSecondScale().setMinY(0);
bgGraph.getSecondScale().setMaxY(maxAllowedBasal * 4);
bgGraph.getGridLabelRenderer().setVerticalLabelsSecondScaleColor(MainApp.instance().getResources().getColor(R.color.background_material_dark));
// **** BG graph ****
List<BgReading> bgReadingsArray = MainApp.getDbHelper().getDataFromTime(fromTime); List<BgReading> bgReadingsArray = MainApp.getDbHelper().getDataFromTime(fromTime);
List<BgReading> inRangeArray = new ArrayList<BgReading>(); List<BgReading> inRangeArray = new ArrayList<BgReading>();
List<BgReading> outOfRangeArray = new ArrayList<BgReading>(); List<BgReading> outOfRangeArray = new ArrayList<BgReading>();
@ -354,38 +409,53 @@ public class OverviewFragment extends Fragment implements PluginBase {
outOfRange = outOfRangeArray.toArray(outOfRange); outOfRange = outOfRangeArray.toArray(outOfRange);
// targets
LineGraphSeries<DataPoint> seriesLow = new LineGraphSeries<DataPoint>(new DataPoint[]{
new DataPoint(fromTime, lowLine),
new DataPoint(toTime, lowLine)
});
seriesLow.setColor(Color.RED);
bgGraph.addSeries(seriesLow);
LineGraphSeries<DataPoint> seriesHigh = new LineGraphSeries<DataPoint>(new DataPoint[]{
new DataPoint(fromTime, highLine),
new DataPoint(toTime, highLine)
});
seriesHigh.setColor(Color.RED);
bgGraph.addSeries(seriesHigh);
if (inRange.length > 0) { if (inRange.length > 0) {
PointsGraphSeries<BgReading> seriesInRage = new PointsGraphSeries<BgReading>(inRange); bgGraph.addSeries(seriesInRage = new PointsGraphSeries<BgReading>(inRange));
bgGraph.addSeries(seriesInRage);
seriesInRage.setShape(PointsGraphSeries.Shape.POINT); seriesInRage.setShape(PointsGraphSeries.Shape.POINT);
seriesInRage.setSize(5); seriesInRage.setSize(5);
seriesInRage.setColor(Color.GREEN); seriesInRage.setColor(Color.GREEN);
} }
if (outOfRange.length > 0) { if (outOfRange.length > 0) {
PointsGraphSeries<BgReading> seriesOutOfRange = new PointsGraphSeries<BgReading>(outOfRange); bgGraph.addSeries(seriesOutOfRange = new PointsGraphSeries<BgReading>(outOfRange));
bgGraph.addSeries(seriesOutOfRange);
seriesOutOfRange.setShape(PointsGraphSeries.Shape.POINT); seriesOutOfRange.setShape(PointsGraphSeries.Shape.POINT);
seriesOutOfRange.setSize(5); seriesOutOfRange.setSize(5);
seriesOutOfRange.setColor(Color.RED); seriesOutOfRange.setColor(Color.RED);
} }
// **** HIGH and LOW targets graph ****
DataPoint[] lowDataPoints = new DataPoint[]{
new DataPoint(fromTime, lowLine),
new DataPoint(toTime, lowLine)
};
DataPoint[] highDataPoints = new DataPoint[]{
new DataPoint(fromTime, highLine),
new DataPoint(toTime, highLine)
};
bgGraph.addSeries(seriesLow = new LineGraphSeries<DataPoint>(lowDataPoints));
seriesLow.setColor(Color.RED);
bgGraph.addSeries(seriesHigh = new LineGraphSeries<DataPoint>(highDataPoints));
seriesHigh.setColor(Color.RED);
// **** NOW line ****
DataPoint[] nowPoints = new DataPoint[]{
new DataPoint(now, 0),
new DataPoint(now, maxY)
};
bgGraph.addSeries(seriesNow = new LineGraphSeries<DataPoint>(nowPoints));
seriesNow.setColor(Color.GREEN);
seriesNow.setDrawDataPoints(false);
//seriesNow.setThickness(1);
// custom paint to make a dotted line
Paint paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(1);
paint.setPathEffect(new DashPathEffect(new float[]{4, 20}, 0));
paint.setColor(Color.WHITE);
seriesNow.setCustomPaint(paint);
// set manual x bounds to have nice steps // set manual x bounds to have nice steps
bgGraph.getViewport().setMaxX(toTime); bgGraph.getViewport().setMaxX(toTime);
bgGraph.getViewport().setMinX(fromTime); bgGraph.getViewport().setMinX(fromTime);

View file

@ -17,6 +17,7 @@ import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.plugins.APSResult; import info.nightscout.androidaps.plugins.APSResult;
import info.nightscout.client.data.NSProfile; import info.nightscout.client.data.NSProfile;
import info.nightscout.utils.Round; import info.nightscout.utils.Round;
import info.nightscout.utils.SafeParse;
public class SafetyFragment extends Fragment implements PluginBase, ConstraintsInterface { public class SafetyFragment extends Fragment implements PluginBase, ConstraintsInterface {
private static Logger log = LoggerFactory.getLogger(SafetyFragment.class); private static Logger log = LoggerFactory.getLogger(SafetyFragment.class);
@ -83,7 +84,7 @@ public class SafetyFragment extends Fragment implements PluginBase, ConstraintsI
@Override @Override
public Double applyBasalConstraints(Double absoluteRate) { public Double applyBasalConstraints(Double absoluteRate) {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
Double maxBasal = Double.parseDouble(SP.getString("openapsma_max_basal", "1").replace(",", ".")); Double maxBasal = SafeParse.stringToDouble(SP.getString("openapsma_max_basal", "1"));
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile(); NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
if (absoluteRate < 0) absoluteRate = 0d; if (absoluteRate < 0) absoluteRate = 0d;
@ -113,7 +114,7 @@ public class SafetyFragment extends Fragment implements PluginBase, ConstraintsI
@Override @Override
public Integer applyBasalConstraints(Integer percentRate) { public Integer applyBasalConstraints(Integer percentRate) {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
Double maxBasal = Double.parseDouble(SP.getString("openapsma_max_basal", "1").replace(",", ".")); Double maxBasal = SafeParse.stringToDouble(SP.getString("openapsma_max_basal", "1"));
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile(); NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
Double currentBasal = profile.getBasal(profile.secondsFromMidnight()); Double currentBasal = profile.getBasal(profile.secondsFromMidnight());
@ -158,7 +159,7 @@ public class SafetyFragment extends Fragment implements PluginBase, ConstraintsI
public Double applyBolusConstraints(Double insulin) { public Double applyBolusConstraints(Double insulin) {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
try { try {
Double maxBolus = Double.parseDouble(SP.getString("treatmentssafety_maxbolus", "3")); Double maxBolus = SafeParse.stringToDouble(SP.getString("treatmentssafety_maxbolus", "3"));
if (insulin < 0) insulin = 0d; if (insulin < 0) insulin = 0d;
if (insulin > maxBolus) insulin = maxBolus; if (insulin > maxBolus) insulin = maxBolus;

View file

@ -27,6 +27,7 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.client.data.NSProfile; import info.nightscout.client.data.NSProfile;
import info.nightscout.utils.SafeParse;
public class SimpleProfileFragment extends Fragment implements PluginBase, ProfileInterface { public class SimpleProfileFragment extends Fragment implements PluginBase, ProfileInterface {
private static Logger log = LoggerFactory.getLogger(SimpleProfileFragment.class); private static Logger log = LoggerFactory.getLogger(SimpleProfileFragment.class);
@ -156,13 +157,13 @@ public class SimpleProfileFragment extends Fragment implements PluginBase, Profi
@Override @Override
public void onTextChanged(CharSequence s, int start, public void onTextChanged(CharSequence s, int start,
int before, int count) { int before, int count) {
try { dia = Double.parseDouble(diaView.getText().toString().replace(",", ".")); } catch (Exception e) {}; dia = SafeParse.stringToDouble(diaView.getText().toString());
try { ic = Double.parseDouble(icView.getText().toString().replace(",", ".")); } catch (Exception e) {}; ic = SafeParse.stringToDouble(icView.getText().toString());
try { isf = Double.parseDouble(isfView.getText().toString().replace(",", ".")); } catch (Exception e) {}; isf = SafeParse.stringToDouble(isfView.getText().toString());
try { car = Double.parseDouble(carView.getText().toString().replace(",", ".")); } catch (Exception e) {}; car = SafeParse.stringToDouble(carView.getText().toString());
try { basal = Double.parseDouble(basalView.getText().toString().replace(",", ".")); } catch (Exception e) {}; basal = SafeParse.stringToDouble(basalView.getText().toString());
try { targetLow = Double.parseDouble(targetlowView.getText().toString().replace(",", ".")); } catch (Exception e) {}; targetLow = SafeParse.stringToDouble(targetlowView.getText().toString());
try { targetHigh = Double.parseDouble(targethighView.getText().toString().replace(",", ".")); } catch (Exception e) {}; targetHigh = SafeParse.stringToDouble(targethighView.getText().toString());
storeSettings(); storeSettings();
} }
}; };

View file

@ -2,6 +2,7 @@ package info.nightscout.androidaps.plugins.TempBasals;
import android.app.Activity; import android.app.Activity;
import android.os.Bundle; import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment; import android.support.v4.app.Fragment;
import android.support.v7.widget.*; import android.support.v7.widget.*;
import android.view.LayoutInflater; import android.view.LayoutInflater;
@ -27,6 +28,7 @@ import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.db.TempBasal; import info.nightscout.androidaps.db.TempBasal;
@ -123,12 +125,16 @@ public class TempBasalsFragment extends Fragment implements PluginBase, TempBasa
boolean update = false; boolean update = false;
if (t.timeEnd == null && t.getPlannedTimeEnd().getTime() < now) { if (t.timeEnd == null && t.getPlannedTimeEnd().getTime() < now) {
t.timeEnd = new Date(t.getPlannedTimeEnd().getTime()); t.timeEnd = new Date(t.getPlannedTimeEnd().getTime());
if (Config.logTempBasalsCut)
log.debug("Add timeEnd to old record");
update = true; update = true;
} }
if (position > 0) { if (position > 0) {
Date startofnewer = tempBasals.get(position - 1).timeStart; Date startofnewer = tempBasals.get(position - 1).timeStart;
if (t.timeEnd == null) { if (t.timeEnd == null) {
t.timeEnd = new Date(Math.min(startofnewer.getTime(), t.getPlannedTimeEnd().getTime())); t.timeEnd = new Date(Math.min(startofnewer.getTime(), t.getPlannedTimeEnd().getTime()));
if (Config.logTempBasalsCut)
log.debug("Add timeEnd to old record");
update = true; update = true;
} else if (t.timeEnd.getTime() > startofnewer.getTime()) { } else if (t.timeEnd.getTime() > startofnewer.getTime()) {
t.timeEnd = startofnewer; t.timeEnd = startofnewer;
@ -137,8 +143,11 @@ public class TempBasalsFragment extends Fragment implements PluginBase, TempBasa
} }
if (update) { if (update) {
dao.update(t); dao.update(t);
log.debug("Fixing unfinished temp end: " + t.log()); if (Config.logTempBasalsCut) {
if (position > 0) log.debug("Previous: " + tempBasals.get(position - 1).log()); log.debug("Fixing unfinished temp end: " + t.log());
if (position > 0)
log.debug("Previous: " + tempBasals.get(position - 1).log());
}
} }
} }
@ -186,6 +195,14 @@ public class TempBasalsFragment extends Fragment implements PluginBase, TempBasa
lastCalculation = total; lastCalculation = total;
} }
@Nullable
@Override
public TempBasal getTempBasal(Date time) {
for (TempBasal t: tempBasals) {
if (t.isInProgress(time)) return t;
}
return null;
}
public static class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.TempBasalsViewHolder> { public static class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.TempBasalsViewHolder> {

View file

@ -38,7 +38,7 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt
Double defaultBasalValue = 0.2d; Double defaultBasalValue = 0.2d;
TempBasal tempBasal = null; //TempBasal tempBasal = null;
TempBasal extendedBolus = null; TempBasal extendedBolus = null;
Integer batteryPercent = 50; Integer batteryPercent = 50;
Integer resevoirInUnits = 50; Integer resevoirInUnits = 50;
@ -127,18 +127,22 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt
void checkForExpiredTempsAndExtended() { void checkForExpiredTempsAndExtended() {
long now = new Date().getTime(); long now = new Date().getTime();
if (isTempBasalInProgress()) { if (isTempBasalInProgress()) {
long plannedTimeEnd = tempBasal.getPlannedTimeEnd().getTime(); //long plannedTimeEnd = tempBasal.getPlannedTimeEnd().getTime();
long plannedTimeEnd = getTempBasal().getPlannedTimeEnd().getTime();
if (plannedTimeEnd < now) { if (plannedTimeEnd < now) {
tempBasal.timeEnd = new Date(plannedTimeEnd); //tempBasal.timeEnd = new Date(plannedTimeEnd);
getTempBasal().timeEnd = new Date(plannedTimeEnd);
try { try {
MainApp.instance().getDbHelper().getDaoTempBasals().update(tempBasal); //MainApp.instance().getDbHelper().getDaoTempBasals().update(tempBasal);
MainApp.instance().getDbHelper().getDaoTempBasals().update(getTempBasal());
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
log.error(e.getMessage()); log.error(e.getMessage());
} }
if (Config.logPumpComm) if (Config.logPumpComm)
log.debug("Canceling expired temp: " + tempBasal); //log.debug("Canceling expired temp: " + tempBasal);
tempBasal = null; log.debug("Canceling expired temp: " + getTempBasal());
//tempBasal = null;
MainApp.bus().post(new EventTreatmentChange()); MainApp.bus().post(new EventTreatmentChange());
} }
} }
@ -161,7 +165,8 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt
@Override @Override
public boolean isTempBasalInProgress() { public boolean isTempBasalInProgress() {
return tempBasal != null; //return tempBasal != null;
return getTempBasal() != null;
} }
@Override @Override
@ -196,28 +201,33 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt
public double getTempBasalAbsoluteRate() { public double getTempBasalAbsoluteRate() {
if (!isTempBasalInProgress()) if (!isTempBasalInProgress())
return 0; return 0;
if (tempBasal.isAbsolute) { //if (tempBasal.isAbsolute) {
return tempBasal.absolute; if (getTempBasal().isAbsolute) {
//return tempBasal.absolute;
return getTempBasal().absolute;
} else { } else {
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile(); NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
if (profile == null) if (profile == null)
return defaultBasalValue; return defaultBasalValue;
Double baseRate = profile.getBasal(profile.secondsFromMidnight()); Double baseRate = profile.getBasal(profile.secondsFromMidnight());
Double tempRate = baseRate * (tempBasal.percent / 100d); //Double tempRate = baseRate * (tempBasal.percent / 100d);
Double tempRate = baseRate * (getTempBasal().percent / 100d);
return baseRate + tempRate; return baseRate + tempRate;
} }
} }
@Override @Override
public TempBasal getTempBasal() { public TempBasal getTempBasal() {
return tempBasal; //return tempBasal;
return MainApp.getConfigBuilder().getActiveTempBasals().getTempBasal(new Date());
} }
@Override @Override
public double getTempBasalRemainingMinutes() { public double getTempBasalRemainingMinutes() {
if (!isTempBasalInProgress()) if (!isTempBasalInProgress())
return 0; return 0;
return tempBasal.getPlannedRemainingMinutes(); //return tempBasal.getPlannedRemainingMinutes();
return getTempBasal().getPlannedRemainingMinutes();
} }
@Override @Override
@ -240,7 +250,8 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt
Result result = cancelTempBasal(); Result result = cancelTempBasal();
if (!result.success) if (!result.success)
return result; return result;
tempBasal = new TempBasal(); //tempBasal = new TempBasal();
TempBasal tempBasal = new TempBasal();
tempBasal.timeStart = new Date(); tempBasal.timeStart = new Date();
tempBasal.isAbsolute = true; tempBasal.isAbsolute = true;
tempBasal.absolute = absoluteRate; tempBasal.absolute = absoluteRate;
@ -272,7 +283,8 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt
if (!result.success) if (!result.success)
return result; return result;
} }
tempBasal = new TempBasal(); //tempBasal = new TempBasal();
TempBasal tempBasal = new TempBasal();
tempBasal.timeStart = new Date(); tempBasal.timeStart = new Date();
tempBasal.isAbsolute = false; tempBasal.isAbsolute = false;
tempBasal.percent = percent; tempBasal.percent = percent;
@ -332,13 +344,15 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt
checkForExpiredTempsAndExtended(); checkForExpiredTempsAndExtended();
Result result = new Result(); Result result = new Result();
result.success = true; result.success = true;
result.isTempCancel = true;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok); result.comment = MainApp.instance().getString(R.string.virtualpump_resultok);
if (isTempBasalInProgress()) { if (isTempBasalInProgress()) {
result.enacted = true; result.enacted = true;
tempBasal.timeEnd = new Date(); //tempBasal.timeEnd = new Date();
getTempBasal().timeEnd = new Date();
try { try {
MainApp.instance().getDbHelper().getDaoTempBasals().update(tempBasal); MainApp.instance().getDbHelper().getDaoTempBasals().update(getTempBasal());
tempBasal = null; //tempBasal = null;
if (Config.logPumpComm) if (Config.logPumpComm)
log.debug("Canceling temp basal: " + result); log.debug("Canceling temp basal: " + result);
updateGUI(); updateGUI();
@ -359,7 +373,7 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt
if (isExtendedBoluslInProgress()) { if (isExtendedBoluslInProgress()) {
extendedBolus.timeEnd = new Date(); extendedBolus.timeEnd = new Date();
try { try {
MainApp.instance().getDbHelper().getDaoTempBasals().update(tempBasal); MainApp.instance().getDbHelper().getDaoTempBasals().update(extendedBolus);
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
result.success = false; result.success = false;
@ -390,12 +404,13 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt
try { try {
battery.put("percent", batteryPercent); battery.put("percent", batteryPercent);
status.put("status", "normal"); status.put("status", "normal");
//status.put("lastbolus", last_bolus_amount);
//status.put("lastbolustime", DateUtil.toISOString(last_bolus_time));
if (isTempBasalInProgress()) { if (isTempBasalInProgress()) {
status.put("tempbasalpct", tempBasal.percent); //status.put("tempbasalpct", tempBasal.percent);
status.put("tempbasalstart", DateUtil.toISOString(tempBasal.timeStart)); //status.put("tempbasalstart", DateUtil.toISOString(tempBasal.timeStart));
status.put("tempbasalremainmin", tempBasal.getPlannedRemainingMinutes()); //status.put("tempbasalremainmin", tempBasal.getPlannedRemainingMinutes());
status.put("tempbasalpct", getTempBasal().percent);
status.put("tempbasalstart", DateUtil.toISOString(getTempBasal().timeStart));
status.put("tempbasalremainmin", getTempBasal().getPlannedRemainingMinutes());
} }
status.put("timestamp", DateUtil.toISOString(new Date())); status.put("timestamp", DateUtil.toISOString(new Date()));
@ -430,7 +445,8 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt
basaBasalRateView.setText(getBaseBasalRate() + "U"); basaBasalRateView.setText(getBaseBasalRate() + "U");
if (isTempBasalInProgress()) { if (isTempBasalInProgress()) {
tempBasalView.setText(tempBasal.toString()); //tempBasalView.setText(tempBasal.toString());
tempBasalView.setText(getTempBasal().toString());
} else { } else {
tempBasalView.setText(""); tempBasalView.setText("");
} }

View file

@ -0,0 +1,26 @@
package info.nightscout.utils;
/**
* Created by mike on 23.06.2016.
*/
public class SafeParse {
public static Double stringToDouble(String input) {
Double result = 0d;
input = input.replace(",", ".");
try {
result = Double.parseDouble(input);
} catch (Exception e) {
}
return result;
}
public static Integer stringToInt(String input) {
Integer result = 0;
input = input.replace(",", ".");
try {
result = Integer.parseInt(input);
} catch (Exception e) {
}
return result;
}
}