Android蓝牙。是否可以在扫描时将数据发送到设备?

Android BLE. Is it possible to send data to devices on scanning?

我正在开发一个具有 BLE 设备的应用程序,该设备仅在扫描时发送某些参数时才显示在扫描中。

App nrf Connect 很好地完成了这项任务(当按原始数据过滤时,并使用 0x02010612435542 原始数据参数)。

设备不会显示其名称,既不是 UUID,也不是制造商数据。 在 nrf Connect 上,它唯一共享的是像这样的原始 return:0X020106124355420000080390BECB49400400CB500CF(这正是我现在需要的)。 通过 Mac 地址扫描(在设备的一个单元上测试),它只得到它的 rssi)

我的问题是,就像 nrfConnect 一样,我如何编写一个过滤器或类似的东西,在扫描时作为参数发送,这样我就可以找到我的设备?这些设备没有名称(扫描时显示 N/A),我无法添加 Mac 地址过滤器列表,因为当我的应用程序时会有大量相同类型的设备完成了。

private List<ScanFilter> scanFilters() {
    List<ScanFilter> list = new ArrayList<ScanFilter>();

        ScanFilter scanFilter = new ScanFilter.Builder().build();
        list.add(scanFilter);

        //What kind of filter do I use to send that data on scanning?

    return list;
}

在您的 BLE 扫描仪中,您收到 ScanResult 包含 BluetoothDevice 的实例,即扫描的设备。至少,您应该能够读取设备的 BLE 地址,即它的硬件地址。使用方法:

BluetoothDevice.getAddress(); 

这个硬件地址应该有一个预定义的范围,比如以"A3:B4"开头,这样可以过滤scanRecords。向您的设备制造商询问这些硬件地址是如何生成的。

此外,如果您知道所支持设备的制造商 ID,则可以根据制造商数据设置过滤器:

ScanFilter scanFilter = new ScanFilter.Builder()
                                .setManufacturerData(manufacturerId, manufacturerData)
                                .build();

注意 manufacturerData 数组的前两个字节是 manufacturerId。

编辑:制造商数据是

返回的字节数组的一部分
scanResult.getScanRecord().getBytes()

scanResult 被传递给你给 BluetoothLESCanner.startScan(...)

ScanCallback

我终于找到了解决问题的方法。

这不是我的想法,但感谢@matdev,我设法以某种方式弄明白了。它没有回答主要问题,即是否可以在扫描时将数据发送到设备,但是,该解决方案对我有用。

首先,我按名称制作了一个过滤器,其中设备name == null

private List<ScanFilter> scanFilters() {
    List<ScanFilter> list = new ArrayList<ScanFilter>();

    ScanFilter scanFilterName = new ScanFilter.Builder().setDeviceName(null).build();

    list.add(scanFilterName);

    return list;
}

它给了我一个包含大量设备的巨大列表。所以我添加了另一个过滤器,但这次是在 scanResult() 上。另一个过滤器是 MAC Address 后缀,正如@matdev 指出的那样,它与我的设备相同。

private Set<String> btDeviceData = new LinkedHashSet<String>();
private ScanCallback scanCallback = new ScanCallback() {
    @Override
    public void onScanResult(int callbackType, ScanResult result) {

        BluetoothDevice device = result.getDevice();

        ScanRecord record = result.getScanRecord();
        byte[] dataByteArray = record.getBytes();

        if (device.getAddress().startsWith("F8:36:9B")) {

            btDeviceData.add(device.getAddress());
        }
    }
};

通过这样做,我得到了一个列表(Set 是具体的),其中只有我正在寻找的设备。