-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
65 lines (56 loc) · 2.22 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
const button = document.getElementById("getDetails");
const details = document.getElementById("details");
button.addEventListener("click", async () => {
try {
// Request the Bluetooth device through browser
const device = await navigator.bluetooth.requestDevice({
optionalServices: ["battery_service", "device_information"],
acceptAllDevices: true,
});
// Connect to the GATT server
// We also get the name of the Bluetooth device here
let deviceName = device.gatt.device.name;
const server = await device.gatt.connect();
// Getting the services we mentioned before through GATT server
const batteryService = await server.getPrimaryService("battery_service");
const infoService = await server.getPrimaryService("device_information");
// Getting the current battery level
const batteryLevelCharacteristic = await batteryService.getCharacteristic(
"battery_level"
);
// Convert recieved buffer to number
const batteryLevel = await batteryLevelCharacteristic.readValue();
const batteryPercent = await batteryLevel.getUint8(0);
// Getting device information
// We will get all characteristics from device_information
const infoCharacteristics = await infoService.getCharacteristics();
console.log(infoCharacteristics);
let infoValues = [];
const promise = new Promise((resolve, reject) => {
infoCharacteristics.forEach(async (characteristic, index, array) => {
// Returns a buffer
const value = await characteristic.readValue();
console.log(new TextDecoder().decode(value));
// Convert the buffer to string
infoValues.push(new TextDecoder().decode(value));
if (index === array.length - 1) resolve();
});
});
promise.then(() => {
console.log(infoValues);
// Display all the information on the screen
// use innerHTML
details.innerHTML = `
Device Name - ${deviceName}<br />
Battery Level - ${batteryPercent}%<br />
Device Information:
<ul>
${infoValues.map((value) => `<li>${value}</li>`).join("")}
</ul>
`;
});
} catch (err) {
console.log(err);
alert("An error occured while fetching device details");
}
});