Java Code Examples for com.eveningoutpost.dexdrip.Home#toaststaticnext()

The following examples show how to use com.eveningoutpost.dexdrip.Home#toaststaticnext() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ActivityRecognizedService.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
private static void disableMotionTrackingDueToErrors(Context context) {
    final long requested = getInternalPrefsLong(REQUESTED);
    final long received = getInternalPrefsLong(RECEIVED);
    Home.toaststaticnext("DISABLED MOTION TRACKING DUE TO FAILURES! See Error Log!");
    final String msg = "Had to disable motion tracking feature as it did not seem to be working and may be incompatible with your phone. Please report this to the developers using the send logs feature: " + requested + " vs " + received + " " + JoH.getDeviceDetails();
    UserError.Log.wtf(TAG, msg);
    UserError.Log.ueh(TAG, msg);
    Pref.setBoolean("motion_tracking_enabled", false);
    evaluateRequestReceivedCounters(true, context); // mark for disable
    setInternalPrefsLong(REQUESTED, 0);
    setInternalPrefsLong(RECEIVED, 0);
    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

    Intent intent = new Intent(xdrip.getAppContext(), ErrorsActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(xdrip.getAppContext(), 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);
    builder.setContentText("Shut down motion detection! See Error Logs - Please report to developer" + JoH.dateTimeText(JoH.tsl()));
    builder.setContentIntent(pendingIntent);
    builder.setSmallIcon(R.drawable.ic_launcher);
    builder.setContentTitle("Problem with motion detection!");
    NotificationManagerCompat.from(context).notify(VEHICLE_NOTIFICATION_ERROR_ID, builder.build());
}
 
Example 2
Source File: ActivityRecognizedService.java    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
private static void disableMotionTrackingDueToErrors(Context context) {
    final long requested = getInternalPrefsLong(REQUESTED);
    final long received = getInternalPrefsLong(RECEIVED);
    Home.toaststaticnext("DISABLED MOTION TRACKING DUE TO FAILURES! See Error Log!");
    final String msg = "Had to disable motion tracking feature as it did not seem to be working and may be incompatible with your phone. Please report this to the developers using the send logs feature: " + requested + " vs " + received + " " + JoH.getDeviceDetails();
    UserError.Log.wtf(TAG, msg);
    UserError.Log.ueh(TAG, msg);
    Pref.setBoolean("motion_tracking_enabled", false);
    evaluateRequestReceivedCounters(true, context); // mark for disable
    setInternalPrefsLong(REQUESTED, 0);
    setInternalPrefsLong(RECEIVED, 0);
    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

    Intent intent = new Intent(xdrip.getAppContext(), ErrorsActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(xdrip.getAppContext(), 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);
    builder.setContentText("Shut down motion detection! See Error Logs - Please report to developer" + JoH.dateTimeText(JoH.tsl()));
    builder.setContentIntent(pendingIntent);
    builder.setSmallIcon(R.drawable.ic_launcher);
    builder.setContentTitle("Problem with motion detection!");
    NotificationManagerCompat.from(context).notify(VEHICLE_NOTIFICATION_ERROR_ID, builder.build());
}
 
Example 3
Source File: Sensor.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
public static Sensor fromJSON(String json) {
    if (json.length()==0) {
        Log.d(TAG,"Empty json received in Sensor fromJson");
        return null;
    }
    try {
        Log.d(TAG, "Processing incoming json: " + json);
       return new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().fromJson(json,Sensor.class);
    } catch (Exception e) {
        Log.d(TAG, "Got exception parsing Sensor json: " + e.toString());
        Home.toaststaticnext("Error on Sensor sync.");
        return null;
    }
}
 
Example 4
Source File: BgReading.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
public static BgReading fromJSON(String json) {
    if (json.length()==0)
    {
        Log.d(TAG,"Empty json received in bgreading fromJson");
        return null;
    }
    try {
        Log.d(TAG, "Processing incoming json: " + json);
       return new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().fromJson(json,BgReading.class);
    } catch (Exception e) {
        Log.d(TAG, "Got exception parsing BgReading json: " + e.toString());
        Home.toaststaticnext("Error on BGReading sync, probably decryption key mismatch");
        return null;
    }
}
 
Example 5
Source File: BloodTest.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
public static BloodTest fromJSON(String json) {
    if ((json == null) || (json.length() == 0)) {
        UserError.Log.d(TAG, "Empty json received in bloodtest fromJson");
        return null;
    }
    try {
        UserError.Log.d(TAG, "Processing incoming json: " + json);
        return new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().fromJson(json, BloodTest.class);
    } catch (Exception e) {
        UserError.Log.d(TAG, "Got exception parsing bloodtest json: " + e.toString());
        Home.toaststaticnext("Error on Bloodtest sync, probably decryption key mismatch");
        return null;
    }
}
 
Example 6
Source File: SendToDataLayerThread.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void onPreExecute()
{
    concurrency++;
    if ((concurrency > 12) || ((concurrency > 3 && (lastlock != 0) && (JoH.tsl() - lastlock) > 300000))) {//KS increase from 8 to 12
        // error if 9 concurrent threads or lock held for >5 minutes with concurrency of 4
        final String err = "Wear Integration deadlock detected!! "+((lastlock !=0) ? "locked" : "")+" state:"+state+" @"+ JoH.hourMinuteString();
        Home.toaststaticnext(err);
        UserError.Log.e(TAG,err);
    }
    if (concurrency<0) Home.toaststaticnext("Wear Integration impossible concurrency!!");
    UserError.Log.d(TAG, "SendDataToLayerThread pre-execute concurrency: " + concurrency);
}
 
Example 7
Source File: Sensor.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public static Sensor fromJSON(String json) {
    if (json.length()==0) {
        Log.d(TAG,"Empty json received in Sensor fromJson");
        return null;
    }
    try {
        Log.d(TAG, "Processing incoming json: " + json);
       return new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().fromJson(json,Sensor.class);
    } catch (Exception e) {
        Log.d(TAG, "Got exception parsing Sensor json: " + e.toString());
        Home.toaststaticnext("Error on Sensor sync.");
        return null;
    }
}
 
Example 8
Source File: BgReading.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public static BgReading fromJSON(String json) {
    if (json.length()==0)
    {
        Log.d(TAG,"Empty json received in bgreading fromJson");
        return null;
    }
    try {
        Log.d(TAG, "Processing incoming json: " + json);
       return new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().fromJson(json,BgReading.class);
    } catch (Exception e) {
        Log.d(TAG, "Got exception parsing BgReading json: " + e.toString());
        Home.toaststaticnext("Error on BGReading sync, probably decryption key mismatch");
        return null;
    }
}
 
Example 9
Source File: G5CollectionService.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
private synchronized void processRxCharacteristic(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {

            Log.i(TAG, "onCharacteristicChanged On Main Thread? " + isOnMainThread());
            Log.e(TAG, "CharBytes-nfy" + Arrays.toString(characteristic.getValue()));
            Log.i(TAG, "CharHex-nfy" + Extensions.bytesToHex(characteristic.getValue()));


            byte[] buffer = characteristic.getValue();
            byte firstByte = buffer[0];
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && gatt != null) {
                gatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH);
            }
            Log.d(TAG, "Received opcode reply: " + JoH.bytesToHex(new byte[] { firstByte }));
            if (firstByte == 0x2f) {
                SensorRxMessage sensorRx = new SensorRxMessage(characteristic.getValue());

                ByteBuffer sensorData = ByteBuffer.allocate(buffer.length);
                sensorData.order(ByteOrder.LITTLE_ENDIAN);
                sensorData.put(buffer, 0, buffer.length);

                int sensor_battery_level = 0;
                if (sensorRx.status == TransmitterStatus.BRICKED) {
                    //TODO Handle this in UI/Notification
                    sensor_battery_level = 206; //will give message "EMPTY"
                } else if (sensorRx.status == TransmitterStatus.LOW) {
                    sensor_battery_level = 209; //will give message "LOW"
                } else {
                    sensor_battery_level = 216; //no message, just system status "OK"
                }

                //Log.e(TAG, "filtered: " + sensorRx.filtered);
                disconnected133 = 0; // reset as we got a reading
                disconnected59 = 0;
                lastState = "Got data OK: " + JoH.hourMinuteString();
                successes++;
                failures=0;
                Log.e(TAG, "SUCCESS!! unfiltered: " + sensorRx.unfiltered + " timestamp: " + sensorRx.timestamp + " " + JoH.qs((double)sensorRx.timestamp / 86400, 1) + " days");
                if (sensorRx.unfiltered == 0) {
                    lastState = "Transmitter sent raw sensor value of 0 !! This isn't good. " + JoH.hourMinuteString();
                }
                last_transmitter_timestamp = sensorRx.timestamp;
                if ((getVersionDetails) && (!haveFirmwareDetails())) {
                    doVersionRequestMessage(gatt, characteristic);
                } else if ((getBatteryDetails) && (getBatteryStatusNow || !haveCurrentBatteryStatus())) {
                    doBatteryInfoRequestMessage(gatt, characteristic);
                } else {
                    doDisconnectMessage(gatt, characteristic);
                }

                // TODO beware that wear G5CollectionService is now getting rather out of sync with app version
                final boolean g6 = usingG6();
                processNewTransmitterData(g6 ? sensorRx.unfiltered * G6_SCALING : sensorRx.unfiltered, g6 ? sensorRx.filtered * G6_SCALING : sensorRx.filtered, sensor_battery_level, new Date().getTime());

                // was this the first success after we force enabled always_authenticate?
                if (force_always_authenticate && (successes == 1)) {
                    Log.wtf(TAG, "We apparently only got a reading after forcing the Always Authenticate option");
                    Home.toaststaticnext("Please Enable G5 Always Authenticate debug option!");
                    // TODO should we actually change the settings here?
                }
            } else if (firstByte == GlucoseRxMessage.opcode) {
                disconnected133 = 0; // reset as we got a reading
                disconnected59 = 0;
                GlucoseRxMessage glucoseRx = new GlucoseRxMessage(characteristic.getValue());
                Log.e(TAG, "SUCCESS!! glucose unfiltered: " + glucoseRx.unfiltered);
                successes++;
                failures=0;
                doDisconnectMessage(gatt, characteristic);
                processNewTransmitterData(glucoseRx.unfiltered, glucoseRx.filtered, 216, new Date().getTime());
            } else if (firstByte == VersionRequestRxMessage.opcode) {
                if (!setStoredFirmwareBytes(defaultTransmitter.transmitterId, characteristic.getValue(), true)) {
                    Log.wtf(TAG, "Could not save out firmware version!");
                }
                doDisconnectMessage(gatt, characteristic);
            } else if (firstByte == BatteryInfoRxMessage.opcode) {
                if (!setStoredBatteryBytes(defaultTransmitter.transmitterId, characteristic.getValue())) {
                    Log.wtf(TAG, "Could not save out battery data!");
                }
                getBatteryStatusNow = false;
                doDisconnectMessage(gatt, characteristic);
            } else {
                Log.e(TAG, "onCharacteristic CHANGED unexpected opcode: " + firstByte + " (have not disconnected!)");
            }
            Log.e(TAG, "OnCharacteristic CHANGED finished: ");
        }
 
Example 10
Source File: PersistentHigh.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
public static boolean checkForPersistentHigh() {

        // skip if not enabled
        if (!Pref.getBooleanDefaultFalse("persistent_high_alert_enabled")) return false;


        final List<BgReading> last = BgReading.latest(1);
        if ((last != null) && (last.size() > 0)) {

            final double highMarkMgDl = Home.convertToMgDlIfMmol(
                    JoH.tolerantParseDouble(Pref.getString("highValue", "170"), 170d));

            final long now = JoH.tsl();
            final long since = now - last.get(0).timestamp;
            // only process if last reading <10 mins
            if (since < MINUTE_IN_MS * 10) {
                // check if exceeding high
                if (last.get(0).getDg_mgdl() > highMarkMgDl) {

                    final double this_slope = last.get(0).getDg_slope() * MINUTE_IN_MS;
                    Log.d(TAG, "CheckForPersistentHigh: Slope: " + JoH.qs(this_slope)+ " "+JoH.dateTimeText(last.get(0).timestamp));

                    // if not falling
                    if (this_slope > 0 && !last.get(0).hide_slope) {
                        final long high_since = Pref.getLong(PERSISTENT_HIGH_SINCE, 0);
                        if (high_since == 0) {
                            // no previous persistent high so set start as now
                            Pref.setLong(PERSISTENT_HIGH_SINCE, now);
                            Log.d(TAG, "Registering start of persistent high at time now");
                        } else {
                            final long high_for_mins = (now - high_since) / MINUTE_IN_MS;
                            long threshold_mins;
                            try {
                                threshold_mins = Long.parseLong(Pref.getString("persistent_high_threshold_mins", "60"));
                            } catch (NumberFormatException e) {
                                threshold_mins = 60;
                                Home.toaststaticnext("Invalid persistent high for longer than minutes setting: using 60 mins instead");
                            }
                            if (high_for_mins > threshold_mins) {
                                // we have been high for longer than the threshold - raise alert

                                // except if alerts are disabled
                                if (Pref.getLong("alerts_disabled_until", 0) > new Date().getTime()) {
                                    Log.i(TAG, "checkforPersistentHigh: Notifications are currently disabled cannot alert!!");
                                    return false;
                                }

                                if (!dataQualityCheck(high_since, highMarkMgDl)) {
                                    Log.d(TAG, "Insufficient data quality to raise persistent high alert");
                                    return false;
                                }

                                Log.i(TAG, "Persistent high for: " + high_for_mins + " mins -> alerting");
                                Notifications.persistentHighAlert(xdrip.getAppContext(), true, xdrip.getAppContext().getString(R.string.persistent_high_for_greater_than) + (int) high_for_mins + xdrip.getAppContext().getString(R.string.space_mins));
                                return true;
                            } else {
                                Log.d(TAG, "Persistent high below time threshold at: " + high_for_mins);
                            }
                        }
                    }
                } else {
                    // not high - cancel any existing
                    if (Pref.getLong(PERSISTENT_HIGH_SINCE, 0) != 0) {
                        Log.i(TAG, "Cancelling previous persistent high as we are no longer high");
                        Pref.setLong(PERSISTENT_HIGH_SINCE, 0); // clear it
                        Notifications.persistentHighAlert(xdrip.getAppContext(), false, ""); // cancel it
                    }
                }
            }
        }
        return false; // actually we should probably return void as we do everything inside this method
    }
 
Example 11
Source File: BgReading.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
public static BgReading createFromRawNoSave(Sensor sensor, Calibration calibration, double raw_data, double filtered_data, long timestamp) {
    final BgReading bgReading = new BgReading();
    if (sensor == null) {
        sensor = Sensor.currentSensor();
        if (sensor == null) {
            return bgReading;
        }
    }
    if (calibration == null) {
        calibration = Calibration.lastValid();
        if (calibration == null) {
            return bgReading;
        }
    }

    bgReading.sensor = sensor;
    bgReading.sensor_uuid = sensor.uuid;
    bgReading.calibration = calibration;
    bgReading.calibration_uuid = calibration.uuid;
    bgReading.raw_data = (raw_data / 1000);
    bgReading.filtered_data = (filtered_data / 1000);
    bgReading.timestamp = timestamp;
    bgReading.uuid = UUID.randomUUID().toString();
    bgReading.time_since_sensor_started = bgReading.timestamp - sensor.started_at;

    bgReading.calculateAgeAdjustedRawValue();

    if (calibration.check_in) {
        double firstAdjSlope = calibration.first_slope + (calibration.first_decay * (Math.ceil(new Date().getTime() - calibration.timestamp) / (1000 * 60 * 10)));
        double calSlope = (calibration.first_scale / firstAdjSlope) * 1000;
        double calIntercept = ((calibration.first_scale * calibration.first_intercept) / firstAdjSlope) * -1;
        bgReading.calculated_value = (((calSlope * bgReading.raw_data) + calIntercept) - 5);
        bgReading.filtered_calculated_value = (((calSlope * bgReading.ageAdjustedFiltered()) + calIntercept) - 5);

    } else {
        BgReading lastBgReading = BgReading.last();
        if (lastBgReading != null && lastBgReading.calibration != null) {
            Log.d(TAG, "Create calibration.uuid=" + calibration.uuid + " bgReading.uuid: " + bgReading.uuid + " lastBgReading.calibration_uuid: " + lastBgReading.calibration_uuid + " lastBgReading.calibration.uuid: " + lastBgReading.calibration.uuid);
            Log.d(TAG, "Create lastBgReading.calibration_flag=" + lastBgReading.calibration_flag + " bgReading.timestamp: " + bgReading.timestamp + " lastBgReading.timestamp: " + lastBgReading.timestamp + " lastBgReading.calibration.timestamp: " + lastBgReading.calibration.timestamp);
            Log.d(TAG, "Create lastBgReading.calibration_flag=" + lastBgReading.calibration_flag + " bgReading.timestamp: " + JoH.dateTimeText(bgReading.timestamp) + " lastBgReading.timestamp: " + JoH.dateTimeText(lastBgReading.timestamp) + " lastBgReading.calibration.timestamp: " + JoH.dateTimeText(lastBgReading.calibration.timestamp));
            if (lastBgReading.calibration_flag == true && ((lastBgReading.timestamp + (60000 * 20)) > bgReading.timestamp) && ((lastBgReading.calibration.timestamp + (60000 * 20)) > bgReading.timestamp)) {
                lastBgReading.calibration.rawValueOverride(BgReading.weightedAverageRaw(lastBgReading.timestamp, bgReading.timestamp, lastBgReading.calibration.timestamp, lastBgReading.age_adjusted_raw_value, bgReading.age_adjusted_raw_value), xdrip.getAppContext());
                newCloseSensorData();
            }
        }

        if ((bgReading.raw_data != 0) && (bgReading.raw_data * 2 == bgReading.filtered_data)) {
            Log.wtf(TAG, "Filtered data is exactly double raw - this is completely wrong - dead transmitter? - blocking glucose calculation");
            bgReading.calculated_value = 0;
            bgReading.filtered_calculated_value = 0;
            bgReading.hide_slope = true;
        } else if (!SensorSanity.isRawValueSane(bgReading.raw_data)) {
            Log.wtf(TAG, "Raw data fails sanity check! " + bgReading.raw_data);
            bgReading.calculated_value = 0;
            bgReading.filtered_calculated_value = 0;
            bgReading.hide_slope = true;
        } else {

            // calculate glucose number from raw
            final CalibrationAbstract.CalibrationData pcalibration;
            final CalibrationAbstract plugin = getCalibrationPluginFromPreferences(); // make sure do this only once

            if ((plugin != null) && ((pcalibration = plugin.getCalibrationData()) != null) && (Pref.getBoolean("use_pluggable_alg_as_primary", false))) {
                Log.d(TAG, "USING CALIBRATION PLUGIN AS PRIMARY!!!");
                if (plugin.isCalibrationSane(pcalibration)) {
                    bgReading.calculated_value = (pcalibration.slope * bgReading.age_adjusted_raw_value) + pcalibration.intercept;
                    bgReading.filtered_calculated_value = (pcalibration.slope * bgReading.ageAdjustedFiltered()) + calibration.intercept;
                } else {
                    UserError.Log.wtf(TAG, "Calibration plugin failed intercept sanity check: " + pcalibration.toS());
                    Home.toaststaticnext("Calibration plugin failed intercept sanity check");
                }
            } else {
                bgReading.calculated_value = ((calibration.slope * bgReading.age_adjusted_raw_value) + calibration.intercept);
                bgReading.filtered_calculated_value = ((calibration.slope * bgReading.ageAdjustedFiltered()) + calibration.intercept);
            }

            updateCalculatedValueToWithinMinMax(bgReading);
        }
    }

    // LimiTTer can send 12 to indicate problem with NFC reading.
    if ((!calibration.check_in) && (raw_data == 12) && (filtered_data == 12)) {
        // store the raw value for sending special codes, note updateCalculatedValue would try to nix it
        bgReading.calculated_value = raw_data;
        bgReading.filtered_calculated_value = filtered_data;
    }
    return  bgReading;
}
 
Example 12
Source File: PersistentHigh.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
public static boolean checkForPersistentHigh() {

        // skip if not enabled
        if (!Pref.getBooleanDefaultFalse("persistent_high_alert_enabled")) return false;


        final List<BgReading> last = BgReading.latest(1);
        if ((last != null) && (last.size() > 0)) {

            final double highMarkMgDl = Home.convertToMgDlIfMmol(
                    JoH.tolerantParseDouble(Pref.getString("highValue", "170"), 170d));

            final long now = JoH.tsl();
            final long since = now - last.get(0).timestamp;
            // only process if last reading <10 mins
            if (since < MINUTE_IN_MS * 10) {
                // check if exceeding high
                if (last.get(0).getDg_mgdl() > highMarkMgDl) {

                    final double this_slope = last.get(0).getDg_slope() * MINUTE_IN_MS;
                    Log.d(TAG, "CheckForPersistentHigh: Slope: " + JoH.qs(this_slope)+ " "+JoH.dateTimeText(last.get(0).timestamp));

                    // if not falling
                    if (this_slope > 0 && !last.get(0).hide_slope) {
                        final long high_since = Pref.getLong(PERSISTENT_HIGH_SINCE, 0);
                        if (high_since == 0) {
                            // no previous persistent high so set start as now
                            Pref.setLong(PERSISTENT_HIGH_SINCE, now);
                            Log.d(TAG, "Registering start of persistent high at time now");
                        } else {
                            final long high_for_mins = (now - high_since) / MINUTE_IN_MS;
                            long threshold_mins;
                            try {
                                threshold_mins = Long.parseLong(Pref.getString("persistent_high_threshold_mins", "60"));
                            } catch (NumberFormatException e) {
                                threshold_mins = 60;
                                Home.toaststaticnext("Invalid persistent high for longer than minutes setting: using 60 mins instead");
                            }
                            if (high_for_mins > threshold_mins) {
                                // we have been high for longer than the threshold - raise alert

                                // except if alerts are disabled
                                if (Pref.getLong("alerts_disabled_until", 0) > new Date().getTime()) {
                                    Log.i(TAG, "checkforPersistentHigh: Notifications are currently disabled cannot alert!!");
                                    return false;
                                }

                                if (!dataQualityCheck(high_since, highMarkMgDl)) {
                                    Log.d(TAG, "Insufficient data quality to raise persistent high alert");
                                    return false;
                                }

                                Log.i(TAG, "Persistent high for: " + high_for_mins + " mins -> alerting");
                                Notifications.persistentHighAlert(xdrip.getAppContext(), true, xdrip.getAppContext().getString(R.string.persistent_high_for_greater_than) + (int) high_for_mins + xdrip.getAppContext().getString(R.string.space_mins));
                                return true;
                            } else {
                                Log.d(TAG, "Persistent high below time threshold at: " + high_for_mins);
                            }
                        }
                    }
                } else {
                    // not high - cancel any existing
                    if (Pref.getLong(PERSISTENT_HIGH_SINCE, 0) != 0) {
                        Log.i(TAG, "Cancelling previous persistent high as we are no longer high");
                        Pref.setLong(PERSISTENT_HIGH_SINCE, 0); // clear it
                        Notifications.persistentHighAlert(xdrip.getAppContext(), false, ""); // cancel it
                    }
                }
            }
        }
        return false; // actually we should probably return void as we do everything inside this method
    }
 
Example 13
Source File: LibreUtils.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
public static boolean isSensorReady(byte sensorStatusByte) {

    String sensorStatusString = "";
    boolean ret = false;

    switch (sensorStatusByte) {
        case 0x01:
            sensorStatusString = "not yet started";
            break;
        case 0x02:
            sensorStatusString = "starting";
            ret = true;
            break;
        case 0x03:          // status for 14 days and 12 h of normal operation, abbott reader quits after 14 days
            sensorStatusString = "ready";
            ret = true;
            break;
        case 0x04:          // status of the following 12 h, sensor delivers last BG reading constantly
            sensorStatusString = "expired";
            // @keencave: to use dead sensor for test
//            ret = true;
            break;
        case 0x05:          // sensor stops operation after 15d after start
            sensorStatusString = "shutdown";
            // @keencave: to use dead sensors for test
//            ret = true;
            break;
        case 0x06:
            sensorStatusString = "in failure";
            break;
        default:
            sensorStatusString = "in an unknown state";
            break;
    }

    Log.i(TAG, "Sensor status is: " + sensorStatusString);

    
    
    
    if (SensorSanity.allowTestingWithDeadSensor()) {
        Log.e(TAG, "Warning allow to use a dead sensor");
        return true;
    }

    if (!ret) {
        Home.toaststaticnext("Can't use this sensor as it is " + sensorStatusString);
    }

    return ret;
}
 
Example 14
Source File: LibreUtils.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
public static boolean isSensorReady(byte sensorStatusByte) {

    String sensorStatusString = "";
    boolean ret = false;

    switch (sensorStatusByte) {
        case 0x01:
            sensorStatusString = "not yet started";
            break;
        case 0x02:
            sensorStatusString = "starting";
            ret = true;
            break;
        case 0x03:          // status for 14 days and 12 h of normal operation, abbott reader quits after 14 days
            sensorStatusString = "ready";
            ret = true;
            break;
        case 0x04:          // status of the following 12 h, sensor delivers last BG reading constantly
            sensorStatusString = "expired";
            // @keencave: to use dead sensor for test
//            ret = true;
            break;
        case 0x05:          // sensor stops operation after 15d after start
            sensorStatusString = "shutdown";
            // @keencave: to use dead sensors for test
//            ret = true;
            break;
        case 0x06:
            sensorStatusString = "in failure";
            break;
        default:
            sensorStatusString = "in an unknown state";
            break;
    }

    Log.i(TAG, "Sensor status is: " + sensorStatusString);

    
    
    
    if (SensorSanity.allowTestingWithDeadSensor()) {
        Log.e(TAG, "Warning allow to use a dead sensor");
        return true;
    }

    if (!ret) {
        Home.toaststaticnext("Can't use this sensor as it is " + sensorStatusString);
    }

    return ret;
}
 
Example 15
Source File: G5CollectionService.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
private synchronized void processRxCharacteristic(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {

            Log.i(TAG, "onCharacteristicChanged On Main Thread? " + isOnMainThread());
            Log.e(TAG, "CharBytes-nfy" + Arrays.toString(characteristic.getValue()));
            Log.i(TAG, "CharHex-nfy" + Extensions.bytesToHex(characteristic.getValue()));


            byte[] buffer = characteristic.getValue();
            byte firstByte = buffer[0];
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && gatt != null) {
                gatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH);
            }
            Log.d(TAG, "Received opcode reply: " + JoH.bytesToHex(new byte[] { firstByte }));
            if (firstByte == 0x2f) {
                SensorRxMessage sensorRx = new SensorRxMessage(characteristic.getValue());

                ByteBuffer sensorData = ByteBuffer.allocate(buffer.length);
                sensorData.order(ByteOrder.LITTLE_ENDIAN);
                sensorData.put(buffer, 0, buffer.length);

                int sensor_battery_level = 0;
                if (sensorRx.status == TransmitterStatus.BRICKED) {
                    //TODO Handle this in UI/Notification
                    sensor_battery_level = 206; //will give message "EMPTY"
                } else if (sensorRx.status == TransmitterStatus.LOW) {
                    sensor_battery_level = 209; //will give message "LOW"
                } else {
                    sensor_battery_level = 216; //no message, just system status "OK"
                }

                //Log.e(TAG, "filtered: " + sensorRx.filtered);
                disconnected133 = 0; // reset as we got a reading
                disconnected59 = 0;
                lastState = "Got data OK: " + JoH.hourMinuteString();
                successes++;
                failures=0;
                Log.e(TAG, "SUCCESS!! unfiltered: " + sensorRx.unfiltered + " timestamp: " + sensorRx.timestamp + " " + JoH.qs((double)sensorRx.timestamp / 86400, 1) + " days");
                if (sensorRx.unfiltered == 0) {
                    lastState = "Transmitter sent raw sensor value of 0 !! This isn't good. " + JoH.hourMinuteString();
                }
                last_transmitter_timestamp = sensorRx.timestamp;
                if ((getVersionDetails) && (!haveFirmwareDetails())) {
                    doVersionRequestMessage(gatt, characteristic);
                } else if ((getBatteryDetails) && (getBatteryStatusNow || !haveCurrentBatteryStatus())) {
                    doBatteryInfoRequestMessage(gatt, characteristic);
                } else {
                    doDisconnectMessage(gatt, characteristic);
                }

                final boolean g6 = usingG6();
                processNewTransmitterData(g6 ? sensorRx.unfiltered * G6_SCALING : sensorRx.unfiltered, g6 ? sensorRx.filtered * G6_SCALING : sensorRx.filtered, sensor_battery_level, new Date().getTime());
                // was this the first success after we force enabled always_authenticate?
                if (force_always_authenticate && (successes == 1)) {
                    Log.wtf(TAG, "We apparently only got a reading after forcing the Always Authenticate option");
                    Home.toaststaticnext("Please Enable G5 Always Authenticate debug option!");
                    // TODO should we actually change the settings here?
                }
            } else if (firstByte == GlucoseRxMessage.opcode) {
                // TODO doesn't support firmware version reading in GlucoseRX
                disconnected133 = 0; // reset as we got a reading
                disconnected59 = 0;
                GlucoseRxMessage glucoseRx = new GlucoseRxMessage(characteristic.getValue());
                Log.e(TAG, "SUCCESS!! glucose unfiltered: " + glucoseRx.unfiltered);
                successes++;
                failures=0;
                doDisconnectMessage(gatt, characteristic);
                processNewTransmitterData(glucoseRx.unfiltered, glucoseRx.filtered, 216, new Date().getTime());
            } else if (firstByte == VersionRequestRxMessage.opcode) {
                if (!setStoredFirmwareBytes(defaultTransmitter.transmitterId, characteristic.getValue(), true)) {
                    Log.wtf(TAG, "Could not save out firmware version!");
                }
                doDisconnectMessage(gatt, characteristic);
            } else if (firstByte == BatteryInfoRxMessage.opcode) {
                if (!setStoredBatteryBytes(defaultTransmitter.transmitterId, characteristic.getValue())) {
                    Log.wtf(TAG, "Could not save out battery data!");
                }
                getBatteryStatusNow = false;
                doDisconnectMessage(gatt, characteristic);
            } else {
                Log.e(TAG, "onCharacteristic CHANGED unexpected opcode: " + firstByte + " (have not disconnected!)");
            }
            Log.e(TAG, "OnCharacteristic CHANGED finished: ");
        }
 
Example 16
Source File: LibreUtils.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
public static boolean isSensorReady(byte sensorStatusByte) {

    String sensorStatusString = "";
    boolean ret = false;

    switch (sensorStatusByte) {
        case 0x01:
            sensorStatusString = "not yet started";
            break;
        case 0x02:
            sensorStatusString = "starting";
            ret = true;
            break;
        case 0x03:          // status for 14 days and 12 h of normal operation, abbott reader quits after 14 days
            sensorStatusString = "ready";
            ret = true;
            break;
        case 0x04:          // status of the following 12 h, sensor delivers last BG reading constantly
            sensorStatusString = "expired";
            // @keencave: to use dead sensor for test
//            ret = true;
            break;
        case 0x05:          // sensor stops operation after 15d after start
            sensorStatusString = "shutdown";
            // @keencave: to use dead sensors for test
//            ret = true;
            break;
        case 0x06:
            sensorStatusString = "in failure";
            break;
        default:
            sensorStatusString = "in an unknown state";
            break;
    }

    Log.i(TAG, "Sensor status is: " + sensorStatusString);

    
    
    
    if (SensorSanity.allowTestingWithDeadSensor()) {
        Log.e(TAG, "Warning allow to use a dead sensor");
        return true;
    }

    if (!ret) {
        Home.toaststaticnext("Can't use this sensor as it is " + sensorStatusString);
    }

    return ret;
}
 
Example 17
Source File: PersistentHigh.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
public static boolean checkForPersistentHigh() {

        // skip if not enabled
        if (!Pref.getBooleanDefaultFalse("persistent_high_alert_enabled")) return false;


        final List<BgReading> last = BgReading.latest(1);
        if ((last != null) && (last.size() > 0)) {

            final double highMarkMgDl = Home.convertToMgDlIfMmol(
                    JoH.tolerantParseDouble(Pref.getString("highValue", "170"), 170d));

            final long now = JoH.tsl();
            final long since = now - last.get(0).timestamp;
            // only process if last reading <10 mins
            if (since < MINUTE_IN_MS * 10) {
                // check if exceeding high
                if (last.get(0).getDg_mgdl() > highMarkMgDl) {

                    final double this_slope = last.get(0).getDg_slope() * MINUTE_IN_MS;
                    Log.d(TAG, "CheckForPersistentHigh: Slope: " + JoH.qs(this_slope)+ " "+JoH.dateTimeText(last.get(0).timestamp));

                    // if not falling
                    if (this_slope > 0 && !last.get(0).hide_slope) {
                        final long high_since = Pref.getLong(PERSISTENT_HIGH_SINCE, 0);
                        if (high_since == 0) {
                            // no previous persistent high so set start as now
                            Pref.setLong(PERSISTENT_HIGH_SINCE, now);
                            Log.d(TAG, "Registering start of persistent high at time now");
                        } else {
                            final long high_for_mins = (now - high_since) / MINUTE_IN_MS;
                            long threshold_mins;
                            try {
                                threshold_mins = Long.parseLong(Pref.getString("persistent_high_threshold_mins", "60"));
                            } catch (NumberFormatException e) {
                                threshold_mins = 60;
                                Home.toaststaticnext("Invalid persistent high for longer than minutes setting: using 60 mins instead");
                            }
                            if (high_for_mins > threshold_mins) {
                                // we have been high for longer than the threshold - raise alert

                                // except if alerts are disabled
                                if (Pref.getLong("alerts_disabled_until", 0) > new Date().getTime()) {
                                    Log.i(TAG, "checkforPersistentHigh: Notifications are currently disabled cannot alert!!");
                                    return false;
                                }

                                if (!dataQualityCheck(high_since, highMarkMgDl)) {
                                    Log.d(TAG, "Insufficient data quality to raise persistent high alert");
                                    return false;
                                }

                                Log.i(TAG, "Persistent high for: " + high_for_mins + " mins -> alerting");
                                Notifications.persistentHighAlert(xdrip.getAppContext(), true, xdrip.getAppContext().getString(R.string.persistent_high_for_greater_than) + (int) high_for_mins + xdrip.getAppContext().getString(R.string.space_mins));
                                return true;
                            } else {
                                Log.d(TAG, "Persistent high below time threshold at: " + high_for_mins);
                            }
                        }
                    }
                } else {
                    // not high - cancel any existing
                    if (Pref.getLong(PERSISTENT_HIGH_SINCE, 0) != 0) {
                        Log.i(TAG, "Cancelling previous persistent high as we are no longer high");
                        Pref.setLong(PERSISTENT_HIGH_SINCE, 0); // clear it
                        Notifications.persistentHighAlert(xdrip.getAppContext(), false, ""); // cancel it
                    }
                }
            }
        }
        return false; // actually we should probably return void as we do everything inside this method
    }
 
Example 18
Source File: BgReading.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
public static boolean checkForPersistentHigh() {

        // skip if not enabled
        if (!Pref.getBooleanDefaultFalse("persistent_high_alert_enabled")) return false;


        List<BgReading> last = BgReading.latest(1);
        if ((last != null) && (last.size()>0)) {

            final long now = JoH.tsl();
            final long since = now - last.get(0).timestamp;
            // only process if last reading <10 mins
            if (since < 600000) {
                // check if exceeding high
                if (last.get(0).calculated_value >
                        Home.convertToMgDlIfMmol(
                                JoH.tolerantParseDouble(Pref.getString("highValue", "170")))) {

                    final double this_slope = last.get(0).calculated_value_slope * 60000;
                    //Log.d(TAG, "CheckForPersistentHigh: Slope: " + JoH.qs(this_slope));

                    // if not falling
                    if (this_slope > 0) {
                        final long high_since = Pref.getLong(PERSISTENT_HIGH_SINCE, 0);
                        if (high_since == 0) {
                            // no previous persistent high so set start as now
                            Pref.setLong(PERSISTENT_HIGH_SINCE, now);
                            Log.d(TAG, "Registering start of persistent high at time now");
                        } else {
                            final long high_for_mins = (now - high_since) / (1000 * 60);
                            long threshold_mins;
                            try {
                                threshold_mins = Long.parseLong(Pref.getString("persistent_high_threshold_mins", "60"));
                            } catch (NumberFormatException e) {
                                threshold_mins = 60;
                                Home.toaststaticnext("Invalid persistent high for longer than minutes setting: using 60 mins instead");
                            }
                            if (high_for_mins > threshold_mins) {
                                // we have been high for longer than the threshold - raise alert

                                // except if alerts are disabled
                                if (Pref.getLong("alerts_disabled_until", 0) > new Date().getTime()) {
                                    Log.i(TAG, "checkforPersistentHigh: Notifications are currently disabled cannot alert!!");
                                    return false;
                                }
                                Log.i(TAG, "Persistent high for: " + high_for_mins + " mins -> alerting");
                                Notifications.persistentHighAlert(xdrip.getAppContext(), true, xdrip.getAppContext().getString(R.string.persistent_high_for_greater_than) + (int) high_for_mins + xdrip.getAppContext().getString(R.string.space_mins));

                            } else {
                                Log.d(TAG, "Persistent high below time threshold at: " + high_for_mins);
                            }
                        }
                    }
                } else {
                    // not high - cancel any existing
                    if (Pref.getLong(PERSISTENT_HIGH_SINCE,0)!=0)
                    {
                        Log.i(TAG,"Cancelling previous persistent high as we are no longer high");
                     Pref.setLong(PERSISTENT_HIGH_SINCE, 0); // clear it
                        Notifications.persistentHighAlert(xdrip.getAppContext(), false, ""); // cancel it
                    }
                }
            }
        }
        return false; // actually we should probably return void as we do everything inside this method
    }
 
Example 19
Source File: BgReading.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
public static BgReading createFromRawNoSave(Sensor sensor, Calibration calibration, double raw_data, double filtered_data, long timestamp) {
    final BgReading bgReading = new BgReading();
    if (sensor == null) {
        sensor = Sensor.currentSensor();
        if (sensor == null) {
            return bgReading;
        }
    }
    if (calibration == null) {
        calibration = Calibration.lastValid();
        if (calibration == null) {
            return bgReading;
        }
    }

    bgReading.sensor = sensor;
    bgReading.sensor_uuid = sensor.uuid;
    bgReading.calibration = calibration;
    bgReading.calibration_uuid = calibration.uuid;
    bgReading.raw_data = (raw_data / 1000);
    bgReading.filtered_data = (filtered_data / 1000);
    bgReading.timestamp = timestamp;
    bgReading.uuid = UUID.randomUUID().toString();
    bgReading.time_since_sensor_started = bgReading.timestamp - sensor.started_at;

    bgReading.calculateAgeAdjustedRawValue();

    if (calibration.check_in) {
        double firstAdjSlope = calibration.first_slope + (calibration.first_decay * (Math.ceil(new Date().getTime() - calibration.timestamp) / (1000 * 60 * 10)));
        double calSlope = (calibration.first_scale / firstAdjSlope) * 1000;
        double calIntercept = ((calibration.first_scale * calibration.first_intercept) / firstAdjSlope) * -1;
        bgReading.calculated_value = (((calSlope * bgReading.raw_data) + calIntercept) - 5);
        bgReading.filtered_calculated_value = (((calSlope * bgReading.ageAdjustedFiltered()) + calIntercept) - 5);

    } else {
        BgReading lastBgReading = BgReading.last();
        if (lastBgReading != null && lastBgReading.calibration != null) {
            Log.d(TAG, "Create calibration.uuid=" + calibration.uuid + " bgReading.uuid: " + bgReading.uuid + " lastBgReading.calibration_uuid: " + lastBgReading.calibration_uuid + " lastBgReading.calibration.uuid: " + lastBgReading.calibration.uuid);
            Log.d(TAG, "Create lastBgReading.calibration_flag=" + lastBgReading.calibration_flag + " bgReading.timestamp: " + bgReading.timestamp + " lastBgReading.timestamp: " + lastBgReading.timestamp + " lastBgReading.calibration.timestamp: " + lastBgReading.calibration.timestamp);
            Log.d(TAG, "Create lastBgReading.calibration_flag=" + lastBgReading.calibration_flag + " bgReading.timestamp: " + JoH.dateTimeText(bgReading.timestamp) + " lastBgReading.timestamp: " + JoH.dateTimeText(lastBgReading.timestamp) + " lastBgReading.calibration.timestamp: " + JoH.dateTimeText(lastBgReading.calibration.timestamp));
            if (lastBgReading.calibration_flag == true && ((lastBgReading.timestamp + (60000 * 20)) > bgReading.timestamp) && ((lastBgReading.calibration.timestamp + (60000 * 20)) > bgReading.timestamp)) {
                lastBgReading.calibration.rawValueOverride(BgReading.weightedAverageRaw(lastBgReading.timestamp, bgReading.timestamp, lastBgReading.calibration.timestamp, lastBgReading.age_adjusted_raw_value, bgReading.age_adjusted_raw_value), xdrip.getAppContext());
                newCloseSensorData();
            }
        }

        if ((bgReading.raw_data != 0) && (bgReading.raw_data * 2 == bgReading.filtered_data)) {
            Log.wtf(TAG, "Filtered data is exactly double raw - this is completely wrong - dead transmitter? - blocking glucose calculation");
            bgReading.calculated_value = 0;
            bgReading.filtered_calculated_value = 0;
            bgReading.hide_slope = true;
        } else if (!SensorSanity.isRawValueSane(bgReading.raw_data)) {
            Log.wtf(TAG, "Raw data fails sanity check! " + bgReading.raw_data);
            bgReading.calculated_value = 0;
            bgReading.filtered_calculated_value = 0;
            bgReading.hide_slope = true;
        } else {

            // calculate glucose number from raw
            final CalibrationAbstract.CalibrationData pcalibration;
            final CalibrationAbstract plugin = getCalibrationPluginFromPreferences(); // make sure do this only once

            if ((plugin != null) && ((pcalibration = plugin.getCalibrationData()) != null) && (Pref.getBoolean("use_pluggable_alg_as_primary", false))) {
                Log.d(TAG, "USING CALIBRATION PLUGIN AS PRIMARY!!!");
                if (plugin.isCalibrationSane(pcalibration)) {
                    bgReading.calculated_value = (pcalibration.slope * bgReading.age_adjusted_raw_value) + pcalibration.intercept;
                    bgReading.filtered_calculated_value = (pcalibration.slope * bgReading.ageAdjustedFiltered()) + calibration.intercept;
                } else {
                    UserError.Log.wtf(TAG, "Calibration plugin failed intercept sanity check: " + pcalibration.toS());
                    Home.toaststaticnext("Calibration plugin failed intercept sanity check");
                }
            } else {
                bgReading.calculated_value = ((calibration.slope * bgReading.age_adjusted_raw_value) + calibration.intercept);
                bgReading.filtered_calculated_value = ((calibration.slope * bgReading.ageAdjustedFiltered()) + calibration.intercept);
            }

            updateCalculatedValueToWithinMinMax(bgReading);
        }
    }

    // LimiTTer can send 12 to indicate problem with NFC reading.
    if ((!calibration.check_in) && (raw_data == 12) && (filtered_data == 12)) {
        // store the raw value for sending special codes, note updateCalculatedValue would try to nix it
        bgReading.calculated_value = raw_data;
        bgReading.filtered_calculated_value = filtered_data;
    }
    return  bgReading;
}
 
Example 20
Source File: BgReading.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
public static BgReading createFromRawNoSave(Sensor sensor, Calibration calibration, double raw_data, double filtered_data, long timestamp) {
    final BgReading bgReading = new BgReading();
    if (sensor == null) {
        sensor = Sensor.currentSensor();
        if (sensor == null) {
            return bgReading;
        }
    }
    if (calibration == null) {
        calibration = Calibration.lastValid();
        if (calibration == null) {
            return bgReading;
        }
    }

    bgReading.sensor = sensor;
    bgReading.sensor_uuid = sensor.uuid;
    bgReading.calibration = calibration;
    bgReading.calibration_uuid = calibration.uuid;
    bgReading.raw_data = (raw_data / 1000);
    bgReading.filtered_data = (filtered_data / 1000);
    bgReading.timestamp = timestamp;
    bgReading.uuid = UUID.randomUUID().toString();
    bgReading.time_since_sensor_started = bgReading.timestamp - sensor.started_at;

    bgReading.calculateAgeAdjustedRawValue();

    if (calibration.check_in) {
        double firstAdjSlope = calibration.first_slope + (calibration.first_decay * (Math.ceil(new Date().getTime() - calibration.timestamp) / (1000 * 60 * 10)));
        double calSlope = (calibration.first_scale / firstAdjSlope) * 1000;
        double calIntercept = ((calibration.first_scale * calibration.first_intercept) / firstAdjSlope) * -1;
        bgReading.calculated_value = (((calSlope * bgReading.raw_data) + calIntercept) - 5);
        bgReading.filtered_calculated_value = (((calSlope * bgReading.ageAdjustedFiltered()) + calIntercept) - 5);

    } else {
        BgReading lastBgReading = BgReading.last();
        if (lastBgReading != null && lastBgReading.calibration != null) {
            Log.d(TAG, "Create calibration.uuid=" + calibration.uuid + " bgReading.uuid: " + bgReading.uuid + " lastBgReading.calibration_uuid: " + lastBgReading.calibration_uuid + " lastBgReading.calibration.uuid: " + lastBgReading.calibration.uuid);
            Log.d(TAG, "Create lastBgReading.calibration_flag=" + lastBgReading.calibration_flag + " bgReading.timestamp: " + bgReading.timestamp + " lastBgReading.timestamp: " + lastBgReading.timestamp + " lastBgReading.calibration.timestamp: " + lastBgReading.calibration.timestamp);
            Log.d(TAG, "Create lastBgReading.calibration_flag=" + lastBgReading.calibration_flag + " bgReading.timestamp: " + JoH.dateTimeText(bgReading.timestamp) + " lastBgReading.timestamp: " + JoH.dateTimeText(lastBgReading.timestamp) + " lastBgReading.calibration.timestamp: " + JoH.dateTimeText(lastBgReading.calibration.timestamp));
            if (lastBgReading.calibration_flag == true && ((lastBgReading.timestamp + (60000 * 20)) > bgReading.timestamp) && ((lastBgReading.calibration.timestamp + (60000 * 20)) > bgReading.timestamp)) {
                lastBgReading.calibration.rawValueOverride(BgReading.weightedAverageRaw(lastBgReading.timestamp, bgReading.timestamp, lastBgReading.calibration.timestamp, lastBgReading.age_adjusted_raw_value, bgReading.age_adjusted_raw_value), xdrip.getAppContext());
                newCloseSensorData();
            }
        }

        if ((bgReading.raw_data != 0) && (bgReading.raw_data * 2 == bgReading.filtered_data)) {
            Log.wtf(TAG, "Filtered data is exactly double raw - this is completely wrong - dead transmitter? - blocking glucose calculation");
            bgReading.calculated_value = 0;
            bgReading.filtered_calculated_value = 0;
            bgReading.hide_slope = true;
        } else if (!SensorSanity.isRawValueSane(bgReading.raw_data)) {
            Log.wtf(TAG, "Raw data fails sanity check! " + bgReading.raw_data);
            bgReading.calculated_value = 0;
            bgReading.filtered_calculated_value = 0;
            bgReading.hide_slope = true;
        } else {

            // calculate glucose number from raw
            final CalibrationAbstract.CalibrationData pcalibration;
            final CalibrationAbstract plugin = getCalibrationPluginFromPreferences(); // make sure do this only once

            if ((plugin != null) && ((pcalibration = plugin.getCalibrationData()) != null) && (Pref.getBoolean("use_pluggable_alg_as_primary", false))) {
                Log.d(TAG, "USING CALIBRATION PLUGIN AS PRIMARY!!!");
                if (plugin.isCalibrationSane(pcalibration)) {
                    bgReading.calculated_value = (pcalibration.slope * bgReading.age_adjusted_raw_value) + pcalibration.intercept;
                    bgReading.filtered_calculated_value = (pcalibration.slope * bgReading.ageAdjustedFiltered()) + calibration.intercept;
                } else {
                    UserError.Log.wtf(TAG, "Calibration plugin failed intercept sanity check: " + pcalibration.toS());
                    Home.toaststaticnext("Calibration plugin failed intercept sanity check");
                }
            } else {
                bgReading.calculated_value = ((calibration.slope * bgReading.age_adjusted_raw_value) + calibration.intercept);
                bgReading.filtered_calculated_value = ((calibration.slope * bgReading.ageAdjustedFiltered()) + calibration.intercept);
            }

            updateCalculatedValueToWithinMinMax(bgReading);
        }
    }

    // LimiTTer can send 12 to indicate problem with NFC reading.
    if ((!calibration.check_in) && (raw_data == 12) && (filtered_data == 12)) {
        // store the raw value for sending special codes, note updateCalculatedValue would try to nix it
        bgReading.calculated_value = raw_data;
        bgReading.filtered_calculated_value = filtered_data;
    }
    return  bgReading;
}