Java Code Examples for android.bluetooth.le.ScanFilter

The following are top voted examples for showing how to use android.bluetooth.le.ScanFilter. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: android-ponewheel   File: BluetoothUtilImpl.java   Source Code and License 10 votes vote down vote up
void scanLeDevice(final boolean enable) {
    Timber.d("scanLeDevice enable = " + enable);
    if (enable) {
        mScanning = true;
        List<ScanFilter> filters_v2 = new ArrayList<>();
        ScanFilter scanFilter = new ScanFilter.Builder()
                .setServiceUuid(ParcelUuid.fromString(OWDevice.OnewheelServiceUUID))
                .build();
        filters_v2.add(scanFilter);
        //c03f7c8d-5e96-4a75-b4b6-333d36230365
        mBluetoothLeScanner.startScan(filters_v2, settings, mScanCallback);
    } else {
        mScanning = false;
        mBluetoothLeScanner.stopScan(mScanCallback);
        // added 10/23 to try cleanup
        mBluetoothLeScanner.flushPendingScanResults(mScanCallback);
    }
    mainActivity.invalidateOptionsMenu();
}
 
Example 2
Project: mDL-ILP   File: BTConnection.java   Source Code and License 7 votes vote down vote up
@NonNull
private List<ScanFilter> getScanFilters(final byte[] serviceData) {
    return Arrays.asList(
                new ScanFilter[]{
                        new ScanFilter.Builder()
                                .setServiceData(Constants.SERVICE_pUUID, serviceData)
                                .build()
                });
}
 
Example 3
Project: AndroidMuseumBleManager   File: ScanFilterCompat.java   Source Code and License 7 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public ScanFilter toApi21() {
    ScanFilter.Builder builder = new ScanFilter.Builder();
    if (mDeviceName != null) {
        builder.setDeviceName(mDeviceName);
    }
    if (mServiceUuid != null) {
        builder.setServiceUuid(mServiceUuid, mServiceUuidMask);
    }
    if (mDeviceAddress != null) {
        builder.setDeviceAddress(mDeviceAddress);
    }
    if (mServiceDataUuid != null) {
        builder.setServiceData(mServiceDataUuid, mServiceData, mServiceDataMask);
    }
    if (mManufacturerId < 0) {
        builder.setManufacturerData(mManufacturerId, mManufacturerData, mManufacturerDataMask);
    }
    return builder.build();
}
 
Example 4
Project: u2f-ble-test   File: U2FBLEDevice.java   Source Code and License 6 votes vote down vote up
protected static void scanDevice(BluetoothAdapter bluetoothAdapter, U2FBLEDeviceNotification notification, Logger logger, Context context, String data, ScanType scanType) {
	BluetoothLeScanner bluetoothScanner = bluetoothAdapter.getBluetoothLeScanner();
	ScanFilter.Builder builder = new ScanFilter.Builder();
	switch(scanType) {
		case SCAN_BY_NAME:
			builder.setDeviceName(data);
			break;
	}
	Vector<ScanFilter> filter = new Vector<ScanFilter>();
	filter.add(builder.build());
	ScanSettings.Builder builderScanSettings = new ScanSettings.Builder();
	builderScanSettings.setScanMode(ScanSettings.SCAN_MODE_BALANCED);
	builderScanSettings.setReportDelay(0);
	LocalScanCallback scannerCallback = new LocalScanCallback(bluetoothAdapter, logger, notification, context);
	bluetoothScanner.startScan(filter, builderScanSettings.build(), scannerCallback);		
}
 
Example 5
Project: xDrip   File: BluetoothGlucoseMeter.java   Source Code and License 6 votes vote down vote up
private void beginScan() {
    if (Build.VERSION.SDK_INT >= 21) {
        if (d) Log.d(TAG, "Preparing for scan...");

        // set up v21 scanner
        mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
        settings = new ScanSettings.Builder()
                .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                .build();
        filters = new ArrayList<>();

        filters.add(new ScanFilter.Builder().setServiceUuid(new ParcelUuid(GLUCOSE_SERVICE)).build());
    }
    // all api versions
    scanLeDevice(true);
}
 
Example 6
Project: xDrip-plus   File: BluetoothGlucoseMeter.java   Source Code and License 6 votes vote down vote up
private void beginScan() {
    if (Build.VERSION.SDK_INT >= 21) {
        if (d) Log.d(TAG, "Preparing for scan...");

        // set up v21 scanner
        mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
        settings = new ScanSettings.Builder()
                .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                .build();
        filters = new ArrayList<>();

        filters.add(new ScanFilter.Builder().setServiceUuid(new ParcelUuid(GLUCOSE_SERVICE)).build());
    }
    // all api versions
    scanLeDevice(true);
}
 
Example 7
Project: SensorLib   File: DsSensorManager.java   Source Code and License 6 votes vote down vote up
public static void searchBleDeviceByNames(final SensorFoundCallback callback, String[] deviceNames) {
    //Log.e(TAG, "Searching for BLE device...");

    List<ScanFilter> filterList = new ArrayList<>();
    for (String name : deviceNames) {
        filterList.add(new ScanFilter.Builder().setDeviceName(name).build());
    }

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
        if (sBleScanner == null) {
            sBleScanner = BluetoothAdapter.getDefaultAdapter().getBluetoothLeScanner();
        }
        if (sScanCallback == null) {
            sScanCallback = new DsScanCallback(callback);
        }

        if (sBleScanner != null) {
            sBleScanner.startScan(filterList, new ScanSettings.Builder().build(), sScanCallback);
        }
    }
}
 
Example 8
Project: SensorLib   File: DsSensorManager.java   Source Code and License 6 votes vote down vote up
public static void searchBleDeviceByUUIDs(SensorFoundCallback callback, UUID[] uuids) {
    //Log.e(TAG, "Searching for BLE device...");

    List<ScanFilter> filterList = new ArrayList<>();
    for (UUID uuid : uuids) {
        filterList.add(new ScanFilter.Builder().setServiceUuid(new ParcelUuid(uuid)).build());
    }

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
        if (sBleScanner == null) {
            sBleScanner = BluetoothAdapter.getDefaultAdapter().getBluetoothLeScanner();
        }
        if (sScanCallback == null) {
            sScanCallback = new DsScanCallback(callback);
        }

        if (sBleScanner != null) {
            sBleScanner.startScan(filterList, new ScanSettings.Builder().build(), sScanCallback);
        }
    }
}
 
Example 9
Project: AndroidBleManager   File: ScanFilterCompat.java   Source Code and License 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public ScanFilter toApi21() {
    ScanFilter.Builder builder = new ScanFilter.Builder();
    if (mDeviceName != null) {
        builder.setDeviceName(mDeviceName);
    }
    if (mServiceUuid != null) {
        builder.setServiceUuid(mServiceUuid, mServiceUuidMask);
    }
    if (mDeviceAddress != null) {
        builder.setDeviceAddress(mDeviceAddress);
    }
    if (mServiceDataUuid != null) {
        builder.setServiceData(mServiceDataUuid, mServiceData, mServiceDataMask);
    }
    if (mManufacturerId < 0) {
        builder.setManufacturerData(mManufacturerId, mManufacturerData, mManufacturerDataMask);
    }
    return builder.build();
}
 
Example 10
Project: AndroidBleManager   File: BluetoothLeScannerCompat.java   Source Code and License 6 votes vote down vote up
@Override
public void startScan(BluetoothAdapter adapter, List<ScanFilterCompat> filters, ScanSettingsCompat settings, ScanCallbackCompat callbackCompat) {

    List<ScanFilter> scanFilters = null;
    if (filters != null) {
        scanFilters = new ArrayList<>(filters.size());

        for (ScanFilterCompat filter : filters) {
            scanFilters.add(filter.toApi21());
        }
    }
    if (settings == null) {
        throw new IllegalStateException("Scan settings are null");
    }
    ScanSettings scanSettings = settings.toApi21();
    adapter.getBluetoothLeScanner().startScan(scanFilters, scanSettings, registerCallback(callbackCompat));
}
 
Example 11
Project: DeviceConnect-Android   File: NewBleDeviceAdapterImpl.java   Source Code and License 6 votes vote down vote up
@Override
public void startScan(final BleDeviceScanCallback callback) {
    mCallback = callback;

    final List<ScanFilter> filters = new ArrayList<>();

    final ScanSettings settings = new ScanSettings.Builder().build();
    mBleScanner = mBluetoothAdapter.getBluetoothLeScanner();

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        if (mBleScanner != null) {
            mBleScanner.startScan(filters, settings, mScanCallback);
        }
    } else {
        // Unless required permissions were acquired, scan does not start.
        if (BleUtils.isBLEPermission(mContext)) {
            if (mBleScanner != null) {
                mBleScanner.startScan(filters, settings, mScanCallback);
            }
        }
    }
}
 
Example 12
Project: DeviceConnect-Android   File: NewBleDeviceAdapterImpl.java   Source Code and License 6 votes vote down vote up
@Override
public void startScan(final BleDeviceScanCallback callback) {
    mCallback = callback;

    List<ScanFilter> filters = new ArrayList<ScanFilter>();
    if (mServiceUuids != null && mServiceUuids.length > 0) {
        for (UUID uuid : mServiceUuids) {
            ScanFilter filter = new ScanFilter.Builder().setServiceUuid(
                    new ParcelUuid(uuid)).build();
            filters.add(filter);
        }
    }
    ScanSettings settings = new ScanSettings.Builder().build();

    mBleScanner = mBluetoothAdapter.getBluetoothLeScanner();
    if (mBleScanner != null) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            mBleScanner.startScan(filters, settings, mScanCallback);
        } else {
            // Unless required permissions were acquired, scan does not start.
            if (BleUtils.isBLEPermission(mContext)) {
                mBleScanner.startScan(filters, settings, mScanCallback);
            }
        }
    }
}
 
Example 13
Project: BluetoothCompat   File: ScanFilterCompat.java   Source Code and License 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
ScanFilter toApi21() {
    ScanFilter.Builder builder = new ScanFilter.Builder();
    if (mDeviceName != null) {
        builder.setDeviceName(mDeviceName);
    }
    if (mServiceUuid != null) {
        builder.setServiceUuid(mServiceUuid, mServiceUuidMask);
    }
    if (mDeviceAddress != null) {
        builder.setDeviceAddress(mDeviceAddress);
    }
    if (mServiceDataUuid != null) {
        builder.setServiceData(mServiceDataUuid, mServiceData, mServiceDataMask);
    }
    if (mManufacturerId < 0) {
        builder.setManufacturerData(mManufacturerId, mManufacturerData, mManufacturerDataMask);
    }
    return builder.build();
}
 
Example 14
Project: BluetoothCompat   File: BluetoothLeScannerCompat.java   Source Code and License 6 votes vote down vote up
@Override
public void startScan(BluetoothAdapter adapter, List<ScanFilterCompat> filters, ScanSettingsCompat settings, ScanCallbackCompat callbackCompat) {

    List<ScanFilter> scanFilters = null;
    if (filters != null) {
        scanFilters = new ArrayList<>(filters.size());

        for (ScanFilterCompat filter : filters) {
            scanFilters.add(filter.toApi21());
        }
    }
    if (settings == null) {
        throw new IllegalStateException("Scan settings are null");
    }
    ScanSettings scanSettings = settings.toApi21();
    adapter.getBluetoothLeScanner().startScan(scanFilters, scanSettings, registerCallback(callbackCompat));
}
 
Example 15
Project: nearby-beacons   File: EddystoneScannerService.java   Source Code and License 6 votes vote down vote up
private void startScanning() {
    List<ScanFilter> filters = new ArrayList<>();
    //Filter on just our requested namespaces
    for (String namespace : NAMESPACE_IDS) {
        ScanFilter beaconFilter = new ScanFilter.Builder()
                .setServiceUuid(UID_SERVICE)
                .setServiceData(UID_SERVICE, getNamespaceFilter(namespace),
                        NAMESPACE_FILTER_MASK)
                .build();
        filters.add(beaconFilter);
    }

    //Run in background mode
    ScanSettings settings = new ScanSettings.Builder()
            .setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)
            .build();

    mBluetoothLeScanner.startScan(filters, settings, mScanCallback);
    if (DEBUG_SCAN) Log.d(TAG, "Scanning started…");
}
 
Example 16
Project: SensorTag-Accelerometer   File: ScanFragment.java   Source Code and License 5 votes vote down vote up
/**
 * Initiates the scan for BLE devices according to the API level.
 */
private void startScan() {
    if (mRecyclerViewAdapter.getSize() == 0) mListener.onShowProgress();
    if (Build.VERSION.SDK_INT < 21) {
        mBluetoothAdapter.startLeScan(mLeScanCallback);
    } else {
        // request BluetoothLeScanner if it hasn't been initialized yet
        if (mLeScanner == null) mLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
        // start scan in low latency mode
        mLeScanner.startScan(new ArrayList<ScanFilter>(), new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build(), mScanCallback);
    }
}
 
Example 17
Project: igrow-android   File: BluetoothLeScanL21Proxy.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void startLeScan() {
    List<ScanFilter> filters = new ArrayList<ScanFilter>();
    ScanFilter filter = new ScanFilter.Builder().build();
    filters.add(filter);

    ScanSettings settings = new ScanSettings.Builder().setScanMode(SCAN_MODE_LOW_LATENCY)
            .build();

    mBluetoothLeScanner.startScan(filters, settings, mLeScanCallback);
}
 
Example 18
Project: microbit   File: PairingActivity.java   Source Code and License 5 votes vote down vote up
/**
 * Allows to start or stop scanning for a low energy device.
 *
 * @param enable True - start scanning, false - stop scanning.
 */
private void scanLeDevice(final boolean enable) {
    logi("scanLeDevice() :: enable = " + enable);
    if(enable) {
        //Start scanning.
        if(!setupBleController()) {
            logi("scanLeDevice() :: FAILED ");
            return;
        }
        if(!scanning) {
            logi("scanLeDevice ::   Searching For " + newDeviceName.toLowerCase());
            // Stops scanning after a pre-defined scan period.
            scanning = true;
            ((TextView) findViewById(R.id.search_microbit_step_3_title))
                    .setText(getString(R.string.searchingTitle));
            handler.postDelayed(scanTimedOut, SCAN_PERIOD);
            if(Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                bluetoothAdapter.startLeScan(getOldScanCallback());
            } else {
                List<ScanFilter> filters = new ArrayList<>();
                // TODO: play with ScanSettings further to ensure the Kit kat devices connectMaybeInit with higher success rate
                ScanSettings settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_BALANCED).build();
                leScanner.startScan(filters, settings, getNewScanCallback());
            }
        }
    } else {
        //Stop scanning.
        if(scanning) {
            scanning = false;
            handler.removeCallbacks(scanTimedOut);
            if(Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                bluetoothAdapter.stopLeScan(getOldScanCallback());
            } else {
                leScanner.stopScan(getNewScanCallback());
            }
        }
    }
}
 
Example 19
Project: AndroidSensors   File: BLEMeasurementsGatherer.java   Source Code and License 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void configureSensorSubscribeAndUnsubscribeBehaviors(FlowableEmitter<SensorRecord> subscriber) {
    List<ScanFilter> scanFilters = initializeScanFilters();
    ScanSettings scanSettings = initializeScanSettings();
    final ScanCallback scanCallback = initializeScanCallbackFor(subscriber);

    startListeningBluetoothMeasurements(scanFilters, scanSettings, scanCallback);
    addUnsuscribeCallbackFor(subscriber, scanCallback);
}
 
Example 20
Project: AndroidSensors   File: BLEMeasurementsGatherer.java   Source Code and License 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void startListeningBluetoothMeasurements(List<ScanFilter> scanFilters,
                                                 ScanSettings scanSettings,
                                                 ScanCallback scanCallback){
    BluetoothLeScanner scanner = bluetoothManager.getAdapter().getBluetoothLeScanner();
    scanner.startScan(scanFilters, scanSettings, scanCallback);
}
 
Example 21
Project: UDOOBluLib-android   File: UdooBluService.java   Source Code and License 5 votes vote down vote up
public void scanLeDevice(final boolean enable, final BluScanCallBack scanCallback) {
    List<ScanFilter> scanFilters = new ArrayList<>();
    ScanFilter scanFilter = new ScanFilter.Builder().setServiceUuid(new ParcelUuid(UDOOBLE.UUID_SENSORS_SERV)).build();
    scanFilters.add(scanFilter);

    ScanSettings scanSettings = new ScanSettings.Builder()
            .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
            .build();

    UdooBluException udooBluException = checkBluetooth(getApplicationContext());
    if (udooBluException != null) {
        if (scanCallback != null)
            scanCallback.onError(udooBluException);
    } else {
        mLEScanner = mBtAdapter.getBluetoothLeScanner();
        if (enable && mScanning.compareAndSet(false, true)) {
            mLEScanner.startScan(scanFilters, scanSettings, scanCallback);
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mLEScanner.stopScan(scanCallback);
                    mScanning.set(false);
                    if (scanCallback != null)
                        scanCallback.onScanFinished();
                }
            }, SCAN_PERIOD);
        } else {
            mScanning.set(false);
            mLEScanner.stopScan(scanCallback);
            if (scanCallback != null)
                scanCallback.onScanFinished();
        }
    }
}
 
Example 22
Project: science-journal   File: DeviceDiscovererV21.java   Source Code and License 5 votes vote down vote up
@Override
public void onStartScanning() {
    mScanner = getBluetoothAdapter().getBluetoothLeScanner();
    List<ScanFilter> filters = new ArrayList<>();
    for (BleServiceSpec spec : BluetoothSensor.SUPPORTED_SERVICES) {
        filters.add(new ScanFilter.Builder()
                .setServiceUuid(ParcelUuid.fromString(spec.getServiceId().toString()))
                .build());
    }
    ScanSettings settings = new ScanSettings.Builder()
            .setScanMode(ScanSettings.SCAN_MODE_BALANCED)
            .build();
    mScanner.startScan(filters, settings, mCallback);
}
 
Example 23
Project: TappyBLE   File: TappyBleVersionUtils.java   Source Code and License 5 votes vote down vote up
public static List<com.taptrack.tcmptappy.blescannercompat.ScanFilter> getCompatScanFilter() {
    com.taptrack.tcmptappy.blescannercompat.ScanFilter.Builder builder =
            new com.taptrack.tcmptappy.blescannercompat.ScanFilter.Builder();
    builder.setServiceUuid(new ParcelUuid(TappyVersions.VersionOne.TRUCONNECT_SERVICE_UUID));
    List<com.taptrack.tcmptappy.blescannercompat.ScanFilter> list = new ArrayList<com.taptrack.tcmptappy.blescannercompat.ScanFilter>(1);
    list.add(builder.build());
    return list;
}
 
Example 24
Project: TappyBLE   File: TappyBleVersionUtils.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static List<ScanFilter> getScanFilter() {
    ScanFilter.Builder builder =
            new ScanFilter.Builder();
    builder.setServiceUuid(new ParcelUuid(TappyVersions.VersionOne.TRUCONNECT_SERVICE_UUID));
    List<ScanFilter> list = new ArrayList<ScanFilter>(1);
    list.add(builder.build());
    return list;
}
 
Example 25
Project: TappyBLE   File: LollipopUtils.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static List<ScanFilter> convertCompatScanFilterListToNative(List<com.taptrack.tcmptappy.blescannercompat.ScanFilter> compatFilters) {
    if(compatFilters == null)
        return null;
    List<ScanFilter> nativeFilters = new ArrayList<>(compatFilters.size());
    for (com.taptrack.tcmptappy.blescannercompat.ScanFilter compatFilter :
            compatFilters) {
        nativeFilters.add(convertCompatScanFilterToNative(compatFilter));
    }
    return nativeFilters;
}
 
Example 26
Project: u2f-ble-test   File: MainActivity.java   Source Code and License 5 votes vote down vote up
private void startScan() {
	BluetoothLeScanner bluetoothScanner = bluetoothAdapter.getBluetoothLeScanner();
	ScanFilter.Builder builder = new ScanFilter.Builder();		
	Vector<ScanFilter> filter = new Vector<ScanFilter>();
	filter.add(builder.build());
	ScanSettings.Builder builderScanSettings = new ScanSettings.Builder();		
	builderScanSettings.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY);
	builderScanSettings.setReportDelay(0);
	bluetoothScanner.startScan(filter, builderScanSettings.build(), leScanCallback);
}
 
Example 27
Project: xDrip   File: G5CollectionService.java   Source Code and License 5 votes vote down vote up
public void setupBluetooth() {

        getTransmitterDetails();
        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            //First time using the app or bluetooth was turned off?
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            Timer single_timer = new Timer();
            single_timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    if (mBluetoothAdapter != null) mBluetoothAdapter.enable();
                }
            }, 1000);
            single_timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    setupBluetooth();
                }
            }, 10000);
        } else {
            if (Build.VERSION.SDK_INT >= 21) {
                mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
                settings = new ScanSettings.Builder()
                        .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                        .build();
                filters = new ArrayList<>();
                //Only look for CGM.
                //filters.add(new ScanFilter.Builder().setServiceUuid(new ParcelUuid(BluetoothServices.Advertisement)).build());
                String transmitterIdLastTwo = Extensions.lastTwoCharactersOfString(defaultTransmitter.transmitterId);
                filters.add(new ScanFilter.Builder().setDeviceName("Dexcom" + transmitterIdLastTwo).build());
            }

            // unbond here to avoid clashes when we are mid-connection
            if (alwaysUnbond()) {
                forgetDevice();
            }
            JoH.ratelimit("G5-timeout",0);//re-init to ensure onStartCommand always executes cycleScan
            cycleScan(0);
        }
    }
 
Example 28
Project: xDrip-plus   File: G5CollectionService.java   Source Code and License 5 votes vote down vote up
public void setupBluetooth() {

        getTransmitterDetails();
        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            //First time using the app or bluetooth was turned off?
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            Timer single_timer = new Timer();
            single_timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    if (mBluetoothAdapter != null) mBluetoothAdapter.enable();
                }
            }, 1000);
            single_timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    setupBluetooth();
                }
            }, 10000);
        } else {
            if (Build.VERSION.SDK_INT >= 21) {
                mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
                settings = new ScanSettings.Builder()
                        .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                        .build();
                filters = new ArrayList<>();
                //Only look for CGM.
                //filters.add(new ScanFilter.Builder().setServiceUuid(new ParcelUuid(BluetoothServices.Advertisement)).build());
                String transmitterIdLastTwo = Extensions.lastTwoCharactersOfString(defaultTransmitter.transmitterId);
                filters.add(new ScanFilter.Builder().setDeviceName("Dexcom" + transmitterIdLastTwo).build());
            }

            // unbond here to avoid clashes when we are mid-connection
            if (alwaysUnbond()) {
                forgetDevice();
            }
            JoH.ratelimit("G5-timeout",0);//re-init to ensure onStartCommand always executes cycleScan
            cycleScan(0);
        }
    }
 
Example 29
Project: BLE-Mesh   File: BLECentral.java   Source Code and License 5 votes vote down vote up
private List<ScanFilter> createScanFilters() {
    ScanFilter.Builder builder = new ScanFilter.Builder();
    builder.setServiceUuid(new ParcelUuid(serviceUUID));
    ArrayList<ScanFilter> scanFilters = new ArrayList<>();
    scanFilters.add(builder.build());
    return scanFilters;
}
 
Example 30
Project: Android-BLE-Library   File: BLEScanner.java   Source Code and License 5 votes vote down vote up
private void initScanData() {
    scanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            Log.i(TAG, "onScanResult" + result);
            String address = result.getDevice().getAddress();
            String name;
            ScanRecord scanRecord = result.getScanRecord();
            name = scanRecord == null ? "unknown" : scanRecord.getDeviceName();
            scanResultListener.onResultReceived(name, address);
        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            super.onBatchScanResults(results);
            Log.e(TAG, "onBatchScanResults");
        }

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
            Log.e(TAG, "onScanFailed");
            scanResultListener.onScanFailed(errorCode);
        }
    };
    filters = new ArrayList<>();
    filters.add(new ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString(BLEProfile.UUID_SERVICE)).build());
    scanSettings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
}
 
Example 31
Project: livingCity-Android   File: BeaconLollipopActivity.java   Source Code and License 5 votes vote down vote up
private void startScan() {
    //Scan for devices advertising the thermometer service
    ScanFilter beaconFilter = new ScanFilter.Builder()
            .setServiceUuid(TemperatureBeacon.THERM_SERVICE)
            .build();
    ArrayList<ScanFilter> filters = new ArrayList<ScanFilter>();
    filters.add(beaconFilter);

    ScanSettings settings = new ScanSettings.Builder()
            .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
            .build();

    mBluetoothLeScanner.startScan(filters, settings, mScanCallback);
}
 
Example 32
Project: probeZero   File: DeviceRanging.java   Source Code and License 5 votes vote down vote up
public void resumeScan() {
    if (mBleAdapter == null || !mBleAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        mContext.startActivity(enableBtIntent);
    } else {
        if (Build.VERSION.SDK_INT >= 21) {
            mLEScanner = mBleAdapter.getBluetoothLeScanner();
            mSettings = new ScanSettings.Builder()
                    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                    .build();
            mFilters = new ArrayList<ScanFilter>();
        }
        scanLeDevice(true);
    }
}
 
Example 33
Project: UdooWtf   File: MainActivity.java   Source Code and License 5 votes vote down vote up
private List<ScanFilter> scanFilters() {
    ScanFilter filter;
    List<ScanFilter> list = new ArrayList<ScanFilter>(new BeaconStorage().getBeaconList().size());
    for (BeaconDevice d: new BeaconStorage().getBeaconList()) {
        filter = new ScanFilter.Builder().setDeviceAddress(d.getMac()).build();
        list.add(filter);
    }
    return list;
}
 
Example 34
Project: UdooWtf   File: Scanner.java   Source Code and License 5 votes vote down vote up
private List<ScanFilter> scanFilters() {
    ScanFilter filter;
    List<ScanFilter> list = new ArrayList<ScanFilter>(new BeaconStorage().getBeaconList().size());
    for (BeaconDevice d: new BeaconStorage().getBeaconList()) {
        filter = new ScanFilter.Builder().setDeviceAddress(d.getMac()).build();
        list.add(filter);
    }
    return list;
}
 
Example 35
Project: android-buruberi   File: ShadowBluetoothLeScanner.java   Source Code and License 5 votes vote down vote up
@Implementation
@RequiresPermission(Manifest.permission.BLUETOOTH)
public void startScan(List<ScanFilter> filters,
                      ScanSettings settings,
                      ScanCallback callback) {
    if (adapter.getState() != BluetoothAdapter.STATE_ON) {
        throw new IllegalStateException("BT Adapter is not turned ON");
    }

    scanCallbacks.add(callback);
}
 
Example 36
Project: xDrip-Experimental   File: G5CollectionService.java   Source Code and License 5 votes vote down vote up
public void setupBluetooth() {
    getTransmitterDetails();
    if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
        //First time using the app or bluetooth was turned off?
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        Timer single_timer = new Timer();
            single_timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    mBluetoothAdapter.enable();
                }
            }, 1000);
        single_timer.schedule(new TimerTask() {
            @Override
            public void run() {
                setupBluetooth();
            }
        }, 10000);
    } else {
        if (Build.VERSION.SDK_INT >= 21) {
            mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
            settings = new ScanSettings.Builder()
                    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                    .build();
            filters = new ArrayList<>();
            //Only look for CGM.
            //filters.add(new ScanFilter.Builder().setServiceUuid(new ParcelUuid(BluetoothServices.Advertisement)).build());
            String transmitterIdLastTwo = Extensions.lastTwoCharactersOfString(defaultTransmitter.transmitterId);
            filters.add(new ScanFilter.Builder().setDeviceName("Dexcom" + transmitterIdLastTwo).build());
        }

        cycleScan(0);
    }
}
 
Example 37
Project: SuperPanel   File: Ble.java   Source Code and License 5 votes vote down vote up
public Ble(Context c, BleListener i, String deviceUuid, String r, String t)
{
    context = c;
    iface = i;
    superPanelUuid = ParcelUuid.fromString(deviceUuid);
    rxUUid = UUID.fromString(r);
    txUUid = UUID.fromString(t);

    adapter = BluetoothAdapter.getDefaultAdapter();
    scanner = adapter.getBluetoothLeScanner();

    ScanFilter.Builder filter = new ScanFilter.Builder();
    filter.setServiceUuid(superPanelUuid);

    ScanFilter.Builder superPanelFilter = new ScanFilter.Builder();
    superPanelFilter.setServiceUuid(superPanelUuid);

    ScanSettings.Builder settings = new ScanSettings.Builder();
    settings.setScanMode(ScanSettings.SCAN_MODE_LOW_POWER);

    List<ScanFilter> filters = new ArrayList<ScanFilter>();
    filters.add(filter.build());
    //filters.add(superPanelFilter.build());

    if(scanner == null)
    {
        System.out.println("Failed to get LE scanner");
        return;
    }
    scanner.startScan(filters, settings.build(), scanCallback);
}
 
Example 38
Project: 365browser   File: Wrappers.java   Source Code and License 5 votes vote down vote up
public void startScan(
        List<ScanFilter> filters, int scanSettingsScanMode, ScanCallbackWrapper callback) {
    ScanSettings settings =
            new ScanSettings.Builder().setScanMode(scanSettingsScanMode).build();

    ForwardScanCallbackToWrapper callbackForwarder =
            new ForwardScanCallbackToWrapper(callback);
    mCallbacks.put(callback, callbackForwarder);

    mScanner.startScan(filters, settings, callbackForwarder);
}
 
Example 39
Project: BTLEDataLogger   File: DeviceScanActivity.java   Source Code and License 5 votes vote down vote up
public void scanBTLEDevices(final boolean enable) {
    if(bluetoothAdapter == null || bluetoothAdapter.getBluetoothLeScanner() == null) {
        Log.d("BTLE", "Bluetooth adapter or scanner were null!");
        return;
    }

    if(enable) {
        // only scan for 5 seconds
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                scanBTLEDevices(false);
            }
        }, 5000);

        //scanning = true;
        setScanning(true);

        bluetoothDevices.clear();
        deviceRSSIs.clear();
        adapter.notifyDataSetChanged();

        // filter explicitly for the UART
        List<ScanFilter> filters = new ArrayList<ScanFilter>();
        filters.add(new ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString("6E400001-B5A3-F393-E0A9-E50E24DCCA9E")).build());

        // setup the scan settings
        ScanSettings settings = new ScanSettings.Builder().setReportDelay(0).setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();

        bluetoothAdapter.getBluetoothLeScanner().startScan(filters, settings, scanCallback);
    }
    else {
        //scanning = false;
        setScanning(false);
        bluetoothAdapter.getBluetoothLeScanner().stopScan(scanCallback);
    }
}
 
Example 40
Project: proximity-manager   File: BeaconRegisterActivity.java   Source Code and License 5 votes vote down vote up
private void startScan() {
    //Return only Eddystone beacons matching the filter
    ScanFilter beaconFilter = new ScanFilter.Builder()
            .setServiceUuid(UID_SERVICE)
            .setServiceData(UID_SERVICE, Beacon.FRAME_FILTER, Beacon.FILTER_MASK)
            .build();
    List<ScanFilter> filters = Collections.singletonList(beaconFilter);

    ScanSettings settings = new ScanSettings.Builder()
            .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
            .build();

    mBluetoothLeScanner.startScan(filters, settings, mScanCallback);
}
 
Example 41
Project: android_wear_for_ios   File: BLEService.java   Source Code and License 5 votes vote down vote up
@TargetApi(21)
    private List<ScanFilter> create_scan_filter(){
//        ScanFilter filter = new ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString(service_ancs)).build();
        ScanFilter filter = new ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString(service_blank)).build();
        List<ScanFilter> list = new ArrayList<ScanFilter>(1);
        list.add(filter);
        return list;
    }
 
Example 42
Project: android_wear_for_ios   File: MusicControlActivity.java   Source Code and License 5 votes vote down vote up
@TargetApi(21)
    private List<ScanFilter> create_scan_filter(){
//        ScanFilter filter = new ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString(service_ancs)).build();
        ScanFilter filter = new ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString(service_ams)).build();
        List<ScanFilter> list = new ArrayList<ScanFilter>(1);
        list.add(filter);
        return list;
    }
 
Example 43
Project: react-native-ble   File: RNBLEModule.java   Source Code and License 5 votes vote down vote up
private List<ScanFilter> buildScanFilters() {
    List<ScanFilter> scanFilters = new ArrayList<>();

    ScanFilter.Builder builder = new ScanFilter.Builder();        
    for(int i = 0; i < this.serviceUuids.size(); i++){
        builder.setServiceUuid(ParcelUuid.fromString(this.serviceUuids.getString(i)));
    }
    scanFilters.add(builder.build());

    return scanFilters;
}
 
Example 44
Project: android-beacon-library   File: CycledLeScannerForLollipop.java   Source Code and License 5 votes vote down vote up
@Override
protected void startScan() {
    if (!isBluetoothOn()) {
        LogManager.d(TAG, "Not starting scan because bluetooth is off");
        return;
    }
    List<ScanFilter> filters = new ArrayList<ScanFilter>();
    ScanSettings settings = null;

    if (!mMainScanCycleActive) {
        LogManager.d(TAG, "starting filtered scan in SCAN_MODE_LOW_POWER");
        settings = (new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)).build();
        filters = new ScanFilterUtils().createScanFiltersForBeaconParsers(
                      mBeaconManager.getBeaconParsers());
    } else {
        LogManager.d(TAG, "starting non-filtered scan in SCAN_MODE_LOW_LATENCY");
        settings = (new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)).build();
        // We create wildcard scan filters that match any advertisement so that we can detect
        // beacons in foreground mode even if the screen is off.  This is a necessary workaround
        // for a change in Android 8.1 that blocks scan results when the screen is off unless
        // there is a scan filter associatd with the scan.  Prior to 8.1, filters could just be
        // left null.  The wildcard filter matches everything.
        filters = new ScanFilterUtils().createWildcardScanFilters();
    }

    if (settings != null) {
        postStartLeScan(filters, settings);
    }
}
 
Example 45
Project: android-beacon-library   File: ScanFilterUtils.java   Source Code and License 5 votes vote down vote up
public List<ScanFilter> createScanFiltersForBeaconParsers(List<BeaconParser> beaconParsers) {
    List<ScanFilter> scanFilters = new ArrayList<ScanFilter>();
    // for each beacon parser, make a filter expression that includes all its desired
    // hardware manufacturers
    for (BeaconParser beaconParser: beaconParsers) {
        List<ScanFilterData> sfds = createScanFilterDataForBeaconParser(beaconParser);
        for (ScanFilterData sfd: sfds) {
            ScanFilter.Builder builder = new ScanFilter.Builder();
            if (sfd.serviceUuid != null) {
                // Use a 16 bit service UUID in a 128 bit form
                String serviceUuidString = String.format("0000%04X-0000-1000-8000-00805f9b34fb", sfd.serviceUuid);
                String serviceUuidMaskString = "FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF";
                ParcelUuid parcelUuid = ParcelUuid.fromString(serviceUuidString);
                ParcelUuid parcelUuidMask = ParcelUuid.fromString(serviceUuidMaskString);
                if (LogManager.isVerboseLoggingEnabled()) {
                    LogManager.d(TAG, "making scan filter for service: "+serviceUuidString+" "+parcelUuid);
                    LogManager.d(TAG, "making scan filter with service mask: "+serviceUuidMaskString+" "+parcelUuidMask);
                }
                builder.setServiceUuid(parcelUuid, parcelUuidMask);
            }
            else {
                builder.setServiceUuid(null);
                builder.setManufacturerData((int) sfd.manufacturer, sfd.filter, sfd.mask);
            }
            ScanFilter scanFilter = builder.build();
            if (LogManager.isVerboseLoggingEnabled()) {
                LogManager.d(TAG, "Set up a scan filter: "+scanFilter);
            }
            scanFilters.add(scanFilter);
        }
    }
    return scanFilters;
}
 
Example 46
Project: divertsy-client   File: BLEScanner.java   Source Code and License 4 votes vote down vote up
public BLEScanner(final Activity activity, int requestEnableBluetooth, @NonNull OnClosestChangedListener onClosestChangedListener) {
    mRequestEnableBluetooth = requestEnableBluetooth;
    mOnClosestChangedListener = onClosestChangedListener;
    init(activity);
    scanFilters = new ArrayList<>();
    scanFilters.add(new ScanFilter.Builder().setServiceUuid(EDDYSTONE_SERVICE_UUID).build());
    scanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            ScanRecord scanRecord = result.getScanRecord();
            if (scanRecord == null) {
                return;
            }

            String deviceAddress = result.getDevice().getAddress();
            Beacon beacon;
            if (!deviceToBeaconMap.containsKey(deviceAddress)) {
                beacon = new Beacon(deviceAddress, result.getRssi());
                deviceToBeaconMap.put(deviceAddress, beacon);
            } else {
                deviceToBeaconMap.get(deviceAddress).lastSeenTimestamp = System.currentTimeMillis();
                deviceToBeaconMap.get(deviceAddress).rssi = result.getRssi();
            }

            byte[] serviceData = scanRecord.getServiceData(EDDYSTONE_SERVICE_UUID);
            validateServiceData(deviceAddress, serviceData);

            findClosest();
        }

        @Override
        public void onScanFailed(int errorCode) {
            switch (errorCode) {
                case SCAN_FAILED_ALREADY_STARTED:
                    logErrorAndShowToast(activity, "SCAN_FAILED_ALREADY_STARTED");
                    break;
                case SCAN_FAILED_APPLICATION_REGISTRATION_FAILED:
                    logErrorAndShowToast(activity, "SCAN_FAILED_APPLICATION_REGISTRATION_FAILED");
                    break;
                case SCAN_FAILED_FEATURE_UNSUPPORTED:
                    logErrorAndShowToast(activity, "SCAN_FAILED_FEATURE_UNSUPPORTED");
                    break;
                case SCAN_FAILED_INTERNAL_ERROR:
                    logErrorAndShowToast(activity, "SCAN_FAILED_INTERNAL_ERROR");
                    break;
                default:
                    logErrorAndShowToast(activity, "Scan failed, unknown error code");
                    break;
            }
        }
    };
}
 
Example 47
Project: react-native-blue-manager   File: LollipopScanManager.java   Source Code and License 4 votes vote down vote up
@Override
public void scan(ReadableArray serviceUUIDs, final int scanSeconds, Callback callback) {

       if(reactContext==null){
           mCallback = callback;
       }
	ScanSettings settings = new ScanSettings.Builder().build();
	List<ScanFilter> filters = new ArrayList<>();

	if (serviceUUIDs != null && serviceUUIDs.size() > 0) {
		for(int i = 0; i < serviceUUIDs.size(); i++){
			ScanFilter.Builder builder = new ScanFilter.Builder();
			builder.setServiceUuid(new ParcelUuid(UUIDHelper.uuidFromString(serviceUUIDs.getString(i))));
			filters.add(builder.build());
			Log.d(bleManager.LOG_TAG, "Filter service: " + serviceUUIDs.getString(i));
		}
	}

	getBluetoothAdapter().getBluetoothLeScanner().startScan(filters, settings, mScanCallback);
	if (scanSeconds > 0) {
		Thread thread = new Thread() {
			private int currentScanSession = scanSessionId.incrementAndGet();

			@Override
			public void run() {

				try {
					Thread.sleep(scanSeconds * 1000);
				} catch (InterruptedException ignored) {
				}

				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						BluetoothAdapter btAdapter = getBluetoothAdapter();
						// check current scan session was not stopped
						if (scanSessionId.intValue() == currentScanSession) {
							if(btAdapter.getState() == BluetoothAdapter.STATE_ON) {
								btAdapter.getBluetoothLeScanner().stopScan(mScanCallback);
							}
							WritableMap map = Arguments.createMap();
							bleManager.sendEvent("BleManagerStopScan", map);
						}
                           if(mCallback!=null) {
                               mCallback.invoke();
                               mCallback=null;
                           }
					}
				});

			}

		};
		thread.start();
	}
       if(reactContext!=null) {
           callback.invoke();
       }
}
 
Example 48
Project: AndroidMuseumBleManager   File: BluetoothLeScannerCompat.java   Source Code and License 4 votes vote down vote up
@Override
public void startScan(BluetoothAdapter adapter, List<ScanFilterCompat> filters, ScanSettingsCompat settings, ScanCallbackCompat callbackCompat) {

    List<ScanFilter> scanFilters = null;
    if (filters != null) {
        scanFilters = new ArrayList<>(filters.size());

        for (ScanFilterCompat filter : filters) {
            scanFilters.add(filter.toApi21());
        }
    }
    if (settings == null) {
        throw new IllegalStateException("Scan settings are null");
    }
    ScanSettings scanSettings = settings.toApi21();
    adapter.getBluetoothLeScanner().startScan(scanFilters, scanSettings, registerCallback(callbackCompat));
}
 
Example 49
Project: AndroidSensors   File: BLEMeasurementsGatherer.java   Source Code and License 4 votes vote down vote up
private List<ScanFilter> initializeScanFilters() {
    return Collections.emptyList();
}
 
Example 50
Project: mesh-core-on-android   File: JniCallbacks.java   Source Code and License 4 votes vote down vote up
private List<ScanFilter> createScanFilters() {
	return null;
}
 
Example 51
Project: RxAndroidBle   File: RxBleAdapterWrapper.java   Source Code and License 4 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void startLeScan(List<ScanFilter> scanFilters, ScanSettings scanSettings, ScanCallback scanCallback) {
    bluetoothAdapter.getBluetoothLeScanner().startScan(scanFilters, scanSettings, scanCallback);
}
 
Example 52
Project: react-native-ble-manager   File: LollipopScanManager.java   Source Code and License 4 votes vote down vote up
@Override
public void scan(ReadableArray serviceUUIDs, final int scanSeconds, ReadableMap options,  Callback callback) {
    ScanSettings.Builder scanSettingsBuilder = new ScanSettings.Builder();
    List<ScanFilter> filters = new ArrayList<>();
    
    scanSettingsBuilder.setScanMode(options.getInt("scanMode"));
    
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
        scanSettingsBuilder.setNumOfMatches(options.getInt("numberOfMatches"));
        scanSettingsBuilder.setMatchMode(options.getInt("matchMode"));
    }
    
    if (serviceUUIDs.size() > 0) {
        for(int i = 0; i < serviceUUIDs.size(); i++){
ScanFilter filter = new ScanFilter.Builder().setServiceUuid(new ParcelUuid(UUIDHelper.uuidFromString(serviceUUIDs.getString(i)))).build();
            filters.add(filter);
            Log.d(bleManager.LOG_TAG, "Filter service: " + serviceUUIDs.getString(i));
        }
    }
    
    getBluetoothAdapter().getBluetoothLeScanner().startScan(filters, scanSettingsBuilder.build(), mScanCallback);
    if (scanSeconds > 0) {
        Thread thread = new Thread() {
            private int currentScanSession = scanSessionId.incrementAndGet();
            
            @Override
            public void run() {
                
                try {
                    Thread.sleep(scanSeconds * 1000);
                } catch (InterruptedException ignored) {
                }
                
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        BluetoothAdapter btAdapter = getBluetoothAdapter();
                        // check current scan session was not stopped
                        if (scanSessionId.intValue() == currentScanSession) {
                            if(btAdapter.getState() == BluetoothAdapter.STATE_ON) {
                                btAdapter.getBluetoothLeScanner().stopScan(mScanCallback);
                            }
                            WritableMap map = Arguments.createMap();
                            bleManager.sendEvent("BleManagerStopScan", map);
                        }
                    }
                });
                
            }
            
        };
        thread.start();
    }
    callback.invoke();
}
 
Example 53
Project: TappyBLE   File: LollipopUtils.java   Source Code and License 4 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static ScanFilter convertCompatScanFilterToNative(com.taptrack.tcmptappy.blescannercompat.ScanFilter compatFilter) {
    if(compatFilter == null)
        return null;

    ScanFilter.Builder nativeBuilder = new ScanFilter.Builder();

    if(compatFilter.getDeviceAddress() != null)
        nativeBuilder = nativeBuilder.setDeviceAddress(compatFilter.getDeviceAddress());

    if(compatFilter.getDeviceName() != null)
        nativeBuilder = nativeBuilder.setDeviceAddress(compatFilter.getDeviceName());

    if(compatFilter.getManufacturerData() != null && compatFilter.getManufacturerId() != -1) {
        if(compatFilter.getManufacturerDataMask() != null) {
            nativeBuilder = nativeBuilder.setManufacturerData(compatFilter.getManufacturerId(),
                    compatFilter.getManufacturerData(),
                    compatFilter.getManufacturerDataMask());
        }
        else {
            nativeBuilder = nativeBuilder.setManufacturerData(compatFilter.getManufacturerId(),
                    compatFilter.getManufacturerData());
        }
    }


    if(compatFilter.getServiceDataUuid() != null && compatFilter.getServiceData() != null) {
        if(compatFilter.getServiceDataMask() != null) {
            nativeBuilder = nativeBuilder.setServiceData(compatFilter.getServiceDataUuid(),
                    compatFilter.getServiceData(),
                    compatFilter.getServiceDataMask());
        }
        else {
            nativeBuilder = nativeBuilder.setServiceData(compatFilter.getServiceDataUuid(),
                    compatFilter.getServiceData());
        }
    }

    if(compatFilter.getServiceUuid() != null) {
        if(compatFilter.getServiceUuidMask() != null)
            nativeBuilder = nativeBuilder.setServiceUuid(compatFilter.getServiceUuid(),compatFilter.getServiceUuidMask());
        else
            nativeBuilder = nativeBuilder.setServiceUuid(compatFilter.getServiceUuid());
    }

    return nativeBuilder.build();
}
 
Example 54
Project: BLECommunication   File: BLEUtil.java   Source Code and License 4 votes vote down vote up
public void scanPeripheralWithServicesUUID_API21(final String uuid) {
    	if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
    		requestOpenBT();
    		return;
    	}
    	BluetoothLeScanner scanner = mBluetoothAdapter.getBluetoothLeScanner();
    	ScanSettings settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
    	List<ScanFilter> list = new ArrayList<ScanFilter>(1);
    	
    	ScanCallback callback = new ScanCallback() {
			@Override
		    public void onScanResult(int callbackType,  android.bluetooth.le.ScanResult result) {
				BluetoothDevice device = result.getDevice();
				
				ScanRecord sr = result.getScanRecord();
			    
				int rssi = result.getRssi();
//				if (rssi > -15) {
//					runCallbackWithErrorCode(BLEUtilErrorCode.E_RSSI_ERROR);
//					return;
//				}
//				if (rssi < -35) {
//					runCallbackWithErrorCode(BLEUtilErrorCode.E_RSSI_TOO_LOW);
//					return;
//				}
				if (matchRules(rssi, sr.getBytes(), uuid)) {
					connectToDevice(device);
				}
		    }
		 
		    @Override
		    public void onScanFailed(int errorCode) {
		 
		    }
		};
    	
    	if (uuid != null) {
	    	ScanFilter filter = new ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString(uuid)).build();
	        list.add(filter);
	        scanner.startScan(list, settings, callback);
    	} else {
//    		scanner.startScan(null, settings, callback);
    		scanner.startScan(callback);
    	}
    }
 
Example 55
Project: BLECommunication   File: BLEUtil.java   Source Code and License 4 votes vote down vote up
public void scanPeripheralWithServicesUUID_API21(final String uuid) {
    	if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
    		requestOpenBT();
    		return;
    	}
    	BluetoothLeScanner scanner = mBluetoothAdapter.getBluetoothLeScanner();
    	ScanSettings settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
    	List<ScanFilter> list = new ArrayList<ScanFilter>(1);
    	
    	ScanCallback callback = new ScanCallback() {
			@Override
		    public void onScanResult(int callbackType,  android.bluetooth.le.ScanResult result) {
				BluetoothDevice device = result.getDevice();
				
				ScanRecord sr = result.getScanRecord();
			    
				int rssi = result.getRssi();
//				if (rssi > -15) {
//					runCallbackWithErrorCode(BLEUtilErrorCode.E_RSSI_ERROR);
//					return;
//				}
//				if (rssi < -35) {
//					runCallbackWithErrorCode(BLEUtilErrorCode.E_RSSI_TOO_LOW);
//					return;
//				}
				if (matchRules(rssi, sr.getBytes(), uuid)) {
					connectToDevice(device);
				}
		    }
		 
		    @Override
		    public void onScanFailed(int errorCode) {
		 
		    }
		};
    	
    	if (uuid != null) {
	    	ScanFilter filter = new ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString(uuid)).build();
	        list.add(filter);
	        scanner.startScan(list, settings, callback);
    	} else {
//    		scanner.startScan(null, settings, callback);
    		scanner.startScan(callback);
    	}
    }
 
Example 56
Project: xDrip   File: G5CollectionService.java   Source Code and License 4 votes vote down vote up
public void setupBluetooth() {

        getTransmitterDetails();
        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            //First time using the app or bluetooth was turned off?
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            Timer single_timer = new Timer();
            single_timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    try {
                        if (mBluetoothAdapter != null) mBluetoothAdapter.enable();
                    } catch (SecurityException e) {
                        JoH.static_toast_short("Please enable Bluetooth!");
                    }
                }
            }, 1000);
            single_timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    setupBluetooth();
                }
            }, 10000);
        } else {
            if (Build.VERSION.SDK_INT >= 21) {
                mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
                settings = new ScanSettings.Builder()
                        .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                        .build();
                filters = new ArrayList<>();
                //Only look for CGM.
                //filters.add(new ScanFilter.Builder().setServiceUuid(new ParcelUuid(BluetoothServices.Advertisement)).build());
                String transmitterIdLastTwo = Extensions.lastTwoCharactersOfString(defaultTransmitter.transmitterId);
                filters.add(new ScanFilter.Builder().setDeviceName("Dexcom" + transmitterIdLastTwo).build());
            }

            // unbond here to avoid clashes when we are mid-connection
            if (alwaysUnbond()) {
                forgetDevice();
            }
            JoH.ratelimit("G5-timeout",0);//re-init to ensure onStartCommand always executes cycleScan
            cycleScan(0);
        }
    }
 
Example 57
Project: xDrip-plus   File: G5CollectionService.java   Source Code and License 4 votes vote down vote up
public void setupBluetooth() {

        getTransmitterDetails();
        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            //First time using the app or bluetooth was turned off?
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            Timer single_timer = new Timer();
            single_timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    try {
                        if (mBluetoothAdapter != null) mBluetoothAdapter.enable();
                    } catch (SecurityException e) {
                        JoH.static_toast_short("Please enable Bluetooth!");
                    }
                }
            }, 1000);
            single_timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    setupBluetooth();
                }
            }, 10000);
        } else {
            if (Build.VERSION.SDK_INT >= 21) {
                mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
                settings = new ScanSettings.Builder()
                        .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                        .build();
                filters = new ArrayList<>();
                //Only look for CGM.
                //filters.add(new ScanFilter.Builder().setServiceUuid(new ParcelUuid(BluetoothServices.Advertisement)).build());
                String transmitterIdLastTwo = Extensions.lastTwoCharactersOfString(defaultTransmitter.transmitterId);
                filters.add(new ScanFilter.Builder().setDeviceName("Dexcom" + transmitterIdLastTwo).build());
            }

            // unbond here to avoid clashes when we are mid-connection
            if (alwaysUnbond()) {
                forgetDevice();
            }
            JoH.ratelimit("G5-timeout",0);//re-init to ensure onStartCommand always executes cycleScan
            cycleScan(0);
        }
    }
 
Example 58
Project: ibeacon-scanner-android   File: DefaultScanService.java   Source Code and License 4 votes vote down vote up
@Override
public void timedOut(final Object anObject)
{
    // no new beacons have been added or removed for {@link BuildConfig#ADD_REGION_TIMEOUT_IN_MILLIS}, stop
    // previous scan and start a new scan with the beacons we should monitor.

    // check if we can scan
    boolean canScan = true;

    // reattach the BluetoothAdapter
    if (!this.bluetoothFactory.canAttachBluetoothAdapter())
    {
        canScan = false;

        if (this.callback != null)
        {
            this.callback.monitoringDidFail(Error.NO_BLUETOOTH_PERMISSION);
        }
    }
    else
    {
        if (!BluetoothUtils.hasBluetoothLE(this.context))
        {
            canScan = false;

            if (this.callback != null)
            {
                this.callback.monitoringDidFail(Error.NO_BLUETOOTH_LE);
            }
        }

        if (!BluetoothUtils.isBluetoothOn())
        {
            canScan = false;

            if (this.callback != null)
            {
                this.callback.monitoringDidFail(Error.BLUETOOTH_OFF);
            }
        }
    }

    if (!LocationUtils.isLocationOn(this.context))
    {
        canScan = false;

        if (this.callback != null)
        {
            this.callback.monitoringDidFail(Error.LOCATION_OFF);
        }
    }

    if (!PermissionUtils.isLocationGranted(this.context))
    {
        canScan = false;

        if (this.callback != null)
        {
            this.callback.monitoringDidFail(Error.NO_LOCATION_PERMISSION);
        }
    }

    if (canScan && this.bluetoothFactory.getBluetoothLeScanner() != null)
    {
        // stop scanning
        this.bluetoothFactory.getBluetoothLeScanner().stopScan(DefaultScanService.this.scannerScanCallback);

        // start scanning
        if (!this.beacons.isEmpty())
        {
            final List<ScanFilter> scanFilters = new ArrayList<>();

            for (final Beacon beacon : this.beacons)
            {
                scanFilters.add(ScanFilterUtils.getScanFilter(beacon));
            }

            this.bluetoothFactory.getBluetoothLeScanner().startScan(scanFilters, getScanSettings(), this.scannerScanCallback);
        }
    }
}
 
Example 59
Project: ibeacon-scanner-android   File: ScanFilterUtils.java   Source Code and License 4 votes vote down vote up
/**
 * Return a {@link ScanFilter} matching the given {@link BeaconInterface}.
 *
 * @param beacon to create {@link ScanFilter} for
 * @return {@link ScanFilter} that matches {@code beacon}
 */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static ScanFilter getScanFilter(@NonNull final BeaconInterface beacon)
{
    final ScanFilter.Builder builder = new ScanFilter.Builder();

    // the manufacturer data byte is the filter!
    final byte[] manufacturerData = new byte[]
    {
            0,0,

            // uuid
            0,0,0,0,
            0,0,
            0,0,
            0,0,0,0,0,0,0,0,

            // major
            0,0,

            // minor
            0,0,

            0
    };

    // the mask tells what bytes in the filter need to match, 1 if it has to match, 0 if not
    final byte[] manufacturerDataMask = new byte[]
    {
            0,0,

            // uuid
            1,1,1,1,
            1,1,
            1,1,
            1,1,1,1,1,1,1,1,

            // major
            1,1,

            // minor
            1,1,

            0
    };

    // copy UUID (with no dashes) into data array
    System.arraycopy(ConversionUtils.UuidToByteArray(beacon.getUUID()), 0, manufacturerData, 2, 16);

    // copy major into data array
    System.arraycopy(ConversionUtils.integerToByteArray(beacon.getMajor()), 0, manufacturerData, 18, 2);

    // copy minor into data array
    System.arraycopy(ConversionUtils.integerToByteArray(beacon.getMinor()), 0, manufacturerData, 20, 2);

    builder.setManufacturerData(
            MANUFACTURER_ID,
            manufacturerData,
            manufacturerDataMask);

    return builder.build();
}
 
Example 60
Project: SensorLib   File: DsSensorManager.java   Source Code and License 4 votes vote down vote up
/**
 * Search for BLE devices.
 *
 * @param callback a callback implementation that receives notifications for found sensors.
 */
public static void searchBleDevices(final SensorFoundCallback callback) throws Exception {

    /*// check if Bluetooth is available (if not, it throws an exception) and enabled before scanning for Ble devices.
    enableBluetooth(activity);

    if (checkBtLePermissions(activity, false) == PERMISSIONS_MISSING) {
        throw new DsException(DsExceptionType.permissionsMissing);
    }*/

    sBleScanner = BluetoothAdapter.getDefaultAdapter().getBluetoothLeScanner();
    if (sBleScanner == null) {
        throw new DsException(DsExceptionType.bleScannerError);
    }

    // set scan settings and filters
    ScanSettings settings = new ScanSettings.Builder()
            .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
            .build();
    List<ScanFilter> filters = new ArrayList<>();

    // is an old scan still running? cancel it.
    cancelRunningScans();
    // create new scan callback
    sScanCallback = new DsScanCallback(callback);

    // post a delayed runnable to stop the BLE scan after SCAN_PERIOD.
    sBleScanHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            Log.d(TAG, "...Stopping BLE scan.");
            if (sScanCallback != null) {
                sBleScanner.stopScan(sScanCallback);
            }
        }
    }, SCAN_PERIOD);

    // start the BLE scan
    Log.d(TAG, "Starting BLE scan for " + SCAN_PERIOD / 1000 + " s ...");
    sBleScanner.startScan(filters, settings, sScanCallback);
}