Search in sources :

Example 6 with BloodTest

use of com.eveningoutpost.dexdrip.Models.BloodTest in project xDrip-plus by jamorham.

the class NightscoutUploader method doRESTUploadTo.

private void doRESTUploadTo(NightscoutService nightscoutService, String secret, List<BgReading> glucoseDataSets, List<BloodTest> meterRecords, List<Calibration> calRecords) throws Exception {
    final JSONArray array = new JSONArray();
    for (BgReading record : glucoseDataSets) {
        populateV1APIBGEntry(array, record);
    }
    for (BloodTest record : meterRecords) {
        populateV1APIMeterReadingEntry(array, record);
    }
    for (Calibration record : calRecords) {
        final BloodTest dupe = BloodTest.getForPreciseTimestamp(record.timestamp, 60000);
        if (dupe == null) {
            // also add calibrations as meter records
            populateV1APIMeterReadingEntry(array, record);
        } else {
            Log.d(TAG, "Found duplicate blood test entry for this calibration record: " + record.bg + " vs " + dupe.mgdl + " mg/dl");
        }
        populateV1APICalibrationEntry(array, record);
    }
    if (array.length() > 0) {
        // KS
        final RequestBody body = RequestBody.create(MediaType.parse("application/json"), array.toString());
        final Response<ResponseBody> r = nightscoutService.upload(secret, body).execute();
        if (!r.isSuccess())
            throw new UploaderException(r.message(), r.code());
        checkGzipSupport(r);
        try {
            postDeviceStatus(nightscoutService, secret);
        } catch (Exception e) {
            Log.e(TAG, "Ignoring devicestatus post exception: " + e);
        }
    }
    try {
        if (Pref.getBooleanDefaultFalse("send_treatments_to_nightscout")) {
            postTreatments(nightscoutService, secret);
        } else {
            Log.d(TAG, "Skipping treatment upload due to preference disabled");
        }
    } catch (Exception e) {
        Log.e(TAG, "Exception uploading REST API treatments: " + e.getMessage());
        if (e.getMessage().equals("Not Found")) {
            final String msg = "Please ensure careportal plugin is enabled on nightscout for treatment upload!";
            Log.wtf(TAG, msg);
            Home.toaststaticnext(msg);
            handleRestFailure(msg);
        }
    }
    // TODO in the future we may want to merge these in to a single post
    if (Pref.getBooleanDefaultFalse("use_pebble_health") && (Home.get_engineering_mode())) {
        try {
            postHeartRate(nightscoutService, secret);
            postStepsCount(nightscoutService, secret);
            postMotionTracking(nightscoutService, secret);
        } catch (Exception e) {
            if (JoH.ratelimit("heartrate-upload-exception", 3600)) {
                Log.e(TAG, "Exception uploading REST API heartrate: " + e.getMessage());
            }
        }
    }
}
Also used : BloodTest(com.eveningoutpost.dexdrip.Models.BloodTest) JSONArray(org.json.JSONArray) BgReading(com.eveningoutpost.dexdrip.Models.BgReading) Calibration(com.eveningoutpost.dexdrip.Models.Calibration) URISyntaxException(java.net.URISyntaxException) JSONException(org.json.JSONException) IOException(java.io.IOException) RequestBody(com.squareup.okhttp.RequestBody) ResponseBody(com.squareup.okhttp.ResponseBody)

Example 7 with BloodTest

use of com.eveningoutpost.dexdrip.Models.BloodTest in project xDrip-plus by jamorham.

the class UploaderTask method doInBackground.

public Void doInBackground(String... urls) {
    try {
        final List<Long> circuits = new ArrayList<>();
        final List<String> types = new ArrayList<>();
        types.add(BgReading.class.getSimpleName());
        types.add(Calibration.class.getSimpleName());
        types.add(BloodTest.class.getSimpleName());
        types.add(Treatments.class.getSimpleName());
        if (Pref.getBooleanDefaultFalse("wear_sync")) {
            circuits.add(UploaderQueue.WATCH_WEARAPI);
        }
        if (Pref.getBooleanDefaultFalse("cloud_storage_mongodb_enable")) {
            circuits.add(UploaderQueue.MONGO_DIRECT);
        }
        if (Pref.getBooleanDefaultFalse("cloud_storage_api_enable")) {
            if ((Pref.getBoolean("cloud_storage_api_use_mobile", true) || (JoH.isLANConnected()))) {
                circuits.add(UploaderQueue.NIGHTSCOUT_RESTAPI);
            } else {
                Log.e(TAG, "Skipping Nightscout upload due to mobile data only");
            }
        }
        if (Pref.getBooleanDefaultFalse("cloud_storage_influxdb_enable")) {
            circuits.add(UploaderQueue.INFLUXDB_RESTAPI);
        }
        for (long THIS_QUEUE : circuits) {
            final List<BgReading> bgReadings = new ArrayList<>();
            final List<Calibration> calibrations = new ArrayList<>();
            final List<BloodTest> bloodtests = new ArrayList<>();
            final List<Treatments> treatmentsAdd = new ArrayList<>();
            final List<String> treatmentsDel = new ArrayList<>();
            final List<UploaderQueue> items = new ArrayList<>();
            for (String type : types) {
                final List<UploaderQueue> bgups = UploaderQueue.getPendingbyType(type, THIS_QUEUE);
                if (bgups != null) {
                    for (UploaderQueue up : bgups) {
                        switch(up.action) {
                            case "insert":
                            case "update":
                            case "create":
                                items.add(up);
                                if (type.equals(BgReading.class.getSimpleName())) {
                                    final BgReading this_bg = BgReading.byid(up.reference_id);
                                    if (this_bg != null) {
                                        bgReadings.add(this_bg);
                                    } else {
                                        Log.wtf(TAG, "BgReading with ID: " + up.reference_id + " appears to have been deleted");
                                    }
                                } else if (type.equals(Calibration.class.getSimpleName())) {
                                    final Calibration this_cal = Calibration.byid(up.reference_id);
                                    if ((this_cal != null) && (this_cal.isValid())) {
                                        calibrations.add(this_cal);
                                    } else {
                                        Log.wtf(TAG, "Calibration with ID: " + up.reference_id + " appears to have been deleted");
                                    }
                                } else if (type.equals(BloodTest.class.getSimpleName())) {
                                    final BloodTest this_bt = BloodTest.byid(up.reference_id);
                                    if (this_bt != null) {
                                        bloodtests.add(this_bt);
                                    } else {
                                        Log.wtf(TAG, "Bloodtest with ID: " + up.reference_id + " appears to have been deleted");
                                    }
                                } else if (type.equals(Treatments.class.getSimpleName())) {
                                    final Treatments this_treat = Treatments.byid(up.reference_id);
                                    if (this_treat != null) {
                                        treatmentsAdd.add(this_treat);
                                    } else {
                                        Log.wtf(TAG, "Treatments with ID: " + up.reference_id + " appears to have been deleted");
                                    }
                                }
                                break;
                            case "delete":
                                if ((THIS_QUEUE == UploaderQueue.WATCH_WEARAPI || THIS_QUEUE == UploaderQueue.NIGHTSCOUT_RESTAPI) && type.equals(Treatments.class.getSimpleName())) {
                                    items.add(up);
                                    Log.wtf(TAG, "Delete Treatments with ID: " + up.reference_uuid);
                                    treatmentsDel.add(up.reference_uuid);
                                } else if (up.reference_uuid != null) {
                                    Log.d(TAG, UploaderQueue.getCircuitName(THIS_QUEUE) + " delete not yet implemented: " + up.reference_uuid);
                                    // mark as completed so as not to tie up the queue for now
                                    up.completed(THIS_QUEUE);
                                }
                                break;
                            default:
                                Log.e(TAG, "Unsupported operation type for " + type + " " + up.action);
                                break;
                        }
                    }
                }
            }
            if ((bgReadings.size() > 0) || (calibrations.size() > 0) || (bloodtests.size() > 0) || (treatmentsAdd.size() > 0 || treatmentsDel.size() > 0) || (UploaderQueue.getPendingbyType(Treatments.class.getSimpleName(), THIS_QUEUE, 1).size() > 0)) {
                Log.d(TAG, UploaderQueue.getCircuitName(THIS_QUEUE) + " Processing: " + bgReadings.size() + " BgReadings and " + calibrations.size() + " Calibrations " + bloodtests.size() + " bloodtests " + treatmentsAdd.size() + " treatmentsAdd " + treatmentsDel.size() + " treatmentsDel");
                boolean uploadStatus = false;
                if (THIS_QUEUE == UploaderQueue.MONGO_DIRECT) {
                    final NightscoutUploader uploader = new NightscoutUploader(xdrip.getAppContext());
                    uploadStatus = uploader.uploadMongo(bgReadings, calibrations, calibrations);
                } else if (THIS_QUEUE == UploaderQueue.NIGHTSCOUT_RESTAPI) {
                    final NightscoutUploader uploader = new NightscoutUploader(xdrip.getAppContext());
                    uploadStatus = uploader.uploadRest(bgReadings, bloodtests, calibrations);
                } else if (THIS_QUEUE == UploaderQueue.INFLUXDB_RESTAPI) {
                    final InfluxDBUploader influxDBUploader = new InfluxDBUploader(xdrip.getAppContext());
                    uploadStatus = influxDBUploader.upload(bgReadings, calibrations, calibrations);
                } else if (THIS_QUEUE == UploaderQueue.WATCH_WEARAPI) {
                    uploadStatus = WatchUpdaterService.sendWearUpload(bgReadings, calibrations, bloodtests, treatmentsAdd, treatmentsDel);
                }
                // TODO some kind of fail counter?
                if (uploadStatus) {
                    for (UploaderQueue up : items) {
                        // approve all types for this queue
                        up.completed(THIS_QUEUE);
                    }
                    Log.d(TAG, UploaderQueue.getCircuitName(THIS_QUEUE) + " Marking: " + items.size() + " Items as successful");
                    if (PersistentStore.getBoolean(BACKFILLING_BOOSTER)) {
                        Log.d(TAG, "Scheduling boosted repeat query");
                        SyncService.startSyncService(2000);
                    }
                }
            } else {
                Log.d(TAG, "Nothing to upload for: " + UploaderQueue.getCircuitName(THIS_QUEUE));
                if (PersistentStore.getBoolean(BACKFILLING_BOOSTER)) {
                    PersistentStore.setBoolean(BACKFILLING_BOOSTER, false);
                    Log.d(TAG, "Switched off backfilling booster");
                }
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "caught exception", e);
        exception = e;
        return null;
    }
    return null;
}
Also used : BloodTest(com.eveningoutpost.dexdrip.Models.BloodTest) ArrayList(java.util.ArrayList) Calibration(com.eveningoutpost.dexdrip.Models.Calibration) InfluxDBUploader(com.eveningoutpost.dexdrip.InfluxDB.InfluxDBUploader) BgReading(com.eveningoutpost.dexdrip.Models.BgReading) Treatments(com.eveningoutpost.dexdrip.Models.Treatments)

Example 8 with BloodTest

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

the class BluetoothGlucoseMeter method processCharacteristicChange.

private synchronized void processCharacteristicChange(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {
    // extra debug
    if (d) {
        UserError.Log.d(TAG, "charactersiticChanged: " + characteristic.getUuid().toString() + " " + JoH.bytesToHex(characteristic.getValue()));
    }
    if (GLUCOSE_CHARACTERISTIC.equals(characteristic.getUuid())) {
        final GlucoseReadingRx gtb = new GlucoseReadingRx(characteristic.getValue(), gatt.getDevice().getAddress());
        UserError.Log.d(TAG, "Result: " + gtb.toString());
        if (ct == null) {
            statusUpdate("Cannot process glucose record as we do not know device time!");
        } else {
            markDeviceAsSuccessful(gatt);
            statusUpdate("Glucose Record: " + JoH.dateTimeText((gtb.time - ct.timediff) + gtb.offsetMs()) + "\n" + unitized_string_with_units_static(gtb.mgdl));
            if (playSounds() && JoH.ratelimit("bt_meter_data_in", 1))
                JoH.playResourceAudio(R.raw.bt_meter_data_in);
            if ((!ignore_control_solution_tests) || (gtb.sampleType != 10)) {
                final BloodTest bt = BloodTest.create((gtb.time - ct.timediff) + gtb.offsetMs(), gtb.mgdl, BLUETOOTH_GLUCOSE_METER_TAG + ":\n" + mLastManufacturer + "   " + mLastConnectedDeviceAddress);
                if (bt != null) {
                    UserError.Log.d(TAG, "Successfully created new BloodTest: " + bt.toS());
                    // add reference
                    bt.glucoseReadingRx = gtb;
                    lastBloodTest = bt;
                    final long record_time = lastBloodTest.timestamp;
                    JoH.runOnUiThreadDelayed(new Runnable() {

                        @Override
                        public void run() {
                            if (lastBloodTest.timestamp == record_time) {
                                evaluateLastRecords();
                            }
                        }
                    }, 1000);
                } else {
                    if (d)
                        UserError.Log.d(TAG, "Failed to create BloodTest record");
                }
            } else {
                UserError.Log.d(TAG, "Ignoring control solution test");
            }
        }
    } else if (RECORDS_CHARACTERISTIC.equals(characteristic.getUuid())) {
        UserError.Log.d(TAG, "Change notification for RECORDS: " + JoH.bytesToHex(characteristic.getValue()));
    } else if (CONTEXT_CHARACTERISTIC.equals(characteristic.getUuid())) {
        UserError.Log.d(TAG, "Change notification for CONTEXT: " + JoH.bytesToHex(characteristic.getValue()));
    } else if (VERIO_F7A3_NOTIFICATION.equals(characteristic.getUuid())) {
        UserError.Log.d(TAG, "Change notification for VERIO: " + JoH.bytesToHex(characteristic.getValue()));
        try {
            final GlucoseReadingRx gtb = VerioHelper.parseMessage(characteristic.getValue());
            if (gtb != null) {
                // if this was a BG reading we could process (offset already pre-calculated in time) - not robust against meter clock changes
                markDeviceAsSuccessful(gatt);
                statusUpdate("Glucose Record: " + JoH.dateTimeText((gtb.time + gtb.offsetMs())) + "\n" + unitized_string_with_units_static(gtb.mgdl));
                if (playSounds() && JoH.ratelimit("bt_meter_data_in", 1))
                    JoH.playResourceAudio(R.raw.bt_meter_data_in);
                final BloodTest bt = BloodTest.create((gtb.time) + gtb.offsetMs(), gtb.mgdl, BLUETOOTH_GLUCOSE_METER_TAG + ":\n" + mLastManufacturer + "   " + mLastConnectedDeviceAddress);
                if (bt != null) {
                    UserError.Log.d(TAG, "Successfully created new BloodTest: " + bt.toS());
                    // add reference
                    bt.glucoseReadingRx = gtb;
                    lastBloodTest = bt;
                    final long record_time = lastBloodTest.timestamp;
                    JoH.runOnUiThreadDelayed(new Runnable() {

                        @Override
                        public void run() {
                            if (lastBloodTest.timestamp == record_time) {
                                // zero hack
                                ct = new CurrentTimeRx();
                                evaluateLastRecords();
                            }
                        }
                    }, 1000);
                } else {
                    if (d)
                        UserError.Log.d(TAG, "Failed to create BloodTest record");
                }
            }
        } catch (Exception e) {
            UserError.Log.wtf(TAG, "Got exception processing Verio data " + e);
        }
    } else {
        UserError.Log.e(TAG, "Unknown characteristic change: " + characteristic.getUuid().toString() + " " + JoH.bytesToHex(characteristic.getValue()));
    }
}
Also used : CurrentTimeRx(com.eveningoutpost.dexdrip.GlucoseMeter.CurrentTimeRx) BloodTest(com.eveningoutpost.dexdrip.Models.BloodTest) GlucoseReadingRx(com.eveningoutpost.dexdrip.GlucoseMeter.GlucoseReadingRx)

Example 9 with BloodTest

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

the class ListenerService method syncBloodTestData.

private synchronized void syncBloodTestData(DataMap dataMap, Context context) {
    // KS
    Log.d(TAG, "syncBloodTestData");
    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, "syncBloodTestData add BloodTest Table entries count=" + entries.size());
        // ensure database has already been initialized
        Sensor.InitDb(context);
        for (DataMap entry : entries) {
            if (entry != null) {
                String record = entry.getString("data");
                if (record != null) {
                    BloodTest data = gson.fromJson(record, BloodTest.class);
                    BloodTest exists = BloodTest.byUUID(data.uuid);
                    if (exists != null) {
                        Log.d(TAG, "syncBloodTestData save existing BloodTest for uuid=" + data.uuid + " timestamp=" + data.timestamp + " timeString=" + JoH.dateTimeText(data.timestamp) + " mgdl=" + data.mgdl + " state=" + data.state);
                        if (exists.mgdl != data.mgdl || exists.state != data.state || exists.timestamp != data.timestamp) {
                            // state indicates if deleted
                            changed = true;
                        }
                        exists.mgdl = data.mgdl;
                        exists.created_timestamp = data.created_timestamp;
                        exists.source = data.source;
                        exists.state = data.state;
                        exists.timestamp = data.timestamp;
                        exists.save();
                    } else {
                        changed = true;
                        data.save();
                        Log.d(TAG, "syncBloodTestData create new BloodTest for uuid=" + data.uuid + " timestamp=" + data.timestamp + " timeString=" + JoH.dateTimeText(data.timestamp) + " mgdl=" + data.mgdl + " state=" + data.state);
                    }
                }
            }
        }
        if (changed) {
            showTreatments(context, "bts");
        }
    }
}
Also used : DateTypeAdapter(com.google.gson.internal.bind.DateTypeAdapter) GsonBuilder(com.google.gson.GsonBuilder) BloodTest(com.eveningoutpost.dexdrip.Models.BloodTest) Gson(com.google.gson.Gson) DataMap(com.google.android.gms.wearable.DataMap)

Example 10 with BloodTest

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

the class WatchUpdaterService method sendWearBloodTestData.

public static boolean sendWearBloodTestData(Integer count, long startTime, List<BloodTest> list) {
    // DataMap
    try {
        if (googleApiClient != null && !googleApiClient.isConnected() && !googleApiClient.isConnecting()) {
            googleApiClient.connect();
        }
        if (googleApiClient != null) {
            BloodTest last = list != null && list.size() > 0 ? list.get(0) : BloodTest.last();
            if (last != null) {
                Log.d(TAG, "sendWearBloodTestData last.timestamp:" + JoH.dateTimeText(last.timestamp));
            } else {
                Log.d(TAG, "sendWearBloodTestData no BloodTest exist");
                return true;
            }
            List<BloodTest> graph;
            if (list != null)
                graph = list;
            else if (startTime == 0)
                graph = BloodTest.last(count);
            else
                graph = BloodTest.latestForGraph(count, startTime);
            if (!graph.isEmpty()) {
                Log.d(TAG, "sendWearBloodTestData graph size=" + graph.size());
                final ArrayList<DataMap> dataMaps = new ArrayList<>(graph.size());
                DataMap entries = dataMap(last);
                for (BloodTest data : graph) {
                    dataMaps.add(dataMap(data));
                }
                Log.d(TAG, "sendWearBloodTestData entries=" + entries);
                // MOST IMPORTANT LINE FOR TIMESTAMP
                entries.putLong("time", new Date().getTime());
                entries.putDataMapArrayList("entries", dataMaps);
                new SendToDataLayerThread(WEARABLE_BLOODTEST_DATA_PATH, googleApiClient).executeOnExecutor(xdrip.executor, entries);
            } else
                Log.d(TAG, "sendWearBloodTestData BloodTest count = 0");
        } else {
            Log.e(TAG, "sendWearBloodTestData No connection to wearable available for send BloodTest!");
            return false;
        }
    } catch (NullPointerException e) {
        Log.e(TAG, "Nullpointer exception in sendWearBloodTestData: " + e);
        return false;
    }
    return true;
}
Also used : BloodTest(com.eveningoutpost.dexdrip.Models.BloodTest) ArrayList(java.util.ArrayList) Date(java.util.Date) DataMap(com.google.android.gms.wearable.DataMap)

Aggregations

BloodTest (com.eveningoutpost.dexdrip.Models.BloodTest)20 ArrayList (java.util.ArrayList)10 BgReading (com.eveningoutpost.dexdrip.Models.BgReading)6 Calibration (com.eveningoutpost.dexdrip.Models.Calibration)6 Treatments (com.eveningoutpost.dexdrip.Models.Treatments)6 DataMap (com.google.android.gms.wearable.DataMap)6 Date (java.util.Date)6 ResponseBody (com.squareup.okhttp.ResponseBody)4 IOException (java.io.IOException)4 URISyntaxException (java.net.URISyntaxException)4 JSONArray (org.json.JSONArray)4 JSONException (org.json.JSONException)4 AlertDialog (android.app.AlertDialog)2 PendingIntent (android.app.PendingIntent)2 DialogInterface (android.content.DialogInterface)2 Intent (android.content.Intent)2 Paint (android.graphics.Paint)2 Point (android.graphics.Point)2 RecognizerIntent (android.speech.RecognizerIntent)2 ListAdapter (android.widget.ListAdapter)2