use of com.eveningoutpost.dexdrip.Models.BloodTest in project xDrip by NightscoutFoundation.
the class BloodTestTable method getData.
private void getData() {
UserError.Log.d(TAG, "getData");
// 3 days
final long startTime = new Date().getTime() - (60000 * 60 * 24 * 3);
final List<BloodTest> latest = BloodTest.latestForGraph(60, startTime);
ListAdapter adapter = new thisAdapter(this, latest);
this.setListAdapter(adapter);
String msg = "";
int size = 0;
if (latest != null)
size = latest.size();
if (size == 0) {
msg = getResources().getString(R.string.notify_table_size, "BloodTest", size);
JoH.static_toast(xdrip.getAppContext(), msg, Toast.LENGTH_SHORT);
}
}
use of com.eveningoutpost.dexdrip.Models.BloodTest in project xDrip by NightscoutFoundation.
the class ListenerService method getBloodTests.
public static DataMap getBloodTests(long startTime) {
BloodTest last = BloodTest.last();
if (last != null) {
Log.d(TAG, "getBloodTests last.timestamp:" + JoH.dateTimeText(last.timestamp));
}
List<BloodTest> graph = BloodTest.latestForGraph(60, startTime);
if (!graph.isEmpty()) {
Log.d(TAG, "getBloodTests graph size=" + graph.size());
final ArrayList<DataMap> dataMaps = new ArrayList<>(graph.size());
DataMap entries = dataMapForWatchface(graph.get(0));
for (BloodTest data : graph) {
dataMaps.add(dataMapForWatchface(data));
}
entries.putDataMapArrayList("entries", dataMaps);
Log.d(TAG, "getBloodTests entries=" + entries);
return entries;
} else {
Log.d(TAG, "getBloodTests no entries for startTime=" + JoH.dateTimeText(startTime));
return null;
}
}
use of com.eveningoutpost.dexdrip.Models.BloodTest in project xDrip by NightscoutFoundation.
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;
}
use of com.eveningoutpost.dexdrip.Models.BloodTest in project xDrip-plus by jamorham.
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()));
}
}
use of com.eveningoutpost.dexdrip.Models.BloodTest 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;
}
Aggregations