android.bluetooth.le.ScanCallback Java Examples

The following examples show how to use android.bluetooth.le.ScanCallback. 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: BluetoothAdapter.java    From android_9.0.0_r45 with Apache License 2.0 8 votes vote down vote up
/**
 * Stops an ongoing Bluetooth LE device scan.
 *
 * @param callback used to identify which scan to stop must be the same handle used to start the
 * scan
 * @deprecated Use {@link BluetoothLeScanner#stopScan(ScanCallback)} instead.
 */
@Deprecated
@RequiresPermission(Manifest.permission.BLUETOOTH_ADMIN)
public void stopLeScan(LeScanCallback callback) {
    if (DBG) {
        Log.d(TAG, "stopLeScan()");
    }
    BluetoothLeScanner scanner = getBluetoothLeScanner();
    if (scanner == null) {
        return;
    }
    synchronized (mLeScanClients) {
        ScanCallback scanCallback = mLeScanClients.remove(callback);
        if (scanCallback == null) {
            if (DBG) {
                Log.d(TAG, "scan not started yet");
            }
            return;
        }
        scanner.stopScan(scanCallback);
    }
}
 
Example #2
Source File: RxBleAdapterWrapper.java    From RxAndroidBle with Apache License 2.0 6 votes vote down vote up
@TargetApi(21 /* Build.VERSION_CODES.LOLLIPOP */)
public void stopLeScan(ScanCallback scanCallback) {
    if (!bluetoothAdapter.isEnabled()) {
        // this situation seems to be a problem since API 29
        RxBleLog.v(
                "BluetoothAdapter is disabled, calling BluetoothLeScanner.stopScan(ScanCallback) may cause IllegalStateException"
        );
        // if stopping the scan is not possible due to BluetoothAdapter turned off then it is probably stopped anyway
        return;
    }
    final BluetoothLeScanner bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
    if (bluetoothLeScanner == null) {
        RxBleLog.w(
                "Cannot call BluetoothLeScanner.stopScan(ScanCallback) on 'null' reference; BluetoothAdapter.isEnabled() == %b",
                bluetoothAdapter.isEnabled()
        );
        // if stopping the scan is not possible due to BluetoothLeScanner not accessible then it is probably stopped anyway
        // this should not happen since the check for BluetoothAdapter.isEnabled() has been added above. This situation was only
        // observed when the adapter was disabled
        return;
    }
    bluetoothLeScanner.stopScan(scanCallback);
}
 
Example #3
Source File: BluetoothCentralTest.java    From blessed-android with MIT License 6 votes vote down vote up
@Test
public void scanForPeripheralsTest()  throws Exception {
    application.grantPermissions(Manifest.permission.ACCESS_COARSE_LOCATION);
    central.scanForPeripherals();
    verify(scanner).startScan(anyList(), any(ScanSettings.class), any(ScanCallback.class));

    // Grab the scan callback that is used
    Field field = BluetoothCentral.class.getDeclaredField("scanByServiceUUIDCallback");
    field.setAccessible(true);
    ScanCallback scanCallback = (ScanCallback) field.get(central);

    // Fake scan result
    ScanResult scanResult = mock(ScanResult.class);
    BluetoothDevice device = mock(BluetoothDevice.class);
    when(device.getAddress()).thenReturn("00:00:00:00");
    when(scanResult.getDevice()).thenReturn(device);
    scanCallback.onScanResult(CALLBACK_TYPE_ALL_MATCHES, scanResult);

    // See if we get it back
    ArgumentCaptor<BluetoothPeripheral> bluetoothPeripheralCaptor = ArgumentCaptor.forClass(BluetoothPeripheral.class);
    ArgumentCaptor<ScanResult> scanResultCaptor = ArgumentCaptor.forClass(ScanResult.class);
    verify(callback).onDiscoveredPeripheral(bluetoothPeripheralCaptor.capture(), scanResultCaptor.capture());

    assertEquals(scanResultCaptor.getValue(), scanResult);
    assertEquals(bluetoothPeripheralCaptor.getValue().getAddress(), "00:00:00:00");
}
 
Example #4
Source File: BluetoothCentralTest.java    From blessed-android with MIT License 6 votes vote down vote up
@Test
public void autoconnectTwice() throws Exception {
    application.grantPermissions(Manifest.permission.ACCESS_COARSE_LOCATION);

    BluetoothPeripheral peripheral = mock(BluetoothPeripheral.class);
    when(peripheral.getAddress()).thenReturn("12:23:34:98:76:54");
    when(peripheral.getType()).thenReturn(BluetoothDevice.DEVICE_TYPE_UNKNOWN);
    central.autoConnectPeripheral(peripheral, peripheralCallback);

    verify(peripheral, never()).autoConnect();
    verify(scanner).startScan(anyList(), any(ScanSettings.class), any(ScanCallback.class));

    central.autoConnectPeripheral(peripheral, peripheralCallback);

    verify(peripheral, never()).autoConnect();
}
 
Example #5
Source File: BluetoothCentralTest.java    From blessed-android with MIT License 6 votes vote down vote up
@Test
public void stopScanTest() throws Exception {
    application.grantPermissions(Manifest.permission.ACCESS_COARSE_LOCATION);
    central.scanForPeripherals();
    verify(scanner).startScan(anyList(), any(ScanSettings.class), any(ScanCallback.class));

    // Grab the scan callback that is used
    Field field = BluetoothCentral.class.getDeclaredField("scanByServiceUUIDCallback");
    field.setAccessible(true);
    ScanCallback scanCallback = (ScanCallback) field.get(central);

    // Stop scan
    central.stopScan();

    // Check if scan is correctly stopped
    verify(scanner).stopScan(scanCallback);

    // Stop scan again
    central.stopScan();

    // Verify that stopScan is not called again
    verify(scanner, times(1)).stopScan(any(ScanCallback.class));
}
 
Example #6
Source File: BluetoothCentral.java    From blessed-android with MIT License 6 votes vote down vote up
/**
 * Set scan timeout timer, timeout time is {@code SCAN_TIMEOUT}.
 * If timeout is executed the scan is stopped and automatically restarted. This is done to avoid Android 9 scan restrictions
 */
private void setScanTimer() {
    cancelTimeoutTimer();

    timeoutRunnable = new Runnable() {
        @Override
        public void run() {
            Timber.d("scanning timeout, restarting scan");
            final ScanCallback callback = currentCallback;
            final List<ScanFilter> filters = currentFilters;
            stopScan();

            // Restart the scan and timer
            callBackHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    startScan(filters, scanSettings, callback);
                }
            }, SCAN_RESTART_DELAY);
        }
    };

    mainHandler.postDelayed(timeoutRunnable, SCAN_TIMEOUT);
}
 
Example #7
Source File: MockLollipopScanner.java    From bitgatt with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Stops an ongoing Bluetooth LE scan.
 *
 * @param callback
 */

public void stopScan(ScanCallback callback) {
    if (!BluetoothAdapter.getAdapterState()) {
        throw new IllegalStateException("Bluetooth off");
    }
    synchronized (mLeScanClients) {
        BleScanCallbackWrapper wrapper = mLeScanClients.remove(callback);
        if (wrapper == null) {
            if (DBG) Log.d(TAG, "could not find callback wrapper");
            return;
        }
        wrapper.stopLeScan();
    }
}
 
Example #8
Source File: MockLollipopScanner.java    From bitgatt with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Flush pending batch scan results stored in Bluetooth controller. This will return Bluetooth
 * LE scan results batched on bluetooth controller. Returns immediately, batch scan results data
 * will be delivered through the {@code callback}.
 *
 * @param callback Callback of the Bluetooth LE Scan, it has to be the same instance as the one
 *                 used to start scan.
 */
public void flushPendingScanResults(ScanCallback callback) {
    if (!BluetoothAdapter.getAdapterState()) {
        throw new IllegalStateException("Bluetooth off");
    }
    if (callback == null) {
        throw new IllegalArgumentException("callback cannot be null!");
    }
    synchronized (mLeScanClients) {
        BleScanCallbackWrapper wrapper = mLeScanClients.get(callback);
        if (wrapper == null) {
            return;
        }
        wrapper.flushPendingBatchResults();
    }
}
 
Example #9
Source File: MockLollipopScanner.java    From bitgatt with Mozilla Public License 2.0 6 votes vote down vote up
public BleScanCallbackWrapper(IBluetoothGatt bluetoothGatt,
                              List<ScanFilter> filters, ScanSettings settings,
                              WorkSource workSource, ScanCallback scanCallback,
                              List<List<ResultStorageDescriptor>> resultStorages) {
    mBluetoothGatt = bluetoothGatt;
    mFilters = filters;
    mSettings = settings;
    mWorkSource = workSource;
    mScanCallback = scanCallback;
    mScannerId = 0;
    mResultStorages = resultStorages;
}
 
Example #10
Source File: MockLollipopScanner.java    From bitgatt with Mozilla Public License 2.0 6 votes vote down vote up
public void startRegistration() {
    synchronized (this) {
        // Scan stopped.
        if (mScannerId == -1 || mScannerId == -2) return;
        try {
            mBluetoothGatt.registerScanner(this, mWorkSource);
            wait(REGISTRATION_CALLBACK_TIMEOUT_MILLIS);
        } catch (InterruptedException e) {
            Timber.tag(TAG).e(e, "application registration exception");
            postCallbackError(mScanCallback, ScanCallback.SCAN_FAILED_INTERNAL_ERROR);
        }
        if (mScannerId > 0) {
            mLeScanClients.put(mScanCallback, this);
        } else {
            // Registration timed out or got exception, reset RscannerId to -1 so no
            // subsequent operations can proceed.
            if (mScannerId == 0) mScannerId = -1;

            // If scanning too frequently, don't report anything to the app.
            if (mScannerId == -2) return;

            postCallbackError(mScanCallback,
                ScanCallback.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED);
        }
    }
}
 
Example #11
Source File: MockLollipopScanner.java    From bitgatt with Mozilla Public License 2.0 6 votes vote down vote up
private int postCallbackErrorOrReturn(final ScanCallback callback, final int errorCode) {
    if (callback == null) {
        return errorCode;
    } else {
        postCallbackError(callback, errorCode);
        return 0;
    }
}
 
Example #12
Source File: BluetoothAdapter.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Use {@link #getDefaultAdapter} to get the BluetoothAdapter instance.
 */
BluetoothAdapter(IBluetoothManager managerService) {

    if (managerService == null) {
        throw new IllegalArgumentException("bluetooth manager service is null");
    }
    try {
        mServiceLock.writeLock().lock();
        mService = managerService.registerAdapter(mManagerCallback);
    } catch (RemoteException e) {
        Log.e(TAG, "", e);
    } finally {
        mServiceLock.writeLock().unlock();
    }
    mManagerService = managerService;
    mLeScanClients = new HashMap<LeScanCallback, ScanCallback>();
    mToken = new Binder();
}
 
Example #13
Source File: DalvikBleService.java    From attach with GNU General Public License v3.0 6 votes vote down vote up
private ScanCallback createDeviceCallback() {
    return new ScanCallback() {

        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            BluetoothDevice device = result.getDevice();
            if (devices.values().contains(device)) {
                return;
            }
            String address = device.getAddress();
            String name = device.getName();
            devices.put(address, device);
            if (debug) {
                Log.v(TAG, "BLE discovered device: " + device + " with name: " + name + " and address: " + address);
            }
            scanDeviceDetected(name, address);
        }
    };
}
 
Example #14
Source File: ThrottledLollipopScannerTest.java    From RxCentralBle with Apache License 2.0 6 votes vote down vote up
@Test
public void scan_failed_onCallback() {
  when(bluetoothAdapter.isEnabled()).thenReturn(true);
  when(BluetoothAdapter.getDefaultAdapter()).thenReturn(bluetoothAdapter);

  scanDataTestObserver = scanner.scan().test();

  testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS);

  ArgumentCaptor<ScanCallback> argument = ArgumentCaptor.forClass(ScanCallback.class);
  verify(bluetoothLeScanner).startScan(any(), any(), argument.capture());

  argument.getValue().onScanFailed(0);

  scanDataTestObserver.assertError(
      throwable -> {
        ConnectionError error = (ConnectionError) throwable;
        return error != null && error.getCode() == ConnectionError.Code.SCAN_FAILED;
      });
}
 
Example #15
Source File: LollipopScannerTest.java    From RxCentralBle with Apache License 2.0 6 votes vote down vote up
@Test
public void scan_failed_onCallback() {
  when(bluetoothAdapter.isEnabled()).thenReturn(true);
  when(BluetoothAdapter.getDefaultAdapter()).thenReturn(bluetoothAdapter);

  scanDataTestObserver = scanner.scan().test();

  ArgumentCaptor<ScanCallback> argument = ArgumentCaptor.forClass(ScanCallback.class);
  verify(bluetoothLeScanner).startScan(any(), any(), argument.capture());

  argument.getValue().onScanFailed(0);

  scanDataTestObserver.assertError(
      throwable -> {
        ConnectionError error = (ConnectionError) throwable;
        return error != null && error.getCode() == ConnectionError.Code.SCAN_FAILED;
      });
}
 
Example #16
Source File: BlueToothService.java    From EFRConnect-android with Apache License 2.0 6 votes vote down vote up
private void stopDiscovery() {
    if (bluetoothAdapter == null) {
        return;
    }

    if (useBLE) {
        if (bluetoothAdapter.getBluetoothLeScanner() == null) {
            return;
        }

        if (bleScannerCallback != null) {
            bluetoothAdapter.getBluetoothLeScanner().stopScan((ScanCallback) bleScannerCallback);
        }
    } else if (bluetoothAdapter.isDiscovering()) {
        bluetoothAdapter.cancelDiscovery();
    }
}
 
Example #17
Source File: ScanOperationApi21.java    From RxAndroidBle with Apache License 2.0 6 votes vote down vote up
@BleScanException.Reason
static int errorCodeToBleErrorCode(int errorCode) {
    switch (errorCode) {
        case ScanCallback.SCAN_FAILED_ALREADY_STARTED:
            return BleScanException.SCAN_FAILED_ALREADY_STARTED;
        case ScanCallback.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED:
            return BleScanException.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED;
        case ScanCallback.SCAN_FAILED_FEATURE_UNSUPPORTED:
            return BleScanException.SCAN_FAILED_FEATURE_UNSUPPORTED;
        case ScanCallback.SCAN_FAILED_INTERNAL_ERROR:
            return BleScanException.SCAN_FAILED_INTERNAL_ERROR;
        case 5: // ScanCallback.SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES
            return BleScanException.SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES;
        default:
            RxBleLog.w("Encountered unknown scanning error code: %d -> check android.bluetooth.le.ScanCallback");
            return BleScanException.UNKNOWN_ERROR_CODE;
    }
}
 
Example #18
Source File: BluetoothCentral.java    From blessed-android with MIT License 5 votes vote down vote up
private void startScan(List<ScanFilter> filters, ScanSettings scanSettings, ScanCallback scanCallback) {
    // Check is BLE is available, enabled and all permission granted
    if (!isBleReady()) return;

    // Make sure we are not already scanning, we only want one scan at the time
    if (isScanning()) {
        Timber.e("other scan still active, stopping scan");
        stopScan();
    }

    // Get a new scanner object
    if (bluetoothScanner == null) {
        bluetoothScanner = bluetoothAdapter.getBluetoothLeScanner();
    }

    // If get scanner was succesful, start the scan
    if (bluetoothScanner != null) {
        // Start the scanner
        setScanTimer();
        currentCallback = scanCallback;
        currentFilters = filters;
        bluetoothScanner.startScan(filters, scanSettings, scanCallback);
        Timber.i("scan started");
    } else {
        Timber.e("starting scan failed");
    }
}
 
Example #19
Source File: BluetoothGlucoseMeter.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
@TargetApi(21)
private void initScanCallback() {
    Log.d(TAG, "init v21 ScanCallback()");

    // v21 version
    if (Build.VERSION.SDK_INT >= 21) {
        mScanCallback = new ScanCallback() {
            @Override
            public void onScanResult(int callbackType, ScanResult result) {
                Log.i(TAG, "onScanResult result: " + result.toString());
                final BluetoothDevice btDevice = result.getDevice();
                scanLeDevice(false); // stop scanning
                connect(btDevice.getAddress());
            }

            @Override
            public void onBatchScanResults(List<ScanResult> results) {
                for (ScanResult sr : results) {
                    Log.i("ScanResult - Results", sr.toString());
                }
            }

            @Override
            public void onScanFailed(int errorCode) {
                Log.e(TAG, "Scan Failed Error Code: " + errorCode);
                if (errorCode == 1) {
                    Log.e(TAG, "Already Scanning: "); // + isScanning);
                    //isScanning = true;
                } else if (errorCode == 2) {
                    // reset bluetooth?
                }
            }
        };
    }
}
 
Example #20
Source File: P_BluetoothCrashResolver.java    From AsteroidOSSync with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Call this method from your BluetoothAdapter.LeScanCallback method.
 * Doing so is optional, but if you do, this class will be able to count the number of
 * disctinct bluetooth devices scanned, and prevent crashes before they happen.
 *
 * This works very well if the app containing this class is the only one running bluetooth
 * LE scans on the device, or it is constantly doing scans (e.g. is in the foreground for
 * extended periods of time.)
 *
 * This will not work well if the application using this class is only scanning periodically
 * (e.g. when in the background to save battery) and another application is also scanning on
 * the same device, because this class will only get the counts from this application.
 *
 * Future augmentation of this class may improve this by somehow centralizing the list of
 * unique scanned devices.
 *
 * @param device
 */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void notifyScannedDevice(P_NativeDeviceLayer device, BluetoothAdapter.LeScanCallback scanner, ScanCallback callback) {
    int oldSize = 0, newSize = 0;

    if (isDebugEnabled()) oldSize = distinctBluetoothAddresses.size();

    synchronized (distinctBluetoothAddresses)
    {
        distinctBluetoothAddresses.add(device.getAddress());
    }
    if (isDebugEnabled()) {
        newSize = distinctBluetoothAddresses.size();
        if (oldSize != newSize && newSize % 100 == 0) {
            if (isDebugEnabled()) Log.d(TAG, "Distinct bluetooth devices seen: "+distinctBluetoothAddresses.size());
        }
    }
    if (distinctBluetoothAddresses.size()  > getCrashRiskDeviceCount()) {
        if (PREEMPTIVE_ACTION_ENABLED && !recoveryInProgress) {
            Log.w(TAG, "Large number of bluetooth devices detected: "+distinctBluetoothAddresses.size()+" Proactively attempting to clear out address list to prevent a crash");
            Log.w(TAG, "Stopping LE Scan");
            if (scanner != null)
            {
                BluetoothAdapter.getDefaultAdapter().stopLeScan(scanner);
            }
            else
            {
                BluetoothAdapter.getDefaultAdapter().getBluetoothLeScanner().stopScan(callback);
            }
            startRecovery();
            processStateChange();
        }
    }
}
 
Example #21
Source File: P_BluetoothCrashResolver.java    From SweetBlue with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Call this method from your BluetoothAdapter.LeScanCallback method.
 * Doing so is optional, but if you do, this class will be able to count the number of
 * disctinct bluetooth devices scanned, and prevent crashes before they happen.
 *
 * This works very well if the app containing this class is the only one running bluetooth
 * LE scans on the device, or it is constantly doing scans (e.g. is in the foreground for
 * extended periods of time.)
 *
 * This will not work well if the application using this class is only scanning periodically
 * (e.g. when in the background to save battery) and another application is also scanning on
 * the same device, because this class will only get the counts from this application.
 *
 * Future augmentation of this class may improve this by somehow centralizing the list of
 * unique scanned devices.
 *
 * @param device
 */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void notifyScannedDevice(P_NativeDeviceLayer device, BluetoothAdapter.LeScanCallback scanner, ScanCallback callback) {
    int oldSize = 0, newSize = 0;

    if (isDebugEnabled()) oldSize = distinctBluetoothAddresses.size();

    synchronized (distinctBluetoothAddresses)
    {
        distinctBluetoothAddresses.add(device.getAddress());
    }
    if (isDebugEnabled()) {
        newSize = distinctBluetoothAddresses.size();
        if (oldSize != newSize && newSize % 100 == 0) {
            if (isDebugEnabled()) Log.d(TAG, "Distinct bluetooth devices seen: "+distinctBluetoothAddresses.size());
        }
    }
    if (distinctBluetoothAddresses.size()  > getCrashRiskDeviceCount()) {
        if (PREEMPTIVE_ACTION_ENABLED && !recoveryInProgress) {
            Log.w(TAG, "Large number of bluetooth devices detected: "+distinctBluetoothAddresses.size()+" Proactively attempting to clear out address list to prevent a crash");
            Log.w(TAG, "Stopping LE Scan");
            if (scanner != null)
            {
                BluetoothAdapter.getDefaultAdapter().stopLeScan(scanner);
            }
            else
            {
                BluetoothAdapter.getDefaultAdapter().getBluetoothLeScanner().stopScan(callback);
            }
            startRecovery();
            processStateChange();
        }
    }
}
 
Example #22
Source File: BluetoothGlucoseMeter.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
@TargetApi(21)
private void initScanCallback() {
    Log.d(TAG, "init v21 ScanCallback()");

    // v21 version
    if (Build.VERSION.SDK_INT >= 21) {
        mScanCallback = new ScanCallback() {
            @Override
            public void onScanResult(int callbackType, ScanResult result) {
                Log.i(TAG, "onScanResult result: " + result.toString());
                final BluetoothDevice btDevice = result.getDevice();
                scanLeDevice(false); // stop scanning
                connect(btDevice.getAddress());
            }

            @Override
            public void onBatchScanResults(List<ScanResult> results) {
                for (ScanResult sr : results) {
                    Log.i("ScanResult - Results", sr.toString());
                }
            }

            @Override
            public void onScanFailed(int errorCode) {
                Log.e(TAG, "Scan Failed Error Code: " + errorCode);
                if (errorCode == 1) {
                    Log.e(TAG, "Already Scanning: "); // + isScanning);
                    //isScanning = true;
                } else if (errorCode == 2) {
                    // reset bluetooth?
                }
            }
        };
    }
}
 
Example #23
Source File: BluetoothLeScannerSnippet.java    From mobly-bundled-snippets with Apache License 2.0 5 votes vote down vote up
/**
 * Stop a BLE scan.
 *
 * @param callbackId The callbackId corresponding to the {@link
 *     BluetoothLeScannerSnippet#bleStartScan} call that started the scan.
 * @throws BluetoothLeScanSnippetException
 */
@RpcMinSdk(Build.VERSION_CODES.LOLLIPOP_MR1)
@Rpc(description = "Stop a BLE scan.")
public void bleStopScan(String callbackId) throws BluetoothLeScanSnippetException {
    ScanCallback callback = mScanCallbacks.remove(callbackId);
    if (callback == null) {
        throw new BluetoothLeScanSnippetException("No ongoing scan with ID: " + callbackId);
    }
    mScanner.stopScan(callback);
}
 
Example #24
Source File: LollipopScannerTest.java    From RxCentralBle with Apache License 2.0 5 votes vote down vote up
@Test
public void scan_withMatches() {
  when(bluetoothAdapter.isEnabled()).thenReturn(true);
  when(BluetoothAdapter.getDefaultAdapter()).thenReturn(bluetoothAdapter);

  scanDataTestObserver = scanner.scan().test();

  ArgumentCaptor<ScanCallback> argument = ArgumentCaptor.forClass(ScanCallback.class);
  verify(bluetoothLeScanner).startScan(any(), any(), argument.capture());

  argument.getValue().onScanResult(0, scanResult);

  scanDataTestObserver.assertValueCount(1);
}
 
Example #25
Source File: ThrottledLollipopScannerTest.java    From RxCentralBle with Apache License 2.0 5 votes vote down vote up
@Test
public void scan_start_throttling() {
  when(bluetoothAdapter.isEnabled()).thenReturn(true);
  when(BluetoothAdapter.getDefaultAdapter()).thenReturn(bluetoothAdapter);

  scanDataTestObserver = scanner.scan().test();
  testScheduler.advanceTimeBy(SCAN_WINDOW_MS / 5, TimeUnit.MILLISECONDS);
  scanDataTestObserver.dispose();

  scanDataTestObserver = scanner.scan().test();
  testScheduler.advanceTimeBy(SCAN_WINDOW_MS / 5, TimeUnit.MILLISECONDS);
  scanDataTestObserver.dispose();

  scanDataTestObserver = scanner.scan().test();
  testScheduler.advanceTimeBy(SCAN_WINDOW_MS / 5, TimeUnit.MILLISECONDS);
  scanDataTestObserver.dispose();

  scanDataTestObserver = scanner.scan().test();
  testScheduler.advanceTimeBy(SCAN_WINDOW_MS / 5, TimeUnit.MILLISECONDS);
  scanDataTestObserver.dispose();

  scanDataTestObserver = scanner.scan().test();
  testScheduler.advanceTimeBy(SCAN_WINDOW_MS / 5, TimeUnit.MILLISECONDS);

  verify(bluetoothLeScanner, times(4))
          .startScan(any(), any(), any(ScanCallback.class));

  testScheduler.advanceTimeBy(SCAN_WINDOW_MS, TimeUnit.MILLISECONDS);

  verify(bluetoothLeScanner, times(5))
          .startScan(any(), any(), any(ScanCallback.class));
}
 
Example #26
Source File: ThrottledLollipopScannerTest.java    From RxCentralBle with Apache License 2.0 5 votes vote down vote up
@Test
public void scan_duration_throttling() {
  when(bluetoothAdapter.isEnabled()).thenReturn(true);
  when(BluetoothAdapter.getDefaultAdapter()).thenReturn(bluetoothAdapter);

  scanDataTestObserver = scanner.scan().test();

  testScheduler.advanceTimeBy(ANDROID_7_MAX_SCAN_DURATION_MS * 3, TimeUnit.MILLISECONDS);

  verify(bluetoothLeScanner, times(3))
          .startScan(any(), any(), any(ScanCallback.class));

  verify(bluetoothLeScanner, times(2)).stopScan(any(ScanCallback.class));
}
 
Example #27
Source File: BluetoothCentralTest.java    From blessed-android with MIT License 5 votes vote down vote up
@Test
public void scanForPeripheralsWithNamesTest() throws Exception {
    application.grantPermissions(Manifest.permission.ACCESS_COARSE_LOCATION);
    String myName = "Polar";
    central.scanForPeripheralsWithNames(new String[]{myName});

    // Make sure startScan is called
    ArgumentCaptor<List> scanFiltersCaptor = ArgumentCaptor.forClass(List.class);
    ArgumentCaptor<ScanSettings> scanSettingsCaptor = ArgumentCaptor.forClass(ScanSettings.class);
    ArgumentCaptor<ScanCallback> scanCallbackCaptor = ArgumentCaptor.forClass(ScanCallback.class);
    verify(scanner).startScan(scanFiltersCaptor.capture(), scanSettingsCaptor.capture(), scanCallbackCaptor.capture());

    // Verify there is no filter set
    List<ScanFilter> filters = scanFiltersCaptor.getValue();
    assertNull(filters);

    // Grab the scan callback that is used
    Field field = BluetoothCentral.class.getDeclaredField("scanByNameCallback");
    field.setAccessible(true);
    ScanCallback scanCallback = (ScanCallback) field.get(central);

    // Fake scan result
    ScanResult scanResult = mock(ScanResult.class);
    BluetoothDevice device = mock(BluetoothDevice.class);
    when(device.getName()).thenReturn("Polar H7");
    when(scanResult.getDevice()).thenReturn(device);
    scanCallback.onScanResult(CALLBACK_TYPE_ALL_MATCHES, scanResult);

    // See if we get it back
    ArgumentCaptor<BluetoothPeripheral> bluetoothPeripheralCaptor = ArgumentCaptor.forClass(BluetoothPeripheral.class);
    ArgumentCaptor<ScanResult> scanResultCaptor = ArgumentCaptor.forClass(ScanResult.class);
    verify(callback).onDiscoveredPeripheral(bluetoothPeripheralCaptor.capture(), scanResultCaptor.capture());

    assertEquals(scanResultCaptor.getValue(), scanResult);
    assertEquals(bluetoothPeripheralCaptor.getValue().getName(), "Polar H7");
}
 
Example #28
Source File: BluetoothCentralTest.java    From blessed-android with MIT License 5 votes vote down vote up
@Test
public void scanFailedTest() throws Exception {
    application.grantPermissions(Manifest.permission.ACCESS_COARSE_LOCATION);
    central.scanForPeripherals();
    verify(scanner).startScan(anyList(), any(ScanSettings.class), any(ScanCallback.class));

    // Grab the scan callback that is used
    Field field = BluetoothCentral.class.getDeclaredField("scanByServiceUUIDCallback");
    field.setAccessible(true);
    ScanCallback scanCallback = (ScanCallback) field.get(central);

    scanCallback.onScanFailed(SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES);

    verify(callback).onScanFailed(SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES);
}
 
Example #29
Source File: BluetoothCentralTest.java    From blessed-android with MIT License 5 votes vote down vote up
@Test
public void scanFailedAutoconnectTest() throws Exception {
    // Grab the scan callback that is used
    Field field = BluetoothCentral.class.getDeclaredField("autoConnectScanCallback");
    field.setAccessible(true);
    ScanCallback scanCallback = (ScanCallback) field.get(central);

    scanCallback.onScanFailed(SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES);

    verify(callback).onScanFailed(SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES);
}
 
Example #30
Source File: BluetoothLeScannerSnippet.java    From mobly-bundled-snippets with Apache License 2.0 5 votes vote down vote up
@Override
public void shutdown() {
    for (ScanCallback callback : mScanCallbacks.values()) {
        mScanner.stopScan(callback);
    }
    mScanCallbacks.clear();
}