Reputation: 41
My BLE android app can currently connect to my BLE hardware and connect to the GATT server. I can also enable notifications and read the characteristic. However the characteristic advertised is of HEX format. On my Service I tried receiving the data on String or Byte Array format, tried a couple of conversion procedures but still i get nonsensical data (ie. ??x etc)
Any ideas on how to receive/convert the hex data? Service:
private void broadcastUpdate(final String action,
final BluetoothGattCharacteristic characteristic) {
final Intent intent = new Intent(action);
if (UUID_BLE_SHIELD_RX.equals(characteristic.getUuid())) {
//final byte[] rx = characteristic.getValue();
final String rx=characteristic.getStringValue(0);
//final char rx=raw(char.value)
intent.putExtra(EXTRA_DATA, rx);
}
Main Activity:
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (Service.ACTION_GATT_DISCONNECTED.equals(action)) {
} else if (Service.ACTION_GATT_SERVICES_DISCOVERED
.equals(action)) {
getGattService(mBluetoothLeService.getSupportedGattService());
} else if (Service.ACTION_DATA_AVAILABLE.equals(action)) {
displayData(intent.getExtras().getString(Service.EXTRA_DATA));
}
Data from BLE module as seen in NRF connect: (0x)04-01-19-00-BE
Upvotes: 2
Views: 2216
Reputation: 35
In your broadcastUpdate function change it as below
if (UUID_BLE_SHIELD_RX.equals(characteristic.getUuid())) {
final byte[] rx = characteristic.getValue();
intent.putExtra(EXTRA_DATA, rx);
}
In MainActivity
} else if (Service.ACTION_DATA_AVAILABLE.equals(action)) {
displayData(intent.getByteArrayExtra(Service.EXTRA_DATA));
}
In displayData call the function to convert byteArray to hexString
public String bytesToHex(byte[] bytes) {
try {
String hex="";
for (byte b : bytes) {
String st = String.format("%02X", b);
hex+=st;
}
return hex;
} catch (Exception ex) {
// Handler for exception
}
}
Upvotes: 0
Reputation: 529
For the characteristics property, it is commonly used:
String yourHexData = theValueOfYourHexData;
yourHexData.getBytes();
This is the method I use to properly convert a hex string to a byte []
:
public static byte[] hexToByteData(String hex)
{
byte[] convertedByteArray = new byte[hex.length()/2];
int count = 0;
for( int i = 0; i < hex.length() -1; i += 2 )
{
String output;
output = hex.substring(i, (i + 2));
int decimal = (int)(Integer.parseInt(output, 16));
convertedByteArray[count] = (byte)(decimal & 0xFF);
count ++;
}
return convertedByteArray;
}
I don't know your intentions on it, but a byte array is also "no human readable". For this, it would be necessary to use a proper hex to String conversion. But, if you need a Hex to Byte Array conversion, try my method.
Hope it helps.
Upvotes: 0