Skip to content

Instantly share code, notes, and snippets.

@leightkt
Created March 13, 2021 19:39
Show Gist options
  • Save leightkt/afc818b5fc98073d4d9991eab3de7fe5 to your computer and use it in GitHub Desktop.
Save leightkt/afc818b5fc98073d4d9991eab3de7fe5 to your computer and use it in GitHub Desktop.
Bluetooth Component for React
function Bluetooth({ setDevice, setCharacteristic, setServer, setService }) {
const connectToDevice = async () => {
const device = await navigator.bluetooth
.requestDevice({
filters: [
{ namePrefix: "Device Name" },
{ services: [ 'Service ID' ]}
]
})
setDevice(device)
const server = await device.gatt.connect()
setServer(server)
const service = await server.getPrimaryService('Service ID')
setService(service)
const characteristic = await service.getCharacteristic('Characteristic ID')
setCharacteristic(characteristic)
device.addEventListener('gattserverdisconnected', onDisconnected)
}
const onDisconnected = (event) => {
alert("Vibrator Disconnected")
const device = ""
setDevice(device)
}
return (
<>
<button className="bluetooth" onClick={connectToDevice}>CONNECT</button>
</>
)
}
export default Bluetooth
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment