use of com.eveningoutpost.dexdrip.Models.LibreBlock in project xDrip by NightscoutFoundation.
the class LibreTrendUtil method getData.
public List<LibreTrendPoint> getData(long startTimestamp, long endTimestamp, boolean calculate_factor) {
Log.i(TAG, "getData called startTimestamp = " + JoH.dateTimeText(startTimestamp) + " endTimestamp = " + JoH.dateTimeText(endTimestamp) + " Size of array is " + m_points.size() + " this = " + this + " m_libreTrendLatest.timestamp " + JoH.dateTimeText(m_libreTrendLatest.timestamp));
long startTime = Math.max(startTimestamp, m_libreTrendLatest.timestamp);
// The extra 1 is to make sure we don't read the last packet again and again.
List<LibreBlock> latestBlocks = LibreBlock.getForTrend(startTime + 1, endTimestamp);
Log.i(TAG, "Size of latestBlocks is " + latestBlocks.size());
if (latestBlocks.size() > 0) {
Log.i(TAG, "Last packet timestamp is " + latestBlocks.get(latestBlocks.size() - 1).timestamp);
}
if (calculate_factor) {
CalculateFactor(latestBlocks);
}
// Go over all blocks from the earlier to the latest, and fill the data.
for (LibreBlock libreBlock : latestBlocks) {
AddLibreblock(libreBlock);
}
if (debug_per_minute) {
Log.i(TAG, "Here are the points that we have");
for (int i = 0; i < MAX_POINTS; i++) {
if (m_points.get(i).rawSensorValue != 0) {
if (i != m_points.get(i).sensorTime) {
Log.i(TAG, "Error in index i = " + i + " sensorTime = " + m_points.get(i).sensorTime);
}
// Only print last 60 minutes.
if (m_libreTrendLatest.id - i < 60) {
Log.i(TAG, "" + i + " " + m_points.get(i).rawSensorValue);
}
}
}
}
return m_points;
}
use of com.eveningoutpost.dexdrip.Models.LibreBlock in project xDrip-plus by jamorham.
the class LibreTrendGraph method setupCharts.
public void setupCharts() {
final TextView trendView = (TextView) findViewById(R.id.textLibreHeader);
chart = (LineChartView) findViewById(R.id.libre_chart);
List<Line> lines = new ArrayList<Line>();
List<PointValue> lineValues = new ArrayList<PointValue>();
final float conversion_factor_mmol = (float) (doMgdl ? 1 : Constants.MGDL_TO_MMOLL);
LibreBlock libreBlock = LibreBlock.getLatestForTrend();
if (libreBlock == null) {
trendView.setText("No libre data to display");
setupEmptyCharts();
return;
}
String time = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(new Date((long) libreBlock.timestamp));
ArrayList<Float> bg_data = getLatestBgForXMinutes(MINUTES_TO_DISPLAY);
if (bg_data == null) {
trendView.setText("Error displaying data for " + time);
setupEmptyCharts();
return;
}
trendView.setText("Scan from " + time);
float min = 1000;
float max = 0;
int i = 0;
for (float bg : bg_data) {
if (bg <= 0) {
i++;
continue;
}
if (min > bg) {
min = bg;
}
if (max < bg) {
max = bg;
}
lineValues.add(new PointValue(-i, bg * conversion_factor_mmol));
i++;
}
Line trendLine = new Line(lineValues);
trendLine.setColor(ChartUtils.COLOR_RED);
trendLine.setHasLines(false);
trendLine.setHasPoints(true);
trendLine.setPointRadius(3);
lines.add(trendLine);
final int MIN_GRAPH = 20;
if (max - min < MIN_GRAPH) {
// On relative flat trend the graph can look very noise althouth with the right resolution it is not that way.
// I will add two dummy invisible points that will cause the graph to look with bigger Y range.
float average = (max + min) / 2;
List<PointValue> dummyPointValues = new ArrayList<PointValue>();
Line dummyPointLine = new Line(dummyPointValues);
dummyPointValues.add(new PointValue(0, (average - MIN_GRAPH / 2) * conversion_factor_mmol));
dummyPointValues.add(new PointValue(0, (average + MIN_GRAPH / 2) * conversion_factor_mmol));
dummyPointLine.setColor(ChartUtils.COLOR_RED);
dummyPointLine.setHasLines(false);
dummyPointLine.setHasPoints(false);
lines.add(dummyPointLine);
}
Axis axisX = new Axis();
Axis axisY = new Axis().setHasLines(true);
axisX.setTextSize(16);
axisY.setTextSize(16);
axisX.setName("Time from last scan");
axisY.setName("Glucose " + (doMgdl ? "mg/dl" : "mmol/l"));
data = new LineChartData(lines);
data.setAxisXBottom(axisX);
data.setAxisYLeft(axisY);
chart.setLineChartData(data);
}
use of com.eveningoutpost.dexdrip.Models.LibreBlock in project xDrip-plus by jamorham.
the class LibreTrendUtil method getData.
public List<LibreTrendPoint> getData(long startTimestamp, long endTimestamp, boolean calculate_factor) {
Log.i(TAG, "getData called startTimestamp = " + JoH.dateTimeText(startTimestamp) + " endTimestamp = " + JoH.dateTimeText(endTimestamp) + " Size of array is " + m_points.size() + " this = " + this + " m_libreTrendLatest.timestamp " + JoH.dateTimeText(m_libreTrendLatest.timestamp));
long startTime = Math.max(startTimestamp, m_libreTrendLatest.timestamp);
// The extra 1 is to make sure we don't read the last packet again and again.
List<LibreBlock> latestBlocks = LibreBlock.getForTrend(startTime + 1, endTimestamp);
Log.i(TAG, "Size of latestBlocks is " + latestBlocks.size());
if (latestBlocks.size() > 0) {
Log.i(TAG, "Last packet timestamp is " + latestBlocks.get(latestBlocks.size() - 1).timestamp);
}
if (calculate_factor) {
CalculateFactor(latestBlocks);
}
// Go over all blocks from the earlier to the latest, and fill the data.
for (LibreBlock libreBlock : latestBlocks) {
AddLibreblock(libreBlock);
}
if (debug_per_minute) {
Log.i(TAG, "Here are the points that we have");
for (int i = 0; i < MAX_POINTS; i++) {
if (m_points.get(i).rawSensorValue != 0) {
if (i != m_points.get(i).sensorTime) {
Log.i(TAG, "Error in index i = " + i + " sensorTime = " + m_points.get(i).sensorTime);
}
// Only print last 60 minutes.
if (m_libreTrendLatest.id - i < 60) {
Log.i(TAG, "" + i + " " + m_points.get(i).rawSensorValue);
}
}
}
}
return m_points;
}
use of com.eveningoutpost.dexdrip.Models.LibreBlock 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, List<TransmitterData> transmittersData, List<LibreBlock> libreBlock) {
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, "REST - 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);
}
Log.i(TAG, "REST - Finshed upload of mbg");
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);
}
DBCollection libreCollection = db.getCollection("libre");
for (LibreBlock libreBlockEntry : libreBlock) {
Log.d(TAG, "uploading new item to mongo");
// Checksum might be wrong, for libre 2 or libre us 14 days.
boolean ChecksumOk = LibreUtils.verify(libreBlockEntry.blockbytes);
// make db object
BasicDBObject testData = new BasicDBObject();
testData.put("SensorId", PersistentStore.getString("LibreSN"));
testData.put("CaptureDateTime", libreBlockEntry.timestamp);
testData.put("BlockBytes", Base64.encodeToString(libreBlockEntry.blockbytes, Base64.NO_WRAP));
if (libreBlockEntry.patchUid != null && libreBlockEntry.patchUid.length != 0) {
testData.put("patchUid", Base64.encodeToString(libreBlockEntry.patchUid, Base64.NO_WRAP));
}
if (libreBlockEntry.patchInfo != null && libreBlockEntry.patchInfo.length != 0) {
testData.put("patchInfo", Base64.encodeToString(libreBlockEntry.patchInfo, Base64.NO_WRAP));
}
testData.put("ChecksumOk", ChecksumOk ? 1 : 0);
testData.put("Uploaded", 1);
testData.put("UploaderBatteryLife", getBatteryLevel());
testData.put("DebugInfo", android.os.Build.MODEL + " " + new Date(libreBlockEntry.timestamp).toLocaleString());
try {
testData.put("TomatoBatteryLife", Integer.parseInt(PersistentStore.getString("Tomatobattery")));
} catch (NumberFormatException e) {
Log.e(TAG, "Error reading battery daya" + PersistentStore.getString("Tomatobattery"));
}
testData.put("FwVersion", PersistentStore.getString("TomatoFirmware"));
testData.put("HwVersion", PersistentStore.getString("TomatoHArdware"));
WriteResult wr = libreCollection.insert(testData, WriteConcern.ACKNOWLEDGED);
Log.d(TAG, "uploaded libreblock data with " + new Date(libreBlockEntry.timestamp).toLocaleString() + " wr = " + wr);
}
// 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);
if (treatment.insulinJSON != null) {
record.put("insulinInjections", treatment.insulinJSON);
}
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;
}
use of com.eveningoutpost.dexdrip.Models.LibreBlock in project xDrip-plus by jamorham.
the class LibreWifiReader method readData.
private void readData() {
// Start very simply by getting only one object and using it.
Log.e(TAG, "readData called");
Long LastReportedTime = 0L;
// TODO change that to work based on readings as well ???
// Allow some packets from the future.
LibreBlock libreBlock = LibreBlock.getLatestForTrend(0L, JoH.tsl() + 5 * 60000);
if (libreBlock != null) {
LastReportedTime = libreBlock.timestamp;
Log.e(TAG, "LastReportedTime = " + JoH.dateTimeText(LastReportedTime));
// jamorham fix to avoid going twice to network when we just got a packet
if ((new Date().getTime() - LastReportedTime) < Constants.MINUTE_IN_MS - 2000) {
Log.d(TAG, "Already have a recent packet - returning");
if (JoH.ratelimit("deferred-msg", 60)) {
statusLog(" Deferred", "Already have recent reading");
}
return;
} else {
statusLog(" Deferred", "");
}
}
String recieversIpAddresses;
// This is the same ip location as for the wixelreader.
if (!WixelReader.IsConfigured()) {
Log.e(TAG, "LibreWifiReader not configured");
return;
}
if ((DexCollectionType.getDexCollectionType() == DexCollectionType.Mock) && Home.get_engineering_mode()) {
recieversIpAddresses = "fake://FAKE_DATA";
} else {
recieversIpAddresses = Pref.getString("wifi_recievers_addresses", "");
}
int packetsToRead = isLibre2() ? 5 : 1;
Log.d(TAG, "reading " + packetsToRead + " packets");
LibreWifiData[] LibreWifiDataArr = Read(recieversIpAddresses, packetsToRead);
Log.d(TAG, "After reading ..." + LibreWifiDataArr);
if (LibreWifiDataArr == null || LibreWifiDataArr.length == 0) {
return;
}
Log.d(TAG, "After verification ... size = " + LibreWifiDataArr.length);
// Last in the array is the most updated reading we have.
for (LibreWifiData LastReading : LibreWifiDataArr) {
// Last in the array is the most updated reading we have.
// TransmitterRawData LastReading = LastReadingArr[LastReadingArr.length -1];
// if (LastReading.CaptureDateTime > LastReportedReading + 5000) {
// Make sure we do not report packets from the far future...
Log.d(TAG, "checking packet from " + JoH.dateTimeText(LastReading.CaptureDateTime));
if ((LastReading.CaptureDateTime > LastReportedTime + Constants.MINUTE_IN_MS - 5000) && LastReading.CaptureDateTime < new Date().getTime() + 2 * Constants.MINUTE_IN_MS) {
// We have a real new reading...
Log.d(TAG, "will call with packet from " + JoH.dateTimeText(LastReading.CaptureDateTime));
byte[] data = Base64.decode(LastReading.BlockBytes, Base64.DEFAULT);
byte[] patchUid = null;
if (LastReading.patchUid != null && (!LastReading.patchUid.isEmpty())) {
patchUid = Base64.decode(LastReading.patchUid, Base64.DEFAULT);
}
byte[] patchInfo = null;
if (LastReading.patchInfo != null && (!LastReading.patchInfo.isEmpty())) {
patchInfo = Base64.decode(LastReading.patchInfo, Base64.DEFAULT);
}
if (data.length == 46) {
// This is the libre 2 case
LibreBluetooth.SendData(data, LastReading.CaptureDateTime);
LastReportedTime = LastReading.CaptureDateTime;
} else {
// This is the libre 1 case
boolean checksum_ok = NFCReaderX.HandleGoodReading(LastReading.SensorId, data, LastReading.CaptureDateTime, false, patchUid, patchInfo);
if (checksum_ok) {
Log.d(TAG, "checksum ok updating LastReportedTime to " + JoH.dateTimeText(LastReading.CaptureDateTime));
// TODO use battery, and other interesting data.
LastReportedTime = LastReading.CaptureDateTime;
PersistentStore.setString("Tomatobattery", Integer.toString(LastReading.TomatoBatteryLife));
Pref.setInt("bridge_battery", LastReading.TomatoBatteryLife);
PersistentStore.setString("TomatoHArdware", LastReading.HwVersion);
PersistentStore.setString("TomatoFirmware", LastReading.FwVersion);
Log.i(TAG, "LastReading.SensorId " + LastReading.SensorId);
PersistentStore.setString("LibreSN", LastReading.SensorId);
if (SensorSanity.checkLibreSensorChangeIfEnabled(LastReading.SensorId)) {
Log.e(TAG, "Problem with Libre Serial Number - not processing");
return;
}
} else {
Log.e(TAG, "Recieved a pacjet with bad checksum");
}
}
}
}
}
Aggregations