com.polidea.rxandroidble2.scan.ScanFilter Java Examples

The following examples show how to use com.polidea.rxandroidble2.scan.ScanFilter. 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: 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 #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: 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 #4
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 #5
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 #6
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 #7
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 #8
Source File: AndroidScanObjectsConverter.java    From RxAndroidBle with Apache License 2.0 5 votes vote down vote up
@Nullable
@RequiresApi(21 /* Build.VERSION_CODES.LOLLIPOP */)
public List<android.bluetooth.le.ScanFilter> toNativeFilters(ScanFilter... scanFilters) {
    final boolean isFilteringDefined = scanFilters != null && scanFilters.length > 0;
    final List<android.bluetooth.le.ScanFilter> returnList;
    if (isFilteringDefined) {
        returnList = new ArrayList<>(scanFilters.length);
        for (ScanFilter scanFilter : scanFilters) {
            returnList.add(toNative(scanFilter));
        }
    } else {
        returnList = null;
    }
    return returnList;
}
 
Example #9
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 #10
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 #11
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 #12
Source File: ScanSetupBuilderImplApi23.java    From RxAndroidBle with Apache License 2.0 5 votes vote down vote up
private static boolean areFiltersSpecified(ScanFilter[] scanFilters) {
    boolean scanFiltersEmpty = true;
    for (ScanFilter scanFilter : scanFilters) {
        scanFiltersEmpty &= scanFilter.isAllFieldsEmpty();
    }
    return !scanFiltersEmpty;
}
 
Example #13
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 #14
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 #15
Source File: AndroidScanObjectsConverter.java    From RxAndroidBle with Apache License 2.0 5 votes vote down vote up
@RequiresApi(21 /* Build.VERSION_CODES.LOLLIPOP */)
private static android.bluetooth.le.ScanFilter toNative(ScanFilter scanFilter) {
    final android.bluetooth.le.ScanFilter.Builder builder = new android.bluetooth.le.ScanFilter.Builder();
    if (scanFilter.getServiceDataUuid() != null) {
        builder.setServiceData(scanFilter.getServiceDataUuid(), scanFilter.getServiceData(), scanFilter.getServiceDataMask());
    }
    return builder
            .setDeviceAddress(scanFilter.getDeviceAddress())
            .setDeviceName(scanFilter.getDeviceName())
            .setManufacturerData(scanFilter.getManufacturerId(), scanFilter.getManufacturerData(), scanFilter.getManufacturerDataMask())
            .setServiceUuid(scanFilter.getServiceUuid(), scanFilter.getServiceUuidMask())
            .build();
}
 
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: Ob1G5CollectionService.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
private synchronized void scan_for_device() {
    if (state == SCAN) {
        msg(gs(R.string.scanning));
        stopScan();
        tryLoadingSavedMAC(); // did we already find it?
        if (always_scan || scan_next_run || (transmitterMAC == null) || (!transmitterID.equals(transmitterIDmatchingMAC)) || (static_last_timestamp < 1)) {
            scan_next_run = false; // reset if set
            transmitterMAC = null; // reset if set
            last_scan_started = tsl();
            scanWakeLock = JoH.getWakeLock("xdrip-jam-g5-scan", (int) Constants.MINUTE_IN_MS * 7);


            historicalTransmitterMAC = PersistentStore.getString(OB1G5_MACSTORE + transmitterID); // "" if unset

            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()
                            //.setScanMode(static_last_timestamp < 1 ? ScanSettings.SCAN_MODE_LOW_LATENCY : ScanSettings.SCAN_MODE_BALANCED)
                            //.setCallbackType(ScanSettings.CALLBACK_TYPE_FIRST_MATCH)
                            .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
                            // TODO revisit scan mode
                            .setScanMode(android_wear ? ScanSettings.SCAN_MODE_BALANCED :
                                    minimize_scanning ? ScanSettings.SCAN_MODE_BALANCED : ScanSettings.SCAN_MODE_LOW_LATENCY)
                            // .setScanMode(ScanSettings.SCAN_MODE_BALANCED)
                            .build(),

                    // scan filter doesn't work reliable on android sdk 23+
                    filter
            )
                    // observe on?
                    // do unsubscribe?
                    //.doOnUnsubscribe(this::clearSubscription)
                    .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");
    }
}
 
Example #19
Source File: ScanMeister.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
public ScanMeister setFilter(final ScanFilter filter) {
    this.customFilter = filter;
    return this;
}
 
Example #20
Source File: Ob1G5CollectionService.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
private synchronized void scan_for_device() {
    if (state == SCAN) {
        msg(gs(R.string.scanning));
        stopScan();
        tryLoadingSavedMAC(); // did we already find it?
        if (always_scan || scan_next_run || (transmitterMAC == null) || (!transmitterID.equals(transmitterIDmatchingMAC)) || (static_last_timestamp < 1)) {
            scan_next_run = false; // reset if set
            transmitterMAC = null; // reset if set
            last_scan_started = tsl();
            scanWakeLock = JoH.getWakeLock("xdrip-jam-g5-scan", (int) Constants.MINUTE_IN_MS * 7);


            historicalTransmitterMAC = PersistentStore.getString(OB1G5_MACSTORE + transmitterID); // "" if unset

            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()
                            //.setScanMode(static_last_timestamp < 1 ? ScanSettings.SCAN_MODE_LOW_LATENCY : ScanSettings.SCAN_MODE_BALANCED)
                            //.setCallbackType(ScanSettings.CALLBACK_TYPE_FIRST_MATCH)
                            .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
                            // TODO revisit scan mode
                            .setScanMode(android_wear ? ScanSettings.SCAN_MODE_BALANCED :
                                    minimize_scanning ? ScanSettings.SCAN_MODE_BALANCED : ScanSettings.SCAN_MODE_LOW_LATENCY)
                            // .setScanMode(ScanSettings.SCAN_MODE_BALANCED)
                            .build(),

                    // scan filter doesn't work reliable on android sdk 23+
                    filter
            )
                    // observe on?
                    // do unsubscribe?
                    //.doOnUnsubscribe(this::clearSubscription)
                    .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");
    }
}
 
Example #21
Source File: ScanMeister.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
public ScanMeister setFilter(final ScanFilter filter) {
    this.customFilter = filter;
    return this;
}
 
Example #22
Source File: Ob1G5CollectionService.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
private synchronized void scan_for_device() {
    if (state == SCAN) {
        msg(gs(R.string.scanning));
        stopScan();
        tryLoadingSavedMAC(); // did we already find it?
        if (always_scan || scan_next_run || (transmitterMAC == null) || (!transmitterID.equals(transmitterIDmatchingMAC)) || (static_last_timestamp < 1)) {
            scan_next_run = false; // reset if set
            transmitterMAC = null; // reset if set
            last_scan_started = JoH.tsl();
            scanWakeLock = JoH.getWakeLock("xdrip-jam-g5-scan", (int) Constants.MINUTE_IN_MS * 7);


            historicalTransmitterMAC = PersistentStore.getString(OB1G5_MACSTORE + transmitterID); // "" if unset

            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()
                            //.setScanMode(static_last_timestamp < 1 ? ScanSettings.SCAN_MODE_LOW_LATENCY : ScanSettings.SCAN_MODE_BALANCED)
                            //.setCallbackType(ScanSettings.CALLBACK_TYPE_FIRST_MATCH)
                            .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
                            // TODO revisit scan mode
                            .setScanMode(android_wear ? ScanSettings.SCAN_MODE_BALANCED :
                                    minimize_scanning ? ScanSettings.SCAN_MODE_BALANCED : ScanSettings.SCAN_MODE_LOW_LATENCY)
                            // .setScanMode(ScanSettings.SCAN_MODE_BALANCED)
                            .build(),

                    // scan filter doesn't work reliable on android sdk 23+
                    filter
            )
                    // observe on?
                    // do unsubscribe?
                    //.doOnUnsubscribe(this::clearSubscription)
                    .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");
    }
}
 
Example #23
Source File: ScanMeister.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
public ScanMeister setFilter(final ScanFilter filter) {
    this.customFilter = filter;
    return this;
}
 
Example #24
Source File: ScanMeister.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
public ScanMeister setFilter(final ScanFilter filter) {
    this.customFilter = filter;
    return this;
}
 
Example #25
Source File: Ob1G5CollectionService.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
private synchronized void scan_for_device() {
    if (state == SCAN) {
        msg(gs(R.string.scanning));
        stopScan();
        tryLoadingSavedMAC(); // did we already find it?
        if (always_scan || scan_next_run || (transmitterMAC == null) || (!transmitterID.equals(transmitterIDmatchingMAC)) || (static_last_timestamp < 1)) {
            scan_next_run = false; // reset if set
            transmitterMAC = null; // reset if set
            last_scan_started = JoH.tsl();
            scanWakeLock = JoH.getWakeLock("xdrip-jam-g5-scan", (int) Constants.MINUTE_IN_MS * 7);


            historicalTransmitterMAC = PersistentStore.getString(OB1G5_MACSTORE + transmitterID); // "" if unset

            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()
                            //.setScanMode(static_last_timestamp < 1 ? ScanSettings.SCAN_MODE_LOW_LATENCY : ScanSettings.SCAN_MODE_BALANCED)
                            //.setCallbackType(ScanSettings.CALLBACK_TYPE_FIRST_MATCH)
                            .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
                            // TODO revisit scan mode
                            .setScanMode(android_wear ? ScanSettings.SCAN_MODE_BALANCED :
                                    minimize_scanning ? ScanSettings.SCAN_MODE_BALANCED : ScanSettings.SCAN_MODE_LOW_LATENCY)
                            // .setScanMode(ScanSettings.SCAN_MODE_BALANCED)
                            .build(),

                    // scan filter doesn't work reliable on android sdk 23+
                    filter
            )
                    // observe on?
                    // do unsubscribe?
                    //.doOnUnsubscribe(this::clearSubscription)
                    .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");
    }
}
 
Example #26
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 #27
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 #28
Source File: ScanSetupBuilder.java    From RxAndroidBle with Apache License 2.0 votes vote down vote up
ScanSetup build(ScanSettings scanSettings, ScanFilter... scanFilters);