Decode BLE GattServices data - android

I am implementing BLE in Android Studio. I have connected with the peripheral device ok. In my onServicesDiscovered method I want to analyze the services (and characteristics) and I get something like the following when I print out:
android.bluetooth.BluetoothGattService#41b6dd18
There is 4 services in the list and they all look similar except for the numbers at the end. How can I convert this to useful information. I have seen no reference to this format.
Thanks.

Try to read the uuid from the BluetoothGattService object.
You can find uuid of standard services on Bluetooth SIG website. If the uuid is not there (i.e. custom services), you should read the manual of the peripheral or reach out the peripheral maker.

That depends on what you consider "useful" information.
BLE works mostly like dictionary where you look up long numbers (characteristics) and get binary data, so without prior information about the device you're working on, there is not much you can see when you discover services.
That said, in the BLE docs, there is a method displayGattServices() which puts the discovered services info in an ExpandableListView, and here I changed it to print the UUIDs of services and characteristics to logcat instead.
Besides the UUIDs, you can use getProperties() to find out other characteristic properties such as the format of the characteristic data, or getPermissions() to see whether you can read or write the characteristic.
// Demonstrates how to iterate through the supported GATT
// Services/Characteristics.
private void displayGattServices(List<BluetoothGattService> gattServices) {
final String TAG = "BleServiceInfo";
if (gattServices == null) return;
String uuid;
String unknownServiceString = "Unknown service"
String unknownCharaString = "Unknown characteristic"
// Loops through available GATT Services.
for (BluetoothGattService gattService : gattServices) {
Log.d(TAG, "Service: " + gattService.getUuid().toString());
// Loops through available Characteristics.
for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
Log.d(TAG, "\tCharacteristic: " + gattCharacteristic.getUuid().toString());
}
}
}
Call this method from onServicesDisccovered() like this:
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
....
displayGattServices(gatt.getServices());
}

Related

writeable characteristic for android custom ble service always returns write permission zero when discovered

I'm creating a custom BLE service on Android with a single characteristic that can be read/written. The code looks like this:
public static UUID MY_SERVICE = UUID.fromString("e0ec8d9c-5e4d-470a-b87f-64f433685301");
public static UUID MY_CHARACTERISTIC = UUID.fromString("e0ec8d9c-5e4d-470a-b87f-64f433685302");
/**
* Return a configured {#link BluetoothGattService} instance for the
* Custom Service.
*/
public static BluetoothGattService createCustomBleService() {
BluetoothGattService service = new BluetoothGattService(MY_SERVICE,
BluetoothGattService.SERVICE_TYPE_PRIMARY);
// Current Configuration characteristic
BluetoothGattCharacteristic characteristic = new BluetoothGattCharacteristic(MY_CHARACTERISTIC,
BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_WRITE,
BluetoothGattCharacteristic.PERMISSION_READ |BluetoothGattCharacteristic.PERMISSION_WRITE);
boolean serviceAdded = service.addCharacteristic(characteristic);
Log.i(TAG, "Building BLE service addCharacteristic returned "+serviceAdded);
return service;
}
The call to addCharacteristic(...) returns true. The service itself is created, can be advertised, and the service and its characteristic are discoverable by clients. Somewhere else in client side code, subsequent to a BLE scan that locates said service, the discovery code that runs looks like this:
for (BluetoothGattService service : gatt.getServices()) {
serviceUuid = service.getUuid().toString();
if( MY_SERVICE.toString().equals(serviceUuid) ) {
List<BluetoothGattCharacteristic> gattCharacteristics = service.getCharacteristics();
for( BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics ) {
characteristicUuid = gattCharacteristic.getUuid().toString();
Log.d(TAG, "onServicesDiscovered() - found characteristic uuid="+characteristicUuid);
int cProps = gattCharacteristic.getProperties();
Log.d(TAG, "onServicesDiscovered() - found characteristic properties "+cProps);
if ((( MY_CHARACTERISTIC.toString().equals(characteristicUuid) ))&&((cProps & BluetoothGattCharacteristic.PROPERTY_WRITE)>0)) {
writeCharacteristic(gatt,gattCharacteristic,"configStringLiteral");
}
}
}
}
When this service discovery code runs, as I mentioned, it finds the custom service and the characteristic that were defined. Any values I set for characteristic properties show up properly at the time of discovery on client side. The characteristic shows as writeable.
The problem is that characteristic write fails always even though the properties say its writable.
Has anyone seen this?... or perhaps I'm doing something dumb and have been looking at it too long.
(BTW the device hosting the custom service at runtime is a Samsung Galaxy 7 and the client is a Galaxy 6 ...or vice versa, same behavior)
Permission info is not sent over BLE when the services are discovered. Therfore the permission property should not be used for remote characteristics.
A client should inspect the characteristic property only to decide what can be done. If it receives an error saying for example encryption needed, the Bluetooth stack shall start encryption and then retry the request.
So, characteristic properties are the correct way to declare to a client what can be done with it. Characteristic permissions only tell the local GATT Server implementation how it should react to incoming GATT requests.

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()?

BLE readCharacteristics always return false, or getvalue is null

I'm trying to use BLE in Android with a deivice that has fields : battery (RO), status (RO), intensity (R/W).
I followed some tutorials about setting up the Gatt with the device.
I Use the following code :
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
Log.w(LOGGER + mOwner.get().getName(), "onServicesDiscovered received: " + status);
if (status == BluetoothGatt.GATT_SUCCESS) {
// Save all services
for (BluetoothGattService gattService : mBluetoothGatt.getServices()) {
for (BluetoothGattCharacteristic charac : gattService
.getCharacteristics()) {
if (isContained(charac) {
mCharacteristics.set(mCharacteristicsUuid.indexOf(charac.getUuid()
.toString()), charac);
mBluetoothGatt.setCharacteristicNotification(charac, true);
// UUID for notification
BluetoothGattDescriptor descriptor = charac
.getDescriptor(UUID.fromString("00002902-0000-1000-" +
"8000-00805f9b34fb"));
if (descriptor != null) {
descriptor.setValue(BluetoothGattDescriptor
.ENABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);
}
}
}
}
So i try to discover services, if done iterate over them, and their characteristics. If their UUIDs are correct, i add them to mCharacteristics.
If this a value readable (here, everyone of them), I enable notification.
When it's done i try to do a first read :
Log.e(LOGGER + mOwner.get().getName(), "Reading first charac(index=0) : " + mBluetoothGatt
.readCharacteristic(mCharacteristics.get(0)));
}
I have to precise that all of this is inside a dedicated thread, kept up in an Android Service.
I'm sure that the device is connected, and characteristics too.
For each one i verified the value of (Property & REEADABLE), that always > 0...
But for the Read only characteristics i ALWAYS get false on read...
And for the intensity (read/write), read returns true, but onCharacteristicRead() is never called, and the getValue() method returns null.
I'm pretty newer using BLE in Android.
Someone has an idea about the problem ?
Thanks in advance !
EDIT : I finally found the solution but not as I expected...
In fact, if I set the notification enabled, ii can't read the characteristic after...
Can someone tell me how i can perform this way :
> 1) on discover
> a) get all characts + set in list characs I want
> b) enable notification for ALL of these charac (if possible, I supposed, because of the descriptor that can be null ? )
> c) first read to know starting values
You have the answer here: BLE Android, can't enable more than 1 notify on read characteristics.
You have to wait for a GATT operation to complete before you can do another one.

android device.getUuids returns null

I'm trying to connect to an Arduino Uno via an android app using Bluetooth Low Energy (BLE).
I'm developing on Android Studio, testing with a Samsung Galaxy S4, and with an Android version 5.0.1
I followed this link: http://www.truiton.com/2015/04/android-bluetooth-low-energy-ble-example/
I'm scanning devices and when I found one, I would like to get it's UUID before connecting to it, to make sure that it's the right type of device:
mScanCallback = new ScanCallback() {
#Override
#TargetApi(21)
public void onScanResult(int callbackType, ScanResult result) {
BluetoothDevice btDevice = result.getDevice();
ParcelUuid[] uuids = btDevice.getUuids(); //<-- this is always null!! :(
Log.d(TAG, ""+btDevice.fetchUuidsWithSdp()); //<-- prints true.
Log.d(TAG, "result : " + result.toString()); //<-- prints a bunch of relevant info that contains the UUID I want to check.
Log.d(TAG, "uuids : " + uuids); //<-- prints null.
/*
for (ParcelUuid u : uuids) {
//Compare with the UUID of my device, and connect if ok.
}
*/
}
However, btDevice.getUuids(); is always returning null with no error...
How can I get the UUID of the scanned device?
A brute force method would be to use regexp with the result.toString() to grab what I want but there must be a better way isn't it?
Thanks
BluetoothLeScanner scanner = mBluetoothAdapter.getBluetoothLeScanner();
// scan for devices
scanner.startScan(new ScanCallback() {
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public void onScanResult(int callbackType, ScanResult result)
{
List<ParcelUuid> uuids = result.getScanRecord().getServiceUuids();
}
}
this is worked for me in Android 6.0.1
After hours of searching I find out that getUuid() is not the way to go if you want to retrieve the uuid of an iBeacon.
If that is the case, you need to get it directly from the Scan result result object.
I managed to work by using the answer provided by ADEBAYO OSIPITAN.
BLE obtain uuid encoded in advertising packet
Here is his code snipet:
//For APIs greater than 21, Returns Device UUID
public String getUUID(ScanResult result){
String UUIDx = UUID
.nameUUIDFromBytes(result.getScanRecord().getBytes()).toString();
return UUIDx;
}
From Java DOC:
public ParcelUuid[] getUuids ()
Added in API level 15
Returns the supported features (UUIDs) of the remote device.
This method does not start a service discovery procedure to retrieve the UUIDs from the remote device. Instead, the local cached copy of the service UUIDs are returned.
Use fetchUuidsWithSdp() if fresh UUIDs are desired.
Requires BLUETOOTH.
Returns
the supported features (UUIDs) of the remote device, or null on error
Your ScanResult probably is a error

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