0

我正在扫描由 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 应用程序成功查看隐藏的 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();
}
}
4

1 回答 1

0

您的代码没有问题,RxAndroidBle. 您正在扫描的外围设备最终会被发现

你遇到的是iOS应用程序在后台模式下的预期行为——The bluetooth-peripheral Background Execution Mode官方参考网站上搜索。

参考文献指出:

如果所有正在做广告的应用程序都在后台,您的外围设备发送广告包的频率可能会降低。

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

此致

于 2018-01-04T15:07:17.583 回答