Search in sources :

Example 6 with BgReading

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

the class xDripWidget method displayCurrentInfo.

private static void displayCurrentInfo(AppWidgetManager appWidgetManager, int appWidgetId, Context context, RemoteViews views) {
    BgGraphBuilder bgGraphBuilder = new BgGraphBuilder(context);
    BgReading lastBgreading = BgReading.lastNoSenssor();
    final boolean showLines = Pref.getBoolean("widget_range_lines", false);
    final boolean showExstraStatus = Pref.getBoolean("extra_status_line", false) && Pref.getBoolean("widget_status_line", false);
    if (lastBgreading != null) {
        double estimate = 0;
        double estimated_delta = -9999;
        try {
            int height = appWidgetManager.getAppWidgetOptions(appWidgetId).getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT);
            int width = appWidgetManager.getAppWidgetOptions(appWidgetId).getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH);
            views.setImageViewBitmap(R.id.widgetGraph, new BgSparklineBuilder(context).setBgGraphBuilder(bgGraphBuilder).setBackgroundColor(ColorCache.getCol(ColorCache.X.color_widget_chart_background)).setHeight(height).setWidth(width).showHighLine(showLines).showLowLine(showLines).build());
            final BestGlucose.DisplayGlucose dg = (use_best_glucose) ? BestGlucose.getDisplayGlucose() : null;
            estimate = (dg != null) ? dg.mgdl : lastBgreading.calculated_value;
            String extrastring = "";
            String slope_arrow = (dg != null) ? dg.delta_arrow : lastBgreading.slopeArrow();
            String stringEstimate;
            if (dg == null) {
                // if not using best glucose helper
                if (BestGlucose.compensateNoise()) {
                    // this needs scaling based on noise intensity
                    estimate = BgGraphBuilder.best_bg_estimate;
                    estimated_delta = BgGraphBuilder.best_bg_estimate - BgGraphBuilder.last_bg_estimate;
                    // delta by minute
                    slope_arrow = BgReading.slopeToArrowSymbol(estimated_delta / (BgGraphBuilder.DEXCOM_PERIOD / 60000));
                    // currentBgValueText.setTypeface(null, Typeface.ITALIC);
                    // warning symbol !
                    extrastring = " \u26A0";
                }
                // TODO functionize this check as it is in multiple places
                if (Pref.getBooleanDefaultFalse("display_glucose_from_plugin") && (PluggableCalibration.getCalibrationPluginFromPreferences() != null)) {
                    extrastring += " " + context.getString(R.string.p_in_circle);
                }
            } else {
                // TODO make a couple of getters in dg for these functions
                extrastring = " " + dg.extra_string + ((dg.from_plugin) ? " " + context.getString(R.string.p_in_circle) : "");
                estimated_delta = dg.delta_mgdl;
                // TODO properly illustrate + standardize warning level
                if (dg.warning > 1)
                    slope_arrow = "";
            }
            // TODO use dg stale calculation and/or preformatted text
            if ((new Date().getTime()) - Home.stale_data_millis() - lastBgreading.timestamp > 0) {
                // estimate = lastBgreading.calculated_value;
                Log.d(TAG, "old value, estimate " + estimate);
                stringEstimate = bgGraphBuilder.unitized_string(estimate);
                // views.setTextViewText(R.id.widgetArrow, "--");
                slope_arrow = "--";
                views.setInt(R.id.widgetBg, "setPaintFlags", Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
            } else {
                // estimate = lastBgreading.calculated_value;
                stringEstimate = bgGraphBuilder.unitized_string(estimate);
                if (lastBgreading.hide_slope) {
                    slope_arrow = "--";
                }
                Log.d(TAG, "newish value, estimate " + stringEstimate + slope_arrow);
                views.setInt(R.id.widgetBg, "setPaintFlags", 0);
            }
            if (Sensor.isActive() || Home.get_follower()) {
                views.setTextViewText(R.id.widgetBg, stringEstimate);
                views.setTextViewText(R.id.widgetArrow, slope_arrow);
            } else {
                views.setTextViewText(R.id.widgetBg, "");
                views.setTextViewText(R.id.widgetArrow, "");
            }
            // is it really necessary to read this data once here and again in unitizedDeltaString?
            // couldn't we just use the unitizedDeltaString to detect the error condition?
            List<BgReading> bgReadingList = BgReading.latest(2, Home.get_follower());
            if (estimated_delta == -9999) {
                // use original delta
                if (bgReadingList != null && bgReadingList.size() == 2) {
                    views.setTextViewText(R.id.widgetDelta, bgGraphBuilder.unitizedDeltaString(true, true, Home.get_follower()));
                } else {
                    views.setTextViewText(R.id.widgetDelta, "--");
                }
            } else {
                // use compensated estimate
                views.setTextViewText(R.id.widgetDelta, bgGraphBuilder.unitizedDeltaStringRaw(true, true, estimated_delta));
            }
            // TODO use dg preformatted localized string
            int timeAgo = (int) Math.floor((new Date().getTime() - lastBgreading.timestamp) / (1000 * 60));
            if (timeAgo == 1) {
                views.setTextViewText(R.id.readingAge, timeAgo + " Minute ago" + extrastring);
            } else {
                views.setTextViewText(R.id.readingAge, timeAgo + " Minutes ago" + extrastring);
            }
            if (timeAgo > 15) {
                views.setTextColor(R.id.readingAge, Color.parseColor("#FFBB33"));
            } else {
                views.setTextColor(R.id.readingAge, Color.WHITE);
            }
            if (showExstraStatus) {
                views.setTextViewText(R.id.widgetStatusLine, Home.extraStatusLine());
                views.setViewVisibility(R.id.widgetStatusLine, View.VISIBLE);
            } else {
                views.setTextViewText(R.id.widgetStatusLine, "");
                views.setViewVisibility(R.id.widgetStatusLine, View.GONE);
            }
            if (bgGraphBuilder.unitized(estimate) <= bgGraphBuilder.lowMark) {
                views.setTextColor(R.id.widgetBg, Color.parseColor("#C30909"));
                views.setTextColor(R.id.widgetDelta, Color.parseColor("#C30909"));
                views.setTextColor(R.id.widgetArrow, Color.parseColor("#C30909"));
            } else if (bgGraphBuilder.unitized(estimate) >= bgGraphBuilder.highMark) {
                views.setTextColor(R.id.widgetBg, Color.parseColor("#FFBB33"));
                views.setTextColor(R.id.widgetDelta, Color.parseColor("#FFBB33"));
                views.setTextColor(R.id.widgetArrow, Color.parseColor("#FFBB33"));
            } else {
                views.setTextColor(R.id.widgetBg, Color.WHITE);
                views.setTextColor(R.id.widgetDelta, Color.WHITE);
                views.setTextColor(R.id.widgetArrow, Color.WHITE);
            }
        } catch (RuntimeException e) {
            Log.e(TAG, "Got exception in displaycurrentinfo: " + e);
        }
    }
}
Also used : BgSparklineBuilder(com.eveningoutpost.dexdrip.UtilityModels.BgSparklineBuilder) BgReading(com.eveningoutpost.dexdrip.Models.BgReading) Paint(android.graphics.Paint) Date(java.util.Date) BgGraphBuilder(com.eveningoutpost.dexdrip.UtilityModels.BgGraphBuilder)

Example 7 with BgReading

use of com.eveningoutpost.dexdrip.Models.BgReading 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 8 with BgReading

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

the class CalibrationAbstract method getBgReadingFromBgReading.

public BgReading getBgReadingFromBgReading(BgReading bgReading, CalibrationData data) {
    if (data == null)
        return null;
    if (bgReading == null)
        return null;
    // do we need deep clone?
    final BgReading new_bg = (BgReading) JoH.cloneObject(bgReading);
    if (new_bg == null)
        return null;
    // algorithm can override to decide whether or not to be using age_adjusted_raw
    new_bg.calculated_value = getGlucoseFromBgReading(bgReading, data);
    new_bg.filtered_calculated_value = getGlucoseFromFilteredBgReading(bgReading, data);
    return new_bg;
}
Also used : BgReading(com.eveningoutpost.dexdrip.Models.BgReading)

Example 9 with BgReading

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

the class Ob1G5StateMachine method processNewTransmitterData.

// Save/process the data in xDrip style
private static synchronized void processNewTransmitterData(int raw_data, int filtered_data, int sensor_battery_level, long captureTime) {
    final TransmitterData transmitterData = TransmitterData.create(raw_data, filtered_data, sensor_battery_level, captureTime);
    if (transmitterData == null) {
        UserError.Log.e(TAG, "TransmitterData.create failed: Duplicate packet");
        return;
    } else {
        UserError.Log.d(TAG, "Created transmitter data " + transmitterData.uuid + " " + JoH.dateTimeText(transmitterData.timestamp));
    // TODO timeInMillisecondsOfLastSuccessfulSensorRead = captureTime;
    }
    Sensor sensor = Sensor.currentSensor();
    if (sensor == null) {
        UserError.Log.e(TAG, "setSerialDataToTransmitterRawData: No Active Sensor, Data only stored in Transmitter Data");
        return;
    }
    // TODO : LOG if unfiltered or filtered values are zero
    Sensor.updateBatteryLevel(sensor, transmitterData.sensor_battery_level);
    if (d)
        UserError.Log.i(TAG, "timestamp create: " + Long.toString(transmitterData.timestamp));
    BgReading bgreading = BgReading.create(transmitterData.raw_data, transmitterData.filtered_data, xdrip.getAppContext(), transmitterData.timestamp);
    // KS
    UserError.Log.d(TAG, "Dex raw_data " + Double.toString(transmitterData.raw_data));
    // KS
    UserError.Log.d(TAG, "Dex filtered_data " + Double.toString(transmitterData.filtered_data));
    // KS
    UserError.Log.d(TAG, "Dex sensor_battery_level " + Double.toString(transmitterData.sensor_battery_level));
    // KS
    UserError.Log.d(TAG, "Dex timestamp " + JoH.dateTimeText(transmitterData.timestamp));
    UserError.Log.d(TAG, "BgReading created: " + bgreading.uuid + " " + JoH.dateTimeText(bgreading.timestamp));
// TODO static_last_timestamp =  transmitterData.timestamp;
}
Also used : TransmitterData(com.eveningoutpost.dexdrip.Models.TransmitterData) BgReading(com.eveningoutpost.dexdrip.Models.BgReading) Sensor(com.eveningoutpost.dexdrip.Models.Sensor)

Example 10 with BgReading

use of com.eveningoutpost.dexdrip.Models.BgReading 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)

Aggregations

BgReading (com.eveningoutpost.dexdrip.Models.BgReading)66 Date (java.util.Date)26 Calibration (com.eveningoutpost.dexdrip.Models.Calibration)20 Sensor (com.eveningoutpost.dexdrip.Models.Sensor)16 ArrayList (java.util.ArrayList)14 DataMap (com.google.android.gms.wearable.DataMap)12 Intent (android.content.Intent)8 Treatments (com.eveningoutpost.dexdrip.Models.Treatments)8 IOException (java.io.IOException)8 JSONException (org.json.JSONException)8 PendingIntent (android.app.PendingIntent)6 Paint (android.graphics.Paint)6 BloodTest (com.eveningoutpost.dexdrip.Models.BloodTest)6 TransmitterData (com.eveningoutpost.dexdrip.Models.TransmitterData)6 BgGraphBuilder (com.eveningoutpost.dexdrip.UtilityModels.BgGraphBuilder)6 CalibrationAbstract (com.eveningoutpost.dexdrip.calibrations.CalibrationAbstract)6 DecimalFormat (java.text.DecimalFormat)6 JSONArray (org.json.JSONArray)6 Point (android.graphics.Point)4 SpannableString (android.text.SpannableString)4