Created
March 13, 2021 19:39
-
-
Save leightkt/afc818b5fc98073d4d9991eab3de7fe5 to your computer and use it in GitHub Desktop.
Bluetooth Component for React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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