实战BLE蓝牙之数据收发

BLE蓝牙用途越来越广泛,在开发安卓过程中或多或少接触到蓝牙,网上关于低功耗蓝牙的资料也非常多,今天我就来总结一下低功耗蓝牙的开发技巧,让大家少走弯路,不妥之处请大家斧正!

注意开启定位权限

BLE蓝牙收发demo
串口收发助手

《实战BLE蓝牙之数据收发》 BLE2540硬件和USB接口

《实战BLE蓝牙之数据收发》 demo界面

《实战BLE蓝牙之数据收发》 PC端串口助手
《实战BLE蓝牙之数据收发》 在我的电脑的属性>设备管理器中查看端口号这里是CMD3

  • BLE硬件可以在淘宝上获得,测试的时候一般将蓝牙和USB串口连接,然后打开电脑端的串口助手,串口助手界面上有个打开串口,点击打开就可以收发手机端发过来的数据了,这个软件需要注意的就是连接蓝牙需要一个波特率,一般默认就是9600,波特率也可以通过AT指令修改,然后还要选择一些端口号

  • 打开BLE蓝牙收发demo中有一个app安装到手机中就是收发数据了如上图;

  • 将demo倒进安卓Studio中,demo中大部分是谷歌提供的源码,如果看懂了我上一篇帖子的话再看这一篇就很容易理解;

DeviceScanActivity

这个类主要是扫描蓝牙然后或获取蓝牙的地址:

// 初始化蓝牙适配器。
final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();

通过蓝牙适配器就可以扫描蓝牙了
mBluetoothAdapter.stopLeScan(mLeScanCallback);

//设备扫描回调。类似于普通蓝牙的广播接收扫描结果
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mLeDeviceListAdapter.addDevice(device,rssi,scanRecord);
mLeDeviceListAdapter.notifyDataSetChanged(); //刷新界面
}
});
}
};

可以看到上面回调当中有三个参数其中device为蓝牙设备,这里面包含蓝牙名称和蓝牙地址,rssi可以通过算出模糊的算出蓝牙直接的距离;

BleSppActivity

在这个类中包括启动服务和接收服务发送过来的广播,以及蓝牙的连接和对服务的什么周期管理;

启动服务
startService(new Intent(this, BluetoothLeService.class));

注册广播
registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter()); //注册广播

连接蓝牙
final boolean result = mBluetoothLeService.connect(mDeviceAddress); //连接蓝牙

可以看到连接蓝牙只需要蓝牙的地址就可以,通过调用服务中封装好的连接蓝牙方法就可以连接
蓝牙建立好连接,然后通过UUID的读写通道建立读写的关系就可以在广播处接受分发送数据到服务类中将数据发送或接收;

BluetoothLeService核心类

连接蓝牙
// 第二个参数: 如果为false,则直接立即连接。
// 如果为true,则等待远程设备可用时(在范围内,。。)连接。并不是断开后重新连接。
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
这里mGattCallback是蓝牙的BluetoothGattCallback的回调,这个回调中有几个重要方法,弄懂这几个方法那就弄懂了蓝牙。

  • onConnectionStateChange连接成功之后就会被触发,连接状态改变 蓝牙连接状态改变的回调:在连接成功之后需要调用discoverServices方法来找服务,只有找到了服务才算是真正的连接成功.有两种状态,BluetoothProfile.STATE_CONNECTED代表连接,BluetoothProfile.STATE_DISCONNECTED代表断开连接。

  • onServicesDiscovered

      //设备服务发现
      //在发现了有可支持的服务之后会回调服务中的onServicesDiscovered()函数,
      // 并发送广播,在官方的演示中发现了可用的服务之后,就查找该BLE设备支持的
      // 所有服务和特性,在这里不需要查找所有的服务,只需要向蓝牙写数据和读取数
      // 据的服务和特征的UUID即可。通过查询低功耗蓝牙(BLE)的数据手册可以得到
      // 所需要的UUID。
      // 先通过Service的UUID找到对应的Service对象,再通过我们想要设置监听的
      // Characteristic的UUID找到相应的Characteristic对象,UUID都是蓝牙设备厂
      // 商在文档中提供的.找到相应的特征后调用setCharacteristicNotification方
      // 法开启监听,就可以在该特征状态发生改变后走到onCharacteristicChanged方法中.
      // 而蓝牙的notify功能需要向CCCD中写入值1才能开启,CCCD值为:
      // public static final UUID CCCD = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");`
    
  • onCharacteristicRead //读回调

  • onCharacteristicChanged
    //Characteristic状态改变的回调: 设备端数据变化回调
    // 这个方法挺重要的,蓝牙广播(是指蓝牙设备本身发出的数据)出来的数据在这里获取,发送
    // 指令后蓝牙的回应也是在这里获取.当然要走这个回调必须先设置相关的characteristic的监听.

  • onCharacteristicWrite
    //Characteristic写操作的结果回调:
    //这个监听在分包发送的时候需要用到,在里面判断的发送结果是否成功,成功的话则发送下一条数据,这样可以保证分包发送的顺序不会错误.

  • onReadRemoteRssi//读取蓝牙信号强度,RSSI在扫描时可以通过扫描回调接口获得,但是在连接之后要不断地使用,mBluetoothGatt.readRemoteRssi()向底层驱动发出读取RSSI请求,当底层获取到新的RSSI后会进行以下回调:

在onServicesDiscovered中调用displayGattServices(getSupportedGattServices());会看到蓝牙设备的所有UUID通道

 private void displayGattServices(List<BluetoothGattService> gattServices) {
        if (gattServices == null)
            return;
        for (BluetoothGattService gattService : gattServices) {
            // -----Service的字段信息----//
            int type = gattService.getType();
            Log.d("print", "-->服务的 type:" + Utils.getServiceType(type));
            Log.d("print", "-->包括服务规模 size:" + gattService.getIncludedServices().size());
            Log.d("print","-->服务的 uuid:" + gattService.getUuid());
            // -----Characteristics的字段信息----//
            List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
            for (final BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
                Log.d("print", "---->char uuid:" + gattCharacteristic.getUuid());
                int permission = gattCharacteristic.getPermissions();
                Log.d("print", "---->char permission:" + Utils.getCharPermission(permission));
                int property = gattCharacteristic.getProperties();
                Log.d("print","---->char property:" + Utils.getCharPropertie(property));
                byte[] data = gattCharacteristic.getValue();
                if (data != null && data.length > 0) {
                    Log.d("print", "---->char value:" + new String(data));
                }
                // -----Descriptors的字段信息----//
                List<BluetoothGattDescriptor> gattDescriptors = gattCharacteristic.getDescriptors();
                for (BluetoothGattDescriptor gattDescriptor : gattDescriptors) {
                    Log.d("print", "-------->desc uuid:" + gattDescriptor.getUuid());
                    int descPermission = gattDescriptor.getPermissions();
                    Log.d("print", "-------->desc permission:" + Utils.getDescPermission(descPermission));
                    byte[] desData = gattDescriptor.getValue();
                    if (desData != null && desData.length > 0) {
                        Log.d("print", "-------->desc value:" + new String(desData));
                    }
                }
            }
        }

    }```

![360截图20170704183235745.jpg](http://upload-images.jianshu.io/upload_images/3983667-bc28dc818913e073.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

![![360截图20170704183301031.jpg](http://upload-images.jianshu.io/upload_images/3983667-14dcebfd09400f9e.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
](http://upload-images.jianshu.io/upload_images/3983667-590f83869bf1570d.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)


### 看上面的每一个UUID都有不同的权限,READ,WRUTE,还有一个通知的权限;
### 如果说其中的UUID只有读的权限那么它只能读取了;


# BleSppGattAttributes

    public static String BLE_SPP_Service = "0000fff0-0000-1000-8000-00805f9b34fb";
    public static String BLE_SPP_Notify_Characteristic = "0000fff4-0000-1000-8000-00805f9b34fb";
    public static String  BLE_SPP_Write_Characteristic = "0000fff1-0000-1000-8000-00805f9b34fb";
    public static String  BLE_SPP_AT_Characteristic = "0000fee2-0000-1000-8000-00805f9b34fb";


这个类主要就是填写能够读写的UUID了,每个BLEapp的写法不同但原理都是一样的;通过UUID获取读写的通道,建立起数据收发,在收发的时候每一次只能发送20个字节,当发送100个字节时其实是发送五个次的,感兴趣的可以看看BLE数据包的结构;


在BleSppActivity接收数据的也是20个字节一次的接收,这里是把它放进字符串缓存中,接收和发送数据的格式多种多样有ASCII码 ,十六进制,字符串,甚至还有JSon,只要能读取到数据其他的就没什么问题了;

工作中用到的蓝牙远不止这些,上面的代码也是最基础的,运用到项目中是远远不够的,但上面的代码还是比较健全的,因为是谷歌官方的demo,实际项目中就会有很多奇特的功能了,比如说蓝牙自动连接,保存后台一直存活,直接在后台收发数据等等。。。
    原文作者:枫雪狼情
    原文地址: https://www.jianshu.com/p/260f1a637307
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞