【发布时间】:2017-12-20 07:28:50
【问题描述】:
在过去的 6 个月里,我一直致力于 BLE 应用程序。 在我最近的项目中,我正在集成一个自定义 BLE 设备,它在读取数据时会出现同步问题。 “onCharacteristicRead”总是返回 133 错误代码。请通过完整的场景,如果有人有任何解决方案,请帮助我。
场景 定制 BLE 设备提供三种服务。
紧急情况
一目了然
电池电量
我的应用程序中只需要两个服务。电池和紧急情况。 最初,我将使用以下代码扫描设备,
private void scan() {
if (isLollyPopOrAbove()) {// Start Scanning For Lollipop devices
mBluetoothAdapter.getBluetoothLeScanner().startScan(scanFilters(), scanSettings(), scanCallback); // Start BLE device Scanning in a separate thread
} else {
mBluetoothAdapter.startLeScan(mLeScanCallback); // Start Scanning for Below Lollipop device
}
}
private List<ScanFilter> scanFilters() {
String emergencyUDID = "3C02E2A5-BB87-4BE0-ADA5-526EF4C14AAA";
ScanFilter filter = new ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString(emergencyUDID)).build();
List<ScanFilter> list = new ArrayList<ScanFilter>(1);
list.add(filter);
return list;
}
private ScanSettings scanSettings() {
ScanSettings settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_BALANCED).build();
return settings;
}
这工作正常,我正在获得扫描结果,我可以连接到设备。建立连接后,我将从 GattCallBack 进行以下调用
mBluetoothGatt.discoverServices();
然后我得到服务发现完成回调
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) { //BLE service discovery complete
if (status == BluetoothGatt.GATT_SUCCESS) { //See if the service discovery was successful
Log.i(TAG, "**ACTION_SERVICE_DISCOVERED**" + status);
broadcastUpdate(BLEConstants.ACTION_GATT_SERVICES_DISCOVERED); //Go broadcast an intent to say we have discovered services
} else { //Service discovery failed so log a warning
Log.i(TAG, "onServicesDiscovered received: " + status);
}
}
从这里我找到使用提供的 UUID 的可用 MLDP 服务。这也很好用。
但是当我阅读特征时,
public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) { //Check that we have access to a Bluetooth radio
return;
}
boolean status = mBluetoothGatt.readCharacteristic(characteristic); //Request the BluetoothGatt to Read the characteristic
Log.i(TAG, "READ STATUS " + status);
}
响应状态为真,但“onCharacteristicRead”回调始终为 133
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { //A request to Read has completed
//String value = characteristic.getStringValue(0);
//int value = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT32, 0);
// if(characteristic.getUuid().e)
if (status == BluetoothGatt.GATT_SUCCESS) {
//See if the read was successful
Log.i(TAG, "**ACTION_DATA_READ**" + characteristic);
broadcastUpdate(BLEConstants.ACTION_DATA_AVAILABLE, characteristic); //Go broadcast an intent with the characteristic data
} else {
Log.i(TAG, "ACTION_DATA_READ: Error" + status);
}
}
【问题讨论】:
标签: android android-studio bluetooth bluetooth-lowenergy