在过去的6个月中,我正在研究BLE应用程序。在我最近的项目中,我正在集成一个自定义的BLE设备,并且在读取数据时会出现同步问题。" CharacteristicRead"始终返回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);
}
响应状态已成为现实,但" characteristicRead"回调始终为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);
}
}
最后,我找到了处理133误差的解决方案。在深入分析中,我发现BLE请求响应过程有一定延迟。因此,我为每次读取和写入一个500毫秒延迟。现在它正常工作。我已经在各种设备及其工作中对其进行了测试。我不知道这是否是解决方法。但这可能对面对类似问题的开发人员有帮助。
错误代码:133是指GATT__ERROR,设备不在范围内。在阅读活动期间可能有错误。我建议请先从设备侧检查。
一个Que:此设备需要连接?