I'm trying to build a web application using React that can communicate with an ESP32 device over Bluetooth and display real-time data. I've already set up the ESP32 to act as a Bluetooth Low Energy (BLE) peripheral device and I'm able to read and write data to the device using the Web Bluetooth API.
Now, I'm trying to figure out how to use React to display the data from the ESP32 device in real-time. I want the data to be updated automatically as soon as it's received from the device.
I have tried to this code but its not working properly, show errror "Device connection failed"
import React, { useState } from "react";
function BluetoothConnection() {
const [devices, setDevices] = useState([]);
const serviceUUID = "00002a00-0000-1000-8000-00805f9b34fb";
const characteristicUUID = "6e400001-b5a3-f393-e0a9-e50e24dcca9e";
const serviceStatus = "6E700000-B5A3-F393-E0A9-E50E24DCCA9E";
async function scanDevices() {
try {
// Request Bluetooth device
const device = await navigator.bluetooth.requestDevice({
acceptAllDevices: true
});
console.log(device)
// Connect to the device
const server = await device.gatt.connect(device);
console.log(server)
// Get the Bluetooth Service
const service = await server.getPrimaryService();
console.log(service)
// Get the Bluetooth Characteristic
const characteristic = await service.getCharacteristic();
console.log(characteristic)
// Read the value of the characteristic
const value = await characteristic.readValue();
console.log('ESP32 Status:', value);
// Disconnect from the device
// await device.gatt.disconnect();
} catch (error) {
console.error(error);
}
}
return (
<div>
<button onClick={scanDevices}>Scan for devices</button>
</div>
);
}
export default BluetoothConnection;
after when I am connecting the device then this error is showing