查找 Android 蓝牙 LE GATT 配置文件



我已经实现了Android LE蓝牙示例,该示例可以找到心率监测器并连接到它。但是,此示例有一个定义 GATT 配置文件的类,如下所示:

 private static HashMap<String, String> attributes = new HashMap();
public static String HEART_RATE_MEASUREMENT = "00002a37-0000-1000-8000-00805f9b34fb";
public static String CLIENT_CHARACTERISTIC_CONFIG = "00002902-0000-1000-8000-00805f9b34fb";
static {
    // Sample Services.
    attributes.put("0000180d-0000-1000-8000-00805f9b34fb", "Heart Rate Service");
    attributes.put("0000180a-0000-1000-8000-00805f9b34fb", "Device Information Service");
    // Sample Characteristics.
    attributes.put(HEART_RATE_MEASUREMENT, "Heart Rate Measurement");
    attributes.put("00002a29-0000-1000-8000-00805f9b34fb", "Manufacturer Name String");
}
public static String lookup(String uuid, String defaultName) {
    String name = attributes.get(uuid);
    return name == null ? defaultName : name;
}

现在,我想做的是更改它,以便该程序找到任何带有蓝牙的设备 le 但我不知道 Google 如何获得客户端特征配置的心率测量信息。

蓝牙 SIG 维护一个"分配号码"列表,其中包括在示例应用中找到的那些 UUID:https://www.bluetooth.com/specifications/assigned-numbers/

尽管 UUID 的长度为 128 位,但为蓝牙 LE 分配的编号列为 16 位十六进制值,因为较低的 96 位在一类属性中是一致的。

例如,所有BLE特征UUID的形式如下:

0000XXXX-0000-1000-8000-00805f9b34fb

心率测量特征 UUID 的分配编号列为 0x2A37 ,这就是示例代码的开发人员可以得出的方法:

00002a37-0000-1000-8000-00805f9b34fb

除了@Godfrey Duke的答案之外,以下是我用来提取UUID有效位的方法:

private static int getAssignedNumber(UUID uuid) {
    // Keep only the significant bits of the UUID
    return (int) ((uuid.getMostSignificantBits() & 0x0000FFFF00000000L) >> 32);
}

用法示例:

    // See https://developer.bluetooth.org/gatt/services/Pages/ServiceViewer.aspx?u=org.bluetooth.service.heart_rate.xml
    private static final int GATT_SERVICE_HEART_RATE = 0x180D;
    (...)
        for (BluetoothGattService service : services) {
            if (getAssignedNumber(service.getUuid()) == GATT_SERVICE_HEART_RATE) {
                // Found heart rate service
                onHeartRateServiceFound(service);
                found = true;
                break;
            }
        }

这是 gatt 回调的页面:https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html

您需要使用 BluetoothGatt.discoverServices();

然后在回调服务发现(...)我认为你需要使用蓝牙Gatt.getServices();

最新更新