Android 蓝牙4.0(ble)开发的解决方案

女爷i 2022-08-20 04:27 223阅读 0赞

最近,随着智能穿戴式设备、智能医疗以及智能家居的普及,蓝牙开发在移动开中显得非常的重要。由于公司需要,研究了一下,蓝牙4.0在Android中的应用。以下是我的一些总结。

1.先介绍一下关于蓝牙4.0中的一些名词吧:

  1. (1)GATT(Gneric Attibute Profile)

通过ble连接,读写属性类小数据Profile通用的规范。现在所有的ble应用Profile 都是基于GATT
(2)ATT(Attribute Protocal)

  1. GATT是基于ATT PotocalATT针对BLE设备专门做的具体就是传输过程中使用尽量少的数据,每个属性都有个唯一的UUID,属性chartcteristics and Service的形式传输。

(3)Service是Characteristic的集合。

  1. (4).Characteristic 特征类型。

比如。有个蓝牙ble的血压计。他可能包括多个Servvice,每个Service有包括多个Characteristic

注意:蓝牙ble只能支持Android 4.3以上的系统 SDK>=18

2.以下是开发的步骤:

  1. 2.1首先获取BluetoothManager
  2. BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
  3. 2.2获取BluetoothAdapter
  4. BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter();
  5. 2.3创建BluetoothAdapter.LeScanCallback
  6. private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
  7. @Override
  8. public void onLeScan(final BluetoothDevice device, int rssi, final byte[] scanRecord) {
  9. runOnUiThread(new Runnable() {
  10. @Override
  11. public void run() {
  12. try {
  13. String struuid = NumberUtils.bytes2HexString(NumberUtils.reverseBytes(scanRecord)).replace("-", "").toLowerCase();
  14. if (device!=null && struuid.contains(DEVICE_UUID_PREFIX.toLowerCase())) {
  15. mBluetoothDevices.add(device);
  16. }
  17. } catch (Exception e) {
  18. e.printStackTrace();
  19. }
  20. }
  21. });
  22. }
  23. };
  24. 2.4.开始搜索设备。
  25. mBluetoothAdapter.startLeScan(mLeScanCallback);

2.5.BluetoothDevice 描述了一个蓝牙设备 提供了getAddress()设备Mac地址,getName()设备的名称。

2.6开始连接设备

  1. /**
  2. * Connects to the GATT server hosted on the Bluetooth LE device.
  3. *
  4. * @param address
  5. * The device address of the destination device.
  6. *
  7. * @return Return true if the connection is initiated successfully. The
  8. * connection result is reported asynchronously through the
  9. * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
  10. * callback.
  11. */
  12. public boolean connect(final String address) {
  13. if (mBluetoothAdapter == null || address == null) {
  14. Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
  15. return false;
  16. }
  17. // Previously connected device. Try to reconnect. (先前连接的设备。 尝试重新连接)
  18. if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress) && mBluetoothGatt != null) {
  19. Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
  20. if (mBluetoothGatt.connect()) {
  21. mConnectionState = STATE_CONNECTING;
  22. return true;
  23. } else {
  24. return false;
  25. }
  26. }
  27. final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
  28. if (device == null) {
  29. Log.w(TAG, "Device not found. Unable to connect.");
  30. return false;
  31. }
  32. // We want to directly connect to the device, so we are setting the
  33. // autoConnect
  34. // parameter to false.
  35. mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
  36. Log.d(TAG, "Trying to create a new connection.");
  37. mBluetoothDeviceAddress = address;
  38. mConnectionState = STATE_CONNECTING;
  39. return true;
  40. }

2.7连接到设备之后获取设备的服务(Service)和服务对应的Characteristic。

  1. // Demonstrates how to iterate through the supported GATT
  2. // Services/Characteristics.
  3. // In this sample, we populate the data structure that is bound to the
  4. // ExpandableListView
  5. // on the UI.
  6. private void displayGattServices(List<BluetoothGattService> gattServices) {
  7. if (gattServices == null)
  8. return;
  9. String uuid = null;
  10. ArrayList<HashMap<String, String>> gattServiceData = new ArrayList<>();
  11. ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData = new ArrayList<>();
  12. mGattCharacteristics = new ArrayList<>();
  13. // Loops through available GATT Services.
  14. for (BluetoothGattService gattService : gattServices) {
  15. HashMap<String, String> currentServiceData = new HashMap<>();
  16. uuid = gattService.getUuid().toString();
  17. if (uuid.contains("ba11f08c-5f14-0b0d-1080")) {//服务的uuid
  18. //System.out.println("this gattService UUID is:" + gattService.getUuid().toString());
  19. currentServiceData.put(LIST_NAME, "Service_OX100");
  20. currentServiceData.put(LIST_UUID, uuid);
  21. gattServiceData.add(currentServiceData);
  22. ArrayList<HashMap<String, String>> gattCharacteristicGroupData = new ArrayList<>();
  23. List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
  24. ArrayList<BluetoothGattCharacteristic> charas = new ArrayList<>();
  25. // Loops through available Characteristics.
  26. for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
  27. charas.add(gattCharacteristic);
  28. HashMap<String, String> currentCharaData = new HashMap<>();
  29. uuid = gattCharacteristic.getUuid().toString();
  30. if (uuid.toLowerCase().contains("cd01")) {
  31. currentCharaData.put(LIST_NAME, "cd01");
  32. } else if (uuid.toLowerCase().contains("cd02")) {
  33. currentCharaData.put(LIST_NAME, "cd02");
  34. } else if (uuid.toLowerCase().contains("cd03")) {
  35. currentCharaData.put(LIST_NAME, "cd03");
  36. } else if (uuid.toLowerCase().contains("cd04")) {
  37. currentCharaData.put(LIST_NAME, "cd04");
  38. } else {
  39. currentCharaData.put(LIST_NAME, "write");
  40. }
  41. currentCharaData.put(LIST_UUID, uuid);
  42. gattCharacteristicGroupData.add(currentCharaData);
  43. }
  44. mGattCharacteristics.add(charas);
  45. gattCharacteristicData.add(gattCharacteristicGroupData);
  46. mCharacteristicCD01 = gattService.getCharacteristic(UUID.fromString("0000cd01-0000-1000-8000-00805f9b34fb"));
  47. mCharacteristicCD02 = gattService.getCharacteristic(UUID.fromString("0000cd02-0000-1000-8000-00805f9b34fb"));
  48. mCharacteristicCD03 = gattService.getCharacteristic(UUID.fromString("0000cd03-0000-1000-8000-00805f9b34fb"));
  49. mCharacteristicCD04 = gattService.getCharacteristic(UUID.fromString("0000cd04-0000-1000-8000-00805f9b34fb"));
  50. mCharacteristicWrite = gattService.getCharacteristic(UUID.fromString("0000cd20-0000-1000-8000-00805f9b34fb"));
  51. //System.out.println("=======================Set Notification==========================");
  52. // 开始顺序监听,第一个:CD01
  53. mBluetoothLeService.setCharacteristicNotification(mCharacteristicCD01, true);
  54. mBluetoothLeService.setCharacteristicNotification(mCharacteristicCD02, true);
  55. mBluetoothLeService.setCharacteristicNotification(mCharacteristicCD03, true);
  56. mBluetoothLeService.setCharacteristicNotification(mCharacteristicCD04, true);
  57. }
  58. }
  59. }

2.8获取到特征之后,找到服务中可以向下位机写指令的特征,向该特征写入指令。

  1. public void wirteCharacteristic(BluetoothGattCharacteristic characteristic) {
  2. if (mBluetoothAdapter == null || mBluetoothGatt == null) {
  3. Log.w(TAG, "BluetoothAdapter not initialized");
  4. return;
  5. }
  6. mBluetoothGatt.writeCharacteristic(characteristic);
  7. }

2.9写入成功之后,开始读取设备返回来的数据。

  1. private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
  2. @Override
  3. public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
  4. String intentAction;
  5. //System.out.println("=======status:" + status);
  6. if (newState == BluetoothProfile.STATE_CONNECTED) {
  7. intentAction = ACTION_GATT_CONNECTED;
  8. mConnectionState = STATE_CONNECTED;
  9. broadcastUpdate(intentAction);
  10. Log.i(TAG, "Connected to GATT server.");
  11. // Attempts to discover services after successful connection.
  12. Log.i(TAG, "Attempting to start service discovery:" + mBluetoothGatt.discoverServices());
  13. } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
  14. intentAction = ACTION_GATT_DISCONNECTED;
  15. mConnectionState = STATE_DISCONNECTED;
  16. Log.i(TAG, "Disconnected from GATT server.");
  17. broadcastUpdate(intentAction);
  18. }
  19. }
  20. @Override
  21. public void onServicesDiscovered(BluetoothGatt gatt, int status) {
  22. if (status == BluetoothGatt.GATT_SUCCESS) {
  23. broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
  24. } else {
  25. Log.w(TAG, "onServicesDiscovered received: " + status);
  26. }
  27. }
  28. //从特征中读取数据
  29. @Override
  30. public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
  31. //System.out.println("onCharacteristicRead");
  32. if (status == BluetoothGatt.GATT_SUCCESS) {
  33. broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
  34. }
  35. }
  36. //向特征中写入数据
  37. @Override
  38. public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
  39. //System.out.println("--------write success----- status:" + status);
  40. }
  41. /*
  42. * when connected successfully will callback this method this method can
  43. * dealwith send password or data analyze
  44. *当连接成功将回调该方法
  45. */
  46. @Override
  47. public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
  48. broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
  49. if (characteristic.getValue() != null) {
  50. //System.out.println(characteristic.getStringValue(0));
  51. }
  52. //System.out.println("--------onCharacteristicChanged-----");
  53. }
  54. @Override
  55. public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
  56. //System.out.println("onDescriptorWriteonDescriptorWrite = " + status + ", descriptor =" + descriptor.getUuid().toString());
  57. UUID uuid = descriptor.getCharacteristic().getUuid();
  58. if (uuid.equals(UUID.fromString("0000cd01-0000-1000-8000-00805f9b34fb"))) {
  59. broadcastUpdate(ACTION_CD01NOTIDIED);
  60. } else if (uuid.equals(UUID.fromString("0000cd02-0000-1000-8000-00805f9b34fb"))) {
  61. broadcastUpdate(ACTION_CD02NOTIDIED);
  62. } else if (uuid.equals(UUID.fromString("0000cd03-0000-1000-8000-00805f9b34fb"))) {
  63. broadcastUpdate(ACTION_CD03NOTIDIED);
  64. } else if (uuid.equals(UUID.fromString("0000cd04-0000-1000-8000-00805f9b34fb"))) {
  65. broadcastUpdate(ACTION_CD04NOTIDIED);
  66. }
  67. }
  68. @Override
  69. public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
  70. //System.out.println("rssi = " + rssi);
  71. }
  72. };
  73. ----------------------------------------------
  74. //从特征中读取数据
  75. @Override
  76. public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
  77. //System.out.println("onCharacteristicRead");
  78. if (status == BluetoothGatt.GATT_SUCCESS) {
  79. broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
  80. }
  81. }

2.10、断开连接

  1. /**
  2. * Disconnects an existing connection or cancel a pending connection. The
  3. * disconnection result is reported asynchronously through the
  4. * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
  5. * callback.
  6. */
  7. public void disconnect() {
  8. if (mBluetoothAdapter == null || mBluetoothGatt == null) {
  9. Log.w(TAG, "BluetoothAdapter not initialized");
  10. return;
  11. }
  12. mBluetoothGatt.disconnect();
  13. }

2.11、数据的转换方法

  1. // byte转十六进制字符串
  2. public static String bytes2HexString(byte[] bytes) {
  3. String ret = "";
  4. for (byte aByte : bytes) {
  5. String hex = Integer.toHexString(aByte & 0xFF);
  6. if (hex.length() == 1) {
  7. hex = '0' + hex;
  8. }
  9. ret += hex.toUpperCase(Locale.CHINA);
  10. }
  11. return ret;
  12. }
  13. /**
  14. * 将16进制的字符串转换为字节数组
  15. *
  16. * @param message
  17. * @return 字节数组
  18. */
  19. public static byte[] getHexBytes(String message) {
  20. int len = message.length() / 2;
  21. char[] chars = message.toCharArray();
  22. String[] hexStr = new String[len];
  23. byte[] bytes = new byte[len];
  24. for (int i = 0, j = 0; j < len; i += 2, j++) {
  25. hexStr[j] = "" + chars[i] + chars[i + 1];
  26. bytes[j] = (byte) Integer.parseInt(hexStr[j], 16);
  27. }
  28. return bytes;
  29. }

大概整体就是如上的步骤。但是也是要具体根据厂家的协议来实现通信的过程。

就那一个我们项目中的demo说一下。
一个蓝牙ble的血压计。 上位机—-手机 下位机 — 血压计
1.血压计与手机连接蓝牙之后。
2.上位机主动向下位机发送一个身份验证指令,下位机收到指令后开始给上位做应答,
3.应答成功,下位机会将测量的血压数据传送到上位机。
4.最后断开连接。

发表评论

表情:
评论列表 (有 0 条评论,223人围观)

还没有评论,来说两句吧...

相关阅读

    相关 android BLE

    直接上代码吧,完整的程序代码如下: 首先是MainActivity,本段代码完成了子模转换和保存数据的功能,并将要发送的数据整理成了和作者的小伙伴说好的格式。需要注意的是,

    相关 Android Ble开发(客户端)

    最近项目里面需要集成一个蓝牙的连接功能,作为一枚刚刚毕业不久的新生,大学几年又白过的。只好在几天内搜搜百度,脑补一下。文章部分内容摘至各大Blog,加上本dust的见解,写了一