0% found this document useful (0 votes)
6 views4 pages

Connect to Bluetooth Device Guide

This document is an HTML code for a web page that allows users to connect to a Bluetooth device using the Web Bluetooth API. It includes a button to initiate the connection and displays the battery level of the connected device. The code also handles errors and updates the user interface with the connection status and battery level information.

Uploaded by

Samuel Arikpo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views4 pages

Connect to Bluetooth Device Guide

This document is an HTML code for a web page that allows users to connect to a Bluetooth device using the Web Bluetooth API. It includes a button to initiate the connection and displays the battery level of the connected device. The code also handles errors and updates the user interface with the connection status and battery level information.

Uploaded by

Samuel Arikpo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

<!

DOCTYPE html> ==$0

<html lang=”en”>

<head>

<meta charset=”UTF-8”>

<meta name=”viewport” content=”width=device-width, initial-scale=1.0”>

<title>Connect to Bluetooth Device</title>

<style>

body {

font-family: Arial, sans-serif;

margin: 20px;

padding: 20px;

background-color: #f4f4f9;

text-align: center;

button {

padding: 15px 30px;

font-size: 16px;

background-color: #007bff;

color: white;

border: none;

cursor: pointer;

button:hover {

background-color: #0056b3;

.status {
margin-top: 20px;

font-size: 18px;

// Check if the browser supports the Web Bluetooth API

if (![Link]) {

alert("Web Bluetooth is not supported by this browser.");

// Element references

const connectButton = [Link]('connectButton');

const statusDiv = [Link]('status');

// Function to update the status on the page

function updateStatus(message) {

[Link] = "Status: " + message;

// Event listener for the connect button

[Link]('click', function () {

// Update status to indicate connection attempt

updateStatus('Requesting Bluetooth device...');

// Request Bluetooth device

[Link]({

acceptAllDevices: true, // Accept any Bluetooth device

optionalServices: ['battery_service'] // Optional service (e.g., battery level)

})

.then(device => {
// Connect to the device directly, without checking for device info

updateStatus('Device selected. Connected');

// Connect to the device

return [Link]();

})

.then(server => {

// Successfully connected to the GATT server

updateStatus('Connected to device.');

// Get the primary service (battery service)

return [Link]('battery_service');

})

.then(service => {

// Get the battery level characteristic

return [Link]('battery_level');

})

.then(characteristic => {

// Read the battery level value

return [Link]();

})

.then(value => {

// Display battery level (Uint8Array format)

const batteryLevel = value.getUint8(0);

updateStatus('Battery Level: ' + batteryLevel + '%');

})
.catch(error => {

// Handle errors

[Link]('Error:', error);

updateStatus('Error: ' + error);

});

});

Common questions

Powered by AI

The script checks for Web Bluetooth API support using navigator.bluetooth. If not supported, it promptly alerts the user with a message indicating that the browser does not support the Web Bluetooth API. This suggests that not all browsers are capable of utilizing this API, implying limited browser compatibility .

During the connection process, the script employs a catch block to manage errors. Any errors encountered are logged to the console, and the user is updated with a status message indicating an error. This mechanism not only enforces robust error handling but also improves the user experience by communicating clear, immediate feedback, thus preventing confusion or perceived failures during interaction .

The 'battery_level' characteristic serves as a practical endpoint for querying the device’s remaining power, an action implemented to demonstrate interfacing beyond mere connectivity. By accessing and displaying this characteristic, the application introduces an additional layer of functionality, offering meaningful insights into the device's readiness or need for charge, thereby improving decision-making regarding device usage and reliability .

The script utilizes the updateStatus function to change the text content of the statusDiv element, dynamically reflecting the current state of the Bluetooth connection process. Initially, it indicates the starting phase with 'Requesting Bluetooth device...', transitions to 'Device selected. Connected' once a device is chosen, and confirms the connection with 'Connected to device.' It then updates the battery level status or error information based on the process outcome .

The script uses an event listener attached to the 'connectButton', which transforms user interactions into asynchronous operations. By executing all connection logic upon a button click, it effectively decouples the actions and maintains a responsive UI. This use of events to trigger the connection workflow demonstrates how event-driven paradigms manage external hardware interactions seamlessly, ensuring that user actions directly govern connectivity processes .

Using 'navigator.bluetooth.requestDevice' with 'acceptAllDevices: true' permits the selection of any nearby Bluetooth device without any filtering. This decision eases device discovery but opens potential security risks, as it does not discriminate between trusted and untrusted devices. While enhancing flexibility and simplifying user interactions, it also implies a need for user diligence in verifying device legitimacy .

The process begins with checking if the browser supports the Web Bluetooth API. If unsupported, an alert is triggered. The next step involves adding an event listener to the connection button, which, upon clicking, updates the status to indicate an attempt to request a Bluetooth device. The navigator.bluetooth.requestDevice function is used to accept any device offering optional battery services. Once a device is selected, a direct connection is established using the device.gatt.connect method. Upon successful GATT server connection, it proceeds to retrieve the primary battery service via server.getPrimaryService, followed by fetching the battery level characteristic through service.getCharacteristic. Finally, the battery level is read using characteristic.readValue and displayed in the status .

Including 'battery_service' as an optional service allows the script to access the Bluetooth device's battery level characteristic specifically. This enhances user interaction by providing additional device information, in this case, the battery status, which is coded to be retrieved and displayed. The logical inclusion of such a service facilitates obtaining more than just a simple connection, but an insightful connection that can serve practical purposes .

The user interface design emphasizes simplicity and usability—characterized by a clear, centralized connection button and status updates aligned prominently on the page. Such a straightforward layout avoids overwhelming users, focusing instead on essential functions. However, enhancements could include more interactive elements or visual cues during connection attempts, potentially offering more engaging feedback while maintaining user engagement in a minimalist style .

The script underscores the critical role of real-time feedback through frequent status updates throughout the connection process. This approach bridges user interaction and system processing seamlessly, greatly enhancing the user experience by providing continuous, clear, and contextual information about the ongoing state of the operation. Particularly in device connectivity scenarios, such feedback conveys reassurance, clarity, and immediacy .

You might also like