Search in sources :

Example 1 with BleGattCharacteristicException

use of com.polidea.rxandroidble2.exceptions.BleGattCharacteristicException in project xDrip by NightscoutFoundation.

the class BlueJayService method sendTime.

// Not using packet queue due to reactive time sensitive nature
private void sendTime() {
    final String func = "SetTime";
    final SetTimeTx outbound = new SetTimeTx();
    UserError.Log.d(TAG, "Outbound: " + bytesToHex(outbound.getBytes()));
    I.connection.writeCharacteristic(THINJAM_WRITE, outbound.getBytes()).subscribe(response -> {
        SetTimeTx reply = new SetTimeTx(response);
        if (D)
            UserError.Log.d(TAG, func + " response: " + bytesToHex(response) + " " + reply.toS());
        UserError.Log.e(TAG, "Time difference with watch: " + ((outbound.getTimestamp() - reply.getTimestamp()) / 1000d));
        changeNextState();
    }, throwable -> {
        UserError.Log.e(TAG, "Failed to write " + func + " request: " + throwable);
        if (throwable instanceof BleGattCharacteristicException) {
            final int status = ((BleGattCharacteristicException) throwable).getStatus();
            UserError.Log.e(TAG, "Got status message: " + Helper.getStatusName(status));
        } else {
            UserError.Log.d(TAG, "Throwable in " + func + " " + throwable);
            if (throwable instanceof BleCharacteristicNotFoundException) {
                UserError.Log.d(TAG, "Assuming wrong firmware version");
                changeNextState();
            } else {
                changeState(CLOSE);
            }
        }
    });
}
Also used : BleGattCharacteristicException(com.polidea.rxandroidble2.exceptions.BleGattCharacteristicException) BleCharacteristicNotFoundException(com.polidea.rxandroidble2.exceptions.BleCharacteristicNotFoundException) SetTimeTx(com.eveningoutpost.dexdrip.watch.thinjam.messages.SetTimeTx) SuppressLint(android.annotation.SuppressLint) SlidingWindowConstraint(com.eveningoutpost.dexdrip.utils.time.SlidingWindowConstraint)

Example 2 with BleGattCharacteristicException

use of com.polidea.rxandroidble2.exceptions.BleGattCharacteristicException in project xDrip by NightscoutFoundation.

the class BlueJayService method requestBulk.

private synchronized void requestBulk(final ThinJamItem item) {
    if (item.buffer == null) {
        UserError.Log.d(TAG, "ThinJamItem buffer is null! " + item.toS());
        return;
    }
    if (item.inProgress) {
        UserError.Log.d(TAG, "Blocking duplicate request for in progress item: " + item.queuedTimestamp);
        return;
    }
    item.inProgress = true;
    final BulkUpRequestTx packet = new BulkUpRequestTx(item.type, item.getId(), BulkUpRequestTx.encodeLength(item.sequence, item.buffer.length), item.buffer, item.quiet);
    if (D)
        UserError.Log.d(TAG, "Bulk request request: " + item.sequence + " " + bytesToHex(packet.getBytes()));
    // value will get notification result itself
    if (I.connection == null) {
        item.inProgress = false;
        UserError.Log.d(TAG, "Connection is null skipping");
    }
    I.connection.writeCharacteristic(THINJAM_WRITE, packet.getBytes()).subscribe(response -> {
        if (D)
            UserError.Log.d(TAG, "Bulk request response: " + bytesToHex(response));
        if (packet.responseOk(response)) {
            lastBulkOk = tsl();
            UserError.Log.d(TAG, "Bulk channel opcode: " + packet.getBulkUpOpcode(response));
            bulkSend(packet.getBulkUpOpcode(response), item.buffer, 15, item.quiet);
        } else {
            UserError.Log.d(TAG, "Bulk request failed: " + packet.responseText(response));
            if (packet.responseText(response).toLowerCase().contains("busy") && item.retryCounterOk()) {
                UserError.Log.d(TAG, "Device is busy, scheduling retry");
                Inevitable.task("bulk-retry-" + item.toS(), 3000, () -> {
                    UserError.Log.d(TAG, "Retrying requestBulk: " + item.toS());
                    item.inProgress = false;
                    requestBulk(item);
                });
            } else if (packet.responseText(response).toLowerCase().contains("out of range") || packet.responseText(response).toLowerCase().contains("unknown error")) {
                UserError.Log.d(TAG, "Setting item to not retry again due to out of range");
                item.inProgress = false;
                item.dontRetryAgain();
                Inevitable.task("tj-next-queue", 0, this::processQueue);
            }
        }
        item.inProgress = false;
    }, throwable -> {
        UserError.Log.e(TAG, "Failed to write bulk request: " + throwable);
        if (throwable instanceof BleGattCharacteristicException) {
            final int status = ((BleGattCharacteristicException) throwable).getStatus();
            UserError.Log.e(TAG, "Got status message: " + Helper.getStatusName(status));
        } else {
            UserError.Log.d(TAG, "Throwable in Bulk End write: " + throwable);
        }
        item.inProgress = false;
    });
}
Also used : BleGattCharacteristicException(com.polidea.rxandroidble2.exceptions.BleGattCharacteristicException) BulkUpRequestTx(com.eveningoutpost.dexdrip.watch.thinjam.messages.BulkUpRequestTx) SuppressLint(android.annotation.SuppressLint) SlidingWindowConstraint(com.eveningoutpost.dexdrip.utils.time.SlidingWindowConstraint)

Example 3 with BleGattCharacteristicException

use of com.polidea.rxandroidble2.exceptions.BleGattCharacteristicException in project xDrip by NightscoutFoundation.

the class BlueJayService method bulkSend.

// write the data packets
private void bulkSend(final int opcode, final byte[] buffer, final int offset, boolean quiet) {
    UserError.Log.d(TAG, "bulksend called: opcode " + opcode + " total " + buffer.length + " offset: " + offset + " quiet:" + quiet);
    if (buffer != null && offset < buffer.length) {
        final BulkUpTx packet = (opcode >= OPCODE_BULK_R_XFER_0 ? new RBulkUpTx(opcode, buffer, offset) : new BulkUpTx(opcode, buffer, offset));
        if (quiet) {
            packet.setQuiet();
        }
        if (offset == 0) {
            // reset counter as this is new bulk up
            revisedOffset = 0;
            lastActionedRevisedOffset = -1;
        // TODO we should check it if we have failed to act on revised offset
        }
        I.connection.writeCharacteristic(quiet ? THINJAM_BULK : THINJAM_WRITE, packet.getBytes()).observeOn(Schedulers.newThread()).subscribe(response -> {
            if (D)
                UserError.Log.d(TAG, "Bulk Up Send response: " + bytesToHex(response));
            if (packet.responseOk(response)) {
                // WARNING recursion
                final int nextOffset;
                if (revisedOffset != 0 && revisedOffset < offset && revisedOffset != lastActionedRevisedOffset) {
                    // TODO we only catch this if we send a packet
                    nextOffset = revisedOffset;
                    lastActionedRevisedOffset = nextOffset;
                    UserError.Log.d(TAG, "Retrying bulk send from: " + nextOffset);
                } else {
                    nextOffset = offset + packet.getBytesIncluded();
                }
                revisedOffset = 0;
                if (nextOffset < buffer.length) {
                    if (!quiet) {
                        JoH.threadSleep(100);
                    } else {
                        JoH.threadSleep(1);
                    }
                    bulkSend(opcode, buffer, nextOffset, packet.isQuiet());
                } else {
                    UserError.Log.d(TAG, "Bulk send completed!");
                    if (!(packet instanceof RBulkUpTx)) {
                        // removes first item from the queue which should be the one we just processed!
                        commandQueue.poll();
                        // 
                        Inevitable.task("tj-next-queue", 10, this::processQueue);
                    } else {
                        // wait 1 second and then retry this upload if we get success reply notification then we remove it elsewhere
                        Inevitable.task("tj-next-queue", 4000, this::processQueue);
                    }
                }
            } else {
                UserError.Log.d(TAG, "Bulk Send failed: " + packet.responseText(response));
                if (!quiet) {
                    // retry shortly
                    Inevitable.task("tj-next-queue", 20000, this::processQueue);
                    if (JoH.ratelimit("tj-allow-bulk-retry", 2)) {
                        UserError.Log.d(TAG, "Retrying packet");
                        // retry packet send
                        bulkSend(opcode, buffer, offset, quiet);
                    }
                } else {
                    UserError.Log.d(TAG, "Quiet is set so not attempting any response to failure here");
                }
            }
        }, throwable -> {
            UserError.Log.e(TAG, "Failed to write bulk Send: " + throwable);
            if (throwable instanceof BleGattCharacteristicException) {
                final int status = ((BleGattCharacteristicException) throwable).getStatus();
                UserError.Log.e(TAG, "Got status message: " + Helper.getStatusName(status));
            } else {
                UserError.Log.d(TAG, "Throwable in Bulk SEnd write: " + throwable);
            }
        });
    } else {
        UserError.Log.d(TAG, "Invalid buffer in bulkSend");
        Inevitable.task("tj-next-queue", 4000, this::processQueue);
    }
}
Also used : BleGattCharacteristicException(com.polidea.rxandroidble2.exceptions.BleGattCharacteristicException) RBulkUpTx(com.eveningoutpost.dexdrip.watch.thinjam.messages.RBulkUpTx) SuppressLint(android.annotation.SuppressLint) SlidingWindowConstraint(com.eveningoutpost.dexdrip.utils.time.SlidingWindowConstraint) BulkUpTx(com.eveningoutpost.dexdrip.watch.thinjam.messages.BulkUpTx) RBulkUpTx(com.eveningoutpost.dexdrip.watch.thinjam.messages.RBulkUpTx)

Example 4 with BleGattCharacteristicException

use of com.polidea.rxandroidble2.exceptions.BleGattCharacteristicException in project xDrip by NightscoutFoundation.

the class Ob1G5StateMachine method doGetData.

// Get Data
@SuppressLint("CheckResult")
public static boolean doGetData(Ob1G5CollectionService parent, RxBleConnection connection) {
    if (connection == null)
        return false;
    // TODO switch modes depending on conditions as to whether we are using internal
    final boolean use_g5_internal_alg = Pref.getBooleanDefaultFalse("ob1_g5_use_transmitter_alg");
    UserError.Log.d(TAG, use_g5_internal_alg ? ("Requesting Glucose Data " + (usingG6() ? "G6" : "G5")) : "Requesting Sensor Data");
    if (!use_g5_internal_alg) {
        // not applicable
        parent.lastSensorStatus = null;
        parent.lastUsableGlucosePacketTime = 0;
    }
    connection.setupIndication(Control).doOnNext(notificationObservable -> {
        if (d)
            UserError.Log.d(TAG, "Notifications enabled");
        speakSlowly();
        connection.writeCharacteristic(Control, nn(use_g5_internal_alg ? (getEGlucose() ? new EGlucoseTxMessage().byteSequence : new GlucoseTxMessage().byteSequence) : new SensorTxMessage().byteSequence)).subscribe(characteristicValue -> {
            if (d)
                UserError.Log.d(TAG, "Wrote SensorTxMessage request");
        }, throwable -> {
            UserError.Log.e(TAG, "Failed to write SensorTxMessage: " + throwable);
            if (throwable instanceof BleGattCharacteristicException) {
                final int status = ((BleGattCharacteristicException) throwable).getStatus();
                UserError.Log.e(TAG, "Got status message: " + getStatusName(status));
                if (status == 8) {
                    UserError.Log.e(TAG, "Request rejected due to Insufficient Authorization failure!");
                    parent.authResult(false);
                }
            }
        });
    }).flatMap(notificationObservable -> notificationObservable).timeout(6, TimeUnit.SECONDS).subscribe(bytes -> {
        // incoming data notifications
        UserError.Log.d(TAG, "Received indication bytes: " + JoH.bytesToHex(bytes));
        final PacketShop data_packet = classifyPacket(bytes);
        switch(data_packet.type) {
            case SensorRxMessage:
                try {
                    checkVersionAndBattery(parent, connection);
                } finally {
                    processSensorRxMessage((SensorRxMessage) data_packet.msg);
                    parent.msg("Got data");
                    parent.updateLast(tsl());
                    parent.clearErrors();
                }
                break;
            case VersionRequest1RxMessage:
                if (!setStoredFirmwareBytes(getTransmitterID(), 1, bytes, true)) {
                    UserError.Log.e(TAG, "Could not save out firmware version!");
                }
                nextBackFillCheckSize = BACKFILL_CHECK_LARGE;
                if (JoH.ratelimit("g6-evaluate", 600)) {
                    Inevitable.task("evaluteG6Settings", 10000, () -> evaluateG6Settings());
                }
                break;
            case VersionRequestRxMessage:
                if (!setStoredFirmwareBytes(getTransmitterID(), 0, bytes, true)) {
                    UserError.Log.e(TAG, "Could not save out firmware version!");
                }
                nextBackFillCheckSize = BACKFILL_CHECK_LARGE;
                if (JoH.ratelimit("g6-evaluate", 600)) {
                    Inevitable.task("evaluteG6Settings", 10000, () -> evaluateG6Settings());
                }
                break;
            case VersionRequest2RxMessage:
                if (!setStoredFirmwareBytes(getTransmitterID(), 2, bytes, true)) {
                    UserError.Log.e(TAG, "Could not save out firmware version!");
                }
                nextBackFillCheckSize = BACKFILL_CHECK_LARGE;
                if (JoH.ratelimit("g6-evaluate", 600)) {
                    Inevitable.task("evaluteG6Settings", 10000, () -> evaluateG6Settings());
                }
                break;
            case BatteryInfoRxMessage:
                if (!setStoredBatteryBytes(getTransmitterID(), bytes)) {
                    UserError.Log.e(TAG, "Could not save out battery data!");
                } else {
                    if (parent.android_wear) {
                        PersistentStore.setBoolean(G5_BATTERY_WEARABLE_SEND, true);
                    }
                }
                nextBackFillCheckSize = BACKFILL_CHECK_LARGE;
                break;
            case SessionStartRxMessage:
                final SessionStartRxMessage session_start = (SessionStartRxMessage) data_packet.msg;
                if (session_start.isOkay()) {
                    // TODO persist this
                    parent.msg("Session Started Successfully: " + JoH.dateTimeText(session_start.getSessionStart()) + " " + JoH.dateTimeText(session_start.getRequestedStart()) + " " + JoH.dateTimeText(session_start.getTransmitterTime()));
                    DexResetHelper.cancel();
                } else {
                    final String msg = "Session Start Failed: " + session_start.message();
                    parent.msg(msg);
                    UserError.Log.ueh(TAG, msg);
                    JoH.showNotification(devName() + " Start Failed", msg, null, Constants.G5_START_REJECT, true, true, false);
                    UserError.Log.ueh(TAG, "Session Start failed info: " + JoH.dateTimeText(session_start.getSessionStart()) + " " + JoH.dateTimeText(session_start.getRequestedStart()) + " " + JoH.dateTimeText(session_start.getTransmitterTime()));
                    if (session_start.isFubar()) {
                        final long tk = DexTimeKeeper.getDexTime(getTransmitterID(), tsl());
                        if (tk > 0) {
                            DexResetHelper.offer("Unusual session start failure, is transmitter crashed? Try Hard Reset?");
                        } else {
                            UserError.Log.e(TAG, "No reset as TimeKeeper reports invalid: " + tk);
                        }
                    }
                    if (Pref.getBooleanDefaultFalse("ob1_g5_restart_sensor") && (Sensor.isActive())) {
                        if (pratelimit("secondary-g5-start", 1800)) {
                            UserError.Log.ueh(TAG, "Trying to Start sensor again");
                            startSensor(tsl());
                        }
                    }
                }
                reReadGlucoseData();
                break;
            case SessionStopRxMessage:
                final SessionStopRxMessage session_stop = (SessionStopRxMessage) data_packet.msg;
                if (session_stop.isOkay()) {
                    // TODO persist this
                    final String msg = "Session Stopped Successfully: " + JoH.dateTimeText(session_stop.getSessionStart()) + " " + JoH.dateTimeText(session_stop.getSessionStop());
                    parent.msg(msg);
                    UserError.Log.ueh(TAG, msg);
                    reReadGlucoseData();
                    enqueueUniqueCommand(new TimeTxMessage(), "Query time after stop");
                } else {
                    // TODO what does an error when session isn't started look like? Probably best to downgrade those somewhat
                    final String msg = "Session Stop Failed: packet valid: " + session_stop.isValid() + "  Status code: " + session_stop.getStatus();
                    UserError.Log.uel(TAG, msg);
                }
                break;
            case GlucoseRxMessage:
                final GlucoseRxMessage glucose = (GlucoseRxMessage) data_packet.msg;
                parent.processCalibrationState(glucose.calibrationState());
                if (glucose.usable()) {
                    parent.msg("Got " + devName() + " glucose");
                } else {
                    parent.msg("Got data from " + devName());
                }
                glucoseRxCommon(glucose, parent, connection);
                break;
            // TODO base class duplication
            case EGlucoseRxMessage:
                final EGlucoseRxMessage eglucose = (EGlucoseRxMessage) data_packet.msg;
                parent.processCalibrationState(eglucose.calibrationState());
                if (eglucose.usable()) {
                    parent.msg("Got G6 glucose");
                } else {
                    parent.msg("Got data from G6");
                }
                glucoseRxCommon(eglucose, parent, connection);
                break;
            case CalibrateRxMessage:
                final CalibrateRxMessage calibrate = (CalibrateRxMessage) data_packet.msg;
                if (calibrate.accepted()) {
                    parent.msg("Calibration accepted");
                    UserError.Log.ueh(TAG, "Calibration accepted by transmitter");
                } else {
                    final String msg = "Calibration rejected: " + calibrate.message();
                    UserError.Log.wtf(TAG, msg);
                    parent.msg(msg);
                    JoH.showNotification("Calibration rejected", msg, null, Constants.G5_CALIBRATION_REJECT, true, true, false);
                }
                reReadGlucoseData();
                break;
            case BackFillRxMessage:
                final BackFillRxMessage backfill = (BackFillRxMessage) data_packet.msg;
                if (backfill.valid()) {
                    UserError.Log.d(TAG, "Backfill request confirmed");
                } else {
                    UserError.Log.wtf(TAG, "Backfill request corrupted!");
                }
                break;
            case TransmitterTimeRxMessage:
                // This message is received every 120-125m
                final TransmitterTimeRxMessage txtime = (TransmitterTimeRxMessage) data_packet.msg;
                DexTimeKeeper.updateAge(getTransmitterID(), txtime.getCurrentTime(), true);
                if (txtime.sessionInProgress()) {
                    UserError.Log.e(TAG, "Session start time reports: " + JoH.dateTimeText(txtime.getRealSessionStartTime()) + " Duration: " + JoH.niceTimeScalar(txtime.getSessionDuration()));
                    DexSessionKeeper.setStart(txtime.getRealSessionStartTime());
                } else {
                    UserError.Log.e(TAG, "Session start time reports: No session in progress");
                    DexSessionKeeper.clearStart();
                }
                if (Pref.getBooleanDefaultFalse("ob1_g5_preemptive_restart")) {
                    int restartDaysThreshold = usingG6() ? 9 : 6;
                    if (txtime.getSessionDuration() > Constants.DAY_IN_MS * restartDaysThreshold && txtime.getSessionDuration() < Constants.MONTH_IN_MS) {
                        UserError.Log.uel(TAG, "Requesting preemptive session restart");
                        restartSensorWithTimeTravel();
                    }
                }
                break;
            case F2DUnknownRxMessage:
                UserError.Log.d(TAG, "Received F2D message");
                try {
                    checkVersionAndBattery(parent, connection);
                } finally {
                    parent.msg("Got no raw");
                    // TODO verify if this is ok to do here
                    parent.updateLast(tsl());
                    // TODO verify if this is ok to do here
                    parent.clearErrors();
                }
                break;
            default:
                UserError.Log.e(TAG, "Got unknown packet rx: " + JoH.bytesToHex(bytes));
                break;
        }
        if (!queued(parent, connection)) {
            inevitableDisconnect(parent, connection);
        }
    }, throwable -> {
        if (!(throwable instanceof OperationSuccess)) {
            if (throwable instanceof BleDisconnectedException) {
                UserError.Log.d(TAG, "Disconnected when waiting to receive indication: " + throwable);
                parent.changeState(Ob1G5CollectionService.STATE.CLOSE);
            } else {
                UserError.Log.e(TAG, "Error receiving indication: " + throwable);
                // throwable.printStackTrace();
                disconnectNow(parent, connection);
            }
        }
    });
    return true;
}
Also used : PersistentStore(com.eveningoutpost.dexdrip.UtilityModels.PersistentStore) Treatments(com.eveningoutpost.dexdrip.Models.Treatments) Arrays(java.util.Arrays) com.eveningoutpost.dexdrip.xdrip(com.eveningoutpost.dexdrip.xdrip) TypeToken(com.google.gson.reflect.TypeToken) Date(java.util.Date) TimeoutException(java.util.concurrent.TimeoutException) SecretKeySpec(javax.crypto.spec.SecretKeySpec) G5_BATTERY_FROM_MARKER(com.eveningoutpost.dexdrip.Services.G5BaseService.G5_BATTERY_FROM_MARKER) Inevitable(com.eveningoutpost.dexdrip.UtilityModels.Inevitable) BleCannotSetCharacteristicNotificationException(com.polidea.rxandroidble2.exceptions.BleCannotSetCharacteristicNotificationException) Pref(com.eveningoutpost.dexdrip.UtilityModels.Pref) PowerManager(android.os.PowerManager) Authentication(com.eveningoutpost.dexdrip.G5Model.BluetoothServices.Authentication) NotificationChannels(com.eveningoutpost.dexdrip.UtilityModels.NotificationChannels) SensorSanity(com.eveningoutpost.dexdrip.Models.SensorSanity) BleGattCharacteristicException(com.polidea.rxandroidble2.exceptions.BleGattCharacteristicException) Schedulers(io.reactivex.schedulers.Schedulers) DEXCOM_PERIOD(com.eveningoutpost.dexdrip.UtilityModels.BgGraphBuilder.DEXCOM_PERIOD) DAY_IN_MS(com.eveningoutpost.dexdrip.UtilityModels.Constants.DAY_IN_MS) G5_BATTERY_WEARABLE_SEND(com.eveningoutpost.dexdrip.Services.G5BaseService.G5_BATTERY_WEARABLE_SEND) BgReading(com.eveningoutpost.dexdrip.Models.BgReading) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) Ob1G5CollectionService.android_wear(com.eveningoutpost.dexdrip.Services.Ob1G5CollectionService.android_wear) Ob1G5CollectionService.wear_broadcast(com.eveningoutpost.dexdrip.Services.Ob1G5CollectionService.wear_broadcast) TransmitterData(com.eveningoutpost.dexdrip.Models.TransmitterData) BluetoothGatt(android.bluetooth.BluetoothGatt) JoH(com.eveningoutpost.dexdrip.Models.JoH) List(java.util.List) BleDisconnectedException(com.polidea.rxandroidble2.exceptions.BleDisconnectedException) Type(java.lang.reflect.Type) R(com.eveningoutpost.dexdrip.R) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Ob1G5CollectionService(com.eveningoutpost.dexdrip.Services.Ob1G5CollectionService) InvalidKeyException(java.security.InvalidKeyException) Home(com.eveningoutpost.dexdrip.Home) BgGraphBuilder(com.eveningoutpost.dexdrip.UtilityModels.BgGraphBuilder) UnsupportedEncodingException(java.io.UnsupportedEncodingException) G5_FIRMWARE_MARKER(com.eveningoutpost.dexdrip.Services.G5BaseService.G5_FIRMWARE_MARKER) Sensor(com.eveningoutpost.dexdrip.Models.Sensor) Constants(com.eveningoutpost.dexdrip.UtilityModels.Constants) Helper.getStatusName(com.eveningoutpost.dexdrip.utils.bt.Helper.getStatusName) RxBleConnection(com.polidea.rxandroidble2.RxBleConnection) HOUR_IN_MS(com.eveningoutpost.dexdrip.UtilityModels.Constants.HOUR_IN_MS) Cipher(javax.crypto.Cipher) HexDump(com.eveningoutpost.dexdrip.ImportedLibraries.usbserial.util.HexDump) ArrayList(java.util.ArrayList) SuppressLint(android.annotation.SuppressLint) Prediction(com.eveningoutpost.dexdrip.Models.Prediction) G5_BATTERY_MARKER(com.eveningoutpost.dexdrip.Services.G5BaseService.G5_BATTERY_MARKER) BestGlucose(com.eveningoutpost.dexdrip.BestGlucose) JoH.tsl(com.eveningoutpost.dexdrip.Models.JoH.tsl) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) Build(android.os.Build) Notifications(com.eveningoutpost.dexdrip.UtilityModels.Notifications) Ob1G5CollectionService.onlyUsingNativeMode(com.eveningoutpost.dexdrip.Services.Ob1G5CollectionService.onlyUsingNativeMode) WholeHouse(com.eveningoutpost.dexdrip.UtilityModels.WholeHouse) ProbablyBackfill(com.eveningoutpost.dexdrip.G5Model.BluetoothServices.ProbablyBackfill) Control(com.eveningoutpost.dexdrip.G5Model.BluetoothServices.Control) JoH.msSince(com.eveningoutpost.dexdrip.Models.JoH.msSince) Mimeograph(com.eveningoutpost.dexdrip.utils.bt.Mimeograph) TimeUnit(java.util.concurrent.TimeUnit) PowerStateReceiver(com.eveningoutpost.dexdrip.utils.PowerStateReceiver) BadPaddingException(javax.crypto.BadPaddingException) G5_BATTERY_LEVEL_MARKER(com.eveningoutpost.dexdrip.Services.G5BaseService.G5_BATTERY_LEVEL_MARKER) BroadcastGlucose(com.eveningoutpost.dexdrip.UtilityModels.BroadcastGlucose) DexCollectionType(com.eveningoutpost.dexdrip.utils.DexCollectionType) JoH.pratelimit(com.eveningoutpost.dexdrip.Models.JoH.pratelimit) SECOND_IN_MS(com.eveningoutpost.dexdrip.UtilityModels.Constants.SECOND_IN_MS) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) WatchUpdaterService(com.eveningoutpost.dexdrip.wearintegration.WatchUpdaterService) Ob1G5CollectionService.getTransmitterID(com.eveningoutpost.dexdrip.Services.Ob1G5CollectionService.getTransmitterID) UserError(com.eveningoutpost.dexdrip.Models.UserError) MINUTE_IN_MS(com.eveningoutpost.dexdrip.UtilityModels.Constants.MINUTE_IN_MS) SuppressLint(android.annotation.SuppressLint) BleGattCharacteristicException(com.polidea.rxandroidble2.exceptions.BleGattCharacteristicException) BleDisconnectedException(com.polidea.rxandroidble2.exceptions.BleDisconnectedException) SuppressLint(android.annotation.SuppressLint)

Example 5 with BleGattCharacteristicException

use of com.polidea.rxandroidble2.exceptions.BleGattCharacteristicException in project xDrip-plus by jamorham.

the class BlueJayService method requestBulk.

private synchronized void requestBulk(final ThinJamItem item) {
    if (item.buffer == null) {
        UserError.Log.d(TAG, "ThinJamItem buffer is null! " + item.toS());
        return;
    }
    if (item.inProgress) {
        UserError.Log.d(TAG, "Blocking duplicate request for in progress item: " + item.queuedTimestamp);
        return;
    }
    item.inProgress = true;
    final BulkUpRequestTx packet = new BulkUpRequestTx(item.type, item.getId(), BulkUpRequestTx.encodeLength(item.sequence, item.buffer.length), item.buffer, item.quiet);
    if (D)
        UserError.Log.d(TAG, "Bulk request request: " + item.sequence + " " + bytesToHex(packet.getBytes()));
    // value will get notification result itself
    if (I.connection == null) {
        item.inProgress = false;
        UserError.Log.d(TAG, "Connection is null skipping");
    }
    I.connection.writeCharacteristic(THINJAM_WRITE, packet.getBytes()).subscribe(response -> {
        if (D)
            UserError.Log.d(TAG, "Bulk request response: " + bytesToHex(response));
        if (packet.responseOk(response)) {
            lastBulkOk = tsl();
            UserError.Log.d(TAG, "Bulk channel opcode: " + packet.getBulkUpOpcode(response));
            bulkSend(packet.getBulkUpOpcode(response), item.buffer, 15, item.quiet);
        } else {
            UserError.Log.d(TAG, "Bulk request failed: " + packet.responseText(response));
            if (packet.responseText(response).toLowerCase().contains("busy") && item.retryCounterOk()) {
                UserError.Log.d(TAG, "Device is busy, scheduling retry");
                Inevitable.task("bulk-retry-" + item.toS(), 3000, () -> {
                    UserError.Log.d(TAG, "Retrying requestBulk: " + item.toS());
                    item.inProgress = false;
                    requestBulk(item);
                });
            } else if (packet.responseText(response).toLowerCase().contains("out of range") || packet.responseText(response).toLowerCase().contains("unknown error")) {
                UserError.Log.d(TAG, "Setting item to not retry again due to out of range");
                item.inProgress = false;
                item.dontRetryAgain();
                Inevitable.task("tj-next-queue", 0, this::processQueue);
            }
        }
        item.inProgress = false;
    }, throwable -> {
        UserError.Log.e(TAG, "Failed to write bulk request: " + throwable);
        if (throwable instanceof BleGattCharacteristicException) {
            final int status = ((BleGattCharacteristicException) throwable).getStatus();
            UserError.Log.e(TAG, "Got status message: " + Helper.getStatusName(status));
        } else {
            UserError.Log.d(TAG, "Throwable in Bulk End write: " + throwable);
        }
        item.inProgress = false;
    });
}
Also used : BleGattCharacteristicException(com.polidea.rxandroidble2.exceptions.BleGattCharacteristicException) BulkUpRequestTx(com.eveningoutpost.dexdrip.watch.thinjam.messages.BulkUpRequestTx) SuppressLint(android.annotation.SuppressLint) SlidingWindowConstraint(com.eveningoutpost.dexdrip.utils.time.SlidingWindowConstraint)

Aggregations

BleGattCharacteristicException (com.polidea.rxandroidble2.exceptions.BleGattCharacteristicException)14 SuppressLint (android.annotation.SuppressLint)12 SlidingWindowConstraint (com.eveningoutpost.dexdrip.utils.time.SlidingWindowConstraint)10 BleDisconnectedException (com.polidea.rxandroidble2.exceptions.BleDisconnectedException)6 Build (android.os.Build)4 PowerManager (android.os.PowerManager)4 HexDump (com.eveningoutpost.dexdrip.ImportedLibraries.usbserial.util.HexDump)4 JoH (com.eveningoutpost.dexdrip.Models.JoH)4 JoH.msSince (com.eveningoutpost.dexdrip.Models.JoH.msSince)4 UserError (com.eveningoutpost.dexdrip.Models.UserError)4 R (com.eveningoutpost.dexdrip.R)4 TargetApi (android.annotation.TargetApi)2 PendingIntent (android.app.PendingIntent)2 BluetoothDevice (android.bluetooth.BluetoothDevice)2 BOND_BONDED (android.bluetooth.BluetoothDevice.BOND_BONDED)2 BOND_NONE (android.bluetooth.BluetoothDevice.BOND_NONE)2 BluetoothGatt (android.bluetooth.BluetoothGatt)2 BluetoothGattCharacteristic (android.bluetooth.BluetoothGattCharacteristic)2 BluetoothGattService (android.bluetooth.BluetoothGattService)2 Intent (android.content.Intent)2