Repository navigation
Expand file tree
/
Copy pathgap_js.go
More file actions
227 lines (191 loc) · 6.12 KB
/
Copy pathgap_js.go
File metadata and controls
227 lines (191 loc) · 6.12 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
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
package bluetooth
import (
"errors"
"syscall/js"
)
// Address contains a Bluetooth address which on WASM is an opaque device ID
// string, since WebBluetooth does not expose MAC addresses.
type Address struct {
// The opaque device identifier provided by the browser.
ID string
}
// IsRandom is not applicable for WebBluetooth.
func (ad Address) IsRandom() bool {
return false
}
// SetRandom is not applicable for WebBluetooth.
func (ad *Address) SetRandom(val bool) {
}
// Set the address from a device ID string.
func (ad *Address) Set(val string) {
ad.ID = val
}
// String returns the device ID as a string.
func (ad Address) String() string {
return ad.ID
}
var _ GAPDevice = Device{}
// ErrScanCanceled is the error from Scan when the user closes the device picker.
var ErrScanCanceled = errors.New("bluetooth: the user closed the device picker")
var errNotConnected = errors.New("bluetooth: not connected")
// Device is a connection to a remote peripheral via WebBluetooth.
type Device struct {
Address Address
adapter *Adapter
device js.Value // BluetoothDevice
server js.Value // BluetoothRemoteGATTServer
}
// Scan opens the device picker of the browser and calls the callback one time
// with the device that the user selects.
//
// WebBluetooth has no continuous scan. Scan returns after the user selects a
// device, and returns ErrScanCanceled if the user closes the picker.
//
// requestDevice gives only the id and the name of the device, so the scan
// result has an RSSI of 0 and a payload with only the local name.
//
// HasServiceUUID and ServiceUUIDs on that payload always give an empty result.
// Put the services in Adapter.RequestedServices and use DiscoverServices.
//
// The browser opens the picker only after a recent user action, such as a
// click. Do no slow work between that action and the call to Scan.
func (a *Adapter) Scan(callback func(*Adapter, ScanResult)) error {
if callback == nil {
return errors.New("bluetooth: must provide callback to Scan function")
}
if a.bluetooth.IsUndefined() {
return errNotEnabled
}
if a.scanning {
return errScanning
}
a.scanning = true
defer func() { a.scanning = false }()
options := js.Global().Get("Object").New()
options.Set("acceptAllDevices", true)
// Without optionalServices the browser gives a SecurityError for every
// service after the connection.
if len(a.RequestedServices) > 0 {
svcs := js.Global().Get("Array").New(len(a.RequestedServices))
for i, uuid := range a.RequestedServices {
svcs.SetIndex(i, js.ValueOf(uuid.String()))
}
options.Set("optionalServices", svcs)
}
promise := a.bluetooth.Call("requestDevice", options)
jsDevice, err := await(promise)
if isDOMError(err, "NotFoundError") {
// Enable checks the availability, so this means that the user chose no device.
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetooth-requestdevice
return ErrScanCanceled
}
if err != nil {
return err
}
deviceID := jsDevice.Get("id").String()
name := ""
if n := jsDevice.Get("name"); !n.IsUndefined() {
name = n.String()
}
// Store the JS device object so it can be retrieved during Connect.
a.devices[deviceID] = jsDevice
// The browser gives no RSSI and no advertisement data.
callback(a, ScanResult{
Address: Address{ID: deviceID},
RSSI: 0,
AdvertisementPayload: &advertisementFields{
AdvertisementFields{
LocalName: name,
},
},
})
return nil
}
// StopScan stops any in-progress scan.
//
// The picker of the browser closes by itself, so this only clears the scan
// state.
func (a *Adapter) StopScan() error {
if !a.scanning {
return errNotScanning
}
a.scanning = false
return nil
}
// Connect starts a connection attempt to the given peripheral device address.
//
// On WebBluetooth, the device must have been discovered via Scan first, so the
// BluetoothDevice JS object is available.
func (a *Adapter) Connect(address Address, params ConnectionParams) (Device, error) {
jsDevice, ok := a.devices[address.ID]
if !ok {
return Device{}, errors.New("bluetooth: device not found, must call Scan first on WASM")
}
gatt := jsDevice.Get("gatt")
if gatt.IsUndefined() {
return Device{}, errors.New("bluetooth: device does not support GATT")
}
server, err := await(gatt.Call("connect"))
if err != nil {
return Device{}, err
}
d := Device{
Address: address,
adapter: a,
device: jsDevice,
server: server,
}
a.setDisconnectHandler(d)
a.connectHandler(d, true)
return d, nil
}
func (a *Adapter) setDisconnectHandler(d Device) {
deviceID := d.Address.ID
if listener, ok := a.disconnectListeners[deviceID]; ok {
d.device.Call("removeEventListener", "gattserverdisconnected", listener)
listener.Release()
delete(a.disconnectListeners, deviceID)
}
var listener js.Func
listener = js.FuncOf(func(this js.Value, args []js.Value) any {
defer listener.Release()
device := Device{
Address: d.Address,
adapter: a,
device: d.device,
server: d.device.Get("gatt"),
}
d.device.Call("removeEventListener", "gattserverdisconnected", listener)
delete(a.disconnectListeners, deviceID)
// The browser drops the characteristics of the device.
// https://webbluetoothcg.github.io/web-bluetooth/#clean-up-the-disconnected-device
a.stopListening(deviceID)
// A blocked JS callback stops the event loop, and every method in
// this package waits for a promise. See syscall/js.FuncOf.
go a.connectHandler(device, false)
return nil
})
a.disconnectListeners[deviceID] = listener
d.device.Call("addEventListener", "gattserverdisconnected", listener)
}
// Disconnect from the BLE device.
func (d Device) Disconnect() error {
if d.server.IsUndefined() || !d.server.Get("connected").Bool() {
return errNotConnected
}
d.server.Call("disconnect")
return nil
}
// Connected returns whether the device is currently connected.
func (d Device) Connected() (bool, error) {
if d.server.IsUndefined() {
return false, nil
}
return d.server.Get("connected").Bool(), nil
}
// RequestConnectionParams requests a different connection latency and timeout.
//
// This is not supported by WebBluetooth and is a no-op.
func (d Device) RequestConnectionParams(params ConnectionParams) error {
return nil
}