BLE设备提供的数据称为特征。这些数据包是特殊形成的、紧密封装的字节数组,它们为特定的特定值编码。Services。您可以查看指定号码 https://www.bluetooth.com/specifications/assigned-numbers/在蓝牙官方网站上。在这里您将找到定义的(权威的)GATT 服务及其所属特征。
例如,您有一个可报告速度和踏频的 BLE 自行车电脑。您可以在指定的数字规格中查找骑行速度和踏频项目。这关贸总协定服务(第 3.4 章)包含服务的 UUID (0x1816)。然后您转到蓝牙规格 https://www.bluetooth.com/specifications/specs/页面并执行以下操作:
- 搜索骑行速度和踏频服务。结果将有链接到规格 https://www.bluetooth.com/specifications/specs/cycling-speed-and-cadence-service-1-0/CSC 服务。其中包含有关服务、其特征等的有用信息。您检查特征并记下您感兴趣的内容。在我们的例子中,它将是CSC测量特征。下一点解释如何获取它的字段。
- 搜索关贸总协定规范补充。结果列表将包含该结果的许多修订关贸总协定规范补充 https://www.bluetooth.com/specifications/specs/gatt-specification-supplement/。该文档包含所有 GATT 特征字段、类型信息等。在 PDF 中搜索CSC测量这应该会带你到第 3.61 章。它描述了 CSC 字段、以八位位组(字节)为单位的数据大小以及有关值的附加信息。
这是一般的蓝牙 LE 部分,现在回到 Android。请注意,您必须查找这些字段才能从特征中获取值。我只是假设您已经具有想要从中获取数据的特征。这是一个检索车轮和曲柄转数(如果可用)的快速示例。
BluetoothGattCharacteristic characteristic = ... ;
int offset = 0; // we define the offset that is to be used when reading the next field
// FORMAT_* values are constants in BluetoothGattCharacteristic
// these represent the values you can find in the "Value Fields" table in the "Format" column
int flags = characteristic.getIntValue(FORMAT_UINT8, offset);
offset += 1; // UINT8 = 8 bits = 1 byte
// we have to check the flags' 0th bit to see if C1 field exists
if ((flags & 1) != 0) {
int cumulativeWheelRevolutions = characteristic.getIntValue(FORMAT_UINT32, offset);
offset += 4; // UINT32 = 32 bits = 4 bytes
int lastWheelEventTime = characteristic.getIntValue(FORMAT_UINT16, offset);
offset += 2; // UINT16 = 16 bits = 2 bytes
}
// we have to check the flags' 1st bit to see if C2 field exists
if ((flags & 2) != 0) {
int cumulativeCrankRevolutions = characteristic.getIntValue(FORMAT_UINT16, offset);
offset += 2;
int lastCrankEventTime = characteristic.getIntValue(FORMAT_UINT16, offset);
offset += 2;
}
The flags
需要检查字段中的特定位,因为设备可能不会报告每种类型的数据,例如它不计算车轮转数。所选特征的工作表始终包含有关此字段的相关信息(如果存在)。
还值得注意的是,文档说
CSC 测量特性(CSC 指骑行速度和踏频)是一种包含标志字段的可变长度结构,并且根据标志字段的内容,可能包含一个或多个附加字段 [...]
这就是为什么您不能假设在 7 个字节(8+32+16位;分别为1+4+2字节) 偏移量,并且当您沿着字段前进时,应该计算偏移量。
这是从 BLE 设备读取骑行速度和踏频值的示例。您必须为您想要在应用程序中支持的每个设备(或更确切地说是服务)查找这些可用字段和值。如果设备是特殊设备并且无法在此 GATT 目录中找到,您需要查阅设备的手册、SDK 或供应商以获取更多信息。