我想创建一个 android 应用程序,以便从 ESP32 板连接和检索数据,以及使用蓝牙低功耗通信向板发送值的能力。
我有一个内部带有 BLE 服务器的 ESP32 板。我已经实现了一个具有以下特性的自定义服务。
/* define the characteristic and it's propeties */
BLECharacteristic dataCharacteristic(
BLEUUID((uint16_t)0x1A00),
BLECharacteristic::PROPERTY_READ |
BLECharacteristic::PROPERTY_WRITE |
BLECharacteristic::PROPERTY_NOTIFY);
我在 android 应用程序中成功实现了所有的扫描、读取和通知功能,但是在编写 BluetoothGatt.writeCharacteristic 时,第一个条件总是返回 false:
if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_WRITE) == 0
&& (characteristic.getProperties()
& BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) == 0) {
return false;
}
在调试 android 应用程序时,characteristic.getProperties() 始终为 18。
public boolean writeCharacteristic(BluetoothGattCharacteristic characteristic) {
if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_WRITE) == 0
&& (characteristic.getProperties()
& BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) == 0) {
return false;
}
if (VDBG) Log.d(TAG, "writeCharacteristic() - uuid: " + characteristic.getUuid());
if (mService == null || mClientIf == 0 || characteristic.getValue() == null) return false;
BluetoothGattService service = characteristic.getService();
if (service == null) return false;
BluetoothDevice device = service.getDevice();
if (device == null) return false;
synchronized (mDeviceBusy) {
if (mDeviceBusy) return false;
mDeviceBusy = true;
}
try {
mService.writeCharacteristic(mClientIf, device.getAddress(),
characteristic.getInstanceId(), characteristic.getWriteType(),
AUTHENTICATION_NONE, characteristic.getValue());
} catch (RemoteException e) {
Log.e(TAG, "", e);
mDeviceBusy = false;
return false;
}
return true;
}
下面是使用上述函数的写特征代码:
//Get BLE Service
BluetoothGattService service = gatt.getService(SERVICE_UUID);
//Get the characteristic
BluetoothGattCharacteristic dataCharacteristic =
service.getCharacteristic(DATA_CHARACTERISTIC_UUID);
//Pass value
dataCharacteristic.setValue(value);
//Write characteristic
boolean success = gatt.writeCharacteristic(dataCharacteristic);
if(success){
Log.d(TAG, "Write characteristic successful");
}
else{
Log.e(TAG, "Write characteristic failed");
}
我已经尝试在没有读取或通知的情况下执行写入操作,以防止多个请求,但结果是相同的。
我还尝试使用具有读写通知功能的外部 BLE 应用程序,它们都与我的 ESP32 设置完美配合。