use of com.eveningoutpost.dexdrip.utils.bt.Subscription in project xDrip by NightscoutFoundation.
the class PendiqService method connect_to_device.
private synchronized void connect_to_device(boolean auto) {
if ((state == CONNECT) || (state == STATE.CONNECT_NOW)) {
// TODO check mac
if (address != null) {
// msg("Connect request");
if (state == STATE.CONNECT_NOW) {
if (connection_linger != null)
JoH.releaseWakeLock(connection_linger);
connection_linger = JoH.getWakeLock("jam-pendiq-pconnect", 60000);
}
// if (d)
// UserError.Log.d(TAG, "Local bonding state: " + (isDeviceLocallyBonded() ? "BONDED" : "NOT Bonded"));
stopConnect();
bleDevice = rxBleClient.getBleDevice(address);
// / / Listen for connection state changes
stateSubscription = new Subscription(bleDevice.observeConnectionStateChanges().subscribeOn(Schedulers.io()).subscribe(this::onConnectionStateChange, throwable -> {
UserError.Log.wtf(TAG, "Got Error from state subscription: " + throwable);
}));
// Attempt to establish a connection
connectionSubscription = new Subscription(bleDevice.establishConnection(auto).timeout(7, TimeUnit.MINUTES).subscribeOn(Schedulers.io()).subscribe(this::onConnectionReceived, this::onConnectionFailure));
} else {
UserError.Log.wtf(TAG, "No transmitter mac address!");
changeState(SCAN);
// state = STATE.SCAN;
// backoff_automata(); // note backoff
}
} else {
UserError.Log.wtf(TAG, "Attempt to connect when not in CONNECT state");
}
}
use of com.eveningoutpost.dexdrip.utils.bt.Subscription in project xDrip by NightscoutFoundation.
the class Ob1G5CollectionService method scan_for_device.
private synchronized void scan_for_device() {
if (state == SCAN) {
msg(gs(R.string.scanning));
stopScan();
// did we already find it?
tryLoadingSavedMAC();
if (always_scan || scan_next_run || (transmitterMAC == null) || (!transmitterID.equals(transmitterIDmatchingMAC)) || (static_last_timestamp < 1)) {
// reset if set
scan_next_run = false;
// reset if set
transmitterMAC = null;
last_scan_started = JoH.tsl();
scanWakeLock = JoH.getWakeLock("xdrip-jam-g5-scan", (int) Constants.MINUTE_IN_MS * 7);
// "" if unset
historicalTransmitterMAC = PersistentStore.getString(OB1G5_MACSTORE + transmitterID);
ScanFilter filter;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && historicalTransmitterMAC.length() > 5) {
filter = new ScanFilter.Builder().setDeviceAddress(historicalTransmitterMAC).build();
} else {
final String localTransmitterID = transmitterID;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && localTransmitterID != null && localTransmitterID.length() > 4) {
filter = new ScanFilter.Builder().setDeviceName(getTransmitterBluetoothName()).build();
} else {
filter = new ScanFilter.Builder().build();
}
}
scanSubscription = new Subscription(rxBleClient.scanBleDevices(new ScanSettings.Builder().setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES).setScanMode(android_wear ? ScanSettings.SCAN_MODE_BALANCED : minimize_scanning ? ScanSettings.SCAN_MODE_BALANCED : ScanSettings.SCAN_MODE_LOW_LATENCY).build(), // scan filter doesn't work reliable on android sdk 23+
filter).subscribeOn(Schedulers.io()).subscribe(this::onScanResult, this::onScanFailure));
if (minimize_scanning) {
// Must be less than fail over timeout
Inevitable.task(STOP_SCAN_TASK_ID, 320 * Constants.SECOND_IN_MS, this::stopScanWithTimeoutAndReschedule);
}
UserError.Log.d(TAG, "Scanning for: " + getTransmitterBluetoothName());
} else {
UserError.Log.d(TAG, "Transmitter mac already known: " + transmitterMAC);
changeState(CONNECT);
}
} else {
UserError.Log.wtf(TAG, "Attempt to scan when not in SCAN state");
}
}
use of com.eveningoutpost.dexdrip.utils.bt.Subscription in project xDrip-plus by jamorham.
the class MiBandService method enableNotification.
@SuppressLint("CheckResult")
private void enableNotification() {
if (d)
UserError.Log.d(TAG, "enableNotifications called");
if (I.connection == null) {
if (d)
UserError.Log.d(TAG, "Cannot enable as connection is null!");
return;
}
enableHeartRateNotification();
if (I.isNotificationEnabled) {
if (d)
UserError.Log.d(TAG, "Notifications already enabled");
changeNextState();
return;
}
if (notifSubscriptionDeviceEvent != null) {
notifSubscriptionDeviceEvent.unsubscribe();
}
if (notifSubscriptionHeartRateMeasurement != null) {
notifSubscriptionHeartRateMeasurement.unsubscribe();
}
if (d)
UserError.Log.d(TAG, "Requesting to enable device event notifications");
I.connection.requestMtu(PREFERRED_MTU_SIZE).subscribe();
notifSubscriptionDeviceEvent = new Subscription(I.connection.setupNotification(Const.UUID_CHARACTERISTIC_DEVICEEVENT).doOnNext(notificationObservable -> {
I.isNotificationEnabled = true;
changeNextState();
}).flatMap(notificationObservable -> notificationObservable).observeOn(Schedulers.newThread()).subscribe(bytes -> {
// incoming notifications
if (d)
UserError.Log.d(TAG, "Received device notification bytes: " + bytesToHex(bytes));
handleDeviceEvent(bytes);
}, 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");
changeNextState();
} else {
UserError.Log.d(TAG, "Disconnected exception");
isNeedToAuthenticate = true;
messageQueue.clear();
changeState(CLOSE);
}
}));
}
use of com.eveningoutpost.dexdrip.utils.bt.Subscription 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.eveningoutpost.dexdrip.utils.bt.Subscription in project xDrip-plus by jamorham.
the class Ob1G5CollectionService method discover_services.
private synchronized void discover_services() {
if (state == DISCOVER) {
if (connection != null) {
if (d)
UserError.Log.d(TAG, "Local bonding state: " + (isDeviceLocallyBonded() ? "BONDED" : "NOT Bonded"));
stopDiscover();
discoverSubscription = new Subscription(connection.discoverServices(10, TimeUnit.SECONDS).subscribe(this::onServicesDiscovered, this::onDiscoverFailed));
} else {
UserError.Log.e(TAG, "No connection when in DISCOVER state - reset");
state = INIT;
background_automata();
}
} else {
UserError.Log.wtf(TAG, "Attempt to discover when not in DISCOVER state");
}
}
Aggregations