<!
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 (!navigator.bluetooth) {
alert("Web Bluetooth is not supported by this browser.");
// Element references
const connectButton = document.getElementById('connectButton');
const statusDiv = document.getElementById('status');
// Function to update the status on the page
function updateStatus(message) {
statusDiv.textContent = "Status: " + message;
// Event listener for the connect button
connectButton.addEventListener('click', function () {
// Update status to indicate connection attempt
updateStatus('Requesting Bluetooth device...');
// Request Bluetooth device
navigator.bluetooth.requestDevice({
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 device.gatt.connect();
})
.then(server => {
// Successfully connected to the GATT server
updateStatus('Connected to device.');
// Get the primary service (battery service)
return server.getPrimaryService('battery_service');
})
.then(service => {
// Get the battery level characteristic
return service.getCharacteristic('battery_level');
})
.then(characteristic => {
// Read the battery level value
return characteristic.readValue();
})
.then(value => {
// Display battery level (Uint8Array format)
const batteryLevel = value.getUint8(0);
updateStatus('Battery Level: ' + batteryLevel + '%');
})
.catch(error => {
// Handle errors
console.log('Error:', error);
updateStatus('Error: ' + error);
});
});