![](/img/trans.png)
[英]Android How to read BLE properties Readable Writable Notifiable GATT Characteristics
[英]How to write the Characteristics into BLE GATT server in android?
我正在使用藍牙低功耗GATT與該芯片進行通信。 我可以讀取芯片的響應,但是無法將特性發送到該芯片中,也無法通知某些特性。 只能幫上什么忙。
提前致謝。
假設您已正確設置BluetoothGattServer,已向服務注冊的特征以及已將服務添加到BluetoothGattServer,以下是向通知特征發送一些數據的示例:
private static final UUID serviceUuid = UUID.fromString("SOME-SERVICE-UUID");
private static final UUID characteristicUuid = UUID.fromString("SOME-CHAR-UUID");
private BluetoothGattServer gattServer;
private BluetoothDevice peerDevice;
public void sendNotification(byte p1, byte p2, byte p3, byte p4, int correlationid) {
ByteBuffer bb = ByteBuffer.allocate(8);
bb.order(ByteOrder.LITTLE_ENDIAN);
bb.put(p1).put(p2).put(p3).put(p4).putInt(correlationid);
BluetoothGattCharacteristic notifyingChar = gattServer.getService(serviceUuid).getCharacteristic(characteristicUuid);
notifyingChar.setValue(bb.array());
gattServer.notifyCharacteristicChanged(peerDevice, notifyingChar, false);
}
在BluetoothGattServerCallback.onNotificationSent
方法中發送數據后,您將收到一個事件:
@Override
public void onNotificationSent(BluetoothDevice device, int status) {
super.onNotificationSent(device, status);
Log.d("SVC", "BluetoothGattServerCallback.onNotificationSent");
}
好吧,首先,我強烈建議您使用名為RxAndroidBle的令人驚嘆的Bluetooth LE開源庫。 這將使整個過程更容易。
在將該庫包含在項目中之后,您將需要執行以下操作:
例:
RxBleClient rxBleClient = RxBleClient.create(context);
Disposable scanSubscription = rxBleClient.scanBleDevices(
new ScanSettings.Builder()
// .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) // change if needed
// .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES) // change if needed
.build()
// add filters if needed
)
.subscribe(
scanResult -> {
// Process scan result here.
},
throwable -> {
// Handle an error here.
}
);
// When done, just dispose.
scanSubscription.dispose();
writeCharacteristic()
方法寫入所需的字節。 例:
device.establishConnection(false)
.flatMapSingle(rxBleConnection -> rxBleConnection.writeCharacteristic(characteristicUUID, bytesToWrite))
.subscribe(
characteristicValue -> {
// Characteristic value confirmed.
},
throwable -> {
// Handle an error here.
}
);
例:
device.establishConnection(false)
.flatMap(rxBleConnection -> rxBleConnection.setupNotification(characteristicUuid))
.doOnNext(notificationObservable -> {
// Notification has been set up
})
.flatMap(notificationObservable -> notificationObservable) // <-- Notification has been set up, now observe value changes.
.subscribe(
bytes -> {
// Given characteristic has been changes, here is the value.
},
throwable -> {
// Handle an error here.
}
);
他們的Github頁面上有很多信息,並且在Stackoverflow中還有自己的專用標簽 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.