use of com.eveningoutpost.dexdrip.Models.BgReading in project xDrip-plus by jamorham.
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;
}
use of com.eveningoutpost.dexdrip.Models.BgReading in project xDrip-plus by jamorham.
the class WatchUpdaterService method syncTransmitterData.
private synchronized void syncTransmitterData(DataMap dataMap, boolean bBenchmark) {
// KS
Log.d(TAG, "syncTransmitterData");
ArrayList<DataMap> entries = dataMap.getDataMapArrayList("entries");
long timeOfLastBG = 0;
Log.d(TAG, "syncTransmitterData add BgReading Table");
if (entries != null) {
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().registerTypeAdapter(Date.class, new DateTypeAdapter()).serializeSpecialFloatingPointValues().create();
int idx = 0;
int count = entries.size();
Log.d(TAG, "syncTransmitterData add BgReading Table entries count=" + count);
for (DataMap entry : entries) {
if (entry != null) {
// Log.d(TAG, "syncTransmitterData add BgReading Table entry=" + entry);
idx++;
String bgrecord = entry.getString("bgs");
if (bgrecord != null) {
// for (TransmitterData bgData : bgs) {
// Log.d(TAG, "syncTransmitterData add TransmitterData Table bgrecord=" + bgrecord);
TransmitterData bgData = gson.fromJson(bgrecord, TransmitterData.class);
// TransmitterData bgData = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().fromJson(bgrecord, TransmitterData.class);
TransmitterData exists = TransmitterData.getForTimestamp(bgData.timestamp);
TransmitterData uuidexists = TransmitterData.findByUuid(bgData.uuid);
timeOfLastBG = bgData.timestamp + 1;
if (exists != null || uuidexists != null) {
Log.d(TAG, "syncTransmitterData BG already exists for uuid=" + bgData.uuid + " timestamp=" + bgData.timestamp + " timeString=" + JoH.dateTimeText(bgData.timestamp) + " raw_data=" + bgData.raw_data);
} else {
Log.d(TAG, "syncTransmitterData add BG; does NOT exist for uuid=" + bgData.uuid + " timestamp=" + bgData.timestamp + " timeString=" + JoH.dateTimeText(bgData.timestamp) + " raw_data=" + bgData.raw_data);
if (!bBenchmark) {
bgData.save();
// Check
if (TransmitterData.findByUuid(bgData.uuid) != null)
Log.d(TAG, "syncTransmitterData: TransmitterData was saved for uuid:" + bgData.uuid);
else {
Log.e(TAG, "syncTransmitterData: TransmitterData was NOT saved for uuid:" + bgData.uuid);
return;
}
// KS the following is from G5CollectionService processNewTransmitterData()
Sensor sensor = Sensor.currentSensor();
if (sensor == null) {
Log.e(TAG, "syncTransmitterData: No Active Sensor, Data only stored in Transmitter Data");
return;
}
// TODO : LOG if unfiltered or filtered values are zero
Sensor.updateBatteryLevel(sensor, bgData.sensor_battery_level);
// android.util.Log.i
Log.i(TAG, "syncTransmitterData: BG timestamp create " + Long.toString(bgData.timestamp));
BgReading bgExists;
// KS TODO wear implements limited alerts, therefore continue to process all alerts on phone for last entry
if (count > 1 && idx < count) {
// Disable Notifications for bulk insert
bgExists = BgReading.create(bgData.raw_data, bgData.filtered_data, this, bgData.timestamp, true);
} else {
bgExists = BgReading.create(bgData.raw_data, bgData.filtered_data, this, bgData.timestamp);
}
if (bgExists != null)
Log.d(TAG, "syncTransmitterData BG GSON saved BG: " + bgExists.toS());
else
Log.e(TAG, "syncTransmitterData BG GSON NOT saved");
}
}
}
}
}
sendDataReceived(DATA_ITEM_RECEIVED_PATH, "DATA_RECEIVED_BGS count=" + entries.size(), timeOfLastBG, bBenchmark ? "BM" : "BG", -1);
}
}
use of com.eveningoutpost.dexdrip.Models.BgReading in project xDrip-plus by jamorham.
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());
}
use of com.eveningoutpost.dexdrip.Models.BgReading in project xDrip-plus by jamorham.
the class Home method extraStatusLine.
@NonNull
public static String extraStatusLine() {
final StringBuilder extraline = new StringBuilder();
final Calibration lastCalibration = Calibration.lastValid();
if (Pref.getBoolean("status_line_calibration_long", false) && lastCalibration != null) {
if (extraline.length() != 0)
extraline.append(' ');
extraline.append("slope = ");
extraline.append(String.format("%.2f", lastCalibration.slope));
extraline.append(' ');
extraline.append("inter = ");
extraline.append(String.format("%.2f", lastCalibration.intercept));
}
if (Pref.getBoolean("status_line_calibration_short", false) && lastCalibration != null) {
if (extraline.length() != 0)
extraline.append(' ');
extraline.append("s:");
extraline.append(String.format("%.2f", lastCalibration.slope));
extraline.append(' ');
extraline.append("i:");
extraline.append(String.format("%.2f", lastCalibration.intercept));
}
if (Pref.getBoolean("status_line_avg", false) || Pref.getBoolean("status_line_a1c_dcct", false) || Pref.getBoolean("status_line_a1c_ifcc", false) || Pref.getBoolean("status_line_in", false) || Pref.getBoolean("status_line_high", false) || Pref.getBoolean("status_line_low", false) || Pref.getBoolean("status_line_stdev", false) || Pref.getBoolean("status_line_carbs", false) || Pref.getBoolean("status_line_insulin", false) || Pref.getBoolean("status_line_royce_ratio", false) || Pref.getBoolean("status_line_accuracy", false) || Pref.getBoolean("status_line_capture_percentage", false) || Pref.getBoolean("status_line_pump_reservoir", false)) {
final StatsResult statsResult = new StatsResult(Pref.getInstance(), Pref.getBooleanDefaultFalse("extra_status_stats_24h"));
if (Pref.getBoolean("status_line_avg", false)) {
if (extraline.length() != 0)
extraline.append(' ');
extraline.append(statsResult.getAverageUnitised());
}
if (Pref.getBoolean("status_line_a1c_dcct", false)) {
if (extraline.length() != 0)
extraline.append(' ');
extraline.append(statsResult.getA1cDCCT());
}
if (Pref.getBoolean("status_line_a1c_ifcc", false)) {
if (extraline.length() != 0)
extraline.append(' ');
extraline.append(statsResult.getA1cIFCC());
}
if (Pref.getBoolean("status_line_in", false)) {
if (extraline.length() != 0)
extraline.append(' ');
extraline.append(statsResult.getInPercentage());
}
if (Pref.getBoolean("status_line_high", false)) {
if (extraline.length() != 0)
extraline.append(' ');
extraline.append(statsResult.getHighPercentage());
}
if (Pref.getBoolean("status_line_low", false)) {
if (extraline.length() != 0)
extraline.append(' ');
extraline.append(statsResult.getLowPercentage());
}
if (Pref.getBoolean("status_line_stdev", false)) {
if (extraline.length() != 0)
extraline.append(' ');
extraline.append(statsResult.getStdevUnitised());
}
if (Pref.getBoolean("status_line_carbs", false)) {
if (extraline.length() != 0)
extraline.append(' ');
// extraline.append("Carbs: " + statsResult.getTotal_carbs());
extraline.append("Carbs:" + Math.round(statsResult.getTotal_carbs()));
}
if (Pref.getBoolean("status_line_insulin", false)) {
if (extraline.length() != 0)
extraline.append(' ');
extraline.append("U:" + JoH.qs(statsResult.getTotal_insulin(), 2));
}
if (Pref.getBoolean("status_line_royce_ratio", false)) {
if (extraline.length() != 0)
extraline.append(' ');
extraline.append("C/I:" + JoH.qs(statsResult.getRatio(), 2));
}
if (Pref.getBoolean("status_line_capture_percentage", false)) {
if (extraline.length() != 0)
extraline.append(' ');
extraline.append(statsResult.getCapturePercentage(false));
}
if (Pref.getBoolean("status_line_accuracy", false)) {
final long accuracy_period = DAY_IN_MS * 3;
if (extraline.length() != 0)
extraline.append(' ');
final String accuracy_report = Accuracy.evaluateAccuracy(accuracy_period);
if ((accuracy_report != null) && (accuracy_report.length() > 0)) {
extraline.append(accuracy_report);
} else {
final String accuracy = BloodTest.evaluateAccuracy(accuracy_period);
extraline.append(((accuracy != null) ? " " + accuracy : ""));
}
}
if (Pref.getBoolean("status_line_pump_reservoir", false)) {
if (extraline.length() != 0)
extraline.append(' ');
extraline.append(PumpStatus.getBolusIoBString());
extraline.append(PumpStatus.getReservoirString());
extraline.append(PumpStatus.getBatteryString());
}
}
if (Pref.getBoolean("extra_status_calibration_plugin", false)) {
// make sure do this only once
final CalibrationAbstract plugin = getCalibrationPluginFromPreferences();
if (plugin != null) {
final CalibrationAbstract.CalibrationData pcalibration = plugin.getCalibrationData();
// not tested on the widget yet
if (extraline.length() > 0)
extraline.append("\n");
if (pcalibration != null)
extraline.append("(" + plugin.getAlgorithmName() + ") s:" + JoH.qs(pcalibration.slope, 2) + " i:" + JoH.qs(pcalibration.intercept, 2));
BgReading bgReading = BgReading.last();
if (bgReading != null) {
final boolean doMgdl = Pref.getString("units", "mgdl").equals("mgdl");
extraline.append(" \u21D2 " + BgGraphBuilder.unitized_string(plugin.getGlucoseFromSensorValue(bgReading.age_adjusted_raw_value), doMgdl) + " " + BgGraphBuilder.unit(doMgdl));
}
}
// If we are using the plugin as the primary then show xdrip original as well
if (Pref.getBooleanDefaultFalse("display_glucose_from_plugin") || Pref.getBooleanDefaultFalse("use_pluggable_alg_as_primary")) {
// make sure do this only once
final CalibrationAbstract plugin_xdrip = getCalibrationPlugin(PluggableCalibration.Type.xDripOriginal);
if (plugin_xdrip != null) {
final CalibrationAbstract.CalibrationData pcalibration = plugin_xdrip.getCalibrationData();
if (extraline.length() > 0)
// not tested on the widget yet
extraline.append("\n");
if (pcalibration != null)
extraline.append("(" + plugin_xdrip.getAlgorithmName() + ") s:" + JoH.qs(pcalibration.slope, 2) + " i:" + JoH.qs(pcalibration.intercept, 2));
BgReading bgReading = BgReading.last();
if (bgReading != null) {
final boolean doMgdl = Pref.getString("units", "mgdl").equals("mgdl");
extraline.append(" \u21D2 " + BgGraphBuilder.unitized_string(plugin_xdrip.getGlucoseFromSensorValue(bgReading.age_adjusted_raw_value), doMgdl) + " " + BgGraphBuilder.unit(doMgdl));
}
}
}
}
if (Pref.getBoolean("status_line_time", false)) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
if (extraline.length() != 0)
extraline.append(' ');
extraline.append(sdf.format(new Date()));
}
return extraline.toString();
}
use of com.eveningoutpost.dexdrip.Models.BgReading in project xDrip-plus by jamorham.
the class Home method displayCurrentInfoFromReading.
private void displayCurrentInfoFromReading(BgReading lastBgReading, boolean predictive) {
double estimate = 0;
double estimated_delta = 0;
if (lastBgReading == null)
return;
final BestGlucose.DisplayGlucose dg = BestGlucose.getDisplayGlucose();
if (dg == null)
return;
// String slope_arrow = lastBgReading.slopeArrow();
String slope_arrow = dg.delta_arrow;
String extrastring = "";
// when stale
if ((new Date().getTime()) - stale_data_millis() - lastBgReading.timestamp > 0) {
notificationText.setText(R.string.signal_missed);
if (!predictive) {
// estimate = lastBgReading.calculated_value;
estimate = dg.mgdl;
} else {
estimate = BgReading.estimated_bg(lastBgReading.timestamp + (6000 * 7));
}
currentBgValueText.setText(bgGraphBuilder.unitized_string(estimate));
currentBgValueText.setPaintFlags(currentBgValueText.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
dexbridgeBattery.setPaintFlags(dexbridgeBattery.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
} else {
// not stale
if (notificationText.getText().length() == 0) {
notificationText.setTextColor(Color.WHITE);
}
boolean bg_from_filtered = Pref.getBoolean("bg_from_filtered", false);
if (!predictive) {
// estimate = lastBgReading.calculated_value; // normal
estimate = dg.mgdl;
currentBgValueText.setTypeface(null, Typeface.NORMAL);
// if noise has settled down then switch off filtered mode
if ((bg_from_filtered) && (BgGraphBuilder.last_noise < BgGraphBuilder.NOISE_FORGIVE) && (Pref.getBoolean("bg_compensate_noise", false))) {
bg_from_filtered = false;
Pref.setBoolean("bg_from_filtered", false);
}
// TODO this should be partially already be covered by dg - recheck
if (BestGlucose.compensateNoise()) {
// this maybe 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";
if ((BgGraphBuilder.last_noise > BgGraphBuilder.NOISE_HIGH) && (DexCollectionType.hasFiltered())) {
// force filtered mode
bg_from_filtered = true;
}
}
if (bg_from_filtered) {
currentBgValueText.setPaintFlags(currentBgValueText.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
estimate = lastBgReading.filtered_calculated_value;
} else {
currentBgValueText.setPaintFlags(currentBgValueText.getPaintFlags() & ~Paint.UNDERLINE_TEXT_FLAG);
}
String stringEstimate = bgGraphBuilder.unitized_string(estimate);
if ((lastBgReading.hide_slope) || (bg_from_filtered)) {
slope_arrow = "";
}
currentBgValueText.setText(stringEstimate + " " + slope_arrow);
} else {
// old depreciated prediction
estimate = BgReading.activePrediction();
String stringEstimate = bgGraphBuilder.unitized_string(estimate);
currentBgValueText.setText(stringEstimate + " " + BgReading.activeSlopeArrow());
}
if (extrastring.length() > 0)
currentBgValueText.setText(extrastring + currentBgValueText.getText());
}
int minutes = (int) (System.currentTimeMillis() - lastBgReading.timestamp) / (60 * 1000);
if ((!small_width) || (notificationText.length() > 0))
notificationText.append("\n");
if (!small_width) {
notificationText.append(minutes + ((minutes == 1) ? getString(R.string.space_minute_ago) : getString(R.string.space_minutes_ago)));
} else {
// small screen
notificationText.append(minutes + getString(R.string.space_mins));
currentBgValueText.setPadding(0, 0, 0, 0);
}
if (small_screen) {
if (currentBgValueText.getText().length() > 4)
currentBgValueText.setTextSize(25);
}
// do we actually need to do this query here if we again do it in unitizedDeltaString
List<BgReading> bgReadingList = BgReading.latest(2, is_follower);
if (bgReadingList != null && bgReadingList.size() == 2) {
// same logic as in xDripWidget (refactor that to BGReadings to avoid redundancy / later inconsistencies)?
// display_delta = bgGraphBuilder.unitizedDeltaString(true, true, is_follower);
display_delta = dg.unitized_delta;
if (BestGlucose.compensateNoise()) {
// final double estimated_delta = BgGraphBuilder.best_bg_estimate - BgGraphBuilder.last_bg_estimate;
display_delta = bgGraphBuilder.unitizedDeltaStringRaw(true, true, estimated_delta);
addDisplayDelta();
if (!Pref.getBoolean("show_noise_workings", false)) {
notificationText.append("\nNoise: " + bgGraphBuilder.noiseString(BgGraphBuilder.last_noise));
}
} else {
addDisplayDelta();
}
}
if (bgGraphBuilder.unitized(estimate) <= bgGraphBuilder.lowMark) {
currentBgValueText.setTextColor(Color.parseColor("#C30909"));
} else if (bgGraphBuilder.unitized(estimate) >= bgGraphBuilder.highMark) {
currentBgValueText.setTextColor(Color.parseColor("#FFBB33"));
} else {
currentBgValueText.setTextColor(Color.WHITE);
}
// TODO this should be made more efficient probably
if (Pref.getBooleanDefaultFalse("display_glucose_from_plugin") && (PluggableCalibration.getCalibrationPluginFromPreferences() != null)) {
// adds warning P in circle icon
currentBgValueText.setText(getString(R.string.p_in_circle) + currentBgValueText.getText());
}
}
Aggregations