Search in sources :

Example 6 with Calibration

use of com.eveningoutpost.dexdrip.Models.Calibration in project xDrip by NightscoutFoundation.

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 7 with Calibration

use of com.eveningoutpost.dexdrip.Models.Calibration in project xDrip by NightscoutFoundation.

the class Notifications method notificationSetter.

/*
 * *****************************************************************************************************************
 */
// returns weather unclear bg reading was detected
private boolean notificationSetter(Context context) {
    ReadPerfs(context);
    final long end = System.currentTimeMillis() + (60000 * 5);
    final long start = end - (60000 * 60 * 3) - (60000 * 10);
    BgGraphBuilder bgGraphBuilder = new BgGraphBuilder(context, start, end);
    // BgGraphBuilder bgGraphBuilder = new BgGraphBuilder(context);
    if (bg_ongoing && (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)) {
        bgOngoingNotification(bgGraphBuilder);
    }
    if (prefs.getLong("alerts_disabled_until", 0) > new Date().getTime()) {
        Log.d("NOTIFICATIONS", "Notifications are currently disabled!!");
        return false;
    }
    boolean unclearReading = BgReading.getAndRaiseUnclearReading(context);
    if (unclearReading) {
        AlertPlayer.getPlayer().stopAlert(context, false, true);
    } else {
        FileBasedNotifications(context);
        BgReading.checkForDropAllert(context);
        BgReading.checkForRisingAllert(context);
    }
    // TODO: Add this alerts as well to depend on unclear sensor reading.
    BgReading.checkForPersistentHigh();
    // KS evaluateLowPredictionAlarm();
    // KS reportNoiseChanges();
    Sensor sensor = Sensor.currentSensor();
    // TODO need to check performance of rest of this method when in follower mode
    final List<BgReading> bgReadings = BgReading.latest(3);
    final List<Calibration> calibrations = Calibration.allForSensorLimited(3);
    if (bgReadings == null || bgReadings.size() < 3) {
        return unclearReading;
    }
    if (calibrations == null || calibrations.size() < 2) {
        return unclearReading;
    }
    BgReading bgReading = bgReadings.get(0);
    if (calibration_notifications) {
        // TODO this should only clear double calibration once after calibrations are achieved
        if (bgReadings.size() >= 3) {
            if (calibrations.size() == 0 && (new Date().getTime() - bgReadings.get(2).timestamp <= (60000 * 30)) && sensor != null) {
                if ((sensor.started_at + (60000 * 60 * 2)) < new Date().getTime()) {
                    doubleCalibrationRequest();
                } else {
                    // TODO should be aware of state
                    clearDoubleCalibrationRequest();
                }
            } else {
                clearDoubleCalibrationRequest();
            }
        } else {
            clearDoubleCalibrationRequest();
        }
        // bgreadings criteria possibly needs a review
        if (CalibrationRequest.shouldRequestCalibration(bgReading) && (new Date().getTime() - bgReadings.get(2).timestamp <= (60000 * 24))) {
            if ((!PowerStateReceiver.is_power_connected()) || (Pref.getBooleanDefaultFalse("calibration_alerts_while_charging"))) {
                if (JoH.pratelimit("calibration-request-notification", CALIBRATION_REQUEST_MAX_FREQUENCY)) {
                    extraCalibrationRequest();
                }
            }
        } else {
            // TODO should be aware of state
            clearExtraCalibrationRequest();
        }
        if (calibrations.size() >= 1 && (Math.abs((new Date().getTime() - calibrations.get(0).timestamp)) / (1000 * 60 * 60) > 12) && (CalibrationRequest.isSlopeFlatEnough(BgReading.last(true)))) {
            Log.d("NOTIFICATIONS", "Calibration difference in hours: " + ((new Date().getTime() - calibrations.get(0).timestamp)) / (1000 * 60 * 60));
            if ((!PowerStateReceiver.is_power_connected()) || (Pref.getBooleanDefaultFalse("calibration_alerts_while_charging"))) {
                // TODO check slope
                if (JoH.pratelimit("calibration-request-notification", CALIBRATION_REQUEST_MIN_FREQUENCY) || Pref.getBooleanDefaultFalse("calibration_alerts_repeat")) {
                    calibrationRequest();
                }
            }
        } else {
            // TODO should be aware of state
            clearCalibrationRequest();
        }
    } else {
        clearAllCalibrationNotifications();
    }
    return unclearReading;
}
Also used : BgReading(com.eveningoutpost.dexdrip.Models.BgReading) Calibration(com.eveningoutpost.dexdrip.Models.Calibration) Date(java.util.Date) Sensor(com.eveningoutpost.dexdrip.Models.Sensor)

Example 8 with Calibration

use of com.eveningoutpost.dexdrip.Models.Calibration in project xDrip by NightscoutFoundation.

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 9 with Calibration

use of com.eveningoutpost.dexdrip.Models.Calibration in project xDrip by NightscoutFoundation.

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 10 with Calibration

use of com.eveningoutpost.dexdrip.Models.Calibration in project xDrip by NightscoutFoundation.

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)

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