gpt4 book ai didi

android - 如何通过蓝牙低功耗 (BLE) 链路发送数据?

转载 作者:IT王子 更新时间:2023-10-28 23:31:24 26 4
gpt4 key购买 nike

我能够发现,连接到蓝牙。

源代码---

通过蓝牙连接到远程设备:

//Get the device by its serial number
bdDevice = mBluetoothAdapter.getRemoteDevice(blackBox);

//for ble connection
bdDevice.connectGatt(getApplicationContext(), true, mGattCallback);

Gatt 状态回调:

 private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
//Connection established
if (status == BluetoothGatt.GATT_SUCCESS
&& newState == BluetoothProfile.STATE_CONNECTED) {

//Discover services
gatt.discoverServices();

} else if (status == BluetoothGatt.GATT_SUCCESS
&& newState == BluetoothProfile.STATE_DISCONNECTED) {

//Handle a disconnect event

}
}

@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {

//Now we can start reading/writing characteristics

}
};

现在我想向远程 BLE 设备发送命令,但不知道该怎么做。

一旦命令发送到 BLE 设备,BLE 设备将通过广播进行响应我的应用程序可以接收的数据。

最佳答案

当您连接到 BLE 设备并发现服务时,您需要将此过程分解为几个步骤:

  1. onServicesDiscovered 中为您的 callback 显示可用的 gattServices

  2. 检查是否可以写一个特征
    检查 BluetoothGattCharacteristic PROPERTIES - 我没有意识到需要在 BLE 硬件上启用 PROPERTY_WRITE,这浪费了很多时间。

  3. 当你编写一个特性时,硬件是否会执行任何操作来明确指示该操作(在我的情况下,我正在点亮一个 LED)

假设 mWriteCharacteristicBluetoothGattCharacteristic检查属性的部分应该是这样的:

if (((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_WRITE) |
(charaProp & BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE)) > 0) {
// writing characteristic functions
mWriteCharacteristic = characteristic;
}

并且,写下你的特点:

// "str" is the string or character you want to write
byte[] strBytes = str.getBytes();
byte[] bytes = activity.mWriteCharacteristic.getValue();
YourActivity.this.mWriteCharacteristic.setValue(bytes);
YourActivity.this.writeCharacteristic(YourActivity.this.mWriteCharacteristic);

这些是您需要精确实现的代码中有用的部分。

请参阅 this github project仅包含基本演示的实现。

关于android - 如何通过蓝牙低功耗 (BLE) 链路发送数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23393010/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com