使用RxBleClient扫描背景中的BLE设备时出现问题

时间:2017-11-02 12:15:25

标签: android bluetooth-lowenergy gatt rxandroidble

我正在扫描由iOS设备创建的BLE设备。然后我连接到特定服务并阅读特定的特征。当具有GATT服务的iOS应用程序位于前台时,它非常有用。但是当隐藏iOS服务器应用程序时,Android客户端会停止检测BLE GATT设备。

public static ScanFilter[] getFilters(UUID serviceUuid) {
   ...
    filters.add(new ScanFilter.Builder().setServiceUuid(new ParcelUuid(serviceUuid)).build());
    return filters.toArray(new ScanFilter[filters.size()]);
}
public static ScanSettings getScanSettings() {
    return new ScanSettings.Builder()
            .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) // change if needed
            .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES) // change if needed
            .build();
}

BLE Scanner app成功查看隐藏的GATT服务器

更新 这是过滤器代码部分

public final class ScannerUtil {
public static final List<UUID> BEACON_UUUIDs = Arrays.asList(
...........

        UUID.fromString("a8427a96-70bd-4a7e-9008-6e5c3d445a2b"));


public static ScanSettings getScanSettings() {
    return new ScanSettings.Builder()
            .setScanMode(ScanSettings.SCAN_MODE_BALANCED) // change if needed
            .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES) // change if needed
            .build();
}

public static ScanFilter[] getFilters(UUID serviceUuid) {
    List<ScanFilter> filters = Stream.of(BEACON_UUUIDs)
            .map(iBeaconScanFilter::setScanFilter)
            .collect(toList());
    filters.add(new ScanFilter.Builder().setServiceUuid(new ParcelUuid(serviceUuid)).build());
    return filters.toArray(new ScanFilter[filters.size()]);
}

}

完整的扫描仪类代码如下:

public class BLEGlobalScanner {
    private final ScannerConfiguration configuration;
    private final Context context;
    private final RxBleClient rxBleClient;
    private final Map<String, String> devicesMap = new HashMap<>();
    private final Map<String, DeviceApoloBeacon> beaconsMap = new HashMap<>();
    private final ScanFilter[] scanFilter;
public BLEGlobalScanner(ScannerConfiguration configuration, Context context) {
    this.configuration = configuration;
    this.context = context;
    this.rxBleClient = RxBleClient.create(context);
    this.scanFilter = getFilters(configuration.beacons(), configuration.gattServer().server());
}

public Observable<BluetoothDeviceApolo> start() {
    return bluetoothEnableObservable(context).switchMap(aBoolean -> startScanner())
            .filter(Optional::isPresent)
            .map(Optional::get);
}

private Observable<Optional<BluetoothDeviceApolo>> startScanner() {
    return rxBleClient.scanBleDevices(getScanSettings(), scanFilter)
            .buffer(2, TimeUnit.SECONDS)
            .flatMap(rxBleDevices -> Observable.from(rxBleDevices)
                    .distinct(scanResult -> scanResult.getBleDevice().getMacAddress())
                    .concatMap(this::handleDevices)
                    .map(Optional::of))
            .observeOn(mainThread())
            .onErrorResumeNext(throwable -> {
                Timber.e(throwable, "startScanner");
                return Observable.just(Optional.empty());
            })
            .onExceptionResumeNext(Observable.just(Optional.empty()))
            .retry();
}

private Observable<BluetoothDeviceApolo> handleDevices(ScanResult scanResult) {
    if (beaconsMap.containsKey(scanResult.getBleDevice().getMacAddress())) {
        return Observable.fromCallable(() -> beaconsMap.get(scanResult.getBleDevice().getMacAddress()))
                .map(beacon -> beacon.toBuilder()
                        .lastSeen(System.currentTimeMillis())
                        .rssi(scanResult.getRssi())
                        .build());
    } else {
        return handleBeacon(scanResult)
                .map(device -> (BluetoothDeviceApolo) device)
                .switchIfEmpty(
                        handleDevice(scanResult).map(deviceApolo -> (BluetoothDeviceApolo) deviceApolo)
                );
    }
}

private Observable<DeviceApoloBeacon> handleBeacon(ScanResult scanResult) {
    return Observable.fromCallable(() -> scanResult.getScanRecord().getManufacturerSpecificData(COMPANY_ID_APPLE))
            .filter(bytes -> bytes != null)
            .filter(bytes -> DeviceApoloBeacon.requiredManufactureSize == bytes.length)
            .map(bytes -> DeviceApoloBeacon.builder()
                    .manufacturedData(bytes)
                    .lastSeen(System.currentTimeMillis())
                    .rssi(scanResult.getRssi())
                    .build())
            .filter(beacon -> configuration.beacons().contains(beacon.uuuid()))
            .doOnNext(beacon -> beaconsMap.put(scanResult.getBleDevice().getMacAddress(), beacon));
}


private Observable<DeviceApolo> handleDevice(ScanResult scanResult) {
    final RxBleDevice rxBleDevice = scanResult.getBleDevice();
    if (devicesMap.containsKey(rxBleDevice.getMacAddress())) {
        return Observable.fromCallable(() -> devicesMap.get(rxBleDevice.getMacAddress()))
                .timestamp()
                .map(deviceStr -> DeviceApolo.create(deviceStr.getValue(), deviceStr.getTimestampMillis(), scanResult.getRssi()));
    } else {
        return readCharacteristic(rxBleDevice, scanResult.getRssi());
    }
}

private Observable<DeviceApolo> readCharacteristic(RxBleDevice rxBleDevice, final int rssi) {
    return rxBleDevice.establishConnection(false)
            .compose(new ConnectionSharingAdapter())
            .switchMap(rxBleConnection -> rxBleConnection.readCharacteristic(configuration.gattServer().characteristic()))
            .map(String::new)
            .doOnNext(s -> devicesMap.put(rxBleDevice.getMacAddress(), s))
            .timestamp()
            .map(deviceStr -> DeviceApolo.create(deviceStr.getValue(), deviceStr.getTimestampMillis(), rssi))
            .retry();
}
}

1 个答案:

答案 0 :(得分:0)

您的代码没有问题,RxAndroidBle也存在问题。您正在扫描is discovered eventually的外围设备。

您遇到的是iOS应用在后台模式中的预期行为 - 在the official reference site上搜索The bluetooth-peripheral Background Execution Mode

参考说明:

  

如果所有宣传的应用都在后台,则外围设备发送广告包的频率可能会降低。

如果您打算将iOS应用程序用作外围设备,那么您可以做的事情就不多了(请查看文档)。或者,您可以检查是否可以在不同的硬件上实现外设(我不知道您的确切用例 - 但这不是这个问题的重点)。

最好的问候