Overview

A Bluetooth manager that abstracts the actual Bluetooth connection from the program using it. It works asynchronously and will provide a program with events when connections are made and lost and data has been successfully sent or received.

It works in Windows 8 universal applications on Windows Phone 8.1 devices and also on Windows 8.1

Adding the code to a solution

Just add the BluetoothManager.cs source file to your project, ideally in the shared part of a unified project.

Enabling Bluetooth for the Application

An application must enable the Bluetooth serial port capability, otherwise it will not be possible to establish Bluetooth connections. The following text must be added to the Package.appmanifest.xml file for each project. It should be added in the Capabilities section at the end of the file. See the example program for more details.

    <DeviceCapability Name="proximity" />
    <m2:DeviceCapability Name="bluetooth.rfcomm">
      <m2:Device Id="any"  >
        <m2:Function Type ="name:serialPort"/>
      </m2:Device>
    </m2:DeviceCapability>

Creating an instance of the manager

The manager lives in the WindowsBluetooth namespace:

using WindowsBluetooth;

You create an instance of the class when your project first runs. I do this in the constructor for the MainWindow, but you can do it in other places if you wish. I use a class variable to hold the manager itself.

myBluetooth = new BluetoothManager();

Managing a Connection

string bluetoothDevice = "PRINTER";
myBluetooth.Initialise(bluetoothDevice); 


The Initialise method will set up a connection to the named Bluetooth device. Note that you must have paired the Bluetooth adapter with your PC or phone before it will work. The adapter that I used is in paring mode whenever it is not connected to a device. The default passcode is 1234. You can change this to other values. In the downloads is a simple Arduino sketch that you can use to configure the adapter.

The method returns immediately. The device will fire connection status events to indicate changes in state of the connection. Before the connection is initialised you should bind to the events that the device can generate:

myBluetooth.StatusChangedNotification += new BluetoothManager.StatusChangedDelegate(bluetoothStatusChanged);

This event is fired when the interface changes state. Use the status changed event to detect when your system loses or gains connection to the Bluetooth device. The bluetoothStatusChanged method is supplied with a single parameter that gives the current state of the connection:

void bluetoothStatusChanged(BluetoothManager.ManagerStatus status)
{
    switch (status)
    {
        case BluetoothManager.ManagerStatus.Idle:
            break;
        case BluetoothManager.ManagerStatus.GettingConnection:
            break;
        case BluetoothManager.ManagerStatus.FailedToGetConnection:
            break;
        case BluetoothManager.ManagerStatus.GotConnection:
            break;
        case BluetoothManager.ManagerStatus.LostConnection:
            break;
    }
}


The manager also provides a property that allows you to determine its status at any time.

if (myBluetooth.Status == BluetoothManager.ManagerStatus.GotConnection)
{
    Console.WriteLine("Got Connection");
}


Note that it can sometimes take a while for an application to "notice" when a remote Bluetooth device has disconnected. This usually happens when you try to send to the device, even though it is no longer present. The only way to have an up to date indication that the device is there is to "ping" it every now and then.

Resetting a Connection

If a connection fails you can reset the Bluetooth Manager by calling the ResetToIdle method:

myBluetooth.ResetToIdle();

Receiving Data

An application can receive data by requesting a Read:

myBluetooth.ReadRequest();

This will return immediately. When the data arrives the GotMessage event will be raised. Note that you need to raise a read request each time you want to read something. The best way to do this is to raise another read request when you get a block of data from the interface.

Got Message Event

myBluetooth.GotMessageNotification += new GotMessageDelegate(gotMessage);

This statements binds a message receiver to the Bluetooth device. The message receiver is a method that accepts a byte array of incoming data:

 void gotMessage(byte[] message)
{
    // Process the message here
}


You can do what you like with the message, and spend all the time you like doing it - within reason. The handler is run on a separate thread from the Bluetooth device and so it will not stop other messages being received. Having said that, if you take too long to service this request you might find a queue of events building up.

Sending Data

myBluetooth.SendBytes(new byte[] { 1, 2, 3, 4 });

The SendBytes method sends an array of bytes to the Bluetooth device. If the program has bound to the SentMessageNotification event this will be fired when the message has been transferred.

Sent Message Event

myBluetooth.SentMessageNotification += new BluetoothManager.SentMessageDelegate(sentMessage);

The sentMessge method is called when the BluetoothManager instance has successfully sent a message.

Diagnostics

An application can bind to diagnostic events that are produced as connections are set up and used.

myBluetooth.DiagnosticsChangedNotification += new BluetoothManager.DiagnosticsMessageDelegate(diagnosticsStringReceived);

Use the diagnostics event to help you debug your application. The Bluetooth manager also exposes a DiagnosticMesssage value that is a string holding the last diagnostic message that was received.

Last edited Jun 29, 2014 at 8:10 PM by RobMiles, version 3