4

我目前有一种方法可以写入 BLE 设备以发出哔哔声。我的蓝牙回调如下:

public class ReadWriteCharacteristic extends BluetoothGattCallback {
    public ReadWriteCharacteristic(Context context, String macAddress, UUID service, UUID characteristic, Object tag, Activity activity) {
        mMacAddress = macAddress;
        mService = service;
        mCharacteristic = characteristic;
        mTag = tag;
        mContext = context;
        this.activity =activity;
        final BluetoothManager bluetoothManager =
                (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();

    }

    final private static String TAG = "ReadCharacteristic";
    private Object mTag;
    private String mMacAddress;
    private UUID mService;
    private BluetoothManager mBluetoothManager = null;
    private BluetoothAdapter mBtAdapter = null;
    private BluetoothGatt mBluetoothGatt = null;
    private String mBluetoothDeviceAddress ="";
    private UUID mCharacteristic;
    BluetoothDevice device;
    private Activity activity;
    private BluetoothAdapter mBluetoothAdapter;
    private Context mContext;
    ReadWriteCharacteristic rc;

    private int retry = 5;


    public String getMacAddress() {
        return mMacAddress;
    }

    public UUID getService() {
        return mService;
    }

    public UUID getCharacteristic() {
        return mCharacteristic;
    }

    public byte[] getValue() { return mValue; }

    public void onError() {
        Log.w(TAG, "onError");
    }

    public void readCharacteristic(){
        if (retry == 0)
        {
            onError();
            return;
        }
        retry--;


                device = mBluetoothAdapter.getRemoteDevice(getMacAddress());


                mBluetoothManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
                int connectionState = mBluetoothManager.getConnectionState(device,
                        BluetoothProfile.GATT);

                if (device != null) {

                    if (connectionState == BluetoothProfile.STATE_DISCONNECTED)
                    {

                        // Previously connected device. Try to reconnect.
                        if (mBluetoothDeviceAddress != null
                                && getMacAddress().equals(mBluetoothDeviceAddress)
                                && mBluetoothGatt != null) {
                            Log.w(TAG, "Re-use GATT connection");
                            if (mBluetoothGatt.connect()) {
                                Log.w(TAG, "Already connected, discovering services");
                                mBluetoothGatt.discoverServices();
                                //return ;
                            } else {
                                Log.w(TAG, "GATT re-connect failed.");
                                return;
                            }
                        }

                        if (device == null) {
                            Log.w(TAG, "Device not found.  Unable to connect.");
                            return;
                        }
                        Log.w(TAG, "Create a new GATT connection.");
                        rc= ReadWriteCharacteristic.this;
                        Log.w(TAG, "Starting Read [" + getService() + "|" + getCharacteristic() + "]");
                        mBluetoothGatt = device.connectGatt(mContext, false, rc);
                        refreshDeviceCache(mBluetoothGatt);
                        mBluetoothDeviceAddress = getMacAddress();
                    } else {
                        Log.w(TAG, "Attempt to connect in state: " + connectionState);
                        if(mBluetoothGatt!=null)
                            mBluetoothGatt.close();
                        readCharacteristic();
                    }

                }

    }

    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        super.onConnectionStateChange(gatt, status, newState);

        Log.w(TAG,"onConnectionStateChange [" + status + "|" + newState + "]");


        if ((newState == 2)&&(status ==0)) {
            gatt.discoverServices();
        }
        else if(status == 133 )
        {
            //gatt.disconnect();
            gatt.close();
            mBluetoothGatt = null;
            try
            {
                Thread.sleep(2000);
            }
            catch(Exception e)
            {

            }
            readCharacteristic();
        }
        else{

            if(mBluetoothGatt!=null)
                mBluetoothGatt.close();

           // gatt.close();

            Log.w(TAG, "[" + status + "]");
            //gatt.disconnect();

            try
            {
                Thread.sleep(2000);
            }
            catch(Exception e)
            {

            }
            mBluetoothGatt = null;
            readCharacteristic();
        }
    }



    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        Log.w(TAG,"onServicesDiscovered [" + status + "]");
        BluetoothGattService bgs = gatt.getService(getService());
        if (bgs != null) {
            BluetoothGattCharacteristic bgc = bgs.getCharacteristic(getCharacteristic());
            gatt.readCharacteristic(bgc);
        }
    }

    @Override
    public void onCharacteristicWrite(BluetoothGatt gatt,
                                      BluetoothGattCharacteristic characteristic,
                                      int status) {
        Log.w(TAG,"onCharacteristicWrite [" + status + "]");
        if (status == BluetoothGatt.GATT_SUCCESS) {
            Log.w(TAG,"onCharacteristicWrite [" + getDataHex(characteristic.getValue()) + "]");
           // gatt.disconnect();
            if(mBluetoothGatt!=null)
                mBluetoothGatt.close();
          //  gatt.close();
          //  mBluetoothGatt=null;
        }
        else if(status ==133)
        {
            gatt.close();
            try
            {
                Thread.sleep(2000);
            }
            catch(Exception e)
            {

            }

            readCharacteristic();
        }

        else{
            //gatt.disconnect();
            gatt.close();

        }
    }

    @Override
    public void onCharacteristicRead(BluetoothGatt gatt,
                                     BluetoothGattCharacteristic characteristic,
                                     int status) {
        Log.w(TAG,"onCharacteristicRead [" + status + "]");
        if (status == BluetoothGatt.GATT_SUCCESS) {
            mValue = characteristic.getValue();
            // Perform write operations
            gatt.writeCharacteristic(bgc);


        }

        else if(status ==133)
        {
            gatt.close();
            try
            {
                Thread.sleep(2000);
            }
            catch(Exception e)
            {

            }

            readCharacteristic();
        }

        else {
          //  gatt.disconnect();
            gatt.close();
        }
    }

}

此代码在运行 Kitkat 及以下的设备上完美运行。但是在运行 Lollipop 的设备上,此代码在第一个实例中运行良好。但是从下一个实例开始,无论我是断开连接还是关闭连接并重试,它都不起作用。它在 onConnectionStateChange 方法中不断给我一个状态码 257。据我所知,kitkat 和 Lollipop 设备的蓝牙 GATT 方法是相同的。

令我惊讶的是,当我使用旧的 BLE API 即 startLeScan(例如 - mBluetoothAdapter.startLeScan(mLeScanCallback);)时,此代码在 Lollipop 设备上运行良好。仅当我使用新的 BLE API 即 BluetoothLeScanner ( ) 时才会出现此问题 scanner.startScan(filters, settings, new scancallback());。使用旧 BLE API 的 Lollipop 设备的扫描速度非常慢,因此我无法使用它。我只是不明白如何解决这个问题。有没有人遇到同样的问题并找到了解决方案?任何帮助将不胜感激。

4

1 回答 1

4

我会在这里改变很多东西。为要从特征中读取的数据创建一个类变量,例如私有字符串heartRate;

1)您不需要 readCharacteristic() 方法。相反,一旦设备正确连接,在 onConnectionStateChange 中调用 mBluetoothGatt.discoverServices()。然后在 onServicesDiscovered() 方法中,我将调用 gatt.getServices()。然后使用foreach循环,遍历返回的服务,比较服务的UUID,直到找到你关心的那个。然后如果 heartRate == null,调用 service.getCharacteristic(HeartRateUUID) 然后读取特征。在 onCharacteristicRead() 检查 UUID 是否等于心率特征。如果是,则将特征值分配给 heartRate 变量。如果您有兴趣,我可以输入方法或提供伪代码。

2) 我不会调用 gatt.connect(),然后调用 gatt.discoverServices()。gatt.connect() 将在看到来自设备的广告数据包后立即重新连接到当前设备。我会调用 gatt.connect(),然后在 onConnectedStateChange() 方法中调用 gatt.discoverServices()。

3) 在 onConnectedStateChange 方法中不要使用 gatt 变量。请改用 mBluetoothGatt。mBluetoothGatt.disconnect() 与当前连接的设备断开连接。mBluetoothGatt.close() 终止 gatt 实例。调用 mBluetoothGatt.Close() 后不能调用 mBluetoothGatt.connect()。这可能不需要,但如果设备已连接,我会调用 mBluetoothGatt.disconnect(),然后调用 mBluetoothGatt.close()。

4)您还可以将特征读数链接在一起。在onCharacteristicRead()中,得到heartRate的值后,可以立即调用characteristic.getService().getCharacteristic(UUIDTemperature),然后读取那个特征。它将再次调用 OnCharacteristicRead 方法。

如果您想让我澄清任何事情,请告诉我;我在蹩脚的 Surface Pro 3 键盘上打字。:)

于 2015-06-25T01:45:52.500 回答