com.polidea.rxandroidble2.scan.ScanSettings Java Examples

The following examples show how to use com.polidea.rxandroidble2.scan.ScanSettings. 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: RxBleClientImpl.java    From RxAndroidBle with Apache License 2.0 6 votes vote down vote up
@Override
public Observable<ScanResult> scanBleDevices(final ScanSettings scanSettings, final ScanFilter... scanFilters) {
    return Observable.defer(new Callable<ObservableSource<? extends ScanResult>>() {
        @Override
        public Observable<ScanResult> call() {
            scanPreconditionVerifier.verify(scanSettings.shouldCheckLocationProviderState());
            final ScanSetup scanSetup = scanSetupBuilder.build(scanSettings, scanFilters);
            final Operation<RxBleInternalScanResult> scanOperation = scanSetup.scanOperation;
            return operationQueue.queue(scanOperation)
                    .unsubscribeOn(bluetoothInteractionScheduler)
                    .compose(scanSetup.scanOperationBehaviourEmulatorTransformer)
                    .map(internalToExternalScanResultMapFunction)
                    .doOnNext(new Consumer<ScanResult>() {
                        @Override
                        public void accept(ScanResult scanResult) {
                            if (RxBleLog.getShouldLogScannedPeripherals()) RxBleLog.i("%s", scanResult);
                        }
                    })
                    .mergeWith(RxBleClientImpl.this.<ScanResult>bluetoothAdapterOffExceptionObservable());
        }
    });
}
 
Example #2
Source File: InPenScanMeister.java    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
@Override
public synchronized void scan() {

    extendWakeLock((scanSeconds + 1) * Constants.SECOND_IN_MS);
    stopScan("Scan start");
    UserError.Log.d(TAG, "startScan called: hunting: " + address + " " + name);
    scanSubscription = new Subscription(rxBleClient.scanBleDevices(
            new ScanSettings.Builder()
                    .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
                    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                    .build(),
            new ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString(SCAN_SERVICE_UUID)).build())
            .timeout(scanSeconds, TimeUnit.SECONDS) // is unreliable
            .subscribeOn(Schedulers.io())
            .subscribe(this::onScanResult, this::onScanFailure));

    Inevitable.task(STOP_SCAN_TASK_ID, scanSeconds * Constants.SECOND_IN_MS, this::stopScanWithTimeoutCallback);
}
 
Example #3
Source File: PendiqService.java    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
private synchronized void scan_for_device() {
    extendWakeLock((SCAN_SECONDS + 1) * Constants.SECOND_IN_MS);
    stopScan();
    scanSubscription = new Subscription(rxBleClient.scanBleDevices(
            new ScanSettings.Builder()

                    .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
                    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                    .build()//,  //new ScanFilter.Builder()
            //
            // add custom filters if needed
            //  .build()
    )
            .timeout(SCAN_SECONDS, TimeUnit.SECONDS) // is unreliable
            .subscribeOn(Schedulers.io())
            .subscribe(this::onScanResult, this::onScanFailure));

    Inevitable.task("stop_pendiq_scan", SCAN_SECONDS * Constants.SECOND_IN_MS, this::stopScan);
}
 
Example #4
Source File: InPenScanMeister.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
@Override
public synchronized void scan() {

    extendWakeLock((scanSeconds + 1) * Constants.SECOND_IN_MS);
    stopScan("Scan start");
    UserError.Log.d(TAG, "startScan called: hunting: " + address + " " + name);
    scanSubscription = new Subscription(rxBleClient.scanBleDevices(
            new ScanSettings.Builder()
                    .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
                    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                    .build(),
            new ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString(SCAN_SERVICE_UUID)).build())
            .timeout(scanSeconds, TimeUnit.SECONDS) // is unreliable
            .subscribeOn(Schedulers.io())
            .subscribe(this::onScanResult, this::onScanFailure));

    Inevitable.task(STOP_SCAN_TASK_ID, scanSeconds * Constants.SECOND_IN_MS, this::stopScanWithTimeoutCallback);
}
 
Example #5
Source File: PendiqService.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
private synchronized void scan_for_device() {
    extendWakeLock((SCAN_SECONDS + 1) * Constants.SECOND_IN_MS);
    stopScan();
    scanSubscription = new Subscription(rxBleClient.scanBleDevices(
            new ScanSettings.Builder()

                    .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
                    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                    .build()//,  //new ScanFilter.Builder()
            //
            // add custom filters if needed
            //  .build()
    )
            .timeout(SCAN_SECONDS, TimeUnit.SECONDS) // is unreliable
            .subscribeOn(Schedulers.io())
            .subscribe(this::onScanResult, this::onScanFailure));

    Inevitable.task("stop_pendiq_scan", SCAN_SECONDS * Constants.SECOND_IN_MS, this::stopScan);
}
 
Example #6
Source File: BackgroundScanActivity.java    From RxAndroidBle with Apache License 2.0 6 votes vote down vote up
private void scanBleDeviceInBackground() {
    if (VERSION.SDK_INT >= VERSION_CODES.O) {
        try {
            rxBleClient.getBackgroundScanner().scanBleDeviceInBackground(
                    callbackIntent,
                    new ScanSettings.Builder()
                            .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                            .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
                            .build(),
                    new ScanFilter.Builder()
                            .setDeviceAddress("5C:31:3E:BF:F7:34")
                            // add custom filters if needed
                            .build()
            );
        } catch (BleScanException scanException) {
            Log.w("BackgroundScanActivity", "Failed to start background scan", scanException);
            ScanExceptionHandler.handleException(this, scanException);
        }
    }
}
 
Example #7
Source File: ScanSetupBuilderImplApi21.java    From RxAndroidBle with Apache License 2.0 6 votes vote down vote up
@RequiresApi(21 /* Build.VERSION_CODES.LOLLIPOP */)
@Override
public ScanSetup build(ScanSettings scanSettings, ScanFilter... scanFilters) {
    /*
     Android 5.0 (API21) does not handle FIRST_MATCH and / or MATCH_LOST callback type
     https://developer.android.com/reference/android/bluetooth/le/ScanSettings.Builder.html#setCallbackType(int)
      */
    final ObservableTransformer<RxBleInternalScanResult, RxBleInternalScanResult> callbackTypeTransformer
            = scanSettingsEmulator.emulateCallbackType(scanSettings.getCallbackType());
    return new ScanSetup(
            new ScanOperationApi21(
                    rxBleAdapterWrapper,
                    internalScanResultCreator,
                    androidScanObjectsConverter,
                    scanSettings,
                    new EmulatedScanFilterMatcher(scanFilters),
                    null),
            callbackTypeTransformer
    );
}
 
Example #8
Source File: ScanSetupBuilderImplApi18.java    From RxAndroidBle with Apache License 2.0 6 votes vote down vote up
@Override
public ScanSetup build(ScanSettings scanSettings, ScanFilter... scanFilters) {
    final ObservableTransformer<RxBleInternalScanResult, RxBleInternalScanResult> scanModeTransformer
            = scanSettingsEmulator.emulateScanMode(scanSettings.getScanMode());
    final ObservableTransformer<RxBleInternalScanResult, RxBleInternalScanResult> callbackTypeTransformer
            = scanSettingsEmulator.emulateCallbackType(scanSettings.getCallbackType());
    return new ScanSetup(
            new ScanOperationApi18(
                    rxBleAdapterWrapper,
                    internalScanResultCreator,
                    new EmulatedScanFilterMatcher(scanFilters)
            ),
            new ObservableTransformer<RxBleInternalScanResult, RxBleInternalScanResult>() {
                @Override
                public Observable<RxBleInternalScanResult> apply(Observable<RxBleInternalScanResult> observable) {
                    return observable.compose(scanModeTransformer)
                            .compose(callbackTypeTransformer);
                }
            }
    );
}
 
Example #9
Source File: BackgroundScannerImpl.java    From RxAndroidBle with Apache License 2.0 6 votes vote down vote up
@RequiresApi(26 /* Build.VERSION_CODES.O */)
@Override
public void scanBleDeviceInBackground(@NonNull PendingIntent callbackIntent, ScanSettings scanSettings, ScanFilter... scanFilters) {
    if (Build.VERSION.SDK_INT < 26 /* Build.VERSION_CODES.O */) {
        RxBleLog.w("PendingIntent based scanning is available for Android O and higher only.");
        return;
    }
    if (!rxBleAdapterWrapper.isBluetoothEnabled()) {
        RxBleLog.w("PendingIntent based scanning is available only when Bluetooth is ON.");
        throw new BleScanException(BleScanException.BLUETOOTH_DISABLED);
    }

    RxBleLog.i("Requesting pending intent based scan.");
    final List<android.bluetooth.le.ScanFilter> nativeScanFilters = scanObjectsConverter.toNativeFilters(scanFilters);
    final android.bluetooth.le.ScanSettings nativeScanSettings = scanObjectsConverter.toNativeSettings(scanSettings);
    final int scanStartResult = rxBleAdapterWrapper.startLeScan(nativeScanFilters, nativeScanSettings, callbackIntent);

    if (scanStartResult != NO_ERROR) {
        final BleScanException bleScanException = new BleScanException(scanStartResult);
        RxBleLog.w(bleScanException, "Failed to start scan"); // TODO?
        throw bleScanException;
    }
}
 
Example #10
Source File: ScanSettingsEmulator.java    From RxAndroidBle with Apache License 2.0 6 votes vote down vote up
ObservableTransformer<RxBleInternalScanResult, RxBleInternalScanResult> emulateScanMode(@ScanSettings.ScanMode int scanMode) {
    switch (scanMode) {

        case ScanSettings.SCAN_MODE_BALANCED:
            return scanModeBalancedTransformer();
        case ScanSettings.SCAN_MODE_OPPORTUNISTIC:
            RxBleLog.w("Cannot emulate opportunistic scan mode since it is OS dependent - fallthrough to low power");
            // fallthrough
        case ScanSettings.SCAN_MODE_LOW_POWER:
            return scanModeLowPowerTransformer();
        case ScanSettings.SCAN_MODE_LOW_LATENCY:
            // return the original observable - fallthrough
        default: // checkstyle always needs default
            return identityTransformer();
    }
}
 
Example #11
Source File: AndroidScanObjectsConverter.java    From RxAndroidBle with Apache License 2.0 5 votes vote down vote up
@RequiresApi(23 /* Build.VERSION_CODES.M */)
private static void setMarshmallowSettings(ScanSettings scanSettings, android.bluetooth.le.ScanSettings.Builder builder) {
    builder
            .setCallbackType(scanSettings.getCallbackType())
            .setMatchMode(scanSettings.getMatchMode())
            .setNumOfMatches(scanSettings.getNumOfMatches());
}
 
Example #12
Source File: AndroidScanObjectsConverter.java    From RxAndroidBle with Apache License 2.0 5 votes vote down vote up
@SuppressLint("NewApi")
@RequiresApi(21 /* Build.VERSION_CODES.LOLLIPOP */)
public android.bluetooth.le.ScanSettings toNativeSettings(ScanSettings scanSettings) {
    final android.bluetooth.le.ScanSettings.Builder builder = new android.bluetooth.le.ScanSettings.Builder();
    if (deviceSdk >= 23 /* Build.VERSION_CODES.M */) {
        setMarshmallowSettings(scanSettings, builder);
    }
    return builder
            .setReportDelay(scanSettings.getReportDelayMillis())
            .setScanMode(scanSettings.getScanMode())
            .build();
}
 
Example #13
Source File: ScanOperationApi21.java    From RxAndroidBle with Apache License 2.0 5 votes vote down vote up
public ScanOperationApi21(
        @NonNull RxBleAdapterWrapper rxBleAdapterWrapper,
        @NonNull final InternalScanResultCreator internalScanResultCreator,
        @NonNull final AndroidScanObjectsConverter androidScanObjectsConverter,
        @NonNull ScanSettings scanSettings,
        @NonNull final EmulatedScanFilterMatcher emulatedScanFilterMatcher,
        @Nullable final ScanFilter[] offloadedScanFilters
) {
    super(rxBleAdapterWrapper);
    this.internalScanResultCreator = internalScanResultCreator;
    this.scanSettings = scanSettings;
    this.emulatedScanFilterMatcher = emulatedScanFilterMatcher;
    this.scanFilters = offloadedScanFilters;
    this.androidScanObjectsConverter = androidScanObjectsConverter;
}
 
Example #14
Source File: ScanActivity.java    From RxAndroidBle with Apache License 2.0 5 votes vote down vote up
private void scanBleDevices() {
        scanDisposable = rxBleClient.scanBleDevices(
                new ScanSettings.Builder()
                        .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                        .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
                        .build(),
                new ScanFilter.Builder()
//                            .setDeviceAddress("B4:99:4C:34:DC:8B")
                        // add custom filters if needed
                        .build()
        )
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(this::dispose)
                .subscribe(resultsAdapter::addScanResult, this::onScanFailure);
    }
 
Example #15
Source File: ScanMeister.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public synchronized void scan() {
    extendWakeLock((scanSeconds + 1) * Constants.SECOND_IN_MS);
    stopScan("Scan start");
    UserError.Log.d(TAG, "startScan called: hunting: " + address + " " + name);

    ScanFilter filter = this.customFilter;
    if (filter == null) {
        final ScanFilter.Builder builder = new ScanFilter.Builder();
        if (address != null) {
            try {
                builder.setDeviceAddress(address);
            } catch (IllegalArgumentException e) {
                UserError.Log.wtf(TAG, "Invalid bluetooth address: " + address);
            }
        }
        // TODO scanning by name doesn't build a filter
        filter = builder.build();
    } else {
        UserError.Log.d(TAG,"Overriding with custom filter");
    }

    scanSubscription = new Subscription(rxBleClient.scanBleDevices(
            new ScanSettings.Builder()
                    .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
                    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                    .build(), legacyNoFilterWorkaround ? ScanFilter.empty() : filter)
            .timeout(scanSeconds, TimeUnit.SECONDS) // is unreliable
            .subscribeOn(Schedulers.io())
            .subscribe(this::onScanResult, this::onScanFailure));

    Inevitable.task(STOP_SCAN_TASK_ID, scanSeconds * Constants.SECOND_IN_MS, this::stopScanWithTimeoutCallback);
}
 
Example #16
Source File: ScanMeister.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public synchronized void scan() {
    extendWakeLock((scanSeconds + 1) * Constants.SECOND_IN_MS);
    stopScan("Scan start");
    UserError.Log.d(TAG, "startScan called: hunting: " + address + " " + name);

    ScanFilter filter = this.customFilter;
    if (filter == null) {
        final ScanFilter.Builder builder = new ScanFilter.Builder();
        if (address != null) {
            try {
                builder.setDeviceAddress(address);
            } catch (IllegalArgumentException e) {
                UserError.Log.wtf(TAG, "Invalid bluetooth address: " + address);
            }
        }
        // TODO scanning by name doesn't build a filter
        filter = builder.build();
    } else {
        UserError.Log.d(TAG,"Overriding with custom filter");
    }

    scanSubscription = new Subscription(rxBleClient.scanBleDevices(
            new ScanSettings.Builder()
                    .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
                    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                    .build(), legacyNoFilterWorkaround ? ScanFilter.empty() : filter)
            .timeout(scanSeconds, TimeUnit.SECONDS) // is unreliable
            .subscribeOn(Schedulers.io())
            .subscribe(this::onScanResult, this::onScanFailure));

    Inevitable.task(STOP_SCAN_TASK_ID, scanSeconds * Constants.SECOND_IN_MS, this::stopScanWithTimeoutCallback);
}
 
Example #17
Source File: ScanSetupBuilderImplApi23.java    From RxAndroidBle with Apache License 2.0 5 votes vote down vote up
@RequiresApi(21 /* Build.VERSION_CODES.LOLLIPOP */)
@Override
public ScanSetup build(ScanSettings scanSettings, ScanFilter... scanFilters) {
    boolean areFiltersSpecified = areFiltersSpecified(scanFilters);
    boolean isFilteringCallbackType = scanSettings.getCallbackType() != ScanSettings.CALLBACK_TYPE_ALL_MATCHES;

    ObservableTransformer<RxBleInternalScanResult, RxBleInternalScanResult> resultTransformer = ObservableUtil.identityTransformer();
    ScanSettings resultScanSettings = scanSettings;

    // native matching (when a device is first seen or no longer seen) does not work with no filters specified —
    // see https://issuetracker.google.com/issues/37127640
    // so we will use a callback type that will work and emulate the desired behaviour
    boolean shouldEmulateCallbackType = isFilteringCallbackType && !areFiltersSpecified;
    if (shouldEmulateCallbackType) {
        RxBleLog.d("ScanSettings.callbackType != CALLBACK_TYPE_ALL_MATCHES but no (or only empty) filters are specified. "
            + "Falling back to callbackType emulation.");
        resultTransformer = scanSettingsEmulator.emulateCallbackType(scanSettings.getCallbackType());
        resultScanSettings = scanSettings.copyWithCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES);
    }

    return new ScanSetup(
            new ScanOperationApi21(
                    rxBleAdapterWrapper,
                    internalScanResultCreator,
                    androidScanObjectsConverter,
                    resultScanSettings,
                    new EmulatedScanFilterMatcher(),
                    scanFilters),
            resultTransformer
    );
}
 
Example #18
Source File: ScanMeister.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
public synchronized void scan() {
    extendWakeLock((scanSeconds + 1) * Constants.SECOND_IN_MS);
    stopScan("Scan start");
    UserError.Log.d(TAG, "startScan called: hunting: " + address + " " + name);

    ScanFilter filter = this.customFilter;
    if (filter == null) {
        final ScanFilter.Builder builder = new ScanFilter.Builder();
        if (address != null) {
            try {
                builder.setDeviceAddress(address);
            } catch (IllegalArgumentException e) {
                UserError.Log.wtf(TAG, "Invalid bluetooth address: " + address);
            }
        }
        // TODO scanning by name doesn't build a filter
        filter = builder.build();
    } else {
        UserError.Log.d(TAG,"Overriding with custom filter");
    }

    scanSubscription = new Subscription(rxBleClient.scanBleDevices(
            new ScanSettings.Builder()
                    .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
                    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                    .build(), legacyNoFilterWorkaround ? ScanFilter.empty() : filter)
            .timeout(scanSeconds, TimeUnit.SECONDS) // is unreliable
            .subscribeOn(Schedulers.io())
            .subscribe(this::onScanResult, this::onScanFailure));

    Inevitable.task(STOP_SCAN_TASK_ID, scanSeconds * Constants.SECOND_IN_MS, this::stopScanWithTimeoutCallback);
}
 
Example #19
Source File: ScanMeister.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
public synchronized void scan() {
    extendWakeLock((scanSeconds + 1) * Constants.SECOND_IN_MS);
    stopScan("Scan start");
    UserError.Log.d(TAG, "startScan called: hunting: " + address + " " + name);

    ScanFilter filter = this.customFilter;
    if (filter == null) {
        final ScanFilter.Builder builder = new ScanFilter.Builder();
        if (address != null) {
            try {
                builder.setDeviceAddress(address);
            } catch (IllegalArgumentException e) {
                UserError.Log.wtf(TAG, "Invalid bluetooth address: " + address);
            }
        }
        // TODO scanning by name doesn't build a filter
        filter = builder.build();
    } else {
        UserError.Log.d(TAG,"Overriding with custom filter");
    }

    scanSubscription = new Subscription(rxBleClient.scanBleDevices(
            new ScanSettings.Builder()
                    .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
                    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                    .build(), legacyNoFilterWorkaround ? ScanFilter.empty() : filter)
            .timeout(scanSeconds, TimeUnit.SECONDS) // is unreliable
            .subscribeOn(Schedulers.io())
            .subscribe(this::onScanResult, this::onScanFailure));

    Inevitable.task(STOP_SCAN_TASK_ID, scanSeconds * Constants.SECOND_IN_MS, this::stopScanWithTimeoutCallback);
}
 
Example #20
Source File: ScanSettingsEmulator.java    From RxAndroidBle with Apache License 2.0 5 votes vote down vote up
ObservableTransformer<RxBleInternalScanResult, RxBleInternalScanResult> emulateCallbackType(
        @ScanSettings.CallbackType final int callbackType) {
    switch (callbackType) {
        case ScanSettings.CALLBACK_TYPE_FIRST_MATCH:
            return splitByAddressAndForEach(emulateFirstMatch);
        case ScanSettings.CALLBACK_TYPE_MATCH_LOST:
            return splitByAddressAndForEach(emulateMatchLost);
        case ScanSettings.CALLBACK_TYPE_FIRST_MATCH | ScanSettings.CALLBACK_TYPE_MATCH_LOST:
            return splitByAddressAndForEach(emulateFirstMatchAndMatchLost);
        case ScanSettings.CALLBACK_TYPE_ALL_MATCHES:
            // return the original observable - fallthrough
        default: // checkstyle always needs default
            return identityTransformer();
    }
}
 
Example #21
Source File: RxBleClientMock.java    From RxAndroidBle with Apache License 2.0 4 votes vote down vote up
@Override
public Observable<ScanResult> scanBleDevices(ScanSettings scanSettings, ScanFilter... scanFilters) {
    return Observable.error(new RuntimeException("not implemented")); // TODO [DS]
}
 
Example #22
Source File: RxBleClient.java    From RxAndroidBle with Apache License 2.0 2 votes vote down vote up
/**
 * Returns an infinite observable emitting BLE scan results.
 * Scan is automatically started and stopped based on the Observable lifecycle.
 * Scan is started on subscribe and stopped on unsubscribe. You can safely subscribe multiple observers to this observable.
 * <p>
 * The library automatically handles Bluetooth adapter state changes but you are supposed to prompt the user
 * to enable it if it is disabled
 *
 * This function works on Android 4.3 in compatibility (emulated) mode.
 *
 * @param scanSettings Scan settings
 * @param scanFilters Filtering settings. ScanResult will be emitted if <i>any</i> of the passed scan filters will match.
 */
public abstract Observable<ScanResult> scanBleDevices(ScanSettings scanSettings, ScanFilter... scanFilters);
 
Example #23
Source File: ScanSetupBuilder.java    From RxAndroidBle with Apache License 2.0 votes vote down vote up
ScanSetup build(ScanSettings scanSettings, ScanFilter... scanFilters);