我正在研究一种广告制造商特定数据的BLE传感器.是否有任何示例代码演示如何在
Android中接收广告数据包并解析其有效负载?
非常感谢您的帮助.
解决方法
这就是我想要的:
BLE扫描API BluetoothAdapter.startLeScan(ScanCallback)需要回调功能才能获得扫描结果.该方法需要如下所示:
private BluetoothAdapter.LeScanCallback ScanCallback =
new BluetoothAdapter.LeScanCallback()onLeScan(final BluetoothDevice device,int RSSi,final byte[] scanRecord)
{...}
scanRecord变量是一个包含广告数据包有效负载的字节数组.
根据BLE规范,有效载荷的结构非常简单如下:
数据包最长可达47个字节,包括:
> 1字节前导码
> 4字节访问地址
> 2-39字节广告channelPDU
> 3字节CRC
对于广告通信信道,访问地址始终为0x8E89bed6.
PDU又有自己的头(2个字节:有效载荷的大小及其类型 – 设备是否支持连接等)和实际有效载荷(最多37个字节).
最后,有效载荷的前6个字节是设备的MAC地址,实际信息最多可以有31个字节.
实际信息的格式如下:
第一个字节是数据的长度,第二个字节是类型,后跟数据.
这是一种聪明的方法,允许任何应用程序跳过整个数据记录,如果他们不关心内容.
以下是确定Advertisement数据包内容的示例代码:
parseAdvertisementPacket(final byte[] scanRecord) {
byte[] advertisedData = Arrays.copyOf(scanRecord,scanRecord.length);
int offset = 0;
while (offset < (advertisedData.length - 2)) {
int len = advertisedData[offset++];
if (len == 0)
break;
int type = advertisedData[offset++];
switch (type) {
case 0x02: // Partial list of 16-bit UUIDs
case 0x03: // Complete list of 16-bit UUIDs
while (len > 1) {
int uuid16 = advertisedData[offset++] & 0xFF;
uuid16 |= (advertisedData[offset++] << 8);
len -= 2;
uuids.add(UUID.fromString(String.format(
"%08x-0000-1000-8000-00805f9b34fb",uuid16)));
}
break;
case 0x06:// Partial list of 128-bit UUIDs
case 0x07:// Complete list of 128-bit UUIDs
// Loop through the advertised 128-bit UUID's.
while (len >= 16) {
try {
// Wrap the advertised bits and order them.
ByteBuffer buffer = ByteBuffer.wrap(advertisedData,offset++,16).order(ByteOrder.LITTLE_ENDIAN);
long mostSignificantBit = buffer.getLong();
long leastSignificantBit = buffer.getLong();
uuids.add(new UUID(leastSignificantBit,mostSignificantBit));
} catch (indexoutofboundsexception e) {
// Defensive programming.
Log.e("BluetoothDeviceFilter.parseUUID",e.toString());
continue;
} finally {
// Move the offset to read the next uuid.
offset += 15;
len -= 16;
}
}
break;
case 0xFF: // Manufacturer Specific Data
Log.d(TAG,"Manufacturer Specific Data size:" + len +" bytes" );
while (len > 1) {
if(i < 32) {
MfgData[i++] = advertisedData[offset++];
}
len -= 1;
}
Log.d(TAG,"Manufacturer Specific Data saved." + MfgData.toString());
break;
default:
offset += (len - 1);
break;
}
}
谢谢
how-ibeacons-work
bluetooth org specs
mass让我朝着正确的方向前进!