onCharacteristicWriteRequest the #Override is red underlined - android

I work on a Android Things Project with bluetooth and the #Override is red underlined.
#Override
public void onCharacteristicWriteRequest(BluetoothDevice device, int requestId, BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {
super.onCharacteristicWriteRequest(device, requestId, characteristic, preparedWrite, responseNeeded, offset, value);
Log.d(TAG, "onCharacteristicwriterequest UUID: " + characteristic.getUuid().toString());
mGattServer.notifyCharacteristicChanged(mBluetoothDevice, characteristic, true);
}

Are you expecting the BluetoothGattCallback method?. If yes, there is no such callback method. This is the callback method available in BluetoothGattCallback
#Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { //A request to Write has completed
if (status == BluetoothGatt.GATT_SUCCESS) { //See if the write was successful
AppLog.logError(TAG, "**ACTION_DATA_WRITTEN**" + characteristic);
broadcastUpdate(BLEConstants.ACTION_DATA_WRITTEN, characteristic); //Go broadcast an intent to say we have have written data
}
}
if you want to write something to the BLE you can use the below method
public void writeCharacteristic(BluetoothGattCharacteristic characteristic) {
try {
if (mBluetoothAdapter == null || mBluetoothGatt == null) { //Check that we have access to a Bluetooth radio
return;
}
int test = characteristic.getProperties(); //Get the properties of the characteristic
if ((test & BluetoothGattCharacteristic.PROPERTY_WRITE) == 0 && (test & BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) == 0) { //Check that the property is writable
return;
}
if (mBluetoothGatt.writeCharacteristic(characteristic)) { //Request the BluetoothGatt to do the Write
AppLog.logInfo(TAG, "****************WRITE CHARACTERISTIC SUCCESSFUL**" + (characteristic.getValue()[0] & 0xFF));//The request was accepted, this does not mean the write completed
/* if(characteristic.getUuid().toString().equalsIgnoreCase(getString(R.string.char_uuid_missed_connection))){
}*/
} else {
AppLog.logInfo(TAG, "writeCharacteristic failed "+ (characteristic.getValue()[0] & 0xFF)); //Write request was not accepted by the BluetoothGatt
}
} catch (Exception e) {
AppLog.logInfo(TAG, e.getMessage());
}
}

Related

BLE glucose meter

I am trying to get data from a glucose meter and I am not able to find good resources regarding the implementation on internet. Here is what I have been able to implement till now:
I am scanning the devices using BluetoothAdapter.LeScanCallback Interface:
#Override
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
if ((device.getName() != null) && !bleDevices.contains(device)) {
bleDevices.add(device);
}
}
After getting the devices I am connecting to device using:
device.connectGatt(MainActivity.this, true, bleGattCallBack);
In BluetoothGattCallback class I am able to get the status connected in:
#Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
int newState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
connectionState = STATE_CONNECTED;
gatt.discoverServices();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
connectionState = STATE_DISCONNECTED;
gatt.close();
}
}
After that onServicesDiscovered gets called
#Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
List<BluetoothGattService> gattServices = gatt.getServices();
for (BluetoothGattService gattService : gattServices) {
String serviceUUID = gattService.getUuid().toString();
if (serviceUUID.equals("00001808-0000-1000-8000-00805f9b34fb")) {
List<BluetoothGattCharacteristic> characteristics = gattService.getCharacteristics();
for (BluetoothGattCharacteristic characteristic : characteristics) {
if (characteristic.getUuid().equals(UUID.fromString("00002a18-0000-1000-8000-00805f9b34fb"))) {
BluetoothGattCharacteristic charGM =
gatt.getService(UUID.fromString("00001808-0000-1000-8000-00805f9b34fb"))
.getCharacteristic(UUID.fromString("00002a18-0000-1000-8000-00805f9b34fb"));
gatt.setCharacteristicNotification(charGM, true);
glucoseCharacteristic = characteristic;
BluetoothGattDescriptor descGM = charGM.getDescriptor(UUID.fromString(BleUuid.CHAR_CLIENT_CHARACTERISTIC_CONFIG_STRING));
descGM.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
gatt.writeDescriptor(descGM);
} else if (characteristic.getUuid().equals(UUID.fromString("00002a52-0000-1000-8000-00805f9b34fb"))) {
BluetoothGattCharacteristic charRACP =
gatt.getService(UUID.fromString("00001808-0000-1000-8000-00805f9b34fb"))
.getCharacteristic(UUID.fromString("00002a52-0000-1000-8000-00805f9b34fb"));
gatt.setCharacteristicNotification(charRACP, true);
BluetoothGattDescriptor descRACP = charRACP.getDescriptor(UUID.fromString(BleUuid.CHAR_CLIENT_CHARACTERISTIC_CONFIG_STRING));
descRACP.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
gatt.writeDescriptor(descRACP);
}
}
}
} else {
}
}
After this onDescriptorWrite gets called:
#Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
super.onDescriptorWrite(gatt, descriptor, status);
if (status == BluetoothGatt.GATT_SUCCESS) {
Log.d(TAG, "onDescriptorWrite: GATT_SUCCESS");
BluetoothGattCharacteristic writeRACPchar =
gatt.getService(UUID.fromString("00001808-0000-1000-8000-00805f9b34fb"))
.getCharacteristic(UUID.fromString("00002a52-0000-1000-8000-00805f9b34fb"));
byte[] data = new byte[2];
data[0] = 0x01; // Report Stored records
data[1] = 0x01; // All records
writeRACPchar.setValue(data);
gatt.writeCharacteristic(writeRACPchar);
} else if (status == BluetoothGatt.GATT_INSUFFICIENT_AUTHENTICATION) {
if (gatt.getDevice().getBondState() != BluetoothDevice.BOND_NONE) {
Log.d(TAG, "onDescriptorWrite: GATT_INSUFFICIENT_AUTHENTICATION");
}
} else {
Log.d(TAG, "onDescriptorWrite: GATT_INSUFFICIENT_AUTHENTICATION");
}
}
and then onCharacteristicWrite
#Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicWrite(gatt, characteristic, status);
final byte[] data = characteristic.getValue();
if (data != null && data.length > 0) {
final StringBuilder stringBuilder = new StringBuilder(data.length);
for (byte byteChar : data)
stringBuilder.append(String.format("%02X ", byteChar));
Log.d(TAG, "onCharacteristicWrite: " + status + "\n" + characteristic.getUuid() + "\n" + stringBuilder.toString() + "\n" + characteristic.getValue().length);
}
}
Now, how do I proceed further? I know that I will get the data in onCharacteristicRead but that is never called.

android 10 is not working on BLE Bluetooth connection

android 10 for BLE Bluetooth connection is not connected , i will set all permission also but i get connection status 133 issues ,how to solve this issues ,here i declare the scanning and callback code ,please check and give your idea
but below android 10 version is working fine,only issues on android 10 device ,give an idea to solve the issues
private void scanLeDevice(final boolean enable) {
if (scanner == null) {
scanner = btAdapter.getBluetoothLeScanner();
}
if (scanCallback == null) setScanCallback(null);
scanner.startScan(createScanFilters(),createScanSettings(),scanCallback);
isScanning = true;
}
ScanCallback scanCallback = new ScanCallback() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onScanResult(int callbackType, #NonNull ScanResult scanResult) {
if (connectedDevices.containsKey(scanResult.getDevice().getAddress())) {
return;
}
if (connectingDevices.contains(scanResult.getDevice().getAddress())) {
// If we're already connected, forget it
//Timber.d("Denied connection. Already connecting to " + scanResult.getDevice().getAddress());
return;
}
if (connectionGovernor != null && !connectionGovernor.shouldConnectToAddress(scanResult.getDevice().getAddress())) {
// If the BLEConnectionGovernor says we should not bother connecting to this peer, don't
return;
}
final BluetoothDevice device = btAdapter.getRemoteDevice(scanResult.getDevice().getAddress());
if (device == null) {
Log.e(TAG, "Device not found. Unable to connect.");
}
connectingDevices.add(scanResult.getDevice().getAddress());
// connectToDevice(device);
Timber.d("Initiating connection to " + scanResult.getDevice().getAddress());
device.connectGatt(context, false, mGattCallback, BluetoothDevice.TRANSPORT_LE );
}
#Override
public void onScanFailed(int i) {
Timber.e("Scan failed with code " + i);
}
};
#NonNull
BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
#Override
public void onConnectionStateChange(#NonNull BluetoothGatt gatt, int status, int newState) {
synchronized (connectedDevices) {
// It appears that certain events (like disconnection) won't have a GATT_SUCCESS status
// even when they proceed as expected, at least with the Motorola bluetooth stack
if (status != BluetoothGatt.GATT_SUCCESS)
Timber.w("onConnectionStateChange with newState %d and non-success status %s", newState, gatt.getDevice().getAddress());
Set<BluetoothGattCharacteristic> characteristicSet;
switch (newState) {
case BluetoothProfile.STATE_DISCONNECTING:
Timber.d("Disconnecting from " + gatt.getDevice().getAddress());
characteristicSet = discoveredCharacteristics.get(gatt.getDevice().getAddress());
for (BluetoothGattCharacteristic characteristic : characteristicSet) {
if (notifyUUIDs.contains(characteristic.getUuid())) {
Timber.d("Attempting to unsubscribe on disconneting");
setIndictaionSubscription(gatt, characteristic, false);
}
}
discoveredCharacteristics.remove(gatt.getDevice().getAddress());
break;
case BluetoothProfile.STATE_DISCONNECTED:
Timber.d("Disconnected from " + gatt.getDevice().getAddress());
connectedDevices.remove(gatt.getDevice().getAddress());
connectingDevices.remove(gatt.getDevice().getAddress());
if (transportCallback != null)
transportCallback.identifierUpdated(BLETransportCallback.DeviceType.CENTRAL,
gatt.getDevice().getAddress(),
Transport.ConnectionStatus.DISCONNECTED,
null);
characteristicSet = discoveredCharacteristics.get(gatt.getDevice().getAddress());
if (characteristicSet != null) { // Have we handled unsubscription on DISCONNECTING?
for (BluetoothGattCharacteristic characteristic : characteristicSet) {
if (notifyUUIDs.contains(characteristic.getUuid())) {
Timber.d("Attempting to unsubscribe before disconnet");
setIndictaionSubscription(gatt, characteristic, false);
}
}
} else
if ( status != BluetoothGatt.GATT_SUCCESS ) {
if ( status == 133) {
refreshDeviceCache(gatt);
}
}
gatt.close(); discoveredCharacteristics.remove(gatt.getDevice().getAddress());
break;
case BluetoothProfile.STATE_CONNECTED:
boolean mtuSuccess = gatt.requestMtu(BLETransport.DEFAULT_MTU_BYTES);
Timber.d("Connected to %s. Requested MTU success %b", gatt.getDevice().getAddress(),
mtuSuccess);
break;
}
super.onConnectionStateChange(gatt, status, newState);
}
}
#Override
public void onMtuChanged(#NonNull BluetoothGatt gatt, int mtu, int status) {
Timber.d("Got MTU (%d bytes) for device %s. Was changed successfully: %b",
mtu,
gatt.getDevice().getAddress(),
status == BluetoothGatt.GATT_SUCCESS);
mtus.put(gatt.getDevice().getAddress(), mtu);
// TODO: Can we craft characteristics and avoid discovery step?
boolean discovering = gatt.discoverServices();
Timber.d("Discovering services : " + discovering);
}
#Override
public void onServicesDiscovered(#NonNull BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS)
Timber.d("Discovered services");
else
Timber.d("Discovered services appears unsuccessful with code " + status);
// TODO: Keep this here to examine characteristics
// eventually we should get rid of the discoverServices step
boolean foundService = false;
try {
List<BluetoothGattService> serviceList = gatt.getServices();
for (BluetoothGattService service : serviceList) {
if (service.getUuid().equals(serviceUUID)) {
Timber.d("Discovered Service");
foundService = true;
HashSet<BluetoothGattCharacteristic> characteristicSet = new HashSet<>();
characteristicSet.addAll(service.getCharacteristics());
discoveredCharacteristics.put(gatt.getDevice().getAddress(), characteristicSet);
for (BluetoothGattCharacteristic characteristic : characteristicSet) {
if (notifyUUIDs.contains(characteristic.getUuid())) {
setIndictaionSubscription(gatt, characteristic, true);
}
}
}
}
if (foundService) {
synchronized (connectedDevices) {
connectedDevices.put(gatt.getDevice().getAddress(), gatt);
}
connectingDevices.remove(gatt.getDevice().getAddress());
}
} catch (Exception e) {
Timber.d("Exception analyzing discovered services " + e.getLocalizedMessage());
e.printStackTrace();
}
if (!foundService)
Timber.d("Could not discover chat service!");
super.onServicesDiscovered(gatt, status);
}
/**
* Subscribe or Unsubscribe to/from indication of a peripheral's characteristic.
*
* After calling this method you must await the result via
* {#link #onDescriptorWrite(BluetoothGatt, BluetoothGattDescriptor, int)}
* before performing any other peripheral actions.
*/
private void setIndictaionSubscription(#NonNull BluetoothGatt peripheral,
#NonNull BluetoothGattCharacteristic characteristic,
boolean enable) {
boolean success = peripheral.setCharacteristicNotification(characteristic, enable);
Timber.d("Request notification %s %s with sucess %b", enable ? "set" : "unset", characteristic.getUuid().toString(), success);
BluetoothGattDescriptor desc = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG);
desc.setValue(enable ? BluetoothGattDescriptor.ENABLE_INDICATION_VALUE : BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
boolean desSuccess = peripheral.writeDescriptor(desc);
Timber.d("Wrote descriptor with success %b", desSuccess);
}
#Override
public void onDescriptorWrite(#NonNull BluetoothGatt gatt, #NonNull BluetoothGattDescriptor descriptor,
int status) {
Timber.d("onDescriptorWrite");
if (status == BluetoothGatt.GATT_SUCCESS && transportCallback != null) {
if (Arrays.equals(descriptor.getValue(), BluetoothGattDescriptor.ENABLE_INDICATION_VALUE)) {
transportCallback.identifierUpdated(BLETransportCallback.DeviceType.CENTRAL,
gatt.getDevice().getAddress(),
Transport.ConnectionStatus.CONNECTED,
null);
} else if (Arrays.equals(descriptor.getValue(), BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE)) {
Timber.d("disabled indications successfully. Closing gatt");
gatt.close();
}
}
}
#Override
public void onCharacteristicChanged(#NonNull BluetoothGatt gatt, #NonNull BluetoothGattCharacteristic characteristic) {
Timber.d("onCharacteristicChanged %s with %d bytes", characteristic.getUuid().toString().substring(0,5),
characteristic.getValue().length);
if (transportCallback != null)
transportCallback.dataReceivedFromIdentifier(BLETransportCallback.DeviceType.CENTRAL,
characteristic.getValue(),
gatt.getDevice().getAddress());
super.onCharacteristicChanged(gatt, characteristic);
}
#Override
public void onCharacteristicWrite(#NonNull BluetoothGatt gatt,
#NonNull BluetoothGattCharacteristic characteristic, int status) {
Timber.d("onCharacteristicWrite with %d bytes", characteristic.getValue().length);
Exception exception = null;
if (status != BluetoothGatt.GATT_SUCCESS) {
String msg = "Write was not successful with code " + status;
Timber.w(msg);
exception = new UnknownServiceException(msg);
}
if (transportCallback != null)
transportCallback.dataSentToIdentifier(BLETransportCallback.DeviceType.CENTRAL,
characteristic.getValue(),
gatt.getDevice().getAddress(),
exception);
}
#Override
public void onReadRemoteRssi(#NonNull BluetoothGatt gatt, int rssi, int status) {
super.onReadRemoteRssi(gatt, rssi, status);
}
};
now the app is working for change the bluetooth device support type
device.connectGatt(context, false, mGattCallback, BluetoothDevice.DEVICE_TYPE_LE);
but now the app is not working on huawei device , if any have idea for the device huawei for this issue

onCharacteristicChanged is not called in BluetoothGatt

What i am doing:
Connecting my Android app to the device using gatt.connect().
After connecting, i am discovering all the services.
Then, i am enabling the notification on all the control characteristics. It is a successful write.
After that, i am trying to write some data on one of those control characteristics, which is a success.
The expected behavior is that i should receive a reply on onCharacteristicChanged(), but it is not triggering.
Connecting:
mBluetoothGatt = device.connectGatt(mContext, false, mGattCallback);
mDevice = device;
GATT Callback
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
#Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
Log.i(Constant.BLUETOOTH_GATT_TAG, "Status: " + status);
super.onConnectionStateChange(gatt, status, newState);
switch (newState) {
case STATE_CONNECTED:
Log.i("gattCallback", "STATE_CONNECTED");
gatt.discoverServices();
break;
}
}
#Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
super.onServicesDiscovered(gatt, status);
services = gatt.getServices();
for (BluetoothGattService service : services) {
Log.i("services Discovered", service.getUuid().toString());
}
BluetoothGattCharacteristic characteristic = gatt.getService(Constant.UUID_FRANK_SERVICE).getCharacteristic(Constant.UUID_ILLUMINATION_CONTROL_POINT_CHARACTERISTICS);
Log.d("Notification Enabled", "" + enableNotificationsForCharacteristic(characteristic));
//getAuthenticated();
}
#Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
super.onCharacteristicChanged(gatt, characteristic);
Log.d(CHARACTERISTICS_CHANGED_TAG, "Received from Characteristic UUID");
}
#Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicWrite(gatt, characteristic, status);
Log.d("onCharacteristicWrite", "Value is written...");
}
#Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
super.onDescriptorWrite(gatt, descriptor, status);
Log.d("onDescriptorWrite", "Descriptior is written...");
Log.d("onDescriptorWrite" , "" + mBluetoothGatt.readDescriptor(descriptor));
}
#Override
public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
super.onDescriptorRead(gatt, descriptor, status);
Log.d("onDescriptorRead" , "" + status);
}
#Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicRead(gatt, characteristic, status);
}
};
Enabling The Notifications:
private boolean enableNotificationsForCharacteristic(BluetoothGattCharacteristic characteristic) {
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
if (mBluetoothGatt != null) {
mBluetoothGatt.setCharacteristicNotification(characteristic, true);
if (mBluetoothGatt.writeDescriptor(descriptor)) {
return true;
}
}
return false;
}
Writing to Characteristic:
private boolean writeToCharacteristic(BluetoothGattService service, BluetoothGattCharacteristic characteristic, byte[] aValue, boolean aWithResponse) {
boolean ret = false;
if (service != null) {
if (characteristic != null) {
characteristic.setValue(aValue);
characteristic.setWriteType(aWithResponse ? BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT : BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
ret = mBluetoothGatt.writeCharacteristic(characteristic);
} else {
Log.e(TAG, "writeToCharacteristic() - Characteristic is null! " + service + " - " + characteristic);
}
} else {
Log.e(TAG, "writeToCharacteristic() - Service is null! " + service);
}
return ret;
}
What i am expecting:
After setting notification descriptor, i am getting a GATT_SUCCESS but when i am writing a characteristic, it is not triggering onCharacteristicChanged(). I am expecting it to trigger so that i can read the notification response. The device is behaving properly because i have confirmed the notification using Nordic Connect App
What have i tried:
Tried verifying the descriptor, to see if it is being written properly. It does.
Cross checking the name of services and characteristics. They are all fine.
Tried putting delay before write descriptor. It is being written properly.
Can anyone help me? Why it is not triggering onCharacteristicChanged?

Nexus 9 in Peripheral mode is not accepting connection from clients or not responding to client requests?

I am using Nexus 9 in peripheral mode. I have created a instance of GATT server:
mGattServer = mBluetoothManager.openGattServer(this, mBluetoothGattServerCallback);
I have created a BluetoothGattService & BluetoothGattCharacteristic.
Added service to GATT server & characteristic to service.
BluetoothGattService service =new BluetoothGattService(SERVICE_UUID,
BluetoothGattService.SERVICE_TYPE_PRIMARY);
BluetoothGattCharacteristic offsetCharacteristic =
new BluetoothGattCharacteristic(CHARACTERISTIC_NUM_UUID,
//Read+write permissions
BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_WRITE,
BluetoothGattCharacteristic.PERMISSION_READ | BluetoothGattCharacteristic.PERMISSION_WRITE);
service.addCharacteristic(offsetCharacteristic);
mGattServer.addService(service);
Instance of BluetoothGattServerCallBack:
private BluetoothGattServerCallback mBluetoothGattServerCallback = new BluetoothGattServerCallback() {
#Override
public void onConnectionStateChange(BluetoothDevice device, int status, int newState) {
//super.onConnectionStateChange(device, status, newState);
Log.i(TAG, "onConnectionStateChange "
+ getStatusDescription(status) + " "
+ getStateDescription(newState));
if (newState == BluetoothProfile.STATE_CONNECTED) {
Log.i(TAG, "Connected..");
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
Log.i(TAG, "Disconnected..");
}
}
#Override
public void onServiceAdded(int status, BluetoothGattService service) {
//super.onServiceAdded(status, service);
Log.i(TAG, "onServiceAdded");
}
#Override
public void onCharacteristicWriteRequest(BluetoothDevice device, int requestId, BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {
super.onCharacteristicWriteRequest(device, requestId, characteristic, preparedWrite, responseNeeded, offset, value);
Log.i(TAG, "onCharacteristicWriteRequest");
}
#Override
public void onCharacteristicReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattCharacteristic characteristic) {
super.onCharacteristicReadRequest(device, requestId, offset, characteristic);
Log.i(TAG, "onCharacteristicReadRequest");
}
#Override
public void onDescriptorReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattDescriptor descriptor) {
super.onDescriptorReadRequest(device, requestId, offset, descriptor);
Log.i(TAG, "onDescriptorReadRequest");
}
#Override
public void onDescriptorWriteRequest(BluetoothDevice device, int requestId, BluetoothGattDescriptor descriptor, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {
super.onDescriptorWriteRequest(device, requestId, descriptor, preparedWrite, responseNeeded, offset, value);
Log.i(TAG, "onDescriptorWriteRequest");
}
#Override
public void onExecuteWrite(BluetoothDevice device, int requestId, boolean execute) {
super.onExecuteWrite(device, requestId, execute);
Log.i(TAG, "onExecuteWrite");
}
#Override
public void onNotificationSent(BluetoothDevice device, int status) {
super.onNotificationSent(device, status);
Log.i(TAG, "onNotificationSent");
}
};
Now when I am trying to connect a GATT client to this server, onConnectionStateChange() method of BluetoothGattServerCallback never invoked.
Code from Client Side app:
To connect to GATT server running on Nexus 9
mConnectedGatt = device.connectGatt(this, false, mGattCallback);
Instance of BluetoothGattCallback:
private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
#Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_CONNECTED) {
Log.i(TAG, "Connected to server");
gatt.discoverServices();
} else if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_DISCONNECTED) {
Log.i(TAG, "Disconnected from server");
} else if (status != BluetoothGatt.GATT_SUCCESS) {
gatt.disconnect();
}
}
#Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
}
#Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
}
#Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
}
#Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
}
#Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
}
};
Device(Nexus 9) is discoverable & I am getting it in onLeScan(). But when I am trying to connect to GATT server running on Nexus 9, status in onConnectionStateChange it always STATE_DISCONNECTED.
I tried to connect from some third party applications like "B-BLE", "BLE Scanner", "Bluetooth 4.0 Explorer". Nexus 9 is discoverable in these applications but when I am trying to connect to GATT server, status in onConnectionStateChange() is always STATE_DISCONNECTED.
Any type of help will be appreciated.
Thanks in advance.
As a first step, check if the addService(..) method returns true - only then has the service successfully been added.
Also, try removing the GATT_SUCCESS check from the onConnectionStateChange() method. As far as I know you don't need to test for this there...

android 4.3 Bluetooth ble don't called onCharacteristicRead() after write operation performed

I want to perform read and write operation with bluetooth peripheral.I have write sample application in which after giving particular input it give me output but inside code onCharacteristicRead not get called after onCharacteristicWrite. Please help me out.
This is my code
BluetoothGattCharacteristic WriteCharacteristic =null;
BluetoothGattCharacteristic ReadCharacteristic =null;
private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
/* State Machine Tracking */
private int mState = 0;
private void reset() { mState = 0; }
private void advance() {
mState++;
}
public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
Log.e("onReliableWriteCompleted", "Called");
};
#Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
Log.d(TAG, "Connection State Change: "+status+" -> "+connectionState(newState));
if (status == BluetoothGatt.GATT_SUCCESS && newState==BluetoothProfile.STATE_CONNECTED) {
/*
* Once successfully connected, we must next discover all the services on the
* device before we can read and write their characteristics.
*/
gatt.discoverServices();
//String servicename = gatt.getService(BATTERY_DATA_CHAR).toString();
//System.out.println(servicename);
mHandler.sendMessage(Message.obtain(null, MSG_PROGRESS, "Discovering Services..."));
} else if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_DISCONNECTED) {
/*
* If at any point we disconnect, send a message to clear the weather values
* out of the UI
*/
connectedDevice = null;
mHandler.sendEmptyMessage(MSG_CLEAR);
} else if (status != BluetoothGatt.GATT_SUCCESS) {
/*
* If there is a failure at any stage, simply disconnect
*/
gatt.disconnect();
connectedDevice = null;
}
}
#Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
Log.d(TAG, "Services Discovered: "+status);
mHandler.sendMessage(Message.obtain(null, MSG_PROGRESS, "Enabling Sensors..."));
/*
* With services discovered, we are going to reset our state machine and start
* working through the sensors we need to enable
*/
//reset();
String test="";
List<BluetoothGattService> strname = gatt.getServices();
String servicename =DINSTANCE_SERVICE.toString();
for(int count=0;count<strname.size();count++)
{
if(servicename.equalsIgnoreCase(strname.get(count).getUuid().toString()))
{
ReadCharacteristic = gatt.getService(DINSTANCE_SERVICE).getCharacteristic(DISTAINCE_READ_DATA);
WriteCharacteristic = gatt.getService(DINSTANCE_SERVICE).getCharacteristic(DISTANCE_WRITE_DATA);
test="123";
//characteristic.getStringValue(18);
//byte bbb[] = characteristic.getValue();
// gatt.readCharacteristic(characteristic);
/*String strInput = "012072";
byte passvalues[] = strInput.getBytes();
WriteCharacteristic.setValue(passvalues);
gatt.writeCharacteristic(WriteCharacteristic);*/
WriteCharacteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
//tChar.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
WriteCharacteristic.setValue(012072, BluetoothGattCharacteristic.FORMAT_SINT32, 0);
gatt.writeCharacteristic(WriteCharacteristic);
break;
}
}
System.out.println(servicename);
}
public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status)
{
Log.e("onDescriptorRead","Read method gets called.");
};
#Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
//For each read, pass the data up to the UI thread to update the display
byte bbb[] = characteristic.getValue();
if (HUMIDITY_DATA_CHAR.equals(characteristic.getUuid())) {
mHandler.sendMessage(Message.obtain(null, MSG_HUMIDITY, characteristic));
}
if (PRESSURE_DATA_CHAR.equals(characteristic.getUuid())) {
mHandler.sendMessage(Message.obtain(null, MSG_PRESSURE, characteristic));
}
if (PRESSURE_CAL_CHAR.equals(characteristic.getUuid())) {
mHandler.sendMessage(Message.obtain(null, MSG_PRESSURE_CAL, characteristic));
}
if(DISTAINCE_READ_DATA.equals(characteristic.getUuid()))
{
mHandler.sendMessage(Message.obtain(null, MSG_BATTERY, characteristic));
}
if(BATTERY_READ_CHAR.equals(characteristic.getUuid()))
{
mHandler.sendMessage(Message.obtain(null, MSG_BATTERY, characteristic));
}
//After reading the initial value, next we enable notifications
//setNotifyNextSensor(gatt);
}
#Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status)
{
//After writing the enable flag, next we read the initial value
// readNextSensor(gatt);
try {
if (status != BluetoothGatt.GATT_SUCCESS)
throw new AssertionError("Error on char write");
super.onCharacteristicWrite(gatt, characteristic, status);
if (characteristic.getUuid().equals(DISTANCE_WRITE_DATA)) {
BluetoothGattService syncService = gatt.getService(DINSTANCE_SERVICE);
BluetoothGattCharacteristic tChar = syncService.getCharacteristic(DISTANCE_WRITE_DATA);
ReadCharacteristic = syncService.getCharacteristic(DISTAINCE_READ_DATA);
if (tChar == null)throw new AssertionError("characteristic null when sync time!");
tChar.setValue(012072,BluetoothGattCharacteristic.FORMAT_SINT32, 0);
gatt.readCharacteristic(ReadCharacteristic);
// gatt.readDescriptor(null);
}
} catch (AssertionError e) {
e.printStackTrace();
}
}
#Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
/*
* After notifications are enabled, all updates from the device on characteristic
* value changes will be posted here. Similar to read, we hand these up to the
* UI thread to update the display.
*/
if (HUMIDITY_DATA_CHAR.equals(characteristic.getUuid())) {
mHandler.sendMessage(Message.obtain(null, MSG_HUMIDITY, characteristic));
}
if (PRESSURE_DATA_CHAR.equals(characteristic.getUuid())) {
mHandler.sendMessage(Message.obtain(null, MSG_PRESSURE, characteristic));
}
if (PRESSURE_CAL_CHAR.equals(characteristic.getUuid())) {
mHandler.sendMessage(Message.obtain(null, MSG_PRESSURE_CAL, characteristic));
}
}
#Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
//Once notifications are enabled, we move to the next sensor and start over with enable
String strInput = "012072";
byte passvalues[] = strInput.getBytes();
descriptor.setValue(passvalues);
advance();
Log.e("onDescriptorWrite", "called");
//enableNextSensor(gatt);
}
#Override
public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status)
{
Log.e("onReadRemoteRssi", "called");
Log.d(TAG, "Remote RSSI: "+rssi);
}
private String connectionState(int status) {
switch (status) {
case BluetoothProfile.STATE_CONNECTED:
return "Connected";
case BluetoothProfile.STATE_DISCONNECTED:
return "Disconnected";
case BluetoothProfile.STATE_CONNECTING:
return "Connecting";
case BluetoothProfile.STATE_DISCONNECTING:
return "Disconnecting";
default:
return String.valueOf(status);
}
}
};
Here you can set up (subscribe) to the charactersitic through either notification or indication by calling:
mBluetoothGatt.setCharacteristicNotification(characteristic, true)
mBluetoothGatt.readCharacteristic(characteristic);
from here

Categories

Resources