Browsed by
Tag: tutorial

Connecting Android Device to Winsock via Bluetooth

Connecting Android Device to Winsock via Bluetooth

I am writing this tutorial in order to help others who find themselves in a similar position to my own. I recently had the task of connecting an android 4.3 device to a windows machine relying entirely on winsock. The more I researched the issue, the more I realized that there simply aren’t many good resources when it comes to this very specific problem I was attempting to solve. As a result, I am going to attempt to outline here the best explanation I can as to how I understand solving this problem. In addition, I will omit things as I see fit (usually with reference to an outside source). Others may or may not find this post helpful (It’s entirely possible this post will end up one more among many others which fail to convey the idea).

Android 4.3 – The following was tested using Android 4.4.4, and 4.3.1

The android side of this project is actually fairly simple. You can find great documentation, and example code on the official website which make this part of the project very doable.

As a result of this, I suggest you take a look and work out the basics of Android bluetooth.

To summarize, however, you want to do the following:

  1. Modify application permissions to allow “android.permission.BLUETOOTH” or “android.permission.BLUETOOTH_ADMIN” as per your needs
  2. Acquire ‘BluetoothAdapter’
  3. Pair with a device
  4. Secure a ‘BluetoothSocket’ connection with the paired device

There are, however, a few tips I would like to add to make this process easier.

Tip 1: Fetch SDP Records – If you android app is having trouble discovering service records on the target device, be sure to call “fetchUuidWithSdp()” on your targetted ‘BluetoothDevice’. I have found this step necessary on at least 3 android devices, and yet it is rarely mentioned on the tutorial page.

Tip 2: COMMON UUID – If you find that your two devices just simply aren’t communicating then be sure to check that your android application UUID string matches your desktop application’s GUID. This is crucial.

Winsock 2.2 – Server Side

In order to create a bluetooth server utilizing winsock we begin by initializing our winsocket context. “MAKEWORD(2,2)” simple instructs winsock to utilize version 2.2 of the library, as opposed to version 1.0.

The next couple of steps are almost identical to how winsock is typically used. We will begin by creating our listener socket, which will be used later to wait on incoming connections. The listener socket MUST be created with the following parameters supplied.

After this will we want to create our bluetooth socket address, and fill it with the relevant information. Since our desktop application will behave as a server, we will fill in the following information. If you want your desktop to behave as a client, I suggest you look here.

Next we will bind our socket, and set it to a listening status.

Now that the socket has been bound, we can acquire more in-depth information which will be used a little bit later. This step may be unnecessary for some situations, but it is likely safest to do it anyways.

After all of this has been finished, we can begin what I consider to be the most complicating step involved in this process. In order for bluetooth devices spanning various platforms to communicate with one another it is necessary for them to share a common understanding of “the connection”. Bluetooth accomplishes this primarily with “Service Discovery Protocol (SDP) Records”. This is the bluetooth device’s way of telling another bluetooth device “Hey! I’m can do these things!” or “I can make these connections!”. The most important thing to know is that both your android application, and winsock application both have to have the same 128-bit GUID in their SDP records.

Above I used the well known GUID for a bluetooth serial board, but you can use any 128-bit hex value you want. Preferably pick something that doesn’t overlap with existing devices.

The end is in our sights at this point. Now we need to fill in our ‘CSADDR_INFO’ structure in order to bridge the local connection with our service record. Notice here that our address info structure refers back to our “SOCKADDR_BTH” we used earlier during the binding stage.

Now that we have all of this finished, we can initialize our service, and set our socket to listen mode.

At this point your program will lock up, and wait for a connection to be secured before resuming. This concludes all the critical steps when it comes to setting up your bluetooth server.

There are a few more functions that you may need to/want to play around with depending on your specific bluetooth adapter. In order to modify local bluetooth adapter settings programmatically you can make use of the functions listed here.

In order to find your local bluetooth device (also known as a ‘radio’) you can make use of the following code:

This will locate the first possible bluetooth device on your system. If there are multiple bluetooth devices which you need to iterate over, you can use the following code.

You can also alter some convenience settings on your local device. For example,

The use of each of these functions is pretty self-explanatory.


Bluetooth Version of Winsock Functions

Bluetooth Functions

You can find my source code here.

Note: If you have any questions or constructive criticism I would be happy to hear it.

Move Construction Explained

Move Construction Explained

C++11 brought us a whole host of useful features, and expansions on STL. One such feature is the introduction of “move semantics” to the C++ language. Put simply, move operations are the ability to “move” a resource (memory, file handle, etc.) instead of copying it. Imagine you are back in college, and missed an important class. To avoid falling behind, you ask a friend if you can copy their notes. As it turns out, your friend took the course last semester and no longer has a need for them. Instead of going through the trouble of copying them, he simply agrees to give you the original notes. In effect, this is what you can achieve with move operations. However, there is an obvious problem here. You can only take the original notes from your friend if he no longer has need for them. Doing otherwise would be incredibly rude.

Back in the programming realm, how do we know if we are able to move a resource, as opposed to copying it? To better answer this question, it will be helpful to first understand the difference between L-values, and R-values.

R-Values vs L-Values

L-values are pieces of the equality statement which exist after the statement is evaluated.

R-values are pieces of the equality statement which do not exist after the statement is evaluated. In effect, R-values are temporary, L-values are not.

From what I’ve heard, the initially referred to “right-hand” value, and “left-hand” value. This indicated whether the value was on the left or right side of the equality statement. So, according to this, “x = 10;”, x would be our L-value, and 10 our R-value. While this definition no longer applies in modern C++, it can still serve as a mnemonic device to help you remember the difference. R-values are temporary to the statement they reside, so you would never see an R-value on the left side of an equality statement.

To answer my earlier question, we know we can move a resource as opposed to copy it if the resource comes from an R-value. After all, R-values are temporary. If we attempt to copy a temporary resource, then we may as well just move ownership instead.

Move Operations

I find the best way to learn is by re-implementing common STL functionality. For this example, we will re-implement an STL vector style collection class.

There we go, now we have the basics of a collection class. Now you might notice some interesting syntax here. Specifically:

This is what’s known as an “R-value reference”. In C++ it is how we can define a parameter overload as being an R-value vs an L-value. Using this syntax we can define our “move constructor” as well as our “move assignment operator”.

Move Constructor Implementation

Similarly to a copy constructor/assignment operator, our move constructor/assignment operator will have nearly identical implementation. They will both have two important pieces.

  1. First we want to transfer the resource from the R-value to the L-value.
  2. Second we want to invalidate the resource stored on the R-value. This is an important step, as we want to prevent the R-value from destructing the contained resource.

And that’s it! the call to ‘release()’ on the smart pointer sets the pointer to null and relinquishes ownership. The move assignment operator is nearly identical, with the exception of the possible need to destruct any existing resources on the L-value. An interesting note, contrary to a copy assignment operator it is not necessary with the move assignment operator to check the parameter’s pointer against the current object’s pointer. This makes sense after all.  It’s difficult to think of reasonable situation in which you could set an R-value equal to itself.

Why is this Important?

Move semantics are important because they allow you to entirely avoid superfluous resource acquisition/release. This means avoiding memory allocation, file access, mutex acquistion, reference counting, etc. It may not seem significant. After all, the compiler is pretty good when it comes to avoiding these situations if it can. That said, you should never rely on the compiler to do the smart thing. With just a little extra effort you can ensure that the compiler does the right thing in all situations involving copying temporaries.

I hope this has helped some of you, and if you have any questions please post them in the comments.