android Ble开发的那些事(二)

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,代码一定最少嘿嘿。还有就是数据分包那部分,如果感兴趣的可以留言给我,我看是否需要分享。谢谢观看

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容

  • 安卓4.3(API 18)为BLE的核心功能提供平台支持和API,App可以利用它来发现设备、查询服务和读写特性。...
    风雨byt阅读 13,847评论 3 43
  • 前言: 本文主要描述Android BLE的一些基础知识及相关操作流程,不牵扯具体的业务实现,其中提供了针对广播包...
    幻影宇寰阅读 5,216评论 6 19
  • Key Terms And Concepts 关键术语和概念 Here is a summary of key B...
    Jaesoon阅读 2,394评论 0 5
  • 时光若水,无言即大美。日子如莲,平凡即至雅。
    寒峰云阅读 212评论 0 1
  • 晚餐:一个桃李子,一个鸡蛋大土豆。 早上跳操半小时,晚上跳操1小时 锻炼前71.2kg,锻炼后70.7kg 今天成...
    影子3623253阅读 98评论 0 1