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:有相关疑问及建议,可留言指导交流;

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

推荐阅读更多精彩内容