TECH

DEVELOPMENT

Bluetooth Web API Guide Based on Our Experience With BLE Device Connection

Updated: {{date}}

{{time}} min read

Contents

Summarize this article with AI

As we live in a technologically advanced world, BLE is essential for connecting a wide range of smart gadgets, from health and fitness wearables to home automation systems. Bluetooth technology has advanced further, and now you can connect and manage your BLE devices not only using your phones but also web browsers. If you want to get insights about Web BLE implementation, read the comprehensive guide based on our extensive experience with BLE device connections.

Join us as we explore the BLE and Web Bluetooth world, and learn how to harness these powerful technologies to create innovative, connected web applications. Whether your business is just beginning to explore BLE connectivity or has already implemented it, this guide offers valuable insights for leveraging the Web Bluetooth API to enhance your products and services.

πŸ” Overview of Key Features, Benefits, and Differences of Bluetooth Low Energy

Let’s start with the answer to the common question: what is Bluetooth Low Energy (BLE)? BLE is a wireless communication technology designed for short-range, low-power data transfer. It’s part of the Bluetooth 4.0 specification and is optimized for devices that need to run on small batteries for extended periods, like fitness trackers, smartwatches, and other IoT devices.

BLE Features

Bluetooth Low Energy offers several unique features that make it a good choice for modern applications, such as when you want to create your own fitness app. These features, integral to IoT software development services, are designed to provide efficient performance while conserving power, ensuring reliable and secure communication.

BLE is essential for IoT software development, offering scalability and low power usage. But how much does it cost to develop an app like PlugShare? when integrating BLE functionality into an EV charging station finder app? Check out in our blog!

Benefits of the BLE

The BLE integration brings numerous benefits to both businesses and end-users. These advantages highlight why BLE is a preferred choice for a wide range of applications, from consumer electronics to industrial devices.

Since you know the benefits and capabilities of BLE technology, you may be interested in how to build a BLE app:

Bluetooth and BLE Difference

Bluetooth Classic and BLE, though part of the same family, serve different purposes. Traditional Bluetooth is designed for continuous, streaming data transfer, making it ideal for applications like audio streaming or file transfers.

In contrast, BLE is optimized for low-power, intermittent data transfer, making it ideal for devices such as health monitors and smart home devices. Additionally, modern interactions with BLE devices are facilitated by the Web Bluetooth API.

πŸ“Œ Check out our guide on how to develop a smart home app and integrate these technologies into a seamless user experience.

According to the Bluetooth Special Interest Group (SIG) 2024 Market Report, Bluetooth and BLE will continue to have a significant impact on technological advancement. Let’s take a look at the numbers:

  • By 2028, annual shipments of Bluetooth-enabled devices are forecasted to reach 7.5 billion, with an 8% compound annual growth rate (CAGR).
  • In 2024, 1.8 billion Bluetooth LE single-mode devices are expected to ship, with annual shipments projected to double in the next five years.
  • Nearly all new smartphones, tablets, and laptops support dual-mode (Bluetooth Classic + BLE).
  • 3.5 billion Bluetooth peripheral devices are expected to ship in 2024, growing to 5.5 billion by 2028 with a CAGR of 12%.

For a detailed comparison, use cases, and statistical insights, you can have a quick look at our Bluetooth vs BLE article. There you will find comprehensive information on how BLE differentiates itself from traditional Bluetooth in terms of technology, application, and performance metrics.

Let’s summarize this section:

  1. BLE is a key technology for modern wireless communication, especially for devices needing low power consumption and efficient data transfer.
  2. Its features like low power use, efficient data transfer, scalability, fast connection, and robust security make it essential for IoT devices.
  3. Benefits such as broad compatibility, long battery life, cost-effectiveness, flexibility, and enhanced security highlight its widespread use and future potential.
  4. Traditional Bluetooth is ideal for continuous data transfer, while BLE is optimized for intermittent data, making it perfect for low-power devices. The projected growth in Bluetooth and BLE device shipments underscores their importance in advancing technology.

πŸ“˜ Introducing Web Bluetooth

Building on the foundation of BLE technology, the Bluetooth Web API represents a significant advancement by allowing web applications to connect and interact with BLE devices directly from the browser. Integrating ANT+ and BLE capabilities alongside Web Bluetooth can enhance interoperability for devices catering to health, fitness, and IoT applications.

This powerful and emerging API bridges the gap between web and hardware, enabling developers to create seamless, real-time experiences without the need for native apps. Let’s explore it in more detail.

What is the Web Bluetooth API?

The Web browser Bluetooth API was created to enable developers to connect to and interact with BLE devices (also known as Bluetooth 4.0). As it is considered an experimental technology, browser support is currently limited. Additionally, there is no official World Wide Web Consortium (W3C) Standard for the Web Bluetooth API. However, you can explore the available documentation and examples on the W3C Community Group website.

Today, the Web Bluetooth API provides a means for web developers to discover and communicate with Bluetooth devices. This API is particularly beneficial in fields such as health and fitness, home automation, and industrial IoT. By leveraging the Web Bluetooth API, web applications can connect to heart rate monitors, smart home devices, industrial sensors, and more, allowing for real-time data exchange and control.

Let’s take a look at some Web BLE examples.

In health and fitness, developers can create web apps that monitor vital signs using BLE-enabled health devices. In home automation, the API can be used to control smart lights, thermostats, and security systems. For industrial IoT, Web Bluetooth enables the monitoring and management of machinery and sensors directly from a web browser.

You can also refer to Google's official documentation for more details on the capabilities and use cases of the Web Bluetooth API.

Browser Compatibility

One of the significant advantages of Web Bluetooth is its cross-browser compatibility, ensuring that a broad range of users can access BLE-enabled web apps regardless of their preferred platform. Additionally, the Web Bluetooth API enables experimental web platform features, allowing developers to explore new possibilities and enhance user experiences. The API is supported by major browsers, making it accessible to a wide audience:

  • Google Chrome. Web Bluetooth is fully supported on both Desktop and Android versions of Chrome, making it a versatile choice for developers targeting a broad user base. Chrome's widespread usage and consistent update cycle ensure that users have access to the latest BLE Web API features and improvements.
  • Microsoft Edge. The support for Web Bluetooth on both Desktop and Android versions of Microsoft Edge provides another robust option for developers. Edge's compatibility ensures that users on Windows and other platforms can leverage BLE functionalities in their web applications.
  • Opera. Like Chrome and Edge, Opera supports Web Bluetooth on both Desktop and Android. This adds another layer of cross-platform accessibility, especially for users who prefer this browser.
  • Mozilla Firefox. There is ongoing discussion and interest within the Mozilla community about the benefits of Web Bluetooth API. As for now, Firefox partially supports Web Bluetooth.

Did you know that Google Chrome is the most widely used browser in the world? According to StatCounter in 2024, Chrome has a 65.68% market share, followed by Safari with a 17.96% share.

Despite its growing adoption, Web Bluetooth isn’t universally supported across all browsers. Notable browsers that don’t currently support the Web Bluetooth API include:

  • Apple Safari. Both the desktop and mobile versions of Safari don’t support Web Bluetooth. This is primarily due to Apple's strict security and privacy guidelines.
  • Internet Explorer. Given its deprecated status and lack of support for many modern web standards, Internet Explorer doesn’t support Web Bluetooth.

While most of the browsers offer solid support for Web Bluetooth, it's important to remember that the technology is still developing. This means that some features may vary slightly or be in different stages of implementation across browsers. Developers should keep an eye on browser updates and community feedback to ensure compatibility and take advantage of new Web Bluetooth demo features as they become available.

Advantages and Disadvantages of Web Bluetooth for Businesses

While Web Bluetooth implementation presents numerous advantages, it also has some notable weaknesses that developers and businesses should consider.

To sum up, Web Bluetooth is a groundbreaking technology that builds on the foundation of BLE, enabling web applications to connect and interact with BLE devices directly from the browser. Despite its current limitations, the Web BLE API promises a future where seamless, real-time interactions with BLE devices are an integral part of web applications, driving innovation and connectivity in various industries.

Looking for a technical partner to integrate Web Bluetooth API into your product? Contact us to discuss how we can bring your vision to life!

Contact Us

πŸ“‹ BLE Design and Implementation

You’re probably eager to move from theory to practice, namely to the guide on how to connect Web Bluetooth API. However, before doing so, we should discuss designing and implementing BLE systems, as the implementation of the Web Bluetooth API requires a deep understanding of its core principles, effective integration strategies, and the implications of its operational bandwidth.

When developing cross-platform solutions, understanding how Android BLE connect functionality works alongside Web Bluetooth can ensure seamless interactions across devices.

Principles of BLE Design

Key elements of BLE design include the roles of central and peripheral devices, the Generic Access Profile (GAP), the Generic Attribute Profile (GATT), services, characteristics, descriptors, and Universally Unique Identifier (UUID). Let’s discuss their roles in the BLE device structure.

  • Central and Peripheral Roles. In BLE, devices can operate in two primary roles: central and peripheral. The central device, often a smartphone or computer, initiates and manages the connection. The peripheral device, such as a fitness tracker or sensor, broadcasts data and responds to the central device’s requests.
  • GAP and GATT. GAP manages the device discovery and connection process. It defines how BLE devices advertise themselves and connect, ensuring smooth and secure interactions. GATT server defines how data is structured and transferred between BLE devices. It uses a hierarchy of services and characteristics, identified by unique UUIDs to facilitate organized and efficient data exchange.
  • Services. They organize data into blocks, known as Characteristics, that are essential for delivering a specific service. For instance, the Fitness Tracking Server features two primary services: the Heart Rate Service and the Activity Monitoring Service.
  • Characteristics. They serve as containers for data points and their values. In the Heart Rate Service, characteristics include Current Heart Rate, Average Heart Rate, and Maximum Heart Rate. In the Activity Monitoring Service, characteristics encompass Total Steps, Distance Traveled, and Calories Burned.
  • Descriptors. They provide additional details about characteristics and their values.
  • UUID. UUIDs are critical in BLE design, serving as unique identifiers for services and characteristics within the GATT structure. They ensure that data is accurately categorized and accessed across different devices and applications.

Implementing BLE in Devices

Integrating BLE into devices involves both hardware and software components. This integration must be carefully planned and executed to ensure optimal performance and reliability, both of which are essential for managing IoT project cost effectively.

  • Hardware Integration. This includes the selection and placement of BLE modules and antennas. The physical design must minimize interference and maximize signal strength to ensure stable connectivity.
  • Software Development. Developing firmware and software to manage BLE communication involves configuring GATT services and characteristics, handling connection events, and ensuring efficient power management. Implementing power-saving features, such as sleep modes, is crucial for extending battery life in BLE devices.

If you want to know how to integrate BLE devices into your React Native, you can read our article on this topic:

BLE's Operational Bandwidth (OBW) Explained

OBW refers to the range of frequencies within which a BLE device operates effectively. BLE operates in the 2.4 GHz ISM band, divided into 40 channels of 2 MHz each.

OBW impacts several performance aspects of BLE devices:

  • Data Throughput. A wider OBW can enhance data transfer rates by accommodating more simultaneous connections and larger data packets.
  • Interference Management. Efficient use of OBW helps in reducing interference from other wireless devices, ensuring stable and reliable connections.
  • Energy Consumption. Optimizing OBW usage can lead to significant energy savings, extending the battery life of BLE devices.

Understanding and optimizing OBW is essential for achieving the desired balance between performance and power efficiency in BLE devices.

By understanding these principles and implementation strategies, developers can build robust, efficient, and secure BLE applications. Mastering these foundational insights is essential for fully harnessing the capabilities of BLE technology in Web Bluetooth applications.

πŸ› οΈ Web BLE Integration for Heart Rate Monitor

After revising the knowledge about BLE and discussing its design and implementation, we can demonstrate how to build a web app using the example of connecting a heart rate monitor to a patient’s web page at a clinic.
Our React Native Developer, Dmytro Zasukha, will guide you on this journey, showcasing various web application development services.

BLE Device Specifications

Let’s start with the technical overview of the Web Bluetooth device info example.

Request Bluetooth Devices

The first step in using Web BLE API is to request Bluetooth devices. In JavaScript, we can achieve this by using the navigator.bluetooth.requestDevice function. This function allows your website to communicate with Bluetooth devices.

In the script below, we’re requesting heart rate monitor devices available around. The 'services' filter specifies the GATT services we're interested in, and we’re using the 'heart_rate' service which is a standard for heart rate monitors.

The requestDevice function is wrapped in a promise and it returns a promise. When the promise resolves, it carries a BluetoothDevice object that has metadata we’re interested in. For instance, device.name will give you the name of the device, while device.id will provide you with the UUID of that device.

As for error handling, it’s important to catch the errors that may occur during the requestDevice call. This can be done by chaining a .catch function to the promise. The catch block will handle any potential errors.

// First specify permission options
let options = {
  filters: [
    {services: ['heart_rate']},
  ]
}

// Then request devices based on the above options
navigator.bluetooth.requestDevice(options)
.then(device => {
  console.log(device.name);
  console.log(device.id);
})
.catch(error => { console.log(error); });

Connecting to BLE Device and Search Services and Characteristics

One of the key points in working with BLE devices is connecting to the device and dealing with its services and characteristics. Here we extend the previous code to include a Web Bluetooth server example.

So you've requested a device and got a BluetoothDevice object. Then, you should connect to the device's GATT server through the device.gatt.connect() call. This returns a promise with a BluetoothRemoteGATTServer object.

Next, you request the specific service you're interested in, which in our case is 'heart_rate'. You do this by calling getPrimaryService() on the connection to our BLE device, for example Web BLE server.

After that, you call getCharacteristic('heart_rate_measurement') on the service. This method returns a characteristic object which represents a piece of data provided by the BLE device. The 'heart_rate_measurement' is a standard characteristic in BLE heart rate monitors; it provides heart rate measurement.

We use the readValue() method to read the current value of the characteristic. This returns a promise that resolves with a DataView. In our case, the second byte in the DataView is the heart rate measurement we're interested in.

let device, server;
// Request the device
navigator.bluetooth.requestDevice({
  filters: [{ services: ['heart_rate'] }]
})
.then(selectedDevice => {
  device = selectedDevice;
  // Connect to the device GATT Server
  return device.gatt.connect();
})
.then(selectedServer => {
  server = selectedServer;
  // Get the Heart Rate Service
  return server.getPrimaryService('heart_rate');
})
.then(service => {
  // Get the Heart Rate Measurement Characteristic
  return service.getCharacteristic('heart_rate_measurement');
})
.then(characteristic => {
  // Use the Characteristic
  return characteristic.readValue();
})
.then(value => {
  console.log('Heart rate is: ' + value.getUint8(1));
})
.catch(error => { console.log(error); });

Handle Characteristic Change

Once a connection to a characteristic (in our case, the heart rate measurement characteristic) is established, we can set up an event listener to handle the characteristicvaluechanged event. This event occurs whenever the characteristic's value changes, which in our example is when a new heart rate measurement is received.

To receive these changes, it's vital to call startNotifications() method on the characteristic.

In the event handler handleHeartRateMeasurement(), we simply print the new heart rate measurement. In a full-fledged application, you could do more with this information β€” for example, displaying it in a user interface, or saving it for later analysis.

let heartRateMeasurementCharacteristic;
// previous connection code
// ...
.then(characteristic => {
  heartRateMeasurementCharacteristic = characteristic;
  // set up a listener for when the characteristic changes
  heartRateMeasurementCharacteristic.addEventListener('characteristicvaluechanged', handleHeartRateMeasurement);
  // start notifications
  return heartRateMeasurementCharacteristic.startNotifications();
})
// ...
.catch(error => { console.log(error); });

function handleHeartRateMeasurement(event) {
  // get the value from the event
  const value = event.target.value;
  console.log('New heart rate measurement: ' + value.getUint8(1));
}

Write on Characteristics

Writing on a characteristic involves finding the appropriate characteristic and then writing a value to it. In many BLE devices on the Web, certain functions can be controlled by writing to their associated characteristic. Here, we're demonstrating how to reset the heart rate measurement by writing to the Heart Rate Control Point Characteristic.

The writing is done via the writeValue method of the BluetoothRemoteGATTCharacteristic object. Values being written must be of type ArrayBuffer or TypedArray; in this scenario, we used Uint8Array.

One thing to point out is that writeValue also returns a promise. When it resolves, it means the write operation is successful, but if it doesn't, that means the operation failed, and an error will be logged to the console. As always, remember to handle errors correctly in your app.

let controlPointCharacteristic;
// previous connection code
// ...
.then(service => {
  // Get the Heart Rate Control Point Characteristic
  return service.getCharacteristic('heart_rate_control_point');
})
.then(characteristic => {
  controlPointCharacteristic = characteristic;
})
// ...

function resetHeartRateMeasurement() {
  let resetValue = Uint8Array.of(1);
  controlPointCharacteristic.writeValue(resetValue)
  .then(_ => {
  console.log('Heart Rate Measurement reset successful');
  })
  .catch(error => {
    console.log('Failed to reset Heart Rate Measurement');
    console.error(error);
  });
}

Read and Write to Bluetooth Descriptors

Reading the Measurement Interval descriptor provides us with the current interval at which the Health Thermometer is taking temperature measurements, expressed in seconds. We're using readValue again to get the current value of this descriptor.

Setting a new interval is done via the writeValue function on the BluetoothDescriptor object. It’s important to note that the value is an array of 16-bit integers (Uint16Array). This value variable is an array that only contains the new interval value to be written.

let measurementIntervalDescriptor;
// previous connection code
// ...
.then(service => {
  // Get the Health Thermometer Service
  return server.getPrimaryService('health_thermometer');
})
.then(service => {
  // Get the Temperature Measurement Characteristic
  return service.getCharacteristic('temperature_measurement');
})
.then(characteristic => {
  // Get the Measurement Interval Descriptor
  return characteristic.getDescriptor('gatt.characteristic_user_description');
})
.then(descriptor => {
  measurementIntervalDescriptor = descriptor;  
  // Read Descriptor
  return descriptor.readValue();
})
.then(value => {
  console.log('Measurement Interval: ' + value.getUint16(0));
})
// ...
// Function to set measurement interval
function setMeasurementInterval(interval) {
    let val = new Uint16Array([interval]);
    measurementIntervalDescriptor.writeValue(val)
    .then(() => {
        console.log('Measurement Interval set to ' + interval);
    })
    .catch(error => {
        console.log('Failed to set Measurement Interval');
        console.error(error);
    });
}

Assigning Events to Buttons

Now, we have two buttons for the Web browser Bluetooth API: one to connect to the heart rate monitor and another to reset it. We use the addEventListener method to attach 'click' event listeners to these buttons.

As a security feature, discovering Bluetooth devices with navigator.bluetooth.requestDevice must be triggered by a user gesture such as a touch or a mouse click. We're talking about listening to pointerup, click, and touchend events.

The ’Connect to HeartRate Monitor' button initiates the Bluetooth device request and subsequent connection when clicked. It also enables the 'Reset HeartRate Monitor' button after a successful connection since we can only reset the heart rate monitor after establishing a connection.

The 'Reset HeartRate Monitor' button invokes the resetHeartRateMeasurement function to send a reset command to the heart rate monitor. Note that at the beginning, this button is disabled. It only becomes enabled after a successful connection.

<!-- In Your HTML Body -->
<button id="connect-btn">Connect to HeartRate Monitor</button>
<button id="reset-btn" disabled>Reset HeartRate Monitor</button>

<!-- Your Existing JavaScript Code -->
// Global variables...
//...
document.getElementById('connect-btn').addEventListener('click', function() {
  // Request the device...
  navigator.bluetooth.requestDevice({
    filters: [{ services: ['heart_rate'] }]
  })  
  //...
  .then(service => {
    // Enable reset button
    document.getElementById('reset-btn').disabled = false;
  })
  .catch(error => { console.log(error); });
});
document.getElementById('reset-btn').addEventListener('click', resetHeartRateMeasurement);

Automatic Reconnection

During this step, we should define a connect function, which is the previous code used to connect to the device. This function can be called multiple times to reconnect to the BLE devices on the Web when needed.

We add an event listener for the 'gattserverdisconnected' event. The event listener function, onDisconnected, will be called whenever the device disconnects. Inside this function, we check a global flag, autoReconnect, and if it's set to true, initiate a reconnection by calling our connect function.

The autoReconnect variable provides an option to control whether to retry the connection on disconnect. It's set to true initially, allowing for automatic reconnection. But in some circumstances, you may wish to stop attempting to reconnect, and in such cases, this variable can be set to false.

It's essential to handle disconnections as they are quite common in real-world scenarios. This could be due to the device going out-of-range, being powered off, or low battery levels. With an automatic reconnection mechanism in place, your Web application Bluetooth will be more robust and provide a better user experience.

let device, server;
let autoReconnect = true;
// previous code ...

function connect() {
  // Request the device...
  navigator.bluetooth.requestDevice({
    filters: [{ services: ['heart_rate'] }]
  })
  // ... existing chained methods ...
  .catch(error => {
    console.log('Failed to reconnect: ', error);
    if(autoReconnect) {
      connect();
    }
  });
}

device.addEventListener('gattserverdisconnected', onDisconnected);

function onDisconnected(event) {
  let device = event.target;
  console.log('Device ' + device.name + ' is disconnected.');
  if(autoReconnect) {
    connect();
  }
}

// initial connection
connect();

Manual Disconnection from the Device

Here we add an event listener to a button with id 'disconnect-btn'. When this button is clicked, we check if the device is not null and is connected, using the device.gatt.connected property.

If the device is connected, the BLE Web API provides a BluetoothRemoteGATTServer.disconnect method, which can be called to manually disconnect from the device. This can be particularly useful when the connection is no longer needed.

In scenarios where user-triggered disconnections are probable, like ending a monitoring session, it's a good practice to allow manual disconnections to save on resources and battery usage for both the BLE device and the website's host device.

let device, server;
// previous code...

document.getElementById('disconnect-btn').addEventListener('click', function() {
  if (device && device.gatt.connected) {
    device.gatt.disconnect();
    console.log('Device disconnected');
  } else {
    console.log('No device connected');
  }
});

By following this guide on integrating BLE devices with web applications using Web Bluetooth and leveraging BLE app development services, you can effectively build and manage connections to BLE devices, ensuring a robust and interactive user experience.

βš™οΈ How to Create the Web BLE App

Now, let’s discuss how to create the Web BLE app using our Web Bluetooth API example.

Concept

The concept for the Web BLE app revolves around providing a minimal and straightforward interface for interacting with a BLE device, in our case, a heart rate monitor.

On the functionality front, the app uses Web Bluetooth API to interact with the BLE device. It effectively handles the complete flow of pairing and connecting to the device.

  1. Searching for Devices. On clicking the 'Search for BLE Device', the app triggers the browser's native BLE device picker. Users can see a list of available devices and select one.
  2. Connecting to Devices. Once a device is selected, the 'Connect to BLE Device' button becomes active. Clicking this connect button will attempt a connection to the chosen device.
  3. Displaying Device State. The app will display updates on the device state below the action buttons, providing interactive feedback on whether a device is found and the success of the connection attempt.

Overall, the app delivers a simple yet effective interface to interact with a BLE device, abstracting away the underlying complexities.

UI

The simplicity of the app's user interface is a key element of the design (making it well-suited for kiosk application development, where users expect clear, browser-based controls). It includes two action buttons: one for searching for a BLE device and another for connecting to the selected device. A text area below the buttons displays the state of the device β€” whether one is found and if it's connected.

The modern and clean design focuses on usability and clarity. Each button triggers a specific action and provides immediate feedback to the user, either by enabling another action or by updating the device information displayed.

The design of the buttons is influenced by the primary Bootstrap button style and provides an aesthetic, uncluttered experience. The app's presentation is responsive and should adapt well to various viewport sizes, from desktop to mobile screens.

HTML Page (DOM Elements)

Let’s discuss Document Object Mode (DOM) elements in more detail. They represent the structure and content of a web document as a set of objects, providing a way to interact with and manipulate the document's elements.

Clicking the 'Search for BLE Device' button fires the searchDevice function, which prompts the user to select a BLE device to pair with. The selected device name is displayed and the "Connect to BLE Device" button is enabled.

Clicking the 'Connect to BLE Device' button fires the connectDevice function, which connects to the selected BLE device and displays a message indicating the successful connection. If no device is found, an error message is displayed.

This design is simple and offers a clear user flow for BLE device interaction. It's also a fantastic starting point for building more complex Web BLE implementation and adding in additional functionality according to your requirements.

<!DOCTYPE html>
<html>
<body>

<h1>BLE Device Interaction</h1>

<button id="search-btn">Search for BLE Device</button>
<button id="connect-btn" disabled>Connect to BLE Device</button>
<p id="device-info">No device connected.</p>

<script>
let device, server;

async function searchDevice() {
  try {
    device = await navigator.bluetooth.requestDevice({
      filters: [{services: ['heart_rate']}],
    });
    document.getElementById('device-info').innerText = `Device found: ${device.name}`;
    document.getElementById('connect-btn').disabled = false;
  } catch (error) {
    console.error(error);
  }
}

async function connectDevice() {
  if (!device) {
    return;
  }
  try {
   server = await device.gatt.connect();
    document.getElementById('device-info').innerText = `Connected to ${device.name}`;
  } catch (error) {
    console.error(error);
  }
}

document.getElementById('search-btn').addEventListener('click', searchDevice);
document.getElementById('connect-btn').addEventListener('click', connectDevice);
</script>

</body>
</html>

Ready to enhance your product with the Web Bluetooth API integration? Contact us today to start building your groundbreaking app!

Contact Us

πŸ“Š Testing the Web BLE App

It’s time to test our Web BLE app. You can utilize 'nRF Connect for Mobile,' which is a powerful, generic tool that allows you to scan, advertise, and explore your Bluetooth Low Energy devices and communicate with them.

Here are the broad steps to simulate our device:

  1. Install nRF Connect for Mobile from Google Play Store or Apple App Store.

  2. Open the app, tap on 'Advertiser' on the bottom tab. Tap the '+' button on top to create a new advertising set.

  3. In the 'Advertising' tab, enter your Device Name under 'Complete Local Name' and set 'Appearance' to 'Generic Heart Rate Sensor.'

  4. In the 'PACKETS' tab,

  • In the 'Advertising' data, add your desired services. For instance, add 'heart_rate' and 'battery_service.' Enter their 16-bit UUIDs.
  • Optionally in 'Scan response' data, put additional services and characteristics.
  1. When you finish, tap on 'Save' and back at the 'Advertiser,' tap on 'ADVERTISE' to start advertising your simulated device.

  2. Now you can use your JavaScript code to connect to this simulated device. The app shows the list of devices that have connected to the simulated peripheral.

Remember that this is just a simulation. Real devices can behave differently and might have more constraints than our Web Bluetooth sample. Also, note that testing should include how your code responds to different situations like device disconnects, different types of errors, and device permissions, among other things.

πŸ’» Styling the Web BLE App

Let’s improve the interface of our Web Bluetooth example from the previous section by adding icons and CSS.

index.html

In the following 'index.html,' we should a link to the style.css file and the favicon.ico within the head tag.

<!DOCTYPE html>
<html>
<head>
    <link rel="icon" href="favicon.ico">
    <link rel="stylesheet" href="style.css">
</head>
<body>
<h1>BLE Device Interaction</h1>

<button id="search-btn" class="action-btn">Search for BLE Device</button>
<button id="connect-btn" class="action-btn" disabled>Connect to BLE Device</button>
<p id="device-info">No device connected.</p>

<script>
    let device, server;

    async function searchDevice() {
   // ... existing code
    }

    async function connectDevice() {
    // ... existing code
    }

    document.getElementById('search-btn').addEventListener('click', searchDevice);
    document.getElementById('connect-btn').addEventListener('click', connectDevice);
</script>

</body>
</html>

style.css

In the CSS, we need to define a few basic styles. The body has been given some padding and a neutral background color. The 'action-btn' class is styled for the buttons, which is similar to Bootstrap's primary button style. And finally, the device information paragraph is given some top margin for better visuals.

body {
    font-family: Arial, sans-serif;
    background: #f0f0f0;
    padding: 50px;
}

h1 {
    color: #333;
}
.action-btn {
    color: #fff;
    background-color: #007bff;
    border-color: #007bff;
    padding: 10px 20px;
    margin: 10px 0;
    cursor: pointer;
}

#device-info {
    color: #666;
    margin-top: 20px;
}

favicon

To use your favicon for your Web BLE examples and samples, simply save it as 'favicon.ico' in the same directory as your HTML and CSS files. You can download the 'favicon.ico.zip' folder here.

In summary, this section focuses on enhancing the visual appeal of the Web BLE application by incorporating CSS and a favicon. This styling upgrade ensures the application is both functional and visually appealing.

πŸ—‚οΈ Our Approach to BLE Connectivity

At Stormotion, we leverage our expertise in BLE technology and mobile application development services to deliver innovative and reliable solutions across various industries, including marine, e-mobility, and fitness. With a deep understanding of BLE protocols and a commitment to seamless integration, we ensure that our client's products communicate efficiently and effectively.

Our approach focuses on robust data exchange, minimizing latency, and optimizing power consumption. This expertise has been demonstrated through our successful collaborations with companies like Norsk, Egret, and SportPlus, where we've tackled unique challenges to enhance their IoT capabilities. Let’s discuss each of them.

Norsk Guardian is an app developed for Norsk, a company specializing in advanced lithium-ion batteries for various water-based activities. They needed an app to monitor multiple batteries, retrieve telemetry data, and display charging indicators for enhanced maritime safety. Each Norsk battery features a unique Bluetooth module, enabling the app to receive and process critical battery status information.

Using the React Native framework, we developed a BLE module for smooth Bluetooth connectivity. Rigorous testing and optimized communication protocols allow the system to detect and alert users of potential issues before they become critical, minimizing battery failure risks and ensuring safe maritime adventures. Now, the app ensures users can monitor battery performance effectively and enjoy safer trips on the water.

There’s no better way to share the impact than through the client’s perspective β€” here’s their view on our cooperation:

Egret, a leading e-scooter manufacturer, faced challenges with transitioning their app from Native to React Native. They sought a solution to optimize OTA update processes and ensure consistent communication across all scooter models via BLE.

Our e-scooter application developers developed a custom native module for direct interaction with the scooter's hardware, enhancing communication speed and reliability. By reverse engineering the original protocol handler, we addressed underlying issues and created a generic protocol handler for seamless communication with all e-scooter BLE models. Our solution dramatically improved the OTA update process, reducing delays and enhancing user experience.

If you need to build a companion app for your IoT BLE device, the SportPlus case will be interesting for you. The key challenge was implementing a stable protocol for BLE communication, complicated by the discovery that their equipment used four different BLE protocols, leading to inconsistency in operation.

To solve this problem, we developed a generic protocol handler to address the challenge of multiple protocols, ensuring consistent communication across all devices. Additionally, we implemented a custom workout functionality with a CMS system, allowing SportPlus to manage and update workout content independently. As a result, we developed a mobile app that seamlessly integrates with SportPlus’s workout equipment, providing personalized exercise routines.

πŸ’‘ Takeaways

In this guide, we've explored how to effectively leverage the Web Bluetooth API to create a robust web application capable of interacting with BLE devices. Let’s summarize:

  • BLE is a low-power, efficient wireless communication technology ideal for IoT devices, offering features like low power consumption, fast connection, and robust security. It is widely compatible, cost-effective, and projected to grow significantly, making it essential for modern applications.
  • The Web Bluetooth API allows web applications to connect and interact with BLE devices directly from the browser, enhancing real-time experiences without native apps. While supported by major browsers, it faces challenges like security concerns and performance variability.
  • Building a web app with BLE integration involves understanding the Web Bluetooth API and implementing it to connect devices, as shown in our Web Bluetooth API tutorial with the heart rate monitor example.
  • Creating a Web BLE app requires a straightforward interface, user-triggered device searches, and efficient connection management.
  • Testing the app can be effectively done using tools like nRF Connect for Mobile to simulate BLE devices and ensure functionality. Finally, styling the app with CSS enhances its visual appeal, ensuring a user-friendly and aesthetically pleasing experience.

Ready to leverage BLE technology and the Web Bluetooth API for your next innovative project? Whether you need to integrate BLE connectivity into your web app or enhance your IoT capabilities, our expert team is here to help.

Building Apps for EV, IoT, Fitness & Digital Health since 2017.

Need a Dev Team that gets things done?

Let's Talk

Stormotion client David Lesser, CEO from Numina

They were a delight to work with. And they delivered the product we wanted. Stormotion fostered an enjoyable work atmosphere and focused on delivering a bug-free solution.

David Lesser, CEO

Numina

Questions you may have

Take a look at how we solve challenges to meet project requirements

What is Web Bluetooth?

Web Bluetooth is an API that allows web applications to connect and interact with BLE devices directly from the browser. It enables developers to create seamless real-time experiences without the need for native apps.

How does it integrate with BLE technology for web applications?

Web Bluetooth integrates with BLE technology by enabling web applications to discover, connect, and communicate with BLE devices. This integration allows for real-time data exchange and control of BLE-enabled devices directly through a web browser.

How do I get started with Web Bluetooth?

To get started with Web Bluetooth, you need a compatible browser and a basic understanding of JavaScript. You can begin by exploring the navigator.bluetooth.requestDevice function to discover and connect to BLE devices, and refer to documentation and tutorials for detailed implementation guidance.

What browsers support Web Bluetooth?

Web Bluetooth is supported by major browsers like Google Chrome, Microsoft Edge, and Opera on both desktop and Android platforms. However, it is not supported by Apple Safari and Internet Explorer.

Which platforms and devices are compatible with this technology?

Web Bluetooth is compatible with a wide range of platforms, including Windows, macOS, Linux, and Android, as long as the device has a compatible browser and Bluetooth functionality. Most modern BLE-enabled devices can connect using Web Bluetooth.

What are the security implications of using Web Bluetooth?

Using Web Bluetooth raises significant security and privacy concerns, as it involves allowing web applications to interact with hardware devices. Ensuring secure connections and protecting user data requires stringent security measures and careful permission management.

How can developers ensure secure connections when using BLE?

Developers can ensure secure connections by implementing strong encryption, such as AES-128, using secure pairing methods and validating device permissions. Regularly updating software and following best practices for secure BLE communication are also crucial.

Can Web Bluetooth access all BLE devices?

Web Bluetooth can access a wide range of BLE devices, but not all. Compatibility depends on the device's support for the necessary BLE services and the browser's implementation of the Web Bluetooth API.

What are the limitations in device compatibility and connectivity?

Limitations include variability in performance across different browsers, lack of support in some browsers like Safari, and dependency on the quality and capabilities of the BLE hardware. Additionally, BLE's short range and potential interference can impact connectivity.

How does Web Bluetooth handle multiple devices?

Web Bluetooth can handle multiple devices by allowing web applications to connect to and manage several BLE devices simultaneously. Developers should manage connections and data streams efficiently to ensure smooth operation and avoid interference.

What are the common use cases for Web Bluetooth?

Common use cases for Web Bluetooth include health and fitness monitoring (e.g., heart rate monitors), home automation (e.g., smart lights and thermostats), and industrial IoT applications (e.g., monitoring machinery and sensors).

How do I debug issues in Web Bluetooth implementations?

Debugging issues in Web Bluetooth implementations involves using browser developer tools to inspect and monitor Bluetooth connections and interactions. Developers can also refer to logs, error messages, and community forums to troubleshoot common issues and find solutions.

Dmytro Zasukha

Dmytro Zasukha

Android | React Native Developer @ Stormotion

Dmytro Zasukha

Dmytro Zasukha

Android | React Native Developer @ Stormotion

Anastasiia Chala

Anastasiia Chala

Rockstar Copywriter @ Stormotion

Writing captivating articles that explain the intricate world of app and web development.

Anastasii...

Anastasiia Chala

Anastasiia Chala

Rockstar Copywriter @ Stormotion

Writing captivating articles that explain the intricate world of app and web development.

Anastasii...

Read also

Let's Build Something Great Together?

Drop us a message