Android蓝牙BLE

作者: 愚蠢的高小星 | 来源:发表于2018-06-15 17:16 被阅读28次

概述
目前主流的蓝牙技术是BLE(4.x)低功耗蓝牙,相对于传统蓝牙,低功耗蓝牙传输速度更快,覆盖范围更广,安全性更高,延迟更短,耗电极低。Android系统4.3以上的版本支持BLE。传统蓝牙一般使用socket连接,而低功耗蓝牙通过Gatt协议实现,所以即使没有使用过传统蓝牙,也可以直接上手低功耗蓝牙。
BLE的通信流程大致可以概括为:扫描、连接、数据读写。本文主要通过这三方面来介绍BLE(4.x)低功耗蓝牙。

扫描
在蓝牙设备建立连接之前,我们需要先找到目标蓝牙设备,获取它的名称、地址等信息,这之后才能进行连接,这个过程就是扫描。

首先需要获取到BluetoothManager

BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);

然后通过BluetoothManager获取到BluetoothAdapter,它是移动设备本地的蓝牙适配器,使用BluetoothAdapter可以对蓝牙进行一系列基本操作,一个Android系统只有一个BluetoothAdapter

BluetoothAdapter bleAdapter = bluetoothManager.getAdapter();

获取到BluetoothAdapter,就可以对蓝牙进行操作了,首先我们先确认下移动设备的蓝牙是打开的

if (!bleAdapter.isEnabled()) {
      Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
      startActivityForResult(intent, REQUEST_BLE);
    }

接下来就可以进行扫描了。这里需要注意的是Android5.0以上和以下系统的扫描方式是不一样的

//扫描
  private void scan() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
      bleAdapter.getBluetoothLeScanner().startScan(scanCallback);
    } else {
      bleAdapter.startLeScan(leScanCallback);
    }
  }
//停止扫描
  private void stopScan() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
      bleAdapter.getBluetoothLeScanner().stopScan(scanCallback);
    } else {
      bleAdapter.stopLeScan(leScanCallback);
    }
  }

其中的scanCallback和leScanCallback就分别是5.0以上和以下的扫描回调函数

//扫描回调  >= 5.0
  ScanCallback scanCallback = new ScanCallback() {
    @Override
    public void onScanResult(int callbackType, ScanResult result) {
      super.onScanResult(callbackType, result);
      BluetoothDevice bleDevice = result.getDevice();
      bleDevice.getName(); //获取设备名称
      bleDevice.getAddress(); //获取设备mac地址
      result.getScanRecord().getBytes(); //获取广播数据和响应数据
      result.getRssi(); //获取无线信号
    }

    @Override
    public void onBatchScanResults(List<ScanResult> results) {
      super.onBatchScanResults(results);
    }

    @Override
    public void onScanFailed(int errorCode) {
      super.onScanFailed(errorCode);
    }
  };

如果扫描成功,可以获取到BluetoothDevice,里面包含了设备mac地址和名称等信息,可以通过这些信息判断是否是目标蓝牙设备。
rssi是信号强度,如果身边刚好有多个相同型号的蓝牙设备,就通过rssi来判断需要连接哪个。一般设备离得越近信号越强。

5.0以下的扫描回调类似,就不介绍了

//扫描回调 < 5.0
  BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {
    @Override
    public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
      
    }
  };

连接
扫描到设备只是找到了该设备,如果要进行数据交互,还要和它进行连接

//连接
  private void connect() {
    BluetoothGatt bluetoothGatt = bleDevice.connectGatt(this, false, gattCallback);
  }

  BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status,
                                        int newState) {
      if (newState == BluetoothProfile.STATE_CONNECTED) {
        bluetoothGatt.discoverServices(); //连接成功 去发现服务
      } else if (newState == BluetoothGatt.STATE_DISCONNECTED) {
        //连接失败
      }

      super.onConnectionStateChange(gatt, status, newState);
    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
      if (status == BluetoothGatt.GATT_SUCCESS) {
        List<BluetoothGattService> services = gatt.getServices();
        for (BluetoothGattService service : services) {
          if (service.getUuid() == UUID.fromString("0000181d-0000-1000-8000-00805f9b34fb")) {
            BluetoothGattCharacteristic c = service.getCharacteristic(UUID.fromString("00002a9d-0000-1000-8000-00805f9b34fb"));

            bluetoothGatt.readCharacteristic(c);

            c.setValue(new byte[]{(byte) 0x28}); //写入byte数据
            bluetoothGatt.writeCharacteristic(c);
          }
        }
      }

      super.onServicesDiscovered(gatt, status);
    }

    @Override
    public void onCharacteristicRead(BluetoothGatt gatt,
                                     BluetoothGattCharacteristic characteristic,
                                     int status) {
      byte[] value = characteristic.getValue(); //读数据
      super.onCharacteristicRead(gatt, characteristic, status);
    }

    @Override
    public void onCharacteristicWrite(BluetoothGatt gatt,
                                      BluetoothGattCharacteristic
                                          characteristic,
                                      int status) {
      super.onCharacteristicWrite(gatt, characteristic, status);
    }

    @Override
    public void onCharacteristicChanged(BluetoothGatt gatt,
                                        BluetoothGattCharacteristic
                                            characteristic) {
      super.onCharacteristicChanged(gatt, characteristic);
    }

    @Override
    public void onDescriptorRead(BluetoothGatt gatt,
                                 BluetoothGattDescriptor descriptor,
                                 int status) {
      super.onDescriptorRead(gatt, descriptor, status);
    }

    @Override
    public void onDescriptorWrite(BluetoothGatt gatt,
                                  BluetoothGattDescriptor descriptor,
                                  int status) {
      super.onDescriptorWrite(gatt, descriptor, status);
    }
  };

调用BluetoothDevice的connectGatt方法进行连接,gattCallback是连接的回调函数,该方法会返回一个BluetoothGatt对象,BluetoothGatt可以用来连接设备、发现服务,并将结果返回给BluetoothGattCallback。

BluetoothGattCallback有很多回调方法,来看一下重要的几个:
首先是onConnectionStateChange,这里可以获取到连接成功还是失败了,如果连接成功,就可以调用BluetoothGatt的discoverServices()方法去寻找Service。这里提到了一个比较重要的概念Service,我们先来了解一下GATT的大致结构:

GATT全称Generic Attribute Profile。一个Profile中包含多个Service,每个Service对应一个UUID。Service是什么呢,举个例子,一个蓝牙体重秤,就可能包括电量Service、体重测量数据Service、设备时间Service等。我们可以通过UUID去找到对应的Service。UUID硬件工程师会给,一般规则都是遵循蓝牙官网的协议:
https://www.bluetooth.com/specifications/gatt/services

每个Service里,同样包含多个特征Characteristic,Characteristic可以看成是一个数据,例如体重测量数据的Service中,包含了多个表示体重数据的Characteristic。类似的,每个Characteristic也对应一个UUID,通过UUID来找到想要的Characteristic。上面的回调里,onCharacteristicWrite和onCharacteristicRead就是对Characteristic的读写。

每个Characteristic中,包含了一个value和多个Descriptor,value就是具体的数值,Descriptor是对这个数值的描述,同样是通过UUID找到对应的Descriptor。上面的回调里,onDescriptorWrite和onDescriptorRead就是对Descriptor的读写。

了解了GATT的大致结构,再回到BluetoothGattCallback回调方法,我们调用bluetoothGatt.discoverServices()去寻找服务,寻找的结果回调到onServicesDiscovered方法中。如果寻找成功,我们可以得到一个BluetoothGattService的列表,然后就可以通过UUID去找到我们想要的BluetoothGattService和BluetoothGattCharacteristic。

然后我们就可以调用BluetoothGatt的readCharacteristic和writeCharacteristic方法读写数据,读写的结果回调在onCharacteristicRead和onCharacteristicWrite方法中。

数据读写
经过前面的几个步骤,我们已经可以从蓝牙设备中读取或者写入数据了,那读写的规则是什么呢?怎么去解析它呢?
硬件工程师一般会给出读写的规则,当然,大多数情况下都是遵循蓝牙官网的协议,例如读取一个温度Characteristic:
https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.temperature_measurement.xml&u=org.bluetooth.characteristic.temperature_measurement.xml

第一个字节是flag标识符,第0位是单位的flag,0表示摄氏度,1表示华氏度;第1位和第2位分别表示时间戳和温度类型是否出现在value中。3-7位留着给硬件工程师自定义一些内容。例如我们读取到的数据的前8个字节是00000000,那我们就知道这是一个摄氏度的数据,并且没有时间戳和温度类型,那么我们接下来只需要再向后读32位,这32位就表示了一个摄氏度的温度数值。

以上就是Android蓝牙BLE的扫描、连接、读写数据的大致流程。其实Android蓝牙的坑还是比较多的,如果要深入学习,这些坑还是得一步一步踩过来~
蓝牙官网链接:https://www.bluetooth.com/

相关文章

网友评论

    本文标题:Android蓝牙BLE

    本文链接:https://www.haomeiwen.com/subject/eertnxtx.html