android Ble开发的那些事(二)

作者: Young_cyy | 来源:发表于2016-08-10 16:50 被阅读9345次

android Ble开发的那些事(一)
android Ble开发的那些事(二)
android Ble开发的那些事(三)--Ble数据分包处理
android Ble开发的那些事(四)—— OTA升级
前一篇文章说到要贴自己的相关代码,这篇开始会结合代码一起和大家一起分享。要开始讲数据的传输了,先讲讲GATT吧。

什么是GATT?

GATT的全名是Generic Attribute Profile(暂且翻译成:普通属性协议),它定义两个BLE设备通过叫做ServiceCharacteristic的东西进行通信。GATT就是使用了ATT(Attribute Protocol)协议,ATT协议把Service、 Characteristic遗迹对应的数据保存在一个查找表中,次查找表使用16 bit ID作为每一项的索引。一旦两个设备建立起了连接,GATT就开始起作用了,这也意味着,你必需完成前面的GAP协议。这里需要说明的是,GATT连接,必需先经过GAP协议。实际上,我们在Android开发中,可以直接使用设备的MAC地址发起连接,可以不经过扫描的步骤。这并不意味不需要经过GAP,实际上在芯片级别已经给你做好了,蓝牙芯片发起连接,总是先扫描设备,扫描到了才会发起连接。

GATT 连接需要特别注意的是:GATT连接是独占的。也就是一个 BLE 外设同时只能被一个中心设备连接。一旦外设被连接,它就会马上停止广播,这样它就对其他设备不可见了。当设备断开,它又开始广播。中心设备和外设需要双向通信的话,唯一的方式就是建立GATT连接。

GATT(Generic Attribute Profile)

由上图可以看出:

  • 一个低功耗蓝牙(ble)可以包括多个Profile
  • 一个Profile中有多个Service(通过uuid就可以找到对应的Service)
  • 一个Service中有多个Characteristic(通过uuid就可以找到对应的Characteristic)
  • 一个Characteristic中包括一个value和多个Descriptor(通过uuid就可以找到对应的Descriptor)

如何开发Ble?

在整个Ble开发中,我有使用别人比较优秀的第三方库辅助开发,推荐这个库:https://github.com/litesuits/android-lite-bluetoothLE , 开发起来真的很方便,使用也比较简单。

1. 准备工作

(1) 声明权限

<!-- 应用使用蓝牙的权限 -->
<uses-permission android:name="android.permission.BLUETOOTH" />
<!-- 扫描蓝牙设备或者操作蓝牙设置 -->
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

(2) 添加lite-ble-0.9.2.jar库到工程中
这步应该不用讲解怎么添加了吧。

(3) 检测蓝牙是否打开并且创建蓝牙操作的对象

private LiteBluetooth liteBluetooth;

 // 检查当前手机是否支持ble 蓝牙,如果不支持退出程序
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, "ble_not_supported", Toast.LENGTH_SHORT).show();
}        
// 初始化 Bluetooth adapter, 通过蓝牙管理器得到一个参考蓝牙适配器(API必须在以上android4.3或以上和版本)        
// 1.获取bluetoothAdapter        
final BluetoothManager bluetoothManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);        
mBluetoothAdapter = bluetoothManager.getAdapter();        
// 2.检查设备上是否支持并开启蓝牙        
if (mBluetoothAdapter == null) {
            Toast.makeText(this, "ble_not_supported", Toast.LENGTH_SHORT).show();
return;   
}        
//创建liteBluetooth的单例对象,(BleUtil是自己写的类,实现单例的)
if (liteBluetooth == null)            
   liteBluetooth = BleUtil.getInstance(getApplicationContext());        
// 为了确保设备上蓝牙能使用, 如果当前蓝牙设备没启用,弹出对话框向用户要求授予权限来启用
//liteBluetooth.enableBluetoothIfDisabled(activity,REQUEST_ENABLE_BT);

2. 搜索设备

private void scanDevicesPeriod() {
    //liteBluetooth = new LiteBluetooth(getBaseContext());
    liteBluetooth.startLeScan(new PeriodScanCallback(SCAN_PERIOD) {
        @Override
        public void onScanTimeout() {
            //超过搜索时间后的相关操作
        }
        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
            //搜到的设备
            if (Math.abs(rssi) <= 90 ){//过滤掉信号强度小于-90的设备
                Log.i("test scan", "device: " + device.getName() + "  mac: "+ device.getAddress()
                  + "  rssi: " + rssi + "  scanRecord: " + DeviceBytes.byte2hex(scanRecord));
            }
        }
    });
}
  • SCAN_PERIOD:搜索的时长,毫秒数
  • ble的mac地址:通过device.getAddress()就可以得到了
  • scanRecord:Ble广播的数据(DeviceBytes是自己写的工具类,有空分享出来)
    这就搜索到设备啦,而且还打印出来了,是不是so easy啊~

3. 连接设备(首次连接)

一旦获取到GATT的Services,就可以读写他们的属性了

private void  connect(final BluetoothDevice device){
    liteBluetooth.connect(device, false, new LiteBleGattCallback() {
        @Override
        public void onConnectSuccess(BluetoothGatt bluetoothGatt, int i) {
            bluetoothGatt.discoverServices();
            //连接成功后,还需要发现服务成功后才能进行相关操作
        }
        @Override
        public void onServicesDiscovered(BluetoothGatt bluetoothGatt, int i) {
            BluetoothUtil.printServices(bluetoothGatt);//把服务打印出来
            //服务发现成功后,我们就可以进行数据相关的操作了,比如写入数据、开启notify等等
        }
        @Override
        public void onConnectFailure(BleException e) {
            bleExceptionHandler.handleException(e);
        }
        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            //开启notify之后,我们就可以在这里接收数据了。
            //处理数据也是需要注意的,在我们项目中需要进行类似分包的操作,感兴趣的我以后分享
            Log.i("notify", "onCharacteristicChanged: "+ DeviceBytes.byte2hex(characteristic.getValue()));
            super.onCharacteristicChanged(gatt, characteristic);
        }
        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            //当我们对ble设备写入相关数据成功后,这里也会被调用
            Log.i("test", "onCharacteristicWrite: "+ DeviceBytes.byte2hex(characteristic.getValue()));
            super.onCharacteristicWrite(gatt, characteristic, status);
        }
    });
}

4. 连接设备(二次重连)

实现二次重连也挺简单的,在第一次连接成功的会掉函数中,我们把设备的mac地址保存下来,二次重连的时候直接把mac地址传进去就好了。

private void scanAndConnect(final String mac) {
    liteBluetooth.scanAndConnect(mac, false, new LiteBleGattCallback() {//默认搜20s
        @Override
        public void onConnectSuccess(BluetoothGatt bluetoothGatt, int i) {
            bluetoothGatt.discoverServices();
            //连接成功后,还需要发现服务成功后才能进行相关操作
        }
        @Override
        public void onServicesDiscovered(BluetoothGatt bluetoothGatt, int i) {
            BluetoothUtil.printServices(bluetoothGatt);//把服务打印出来
            //服务发现成功后,我们就可以进行数据相关的操作了,比如写入数据、开启notify等等
        }
        @Override
        public void onConnectFailure(BleException e) {
            bleExceptionHandler.handleException(e);
        }
        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            //开启notify之后,我们就可以在这里接收数据了。
            //处理数据也是需要注意的,在我们项目中需要进行类似分包的操作,感兴趣的我以后分享
            Log.i("notify", "onCharacteristicChanged: "+ DeviceBytes.byte2hex(characteristic.getValue()));
            super.onCharacteristicChanged(gatt, characteristic);
        }
        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            //当我们对ble设备写入相关数据成功后,这里也会被调用
            Log.i("test", "onCharacteristicWrite: "+ DeviceBytes.byte2hex(characteristic.getValue()));
            super.onCharacteristicWrite(gatt, characteristic, status);
        }
    });
}

5. 开启notify接收数据

如果设备主动给手机发信息,则可以通过notification的方式,这种方式不用手机去轮询地读设备上的数据。手机可以用如下方式给设备设置notification功能。如果notificaiton方式对于某个Characteristic是enable的,那么当设备上的这个Characteristic改变时,手机上的[onCharacteristicChanged()](http://developer.android.com/reference/android/bluetooth/BluetoothGattCallback.html#onCharacteristicChanged(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic))回调就会被促发。

我尝试调用那个库的方法来开启notify,但始终没有成功,所以索性自己写了。原理不难,也是一步步的通过uuid找到服务、在服务中通过uuid找Characteristic、再通过uuid找到Descriptor。有没有觉得很熟悉?就是文章一开始放的那张图!嘿嘿是不是就理解了

//uuid需要替换成项目中使用的uuid,这只是举个例子
private static final String serviceid = "0000fee7-0000-1000-8000-00805f9b34fb";
private static final String charaid   = "0000feaa-0000-1000-8000-00805f9b34fb";
private static final String notifyid  = "00001202-0000-1000-8000-00805f9b34fb";
private void enableNotificationOfCharacteristic(final boolean enable) {
    UUID ServiceUUID = UUID.fromString(serviceid);
    UUID CharaUUID = UUID.fromString(charaid);
    if(!mBluetoothGatt.equals(null)){
        BluetoothGattService service = mBluetoothGatt.getService(ServiceUUID);
        if(service != null){
            BluetoothGattCharacteristic chara= service.getCharacteristic(CharaUUID);
            if(chara != null){
                boolean success = mBluetoothGatt.setCharacteristicNotification(chara,enable);
                Log.i("success", "setCharactNotify: "+success);
                BluetoothGattDescriptor descriptor = chara.getDescriptor(UUID.fromString(notifyid));
                if (descriptor != null){
                    if (enable) {
                        descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
                    } else {
                        descriptor.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
                    }
                    SystemClock.sleep(200);
                    mBluetoothGatt.writeDescriptor(descriptor);
                }
            }
        }
    }
}

6. 写入数据

    private void writeDataToCharacteristic(byte[] value) {
        if (liteBluetooth.isServiceDiscoered()){
            LiteBleConnector connector = liteBluetooth.newBleConnector();
            connector.withUUIDString(serviceid, get_write_charaid, null)
                    .writeCharacteristic(connector.getCharacteristic(), value, new BleCharactCallback() {
                        @Override
                        public void onSuccess(BluetoothGattCharacteristic characteristic) {
//                        BleLog.i(TAG, "Write Success, DATA: " + DeviceBytes.byte2hex(characteristic.getValue()));
                        }
                        @Override
                        public void onFailure(BleException exception) {
                            BleLog.i(TAG, "Write failure: " + exception);
                            bleExceptionHandler.handleException(exception);
                        }
                    });
        }else {
            return;
        }
    }

7. 关闭连接

if (liteBluetooth.isConnectingOrConnected()) {
        liteBluetooth.closeBluetoothGatt();
}

在蓝牙的数据收发过程中,几乎都是用byte[]数组来进行的,那么我们调试保存的数据难免会为数据格式的转换而各种百度,下面和大家分享下我项目中用到的一些方法~

数据格式转化的工具类

1. 两个byte -->int

private  int byteToInt(byte b, byte c) {//计算总包长,两个字节表示的
    short s = 0;
    int ret;
    short s0 = (short) (c & 0xff);// 最低位
    short s1 = (short) (b & 0xff);
    s1 <<= 8;
    s = (short) (s0 | s1);
    ret = s;
    return ret;
}

2. int -->两个byte

private byte[] int2byte(int res) {
    byte[] targets = new byte[2];
    targets[1] = (byte) (res & 0xff);// 最低位
    targets[0] = (byte) ((res >> 8) & 0xff);// 次低位
    return targets;
}

3. 16进制字符串 -->byte[ ]

public static byte[] hexStringToByte(String hex) {
    int len = (hex.length() / 2);
    byte[] result = new byte[len];
    char[] achar = hex.toCharArray();
    for (int i = 0; i < len; i++) {
        int pos = i * 2;
        result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
    }
    return result;
}
private static byte toByte(char c) {
    byte b = (byte) "0123456789ABCDEF".indexOf(c);
    return b;
}

4. byte[ ] -->16进制字符串

 public static String byte2hex(byte [] buffer){
        String h = "";
        for(int i = 0; i < buffer.length; i++){
            String temp = Integer.toHexString(buffer[i] & 0xFF);
            if(temp.length() == 1){
                temp = "0" + temp;
            }
            h = h + temp;
        }
        return h;
  }

Ble基本的操作几乎都列出来了,下篇和大家分享低耗蓝牙空中升级,网上的demo都太庞大了,下次分享我实现的demo,代码一定最少嘿嘿。还有就是数据分包那部分,如果感兴趣的可以留言给我,我看是否需要分享。谢谢观看

原创作品,如需转载,请与作者联系,否则将追究法律责任。

相关文章

网友评论

  • NN又回来了:为什么感觉写的好简单的,自己实现起来好难的
  • KyrieIrvin_8268:楼主可以发个demo来参考学习下么:smile:
  • b4ac4d3184ef:源码呢?刚学蓝牙就要接触固件升级好心塞
  • jackzhoud:问个问题,注册监听某个Characteristic时,这句代码中
    BluetoothGattDescriptor descriptor = chara.getDescriptor(UUID.fromString(notifyid));
    notifyid是什么?怎么确定它的值呢
  • 64cfe164bc61:加密连接怎么做
  • shengshengboom:问个问题哈,就是gatt.close()了还返回133连接失败的状态,怎么解决好呢
  • e1d0b15c7704:楼主你好,我获取到所有的BluetoothGattDescriptor都为空,无法setValue进去,不知道楼主可知道为什么?
  • 墨白1629:可是实现多连接吗
    墨白1629:@Young_cyy 好吧 我现在在做多连接,数据不同步,丢包,还会断断续续,心好累
    Young_cyy:@小江yue 这个我没有实现哦~ 可能需要看看其他方案
  • 57d0418d8a31:你好,能加一下我的QQ吗,我有一些问题想请教一下,QQ 1220385582
  • 鸩羽千夜92:lz,请问一下,链接很慢,而且很容易断开,这个一般是什么原因
  • beb2cef84e25:写的很详细,刚接手蓝牙项目,头晕
  • hiyoung:博主,ble有random address ,当外围设备的地址是随机地址时,你的二次重连就不管用了..
  • e1db934a9946:话说你的源码怎么还没看到啊,是不是被你吃啊:sweat:
    Young_cyy:@xiongyingjun 你这素质 呵呵:+1::+1:棒!祝你工作顺利
    e1db934a9946:@Young_cyy 好像你没有胜过手一样 fuck you
    Young_cyy:@xiongyingjun 该给的类和代码都给出了 伸手族我也没办法:sunglasses:
  • d3d9d27fd4b4:方便加微信或者qq吗?想请教些ble的简单问题。。。。
    d3d9d27fd4b4:@Young_cyy 406408900 微信qq都是:smile:
    Young_cyy:@一个善良的Man 我加你吧
  • d2a40bfac3b9:楼主,我想问一下,如果Android作为外围设备,那么我定义Service的时候,那个uuid是怎么确定的,是有固定的可以使用的UUID吗?还是什么
    Young_cyy:@想做英雄的一只猪 不是特别了解哦 我可以帮你问问我们硬件
  • scofieldwenwen:楼主,你好!请教一下:怎么通过 service uuid 扫描出特定的设备呢?
    scofieldwenwen:@Young_cyy 请问一下,ble本来是连接状态,超出范围后断开了连接,再回到连接范围内,部分手机出现连接不上,也扫描不出的情况.这个怎么解决呢?
    scofieldwenwen:@Young_cyy 问题已经解决了 public boolean startLeScan(final UUID[] serviceUuids, final LeScanCallback callback) 用这个方法可以实现过滤扫描
    Young_cyy:@scofieldwenwen service uuid?不是一般都通过Mac地址嘛?
  • Vane_Subin:看到你的notifyid并不是通用的UUID,通用的通知BluetoothGattDescriptor的UUID是“00002902-0000-1000-8000-00805f9b34fb”。估计你用那个库也是写死了的,所以导致你开启notify没用
    Young_cyy:@Vane9 :heart_eyes::heart_eyes:谢谢提点 我有空看看 有可能 谢谢!
  • 大呆鼠:楼主有遇到过android4.0可以连接,高版本的5.0之类连接不成功这种情况吗?
    Young_cyy:@大呆鼠 高版本好像要注意权限的问题,你可以看看
  • 772908402265:看完你写的了 有图很形象 果断关注
    Young_cyy:@fly940912 谢谢:stuck_out_tongue_winking_eye::stuck_out_tongue_winking_eye:
  • 杨卢阳:创建LiteBluetooth对象后面那一句不应该注释掉。
    我看了看Github上作者的例子,他是这么写的
    activity = this;
    liteBluetooth.enableBluetooth(activity,1);
    Young_cyy:@杨卢阳 嗯嗯 这段代码我写在服务里面的,在activity中有写的
  • 到了我的周末:怎么大部分呢的开发BLE都是用的eclipse啊。android studio开发BLE的比较少啊。
    Young_cyy:@到了我的周末 感觉都一样吧?就开发工具不同而已吧……
  • scofieldwenwen:楼主,请问一下:ble扫描之后只获取到mac地址,而没有设备name,有什么办法获取到设备name吗?我用扫描所有蓝牙设备(非ble扫描),可以扫出name,但是扫描只能使用其中一种方式.
    scofieldwenwen:@Young_cyy mac一定能获取到,但是name不能每次确保得到,扫描时间是10秒,不确定是不是跟扫描时间有关系
    Young_cyy:@scofieldwenwen :scream::scream:可以有名字的吧?device有getName方法吧?
    0282da8776d7:@scofieldwenwen 那就说明你的设备不支持ble
  • 尘尘尘尘尘:写数据的时候,会在回调里面成功的位置打印好多次我发送的数据,这个是正常的么?
    AiFocus:方便留个联系方式吗 或者建个QQ群,便于大家交流,感觉在这留言的大多都是做蓝牙这一块的
    Young_cyy:@尘往风中吹 感觉不太正常 你可以优化下
  • 混混_X:楼主你好,请教个问题:我调用startlescan之后,onLeScan回调方法只会调用4分钟,4分钟之后就收不到广播数据了。问下你知道这个时间是否可以设置吗?
    Young_cyy:@混混_X 可以设置的
  • lovedabaozi:请问怎么获取设备的serviceuuid 和 writeUUID 有没有方法不用联系硬件厂商可以获得
    lovedabaozi:请问写操作的时候用到的uuid怎么获取
    Young_cyy:@记忆深处里 你手机安装这个light blue app, 连上去应该可以看到相关uuid了 (我用ios下载的,android具体不知道在哪里下,你可以搜下)如果帮到你给我点个赞哟 :stuck_out_tongue_closed_eyes:
  • CrazyLeaf:android ble 坑的不要不要的
    Young_cyy:@Laputa_Zeej :joy: 习惯就好,有机会大家一起分享啊
  • 郭子语:好的,关注你了,我的新项目可能就是ble的,希望以后多多交流
    Young_cyy:@AlphaBing :smile: 嗯呢
  • 7fb3847d8cc1:等的好辛苦,咋没有了呢?
    7fb3847d8cc1:@Young_cyy 能有demo配合着就好了
    Young_cyy:@我爱君君 最近在赶新需求 你想哪部分:stuck_out_tongue_winking_eye:打算写升级或者数据分包处理
  • 桃园小七:感谢分享 比好多入门级的demo blog强很多 呃 这一篇就是错别字多了点 :joy:
    Young_cyy:@桃园小七 :joy: 上班空闲时间写的~有空我改改 哈哈 刚开始写这些,文笔也不太好,辛苦你们看我这么烂的文笔了 :stuck_out_tongue:
  • 萌萌细语:文章写得棒棒哒,但是,小白还是没明白UUID怎样获取,前辈,能讲一下吗
    Young_cyy:@萌萌细语 uuid的话,一般你可以问问硬件那边,都是硬件那边定的
  • 皮球二二:Android的ble太坑爹了,坑太尼玛多了
    酷玩技术派::mask: + 1 快坑哭了
    Hardy小叶: @r17171709 坑太多了 各种连接不稳定
    Young_cyy:@r17171709 :sob: 是的 太多坑了 适配起来更痛苦
  • 024a6bba9544:数据格式转化java已经提供方法了, 例如: ByteOrder 是大小端模式选择
    public static int bytes2Int(byte[] src,ByteOrder byteOrder){
    ByteBuffer buffer = ByteBuffer.wrap(src);
    buffer.order(byteOrder);
    return buffer.getInt();
    }
    Young_cyy:@魂魄 :yum: 嗯啊 谢谢提醒哈~
  • 024a6bba9544:分享个Rx_BLE库 韩国人写的:
    https://github.com/kam6512/RxBleGattManager
    Young_cyy:@魂魄 有空我看看 :grin: 谢谢啦
  • 7fb3847d8cc1:期待下一篇
    Young_cyy:@我爱君君 嗯啊 ~谢谢捧场 :stuck_out_tongue:
  • 7fb3847d8cc1:很棒,今天下午刚看到liteble,晚上就在这里看到了你的文章。多谢分享,赞
    Young_cyy:@我爱君君 :stuck_out_tongue_winking_eye: 喜欢就点喜欢哇 嘿嘿
  • 024a6bba9544:问你个问题ENABLE_INDICATION_VALUE和ENABLE_NOTIFICATION_VALUE数据交互方式有啥区别了
    Young_cyy:@魂魄 目前我只接触到了notify,开启后就不用轮训,直接发送数据出来。indication的话,在网上看到,好像是从机通知主机后,主机需要调用simpleprofile_writeattrcb,读取从机的数据。
  • 024a6bba9544:期待数据分包
    Young_cyy:@魂魄 :blush: 嗯嗯

本文标题:android Ble开发的那些事(二)

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