Android蓝牙使用(二)

转载自:

https://blog.csdn.net/duo_shine/article/details/70259928

蓝牙使用(一)http://blog.csdn.net/duo_shine/article/details/70257113 
蓝牙固件升级:http://blog.csdn.net/duo_shine/article/details 
封装的一个BleDemo:非常简单几行代码即可调用,如何使用在github写的也很详细:https://github.com/duoshine/BlueToothConnect-master

能get到的:

认识蓝牙
了解蓝牙4.0
如何开启蓝牙
如何扫描周边蓝牙设备
如何连接蓝牙设备
手机端如何与ble终端通信
五,如何连接蓝牙设备 
上一篇我们已经拿到了蓝牙设备列表,接下来就是连接ble终端了 
首先停止扫描

mBluetoothAdapter.stopLeScan(mLeScanCallback);
1
然后释放建立连接请求,进行下一个设备连接请求

public void disconnect() {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        mBluetoothGatt.disconnect();
    }

连接address就是ble终端的mac地址

BluetoothDevice device=mBluetoothAdapter.getRemoteDevice(address);
//直接连接到设备传入false
mBluetoothGatt = device.connectGatt(mContext, false, mGattCallback);

mGattCallback是已经连接上设备,对设备的某些操作后返回的结果。返回中央的状态和周边提供的数据,这个抽象类就9个方法, 
根据你需求实现吧

private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status,
                int newState) {
        //与ble终端连接状态发生变化时
        //STATE_DISCONNECTED 断开
        //STATE_CONNECTING 连接中
        //STATE_CONNECTED 连接
        //STATE_DISCONNECTING 断开中
        //连接成功
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                 //        搜索连接设备所支持的service  需要连接上才可以
        gatt.discoverServices();
            //断开连接
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {

            }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        //搜索服务
          findService(gatt.getServices());
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt,
                BluetoothGattCharacteristic characteristic, int status) {
           // 从蓝牙设备读取信息
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt,
                BluetoothGattCharacteristic characteristic) {
    //发送指令成功后   

        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status)
        {
            super.onCharacteristicWrite(gatt, characteristic, status);
    //写入成功
        }
    };

到这里可以连接ble终端成功了,在这个onConnectionStateChange方法中根据状态判断是否连接,断开的信息,接下来就是通信了 
接下来你需要和硬件工程师配合好,不管你做的是什么ble终端设备,他必定有相关协议,先了解一下UUID,UUID是ble终端service,characteristic,descriptor的唯一标识, 
上面的搜索服务方法,需要用到UUID

public void findService(List<BluetoothGattService> paramList) {
        Iterator localIterator1 = paramList.iterator();
        while (localIterator1.hasNext()) {
            BluetoothGattService localBluetoothGattService = (BluetoothGattService) localIterator1
                    .next();
            //根据唯一标识uuid去找到我们需要用到的那个service  service uuid
            if (localBluetoothGattService.getUuid().toString()
                    .equalsIgnoreCase(ConstantUtils.UUID_SERVER)) {
                //拿到该服务中的所有Characteristics
                List localList = localBluetoothGattService.getCharacteristics();
                Iterator localIterator2 = localList.iterator();
                while (localIterator2.hasNext()) {
                    BluetoothGattCharacteristic localBluetoothGattCharacteristic = (BluetoothGattCharacteristic) localIterator2
                            .next();
                    //根据uuid拿到我们需要用到的Characteristics  通知 uuid
                    if (localBluetoothGattCharacteristic.getUuid().toString()
                            .equalsIgnoreCase(ConstantUtils.UUID_NOTIFY)) {
                        bleGattCharacteristic = localBluetoothGattCharacteristic;
                        break;
                    }
                }
                break;
            }
        }
        //  设置为true启用该通知对象
        mBluetoothGatt.setCharacteristicNotification(bleGattCharacteristic, true);
    }

上面用到了两个uuid 分别是service的和notification的,还有一个write的,这个不固定,可能你的协议上只有两个uuid,通知和写用的是同一个uuid 
接下来就是发送指令给ble终端了,一般协议规定都是发送byte[],数据格式要严格按照协议规定来写,比如加密/解密,效验,分包,长度等等

六,发送指令至ble终端

public boolean write(byte byteArray[]) {
        if (mBluetoothGatt == null) {
            return false;
        }
        BluetoothGattCharacteristic writeCharacteristic = getCharcteristic(ConstantUtils.UUID_SERVER, ConstantUtils
                .UUID_WRITE);  //这里用到了写的uuid 
        if (writeCharacteristic == null) {

            return false;
        }
        writeCharacteristic.setValue(byteArray);
        return mBluetoothGatt.writeCharacteristic(writeCharacteristic);
    }

private BluetoothGattCharacteristic getCharcteristic(String serviceUUID, String characteristicUUID) {
        //得到服务对象
        BluetoothGattService service = getService(UUID.fromString(serviceUUID));  //调用上面获取服务的方法
        if (service == null) {
            return null;
        }
        //得到此服务结点下Characteristic对象
        final BluetoothGattCharacteristic gattCharacteristic = service.getCharacteristic(UUID.fromString
                (characteristicUUID));
        if (gattCharacteristic != null) {
            return gattCharacteristic;
        } else {

            return null;
        }
    }

//根据uuid拿到
  public BluetoothGattService getService(UUID uuid) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            return null;
        }
        return mBluetoothGatt.getService(uuid);
    }

看下getService的源码

    public BluetoothGattService getService(UUID uuid) {
        for (BluetoothGattService service : mServices) {
            if (service.getDevice().equals(mDevice) &&
                service.getUuid().equals(uuid)) {
                return service;
            }
        }

        return null;
    }

遍历了这个mServices集合如果service的uuid相同就返回这个BluetoothGattService ,同样的看下getCharacteristic的源码, 根据写的uuid拿到BluetoothGattCharacteristic ,ok现在就可以使用BluetoothGattCharacteristic 发送指令至ble终端了

public BluetoothGattCharacteristic getCharacteristic(UUID uuid) {
        for(BluetoothGattCharacteristic characteristic : mCharacteristics) {
            if (uuid.equals(characteristic.getUuid()))
                return characteristic;
        }
        return null;
    }

到这里发送指令成功write返回true,否则取反,如果失败了的话,可能你的uuid使用错误,比如写的uuid用成了读的,发送的数据前面已经提过,根据你的协议来定的,不清楚就多和硬件工程师沟通

接收蓝牙返回的数据 
蓝牙成功收到我们发送的指令后,onCharacteristicChanged该方法会收到蓝牙返回的数据,

 @Override
        public void onCharacteristicChanged(BluetoothGatt gatt,
                                            BluetoothGattCharacteristic characteristic) {                               
            byte[] arrayOfByte = characteristic
                    .getValue();
}

Ok,拿到这个数组该干啥干啥吧,有什么错误希望指出,共同学习

demo:https://github.com/duoshine/BlueToothConnect-master
 

猜你喜欢

转载自blog.csdn.net/parasoft/article/details/84344136