Java Code Examples for com.eveningoutpost.dexdrip.Models.Calibration#lastValid()

The following examples show how to use com.eveningoutpost.dexdrip.Models.Calibration#lastValid() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CalibrationGraph.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean onCreateOptionsMenu(Menu menu) {

    //Just generate the menu in engineering mode
    if (!Pref.getBooleanDefaultFalse("engineering_mode")) {
        return false;
    }

    getMenuInflater().inflate(R.menu.menu_calibrationgraph, menu);

    // Only show elements if there is a calibration to overwrite
    if (Calibration.lastValid() != null) {
        menu.findItem(R.id.action_overwrite_intercept).setVisible(true);
        menu.findItem(R.id.action_overwrite_slope).setVisible(true);
        menu.findItem(R.id.action_overwrite_calibration_impossible).setVisible(false);
    }

    return super.onCreateOptionsMenu(menu);
}
 
Example 2
Source File: CalibrationGraph.java    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean onCreateOptionsMenu(Menu menu) {

    //Just generate the menu in engineering mode
    if (!Pref.getBooleanDefaultFalse("engineering_mode")) {
        return false;
    }

    getMenuInflater().inflate(R.menu.menu_calibrationgraph, menu);

    // Only show elements if there is a calibration to overwrite
    if (Calibration.lastValid() != null) {
        menu.findItem(R.id.action_overwrite_intercept).setVisible(true);
        menu.findItem(R.id.action_overwrite_slope).setVisible(true);
        menu.findItem(R.id.action_overwrite_calibration_impossible).setVisible(false);
    }

    return super.onCreateOptionsMenu(menu);
}
 
Example 3
Source File: WebServicePebble.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
public WebResponse request(String query) {

        final BestGlucose.DisplayGlucose dg = BestGlucose.getDisplayGlucose();
        if (dg == null) return null; // TODO better error handling?

        final BgReading bgReading = BgReading.last();
        if (bgReading == null) return null; // TODO better error handling?

        final Calibration calibration = Calibration.lastValid(); // this can be null

        // prepare json objects
        final JSONObject reply = new JSONObject();

        final JSONObject status = new JSONObject();
        final JSONObject bgs = new JSONObject();
        final JSONObject cals = new JSONObject();

        final JSONArray status_array = new JSONArray();
        final JSONArray bgs_array = new JSONArray();
        final JSONArray cals_array = new JSONArray();

        // populate json structures
        try {

            status.put("now", JoH.tsl());

            bgs.put("sgv", dg.unitized);
            bgs.put("trend", bgReading.getSlopeOrdinal()); // beware not coming from Display Glucose
            bgs.put("direction", dg.delta_name);
            bgs.put("datetime", dg.timestamp);
            bgs.put("filtered", (long) (bgReading.filtered_data * 1000));
            bgs.put("unfiltered", (long) (bgReading.raw_data * 1000));

            bgs.put("noise", bgReading.noiseValue());

            // apparently curious way to differentiate between mgdl/mmol on the watch face
            if (dg.doMgDl) {
                bgs.put("bgdelta", (long) dg.delta_mgdl);
            } else {
                bgs.put("bgdelta", dg.unitized_delta_no_units.replaceFirst("\\+", ""));
            }

            bgs.put("battery", microStatus.gs("bestBridgeBattery"));
            bgs.put("iob", 0); // TODO get iob
            // TODO output bwp and bwpo

            status_array.put(status);
            bgs_array.put(bgs);

            reply.put("status", status_array);
            reply.put("bgs", bgs_array);

            // optional calibration
            if (calibration != null) {
                cals.put("scale", 1);
                cals.put("slope", calibration.slope * 1000);
                cals.put("intercept", calibration.intercept * 1000); // negated??
                cals_array.put(cals);
                reply.put("cals", cals_array);

            }
            Log.d(TAG, "Output: " + reply.toString());

        } catch (JSONException e) {
            UserError.Log.wtf(TAG, "Got json exception: " + e);
        }
        // {"status":[{"now":1515263236782}],"bgs":[{"sgv":"16.8","trend":3,"direction":"FortyFiveUp","datetime":1515263092650,"filtered":292672,"unfiltered":296384,"noise":1,"bgdelta":"0.3","battery":"72","iob":0,"bwp":"29.50","bwpo":303}],"cals":[{"slope":1000,"intercept":13056.86000000003,"scale":1}]}

        return new WebResponse(reply.toString());
    }
 
Example 4
Source File: WixelReader.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
private void readData() {
    Long LastReportedTime = 0L;
    TransmitterData lastTransmitterData = TransmitterData.last();
    if (lastTransmitterData != null) {
        LastReportedTime = lastTransmitterData.timestamp;

        // jamorham fix to avoid going twice to network when we just got a packet
        if ((new Date().getTime() - LastReportedTime) < DEXCOM_PERIOD - 2000) {
            Log.d(TAG, "Already have a recent packet - returning");
            if (JoH.ratelimit("deferred-msg", 60)) {
                statusLog(" Deferred", "Already have recent reading");
            }
            return;
        } else {
            statusLog(" Deferred", "");
        }


    }
    Long startReadTime = LastReportedTime;

    TransmitterRawData LastReportedReading = null;
    Log.d(TAG, "Starting... LastReportedReading " + LastReportedReading);
    // try to read one object...
    TransmitterRawData[] LastReadingArr = null;

    String recieversIpAddresses;

    if (!WixelReader.IsConfigured()) {
        return;
    }

    if ((DexCollectionType.getDexCollectionType() == DexCollectionType.Mock) && Home.get_engineering_mode()) {
        recieversIpAddresses = "fake://FAKE_DATA";
    } else {
        recieversIpAddresses = Pref.getString("wifi_recievers_addresses", "");
    }

    // How many packets should we read? we look at the maximum time between last calibration and last reading time
    // and calculate how much are needed.

    final Calibration lastCalibration = Calibration.lastValid();
    if (lastCalibration != null) {
        startReadTime = Math.max(startReadTime, lastCalibration.timestamp);
    }
    Long gapTime = new Date().getTime() - startReadTime + 120000;
    int packetsToRead = (int) (gapTime / (5 * 60000));
    packetsToRead = Math.min(packetsToRead, 200); // don't read too much, but always read 1.
    packetsToRead = Math.max(packetsToRead, 1);


    Log.d(TAG, "reading " + packetsToRead + " packets");
    LastReadingArr = Read(recieversIpAddresses, packetsToRead);

    if (LastReadingArr == null || LastReadingArr.length == 0) {
        return;
    }

    for (TransmitterRawData LastReading : LastReadingArr) {
        // Last in the array is the most updated reading we have.
        //TransmitterRawData LastReading = LastReadingArr[LastReadingArr.length -1];


        //if (LastReading.CaptureDateTime > LastReportedReading + 5000) {
        // Make sure we do not report packets from the far future...
        if ((LastReading.CaptureDateTime > LastReportedTime + 120000) &&
                (!almostEquals(LastReading, LastReportedReading)) &&
                LastReading.CaptureDateTime < new Date().getTime() + 120000) {
            // We have a real new reading...
            Log.d(TAG, "calling setSerialDataToTransmitterRawData " + LastReading.RawValue +
                    " LastReading.CaptureDateTime " + LastReading.CaptureDateTime + " " + LastReading.TransmissionId);
            setSerialDataToTransmitterRawData(LastReading.RawValue, LastReading.FilteredValue, LastReading.BatteryLife, LastReading.CaptureDateTime);
            LastReportedReading = LastReading;
            LastReportedTime = LastReading.CaptureDateTime;


            if (LastReading.UploaderBatteryLife > 0) {
                Pref.setInt("parakeet_battery", LastReading.UploaderBatteryLife);
                CheckBridgeBattery.checkParakeetBattery();
                if (Home.get_master()) {
                    GcmActivity.sendParakeetBattery(LastReading.UploaderBatteryLife);
                }
            }

        }
    }
}
 
Example 5
Source File: BluetoothGlucoseMeter.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
private synchronized void evaluateLastRecords() {
    if (lastBloodTest != null) {
        GcmActivity.syncBloodTests();

        final boolean delay_calibration = true;
        final GlucoseReadingRx lastGlucoseRecord = lastBloodTest.glucoseReadingRx;
        if ((lastGlucoseRecord != null) && (lastGlucoseRecord.device != null) && (ct != null)) {
            final String sequence_id = "last-btm-sequence-" + lastGlucoseRecord.device;
            final String timestamp_id = "last-btm-timestamp" + lastGlucoseRecord.device;
            // sequence numbers start from 0 so we add 1
            if ((lastGlucoseRecord.sequence + 1) > PersistentStore.getLong(sequence_id)) {
                PersistentStore.setLong(sequence_id, lastGlucoseRecord.sequence + 1);
                // get adjusted timestamp
                if (lastBloodTest.timestamp > PersistentStore.getLong(timestamp_id)) {
                    PersistentStore.setLong(timestamp_id, lastBloodTest.timestamp);
                    Log.d(TAG, "evaluateLastRecords: appears to be a new record: sequence:" + lastGlucoseRecord.sequence);
                    JoH.runOnUiThreadDelayed(Home::staticRefreshBGCharts, 300);
                    if (Pref.getBooleanDefaultFalse("bluetooth_meter_for_calibrations")
                            || Pref.getBooleanDefaultFalse("bluetooth_meter_for_calibrations_auto")) {
                        final long time_since = JoH.msSince(lastBloodTest.timestamp);
                        if (time_since >= 0) {
                            if (time_since < (12 * Constants.HOUR_IN_MS)) {
                                final Calibration calibration = Calibration.lastValid();
                                // check must also be younger than most recent calibration
                                if ((calibration == null) || (lastBloodTest.timestamp > calibration.timestamp)) {
                                    UserError.Log.ueh(TAG, "Prompting for calibration for: " + BgGraphBuilder.unitized_string_with_units_static(lastBloodTest.mgdl) + " from: " + JoH.dateTimeText(lastBloodTest.timestamp));
                                    JoH.clearCache();
                                    Home.startHomeWithExtra(getApplicationContext(), Home.HOME_FULL_WAKEUP, "1");
                                    JoH.runOnUiThreadDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            Home.staticRefreshBGCharts();
                                            // requires offset in past

                                            if ((Pref.getBooleanDefaultFalse("bluetooth_meter_for_calibrations_auto") && isSlopeFlatEnough())) {
                                                Log.d(TAG, "Slope flat enough for auto calibration");
                                                if (!delay_calibration) {
                                                    Home.startHomeWithExtra(xdrip.getAppContext(),
                                                            Home.BLUETOOTH_METER_CALIBRATION,
                                                            BgGraphBuilder.unitized_string_static(lastBloodTest.mgdl),
                                                            Long.toString(time_since),
                                                            "auto");
                                                } else {
                                                    Log.d(TAG, "Delaying calibration for later");
                                                    JoH.static_toast_long("Waiting for 15 minutes more sensor data for calibration");
                                                }
                                            } else {
                                                if (Pref.getBooleanDefaultFalse("bluetooth_meter_for_calibrations")) {
                                                    // manual calibration
                                                    Home.startHomeWithExtra(xdrip.getAppContext(),
                                                            Home.BLUETOOTH_METER_CALIBRATION,
                                                            BgGraphBuilder.unitized_string_static(lastBloodTest.mgdl),
                                                            Long.toString(time_since),
                                                            "manual");
                                                } else {
                                                    Log.d(TAG, "Not flat enough slope for auto calibration and manual calibration not enabled");
                                                }
                                            }
                                        }
                                    }, 500);
                                } else {
                                    UserError.Log.e(TAG, "evaluateLastRecords: meter reading is at least as old as last calibration - ignoring");
                                }
                            } else {
                                UserError.Log.e(TAG, "evaluateLastRecords: meter reading is too far in the past: " + JoH.dateTimeText(lastBloodTest.timestamp));
                            }
                        } else {
                            UserError.Log.e(TAG, "evaluateLastRecords: time is in the future - ignoring");
                        }
                    }
                }
            } else {
                UserError.Log.d(TAG, "evaluateLastRecords: sequence isn't newer");
            }
        } else {
            UserError.Log.e(TAG, "evaluateLastRecords: Data missing for evaluation");
        }
    } else {
        UserError.Log.e(TAG, "evaluateLastRecords: lastBloodTest is Null!!");
    }
}
 
Example 6
Source File: CalibrationGraph.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
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);

}
 
Example 7
Source File: WebServicePebble.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
public WebResponse request(String query) {

        final BestGlucose.DisplayGlucose dg = BestGlucose.getDisplayGlucose();
        if (dg == null) return null; // TODO better error handling?

        final BgReading bgReading = BgReading.last();
        if (bgReading == null) return null; // TODO better error handling?

        final Calibration calibration = Calibration.lastValid(); // this can be null

        // prepare json objects
        final JSONObject reply = new JSONObject();

        final JSONObject status = new JSONObject();
        final JSONObject bgs = new JSONObject();
        final JSONObject cals = new JSONObject();

        final JSONArray status_array = new JSONArray();
        final JSONArray bgs_array = new JSONArray();
        final JSONArray cals_array = new JSONArray();

        // populate json structures
        try {

            status.put("now", JoH.tsl());

            bgs.put("sgv", dg.unitized);
            bgs.put("trend", bgReading.getSlopeOrdinal()); // beware not coming from Display Glucose
            bgs.put("direction", dg.delta_name);
            bgs.put("datetime", dg.timestamp);
            bgs.put("filtered", (long) (bgReading.filtered_data * 1000));
            bgs.put("unfiltered", (long) (bgReading.raw_data * 1000));

            bgs.put("noise", bgReading.noiseValue());

            // apparently curious way to differentiate between mgdl/mmol on the watch face
            if (dg.doMgDl) {
                bgs.put("bgdelta", (long) dg.delta_mgdl);
            } else {
                bgs.put("bgdelta", dg.unitized_delta_no_units.replaceFirst("\\+", ""));
            }

            bgs.put("battery", microStatus.gs("bestBridgeBattery"));
            bgs.put("iob", 0); // TODO get iob
            // TODO output bwp and bwpo

            status_array.put(status);
            bgs_array.put(bgs);

            reply.put("status", status_array);
            reply.put("bgs", bgs_array);

            // optional calibration
            if (calibration != null) {
                cals.put("scale", 1);
                cals.put("slope", calibration.slope * 1000);
                cals.put("intercept", calibration.intercept * 1000); // negated??
                cals_array.put(cals);
                reply.put("cals", cals_array);

            }
            Log.d(TAG, "Output: " + reply.toString());

        } catch (JSONException e) {
            UserError.Log.wtf(TAG, "Got json exception: " + e);
        }
        // {"status":[{"now":1515263236782}],"bgs":[{"sgv":"16.8","trend":3,"direction":"FortyFiveUp","datetime":1515263092650,"filtered":292672,"unfiltered":296384,"noise":1,"bgdelta":"0.3","battery":"72","iob":0,"bwp":"29.50","bwpo":303}],"cals":[{"slope":1000,"intercept":13056.86000000003,"scale":1}]}

        return new WebResponse(reply.toString());
    }
 
Example 8
Source File: WixelReader.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
private void readData() {
    Long LastReportedTime = 0L;
    TransmitterData lastTransmitterData = TransmitterData.last();
    if (lastTransmitterData != null) {
        LastReportedTime = lastTransmitterData.timestamp;

        // jamorham fix to avoid going twice to network when we just got a packet
        if ((new Date().getTime() - LastReportedTime) < DEXCOM_PERIOD - 2000) {
            Log.d(TAG, "Already have a recent packet - returning");
            if (JoH.ratelimit("deferred-msg", 60)) {
                statusLog(" Deferred", "Already have recent reading");
            }
            return;
        } else {
            statusLog(" Deferred", "");
        }


    }
    Long startReadTime = LastReportedTime;

    TransmitterRawData LastReportedReading = null;
    Log.d(TAG, "Starting... LastReportedReading " + LastReportedReading);
    // try to read one object...
    TransmitterRawData[] LastReadingArr = null;

    String recieversIpAddresses;

    if (!WixelReader.IsConfigured()) {
        return;
    }

    if ((DexCollectionType.getDexCollectionType() == DexCollectionType.Mock) && Home.get_engineering_mode()) {
        recieversIpAddresses = "fake://FAKE_DATA";
    } else {
        recieversIpAddresses = Pref.getString("wifi_recievers_addresses", "");
    }

    // How many packets should we read? we look at the maximum time between last calibration and last reading time
    // and calculate how much are needed.

    final Calibration lastCalibration = Calibration.lastValid();
    if (lastCalibration != null) {
        startReadTime = Math.max(startReadTime, lastCalibration.timestamp);
    }
    Long gapTime = new Date().getTime() - startReadTime + 120000;
    int packetsToRead = (int) (gapTime / (5 * 60000));
    packetsToRead = Math.min(packetsToRead, 200); // don't read too much, but always read 1.
    packetsToRead = Math.max(packetsToRead, 1);


    Log.d(TAG, "reading " + packetsToRead + " packets");
    LastReadingArr = Read(recieversIpAddresses, packetsToRead);

    if (LastReadingArr == null || LastReadingArr.length == 0) {
        return;
    }

    for (TransmitterRawData LastReading : LastReadingArr) {
        // Last in the array is the most updated reading we have.
        //TransmitterRawData LastReading = LastReadingArr[LastReadingArr.length -1];


        //if (LastReading.CaptureDateTime > LastReportedReading + 5000) {
        // Make sure we do not report packets from the far future...
        if ((LastReading.CaptureDateTime > LastReportedTime + 120000) &&
                (!almostEquals(LastReading, LastReportedReading)) &&
                LastReading.CaptureDateTime < new Date().getTime() + 120000) {
            // We have a real new reading...
            Log.d(TAG, "calling setSerialDataToTransmitterRawData " + LastReading.RawValue +
                    " LastReading.CaptureDateTime " + LastReading.CaptureDateTime + " " + LastReading.TransmissionId);
            setSerialDataToTransmitterRawData(LastReading.RawValue, LastReading.FilteredValue, LastReading.BatteryLife, LastReading.CaptureDateTime);
            LastReportedReading = LastReading;
            LastReportedTime = LastReading.CaptureDateTime;


            if (LastReading.UploaderBatteryLife > 0) {
                Pref.setInt("parakeet_battery", LastReading.UploaderBatteryLife);
                CheckBridgeBattery.checkParakeetBattery();
                if (Home.get_master()) {
                    GcmActivity.sendParakeetBattery(LastReading.UploaderBatteryLife);
                }
            }

        }
    }
}
 
Example 9
Source File: BluetoothGlucoseMeter.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
private synchronized void evaluateLastRecords() {
    if (lastBloodTest != null) {
        GcmActivity.syncBloodTests();

        final boolean delay_calibration = true;
        final GlucoseReadingRx lastGlucoseRecord = lastBloodTest.glucoseReadingRx;
        if ((lastGlucoseRecord != null) && (lastGlucoseRecord.device != null) && (ct != null)) {
            final String sequence_id = "last-btm-sequence-" + lastGlucoseRecord.device;
            final String timestamp_id = "last-btm-timestamp" + lastGlucoseRecord.device;
            // sequence numbers start from 0 so we add 1
            if ((lastGlucoseRecord.sequence + 1) > PersistentStore.getLong(sequence_id)) {
                PersistentStore.setLong(sequence_id, lastGlucoseRecord.sequence + 1);
                // get adjusted timestamp
                if (lastBloodTest.timestamp > PersistentStore.getLong(timestamp_id)) {
                    PersistentStore.setLong(timestamp_id, lastBloodTest.timestamp);
                    Log.d(TAG, "evaluateLastRecords: appears to be a new record: sequence:" + lastGlucoseRecord.sequence);
                    JoH.runOnUiThreadDelayed(Home::staticRefreshBGCharts, 300);
                    if (Pref.getBooleanDefaultFalse("bluetooth_meter_for_calibrations")
                            || Pref.getBooleanDefaultFalse("bluetooth_meter_for_calibrations_auto")) {
                        final long time_since = JoH.msSince(lastBloodTest.timestamp);
                        if (time_since >= 0) {
                            if (time_since < (12 * Constants.HOUR_IN_MS)) {
                                final Calibration calibration = Calibration.lastValid();
                                // check must also be younger than most recent calibration
                                if ((calibration == null) || (lastBloodTest.timestamp > calibration.timestamp)) {
                                    UserError.Log.ueh(TAG, "Prompting for calibration for: " + BgGraphBuilder.unitized_string_with_units_static(lastBloodTest.mgdl) + " from: " + JoH.dateTimeText(lastBloodTest.timestamp));
                                    JoH.clearCache();
                                    Home.startHomeWithExtra(getApplicationContext(), Home.HOME_FULL_WAKEUP, "1");
                                    JoH.runOnUiThreadDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            Home.staticRefreshBGCharts();
                                            // requires offset in past

                                            if ((Pref.getBooleanDefaultFalse("bluetooth_meter_for_calibrations_auto") && isSlopeFlatEnough())) {
                                                Log.d(TAG, "Slope flat enough for auto calibration");
                                                if (!delay_calibration) {
                                                    Home.startHomeWithExtra(xdrip.getAppContext(),
                                                            Home.BLUETOOTH_METER_CALIBRATION,
                                                            BgGraphBuilder.unitized_string_static(lastBloodTest.mgdl),
                                                            Long.toString(time_since),
                                                            "auto");
                                                } else {
                                                    Log.d(TAG, "Delaying calibration for later");
                                                    JoH.static_toast_long("Waiting for 15 minutes more sensor data for calibration");
                                                }
                                            } else {
                                                if (Pref.getBooleanDefaultFalse("bluetooth_meter_for_calibrations")) {
                                                    // manual calibration
                                                    Home.startHomeWithExtra(xdrip.getAppContext(),
                                                            Home.BLUETOOTH_METER_CALIBRATION,
                                                            BgGraphBuilder.unitized_string_static(lastBloodTest.mgdl),
                                                            Long.toString(time_since),
                                                            "manual");
                                                } else {
                                                    Log.d(TAG, "Not flat enough slope for auto calibration and manual calibration not enabled");
                                                }
                                            }
                                        }
                                    }, 500);
                                } else {
                                    UserError.Log.e(TAG, "evaluateLastRecords: meter reading is at least as old as last calibration - ignoring");
                                }
                            } else {
                                UserError.Log.e(TAG, "evaluateLastRecords: meter reading is too far in the past: " + JoH.dateTimeText(lastBloodTest.timestamp));
                            }
                        } else {
                            UserError.Log.e(TAG, "evaluateLastRecords: time is in the future - ignoring");
                        }
                    }
                }
            } else {
                UserError.Log.d(TAG, "evaluateLastRecords: sequence isn't newer");
            }
        } else {
            UserError.Log.e(TAG, "evaluateLastRecords: Data missing for evaluation");
        }
    } else {
        UserError.Log.e(TAG, "evaluateLastRecords: lastBloodTest is Null!!");
    }
}
 
Example 10
Source File: CalibrationGraph.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
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);

}