October 2015

Volume 30 Number 10

Microsoft Band - Develop a Windows 10 App with the Microsoft Band SDK

By Kevin Ashley

Microsoft Bing predicted wearables would be the hottest trend in technology in 2015 (binged.it/1hCBv9A), ahead of personal digital assistants, home automation, 3D printing and virtual reality gaming.

One such device, Microsoft Band, combines most sensors people need to track their health, fitness, sleep quality and more. It packs more sensors than many of the more expensive devices available in the market.

As a mobile app developer, I’m interested in creating useful applications with Microsoft Band. Some of the examples used in this code I used in my Active Fitness app (activefitness.co), which has more than 2 million users on Windows, iOS and Android. Most consumer apps need to work on multiple platforms such as Windows, iOS and Android to reach a maximum audience. In this article, I’ll explain how to develop Windows 10 apps for Band and explore cross-platform options. It was an honor to participate in the early versions of the Band SDK. Now that it has been made publically available, I can share code examples, enhanced with the latest releases of the Band SDK and the developer community.

Gravity Hero: Windows 10 Sample App

I wanted to build something fun that showcases Band features and at the same time works almost like a game. So I built a Universal Windows app called “Gravity Hero,” as shown in Figure 1. The idea is simple: You jump wearing the Band and the device tells you whether you made your best jump ever. And because I built a Universal Windows app, it’ll work on any Windows 10 device. I also added sample code on GitHub for a native Android app to demonstrate how you can easily target other devices. In addition, the Band Developer Web site includes links to documentation and SDK code samples (developer.microsoftband.com).

Gravity Hero Sample App Running on Windows 10
Figure 1 Gravity Hero Sample App Running on Windows 10

The Microsoft Band team provides SDKs for Windows, iOS and Android. In addition, there’s a cross-platform SDK solution with Xamarin, technology that enables a great code reuse. Which technology should you choose? With support of Microsoft and the community, you have the following options when developing for the Band device:

  • Microsoft Band SDK (Microsoft) for native development with Windows, iOS and Android (bit.ly/1JfiFvW)
  • Web Tile SDK (Microsoft) for quickly delivering information to the Band from any Web source in just a few easy steps (bit.ly/1h94CjZ)
  • Cloud API (Microsoft) for accessing RESTful APIs with comprehensive fitness and health data in an easy-to-consume JSON format (bit.ly/1MIBOL7)
  • Cross-Platform SDK (Xamarin) for use in Xamarin cross-platform apps, targeting iOS, Android and Windows; with Xamarin you can use a single code base for all platforms (bit.ly/1EfhqjK)

If you already have a Windows, iOS or Android app, simply use a native Band SDK for each of these platforms. If you’re starting from scratch or want to target all platforms with the same code, you might want to take a look at Xamarin. The choice is yours. The platform-friendly approach gives you all the choices you need to start building apps. In this article, I’ll look at both options.

Connecting the Band to a Windows 10 PC

Before you start with development, you’ll need to connect the Band to a Windows 10 PC. Windows 10 includes Bluetooth support, so this is very easy to do:

On your Band, flip to the Settings tile, click the Bluetooth icon and switch to Pairing. Your Band is now in pairing mode. On your Windows 10 PC, go to Settings or type Bluetooth in Cortana and open the Bluetooth settings page, as shown in Figure 2. Note the status of your Band in the list of Bluetooth devices. Band names usually start with your name and a code, unless you changed it to something else (in this case, I have “Kevin’s Band ec:5a”). If the status says “Connected,” you’re good to go; otherwise, tap Pair and follow the prompts.

Connecting Microsoft Band to a Windows 10 PC
Figure 2 Connecting Microsoft Band to a Windows 10 PC

Creating a Windows 10 App in Visual Studio

You can start with the sample app I created on GitHub (bit.ly/1U2sLup). Remember that if you decide to create your app from scratch, you need to include Bluetooth device capability in your manifest; Visual Studio by default doesn’t include this capability in the application template:

<Capabilities>
  <DeviceCapability Name="bluetooth" />
</Capabilities>

If you add the Band to your own app or create a Windows 10 app from scratch you’ll also need to get a Microsoft Band NuGet package. There are several packages out there, some created by Microsoft and some added by the community (the Xamarin.Microsoft.Band package, for example). For the purpose of the Universal Windows app, I added the Microsoft package, as shown in Figure 3.

Microsoft Band NuGet Packages
Figure 3 Microsoft Band NuGet Packages

The Microsoft Band SDK allows developers to access sensors on the Band, creating and updating tiles and personalizing the device. Your app can send notifications, including haptics, to the Band. The Band itself has a nice, clean and simple look to it, as shown in Figure 4.

Microsoft Band
Figure 4 Microsoft Band

The Band is packed with sensors (the full list can be seen in Figure 5); for the purpose of my Gravity Hero sample app, I focused on the Accelerometer sensor.

Figure 5 Sensors Available on the Microsoft Band

Sensor Details
Accelerometer Provides X, Y and Z acceleration in g units. 1 g = 9.81 meters per second squared (m/s2).
Gyroscope Provides X, Y and Z angular velocity in degrees per second (°/sec) units.
Distance Provides the total distance in centimeters, current speed in centimeters per second (cm/s), current pace in milliseconds per meter (ms/m), and the current  pedometer mode (such as walking or running).
Heart Rate

Provides the number of beats per minute; also indicates if the heart rate sensor is fully locked onto the wearer’s heart rate.

The data returned should be used only in resting mode. The Band SDK doesn’t provide access to the heart rate values optimized for any other activity.

Pedometer Provides the total number of steps the wearer has taken.
Skin Temperature Provides the current skin temperature of the wearer in degrees Celsius.
UV Provides the current ultraviolet radiation exposure intensity.
Band Contact Provides the current state of the Band as being worn/not worn.
Calories Provides the total number of calories the wearer has burned. 

Designing a Data Model

As always, I start with a data model in Visual Studio, as shown in Figure 6. A good data model always helps, as it separates data into a separate tier, which can be easily shared across your apps and even a cloud back end if you decide to have a Web site displaying your data. I want to make my data model flexible enough to collect data from sensors and present them in the Gravity Hero app. I can reuse my data model in other apps, so it’s worth placing it in a separate folder in my Visual Studio solution.

Visual Studio Solution with the Sample Project and Data Model
Figure 6 Visual Studio Solution with the Sample Project and Data Model

The data model for the Gravity Hero app is using a helper class conveniently called ViewModel. I can use a myriad of existing Model-View-ViewModel (MVVM) helper libraries, but in this example I simply implemented one to make the code as transparent as possible. The ViewModel class implements the INotifyPropertyChanged interface. This is a fairly standard approach in .NET apps when you want to reflect changes in your data model in the UI. In the implementation of my sample app, I’d like to make sure that the class notifies the UI via the PropertyChanged mechanism.

SensorReading is the class to catch Band sensor readings and notify anything in the UI that’s subscribed to the data model changes. Let’s look at this class more closely. The class derives from the ViewModel introduced earlier and also includes attributes that might be useful to serialize data and send it across the wire (to your cloud storage, for example). DataContract attribute on the SensorReading class does just that, and DataMember attributes on individual data members allow for data to be serialized, either into JSON or XML, depending on the serializer. Another advantage to the SensorReading class is that it provides a normalized form because the class holds a 3D vector reading or Vector3. As shown in Figure 7, I also provide a Value member that returns a normalized vector (a very useful thing when you deal with 3D calculations).

Figure 7 SensorReading Class for the Sensor Data Model

[DataContract]
public class SensorReading : ViewModel
{
  DateTimeOffset _timestamp;
  [DataMember]
  public DateTimeOffset Timestamp
  {
    get { return _timestamp; }
    set
    {
      SetValue(ref _timestamp, value, "Timestamp");
    }
  }
  double _x;
  [DataMember]
  public double X
  {
    get { return _x; }
    set
    {
      SetValue(ref _x, value, "X", "Value");
    }
  }
  double _y;
  [DataMember]
  public double Y
  {
    get { return _y; }
    set
    {
      SetValue(ref _y, value, "Y", "Value");
    }
  }
  double _z;
  [DataMember]
  public double Z
  {
    get { return _z; }
    set
    {
      SetValue(ref _z, value, "Z", "Value");
    }
  }
  public double Value
  {
    get
    {
      return Math.Sqrt(X * X + Y * Y + Z * Z);
    }
  }
}

BandModel is used to manage the Band, as shown in Figure 8. This is the manager class that helps in case I have multiple Band devices connected to my PC; it also can tell me if any Band is connected. 

Figure 8 BandModel for Managing the Bands

public class BandModel : ViewModel
{
  static IBandInfo _selectedBand;
  public static IBandInfo SelectedBand
  {
    get { return BandModel._selectedBand; }
    set { BandModel._selectedBand = value; }
  }
  private static IBandClient _bandClient;
  public static IBandClient BandClient
  {
    get { return _bandClient; }
    set
    {
      _bandClient = value;
    }
  }
  public static bool IsConnected
  {
    get {
      return BandClient != null;
    }
  }
  public static async Task FindDevicesAsync()
  {
    var bands = await BandClientManager.Instance.GetBandsAsync();
    if (bands != null && bands.Length > 0)
    {
      SelectedBand = bands[0]; // Take the first band
    }
  }
  public static async Task InitAsync()
  {
    try
    {
      if (IsConnected)
        return;
      await FindDevicesAsync();
      if (SelectedBand != null)
      {
        BandClient =
          await BandClientManager.Instance.ConnectAsync(SelectedBand);
        // Connected!
          BandModel.BandClient.NotificationManager.VibrateAsync(
            Microsoft.Band.Notifications.VibrationType.ExerciseRunLap);
      }
    }
    catch (Exception x)
    {
      Debug.WriteLine(x.Message);
    }
  }
}

AccelerometerModel is designed specifically for the Gravity Hero game. Gravity is the force that can effectively be measured by the built-in Accelerometer sensor in the Band. Now you see how the data model classes are created; you can add additional classes for any of the Band sensors you want to use in your apps. When I need to initialize the Accelerometer class in Init method, I subscribe to several events conveniently presented by the Band SDK:

if (BandModel.IsConnected)
  {
    BandModel.BandClient.SensorManager.
      Accelerometer.ReadingChanged +=
      Accelerometer_ReadingChanged;
    BandModel.BandClient.SensorManager.
      Accelerometer.ReportingInterval =
      TimeSpan.FromMilliseconds(16.0);
    BandModel.BandClient.SensorManager.
      Accelerometer.StartReadingsAsync(
      new CancellationToken());
    totalTime = 0.0;
  }

The first event is ReadingChanged. This is the event that gives me data from the accelerometer sensor based on the ReportingInterval time period that I define. For reading Accelerometer values, I use a 16 ms threshold. It’s important to keep the reporting interval as small as possible for precision, but at the same time consider that battery consumption increases with extensive use of the sensor. Next, I call StartReadings­Async, the method that starts reading values from the sensor and sends it back to the app. This method just starts a listener for sensor data readings. The data is passed to the ReadingChanged event.

In the ReadingChanged event I capture the reading and recalculate values in my data model:

void Accelerometer_ReadingChanged(object sender,
  BandSensorReadingEventArgs<IBandAccelerometerReading> e)
{
  SensorReading reading = new SensorReading {
    X = e.SensorReading.AccelerationX, Y = e.SensorReading.AccelerationY,
    Z = e.SensorReading.AccelerationZ };
  _prev = _last;
  _last = reading;
  Recalculate();
}

The Recalculate model method is where most of my logic happens (see Figure 9). I want to fire Changed event back to the app when I exceed values achieved earlier when I started the game. Remember, I implement a Gravity Hero game here, so I’m looking for the best results. I want to make sure that I use Dispatcher class, because Band sensor events may be triggered on non-UI threads, so I need to marshal the code to the UI thread for my Changed event.

Figure 9 The Recalculate Model Method

DateTimeOffset _startedTime = DateTimeOffset.MinValue;
double totalTime = 0.0;
double lastTime = 0.0;
SensorReading _prev;
SensorReading _last;
double MIN = 0.4;
void Recalculate()
{
  if (_last.Value <= MIN)
  {
    if (_startedTime > DateTimeOffset.MinValue)
      lastTime = (DateTimeOffset.Now - _startedTime).TotalSeconds;
    else
      _startedTime = DateTimeOffset.Now;
    }
    else
    {
      if (_startedTime > DateTimeOffset.MinValue)
      {
        lastTime = (DateTimeOffset.Now - _startedTime).TotalSeconds;
        totalTime += lastTime;
        lastTime = 0.0;
        _startedTime = DateTimeOffset.MinValue;       
          CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
          CoreDispatcherPriority.Normal,        () =>
        {
          if (Changed != null)
            Changed(_last.Value);
            });
        }
      }
    }
¡  } 
}

My UI needs to be updated when events come back from the Band (see Figure 10). This is done in the Changed event, which I subscribed to in my MainPage.xaml. I display G-force and count achievements. I also invoke the Band haptic feedback via the VibrateAsync method. As a Band user for many months, I really like the ability to send haptic notifications (just remember not to abuse it and notify users only when appropriate).

Figure 10 UI Updated in Changed Event

void _accelerometerModel_Changed(double force)
{
  bandCount++;
  UpdateCount();
  if (force > maxForce)
  {
    maxForce = force;
    heroText.Text = String.Format("Intensity {0:F2}G", maxForce);
  }
  if (!isAchievementUnlocked && bandCount >= maxCount*0.2)
  {
    Speak("Just a few more!");
    isAchievementUnlocked = true;
  }
  if (!isSecondAchievementUnlocked && isAchievementUnlocked &&
    bandCount >= maxCount * 0.8)
  {
    Speak("Almost there!");
    isAchievementUnlocked = true;
  }
    BandModel.BandClient.NotificationManager.VibrateAsync(
      Microsoft.Band.Notifications.VibrationType.ExerciseRunLap);
  // Speak(bandCount.ToString()+"!");
}

Let the Fun Begin

Now, with everything in place, let the fun begin. Build and launch the app: Remember, the app runs on any Windows 10 device. Because I’m using the Band sensors, I don’t care about PC or phone support for Accelerometers. I’ll be using a PC to display information from the Band, while the Band will be doing all the hard work.

As shown in Figure 11, when you launch the app for the first time whether from Visual Studio or from the tile, Windows 10 automatically prompts you to confirm that you want to grant Gravity Hero app access to the Band; just select Yes.

Windows 10 Dialog Automatically Requesting Access to the Band
Figure 11 Windows 10 Dialog Automatically Requesting Access to the Band

When Gravity Hero connects to the Band, you’ll feel the Band vibrate. This is done intentionally, to let you know that everything is set up for jumps. I also added audible prompts to notify you that you can start the action:

BandModel.BandClient.NotificationManager.VibrateAsync(
  Microsoft.Band.Notifications.VibrationType.ExerciseRunLap);

Now, keep jumping. The app will count your jumps and congratulate you on each achievement.

All sample code for this article is available on GitHub: bit.ly/1MIKIIK. To use this source you can use Visual Studio 2015 and Windows 10. The project uses the Microsoft Band SDK NuGet package.

Wrapping Up

Microsoft Band provides powerful SDKs and community support for multiple platforms—Windows, Android and iOS. Developers can use Microsoft SDKs and community components from Xamarin, GitHub and the developer community to extend apps to use Microsoft Band. You can use the code in this article to integrate Microsoft Band into your own apps for Windows 10.


Kevin Ashley is a senior game developer evangelist for Microsoft. He’s a co-author of “Professional Windows 8 Programming” (Wrox, 2012) and a developer of top apps and games, most notably Active Fitness, which has more than 2 million users (activefitness.co). He often presents on technology at various events, industry shows and Web casts. In his role, he works with startups and partners, advising on software design, business and technology strategy, architecture, and development. You can follow Ashley on his blog at kevinashley.com and on Twitter @kashleytwit.

Thanks to the following Microsoft technical expert for reviewing this article: Jaime Rodriguez