Bluetooth

Reference

Check bluetooth availability

chrome://bluetooth-internals/#adapter

Connect

const [connectedDevice,setConnectedDevice]=useState()

const options = {
		filters: [{
			name: 'Zikr Ring Lite'
		  }],
		// services:services,
		optionalServices: ['device_information']
	}
function findDevice(){
	console.log('Requesting Bluetooth Device...');
	navigator.bluetooth.requestDevice(options)
	.then(device => {
		console.log(device,'device in find device')
		bluetoothDevice = device;
		bluetoothDevice.addEventListener('gattserverdisconnected', onDisconnected);
		return connect();
	})
	.catch(error => {
		console.log('Argh! ' + error);
	});
}


function connect() {
	console.log('Connecting to Bluetooth Device...');
	return bluetoothDevice.gatt.connect()
	.then(server => {
		setConnectedDevice(bluetoothDevice)
		console.log(server,'server')
		console.log('> Bluetooth Device connected');
	});
}


<button onClick={()=>findDevice()}>connect</button>

Disconnect

function onDisconnectButtonClick() {
	console.log('< disconnecting',connectedDevice)
	if (!connectedDevice) {
	  return;
	}
	console.log('Disconnecting from Bluetooth Device...');
	if (connectedDevice.gatt.connected) {
		connectedDevice.gatt.disconnect();
	} else {
		setConnectedDevice()
		console.log('> Bluetooth Device is already disconnected');
	}
}

<button onClick={()=>onDisconnectButtonClick()}>disconnect</button>

get Bluetooth Characteristic

async function getBTService() {
		const currentUUID = 'UUID_HERE'
		try {
		 console.log('Requesting any Bluetooth Device...');
		  const device = await navigator.bluetooth.requestDevice({
			filters: [{
				name: 'Zikr Ring Lite'
			}],
			//   acceptAllDevices: true,
			  optionalServices: ['device_information']});
	  
		  console.log('Connecting to GATT Server...');
		  const server = await device.gatt.connect();
	  
		  console.log('Getting Device Information Service...');
		  const service = await server.getPrimaryService('SERVICE_UUID_HERE');
	  
		  console.log('Getting Device Information Characteristics...');
		  const characteristics = await service.getCharacteristics();
		  
		  console.log(characteristics)

		} catch(error) {
			console.log('Argh! ' + error);
		}
	}
	
<button onClick={()=>getBTService()}>get characteristics</button>

Last updated

Was this helpful?