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

问题描述 投票:0回答:1

我正在扫描由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();
}
}
android bluetooth-lowenergy gatt rxandroidble
1个回答
0
投票

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

你正在经历的是iOS应用程序在后台模式中的预期行为 - 在The bluetooth-peripheral Background Execution Mode上搜索the official reference site

参考说明:

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

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

最好的祝福

© www.soinside.com 2019 - 2024. All rights reserved.