From f67ee83a22ee8a16c3421041468e61e23f866139 Mon Sep 17 00:00:00 2001 From: Jakub Pawlowski Date: Mon, 24 Oct 2016 13:56:54 -0700 Subject: [PATCH] Add helper method to convert Bluetooth UUID to bytes Bug: 30622771 Test: sl4a ConcurrentBleAdvertisingTest Change-Id: I7f646d1d357c51b82efc504a0e65d868ad363ddb --- core/java/android/bluetooth/BluetoothUuid.java | 42 ++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/core/java/android/bluetooth/BluetoothUuid.java b/core/java/android/bluetooth/BluetoothUuid.java index 2ded4c8fea32..243579a31ce0 100644 --- a/core/java/android/bluetooth/BluetoothUuid.java +++ b/core/java/android/bluetooth/BluetoothUuid.java @@ -275,6 +275,48 @@ public final class BluetoothUuid { } /** + * Parse UUID to bytes. The returned value is shortest representation, a 16-bit, 32-bit or 128-bit UUID, + * Note returned value is little endian (Bluetooth). + * + * @param uuid uuid to parse. + * @return shortest representation of {@code uuid} as bytes. + * @throws IllegalArgumentException If the {@code uuid} is null. + */ + public static byte[] uuidToBytes(ParcelUuid uuid) { + if (uuid == null) { + throw new IllegalArgumentException("uuid cannot be null"); + } + + if (is16BitUuid(uuid)) { + byte[] uuidBytes = new byte[UUID_BYTES_16_BIT]; + int uuidVal = getServiceIdentifierFromParcelUuid(uuid); + uuidBytes[0] = (byte)(uuidVal & 0xFF); + uuidBytes[1] = (byte)((uuidVal & 0xFF00) >> 8); + return uuidBytes; + } + + if (is32BitUuid(uuid)) { + byte[] uuidBytes = new byte[UUID_BYTES_32_BIT]; + int uuidVal = getServiceIdentifierFromParcelUuid(uuid); + uuidBytes[0] = (byte)(uuidVal & 0xFF); + uuidBytes[1] = (byte)((uuidVal & 0xFF00) >> 8); + uuidBytes[2] = (byte)((uuidVal & 0xFF0000) >> 16); + uuidBytes[3] = (byte)((uuidVal & 0xFF000000) >> 24); + return uuidBytes; + } + + // Construct a 128 bit UUID. + long msb = uuid.getUuid().getMostSignificantBits(); + long lsb = uuid.getUuid().getLeastSignificantBits(); + + byte[] uuidBytes = new byte[UUID_BYTES_128_BIT]; + ByteBuffer buf = ByteBuffer.wrap(uuidBytes).order(ByteOrder.LITTLE_ENDIAN); + buf.putLong(8, msb); + buf.putLong(0, lsb); + return uuidBytes; + } + + /** * Check whether the given parcelUuid can be converted to 16 bit bluetooth uuid. * * @param parcelUuid -- 2.11.0