How to receive Bluetooth value in Android app

42 views Asked by At
BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
    @SuppressLint("MissingPermission")
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        super.onConnectionStateChange(gatt, status, newState);
        Log.i(TAG, "onConnectionStateChange newstate:" + newState + " status:" + status);
        if (status == BluetoothGatt.GATT_SUCCESS) {
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                Log.i(TAG, "============>GATT Connect Success!!<=============");
                //step 5
                mBluetoothGatt.discoverServices();
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                if (mBluetoothGatt != null) {
                    mBluetoothGatt.close();
                    mBluetoothGatt = null;
                }
            }
        }


    }



    @SuppressLint("MissingPermission")
    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        super.onServicesDiscovered(gatt, status);
        Log.i(TAG, "onServicesDiscovered(), status = " + status);
        
        if (status == BluetoothGatt.GATT_SUCCESS) {
            List<BluetoothGattService> services = gatt.getServices();                
            for (BluetoothGattService service : services){
                UUID serviceUUID = service.getUuid();
                Log.i(TAG,"serviceUUID:" + serviceUUID);
               
                List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
                for (BluetoothGattCharacteristic characteristic : characteristics) {
                    UUID characteristicUUID = characteristic.getUuid();
                    Log.i(TAG,"characteristic UUID:" + characteristicUUID);                       
                    
                    List<BluetoothGattDescriptor> descriptors = characteristic.getDescriptors();
                    for (BluetoothGattDescriptor descriptor : descriptors) {
                        UUID descriptorUUID = descriptor.getUuid();
                        Log.d(TAG, "Descriptor UUID: " + descriptorUUID.toString());                           
                    }

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mCharUUID.setText("characteristic UUID:" + characteristicUUID);
                        }
                    });

                    gatt.readCharacteristic(characteristic);
                    //setNotify(characteristic);
                  
                    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
                            UUID.fromString("00002902-0000-1000-8000-00805f9b34fb")); 
                    if (descriptor != null) {
                        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                        gatt.writeDescriptor(descriptor);
                        Log.i(TAG,"descriptor != null");
                    }

                }
            }
        } else {
            Log.i(TAG, "onServicesDiscovered status false");
        }
        setEnableNotify(characteristic, true); 
       
        setCharacteristicNotification(characteristic, true);
        sendSetting();
    }

    
    @Override
    public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
        super.onCharacteristicRead(gatt, characteristic, status);         
    }

    @Override
    public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, byte[] value) {
        super.onCharacteristicChanged(gatt, characteristic, value);
        String receivedData = new String(value, StandardCharsets.UTF_8); 
        Log.d(TAG, "Received data: " + receivedData);
        
    }


    @Override
    public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
        super.onCharacteristicWrite(gatt, characteristic, status);
        if(status == BluetoothGatt.GATT_SUCCESS){
            Log.i(TAG,"onCharacteristicWrite status : " + status);
            Log.i(TAG,"value write success !!" );
        }
        else{
            Log.i(TAG,"onCharacteristicWrite status : " + status);
            Log.w(TAG,"value write false !!");
        }
    }
};


@SuppressLint("MissingPermission")
public boolean setNotify(BluetoothGattCharacteristic data_char) {       
    if (0 != (data_char.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY)) {
        mBluetoothGatt.setCharacteristicNotification(data_char, true);
        BluetoothGattDescriptor descriptor = data_char.getDescriptor(
                UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb"));
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        mBluetoothGatt.writeDescriptor(descriptor);
    } else if (0 != (data_char.getProperties() & BluetoothGattCharacteristic.PROPERTY_INDICATE)) {
        mBluetoothGatt.setCharacteristicNotification(data_char, true);
        BluetoothGattDescriptor descriptor = data_char.getDescriptor(UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb"));
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
        mBluetoothGatt.writeDescriptor(descriptor);
    }
    return true;
}

@SuppressLint("MissingPermission")
public boolean setEnableNotify(BluetoothGattCharacteristic data_char, boolean enable) {
    
    mBluetoothGatt.setCharacteristicNotification(data_char, enable);
    return true;
}


@SuppressLint("MissingPermission")
private void connectGatt() {
    if (mdevice != null)
        mBluetoothGatt = mdevice.connectGatt(MainActivity.this, false, mGattCallback);
    else
        Toast.makeText(MainActivity.this, "Not Bluetooth Device,can't build GATT", Toast.LENGTH_LONG).show();
}


public byte[] hexStringToByteArray(String hexString) {
    int len = hexString.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
                + Character.digit(hexString.charAt(i + 1), 16));
    }
    return data;
}

@SuppressLint("MissingPermission")
public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
                                          boolean enabled) {
    String characteristicString = characteristic.toString();
    Log.i(TAG,"characteristicString : " + characteristicString);
    if (mBTAdapter == null || mBluetoothGatt == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return;
    }

    mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);

    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
            UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
    mBluetoothGatt.writeDescriptor(descriptor);
}

As a beginner in Android Studio, I aim to send a hexadecimal command 87 and receive Bluetooth responses.

Currently, I am able to connect to the Bluetooth device, and the onConnectionStateChange(), onServicesDiscovered(), and onCharacteristicWrite() functions are be executed.

However, I cannot receive Bluetooth data, and onCharacteristicChanged() is not being invoked. Am I missing any steps or are these code snippets incorrect?

If you could assist me in modifying the code, I would greatly appreciate it.

0

There are 0 answers