Mar 302015
 
 March 30, 2015  Posted by at 3:06 pm Microsoft Band  Add comments

Welcome to part two 🙂 Obviously my definition of ‘tomorrow’ is on developer time, so add a day or two 😉

Let’s talk code.

The SDK allows us to connect to one or more bands, but since I only have one we will only use one for the tutorial. For communication the bands uses Bluetooth so before we even attempt to find and connect to a band it makes sense to check if the user has Bluetooth enabled. Unfortunately (as far as I know) in 8.1 there isn’t a straight forward easy to do that and usually you use the native Bluetooth API to see if there are nearby peers or devices. If none it might be off. Since we specifically want to connect to a band we can use the SDK for the band to look for Microsoft Band devices- under the cover it does what the native Bluetooth APIs do but only returns paired bands. This also means that that specific line will not through an exception if none are paired, it will simply return an empty array. This is how we look for paired Microsoft band devices


var bandManager = BandClientManager.Instance;
var pairedBands = await bandManager.GetBandsAsync();

If none are found we could notify the user and suggest that they make sure that Bluetooth is enabled under settings and the device is paired by providing a link that will open up Bluetooth settings. This is how we launch Bluetooth settings:


await Launcher.LaunchUriAsync(new Uri("ms-settings-bluetooth:"));

Let’s take a step back and talk about the band client manager class. The SDK has currently five managers, each with the following responsibilities:

2015-03-30_23-26-09

The BandClientManager used for finding devices and connecting to them, as well as retrieving hardware and firmware information once we have connected to the band through the return type IBandClient. The name of the device is retrieved directly from the BandClientManager, the same goes for connection type (USB or Bluetooth).
The NotificationManager let’s us send messages, dialogs and vibrations
The PersonalizationManager manages the me-tile (main tile on the band) and themes for the band.
The TileManager is what we use to manage our own tile (and the tile theme is set as a property on the tile if you want a separate theme on the tile)
The SensorManager is of course as the name implies how we access sensors, this also includes the sensor that tells us if the band is worn or not.

Each manager type implements its own interface which defines accessible properties and methods. Here is for example the BandClientManager:


public interface IBandClientManager
{
    Task<IBandClient> ConnectAsync(IBandInfo bandInfo);
    Task<IBandInfo[]> GetBandsAsync();
}

The manager classes are singletons and that is why we are accessing the actual object through the object property. In case you aren’t familiar with design patterns a singleton is simply a class that only allows one instance of itself to be created. If you want to extend this class there are a few ways (although it’s probably best to leave it as is) and I’ve added an extension method to swap that instance with one that works with a simulator I have created so if you see EnableSimulator() on instances know that it is *not* a part of the SDK. I’ll add a gentle reminder here and there 🙂 I’ll write more about the simulator at a later point.

Let’s get back to connecting, once we have asked for how many devices we can find we check if we have at least one. To keep things simple we will assume just one band and retrieve the first one and connect to it.

The array returned will contain zero, one or several BandInfo instances that implement the IBandInfo interface which specifies a name and connectiontype property. Once we have connected to a device by passing in the bandinfo retrieved we will in return get a BandClient which implements the IBandClient interface that exposes the four other managers, as well as hardware and firmware information.
Why not also go ahead and get some band information- this might come in handy if we need to make sure that the user has a specific firmware installed, that we have connected to the right device, and/or if its USB or Bluetooth (at the moment Bluetooth is the only option for connecting the band to the phone). Here is the code:


private async void OnConnectToBand(object sTappedRoutedEventArgs e)
{

    var bandManager = BandClientManager.Instance.EnableSimulator(); 
    var pairedBands = await bandManager.GetBandsAsync();

    try
    {
        if (pairedBands.Length < 1)
        {
            info.Text = "Could not connect";
            return;
        }
        _bandClient = await bandManager.ConnectAsync(pairedBands[0]);
        await DisplayBandInfo(pairedBands[0]);
    }
    catch (BandException bandException)
    {
        Debug.WriteLine(bandException.Message);
    }
}

Notice the BandException and the try catch block. There are three exceptions defined for the band, inheriting from each other with the BandException being the one you’ll probably encounter the most. Any do-something-async-with-the-band should be wrapped in a try catch and managed appropriately.

My EnableSimulator() simply does this (see below). It checks if we are running the app in a virtual environment, and if yes it swaps the BandClientManager instance with one that the simulator API uses, if its deployed to a device it uses the standard Microsoft Band SKD.


public static class Extensions
{
    public static IBandClientManager EnableSimulator (this IBandClientManager mng)
    {
        var deviceInfo = new EasClientDeviceInformation();

        var productName = deviceInfo.SystemProductName;

        return productName == "Virtual" 
            ? BandClientManager.Instance // Simulator API
            : Microsoft.Band.BandClientManager.Instance;
    }
}

Here is the code for fetching band information:


// NOT a SDK class- just an example 🙂
public class BandInformation
{
    public string Name { getprivate set; }
    public string Firmware { getprivate set; }
    public string Hardware { getprivate set; }
    public BandConnectionType ConnectionType { getprivate set; }

    public async Task<string> RetrieveInfo(IBandInfo bandInfoIBandClient client)
    {
        Name = bandInfo.Name;
        ConnectionType = bandInfo.ConnectionType;
        Firmware = await client.GetFirmwareVersionAsync();
        Hardware = await client.GetHardwareVersionAsync();
        return string.Format(" Connected to: {0}" +
                             " \n Connection type : {1}" +
                             " \n Firmware : {2} \n Hardware : {3}",
                NameConnectionTypeFirmwareHardware);
    }
}

  One Response to “Developing for Microsoft Band Tutorial part 2: Connecting to the band and retrieving band information”

  1. can you please post the source code for download?

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)

What is 11 + 10 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)