OnCharacteristicRead无法调用(Android平板电脑BLE通讯)

时间:2017-01-23 14:11:04

标签: java android bluetooth-lowenergy

我的应用程序与连接到Arduino Mega的BLE模块(High-flyer)进行通信,连接后我按下一个按钮,向Mega发送一个数组,然后返回4个数字。

问题是我有时会启动应用程序&连接,将数据发送到Mega但无法读取任何内容。我可以看到Mega接收到第一个被发送的数组,并且还传回了4个数字,但是在应用程序端没有任何反应。 这个bug来来去去,有时候一切都很完美,有时它会卡住,当我尝试重新启动应用程序或重新安装它时,除此之外我无法找到任何方法来处理或解决它。

非常感谢任何帮助。

BluetoothLeService.java:

public class BluetoothLeService extends Service {
private final static String TAG = BluetoothLeService.class.getSimpleName();

private BluetoothManager mBluetoothManager;
private BluetoothAdapter mBluetoothAdapter;
private String mBluetoothDeviceAddress;
private BluetoothGatt mBluetoothGatt;
private int mConnectionState = STATE_DISCONNECTED;
public boolean BLEfree = true;

private static final int STATE_DISCONNECTED = 0;
private static final int STATE_CONNECTING = 1;
private static final int STATE_CONNECTED = 2;

public final static String ACTION_GATT_CONNECTED =
        "com.example.bluetooth.le.ACTION_GATT_CONNECTED";
public final static String ACTION_GATT_DISCONNECTED =
        "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
public final static String ACTION_GATT_SERVICES_DISCOVERED =
        "com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";
public final static String ACTION_DATA_AVAILABLE =
        "com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
public final static String EXTRA_DATA =
        "com.example.bluetooth.le.EXTRA_DATA";

public final static UUID UUID_HEART_RATE_MEASUREMENT =
        UUID.fromString(SampleGattAttributes.HEART_RATE_MEASUREMENT);

public static int currentPointer = 0,lastPointer =0;
public static byte[][] receivedArray = new byte[250][2];

// Implements callback methods for GATT events that the app cares about.  For example,
// connection change and services discovered.
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        String intentAction;
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            intentAction = ACTION_GATT_CONNECTED;
            mConnectionState = STATE_CONNECTED;
            broadcastUpdate(intentAction);
            Log.i(TAG, "Connected to GATT server.");
            // Attempts to discover services after successful connection.
            Log.i(TAG, "Attempting to start service discovery:" +
                    mBluetoothGatt.discoverServices());

        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            intentAction = ACTION_GATT_DISCONNECTED;
            mConnectionState = STATE_DISCONNECTED;
            Log.i(TAG, "Disconnected from GATT server.");
            broadcastUpdate(intentAction);
        }
    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
        } else {
            Log.w(TAG, "onServicesDiscovered received: " + status);
        }
    }

    @Override
    public void onCharacteristicRead(BluetoothGatt gatt,
                                     BluetoothGattCharacteristic characteristic,
                                     int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
        }
    }

    @Override
    public void onCharacteristicChanged(BluetoothGatt gatt,
                                        BluetoothGattCharacteristic characteristic) {
        broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
    }
};

private void broadcastUpdate(final String action) {
    final Intent intent = new Intent(action);
    sendBroadcast(intent);
}

private void broadcastUpdate(final String action,
                             final BluetoothGattCharacteristic characteristic) {
    final Intent intent = new Intent(action);

    // This is special handling for the Heart Rate Measurement profile.  Data parsing is
    // carried out as per profile specifications:
    // http://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml
    if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
        int flag = characteristic.getProperties();
        int format = -1;
        if ((flag & 0x01) != 0) {
            format = BluetoothGattCharacteristic.FORMAT_UINT16;
            Log.d(TAG, "Heart rate format UINT16.");
        } else {
            format = BluetoothGattCharacteristic.FORMAT_UINT8;
            Log.d(TAG, "Heart rate format UINT8.");
        }
        final int heartRate = characteristic.getIntValue(format, 1);
        Log.d(TAG, String.format("Received heart rate: %d", heartRate));
        intent.putExtra(EXTRA_DATA, String.valueOf(heartRate));
    } else {
        // For all other profiles, writes the data formatted in HEX.
        final byte[] data = characteristic.getValue();
        //sendFunction(data);
        //Log.d(TAG, "******Received:  " + characteristic.getValue());
        //Log.d(TAG, "    DATA: " + data);


        if (data != null && data.length > 0) {                                  // ******* broadcastUpdate
            final StringBuilder stringBuilder = new StringBuilder(data.length);
            for(byte byteChar : data)
            // stringBuilder.append(String.format("%02X ", byteChar));
            //intent.putExtra(EXTRA_DATA, new String(data) + "\n" + stringBuilder.toString());
            intent.putExtra(EXTRA_DATA, new String(data) + "\n");


            //send(data);

            for(int j=0;j<data.length;j++){
                byteArrayAppand(data[j]);
                //Log.d(TAG,"Data - "+data[j]);
            }
            /*try{
                Thread.sleep(5);
            }catch (InterruptedException e){

            }*/

            //intent.putExtra("dataArray", data);     // Data passing between activities
            //createByteArray(data);

        }
    }
    sendBroadcast(intent);
}

public void byteArrayAppand(byte data){
    receivedArray[lastPointer][0] = data;
    receivedArray[lastPointer][1] = 1;
    //Log.d(TAG,"Byte Array index - " + lastPointer + " With value of - "+receivedArray[lastPointer][0]);
    lastPointer++;
    if(lastPointer==250) {
        lastPointer = 0;
    }


}

public class LocalBinder extends Binder {
    BluetoothLeService getService() {
        return BluetoothLeService.this;
    }
}

@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

@Override
public boolean onUnbind(Intent intent) {
    close();
    return super.onUnbind(intent);
}

private final IBinder mBinder = new LocalBinder();

public boolean initialize() {
    if (mBluetoothManager == null) {
        mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        if (mBluetoothManager == null) {
            Log.e(TAG, "Unable to initialize BluetoothManager.");
            return false;
        }
    }

    mBluetoothAdapter = mBluetoothManager.getAdapter();
    if (mBluetoothAdapter == null) {
        Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
        return false;
    }

    return true;
}

public boolean connect(final String address) {
    if (mBluetoothAdapter == null || address == null) {
        Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
        return false;
    }

    if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)
            && mBluetoothGatt != null) {
        Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
        if (mBluetoothGatt.connect()) {
            mConnectionState = STATE_CONNECTING;
            return true;
        } else {
            return false;
        }
    }

    final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
    if (device == null) {
        Log.w(TAG, "Device not found.  Unable to connect.");
        return false;
    }
    mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
    Log.d(TAG, "Trying to create a new connection.");
    mBluetoothDeviceAddress = address;
    mConnectionState = STATE_CONNECTING;
    return true;
}

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

public void close() {
    if (mBluetoothGatt == null) {
        return;
    }
    mBluetoothGatt.close();
    mBluetoothGatt = null;
}

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

public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
                                          boolean enabled) {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return;
    }
    mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);

    // This is specific to Heart Rate Measurement.
    if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
                UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        mBluetoothGatt.writeDescriptor(descriptor);
    }
}

public List<BluetoothGattService> getSupportedGattServices() {
    if (mBluetoothGatt == null) return null;

    return mBluetoothGatt.getServices();
}

public byte[] readCustomCharacteristic() {
    BLEfree = false;
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return null;
    }

    BluetoothGattService mCustomService = mBluetoothGatt.getService(UUID.fromString("00002b00-0000-1000-8000-00805f9b34fb"));

    if(mCustomService == null){
        Log.w(TAG, "Custom BLE Service not found");
        return null;
    }

    BluetoothGattCharacteristic mReadCharacteristic = mCustomService.getCharacteristic(UUID.fromString("00002b10-0000-1000-8000-00805f9b34fb"));
    UUID uuid = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
    BluetoothGattDescriptor descriptor = mReadCharacteristic.getDescriptor(uuid);
    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
    mBluetoothGatt.writeDescriptor(descriptor);
    //To receive notification in Android is mandatory to set characteristic notification to true
    mBluetoothGatt.setCharacteristicNotification(mReadCharacteristic, true);

  /*get the read characteristic from the service*/
    if(mBluetoothGatt.readCharacteristic(mReadCharacteristic) == false){
        Log.w(TAG, "Failed to read characteristic from read");
    }
    BLEfree = true;
    return mReadCharacteristic.getValue();
}

private void msg(String s)
{
    Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}

public boolean send(byte[] data) {

    BLEfree = false;
    BluetoothGattService mCustomService = mBluetoothGatt.getService(UUID.fromString("00002b00-0000-1000-8000-00805f9b34fb"));
    if(mCustomService == null){
        Log.w(TAG, "Custom BLE Service not found on write");
        return false;
    }

    if (mBluetoothGatt == null || mCustomService == null) {
        Log.w(TAG, "BluetoothGatt not initialized");
        return false;
    }

    BluetoothGattCharacteristic characteristic =
            mCustomService.getCharacteristic(UUID.fromString("00002b11-0000-1000-8000-00805f9b34fb"));

    if (characteristic == null) {
        Log.w(TAG, "Send characteristic not found");
        return false;
    }


    characteristic.setValue(data);
    characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
    boolean returnVal = mBluetoothGatt.writeCharacteristic(characteristic);

    BLEfree = true;
    return returnVal;
}
}

0 个答案:

没有答案