TECH

DEVELOPMENT

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

Published: July 30, 2024

25 min read

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.

Feature

Explanation

Low Power Consumption

BLE is designed to use minimal power, making it perfect for devices that need to run for long periods on small batteries.

Efficient Data Transfer

While conserving power, BLE still provides efficient data transfer, suitable for applications requiring periodic data updates.

Scalability and Flexibility

BLE can connect multiple devices simultaneously and can be integrated into various devices and applications from data broadcasting to mesh networks.

Fast Connection and Communication

BLE supports quick pairing and rapid data exchanges, ensuring smooth user experiences.

Robust Security

BLE incorporates strong security measures, including AES-128 encryption and privacy features, to protect data and ensure secure connections.

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.

Key Benefits of the BLE Technology

  1. Compatible with a Broad Range of Devices. BLE is supported by most modern smartphones, tablets, and other devices, ensuring wide compatibility.
  2. Long Battery Life. Due to its low power consumption, BLE-enabled devices can operate for extended periods without frequent battery replacements or recharges.
  3. Fast Pairing and Connection. BLE devices can quickly pair and establish connections, enhancing the user experience by reducing wait times.
  4. Cost-Effective. Implementing BLE can be cost-efficient for manufacturers, as it reduces power and resource requirements.
  5. Flexible and Scalable. BLE’s architecture allows it to be easily adapted and scaled for various applications and device networks.
  6. Improved Privacy and Security. BLE includes built-in privacy features to prevent unauthorized tracking and ensure secure data transmission.
  7. Increased Range. BLE can communicate over greater distances (up to 100 m in Bluetooth 5 and later versions) compared to traditional Bluetooth, making it suitable for a broader range of applications.

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.

An example of the Bluetooth technology implementation

Bluetooth is a wireless technology used for exchanging data between devices over short distances (image by Serge Strokov)

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.

 A hardware wallet can securely connect to a web application using BLE without exposing sensitive information to potential threats

Hardware wallets can connect to web applications via Web Bluetooth API, allowing secure transactions and interactions with cryptocurrencies (image by Yu Long)

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.
The Web BLE API allows web apps to directly control smart home devices via BLE

The Web BLE API enables web apps to communicate with smart home devices via BLE, simplifying their control and management (image by Jack R.)

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.

Key Benefits of the Web Bluetooth

  1. Cross-Platform Compatibility. Web Bluetooth works across multiple browsers and operating systems, making it easy to deploy solutions widely.
  2. No Native App Requirement. Businesses can save on development costs and time by not needing to create and maintain native apps.
  3. Rapid Development and Deployment. With Web Bluetooth, developers can quickly create and deploy web applications, speeding up the time-to-market.
  4. Access to a Wide Range of Devices. The API supports a variety of BLE devices, allowing businesses to innovate and expand their product offerings.
  5. Enhanced User Experience. Web Bluetooth enables seamless, real-time interactions with devices, enhancing user satisfaction and engagement.
  6. Leverage of Existing Web Technologies. Businesses can utilize familiar web development tools and frameworks, reducing the learning curve and development complexity.
  7. Improved Connectivity for IoT. Web Bluetooth simplifies the integration of IoT devices, providing robust and reliable connectivity.
  8. Innovation and Experimentation. The flexibility of Web Bluetooth, combined with experimental web platform features, encourages experimentation and innovation, opening new avenues for product development.
  9. Wide Browser Support. Web BLE ensures accessibility and ease of use across different user environments.

Key Weakness of the Web Bluetooth

  1. Security and Privacy Concerns. The ability to interact with hardware devices through a web browser raises significant security and privacy issues. Ensuring secure connections and protecting user data requires stringent measures.
  2. Performance Variability. The performance of Web Bluetooth can vary significantly depending on the browser and device used, leading to inconsistent user experiences.
  3. Complexity in Debugging. Debugging Web Bluetooth applications can be challenging due to the intricacies of BLE communication and the lack of mature debugging tools.
  4. Dependency on BLE Hardware. The effectiveness of Web Bluetooth is inherently tied to the quality and capabilities of the BLE hardware it connects to, which can vary widely.
  5. Limited Range. Bluetooth communication generally covers short distances, with Bluetooth 5.0 reaching up to 100 meters under ideal conditions.

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.

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.

An example of the BLE design

Design of BLE device (shots from O’Reilly)

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

Device Name

BLE Health Monitor

Bluetooth Version

Bluetooth 4.0

Device Type

Generic Health Monitor

Supported Services

Heart Rate Service ('heart_rate', 0x180D). This service exposes heart rate data and other related data from a Heart Rate Sensor intended for fitness applications.

Device Information Service ('device_information', 0x180A). This service exposes manufacturer and/or vendor-specific information about a device.

Battery Service ('battery_service', 0x180F). This service allows access to battery level information for a device

Key Characteristics

Heart Rate Measurement ('heart_rate_measurement', 0x2A37). This characteristic sends the heart rate information.

Body Sensor Location ('body_sensor_location', 0x2A38). This characteristic explains the intended body location of the sensor.

Battery Level ('battery_level', 0x2A19). This characteristic represents the level of power remaining in the battery.

Optional Services

Blood Pressure Service ('blood_pressure', 0x1810). This service exposes blood pressure and other related data from a blood pressure sensor.

Health Thermometer Service ('health_thermometer', 0x1809). This service exposes temperature and related data from a health thermometer.

Maximum Connection Interval: 60-70ms. This value gives a balance between power consumption and data transmission rate.

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.

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.

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.

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.

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.

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.

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.

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.

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

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.

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.

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.

Norsk Guardian is an app that monitors lithium-ion batteries for water-based activities, ensuring safety by providing real-time telemetry data and alerts

The Norsk Guardian app allows users to monitor and manage multiple lithium-ion batteries for safe maritime voyages (image by Stormotion)

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.

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.

Egret's app optimizes e-scooter performance by providing fast and reliable OTA updates and consistent Bluetooth communication

The Egret e-scooter app ensures communication between the app and scooters via BLE technology (image by Stormotion)

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.

SportPlus provides exercise routines and manage workout content efficiently

The SportPlus fitness app seamlessly integrates with workout equipment, offering personalized workouts and consistent BLE communication (image by Stormotion)

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.

Contact us

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.

Read also

How can we help you?

Our clients say

Stormotion client Alexander Wolff, CPO from [object Object]

When I was working with Stormotion, I forgot they were an external agency. They put such effort into my product it might as well have been their own. I’ve never worked with such a client-focused company before.

Alexander Wolff, CPO

Sjut