-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathWebBLEBackend.ts
171 lines (147 loc) · 5.42 KB
/
WebBLEBackend.ts
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
/// <reference types="@types/web-bluetooth" />
import type { Backend } from '../types'
import { anySignals, getUint16, racePromise } from '../utils'
const CHUNK_SIZE = 2 << 6 // 128 bytes
const NAME_PREFIX = 'ESTKme-RED'
const SERIAL_SERVICE = 0x4553
const SERIAL_TX_CHARACTERISTIC = 0x6d65
const SERIAL_RX_CHARACTERISTIC = 0x544b
export class WebBLEBackend implements EventListenerObject, Backend {
private static getRequestOptions(): RequestDeviceOptions {
if (/Bluefy/i.test(navigator.userAgent)) {
return {
filters: [{ namePrefix: NAME_PREFIX, services: [SERIAL_SERVICE] }],
}
}
return {
filters: [{ namePrefix: NAME_PREFIX }],
optionalServices: [SERIAL_SERVICE],
}
}
static async requestDevice(bluetooth = navigator.bluetooth) {
if (!(await this.getAvailability())) throw new Error('WebBLE is not available')
return bluetooth.requestDevice(this.getRequestOptions())
}
static async getAvailability(bluetooth = navigator.bluetooth) {
if (bluetooth === undefined || bluetooth === null) return false
if (typeof bluetooth.requestDevice !== 'function') return false
if (typeof bluetooth.getAvailability !== 'function') return true
return bluetooth.getAvailability()
}
static async open(device: BluetoothDevice, options?: WebBLEBackend.Options): Promise<WebBLEBackend> {
if (device.gatt === undefined) throw new Error('Bluetooth GATT is not available')
const gatt = await device.gatt.connect()
const service = await gatt.getPrimaryService(SERIAL_SERVICE)
const tx = await service.getCharacteristic(SERIAL_TX_CHARACTERISTIC)
const rx = await service.getCharacteristic(SERIAL_RX_CHARACTERISTIC)
await rx.startNotifications()
return new this(service, tx, rx, options?.chunkSize ?? CHUNK_SIZE)
}
private readonly tx: CharacteristicValue
private readonly rx: CharacteristicValue
private readonly abortController = new AbortController()
private constructor(
private readonly service: BluetoothRemoteGATTService,
tx: BluetoothRemoteGATTCharacteristic,
rx: BluetoothRemoteGATTCharacteristic,
private readonly chunkSize: number
) {
service.device.addEventListener('gattserverdisconnected', this)
this.tx = new CharacteristicValue(tx, this.abortController.signal)
this.rx = new CharacteristicValue(rx, this.abortController.signal)
}
handleEvent(event: Event): void {
if (event.type === 'gattserverdisconnected') {
this.abortController.abort(new Error('discoonnect'))
}
}
get connected() {
if (this.gatt) return this.gatt.connected
return false
}
get gatt() {
return this.device.gatt
}
get device() {
return this.service.device
}
async invoke(request: Uint8Array, options?: Backend.InvokeOptions) {
const signal = anySignals(this.abortController.signal, options?.signal)
await racePromise(this.tx.writeValue(request, this.chunkSize), signal)
return await racePromise(new Promise(this.rx.then.bind(this.rx)), signal)
}
async close(options?: Backend.CloseOptions) {
this.service.device.removeEventListener('gattserverdisconnected', this)
this.abortController.abort(new Error('close'))
await this.tx.close()
await this.rx.close()
if (this.gatt?.connected) this.gatt.disconnect()
if (options?.forget) await this.device.forget()
return
}
[Symbol.asyncDispose]() {
return this.close()
}
get [Symbol.toStringTag]() {
return 'WebBLEBackend'
}
toString() {
return `WebBLE:${this.device.name}`
}
}
export namespace WebBLEBackend {
export interface Options {
readonly chunkSize?: number
}
}
class CharacteristicValue implements EventListenerObject {
private resolve: ((value: Uint8Array) => void) | undefined
private reject: ((reason: unknown) => void) | undefined
private packet = new Uint8Array(0)
private offset = Number.NaN
constructor(private readonly chara: BluetoothRemoteGATTCharacteristic, private readonly signal: AbortSignal) {
this.chara.addEventListener('characteristicvaluechanged', this)
this.signal.addEventListener('abort', this)
}
async writeValue(request: Uint8Array, chunkSize: number) {
for (let offset = 0; offset < request.byteLength; offset += chunkSize) {
this.signal.throwIfAborted()
await this.chara.writeValue(request.slice(offset, offset + chunkSize))
}
}
handleEvent(event: Event) {
if (event.type === 'abort' && this.reject) {
this.reject(this.signal.reason)
this.reset()
}
if (event.type === 'characteristicvaluechanged' && this.resolve) {
if (this.signal.aborted) return
const chunk = new Uint8Array(this.chara.value!.buffer)
if (Number.isNaN(this.offset)) {
this.packet = new Uint8Array(3 + getUint16(chunk, 1))
this.offset = 0
}
this.packet.set(chunk, this.offset)
this.offset += chunk.byteLength
if (this.offset < this.packet.byteLength) return
this.resolve(Uint8Array.from(this.packet))
this.reset()
}
}
then(resolve: typeof this.resolve, reject: typeof this.reject) {
this.signal.throwIfAborted()
this.resolve = resolve
this.reject = reject
this.offset = Number.NaN
}
async close() {
this.signal.removeEventListener('abort', this)
this.chara.removeEventListener('characteristicvaluechanged', this)
await this.chara.stopNotifications()
}
private reset() {
this.resolve = undefined
this.reject = undefined
this.offset = Number.NaN
}
}