use of com.polidea.rxandroidble2.exceptions.BleDisconnectedException 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;
}
use of com.polidea.rxandroidble2.exceptions.BleDisconnectedException in project xDrip-plus by jamorham.
the class MiBandService method authPhase.
@SuppressLint("CheckResult")
private void authPhase() {
extendWakeLock(30000);
RxBleConnection connection = I.connection;
if (d)
UserError.Log.d(TAG, "Authorizing");
if (I.connection == null) {
if (d)
UserError.Log.d(TAG, "Cannot enable as connection is null!");
return;
}
String authKey = MiBand.getPersistentAuthKey();
if (MiBand.getMibandType() == MI_BAND4) {
if (authKey.isEmpty()) {
authKey = MiBand.getAuthKey();
if (authKey.isEmpty()) {
authKey = AuthMessages.getAuthCodeFromFilesSystem(MiBand.getMac());
}
if (!AuthMessages.isValidAuthKey(authKey)) {
JoH.static_toast_long("Wrong miband authorization key, please recheck a key and try to reconnect again");
changeState(AUTHORIZE_FAILED);
return;
} else {
MiBand.setAuthKey(authKey);
}
}
}
if (!AuthMessages.isValidAuthKey(authKey)) {
authKey = "";
}
if (d)
UserError.Log.d(TAG, "authKey: " + authKey);
authorisation = new AuthMessages(MiBand.getMibandType(), authKey);
if (d)
UserError.Log.d(TAG, "localKey: " + JoH.bytesToHex(authorisation.getLocalKey()));
authSubscription = new Subscription(connection.setupNotification(authorisation.getCharacteristicUUID()).timeout(20, // WARN
TimeUnit.SECONDS).doOnNext(notificationObservable -> {
if (d)
UserError.Log.d(TAG, "Notification for auth enabled");
if (MiBand.isAuthenticated()) {
// get random key from band
connection.writeCharacteristic(authorisation.getCharacteristicUUID(), authorisation.getAuthKeyRequest()).subscribe(val -> {
if (d)
UserError.Log.d(TAG, "Wrote getAuthKeyRequest: " + JoH.bytesToHex(val));
}, throwable -> {
UserError.Log.e(TAG, "Could not getAuthKeyRequest: " + throwable);
});
} else {
connection.writeCharacteristic(authorisation.getCharacteristicUUID(), authorisation.getAuthCommand()).subscribe(characteristicValue -> {
UserError.Log.d(TAG, "Wrote getAuthCommand, got: " + JoH.bytesToHex(characteristicValue));
}, throwable -> {
UserError.Log.e(TAG, "Could not write getAuthCommand: " + throwable);
});
}
}).flatMap(notificationObservable -> notificationObservable).subscribe(bytes -> {
// incoming notifications
if (d)
UserError.Log.d(TAG, "Received auth notification bytes: " + bytesToHex(bytes));
ProcessAuthCommands(connection, bytes);
// changeNextState();
}, throwable -> {
UserError.Log.d(TAG, "Throwable in Record Notification: " + throwable);
if (throwable instanceof BleCharacteristicNotFoundException) {
// maybe legacy - ignore for now but needs better handling
UserError.Log.d(TAG, "Characteristic not found for notification");
} else if (throwable instanceof BleCannotSetCharacteristicNotificationException) {
UserError.Log.e(TAG, "Problems setting notifications - disconnecting");
} else if (throwable instanceof BleDisconnectedException) {
UserError.Log.d(TAG, "Disconnected while enabling notifications");
} else if (throwable instanceof TimeoutException) {
// check if it is normal timeout
if (!MiBand.isAuthenticated()) {
String errorText = "MiBand authentication failed due to authentication timeout. When your Mi Band vibrates and blinks, tap it a few times in a row.";
UserError.Log.d(TAG, errorText);
JoH.static_toast_long(errorText);
}
}
if (authSubscription != null) {
authSubscription.unsubscribe();
}
changeState(CLOSE);
}));
}
use of com.polidea.rxandroidble2.exceptions.BleDisconnectedException in project xDrip-plus by jamorham.
the class BlueJayService method sendOtaChunk.
boolean sendOtaChunk(final UUID uuid, final byte[] bytes) {
if (I.connection == null || !I.isConnected)
return false;
I.connection.writeCharacteristic(uuid, bytes).observeOn(Schedulers.io()).subscribeOn(Schedulers.io()).subscribe(characteristicValue -> {
if (D)
UserError.Log.d(TAG, "Wrote record request request: " + bytesToHex(characteristicValue));
busy = false;
}, throwable -> {
UserError.Log.e(TAG, "Failed to write record request: " + throwable);
if (throwable instanceof BleGattCharacteristicException) {
final int status = ((BleGattCharacteristicException) throwable).getStatus();
UserError.Log.e(TAG, "Got status message: " + Helper.getStatusName(status));
} else {
if (throwable instanceof BleDisconnectedException) {
changeState(CLOSE);
}
UserError.Log.d(TAG, "Throwable in Record End write: " + throwable);
}
});
// only that we didn't fail in setup
return true;
}
use of com.polidea.rxandroidble2.exceptions.BleDisconnectedException in project xDrip-plus by jamorham.
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;
}
use of com.polidea.rxandroidble2.exceptions.BleDisconnectedException in project xDrip by NightscoutFoundation.
the class BlueJayService method enableNotifications.
private void enableNotifications() {
UserError.Log.d(TAG, "enableNotifications called()");
if (I.isNotificationEnabled) {
UserError.Log.d(TAG, "Notifications already enabled");
changeNextState();
return;
}
if (notificationSubscription != null) {
notificationSubscription.unsubscribe();
}
JoH.threadSleep(500);
UserError.Log.d(TAG, "Requesting to enable notifications");
if (I.connection == null) {
UserError.Log.d(TAG, "Connection went away before we could enable notifications");
return;
}
notificationSubscription = new Subscription(I.connection.setupNotification(THINJAM_WRITE).observeOn(// needed?
Schedulers.newThread()).doOnNext(notificationObservable -> {
UserError.Log.d(TAG, "Notifications enabled");
I.connection.writeCharacteristic(THINJAM_BULK, new byte[] { 0x55 });
// Debug sleep to make sure notifications are actually enabled???
JoH.threadSleep(500);
I.isNotificationEnabled = true;
changeNextState();
}).flatMap(notificationObservable -> notificationObservable).observeOn(Schedulers.newThread()).subscribe(bytes -> {
// incoming notifications
UserError.Log.d(TAG, "Received notification bytes: " + JoH.bytesToHex(bytes));
val pushRx = PushRx.parse(bytes);
if (pushRx != null) {
UserError.Log.d(TAG, "Received PushRX: " + pushRx.toS());
getInfo().processPushRx(pushRx);
processPushRxActions(pushRx);
} else if (bytes[0] == 0x06) {
// TODO move this to parsed response
final int replyParam = ((int) bytes[1]) & 0xff;
if (replyParam == 0) {
UserError.Log.d(TAG, "Bulk up success reply marker received! - removing queue head item");
// removes first item from the queue which should be the one we just processed!
commandQueue.poll();
UserError.Log.d(TAG, "Scheduling immediate run of queue");
// remove timeout retry task
Inevitable.kill("tj-next-queue");
Inevitable.task("tj-next-queue", 0, this::processQueue);
} else {
revisedOffset = replyParam;
// race condition on display
UserError.Log.d(TAG, "Bulk up failure at: " + revisedOffset);
}
} else if (bytes[0] == (byte) 0xFE) {
audioStreamCallBack(bytes);
} else {
if (ThinJamActivity.isD()) {
notificationString.append(new String(bytes));
Inevitable.task("tj update notifi", 250, new Runnable() {
@Override
public void run() {
stringObservableField.set(notificationString.toString());
}
});
}
}
}, throwable -> {
UserError.Log.d(TAG, "Throwable in Record Notification: " + throwable);
I.isNotificationEnabled = false;
if (throwable instanceof BleCharacteristicNotFoundException) {
// maybe legacy - ignore for now but needs better handling
UserError.Log.d(TAG, "Characteristic not found for notification");
debug.processTestSuite("logcharerror");
tryGattRefresh(getI().connection);
}
if (throwable instanceof BleCannotSetCharacteristicNotificationException) {
UserError.Log.e(TAG, "Problems setting notifications - disconnecting");
changeState(CLOSE);
}
if (throwable instanceof BleDisconnectedException) {
UserError.Log.d(TAG, "Disconnected while enabling notifications");
changeState(CLOSE);
}
}));
}
Aggregations