Interacting with Polar Verity Sense using Web Bluetooth
Tags: javascript, webdev, bluetooth, programming
Published: 2022-09-18 10:03:21

> How can I connect a Bluetooth device to my web application?

If you are looking for an answer to the above question, read on. More specifically, we'll try to decipher how can you use the [Web Bluetooth API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Bluetooth_API) to connect to a [standards](https://www.bluetooth.com/specifications/specs/) compliant BLE device.

While our discussion applies to any standards compliant BLE device, the example focuses on [Polar Verity Sense](https://www.polar.com/us-en/products/accessories/polar-verity-sense), Heart Rate Monitoring, and Device Battery Level Monitoring. [Polar](https://www.polar.com/en/about_polar/who_we_are/), among other things, is a top manufacturer of heart rate sensors.

---

#### Steps:

- Request device connection using [`navigator.bluetooth.requestDevice`](https://developer.mozilla.org/en-US/docs/Web/API/Bluetooth/requestDevice). 
  - The method allows you to **filter** the available devices present in your vicinity. 
  - This is good because we can utilize this filter to showcase only those devices to the end user that are relevant to the web app. 
  - For instance, if our app is focused solely on connecting to Polar Verity Sense devices, we can do:

---

```ts
  const device = await navigator.bluetooth.requestDevice({
      filters: [
        {
          namePrefix: "Polar Sense",
          manufacturerData: [{ companyIdentifier: 0x006b }],
        },
      ],
      acceptAllDevices: false,
      optionalServices: [0x180d, 0x180f]
    });
```

---

Here, `0x006b` is a unique identifier assigned by the Bluetooth Special Interest Group (SIG) specifically to the **Polar Electro OY** company. If you are working with devices by some other manufacturers, this [list](https://www.bluetooth.com/specifications/assigned-numbers/company-identifiers/) can come in handy.

One manufacturer can have multiple devices/products in the market. For example: Polar Verity Sense and Polar H10. 

If we want to further filter down on the devices, the `namePrefix` can help achieve that. In our case, our focus was `Polar Verity Sense` and all such devices show up in the _available BLE devices list_ as `Polar Sense XXXXXX`. Hence, the `namePrefix` of `Polar Sense` was used.

Note: The _available BLE devices list_ shows up as soon as your fire `navigator.bluetooth.requestDevice` method. From the list, you can then select the device you want to connect to. Here's how it looks.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/otb6gkb4sadpyj5x8kkc.png)

Moving further, it is an API quirk that `acceptAllDevices` must not be `true` if `filters` are defined. Please go through the `TypeError` [exceptions](https://developer.mozilla.org/en-US/docs/Web/API/Bluetooth/requestDevice#exceptions) to dig more.

You may encounter an error like this:

```
Origin is not allowed to access any service. Tip: Add the service UUID to 'optionalServices' in requestDevice() options.
```

To tackle this, `optionalServices` property can be defined as well. Since, we only care about heart rate and device battery level monitoring, only the corresponding [GATT](https://www.bluetooth.com/bluetooth-resources/intro-to-bluetooth-gap-gatt/) services are specified: `0x180d, 0x180f`. If you are interested in allowing other services or knowing the codes for other services, this [document](https://btprodspecificationrefs.blob.core.windows.net/assigned-values/16-bit%20UUID%20Numbers%20Document.pdf) should greatly help. If you don't know which services your device supports, you can also obtain a list of all [the available services](https://developer.mozilla.org/en-US/docs/Web/API/BluetoothRemoteGATTServer/getPrimaryServices) in your device.

---

- Once you have access to the [`BluetoothDevice`](https://developer.mozilla.org/en-US/docs/Web/API/BluetoothDevice) object, you can initiate a connection to the device's [GATT server](https://developer.mozilla.org/en-US/docs/Web/API/BluetoothRemoteGATTServer) via the following.

```ts
const gattServer = await device.gatt?.connect();
```

> [MDN](https://developer.mozilla.org/en-US/docs/Web/API/BluetoothRemoteGATTServer): The BluetoothDevice.gatt read-only property returns a reference to the device's BluetoothRemoteGATTServer.

- After the GATT server is connected to, you can access the concerned [services](https://developer.mozilla.org/en-US/docs/Web/API/BluetoothRemoteGATTService) via:

```ts
  const heartRateService = await gattServer?.getPrimaryService(0x180d);
  const batteryLevelService = await gattServer?.getPrimaryService(0x180f);
```

- A "service" is simply a collection of attributes that we may be interested in. The attributes which holds the value of the property of interest are termed as [characteristics](https://developer.mozilla.org/en-US/docs/Web/API/BluetoothRemoteGATTCharacteristic). Now, we want to obtain the heart rate and battery level characteristics from the respective services:

```ts
  const heartRate = await heartRateService?.getCharacteristic(0x2a37);
  const batteryLevel = await batteryLevelService?.getCharacteristic(0x2a19);
```

---

`0x2a37` and `0x2a19` are the BluetoothCharacteristicUUIDs which can be obtained from this [document](https://btprodspecificationrefs.blob.core.windows.net/assigned-values/16-bit%20UUID%20Numbers%20Document.pdf). Similar to services, you can also discover a [list of characteristics](https://developer.mozilla.org/en-US/docs/Web/API/BluetoothRemoteGATTService/getCharacteristics) contained by your service of interest.

---

- At this stage, all the necessary connections are established and all the required object references are obtained. Now, we simply need to start _listening_ to the changes in these "charateristics". The API is rather simple here:

```ts
heartRate.addEventListener("characteristicvaluechanged", () => { ... }
batteryLevel.addEventListener("characteristicvaluechanged", () => { ... }
```

- The above snippet simply start listening to the "changes" in characteristics of interest. We also need to tell the device to regularly publish its data to our web app as follows:

```ts
await heartRate.startNotifications();
await batteryLevel.startNotifications();
```

- Fortunately, we also have the option to read any characteristics [on-demand](https://developer.mozilla.org/en-US/docs/Web/API/BluetoothRemoteGATTCharacteristic/readValue) via:

```ts
const batteryData = await batteryLevel.readValue();
const heartData = await heartRate.readValue();
```

- Now, the more interesting part arrives. The data/[characteristic's values](https://developer.mozilla.org/en-US/docs/Web/API/BluetoothRemoteGATTCharacteristic/value) that we get from the device is in binary format and is exposed via [DataView](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView). As a result, we need to parse them in a certain way to make them inferable. Each characteristic can pack its data in certain way. Hence, as the characteristic's type changes, the parsing logic may also need to be changed.

- The parsing logic for heart rate and battery level characteristics are:

```ts
function parseHeartRate(input: DataView): number {
  const dataFlag = input.getUint8(0);
  let heartRate = NaN;
  if (dataFlag === 0) {
    heartRate = input.getUint8(1);
  } else {
    heartRate = input.getUint16(0);
  }
  return heartRate;
}

function parseBatteryLevel(input: DataView): number {
  return input.getUint8(0);
}
```

- If you encounter a different characteristic in your use case, you can derive the parsing logic yourself by going through the respective [service specifications](https://www.bluetooth.com/specifications/specs/). 

- Once you finally have the data in the desired form/type, you enter into a realm of endless possibilities wherein you can your data can behave the way your business logic demands.

---

Parting Notes:

1. We strongly recommend going through [Communicating with Bluetooth devices over JavaScript](https://web.dev/bluetooth/) for deeper dive into the subject.
2. [Web Bluetooth Samples](https://googlechrome.github.io/samples/web-bluetooth/) are live samples that can help you rapidly test your BLE devices without any coding/initial setup.
3. [Bluetooth Generic Attribute Profile](https://www.bluetooth.com/bluetooth-resources/intro-to-bluetooth-gap-gatt/) presents a good primer on the terms like "server", "service", "attributes", "characteristics", etc. in the BLE context.