I'm working on a Android project which is to connect Nexus 7 and a bio sensor through BLE link. The problem is that, I can successfully detect and get list of services and characteristics of the sensor. When I write some data to the specific characteristic, onCharacteristicWrite is automatically called and showed me writing operation is successful. However, the sensor never receive anything from the tablet. And if I use similar app on iPhone, everything works fine. So there's no problem with the device.
Does anyone have any idea of the problem?
Here is my code for write:
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
#Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
mConnected = true;
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) {
mConnected = false;
Log.i(TAG, "Disconnected from GATT server.");
}
}
#Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
//Once detected services, write to characteristic for 6 times.
int count =6;
while(count>0){
writeCharacteristic();
count--;
}
} else {
Log.w(TAG, "onServicesDiscovered received: " + status);
}
}
#Override
public void onCharacteristicWrite(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status){
if (status == BluetoothGatt.GATT_SUCCESS){
Log.d(TAG,"Write to Characteristic Success! !");
}
}
};
public boolean writeCharacteristic(){
//check mBluetoothGatt is available
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return false;
}
BluetoothGattService Service = mBluetoothGatt.getService(UUID_MY_SERVICE);
if (Service == null) {
Log.e(TAG, "service not found!");
return false;
}
BluetoothGattCharacteristic characteristic = Service
.getCharacteristic(UUID_MY_CHARACTERISTIC);
if (characteristic == null) {
Log.e(TAG, "char not found!");
return false;
}
byte[] value = {(byte)300,(byte)100,(byte)100};
characteristic.setValue(value);
boolean status = mBluetoothGatt.writeCharacteristic(characteristic);
return status;
}
The output shows "Write to Characteristic Success! !" for six times, thus the writing operation succeeded. However, the device shows that nothing been received from tablet. I also tried to write one byte at a time, or add a timer to let the tablet write to sensor every 2 seconds. But none of them worked. Any ideas?
(Answered by question edit. Converted to a community wiki answer. See What is the appropriate action when the answer to a question is added to the question itself? )
The OP wrote:
Follow Up:
The problem solved by manually pairing the tablet with the device first in the setting instead of pairing by code.
So only using the code snippet of connecting Gatt provided by Android is not good enough to pair the device. I should add another code I found online to pair the devices if I don't want to pair them manually every time:
private void pairDevice(BluetoothDevice device) {
try {
Log.d("pairDevice()", "Start Pairing...");
Method m = device.getClass()
.getMethod("createBond", (Class[]) null);
m.invoke(device, (Object[]) null);
Log.d("pairDevice()", "Pairing finished.");
} catch (Exception e) {
Log.e("pairDevice()", e.getMessage());
}
}
Related
I've been developing an app for Android who communicates with a physical piece of hardware via bluetooth. Until now we've been using normal bluetooth, but this has now changed to BLE. I am not an android developer, why this is a bit difficult for me.
At the moment I am just running a proof of concept. Whenever the physical device receives something, it transmits it back, and I can confirm this using proper BLE terminal apps. I've identified the characteristics I need to use, and I can connect to the device and send data to it. Though I cannot receive data, I am never receiving anything back.
The code shown below shows what I'm currently doing, trying to send (successfully) to the device and not so successfully receiving data. Am I totally misunderstand this concept?
Hope someone can give me a hand.
#Override
public void onConnectionStateChange(BluetoothGatt
gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
switch (newState) {
case BluetoothProfile.STATE_CONNECTED:
Log.i("GattCallback", "connected");
gatt.discoverServices();
break;
case BluetoothProfile.STATE_DISCONNECTED:
Log.i("GattCallback", "Disconnected");
break;
default:
System.out.println(newState);
}
}
#Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
super.onCharacteristicChanged(gatt, characteristic);
byte[] newValue = characteristic.getValue();
System.out.println("RECEIVED: " + Arrays.toString(newValue));
}
#Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
for (BluetoothGattService gattService : gatt.getServices()) {
Log.i("derp", "onServicesDiscovered: service=" + gattService.getUuid());
for (BluetoothGattCharacteristic characteristic : gattService.getCharacteristics()) {
Log.i("derp", "onServicesDiscovered: characteristic=" + characteristic.getUuid());
if(characteristic.getUuid().toString().contains("9616")){
System.out.println("We have found the read characteristic.");
gatt.setCharacteristicNotification(characteristic, true);
BluetoothGattDescriptor desc = characteristic.getDescriptor(UUID.fromString("49535343-1e4d-4bd9-ba61-23c647249616"));
if(desc == null){
System.out.println("NULL!");
return;
}
desc.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
gatt.writeDescriptor(desc);
System.out.println("Should be subscribed.");
}
else if(characteristic.getUuid().toString().contains("9bb3")){
System.out.println("Send characteristic found");
characteristic.setValue("Test\n\r");
boolean res = gatt.writeCharacteristic(characteristic);
if(res)
System.out.println("Success");
break;
}
}
}
}
}
I have a BLE device (smartwatch) in which i want to read all data from services and use in my application(Swift and Android), How can i access data from the custom services, but i cant see the UUID in the GATT services and characteristics
You can read data using this code. it's work for me.
When you Smartwatch connected then you needs to send request for service discover. So, Below callback method triggered. In this method get your service and characteristics.
#Override
public void onServicesDiscovered(final BluetoothGatt gatt, final int status) {
Log.e(TAG, "onServicesDiscovered: ");
if (status != BluetoothGatt.GATT_SUCCESS) {
Log.w(TAG, "onServicesDiscovered received: " + status);
return;
}
BluetoothGattService customService = gatt.getService(CUSTOM_SERVICE_UUID);
if (customService != null) {
customNotifyCharacteristic = customService.getCharacteristic(CUSTOM_CHARACTERISTICS_NOTIFY_UUID);
customWriteCharacteristic = customService.getCharacteristic(CUSTOM_CHARACTERISTICS_WRITE_UUID);
customReadCharacteristic = customService.getCharacteristic(CUSTOM_CHARACTERISTICS_READ_UUID);
}
}
After getting all characteristics and services send read request like below.
put below line where you need to read data.
readCharacteristic(customReadCharacteristic);
below explain readCharacteristic method.
public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.readCharacteristic(characteristic);
}
So, onCharacteristicRead callback triggered.
#Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
byte[] data = characteristic.getValue();
}
}
byte[] data = characteristic.getValue();
return your data which you want to read form device.
I am developing and application to read and write in a custom device through Bluetooth BLE. There is no problem for writing. I am able to establish a connections, discover the service and the characteristics.
Note the call to enableRXNotification
public void startReceiving() {
boolean readOk = gatt.readCharacteristic(rx);
if (!readOk) {
Log.d("ANUBEBT", "ERROR INITIATING READ CHARACTERISTIC");
}
}
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
super.onServicesDiscovered(gatt, status);
// Notify connection failure if service discovery failed.
if (status == BluetoothGatt.GATT_FAILURE) {
connectFailure();
return;
}
// Save reference to each UART characteristic.
tx = gatt.getService(SERIAL_SERVICE_UUID).getCharacteristic(TX_CHAR_UUID);
rx = gatt.getService(SERIAL_SERVICE_UUID).getCharacteristic(RX_CHAR_UUID);
enableRXNotification();
// Notify of connection completion.
notifyOnConnected(context);
}
public boolean enableRXNotification() {
if (gatt == null) return false;
BluetoothGattService SerialService = gatt.getService(SERIAL_SERVICE_UUID);
if (SerialService == null) return false;
BluetoothGattCharacteristic RxChar = SerialService.getCharacteristic(RX_CHAR_UUID);
if (RxChar == null) {
Log.d("ANUBEBT", "Error getting rx characteristic");
connectFailure();
return false;
}
if (!setCharacteristicNotification(RxChar, true)) {
Log.d("ANUBEBT", "Error setting rx notification");
connectFailure();
return false;
}
return true;
}
After that, I have tried to call readCharacteristic but always returns false. I have tried several alternatives:
Press a button and call to readCharacteristic
call to readCharacteristic in the onCharacteristicWrite callback (just to make sure there is no pending operations)
Do you know what's going on here?
#Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicWrite(gatt, characteristic, status);
Log.d("ANUBEBT", "onCharacteristicWrite " + status);
if (status == BluetoothGatt.GATT_SUCCESS) {
notifyOnCommunicationError(characteristic.getStringValue(0).length(), characteristic.getStringValue(0));
}
writeInProgress = false;
startReceiving();
}
I'm trying to connect to a Bluetooth Peripheral I wrote for Mac OS X from Android. I have the following code below:
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
String intentAction;
mBluetoothGatt = gatt;
if (newState == BluetoothProfile.STATE_CONNECTED) {
intentAction = ACTION_GATT_CONNECTED;
mConnectionState = STATE_CONNECTED;
broadcastUpdate(intentAction);
Log.i(TAG, "Connected to GATT server.");
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);
mBluetoothGatt.setCharacteristicNotification(characteristic, false);
}
}
// New services discovered
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
Log.i(TAG, "onServicesDiscovered received: " + status);
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
} else {
Log.w(TAG, "onServicesDiscovered received: " + status);
}
}
// Result of a characteristic read operation
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
}
};
Most of the above documentation was on Google's website:
https://developer.android.com/guide/topics/connectivity/bluetooth-le.html#read
However, I keep getting status 129 on onServicesDiscovered and i'm not able to send any data to my peripheral. Is there something i'm doing incorrectly in the above? It seems i'm following the documentation and i'm not able to do it.
EDIT
Seems like in API 21 Google made some changes to the BLE API and they didn't update their documentation (obviously very convenient for us developers). I found the following tutorial helpful:
http://www.truiton.com/2015/04/android-bluetooth-low-energy-ble-example/
Basically with API 21+ you have to use BluetoothLeScanner mLEScanner for scanning for LE devices near by. When the scan is done we have a callback like so:
private ScanCallback mScanCallback = new ScanCallback() {
public void onScanResult(int callbackType, ScanResult result) {
Log.i("callbackType", String.valueOf(callbackType));
Log.i("result", result.toString());
onScan(result.getDevice(), 0, null);
}
public void onBatchScanResults(List<ScanResult> results) {
for (ScanResult sr : results) {
onScan(sr.getDevice(), 0, null);
}
}
public void onScanFailed(int errorCode) {
Log.e("Scan Failed", "Error Code: " + errorCode);
}
};
We can get the devices from the ScanResult and use that for connection and it works on some devices but not all. I get it to work on my Nexus 7 but not my Samsung Galaxy S6. Android BLE is a MESS.
EDIT 2
For now we are just using Bluetooth Classic and not Bluetooth LE. Hopefully Google gets their LE stack figured out properly. I'm not able to get BLE code working on most of the devices in the market.
Even Google's own sample code works on less than half the devices I tested on!
I'm connecting to ios device (Peripheral )from android device as central, I could able to read and write the characteristic. Let me know, what exactly you are looking for now !!!
Follow the sample code
I currently have a method which writes to the BLE devices to beep it. My Bluetooth Callback goes as follows :
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();
}
}
}
This code works perfectly on device running Kitkat and below. But on Devices running Lollipop, this code works fine for the first instance. But from the next instance, irrespective of whether I disconnect or close the connection and try again, it just does not work. It keeps giving me a status code of 257 in onConnectionStateChange method. As far as I know, The Bluetooth GATT methods are the same for both kitkat and Lollipop devices.
What surprises me is that this code works fine on Lollipop devices when i use the old BLE API i.e startLeScan ( For eg - mBluetoothAdapter.startLeScan(mLeScanCallback);). This problem only arises when I use the new BLE API i.e BluetoothLeScanner ( scanner.startScan(filters, settings, new scancallback());). The scanning rate is really slow for Lollipop devices using the old BLE API, hence I cannot use it. I just don't understand how to solve this problem.Has anyone faced the same problem and found a solution? Any help would be deeply appreciated.
Quite a few things I would change here. Create a class variable for the data you want to read from the characteristic, such as private string heartRate;
1) You don't need the readCharacteristic() method. Instead, in the onConnectionStateChange once the device has connected properly, call mBluetoothGatt.discoverServices(). Then in the onServicesDiscovered() method I would call gatt.getServices(). Then use a foreach loop and loop through the returned services and compare the UUID of the service until you find the one you care about. Then if heartRate == null, call service.getCharacteristic(HeartRateUUID) and then read the characteristic. In onCharacteristicRead() check if the UUID is equal to the heart rate characteristic. If it is, assign the value of the characteristic to the heartRate variable. If you are interested, I can type out the methods or provide pseudocode.
2) I wouldn't call gatt.connect() followed by gatt.discoverServices(). gatt.connect() will reconnect to the current device as soon as it sees an advertisement packet from the device. I would call gatt.connect() and then call gatt.discoverServices() in the onConnectedStateChange() method.
3) In the onConnectedStateChange method don't use the gatt variable. Use mBluetoothGatt instead. mBluetoothGatt.disconnect() disconnects from the currently connected device. mBluetoothGatt.close() terminates the gatt instance. You cannot call mBluetoothGatt.connect() after calling mBluetoothGatt.Close(). This might not be needed, but if the device is connected I call mBluetoothGatt.disconnect() followed by mBluetoothGatt.close().
4) You can also chain characteristic readings together. In onCharacteristicRead(), after you get the value of the heartRate, you can immediately call characteristic.getService().getCharacteristic(UUIDTemperature) and then read that characteristic. It will call the OnCharacteristicRead method again.
Let me know if you want me to clarify anything; I'm typing on the crappy Surface Pro 3 keyboard. :)