android ble开发--手机与ble终端通信

1. Android手机与BLE终端设备通信结果都是以回调的形式返回:

private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        //连接状态改变的回调
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status,
                int newState) {
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                // 连接成功后启动服务发现
                Log.e("test", "启动服务发现:" + mBluetoothGatt.discoverServices());
            }
        };

        //发现服务的回调
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {                                   
                 Log.e(TAG, "成功发现服务");
                           }else{
                   Log.e(TAG, "服务发现失败,错误码为:" + status);
                        }
        };
                 
        //写操作的回调
        public void onCharacteristicWrite(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                  Log.e(TAG, "写入成功" +characteristic.getValue());
                       }
               };
          
       //读操作的回调
       public void onCharacteristicRead(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                    Log.e(TAG, "读取成功" +characteristic.getValue());
                    }
                }
                
      //数据返回的回调(此处接收BLE设备返回数据)
      public void onCharacteristicChanged(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic) {
                };
            };
      }

2. 连接蓝牙BLE终端设备两种方式:

  • 通过BLE 设备的蓝牙 mac 地址
public boolean connect(String address) {
    if (mBluetoothAdapter == null || address == null) {
        ULog.e("BluetoothAdapter not initialized or unspecified address.");
        return false;
    }

    if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)
            && mBluetoothGatt != null) {
        ULog.i("Trying to use an existing mBluetoothGatt for connection.");
        return mBluetoothGatt.connect();
    }

    final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
    if (device == null) {
        ULog.e("Device not found,Unable to connect.");
        return false;
    }
    mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
    ULog.i("Trying to create a new connection.");
    mBluetoothDeviceAddress = address;
    return true;
}
  • 或者使用 BluetoothDevice 对象
private boolean connectBLEDevice(BluetoothDevice device) {
    if (null == mBluetoothAdapter || null == device) {
        LogUtils.e(TAG, "蓝牙适配器对象为null,或 device 为空");
        return false;
    }

    if (mState != State.STATE_IDLE && mState != State.STATE_DISCONNECT) {
        LogUtils.e(TAG, "connectBLEDevice():当前状态不可连接" + mState.name());
        return false;
    }
    //新建连接,device.connectGatt()方法中 false 表示立刻连接,true 表示在合适的时间连接
    mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
    LogUtils.d(TAG, "新建 Gatt 连接");
    mState = State.STATE_CONNECTING;
    return true;
}

连接成功与否都会通过BluetoothGattCallback这个回调来告诉我们:

// 连接状态改变的回调
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status,
                int newState) {
                        //代表连接成功,此处我们可以发送一个广播回去告诉activity已成功连接
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                //连接成功后启动服务发现
                Log.e("test", "启动服务发现:" + mBluetoothGatt.discoverServices());
            }
        }

3.启动服务发现

  • 连接成功后,我们就要去寻找我们所需要的服务,这里需要先启动服务发现:
mBluetoothGatt.discoverServices() ;
  • 启动服务发现的BluetoothGattCallback中回调:
// 发现服务的回调
    @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if(D) ULog.i(TAG, "onServicesDiscovered:");

            if (status == BluetoothGatt.GATT_SUCCESS) {
                /* broadcast the Service Discovered state to Page */
                ULog.i("ttest", "onServicesDiscovered");
                for(BluetoothGattService service : gatt.getServices()) {
                    ULog.i("ttest", "service UUID = " + service.getUuid());
                    //System.out.println("service UUID = " + service.getUuid());
                    
                    for(BluetoothGattCharacteristic characteristic : service.getCharacteristics()) {
                        ULog.i("ttest", "    characteristic UUID = " + characteristic.getUuid());
                        //System.out.println("characteristic UUID = " + characteristic.getUuid());

                        for(BluetoothGattDescriptor descriptor : characteristic.getDescriptors()) {
                            ULog.i("ttest", "        descriptor UUID = " + descriptor.getUuid());
                            //System.out.println("descriptor UUID = " + descriptor.getUuid());
                        }
                    }
                }
            } else {
                if(D) ULog.w(TAG, "onServicesDiscovered received: " + status);
            }
        }

4.开始通信

  • 可以从硬件工程师那边得到serviceUUID和characteristicUUID
BluetoothGattService service = mBluetoothGatt.getService(UUID.fromString("your service uuid"));
BluetoothGattCharacteristic characteristic= service.getCharacteristic(UUID.fromString("your characteristicUUID"));
  • 读操作,只需将相应的特征值传入即可得到该特征值下的数据,比如跟硬件工程师约定好serviceUUID和characteristicUUID直接读取ble设备中bin文件版本等一些功能,如下:
mBluetoothGatt.readCharacteristic(characteristic);

读取的结果通过onCharacteristicRead回调返回:(通过characteristic.getValue()就可以得到读取到的值了)

    @Override
    public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            Log.i("ttest", "UUID = " + characteristic.getUuid());
        }
  • 写操作,通过向characteristic写入指令(发送指令)以此来达到控制BLE终端设备的目的:
//将指令放置进特征中
characteristic.setValue(new byte[] {0x7a, 0x11, 0x03, 0x02,0x01,(byte) 0xab});
 //设置回复形式
 characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
 //开始写数据
mBluetoothGatt.writeCharacteristic(chharacteristic);

注:与仪器通信,我们这里发送的是16进制的数据,发送的时候需要先将其装载到byte[]数组中,例如我发送 7e 14 00 00 00 aa这个指令,我需要把它转化为ew byte[] {0x7a, 0x11, 0x03, 0x02,0x01,(byte) 0xab}这样去发送,因为BLE传输过程每次最大只能传输20个字节,所以如果发送的指令大于20字节的话要分包发送,例如现在要发送28个字节的,可以先write(前20个字节),开启线程sleep(几十毫秒)后在write(后面8个字节)。

5.ble终端设备返回数据

  • 当我们向BLE终端设备写入指令时,如果写入成功并且指令也正确,我们就会获得相应的响应指令,在下面这个回调中我们可以得到BLE设备返回回来的响应指令(通过characteristic.getValue()取出返回数据):
    // 数据返回的回调(此处接收机器返回数据并作处理)
        public void onCharacteristicChanged(BluetoothGatt gatt,    BluetoothGattCharacteristic characteristic) {
            Log.e("test",characteristic.getValue());
        };
  • 接收到返回数据的前提是我们设置了该特征具有Notification功能,所以完整的写操作代码应该是这样的(注意设置特征Notification的代码要放在最前):

           mBluetoothGatt.setCharacteristicNotification(characteristic,true)
           //将指令放置进来
           characteristic.setValue(new byte[] {0x7a, 0x11, 0x03, 0x02,0x01,(byte) 0xab});
           //设置回复形式
           characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
           //开始写数据
           mBluetoothGatt.writeCharacteristic(chharacteristic);

项目demo下载地址:

https://download.csdn.net/download/qingshui1234567/10629498
ps:有相关疑问及建议,可留言指导交流;

    原文作者:dong_hui
    原文地址: https://www.jianshu.com/p/09c2f816c1ef
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞