DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 967,611 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Interacting with Polar Verity Sense using Web Bluetooth

Interacting with Polar Verity Sense using Web Bluetooth

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 to connect to a standards compliant BLE device.

While our discussion applies to any standards compliant BLE device, the example focuses on Polar Verity Sense, Heart Rate Monitoring, and Device Battery Level Monitoring. Polar, among other things, is a top manufacturer of heart rate sensors.


Steps:

  • Request device connection using navigator.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:

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

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 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

Moving further, it is an API quirk that acceptAllDevices must not be true if filters are defined. Please go through the TypeError 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.
Enter fullscreen mode Exit fullscreen mode

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 services are specified: 0x180d, 0x180f. If you are interested in allowing other services or knowing the codes for other services, this document should greatly help. If you don't know which services your device supports, you can also obtain a list of all the available services in your device.


  • Once you have access to the BluetoothDevice object, you can initiate a connection to the device's GATT server via the following.
const gattServer = await device.gatt?.connect();
Enter fullscreen mode Exit fullscreen mode

MDN: 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 via:
  const heartRateService = await gattServer?.getPrimaryService(0x180d);
  const batteryLevelService = await gattServer?.getPrimaryService(0x180f);
Enter fullscreen mode Exit fullscreen mode
  • 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. Now, we want to obtain the heart rate and battery level characteristics from the respective services:
  const heartRate = await heartRateService?.getCharacteristic(0x2a37);
  const batteryLevel = await batteryLevelService?.getCharacteristic(0x2a19);
Enter fullscreen mode Exit fullscreen mode

0x2a37 and 0x2a19 are the BluetoothCharacteristicUUIDs which can be obtained from this document. Similar to services, you can also discover a list of characteristics 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:
heartRate.addEventListener("characteristicvaluechanged", () => { ... }
batteryLevel.addEventListener("characteristicvaluechanged", () => { ... }
Enter fullscreen mode Exit fullscreen mode
  • 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:
await heartRate.startNotifications();
await batteryLevel.startNotifications();
Enter fullscreen mode Exit fullscreen mode
  • Fortunately, we also have the option to read any characteristics on-demand via:
const batteryData = await batteryLevel.readValue();
const heartData = await heartRate.readValue();
Enter fullscreen mode Exit fullscreen mode
  • Now, the more interesting part arrives. The data/characteristic's values that we get from the device is in binary format and is exposed via 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:

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);
}
Enter fullscreen mode Exit fullscreen mode
  • If you encounter a different characteristic in your use case, you can derive the parsing logic yourself by going through the respective service specifications.

  • 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 for deeper dive into the subject.
  2. Web Bluetooth Samples are live samples that can help you rapidly test your BLE devices without any coding/initial setup.
  3. Bluetooth Generic Attribute Profile presents a good primer on the terms like "server", "service", "attributes", "characteristics", etc. in the BLE context.

Top comments (1)

Need a better mental model for async/await?

Check out this classic DEV post on the subject.

β­οΈπŸŽ€ JavaScript Visualized: Promises & Async/Await

async await