@capacitor-community/bluetooth-le 7.0.0 → 7.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CapacitorCommunityBluetoothLe.podspec +17 -17
  2. package/LICENSE +21 -21
  3. package/README.md +94 -16
  4. package/android/build.gradle +68 -68
  5. package/android/src/main/AndroidManifest.xml +22 -22
  6. package/android/src/main/java/com/capacitorjs/community/plugins/bluetoothle/BluetoothLe.kt +1068 -1009
  7. package/android/src/main/java/com/capacitorjs/community/plugins/bluetoothle/Conversion.kt +51 -51
  8. package/android/src/main/java/com/capacitorjs/community/plugins/bluetoothle/Device.kt +720 -718
  9. package/android/src/main/java/com/capacitorjs/community/plugins/bluetoothle/DeviceList.kt +28 -28
  10. package/android/src/main/java/com/capacitorjs/community/plugins/bluetoothle/DeviceScanner.kt +189 -189
  11. package/dist/docs.json +926 -78
  12. package/dist/esm/bleClient.d.ts +277 -277
  13. package/dist/esm/bleClient.js +349 -349
  14. package/dist/esm/bleClient.js.map +1 -1
  15. package/dist/esm/config.d.ts +53 -53
  16. package/dist/esm/config.js +2 -2
  17. package/dist/esm/config.js.map +1 -1
  18. package/dist/esm/conversion.d.ts +34 -34
  19. package/dist/esm/conversion.js +84 -84
  20. package/dist/esm/conversion.js.map +1 -1
  21. package/dist/esm/definitions.d.ts +313 -292
  22. package/dist/esm/definitions.js +42 -42
  23. package/dist/esm/definitions.js.map +1 -1
  24. package/dist/esm/index.d.ts +5 -5
  25. package/dist/esm/index.js +5 -5
  26. package/dist/esm/index.js.map +1 -1
  27. package/dist/esm/plugin.d.ts +2 -2
  28. package/dist/esm/plugin.js +4 -4
  29. package/dist/esm/plugin.js.map +1 -1
  30. package/dist/esm/queue.d.ts +3 -3
  31. package/dist/esm/queue.js +17 -17
  32. package/dist/esm/queue.js.map +1 -1
  33. package/dist/esm/timeout.d.ts +1 -1
  34. package/dist/esm/timeout.js +9 -9
  35. package/dist/esm/timeout.js.map +1 -1
  36. package/dist/esm/validators.d.ts +1 -1
  37. package/dist/esm/validators.js +11 -11
  38. package/dist/esm/validators.js.map +1 -1
  39. package/dist/esm/web.d.ts +56 -56
  40. package/dist/esm/web.js +340 -335
  41. package/dist/esm/web.js.map +1 -1
  42. package/dist/plugin.cjs.js +839 -834
  43. package/dist/plugin.cjs.js.map +1 -1
  44. package/dist/plugin.js +839 -834
  45. package/dist/plugin.js.map +1 -1
  46. package/ios/Plugin/Conversion.swift +83 -83
  47. package/ios/Plugin/Device.swift +423 -423
  48. package/ios/Plugin/DeviceManager.swift +401 -349
  49. package/ios/Plugin/Info.plist +24 -24
  50. package/ios/Plugin/Logging.swift +8 -8
  51. package/ios/Plugin/Plugin.h +10 -10
  52. package/ios/Plugin/Plugin.m +41 -41
  53. package/ios/Plugin/Plugin.swift +682 -636
  54. package/ios/Plugin/ThreadSafeDictionary.swift +13 -13
  55. package/package.json +101 -101
package/dist/plugin.js CHANGED
@@ -1,854 +1,859 @@
1
1
  var capacitorCommunityBluetoothLe = (function (exports, core) {
2
2
  'use strict';
3
3
 
4
- /**
5
- * Android scan mode
6
- */
7
- exports.ScanMode = void 0;
8
- (function (ScanMode) {
9
- /**
10
- * Perform Bluetooth LE scan in low power mode. This mode is enforced if the scanning application is not in foreground.
11
- * https://developer.android.com/reference/android/bluetooth/le/ScanSettings#SCAN_MODE_LOW_POWER
12
- */
13
- ScanMode[ScanMode["SCAN_MODE_LOW_POWER"] = 0] = "SCAN_MODE_LOW_POWER";
14
- /**
15
- * Perform Bluetooth LE scan in balanced power mode. (default) Scan results are returned at a rate that provides a good trade-off between scan frequency and power consumption.
16
- * https://developer.android.com/reference/android/bluetooth/le/ScanSettings#SCAN_MODE_BALANCED
17
- */
18
- ScanMode[ScanMode["SCAN_MODE_BALANCED"] = 1] = "SCAN_MODE_BALANCED";
19
- /**
20
- * Scan using highest duty cycle. It's recommended to only use this mode when the application is running in the foreground.
21
- * https://developer.android.com/reference/android/bluetooth/le/ScanSettings#SCAN_MODE_LOW_LATENCY
22
- */
23
- ScanMode[ScanMode["SCAN_MODE_LOW_LATENCY"] = 2] = "SCAN_MODE_LOW_LATENCY";
24
- })(exports.ScanMode || (exports.ScanMode = {}));
25
- /**
26
- * Android connection priority used in `requestConnectionPriority`
27
- */
28
- exports.ConnectionPriority = void 0;
29
- (function (ConnectionPriority) {
30
- /**
31
- * Use the connection parameters recommended by the Bluetooth SIG. This is the default value if no connection parameter update is requested.
32
- * https://developer.android.com/reference/android/bluetooth/BluetoothGatt#CONNECTION_PRIORITY_BALANCED
33
- */
34
- ConnectionPriority[ConnectionPriority["CONNECTION_PRIORITY_BALANCED"] = 0] = "CONNECTION_PRIORITY_BALANCED";
35
- /**
36
- * Request a high priority, low latency connection. An application should only request high priority connection parameters to transfer large amounts of data over LE quickly. Once the transfer is complete, the application should request CONNECTION_PRIORITY_BALANCED connection parameters to reduce energy use.
37
- * https://developer.android.com/reference/android/bluetooth/BluetoothGatt#CONNECTION_PRIORITY_HIGH
38
- */
39
- ConnectionPriority[ConnectionPriority["CONNECTION_PRIORITY_HIGH"] = 1] = "CONNECTION_PRIORITY_HIGH";
40
- /**
41
- * Request low power, reduced data rate connection parameters.
42
- * https://developer.android.com/reference/android/bluetooth/BluetoothGatt#CONNECTION_PRIORITY_LOW_POWER
43
- */
44
- ConnectionPriority[ConnectionPriority["CONNECTION_PRIORITY_LOW_POWER"] = 2] = "CONNECTION_PRIORITY_LOW_POWER";
4
+ /**
5
+ * Android scan mode
6
+ */
7
+ exports.ScanMode = void 0;
8
+ (function (ScanMode) {
9
+ /**
10
+ * Perform Bluetooth LE scan in low power mode. This mode is enforced if the scanning application is not in foreground.
11
+ * https://developer.android.com/reference/android/bluetooth/le/ScanSettings#SCAN_MODE_LOW_POWER
12
+ */
13
+ ScanMode[ScanMode["SCAN_MODE_LOW_POWER"] = 0] = "SCAN_MODE_LOW_POWER";
14
+ /**
15
+ * Perform Bluetooth LE scan in balanced power mode. (default) Scan results are returned at a rate that provides a good trade-off between scan frequency and power consumption.
16
+ * https://developer.android.com/reference/android/bluetooth/le/ScanSettings#SCAN_MODE_BALANCED
17
+ */
18
+ ScanMode[ScanMode["SCAN_MODE_BALANCED"] = 1] = "SCAN_MODE_BALANCED";
19
+ /**
20
+ * Scan using highest duty cycle. It's recommended to only use this mode when the application is running in the foreground.
21
+ * https://developer.android.com/reference/android/bluetooth/le/ScanSettings#SCAN_MODE_LOW_LATENCY
22
+ */
23
+ ScanMode[ScanMode["SCAN_MODE_LOW_LATENCY"] = 2] = "SCAN_MODE_LOW_LATENCY";
24
+ })(exports.ScanMode || (exports.ScanMode = {}));
25
+ /**
26
+ * Android connection priority used in `requestConnectionPriority`
27
+ */
28
+ exports.ConnectionPriority = void 0;
29
+ (function (ConnectionPriority) {
30
+ /**
31
+ * Use the connection parameters recommended by the Bluetooth SIG. This is the default value if no connection parameter update is requested.
32
+ * https://developer.android.com/reference/android/bluetooth/BluetoothGatt#CONNECTION_PRIORITY_BALANCED
33
+ */
34
+ ConnectionPriority[ConnectionPriority["CONNECTION_PRIORITY_BALANCED"] = 0] = "CONNECTION_PRIORITY_BALANCED";
35
+ /**
36
+ * Request a high priority, low latency connection. An application should only request high priority connection parameters to transfer large amounts of data over LE quickly. Once the transfer is complete, the application should request CONNECTION_PRIORITY_BALANCED connection parameters to reduce energy use.
37
+ * https://developer.android.com/reference/android/bluetooth/BluetoothGatt#CONNECTION_PRIORITY_HIGH
38
+ */
39
+ ConnectionPriority[ConnectionPriority["CONNECTION_PRIORITY_HIGH"] = 1] = "CONNECTION_PRIORITY_HIGH";
40
+ /**
41
+ * Request low power, reduced data rate connection parameters.
42
+ * https://developer.android.com/reference/android/bluetooth/BluetoothGatt#CONNECTION_PRIORITY_LOW_POWER
43
+ */
44
+ ConnectionPriority[ConnectionPriority["CONNECTION_PRIORITY_LOW_POWER"] = 2] = "CONNECTION_PRIORITY_LOW_POWER";
45
45
  })(exports.ConnectionPriority || (exports.ConnectionPriority = {}));
46
46
 
47
- /**
48
- * Convert an array of numbers into a DataView.
49
- */
50
- function numbersToDataView(value) {
51
- return new DataView(Uint8Array.from(value).buffer);
52
- }
53
- /**
54
- * Convert a DataView into an array of numbers.
55
- */
56
- function dataViewToNumbers(value) {
57
- return Array.from(new Uint8Array(value.buffer, value.byteOffset, value.byteLength));
58
- }
59
- /**
60
- * Convert a string into a DataView.
61
- */
62
- function textToDataView(value) {
63
- return numbersToDataView(value.split('').map((s) => s.charCodeAt(0)));
64
- }
65
- /**
66
- * Convert a DataView into a string.
67
- */
68
- function dataViewToText(value) {
69
- return String.fromCharCode(...dataViewToNumbers(value));
70
- }
71
- /**
72
- * Convert a 16 bit UUID into a 128 bit UUID string
73
- * @param value number, e.g. 0x180d
74
- * @return string, e.g. '0000180d-0000-1000-8000-00805f9b34fb'
75
- */
76
- function numberToUUID(value) {
77
- return `0000${value.toString(16).padStart(4, '0')}-0000-1000-8000-00805f9b34fb`;
78
- }
79
- /**
80
- * Convert a string of hex into a DataView of raw bytes.
81
- * Note: characters other than [0-9a-fA-F] are ignored
82
- * @param hex string of values, e.g. "00 01 02" or "000102"
83
- * @return DataView of raw bytes
84
- */
85
- function hexStringToDataView(hex) {
86
- const bin = [];
87
- let i, c, isEmpty = 1, buffer = 0;
88
- for (i = 0; i < hex.length; i++) {
89
- c = hex.charCodeAt(i);
90
- if ((c > 47 && c < 58) || (c > 64 && c < 71) || (c > 96 && c < 103)) {
91
- buffer = (buffer << 4) ^ ((c > 64 ? c + 9 : c) & 15);
92
- if ((isEmpty ^= 1)) {
93
- bin.push(buffer & 0xff);
94
- }
95
- }
96
- }
97
- return numbersToDataView(bin);
98
- }
99
- function dataViewToHexString(value) {
100
- return dataViewToNumbers(value)
101
- .map((n) => {
102
- let s = n.toString(16);
103
- if (s.length == 1) {
104
- s = '0' + s;
105
- }
106
- return s;
107
- })
108
- .join('');
109
- }
110
- function webUUIDToString(uuid) {
111
- if (typeof uuid === 'string') {
112
- return uuid;
113
- }
114
- else if (typeof uuid === 'number') {
115
- return numberToUUID(uuid);
116
- }
117
- else {
118
- throw new Error('Invalid UUID');
119
- }
120
- }
121
- function mapToObject(map) {
122
- const obj = {};
123
- if (!map) {
124
- return undefined;
125
- }
126
- map.forEach((value, key) => {
127
- obj[key.toString()] = value;
128
- });
129
- return obj;
47
+ /**
48
+ * Convert an array of numbers into a DataView.
49
+ */
50
+ function numbersToDataView(value) {
51
+ return new DataView(Uint8Array.from(value).buffer);
52
+ }
53
+ /**
54
+ * Convert a DataView into an array of numbers.
55
+ */
56
+ function dataViewToNumbers(value) {
57
+ return Array.from(new Uint8Array(value.buffer, value.byteOffset, value.byteLength));
58
+ }
59
+ /**
60
+ * Convert a string into a DataView.
61
+ */
62
+ function textToDataView(value) {
63
+ return numbersToDataView(value.split('').map((s) => s.charCodeAt(0)));
64
+ }
65
+ /**
66
+ * Convert a DataView into a string.
67
+ */
68
+ function dataViewToText(value) {
69
+ return String.fromCharCode(...dataViewToNumbers(value));
70
+ }
71
+ /**
72
+ * Convert a 16 bit UUID into a 128 bit UUID string
73
+ * @param value number, e.g. 0x180d
74
+ * @return string, e.g. '0000180d-0000-1000-8000-00805f9b34fb'
75
+ */
76
+ function numberToUUID(value) {
77
+ return `0000${value.toString(16).padStart(4, '0')}-0000-1000-8000-00805f9b34fb`;
78
+ }
79
+ /**
80
+ * Convert a string of hex into a DataView of raw bytes.
81
+ * Note: characters other than [0-9a-fA-F] are ignored
82
+ * @param hex string of values, e.g. "00 01 02" or "000102"
83
+ * @return DataView of raw bytes
84
+ */
85
+ function hexStringToDataView(hex) {
86
+ const bin = [];
87
+ let i, c, isEmpty = 1, buffer = 0;
88
+ for (i = 0; i < hex.length; i++) {
89
+ c = hex.charCodeAt(i);
90
+ if ((c > 47 && c < 58) || (c > 64 && c < 71) || (c > 96 && c < 103)) {
91
+ buffer = (buffer << 4) ^ ((c > 64 ? c + 9 : c) & 15);
92
+ if ((isEmpty ^= 1)) {
93
+ bin.push(buffer & 0xff);
94
+ }
95
+ }
96
+ }
97
+ return numbersToDataView(bin);
98
+ }
99
+ function dataViewToHexString(value) {
100
+ return dataViewToNumbers(value)
101
+ .map((n) => {
102
+ let s = n.toString(16);
103
+ if (s.length == 1) {
104
+ s = '0' + s;
105
+ }
106
+ return s;
107
+ })
108
+ .join('');
109
+ }
110
+ function webUUIDToString(uuid) {
111
+ if (typeof uuid === 'string') {
112
+ return uuid;
113
+ }
114
+ else if (typeof uuid === 'number') {
115
+ return numberToUUID(uuid);
116
+ }
117
+ else {
118
+ throw new Error('Invalid UUID');
119
+ }
120
+ }
121
+ function mapToObject(map) {
122
+ const obj = {};
123
+ if (!map) {
124
+ return undefined;
125
+ }
126
+ map.forEach((value, key) => {
127
+ obj[key.toString()] = value;
128
+ });
129
+ return obj;
130
130
  }
131
131
 
132
- const BluetoothLe = core.registerPlugin('BluetoothLe', {
133
- web: () => Promise.resolve().then(function () { return web; }).then((m) => new m.BluetoothLeWeb()),
132
+ const BluetoothLe = core.registerPlugin('BluetoothLe', {
133
+ web: () => Promise.resolve().then(function () { return web; }).then((m) => new m.BluetoothLeWeb()),
134
134
  });
135
135
 
136
- const makeQueue = () => {
137
- let currentTask = Promise.resolve();
138
- // create a new promise so that errors can be bubbled
139
- // up to the caller without being caught by the queue
140
- return (fn) => new Promise((resolve, reject) => {
141
- currentTask = currentTask
142
- .then(() => fn())
143
- .then(resolve)
144
- .catch(reject);
145
- });
146
- };
147
- function getQueue(enabled) {
148
- if (enabled) {
149
- return makeQueue();
150
- }
151
- return (fn) => fn();
136
+ const makeQueue = () => {
137
+ let currentTask = Promise.resolve();
138
+ // create a new promise so that errors can be bubbled
139
+ // up to the caller without being caught by the queue
140
+ return (fn) => new Promise((resolve, reject) => {
141
+ currentTask = currentTask
142
+ .then(() => fn())
143
+ .then(resolve)
144
+ .catch(reject);
145
+ });
146
+ };
147
+ function getQueue(enabled) {
148
+ if (enabled) {
149
+ return makeQueue();
150
+ }
151
+ return (fn) => fn();
152
152
  }
153
153
 
154
- function parseUUID(uuid) {
155
- if (typeof uuid !== 'string') {
156
- throw new Error(`Invalid UUID type ${typeof uuid}. Expected string.`);
157
- }
158
- uuid = uuid.toLowerCase();
159
- const is128BitUuid = uuid.search(/^[0-9a-f]{8}\b-[0-9a-f]{4}\b-[0-9a-f]{4}\b-[0-9a-f]{4}\b-[0-9a-f]{12}$/) >= 0;
160
- if (!is128BitUuid) {
161
- throw new Error(`Invalid UUID format ${uuid}. Expected 128 bit string (e.g. "0000180d-0000-1000-8000-00805f9b34fb").`);
162
- }
163
- return uuid;
154
+ function parseUUID(uuid) {
155
+ if (typeof uuid !== 'string') {
156
+ throw new Error(`Invalid UUID type ${typeof uuid}. Expected string.`);
157
+ }
158
+ uuid = uuid.toLowerCase();
159
+ const is128BitUuid = uuid.search(/^[0-9a-f]{8}\b-[0-9a-f]{4}\b-[0-9a-f]{4}\b-[0-9a-f]{4}\b-[0-9a-f]{12}$/) >= 0;
160
+ if (!is128BitUuid) {
161
+ throw new Error(`Invalid UUID format ${uuid}. Expected 128 bit string (e.g. "0000180d-0000-1000-8000-00805f9b34fb").`);
162
+ }
163
+ return uuid;
164
164
  }
165
165
 
166
- class BleClientClass {
167
- constructor() {
168
- this.scanListener = null;
169
- this.eventListeners = new Map();
170
- this.queue = getQueue(true);
171
- }
172
- enableQueue() {
173
- this.queue = getQueue(true);
174
- }
175
- disableQueue() {
176
- this.queue = getQueue(false);
177
- }
178
- async initialize(options) {
179
- await this.queue(async () => {
180
- await BluetoothLe.initialize(options);
181
- });
182
- }
183
- async isEnabled() {
184
- const enabled = await this.queue(async () => {
185
- const result = await BluetoothLe.isEnabled();
186
- return result.value;
187
- });
188
- return enabled;
189
- }
190
- async requestEnable() {
191
- await this.queue(async () => {
192
- await BluetoothLe.requestEnable();
193
- });
194
- }
195
- async enable() {
196
- await this.queue(async () => {
197
- await BluetoothLe.enable();
198
- });
199
- }
200
- async disable() {
201
- await this.queue(async () => {
202
- await BluetoothLe.disable();
203
- });
204
- }
205
- async startEnabledNotifications(callback) {
206
- await this.queue(async () => {
207
- var _a;
208
- const key = `onEnabledChanged`;
209
- await ((_a = this.eventListeners.get(key)) === null || _a === undefined ? undefined : _a.remove());
210
- const listener = await BluetoothLe.addListener(key, (result) => {
211
- callback(result.value);
212
- });
213
- this.eventListeners.set(key, listener);
214
- await BluetoothLe.startEnabledNotifications();
215
- });
216
- }
217
- async stopEnabledNotifications() {
218
- await this.queue(async () => {
219
- var _a;
220
- const key = `onEnabledChanged`;
221
- await ((_a = this.eventListeners.get(key)) === null || _a === undefined ? undefined : _a.remove());
222
- this.eventListeners.delete(key);
223
- await BluetoothLe.stopEnabledNotifications();
224
- });
225
- }
226
- async isLocationEnabled() {
227
- const enabled = await this.queue(async () => {
228
- const result = await BluetoothLe.isLocationEnabled();
229
- return result.value;
230
- });
231
- return enabled;
232
- }
233
- async openLocationSettings() {
234
- await this.queue(async () => {
235
- await BluetoothLe.openLocationSettings();
236
- });
237
- }
238
- async openBluetoothSettings() {
239
- await this.queue(async () => {
240
- await BluetoothLe.openBluetoothSettings();
241
- });
242
- }
243
- async openAppSettings() {
244
- await this.queue(async () => {
245
- await BluetoothLe.openAppSettings();
246
- });
247
- }
248
- async setDisplayStrings(displayStrings) {
249
- await this.queue(async () => {
250
- await BluetoothLe.setDisplayStrings(displayStrings);
251
- });
252
- }
253
- async requestDevice(options) {
254
- options = options ? this.validateRequestBleDeviceOptions(options) : undefined;
255
- const result = await this.queue(async () => {
256
- const device = await BluetoothLe.requestDevice(options);
257
- return device;
258
- });
259
- return result;
260
- }
261
- async requestLEScan(options, callback) {
262
- options = this.validateRequestBleDeviceOptions(options);
263
- await this.queue(async () => {
264
- var _a;
265
- await ((_a = this.scanListener) === null || _a === undefined ? undefined : _a.remove());
266
- this.scanListener = await BluetoothLe.addListener('onScanResult', (resultInternal) => {
267
- const result = Object.assign(Object.assign({}, resultInternal), { manufacturerData: this.convertObject(resultInternal.manufacturerData), serviceData: this.convertObject(resultInternal.serviceData), rawAdvertisement: resultInternal.rawAdvertisement
268
- ? this.convertValue(resultInternal.rawAdvertisement)
269
- : undefined });
270
- callback(result);
271
- });
272
- await BluetoothLe.requestLEScan(options);
273
- });
274
- }
275
- async stopLEScan() {
276
- await this.queue(async () => {
277
- var _a;
278
- await ((_a = this.scanListener) === null || _a === undefined ? undefined : _a.remove());
279
- this.scanListener = null;
280
- await BluetoothLe.stopLEScan();
281
- });
282
- }
283
- async getDevices(deviceIds) {
284
- if (!Array.isArray(deviceIds)) {
285
- throw new Error('deviceIds must be an array');
286
- }
287
- return this.queue(async () => {
288
- const result = await BluetoothLe.getDevices({ deviceIds });
289
- return result.devices;
290
- });
291
- }
292
- async getConnectedDevices(services) {
293
- if (!Array.isArray(services)) {
294
- throw new Error('services must be an array');
295
- }
296
- services = services.map(parseUUID);
297
- return this.queue(async () => {
298
- const result = await BluetoothLe.getConnectedDevices({ services });
299
- return result.devices;
300
- });
301
- }
302
- async getBondedDevices() {
303
- return this.queue(async () => {
304
- const result = await BluetoothLe.getBondedDevices();
305
- return result.devices;
306
- });
307
- }
308
- async connect(deviceId, onDisconnect, options) {
309
- await this.queue(async () => {
310
- var _a;
311
- if (onDisconnect) {
312
- const key = `disconnected|${deviceId}`;
313
- await ((_a = this.eventListeners.get(key)) === null || _a === undefined ? undefined : _a.remove());
314
- const listener = await BluetoothLe.addListener(key, () => {
315
- onDisconnect(deviceId);
316
- });
317
- this.eventListeners.set(key, listener);
318
- }
319
- await BluetoothLe.connect(Object.assign({ deviceId }, options));
320
- });
321
- }
322
- async createBond(deviceId, options) {
323
- await this.queue(async () => {
324
- await BluetoothLe.createBond(Object.assign({ deviceId }, options));
325
- });
326
- }
327
- async isBonded(deviceId) {
328
- const isBonded = await this.queue(async () => {
329
- const result = await BluetoothLe.isBonded({ deviceId });
330
- return result.value;
331
- });
332
- return isBonded;
333
- }
334
- async disconnect(deviceId) {
335
- await this.queue(async () => {
336
- await BluetoothLe.disconnect({ deviceId });
337
- });
338
- }
339
- async getServices(deviceId) {
340
- const services = await this.queue(async () => {
341
- const result = await BluetoothLe.getServices({ deviceId });
342
- return result.services;
343
- });
344
- return services;
345
- }
346
- async discoverServices(deviceId) {
347
- await this.queue(async () => {
348
- await BluetoothLe.discoverServices({ deviceId });
349
- });
350
- }
351
- async getMtu(deviceId) {
352
- const value = await this.queue(async () => {
353
- const result = await BluetoothLe.getMtu({ deviceId });
354
- return result.value;
355
- });
356
- return value;
357
- }
358
- async requestConnectionPriority(deviceId, connectionPriority) {
359
- await this.queue(async () => {
360
- await BluetoothLe.requestConnectionPriority({ deviceId, connectionPriority });
361
- });
362
- }
363
- async readRssi(deviceId) {
364
- const value = await this.queue(async () => {
365
- const result = await BluetoothLe.readRssi({ deviceId });
366
- return parseFloat(result.value);
367
- });
368
- return value;
369
- }
370
- async read(deviceId, service, characteristic, options) {
371
- service = parseUUID(service);
372
- characteristic = parseUUID(characteristic);
373
- const value = await this.queue(async () => {
374
- const result = await BluetoothLe.read(Object.assign({ deviceId,
375
- service,
376
- characteristic }, options));
377
- return this.convertValue(result.value);
378
- });
379
- return value;
380
- }
381
- async write(deviceId, service, characteristic, value, options) {
382
- service = parseUUID(service);
383
- characteristic = parseUUID(characteristic);
384
- return this.queue(async () => {
385
- if (!(value === null || value === undefined ? undefined : value.buffer)) {
386
- throw new Error('Invalid data.');
387
- }
388
- let writeValue = value;
389
- if (core.Capacitor.getPlatform() !== 'web') {
390
- // on native we can only write strings
391
- writeValue = dataViewToHexString(value);
392
- }
393
- await BluetoothLe.write(Object.assign({ deviceId,
394
- service,
395
- characteristic, value: writeValue }, options));
396
- });
397
- }
398
- async writeWithoutResponse(deviceId, service, characteristic, value, options) {
399
- service = parseUUID(service);
400
- characteristic = parseUUID(characteristic);
401
- await this.queue(async () => {
402
- if (!(value === null || value === undefined ? undefined : value.buffer)) {
403
- throw new Error('Invalid data.');
404
- }
405
- let writeValue = value;
406
- if (core.Capacitor.getPlatform() !== 'web') {
407
- // on native we can only write strings
408
- writeValue = dataViewToHexString(value);
409
- }
410
- await BluetoothLe.writeWithoutResponse(Object.assign({ deviceId,
411
- service,
412
- characteristic, value: writeValue }, options));
413
- });
414
- }
415
- async readDescriptor(deviceId, service, characteristic, descriptor, options) {
416
- service = parseUUID(service);
417
- characteristic = parseUUID(characteristic);
418
- descriptor = parseUUID(descriptor);
419
- const value = await this.queue(async () => {
420
- const result = await BluetoothLe.readDescriptor(Object.assign({ deviceId,
421
- service,
422
- characteristic,
423
- descriptor }, options));
424
- return this.convertValue(result.value);
425
- });
426
- return value;
427
- }
428
- async writeDescriptor(deviceId, service, characteristic, descriptor, value, options) {
429
- service = parseUUID(service);
430
- characteristic = parseUUID(characteristic);
431
- descriptor = parseUUID(descriptor);
432
- return this.queue(async () => {
433
- if (!(value === null || value === undefined ? undefined : value.buffer)) {
434
- throw new Error('Invalid data.');
435
- }
436
- let writeValue = value;
437
- if (core.Capacitor.getPlatform() !== 'web') {
438
- // on native we can only write strings
439
- writeValue = dataViewToHexString(value);
440
- }
441
- await BluetoothLe.writeDescriptor(Object.assign({ deviceId,
442
- service,
443
- characteristic,
444
- descriptor, value: writeValue }, options));
445
- });
446
- }
447
- async startNotifications(deviceId, service, characteristic, callback) {
448
- service = parseUUID(service);
449
- characteristic = parseUUID(characteristic);
450
- await this.queue(async () => {
451
- var _a;
452
- const key = `notification|${deviceId}|${service}|${characteristic}`;
453
- await ((_a = this.eventListeners.get(key)) === null || _a === undefined ? undefined : _a.remove());
454
- const listener = await BluetoothLe.addListener(key, (event) => {
455
- callback(this.convertValue(event === null || event === undefined ? undefined : event.value));
456
- });
457
- this.eventListeners.set(key, listener);
458
- await BluetoothLe.startNotifications({
459
- deviceId,
460
- service,
461
- characteristic,
462
- });
463
- });
464
- }
465
- async stopNotifications(deviceId, service, characteristic) {
466
- service = parseUUID(service);
467
- characteristic = parseUUID(characteristic);
468
- await this.queue(async () => {
469
- var _a;
470
- const key = `notification|${deviceId}|${service}|${characteristic}`;
471
- await ((_a = this.eventListeners.get(key)) === null || _a === undefined ? undefined : _a.remove());
472
- this.eventListeners.delete(key);
473
- await BluetoothLe.stopNotifications({
474
- deviceId,
475
- service,
476
- characteristic,
477
- });
478
- });
479
- }
480
- validateRequestBleDeviceOptions(options) {
481
- if (options.services) {
482
- options.services = options.services.map(parseUUID);
483
- }
484
- if (options.optionalServices) {
485
- options.optionalServices = options.optionalServices.map(parseUUID);
486
- }
487
- return options;
488
- }
489
- convertValue(value) {
490
- if (typeof value === 'string') {
491
- return hexStringToDataView(value);
492
- }
493
- else if (value === undefined) {
494
- return new DataView(new ArrayBuffer(0));
495
- }
496
- return value;
497
- }
498
- convertObject(obj) {
499
- if (obj === undefined) {
500
- return undefined;
501
- }
502
- const result = {};
503
- for (const key of Object.keys(obj)) {
504
- result[key] = this.convertValue(obj[key]);
505
- }
506
- return result;
507
- }
508
- }
166
+ class BleClientClass {
167
+ constructor() {
168
+ this.scanListener = null;
169
+ this.eventListeners = new Map();
170
+ this.queue = getQueue(true);
171
+ }
172
+ enableQueue() {
173
+ this.queue = getQueue(true);
174
+ }
175
+ disableQueue() {
176
+ this.queue = getQueue(false);
177
+ }
178
+ async initialize(options) {
179
+ await this.queue(async () => {
180
+ await BluetoothLe.initialize(options);
181
+ });
182
+ }
183
+ async isEnabled() {
184
+ const enabled = await this.queue(async () => {
185
+ const result = await BluetoothLe.isEnabled();
186
+ return result.value;
187
+ });
188
+ return enabled;
189
+ }
190
+ async requestEnable() {
191
+ await this.queue(async () => {
192
+ await BluetoothLe.requestEnable();
193
+ });
194
+ }
195
+ async enable() {
196
+ await this.queue(async () => {
197
+ await BluetoothLe.enable();
198
+ });
199
+ }
200
+ async disable() {
201
+ await this.queue(async () => {
202
+ await BluetoothLe.disable();
203
+ });
204
+ }
205
+ async startEnabledNotifications(callback) {
206
+ await this.queue(async () => {
207
+ var _a;
208
+ const key = `onEnabledChanged`;
209
+ await ((_a = this.eventListeners.get(key)) === null || _a === undefined ? undefined : _a.remove());
210
+ const listener = await BluetoothLe.addListener(key, (result) => {
211
+ callback(result.value);
212
+ });
213
+ this.eventListeners.set(key, listener);
214
+ await BluetoothLe.startEnabledNotifications();
215
+ });
216
+ }
217
+ async stopEnabledNotifications() {
218
+ await this.queue(async () => {
219
+ var _a;
220
+ const key = `onEnabledChanged`;
221
+ await ((_a = this.eventListeners.get(key)) === null || _a === undefined ? undefined : _a.remove());
222
+ this.eventListeners.delete(key);
223
+ await BluetoothLe.stopEnabledNotifications();
224
+ });
225
+ }
226
+ async isLocationEnabled() {
227
+ const enabled = await this.queue(async () => {
228
+ const result = await BluetoothLe.isLocationEnabled();
229
+ return result.value;
230
+ });
231
+ return enabled;
232
+ }
233
+ async openLocationSettings() {
234
+ await this.queue(async () => {
235
+ await BluetoothLe.openLocationSettings();
236
+ });
237
+ }
238
+ async openBluetoothSettings() {
239
+ await this.queue(async () => {
240
+ await BluetoothLe.openBluetoothSettings();
241
+ });
242
+ }
243
+ async openAppSettings() {
244
+ await this.queue(async () => {
245
+ await BluetoothLe.openAppSettings();
246
+ });
247
+ }
248
+ async setDisplayStrings(displayStrings) {
249
+ await this.queue(async () => {
250
+ await BluetoothLe.setDisplayStrings(displayStrings);
251
+ });
252
+ }
253
+ async requestDevice(options) {
254
+ options = options ? this.validateRequestBleDeviceOptions(options) : undefined;
255
+ const result = await this.queue(async () => {
256
+ const device = await BluetoothLe.requestDevice(options);
257
+ return device;
258
+ });
259
+ return result;
260
+ }
261
+ async requestLEScan(options, callback) {
262
+ options = this.validateRequestBleDeviceOptions(options);
263
+ await this.queue(async () => {
264
+ var _a;
265
+ await ((_a = this.scanListener) === null || _a === undefined ? undefined : _a.remove());
266
+ this.scanListener = await BluetoothLe.addListener('onScanResult', (resultInternal) => {
267
+ const result = Object.assign(Object.assign({}, resultInternal), { manufacturerData: this.convertObject(resultInternal.manufacturerData), serviceData: this.convertObject(resultInternal.serviceData), rawAdvertisement: resultInternal.rawAdvertisement
268
+ ? this.convertValue(resultInternal.rawAdvertisement)
269
+ : undefined });
270
+ callback(result);
271
+ });
272
+ await BluetoothLe.requestLEScan(options);
273
+ });
274
+ }
275
+ async stopLEScan() {
276
+ await this.queue(async () => {
277
+ var _a;
278
+ await ((_a = this.scanListener) === null || _a === undefined ? undefined : _a.remove());
279
+ this.scanListener = null;
280
+ await BluetoothLe.stopLEScan();
281
+ });
282
+ }
283
+ async getDevices(deviceIds) {
284
+ if (!Array.isArray(deviceIds)) {
285
+ throw new Error('deviceIds must be an array');
286
+ }
287
+ return this.queue(async () => {
288
+ const result = await BluetoothLe.getDevices({ deviceIds });
289
+ return result.devices;
290
+ });
291
+ }
292
+ async getConnectedDevices(services) {
293
+ if (!Array.isArray(services)) {
294
+ throw new Error('services must be an array');
295
+ }
296
+ services = services.map(parseUUID);
297
+ return this.queue(async () => {
298
+ const result = await BluetoothLe.getConnectedDevices({ services });
299
+ return result.devices;
300
+ });
301
+ }
302
+ async getBondedDevices() {
303
+ return this.queue(async () => {
304
+ const result = await BluetoothLe.getBondedDevices();
305
+ return result.devices;
306
+ });
307
+ }
308
+ async connect(deviceId, onDisconnect, options) {
309
+ await this.queue(async () => {
310
+ var _a;
311
+ if (onDisconnect) {
312
+ const key = `disconnected|${deviceId}`;
313
+ await ((_a = this.eventListeners.get(key)) === null || _a === undefined ? undefined : _a.remove());
314
+ const listener = await BluetoothLe.addListener(key, () => {
315
+ onDisconnect(deviceId);
316
+ });
317
+ this.eventListeners.set(key, listener);
318
+ }
319
+ await BluetoothLe.connect(Object.assign({ deviceId }, options));
320
+ });
321
+ }
322
+ async createBond(deviceId, options) {
323
+ await this.queue(async () => {
324
+ await BluetoothLe.createBond(Object.assign({ deviceId }, options));
325
+ });
326
+ }
327
+ async isBonded(deviceId) {
328
+ const isBonded = await this.queue(async () => {
329
+ const result = await BluetoothLe.isBonded({ deviceId });
330
+ return result.value;
331
+ });
332
+ return isBonded;
333
+ }
334
+ async disconnect(deviceId) {
335
+ await this.queue(async () => {
336
+ await BluetoothLe.disconnect({ deviceId });
337
+ });
338
+ }
339
+ async getServices(deviceId) {
340
+ const services = await this.queue(async () => {
341
+ const result = await BluetoothLe.getServices({ deviceId });
342
+ return result.services;
343
+ });
344
+ return services;
345
+ }
346
+ async discoverServices(deviceId) {
347
+ await this.queue(async () => {
348
+ await BluetoothLe.discoverServices({ deviceId });
349
+ });
350
+ }
351
+ async getMtu(deviceId) {
352
+ const value = await this.queue(async () => {
353
+ const result = await BluetoothLe.getMtu({ deviceId });
354
+ return result.value;
355
+ });
356
+ return value;
357
+ }
358
+ async requestConnectionPriority(deviceId, connectionPriority) {
359
+ await this.queue(async () => {
360
+ await BluetoothLe.requestConnectionPriority({ deviceId, connectionPriority });
361
+ });
362
+ }
363
+ async readRssi(deviceId) {
364
+ const value = await this.queue(async () => {
365
+ const result = await BluetoothLe.readRssi({ deviceId });
366
+ return parseFloat(result.value);
367
+ });
368
+ return value;
369
+ }
370
+ async read(deviceId, service, characteristic, options) {
371
+ service = parseUUID(service);
372
+ characteristic = parseUUID(characteristic);
373
+ const value = await this.queue(async () => {
374
+ const result = await BluetoothLe.read(Object.assign({ deviceId,
375
+ service,
376
+ characteristic }, options));
377
+ return this.convertValue(result.value);
378
+ });
379
+ return value;
380
+ }
381
+ async write(deviceId, service, characteristic, value, options) {
382
+ service = parseUUID(service);
383
+ characteristic = parseUUID(characteristic);
384
+ return this.queue(async () => {
385
+ if (!(value === null || value === undefined ? undefined : value.buffer)) {
386
+ throw new Error('Invalid data.');
387
+ }
388
+ let writeValue = value;
389
+ if (core.Capacitor.getPlatform() !== 'web') {
390
+ // on native we can only write strings
391
+ writeValue = dataViewToHexString(value);
392
+ }
393
+ await BluetoothLe.write(Object.assign({ deviceId,
394
+ service,
395
+ characteristic, value: writeValue }, options));
396
+ });
397
+ }
398
+ async writeWithoutResponse(deviceId, service, characteristic, value, options) {
399
+ service = parseUUID(service);
400
+ characteristic = parseUUID(characteristic);
401
+ await this.queue(async () => {
402
+ if (!(value === null || value === undefined ? undefined : value.buffer)) {
403
+ throw new Error('Invalid data.');
404
+ }
405
+ let writeValue = value;
406
+ if (core.Capacitor.getPlatform() !== 'web') {
407
+ // on native we can only write strings
408
+ writeValue = dataViewToHexString(value);
409
+ }
410
+ await BluetoothLe.writeWithoutResponse(Object.assign({ deviceId,
411
+ service,
412
+ characteristic, value: writeValue }, options));
413
+ });
414
+ }
415
+ async readDescriptor(deviceId, service, characteristic, descriptor, options) {
416
+ service = parseUUID(service);
417
+ characteristic = parseUUID(characteristic);
418
+ descriptor = parseUUID(descriptor);
419
+ const value = await this.queue(async () => {
420
+ const result = await BluetoothLe.readDescriptor(Object.assign({ deviceId,
421
+ service,
422
+ characteristic,
423
+ descriptor }, options));
424
+ return this.convertValue(result.value);
425
+ });
426
+ return value;
427
+ }
428
+ async writeDescriptor(deviceId, service, characteristic, descriptor, value, options) {
429
+ service = parseUUID(service);
430
+ characteristic = parseUUID(characteristic);
431
+ descriptor = parseUUID(descriptor);
432
+ return this.queue(async () => {
433
+ if (!(value === null || value === undefined ? undefined : value.buffer)) {
434
+ throw new Error('Invalid data.');
435
+ }
436
+ let writeValue = value;
437
+ if (core.Capacitor.getPlatform() !== 'web') {
438
+ // on native we can only write strings
439
+ writeValue = dataViewToHexString(value);
440
+ }
441
+ await BluetoothLe.writeDescriptor(Object.assign({ deviceId,
442
+ service,
443
+ characteristic,
444
+ descriptor, value: writeValue }, options));
445
+ });
446
+ }
447
+ async startNotifications(deviceId, service, characteristic, callback) {
448
+ service = parseUUID(service);
449
+ characteristic = parseUUID(characteristic);
450
+ await this.queue(async () => {
451
+ var _a;
452
+ const key = `notification|${deviceId}|${service}|${characteristic}`;
453
+ await ((_a = this.eventListeners.get(key)) === null || _a === undefined ? undefined : _a.remove());
454
+ const listener = await BluetoothLe.addListener(key, (event) => {
455
+ callback(this.convertValue(event === null || event === undefined ? undefined : event.value));
456
+ });
457
+ this.eventListeners.set(key, listener);
458
+ await BluetoothLe.startNotifications({
459
+ deviceId,
460
+ service,
461
+ characteristic,
462
+ });
463
+ });
464
+ }
465
+ async stopNotifications(deviceId, service, characteristic) {
466
+ service = parseUUID(service);
467
+ characteristic = parseUUID(characteristic);
468
+ await this.queue(async () => {
469
+ var _a;
470
+ const key = `notification|${deviceId}|${service}|${characteristic}`;
471
+ await ((_a = this.eventListeners.get(key)) === null || _a === undefined ? undefined : _a.remove());
472
+ this.eventListeners.delete(key);
473
+ await BluetoothLe.stopNotifications({
474
+ deviceId,
475
+ service,
476
+ characteristic,
477
+ });
478
+ });
479
+ }
480
+ validateRequestBleDeviceOptions(options) {
481
+ if (options.services) {
482
+ options.services = options.services.map(parseUUID);
483
+ }
484
+ if (options.optionalServices) {
485
+ options.optionalServices = options.optionalServices.map(parseUUID);
486
+ }
487
+ return options;
488
+ }
489
+ convertValue(value) {
490
+ if (typeof value === 'string') {
491
+ return hexStringToDataView(value);
492
+ }
493
+ else if (value === undefined) {
494
+ return new DataView(new ArrayBuffer(0));
495
+ }
496
+ return value;
497
+ }
498
+ convertObject(obj) {
499
+ if (obj === undefined) {
500
+ return undefined;
501
+ }
502
+ const result = {};
503
+ for (const key of Object.keys(obj)) {
504
+ result[key] = this.convertValue(obj[key]);
505
+ }
506
+ return result;
507
+ }
508
+ }
509
509
  const BleClient = new BleClientClass();
510
510
 
511
- async function runWithTimeout(promise, time, exception) {
512
- let timer;
513
- return Promise.race([
514
- promise,
515
- new Promise((_, reject) => {
516
- timer = setTimeout(() => reject(exception), time);
517
- }),
518
- ]).finally(() => clearTimeout(timer));
511
+ async function runWithTimeout(promise, time, exception) {
512
+ let timer;
513
+ return Promise.race([
514
+ promise,
515
+ new Promise((_, reject) => {
516
+ timer = setTimeout(() => reject(exception), time);
517
+ }),
518
+ ]).finally(() => clearTimeout(timer));
519
519
  }
520
520
 
521
- class BluetoothLeWeb extends core.WebPlugin {
522
- constructor() {
523
- super(...arguments);
524
- this.deviceMap = new Map();
525
- this.discoveredDevices = new Map();
526
- this.scan = null;
527
- this.DEFAULT_CONNECTION_TIMEOUT = 10000;
528
- this.onAdvertisementReceivedCallback = this.onAdvertisementReceived.bind(this);
529
- this.onDisconnectedCallback = this.onDisconnected.bind(this);
530
- this.onCharacteristicValueChangedCallback = this.onCharacteristicValueChanged.bind(this);
531
- }
532
- async initialize() {
533
- if (typeof navigator === 'undefined' || !navigator.bluetooth) {
534
- throw this.unavailable('Web Bluetooth API not available in this browser.');
535
- }
536
- const isAvailable = await navigator.bluetooth.getAvailability();
537
- if (!isAvailable) {
538
- throw this.unavailable('No Bluetooth radio available.');
539
- }
540
- }
541
- async isEnabled() {
542
- // not available on web
543
- return { value: true };
544
- }
545
- async requestEnable() {
546
- throw this.unavailable('requestEnable is not available on web.');
547
- }
548
- async enable() {
549
- throw this.unavailable('enable is not available on web.');
550
- }
551
- async disable() {
552
- throw this.unavailable('disable is not available on web.');
553
- }
554
- async startEnabledNotifications() {
555
- // not available on web
556
- }
557
- async stopEnabledNotifications() {
558
- // not available on web
559
- }
560
- async isLocationEnabled() {
561
- throw this.unavailable('isLocationEnabled is not available on web.');
562
- }
563
- async openLocationSettings() {
564
- throw this.unavailable('openLocationSettings is not available on web.');
565
- }
566
- async openBluetoothSettings() {
567
- throw this.unavailable('openBluetoothSettings is not available on web.');
568
- }
569
- async openAppSettings() {
570
- throw this.unavailable('openAppSettings is not available on web.');
571
- }
572
- async setDisplayStrings() {
573
- // not available on web
574
- }
575
- async requestDevice(options) {
576
- const filters = this.getFilters(options);
577
- const device = await navigator.bluetooth.requestDevice({
578
- filters: filters.length ? filters : undefined,
579
- optionalServices: options === null || options === undefined ? undefined : options.optionalServices,
580
- acceptAllDevices: filters.length === 0,
581
- });
582
- this.deviceMap.set(device.id, device);
583
- const bleDevice = this.getBleDevice(device);
584
- return bleDevice;
585
- }
586
- async requestLEScan(options) {
587
- this.requestBleDeviceOptions = options;
588
- const filters = this.getFilters(options);
589
- await this.stopLEScan();
590
- this.discoveredDevices = new Map();
591
- navigator.bluetooth.removeEventListener('advertisementreceived', this.onAdvertisementReceivedCallback);
592
- navigator.bluetooth.addEventListener('advertisementreceived', this.onAdvertisementReceivedCallback);
593
- this.scan = await navigator.bluetooth.requestLEScan({
594
- filters: filters.length ? filters : undefined,
595
- acceptAllAdvertisements: filters.length === 0,
596
- keepRepeatedDevices: options === null || options === undefined ? undefined : options.allowDuplicates,
597
- });
598
- }
599
- onAdvertisementReceived(event) {
600
- var _a, _b;
601
- const deviceId = event.device.id;
602
- this.deviceMap.set(deviceId, event.device);
603
- const isNew = !this.discoveredDevices.has(deviceId);
604
- if (isNew || ((_a = this.requestBleDeviceOptions) === null || _a === undefined ? undefined : _a.allowDuplicates)) {
605
- this.discoveredDevices.set(deviceId, true);
606
- const device = this.getBleDevice(event.device);
607
- const result = {
608
- device,
609
- localName: device.name,
610
- rssi: event.rssi,
611
- txPower: event.txPower,
612
- manufacturerData: mapToObject(event.manufacturerData),
613
- serviceData: mapToObject(event.serviceData),
614
- uuids: (_b = event.uuids) === null || _b === undefined ? undefined : _b.map(webUUIDToString),
615
- };
616
- this.notifyListeners('onScanResult', result);
617
- }
618
- }
619
- async stopLEScan() {
620
- var _a;
621
- if ((_a = this.scan) === null || _a === undefined ? undefined : _a.active) {
622
- this.scan.stop();
623
- }
624
- this.scan = null;
625
- }
626
- async getDevices(options) {
627
- const devices = await navigator.bluetooth.getDevices();
628
- const bleDevices = devices
629
- .filter((device) => options.deviceIds.includes(device.id))
630
- .map((device) => {
631
- this.deviceMap.set(device.id, device);
632
- const bleDevice = this.getBleDevice(device);
633
- return bleDevice;
634
- });
635
- return { devices: bleDevices };
636
- }
637
- async getConnectedDevices(_options) {
638
- const devices = await navigator.bluetooth.getDevices();
639
- const bleDevices = devices
640
- .filter((device) => {
641
- var _a;
642
- return (_a = device.gatt) === null || _a === undefined ? undefined : _a.connected;
643
- })
644
- .map((device) => {
645
- this.deviceMap.set(device.id, device);
646
- const bleDevice = this.getBleDevice(device);
647
- return bleDevice;
648
- });
649
- return { devices: bleDevices };
650
- }
651
- async getBondedDevices() {
652
- return {};
653
- }
654
- async connect(options) {
655
- var _a, _b;
656
- const device = this.getDeviceFromMap(options.deviceId);
657
- device.removeEventListener('gattserverdisconnected', this.onDisconnectedCallback);
658
- device.addEventListener('gattserverdisconnected', this.onDisconnectedCallback);
659
- const timeoutError = Symbol();
660
- if (device.gatt === undefined) {
661
- throw new Error('No gatt server available.');
662
- }
663
- try {
664
- const timeout = (_a = options.timeout) !== null && _a !== void 0 ? _a : this.DEFAULT_CONNECTION_TIMEOUT;
665
- await runWithTimeout(device.gatt.connect(), timeout, timeoutError);
666
- }
667
- catch (error) {
668
- // cancel pending connect call, does not work yet in chromium because of a bug:
669
- // https://bugs.chromium.org/p/chromium/issues/detail?id=684073
670
- await ((_b = device.gatt) === null || _b === undefined ? undefined : _b.disconnect());
671
- if (error === timeoutError) {
672
- throw new Error('Connection timeout');
673
- }
674
- else {
675
- throw error;
676
- }
677
- }
678
- }
679
- onDisconnected(event) {
680
- const deviceId = event.target.id;
681
- const key = `disconnected|${deviceId}`;
682
- this.notifyListeners(key, null);
683
- }
684
- async createBond(_options) {
685
- throw this.unavailable('createBond is not available on web.');
686
- }
687
- async isBonded(_options) {
688
- throw this.unavailable('isBonded is not available on web.');
689
- }
690
- async disconnect(options) {
691
- var _a;
692
- (_a = this.getDeviceFromMap(options.deviceId).gatt) === null || _a === undefined ? undefined : _a.disconnect();
693
- }
694
- async getServices(options) {
695
- var _a, _b;
696
- const services = (_b = (await ((_a = this.getDeviceFromMap(options.deviceId).gatt) === null || _a === undefined ? undefined : _a.getPrimaryServices()))) !== null && _b !== undefined ? _b : [];
697
- const bleServices = [];
698
- for (const service of services) {
699
- const characteristics = await service.getCharacteristics();
700
- const bleCharacteristics = [];
701
- for (const characteristic of characteristics) {
702
- bleCharacteristics.push({
703
- uuid: characteristic.uuid,
704
- properties: this.getProperties(characteristic),
705
- descriptors: await this.getDescriptors(characteristic),
706
- });
707
- }
708
- bleServices.push({ uuid: service.uuid, characteristics: bleCharacteristics });
709
- }
710
- return { services: bleServices };
711
- }
712
- async getDescriptors(characteristic) {
713
- try {
714
- const descriptors = await characteristic.getDescriptors();
715
- return descriptors.map((descriptor) => ({
716
- uuid: descriptor.uuid,
717
- }));
718
- }
719
- catch (_a) {
720
- return [];
721
- }
722
- }
723
- getProperties(characteristic) {
724
- return {
725
- broadcast: characteristic.properties.broadcast,
726
- read: characteristic.properties.read,
727
- writeWithoutResponse: characteristic.properties.writeWithoutResponse,
728
- write: characteristic.properties.write,
729
- notify: characteristic.properties.notify,
730
- indicate: characteristic.properties.indicate,
731
- authenticatedSignedWrites: characteristic.properties.authenticatedSignedWrites,
732
- reliableWrite: characteristic.properties.reliableWrite,
733
- writableAuxiliaries: characteristic.properties.writableAuxiliaries,
734
- };
735
- }
736
- async getCharacteristic(options) {
737
- var _a;
738
- const service = await ((_a = this.getDeviceFromMap(options.deviceId).gatt) === null || _a === undefined ? undefined : _a.getPrimaryService(options === null || options === undefined ? undefined : options.service));
739
- return service === null || service === undefined ? undefined : service.getCharacteristic(options === null || options === undefined ? undefined : options.characteristic);
740
- }
741
- async getDescriptor(options) {
742
- const characteristic = await this.getCharacteristic(options);
743
- return characteristic === null || characteristic === undefined ? undefined : characteristic.getDescriptor(options === null || options === undefined ? undefined : options.descriptor);
744
- }
745
- async discoverServices(_options) {
746
- throw this.unavailable('discoverServices is not available on web.');
747
- }
748
- async getMtu(_options) {
749
- throw this.unavailable('getMtu is not available on web.');
750
- }
751
- async requestConnectionPriority(_options) {
752
- throw this.unavailable('requestConnectionPriority is not available on web.');
753
- }
754
- async readRssi(_options) {
755
- throw this.unavailable('readRssi is not available on web.');
756
- }
757
- async read(options) {
758
- const characteristic = await this.getCharacteristic(options);
759
- const value = await (characteristic === null || characteristic === undefined ? undefined : characteristic.readValue());
760
- return { value };
761
- }
762
- async write(options) {
763
- const characteristic = await this.getCharacteristic(options);
764
- let dataView;
765
- if (typeof options.value === 'string') {
766
- dataView = hexStringToDataView(options.value);
767
- }
768
- else {
769
- dataView = options.value;
770
- }
771
- await (characteristic === null || characteristic === undefined ? undefined : characteristic.writeValueWithResponse(dataView));
772
- }
773
- async writeWithoutResponse(options) {
774
- const characteristic = await this.getCharacteristic(options);
775
- let dataView;
776
- if (typeof options.value === 'string') {
777
- dataView = hexStringToDataView(options.value);
778
- }
779
- else {
780
- dataView = options.value;
781
- }
782
- await (characteristic === null || characteristic === undefined ? undefined : characteristic.writeValueWithoutResponse(dataView));
783
- }
784
- async readDescriptor(options) {
785
- const descriptor = await this.getDescriptor(options);
786
- const value = await (descriptor === null || descriptor === undefined ? undefined : descriptor.readValue());
787
- return { value };
788
- }
789
- async writeDescriptor(options) {
790
- const descriptor = await this.getDescriptor(options);
791
- let dataView;
792
- if (typeof options.value === 'string') {
793
- dataView = hexStringToDataView(options.value);
794
- }
795
- else {
796
- dataView = options.value;
797
- }
798
- await (descriptor === null || descriptor === undefined ? undefined : descriptor.writeValue(dataView));
799
- }
800
- async startNotifications(options) {
801
- const characteristic = await this.getCharacteristic(options);
802
- characteristic === null || characteristic === undefined ? undefined : characteristic.removeEventListener('characteristicvaluechanged', this.onCharacteristicValueChangedCallback);
803
- characteristic === null || characteristic === undefined ? undefined : characteristic.addEventListener('characteristicvaluechanged', this.onCharacteristicValueChangedCallback);
804
- await (characteristic === null || characteristic === undefined ? undefined : characteristic.startNotifications());
805
- }
806
- onCharacteristicValueChanged(event) {
807
- var _a, _b;
808
- const characteristic = event.target;
809
- const key = `notification|${(_a = characteristic.service) === null || _a === undefined ? undefined : _a.device.id}|${(_b = characteristic.service) === null || _b === undefined ? undefined : _b.uuid}|${characteristic.uuid}`;
810
- this.notifyListeners(key, {
811
- value: characteristic.value,
812
- });
813
- }
814
- async stopNotifications(options) {
815
- const characteristic = await this.getCharacteristic(options);
816
- await (characteristic === null || characteristic === undefined ? undefined : characteristic.stopNotifications());
817
- }
818
- getFilters(options) {
819
- var _a;
820
- const filters = [];
821
- for (const service of (_a = options === null || options === undefined ? undefined : options.services) !== null && _a !== undefined ? _a : []) {
822
- filters.push({
823
- services: [service],
824
- name: options === null || options === undefined ? undefined : options.name,
825
- namePrefix: options === null || options === undefined ? undefined : options.namePrefix,
826
- });
827
- }
828
- if (((options === null || options === undefined ? undefined : options.name) || (options === null || options === undefined ? undefined : options.namePrefix)) && filters.length === 0) {
829
- filters.push({
830
- name: options.name,
831
- namePrefix: options.namePrefix,
832
- });
833
- }
834
- return filters;
835
- }
836
- getDeviceFromMap(deviceId) {
837
- const device = this.deviceMap.get(deviceId);
838
- if (device === undefined) {
839
- throw new Error('Device not found. Call "requestDevice", "requestLEScan" or "getDevices" first.');
840
- }
841
- return device;
842
- }
843
- getBleDevice(device) {
844
- var _a;
845
- const bleDevice = {
846
- deviceId: device.id,
847
- // use undefined instead of null if name is not available
848
- name: (_a = device.name) !== null && _a !== undefined ? _a : undefined,
849
- };
850
- return bleDevice;
851
- }
521
+ class BluetoothLeWeb extends core.WebPlugin {
522
+ constructor() {
523
+ super(...arguments);
524
+ this.deviceMap = new Map();
525
+ this.discoveredDevices = new Map();
526
+ this.scan = null;
527
+ this.DEFAULT_CONNECTION_TIMEOUT = 10000;
528
+ this.onAdvertisementReceivedCallback = this.onAdvertisementReceived.bind(this);
529
+ this.onDisconnectedCallback = this.onDisconnected.bind(this);
530
+ this.onCharacteristicValueChangedCallback = this.onCharacteristicValueChanged.bind(this);
531
+ }
532
+ async initialize() {
533
+ if (typeof navigator === 'undefined' || !navigator.bluetooth) {
534
+ throw this.unavailable('Web Bluetooth API not available in this browser.');
535
+ }
536
+ const isAvailable = await navigator.bluetooth.getAvailability();
537
+ if (!isAvailable) {
538
+ throw this.unavailable('No Bluetooth radio available.');
539
+ }
540
+ }
541
+ async isEnabled() {
542
+ // not available on web
543
+ return { value: true };
544
+ }
545
+ async requestEnable() {
546
+ throw this.unavailable('requestEnable is not available on web.');
547
+ }
548
+ async enable() {
549
+ throw this.unavailable('enable is not available on web.');
550
+ }
551
+ async disable() {
552
+ throw this.unavailable('disable is not available on web.');
553
+ }
554
+ async startEnabledNotifications() {
555
+ // not available on web
556
+ }
557
+ async stopEnabledNotifications() {
558
+ // not available on web
559
+ }
560
+ async isLocationEnabled() {
561
+ throw this.unavailable('isLocationEnabled is not available on web.');
562
+ }
563
+ async openLocationSettings() {
564
+ throw this.unavailable('openLocationSettings is not available on web.');
565
+ }
566
+ async openBluetoothSettings() {
567
+ throw this.unavailable('openBluetoothSettings is not available on web.');
568
+ }
569
+ async openAppSettings() {
570
+ throw this.unavailable('openAppSettings is not available on web.');
571
+ }
572
+ async setDisplayStrings() {
573
+ // not available on web
574
+ }
575
+ async requestDevice(options) {
576
+ const filters = this.getFilters(options);
577
+ const device = await navigator.bluetooth.requestDevice({
578
+ filters: filters.length ? filters : undefined,
579
+ optionalServices: options === null || options === undefined ? undefined : options.optionalServices,
580
+ acceptAllDevices: filters.length === 0,
581
+ });
582
+ this.deviceMap.set(device.id, device);
583
+ const bleDevice = this.getBleDevice(device);
584
+ return bleDevice;
585
+ }
586
+ async requestLEScan(options) {
587
+ this.requestBleDeviceOptions = options;
588
+ const filters = this.getFilters(options);
589
+ await this.stopLEScan();
590
+ this.discoveredDevices = new Map();
591
+ navigator.bluetooth.removeEventListener('advertisementreceived', this.onAdvertisementReceivedCallback);
592
+ navigator.bluetooth.addEventListener('advertisementreceived', this.onAdvertisementReceivedCallback);
593
+ this.scan = await navigator.bluetooth.requestLEScan({
594
+ filters: filters.length ? filters : undefined,
595
+ acceptAllAdvertisements: filters.length === 0,
596
+ keepRepeatedDevices: options === null || options === undefined ? undefined : options.allowDuplicates,
597
+ });
598
+ }
599
+ onAdvertisementReceived(event) {
600
+ var _a, _b;
601
+ const deviceId = event.device.id;
602
+ this.deviceMap.set(deviceId, event.device);
603
+ const isNew = !this.discoveredDevices.has(deviceId);
604
+ if (isNew || ((_a = this.requestBleDeviceOptions) === null || _a === undefined ? undefined : _a.allowDuplicates)) {
605
+ this.discoveredDevices.set(deviceId, true);
606
+ const device = this.getBleDevice(event.device);
607
+ const result = {
608
+ device,
609
+ localName: device.name,
610
+ rssi: event.rssi,
611
+ txPower: event.txPower,
612
+ manufacturerData: mapToObject(event.manufacturerData),
613
+ serviceData: mapToObject(event.serviceData),
614
+ uuids: (_b = event.uuids) === null || _b === undefined ? undefined : _b.map(webUUIDToString),
615
+ };
616
+ this.notifyListeners('onScanResult', result);
617
+ }
618
+ }
619
+ async stopLEScan() {
620
+ var _a;
621
+ if ((_a = this.scan) === null || _a === undefined ? undefined : _a.active) {
622
+ this.scan.stop();
623
+ }
624
+ this.scan = null;
625
+ }
626
+ async getDevices(options) {
627
+ const devices = await navigator.bluetooth.getDevices();
628
+ const bleDevices = devices
629
+ .filter((device) => options.deviceIds.includes(device.id))
630
+ .map((device) => {
631
+ this.deviceMap.set(device.id, device);
632
+ const bleDevice = this.getBleDevice(device);
633
+ return bleDevice;
634
+ });
635
+ return { devices: bleDevices };
636
+ }
637
+ async getConnectedDevices(_options) {
638
+ const devices = await navigator.bluetooth.getDevices();
639
+ const bleDevices = devices
640
+ .filter((device) => {
641
+ var _a;
642
+ return (_a = device.gatt) === null || _a === undefined ? undefined : _a.connected;
643
+ })
644
+ .map((device) => {
645
+ this.deviceMap.set(device.id, device);
646
+ const bleDevice = this.getBleDevice(device);
647
+ return bleDevice;
648
+ });
649
+ return { devices: bleDevices };
650
+ }
651
+ async getBondedDevices() {
652
+ return {};
653
+ }
654
+ async connect(options) {
655
+ var _a, _b;
656
+ const device = this.getDeviceFromMap(options.deviceId);
657
+ device.removeEventListener('gattserverdisconnected', this.onDisconnectedCallback);
658
+ device.addEventListener('gattserverdisconnected', this.onDisconnectedCallback);
659
+ const timeoutError = Symbol();
660
+ if (device.gatt === undefined) {
661
+ throw new Error('No gatt server available.');
662
+ }
663
+ try {
664
+ const timeout = (_a = options.timeout) !== null && _a !== void 0 ? _a : this.DEFAULT_CONNECTION_TIMEOUT;
665
+ await runWithTimeout(device.gatt.connect(), timeout, timeoutError);
666
+ }
667
+ catch (error) {
668
+ // cancel pending connect call, does not work yet in chromium because of a bug:
669
+ // https://bugs.chromium.org/p/chromium/issues/detail?id=684073
670
+ await ((_b = device.gatt) === null || _b === undefined ? undefined : _b.disconnect());
671
+ if (error === timeoutError) {
672
+ throw new Error('Connection timeout');
673
+ }
674
+ else {
675
+ throw error;
676
+ }
677
+ }
678
+ }
679
+ onDisconnected(event) {
680
+ const deviceId = event.target.id;
681
+ const key = `disconnected|${deviceId}`;
682
+ this.notifyListeners(key, null);
683
+ }
684
+ async createBond(_options) {
685
+ throw this.unavailable('createBond is not available on web.');
686
+ }
687
+ async isBonded(_options) {
688
+ throw this.unavailable('isBonded is not available on web.');
689
+ }
690
+ async disconnect(options) {
691
+ var _a;
692
+ (_a = this.getDeviceFromMap(options.deviceId).gatt) === null || _a === undefined ? undefined : _a.disconnect();
693
+ }
694
+ async getServices(options) {
695
+ var _a, _b;
696
+ const services = (_b = (await ((_a = this.getDeviceFromMap(options.deviceId).gatt) === null || _a === undefined ? undefined : _a.getPrimaryServices()))) !== null && _b !== undefined ? _b : [];
697
+ const bleServices = [];
698
+ for (const service of services) {
699
+ const characteristics = await service.getCharacteristics();
700
+ const bleCharacteristics = [];
701
+ for (const characteristic of characteristics) {
702
+ bleCharacteristics.push({
703
+ uuid: characteristic.uuid,
704
+ properties: this.getProperties(characteristic),
705
+ descriptors: await this.getDescriptors(characteristic),
706
+ });
707
+ }
708
+ bleServices.push({ uuid: service.uuid, characteristics: bleCharacteristics });
709
+ }
710
+ return { services: bleServices };
711
+ }
712
+ async getDescriptors(characteristic) {
713
+ try {
714
+ const descriptors = await characteristic.getDescriptors();
715
+ return descriptors.map((descriptor) => ({
716
+ uuid: descriptor.uuid,
717
+ }));
718
+ }
719
+ catch (_a) {
720
+ return [];
721
+ }
722
+ }
723
+ getProperties(characteristic) {
724
+ return {
725
+ broadcast: characteristic.properties.broadcast,
726
+ read: characteristic.properties.read,
727
+ writeWithoutResponse: characteristic.properties.writeWithoutResponse,
728
+ write: characteristic.properties.write,
729
+ notify: characteristic.properties.notify,
730
+ indicate: characteristic.properties.indicate,
731
+ authenticatedSignedWrites: characteristic.properties.authenticatedSignedWrites,
732
+ reliableWrite: characteristic.properties.reliableWrite,
733
+ writableAuxiliaries: characteristic.properties.writableAuxiliaries,
734
+ };
735
+ }
736
+ async getCharacteristic(options) {
737
+ var _a;
738
+ const service = await ((_a = this.getDeviceFromMap(options.deviceId).gatt) === null || _a === undefined ? undefined : _a.getPrimaryService(options === null || options === undefined ? undefined : options.service));
739
+ return service === null || service === undefined ? undefined : service.getCharacteristic(options === null || options === undefined ? undefined : options.characteristic);
740
+ }
741
+ async getDescriptor(options) {
742
+ const characteristic = await this.getCharacteristic(options);
743
+ return characteristic === null || characteristic === undefined ? undefined : characteristic.getDescriptor(options === null || options === undefined ? undefined : options.descriptor);
744
+ }
745
+ async discoverServices(_options) {
746
+ throw this.unavailable('discoverServices is not available on web.');
747
+ }
748
+ async getMtu(_options) {
749
+ throw this.unavailable('getMtu is not available on web.');
750
+ }
751
+ async requestConnectionPriority(_options) {
752
+ throw this.unavailable('requestConnectionPriority is not available on web.');
753
+ }
754
+ async readRssi(_options) {
755
+ throw this.unavailable('readRssi is not available on web.');
756
+ }
757
+ async read(options) {
758
+ const characteristic = await this.getCharacteristic(options);
759
+ const value = await (characteristic === null || characteristic === undefined ? undefined : characteristic.readValue());
760
+ return { value };
761
+ }
762
+ async write(options) {
763
+ const characteristic = await this.getCharacteristic(options);
764
+ let dataView;
765
+ if (typeof options.value === 'string') {
766
+ dataView = hexStringToDataView(options.value);
767
+ }
768
+ else {
769
+ dataView = options.value;
770
+ }
771
+ await (characteristic === null || characteristic === undefined ? undefined : characteristic.writeValueWithResponse(dataView));
772
+ }
773
+ async writeWithoutResponse(options) {
774
+ const characteristic = await this.getCharacteristic(options);
775
+ let dataView;
776
+ if (typeof options.value === 'string') {
777
+ dataView = hexStringToDataView(options.value);
778
+ }
779
+ else {
780
+ dataView = options.value;
781
+ }
782
+ await (characteristic === null || characteristic === undefined ? undefined : characteristic.writeValueWithoutResponse(dataView));
783
+ }
784
+ async readDescriptor(options) {
785
+ const descriptor = await this.getDescriptor(options);
786
+ const value = await (descriptor === null || descriptor === undefined ? undefined : descriptor.readValue());
787
+ return { value };
788
+ }
789
+ async writeDescriptor(options) {
790
+ const descriptor = await this.getDescriptor(options);
791
+ let dataView;
792
+ if (typeof options.value === 'string') {
793
+ dataView = hexStringToDataView(options.value);
794
+ }
795
+ else {
796
+ dataView = options.value;
797
+ }
798
+ await (descriptor === null || descriptor === undefined ? undefined : descriptor.writeValue(dataView));
799
+ }
800
+ async startNotifications(options) {
801
+ const characteristic = await this.getCharacteristic(options);
802
+ characteristic === null || characteristic === undefined ? undefined : characteristic.removeEventListener('characteristicvaluechanged', this.onCharacteristicValueChangedCallback);
803
+ characteristic === null || characteristic === undefined ? undefined : characteristic.addEventListener('characteristicvaluechanged', this.onCharacteristicValueChangedCallback);
804
+ await (characteristic === null || characteristic === undefined ? undefined : characteristic.startNotifications());
805
+ }
806
+ onCharacteristicValueChanged(event) {
807
+ var _a, _b;
808
+ const characteristic = event.target;
809
+ const key = `notification|${(_a = characteristic.service) === null || _a === undefined ? undefined : _a.device.id}|${(_b = characteristic.service) === null || _b === undefined ? undefined : _b.uuid}|${characteristic.uuid}`;
810
+ this.notifyListeners(key, {
811
+ value: characteristic.value,
812
+ });
813
+ }
814
+ async stopNotifications(options) {
815
+ const characteristic = await this.getCharacteristic(options);
816
+ await (characteristic === null || characteristic === undefined ? undefined : characteristic.stopNotifications());
817
+ }
818
+ getFilters(options) {
819
+ var _a, _b;
820
+ const filters = [];
821
+ for (const service of (_a = options === null || options === undefined ? undefined : options.services) !== null && _a !== undefined ? _a : []) {
822
+ filters.push({
823
+ services: [service],
824
+ name: options === null || options === undefined ? undefined : options.name,
825
+ namePrefix: options === null || options === undefined ? undefined : options.namePrefix,
826
+ });
827
+ }
828
+ if (((options === null || options === undefined ? undefined : options.name) || (options === null || options === undefined ? undefined : options.namePrefix)) && filters.length === 0) {
829
+ filters.push({
830
+ name: options.name,
831
+ namePrefix: options.namePrefix,
832
+ });
833
+ }
834
+ for (const manufacturerData of (_b = options === null || options === undefined ? undefined : options.manufacturerData) !== null && _b !== undefined ? _b : []) {
835
+ filters.push({
836
+ manufacturerData: [manufacturerData],
837
+ });
838
+ }
839
+ return filters;
840
+ }
841
+ getDeviceFromMap(deviceId) {
842
+ const device = this.deviceMap.get(deviceId);
843
+ if (device === undefined) {
844
+ throw new Error('Device not found. Call "requestDevice", "requestLEScan" or "getDevices" first.');
845
+ }
846
+ return device;
847
+ }
848
+ getBleDevice(device) {
849
+ var _a;
850
+ const bleDevice = {
851
+ deviceId: device.id,
852
+ // use undefined instead of null if name is not available
853
+ name: (_a = device.name) !== null && _a !== undefined ? _a : undefined,
854
+ };
855
+ return bleDevice;
856
+ }
852
857
  }
853
858
 
854
859
  var web = /*#__PURE__*/Object.freeze({