com.polidea.rxandroidble2.RxBleClient Java Examples

The following examples show how to use com.polidea.rxandroidble2.RxBleClient. 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: MainActivity.java    From Mi365Locker with GNU General Public License v3.0 6 votes vote down vote up
private void stopScan() {
    for (Map.Entry<String, DeviceConnection> device_entry: this.devices_connections.entrySet())
    {
        device_entry.getValue().dispose();
    }
    bluetoothLeScanner.stopScan(this.mLeScanCallback);

    this.rxBleClient = RxBleClient.create(getApplicationContext());
    this.devicesAdapter = new DeviceAdapter(this, R.layout.list_device_item, new ArrayList<>());
    this.lv_scan.setAdapter(this.devicesAdapter);


    this.btManager= (BluetoothManager) this.getSystemService(Context.BLUETOOTH_SERVICE);
    mBTAdapter = this.btManager.getAdapter();

    bluetoothLeScanner = this.mBTAdapter.getBluetoothLeScanner();


    this.devices_connections = new HashMap<>();
    this.devices_to_attack = new ConcurrentLinkedQueue<>();
    this.scanning = false;
    this.updateStatus();

    this.devicesAdapter.notifyDataSetChanged();
}
 
Example #2
Source File: LocationPermission.java    From RxAndroidBle with Apache License 2.0 6 votes vote down vote up
public static boolean isRequestLocationPermissionGranted(final int requestCode, final String[] permissions,
                                                         final int[] grantResults, RxBleClient client) {
    if (requestCode != REQUEST_PERMISSION_BLE_SCAN) {
        return false;
    }

    String[] recommendedScanRuntimePermissions = client.getRecommendedScanRuntimePermissions();
    for (int i = 0; i < permissions.length; i++) {
        for (String recommendedScanRuntimePermission : recommendedScanRuntimePermissions) {
            if (permissions[i].equals(recommendedScanRuntimePermission)
                    && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                return true;
            }
        }
    }

    return false;
}
 
Example #3
Source File: SampleApplication.java    From RxAndroidBle with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    rxBleClient = RxBleClient.create(this);
    RxBleClient.updateLogOptions(new LogOptions.Builder()
            .setLogLevel(LogConstants.INFO)
            .setMacAddressLogSetting(LogConstants.MAC_ADDRESS_FULL)
            .setUuidsLogSetting(LogConstants.UUIDS_FULL)
            .setShouldLogAttributeValues(true)
            .build()
    );
    RxJavaPlugins.setErrorHandler(throwable -> {
        if (throwable instanceof UndeliverableException && throwable.getCause() instanceof BleException) {
            Log.v("SampleApplication", "Suppressed UndeliverableException: " + throwable.toString());
            return; // ignore BleExceptions as they were surely delivered at least once
        }
        // add other custom handlers if needed
        throw new RuntimeException("Unexpected Throwable in RxJavaPlugins error handler", throwable);
    });
}
 
Example #4
Source File: MainActivity.java    From Mi365Locker with GNU General Public License v3.0 6 votes vote down vote up
@NeedsPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
void startScan()
{
    this.scanning = true;
    if (this.mBTAdapter != null) {

        RxBleClient client = this.rxBleClient;
        RxBleClient.State state = client.getState();

        if(state == RxBleClient.State.READY) {

            bluetoothLeScanner.startScan(this.mLeScanCallback);
        } else {
            Toast.makeText(this, "Enable bluetooth", Toast.LENGTH_LONG).show();
            stopScan();
        }

    }

    this.updateStatus();
}
 
Example #5
Source File: ClientStateObservable.java    From RxAndroidBle with Apache License 2.0 5 votes vote down vote up
@NonNull
static Observable<RxBleClient.State> checkAdapterAndServicesState(
        RxBleAdapterWrapper rxBleAdapterWrapper,
        Observable<RxBleAdapterStateObservable.BleAdapterState> rxBleAdapterStateObservable,
        final Observable<Boolean> locationServicesOkObservable
) {
    return rxBleAdapterStateObservable
            .startWith(rxBleAdapterWrapper.isBluetoothEnabled()
                    ? RxBleAdapterStateObservable.BleAdapterState.STATE_ON
                    /*
                     * Actual RxBleAdapterStateObservable.BleAdapterState does not really matter - because in the .switchMap() below
                     * we only check if it is STATE_ON or not
                     */
                    : RxBleAdapterStateObservable.BleAdapterState.STATE_OFF)
            .switchMap(new Function<RxBleAdapterStateObservable.BleAdapterState, Observable<RxBleClient.State>>() {
                @Override
                public Observable<RxBleClient.State> apply(
                        RxBleAdapterStateObservable.BleAdapterState bleAdapterState) {
                    if (bleAdapterState != RxBleAdapterStateObservable.BleAdapterState.STATE_ON) {
                        return Observable.just(RxBleClient.State.BLUETOOTH_NOT_ENABLED);
                    } else {
                        return locationServicesOkObservable.map(new Function<Boolean, RxBleClient.State>() {
                            @Override
                            public RxBleClient.State apply(Boolean locationServicesOk) {
                                return locationServicesOk ? RxBleClient.State.READY
                                        : RxBleClient.State.LOCATION_SERVICES_NOT_ENABLED;
                            }
                        });
                    }
                }
            });
}
 
Example #6
Source File: ClientStateObservable.java    From RxAndroidBle with Apache License 2.0 5 votes vote down vote up
@Override
protected void subscribeActual(Observer<? super RxBleClient.State> observer) {
    if (!rxBleAdapterWrapper.hasBluetoothAdapter()) {
        observer.onSubscribe(Disposables.empty());
        observer.onComplete();
        return;
    }

    checkPermissionUntilGranted(locationServicesStatus, timerScheduler)
            .flatMapObservable(new Function<Boolean, Observable<RxBleClient.State>>() {
                @Override
                public Observable<RxBleClient.State> apply(Boolean permissionWasInitiallyGranted) {
                    Observable<RxBleClient.State> stateObservable = checkAdapterAndServicesState(
                            rxBleAdapterWrapper,
                            bleAdapterStateObservable,
                            locationServicesOkObservable
                    )
                            .distinctUntilChanged();
                    return permissionWasInitiallyGranted
                            /*
                             * If permission was granted from the beginning then the first value is not a change. The above Observable
                             * does emit value at the moment of subscription.
                             */
                            ? stateObservable.skip(1)
                            : stateObservable;
                }
            })
            .subscribe(observer);
}
 
Example #7
Source File: LocationPermission.java    From RxAndroidBle with Apache License 2.0 5 votes vote down vote up
public static void requestLocationPermission(final Activity activity, final RxBleClient client) {
    ActivityCompat.requestPermissions(
            activity,
            /*
             * the below would cause a ArrayIndexOutOfBoundsException on API < 23. Yet it should not be called then as runtime
             * permissions are not needed and RxBleClient.isScanRuntimePermissionGranted() returns `true`
             */
            new String[]{client.getRecommendedScanRuntimePermissions()[0]},
            REQUEST_PERMISSION_BLE_SCAN
    );
}
 
Example #8
Source File: RxBleProvider.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public static synchronized RxBleClient getSingleton(final String name) {
    final RxBleClient cached = singletons.get(name);
    if (cached != null) return cached;
    //UserError.Log.wtf("RxBleProvider", "Creating new instance for: " + name); // TODO DEBUG ONLY
    final RxBleClient created = RxBleClient.create(xdrip.getAppContext());
    singletons.put(name, created);
    return created;
}
 
Example #9
Source File: RxBleProvider.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public static synchronized RxBleClient getSingleton(final String name) {
    final RxBleClient cached = singletons.get(name);
    if (cached != null) return cached;
    //UserError.Log.wtf("RxBleProvider", "Creating new instance for: " + name); // TODO DEBUG ONLY
    final RxBleClient created = RxBleClient.create(xdrip.getAppContext());
    singletons.put(name, created);
    RxJavaPlugins.setErrorHandler(e -> UserError.Log.d("RXBLE" + name, "RxJavaError: " + e.getMessage()));
    return created;
}
 
Example #10
Source File: RxBleProvider.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
public static synchronized RxBleClient getSingleton(final String name) {
    final RxBleClient cached = singletons.get(name);
    if (cached != null) return cached;
    //UserError.Log.wtf("RxBleProvider", "Creating new instance for: " + name); // TODO DEBUG ONLY
    final RxBleClient created = RxBleClient.create(xdrip.getAppContext());
    singletons.put(name, created);
    return created;
}
 
Example #11
Source File: RxBleProvider.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
public static synchronized RxBleClient getSingleton(final String name) {
    final RxBleClient cached = singletons.get(name);
    if (cached != null) return cached;
    //UserError.Log.wtf("RxBleProvider", "Creating new instance for: " + name); // TODO DEBUG ONLY
    final RxBleClient created = RxBleClient.create(xdrip.getAppContext());
    singletons.put(name, created);
    RxJavaPlugins.setErrorHandler(e -> UserError.Log.d("RXBLE" + name, "RxJavaError: " + e.getMessage()));
    return created;
}
 
Example #12
Source File: SampleApplication.java    From RxAndroidBle with Apache License 2.0 4 votes vote down vote up
/**
 * In practice you will use some kind of dependency injection pattern.
 */
public static RxBleClient getRxBleClient(Context context) {
    SampleApplication application = (SampleApplication) context.getApplicationContext();
    return application.rxBleClient;
}
 
Example #13
Source File: DeviceActivity.java    From M365-Power with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    setTheme(R.style.MyAppTheme);
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setContentView(R.layout.activity_device);


    voltageMeter = this.findViewById(R.id.voltageMeter);
    voltageMeter.setType(RequestType.VOLTAGE);
    textViews.add(voltageMeter);

    ampMeter = this.findViewById(R.id.ampMeter);
    ampMeter.setType(RequestType.AMEPERE);
    textViews.add(ampMeter);

    speedMeter = this.findViewById(R.id.speedMeter);
    speedMeter.setType(RequestType.SPEED);
    textViews.add(speedMeter);

    powerMeter = this.findViewById(R.id.powerMeter);

    minPowerView = this.findViewById(R.id.minPowerView);

    maxPowerView = this.findViewById(R.id.maxPowerView);

    efficiencyMeter = this.findViewById(R.id.efficiencyMeter);

    rangeMeter = this.findViewById(R.id.rangeMeter);

    recoveredPower = this.findViewById(R.id.recoveredPower);

    startHandlerButton = this.findViewById(R.id.start_handler_button);

    spentPower = this.findViewById(R.id.spentPower);

    battTemp = this.findViewById(R.id.battTemp);

    distance = this.findViewById(R.id.distanceMeter);

    capacity = this.findViewById(R.id.remainingAmps);

    averageEfficiency = this.findViewById(R.id.AverageEfficiencyMeter);

    averageSpeed = this.findViewById(R.id.averageSpeedMeter);

    motorTemp = this.findViewById(R.id.motorTemp);

    time = this.findViewById(R.id.time);
    life = this.findViewById(R.id.life);
    life.setType(RequestType.BATTERYLIFE);
    textViews.add(life);


    final Intent intent = getIntent();
    mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);
    mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);

    rxBleClient = RxBleClient.create(this);
    bleDevice = rxBleClient.getBleDevice(mDeviceAddress);
    connectionObservable = prepareConnectionObservable();

    requestTypes.put(RequestType.VOLTAGE, new VoltageRequest());
    requestTypes.put(RequestType.AMEPERE, new AmpereRequest());
    requestTypes.put(RequestType.BATTERYLIFE, new BatteryLifeRequest());
    requestTypes.put(RequestType.SPEED, new SpeedRequest());
    requestTypes.put(RequestType.DISTANCE, new DistanceRequest());
    requestTypes.put(RequestType.SUPERMASTER, new SuperMasterRequest());
    requestTypes.put(RequestType.SUPERBATTERY, new SuperBatteryRequest());

    requestTypes.put(RequestType.LOCK,new CheckLock());
    requestTypes.put(RequestType.CRUISE,new CheckCruise());
    requestTypes.put(RequestType.LIGHT,new CheckLight());
    requestTypes.put(RequestType.RECOVERY,new CheckRecovery());

    fillCheckFirstList();

    lastTimeStamp = System.nanoTime();
    mRootView= findViewById(R.id.root);

    handlerThread=new HandlerThread("RequestThread");
    handlerThread.start();
    handler=new Handler(handlerThread.getLooper());
    handlerThread1=new HandlerThread("LoggingThread");
    handlerThread1.start();
    handler1=new Handler(handlerThread1.getLooper());

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
        requestStoragePermission();
    }
    else{
        storagePermission=true;
    }
}
 
Example #14
Source File: LongWriteExampleActivity.java    From RxAndroidBle with Apache License 2.0 4 votes vote down vote up
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    final RxBleClient rxBleClient = SampleApplication.getRxBleClient(this);
    disposable = rxBleClient.getBleDevice(DUMMY_DEVICE_ADDRESS) // get our assumed device
            .establishConnection(false) // establish the connection
            .flatMap(rxBleConnection -> Observable.combineLatest(
                    // after establishing the connection lets setup the notifications
                    rxBleConnection.setupNotification(DEVICE_CALLBACK_0),
                    rxBleConnection.setupNotification(DEVICE_CALLBACK_1),
                    Pair::new
            ), (rxBleConnection, callbackObservablePair) -> { // after the setup lets start the long write
                Observable<byte[]> deviceCallback0 = callbackObservablePair.first;
                Observable<byte[]> deviceCallback1 = callbackObservablePair.second;
                return rxBleConnection.createNewLongWriteBuilder() // create a new long write builder
                        .setBytes(bytesToWrite) // REQUIRED - set the bytes to write
                        /*
                         * REQUIRED - To perform a write you need to specify to which characteristic you want to write. You can do it
                         * either by calling {@link LongWriteOperationBuilder#setCharacteristicUuid(UUID)} or
                         * {@link LongWriteOperationBuilder#setCharacteristic(BluetoothGattCharacteristic)}
                         */
                        .setCharacteristicUuid(WRITE_CHARACTERISTIC) // set the UUID of the characteristic to write
                        // .setCharacteristic( /* some BluetoothGattCharacteristic */ ) // alternative to setCharacteristicUuid()
                        /*
                         * If you want to send batches with length other than default.
                         * Default value is 20 bytes if MTU was not negotiated. If the MTU was negotiated prior to the Long Write
                         * Operation execution then the batch size default is the new MTU.
                         */
                        // .setMaxBatchSize( /* your batch size */ )
                        /*
                          Inform the Long Write when we want to send the next batch of data. If not set the operation will try to write
                          the next batch of data as soon as the Android will call `BluetoothGattCallback.onCharacteristicWrite()` but
                          we want to postpone it until also DC0 and DC1 will emit.
                         */
                        .setWriteOperationAckStrategy(new RxBleConnection.WriteOperationAckStrategy() {
                            @Override
                            public ObservableSource<Boolean> apply(Observable<Boolean> booleanObservable) {
                                return Observable.zip(
                                        // so we zip three observables
                                        deviceCallback0, // DEVICE_CALLBACK_0
                                        deviceCallback1, // DEVICE_CALLBACK_1
                                        booleanObservable, /* previous batch of data was sent - we do not care if value emitted from
                                        the booleanObservable is TRUE or FALSE. But the value will be TRUE unless the previously sent
                                        data batch was the final one */
                                        (callback0, callback1, aBoolean) -> aBoolean // value of the returned Boolean is not important
                                );
                            }
                        })
                        .build();
            })
            .flatMap(observable -> observable)
            .take(1) // after the successful write we are no longer interested in the connection so it will be released
            .subscribe(
                    bytes -> {
                        // react
                    },
                    throwable -> {
                        // handle error
                    }
            );
}
 
Example #15
Source File: RxBleProvider.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
public static RxBleClient getSingleton() {
    return getSingleton("base");
}
 
Example #16
Source File: RxBleProvider.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
public static RxBleClient getSingleton() {
    return getSingleton("base");
}
 
Example #17
Source File: RxBleProvider.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
public static RxBleClient getSingleton() {
    return getSingleton("base");
}
 
Example #18
Source File: RxBleProvider.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
public static RxBleClient getSingleton() {
    return getSingleton("base");
}