Search in sources :

Example 6 with ScanRecord

use of android.bluetooth.le.ScanRecord in project android_frameworks_base by crdroidandroid.

the class ScanRecordTest method testParser.

@SmallTest
public void testParser() {
    byte[] scanRecord = new byte[] { // advertising flags
    0x02, // advertising flags
    0x01, // advertising flags
    0x1a, // 16 bit service uuids
    0x05, // 16 bit service uuids
    0x02, // 16 bit service uuids
    0x0b, // 16 bit service uuids
    0x11, // 16 bit service uuids
    0x0a, // 16 bit service uuids
    0x11, // name
    0x04, // name
    0x09, // name
    0x50, // name
    0x65, // name
    0x64, // tx power level
    0x02, // tx power level
    0x0A, // tx power level
    (byte) 0xec, // service data
    0x05, // service data
    0x16, // service data
    0x0b, // service data
    0x11, // service data
    0x50, // service data
    0x64, // manufacturer specific data
    0x05, // manufacturer specific data
    (byte) 0xff, // manufacturer specific data
    (byte) 0xe0, // manufacturer specific data
    0x00, // manufacturer specific data
    0x02, // manufacturer specific data
    0x15, // an unknown data type won't cause trouble
    0x03, // an unknown data type won't cause trouble
    0x50, // an unknown data type won't cause trouble
    0x01, // an unknown data type won't cause trouble
    0x02 };
    ScanRecord data = ScanRecord.parseFromBytes(scanRecord);
    assertEquals(0x1a, data.getAdvertiseFlags());
    ParcelUuid uuid1 = ParcelUuid.fromString("0000110A-0000-1000-8000-00805F9B34FB");
    ParcelUuid uuid2 = ParcelUuid.fromString("0000110B-0000-1000-8000-00805F9B34FB");
    assertTrue(data.getServiceUuids().contains(uuid1));
    assertTrue(data.getServiceUuids().contains(uuid2));
    assertEquals("Ped", data.getDeviceName());
    assertEquals(-20, data.getTxPowerLevel());
    assertTrue(data.getManufacturerSpecificData().get(0x00E0) != null);
    assertArrayEquals(new byte[] { 0x02, 0x15 }, data.getManufacturerSpecificData().get(0x00E0));
    assertTrue(data.getServiceData().containsKey(uuid2));
    assertArrayEquals(new byte[] { 0x50, 0x64 }, data.getServiceData().get(uuid2));
}
Also used : ParcelUuid(android.os.ParcelUuid) ScanRecord(android.bluetooth.le.ScanRecord) SmallTest(android.test.suitebuilder.annotation.SmallTest)

Example 7 with ScanRecord

use of android.bluetooth.le.ScanRecord in project android-beacon-library by AltBeacon.

the class ScanJob method onStartJob.

@Override
public boolean onStartJob(final JobParameters jobParameters) {
    // We start off on the main UI thread here.
    // But the ScanState restore from storage sometimes hangs, so we start new thread here just
    // to kick that off.  This way if the restore hangs, we don't hang the UI thread.
    LogManager.i(TAG, "ScanJob Lifecycle START: " + ScanJob.this);
    new Thread(new Runnable() {

        public void run() {
            IntentScanStrategyCoordinator intentStrategyCoord = BeaconManager.getInstanceForApplication(ScanJob.this).getIntentScanStrategyCoordinator();
            if (intentStrategyCoord != null) {
                // cycle.
                synchronized (ScanJob.this) {
                    if (mStopCalled) {
                        LogManager.d(TAG, "Quitting scan job before we even start.  Somebody told us to stop.");
                        ScanJob.this.jobFinished(jobParameters, false);
                        return;
                    }
                    LogManager.d(TAG, "Scan job calling IntentScanStrategyCoordinator");
                    intentStrategyCoord.performPeriodicProcessing(ScanJob.this);
                    LogManager.d(TAG, "Scan job finished.  Calling jobFinished");
                    ScanJob.this.jobFinished(jobParameters, false);
                    return;
                }
            }
            if (!initialzeScanHelper()) {
                LogManager.e(TAG, "Cannot allocate a scanner to look for beacons.  System resources are low.");
                ScanJob.this.jobFinished(jobParameters, false);
            }
            ScanJobScheduler.getInstance().ensureNotificationProcessorSetup(getApplicationContext());
            if (jobParameters.getJobId() == getImmediateScanJobId(ScanJob.this)) {
                LogManager.i(TAG, "Running immediate scan job: instance is " + ScanJob.this);
            } else {
                LogManager.i(TAG, "Running periodic scan job: instance is " + ScanJob.this);
            }
            List<ScanResult> queuedScanResults = new ArrayList<>(ScanJobScheduler.getInstance().dumpBackgroundScanResultQueue());
            LogManager.d(TAG, "Processing %d queued scan results", queuedScanResults.size());
            for (ScanResult result : queuedScanResults) {
                ScanRecord scanRecord = result.getScanRecord();
                if (scanRecord != null) {
                    if (mScanHelper != null) {
                        mScanHelper.processScanResult(result.getDevice(), result.getRssi(), scanRecord.getBytes(), System.currentTimeMillis() - SystemClock.elapsedRealtime() + result.getTimestampNanos() / 1000000);
                    }
                }
            }
            LogManager.d(TAG, "Done processing queued scan results");
            // closing out the CycledScanner
            synchronized (ScanJob.this) {
                if (mStopCalled) {
                    LogManager.d(TAG, "Quitting scan job before we even start.  Somebody told us to stop.");
                    ScanJob.this.jobFinished(jobParameters, false);
                    return;
                }
                boolean startedScan;
                if (mInitialized) {
                    LogManager.d(TAG, "Scanning already started.  Resetting for current parameters");
                    startedScan = restartScanning();
                } else {
                    startedScan = startScanning();
                }
                mStopHandler.removeCallbacksAndMessages(null);
                if (startedScan) {
                    if (mScanState != null) {
                        LogManager.i(TAG, "Scan job running for " + mScanState.getScanJobRuntimeMillis() + " millis");
                        mStopHandler.postDelayed(new Runnable() {

                            @Override
                            public void run() {
                                LogManager.i(TAG, "Scan job runtime expired: " + ScanJob.this);
                                stopScanning();
                                mScanState.save();
                                ScanJob.this.jobFinished(jobParameters, false);
                                // need to execute this after the current block or Android stops this job prematurely
                                mStopHandler.post(new Runnable() {

                                    @Override
                                    public void run() {
                                        scheduleNextScan();
                                    }
                                });
                            }
                        }, mScanState.getScanJobRuntimeMillis());
                    }
                } else {
                    LogManager.i(TAG, "Scanning not started so Scan job is complete.");
                    stopScanning();
                    mScanState.save();
                    LogManager.d(TAG, "ScanJob Lifecycle STOP (start fail): " + ScanJob.this);
                    ScanJob.this.jobFinished(jobParameters, false);
                }
            }
        }
    }).start();
    return true;
}
Also used : ScanResult(android.bluetooth.le.ScanResult) ArrayList(java.util.ArrayList) ScanRecord(android.bluetooth.le.ScanRecord)

Example 8 with ScanRecord

use of android.bluetooth.le.ScanRecord in project facebook-android-sdk by facebook.

the class BleScannerImpl method newBluetoothScanResult.

private static BluetoothScanResult newBluetoothScanResult(ScanResult scanResult) {
    ScanRecord scanRecord = scanResult.getScanRecord();
    byte[] scanRecordBytes = scanRecord.getBytes();
    if (isBeacon(scanRecordBytes)) {
        String payload = formatPayload(scanRecord.getBytes());
        int rssi = scanResult.getRssi();
        BluetoothScanResult bluetoothScanResult = new BluetoothScanResult(payload, rssi);
        return bluetoothScanResult;
    }
    return null;
}
Also used : ScanRecord(android.bluetooth.le.ScanRecord)

Example 9 with ScanRecord

use of android.bluetooth.le.ScanRecord in project platform_frameworks_base by android.

the class BluetoothAdapter method startLeScan.

/**
     * Starts a scan for Bluetooth LE devices, looking for devices that
     * advertise given services.
     *
     * <p>Devices which advertise all specified services are reported using the
     * {@link LeScanCallback#onLeScan} callback.
     *
     * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission.
     *
     * @param serviceUuids Array of services to look for
     * @param callback the callback LE scan results are delivered
     * @return true, if the scan was started successfully
     * @deprecated use {@link BluetoothLeScanner#startScan(List, ScanSettings, ScanCallback)}
     *             instead.
     */
@Deprecated
@RequiresPermission(Manifest.permission.BLUETOOTH_ADMIN)
public boolean startLeScan(final UUID[] serviceUuids, final LeScanCallback callback) {
    if (DBG)
        Log.d(TAG, "startLeScan(): " + Arrays.toString(serviceUuids));
    if (callback == null) {
        if (DBG)
            Log.e(TAG, "startLeScan: null callback");
        return false;
    }
    BluetoothLeScanner scanner = getBluetoothLeScanner();
    if (scanner == null) {
        if (DBG)
            Log.e(TAG, "startLeScan: cannot get BluetoothLeScanner");
        return false;
    }
    synchronized (mLeScanClients) {
        if (mLeScanClients.containsKey(callback)) {
            if (DBG)
                Log.e(TAG, "LE Scan has already started");
            return false;
        }
        try {
            IBluetoothGatt iGatt = mManagerService.getBluetoothGatt();
            if (iGatt == null) {
                // BLE is not supported
                return false;
            }
            ScanCallback scanCallback = new ScanCallback() {

                @Override
                public void onScanResult(int callbackType, ScanResult result) {
                    if (callbackType != ScanSettings.CALLBACK_TYPE_ALL_MATCHES) {
                        // Should not happen.
                        Log.e(TAG, "LE Scan has already started");
                        return;
                    }
                    ScanRecord scanRecord = result.getScanRecord();
                    if (scanRecord == null) {
                        return;
                    }
                    if (serviceUuids != null) {
                        List<ParcelUuid> uuids = new ArrayList<ParcelUuid>();
                        for (UUID uuid : serviceUuids) {
                            uuids.add(new ParcelUuid(uuid));
                        }
                        List<ParcelUuid> scanServiceUuids = scanRecord.getServiceUuids();
                        if (scanServiceUuids == null || !scanServiceUuids.containsAll(uuids)) {
                            if (DBG)
                                Log.d(TAG, "uuids does not match");
                            return;
                        }
                    }
                    callback.onLeScan(result.getDevice(), result.getRssi(), scanRecord.getBytes());
                }
            };
            ScanSettings settings = new ScanSettings.Builder().setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES).setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
            List<ScanFilter> filters = new ArrayList<ScanFilter>();
            if (serviceUuids != null && serviceUuids.length > 0) {
                // Note scan filter does not support matching an UUID array so we put one
                // UUID to hardware and match the whole array in callback.
                ScanFilter filter = new ScanFilter.Builder().setServiceUuid(new ParcelUuid(serviceUuids[0])).build();
                filters.add(filter);
            }
            scanner.startScan(filters, settings, scanCallback);
            mLeScanClients.put(callback, scanCallback);
            return true;
        } catch (RemoteException e) {
            Log.e(TAG, "", e);
        }
    }
    return false;
}
Also used : ParcelUuid(android.os.ParcelUuid) BluetoothLeScanner(android.bluetooth.le.BluetoothLeScanner) ScanResult(android.bluetooth.le.ScanResult) ScanSettings(android.bluetooth.le.ScanSettings) ScanFilter(android.bluetooth.le.ScanFilter) ArrayList(java.util.ArrayList) ScanCallback(android.bluetooth.le.ScanCallback) UUID(java.util.UUID) RemoteException(android.os.RemoteException) ScanRecord(android.bluetooth.le.ScanRecord) RequiresPermission(android.annotation.RequiresPermission)

Example 10 with ScanRecord

use of android.bluetooth.le.ScanRecord in project platform_frameworks_base by android.

the class ScanRecordTest method testParser.

@SmallTest
public void testParser() {
    byte[] scanRecord = new byte[] { // advertising flags
    0x02, // advertising flags
    0x01, // advertising flags
    0x1a, // 16 bit service uuids
    0x05, // 16 bit service uuids
    0x02, // 16 bit service uuids
    0x0b, // 16 bit service uuids
    0x11, // 16 bit service uuids
    0x0a, // 16 bit service uuids
    0x11, // name
    0x04, // name
    0x09, // name
    0x50, // name
    0x65, // name
    0x64, // tx power level
    0x02, // tx power level
    0x0A, // tx power level
    (byte) 0xec, // service data
    0x05, // service data
    0x16, // service data
    0x0b, // service data
    0x11, // service data
    0x50, // service data
    0x64, // manufacturer specific data
    0x05, // manufacturer specific data
    (byte) 0xff, // manufacturer specific data
    (byte) 0xe0, // manufacturer specific data
    0x00, // manufacturer specific data
    0x02, // manufacturer specific data
    0x15, // an unknown data type won't cause trouble
    0x03, // an unknown data type won't cause trouble
    0x50, // an unknown data type won't cause trouble
    0x01, // an unknown data type won't cause trouble
    0x02 };
    ScanRecord data = ScanRecord.parseFromBytes(scanRecord);
    assertEquals(0x1a, data.getAdvertiseFlags());
    ParcelUuid uuid1 = ParcelUuid.fromString("0000110A-0000-1000-8000-00805F9B34FB");
    ParcelUuid uuid2 = ParcelUuid.fromString("0000110B-0000-1000-8000-00805F9B34FB");
    assertTrue(data.getServiceUuids().contains(uuid1));
    assertTrue(data.getServiceUuids().contains(uuid2));
    assertEquals("Ped", data.getDeviceName());
    assertEquals(-20, data.getTxPowerLevel());
    assertTrue(data.getManufacturerSpecificData().get(0x00E0) != null);
    assertArrayEquals(new byte[] { 0x02, 0x15 }, data.getManufacturerSpecificData().get(0x00E0));
    assertTrue(data.getServiceData().containsKey(uuid2));
    assertArrayEquals(new byte[] { 0x50, 0x64 }, data.getServiceData().get(uuid2));
}
Also used : ParcelUuid(android.os.ParcelUuid) ScanRecord(android.bluetooth.le.ScanRecord) SmallTest(android.test.suitebuilder.annotation.SmallTest)

Aggregations

ScanRecord (android.bluetooth.le.ScanRecord)12 ParcelUuid (android.os.ParcelUuid)10 ScanResult (android.bluetooth.le.ScanResult)6 ArrayList (java.util.ArrayList)6 RequiresPermission (android.annotation.RequiresPermission)5 BluetoothLeScanner (android.bluetooth.le.BluetoothLeScanner)5 ScanCallback (android.bluetooth.le.ScanCallback)5 ScanFilter (android.bluetooth.le.ScanFilter)5 ScanSettings (android.bluetooth.le.ScanSettings)5 RemoteException (android.os.RemoteException)5 SmallTest (android.test.suitebuilder.annotation.SmallTest)5 UUID (java.util.UUID)5