BLE Device disconnect with Android device automatically. Android BLE - android

I'm using Android Nexus 7 to connect a device via Bluetooth Low Energy link. I'm able to connect the device, and stay connected if I don't do any communication with the device.
However, if I enable the notification of one specific characteristic by clicking a button, then the device would disconnect with the tablet after a few seconds' data transmission.
Does anyone know what might be the problem? Thank you very much!
Here's my code:
public boolean setCharacteristicNotification(boolean enabled){
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);
final int charaProp = characteristic.getProperties();
if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);
return true;
}
return false;
}

(Answered in a 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:
I solved this problem today.
Just change descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
to descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
Follow Up:
After I did some research and testing, I found that the automatically disconnection problem has something to do with the interference between Bluetooth and WIFI on Nexus 7. If I turned off the WIFI, then the disconnection problem of Bluetooth has gone. And this problem did not occur on Galaxy 3,4,5.

Problem: I was having same problem on Tesco Hudl 2, if i transmit some
data soon as Bluetooth is connected, it will disconnect.
Solution: Wait for few
seconds after connection, it seems to work okay.

Related

Failing to establish a connection with a custom service

I currently own a LilyPad Simblee BLE Board - RFD77101, with which I'm trying to establish a connection with a custom service that I am defining in arduino 1.6.5 IDE with the Simblee.customUUID command.
I later tried to get the service and the characteristic in Android Studio with the BluetoothleGatt sample code using the UUID I established previously.
The problem is when I connect to the Simblee the app fails to recognize the service and logs me the following error.
Custom BLE Service not found
The code is kinda long hence I am not posting all of it directly. If anyone has an idea as to a solution to my problem and need and part of code I am obviously more than glad to post it.
Thanks to anyone in advance.
This is the public void where I attempt to obtain the characteristic:
public void readCustomCharacteristic() {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
/*check if the service is available on the device*/
BluetoothGattService mCustomService = mBluetoothGatt.getService(UUID.fromString("fe84-0000-1000-8000-00805f9b34fb"));
if(mCustomService == null) {
Log.w(TAG, "Custom BLE Service not found");
return;
}
/*get the read characteristic from the service*/
BluetoothGattCharacteristic mReadCharacteristic = mCustomService.getCharacteristic(UUID.fromString("2d30c083-f39f-4ce6-923f-3484ea480596"));
if(!mBluetoothGatt.readCharacteristic(mReadCharacteristic)) {
Log.w(TAG, "Failed to read characteristic");
}
}
BluetoothGattService mCustomService = mBluetoothGatt.getService(UUID.fromString("fe84-0000-1000-8000-00805f9b34fb"));
The UUID you provided is not in correct format. According to the documentation, the part before first hyphen should consist of 4 hex octets (See the one you provided for characteristics) but you only got 2 here. You should add padding 0 in front like
BluetoothGattService mCustomService = mBluetoothGatt.getService(UUID.fromString("0000fe84-0000-1000-8000-00805f9b34fb"));
Edit : Missing a point here. Have you called mBluetoothGatt.discoverServices()?

Connect to Bluetooth programmatically

I'm trying to connect programmatically my device to for example on my Headsets... I had KitKat version and all worked perfect (Bluetooth always was connecting without problems autommatically) but since I've updated to Lolipop it doesn't. I'd like to know if there is any way to connect any paired device of my Android phone to Bluetooth when it turns on.
Since now I've this code (gets the Device name and Device Address) because I thought with it I could connect doing something like device.connect(MAC-Address); but it didn't work...
BluetoothAdapter bluetoothAdapter
= BluetoothAdapter.getDefaultAdapter();
Set < BluetoothDevice > pairedDevices = bluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device: pairedDevices) {
mDeviceName.add(device.getName());
mDeviceMAC.add(device.getAddress());
}
}
bluetoothClass.setDeviceName(mDeviceName);
bluetoothClass.setDeviceMac(mDeviceMAC);
Question
On my MotoG (KitKat) if I turn my Bluetooth it connects autommatically to device (if it's near and paired ofc...) but on my LG G3 I must go to Configuration/Bluetooth/Paired devices/ and there tap the device to connect... and I want to avoid this... should be possible?
I would like to know if there is any possibility to connect to specific Bluetooth just adding the Device name or Device MAC... More or less like Android does when I click on my device to connect it connects autommatically... I just want to get that CLICK event.
I know that Android should connect autommatically to a paired device but there's any exceptions that doesn not ... the only way to pair it it's doing the click... that's why I'm wondering if it's there a way to do it...
I've read and tested kcoppock answer but it still don't work ..
Any suggestion?
EDIT
The main thing that I wanted to do is to connect my Bluetooth autommatically but since I've read on Hey you answer... I figured it out and I know it's an Android bug, so the thing that I would like to do is select the paired devices and then click on the device that I want to connect (Without doing any Intent) and connect it, instead to go Configuration/Bluetooth/....
Btw I've read any answers on StackOverflow and I found something with Sockets are they used to connect Bluetooth?Could be it a solution?
Edit to answer latest question
You can avoid using an intent to search for paired devices. When connecting to a device that is not paired, a notification will pop up asking to pair the devices. Once paired this message should not show again for these devices, the connection should be automatic (according to how you have written your program).
I use an intent to enable bluetooth, and to make my device discoverable, I then set up my code to connect, and press a button to connect. In your case, you will need to ensure your accessories are discoverable also. In my case I use a unique UUID, and both devices must recognise this to connect. This can only be used if you are programming both devices, whether both are android or one android and one other device type.
Try this, and see if it solves your problem.
This answer is to the original question before it was edited to be another question.
I've edited my answer for clarity as I can see from the comments it is misleading. Your question has two parts.
On my MotoG (KitKat) if I turn my Bluetooth it connects autommatically
to device (if it's near and paired ofc...) but on my LG G3 I must go
to Configuration/Bluetooth/Paired devices/ and there tap the device to
connect... and I want to avoid this... should be possible?
This is less of a programming issue and more of a platform issue.
There is a well documented bug in Android 5.0 with Bluetooth not automatically connecting and many other BT issues. These issues continue with all the updates on 5.0. versions and is not fixed until the 5.1. upgrade.
http://www.digitaltrends.com/mobile/android-lollipop-problems/11/
http://forums.androidcentral.com/lg-g3/473064-bluetooth-streaming-choppy-lg-3-lollipop.html
First port of call is to update to 5.1
These issues have been addressed in the Lollipop update 5.1
http://www.reddit.com/r/Android/comments/306m3y/lollipop_51_bluetooth/
Edit:
I don't believe this is going to fix your problem of the automatic pairing, you wanted to know how to use BTGatt.
I've seen if I type device. to check what can I do it let me
connectGatt() means /.../
But I can't figure it out how to do this...
To use BluetoothGatt
https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html
This class provides Bluetooth GATT functionality to enable
communication with Bluetooth Smart or Smart Ready devices.
/.../
GATT capable devices can be discovered using the Bluetooth device
discovery or BLE scan process.
https://developer.android.com/reference/android/bluetooth/BluetoothGattCallback.html
Here is a great example of how to use BluetoothGatt (it uses hear rate):
https://github.com/googlesamples/android-BluetoothLeGatt/blob/master/Application/src/main/java/com/example/android/bluetoothlegatt/BluetoothLeService.java
I have reproduced some of the code here, in case the link dies.
It basically follows similar lines to a regular bluetooth connection. You need to discover and find supported devices.
Monitor state, etc.
These are the two most pertinent features to gatt.
The callback:
// 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);
}
};
The broadcast:
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();
if (data != null && data.length > 0) {
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());
}
}
sendBroadcast(intent);
}
This question also has some relevant code that may help cut it down when learning:
BLuetooth Gatt Callback not working with new API for Lollipop
Now here's the rub. Are your devices bluetooth smart or smart ready?
This link gives a great list of smart devices. You will also find out when you implement your program.
http://www.bluetooth.com/Pages/Bluetooth-Smart-Devices-List.aspx
This is how i made this work using Java Reflection and BluetoothProfile:
Attributes:
private boolean mIsConnect = true;
private BluetoothDevice mDevice;
private BluetoothA2dp mBluetoothA2DP;
private BluetoothHeadset mBluetoothHeadset;
private BluetoothHealth mBluetoothHealth;
Call:
mBluetoothAdapter.getProfileProxy(getApplicationContext() , mProfileListener, BluetoothProfile.A2DP);
mBluetoothAdapter.getProfileProxy(getApplicationContext() , mProfileListener, BluetoothProfile.HEADSET);
mBluetoothAdapter.getProfileProxy(getApplicationContext() , mProfileListener, BluetoothProfile.HEALTH);
Listener:
private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
public void onServiceConnected(int profile, BluetoothProfile proxy) {
if (profile == BluetoothProfile.A2DP) {
mBluetoothA2DP = (BluetoothA2dp) proxy;
try {
if (mIsConnect) {
Method connect = BluetoothA2dp.class.getDeclaredMethod("connect", BluetoothDevice.class);
connect.setAccessible(true);
connect.invoke(mBluetoothA2DP, mDevice);
} else {
Method disconnect = BluetoothA2dp.class.getDeclaredMethod("disconnect", BluetoothDevice.class);
disconnect.setAccessible(true);
disconnect.invoke(mBluetoothA2DP, mDevice);
}
}catch (Exception e){
} finally {
}
} else if (profile == BluetoothProfile.HEADSET) {
mBluetoothHeadset = (BluetoothHeadset) proxy;
try {
if (mIsConnect) {
Method connect = BluetoothHeadset.class.getDeclaredMethod("connect", BluetoothDevice.class);
connect.setAccessible(true);
connect.invoke(mBluetoothHeadset, mDevice);
} else {
Method disconnect = BluetoothHeadset.class.getDeclaredMethod("disconnect", BluetoothDevice.class);
disconnect.setAccessible(true);
disconnect.invoke(mBluetoothHeadset, mDevice);
}
}catch (Exception e){
} finally {
}
} else if (profile == BluetoothProfile.HEALTH) {
mBluetoothHealth = (BluetoothHealth) proxy;
try {
if (mIsConnect) {
Method connect = BluetoothHealth.class.getDeclaredMethod("connect", BluetoothDevice.class);
connect.setAccessible(true);
connect.invoke(mBluetoothHealth, mDevice);
} else {
Method disconnect = BluetoothHealth.class.getDeclaredMethod("disconnect", BluetoothDevice.class);
disconnect.setAccessible(true);
disconnect.invoke(mBluetoothHealth, mDevice);
}
}catch (Exception e){
} finally {
}
}
}
public void onServiceDisconnected(int profile) {
}
};
I hope this helps anyone trying to connect to Bluetooth Audio devices and headsets.

Android bluetooth get the heart rate measurement

I want to get the value of the HRM of an "A&D UA-651BLE" device.
this is what's written in the datasheet of this device to get the HRM value:
Set the application to pairing mode to start scanning.
Start pairing of A&D BLE device following each instruction manual.
At pairing mode, the application should set time and date and any other device settings
to A&D BLE device. After successful pairing, A&D BLE device shows “End” on the screen.
Take a measurement and finish the measurement, then A&D BLE device start BLE
connection with advertising. The application starts scanning with suitable interval so that
the application catches the advertising of A&D BLE device as soon as it can.
At initial connection or pairing, the Application set “2” to CCCD (Client Characteristic
Configuration Descriptor) so that A&D BLE device sends a measurement data with
Indication.
After A&D device recognizes to be set “2” to CCCD and to be synchronized time and date
within 5 seconds after connected, send the data with Indication.
If the timeout set CCCD and time and date is expired, A&D BLE device will not send data
and store the data in memory. The stored data in A&D BLE device can send next
successful connection.
this is my service code:
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);
}
}
and this is the method that read data:
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.e("HRM value",stringBuilder.toString());
dataComposition.put(characteristic.getUuid().toString(),stringBuilder.toString());
intent.putExtra(EXTRA_DATA,dataComposition);
}
the problem is that this code doesn't return any data !!
There's an Android Open Source Project example that does precisely this, easiest option would be to clone the android-BluetoothLeGatt code, build and compare it to your own. If you can't spot the difference / issue simply deploy both app's and step through both sets of code. Having some known working code will also help to rule out the possibility that the HRM is not functioning properly.
Do you have and example , i try this with equal device and i cant obtain the information y try with
public String response() {
if (mConnected) {
mBluetoothLeService.readCharacteristic(characteristica);
byte response[] = characteristica.getValue();
String respuesta = ReadBytes(response);
mBluetoothLeService.disconnect();
return respuesta;
} else {
return null;
}
}

keyfob cc2541 bluetooth connection drops when trying to enable acclerometer on android

I am developing an Android app that needs to read the Keyfob's Accelerometer data. Until now I've followed this tutorial: https://thenewcircle.com/s/post/1553/bluetooth_smart_le_android_tutorial
With it I was able to connect with the Keyfob, search for services and read some characteristics. The problem is when I try to enable the keyfob's Accelerometer, the bluetooth connection simply drops.
This is the code I use to try to enable the accelerometer:
private void enableAccelerometer(BluetoothGatt gatt){
BluetoothGattCharacteristic characteristic;
BluetoothGattService service;
Log.d(TAG, "ligando acelerometro");
service = gatt.getService(ACCELEROMETER_SERVICE);
if(service == null){
Log.d(TAG, "Not able to find the service");
}
else{
Log.d(TAG, "Service found");
characteristic = service.getCharacteristic(ENABLE_ACCELEROMETER);
if(characteristic == null){
Log.d(TAG, "Characteristic not found");
}
else{
characteristic.setValue(new byte[] {0x01});
if (!gatt.writeCharacteristic(characteristic)){
Log.d(TAG, "writing failed ");
}
else {
Log.d(TAG, "writing successful: ");
}
}
}
This method is called in the "onServicesDiscovered" callback function.
The Texas Instrument CC2540/41 Mini Development Kit User’s Guide states that to enable the accelerometer it is necessary to write "01" in the enable acceleromenter characteristic in the accelerometer serivce, that's what I am doing with this code.
The connection between the phone (LG G2 mini running Android 4.4.2) drops when I write:
characteristic.setValue(new byte[] {0x01});
I am sure it is this line that is making the connection drop, if I comment it out or simply try to write a string instead of a byte, the connection doesn't drop.
Does anyone have any idea what am I doing wrong?
Turns out that after a week I found a way to turn the accelerometer on. I still don't know why it is working only that way, but I just changed:
characteristic.setValue(new byte[] {0x01});
to
characteristic.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
I don't know what value is exactly inside the "BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE" constant, but it worked.

HM-10 Bluetooth Module - BLE 4.0 Keep Losing Connection

has anyone tried using HM-10 Bluetooth module?
I'm able to pair with it using an Android device and passing the pre-defined PIN. Based on the UART return, the pairing is successful (module returns OK+CONN - means a connection was established)
However, after a few seconds (2-3), the UART receives OK+LOST; means the connection was lost. Also, the LED starts blinking (normally, when a connection is active, it stays lit)
Is this normal behaviour for bluetooth in general or the HM-10 module.
This is the product's website: http://www.jnhuamao.cn/bluetooth.asp?ID=1
I'm not sure, but HM -10 don't support rfcom. It's mean that you must use GATT functionality for communication. Entity of BLE is usage of minimum data package as it possible, so BLE don't hold the connection all times and use something like statuses [attributes].
So, few code lines for example, how work with BLE:
1.
BluetoothAdapter mBluetoothAdapter = mBluetoothManager.getAdapter();
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(DEVICE_ADDR);
That's device initiation, the same like with simple bluetooth, where DEVICE_ADDR is the MAC of your BLE(how to find this address you can find in google or stack overflow, its trivial)
2.
BluetoothGattService mBluetoothGattService;
BluetoothGatt mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
#Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
mBluetoothGatt.discoverServices();
}
}
#Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
List<BluetoothGattService> gattServices = mBluetoothGatt.getServices();
for(BluetoothGattService gattService : gattServices) {
if("0000ffe0-0000-1000-8000-00805f9b34fb".equals(gattService.getUuid().toString()))
{
mBluetoothGattService = gattService;
}
}
} else {
Log.d(TAG, "onServicesDiscovered received: " + status);
}
}
};
So, what this code mean: if u can see from this part of code, i describe how GATT service find. This service needed for "attribute" communication. gattService.getUuid() has few uuids for communication(4 in my module), some of them used for RX, some for TX etc. "0000ffe0-0000-1000-8000-00805f9b34fb" that is one of uuid that use for communication thats why i check it.
The final part of code is message sending:
BluetoothGattCharacteristic gattCharacteristic = mBluetoothGattService.getCharacteristic(UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb"));
String msg = "HELLO BLE =)";
byte b = 0x00;
byte[] temp = msg.getBytes();
byte[] tx = new byte[temp.length + 1];
tx[0] = b;
for(int i = 0; i < temp.length; i++)
tx[i+1] = temp[i];
gattCharacteristic.setValue(tx);
mBluetoothGatt.writeCharacteristic(gattCharacteristic);
After sending message contain hold on and you can send another message or can close connection.
More info, you can find on https://developer.android.com/guide/topics/connectivity/bluetooth-le.html.
PS: MAC address of your module can find with ble scanner code or with AT cmd:
on my firmware AT+ADDR or AT+LADDR
About UUIDs usage: not sure, but in my case, i find it with next AT+UUID [Get/Set system SERVER_UUID] -> Response +UUID=0xFFE0, AT+CHAR [Get/Set system CHAR_UUID] - Response +CHAR=0xFFE1. Thats why i make conclusion that UUID which i must use fe "0000[ffe0/is 0xFFE0 from AT response]-0000-1000-8000-00805f9b34fb"

Categories

Resources