Search in sources :

Example 1 with Calibration

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

the class WatchUpdaterService method sendWearCalibrationData.

private static boolean sendWearCalibrationData(Integer count, long startTime, List<Calibration> list) {
    try {
        if (googleApiClient != null && !googleApiClient.isConnected() && !googleApiClient.isConnecting()) {
            googleApiClient.connect();
        }
        // if ((googleApiClient != null) && (googleApiClient.isConnected())) {
        if (googleApiClient != null) {
            Log.d(TAG, "sendWearCalibrationData");
            final Sensor sensor = Sensor.currentSensor();
            final Calibration last = list != null && list.size() > 0 ? list.get(0) : Calibration.last();
            List<Calibration> latest;
            BgReading lastBgReading = BgReading.last();
            // From BgReading:     lastBgReading.calibration.rawValueOverride()
            if (list != null)
                latest = list;
            else if (startTime != 0)
                latest = Calibration.latestForGraphSensor(count, startTime, Long.MAX_VALUE);
            else if (lastBgReading != null && lastBgReading.calibration != null && lastBgReading.calibration_flag == true) {
                Log.d(TAG, "sendWearCalibrationData lastBgReading.calibration_flag=" + lastBgReading.calibration_flag + " lastBgReading.timestamp: " + lastBgReading.timestamp + " lastBgReading.calibration.timestamp: " + lastBgReading.calibration.timestamp);
                latest = Calibration.allForSensor();
            } else {
                latest = Calibration.latest(count);
            }
            if ((sensor != null) && (last != null) && (latest != null && !latest.isEmpty())) {
                Log.d(TAG, "sendWearCalibrationData latest count = " + latest.size());
                final DataMap entries = dataMap(last);
                final ArrayList<DataMap> dataMaps = new ArrayList<>(latest.size());
                if (sensor.uuid != null) {
                    for (Calibration bg : latest) {
                        if ((bg != null) && (bg.sensor_uuid != null) && (bg.sensor_uuid.equals(sensor.uuid))) {
                            dataMaps.add(dataMap(bg));
                        }
                    }
                }
                // MOST IMPORTANT LINE FOR TIMESTAMP
                entries.putLong("time", new Date().getTime());
                entries.putDataMapArrayList("entries", dataMaps);
                new SendToDataLayerThread(WEARABLE_CALIBRATION_DATA_PATH, googleApiClient).executeOnExecutor(xdrip.executor, entries);
            } else
                Log.d(TAG, "sendWearCalibrationData latest count = 0");
        } else {
            Log.e(TAG, "sendWearCalibrationData No connection to wearable available for send treatment!");
            return false;
        }
    } catch (NullPointerException e) {
        Log.e(TAG, "Nullpointer exception in sendWearCalibrationData: " + e);
        return false;
    }
    return true;
}
Also used : ArrayList(java.util.ArrayList) Calibration(com.eveningoutpost.dexdrip.Models.Calibration) BgReading(com.eveningoutpost.dexdrip.Models.BgReading) Date(java.util.Date) Sensor(com.eveningoutpost.dexdrip.Models.Sensor) DataMap(com.google.android.gms.wearable.DataMap)

Example 2 with Calibration

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

the class ListenerService method syncCalibrationData.

private synchronized void syncCalibrationData(DataMap dataMap, Context context) {
    // KS
    Log.d(TAG, "syncCalibrationData");
    boolean changed = false;
    ArrayList<DataMap> entries = dataMap.getDataMapArrayList("entries");
    if (entries != null) {
        Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().registerTypeAdapter(Date.class, new DateTypeAdapter()).serializeSpecialFloatingPointValues().create();
        Log.d(TAG, "syncCalibrationData add Calibration Table entries count=" + entries.size());
        // ensure database has already been initialized
        Sensor.InitDb(context);
        Sensor sensor = Sensor.currentSensor();
        if (sensor != null) {
            for (DataMap entry : entries) {
                if (entry != null) {
                    String bgrecord = entry.getString("bgs");
                    if (bgrecord != null) {
                        Calibration bgData = gson.fromJson(bgrecord, Calibration.class);
                        Calibration exists = Calibration.findByUuid(bgData.uuid);
                        bgData.sensor = sensor;
                        if (exists != null) {
                            Log.d(TAG, "syncCalibrationData Calibration exists for uuid=" + bgData.uuid + " bg=" + bgData.bg + " timestamp=" + bgData.timestamp + " timeString=" + JoH.dateTimeText(bgData.timestamp));
                            if (exists.slope != bgData.slope || exists.slope_confidence != bgData.slope_confidence || exists.timestamp != bgData.timestamp || exists.bg != bgData.bg) {
                                // slope* indicates if shown on graph
                                changed = true;
                            }
                            exists.adjusted_raw_value = bgData.adjusted_raw_value;
                            exists.bg = bgData.bg;
                            exists.check_in = bgData.check_in;
                            exists.distance_from_estimate = bgData.distance_from_estimate;
                            exists.estimate_bg_at_time_of_calibration = bgData.estimate_bg_at_time_of_calibration;
                            exists.estimate_raw_at_time_of_calibration = bgData.estimate_raw_at_time_of_calibration;
                            exists.first_decay = bgData.first_decay;
                            exists.first_intercept = bgData.first_intercept;
                            exists.first_scale = bgData.first_scale;
                            exists.first_slope = bgData.first_slope;
                            exists.intercept = bgData.intercept;
                            exists.possible_bad = bgData.possible_bad;
                            exists.raw_timestamp = bgData.raw_timestamp;
                            exists.raw_value = bgData.raw_value;
                            exists.second_decay = bgData.second_decay;
                            exists.second_intercept = bgData.second_intercept;
                            exists.second_scale = bgData.second_scale;
                            exists.second_slope = bgData.second_slope;
                            exists.sensor = sensor;
                            exists.sensor_age_at_time_of_estimation = bgData.sensor_age_at_time_of_estimation;
                            exists.sensor_confidence = bgData.sensor_confidence;
                            exists.sensor_uuid = bgData.sensor_uuid;
                            exists.slope = bgData.slope;
                            exists.slope_confidence = bgData.slope_confidence;
                            exists.timestamp = bgData.timestamp;
                            exists.save();
                        } else {
                            changed = true;
                            bgData.save();
                            // final boolean adjustPast = mPrefs.getBoolean("rewrite_history", true);
                            Log.d(TAG, "syncCalibrationData Calibration does not exist for uuid=" + bgData.uuid + " timestamp=" + bgData.timestamp + " timeString=" + JoH.dateTimeText(bgData.timestamp));
                        // Calibration.adjustRecentBgReadings(adjustPast ? 30 : 2);
                        }
                        exists = Calibration.findByUuid(bgData.uuid);
                        if (exists != null)
                            Log.d(TAG, "syncCalibrationData Calibration GSON saved BG: " + exists.toS());
                        else
                            Log.d(TAG, "syncCalibrationData Calibration GSON NOT saved");
                    }
                }
            }
        } else {
            Log.d(TAG, "syncCalibrationData No Active Sensor!! Request WEARABLE_INITDB_PATH");
            sendData(WEARABLE_INITDB_PATH, null);
        }
        if (changed) {
            showTreatments(context, "cals");
        }
    }
}
Also used : DateTypeAdapter(com.google.gson.internal.bind.DateTypeAdapter) GsonBuilder(com.google.gson.GsonBuilder) Gson(com.google.gson.Gson) Calibration(com.eveningoutpost.dexdrip.Models.Calibration) DataMap(com.google.android.gms.wearable.DataMap) Sensor(com.eveningoutpost.dexdrip.Models.Sensor)

Example 3 with Calibration

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

the class ListenerService method getCalibrations.

public static DataMap getCalibrations(long startTime) {
    Calibration last = Calibration.last();
    if (last != null) {
        Log.d(TAG, "getCalibrations last.timestamp:" + JoH.dateTimeText(last.timestamp));
    }
    List<Calibration> graph = Calibration.latestForGraph(60, startTime, Long.MAX_VALUE);
    // calibrations = Calibration.latestForGraph(numValues, start - (3 * Constants.DAY_IN_MS), end);
    if (!graph.isEmpty()) {
        Log.d(TAG, "getCalibrations graph size=" + graph.size());
        final ArrayList<DataMap> dataMaps = new ArrayList<>(graph.size());
        DataMap entries = null;
        // if (last.slope_confidence != 0) entries = dataMapForWatchface(last);
        for (Calibration data : graph) {
            if (data.slope_confidence != 0) {
                if (entries == null) {
                    entries = dataMapForWatchface(data);
                    dataMaps.add(dataMapForWatchface(data));
                } else
                    dataMaps.add(dataMapForWatchface(data));
            }
        }
        if (entries != null) {
            entries.putDataMapArrayList("entries", dataMaps);
            Log.d(TAG, "getCalibrations entries=" + entries);
        }
        return entries;
    } else
        return null;
}
Also used : ArrayList(java.util.ArrayList) Calibration(com.eveningoutpost.dexdrip.Models.Calibration) DataMap(com.google.android.gms.wearable.DataMap)

Example 4 with Calibration

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

the class WebServicePebble method request.

// process the request and produce a response object
public WebResponse request(String query) {
    final BestGlucose.DisplayGlucose dg = BestGlucose.getDisplayGlucose();
    // TODO better error handling?
    if (dg == null)
        return null;
    final BgReading bgReading = BgReading.last();
    // TODO better error handling?
    if (bgReading == null)
        return null;
    // this can be null
    final Calibration calibration = Calibration.lastValid();
    // 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);
        // beware not coming from Display Glucose
        bgs.put("trend", bgReading.getSlopeOrdinal());
        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"));
        // TODO get iob
        bgs.put("iob", 0);
        // 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);
            // negated??
            cals.put("intercept", calibration.intercept * 1000);
            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);
    }
    return new WebResponse(reply.toString());
}
Also used : BestGlucose(com.eveningoutpost.dexdrip.BestGlucose) JSONObject(org.json.JSONObject) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) BgReading(com.eveningoutpost.dexdrip.Models.BgReading) Calibration(com.eveningoutpost.dexdrip.Models.Calibration)

Example 5 with Calibration

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

the class LastSevenUnweightedA method getCalibrationData.

@Override
public CalibrationData getCalibrationData(long until) {
    // TODO cache must understand until
    // CalibrationData cd = loadDataFromCache(TAG);
    CalibrationData cd = null;
    if (cd == null) {
        // first is most recent
        final List<Calibration> calibrations = Calibration.latestValid(7, until);
        if ((calibrations == null) || (calibrations.size() == 0))
            return null;
        // have we got enough data to have a go
        if (calibrations.size() < 4) {
            // just use whatever xDrip original would have come up with at this point
            Log.d(TAG, "Falling back to xDrip-original values");
            cd = new CalibrationData(calibrations.get(0).slope, calibrations.get(0).intercept);
        } else {
            // TODO sanity checks
            final TrendLine bg_to_raw = new PolyTrendLine(1);
            final List<Double> raws = new ArrayList<>();
            final List<Double> bgs = new ArrayList<>();
            final boolean adjust_raw = !DexCollectionType.hasLibre();
            for (Calibration calibration : calibrations) {
                // sanity check?
                // weighting!
                final double raw = adjust_raw ? calibration.adjusted_raw_value : calibration.raw_value;
                Log.d(TAG, "Calibration: " + raw + " -> " + calibration.bg);
                raws.add(raw);
                bgs.add(calibration.bg);
            }
            bg_to_raw.setValues(PolyTrendLine.toPrimitiveFromList(bgs), PolyTrendLine.toPrimitiveFromList(raws));
            Log.d(TAG, "Error Variance: " + bg_to_raw.errorVarience());
            final double intercept = bg_to_raw.predict(0);
            Log.d(TAG, "Intercept: " + intercept);
            final double one = bg_to_raw.predict(1);
            Log.d(TAG, "One: " + one);
            final double slope = one - intercept;
            Log.d(TAG, "Slope: " + slope);
            cd = new CalibrationData(slope, intercept);
        }
    }
    // null if invalid
    return cd;
}
Also used : PolyTrendLine(com.eveningoutpost.dexdrip.Models.Forecast.PolyTrendLine) ArrayList(java.util.ArrayList) Calibration(com.eveningoutpost.dexdrip.Models.Calibration) PolyTrendLine(com.eveningoutpost.dexdrip.Models.Forecast.PolyTrendLine) TrendLine(com.eveningoutpost.dexdrip.Models.Forecast.TrendLine)

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