Skip to content

Instantly share code, notes, and snippets.

@alic-xc
Last active January 21, 2024 14:04
Show Gist options
  • Save alic-xc/b4fe7fd10760e953a2561d4b5948167a to your computer and use it in GitHub Desktop.
Save alic-xc/b4fe7fd10760e953a2561d4b5948167a to your computer and use it in GitHub Desktop.
import React from "react";
import "./App.css";
function App() {
const [isLoading, setIsLoading] = React.useState(false);
const [isConnected, setIsConnected] = React.useState(false);
const [batteryLevel, setBatteryLevel] = React.useState(0);
const btnText = isLoading
? "Loading..."
: isConnected
? "Connected"
: "Connect Device";
const fetchDeviceDetailsHandler = async () => {
setIsLoading(true);
setIsConnected(false);
var request = await navigator.bluetooth.requestDevice({
optionalServices: ["battery_service", "device_information"],
acceptAllDevices: true,
});
try {
const deviceServer = await request.gatt.connect();
console.log("connnect");
const battery = await deviceServer.getPrimaryService("battery_service");
const batteryLevel = await battery.getCharacteristic("battery_level");
const batteryLevelChars = await batteryLevel.readValue();
const batteryLevelVal = await batteryLevelChars.getUint8(0);
setBatteryLevel(batteryLevelVal);
setIsConnected(true);
} catch (err) {
alert(err);
} finally {
request.gatt.disconnect();
setIsLoading(false);
}
};
return (
<>
<button onClick={isLoading ? undefined : fetchDeviceDetailsHandler}>
{btnText}
</button>
<table border="1" style={{ marginTop: "10px", width: "500px" }}>
<tbody>
<tr>
<td align="left">Battery Level</td>
<td>{batteryLevel}%</td>
</tr>
</tbody>
</table>
</>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment