android.bluetooth.le.ScanRecord Java Examples

The following examples show how to use android.bluetooth.le.ScanRecord. 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: MockScanResultProvider.java    From bitgatt with Mozilla Public License 2.0 6 votes vote down vote up
MockScanResultProvider(int numberOfMockResults, int minRssi, int maxRssi){
    rnd = new Random(System.currentTimeMillis());
    scanResults = new ArrayList<>(numberOfMockResults);
    serviceDataMap = new HashMap<>();
    byte[] randomData = new byte[16];
    rnd.nextBytes(randomData);
    serviceDataMap.put(new ParcelUuid(UUID.fromString("adabfb00-6e7d-4601-bda2-bffaa68956ba")), randomData);
    for(int i=0; i < numberOfMockResults; i++) {
        ScanResult result = Mockito.mock(ScanResult.class);
        BluetoothDevice device = Mockito.mock(BluetoothDevice.class);
        ScanRecord record = Mockito.mock(ScanRecord.class);
        Mockito.when(device.getAddress()).thenReturn(randomMACAddress());
        Mockito.when(device.getName()).thenReturn("foobar-" + String.valueOf(i));
        Mockito.when(result.getDevice()).thenReturn(device);
        Mockito.when(result.getRssi()).thenReturn(-1 * (rnd.nextInt(Math.abs(minRssi) + 1 - Math.abs(maxRssi)) + Math.abs(maxRssi)));
        Assert.assertTrue("Rssi is less than zero", result.getRssi() < 0);
        Mockito.when(record.getDeviceName()).thenReturn("foobar-" + String.valueOf(i));
        Mockito.when(record.getServiceData()).thenReturn(serviceDataMap);
        scanResults.add(result);
    }
}
 
Example #2
Source File: BleScanner.java    From EasyBle with Apache License 2.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private boolean hasResultByFilterUuids(ScanResult result) {
    if (mServiceUuids == null || mServiceUuids.length <= 0) {//no filtered uuids
        return true;
    }
    ScanRecord scanRecord = result.getScanRecord();
    if (scanRecord == null) {
        return false;
    }
    List<ParcelUuid> serviceUuidList = new ArrayList<>();
    for (UUID uuid : mServiceUuids) {
        serviceUuidList.add(new ParcelUuid(uuid));
    }
    List<ParcelUuid> scanServiceUuids = result.getScanRecord().getServiceUuids();
    return scanServiceUuids != null && scanServiceUuids.containsAll(serviceUuidList);
}
 
Example #3
Source File: ScanRecordCompat.java    From EFRConnect-android with Apache License 2.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static ScanRecordCompat from(Object lollipopScanRecord) {
    if (lollipopScanRecord == null) {
        return null;
    }

    sr = (ScanRecord) lollipopScanRecord;
    ScanRecordCompat retVal = new ScanRecordCompat();
    retVal.advertiseFlags = sr.getAdvertiseFlags();
    retVal.bytes = sr.getBytes();
    retVal.deviceName = sr.getDeviceName();
    retVal.manufacturerSpecificData = sr.getManufacturerSpecificData();
    retVal.serviceData = sr.getServiceData();
    retVal.serviceUuids = sr.getServiceUuids();
    retVal.txPowerLevel = sr.getTxPowerLevel();
    return retVal;

}
 
Example #4
Source File: FitbitGatt.java    From bitgatt with Mozilla Public License 2.0 5 votes vote down vote up
@VisibleForTesting
synchronized void addScannedDevice(FitbitBluetoothDevice device) {
    // we need to deal with the scenario where the peripheral was connected, but now
    // it is disconnected, then it is picked up in the background with the scan
    // the listener could potentially be called back twice for the same connection
    // if the user has a background scan running while an active scan is running
    GattConnection conn = connectionMap.get(device);
    if (null == conn) {
        if (appContext == null) {
            Timber.w("[%s] Bitgatt must not be started, please start bitgatt client", device);
            return;
        }
        Timber.v("Adding scanned device %s", device.toString());
        conn = new GattConnection(device, appContext.getMainLooper());
        device.origin = FitbitBluetoothDevice.DeviceOrigin.SCANNED;
        connectionMap.put(device, conn);
        notifyListenersOfConnectionAdded(conn);
    } else {
        FitbitBluetoothDevice oldDevice = conn.getDevice();
        String previousDeviceName = oldDevice.getName();
        ScanRecord previousScanRecord = oldDevice.getScanRecord();
        int previousRssi = oldDevice.getRssi();
        if (!previousDeviceName.equals(device.getName())) {
            Timber.w("This device has the same mac (bluetooth ID) as a known device, but has changed it's BT name, IRL be careful this can break upstream logic, or have security implications.");
        }
        oldDevice.origin = FitbitBluetoothDevice.DeviceOrigin.SCANNED;
        if (!previousDeviceName.equals(device.getName()) ||
            previousRssi != device.getRssi() ||
            (previousScanRecord != null && device.getScanRecord() != null &&
                !Arrays.equals(previousScanRecord.getBytes(), device.getScanRecord().getBytes()))) {
            //Timber.v("Found device may have changed was %s, and now is %s", oldDevice, device);
            oldDevice.setName(device.getName());
            oldDevice.setScanRecord(device.getScanRecord());
            oldDevice.setRssi(device.getRssi());
        }
        notifyListenersOfConnectionAdded(conn);
    }
}
 
Example #5
Source File: AbstractScanner.java    From easyble-x with Apache License 2.0 5 votes vote down vote up
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
void parseScanResult(BluetoothDevice device, @Nullable ScanResult result) {
    if (result == null) {
        parseScanResult(device, false);
    } else {
        ScanRecord record = result.getScanRecord();
        parseScanResult(device, false, result, result.getRssi(), record == null ? null : record.getBytes());            
    }
}
 
Example #6
Source File: DeviceDiscovererV21.java    From science-journal with Apache License 2.0 5 votes vote down vote up
private void manageScanResult(ScanResult result) {
  List<String> serviceUuids = new ArrayList<>();
  ScanRecord record = result.getScanRecord();
  if (record != null) {
    List<ParcelUuid> parcelUuids = record.getServiceUuids();
    if (parcelUuids != null) {
      for (ParcelUuid uuid : parcelUuids) {
        serviceUuids.add(uuid.toString());
      }
    }
  }
  addOrUpdateDevice(new NativeDevice(result.getDevice(), serviceUuids), result.getRssi());
}
 
Example #7
Source File: BleManager.java    From FastBle with Apache License 2.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public BleDevice convertBleDevice(ScanResult scanResult) {
    if (scanResult == null) {
        throw new IllegalArgumentException("scanResult can not be Null!");
    }
    BluetoothDevice bluetoothDevice = scanResult.getDevice();
    int rssi = scanResult.getRssi();
    ScanRecord scanRecord = scanResult.getScanRecord();
    byte[] bytes = null;
    if (scanRecord != null)
        bytes = scanRecord.getBytes();
    long timestampNanos = scanResult.getTimestampNanos();
    return new BleDevice(bluetoothDevice, rssi, bytes, timestampNanos);
}
 
Example #8
Source File: ScanRecordCompat.java    From AndroidBleManager with Apache License 2.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
ScanRecordCompat(ScanRecord record) {
    mServiceUuids = record.getServiceUuids();
    mManufacturerSpecificData = record.getManufacturerSpecificData();
    mServiceData = record.getServiceData();
    mDeviceName = record.getDeviceName();
    mAdvertiseFlags = record.getAdvertiseFlags();
    mTxPowerLevel = record.getTxPowerLevel();
    mBytes = record.getBytes();
}
 
Example #9
Source File: EddystoneScannerService.java    From nearby-beacons with MIT License 5 votes vote down vote up
private void processResult(ScanResult result) {
    ScanRecord record = result.getScanRecord();
    if (record == null) {
        Log.w(TAG, "Invalid scan record.");
        return;
    }
    final byte[] data = record.getServiceData(UID_SERVICE);
    if (data == null) {
        Log.w(TAG, "Invalid Eddystone scan result.");
        return;
    }

    final String deviceAddress = result.getDevice().getAddress();
    final int rssi = result.getRssi();
    byte frameType = data[0];
    switch (frameType) {
        case TYPE_UID:
            mCallbackHandler.post(new Runnable() {
                @Override
                public void run() {
                    processUidPacket(deviceAddress, rssi, data);
                }
            });
            break;
        case TYPE_TLM:
        case TYPE_URL:
            //Do nothing, ignoring these
            return;
        default:
            Log.w(TAG, "Invalid Eddystone scan result.");
    }
}
 
Example #10
Source File: ScanCallbackBridge.java    From BlueSTSDK_Android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void onScanResult(int callbackType, ScanResult result) {
    super.onScanResult(callbackType, result);
    ScanRecord record = result.getScanRecord();
    if(record!=null)
        mCallbackPre21.onLeScan(result.getDevice(),result.getRssi(),record.getBytes());
}
 
Example #11
Source File: FitbitBluetoothDevice.java    From bitgatt with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * Scan Record which is useful for getting service data for further filtering
 * @return The scan record
 */

public @Nullable ScanRecord getScanRecord() {
    return scanRecord;
}
 
Example #12
Source File: FitbitBluetoothDevice.java    From bitgatt with Mozilla Public License 2.0 4 votes vote down vote up
void setScanRecord(ScanRecord scanRecord) {
    this.scanRecord = scanRecord;
    notifyListenersOfPropertyChanged();
}
 
Example #13
Source File: LollipopPeripheral.java    From react-native-ble-manager with Apache License 2.0 4 votes vote down vote up
public void updateData(ScanRecord scanRecord) {
	advertisingData = scanRecord;
	advertisingDataBytes = scanRecord.getBytes();
}
 
Example #14
Source File: ScanJob.java    From android-beacon-library with Apache License 2.0 4 votes vote down vote up
@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.d(TAG, "ScanJob Lifecycle START: "+ScanJob.this);
    new Thread(new Runnable() {
        public void run() {
            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");

            // This syncronized block is around the scan start.
            // Without it, it is possilbe that onStopJob is called in another thread and
            // 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;
}
 
Example #15
Source File: JsonSerializer.java    From mobly-bundled-snippets with Apache License 2.0 3 votes vote down vote up
/**
 * Serialize ScanRecord for Bluetooth LE.
 *
 * <p>Not all fields are serialized here. Will add more as we need.
 *
 * <pre>The returned {@link Bundle} has the following info:
 *          "DeviceName", String
 *          "TxPowerLevel", String
 * </pre>
 *
 * @param record A {@link ScanRecord} object.
 * @return A {@link Bundle} object.
 */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private Bundle serializeBleScanRecord(ScanRecord record) {
    Bundle result = new Bundle();
    result.putString("DeviceName", record.getDeviceName());
    result.putInt("TxPowerLevel", record.getTxPowerLevel());
    return result;
}