Search in sources :

Example 6 with Treatments

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

the class Home method processAndApproveTreatment.

private void processAndApproveTreatment() {
    // preserve globals before threading off
    final double myglucosenumber = thisglucosenumber;
    double mytimeoffset = thistimeoffset;
    // TODO Handle BG Tests here also
    if (watchkeypad) {
        // calculate absolute offset
        long treatment_timestamp = watchkeypad_timestamp - (long) mytimeoffset;
        mytimeoffset = JoH.tsl() - treatment_timestamp;
        Log.d(TAG, "Watch Keypad timestamp is: " + JoH.dateTimeText(treatment_timestamp) + " Original offset: " + JoH.qs(thistimeoffset) + " New: " + JoH.qs(mytimeoffset));
        if ((mytimeoffset > (DAY_IN_MS * 3)) || (mytimeoffset < -HOUR_IN_MS * 3)) {
            Log.e(TAG, "Treatment timestamp out of range: " + mytimeoffset);
            JoH.static_toast_long("Treatment time wrong");
            WatchUpdaterService.sendWearLocalToast("Treatment error", Toast.LENGTH_LONG);
        } else {
            JoH.static_toast_long("Treatment processed");
            WatchUpdaterService.sendWearLocalToast("Treatment processed", Toast.LENGTH_LONG);
            long time = Treatments.getTimeStampWithOffset(mytimeoffset);
            // sanity check timestamp
            final Treatments exists = Treatments.byTimestamp(time);
            if (exists == null) {
                Log.d(TAG, "processAndApproveTreatment create watchkeypad Treatment carbs=" + thiscarbsnumber + " insulin=" + thisinsulinnumber + " timestamp=" + JoH.dateTimeText(time) + " uuid=" + thisuuid);
                Treatments.create(thiscarbsnumber, thisinsulinnumber, time, thisuuid);
            } else {
                Log.d(TAG, "processAndApproveTreatment Treatment already exists carbs=" + thiscarbsnumber + " insulin=" + thisinsulinnumber + " timestamp=" + JoH.dateTimeText(time));
            }
        }
    } else {
        WatchUpdaterService.sendWearToast("Treatment processed", Toast.LENGTH_LONG);
        Treatments.create(thiscarbsnumber, thisinsulinnumber, Treatments.getTimeStampWithOffset(mytimeoffset));
    }
    hideAllTreatmentButtons();
    if (hideTreatmentButtonsIfAllDone()) {
        updateCurrentBgInfo("approve button");
    }
    if (watchkeypad) {
        if (myglucosenumber > 0) {
            if ((mytimeoffset > (DAY_IN_MS * 3)) || (mytimeoffset < -HOUR_IN_MS * 3)) {
                Log.e(TAG, "Treatment bloodtest timestamp out of range: " + mytimeoffset);
            } else {
                BloodTest.createFromCal(myglucosenumber, mytimeoffset, "Manual Entry", thisuuid);
            }
        }
        watchkeypad = false;
        watchkeypadset = false;
        watchkeypad_timestamp = -1;
    } else
        processCalibrationNoUI(myglucosenumber, mytimeoffset);
    staticRefreshBGCharts();
}
Also used : Treatments(com.eveningoutpost.dexdrip.Models.Treatments)

Example 7 with Treatments

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

the class NightscoutUploader method doMongoUpload.

private boolean doMongoUpload(SharedPreferences prefs, List<BgReading> glucoseDataSets, List<Calibration> meterRecords, List<Calibration> calRecords) {
    final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US);
    format.setTimeZone(TimeZone.getDefault());
    final String dbURI = prefs.getString("cloud_storage_mongodb_uri", null);
    if (dbURI != null) {
        try {
            final URI uri = new URI(dbURI.trim());
            if ((uri.getHost().startsWith("192.168.")) && prefs.getBoolean("skip_lan_uploads_when_no_lan", true) && (!JoH.isLANConnected())) {
                Log.d(TAG, "Skipping mongo upload to: " + dbURI + " due to no LAN connection");
                return false;
            }
        } catch (URISyntaxException e) {
            UserError.Log.e(TAG, "Invalid mongo URI: " + e);
        }
    }
    final String collectionName = prefs.getString("cloud_storage_mongodb_collection", null);
    final String dsCollectionName = prefs.getString("cloud_storage_mongodb_device_status_collection", "devicestatus");
    if (dbURI != null && collectionName != null) {
        try {
            // connect to db
            MongoClientURI uri = new MongoClientURI(dbURI.trim() + "?socketTimeoutMS=180000");
            MongoClient client = new MongoClient(uri);
            // get db
            DB db = client.getDB(uri.getDatabase());
            // get collection
            DBCollection dexcomData = db.getCollection(collectionName.trim());
            try {
                Log.i(TAG, "The number of EGV records being sent to MongoDB is " + glucoseDataSets.size());
                for (BgReading record : glucoseDataSets) {
                    // make db object
                    BasicDBObject testData = new BasicDBObject();
                    testData.put("device", "xDrip-" + prefs.getString("dex_collection_method", "BluetoothWixel"));
                    if (record != null) {
                        // KS
                        testData.put("date", record.timestamp);
                        testData.put("dateString", format.format(record.timestamp));
                        testData.put("sgv", Math.round(record.calculated_value));
                        testData.put("direction", record.slopeName());
                        testData.put("type", "sgv");
                        testData.put("filtered", record.ageAdjustedFiltered() * 1000);
                        testData.put("unfiltered", record.usedRaw() * 1000);
                        testData.put("rssi", 100);
                        testData.put("noise", record.noiseValue());
                        dexcomData.insert(testData, WriteConcern.UNACKNOWLEDGED);
                    } else
                        Log.e(TAG, "MongoDB BG record is null.");
                }
                Log.i(TAG, "The number of MBG records being sent to MongoDB is " + meterRecords.size());
                for (Calibration meterRecord : meterRecords) {
                    // make db object
                    BasicDBObject testData = new BasicDBObject();
                    testData.put("device", "xDrip-" + prefs.getString("dex_collection_method", "BluetoothWixel"));
                    testData.put("type", "mbg");
                    testData.put("date", meterRecord.timestamp);
                    testData.put("dateString", format.format(meterRecord.timestamp));
                    testData.put("mbg", meterRecord.bg);
                    dexcomData.insert(testData, WriteConcern.UNACKNOWLEDGED);
                }
                for (Calibration calRecord : calRecords) {
                    // do not upload undefined slopes
                    if (calRecord.slope == 0d)
                        break;
                    // make db object
                    BasicDBObject testData = new BasicDBObject();
                    testData.put("device", "xDrip-" + prefs.getString("dex_collection_method", "BluetoothWixel"));
                    testData.put("date", calRecord.timestamp);
                    testData.put("dateString", format.format(calRecord.timestamp));
                    if (calRecord.check_in) {
                        testData.put("slope", (calRecord.first_slope));
                        testData.put("intercept", ((calRecord.first_intercept)));
                        testData.put("scale", calRecord.first_scale);
                    } else {
                        testData.put("slope", (1000 / calRecord.slope));
                        testData.put("intercept", ((calRecord.intercept * -1000) / (calRecord.slope)));
                        testData.put("scale", 1);
                    }
                    testData.put("type", "cal");
                    dexcomData.insert(testData, WriteConcern.UNACKNOWLEDGED);
                }
                // TODO: quick port from original code, revisit before release
                DBCollection dsCollection = db.getCollection(dsCollectionName);
                BasicDBObject devicestatus = new BasicDBObject();
                devicestatus.put("uploaderBattery", getBatteryLevel());
                devicestatus.put("created_at", format.format(System.currentTimeMillis()));
                dsCollection.insert(devicestatus, WriteConcern.UNACKNOWLEDGED);
                // treatments mongo sync using unified queue
                Log.d(TAG, "Starting treatments mongo direct");
                final long THIS_QUEUE = UploaderQueue.MONGO_DIRECT;
                final DBCollection treatmentDb = db.getCollection("treatments");
                final List<UploaderQueue> tups = UploaderQueue.getPendingbyType(Treatments.class.getSimpleName(), THIS_QUEUE);
                if (tups != null) {
                    for (UploaderQueue up : tups) {
                        if ((up.action.equals("insert") || (up.action.equals("update")))) {
                            Treatments treatment = Treatments.byid(up.reference_id);
                            if (treatment != null) {
                                BasicDBObject record = new BasicDBObject();
                                record.put("timestamp", treatment.timestamp);
                                record.put("eventType", treatment.eventType);
                                record.put("enteredBy", treatment.enteredBy);
                                if (treatment.notes != null)
                                    record.put("notes", treatment.notes);
                                record.put("uuid", treatment.uuid);
                                record.put("carbs", treatment.carbs);
                                record.put("insulin", treatment.insulin);
                                record.put("created_at", treatment.created_at);
                                final BasicDBObject searchQuery = new BasicDBObject().append("uuid", treatment.uuid);
                                // treatmentDb.insert(record, WriteConcern.UNACKNOWLEDGED);
                                Log.d(TAG, "Sending upsert for: " + treatment.toJSON());
                                treatmentDb.update(searchQuery, record, true, false);
                            } else {
                                Log.d(TAG, "Got null for treatment id: " + up.reference_id);
                            }
                            up.completed(THIS_QUEUE);
                        } else if (up.action.equals("delete")) {
                            if (up.reference_uuid != null) {
                                Log.d(TAG, "Processing treatment delete mongo sync for: " + up.reference_uuid);
                                final BasicDBObject searchQuery = new BasicDBObject().append("uuid", up.reference_uuid);
                                Log.d(TAG, treatmentDb.remove(searchQuery, WriteConcern.UNACKNOWLEDGED).toString());
                            }
                            up.completed(THIS_QUEUE);
                        } else {
                            Log.e(TAG, "Unsupported operation type for treatment: " + up.action);
                        }
                    }
                    Log.d(TAG, "Processed " + tups.size() + " Treatment mongo direct upload records");
                }
                client.close();
                failurecount = 0;
                return true;
            } catch (Exception e) {
                Log.e(TAG, "Unable to upload data to mongo " + e.getMessage());
                failurecount++;
                if (failurecount > 4) {
                    Home.toaststaticnext("Mongo " + failurecount + " up fails: " + e.getMessage().substring(0, 51));
                }
            } finally {
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Unable to upload data to mongo " + e.getMessage());
        }
    }
    return false;
}
Also used : MongoClientURI(com.mongodb.MongoClientURI) URISyntaxException(java.net.URISyntaxException) Calibration(com.eveningoutpost.dexdrip.Models.Calibration) URI(java.net.URI) MongoClientURI(com.mongodb.MongoClientURI) URISyntaxException(java.net.URISyntaxException) JSONException(org.json.JSONException) IOException(java.io.IOException) MongoClient(com.mongodb.MongoClient) DBCollection(com.mongodb.DBCollection) BasicDBObject(com.mongodb.BasicDBObject) BgReading(com.eveningoutpost.dexdrip.Models.BgReading) Treatments(com.eveningoutpost.dexdrip.Models.Treatments) SimpleDateFormat(java.text.SimpleDateFormat) DB(com.mongodb.DB)

Example 8 with Treatments

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

the class NightscoutUploader method doRESTtreatmentDownload.

private synchronized boolean doRESTtreatmentDownload(SharedPreferences prefs) {
    final String baseURLSettings = prefs.getString("cloud_storage_api_base", "");
    final ArrayList<String> baseURIs = new ArrayList<>();
    boolean new_data = false;
    Log.d(TAG, "doRESTtreatmentDownload() starting run");
    try {
        for (String baseURLSetting : baseURLSettings.split(" ")) {
            String baseURL = baseURLSetting.trim();
            if (baseURL.isEmpty())
                continue;
            baseURIs.add(baseURL + (baseURL.endsWith("/") ? "" : "/"));
        }
    } catch (Exception e) {
        Log.e(TAG, "Unable to process API Base URL: " + e);
        return false;
    }
    // process a list of base uris
    for (String baseURI : baseURIs) {
        try {
            int apiVersion = 0;
            URI uri = new URI(baseURI);
            if ((uri.getHost().startsWith("192.168.")) && prefs.getBoolean("skip_lan_uploads_when_no_lan", true) && (!JoH.isLANConnected())) {
                Log.d(TAG, "Skipping Nighscout download from: " + uri.getHost() + " due to no LAN connection");
                continue;
            }
            if (uri.getPath().endsWith("/v1/"))
                apiVersion = 1;
            String baseURL;
            String secret = uri.getUserInfo();
            if ((secret == null || secret.isEmpty()) && apiVersion == 0) {
                baseURL = baseURI;
            } else if ((secret == null || secret.isEmpty())) {
                throw new Exception("Starting with API v1, a pass phase is required");
            } else if (apiVersion > 0) {
                baseURL = baseURI.replaceFirst("//[^@]+@", "//");
            } else {
                throw new Exception("Unexpected baseURI: " + baseURI);
            }
            final Retrofit retrofit = new Retrofit.Builder().baseUrl(baseURL).client(client).build();
            final NightscoutService nightscoutService = retrofit.create(NightscoutService.class);
            final String checkurl = retrofit.baseUrl().url().toString();
            if (!isNightscoutCompatible(checkurl)) {
                Log.e(TAG, "Nightscout version: " + getNightscoutVersion(checkurl) + " on " + checkurl + " is not compatible with the Rest-API download feature!");
                continue;
            }
            if (apiVersion == 1) {
                final String hashedSecret = Hashing.sha1().hashBytes(secret.getBytes(Charsets.UTF_8)).toString();
                final Response<ResponseBody> r;
                if (hashedSecret != null) {
                    // update status if needed
                    doStatusUpdate(nightscoutService, retrofit.baseUrl().url().toString(), hashedSecret);
                    // per uri marker
                    final String LAST_MODIFIED_KEY = LAST_SUCCESS_TREATMENT_DOWNLOAD + CipherUtils.getMD5(uri.toString());
                    String last_modified_string = PersistentStore.getString(LAST_MODIFIED_KEY);
                    if (last_modified_string.equals(""))
                        last_modified_string = JoH.getRFC822String(0);
                    final long request_start = JoH.tsl();
                    r = nightscoutService.downloadTreatments(hashedSecret, last_modified_string).execute();
                    if ((r != null) && (r.raw().networkResponse().code() == HttpURLConnection.HTTP_NOT_MODIFIED)) {
                        Log.d(TAG, "Treatments on " + uri.getHost() + ":" + uri.getPort() + " not modified since: " + last_modified_string);
                        // skip further processing of this url
                        continue;
                    }
                    if ((r != null) && (r.isSuccess())) {
                        last_modified_string = r.raw().header("Last-Modified", JoH.getRFC822String(request_start));
                        final String this_etag = r.raw().header("Etag", "");
                        if (this_etag.length() > 0) {
                            // older versions of nightscout don't support if-modified-since so check the etag for duplication
                            if (this_etag.equals(PersistentStore.getString(ETAG + LAST_MODIFIED_KEY))) {
                                Log.d(TAG, "Skipping Treatments on " + uri.getHost() + ":" + uri.getPort() + " due to etag duplicate: " + this_etag);
                                continue;
                            }
                            PersistentStore.setString(ETAG + LAST_MODIFIED_KEY, this_etag);
                        }
                        final String response = r.body().string();
                        if (d)
                            Log.d(TAG, "Response: " + response);
                        final JSONArray jsonArray = new JSONArray(response);
                        for (int i = 0; i < jsonArray.length(); i++) {
                            final JSONObject tr = (JSONObject) jsonArray.get(i);
                            final String etype = tr.has("eventType") ? tr.getString("eventType") : "<null>";
                            // TODO if we are using upsert then we should favour _id over uuid!?
                            final String uuid = (tr.has("uuid") && (tr.getString("uuid") != null)) ? tr.getString("uuid") : UUID.nameUUIDFromBytes(tr.getString("_id").getBytes("UTF-8")).toString();
                            final String nightscout_id = (tr.getString("_id") == null) ? uuid : tr.getString("_id");
                            if (bad_uuids.contains(nightscout_id)) {
                                Log.d(TAG, "Skipping previously baulked uuid: " + nightscout_id);
                                continue;
                            }
                            if (d)
                                Log.d(TAG, "event: " + etype + "_id: " + nightscout_id + " uuid:" + uuid);
                            boolean from_xdrip = false;
                            try {
                                if (tr.getString("enteredBy").startsWith(Treatments.XDRIP_TAG)) {
                                    from_xdrip = true;
                                    if (d)
                                        Log.d(TAG, "This record came from xDrip");
                                }
                            } catch (JSONException e) {
                            // 
                            }
                            // extract blood test data if present
                            try {
                                if (!from_xdrip) {
                                    if (tr.getString("glucoseType").equals("Finger")) {
                                        if (bad_bloodtest_uuids.contains(nightscout_id)) {
                                            Log.d(TAG, "Skipping baulked bloodtest nightscout id: " + nightscout_id);
                                            continue;
                                        }
                                        final BloodTest existing = BloodTest.byUUID(uuid);
                                        if (existing == null) {
                                            final long timestamp = DateUtil.tolerantFromISODateString(tr.getString("created_at")).getTime();
                                            double mgdl = JoH.tolerantParseDouble(tr.getString("glucose"));
                                            if (tr.getString("units").equals("mmol"))
                                                mgdl = mgdl * Constants.MMOLL_TO_MGDL;
                                            final BloodTest bt = BloodTest.create(timestamp, mgdl, tr.getString("enteredBy") + " " + VIA_NIGHTSCOUT_TAG);
                                            if (bt != null) {
                                                // override random uuid with nightscout one
                                                bt.uuid = uuid;
                                                bt.saveit();
                                                new_data = true;
                                                Log.ueh(TAG, "Received new Bloodtest data from Nightscout: " + BgGraphBuilder.unitized_string_with_units_static(mgdl) + " @ " + JoH.dateTimeText(timestamp));
                                            } else {
                                                Log.d(TAG, "Error creating bloodtest record: " + mgdl + " mgdl " + tr.toString());
                                                bad_bloodtest_uuids.add(nightscout_id);
                                            }
                                        } else {
                                            if (d)
                                                Log.d(TAG, "Already a bloodtest with uuid: " + uuid);
                                        }
                                    } else {
                                        if (JoH.quietratelimit("blood-test-type-finger", 2)) {
                                            Log.e(TAG, "Cannot use bloodtest which is not type Finger: " + tr.getString("glucoseType"));
                                        }
                                    }
                                }
                            } catch (JSONException e) {
                            // Log.d(TAG, "json processing: " + e);
                            }
                            // extract treatment data if present
                            double carbs = 0;
                            double insulin = 0;
                            String notes = null;
                            try {
                                carbs = tr.getDouble("carbs");
                            } catch (JSONException e) {
                            // Log.d(TAG, "json processing: " + e);
                            }
                            try {
                                insulin = tr.getDouble("insulin");
                            } catch (JSONException e) {
                            // Log.d(TAG, "json processing: " + e);
                            }
                            try {
                                notes = tr.getString("notes");
                            } catch (JSONException e) {
                            // Log.d(TAG, "json processing: " + e);
                            }
                            if ((notes != null) && ((notes.equals("AndroidAPS started") || notes.equals("null") || (notes.equals("Bolus Std")))))
                                notes = null;
                            if ((carbs > 0) || (insulin > 0) || (notes != null)) {
                                final long timestamp = DateUtil.tolerantFromISODateString(tr.getString("created_at")).getTime();
                                if (timestamp > 0) {
                                    if (d)
                                        Log.d(TAG, "Treatment: Carbs: " + carbs + " Insulin: " + insulin + " timestamp: " + timestamp);
                                    Treatments existing = Treatments.byuuid(nightscout_id);
                                    if (existing == null)
                                        existing = Treatments.byuuid(uuid);
                                    if ((existing == null) && (!from_xdrip)) {
                                        // check for close timestamp duplicates perhaps
                                        existing = Treatments.byTimestamp(timestamp, 60000);
                                        if (!((existing != null) && (JoH.roundDouble(existing.insulin, 2) == JoH.roundDouble(insulin, 2)) && (JoH.roundDouble(existing.carbs, 2) == JoH.roundDouble(carbs, 2)) && ((existing.notes == null && notes == null) || ((existing.notes != null) && existing.notes.equals(notes != null ? notes : ""))))) {
                                            Log.ueh(TAG, "New Treatment from Nightscout: Carbs: " + carbs + " Insulin: " + insulin + " timestamp: " + JoH.dateTimeText(timestamp) + ((notes != null) ? " Note: " + notes : ""));
                                            final Treatments t;
                                            if ((carbs > 0) || (insulin > 0)) {
                                                t = Treatments.create(carbs, insulin, timestamp, nightscout_id);
                                                if (notes != null)
                                                    t.notes = notes;
                                            } else {
                                                t = Treatments.create_note(notes, timestamp, -1, nightscout_id);
                                                if (t == null) {
                                                    Log.d(TAG, "Create note baulked and returned null, so skipping");
                                                    bad_uuids.add(nightscout_id);
                                                    continue;
                                                }
                                            }
                                            // t.uuid = nightscout_id; // replace with nightscout uuid
                                            try {
                                                t.enteredBy = tr.getString("enteredBy") + " " + VIA_NIGHTSCOUT_TAG;
                                            } catch (JSONException e) {
                                                t.enteredBy = VIA_NIGHTSCOUT_TAG;
                                            }
                                            t.save();
                                            // pushTreatmentSync(t, false);
                                            if (Home.get_show_wear_treatments())
                                                pushTreatmentSyncToWatch(t, true);
                                            new_data = true;
                                        } else {
                                            Log.e(TAG, "Skipping treatment as it appears identical to one we already have: " + JoH.dateTimeText(timestamp) + " " + insulin + " " + carbs + " " + notes);
                                        }
                                    } else {
                                        if (existing != null) {
                                            if (d)
                                                Log.d(TAG, "Treatment with uuid: " + uuid + " / " + nightscout_id + " already exists");
                                            if (notes == null)
                                                notes = "";
                                            if (existing.notes == null)
                                                existing.notes = "";
                                            if ((existing.carbs != carbs) || (existing.insulin != insulin) || ((existing.timestamp / Constants.SECOND_IN_MS) != (timestamp / Constants.SECOND_IN_MS)) || (!existing.notes.contains(notes))) {
                                                Log.ueh(TAG, "Treatment changes from Nightscout: " + carbs + " Insulin: " + insulin + " timestamp: " + JoH.dateTimeText(timestamp) + " " + notes + " " + " vs " + existing.carbs + " " + existing.insulin + " " + JoH.dateTimeText(existing.timestamp) + " " + existing.notes);
                                                existing.carbs = carbs;
                                                existing.insulin = insulin;
                                                existing.timestamp = timestamp;
                                                existing.created_at = DateUtil.toISOString(timestamp);
                                                if (existing.notes.length() > 0) {
                                                    existing.notes += " \u2192 " + notes;
                                                } else {
                                                    existing.notes = notes;
                                                }
                                                existing.save();
                                                if (Home.get_show_wear_treatments())
                                                    pushTreatmentSyncToWatch(existing, false);
                                                new_data = true;
                                            }
                                        } else {
                                            Log.d(TAG, "Skipping record creation as original source is xDrip");
                                        }
                                    }
                                }
                            }
                        }
                        PersistentStore.setString(LAST_MODIFIED_KEY, last_modified_string);
                        checkGzipSupport(r);
                    } else {
                        Log.d(TAG, "Failed to get treatments from: " + baseURI);
                    }
                } else {
                    Log.d(TAG, "Old api version not supported");
                }
            }
        } catch (Exception e) {
            String msg = "Unable to do REST API Download " + e + " " + e.getMessage() + " url: " + baseURI;
            handleRestFailure(msg);
        }
    }
    Log.d(TAG, "doRESTtreatmentDownload() finishing run");
    return new_data;
}
Also used : BloodTest(com.eveningoutpost.dexdrip.Models.BloodTest) ArrayList(java.util.ArrayList) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) URI(java.net.URI) MongoClientURI(com.mongodb.MongoClientURI) URISyntaxException(java.net.URISyntaxException) JSONException(org.json.JSONException) IOException(java.io.IOException) ResponseBody(com.squareup.okhttp.ResponseBody) Retrofit(retrofit.Retrofit) JSONObject(org.json.JSONObject) Treatments(com.eveningoutpost.dexdrip.Models.Treatments)

Example 9 with Treatments

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

the class NightscoutUploader method postTreatments.

private void postTreatments(NightscoutService nightscoutService, String apiSecret) throws Exception {
    Log.d(TAG, "Processing treatments for RESTAPI");
    final long THIS_QUEUE = UploaderQueue.NIGHTSCOUT_RESTAPI;
    final List<UploaderQueue> tups = UploaderQueue.getPendingbyType(Treatments.class.getSimpleName(), THIS_QUEUE);
    if (tups != null) {
        JSONArray insert_array = new JSONArray();
        JSONArray upsert_array = new JSONArray();
        for (UploaderQueue up : tups) {
            if ((up.action.equals("insert") || (up.action.equals("update")))) {
                final Treatments treatment = Treatments.byid(up.reference_id);
                if (up.action.equals("insert")) {
                    // populateV1APITreatmentEntry(insert_array, treatment);
                    // TODO always use singular upserts for now
                    populateV1APITreatmentEntry(upsert_array, treatment);
                } else if (up.action.equals("update")) {
                    populateV1APITreatmentEntry(upsert_array, treatment);
                }
            } else if (up.action.equals("delete")) {
                if (up.reference_uuid != null) {
                    if (apiSecret != null) {
                        // do we already have a nightscout style reference id
                        String this_id = up.reference_uuid.length() == 24 ? up.reference_uuid : null;
                        Response<ResponseBody> lookup = null;
                        if (this_id == null) {
                            // look up the _id to delete as we can't use find with delete action nor can we specify our own _id on submission circa nightscout 0.9.2
                            lookup = nightscoutService.findTreatmentByUUID(apiSecret, up.reference_uuid).execute();
                        }
                        // throw an exception if we failed lookup
                        if ((this_id == null) && (lookup != null) && !lookup.isSuccess()) {
                            throw new UploaderException(lookup.message(), lookup.code());
                        } else {
                            // parse the result
                            if (this_id == null) {
                                try {
                                    final String response = lookup.body().string();
                                    final JSONArray jsonArray = new JSONArray(response);
                                    // can only be one
                                    final JSONObject tr = (JSONObject) jsonArray.get(0);
                                    this_id = tr.getString("_id");
                                } catch (Exception e) {
                                    Log.e(TAG, "Got exception parsing treatment lookup response: " + e);
                                }
                            }
                            // is the id valid now?
                            if ((this_id != null) && (this_id.length() == 24)) {
                                final Response<ResponseBody> r = nightscoutService.deleteTreatment(apiSecret, this_id).execute();
                                if (!r.isSuccess()) {
                                    throw new UploaderException(r.message(), r.code());
                                } else {
                                    up.completed(THIS_QUEUE);
                                    Log.d(TAG, "Success for RESTAPI treatment delete: " + up.reference_uuid + " _id: " + this_id);
                                }
                            } else {
                                Log.wtf(TAG, "Couldn't find a reference _id for uuid: " + up.reference_uuid + " got: " + this_id);
                                // don't retry
                                up.completed(THIS_QUEUE);
                            }
                        }
                    } else {
                        Log.wtf(TAG, "Cannot delete treatments without api secret being set");
                    }
                }
            } else {
                Log.wtf(TAG, "Unsupported operation type for treatment: " + up.action);
                // don't retry it
                up.completed(THIS_QUEUE);
            }
        }
        // handle insert types
        if (insert_array.length() != 0) {
            final RequestBody body = RequestBody.create(MediaType.parse("application/json"), insert_array.toString());
            final Response<ResponseBody> r;
            if (apiSecret != null) {
                r = nightscoutService.uploadTreatments(apiSecret, body).execute();
                if (!r.isSuccess()) {
                    throw new UploaderException(r.message(), r.code());
                } else {
                    Log.d(TAG, "Success for RESTAPI treatment insert upload");
                    for (UploaderQueue up : tups) {
                        if (up.action.equals("insert")) {
                            // approve all types for this queue
                            up.completed(THIS_QUEUE);
                        }
                    }
                    checkGzipSupport(r);
                }
            } else {
                Log.wtf(TAG, "Cannot upload treatments without api secret being set");
            }
        }
        // handle upsert types
        if (upsert_array.length() != 0) {
            for (int i = 0; i < upsert_array.length(); i++) {
                JSONObject item = (JSONObject) upsert_array.get(i);
                final String match_uuid = item.getString("uuid");
                item.put("_id", uuid_to_id(match_uuid));
                final RequestBody body = RequestBody.create(MediaType.parse("application/json"), item.toString());
                final Response<ResponseBody> r;
                if (apiSecret != null) {
                    r = nightscoutService.upsertTreatments(apiSecret, body).execute();
                    if (!r.isSuccess()) {
                        throw new UploaderException(r.message(), r.code());
                    } else {
                        Log.d(TAG, "Success for RESTAPI treatment upsert upload: " + match_uuid);
                        for (UploaderQueue up : tups) {
                            if (d)
                                Log.d(TAG, "upsert: " + match_uuid + " / " + up.reference_uuid + " " + up.action + " " + up.reference_id);
                            if ((up.action.equals("update") || (up.action.equals("insert"))) && (up.reference_uuid.equals(match_uuid) || (uuid_to_id(up.reference_uuid).equals(match_uuid)))) {
                                if (d)
                                    Log.d(TAG, "upsert: matched");
                                // approve all types for this queue
                                up.completed(THIS_QUEUE);
                                break;
                            }
                        }
                        checkGzipSupport(r);
                    }
                } else {
                    Log.wtf(TAG, "Cannot upload treatments without api secret being set");
                    return;
                }
            }
            // if we got this far without exception then mark everything as completed to fix harmless erroneous queue entries
            for (UploaderQueue up : tups) {
                if (d)
                    Log.d(TAG, "Marking all items completed");
                up.completed(THIS_QUEUE);
            }
        }
    }
}
Also used : JSONArray(org.json.JSONArray) URISyntaxException(java.net.URISyntaxException) JSONException(org.json.JSONException) IOException(java.io.IOException) ResponseBody(com.squareup.okhttp.ResponseBody) Response(retrofit.Response) JSONObject(org.json.JSONObject) Treatments(com.eveningoutpost.dexdrip.Models.Treatments) RequestBody(com.squareup.okhttp.RequestBody)

Example 10 with Treatments

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

Aggregations

Treatments (com.eveningoutpost.dexdrip.Models.Treatments)26 ArrayList (java.util.ArrayList)12 BgReading (com.eveningoutpost.dexdrip.Models.BgReading)8 DataMap (com.google.android.gms.wearable.DataMap)8 Date (java.util.Date)8 BloodTest (com.eveningoutpost.dexdrip.Models.BloodTest)6 Calibration (com.eveningoutpost.dexdrip.Models.Calibration)6 IOException (java.io.IOException)6 URISyntaxException (java.net.URISyntaxException)6 JSONException (org.json.JSONException)6 MongoClientURI (com.mongodb.MongoClientURI)4 ResponseBody (com.squareup.okhttp.ResponseBody)4 URI (java.net.URI)4 JSONArray (org.json.JSONArray)4 JSONObject (org.json.JSONObject)4 PowerManager (android.os.PowerManager)2 ListAdapter (android.widget.ListAdapter)2 AddCalibration (com.eveningoutpost.dexdrip.AddCalibration)2 InfluxDBUploader (com.eveningoutpost.dexdrip.InfluxDB.InfluxDBUploader)2 Forecast (com.eveningoutpost.dexdrip.Models.Forecast)2