下面列出了com.google.gson.internal.bind.DateTypeAdapter#com.eveningoutpost.dexdrip.Models.BgReading 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static BgReading bgReadingInsertFromData(long timestamp, double sgv, double slope, boolean do_notification) {
Log.d(TAG, "bgReadingInsertFromData called timestamp = " + timestamp + " bg = " + sgv + " time =" + JoH.dateTimeText(timestamp));
final JSONObject faux_bgr = new JSONObject();
try {
faux_bgr.put("timestamp", timestamp);
faux_bgr.put("calculated_value", sgv);
faux_bgr.put("filtered_calculated_value", sgv);
faux_bgr.put("calculated_value_slope", slope);
// sanity checking???
// fake up some extra data
faux_bgr.put("raw_data", sgv);
faux_bgr.put("age_adjusted_raw_value", sgv);
faux_bgr.put("filtered_data", sgv);
faux_bgr.put("uuid", UUID.randomUUID().toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
UserError.Log.e(TAG, "bgReadingInsertFromData Got JSON exception: " + e);
return null;
}
Log.d(TAG, "Received NSEmulator SGV: " + faux_bgr);
return bgReadingInsertFromJson(faux_bgr.toString(), do_notification, true); // notify and force sensor
}
private void resendData(long since) {
Log.d(TAG, "resendData ENTER");
forceGoogleApiConnect();
final long startTime = since == 0 ? new Date().getTime() - (60000 * 60 * 24) : since;
Log.d(TAG, "resendData googleApiClient connected ENTER, sending since: " + JoH.dateTimeText(startTime));
final BgReading last_bg = BgReading.last();
if (last_bg != null) {
List<BgReading> graph_bgs = BgReading.latestForGraph(60, startTime);
BgGraphBuilder bgGraphBuilder = new BgGraphBuilder(getApplicationContext());
if (!graph_bgs.isEmpty()) {
final int battery = PowerStateReceiver.getBatteryLevel(getApplicationContext());
DataMap entries = dataMap(last_bg, mPrefs, bgGraphBuilder, battery);
final ArrayList<DataMap> dataMaps = new ArrayList<>(graph_bgs.size());
for (BgReading bg : graph_bgs) {
dataMaps.add(dataMap(bg, mPrefs, bgGraphBuilder, battery));
}
entries.putLong("time", new Date().getTime()); // MOST IMPORTANT LINE FOR TIMESTAMP
entries.putDataMapArrayList("entries", dataMaps);
if (mPrefs.getBoolean("extra_status_line", false)) {
entries.putString("extra_status_line", StatusLine.extraStatusLine());
}
new SendToDataLayerThread(WEARABLE_DATA_PATH, googleApiClient).executeOnExecutor(xdrip.executor, entries);
}
}
}
public static double getNightscoutRaw(BgReading bgReading, Calibration cal) {
double slope = 0, intercept = 0, scale = 0, filtered = 0, unfiltered = 0, nightscoutRaw = 0;
if (cal != null){
// slope/intercept/scale like uploaded to NightScout (NightScoutUploader.java)
slope = getNightscoutSlope(cal);
intercept = getNightscoutIntercept(cal);
scale = getNightscoutScale(cal);
unfiltered= bgReading.usedRaw()*1000;
filtered = bgReading.ageAdjustedFiltered()*1000;
}
//nightscoutRaw logic from https://github.com/nightscout/cgm-remote-monitor/blob/master/lib/plugins/rawbg.js#L59
if (slope != 0 && intercept != 0 && scale != 0) {
if (filtered == 0 || bgReading.calculated_value < 40) {
nightscoutRaw = scale * (unfiltered - intercept) / slope;
} else {
double ratio = scale * (filtered - intercept) / slope / bgReading.calculated_value;
nightscoutRaw = scale * (unfiltered - intercept) / slope / ratio;
}
}
return nightscoutRaw;
}
private synchronized void processNewTransmitterData(TransmitterData transmitterData, long timestamp) {
if (transmitterData == null) {
return;
}
final Sensor sensor = Sensor.currentSensor();
if (sensor == null) {
Log.i(TAG, "setSerialDataToTransmitterRawData: No Active Sensor, Data only stored in Transmitter Data");
return;
}
if (use_transmiter_pl_bluetooth && (transmitterData.raw_data == 100000)) {
Log.wtf(TAG, "Ignoring probably erroneous Transmiter_PL data: " + transmitterData.raw_data);
return;
}
//sensor.latest_battery_level = (sensor.latest_battery_level != 0) ? Math.min(sensor.latest_battery_level, transmitterData.sensor_battery_level) : transmitterData.sensor_battery_level;
sensor.latest_battery_level = transmitterData.sensor_battery_level; // allow level to go up and down
sensor.save();
last_transmitter_Data = transmitterData;
Log.d(TAG, "BgReading.create: new BG reading at " + timestamp + " with a timestamp of " + transmitterData.timestamp);
BgReading.create(transmitterData.raw_data, transmitterData.filtered_data, this, transmitterData.timestamp);
}
public void setRetryTimer() {
if (CollectionServiceStarter.isBTShare(getApplicationContext())) {
BgReading bgReading = BgReading.last();
long retry_in;
if (bgReading != null) {
retry_in = Math.min(Math.max((1000 * 30), (1000 * 60 * 5) - (new Date().getTime() - bgReading.timestamp) + (1000 * 5)), (1000 * 60 * 5));
} else {
retry_in = (1000 * 20);
}
Log.d(TAG, "Restarting in: " + (retry_in / (60 * 1000)) + " minutes");
Calendar calendar = Calendar.getInstance();
AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
if (pendingIntent != null)
alarm.cancel(pendingIntent);
long wakeTime = calendar.getTimeInMillis() + retry_in;
pendingIntent = PendingIntent.getService(this, 0, new Intent(this, this.getClass()), 0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarm.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, wakeTime, pendingIntent);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarm.setExact(AlarmManager.RTC_WAKEUP, wakeTime, pendingIntent);
} else
alarm.set(AlarmManager.RTC_WAKEUP, wakeTime, pendingIntent);
}
}
public static void newBgReading(BgReading bgReading, boolean is_follower) {
sendToPebble();
sendToWear();
sendToAmazfit();
sendToLeFun();
sendToMiBand();
sendToBlueJay();
sendToRemoteBlueJay();
Notifications.start();
uploadToShare(bgReading, is_follower);
textToSpeech(bgReading, null);
LibreBlock.UpdateBgVal(bgReading.timestamp, bgReading.calculated_value);
LockScreenWallPaper.setIfEnabled();
TidepoolEntry.newData();
}
public BgGraphBuilder(Context context, long start, long end, int numValues){
end_time = end;
start_time = start;
bgReadings = BgReading.latestForGraph( numValues, start, end);
calibrations = Calibration.latestForGraph( numValues, start, end);
this.context = context;
this.prefs = PreferenceManager.getDefaultSharedPreferences(context);
this.highMark = Double.parseDouble(prefs.getString("highValue", "170"));
this.lowMark = Double.parseDouble(prefs.getString("lowValue", "70"));
this.doMgdl = (prefs.getString("units", "mgdl").equals("mgdl"));
defaultMinY = unitized(40);
defaultMaxY = unitized(250);
pointSize = isXLargeTablet(context) ? 5 : 3;
axisTextSize = isXLargeTablet(context) ? 20 : Axis.DEFAULT_TEXT_SIZE_SP;
previewAxisTextSize = isXLargeTablet(context) ? 12 : 5;
hoursPreviewStep = isXLargeTablet(context) ? 2 : 1;
}
private void addBgReadingValues() {
final boolean show_filtered = prefs.getBoolean("show_filtered_curve", false);
for (BgReading bgReading : bgReadings) {
if (bgReading.raw_calculated != 0 && prefs.getBoolean("interpret_raw", false)) {
rawInterpretedValues.add(new PointValueExtended((float) (bgReading.timestamp / FUZZER), (float) unitized(bgReading.raw_calculated),(float) unitized(bgReading.filtered_calculated_value)));
} else if (bgReading.calculated_value >= 400) {
highValues.add(new PointValueExtended((float) (bgReading.timestamp / FUZZER), (float) unitized(400),(float) unitized(bgReading.filtered_calculated_value)));
} else if (unitized(bgReading.calculated_value) >= highMark) {
highValues.add(new PointValueExtended((float) (bgReading.timestamp / FUZZER), (float) unitized(bgReading.calculated_value), (float) unitized(bgReading.filtered_calculated_value)));
} else if (unitized(bgReading.calculated_value) >= lowMark) {
inRangeValues.add(new PointValueExtended((float) (bgReading.timestamp / FUZZER), (float) unitized(bgReading.calculated_value), (float) unitized(bgReading.filtered_calculated_value)));
} else if (bgReading.calculated_value >= 40) {
lowValues.add(new PointValueExtended((float) (bgReading.timestamp / FUZZER), (float) unitized(bgReading.calculated_value),(float) unitized(bgReading.filtered_calculated_value)));
} else if (bgReading.calculated_value > 13) {
lowValues.add(new PointValueExtended((float) (bgReading.timestamp / FUZZER), (float) unitized(40), (float) unitized(bgReading.filtered_calculated_value)));
}
if ((show_filtered) && (bgReading.filtered_calculated_value > 0) && (bgReading.filtered_calculated_value != bgReading.calculated_value)) {
filteredValues.add(new PointValueExtended((float) ((bgReading.timestamp - timeshift) / FUZZER), (float) unitized(bgReading.filtered_calculated_value)));
}
}
for (Calibration calibration : calibrations) {
calibrationValues.add(new PointValueExtended((float) (calibration.timestamp / FUZZER), (float) unitized(calibration.bg)));
}
}
@Test
public void bgReadingInsertFromDataTest() throws JSONException {
// test data courtesy of philipgo - thanks
final JSONObject json_object = new JSONObject();
json_object.put("date", 1526717691000.0);
json_object.put("sgv", 148);
json_object.put("direction", "SingleUp");
final BgReading result = NSEmulatorReceiver.bgReadingInsertFromData(json_object.getLong("date"),
json_object.getDouble("sgv"),
BgReading.slopefromName(json_object.getString("direction")),
true);
assertWithMessage("result not null").that(result).isNotNull();
assertWithMessage("direction matches").that(result.slopeName()).isEqualTo("SingleUp");
assertWithMessage("timestamp matches").that(result.timestamp).isEqualTo(1526717691000L);
assertWithMessage("sgv matches 1").that(result.calculated_value).isEqualTo(148d);
assertWithMessage("sgv matches 2").that(result.filtered_calculated_value).isEqualTo(148d);
assertWithMessage("sgv matches 3").that(result.raw_data).isEqualTo(148d);
assertWithMessage("sgv matches 4").that(result.filtered_data).isEqualTo(148d);
//System.out.println(result.toJSON(true));
//System.out.println(result.slopeName());
}
public void addListenerOnButton() {
button = (Button)findViewById(R.id.log);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText value = (EditText) findViewById(R.id.bg_value);
int intValue = Integer.parseInt(value.getText().toString());
BgReading bgReading = BgReading.create(intValue * 1000, getApplicationContext(), new Date().getTime());
Intent intent = new Intent(getApplicationContext(), Home.class);
startActivity(intent);
finish();
}
});
}
private static void process15minData(byte[] buffer, int src_offset, int min_offset, int count) {
long timestamp = JoH.tsl();
for (int i = src_offset; i < (src_offset + (count * 2)); i = i + 2) {
double val = LIBRE_MULTIPLIER * (unsignedBytesToInt(buffer[i], buffer[i + 1]) & 0xFFF);
UserError.Log.d(TAG, "Received 15 min value: " + JoH.qs(val, 4) + " for minute: " + min_offset);
final long this_timestamp = timestamp - (min_offset * Constants.MINUTE_IN_MS);
// TODO we may want to use getForPreciseTimestamp instead..
if (BgReading.readingNearTimeStamp(this_timestamp) == null) {
UserError.Log.d(TAG, "Creating a new reading at: " + JoH.dateTimeText(this_timestamp));
BgReading.create(val, val, xdrip.getAppContext(), this_timestamp, min_offset != 0);
} else {
UserError.Log.d(TAG, "Already a reading for minute offset: " + min_offset);
}
min_offset++;
}
}
private void setSerialDataToTransmitterRawData(int raw_data, int filtered_data, int sensor_battery_leve, Long CaptureTime) {
final TransmitterData transmitterData = TransmitterData.create(raw_data, filtered_data, sensor_battery_leve, CaptureTime);
if (transmitterData != null) {
final Sensor sensor = Sensor.currentSensor();
if (sensor != null) {
BgReading bgReading = BgReading.create(transmitterData.raw_data, filtered_data, null, CaptureTime);
//sensor.latest_battery_level = (sensor.latest_battery_level!=0)?Math.min(sensor.latest_battery_level, transmitterData.sensor_battery_level):transmitterData.sensor_battery_level;
sensor.latest_battery_level = transmitterData.sensor_battery_level; // don't lock it only going downwards
sensor.save();
} else {
Log.d(TAG, "No Active Sensor, Data only stored in Transmitter Data");
}
}
}
public static synchronized double getCurrentLowOccursAt() {
try {
final long last_bg_reading_timestamp = BgReading.last().timestamp;
// TODO remove any duplication by using refreshNoiseIfOlderThan()
if (low_occurs_at_processed_till_timestamp < last_bg_reading_timestamp) {
Log.d(TAG, "Recalculating lowOccursAt: " + JoH.dateTimeText((long) low_occurs_at_processed_till_timestamp) + " vs " + JoH.dateTimeText(last_bg_reading_timestamp));
// new only the last hour worth of data for this
(new BgGraphBuilder(xdrip.getAppContext(), System.currentTimeMillis() - 60 * 60 * 1000, System.currentTimeMillis() + 5 * 60 * 1000, 24, true)).addBgReadingValues(false);
} else {
Log.d(TAG, "Cached current low timestamp ok: " + JoH.dateTimeText((long) low_occurs_at_processed_till_timestamp) + " vs " + JoH.dateTimeText(last_bg_reading_timestamp));
}
} catch (Exception e) {
Log.e(TAG, "Got exception in getCurrentLowOccursAt() " + e);
}
return low_occurs_at;
}
private synchronized void processNewTransmitterData(TransmitterData transmitterData, long timestamp) {
if (transmitterData == null) {
return;
}
final Sensor sensor = Sensor.currentSensor();
if (sensor == null) {
Log.i(TAG, "setSerialDataToTransmitterRawData: No Active Sensor, Data only stored in Transmitter Data");
return;
}
if (use_transmiter_pl_bluetooth && (transmitterData.raw_data == 100000)) {
Log.wtf(TAG, "Ignoring probably erroneous Transmiter_PL data: " + transmitterData.raw_data);
return;
}
//sensor.latest_battery_level = (sensor.latest_battery_level != 0) ? Math.min(sensor.latest_battery_level, transmitterData.sensor_battery_level) : transmitterData.sensor_battery_level;
sensor.latest_battery_level = transmitterData.sensor_battery_level; // allow level to go up and down
sensor.save();
last_transmitter_Data = transmitterData;
Log.d(TAG, "BgReading.create: new BG reading at " + timestamp + " with a timestamp of " + transmitterData.timestamp);
BgReading.create(transmitterData.raw_data, transmitterData.filtered_data, this, transmitterData.timestamp);
}
public static int noReadingsBelowRange(Context context) {
Bounds bounds = new Bounds().invoke();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
boolean mgdl = "mgdl".equals(settings.getString("units", "mgdl"));
double low = Double.parseDouble(settings.getString("lowValue", "70"));
if (!mgdl) {
low *= Constants.MMOLL_TO_MGDL;
}
int count = new Select()
.from(BgReading.class)
.where("timestamp >= " + bounds.start)
.where("timestamp <= " + bounds.stop)
.where("calculated_value > " + CUTOFF)
.where("calculated_value < " + low)
.where("snyced == 0")
.count();
Log.d("DrawStats", "Low count: " + count);
return count;
}
public static void requestBGsync() {
if (token != null) {
if ((JoH.tsl() - last_sync_request) > (60 * 1000 * (5 + bg_sync_backoff))) {
last_sync_request = JoH.tsl();
final BgReading bgReading = BgReading.last();
if (JoH.pratelimit("gcm-bfr", 299)) {
GcmActivity.sendMessage("bfr", bgReading != null ? "" + bgReading.timestamp : "");
}
bg_sync_backoff++;
} else {
Log.d(TAG, "Already requested BGsync recently, backoff: " + bg_sync_backoff);
if (JoH.ratelimit("check-queue", 20)) {
queueCheckOld(xdrip.getAppContext());
}
}
} else {
Log.d(TAG, "No token for BGSync");
}
}
public static void newBgReading(BgReading bgReading, boolean is_follower) {
sendToPebble();
sendToWear();
sendToAmazfit();
sendToLeFun();
sendToMiBand();
sendToBlueJay();
sendToRemoteBlueJay();
Notifications.start();
uploadToShare(bgReading, is_follower);
textToSpeech(bgReading, null);
LibreBlock.UpdateBgVal(bgReading.timestamp, bgReading.calculated_value);
LockScreenWallPaper.setIfEnabled();
TidepoolEntry.newData();
}
public BgGraphBuilder(Context context, long start, long end, int numValues){
end_time = end;
start_time = start;
bgReadings = BgReading.latestForGraph( numValues, start, end);
calibrations = Calibration.latestForGraph( numValues, start, end);
this.context = context;
this.prefs = PreferenceManager.getDefaultSharedPreferences(context);
this.highMark = Double.parseDouble(prefs.getString("highValue", "170"));
this.lowMark = Double.parseDouble(prefs.getString("lowValue", "70"));
this.doMgdl = (prefs.getString("units", "mgdl").equals("mgdl"));
defaultMinY = unitized(40);
defaultMaxY = unitized(250);
pointSize = isXLargeTablet(context) ? 5 : 3;
axisTextSize = isXLargeTablet(context) ? 20 : Axis.DEFAULT_TEXT_SIZE_SP;
previewAxisTextSize = isXLargeTablet(context) ? 12 : 5;
hoursPreviewStep = isXLargeTablet(context) ? 2 : 1;
}
private synchronized DataMap getWearBgReadingData(int count, long last_send_time, int min_count) {
forceGoogleApiConnect();
Log.d(TAG, "getWearBgReadingData last_send_time:" + JoH.dateTimeText(last_send_time));
BgReading last_bg = BgReading.last();
if (last_bg != null) {
Log.d(TAG, "getWearBgReadingData last_bg.timestamp:" + JoH.dateTimeText(last_bg.timestamp));
}
if (last_bg != null && last_send_time <= last_bg.timestamp) {//startTime
long last_send_success = last_send_time;
Log.d(TAG, "getWearBgData last_send_time < last_bg.timestamp:" + JoH.dateTimeText(last_bg.timestamp));
final List<BgReading> graph_bgs = BgReading.latestForGraphAsc(count, last_send_time);
if (!graph_bgs.isEmpty() && graph_bgs.size() > min_count) {
//Log.d(TAG, "getWearBgData count = " + graph_bgs.size());
final DataMap entries = dataMap(last_bg);
final ArrayList<DataMap> dataMaps = new ArrayList<>(graph_bgs.size());
for (BgReading bg : graph_bgs) {
dataMaps.add(dataMap(bg));
last_send_success = bg.timestamp;
//Log.d(TAG, "getWearBgData bg getId:" + bg.getId() + " raw_data:" + bg.raw_data + " filtered_data:" + bg.filtered_data + " timestamp:" + bg.timestamp + " uuid:" + bg.uuid);
}
entries.putLong("time", new Date().getTime()); // MOST IMPORTANT LINE FOR TIMESTAMP
entries.putDataMapArrayList("entries", dataMaps);
Log.i(TAG, "getWearBgReadingData SYNCED BGs up to " + JoH.dateTimeText(last_send_success) + " count = " + graph_bgs.size());
return entries;
} else
Log.i(TAG, "getWearBgReading SYNCED BGs up to " + JoH.dateTimeText(last_send_success) + " count = 0");
}
return null;
}
private boolean restartWatchDog() {//KS from app/MissedReadingService.java
final long stale_millis = Home.stale_data_millis();
if (is_using_bt) {//(prefs.getBoolean("aggressive_service_restart", false) || DexCollectionType.isFlakey()) {
if (!BgReading.last_within_millis(stale_millis)) {
if (JoH.ratelimit("aggressive-restart", aggressive_backoff_timer)) {
Log.e(TAG, "Aggressively restarting wear collector service due to lack of reception: backoff: "+aggressive_backoff_timer);
if (aggressive_backoff_timer < 1200) aggressive_backoff_timer+=60;
return true;//CollectionServiceStarter.restartCollectionService
} else {
aggressive_backoff_timer = 120; // reset
}
}
}
return false;
}
private void doLegacyRESTUploadTo(NightscoutService nightscoutService, List<BgReading> glucoseDataSets) throws Exception {
for (BgReading record : glucoseDataSets) {
Response<ResponseBody> r = nightscoutService.upload(populateLegacyAPIEntry(record)).execute();
if (!r.isSuccess()) throw new UploaderException(r.message(), r.code());
}
postDeviceStatus(nightscoutService, null);
}
@Test
public void slopePerMsFromDirectionTest() {
for (int direction = 1; direction < 8; direction++) {
final ShareGlucoseRecord record = new ShareGlucoseRecord();
record.Trend = direction;
assertWithMessage("Slope check " + direction).that(BgReading.slopeName(record.slopePerMsFromDirection() * 60000)).isEqualTo(record.slopeDirection());
}
}
static synchronized void syncBGTable2() {
if (!Sensor.isActive()) return;
new Thread() {
@Override
public void run() {
final PowerManager.WakeLock wl = JoH.getWakeLock("syncBGTable", 300000);
//if ((JoH.ts() - last_sync_fill) > (60 * 1000 * (5 + bg_sync_backoff))) {
if (JoH.pratelimit("last-sync-fill", 60 * (5 + bg_sync_backoff))) {
last_sync_fill = JoH.tsl();
bg_sync_backoff++;
// Since this is a big update, also update sensor and calibrations
syncSensor(Sensor.currentSensor(), true);
final List<BgReading> bgReadings = BgReading.latestForGraph(300, JoH.tsl() - (24 * 60 * 60 * 1000));
StringBuilder stringBuilder = new StringBuilder();
for (BgReading bgReading : bgReadings) {
String myrecord = bgReading.toJSON(false);
if (stringBuilder.length() > 0) {
stringBuilder.append("^");
}
stringBuilder.append(myrecord);
}
final String mypacket = stringBuilder.toString();
Log.d(TAG, "Total BGreading sync packet size: " + mypacket.length());
if (mypacket.length() > 0) {
DisplayQRCode.uploadBytes(mypacket.getBytes(Charset.forName("UTF-8")), 2);
} else {
Log.i(TAG, "Not uploading data due to zero length");
}
} else {
Log.d(TAG, "Ignoring recent sync request, backoff: " + bg_sync_backoff);
}
JoH.releaseWakeLock(wl);
}
}.start();
}
public static synchronized double getCurrentLowOccursAt() {//KS TODO implement low predictions
try {
final long last_bg_reading_timestamp = BgReading.last().timestamp;
if (low_occurs_at_processed_till_timestamp < last_bg_reading_timestamp) {
Log.d(TAG, "Recalculating lowOccursAt: " + JoH.dateTimeText((long) low_occurs_at_processed_till_timestamp) + " vs " + JoH.dateTimeText(last_bg_reading_timestamp));
// new only the last hour worth of data for this
(new BgGraphBuilder(xdrip.getAppContext(), System.currentTimeMillis() - 60 * 60 * 1000, System.currentTimeMillis() + 5 * 60 * 1000, 24, true)).addBgReadingValues(false);
} else {
Log.d(TAG, "Cached current low timestamp ok: " + JoH.dateTimeText((long) low_occurs_at_processed_till_timestamp) + " vs " + JoH.dateTimeText(last_bg_reading_timestamp));
}
} catch (Exception e) {
Log.e(TAG, "Got exception in getCurrentLowOccursAt() " + e);
}
return low_occurs_at;
}
public boolean uploadMongo(List<BgReading> glucoseDataSets, List<Calibration> meterRecords, List<Calibration> calRecords, List<TransmitterData> transmittersData, List<LibreBlock> libreBlock) {
boolean mongoStatus = false;
if (enableMongoUpload) {
double start = new Date().getTime();
mongoStatus = doMongoUpload(prefs, glucoseDataSets, meterRecords, calRecords, transmittersData, libreBlock);
Log.i(TAG, String.format("Finished upload of %s record using a Mongo in %s ms result: %b",
glucoseDataSets.size() + meterRecords.size() + calRecords.size() + transmittersData.size() + libreBlock.size(), System.currentTimeMillis() - start, mongoStatus));
}
return mongoStatus;
}
public static boolean sendWearUpload(List<BgReading> bgs, List<Calibration> cals, List<BloodTest> bts, List<Treatments> treatsAdd, List<String> treatsDel) {
boolean statusCals = sendWearCalibrationData(0, 0, cals);
boolean statusBgs = sendWearBgData(0, 0, bgs);
boolean statusBts = sendWearBloodTestData(0, 0, bts);
boolean statusTreats = sendWearTreatmentsData(0, 0, treatsAdd);
boolean statusTreatsDel = sendWearTreatmentsDataDelete(treatsDel);
return (statusCals && statusBts && statusTreats && statusTreatsDel && statusBgs);
}
boolean trendingToAlertEnd(Context context, Boolean newAlert, AlertType Alert) {
if (newAlert && !smart_alerting) {
// User does not want smart alerting at all.
return false;
}
if ((!newAlert) && (!smart_snoozing)) {
// User does not want smart snoozing at all.
return false;
}
return BgReading.trendingToAlertEnd(context, Alert.above);
}
private static Pair<Long, Long> getBackFillStatus() {
final long maxBackfillPeriodMs = getMaxBackFillHours() * HOUR_IN_MS; // how far back to request backfill data
final int check_readings = getMaxBackFillHours() * recordsPerHour();
UserError.Log.d(TAG, "Checking " + check_readings + " for backfill requirement");
final List<BgReading> lastReadings = BgReading.latest_by_size(check_readings);
boolean ask_for_backfill = false;
long earliest_timestamp = tsl() - maxBackfillPeriodMs;
long latest_timestamp = tsl();
if ((lastReadings == null) || (lastReadings.size() != check_readings)) {
ask_for_backfill = true;
} else {
for (int i = 0; i < lastReadings.size(); i++) {
final BgReading reading = lastReadings.get(i);
if ((reading == null) || (msSince(reading.timestamp) > ((DEXCOM_PERIOD * i) + Constants.MINUTE_IN_MS * 7))) {
ask_for_backfill = true;
if ((reading != null) && (msSince(reading.timestamp) <= maxBackfillPeriodMs)) {
earliest_timestamp = reading.timestamp;
}
if (reading != null) {
UserError.Log.d(TAG, "Flagging backfill tripped by reading: " + i + " at time: " + JoH.dateTimeText(reading.timestamp) + " creating backfill window: " + JoH.dateTimeText(earliest_timestamp));
} else {
UserError.Log.d(TAG, "Flagging backfill tripped by null reading: " + i);
}
break;
} else {
// good record
latest_timestamp = reading.timestamp;
}
}
}
return new Pair<>(ask_for_backfill ? earliest_timestamp : -1, latest_timestamp);
}
private static void createBGfromGD(GlucoseData gd, boolean use_smoothed_data, boolean quick) {
final double converted;
if (gd.glucoseLevelRaw > 0) {
if(use_smoothed_data) {
converted = convert_for_dex(gd.glucoseLevelRawSmoothed);
Log.e(TAG,"Using smoothed value " + converted + " instead of " + convert_for_dex(gd.glucoseLevelRaw) );
} else {
converted = convert_for_dex(gd.glucoseLevelRaw);
}
} else {
converted = 12; // RF error message - might be something else like unconstrained spline
}
if (gd.realDate > 0) {
// Log.d(TAG, "Raw debug: " + JoH.dateTimeText(gd.realDate) + " raw: " + gd.glucoseLevelRaw + " converted: " + converted);
if ((newest_cmp == -1) || (oldest_cmp == -1) || (gd.realDate < oldest_cmp) || (gd.realDate > newest_cmp)) {
// if (BgReading.readingNearTimeStamp(gd.realDate) == null) {
if ((gd.realDate < oldest) || (oldest == -1)) oldest = gd.realDate;
if ((gd.realDate > newest) || (newest == -1)) newest = gd.realDate;
if (BgReading.getForPreciseTimestamp(gd.realDate, segmentation_timeslice, false) == null) {
Log.d(TAG, "Creating bgreading at: " + JoH.dateTimeText(gd.realDate));
BgReading.create(converted, converted, xdrip.getAppContext(), gd.realDate, quick); // quick lite insert
} else {
if (d)
Log.d(TAG, "Ignoring duplicate timestamp for: " + JoH.dateTimeText(gd.realDate));
}
} else {
if (d)
Log.d(TAG, "Already processed from date range: " + JoH.dateTimeText(gd.realDate));
}
} else {
Log.e(TAG, "Fed a zero or negative date");
}
if (d)
Log.d(TAG, "Oldest : " + JoH.dateTimeText(oldest_cmp) + " Newest : " + JoH.dateTimeText(newest_cmp));
}
private static void addToQueue(BgReading bgReading, String operation_type) {
BgSendQueue bgSendQueue = new BgSendQueue();
bgSendQueue.operation_type = operation_type;
bgSendQueue.bgReading = bgReading;
bgSendQueue.success = false;
bgSendQueue.mongo_success = false;
bgSendQueue.save();
Log.d("BGQueue", "New value added to queue!");
}