-
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathgatt.ts
More file actions
69 lines (54 loc) · 1.86 KB
/
gatt.ts
File metadata and controls
69 lines (54 loc) · 1.86 KB
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
66
67
68
69
import type { RpcTransport } from './';
const SERVICE_UUID = '00000000-0196-6107-c967-c5cfb1c2482a';
const RPC_CHRC_UUID = '00000001-0196-6107-c967-c5cfb1c2482a';
export async function connect(): Promise<RpcTransport> {
let dev = await navigator.bluetooth.requestDevice({
filters: [{ services: [SERVICE_UUID] }],
optionalServices: [SERVICE_UUID],
});
if (!dev.gatt) {
filters: {
throw 'No GATT service!';
}
}
let label = dev.name || 'Unknown';
if (!dev.gatt.connected) {
await dev.gatt.connect();
}
let svc = await dev.gatt.getPrimaryService(SERVICE_UUID);
let char = await svc.getCharacteristic(RPC_CHRC_UUID);
let readable = new ReadableStream({
async start(controller) {
// Reconnect to the same device will lose notifications if we don't first force a stop before starting again.
await char.stopNotifications();
await char.startNotifications();
let vc = (ev: Event) => {
let buf = (ev.target as BluetoothRemoteGATTCharacteristic)?.value
?.buffer;
if (!buf) {
return;
}
controller.enqueue(new Uint8Array(buf));
};
char.addEventListener('characteristicvaluechanged', vc);
let cb = async () => {
char.removeEventListener('characteristicvaluechanged', vc);
dev.removeEventListener('gattserverdisconnected', cb);
controller.close();
};
dev.addEventListener('gattserverdisconnected', cb);
},
});
let writableWithoutResponse = new WritableStream({
write(chunk) {
return char.writeValueWithoutResponse(chunk);
},
});
let writableWithResponse = new WritableStream({
write(chunk) {
return char.writeValueWithResponse(chunk);
},
});
return { label, readable,
writable: char.properties.writeWithoutResponse ? writableWithoutResponse : writableWithResponse };
}