Search in sources :

Example 21 with Calibration

use of com.eveningoutpost.dexdrip.Models.Calibration in project xDrip-plus by jamorham.

the class XDripOriginal method getCalibrationData.

@Override
public CalibrationData getCalibrationData(long until) {
    // TODO cache must understand until
    CalibrationData cd = loadDataFromCache(TAG);
    if (cd == null) {
        UserError.Log.d(TAG, "Regenerating Calibration data cache");
        final List<Calibration> calibrationl = Calibration.latestValid(1, until);
        if ((calibrationl != null) && (calibrationl.size() > 0)) {
            // first and only
            final Calibration calibration = calibrationl.get(0);
            if (calibration != null) {
                // produce the CalibrationData result
                cd = new CalibrationData(calibration.slope, calibration.intercept);
            // saveDataToCache(TAG, cd);
            }
        }
    }
    // null if invalid
    return cd;
}
Also used : Calibration(com.eveningoutpost.dexdrip.Models.Calibration)

Example 22 with Calibration

use of com.eveningoutpost.dexdrip.Models.Calibration in project xDrip-plus by jamorham.

the class Home method extraStatusLine.

@NonNull
public static String extraStatusLine() {
    final StringBuilder extraline = new StringBuilder();
    final Calibration lastCalibration = Calibration.lastValid();
    if (Pref.getBoolean("status_line_calibration_long", false) && lastCalibration != null) {
        if (extraline.length() != 0)
            extraline.append(' ');
        extraline.append("slope = ");
        extraline.append(String.format("%.2f", lastCalibration.slope));
        extraline.append(' ');
        extraline.append("inter = ");
        extraline.append(String.format("%.2f", lastCalibration.intercept));
    }
    if (Pref.getBoolean("status_line_calibration_short", false) && lastCalibration != null) {
        if (extraline.length() != 0)
            extraline.append(' ');
        extraline.append("s:");
        extraline.append(String.format("%.2f", lastCalibration.slope));
        extraline.append(' ');
        extraline.append("i:");
        extraline.append(String.format("%.2f", lastCalibration.intercept));
    }
    if (Pref.getBoolean("status_line_avg", false) || Pref.getBoolean("status_line_a1c_dcct", false) || Pref.getBoolean("status_line_a1c_ifcc", false) || Pref.getBoolean("status_line_in", false) || Pref.getBoolean("status_line_high", false) || Pref.getBoolean("status_line_low", false) || Pref.getBoolean("status_line_stdev", false) || Pref.getBoolean("status_line_carbs", false) || Pref.getBoolean("status_line_insulin", false) || Pref.getBoolean("status_line_royce_ratio", false) || Pref.getBoolean("status_line_accuracy", false) || Pref.getBoolean("status_line_capture_percentage", false) || Pref.getBoolean("status_line_pump_reservoir", false)) {
        final StatsResult statsResult = new StatsResult(Pref.getInstance(), Pref.getBooleanDefaultFalse("extra_status_stats_24h"));
        if (Pref.getBoolean("status_line_avg", false)) {
            if (extraline.length() != 0)
                extraline.append(' ');
            extraline.append(statsResult.getAverageUnitised());
        }
        if (Pref.getBoolean("status_line_a1c_dcct", false)) {
            if (extraline.length() != 0)
                extraline.append(' ');
            extraline.append(statsResult.getA1cDCCT());
        }
        if (Pref.getBoolean("status_line_a1c_ifcc", false)) {
            if (extraline.length() != 0)
                extraline.append(' ');
            extraline.append(statsResult.getA1cIFCC());
        }
        if (Pref.getBoolean("status_line_in", false)) {
            if (extraline.length() != 0)
                extraline.append(' ');
            extraline.append(statsResult.getInPercentage());
        }
        if (Pref.getBoolean("status_line_high", false)) {
            if (extraline.length() != 0)
                extraline.append(' ');
            extraline.append(statsResult.getHighPercentage());
        }
        if (Pref.getBoolean("status_line_low", false)) {
            if (extraline.length() != 0)
                extraline.append(' ');
            extraline.append(statsResult.getLowPercentage());
        }
        if (Pref.getBoolean("status_line_stdev", false)) {
            if (extraline.length() != 0)
                extraline.append(' ');
            extraline.append(statsResult.getStdevUnitised());
        }
        if (Pref.getBoolean("status_line_carbs", false)) {
            if (extraline.length() != 0)
                extraline.append(' ');
            // extraline.append("Carbs: " + statsResult.getTotal_carbs());
            extraline.append("Carbs:" + Math.round(statsResult.getTotal_carbs()));
        }
        if (Pref.getBoolean("status_line_insulin", false)) {
            if (extraline.length() != 0)
                extraline.append(' ');
            extraline.append("U:" + JoH.qs(statsResult.getTotal_insulin(), 2));
        }
        if (Pref.getBoolean("status_line_royce_ratio", false)) {
            if (extraline.length() != 0)
                extraline.append(' ');
            extraline.append("C/I:" + JoH.qs(statsResult.getRatio(), 2));
        }
        if (Pref.getBoolean("status_line_capture_percentage", false)) {
            if (extraline.length() != 0)
                extraline.append(' ');
            extraline.append(statsResult.getCapturePercentage(false));
        }
        if (Pref.getBoolean("status_line_accuracy", false)) {
            final long accuracy_period = DAY_IN_MS * 3;
            if (extraline.length() != 0)
                extraline.append(' ');
            final String accuracy_report = Accuracy.evaluateAccuracy(accuracy_period);
            if ((accuracy_report != null) && (accuracy_report.length() > 0)) {
                extraline.append(accuracy_report);
            } else {
                final String accuracy = BloodTest.evaluateAccuracy(accuracy_period);
                extraline.append(((accuracy != null) ? " " + accuracy : ""));
            }
        }
        if (Pref.getBoolean("status_line_pump_reservoir", false)) {
            if (extraline.length() != 0)
                extraline.append(' ');
            extraline.append(PumpStatus.getBolusIoBString());
            extraline.append(PumpStatus.getReservoirString());
            extraline.append(PumpStatus.getBatteryString());
        }
    }
    if (Pref.getBoolean("extra_status_calibration_plugin", false)) {
        // make sure do this only once
        final CalibrationAbstract plugin = getCalibrationPluginFromPreferences();
        if (plugin != null) {
            final CalibrationAbstract.CalibrationData pcalibration = plugin.getCalibrationData();
            // not tested on the widget yet
            if (extraline.length() > 0)
                extraline.append("\n");
            if (pcalibration != null)
                extraline.append("(" + plugin.getAlgorithmName() + ") s:" + JoH.qs(pcalibration.slope, 2) + " i:" + JoH.qs(pcalibration.intercept, 2));
            BgReading bgReading = BgReading.last();
            if (bgReading != null) {
                final boolean doMgdl = Pref.getString("units", "mgdl").equals("mgdl");
                extraline.append(" \u21D2 " + BgGraphBuilder.unitized_string(plugin.getGlucoseFromSensorValue(bgReading.age_adjusted_raw_value), doMgdl) + " " + BgGraphBuilder.unit(doMgdl));
            }
        }
        // If we are using the plugin as the primary then show xdrip original as well
        if (Pref.getBooleanDefaultFalse("display_glucose_from_plugin") || Pref.getBooleanDefaultFalse("use_pluggable_alg_as_primary")) {
            // make sure do this only once
            final CalibrationAbstract plugin_xdrip = getCalibrationPlugin(PluggableCalibration.Type.xDripOriginal);
            if (plugin_xdrip != null) {
                final CalibrationAbstract.CalibrationData pcalibration = plugin_xdrip.getCalibrationData();
                if (extraline.length() > 0)
                    // not tested on the widget yet
                    extraline.append("\n");
                if (pcalibration != null)
                    extraline.append("(" + plugin_xdrip.getAlgorithmName() + ") s:" + JoH.qs(pcalibration.slope, 2) + " i:" + JoH.qs(pcalibration.intercept, 2));
                BgReading bgReading = BgReading.last();
                if (bgReading != null) {
                    final boolean doMgdl = Pref.getString("units", "mgdl").equals("mgdl");
                    extraline.append(" \u21D2 " + BgGraphBuilder.unitized_string(plugin_xdrip.getGlucoseFromSensorValue(bgReading.age_adjusted_raw_value), doMgdl) + " " + BgGraphBuilder.unit(doMgdl));
                }
            }
        }
    }
    if (Pref.getBoolean("status_line_time", false)) {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        if (extraline.length() != 0)
            extraline.append(' ');
        extraline.append(sdf.format(new Date()));
    }
    return extraline.toString();
}
Also used : CalibrationAbstract(com.eveningoutpost.dexdrip.calibrations.CalibrationAbstract) Calibration(com.eveningoutpost.dexdrip.Models.Calibration) PluggableCalibration(com.eveningoutpost.dexdrip.calibrations.PluggableCalibration) BgReading(com.eveningoutpost.dexdrip.Models.BgReading) SimpleDateFormat(java.text.SimpleDateFormat) StatsResult(com.eveningoutpost.dexdrip.stats.StatsResult) Date(java.util.Date) NonNull(android.support.annotation.NonNull)

Example 23 with Calibration

use of com.eveningoutpost.dexdrip.Models.Calibration in project xDrip-plus by jamorham.

the class Home method updateCurrentBgInfoCommon.

private void updateCurrentBgInfoCommon(DexCollectionType collector, TextView notificationText) {
    // with bluetooth and wifi, skip second time
    if (alreadyDisplayedBgInfoCommon)
        return;
    alreadyDisplayedBgInfoCommon = true;
    final boolean isSensorActive = Sensor.isActive();
    if (!isSensorActive) {
        notificationText.setText(R.string.now_start_your_sensor);
        if ((dialog == null) || (!dialog.isShowing())) {
            if (!Experience.gotData() && Experience.backupAvailable() && JoH.ratelimit("restore-backup-prompt", 10)) {
                final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                final Context context = this;
                builder.setTitle("Restore Backup?");
                builder.setMessage("Do you want to restore the backup file: " + Pref.getString("last-saved-database-zip", "ERROR").replaceFirst("^.*/", ""));
                builder.setNegativeButton("No", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setPositiveButton("Restore", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        startActivity(new Intent(context, ImportDatabaseActivity.class).putExtra("importit", Pref.getString("last-saved-database-zip", "")).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                    }
                });
                dialog = builder.create();
                dialog.show();
            } else {
                if (!Experience.gotData() && !DexCollectionHelper.isDialogShowing() && JoH.ratelimit("start-sensor_prompt", 20)) {
                    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    final Context context = this;
                    builder.setTitle(getString(R.string.start_sensor) + "?");
                    builder.setMessage("Data Source is set to: " + DexCollectionType.getDexCollectionType().toString() + "\n\nDo you want to change settings or start sensor?");
                    builder.setNegativeButton("Change settings", new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            startActivity(new Intent(context, Preferences.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                        }
                    });
                    builder.setPositiveButton(R.string.start_sensor, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            startActivity(new Intent(context, StartNewSensor.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                        }
                    });
                    dialog = builder.create();
                    dialog.show();
                }
            }
        }
        return;
    }
    final long now = System.currentTimeMillis();
    if (Sensor.currentSensor().started_at + 60000 * 60 * 2 >= now) {
        double waitTime = (Sensor.currentSensor().started_at + 60000 * 60 * 2 - now) / 60000.0;
        notificationText.setText(getString(R.string.please_wait_while_sensor_warms_up) + JoH.qs(waitTime, 0) + getString(R.string.minutes_with_bracket));
        showUncalibratedSlope();
        return;
    }
    if (DexCollectionType.isLibreOOPAlgorithm(collector)) {
        // And even once we will have, there is probably no need to force a calibration at start of sensor use.
        return;
    }
    if (BgReading.latest(3).size() > 2) {
        // TODO potential to calibrate off stale data here
        final List<Calibration> calibrations = Calibration.latestValid(2);
        if (calibrations.size() > 1) {
            if (calibrations.get(0).possible_bad != null && calibrations.get(0).possible_bad == true && calibrations.get(1).possible_bad != null && calibrations.get(1).possible_bad != true) {
                notificationText.setText(R.string.possible_bad_calibration);
            }
            displayCurrentInfo();
            if (screen_forced_on)
                dontKeepScreenOn();
        } else {
            notificationText.setText(R.string.please_enter_two_calibrations_to_get_started);
            showUncalibratedSlope();
            Log.d(TAG, "Asking for calibration A: Uncalculated BG readings: " + BgReading.latest(2).size() + " / Calibrations size: " + calibrations.size());
            promptForCalibration();
            dontKeepScreenOn();
        }
    } else {
        if (!BgReading.isDataSuitableForDoubleCalibration()) {
            notificationText.setText(R.string.please_wait_need_two_readings_first);
            showInitialStatusHelper();
        } else {
            List<Calibration> calibrations = Calibration.latest(2);
            if (calibrations.size() < 2) {
                notificationText.setText(R.string.please_enter_two_calibrations_to_get_started);
                showUncalibratedSlope();
                Log.d(TAG, "Asking for calibration B: Uncalculated BG readings: " + BgReading.latestUnCalculated(2).size() + " / Calibrations size: " + calibrations.size());
                promptForCalibration();
                dontKeepScreenOn();
            }
        }
    }
}
Also used : AlertDialog(android.app.AlertDialog) Context(android.content.Context) DialogInterface(android.content.DialogInterface) BgGraphBuilder(com.eveningoutpost.dexdrip.UtilityModels.BgGraphBuilder) PendingIntent(android.app.PendingIntent) Intent(android.content.Intent) RecognizerIntent(android.speech.RecognizerIntent) Calibration(com.eveningoutpost.dexdrip.Models.Calibration) PluggableCalibration(com.eveningoutpost.dexdrip.calibrations.PluggableCalibration) Paint(android.graphics.Paint) Point(android.graphics.Point) Preferences(com.eveningoutpost.dexdrip.utils.Preferences) PluggableCalibration.getCalibrationPluginFromPreferences(com.eveningoutpost.dexdrip.calibrations.PluggableCalibration.getCalibrationPluginFromPreferences)

Example 24 with Calibration

use of com.eveningoutpost.dexdrip.Models.Calibration in project xDrip-plus by jamorham.

the class CalibrationGraph method setupCharts.

public void setupCharts() {
    chart = (LineChartView) findViewById(R.id.chart);
    List<Line> lines = new ArrayList<Line>();
    // calibration values
    List<Calibration> calibrations = Calibration.allForSensor();
    List<Line> greyLines = getCalibrationsLine(calibrations, Color.parseColor("#66FFFFFF"));
    calibrations = Calibration.allForSensorInLastFourDays();
    List<Line> blueLines = getCalibrationsLine(calibrations, ChartUtils.COLOR_BLUE);
    Calibration calibration = Calibration.lastValid();
    if (calibration != null) {
        // set header
        DecimalFormat df = new DecimalFormat("#");
        df.setMaximumFractionDigits(2);
        df.setMinimumFractionDigits(2);
        String Header = "slope = " + df.format(calibration.slope) + " intercept = " + df.format(calibration.intercept);
        GraphHeader.setText(Header);
        // red line
        List<PointValue> lineValues = new ArrayList<PointValue>();
        final float conversion_factor = (float) (doMgdl ? 1 : Constants.MGDL_TO_MMOLL);
        lineValues.add(new PointValue((float) start_x, (conversion_factor * (float) (start_x * calibration.slope + calibration.intercept))));
        lineValues.add(new PointValue((float) end_x, (conversion_factor * (float) (end_x * calibration.slope + calibration.intercept))));
        Line calibrationLine = new Line(lineValues);
        calibrationLine.setColor(ChartUtils.COLOR_RED);
        calibrationLine.setHasLines(true);
        calibrationLine.setHasPoints(false);
        lines.add(calibrationLine);
        // calibration plugin
        final CalibrationAbstract plugin = getCalibrationPluginFromPreferences();
        if (plugin != null) {
            final CalibrationAbstract.CalibrationData pcalibration = plugin.getCalibrationData();
            final List<PointValue> plineValues = new ArrayList<PointValue>();
            plineValues.add(new PointValue((float) start_x, (conversion_factor * (float) (plugin.getGlucoseFromSensorValue(start_x, pcalibration)))));
            plineValues.add(new PointValue((float) end_x, (conversion_factor * (float) (plugin.getGlucoseFromSensorValue(end_x, pcalibration)))));
            final Line pcalibrationLine = new Line(plineValues);
            pcalibrationLine.setColor(Color.parseColor(plugin_color));
            pcalibrationLine.setHasLines(true);
            pcalibrationLine.setHasPoints(false);
            lines.add(pcalibrationLine);
            PluginHeader.setText("(" + plugin.getAlgorithmName() + ")  " + "s = " + df.format(pcalibration.slope) + "  i = " + df.format(pcalibration.intercept));
            PluginHeader.setTextColor(Color.parseColor(plugin_color));
        }
        // add lines in order
        for (Line greyLine : greyLines) {
            lines.add(greyLine);
        }
        for (Line blueLine : blueLines) {
            lines.add(blueLine);
        }
    }
    Axis axisX = new Axis();
    Axis axisY = new Axis().setHasLines(true);
    axisX.setName("Raw Value");
    axisY.setName("Glucose " + (doMgdl ? "mg/dl" : "mmol/l"));
    data = new LineChartData(lines);
    data.setAxisXBottom(axisX);
    data.setAxisYLeft(axisY);
    chart.setLineChartData(data);
}
Also used : PointValue(lecho.lib.hellocharts.model.PointValue) DecimalFormat(java.text.DecimalFormat) ArrayList(java.util.ArrayList) Calibration(com.eveningoutpost.dexdrip.Models.Calibration) Line(lecho.lib.hellocharts.model.Line) CalibrationAbstract(com.eveningoutpost.dexdrip.calibrations.CalibrationAbstract) LineChartData(lecho.lib.hellocharts.model.LineChartData) Axis(lecho.lib.hellocharts.model.Axis)

Example 25 with Calibration

use of com.eveningoutpost.dexdrip.Models.Calibration in project xDrip-plus by jamorham.

the class CalibrationOverride method addListenerOnButton.

public void addListenerOnButton() {
    button = (Button) findViewById(R.id.save_calibration_button);
    button.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            if (Sensor.isActive()) {
                EditText value = (EditText) findViewById(R.id.bg_value);
                String string_value = value.getText().toString();
                if (!TextUtils.isEmpty(string_value)) {
                    try {
                        final double calValue = JoH.tolerantParseDouble(string_value);
                        final Calibration last_calibration = Calibration.lastValid();
                        if (last_calibration == null) {
                            Log.wtf(TAG, "Last valid calibration is null when trying to cancel it in override!");
                        } else {
                            last_calibration.sensor_confidence = 0;
                            last_calibration.slope_confidence = 0;
                            last_calibration.save();
                            CalibrationSendQueue.addToQueue(last_calibration, getApplicationContext());
                        // TODO we need to push the nixing of this last calibration
                        }
                        final Calibration calibration = Calibration.create(calValue, getApplicationContext());
                        if (calibration != null) {
                            UndoRedo.addUndoCalibration(calibration.uuid);
                            GcmActivity.pushCalibration(string_value, "0");
                        // startWatchUpdaterService(v.getContext(), WatchUpdaterService.ACTION_SYNC_CALIBRATION, TAG);
                        } else {
                            Log.e(TAG, "Calibration creation resulted in null");
                            JoH.static_toast_long("Could not create calibration!");
                        }
                        Intent tableIntent = new Intent(v.getContext(), Home.class);
                        startActivity(tableIntent);
                        finish();
                    } catch (NumberFormatException e) {
                        value.setError("Number error: " + e);
                    }
                } else {
                    value.setError("Calibration Can Not be blank");
                }
            } else {
                Log.w("Calibration", "ERROR, no active sensor");
            }
        }
    });
}
Also used : EditText(android.widget.EditText) Intent(android.content.Intent) Calibration(com.eveningoutpost.dexdrip.Models.Calibration) View(android.view.View)

Aggregations

Calibration (com.eveningoutpost.dexdrip.Models.Calibration)54 BgReading (com.eveningoutpost.dexdrip.Models.BgReading)20 ArrayList (java.util.ArrayList)16 Date (java.util.Date)12 EditText (android.widget.EditText)8 Sensor (com.eveningoutpost.dexdrip.Models.Sensor)8 DataMap (com.google.android.gms.wearable.DataMap)8 DialogInterface (android.content.DialogInterface)6 Intent (android.content.Intent)6 NonNull (android.support.annotation.NonNull)6 BloodTest (com.eveningoutpost.dexdrip.Models.BloodTest)6 PolyTrendLine (com.eveningoutpost.dexdrip.Models.Forecast.PolyTrendLine)6 TrendLine (com.eveningoutpost.dexdrip.Models.Forecast.TrendLine)6 Treatments (com.eveningoutpost.dexdrip.Models.Treatments)6 CalibrationAbstract (com.eveningoutpost.dexdrip.calibrations.CalibrationAbstract)6 PluggableCalibration (com.eveningoutpost.dexdrip.calibrations.PluggableCalibration)6 IOException (java.io.IOException)6 PointValue (lecho.lib.hellocharts.model.PointValue)6 JSONException (org.json.JSONException)6 View (android.view.View)4