Log
欲善其事,先利其器。推荐一款功能强大的测试工具:nRF Connect
一般情况蓝牙设备所有的UUID都是硬件工程师提供的,但也有例外,比如和我对接的硬件工程师连UUID是什么都不知道……那你就需要自己动手丰衣足食,使用nRF Connect这款工具来查看你的设备的UUID。
一、使用的Android自带的bluetooth
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
二、接收数据需要订阅,重写BluetoothGattCallback里onServicesDiscovered方法,然后在里面订阅
/**
* 发现设备(真正建立连接)
* @param gatt
* @param status
*/
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status)
{
//直到这里才是真正建立了可通信的连接
//通过UUID找到服务
m_bluetoothGattService = m_bluetoothGatt.getService(SERVICE_UUID);
if(m_bluetoothGattService != null)
{
//写数据的服务和特征
m_bluetoothGattCharacteristic_write = m_bluetoothGattService.getCharacteristic(WRITE_UUID);
if(m_bluetoothGattCharacteristic_write != null)
{
Log.i(TAG, ">>>已找到写入数据的特征值!");
Message message = new Message();
message.what = MESSAGE_1;
handler.sendMessage(message);
}
else
{
Log.e(TAG, ">>>该UUID无写入数据的特征值!");
}
//读取数据的服务和特征
m_bluetoothGattCharacteristic_read = m_bluetoothGattService.getCharacteristic(READ_UUID);
if(m_bluetoothGattCharacteristic_read != null)
{
Log.i(TAG, ">>>已找到读取数据的特征值!");
//订阅读取通知
gatt.setCharacteristicNotification(m_bluetoothGattCharacteristic_read, true);
BluetoothGattDescriptor descriptor = m_bluetoothGattCharacteristic_read.getDescriptor(CONFIG_UUID);
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
gatt.writeDescriptor(descriptor);
}
else
{
Log.e(TAG, ">>>该UUID无读取数据的特征值!");
}
}
}
SERVICE_UUID、WRITE_UUID、READ_UUID可以通过工具识别出来,CONFIG_UUID后面再说:
正常情况下工具会把CLIENT_CHARACTERISTIC_CONFIG对应的UUID也给识别出来,但是我手里这个设备它就是没有,再但是,没有CONFIG的UUID那这个工具又是怎么以Notify的方式接收到数据的???参考了别人的博客,抱着试一试的心态把别人UUID:00002902-0000-1000-8000-00805f9b34fb复制过来了,然后就接收到数据了(技术不够,玄学来凑)……