Aya*_*fov 5 android bluetooth-lowenergy
在蓝牙低功耗协议的问题上苦苦挣扎。例如,一个设备有一个服务,该服务包含一个包含描述符的特征。服务的 UUID、特征和描述符事先未知。我的问题是如何以我们知道这个特定 UUID 是一种服务/特性/描述符的方式获取它们的 UUID?
BluetoothGatt.getServices()没有帮助,因为它会一起返回所有 UUID,而我们不知道哪一个属于该服务。我确信有一种方法可以分割 UUID。至少 nRF Connect 应用程序(您可以在 Play 商店中找到它)可以做到这一点。
我解决该问题的唯一方法是使用ScanRecord从ScanResult. ScanRecord存储有关每个扫描设备的一些信息,包括服务的 UUID。ScanRecord一旦通过方法开始扫描initScanning()并返回任何结果,我们就可以访问对象onScanResult():
List<UUID> serviceUUIDsList = new ArrayList<>();
List<UUID> characteristicUUIDsList = new ArrayList<>();
List<UUID> descriptorUUIDsList = new ArrayList<>();
private void initScanning(BluetoothLeScannerCompat bleScanner)
{
bleScanner.startScan(getScanCallback());
}
private ScanCallback getScanCallback()
{
return new ScanCallback()
{
@Override
public void onScanResult(int callbackType, ScanResult scanResult)
{
super.onScanResult(callbackType, scanResult);
serviceUUIDsList = getServiceUUIDsList(scanResult);
}
};
}
private List<UUID> getServiceUUIDsList(ScanResult scanResult)
{
List<ParcelUuid> parcelUuids = scanResult.getScanRecord().getServiceUuids();
List<UUID> serviceList = new ArrayList<>();
for (int i = 0; i < parcelUuids.size(); i++)
{
UUID serviceUUID = parcelUuids.get(i).getUuid();
if (!serviceList.contains(serviceUUID))
serviceList.add(serviceUUID);
}
return serviceList;
}
Run Code Online (Sandbox Code Playgroud)
因此,当我们知道服务 UUID 时,我们可以获得特征和描述符的 UUID:
private void defineCharAndDescrUUIDs(BluetoothGatt bluetoothGatt)
{
List<BluetoothGattService> servicesList = bluetoothGatt.getServices();
for (int i = 0; i < servicesList.size(); i++)
{
BluetoothGattService bluetoothGattService = servicesList.get(i);
if (serviceUUIDsList.contains(bluetoothGattService.getUuid()))
{
List<BluetoothGattCharacteristic> bluetoothGattCharacteristicList = bluetoothGattService.getCharacteristics();
for (BluetoothGattCharacteristic bluetoothGattCharacteristic : bluetoothGattCharacteristicList)
{
characteristicUUIDsList.add(bluetoothGattCharacteristic.getUuid());
List<BluetoothGattDescriptor> bluetoothGattDescriptorsList = bluetoothGattCharacteristic.getDescriptors();
for (BluetoothGattDescriptor bluetoothGattDescriptor : bluetoothGattDescriptorsList)
{
descriptorUUIDsList.add(bluetoothGattDescriptor.getUuid());
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我希望,我也可以帮助其他遇到类似问题的人。
| 归档时间: |
|
| 查看次数: |
29396 次 |
| 最近记录: |