Category Archives: Bluetooth

Privates exposed

We’re all tempted, right… But don’t do it. Just don’t.

Access modifiers, as we all know, are fundamental part of object oriented languages. When used correctly, they help to provide clear interfaces for classes by data encapsulation and allow carefree development of software using various APIs. When you see a private (or protected) method, you think there’s a good reason why the one who implemented the class decided to do so. If for some reason you do need to go further than the public API allows you to, you usually find a valid workaround – and even then you question if there is a better way to achieve what you are trying to accomplish.

However, in some extremely rare cases you might find yourself in a situation where there is no workaround and without access to some protected/private method you are facing a wall. Or the possible workaround costs you hours or even weeks more work when with the access you could be done in just few minutes. What to do? Well, it’s up to you, but if you really want to take the easy (but risky) path, you can, since there really are no such things as protected or private. An access modifier is more than a recommendation though and you should think not twice but N times before dismissing one.

You have been warned

Accessing private bits in C++ is a bit tricky. The method I’d recommend is to get the address of, i.e. pointer to the function in question. You might need to calculate the offset from e.g. the class pointer, but this can be done by ye olde trial-and-error method. You may also consider trying #ifdef hacks, but those could drive you crazy with all the other errors they might cause.

In other languages, namely those that support the magicks of reflection (Java and C# for instance), things can be far more simple. For example, in (Android) Java you access and invoke a private method as follows:

Method method = SomeClass.class.getDeclaredMethod("methodName");
method.setAccessible(true);
SomeClass someClass = new SomeClass();
method.invoke(someClass);

The constructors and members are accessible in a similar fashion. See Class and Method classes for more information.

Note that  even though your code accessing and invoking private methods works now, you cannot rely it to work in the future. If – and often times when – the code you’re referencing and the private method signature changes, your code will throw a NoSuchMethodException. Therefore, it’s a no-brainer to surround the code with try-catch. But what then? What do you do when an exception is thrown and you’ve caught it. Albeit this is from programming 101, I’m gonna say it: Handle the exception gracefully; Your application has to perform even when your hack of access violation trickery doesn’t! Same goes regardless of what your weapon (language) of choice is.

I warned you

 

Case Android Bluetooth socket

I was working on a cross-platform peer web project called Thali. Furthermore, I was in charge of the native Android layer of the project (see Thali Android Connector Library). We had had issues (in addition to number of other problems) with failing Bluetooth sockets, namely in the connection process.

We noticed that many reported better results using a workaround that they used to create a socket with a specified port. One uses BluetoothDevice class to construct BluetoothSocket instances. However, using the publicly available methods (read: the methods intended to be used) to create sockets one cannot define the port – instead the port is decided for you. If you really want to define the port yourself, there is a way: Use reflection to invoke the method with which you can define the port. And it’s not even protected/private, just cannot be called directly:

// bluetoothDevice is an instance of BluetoothDevice class
Method method = bluetoothDevice.getClass().getMethod("createRfcommSocket", new Class[] { int.class });
BluetoothSocket bluetoothSocket = (BluetoothSocket) method.invoke(bluetoothDevice, 1); // 1 is the port number

This solution didn’t work for us since Thali project uses insecure RFCOMM sockets vs. the secure ones and the method for constructing insecure sockets with a specified port number is neither public nor available. Thus, to accomplish the same effect as the aforementioned code snippet, one has to access the private constructor of the BluetoothSocket class. So I created a helper method which allows you to construct both secure and insecure BluetoothSocket instances with the desired channel/port (see BluetoothUtils class in Thali Android Connectivity Library project):

public static BluetoothSocket createBluetoothSocketToServiceRecord(
        BluetoothDevice bluetoothDevice, UUID serviceRecordUuid, int channelOrPort, boolean secure) {
    Constructor[] bluetoothSocketConstructors = BluetoothSocket.class.getDeclaredConstructors();
    Constructor bluetoothSocketConstructor = null;

    for (Constructor constructor : bluetoothSocketConstructors) {
        Class<?>[] parameterTypes = constructor.getParameterTypes();
        boolean takesBluetoothDevice = false;
        boolean takesParcelUuid = false;

        for (Class<?> parameterType : parameterTypes) {
            if (parameterType.equals(BluetoothDevice.class)) {
                takesBluetoothDevice = true;
            } else if (parameterType.equals(ParcelUuid.class)) {
                takesParcelUuid = true;
            }
        }

        if (takesBluetoothDevice && takesParcelUuid) {
            // We found the right constructor
            bluetoothSocketConstructor = constructor;
            break;
        }
    }

    // This is the constructor we should now have:
    // BluetoothSocket(int type, int fd, boolean auth, boolean encrypt, BluetoothDevice device,
    //      int port, ParcelUuid uuid) throws IOException

    // Create the parameters for the constructor
    Object[] parameters = new Object[] {
            Integer.valueOf(1), // BluetoothSocket.TYPE_RFCOMM
            Integer.valueOf(-1),
            Boolean.valueOf(secure),
            Boolean.valueOf(secure),
            bluetoothDevice,
            Integer.valueOf(channelOrPort),
            new ParcelUuid(serviceRecordUuid)
    };

    bluetoothSocketConstructor.setAccessible(true);
    BluetoothSocket bluetoothSocket = null;

    try {
        bluetoothSocket = (BluetoothSocket)bluetoothSocketConstructor.newInstance(parameters);
        Log.d(TAG, "createBluetoothSocketToServiceRecord: Socket created with channel/port " + channelOrPort);
    } catch (Exception e) {
        Log.e(TAG, "createBluetoothSocketToServiceRecord: Failed to create a new Bluetooth socket instance: " + e.getMessage(), e);
    }

    return bluetoothSocket;
}

What good did it do?

None. Jacksh*t! It did no good at all as far as I can tell.

“Paskaaks se mitään teki.”

The hack didn’t solve our problems. Turns out the problem was elsewhere and fault of my own (I’ll let you in on a secret, if you haven’t realized it by now: I’m not a guru. I’m not a master programmer. I’m your average software developer and, if anything, I’m lazy enough to find quick, clean solutions to problems that usually work.) That said, the hack might have provided useful on earlier versions of Android, but the possible platform issue was most likely fixed on Lollipop and newer. With the hack the Bluetooth socket worked as well as without the trickery and when it was bound to fail it did so regardless.

So as final words I give you…

Reasons why NOT to access protected/private stuff

  1. 99.9 times out of 100, there’s really no need – work around it!
  2. Given that whoever wrote the code is not a complete tool, made it inaccessible for a reason.
  3. Your hack won’t most probably be sustainable. It will break. Just see. Unless, of course, no one will eveeeeer touch the code you’re referencing.
  4. As per the aforementioned – you have to keep maintaining your code constantly to make sure it stays up-to-date with the code you are referencing.
  5. You’re just asking for trouble.
  6. Go to 1.
Run away
The recommended action

Working with Conspicuous Devices (My One Obligatory IoT Article)

IoT! The new, hip word meaning “Internet of Things” – unlike many other trends that come and go, this one is here to stay. Oh, and grow! But enough of the hyped marketing talk; I’m not good at that anyways. What I want to offer to you, developers, in this short blog post, is a small part of Windows 10 offering for IoT related app development, specifically for Bluetooth LE (BLE) beacons.

What is a BLE beacon you ask? It’s a small piece of hardware, typically run by a small battery of which lifetime varies from months to many years. It does but one thing: Transmits a signal with a small payload over and over again (hence the name beacon). Beacons can be attached in many places, both stationary and mobile. Who knows – you could have one in your pants right now!

So, a beacon alone does not do anything useful, but think of what devices receiving the signals can do! Like the whole field of IoT, it’s hard to foresee all the use cases random tech enthusiasts devise with beacons and similar devices. I already worked with one of the visionaries in the field, a company called Sensorberg, and it’s hard not to get excited by their enthusiasm alone.

But, let’s cut to the chase (I promised this would be a short article)!

Windows 10 and its new converged Bluetooth stack

Windows 8.1 did not have enablers for developers to work with beacons, but this unfortunate shortcoming is spectacularly fixed in the spanking new Windows 10. Not only that, but the whole Bluetooth stack is now converged i.e. it’s the same on all devices running Windows 10. However, you should note that some of the features have hardware dependencies, which you have to take into consideration when developing universal apps. The good news is that the same code works everywhere; you just have to catch the possible exceptions in the case of missing hardware support.

The new namespaces for working with beacons are Windows.Devices.Bluetooth.Advertisement and Windows.Devices.Bluetooth.Background. The aforementioned is the one I’ll be focusing in this article. The latter provides the means to work with beacons using a background task.

Implementing a tricorder

What does it take to make your Windows 10 device to scan for beacons. Not much. You simply construct a BLE advertisement watcher instance, give it some filters, start it and wait for beacons to come in range. Then, simply catch the event and do something with the data you received.

DataTricorder“Look Geordi! I received a coupon code!”

In code setting the watcher up and starting it is done like this (based on the snippet taken from the official Microsoft sample):

BluetoothLEAdvertisementWatcher watcher =
    new BluetoothLEAdvertisementWatcher();

var manufacturerData = new BluetoothLEManufacturerData();

// Then, set the company ID for the manufacturer data.
// Here we picked an unused value: 0xFFFE
manufacturerData.CompanyId = 0xFFFE;

// Finally set the data payload within the manufacturer-specific section
// Here, use a 16-bit UUID: 0x1234 -> {0x34, 0x12} (little-endian)
var writer = new DataWriter();
writer.WriteUInt16(0x1234);

// Make sure that the buffer length can fit within an advertisement payload.
// Otherwise you will get an exception.
manufacturerData.Data = writer.DetachBuffer();

// Add the manufacturer data to the advertisement filter on the watcher:
watcher.AdvertisementFilter.Advertisement.ManufacturerData.Add(manufacturerData);

watcher.Start();

To catch the received beacon data you must hook to BluetoothLEAdvertisementWatcher.Received event, where you get the data encapsulated in BluetoothLEAdvertisementReceivedEventArgs. You will find all the data transmitted there as raw byte array and some of the data is provided as properties for convenience. You can check out the format of the beacon data here.

If at this point you are too eager to jump right into code, I don’t mind. You can check out the official Microsoft sample code here or take a look at my awesome sample here.

Your device can be a beacon too

Windows 10 also allows you to make your device function as a beacon (and remember that Windows 10 runs on all kinds of devices including even the smallest ones). This is handy for a number of reasons, probably many use cases exist that I can’t even imagine yet, but of course, the obvious one is testing your app – unlike a standard, physical beacon, the beacon ID, used to identify a certain beacon, can be changed dynamically and you can easily start or stop broadcasting with a push of a button.

For turning your device into beacon there’s a class called BluetoothLEAdvertisementPublisher. The use of it is just as simple as that of the watcher; construct the instance, give it a payload and hit start! Here’s an example (based on the snippet taken from the official Microsoft sample):

// Create and initialize a new publisher instance.
BluetoothLEAdvertisementPublisher publisher =
    new BluetoothLEAdvertisementPublisher();

// We need to add some payload to the advertisement. A publisher without any payload
// or with invalid ones cannot be started. We only need to configure the payload once
// for any publisher.

// Add a manufacturer-specific section:
// First, let create a manufacturer data section
var manufacturerData = new BluetoothLEManufacturerData();

// Then, set the company ID for the manufacturer data. Here we picked an unused value: 0xFFFE
manufacturerData.CompanyId = 0xFFFE;

// Finally set the data payload within the manufacturer-specific section
// Here, use a 16-bit UUID: 0x1234 -> {0x34, 0x12} (little-endian)
var writer = new DataWriter();
UInt16 uuidData = 0x1234;
writer.WriteUInt16(uuidData);

// Make sure that the buffer length can fit within an advertisement payload. Otherwise you will get an exception.
manufacturerData.Data = writer.DetachBuffer();

// Add the manufacturer data to the advertisement publisher:
publisher.Advertisement.ManufacturerData.Add(manufacturerData);

publisher.Start();

Note that the advertising feature is a limited hardware resource, which can be used by multiple apps. So, unless your app is the only one using it on your device, be prepared for having to wait for the resource to be available. Luckily, you can hook to BluetoothLEAdvertisementPublisher.StatusChanged event. One of the statuses is “Waiting”.

 

Please, have my code

Screenshot of BLE Beacon Sample

You can check out my BLE beacon sample, which does both scanning (using the watcher) and advertising (using the publisher). It allows you to enter the desired beacon IDs. I tried to keep the code as simple as I could by adding two utility classes: Beacon and BeaconFactory. The sample is hosted in GitHub here.

Wait, there’s more…

You might have noticed that I did not cover beacon scanning scenario where the application is in the background. That’s because my dear colleague, Juhana Koski, has already covered that in his article, and it also comes with a code sample.

Do also check out this great session on BLE advertisement APIs from the 2015 //build/ conference.

Finally, for a proper developer, which I’m sure you are, code speaks more than… umm… 1000 words which are not code. Thus, check these samples to get a quick dive-in to the world of BLE beacons on Windows 10 universal platform: