问题描述
我能够发现并连接到蓝牙.
I am able to discover, connect to bluetooth.
源代码---
通过蓝牙连接到远程设备:
//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 设备发送命令,但不知道该怎么做.
Now I want to send commands to Remote BLE device but don't know how to do that.
一旦命令发送到 BLE 设备,BLE 设备将通过广播响应我的应用程序可以接收的数据.
Once the command is sent to the BLE device, the BLE device will respond by broadcastingdata which my application can receive.
推荐答案
当您连接到 BLE 设备并发现服务时,您需要将此过程分解为几个步骤:
You need to break this process into a few steps, when you connect to a BLE device and discover Services:
在
onServicesDiscovered
中为您的callback
显示可用的gattServices
Display available
gattServices
inonServicesDiscovered
for yourcallback
检查你是否可以写一个特性
检查 BluetoothGattCharacteristic PROPERTIES - 我没有意识到需要在BLE 硬件,这浪费了很多时间.
To check whether you can write a characteristic or not
check for BluetoothGattCharacteristic PROPERTIES -I didn't realize that need to enable the PROPERTY_WRITE on the BLE hardware and that wasted a lot of time.
当你写一个特性时,硬件是否执行任何动作来明确指示操作(在我的例子中我点亮了一个 LED)
When you write a characteristic, does the hardware perform any action to explicitly indicate the operation (in my case i was lighting an led)
假设 mWriteCharacteristic
是一个 BluetoothGattCharacteristic检查属性的部分应该是这样的:
Suppose mWriteCharacteristic
is a BluetoothGattCharacteristicThe part where to check the PROPERTY should be like:
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);
这些是您需要精确实现的代码的有用部分.
Those are the useful parts of the code that you need to implement precisely.
请参阅这个 github 项目,了解仅包含基本演示的实现.
Refer this github project for an implementation with just a basic demo.
这篇关于如何通过低功耗蓝牙 (BLE) 链接发送数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!