startLeScan with 128 bit UUIDs doesn't work on native Android BLE implementation

OneWorld picture OneWorld · Aug 2, 2013 · Viewed 29.1k times · Source

I am having trouble using startLeScan( new UUID[]{ MY_DESIRED_128_BIT_SERVICE_UUID }, callback ) on the new introduced BLE API of Android 4.3 on my Nexus 4.

The callback just doesn't get called. I still can see incoming packages in the log:

08-02 15:48:57.985: I/bt-hci(1051): btu_ble_process_adv_pkt
08-02 15:48:58.636: I/bt-hci(1051): BLE HCI(id=62) event = 0x02)

If I don't use the parameter to filter for UUIDs it works. We are using a manufacturer specific 128bit UUID for device of our company.

Now, our device offers more services than I am providing in the array. But that shouldn't be the problem.

Is anyone facing the same problem? Any solutions?

Edit

There are several problems related to scanning, this question only discusses one: If you also have some issue with scanning, read this comment first. Also keep in mind, that my device imposes a 16bit and a 128bit UUID. Most of you guys use 16bit UUIDs provided by the BLE standard like Heart rate or Speed and Cadence.

Answer

Harold Cooper picture Harold Cooper · Jul 2, 2014

@Navin's code is good, but it includes an overflow bug from the original 16-bit Android code. (If either byte is larger than 127 then it becomes a negative integer.)

Here's an implementation which fixes that bug and adds 128-bit support:

private List<UUID> parseUuids(byte[] advertisedData) {
     List<UUID> uuids = new ArrayList<UUID>();

     ByteBuffer buffer = ByteBuffer.wrap(advertisedData).order(ByteOrder.LITTLE_ENDIAN);
     while (buffer.remaining() > 2) {
         byte length = buffer.get();
         if (length == 0) break;

         byte type = buffer.get();
         switch (type) {
             case 0x02: // Partial list of 16-bit UUIDs
             case 0x03: // Complete list of 16-bit UUIDs
                 while (length >= 2) {
                     uuids.add(UUID.fromString(String.format(
                             "%08x-0000-1000-8000-00805f9b34fb", buffer.getShort())));
                     length -= 2;
                 }
                 break;

             case 0x06: // Partial list of 128-bit UUIDs
             case 0x07: // Complete list of 128-bit UUIDs
                 while (length >= 16) {
                     long lsb = buffer.getLong();
                     long msb = buffer.getLong();
                     uuids.add(new UUID(msb, lsb));
                     length -= 16;
                 }
                 break;

             default:
                 buffer.position(buffer.position() + length - 1);
                 break;
         }
     }

     return uuids;
 }