我正在研究蓝牙低功耗GATT,以便与芯片进行通信。我可以读取芯片的响应,但我无法将特征发送到芯片中,也无法通知某些特征。只能帮上忙了。
提前谢谢。
发布于 2019-08-08 03:44:24
假设您的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");
}发布于 2019-08-08 04:00:09
首先,我强烈建议您使用令人惊叹的蓝牙LE开源库RxAndroidBle。这将使整个过程变得更容易。
一旦您在项目中包含了该库,您将需要执行以下操作:
对于设备,请确保蓝牙已启用,并且您已要求用户提供Location permissions.
示例:
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页面上有很多信息,他们也有自己的own dedicated tag in Stackoverflow。
https://stackoverflow.com/questions/36275550
复制相似问题